{"lang_cluster":"Ada","source_code":"\n\ngeneric\n type Element_Type is private; \npackage Generic_Stack is\n type Stack is private; \n procedure Push (Item : Element_Type; Onto : in out Stack); \n procedure Pop (Item : out Element_Type; From : in out Stack); \n function Create return Stack;\n Stack_Empty_Error : exception;\nprivate\n type Node; \n type Stack is access Node; \n type Node is record \n Element : Element_Type; \n Next : Stack := null; \n end record; \nend Generic_Stack;\n\nwith Ada.Unchecked_Deallocation;\n\npackage body Generic_Stack is\n \n ------------\n -- Create --\n ------------\n \n function Create return Stack is\n begin\n return (null);\n end Create;\n\n ----------\n -- Push --\n ----------\n\n procedure Push(Item : Element_Type; Onto : in out Stack) is\n Temp : Stack := new Node;\n begin\n Temp.Element := Item;\n Temp.Next := Onto;\n Onto := Temp; \n end Push;\n\n ---------\n -- Pop --\n ---------\n\n procedure Pop(Item : out Element_Type; From : in out Stack) is\n procedure Free is new Ada.Unchecked_Deallocation(Node, Stack);\n Temp : Stack := From;\n begin\n if Temp = null then\n raise Stack_Empty_Error;\n end if;\n Item := Temp.Element;\n From := Temp.Next;\n Free(Temp);\n end Pop;\n\nend Generic_Stack;\n\n","human_summarization":"implement a generic stack with basic operations including push (adding a new element to the top of the stack), pop (removing and returning the last pushed element from the stack), and empty (checking if the stack contains no elements). The stack follows a last in, first out (LIFO) access policy.","id":1} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO, Ada.Command_Line;\n\nprocedure Fib is\n\n X: Positive := Positive'Value(Ada.Command_Line.Argument(1));\n\n function Fib(P: Positive) return Positive is\n begin\n if P <= 2 then\n return 1;\n else\n return Fib(P-1) + Fib(P-2);\n end if;\n end Fib;\n\nbegin\n Ada.Text_IO.Put(\"Fibonacci(\" & Integer'Image(X) & \" ) = \");\n Ada.Text_IO.Put_Line(Integer'Image(Fib(X)));\nend Fib;\n\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_Fibonacci is\n function Fibonacci (N : Natural) return Natural is\n This : Natural := 0;\n That : Natural := 1;\n Sum : Natural;\n begin\n for I in 1..N loop\n Sum := This + That;\n That := This;\n This := Sum;\n end loop;\n return This;\n end Fibonacci;\nbegin\n for N in 0..10 loop\n Put_Line (Positive'Image (Fibonacci (N)));\n end loop;\nend Test_Fibonacci;\n\n\n","human_summarization":"The code implements a function to generate the nth Fibonacci number, using either an iterative or recursive approach. It optionally supports negative n values by inversely applying the Fibonacci sequence formula. The function utilizes a big integer implementation from a cryptographic library.","id":2} {"lang_cluster":"Ada","source_code":"\nwith Ada.Integer_Text_Io; use Ada.Integer_Text_Io;\nwith Ada.Text_Io; use Ada.Text_Io;\n\nprocedure Array_Selection is\n type Array_Type is array (Positive range <>) of Integer;\n Null_Array : Array_Type(1..0);\n\n function Evens (Item : Array_Type) return Array_Type is\n begin\n if Item'Length > 0 then\n if Item(Item'First) mod 2 = 0 then\n return Item(Item'First) & Evens(Item((Item'First + 1)..Item'Last));\n else\n return Evens(Item((Item'First + 1)..Item'Last));\n end if;\n else\n return Null_Array;\n end if;\n end Evens;\n\n procedure Print(Item : Array_Type) is\n begin\n for I in Item'range loop\n Put(Item(I));\n New_Line;\n end loop;\n end Print;\n\n Foo : Array_Type := (1,2,3,4,5,6,7,8,9,10);\nbegin\n Print(Evens(Foo));\nend Array_Selection;\n\n\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Array_Selection is\n type Array_Type is array (Positive range <>) of Integer;\n\n function Evens (Item : Array_Type) return Array_Type is\n Result : Array_Type (1..Item'Length);\n Index : Positive := 1;\n begin\n for I in Item'Range loop\n if Item (I) mod 2 = 0 then\n Result (Index) := Item (I);\n Index := Index + 1;\n end if;\n end loop;\n return Result (1..Index - 1);\n end Evens;\n\n procedure Put (Item : Array_Type) is\n begin\n for I in Item'range loop\n Put (Integer'Image (Item (I)));\n end loop;\n end Put;\nbegin\n Put (Evens ((1,2,3,4,5,6,7,8,9,10)));\n New_Line;\nend Array_Selection;\n\n","human_summarization":"select certain elements from an array into a new array, specifically all even numbers. It also provides an optional destructive filtering solution that modifies the original array instead of creating a new one.","id":3} {"lang_cluster":"Ada","source_code":"\n\ntype String is array (Positive range <>) of Character;\n\n\nA (..)\n\n\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Strings.Fixed; use Ada.Strings.Fixed;\n\nprocedure Test_Slices is\n Str : constant String := \"abcdefgh\";\n N : constant := 2;\n M : constant := 3;\nbegin\n Put_Line (Str (Str'First + N - 1..Str'First + N + M - 2));\n Put_Line (Str (Str'First + N - 1..Str'Last));\n Put_Line (Str (Str'First..Str'Last - 1));\n Put_Line (Head (Tail (Str, Str'Last - Index (Str, \"d\", 1)), M));\n Put_Line (Head (Tail (Str, Str'Last - Index (Str, \"de\", 1) - 1), M));\nend Test_Slices;\n\n\n","human_summarization":"- Display a substring starting from a specific character position and of a certain length.\n- Display a substring starting from a specific character position up to the end of the string.\n- Display the entire string minus the last character.\n- Display a substring starting from a known character within the string and of a certain length.\n- Display a substring starting from a known substring within the string and of a certain length.\n- The codes are compatible with any valid Unicode code point in UTF-8 or UTF-16.\n- The codes reference logical characters, not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- The codes are not required to handle all Unicode characters for other encodings.\n- In Ada language, the codes use the term slice for substring and can handle slices in mutable or immutable mode.\n- The codes use the first character of the string as the starting point for slicing.","id":4} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n \nprocedure Reverse_String is\n function Reverse_It (Item : String) return String is\n Result : String (Item'Range);\n begin\n for I in Item'range loop\n Result (Result'Last - I + Item'First) := Item (I);\n end loop;\n return Result;\n end Reverse_It;\nbegin\n Put_Line (Reverse_It (Get_Line));\nend Reverse_String;\n\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":5} {"lang_cluster":"Ada","source_code":"\nWorks with: GNAT\n\nprivate with Ada.Containers.Ordered_Maps;\ngeneric\n type t_Vertex is (<>);\npackage Dijkstra is\n \n type t_Graph is limited private;\n \n -- Defining a graph (since limited private, only way to do this is to use the Build function)\n type t_Edge is record\n From, To : t_Vertex;\n Weight : Positive;\n end record;\n type t_Edges is array (Integer range <>) of t_Edge;\n function Build (Edges : in t_Edges; Oriented : in Boolean := True) return t_Graph;\n \n -- Computing path and distance\n type t_Path is array (Integer range <>) of t_Vertex;\n function Shortest_Path (Graph : in out t_Graph;\n From, To : in t_Vertex) return t_Path;\n function Distance (Graph : in out t_Graph;\n From, To : in t_Vertex) return Natural;\n \nprivate\n package Neighbor_Lists is new Ada.Containers.Ordered_Maps (Key_Type => t_Vertex, Element_Type => Positive);\n type t_Vertex_Data is record\n Neighbors : Neighbor_Lists.Map; -- won't be affected after build\n -- Updated each time a function is called with a new source\n Previous : t_Vertex;\n Distance : Natural;\n end record;\n type t_Graph is array (t_Vertex) of t_Vertex_Data;\nend Dijkstra;\n\nwith Ada.Containers.Ordered_Sets;\npackage body Dijkstra is\n\n Infinite : constant Natural := Natural'Last;\n \n -- ----- Graph constructor\n function Build (Edges : in t_Edges; Oriented : in Boolean := True) return t_Graph is\n begin\n return Answer : t_Graph := (others => (Neighbors => Neighbor_Lists.Empty_Map,\n Previous => t_Vertex'First,\n Distance => Natural'Last)) do\n for Edge of Edges loop\n Answer(Edge.From).Neighbors.Insert (Key => Edge.To, New_Item => Edge.Weight);\n if not Oriented then\n Answer(Edge.To).Neighbors.Insert (Key => Edge.From, New_Item => Edge.Weight);\n end if;\n end loop;\n end return;\n end Build;\n \n -- ----- Paths \/ distances data updating in case of computation request for a new source\n procedure Update_For_Source (Graph : in out t_Graph;\n From : in t_Vertex) is\n function Nearer (Left, Right : in t_Vertex) return Boolean is\n (Graph(Left).Distance < Graph(Right).Distance or else\n (Graph(Left).Distance = Graph(Right).Distance and then Left < Right));\n package Ordered is new Ada.Containers.Ordered_Sets (Element_Type => t_Vertex, \"<\" => Nearer);\n use Ordered;\n Remaining : Set := Empty_Set;\n begin\n -- First, let's check if vertices data are already computed for this source\n if Graph(From).Distance \/= 0 then\n -- Reset distances and remaining vertices for a new source\n for Vertex in Graph'range loop\n Graph(Vertex).Distance := (if Vertex = From then 0 else Infinite);\n Remaining.Insert (Vertex);\n end loop;\n -- ----- The Dijkstra algorithm itself\n while not Remaining.Is_Empty\n -- If some targets are not connected to source, at one point, the remaining\n -- distances will all be infinite, hence the folllowing stop condition\n and then Graph(Remaining.First_Element).Distance \/= Infinite loop\n declare\n Nearest : constant t_Vertex := Remaining.First_Element;\n procedure Update_Neighbor (Position : in Neighbor_Lists.Cursor) is\n use Neighbor_Lists;\n Neighbor : constant t_Vertex := Key (Position); \n In_Remaining : Ordered.Cursor := Remaining.Find (Neighbor);\n Try_Distance : constant Natural :=\n (if In_Remaining = Ordered.No_Element\n then Infinite -- vertex already reached, this distance will fail the update test below\n else Graph(Nearest).Distance + Element (Position)); \n begin\n if Try_Distance < Graph(Neighbor).Distance then\n -- Update distance\/path data and reorder the remaining set\n Remaining.Delete (In_Remaining);\n Graph(Neighbor).Distance := Try_Distance;\n Graph(Neighbor).Previous := Nearest;\n Remaining.Insert (Neighbor);\n end if;\n end Update_Neighbor;\n begin\n Remaining.Delete_First;\n Graph(Nearest).Neighbors.Iterate (Update_Neighbor'Access);\n end;\n end loop;\n end if;\n end Update_For_Source;\n \n -- ----- Bodies for the interfaced functions\n function Shortest_Path (Graph : in out t_Graph;\n From, To : in t_Vertex) return t_Path is\n function Recursive_Build (From, To : in t_Vertex) return t_Path is\n (if From = To then (1 => From)\n else Recursive_Build(From, Graph(To).Previous) & (1 => To));\n begin\n Update_For_Source (Graph, From);\n if Graph(To).Distance = Infinite then\n raise Constraint_Error with \"No path from \" & From'Img & \" to \" & To'Img;\n end if;\n return Recursive_Build (From, To);\n end Shortest_Path;\n\n function Distance (Graph : in out t_Graph;\n From, To : in t_Vertex) return Natural is\n begin\n Update_For_Source (Graph, From);\n return Graph(To).Distance;\n end Distance;\n\nend Dijkstra;\n\n\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Dijkstra;\nprocedure Test_Dijkstra is\n subtype t_Tested_Vertices is Character range 'a'..'f';\n package Tested is new Dijkstra (t_Vertex => t_Tested_Vertices);\n use Tested;\n Graph : t_Graph := Build (Edges => (('a', 'b', 7),\n ('a', 'c', 9),\n ('a', 'f', 14),\n ('b', 'c', 10),\n ('b', 'd', 15),\n ('c', 'd', 11),\n ('c', 'f', 2),\n ('d', 'e', 6),\n ('e', 'f', 9)));\n procedure Display_Path (From, To : in t_Tested_Vertices) is\n function Path_Image (Path : in t_Path; Start : Boolean := True) return String is\n ((if Start then \"[\"\n elsif Path'Length \/= 0 then \",\"\n else \"\") &\n (if Path'Length = 0 then \"]\"\n else Path(Path'First) & Path_Image(Path(Path'First+1..Path'Last), Start => False)));\n begin\n Put (\"Path from '\" & From & \"' to '\" & To & \"' = \");\n Put_Line (Path_Image (Shortest_Path (Graph, From, To))\n & \" distance =\" & Distance (Graph, From, To)'Img);\n exception\n when others => Put_Line(\"no path\");\n end Display_Path;\nbegin\n Display_Path ('a', 'e');\n Display_Path ('a', 'f');\n New_Line;\n for From in t_Tested_Vertices loop\n for To in t_Tested_Vertices loop\n Display_Path (From, To);\n end loop;\n end loop; \nend Test_Dijkstra;\n\n\n","human_summarization":"The code implements Dijkstra's algorithm to find the shortest path from a single source to all other vertices in a directed, weighted graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm takes into account non-negative edge path costs. The output is a set of edges representing the shortest path to each reachable node from the origin. The code also includes functionality to interpret the output and display the shortest path from a specific node to other selected nodes. The vertices and edges of the graph can be identified either by numbers or names.","id":6} {"lang_cluster":"Ada","source_code":"with Ada.Text_IO, Ada.Finalization, Ada.Unchecked_Deallocation;\n\nprocedure Main is\n\n generic\n type Key_Type is private;\n with function \"<\"(a, b : Key_Type) return Boolean is <>;\n with function \"=\"(a, b : Key_Type) return Boolean is <>;\n with function \"<=\"(a, b : Key_Type) return Boolean is <>;\n package AVL_Tree is\n type Tree is tagged limited private;\n function insert(self : in out Tree; key : Key_Type) return Boolean;\n procedure delete(self : in out Tree; key : Key_Type);\n procedure print_balance(self : in out Tree);\n\n private\n type Height_Amt is range -1 .. Integer'Last;\n\n -- Since only one key is inserted before each rebalance, the balance of\n -- all trees\/subtrees will stay in range -2 .. 2\n type Balance_Amt is range -2 .. 2;\n\n type Node;\n type Node_Ptr is access Node;\n type Node is new Ada.Finalization.Limited_Controlled with record\n left, right, parent : Node_Ptr := null;\n key : Key_Type;\n balance : Balance_Amt := 0;\n end record;\n overriding procedure Finalize(self : in out Node);\n subtype Node_Parent is Ada.Finalization.Limited_Controlled;\n\n type Tree is new Ada.Finalization.Limited_Controlled with record\n root : Node_Ptr := null;\n end record;\n overriding procedure Finalize(self : in out Tree);\n\n end AVL_Tree;\n\n package body AVL_Tree is\n\n procedure Free_Node is new Ada.Unchecked_Deallocation(Node, Node_Ptr);\n\n overriding procedure Finalize(self : in out Node) is\n begin\n Free_Node(self.left);\n Free_Node(self.right);\n end Finalize;\n\n overriding procedure Finalize(self : in out Tree) is\n begin\n Free_Node(self.root);\n end Finalize;\n\n\n function height(n : Node_Ptr) return Height_Amt is\n begin\n if n = null then\n return -1;\n else\n return 1 + Height_Amt'Max(height(n.left), height(n.right));\n end if;\n end height;\n\n procedure set_balance(n : not null Node_Ptr) is\n begin\n n.balance := Balance_Amt(height(n.right) - height(n.left));\n end set_balance;\n\n procedure update_parent(parent : Node_Ptr; new_child : Node_Ptr; old_child : Node_Ptr) is\n begin\n if parent \/= null then\n if parent.right = old_child then\n parent.right := new_child;\n else\n parent.left := new_child;\n end if;\n end if;\n end update_parent;\n\n function rotate_left(a : not null Node_Ptr) return Node_Ptr is\n b : Node_Ptr := a.right;\n begin\n b.parent := a.parent;\n a.right := b.left;\n if a.right \/= null then\n a.right.parent := a;\n end if;\n b.left := a;\n a.parent := b;\n update_parent(parent => b.parent, new_child => b, old_child => a);\n\n set_balance(a);\n set_balance(b);\n return b;\n end rotate_left;\n\n function rotate_right(a : not null Node_Ptr) return Node_Ptr is\n b : Node_Ptr := a.left;\n begin\n b.parent := a.parent;\n a.left := b.right;\n if a.left \/= null then\n a.left.parent := a;\n end if;\n b.right := a;\n a.parent := b;\n update_parent(parent => b.parent, new_child => b, old_child => a);\n\n set_balance(a);\n set_balance(b);\n return b;\n end rotate_right;\n\n function rotate_left_right(n : not null Node_Ptr) return Node_Ptr is\n begin\n n.left := rotate_left(n.left);\n return rotate_right(n);\n end rotate_left_right;\n\n function rotate_right_left(n : not null Node_Ptr) return Node_Ptr is\n begin\n n.right := rotate_right(n.right);\n return rotate_left(n);\n end rotate_right_left;\n\n procedure rebalance(self : in out Tree; n : not null Node_Ptr) is\n new_n : Node_Ptr := n;\n begin\n set_balance(new_n);\n if new_n.balance = -2 then\n if height(new_n.left.left) >= height(new_n.left.right) then\n new_n := rotate_right(new_n);\n else\n new_n := rotate_left_right(new_n);\n end if;\n elsif new_n.balance = 2 then\n if height(new_n.right.right) >= height(new_n.right.left) then\n new_n := rotate_left(new_n);\n else\n new_n := rotate_right_left(new_n);\n end if;\n end if;\n\n if new_n.parent \/= null then\n rebalance(self, new_n.parent);\n else\n self.root := new_n;\n end if;\n end rebalance;\n\n function new_node(key : Key_Type) return Node_Ptr is\n (new Node'(Node_Parent with key => key, others => <>));\n\n function insert(self : in out Tree; key : Key_Type) return Boolean is\n curr, parent : Node_Ptr;\n go_left : Boolean;\n begin\n if self.root = null then\n self.root := new_node(key);\n return True;\n end if;\n\n curr := self.root;\n while curr.key \/= key loop\n parent := curr;\n go_left := key < curr.key;\n curr := (if go_left then curr.left else curr.right);\n if curr = null then\n if go_left then\n parent.left := new_node(key);\n parent.left.parent := parent;\n else\n parent.right := new_node(key);\n parent.right.parent := parent;\n end if;\n rebalance(self, parent);\n return True;\n end if;\n end loop;\n return False;\n end insert;\n\n procedure delete(self : in out Tree; key : Key_Type) is\n successor, parent, child : Node_Ptr := self.root;\n to_delete : Node_Ptr := null;\n begin\n if self.root = null then\n return;\n end if;\n\n while child \/= null loop\n parent := successor;\n successor := child;\n child := (if successor.key <= key then successor.right else successor.left);\n if successor.key = key then\n to_delete := successor;\n end if;\n end loop;\n\n if to_delete = null then\n return;\n end if;\n to_delete.key := successor.key;\n child := (if successor.left = null then successor.right else successor.left);\n if self.root.key = key then\n self.root := child;\n else\n update_parent(parent => parent, new_child => child, old_child => successor);\n rebalance(self, parent);\n end if;\n Free_Node(successor);\n end delete;\n\n procedure print_balance(n : Node_Ptr) is\n begin\n if n \/= null then\n print_balance(n.left);\n Ada.Text_IO.Put(n.balance'Image);\n print_balance(n.right);\n end if;\n end print_balance;\n\n procedure print_balance(self : in out Tree) is\n begin\n print_balance(self.root);\n end print_balance;\n end AVL_Tree;\n\n package Int_AVL_Tree is new AVL_Tree(Integer);\n\n tree : Int_AVL_Tree.Tree;\n success : Boolean;\nbegin\n for i in 1 .. 10 loop\n success := tree.insert(i);\n end loop;\n Ada.Text_IO.Put(\"Printing balance: \");\n tree.print_balance;\n Ada.Text_IO.New_Line;\nend Main;\n\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.","id":7} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Numerics.Discrete_Random;\n\nprocedure Test_Loop_Break is\n type Value_Type is range 0..19;\n package Random_Values is new Ada.Numerics.Discrete_Random (Value_Type);\n use Random_Values;\n Dice : Generator;\n A, B : Value_Type;\nbegin\n loop\n A := Random (Dice);\n Put_Line (Value_Type'Image (A));\n exit when A = 10;\n B := Random (Dice);\n Put_Line (Value_Type'Image (B));\n end loop;\nend Test_Loop_Break;\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":8} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO;\n-- reuse Is_Prime from [[Primality by Trial Division]]\nwith Is_Prime;\n\nprocedure Mersenne is\n function Is_Set (Number : Natural; Bit : Positive) return Boolean is\n begin\n return Number \/ 2 ** (Bit - 1) mod 2 = 1;\n end Is_Set;\n\n function Get_Max_Bit (Number : Natural) return Natural is\n Test : Natural := 0;\n begin\n while 2 ** Test <= Number loop\n Test := Test + 1;\n end loop;\n return Test;\n end Get_Max_Bit;\n\n function Modular_Power (Base, Exponent, Modulus : Positive) return Natural is\n Maximum_Bit : constant Natural := Get_Max_Bit (Exponent);\n Square : Natural := 1;\n begin\n for Bit in reverse 1 .. Maximum_Bit loop\n Square := Square ** 2;\n if Is_Set (Exponent, Bit) then\n Square := Square * Base;\n end if;\n Square := Square mod Modulus;\n end loop;\n return Square;\n end Modular_Power;\n\n Not_A_Prime_Exponent : exception;\n\n function Get_Factor (Exponent : Positive) return Natural is\n Factor : Positive;\n begin\n if not Is_Prime (Exponent) then\n raise Not_A_Prime_Exponent;\n end if;\n for K in 1 .. 16384 \/ Exponent loop\n Factor := 2 * K * Exponent + 1;\n if Factor mod 8 = 1 or else Factor mod 8 = 7 then\n if Is_Prime (Factor) and then Modular_Power (2, Exponent, Factor) = 1 then\n return Factor;\n end if;\n end if;\n end loop;\n return 0;\n end Get_Factor;\n\n To_Test : constant Positive := 929;\n Factor : Natural;\nbegin\n Ada.Text_IO.Put (\"2 **\" & Integer'Image (To_Test) & \" - 1 \");\n begin\n Factor := Get_Factor (To_Test);\n if Factor = 0 then\n Ada.Text_IO.Put_Line (\"is prime.\");\n else\n Ada.Text_IO.Put_Line (\"has factor\" & Integer'Image (Factor));\n end if;\n exception\n when Not_A_Prime_Exponent =>\n Ada.Text_IO.Put_Line (\"is not a Mersenne number\");\n end;\nend Mersenne;\n\n\n","human_summarization":"The code implements a method to find a factor of a Mersenne number, specifically 2^929-1 (M929). It uses efficient algorithms to determine if a number divides 2^P-1 and implements the modPow operation. The code also includes a primality test that works only on Mersenne numbers where P is prime. The process is refined by considering properties of Mersenne numbers, such as any factor q of 2^P-1 must be of the form 2kP+1, k being a positive integer or zero, and q must be 1 or 7 mod 8. The algorithm stops when 2kP+1 > sqrt(N).","id":9} {"lang_cluster":"Ada","source_code":"\n\nwith ada.containers.ordered_sets, ada.text_io;\nuse ada.text_io;\n\nprocedure set_demo is\n\tpackage cs is new ada.containers.ordered_sets (character); use cs;\n\n\tfunction \"+\" (s : string) return set is\n\t(if s = \"\" then empty_set else Union(+ s(s'first..s'last - 1), To_Set (s(s'last))));\n\n\tfunction \"-\" (s : Set) return string is\n\t(if s = empty_set then \"\" else - (s - To_Set (s.last_element)) & s.last_element);\n\ts1, s2 : set;\nbegin\n\tloop\n\t\tput (\"s1= \");\n\t\ts1 := + get_line;\t\t\n\t\texit when s1 = +\"Quit!\";\n\t\tput (\"s2= \");\n\t\ts2 := + get_line;\n\t\tPut_Line(\"Sets [\" & (-s1) & \"], [\" & (-s2) & \"] of size\"\n & S1.Length'img & \" and\" & s2.Length'img & \".\");\n \t\tPut_Line(\"Intersection: [\" & (-(Intersection(S1, S2))) & \"],\");\n \t\tPut_Line(\"Union: [\" & (-(Union(s1, s2))) & \"],\");\n \t\tPut_Line(\"Difference: [\" & (-(Difference(s1, s2))) & \"],\");\n \t\tPut_Line(\"Symmetric Diff: [\" & (-(s1 xor s2)) & \"],\");\n \t\tPut_Line(\"Subset: \" & Boolean'Image(s1.Is_Subset(s2))\n & \", Equal: \" & Boolean'Image(s1 = s2) & \".\");\n\tend loop;\nend set_demo;\n\n\n","human_summarization":"demonstrate various set operations including set creation, testing if an element is in a set, union, intersection, difference, subset, and equality of sets. It also optionally shows other set operations and methods to modify a mutable set. The set can be implemented using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code uses the Ordered_Sets package from the Ada.Containers standard library, but an alternative solution could use the Hashed_Maps package from Ada.Containers.","id":10} {"lang_cluster":"Ada","source_code":"\nwith Ada.Calendar.Formatting; use Ada.Calendar.Formatting;\nwith Ada.Text_IO; use Ada.Text_IO;\n \nprocedure Yuletide is\nbegin\n for Year in 2008..2121 loop\n if Day_Of_Week (Time_Of (Year, 12, 25)) = Sunday then\n Put_Line (Image (Time_Of (Year, 12, 25)));\n end if;\n end loop;\nend Yuletide;\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":11} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Numerics.Real_Arrays; use Ada.Numerics.Real_Arrays;\nwith Ada.Numerics.Generic_Elementary_Functions;\nprocedure QR is\n\n procedure Show (mat : Real_Matrix) is\n package FIO is new Ada.Text_IO.Float_IO (Float);\n begin\n for row in mat'Range (1) loop\n for col in mat'Range (2) loop\n FIO.Put (mat (row, col), Exp => 0, Aft => 4, Fore => 5);\n end loop;\n New_Line;\n end loop;\n end Show;\n\n function GetCol (mat : Real_Matrix; n : Integer) return Real_Matrix is\n column : Real_Matrix (mat'Range (1), 1 .. 1);\n begin\n for row in mat'Range (1) loop\n column (row, 1) := mat (row, n);\n end loop;\n return column;\n end GetCol;\n\n function Mag (mat : Real_Matrix) return Float is\n sum : Real_Matrix := Transpose (mat) * mat;\n package Math is new Ada.Numerics.Generic_Elementary_Functions\n (Float);\n begin\n return Math.Sqrt (sum (1, 1));\n end Mag;\n\n function eVect (col : Real_Matrix; n : Integer) return Real_Matrix is\n vect : Real_Matrix (col'Range (1), 1 .. 1);\n begin\n for row in col'Range (1) loop\n if row \/= n then vect (row, 1) := 0.0;\n else vect (row, 1) := 1.0; end if;\n end loop;\n return vect;\n end eVect;\n\n function Identity (n : Integer) return Real_Matrix is\n mat : Real_Matrix (1 .. n, 1 .. n) := (1 .. n => (others => 0.0));\n begin\n for i in Integer range 1 .. n loop mat (i, i) := 1.0; end loop;\n return mat;\n end Identity;\n\n function Chop (mat : Real_Matrix; n : Integer) return Real_Matrix is\n small : Real_Matrix (n .. mat'Length (1), n .. mat'Length (2));\n begin\n for row in small'Range (1) loop\n for col in small'Range (2) loop\n small (row, col) := mat (row, col);\n end loop;\n end loop;\n return small;\n end Chop;\n\n function H_n (inmat : Real_Matrix; n : Integer)\n return Real_Matrix is\n mat : Real_Matrix := Chop (inmat, n);\n col : Real_Matrix := GetCol (mat, n);\n colT : Real_Matrix (1 .. 1, mat'Range (1));\n H : Real_Matrix := Identity (mat'Length (1));\n Hall : Real_Matrix := Identity (inmat'Length (1));\n begin\n col := col - Mag (col) * eVect (col, n);\n col := col \/ Mag (col);\n colT := Transpose (col);\n H := H - 2.0 * (col * colT);\n for row in H'Range (1) loop\n for col in H'Range (2) loop\n Hall (n - 1 + row, n - 1 + col) := H (row, col);\n end loop;\n end loop;\n return Hall;\n end H_n;\n\n A : constant Real_Matrix (1 .. 3, 1 .. 3) := (\n (12.0, -51.0, 4.0),\n (6.0, 167.0, -68.0),\n (-4.0, 24.0, -41.0));\n Q1, Q2, Q3, Q, R: Real_Matrix (1 .. 3, 1 .. 3);\nbegin\n Q1 := H_n (A, 1);\n Q2 := H_n (Q1 * A, 2);\n Q3 := H_n (Q2 * Q1* A, 3);\n Q := Transpose (Q1) * Transpose (Q2) * TransPose(Q3);\n R := Q3 * Q2 * Q1 * A;\n Put_Line (\"Q:\"); Show (Q);\n Put_Line (\"R:\"); Show (R);\nend QR;\n\n\n","human_summarization":"\"Implement QR decomposition using Householder reflections. The code takes a rectangular matrix and decomposes it into a product of an orthogonal matrix and an upper triangular matrix. It also demonstrates the QR decomposition on a given example matrix and uses it to solve linear least squares problems. The code handles cases where the matrix is not square by cutting off zero padded bottom rows. The solution is then obtained by back substitution.\"","id":12} {"lang_cluster":"Ada","source_code":"\nWorks with: GNAT version GPL 2018\nwith Ada.Containers.Ordered_Sets, Ada.Text_IO;\nuse Ada.Text_IO;\n \nprocedure Duplicate is\t\n\tpackage Int_Sets is new Ada.Containers.Ordered_Sets (Integer);\n\tNums : constant array (Natural range <>) of Integer := (1,2,3,4,5,5,6,7,1);\n\tUnique : Int_Sets.Set;\nbegin\n\tfor n of Nums loop\n\t\tUnique.Include (n);\n\tend loop;\n\tfor e of Unique loop\n\t\tPut (e'img);\n\tend loop;\nend Duplicate;\n\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":13} {"lang_cluster":"Ada","source_code":"\n\n-----------------------------------------------------------------------\n-- Generic Quick_Sort procedure\n-----------------------------------------------------------------------\ngeneric\n type Element is private;\n type Index is (<>);\n type Element_Array is array(Index range <>) of Element;\n with function \"<\" (Left, Right : Element) return Boolean is <>;\nprocedure Quick_Sort(A : in out Element_Array);\n\n\n-----------------------------------------------------------------------\n-- Generic Quick_Sort procedure\n----------------------------------------------------------------------- \n\nprocedure Quick_Sort (A : in out Element_Array) is\n \n procedure Swap(Left, Right : Index) is\n Temp : Element := A (Left);\n begin\n A (Left) := A (Right);\n A (Right) := Temp;\n end Swap;\n \nbegin\n if A'Length > 1 then\n declare\n Pivot_Value : Element := A (A'First);\n Right : Index := A'Last;\n Left : Index := A'First;\n begin\n loop\n while Left < Right and not (Pivot_Value < A (Left)) loop\n Left := Index'Succ (Left);\n end loop;\n while Pivot_Value < A (Right) loop\n Right := Index'Pred (Right);\n end loop;\n exit when Right <= Left;\n Swap (Left, Right);\n Left := Index'Succ (Left);\n Right := Index'Pred (Right);\n end loop;\n if Right = A'Last then\n Right := Index'Pred (Right);\n Swap (A'First, A'Last);\n end if;\n if Left = A'First then\n Left := Index'Succ (Left);\n end if;\n Quick_Sort (A (A'First .. Right));\n Quick_Sort (A (Left .. A'Last));\n end;\n end if;\nend Quick_Sort;\n\n\nwith Ada.Text_Io;\nwith Ada.Float_Text_IO; use Ada.Float_Text_IO; \nwith Quick_Sort;\n\nprocedure Sort_Test is\n type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);\n type Sales is array (Days range <>) of Float;\n procedure Sort_Days is new Quick_Sort(Float, Days, Sales);\n \n procedure Print (Item : Sales) is\n begin\n for I in Item'range loop\n Put(Item => Item(I), Fore => 5, Aft => 2, Exp => 0);\n end loop;\n end Print;\n \n Weekly_Sales : Sales := (Mon => 300.0, \n Tue => 700.0, \n Wed => 800.0, \n Thu => 500.0, \n Fri => 200.0, \n Sat => 100.0, \n Sun => 900.0);\n \nbegin\n \n Print(Weekly_Sales);\n Ada.Text_Io.New_Line(2);\n Sort_Days(Weekly_Sales);\n Print(Weekly_Sales);\n \nend Sort_Test;\n\n","human_summarization":"implement the quicksort algorithm to sort an array or list elements. The algorithm selects a pivot from the array, divides the rest of the elements into two partitions (one with elements less than the pivot and one with elements greater than the pivot), and then recursively sorts these partitions. The codes also include an optimized version of quicksort that works in place by swapping elements within the array to avoid additional memory allocation. The pivot selection method is not specified and can vary. The codes can handle any discrete index type.","id":14} {"lang_cluster":"Ada","source_code":"\nwith Ada.Calendar; use Ada.Calendar;\nwith Ada.Calendar.Formatting; use Ada.Calendar.Formatting;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Date_Format is\n function Image (Month : Month_Number) return String is\n begin\n case Month is\n when 1 => return \"January\";\n when 2 => return \"February\";\n when 3 => return \"March\";\n when 4 => return \"April\";\n when 5 => return \"May\";\n when 6 => return \"June\";\n when 7 => return \"July\";\n when 8 => return \"August\";\n when 9 => return \"September\";\n when 10 => return \"October\";\n when 11 => return \"November\";\n when 12 => return \"December\";\n end case;\n end Image;\n function Image (Day : Day_Name) return String is\n begin\n case Day is\n when Monday => return \"Monday\";\n when Tuesday => return \"Tuesday\";\n when Wednesday => return \"Wednesday\";\n when Thursday => return \"Thursday\";\n when Friday => return \"Friday\";\n when Saturday => return \"Saturday\";\n when Sunday => return \"Sunday\";\n end case;\n end Image;\n Today : Time := Clock;\nbegin\n Put_Line (Image (Today) (1..10));\n Put_Line\n ( Image (Day_Of_Week (Today)) & \", \"\n & Image (Ada.Calendar.Month (Today))\n & Day_Number'Image (Ada.Calendar.Day (Today)) & \",\"\n & Year_Number'Image (Ada.Calendar.Year (Today))\n );\nend Date_Format;\n\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":15} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO, Ada.Command_Line;\nuse Ada.Text_IO, Ada.Command_Line;\n \nprocedure powerset is\nbegin\n\tfor set in 0..2**Argument_Count-1 loop\n\t\tPut (\"{\");\t\t\t\n\t\tdeclare\n\t\t\tk : natural := set;\n\t\t\tfirst : boolean := true;\n\t\tbegin\n\t\t\tfor i in 1..Argument_Count loop\n\t\t\t\tif k mod 2 = 1 then\n\t\t\t\t\tPut ((if first then \"\" else \",\") & Argument (i));\n\t\t\t\t\tfirst := false;\n\t\t\t \tend if;\n\t\t\t\tk := k \/ 2; -- we go to the next bit of \"set\"\n\t\t\tend loop;\n\t\tend;\n\t\tPut_Line(\"}\");\n\tend loop;\nend powerset;\n\n\n\n","human_summarization":"The code takes a set S as input and generates its power set. The power set includes all subsets of S, including the empty set and the set itself. For a set with n elements, the power set will have 2^n elements. The code also demonstrates the handling of power sets for an empty set and a set that contains only the empty set. The implementation uses either a library or built-in set type, or a custom set type with necessary operations. The code also has a feature to print the power set of n arguments passed via the command line, using the i'th bit of a natural number between 0 and 2^n -1 to determine whether to include the i'th element of the command line in the set.","id":16} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Roman_Numeral_Test is\n function To_Roman (Number : Positive) return String is\n subtype Digit is Integer range 0..9;\n function Roman (Figure : Digit; I, V, X : Character) return String is\n begin\n case Figure is\n when 0 => return \"\";\n when 1 => return \"\" & I;\n when 2 => return I & I;\n when 3 => return I & I & I;\n when 4 => return I & V;\n when 5 => return \"\" & V;\n when 6 => return V & I;\n when 7 => return V & I & I;\n when 8 => return V & I & I & I;\n when 9 => return I & X;\n end case;\n end Roman;\n begin\n pragma Assert (Number >= 1 and Number < 4000);\n return\n Roman (Number \/ 1000, 'M', ' ', ' ') &\n Roman (Number \/ 100 mod 10, 'C', 'D', 'M') &\n Roman (Number \/ 10 mod 10, 'X', 'L', 'C') &\n Roman (Number mod 10, 'I', 'V', 'X');\n end To_Roman;\nbegin\n Put_Line (To_Roman (1999));\n Put_Line (To_Roman (25));\n Put_Line (To_Roman (944));\nend Roman_Numeral_Test;\n\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":17} {"lang_cluster":"Ada","source_code":"\nprocedure Array_Test is\n\n A, B : array (1..20) of Integer;\n\n -- Ada array indices may begin at any value, not just 0 or 1\n C : array (-37..20) of integer\n\n -- Ada arrays may be indexed by enumerated types, which are \n -- discrete non-numeric types\n type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);\n type Activities is (Work, Fish);\n type Daily_Activities is array(Days) of Activities;\n This_Week : Daily_Activities := (Mon..Fri => Work, Others => Fish);\n\n -- Or any numeric type\n type Fingers is range 1..4; -- exclude thumb\n type Fingers_Extended_Type is array(fingers) of Boolean;\n Fingers_Extended : Fingers_Extended_Type;\n\n -- Array types may be unconstrained. The variables of the type\n -- must be constrained\n type Arr is array (Integer range <>) of Integer;\n Uninitialized : Arr (1 .. 10);\n Initialized_1 : Arr (1 .. 20) := (others => 1);\n Initialized_2 : Arr := (1 .. 30 => 2);\n Const : constant Arr := (1 .. 10 => 1, 11 .. 20 => 2, 21 | 22 => 3);\n Centered : Arr (-50..50) := (0 => 1, Others => 0);\n\n Result : Integer\nbegin\n\n A := (others => 0); -- Assign whole array\n B := (1 => 1, 2 => 1, 3 => 2, others => 0); \n -- Assign whole array, different values \n A (1) := -1; -- Assign individual element\n A (2..4) := B (1..3); -- Assign a slice\n A (3..5) := (2, 4, -1); -- Assign a constant slice\n A (3..5) := A (4..6); -- It is OK to overlap slices when assigned\n \n Fingers_Extended'First := False; -- Set first element of array\n Fingers_Extended'Last := False; -- Set last element of array\n\nend Array_Test;\n\n\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. They include creating an array, assigning a value to it, and retrieving an element from it. Both fixed-length and dynamic arrays are covered. The codes also show that arrays are first-class objects in Ada, which can be allocated statically or dynamically. The number of elements in an array is always constrained, and variable size arrays are provided by the standard container library.","id":18} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO; use Ada.Text_IO;\n \nprocedure Read_And_Write_File_Line_By_Line is\n Input, Output : File_Type;\nbegin\n Open (File => Input,\n Mode => In_File,\n Name => \"input.txt\");\n Create (File => Output,\n Mode => Out_File,\n Name => \"output.txt\");\n loop\n declare\n Line : String := Get_Line (Input);\n begin\n -- You can process the contents of Line here.\n Put_Line (Output, Line);\n end;\n end loop;\n Close (Input);\n Close (Output);\nexception\n when End_Error =>\n if Is_Open(Input) then \n Close (Input);\n end if;\n if Is_Open(Output) then \n Close (Output);\n end if;\nend Read_And_Write_File_Line_By_Line;\n\n\nwith Ada.Command_Line, Ada.Text_IO; use Ada.Command_Line, Ada.Text_IO;\n \nprocedure Read_And_Write_File_Line_By_Line is\n Read_From : constant String := \"input.txt\";\n Write_To : constant String := \"output.txt\";\n \n Input, Output : File_Type;\nbegin\n begin\n Open (File => Input,\n Mode => In_File,\n Name => Read_From);\n exception\n when others =>\n Put_Line (Standard_Error,\n \"Can not open the file '\" & Read_From & \"'. Does it exist?\");\n Set_Exit_Status (Failure);\n return;\n end;\n \n begin\n Create (File => Output,\n Mode => Out_File,\n Name => Write_To);\n exception\n when others =>\n Put_Line (Standard_Error,\n \"Can not create a file named '\" & Write_To & \"'.\");\n Set_Exit_Status (Failure);\n return;\n end;\n \n loop\n declare\n Line : String := Get_Line (Input);\n begin\n -- You can process the contents of Line here.\n Put_Line (Output, Line);\n end;\n end loop;\n Close (Input);\n Close (Output);\nexception\n when End_Error =>\n if Is_Open(Input) then \n Close (Input);\n end if;\n if Is_Open(Output) then \n Close (Output);\n end if;\nend Read_And_Write_File_Line_By_Line;\n\n\nwith Ada.Sequential_IO;\n\nprocedure Read_And_Write_File_Character_By_Character is\n package Char_IO is new Ada.Sequential_IO (Character);\n use Char_IO;\n\n Input, Output : File_Type;\n Buffer : Character;\nbegin\n Open (File => Input, Mode => In_File, Name => \"input.txt\");\n Create (File => Output, Mode => Out_File, Name => \"output.txt\");\n loop\n Read (File => Input, Item => Buffer);\n Write (File => Output, Item => Buffer);\n end loop;\n Close (Input);\n Close (Output);\nexception\n when End_Error =>\n if Is_Open(Input) then\n Close (Input);\n end if;\n if Is_Open(Output) then\n Close (Output);\n end if;\nend Read_And_Write_File_Character_By_Character;\n\n\nwith Ada.Text_IO; use Ada.Text_IO; \nwith Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;\n \nprocedure Using_Text_Streams is\n Input, Output : File_Type;\n Buffer : Character;\nbegin\n Open (File => Input, Mode => In_File, Name => \"input.txt\");\n Create (File => Output, Mode => Out_File, Name => \"output.txt\");\n loop\n Buffer := Character'Input (Stream (Input));\n Character'Write (Stream (Output), Buffer);\n end loop;\n Close (Input);\n Close (Output);\nexception\n when End_Error =>\n if Is_Open(Input) then\n Close (Input);\n end if;\n if Is_Open(Output) then\n Close (Output);\n end if;\nend Using_Text_Streams;\n\n","human_summarization":"The code reads the contents of \"input.txt\" file into an intermediate variable, then writes the contents of this variable into a new file called \"output.txt\". It demonstrates file reading and writing operations with proper error handling. It also includes an example of using stream I\/O for more efficient reading and writing, skipping formatting.","id":19} {"lang_cluster":"Ada","source_code":"\nwith Ada.Characters.Handling, Ada.Text_IO;\nuse Ada.Characters.Handling, Ada.Text_IO;\n\nprocedure Upper_Case_String is\n S : constant String := \"alphaBETA\";\nbegin\n Put_Line (To_Upper (S));\n Put_Line (To_Lower (S));\nend Upper_Case_String;\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":20} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Numerics.Generic_Elementary_Functions;\nwith Ada.Text_IO;\n\nprocedure Closest is\n package Math is new Ada.Numerics.Generic_Elementary_Functions (Float);\n\n Dimension : constant := 2;\n type Vector is array (1 .. Dimension) of Float;\n type Matrix is array (Positive range <>) of Vector;\n\n -- calculate the distance of two points\n function Distance (Left, Right : Vector) return Float is\n Result : Float := 0.0;\n Offset : Natural := 0;\n begin\n loop\n Result := Result + (Left(Left'First + Offset) - Right(Right'First + Offset))**2;\n Offset := Offset + 1;\n exit when Offset >= Left'Length;\n end loop;\n return Math.Sqrt (Result);\n end Distance;\n\n -- determine the two closest points inside a cloud of vectors\n function Get_Closest_Points (Cloud : Matrix) return Matrix is\n Result : Matrix (1..2);\n Min_Distance : Float;\n begin\n if Cloud'Length(1) < 2 then\n raise Constraint_Error;\n end if;\n Result := (Cloud (Cloud'First), Cloud (Cloud'First + 1));\n Min_Distance := Distance (Cloud (Cloud'First), Cloud (Cloud'First + 1));\n for I in Cloud'First (1) .. Cloud'Last(1) - 1 loop\n for J in I + 1 .. Cloud'Last(1) loop\n if Distance (Cloud (I), Cloud (J)) < Min_Distance then\n Min_Distance := Distance (Cloud (I), Cloud (J));\n Result := (Cloud (I), Cloud (J));\n end if;\n end loop;\n end loop;\n return Result;\n end Get_Closest_Points;\n\n Test_Cloud : constant Matrix (1 .. 10) := ( (5.0, 9.0), (9.0, 3.0),\n (2.0, 0.0), (8.0, 4.0),\n (7.0, 4.0), (9.0, 10.0),\n (1.0, 9.0), (8.0, 2.0),\n (0.0, 10.0), (9.0, 6.0));\n Closest_Points : Matrix := Get_Closest_Points (Test_Cloud);\n\n Second_Test : constant Matrix (1 .. 10) := ( (0.654682, 0.925557), (0.409382, 0.619391),\n (0.891663, 0.888594), (0.716629, 0.9962),\n (0.477721, 0.946355), (0.925092, 0.81822),\n (0.624291, 0.142924), (0.211332, 0.221507),\n (0.293786, 0.691701), (0.839186, 0.72826));\n Second_Points : Matrix := Get_Closest_Points (Second_Test);\nbegin\n Ada.Text_IO.Put_Line (\"Closest Points:\");\n Ada.Text_IO.Put_Line (\"P1: \" & Float'Image (Closest_Points (1) (1)) & \" \" & Float'Image (Closest_Points (1) (2)));\n Ada.Text_IO.Put_Line (\"P2: \" & Float'Image (Closest_Points (2) (1)) & \" \" & Float'Image (Closest_Points (2) (2)));\n Ada.Text_IO.Put_Line (\"Distance: \" & Float'Image (Distance (Closest_Points (1), Closest_Points (2))));\n Ada.Text_IO.Put_Line (\"Closest Points 2:\");\n Ada.Text_IO.Put_Line (\"P1: \" & Float'Image (Second_Points (1) (1)) & \" \" & Float'Image (Second_Points (1) (2)));\n Ada.Text_IO.Put_Line (\"P2: \" & Float'Image (Second_Points (2) (1)) & \" \" & Float'Image (Second_Points (2) (2)));\n Ada.Text_IO.Put_Line (\"Distance: \" & Float'Image (Distance (Second_Points (1), Second_Points (2))));\nend Closest;\n\n\n","human_summarization":"The code provides a solution to the Closest Pair of Points problem in a two-dimensional plane. It includes two functions: one implementing a brute-force algorithm with a time complexity of O(n^2), and another using a recursive divide-and-conquer approach with a time complexity of O(n log n). Both functions return the minimum distance and the pair of points with the minimum distance from a given set of points. The divide-and-conquer function sorts the points by x and y coordinates and uses the brute-force function for small subsets. The code also includes a procedure for formatting the output.","id":21} {"lang_cluster":"Ada","source_code":"\n\n\nprocedure Array_Collection is\n\n A : array (-3 .. -1) of Integer := (1, 2, 3);\n \nbegin\n \n A (-3) := 3;\n A (-2) := 2;\n A (-1) := 1;\n \nend Array_Collection;\n\n\nprocedure Array_Collection is\n\n type Array_Type is array (1 .. 3) of Integer;\n A : Array_Type := (1, 2, 3);\n \nbegin\n \n A (1) := 3;\n A (2) := 2;\n A (3) := 1;\n \nend Array_Collection;\n\n\nprocedure Array_Collection is\n\n type Array_Type is array (positive range <>) of Integer; -- may be indexed with any positive\n -- Integer value\n A : Array_Type(1 .. 3); -- creates an array of three integers, indexed from 1 to 3\n \nbegin\n \n A (1) := 3;\n A (2) := 2;\n A (3) := 1;\n \nend Array_Collection;\n\nWorks with: Ada 2005\nLibrary: Ada.Containers.Doubly_Linked_Lists\nwith Ada.Containers.Doubly_Linked_Lists;\nuse Ada.Containers;\n\nprocedure Doubly_Linked_List is\n\n package DL_List_Pkg is new Doubly_Linked_Lists (Integer);\n use DL_List_Pkg;\n \n DL_List : List;\n \nbegin\n \n DL_List.Append (1);\n DL_List.Append (2);\n DL_List.Append (3);\n \nend Doubly_Linked_List;\n\nWorks with: Ada 2005\nLibrary: Ada.Containers.Vectors\nwith Ada.Containers.Vectors;\nuse Ada.Containers;\n\nprocedure Vector_Example is\n\n package Vector_Pkg is new Vectors (Natural, Integer);\n use Vector_Pkg;\n \n V : Vector;\n \nbegin\n \n V.Append (1);\n V.Append (2);\n V.Append (3);\n \nend Vector_Example;\n\n","human_summarization":"create a collection and add a few values to it. The codes also demonstrate the use of arrays in Ada 95 and Ada 2005, including the creation of anonymous and dynamic arrays. The limitations of anonymous arrays are also discussed. Examples of Doubly Linked Lists and Vectors are provided, along with the usage of hashed and ordered Maps and Sets. The codes also illustrate how arrays can be indexed on any range of discrete values.","id":22} {"lang_cluster":"Ada","source_code":"with Ada.Text_IO;\n\nprocedure Knapsack_Unbounded is\n\n type Bounty is record\n Value : Natural;\n Weight : Float;\n Volume : Float;\n end record;\n\n function Min (A, B : Float) return Float is\n begin\n if A < B then\n return A;\n else\n return B;\n end if;\n end Min;\n\n Panacea : Bounty := (3000, 0.3, 0.025);\n Ichor : Bounty := (1800, 0.2, 0.015);\n Gold : Bounty := (2500, 2.0, 0.002);\n Limits : Bounty := ( 0, 25.0, 0.250);\n Best : Bounty := ( 0, 0.0, 0.000);\n Current : Bounty := ( 0, 0.0, 0.000);\n\n Best_Amounts : array (1 .. 3) of Natural := (0, 0, 0);\n\n Max_Panacea : Natural := Natural (Float'Floor (Min\n (Limits.Weight \/ Panacea.Weight,\n Limits.Volume \/ Panacea.Volume)));\n Max_Ichor : Natural := Natural (Float'Floor (Min\n (Limits.Weight \/ Ichor.Weight,\n Limits.Volume \/ Ichor.Volume)));\n Max_Gold : Natural := Natural (Float'Floor (Min\n (Limits.Weight \/ Gold.Weight,\n Limits.Volume \/ Gold.Volume)));\n\nbegin\n for Panacea_Count in 0 .. Max_Panacea loop\n for Ichor_Count in 0 .. Max_Ichor loop\n for Gold_Count in 0 .. Max_Gold loop\n Current.Value := Panacea_Count * Panacea.Value +\n Ichor_Count * Ichor.Value +\n Gold_Count * Gold.Value;\n Current.Weight := Float (Panacea_Count) * Panacea.Weight +\n Float (Ichor_Count) * Ichor.Weight +\n Float (Gold_Count) * Gold.Weight;\n Current.Volume := Float (Panacea_Count) * Panacea.Volume +\n Float (Ichor_Count) * Ichor.Volume +\n Float (Gold_Count) * Gold.Volume;\n if Current.Value > Best.Value and\n Current.Weight <= Limits.Weight and\n Current.Volume <= Limits.Volume then\n Best := Current;\n Best_Amounts := (Panacea_Count, Ichor_Count, Gold_Count);\n end if;\n end loop;\n end loop;\n end loop;\n Ada.Text_IO.Put_Line (\"Maximum value:\" & Natural'Image (Best.Value));\n Ada.Text_IO.Put_Line (\"Panacea:\" & Natural'Image (Best_Amounts (1)));\n Ada.Text_IO.Put_Line (\"Ichor: \" & Natural'Image (Best_Amounts (2)));\n Ada.Text_IO.Put_Line (\"Gold: \" & Natural'Image (Best_Amounts (3)));\nend Knapsack_Unbounded;\n\n","human_summarization":"determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.","id":23} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\n\nprocedure LoopsAndHalf is \nbegin\n for i in 1 .. 10 loop\n Ada.Text_IO.put (i'Img);\n exit when i = 10;\n Ada.Text_IO.put (\",\");\n end loop;\n Ada.Text_IO.new_line;\nend LoopsAndHalf;\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":24} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Containers.Vectors; use Ada.Containers;\n\npackage Digraphs is\n\n type Node_Idx_With_Null is new Natural;\n subtype Node_Index is Node_Idx_With_Null range 1 .. Node_Idx_With_Null'Last;\n -- a Node_Index is a number from 1, 2, 3, ... and the representative of a node\n\n type Graph_Type is tagged private;\n\n -- make sure Node is in Graph (possibly without connections)\n procedure Add_Node\n (Graph: in out Graph_Type'Class; Node: Node_Index);\n\n -- insert an edge From->To into Graph; do nothing if already there\n procedure Add_Connection\n (Graph: in out Graph_Type'Class; From, To: Node_Index);\n\n -- get the largest Node_Index used in any Add_Node or Add_Connection op.\n -- iterate over all nodes of Graph: \"for I in 1 .. Graph.Node_Count loop ...\"\n function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null;\n\n -- remove an edge From->To from Fraph; do nothing if not there\n -- Graph.Node_Count is not changed\n procedure Del_Connection\n (Graph: in out Graph_Type'Class; From, To: Node_Index);\n\n -- check if an edge From->to exists in Graph\n function Connected\n (Graph: Graph_Type; From, To: Node_Index) return Boolean;\n\n -- data structure to store a list of nodes\n package Node_Vec is new Vectors(Positive, Node_Index);\n\n -- get a list of all nodes From->Somewhere in Graph\n function All_Connections\n (Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector;\n\n Graph_Is_Cyclic: exception;\n\n -- a depth-first search to find a topological sorting of the nodes\n -- raises Graph_Is_Cyclic if no topological sorting is possible\n function Top_Sort\n (Graph: Graph_Type) return Node_Vec.Vector;\n\nprivate\n\n package Conn_Vec is new Vectors(Node_Index, Node_Vec.Vector, Node_Vec.\"=\");\n\n type Graph_Type is new Conn_Vec.Vector with null record;\n\nend Digraphs;\n\n\npackage body Digraphs is\n\n function Node_Count(Graph: Graph_Type) return Node_Idx_With_Null is\n begin\n return Node_Idx_With_Null(Graph.Length);\n end Node_Count;\n\n procedure Add_Node(Graph: in out Graph_Type'Class; Node: Node_Index) is\n begin\n for I in Node_Index range Graph.Node_Count+1 .. Node loop\n Graph.Append(Node_Vec.Empty_Vector);\n end loop;\n end Add_Node;\n\n procedure Add_Connection\n (Graph: in out Graph_Type'Class; From, To: Node_Index) is\n begin\n Graph.Add_Node(Node_Index'Max(From, To));\n declare\n Connection_List: Node_Vec.Vector := Graph.Element(From);\n begin\n for I in Connection_List.First_Index .. Connection_List.Last_Index loop\n if Connection_List.Element(I) >= To then\n if Connection_List.Element(I) = To then\n return; -- if To is already there, don't add it a second time\n else -- I is the first index with Element(I)>To, insert To here\n Connection_List.Insert(Before => I, New_Item => To);\n Graph.Replace_Element(From, Connection_List);\n return;\n end if;\n end if;\n end loop;\n -- there was no I with no Element(I) > To, so insert To at the end\n Connection_List.Append(To);\n Graph.Replace_Element(From, Connection_List);\n return;\n end;\n end Add_Connection;\n\n procedure Del_Connection\n (Graph: in out Graph_Type'Class; From, To: Node_Index) is\n Connection_List: Node_Vec.Vector := Graph.Element(From);\n begin\n for I in Connection_List.First_Index .. Connection_List.Last_Index loop\n if Connection_List.Element(I) = To then\n Connection_List.Delete(I);\n Graph.Replace_Element(From, Connection_List);\n return; -- we are done\n end if;\n end loop;\n end Del_Connection;\n\n function Connected\n (Graph: Graph_Type; From, To: Node_Index) return Boolean is\n Connection_List: Node_Vec.Vector renames Graph.Element(From);\n begin\n for I in Connection_List.First_Index .. Connection_List.Last_Index loop\n if Connection_List.Element(I) = To then\n return True;\n end if;\n end loop;\n return False;\n end Connected;\n\n function All_Connections\n (Graph: Graph_Type; From: Node_Index) return Node_Vec.Vector is\n begin\n return Graph.Element(From);\n end All_Connections;\n\n function Top_Sort\n (Graph: Graph_Type) return Node_Vec.Vector is\n\n Result: Node_Vec.Vector;\n Visited: array(1 .. Graph.Node_Count) of Boolean := (others => False);\n Active: array(1 .. Graph.Node_Count) of Boolean := (others => False);\n\n procedure Visit(Node: Node_Index) is\n begin\n if not Visited(Node) then\n Visited(Node) := True;\n Active(Node) := True;\n declare\n Cons: Node_Vec.Vector := All_Connections(Graph, Node);\n begin\n for Idx in Cons.First_Index .. Cons.Last_Index loop\n Visit(Cons.Element(Idx));\n end loop;\n end;\n Active(Node) := False;\n Result.Append(Node);\n else\n if Active(Node) then\n raise Constraint_Error with \"Graph is Cyclic\";\n end if;\n end if;\n end Visit;\n\n begin\n for Some_Node in Visited'Range loop\n Visit(Some_Node);\n end loop;\n return Result;\n end Top_Sort;\n\nend Digraphs;\n\n\nprivate with Ada.Containers.Indefinite_Vectors;\n\ngeneric\n type Index_Type_With_Null is new Natural;\npackage Set_Of_Names is\n subtype Index_Type is Index_Type_With_Null\n range 1 .. Index_Type_With_Null'Last;\n -- manage a set of strings;\n -- each string in the set is assigned a unique index of type Index_Type\n\n type Set is tagged private;\n\n -- inserts Name into Names; do nothing if already there;\n procedure Add(Names: in out Set; Name: String);\n\n -- Same operation, additionally emiting Index=Names.Idx(Name)\n procedure Add(Names: in out Set; Name: String; Index: out Index_Type);\n\n -- remove Name from Names; do nothing if not found\n -- the removal may change the index of other strings in Names\n procedure Sub(Names: in out Set; Name: String);\n\n -- returns the unique index of Name in Set; or 0 if Name is not there\n function Idx(Names: Set; Name: String) return Index_Type_With_Null;\n\n -- returns the unique name of Index;\n function Name(Names: Set; Index: Index_Type) return String;\n\n -- first index, last index and total number of names in set\n -- to iterate over Names, use \"for I in Names.Start .. Names.Stop loop ...\n function Start(Names: Set) return Index_Type;\n function Stop(Names: Set) return Index_Type_With_Null;\n function Size(Names: Set) return Index_Type_With_Null;\n\nprivate\n\n package Vecs is new Ada.Containers.Indefinite_Vectors\n (Index_Type => Index_Type, Element_Type => String);\n\n type Set is new Vecs.Vector with null record;\n\nend Set_Of_Names;\n\n\npackage body Set_Of_Names is\n\n use type Ada.Containers.Count_Type, Vecs.Cursor;\n\n function Start(Names: Set) return Index_Type is\n begin\n if Names.Length = 0 then\n return 1;\n else\n return Names.First_Index;\n end if;\n end Start;\n\n function Stop(Names: Set) return Index_Type_With_Null is\n begin\n if Names.Length=0 then\n return 0;\n else\n return Names.Last_Index;\n end if;\n end Stop;\n\n function Size(Names: Set) return Index_Type_With_Null is\n begin\n return Index_Type_With_Null(Names.Length);\n end Size;\n\n procedure Add(Names: in out Set; Name: String; Index: out Index_Type) is\n I: Index_Type_With_Null := Names.Idx(Name);\n begin\n if I = 0 then -- Name is not yet in Set\n Names.Append(Name);\n Index := Names.Stop;\n else\n Index := I;\n end if;\n end Add;\n\n procedure Add(Names: in out Set; Name: String) is\n I: Index_Type;\n begin\n Names.Add(Name, I);\n end Add;\n\n procedure Sub(Names: in out Set; Name: String) is\n I: Index_Type_With_Null := Names.Idx(Name);\n begin\n if I \/= 0 then -- Name is in set\n Names.Delete(I);\n end if;\n end Sub;\n\n function Idx(Names: Set; Name: String) return Index_Type_With_Null is\n begin\n for I in Names.First_Index .. Names.Last_Index loop\n if Names.Element(I) = Name then\n return I;\n end if;\n end loop;\n return 0;\n end Idx;\n\n function Name(Names: Set; Index: Index_Type) return String is\n begin\n return Names.Element(Index);\n end Name;\n\nend Set_Of_Names;\n\n\nwith Ada.Text_IO, Digraphs, Set_Of_Names, Ada.Command_Line;\n\nprocedure Toposort is\n\n -- shortcuts for package names, intantiation of generic package\n package TIO renames Ada.Text_IO;\n package DG renames Digraphs;\n package SN is new Set_Of_Names(DG.Node_Idx_With_Null);\n\n -- reat the graph from the file with the given Filename\n procedure Read(Filename: String; G: out DG.Graph_Type; N: out SN.Set) is\n\n -- finds the first word in S(Start .. S'Last), delimited by spaces\n procedure Find_Token(S: String; Start: Positive;\n First: out Positive; Last: out Natural) is\n\n begin\n First := Start;\n while First <= S'Last and then S(First)= ' ' loop\n First := First + 1;\n end loop;\n Last := First-1;\n while Last < S'Last and then S(Last+1) \/= ' ' loop\n Last := Last + 1;\n end loop;\n end Find_Token;\n\n File: TIO.File_Type;\n begin\n TIO.Open(File, TIO.In_File, Filename);\n TIO.Skip_Line(File, 2);\n -- the first two lines contain header and \"===...===\"\n while not TIO.End_Of_File(File) loop\n declare\n Line: String := TIO.Get_Line(File);\n First: Positive;\n Last: Natural;\n To, From: DG.Node_Index;\n begin\n Find_Token(Line, Line'First, First, Last);\n if Last >= First then\n N.Add(Line(First .. Last), From);\n G.Add_Node(From);\n loop\n Find_Token(Line, Last+1, First, Last);\n exit when Last < First;\n N.Add(Line(First .. Last), To);\n G.Add_Connection(From, To);\n end loop;\n end if;\n end;\n end loop;\n TIO.Close(File);\n end Read;\n\n Graph: DG.Graph_Type;\n Names: SN.Set;\n\nbegin\n Read(Ada.Command_Line.Argument(1), Graph, Names);\n\n -- eliminat self-cycles\n for Start in 1 .. Graph.Node_Count loop\n Graph.Del_Connection(Start, Start);\n end loop;\n\n -- perform the topological sort and output the result\n declare\n Result: DG.Node_Vec.Vector;\n begin\n Result := Graph.Top_Sort;\n for Index in Result.First_Index .. Result.Last_Index loop\n TIO.Put(Names.Name(Result.Element(Index)));\n if Index < Result.Last_Index then\n TIO.Put(\" -> \");\n end if;\n end loop;\n TIO.New_Line;\n exception\n when DG.Graph_Is_Cyclic =>\n TIO.Put_Line(\"There is no topological sorting -- the Graph is cyclic!\");\n end;\nend Toposort;\n\n\n","human_summarization":"The code is a function that performs a topological sort on a given set of VHDL libraries and their dependencies. It takes a file with library dependencies as input and returns a valid compile order of the libraries. The function also handles special cases such as self-dependencies, which are ignored, and un-orderable dependencies, which are flagged. The function uses Kahn's 1962 topological sort and depth-first search algorithms for sorting. If the dependencies are circular, the function indicates this in the output. The code also includes a package for directed graphs, representing nodes as positive numbers, and a feature for translating strings into numbers and vice versa.","id":25} {"lang_cluster":"Ada","source_code":"\nwith Ada.Strings.Fixed; use Ada.Strings.Fixed;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Match_Strings is\n S1 : constant String := \"abcd\";\n S2 : constant String := \"abab\";\n S3 : constant String := \"ab\";\nbegin\n if S1'Length >= S3'Length and then S1 (S1'First..S1'First + S3'Length - 1) = S3 then\n Put_Line (''' & S1 & \"' starts with '\" & S3 & ''');\n end if;\n if S2'Length >= S3'Length and then S2 (S2'Last - S3'Length + 1..S2'Last) = S3 then\n Put_Line (''' & S2 & \"' ends with '\" & S3 & ''');\n end if;\n Put_Line (''' & S3 & \"' first appears in '\" & S1 & \"' at\" & Integer'Image (Index (S1, S3)));\n Put_Line\n ( ''' & S3 & \"' appears in '\" & S2 & ''' &\n Integer'Image (Ada.Strings.Fixed.Count (S2, S3)) & \" times\"\n );\nend Match_Strings;\n\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":26} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\n\nprocedure Puzzle_Square_4 is\n\n procedure Four_Rings (Low, High : in Natural; Unique, Show : in Boolean) is\n subtype Test_Range is Natural range Low .. High;\n\n type Value_List is array (Positive range <>) of Natural;\n function Is_Unique (Values : Value_List) return Boolean is\n Count : array (Test_Range) of Natural := (others => 0);\n begin\n for Value of Values loop\n Count (Value) := Count (Value) + 1;\n if Count (Value) > 1 then\n return False;\n end if;\n end loop;\n return True;\n end Is_Unique;\n\n function Is_Valid (A,B,C,D,E,F,G : in Natural) return Boolean is\n Ring_1 : constant Integer := A + B;\n Ring_2 : constant Integer := B + C + D;\n Ring_3 : constant Integer := D + E + F;\n Ring_4 : constant Integer := F + G;\n begin\n return\n Ring_1 = Ring_2 and\n Ring_1 = Ring_3 and\n Ring_1 = Ring_4;\n end Is_Valid;\n\n use Ada.Text_IO;\n Count : Natural := 0;\n begin\n for A in Test_Range loop\n for B in Test_Range loop\n for C in Test_Range loop\n for D in Test_Range loop\n for E in Test_Range loop\n for F in Test_Range loop\n for G in Test_Range loop\n if Is_Valid (A,B,C,D,E,F,G) then\n if not Unique or (Unique and Is_Unique ((A,B,C,D,E,F,G))) then\n Count := Count + 1;\n if Show then\n Put_Line (A'Image & B'Image & C'Image & D'Image & E'Image & F'Image & G'Image);\n end if;\n end if;\n end if;\n end loop;\n end loop;\n end loop;\n end loop;\n end loop;\n end loop;\n end loop;\n Put_Line (\"There are \" & Count'Image &\n (if Unique then \" unique \" else \" non-unique \") &\n \"solutions in \" & Low'Image & \" ..\" & High'Image);\n New_Line;\n end Four_Rings;\n\nbegin\n Four_Rings (Low => 1, High => 7, Unique => True, Show => True);\n Four_Rings (Low => 3, High => 9, Unique => True, Show => True);\n Four_Rings (Low => 0, High => 9, Unique => False, Show => False);\nend Puzzle_Square_4;\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":27} {"lang_cluster":"Ada","source_code":"\nLibrary: SDLAda\nwith Ada.Numerics.Elementary_Functions;\nwith Ada.Calendar.Formatting;\nwith Ada.Calendar.Time_Zones;\n\nwith SDL.Video.Windows.Makers;\nwith SDL.Video.Renderers.Makers;\nwith SDL.Events.Events;\n\nprocedure Draw_A_Clock is\n use Ada.Calendar;\n use Ada.Calendar.Formatting;\n Window : SDL.Video.Windows.Window;\n Renderer : SDL.Video.Renderers.Renderer;\n Event : SDL.Events.Events.Events;\n Offset : Time_Zones.Time_Offset;\n\n procedure Draw_Clock (Stamp : Time)\n is\n use SDL.C;\n use Ada.Numerics.Elementary_Functions;\n Radi : constant array (0 .. 59) of int := (0 | 15 | 30 | 45 => 2,\n 5 | 10 | 20 | 25 | 35 | 40 | 50 | 55 => 1,\n others => 0);\n Diam : constant array (0 .. 59) of int := (0 | 15 | 30 | 45 => 5,\n 5 | 10 | 20 | 25 | 35 | 40 | 50 | 55 => 3,\n others => 1);\n Width : constant int := Window.Get_Surface.Size.Width;\n Height : constant int := Window.Get_Surface.Size.Height;\n Radius : constant Float := Float (int'Min (Width, Height));\n R_1 : constant Float := 0.48 * Radius;\n R_2 : constant Float := 0.35 * Radius;\n R_3 : constant Float := 0.45 * Radius;\n R_4 : constant Float := 0.47 * Radius;\n Hour : constant Hour_Number := Formatting.Hour (Stamp, Offset);\n Minute : constant Minute_Number := Formatting.Minute (Stamp, Offset);\n Second : constant Second_Number := Formatting.Second (Stamp);\n\n function To_X (A : Float; R : Float) return int is\n (Width \/ 2 + int (R * Sin (A, 60.0)));\n\n function To_Y (A : Float; R : Float) return int is\n (Height \/ 2 - int (R * Cos (A, 60.0)));\n\n begin\n SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);\n Renderer.Set_Draw_Colour ((0, 0, 150, 255));\n Renderer.Fill (Rectangle => (0, 0, Width, Height));\n Renderer.Set_Draw_Colour ((200, 200, 200, 255));\n for A in 0 .. 59 loop\n Renderer.Fill (Rectangle => (To_X (Float (A), R_1) - Radi (A),\n To_Y (Float (A), R_1) - Radi (A), Diam (A), Diam (A)));\n end loop;\n Renderer.Set_Draw_Colour ((200, 200, 0, 255));\n Renderer.Draw (Line => ((Width \/ 2, Height \/ 2),\n (To_X (5.0 * (Float (Hour) + Float (Minute) \/ 60.0), R_2),\n To_Y (5.0 * (Float (Hour) + Float (Minute) \/ 60.0), R_2))));\n Renderer.Draw (Line => ((Width \/ 2, Height \/ 2),\n (To_X (Float (Minute) + Float (Second) \/ 60.0, R_3),\n To_Y (Float (Minute) + Float (Second) \/ 60.0, R_3))));\n Renderer.Set_Draw_Colour ((220, 0, 0, 255));\n Renderer.Draw (Line => ((Width \/ 2, Height \/ 2),\n (To_X (Float (Second), R_4),\n To_Y (Float (Second), R_4))));\n Renderer.Fill (Rectangle => (Width \/ 2 - 3, Height \/ 2 - 3, 7, 7));\n end Draw_Clock;\n\n function Poll_Quit return Boolean is\n use type SDL.Events.Event_Types;\n begin\n while SDL.Events.Events.Poll (Event) loop\n if Event.Common.Event_Type = SDL.Events.Quit then\n return True;\n end if;\n end loop;\n return False;\n end Poll_Quit;\n\nbegin\n Offset := Time_Zones.UTC_Time_Offset;\n\n if not SDL.Initialise (Flags => SDL.Enable_Screen) then\n return;\n end if;\n\n SDL.Video.Windows.Makers.Create (Win => Window,\n Title => \"Draw a clock\",\n Position => SDL.Natural_Coordinates'(X => 10, Y => 10),\n Size => SDL.Positive_Sizes'(300, 300),\n Flags => SDL.Video.Windows.Resizable);\n loop\n Draw_Clock (Clock);\n Window.Update_Surface;\n delay 0.200;\n exit when Poll_Quit;\n end loop;\n\n Window.Finalize;\n SDL.Finalise;\nend Draw_A_Clock;\n\n\n","human_summarization":"draw a time-keeping device that updates every second, cycles periodically, and aligns with the system clock without overusing CPU resources. The code is simple, clear, and efficient.","id":28} {"lang_cluster":"Ada","source_code":"\n\nWITH PRINTABLE_CALENDAR;\n\nPROCEDURE REAL_CAL IS\n\n C: PRINTABLE_CALENDAR.CALENDAR := PRINTABLE_CALENDAR.INIT_132\n ((WEEKDAY_REP =>\n \"MO TU WE TH FR SA SO\",\n MONTH_REP =>\n (\" JANUARY \", \" FEBRUARY \",\n \" MARCH \", \" APRIL \",\n \" MAY \", \" JUNE \",\n \" JULY \", \" AUGUST \",\n \" SEPTEMBER \", \" OCTOBER \",\n \" NOVEMBER \", \" DECEMBER \")\n ));\n\nBEGIN\n C.PRINT_LINE_CENTERED(\"[SNOOPY]\");\n C.NEW_LINE;\n C.PRINT(1969, \"NINETEEN-SIXTY-NINE\");\nEND REAL_CAL;\n\n\n","human_summarization":"The code provides an algorithm that generates a printable calendar, formatted to fit a page that is 132 characters wide. The entire code is written in uppercase, inspired by the programming practices of the 1960s. The code does not include Snoopy generation, instead, it outputs a placeholder. The code is written in Ada and reuses the \"PRINTABLE_CALENDAR\" package from a previous calendar task. The output can be adjusted for 80-character devices by replacing \"INIT_132\" with \"INIT_80\".","id":29} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO;\n\nprocedure Pythagorean_Triples is\n\n type Large_Natural is range 0 .. 2**63-1;\n -- this is the maximum for gnat\n\n procedure New_Triangle(A, B, C: Large_Natural;\n Max_Perimeter: Large_Natural;\n Total_Cnt, Primitive_Cnt: in out Large_Natural) is\n Perimeter: constant Large_Natural := A + B + C;\n begin\n if Perimeter <= Max_Perimeter then\n Primitive_Cnt := Primitive_Cnt + 1;\n Total_Cnt := Total_Cnt + Max_Perimeter \/ Perimeter;\n New_Triangle(A-2*B+2*C, 2*A-B+2*C, 2*A-2*B+3*C, Max_Perimeter, Total_Cnt, Primitive_Cnt);\n New_Triangle(A+2*B+2*C, 2*A+B+2*C, 2*A+2*B+3*C, Max_Perimeter, Total_Cnt, Primitive_Cnt);\n New_Triangle(2*B+2*C-A, B+2*C-2*A, 2*B+3*C-2*A, Max_Perimeter, Total_Cnt, Primitive_Cnt);\n end if;\n end New_Triangle;\n\n T_Cnt, P_Cnt: Large_Natural;\n\nbegin\n for I in 1 .. 9 loop\n T_Cnt := 0;\n P_Cnt := 0;\n New_Triangle(3,4,5, 10**I, Total_Cnt => T_Cnt, Primitive_Cnt => P_Cnt);\n Ada.Text_IO.Put_Line(\"Up to 10 **\" & Integer'Image(I) & \"\u00a0:\" &\n Large_Natural'Image(T_Cnt) & \" Triples,\" &\n Large_Natural'Image(P_Cnt) & \" Primitives\");\n end loop;\nend Pythagorean_Triples;\n\n\nUp to 10 ** 1\u00a0: 0 Triples, 0 Primitives\nUp to 10 ** 2\u00a0: 17 Triples, 7 Primitives\nUp to 10 ** 3\u00a0: 325 Triples, 70 Primitives\nUp to 10 ** 4\u00a0: 4858 Triples, 703 Primitives\nUp to 10 ** 5\u00a0: 64741 Triples, 7026 Primitives\nUp to 10 ** 6\u00a0: 808950 Triples, 70229 Primitives\nUp to 10 ** 7\u00a0: 9706567 Triples, 702309 Primitives\nUp to 10 ** 8\u00a0: 113236940 Triples, 7023027 Primitives\nUp to 10 ** 9\u00a0: 1294080089 Triples, 70230484 Primitives\n","human_summarization":"The code calculates the number of Pythagorean triples with a perimeter not exceeding 100, as well as the number of these triples that are primitive. It also has the capability to handle larger perimeter values up to 100,000,000. The Pythagorean triples are sets of three positive integers that satisfy the condition a^2 + b^2 = c^2 and a < b < c. A triple is considered primitive if the greatest common divisor of any two numbers is 1. The code uses an efficient algorithm to deliver results in a timely manner.","id":30} {"lang_cluster":"Ada","source_code":"\nLibrary: GTK\nLibrary: GtkAda\nUses: GtkAda (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses library\" (as page type) with input value \"library\/GtkAda\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\nwith Gtk.Window; use Gtk.Window;\nwith Gtk.Widget; use Gtk.Widget;\n\nwith Gtk.Handlers;\nwith Gtk.Main;\n\nprocedure Windowed_Application is\n Window : Gtk_Window;\n\n package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record);\n package Return_Handlers is\n new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);\n\n function Delete_Event (Widget : access Gtk_Widget_Record'Class)\n return Boolean is\n begin\n return False;\n end Delete_Event;\n\n procedure Destroy (Widget : access Gtk_Widget_Record'Class) is\n begin\n Gtk.Main.Main_Quit;\n end Destroy;\n\nbegin\n Gtk.Main.Init;\n Gtk.Window.Gtk_New (Window);\n Return_Handlers.Connect\n ( Window,\n \"delete_event\",\n Return_Handlers.To_Marshaller (Delete_Event'Access)\n );\n Handlers.Connect\n ( Window,\n \"destroy\",\n Handlers.To_Marshaller (Destroy'Access)\n );\n Show (Window);\n\n Gtk.Main.Main;\nend Windowed_Application;\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":31} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\n\nprocedure Letter_Frequency is\n Counters: array (Character) of Natural := (others => 0); -- initialize all Counters to 0\n C: Character;\n File: Ada.Text_IO.File_Type;\n\nbegin\n Ada.Text_IO.Open(File, Mode => Ada.Text_IO.In_File, Name => \"letter_frequency.adb\");\n while not Ada.Text_IO.End_Of_File(File) loop\n Ada.Text_IO.Get(File, C);\n Counters(C) := Counters(C) + 1;\n end loop;\n\n for I in Counters'Range loop\n if Counters(I) > 0 then\n Ada.Text_IO.Put_Line(\"'\" & I & \"':\" & Integer'Image(Counters(I)));\n end if;\n end loop;\nend Letter_Frequency;\n\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":32} {"lang_cluster":"Ada","source_code":"\ntype Link;\ntype Link_Access is access Link;\ntype Link is record\n Next : Link_Access := null;\n Data : Integer;\nend record;\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":33} {"lang_cluster":"Ada","source_code":"\nLibrary: SDLAda\nwith Ada.Numerics.Elementary_Functions;\n\nwith SDL.Video.Windows.Makers;\nwith SDL.Video.Renderers.Makers;\nwith SDL.Video.Rectangles;\nwith SDL.Events.Events;\n\nprocedure Fractal_Tree is\n\n Width : constant := 600;\n Height : constant := 600;\n Level : constant := 13;\n Length : constant := 130.0;\n X_Start : constant := 475.0;\n Y_Start : constant := 580.0;\n A_Start : constant := -1.54;\n Angle_1 : constant := 0.10;\n Angle_2 : constant := 0.35;\n C_1 : constant := 0.71;\n C_2 : constant := 0.87;\n\n Window : SDL.Video.Windows.Window;\n Renderer : SDL.Video.Renderers.Renderer;\n Event : SDL.Events.Events.Events;\n\n procedure Draw_Tree (Level : in Natural;\n Length : in Float;\n Angle : in Float;\n X, Y : in Float)\n is\n use SDL;\n use Ada.Numerics.Elementary_Functions;\n Pi : constant := Ada.Numerics.Pi;\n X_2 : constant Float := X + Length * Cos (Angle, 2.0 * Pi);\n Y_2 : constant Float := Y + Length * Sin (Angle, 2.0 * Pi);\n Line : constant SDL.Video.Rectangles.Line_Segment\n := ((C.int (X), C.int (Y)), (C.int (X_2), C.int (Y_2)));\n begin\n if Level > 0 then\n Renderer.Set_Draw_Colour (Colour => (0, 220, 0, 255));\n Renderer.Draw (Line => Line);\n\n Draw_Tree (Level - 1, C_1 * Length, Angle + Angle_1, X_2, Y_2);\n Draw_Tree (Level - 1, C_2 * Length, Angle - Angle_2, X_2, Y_2);\n end if;\n end Draw_Tree;\n\n procedure Wait is\n use type SDL.Events.Event_Types;\n begin\n loop\n while SDL.Events.Events.Poll (Event) loop\n if Event.Common.Event_Type = SDL.Events.Quit then\n return;\n end if;\n end loop;\n delay 0.100;\n end loop;\n end Wait;\n\nbegin\n if not SDL.Initialise (Flags => SDL.Enable_Screen) then\n return;\n end if;\n\n SDL.Video.Windows.Makers.Create (Win => Window,\n Title => \"Fractal tree\",\n Position => SDL.Natural_Coordinates'(X => 10, Y => 10),\n Size => SDL.Positive_Sizes'(Width, Height),\n Flags => 0);\n SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);\n Renderer.Set_Draw_Colour ((0, 0, 0, 255));\n Renderer.Fill (Rectangle => (0, 0, Width, Height));\n\n Draw_Tree (Level, Length, A_Start, X_Start, Y_Start);\n Window.Update_Surface;\n\n Wait;\n Window.Finalize;\n SDL.Finalise;\nend Fractal_Tree;\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":34} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\nwith Ada.Command_Line;\nprocedure Factors is\n Number : Positive;\n Test_Nr : Positive := 1;\nbegin\n if Ada.Command_Line.Argument_Count \/= 1 then\n Ada.Text_IO.Put (Ada.Text_IO.Standard_Error, \"Missing argument!\");\n Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);\n return;\n end if;\n Number := Positive'Value (Ada.Command_Line.Argument (1));\n Ada.Text_IO.Put (\"Factors of\" & Positive'Image (Number) & \": \");\n loop\n if Number mod Test_Nr = 0 then\n Ada.Text_IO.Put (Positive'Image (Test_Nr) & \",\");\n end if;\n exit when Test_Nr ** 2 >= Number;\n Test_Nr := Test_Nr + 1;\n end loop;\n Ada.Text_IO.Put_Line (Positive'Image (Number) & \".\");\nend Factors;\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":35} {"lang_cluster":"Ada","source_code":"\nLibrary: Simple components for Ada\nwith Ada.Characters.Latin_1; use Ada.Characters.Latin_1;\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Strings_Edit; use Strings_Edit; \n\nprocedure Column_Aligner is\n Text : constant String :=\n \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\" & NUL &\n \"are$delineated$by$a$single$'dollar'$character,$write$a$program\" & NUL &\n \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\" & NUL &\n \"column$are$separated$by$at$least$one$space.\" & NUL &\n \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\" & NUL &\n \"justified,$right$justified,$or$center$justified$within$its$column.\" & NUL;\n File : File_Type;\n Width : array (1..1_000) of Natural := (others => 0);\n Line : String (1..200);\n Column : Positive := 1;\n Start : Positive := 1;\n Pointer : Positive;\nbegin\n Create (File, Out_File, \"columned.txt\");\n -- Determining the widths of columns\n for I in Text'Range loop\n case Text (I) is\n when '$' | NUL =>\n Width (Column) := Natural'Max (Width (Column), I - Start + 1);\n Start := I + 1;\n if Text (I) = NUL then\n Column := 1;\n else\n Column := Column + 1;\n end if;\n when others =>\n null;\n end case;\n end loop;\n -- Formatting\n for Align in Alignment loop\n Column := 1;\n Start := 1;\n Pointer := 1;\n for I in Text'Range loop\n case Text (I) is\n when '$' | NUL =>\n Put -- Formatted output of a word\n ( Destination => Line,\n Pointer => Pointer,\n Value => Text (Start..I - 1),\n Field => Width (Column),\n Justify => Align\n );\n Start := I + 1;\n if Text (I) = NUL then\n Put_Line (File, Line (1..Pointer - 1));\n Pointer := 1;\n Column := 1;\n else\n Column := Column + 1;\n end if;\n when others =>\n null;\n end case;\n end loop;\n end loop;\n Close (File);\nend Column_Aligner;\n\n\nGiven a text file of many lines, where fields within a line \nare delineated by a single 'dollar' character, write a program \nthat aligns each column of fields by ensuring that words in each \ncolumn are separated by at least one space. \nFurther, allow for each word in a column to be either left \njustified, right justified, or center justified within its column. \n Given a text file of many lines, where fields within a line \n are delineated by a single 'dollar' character, write a program\n that aligns each column of fields by ensuring that words in each \n column are separated by at least one space.\n Further, allow for each word in a column to be either left \n justified, right justified, or center justified within its column.\n Given a text file of many lines, where fields within a line \n are delineated by a single 'dollar' character, write a program \n that aligns each column of fields by ensuring that words in each \n column are separated by at least one space. \n Further, allow for each word in a column to be either left \njustified, right justified, or center justified within its column. \n\n","human_summarization":"The code reads a text file where fields within a line are separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows for words in a column to be left justified, right justified, or center justified. The code disregards trailing dollar characters, consecutive spaces at the end of lines, and does not require separating characters between or around columns. The minimum space between columns is computed from the text.","id":36} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO;\n\nprocedure Main is\n type Char_Matrix is\n array (Positive range <>, Positive range <>) of Character;\n\n function Create_Cuboid\n (Width, Height, Depth : Positive)\n return Char_Matrix\n is\n Result : Char_Matrix (1 .. Height + Depth + 3,\n 1 .. 2 * Width + Depth + 3) := (others => (others => ' '));\n begin\n -- points\n Result (1, 1) := '+';\n Result (Height + 2, 1) := '+';\n Result (1, 2 * Width + 2) := '+';\n Result (Height + 2, 2 * Width + 2) := '+';\n Result (Height + Depth + 3, Depth + 2) := '+';\n Result (Depth + 2, 2 * Width + Depth + 3) := '+';\n Result (Height + Depth + 3, 2 * Width + Depth + 3) := '+';\n -- width lines\n for I in 1 .. 2 * Width loop\n Result (1, I + 1) := '-';\n Result (Height + 2, I + 1) := '-';\n Result (Height + Depth + 3, Depth + I + 2) := '-';\n end loop;\n -- height lines\n for I in 1 .. Height loop\n Result (I + 1, 1) := '|';\n Result (I + 1, 2 * Width + 2) := '|';\n Result (Depth + I + 2, 2 * Width + Depth + 3) := '|';\n end loop;\n -- depth lines\n for I in 1 .. Depth loop\n Result (Height + 2 + I, 1 + I) := '\/';\n Result (1 + I, 2 * Width + 2 + I) := '\/';\n Result (Height + 2 + I, 2 * Width + 2 + I) := '\/';\n end loop;\n return Result;\n end Create_Cuboid;\n\n procedure Print_Cuboid (Width, Height, Depth : Positive) is\n Cuboid : Char_Matrix := Create_Cuboid (Width, Height, Depth);\n begin\n for Row in reverse Cuboid'Range (1) loop\n for Col in Cuboid'Range (2) loop\n Ada.Text_IO.Put (Cuboid (Row, Col));\n end loop;\n Ada.Text_IO.New_Line;\n end loop;\n end Print_Cuboid;\nbegin\n Print_Cuboid (2, 3, 4);\nend Main;\n\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, using either static or rotational projection. A single width unit in ASCII art is represented by two characters long ('--').","id":37} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO.Text_Streams; use Ada.Text_IO.Text_Streams;\nwith Ada.Strings.Maps; use Ada.Strings.Maps;\nwith Ada.Command_Line; use Ada.Command_Line;\n\nprocedure Rot_13 is\n \n From_Sequence : Character_Sequence := \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n Result_Sequence : Character_Sequence := \"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM\";\n Rot_13_Mapping : Character_Mapping := To_Mapping(From_Sequence, Result_Sequence);\n\n In_Char : Character;\n Stdio : Stream_Access := Stream(Ada.Text_IO.Standard_Input);\n Stdout : Stream_Access := Stream(Ada.Text_Io.Standard_Output);\n Input : Ada.Text_Io.File_Type;\n \nbegin\n if Argument_Count > 0 then\n for I in 1..Argument_Count loop\n begin\n Ada.Text_Io.Open(File => Input, Mode => Ada.Text_Io.In_File, Name => Argument(I));\n Stdio := Stream(Input);\n while not Ada.Text_Io.End_Of_File(Input) loop\n In_Char :=Character'Input(Stdio); \n Character'Output(Stdout, Value(Rot_13_Mapping, In_Char));\n end loop;\n Ada.Text_IO.Close(Input);\n exception\n when Ada.Text_IO.Name_Error =>\n Ada.Text_Io.Put_Line(File => Ada.Text_Io.Standard_Error, Item => \"File \" & Argument(I) & \" is not a file.\");\n when Ada.Text_Io.Status_Error =>\n Ada.Text_Io.Put_Line(File => Ada.Text_Io.Standard_Error, Item => \"File \" & Argument(I) & \" is already opened.\");\n end;\n end loop;\n else\n while not Ada.Text_Io.End_Of_File loop\n In_Char :=Character'Input(Stdio); \n Character'Output(Stdout, Value(Rot_13_Mapping, In_Char));\n end loop;\n end if;\nend Rot_13;\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":38} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Strings.Unbounded; use Ada.Strings.Unbounded;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nwith Ada.Containers.Generic_Array_Sort;\n\nprocedure Demo_Array_Sort is\n\n function \"+\" (S : String) return Unbounded_String renames To_Unbounded_String;\n\n type A_Composite is\n record\n Name : Unbounded_String;\n Value : Unbounded_String;\n end record;\n\n function \"<\" (L, R : A_Composite) return Boolean is\n begin\n return L.Name < R.Name;\n end \"<\";\n\n procedure Put_Line (C : A_Composite) is\n begin\n Put_Line (To_String (C.Name) & \" \" & To_String (C.Value));\n end Put_Line;\n\n type An_Array is array (Natural range <>) of A_Composite;\n\n procedure Sort is new Ada.Containers.Generic_Array_Sort (Natural, A_Composite, An_Array);\n\n Data : An_Array := (1 => (Name => +\"Joe\", Value => +\"5531\"),\n 2 => (Name => +\"Adam\", Value => +\"2341\"),\n 3 => (Name => +\"Bernie\", Value => +\"122\"),\n 4 => (Name => +\"Walter\", Value => +\"1234\"),\n 5 => (Name => +\"David\", Value => +\"19\"));\n\nbegin\n Sort (Data);\n for I in Data'Range loop\n Put_Line (Data (I));\n end loop;\nend Demo_Array_Sort;\n\n\n C:\\Ada\\sort_composites\\lib\\demo_array_sort\n Adam 2341\n Bernie 122\n David 19\n Joe 5531\n Walter 1234\n\n\nwith Ada.Strings.Unbounded; use Ada.Strings.Unbounded;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nwith Ada.Containers.Ordered_Sets;\n\nprocedure Sort_Composites is\n\n function \"+\" (S : String) return Unbounded_String renames To_Unbounded_String;\n\n type A_Composite is\n record\n Name : Unbounded_String;\n Value : Unbounded_String;\n end record;\n\n function \"<\" (L, R : A_Composite) return Boolean is\n begin\n return L.Name < R.Name;\n end \"<\";\n\n procedure Put_Line (C : A_Composite) is\n begin\n Put_Line (To_String (C.Name) & \" \" & To_String (C.Value));\n end Put_Line;\n\n package Composite_Sets is new Ada.Containers.Ordered_Sets (A_Composite);\n\n procedure Put_Line (C : Composite_Sets.Cursor) is\n begin\n Put_Line (Composite_Sets.Element (C));\n end Put_Line;\n\n Data : Composite_Sets.Set;\n\nbegin\n Data.Insert (New_Item => (Name => +\"Joe\", Value => +\"5531\"));\n Data.Insert (New_Item => (Name => +\"Adam\", Value => +\"2341\"));\n Data.Insert (New_Item => (Name => +\"Bernie\", Value => +\"122\"));\n Data.Insert (New_Item => (Name => +\"Walter\", Value => +\"1234\"));\n Data.Insert (New_Item => (Name => +\"David\", Value => +\"19\"));\n Data.Iterate (Put_Line'Access);\nend Sort_Composites;\n\n\n C:\\Ada\\sort_composites\\lib\\sort_composites\n Adam 2341\n Bernie 122\n David 19\n Joe 5531\n Walter 1234\n\n\nwith Ada.Text_Io;\nwith Ada.Strings.Unbounded; use Ada.Strings.Unbounded;\n\nprocedure Sort_Composite is\n type Composite_Record is record\n Name : Unbounded_String;\n Value : Unbounded_String;\n end record;\n \n type Pairs_Array is array(Positive range <>) of Composite_Record;\n \n procedure Swap(Left, Right : in out Composite_Record) is\n Temp : Composite_Record := Left;\n begin\n Left := Right;\n Right := Temp;\n end Swap; \n \n -- Sort_Names uses a bubble sort\n \n procedure Sort_Name(Pairs : in out Pairs_Array) is\n Swap_Performed : Boolean := True;\n begin\n while Swap_Performed loop\n Swap_Performed := False;\n for I in Pairs'First..(Pairs'Last - 1) loop\n if Pairs(I).Name > Pairs(I + 1).Name then\n Swap (Pairs(I), Pairs(I + 1));\n Swap_Performed := True;\n end if;\n end loop;\n end loop;\n end Sort_Name;\n \n procedure Print(Item : Pairs_Array) is\n begin\n for I in Item'range loop\n Ada.Text_Io.Put_Line(To_String(Item(I).Name) & \", \" & \n to_String(Item(I).Value));\n end loop;\n end Print;\n type Names is (Fred, Barney, Wilma, Betty, Pebbles);\n type Values is (Home, Work, Cook, Eat, Bowl);\n My_Pairs : Pairs_Array(1..5);\nbegin\n for I in My_Pairs'range loop\n My_Pairs(I).Name := To_Unbounded_String(Names'Image(Names'Val(Integer(I - 1))));\n My_Pairs(I).Value := To_Unbounded_String(Values'Image(Values'Val(Integer(I - 1))));\n end loop;\n Print(My_Pairs);\n Ada.Text_Io.Put_Line(\"=========================\");\n Sort_Name(My_Pairs);\n Print(My_Pairs);\nend Sort_Composite;\n\n","human_summarization":"define a composite structure named pair with two string properties: name and value. It also creates an array of such pairs. Then, it sorts this array by the key 'name' using a custom comparator. In Ada 2005, it uses standard subprograms for sorting both constrained and unconstrained arrays. It also provides ordered containers, eliminating the need for explicit sorting calls. For Ada 95, a simple bubble sort function is implemented as there is no standard sort function.","id":39} {"lang_cluster":"Ada","source_code":"\nfor I in 1..5 loop\n for J in 1..I loop\n Put(\"*\");\n end loop;\n New_Line;\nend loop;\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":40} {"lang_cluster":"Ada","source_code":"\nWorks with: GNAT version GPL 2007\nwith Ada.Containers.Ordered_Maps;\nwith Ada.Strings.Unbounded; use Ada.Strings.Unbounded;\nwith Ada.Text_IO;\n\nprocedure Associative_Array is\n \n -- Instantiate the generic package Ada.Containers.Ordered_Maps\n\n package Associative_Int is new Ada.Containers.Ordered_Maps(Unbounded_String, Integer);\n use Associative_Int;\n \n Color_Map : Map;\n Color_Cursor : Cursor;\n Success : Boolean;\n Value : Integer;\nbegin\n\n -- Add values to the ordered map\n\n Color_Map.Insert(To_Unbounded_String(\"Red\"), 10, Color_Cursor, Success);\n Color_Map.Insert(To_Unbounded_String(\"Blue\"), 20, Color_Cursor, Success);\n Color_Map.Insert(To_Unbounded_String(\"Yellow\"), 5, Color_Cursor, Success);\n\n -- retrieve values from the ordered map and print the value and key\n -- to the screen\n\n Value := Color_Map.Element(To_Unbounded_String(\"Red\"));\n Ada.Text_Io.Put_Line(\"Red:\" & Integer'Image(Value));\n Value := Color_Map.Element(To_Unbounded_String(\"Blue\"));\n Ada.Text_IO.Put_Line(\"Blue:\" & Integer'Image(Value));\n Value := Color_Map.Element(To_Unbounded_String(\"Yellow\"));\n Ada.Text_IO.Put_Line(\"Yellow:\" & Integer'Image(Value));\nend Associative_Array;\n\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":41} {"lang_cluster":"Ada","source_code":"\n\ngeneric\n type Base_Type is mod <>;\n Multiplyer, Adder: Base_Type;\n Output_Divisor: Base_Type := 1;\npackage LCG is\n\n procedure Initialize(Seed: Base_Type);\n function Random return Base_Type;\n -- changes the state and outputs the result\n\nend LCG;\n\n\npackage body LCG is\n\n State: Base_Type := Base_Type'First;\n\n procedure Initialize(Seed: Base_Type) is\n begin\n State := Seed;\n end Initialize;\n\n function Random return Base_Type is\n begin\n State := State * Multiplyer + Adder;\n return State \/ Output_Divisor;\n end Random;\n\nend LCG;\n\n\nwith Ada.Text_IO, LCG;\n\nprocedure Run_LCGs is\n\n type M31 is mod 2**31;\n\n package BSD_Rand is new LCG(Base_Type => M31, Multiplyer => 1103515245,\n Adder => 12345);\n\n package MS_Rand is new LCG(Base_Type => M31, Multiplyer => 214013,\n Adder => 2531011, Output_Divisor => 2**16);\n\nbegin\n for I in 1 .. 10 loop\n Ada.Text_IO.Put_Line(M31'Image(BSD_Rand.Random));\n end loop;\n for I in 1 .. 10 loop\n Ada.Text_IO.Put_Line(M31'Image(MS_Rand.Random));\n end loop;\nend Run_LCGs;\n\n\n 12345\n 1406932606\n 654583775\n 1449466924\n 229283573\n 1109335178\n 1051550459\n 1293799192\n 794471793\n 551188310\n 38\n 7719\n 21238\n 2437\n 8855\n 11797\n 8365\n 32285\n 10450\n 30612\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). The generators are based on the Linear Congruential Generator (LCG) formula and are designed to replicate the same sequence of integers as the original generators when given the same seed. The code also includes a generic package for LCG and specific implementations for the BSD and Microsoft formulas.","id":42} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Unchecked_Deallocation;\n-- Define the link type\nprocedure Singly_Linked is\n \n type Link;\n type Link_Access is access Link;\n type Link is record\n Data : Integer;\n Next : Link_Access := null;\n end record;\n -- Instantiate the generic deallocator for the link type\n procedure Free is new Ada.Unchecked_Deallocation(Link, Link_Access);\n\n -- Define the procedure\n procedure Insert_Append(Anchor : Link_Access; Newbie : Link_Access) is\n begin\n if Anchor \/= null and Newbie \/= null then\n Newbie.Next := Anchor.Next;\n Anchor.Next := Newbie;\n end if;\n end Insert_Append;\n\n -- Create the link elements\n A : Link_Access := new Link'(1, null);\n B : Link_Access := new Link'(2, null);\n C : Link_Access := new Link'(3, null); \n-- Execute the program\nbegin\n Insert_Append(A, B);\n Insert_Append(A, C);\n Free(A);\n Free(B);\n Free(C);\nend Singly_Linked;\n\n","human_summarization":"define a method for inserting an element into a singly-linked list after a specified element. The method is used to insert an element 'C' into a list containing elements 'A' and 'B', specifically after element 'A'. The code also makes the predefined generic procedure 'Ada.Unchecked_Deallocation' visible in its context.","id":43} {"lang_cluster":"Ada","source_code":"\nwith ada.text_io;use ada.text_io;\n\nprocedure ethiopian is\n function double (n : Natural) return Natural is (2*n);\n function halve (n : Natural) return Natural is (n\/2);\n function is_even (n : Natural) return Boolean is (n mod 2 = 0);\n \n function mul (l, r : Natural) return Natural is \n (if l = 0 then 0 elsif l = 1 then r elsif is_even (l) then mul (halve (l),double (r)) \n else r + double (mul (halve (l), r)));\n \nbegin\n put_line (mul (17,34)'img);\nend ethiopian;\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":44} {"lang_cluster":"Ada","source_code":"\nfunction Factorial (N : Positive) return Positive is\n Result : Positive := N;\n Counter : Natural := N - 1;\nbegin\n for I in reverse 1..Counter loop\n Result := Result * I;\n end loop;\n return Result;\nend Factorial;\n\nfunction Factorial(N : Positive) return Positive is\n Result : Positive := 1;\nbegin\n if N > 1 then\n Result := N * Factorial(N - 1);\n end if;\n return Result;\nend Factorial;\n\nwith Ada.Numerics.Generic_Complex_Types;\nwith Ada.Numerics.Generic_Complex_Elementary_Functions;\nwith Ada.Numerics.Generic_Elementary_Functions;\nwith Ada.Text_IO.Complex_Io;\nwith Ada.Text_Io; use Ada.Text_Io;\n\nprocedure Factorial_Numeric_Approximation is\n type Real is digits 15;\n package Complex_Pck is new Ada.Numerics.Generic_Complex_Types(Real);\n use Complex_Pck;\n package Complex_Io is new Ada.Text_Io.Complex_Io(Complex_Pck);\n use Complex_IO;\n package Cmplx_Elem_Funcs is new Ada.Numerics.Generic_Complex_Elementary_Functions(Complex_Pck);\n use Cmplx_Elem_Funcs;\n \n function Gamma(X : Complex) return Complex is\n package Elem_Funcs is new Ada.Numerics.Generic_Elementary_Functions(Real);\n use Elem_Funcs;\n use Ada.Numerics;\n -- Coefficients used by the GNU Scientific Library\n G : Natural := 7;\n P : constant array (Natural range 0..G + 1) of Real := (\n 0.99999999999980993, 676.5203681218851, -1259.1392167224028,\n 771.32342877765313, -176.61502916214059, 12.507343278686905,\n -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7);\n Z : Complex := X;\n Cx : Complex;\n Ct : Complex;\n begin\n if Re(Z) < 0.5 then\n return Pi \/ (Sin(Pi * Z) * Gamma(1.0 - Z));\n else\n Z := Z - 1.0;\n Set_Re(Cx, P(0));\n Set_Im(Cx, 0.0);\n for I in 1..P'Last loop\n Cx := Cx + (P(I) \/ (Z + Real(I)));\n end loop;\n Ct := Z + Real(G) + 0.5;\n return Sqrt(2.0 * Pi) * Ct**(Z + 0.5) * Exp(-Ct) * Cx;\n end if;\n end Gamma;\n \n function Factorial(N : Complex) return Complex is\n begin\n return Gamma(N + 1.0);\n end Factorial;\n Arg : Complex;\nbegin\n Put(\"factorial(-0.5)**2.0 = \");\n Set_Re(Arg, -0.5);\n Set_Im(Arg, 0.0);\n Put(Item => Factorial(Arg) **2.0, Fore => 1, Aft => 8, Exp => 0);\n New_Line;\n for I in 0..9 loop\n Set_Re(Arg, Real(I));\n Set_Im(Arg, 0.0);\n Put(\"factorial(\" & Integer'Image(I) & \") = \");\n Put(Item => Factorial(Arg), Fore => 6, Aft => 8, Exp => 0);\n New_Line;\n end loop;\nend Factorial_Numeric_Approximation;\n\n\n","human_summarization":"The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.","id":45} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Numerics.Discrete_Random;\n\nprocedure Bulls_And_Cows is\n package Random_Natural is new Ada.Numerics.Discrete_Random (Natural);\n Number : String (1..4);\nbegin\n declare -- Generation of number\n use Random_Natural;\n Digit : String := \"123456789\";\n Size : Positive := 9;\n Dice : Generator;\n Position : Natural;\n begin\n Reset (Dice);\n for I in Number'Range loop\n Position := Random (Dice) mod Size + 1;\n Number (I) := Digit (Position);\n Digit (Position..Size - 1) := Digit (Position + 1..Size);\n Size := Size - 1;\n end loop;\n end;\n loop -- Guessing loop\n Put (\"Enter four digits:\");\n declare\n Guess : String := Get_Line;\n Bulls : Natural := 0;\n Cows : Natural := 0;\n begin\n if Guess'Length \/= 4 then\n raise Data_Error;\n end if;\n for I in Guess'Range loop\n for J in Number'Range loop \n if Guess (I) not in '1'..'9' or else (I < J and then Guess (I) = Guess (J)) then\n raise Data_Error;\n end if;\n if Number (I) = Guess (J) then\n if I = J then\n Bulls := Bulls + 1;\n else\n Cows := Cows + 1;\n end if;\n end if;\n end loop;\n end loop;\n exit when Bulls = 4;\n Put_Line (Integer'Image (Bulls) & \" bulls,\" & Integer'Image (Cows) & \" cows\");\n exception\n when Data_Error => Put_Line (\"You should enter four different digits 1..9\");\n end;\n end loop;\nend Bulls_And_Cows;\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":46} {"lang_cluster":"Ada","source_code":"\nwith Ada.Numerics; use Ada.Numerics;\nwith Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;\nwith Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;\n\nprocedure Normal_Random is\n function Normal_Distribution\n ( Seed : Generator;\n Mu : Float := 1.0;\n Sigma : Float := 0.5\n ) return Float is \n begin\n return\n Mu + (Sigma * Sqrt (-2.0 * Log (Random (Seed), 10.0)) * Cos (2.0 * Pi * Random (Seed)));\n end Normal_Distribution;\n \n Seed : Generator;\n Distribution : array (1..1_000) of Float; \nbegin\n Reset (Seed);\n for I in Distribution'Range loop\n Distribution (I) := Normal_Distribution (Seed);\n end loop;\nend Normal_Random;\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":47} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\nprocedure dot_product is\n\ttype vect is array(Positive range <>) of Integer;\n\tv1 : vect := (1,3,-5);\n\tv2 : vect := (4,-2,-1);\n\n\tfunction dotprod(a: vect; b: vect) return Integer is\n\t\tsum : Integer := 0;\n\t\tbegin\n\t\tif not (a'Length=b'Length) then raise Constraint_Error; end if;\n\t\tfor p in a'Range loop\n\t\t\tsum := sum + a(p)*b(p);\n\t\tend loop;\n\t\treturn sum;\n\tend dotprod;\n\t\nbegin\nput_line(Integer'Image(dotprod(v1,v2)));\nend dot_product;\n\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":48} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_Io; use Ada.Text_Io;\n\nprocedure Read_Stream is\n Line : String(1..10);\n Length : Natural;\nbegin\n while not End_Of_File loop\n Get_Line(Line, Length); -- read up to 10 characters at a time\n Put(Line(1..Length));\n -- The current line of input data may be longer than the string receiving the data.\n -- If so, the current input file column number will be greater than 0\n -- and the extra data will be unread until the next iteration.\n -- If not, we have read past an end of line marker and col will be 1\n if Col(Current_Input) = 1 then\n New_Line;\n end if;\n end loop;\nend Read_Stream;\n\n","human_summarization":"\"Code reads a text stream from standard input either word-by-word or line-by-line until no more data is available, then writes the output to standard output.\"","id":49} {"lang_cluster":"Ada","source_code":"\nWorks with: GNAT\n\nwith Ada.Text_IO.Text_Streams;\nwith DOM.Core.Documents;\nwith DOM.Core.Nodes;\n\nprocedure Serialization is\n My_Implementation : DOM.Core.DOM_Implementation;\n My_Document : DOM.Core.Document;\n My_Root_Node : DOM.Core.Element;\n My_Element_Node : DOM.Core.Element;\n My_Text_Node : DOM.Core.Text;\nbegin\n My_Document := DOM.Core.Create_Document (My_Implementation);\n My_Root_Node := DOM.Core.Documents.Create_Element (My_Document, \"root\");\n My_Root_Node := DOM.Core.Nodes.Append_Child (My_Document, My_Root_Node);\n My_Element_Node := DOM.Core.Documents.Create_Element (My_Document, \"element\");\n My_Element_Node := DOM.Core.Nodes.Append_Child (My_Root_Node, My_Element_Node);\n My_Text_Node := DOM.Core.Documents.Create_Text_Node (My_Document, \"Some text here\");\n My_Text_Node := DOM.Core.Nodes.Append_Child (My_Element_Node, My_Text_Node);\n DOM.Core.Nodes.Write\n (Stream => Ada.Text_IO.Text_Streams.Stream\n (Ada.Text_IO.Standard_Output),\n N => My_Document,\n Pretty_Print => True);\nend Serialization;\n\n\n\n\n Some text here<\/element>\n<\/root>\n","human_summarization":"create a simple DOM and serialize it to XML format using XML\/Ada from AdaCore. The code can be optimized by adding \"use\" clauses and writing the creation functions in the declaration part.","id":50} {"lang_cluster":"Ada","source_code":"\nThe following example displays a date-time stamp. The time zone value is the number of minutes offset from the prime meridian.with Ada.Calendar; use Ada.Calendar;\nwith Ada.Calendar.Formatting; use Ada.Calendar.Formatting;\nwith Ada.Calendar.Time_Zones; use Ada.Calendar.Time_Zones;\nwith Ada.Text_Io; use Ada.Text_Io;\n \nprocedure System_Time is\n Now : Time := Clock;\nbegin\n Put_line(Image(Date => Now, Time_Zone => -7*60));\nend System_Time;\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":51} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_SEDOL is\n\n subtype SEDOL_String is String (1..6);\n type SEDOL_Sum is range 0..9;\n\n function Check (SEDOL : SEDOL_String) return SEDOL_Sum is\n Weight : constant array (SEDOL_String'Range) of Integer := (1,3,1,7,3,9);\n Sum : Integer := 0;\n Item : Integer;\n begin\n for Index in SEDOL'Range loop\n Item := Character'Pos (SEDOL (Index));\n case Item is\n when Character'Pos ('0')..Character'Pos ('9') =>\n Item := Item - Character'Pos ('0');\n when Character'Pos ('B')..Character'Pos ('D') |\n Character'Pos ('F')..Character'Pos ('H') |\n Character'Pos ('J')..Character'Pos ('N') |\n Character'Pos ('P')..Character'Pos ('T') |\n Character'Pos ('V')..Character'Pos ('Z') =>\n Item := Item - Character'Pos ('A') + 10;\n when others =>\n raise Constraint_Error;\n end case;\n Sum := Sum + Item * Weight (Index);\n end loop;\n return SEDOL_Sum ((-Sum) mod 10);\n end Check;\n\n Test : constant array (1..10) of SEDOL_String :=\n ( \"710889\", \"B0YBKJ\", \"406566\", \"B0YBLH\", \"228276\",\n \"B0YBKL\", \"557910\", \"B0YBKR\", \"585284\", \"B0YBKT\"\n );\nbegin\n for Index in Test'Range loop\n Put_Line (Test (Index) & Character'Val (Character'Pos ('0') + Check (Test (Index))));\n end loop;\nend Test_SEDOL;\n\n\n7108899\nB0YBKJ7\n4065663\nB0YBLH2\n2282765\nB0YBKL9\n5579107\nB0YBKR5\n5852842\nB0YBKT7\n","human_summarization":"The code calculates and appends the checksum digit for each 6-digit SEDOL number in the given list. It also verifies the validity of each input SEDOL string and raises a Constraint_Error for any invalid input. The checksum is computed using the formula (-sum) mod 10.","id":52} {"lang_cluster":"Ada","source_code":"\nLibrary: GtkAda\n\n\nwith Glib; use Glib;\nwith Cairo; use Cairo;\nwith Cairo.Png; use Cairo.Png;\nwith Cairo.Pattern; use Cairo.Pattern;\nwith Cairo.Image_Surface; use Cairo.Image_Surface;\nwith Ada.Numerics;\n\nprocedure Sphere is\n subtype Dub is Glib.Gdouble;\n\n Surface : Cairo_Surface;\n Cr : Cairo_Context;\n Pat : Cairo_Pattern;\n Status_Out : Cairo_Status;\n M_Pi : constant Dub := Dub (Ada.Numerics.Pi);\n\nbegin\n Surface := Create (Cairo_Format_ARGB32, 512, 512);\n Cr := Create (Surface);\n Pat :=\n Cairo.Pattern.Create_Radial (230.4, 204.8, 51.1, 204.8, 204.8, 256.0);\n Cairo.Pattern.Add_Color_Stop_Rgba (Pat, 0.0, 1.0, 1.0, 1.0, 1.0);\n Cairo.Pattern.Add_Color_Stop_Rgba (Pat, 1.0, 0.0, 0.0, 0.0, 1.0);\n Cairo.Set_Source (Cr, Pat);\n Cairo.Arc (Cr, 256.0, 256.0, 153.6, 0.0, 2.0 * M_Pi);\n Cairo.Fill (Cr);\n Cairo.Pattern.Destroy (Pat);\n Status_Out := Write_To_Png (Surface, \"SphereAda.png\");\n pragma Assert (Status_Out = Cairo_Status_Success);\nend Sphere;\n\nLibrary: Display\n\nwith Display; use Display;\nwith Display.Basic; use Display.Basic;\n\nprocedure Main is\n Ball : Shape_Id := New_Circle\n (X => 0.0,\n Y => 0.0,\n Radius => 20.0,\n Color => Blue);\nbegin\n null;\nend Main;\n\n","human_summarization":"The code generates a graphical or ASCII representation of a sphere, using either static or rotational projection. It translates from the C code found at the specified URL, utilizing the Cairo component of GtkAda to create and save the sphere as a PNG. The code operates on a loose binding to SDL, requiring a new project to be initiated from an empty game template in the GPS installation.","id":53} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\n\nprocedure Nth is\n \n function Suffix(N: Natural) return String is\n begin\n if N mod 10 = 1 and then N mod 100 \/= 11 then return \"st\";\n elsif N mod 10 = 2 and then N mod 100 \/= 12 then return \"nd\";\n elsif N mod 10 = 3 and then N mod 100 \/= 13 then return \"rd\";\n else return \"th\";\n end if;\n end Suffix;\n \n procedure Print_Images(From, To: Natural) is\n begin\n for I in From .. To loop\n\t Ada.Text_IO.Put(Natural'Image(I) & Suffix(I));\n end loop;\n Ada.Text_IO.New_Line;\n end Print_Images;\n \nbegin\n Print_Images( 0, 25);\n Print_Images( 250, 265);\n Print_Images(1000, 1025);\nend Nth;\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":54} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\n\nprocedure Strip_Characters_From_String is\n\n function Strip(The_String: String; The_Characters: String)\n return String is\n Keep: array (Character) of Boolean := (others => True);\n Result: String(The_String'Range);\n Last: Natural := Result'First-1;\n begin\n for I in The_Characters'Range loop\n Keep(The_Characters(I)) := False;\n end loop;\n for J in The_String'Range loop\n if Keep(The_String(J)) then\n Last := Last+1;\n Result(Last) := The_String(J);\n end if;\n end loop;\n return Result(Result'First .. Last);\n end Strip;\n\n S: String := \"She was a soul stripper. She took my heart!\";\n\nbegin -- main\n Ada.Text_IO.Put_Line(Strip(S, \"aei\"));\nend Strip_Characters_From_String;\n\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":55} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Integer_Text_IO; use Ada.Integer_Text_IO;\nwith Ada.Containers.Generic_Array_Sort;\nwith Ada.Strings.Unbounded; use Ada.Strings.Unbounded;\nwith Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;\n\nprocedure Main is\n type map_element is record\n Num : Positive;\n Word : Unbounded_String;\n end record;\n\n type map_list is array (Positive range <>) of map_element;\n\n function \"<\" (Left, Right : map_element) return Boolean is\n begin\n return Left.Num < Right.Num;\n end \"<\";\n\n procedure list_sort is new Ada.Containers.Generic_Array_Sort\n (Index_Type => Positive, Element_Type => map_element,\n Array_Type => map_list);\n \n procedure general_fizz_buzz (max : Positive; words : in out map_list) is\n found : Boolean;\n begin\n list_sort (words);\n\n for i in 1 .. max loop\n found := False;\n for element of words loop\n if i mod element.Num = 0 then\n found := True;\n Put (element.Word);\n end if;\n end loop;\n if not found then\n Put (Item => i, Width => 1);\n end if;\n New_Line;\n end loop;\n end general_fizz_buzz;\n\n fizzy : map_list :=\n ((3, To_Unbounded_String (\"FIZZ\")), (7, To_Unbounded_String (\"BAXX\")),\n (5, To_Unbounded_String (\"BUZZ\")));\n\nbegin\n general_fizz_buzz (20, fizzy);\nend Main;\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":56} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;\n\nprocedure Prepend_String is \n S: Unbounded_String := To_Unbounded_String(\"World!\"); \nbegin\n S := \"Hello \" & S;-- this is the operation to prepend \"Hello \" to S. \n Ada.Text_IO.Put_Line(To_String(S));\nend Prepend_String;\n\n\n","human_summarization":"create a string variable with a specific text value, prepend another string literal to this variable, and display the content of the updated variable. If possible, the task is performed idiomatically without referring to the variable twice. In Ada language, due to the immutability of string length, an Unbounded_String type variable is used, requiring conversions for initialization and printing.","id":57} {"lang_cluster":"Ada","source_code":"\n\n\n-- FILE: dragon_curve.gpr --\nwith \"gtkada\";\n\nproject Dragon_Curve is\n Adaflags := External_As_List (\"ADAFLAGS\", \" \");\n Ldflags := External_As_List (\"LDFLAGS\", \" \");\n\n for Languages use (\"Ada\");\n for Main use (\"dragon_curve.adb\");\n for Source_Dirs use (\".\/\");\n for Object_Dir use \"obj\/\";\n for Exec_Dir use \".\";\n\n package Compiler is\n for Switches (\"Ada\") use (\"-g\", \"-O0\", \"-gnaty-s\", \"-gnatwJ\")\n & Adaflags;\n end Compiler;\n\n package Linker is\n for Leading_Switches (\"Ada\") use Ldflags;\n end Linker;\n\nend Dragon_Curve;\n\n-- FILE: dragon_curve.adb --\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Events; use Events;\nwith GLib.Main; use GLib.Main;\nwith GTK;\nwith GTK.Drawing_Area; use GTK.Drawing_Area;\nwith GTK.Main;\nwith GTK.Window; use GTK.Window;\n\nprocedure Dragon_Curve is\n Window : GTK_Window;\nbegin\n GTK.Main.Init; \n GTK_New (Window);\n GTK_New (Drawing_Area);\n Window.Add (Drawing_Area);\n Drawing_Area.On_Draw (Events.Draw'Access, Drawing_Area);\n Show_All (Window);\n Resize (Window, 800, 800);\n GTK.Main.Main;\nend Dragon_Curve;\n\n-- FILE: events.ads --\nwith Ada.Numerics.Generic_Elementary_Functions;\nwith Cairo;\nwith GLib; use Glib;\nwith GTK.Drawing_Area; use GTK.Drawing_Area;\nwith GTK.Widget; use GTK.Widget;\nwith GLib.Object; use GLib.Object;\n\npackage Events is\n Drawing_Area : GTK_Drawing_Area;\n\n package GDouble_Elementary_Functions is new Ada.Numerics.Generic_Elementary_Functions (Float);\n use GDouble_Elementary_Functions;\n\n function Draw (Self : access GObject_Record'Class;\n CC : Cairo.Cairo_Context)\n return Boolean;\nend Events;\n\n-- FILE: events.adb --\nwith Cairo;\nwith GTK;\n\npackage body Events is\n function Draw (Self : access GObject_Record'Class;\n CC : Cairo.Cairo_Context)\n return Boolean\n is\n type Rotate_Type is (Counterclockwise, Clockwise);\n\n type Point is record\n X, Y : GDouble;\n end record;\n \n procedure Heighway_Branch (CC : Cairo.Cairo_Context;\n A, B : Point;\n Rotate : Rotate_Type;\n N : Natural)\n is\n R, RU, C : Point;\n begin\n if N = 0 then\n Cairo.Move_To (CC, A.X, A.Y); \n Cairo.Line_To (CC, B.X, B.Y);\n Cairo.Stroke (CC);\n else \n -- Rotate 45 degrees --\n case Rotate is\n when Clockwise =>\n R.X := GDouble ((1.0 \/ Sqrt (2.0)) * Float (B.X - A.X)\n - (1.0 \/ Sqrt (2.0)) * Float (B.Y - A.Y));\n R.Y := GDouble ((1.0 \/ Sqrt (2.0)) * Float (B.X - A.X)\n + (1.0 \/ Sqrt (2.0)) * Float (B.Y - A.Y));\n when Counterclockwise =>\n R.X := GDouble ((1.0 \/ Sqrt (2.0)) * Float (B.X - A.X) \n + (1.0 \/ Sqrt (2.0)) * Float (B.Y - A.Y));\n R.Y := GDouble (-(1.0 \/ Sqrt (2.0)) * Float (B.X - A.X)\n + (1.0 \/ Sqrt (2.0)) * Float (B.Y - A.Y));\n end case;\n\n -- Make unit vector from rotation --\n RU.X := GDouble (Float (R.X) \/ Sqrt ( Float (R.X ** 2 + R.Y ** 2)));\n RU.Y := GDouble (Float (R.Y) \/ Sqrt ( Float (R.X ** 2 + R.Y ** 2)));\n\n -- Scale --\n R.X := RU.X * GDouble (Sqrt (Float (B.X - A.X) ** 2 + Float (B.Y - A.Y) ** 2) \/ Sqrt (2.0));\n R.Y := RU.Y * GDouble (Sqrt (Float (B.X - A.X) ** 2 + Float (B.Y - A.Y) ** 2) \/ Sqrt (2.0));\n\n C := (R.X + A.X, R.Y + A.Y);\n \n Heighway_Branch (CC, A, C, Clockwise, N - 1);\n Heighway_Branch (CC, C, B, Counterclockwise, N - 1);\n end if;\n end Heighway_Branch;\n\n Depth : constant := 14;\n Center, Right, Bottom, Left: Point;\n Width : GDouble := GDouble (Drawing_Area.Get_Allocated_Width);\n Height : GDouble := GDouble (Drawing_Area.Get_Allocated_Height);\n\n begin\n Center := (Width \/ 2.0, Height \/ 2.0);\n Right := (Width, Height \/ 2.0);\n Left := (0.0, Height \/ 2.0);\n Bottom := (Width \/ 2.0, Height);\n\n Cairo.Set_Source_RGB (CC, 0.0, 1.0, 0.0);\n Heighway_Branch (CC, Center, Right, Clockwise, Depth);\n Cairo.Set_Source_RGB (CC, 0.0, 1.0, 1.0);\n Heighway_Branch (CC, Center, Left, Clockwise, Depth);\n Cairo.Set_Source_RGB (CC, 0.0, 1.0, 0.5);\n Heighway_Branch (CC, Center, Bottom, Clockwise, Depth);\n \n return True;\n end Draw;\nend Events;\n\n","human_summarization":"The code generates a dragon curve fractal, either displaying it directly or writing it to an image file. It uses various algorithms to create the fractal, including recursive, successive approximation, iterative, and Lindenmayer system methods. The code also includes functionality for determining the direction of the curve at each point, calculating absolute X,Y coordinates for each point, and testing whether a given point or segment is on the curve. It can also limit the curve to a certain number of points or a specific subsection. The code is written using GTKAda and Cairo.","id":58} {"lang_cluster":"Ada","source_code":"\nwith Ada.Numerics.Discrete_Random;\nwith Ada.Text_IO;\nprocedure Guess_Number is\n subtype Number is Integer range 1 .. 10;\n package Number_IO is new Ada.Text_IO.Integer_IO (Number);\n package Number_RNG is new Ada.Numerics.Discrete_Random (Number);\n Generator : Number_RNG.Generator;\n My_Number : Number;\n Your_Guess : Number;\nbegin\n Number_RNG.Reset (Generator);\n My_Number := Number_RNG.Random (Generator);\n Ada.Text_IO.Put_Line (\"Guess my number!\");\n loop\n Ada.Text_IO.Put (\"Your guess: \");\n Number_IO.Get (Your_Guess);\n exit when Your_Guess = My_Number;\n Ada.Text_IO.Put_Line (\"Wrong, try again!\");\n end loop;\n Ada.Text_IO.Put_Line (\"Well guessed!\");\nend Guess_Number;\n\n-------------------------------------------------------------------------------------------------------\n-- Another version ------------------------------------------------------------------------------------\n-------------------------------------------------------------------------------------------------------\n\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Integer_Text_IO; use Ada.Integer_Text_IO;\nwith Ada.Numerics.Discrete_Random;\n\n-- procedure main - begins program execution\nprocedure main is\nguess : Integer := 0;\ncounter : Integer := 0;\ntheNumber : Integer := 0;\n\n-- function generate number - creates and returns a random number between the\n-- ranges of 1 to 100\nfunction generateNumber return Integer is\n type randNum is new Integer range 1 .. 100;\n package Rand_Int is new Ada.Numerics.Discrete_Random(randNum);\n use Rand_Int;\n gen : Generator;\n numb : randNum;\n\nbegin\n Reset(gen);\n \n numb := Random(gen);\n \n return Integer(numb);\nend generateNumber;\n\n-- procedure intro - prints text welcoming the player to the game\nprocedure intro is\nbegin\n Put_Line(\"Welcome to Guess the Number\");\n Put_Line(\"===========================\");\n New_Line;\n \n Put_Line(\"Try to guess the number. It is in the range of 1 to 100.\");\n Put_Line(\"Can you guess it in the least amount of tries possible?\");\n New_Line;\nend intro;\n\nbegin\n New_Line;\n \n intro;\n theNumber := generateNumber;\n \n -- main game loop\n while guess \/= theNumber loop\n Put(\"Enter a guess: \");\n guess := integer'value(Get_Line);\n \n counter := counter + 1;\n \n if guess > theNumber then\n Put_Line(\"Too high!\");\n elsif guess < theNumber then\n Put_Line(\"Too low!\");\n end if;\n end loop;\n \n New_Line;\n \n Put_Line(\"CONGRATULATIONS! You guessed it!\");\n Put_Line(\"It took you a total of \" & integer'image(counter) & \" attempts.\");\n \n New_Line;\nend main;\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":59} {"lang_cluster":"Ada","source_code":"\n\n type Lower_Case is new Character range 'a' .. 'z';\n\n\n type Arr_Type is array (Integer range <>) of Lower_Case;\n A : Arr_Type (1 .. 26) := \"abcdefghijklmnopqrstuvwxyz\";\n\n\n B : Arr_Type (1 .. 26);\nbegin\n B(B'First) := 'a';\n for I in B'First .. B'Last-1 loop\n B(I+1) := Lower_Case'Succ(B(I));\n end loop; -- now all the B(I) are different\n\n","human_summarization":"generates an array or list of all lower case ASCII characters from a to z using a reliable and strongly typed coding style. It ensures no manual enumeration of characters, thus reducing the risk of bugs. It also checks for errors such as inclusion of upper-case letters or symbols, and incorrect number of letters. The code also prevents duplication of letters in the array.","id":60} {"lang_cluster":"Ada","source_code":"\nwith ada.text_io; use ada.text_io;\nprocedure binary is \n bit : array (0..1) of character := ('0','1');\n\n function bin_image (n : Natural) return string is \n (if n < 2 then (1 => bit (n)) else bin_image (n \/ 2) & bit (n mod 2));\n\n test_values : array (1..3) of Natural := (5,50,9000); \nbegin\n for test of test_values loop \n\tput_line (\"Output for\" & test'img & \" is \" & bin_image (test)); \n end loop; \nend binary;\n\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":61} {"lang_cluster":"Ada","source_code":"\nLibrary: SDLAda\nwith SDL.Video.Windows.Makers;\nwith SDL.Video.Renderers.Makers;\nwith SDL.Events.Events;\n\nprocedure Draw_A_Pixel is\n\n Width : constant := 320;\n Height : constant := 200;\n\n Window : SDL.Video.Windows.Window;\n Renderer : SDL.Video.Renderers.Renderer;\n\n procedure Wait is\n use type SDL.Events.Event_Types;\n Event : SDL.Events.Events.Events;\n begin\n loop\n while SDL.Events.Events.Poll (Event) loop\n if Event.Common.Event_Type = SDL.Events.Quit then\n return;\n end if;\n end loop;\n delay 0.100;\n end loop;\n end Wait;\n\nbegin\n if not SDL.Initialise (Flags => SDL.Enable_Screen) then\n return;\n end if;\n\n SDL.Video.Windows.Makers.Create (Win => Window,\n Title => \"Draw a pixel\",\n Position => SDL.Natural_Coordinates'(X => 10, Y => 10),\n Size => SDL.Positive_Sizes'(Width, Height),\n Flags => 0);\n SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface);\n Renderer.Set_Draw_Colour ((0, 0, 0, 255));\n Renderer.Fill (Rectangle => (0, 0, Width, Height));\n Renderer.Set_Draw_Colour ((255, 0, 0, 255));\n Renderer.Draw (Point => (100, 100));\n Window.Update_Surface;\n\n Wait;\n Window.Finalize;\n SDL.Finalise;\nend Draw_A_Pixel;\n\n","human_summarization":"\"Creates a 320x240 window and draws a single red pixel at position (100, 100).\"","id":62} {"lang_cluster":"Ada","source_code":"\nWorks with: Ada version 2005\n\nwith Config; use Config;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Rosetta_Read_Cfg is\n cfg: Configuration:= Init(\"rosetta_read.cfg\", Case_Sensitive => False, Variable_Terminator => ' ');\n fullname : String := cfg.Value_Of(\"*\", \"fullname\");\n favouritefruit : String := cfg.Value_Of(\"*\", \"favouritefruit\");\n needspeeling : Boolean := cfg.Is_Set(\"*\", \"needspeeling\");\n seedsremoved : Boolean := cfg.Is_Set(\"*\", \"seedsremoved\");\n otherfamily : String := cfg.Value_Of(\"*\", \"otherfamily\");\nbegin\n Put_Line(\"fullname = \" & fullname);\n Put_Line(\"favouritefruit = \" & favouritefruit);\n Put_Line(\"needspeeling = \" & Boolean'Image(needspeeling));\n Put_Line(\"seedsremoved = \" & Boolean'Image(seedsremoved));\n Put_Line(\"otherfamily = \" & otherfamily);\nend;\n\n\n","human_summarization":"The code reads a standard configuration file, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration entries, treating data as case sensitive. It also handles options with multiple parameters, storing them in an array. The code uses the Config package from SourceForge.","id":63} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;\nwith Ada.Numerics.Generic_Elementary_Functions;\n\nprocedure Haversine_Formula is\n\n package Math is new Ada.Numerics.Generic_Elementary_Functions (Long_Float); use Math;\n\n -- Compute great circle distance, given latitude and longitude of two points, in radians\n function Great_Circle_Distance (lat1, long1, lat2, long2 : Long_Float) return Long_Float is\n Earth_Radius : constant := 6371.0; -- in kilometers\n a : Long_Float := Sin (0.5 * (lat2 - lat1));\n b : Long_Float := Sin (0.5 * (long2 - long1));\n begin\n return 2.0 * Earth_Radius * ArcSin (Sqrt (a * a + Cos (lat1) * Cos (lat2) * b * b));\n end Great_Circle_Distance;\n\n -- convert degrees, minutes and seconds to radians\n function DMS_To_Radians (Deg, Min, Sec : Long_Float := 0.0) return Long_Float is\n Pi_Over_180 : constant := 0.017453_292519_943295_769236_907684_886127;\n begin\n return (Deg + Min\/60.0 + Sec\/3600.0) * Pi_Over_180;\n end DMS_To_Radians;\n\nbegin\n Put_Line(\"Distance in kilometers between BNA and LAX\");\n Put (Great_Circle_Distance (\n DMS_To_Radians (36.0, 7.2), DMS_To_Radians (86.0, 40.2), -- Nashville International Airport (BNA)\n DMS_To_Radians (33.0, 56.4), DMS_To_Radians (118.0, 24.0)), -- Los Angeles International Airport (LAX)\n Aft=>3, Exp=>0);\nend Haversine_Formula;\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":64} {"lang_cluster":"Ada","source_code":"\nLibrary: AWS\nwith Ada.Text_IO; use Ada.Text_IO;\n\nwith AWS.Client;\nwith AWS.Response;\n\nprocedure HTTP_Request is\nbegin\n Put_Line (AWS.Response.Message_Body (AWS.Client.Get (URL => \"http:\/\/www.rosettacode.org\")));\nend HTTP_Request;\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":65} {"lang_cluster":"Ada","source_code":"Works with: GNAT\nwith Ada.Text_IO;\nuse Ada.Text_IO;\n\nprocedure Luhn is\n\n function Luhn_Test (Number: String) return Boolean is\n Sum : Natural := 0;\n Odd : Boolean := True;\n Digit: Natural range 0 .. 9;\n begin\n for p in reverse Number'Range loop\n Digit := Integer'Value (Number (p..p));\n if Odd then\n Sum := Sum + Digit;\n else\n Sum := Sum + (Digit*2 mod 10) + (Digit \/ 5);\n end if;\n Odd := not Odd;\n end loop;\n return (Sum mod 10) = 0;\n end Luhn_Test;\n \nbegin\n\n Put_Line (Boolean'Image (Luhn_Test (\"49927398716\")));\n Put_Line (Boolean'Image (Luhn_Test (\"49927398717\")));\n Put_Line (Boolean'Image (Luhn_Test (\"1234567812345678\")));\n Put_Line (Boolean'Image (Luhn_Test (\"1234567812345670\")));\n\nend Luhn;\n\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":66} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Command_Line, Ada.Text_IO;\n\nprocedure Josephus is\n\n function Arg(Idx, Default: Positive) return Positive is -- read Argument(Idx)\n (if Ada.Command_Line.Argument_Count >= Index\n then Positive'Value(Ada.Command_Line.Argument(Index)) else Default);\n\n Prisoners: constant Positive := Arg(Idx => 1, Default => 41);\n Steps: constant Positive := Arg(Idx => 2, Default => 3);\n Survivors: constant Positive := Arg(Idx => 3, Default => 1);\n Print: Boolean := (Arg(Idx => 4, Default => 1) = 1);\n\n subtype Index_Type is Natural range 0 .. Prisoners-1;\n Next: array(Index_Type) of Index_Type;\n X: Index_Type := (Steps-2) mod Prisoners;\n\nbegin\n Ada.Text_IO.Put_Line\n (\"N =\" & Positive'Image(Prisoners) & \", K =\" & Positive'Image(Steps) &\n (if Survivors > 1 then \", #survivors =\" & Positive'Image(Survivors)\n else \"\"));\n for Idx in Next'Range loop -- initialize Next\n Next(Idx) := (Idx+1) mod Prisoners;\n end loop;\n if Print then\n Ada.Text_IO.Put(\"Executed: \");\n end if;\n for Execution in reverse 1 .. Prisoners loop\n if Execution = Survivors then\n Ada.Text_IO.New_Line;\n Ada.Text_IO.Put(\"Surviving: \");\n Print := True;\n end if;\n if Print then\n Ada.Text_IO.Put(Positive'Image(Next(X)));\n end if;\n Next(X) := Next(Next(X)); -- \"delete\" a prisoner\n for Prisoner in 1 .. Steps-1 loop\n X := Next(X);\n end loop;\n end loop;\nend Josephus;\n\n\n","human_summarization":"The code takes four parameters: the total number of prisoners (N), the step size (K), the number of survivors (M), and an indicator to print executions or survivors. It simulates the Josephus problem where prisoners are sequentially eliminated every K steps in a circle until only M survivors remain. The code calculates and prints the killing sequence or the surviving prisoners based on the indicator. The prisoners are numbered from 0 to N-1. The default parameters are 41, 3, 1, 1.","id":67} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Strings.Fixed; use Ada.Strings.Fixed;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure String_Multiplication is\nbegin\n Put_Line (5 * \"ha\");\nend String_Multiplication;\n\n\nhahahahaha\n\n","human_summarization":"The code takes a string and a number as input and repeats the string for the given number of times. It also provides a method to repeat a single character to create a new string. An example of its usage in Ada programming language is also given.","id":68} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO; with Gnat.Regpat; use Ada.Text_IO;\n\nprocedure Regex is\n\n package Pat renames Gnat.Regpat;\n\n procedure Search_For_Pattern(Compiled_Expression: Pat.Pattern_Matcher;\n Search_In: String;\n First, Last: out Positive;\n Found: out Boolean) is\n Result: Pat.Match_Array (0 .. 1);\n begin\n Pat.Match(Compiled_Expression, Search_In, Result);\n Found := not Pat.\"=\"(Result(1), Pat.No_Match);\n if Found then\n First := Result(1).First;\n Last := Result(1).Last;\n end if;\n end Search_For_Pattern;\n\n Word_Pattern: constant String := \"([a-zA-Z]+)\";\n\n Str: String:= \"I love PATTERN matching!\";\n Current_First: Positive := Str'First;\n First, Last: Positive;\n Found: Boolean;\n\nbegin\n -- first, find all the words in Str\n loop\n Search_For_Pattern(Pat.Compile(Word_Pattern),\n Str(Current_First .. Str'Last),\n First, Last, Found);\n exit when not Found;\n Put_Line(\"<\" & Str(First .. Last) & \">\");\n Current_First := Last+1;\n end loop;\n\n -- second, replace \"PATTERN\" in Str by \"pattern\"\n Search_For_Pattern(Pat.Compile(\"(PATTERN)\"), Str, First, Last, Found);\n Str := Str(Str'First .. First-1) & \"pattern\" & Str(Last+1 .. Str'Last);\n Put_Line(Str);\nend Regex;\n\n\n","human_summarization":"utilize a gnat\/gcc library to match a string against a regular expression and substitute part of a string using a regular expression, as there is no Regular Expression library in the Ada Standard.","id":69} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_Io;\nwith Ada.Integer_Text_IO;\n\nprocedure Integer_Arithmetic is\n use Ada.Text_IO;\n use Ada.Integer_Text_Io;\n\n A, B : Integer;\nbegin\n Get(A);\n Get(B);\n Put_Line(\"a+b = \" & Integer'Image(A + B));\n Put_Line(\"a-b = \" & Integer'Image(A - B));\n Put_Line(\"a*b = \" & Integer'Image(A * B));\n Put_Line(\"a\/b = \" & Integer'Image(A \/ B));\n Put_Line(\"a mod b = \" & Integer'Image(A mod B)); -- Sign matches B\n Put_Line(\"remainder of a\/b = \" & Integer'Image(A rem B)); -- Sign matches A\n Put_Line(\"a**b = \" & Integer'Image(A ** B)); \n\nend Integer_Arithmetic;\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":70} {"lang_cluster":"Ada","source_code":"\nwith Ada.Strings.Fixed, Ada.Integer_Text_IO;\n\nprocedure Substrings is\nbegin\n Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => \"the three truths\",\n Pattern => \"th\"));\n Ada.Integer_Text_IO.Put (Ada.Strings.Fixed.Count (Source => \"ababababab\",\n Pattern => \"abab\"));\nend Substrings;\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":71} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_Io; use Ada.Text_Io;\n\nprocedure Towers is\n type Pegs is (Left, Center, Right);\n procedure Hanoi (Ndisks : Natural; Start_Peg : Pegs := Left; End_Peg : Pegs := Right; Via_Peg : Pegs := Center) is\n begin\n if Ndisks > 0 then\n Hanoi(Ndisks - 1, Start_Peg, Via_Peg, End_Peg);\n Put_Line(\"Move disk\" & Natural'Image(Ndisks) & \" from \" & Pegs'Image(Start_Peg) & \" to \" & Pegs'Image(End_Peg));\n Hanoi(Ndisks - 1, Via_Peg, End_Peg, Start_Peg);\n end if;\n end Hanoi;\nbegin\n Hanoi(4);\nend Towers;\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":72} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\nprocedure Test_Binomial is\n function Binomial (N, K : Natural) return Natural is\n Result : Natural := 1;\n M : Natural;\n begin\n if N < K then\n raise Constraint_Error;\n end if;\n if K > N\/2 then -- Use symmetry\n M := N - K;\n else\n M := K;\n end if;\n for I in 1..M loop\n Result := Result * (N - M + I) \/ I;\n end loop;\n return Result;\n end Binomial;\nbegin\n for N in 0..17 loop\n for K in 0..N loop\n Put (Integer'Image (Binomial (N, K)));\n end loop;\n New_Line;\n end loop;\nend Test_Binomial;\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":73} {"lang_cluster":"Ada","source_code":"\n\ngeneric\n type Element_Type is digits <>;\n type Index_Type is (<>);\n type Array_Type is array(Index_Type range <>) of Element_Type;\npackage Shell_Sort is\n procedure Sort(Item : in out Array_Type);\nend Shell_Sort;\n\npackage body Shell_Sort is\n \n ----------\n -- Sort --\n ----------\n\n procedure Sort (Item : in out Array_Type) is\n Increment : Natural := Index_Type'Pos(Item'Last) \/ 2;\n J : Index_Type;\n Temp : Element_Type;\n begin\n while Increment > 0 loop\n for I in Index_Type'Val(Increment) .. Item'Last loop\n J := I;\n Temp := Item(I);\n while J > Index_Type'val(Increment) and then Item (Index_Type'Val(Index_Type'Pos(J) - Increment)) > Temp loop\n Item(J) := Item (Index_Type'Val(Index_Type'Pos(J) - Increment));\n J := Index_Type'Val(Index_Type'Pos(J) - Increment);\n end loop;\n Item(J) := Temp;\n end loop;\n if Increment = 2 then\n Increment := 1;\n else\n Increment := Increment * 5 \/ 11;\n end if;\n end loop;\n end Sort;\n\nend Shell_Sort;\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. The algorithm, named after Donald Shell, uses a diminishing increment sort method. It performs a series of interleaved insertion sorts based on an increment sequence, reducing the increment size after each pass until it reaches 1. The final sort is a basic insertion sort, but the data is almost sorted at this point, making it the \"best case\" scenario for insertion sort. The algorithm can use any sequence ending in 1, with a geometric increment sequence with a ratio of about 2.2 showing good performance in empirical studies. The implementation is generic and can handle arrays indexed by integer or enumeration types starting at any value.","id":74} {"lang_cluster":"Ada","source_code":"\ntype Grayscale_Image is array (Positive range <>, Positive range <>) of Luminance;\n\n\nfunction Grayscale (Picture : Image) return Grayscale_Image is\n type Extended_Luminance is range 0..10_000_000;\n Result : Grayscale_Image (Picture'Range (1), Picture'Range (2));\n Color : Pixel;\nbegin\n for I in Picture'Range (1) loop\n for J in Picture'Range (2) loop\n Color := Picture (I, J);\n Result (I, J) :=\n Luminance\n ( ( 2_126 * Extended_Luminance (Color.R)\n + 7_152 * Extended_Luminance (Color.G)\n + 722 * Extended_Luminance (Color.B)\n )\n \/ 10_000\n );\n end loop;\n end loop;\n return Result;\nend Grayscale;\n\n\nfunction Color (Picture : Grayscale_Image) return Image is\n Result : Image (Picture'Range (1), Picture'Range (2));\nbegin\n for I in Picture'Range (1) loop\n for J in Picture'Range (2) loop\n Result (I, J) := (others => Picture (I, J));\n end loop;\n end loop;\n return Result;\nend Color;\n\n","human_summarization":"extend the data storage type to support grayscale images, define operations to convert a color image to a grayscale image and vice versa, calculate luminance of a color using a specific formula, and handle potential rounding errors in floating-point arithmetic.","id":75} {"lang_cluster":"Ada","source_code":"\nWorks with: GNAT\nLibrary: GtkAda\n\nwith Gtk.Main;\nwith Gtk.Handlers;\nwith Gtk.Label;\nwith Gtk.Button;\nwith Gtk.Window;\nwith Glib.Main;\n\nprocedure Animation is\n Scroll_Forwards : Boolean := True;\n\n package Button_Callbacks is new Gtk.Handlers.Callback\n (Gtk.Button.Gtk_Button_Record);\n\n package Label_Timeout is new Glib.Main.Generic_Sources\n (Gtk.Label.Gtk_Label);\n\n package Window_Callbacks is new Gtk.Handlers.Return_Callback\n (Gtk.Window.Gtk_Window_Record, Boolean);\n\n -- Callback for click event\n procedure On_Button_Click\n (Object : access Gtk.Button.Gtk_Button_Record'Class);\n\n -- Callback for delete event\n function On_Main_Window_Delete\n (Object : access Gtk.Window.Gtk_Window_Record'Class)\n return Boolean;\n\n function Scroll_Text (Data : Gtk.Label.Gtk_Label) return Boolean;\n\n procedure On_Button_Click\n (Object : access Gtk.Button.Gtk_Button_Record'Class)\n is\n pragma Unreferenced (Object);\n begin\n Scroll_Forwards := not Scroll_Forwards;\n end On_Button_Click;\n\n function On_Main_Window_Delete\n (Object : access Gtk.Window.Gtk_Window_Record'Class)\n return Boolean\n is\n pragma Unreferenced (Object);\n begin\n Gtk.Main.Main_Quit;\n return True;\n end On_Main_Window_Delete;\n\n function Scroll_Text (Data : Gtk.Label.Gtk_Label) return Boolean is\n Text : constant String := Gtk.Label.Get_Text (Data);\n begin\n if Scroll_Forwards then\n Gtk.Label.Set_Text\n (Label => Data,\n Str => Text (Text'First + 1 .. Text'Last) & Text (Text'First));\n else\n Gtk.Label.Set_Text\n (Label => Data,\n Str => Text (Text'Last) & Text (Text'First .. Text'Last - 1));\n end if;\n return True;\n end Scroll_Text;\n\n Main_Window : Gtk.Window.Gtk_Window;\n Text_Button : Gtk.Button.Gtk_Button;\n Scrolling_Text : Gtk.Label.Gtk_Label;\n Timeout_ID : Glib.Main.G_Source_Id;\n pragma Unreferenced (Timeout_ID);\n\nbegin\n Gtk.Main.Init;\n Gtk.Window.Gtk_New (Window => Main_Window);\n Gtk.Label.Gtk_New (Label => Scrolling_Text, Str => \"Hello World! \");\n Gtk.Button.Gtk_New (Button => Text_Button);\n Gtk.Button.Add (Container => Text_Button, Widget => Scrolling_Text);\n Button_Callbacks.Connect\n (Widget => Text_Button,\n Name => \"clicked\",\n Marsh => Button_Callbacks.To_Marshaller (On_Button_Click'Access));\n Timeout_ID :=\n Label_Timeout.Timeout_Add\n (Interval => 125,\n Func => Scroll_Text'Access,\n Data => Scrolling_Text);\n Gtk.Window.Add (Container => Main_Window, Widget => Text_Button);\n Window_Callbacks.Connect\n (Widget => Main_Window,\n Name => \"delete_event\",\n Marsh => Window_Callbacks.To_Marshaller (On_Main_Window_Delete'Access));\n Gtk.Window.Show_All (Widget => Main_Window);\n Gtk.Main.Main;\nend Animation;\n\n","human_summarization":"The code creates a GUI with an animated \"Hello World!\" text that appears to be rotating to the right. The rotation direction reverses whenever the user clicks on the text within the window.","id":76} {"lang_cluster":"Ada","source_code":"\nloop\n Value := Value + 1;\n Put (Value);\n exit when Value mod 6 = 0;\nend loop;\n\n\nfor Value in 0..Integer'Last loop\n Put (Value);\n exit when Value mod 6 = 0;\nend loop;\n\n","human_summarization":"Initialize a value at 0, then enter a loop where the value is incremented by 1 and printed each iteration. The loop continues as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":77} {"lang_cluster":"Ada","source_code":"\nWorks with: GCC version 4.1.2\nStr : String := \"Hello World\";\nLength : constant Natural := Str'Size \/ 8;\n\n\nLatin_1_Str : String := \"Hello World\";\nUCS_16_Str : Wide_String := \"Hello World\";\nUnicode_Str : Wide_Wide_String := \"Hello World\";\nLatin_1_Length : constant Natural := Latin_1_Str'Length;\nUCS_16_Length : constant Natural := UCS_16_Str'Length;\nUnicode_Length : constant Natural := Unicode_Str'Length;\n\n\n","human_summarization":"determine the character and byte length of a string, taking into account different encodings such as UTF-8 and UTF-16. The character length is calculated based on individual Unicode code points, not user-visible graphemes. The code also handles Non-BMP code points correctly. It provides the option to mark examples with character length, byte length or grapheme length. For languages capable of providing string length in graphemes, it marks those examples accordingly. It also considers the 'Size attribute for byte length calculation and 'Length attribute for character length calculation in Ada language. The code supports strings of Latin-1, UCS-16 and full Unicode characters.","id":78} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Streams.Stream_IO;\nwith Ada.Text_IO;\nprocedure Random is\n Number : Integer;\n Random_File : Ada.Streams.Stream_IO.File_Type;\nbegin\n Ada.Streams.Stream_IO.Open (File => Random_File,\n Mode => Ada.Streams.Stream_IO.In_File,\n Name => \"\/dev\/random\");\n Integer'Read (Ada.Streams.Stream_IO.Stream (Random_File), Number);\n Ada.Streams.Stream_IO.Close (Random_File);\n Ada.Text_IO.Put_Line (\"Number:\" & Integer'Image (Number));\nend Random;\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using a system's built-in mechanism, not relying solely on a software algorithm like \/dev\/urandom devices in Unix.","id":79} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\n\nprocedure Remove_Characters is\n S: String := \"upraisers\";\n use Ada.Text_IO;\nbegin\n Put_Line(\"Full String: \"\"\" & S & \"\"\"\");\n Put_Line(\"Without_First: \"\"\" & S(S'First+1 .. S'Last) & \"\"\"\");\n Put_Line(\"Without_Last: \"\"\" & S(S'First .. S'Last-1) & \"\"\"\");\n Put_Line(\"Without_Both: \"\"\" & S(S'First+1 .. S'Last-1) & \"\"\"\");\nend Remove_Characters;\n\n\nFull String: \"upraisers\"\nWithout_First: \"praisers\"\nWithout_Last: \"upraiser\"\nWithout_Both: \"praiser\"\n\nwith Ada.Text_IO;\nwith Ada.Strings.UTF_Encoding.Wide_Strings;\n\nprocedure Remove_Characters\nis\n use Ada.Text_IO;\n use Ada.Strings.UTF_Encoding;\n use Ada.Strings.UTF_Encoding.Wide_Strings;\n \n S : String := \"upraisers\";\n U : Wide_String := Decode (UTF_8_String'(S));\n \n function To_String (X : Wide_String)return String\n is\n begin\n return String (UTF_8_String'(Encode (X)));\n end To_String;\n \nbegin\n Put_Line\n (To_String\n (\"Full String: \"\"\" & U & \"\"\"\"));\n Put_Line\n (To_String\n (\"Without_First: \"\"\" & U (U'First + 1 .. U'Last) & \"\"\"\"));\n Put_Line\n (To_String\n (\"Without_Last: \"\"\" & U (U'First .. U'Last - 1) & \"\"\"\"));\n Put_Line\n (To_String\n (\"Without_Both: \"\"\" & U (U'First + 1 .. U'Last - 1) & \"\"\"\"));\n\nend Remove_Characters;\n\n\nFull String: \"upraisers\"\nWithout_First: \"praisers\"\nWithout_Last: \"upraiser\"\nWithout_Both: \"praiser\"\n","human_summarization":"demonstrate how to remove the first, last, or both characters from a string, ensuring compatibility with any valid Unicode code point in UTF-8 or UTF-16 encoding. The program references logical characters, not 8-bit or 16-bit code units.","id":80} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO;\n\nprocedure Single_Instance is\n\n package IO renames Ada.Text_IO;\n Lock_File: IO.File_Type;\n Lock_File_Name: String := \"single_instance.magic_lock\";\n\nbegin\n begin\n IO.Open(File => Lock_File, Mode=> IO.In_File, Name => Lock_File_Name);\n IO.Close(Lock_File);\n IO.Put_Line(\"I can't -- another instance of me is running ...\");\n exception\n when IO.Name_Error =>\n IO.Put_Line(\"I can run!\");\n IO.Create(File => Lock_File, Name => Lock_File_Name);\n for I in 1 .. 10 loop\n IO.Put(Integer'Image(I));\n delay 1.0; -- wait one second\n end loop;\n IO.Delete(Lock_File);\n IO.New_Line;\n IO.Put_Line(\"I am done!\");\n end;\nexception\n when others => IO.Delete(Lock_File);\nend Single_Instance;\n\n\n","human_summarization":"The code checks if there is only one instance of an application running. It attempts to open a file for reading, if the file doesn't exist, it raises a 'Name_Error', creates the file, and performs its task. If the file exists or any other exception is raised, the program stops. It also handles a race condition where multiple instances might run if they try to open the file before it's created.","id":81} {"lang_cluster":"Ada","source_code":"\nLibrary: GTK\nLibrary: GtkAda\nwith Gtk.Main;\nwith Glib;\nwith Gtk.Window; use Gtk.Window;\nwith Gtk.Enums; use Gtk.Enums;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Max_Size is\n\n Win : Gtk_Window;\n Win_W, Win_H : Glib.Gint;\n package Int_Io is new Integer_IO (Glib.Gint);\n Hid : Gtk.Main.Quit_Handler_Id;\n\nbegin\n Gtk.Main.Init;\n Gtk_New (Win);\n Initialize (Win, Window_Toplevel);\n Maximize (Win);\n Show (Win);\n Get_Size (Win, Win_W, Win_H);\n Put (\"Maximum dimensions of window\u00a0: W \");\n Int_Io.Put (Win_W, Width => 4);\n Put (\" x H \");\n Int_Io.Put (Win_H, Width => 4);\n New_Line;\n Hid := Gtk.Main.Quit_Add_Destroy (0, Win);\nend Max_Size;\n\n\nMaximum dimensions of window\u00a0: W 1280 x H 734\n\n","human_summarization":"determine the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations, menubars, multiple monitors, and tiling window managers. The output is based on a 1280 x 800 screen with Windows XP.","id":82} {"lang_cluster":"Ada","source_code":"with Ada.Text_IO;\n\nprocedure Sudoku is\n type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9;\n FINISH_EXCEPTION : exception;\n\n procedure prettyprint(sudoku_ar: sudoku_ar_t);\n function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean;\n procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t);\n procedure solve(sudoku_ar: in out sudoku_ar_t);\n\n\n function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean\n is\n begin\n for i in 0..8 loop\n\n if ( sudoku_ar( y * 9 + i ) = val or sudoku_ar( i * 9 + x ) = val ) then\n return False;\n end if;\n end loop;\n\n declare\n startX : constant integer := ( x \/ 3 ) * 3;\n startY : constant integer := ( y \/ 3 ) * 3;\n begin\n for i in startY..startY+2 loop\n for j in startX..startX+2 loop\n if ( sudoku_ar( i * 9 +j ) = val ) then\n return False;\n end if;\n end loop;\n end loop;\n return True;\n end;\n end checkValidity;\n\n\n\n procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t)\n is\n begin\n if ( pos = 81 ) then\n raise FINISH_EXCEPTION;\n end if;\n if ( sudoku_ar(pos) > 0 ) then\n placeNumber(pos+1, sudoku_ar);\n return;\n end if;\n for n in 1..9 loop\n if( checkValidity( n, pos mod 9, pos \/ 9 , sudoku_ar ) ) then\n sudoku_ar(pos) := n;\n placeNumber(pos + 1, sudoku_ar );\n sudoku_ar(pos) := 0;\n end if;\n end loop;\n end placeNumber;\n\n\n procedure solve(sudoku_ar: in out sudoku_ar_t)\n is\n begin\n placeNumber( 0, sudoku_ar );\n Ada.Text_IO.Put_Line(\"Unresolvable\u00a0!\");\n exception\n when FINISH_EXCEPTION =>\n Ada.Text_IO.Put_Line(\"Finished\u00a0!\");\n prettyprint(sudoku_ar);\n end solve;\n\n\n\n\n procedure prettyprint(sudoku_ar: sudoku_ar_t)\n is\n line_sep : constant String := \"------+------+------\";\n begin\n for i in sudoku_ar'Range loop\n Ada.Text_IO.Put(sudoku_ar(i)'Image);\n if (i+1) mod 3 = 0 and not((i+1) mod 9 = 0) then\n Ada.Text_IO.Put(\"|\");\n end if;\n if (i+1) mod 9 = 0 then\n Ada.Text_IO.Put_Line(\"\");\n end if;\n if (i+1) mod 27 = 0 then\n Ada.Text_IO.Put_Line(line_sep);\n end if;\n end loop;\n end prettyprint;\n\n \n sudoku_ar : sudoku_ar_t :=\n (\n 8,5,0,0,0,2,4,0,0,\n 7,2,0,0,0,0,0,0,9,\n 0,0,4,0,0,0,0,0,0,\n 0,0,0,1,0,7,0,0,2,\n 3,0,5,0,0,0,9,0,0,\n 0,4,0,0,0,0,0,0,0,\n 0,0,0,0,8,0,0,7,0,\n 0,1,7,0,0,0,0,0,0,\n 0,0,0,0,3,6,0,4,0\n );\n\nbegin\n solve( sudoku_ar );\nend Sudoku;\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":83} {"lang_cluster":"Ada","source_code":"\n\ngeneric\n type Element_Type is private;\n type Array_Type is array (Positive range <>) of Element_Type;\n \nprocedure Generic_Shuffle (List : in out Array_Type);\n\nwith Ada.Numerics.Discrete_Random;\n\nprocedure Generic_Shuffle (List : in out Array_Type) is\n package Discrete_Random is new Ada.Numerics.Discrete_Random(Result_Subtype => Integer);\n use Discrete_Random;\n K : Integer;\n G : Generator;\n T : Element_Type;\nbegin\n Reset (G);\n for I in reverse List'Range loop\n K := (Random(G) mod I) + 1;\n T := List(I);\n List(I) := List(K);\n List(K) := T;\n end loop;\nend Generic_Shuffle;\n\n\nwith Ada.Text_IO;\nwith Generic_Shuffle;\n\nprocedure Test_Shuffle is\n \n type Integer_Array is array (Positive range <>) of Integer;\n\n Integer_List : Integer_Array\n := (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18);\n procedure Integer_Shuffle is new Generic_Shuffle(Element_Type => Integer,\n Array_Type => Integer_Array);\nbegin\n\n for I in Integer_List'Range loop\n Ada.Text_IO.Put(Integer'Image(Integer_List(I)));\n end loop;\n Integer_Shuffle(List => Integer_List);\n Ada.Text_IO.New_Line;\n for I in Integer_List'Range loop\n Ada.Text_IO.Put(Integer'Image(Integer_List(I)));\n end loop;\nend Test_Shuffle;\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. The algorithm randomly shuffles the elements of an integer array or an array of any type. The shuffle is done in-place, but can be modified to return a new array if necessary. The algorithm can also be adjusted to iterate from left to right.","id":84} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO, GNAT.Calendar.Time_IO, Ada.Command_Line,\n Ada.Calendar.Formatting, Ada.Calendar.Arithmetic;\n\nprocedure Last_Weekday_In_Month is\n \n procedure Put_Line(T: Ada.Calendar.Time) is\n use GNAT.Calendar.Time_IO;\n begin\n Ada.Text_IO.Put_Line(Image(Date => T, Picture => ISO_Date));\n end Put_Line;\n \n use Ada.Calendar, Ada.Calendar.Arithmetic;\n subtype Day_Name is Formatting.Day_Name; use type Formatting.Day_Name;\n \n T, Selected : Time;\n Weekday: Day_Name := Day_Name'Value(Ada.Command_Line.Argument (1));\n Year : Year_Number := Integer'Value (Ada.Command_Line.Argument (2));\n \nbegin\n for Month in 1 .. 12 loop\n T := Time_Of (Year => Year, Month => Month, Day => 01);\n while Ada.Calendar.Month(T) = Month loop\n\t if Formatting.Day_Of_Week (T) = Weekday then\n\t Selected := T;\n\t end if;\n\t T := T + Day_Count(1);\n end loop;\n Put_Line(Selected);\n end loop;\nend Last_Weekday_In_Month;\n\n\n","human_summarization":"The code takes a year as input and returns the dates of the last Fridays of each month for that given year.","id":85} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO;\n\nprocedure Goodbye_World is\nbegin\n Ada.Text_IO.Put(\"Goodbye, World!\");\nend Goodbye_World;\n\n\nwith Ada.Text_IO;\nwith Ada.Text_IO.Text_Streams;\n\nprocedure Goodbye_World is\n stdout: Ada.Text_IO.File_Type := Ada.Text_IO.Standard_Output;\nbegin\n String'Write(Ada.Text_IO.Text_Streams.Stream(stdout), \"Goodbye World\");\nend Goodbye_World;\n\n","human_summarization":"display the string \"Goodbye, World!\" without a trailing newline using Ada.Text_IO.Text_Streams to control the termination. The codes also handle the automatic insertion of a newline in some languages and ensure the output includes a final, implementation-defined terminator if the output is a file such as stdout on UNIX systems.","id":86} {"lang_cluster":"Ada","source_code":"\nLibrary: GTK\u00a0version GtkAda\nLibrary: GtkAda\nwith Gtk.Button; use Gtk.Button;\nwith Gtk.GEntry; use Gtk.GEntry;\nwith Gtk.Label; use Gtk.Label;\nwith Gtk.Window; use Gtk.Window;\nwith Gtk.Widget; use Gtk.Widget;\nwith Gtk.Table; use Gtk.Table;\n \nwith Gtk.Handlers;\nwith Gtk.Main;\n \nprocedure Graphic_Input is\n Window : Gtk_Window;\n Grid : Gtk_Tnetable;\n Label : Gtk_Label;\n Message : Gtk_Label;\n Edit : Gtk_GEntry;\n Button : Gtk_Button;\n \n package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record);\n package Return_Handlers is\n new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);\n \n function Delete_Event (Widget : access Gtk_Widget_Record'Class)\n return Boolean is\n begin\n return False;\n end Delete_Event;\n \n procedure Destroy (Widget : access Gtk_Widget_Record'Class) is\n begin\n Gtk.Main.Main_Quit;\n end Destroy;\n \n procedure Clicked (Widget : access Gtk_Widget_Record'Class) is\n begin\n if Get_Text (Label) = \"Enter integer:\" then\n Set_Text (Message, \"Entered:\" & Integer'Image (Integer'Value (Get_Text (Edit))));\n Set_Sensitive (Button, False);\n else\n Set_Text (Message, \"Entered:\" & Get_Text (Edit));\n Set_Text (Label, \"Enter integer:\");\n end if;\n exception\n when Constraint_Error =>\n Set_Text (Message, \"Error integer input\");\n end Clicked;\n \nbegin\n Gtk.Main.Init;\n Gtk.Window.Gtk_New (Window);\n Gtk_New (Grid, 2, 3, False);\n Add (Window, Grid);\n Gtk_New (Label, \"Enter string:\");\n Attach (Grid, Label, 0, 1, 0, 1);\n Gtk_New (Edit); \n Attach (Grid, Edit, 1, 2, 0, 1);\n Gtk_New (Button, \"OK\"); \n Attach (Grid, Button, 2, 3, 0, 1);\n Gtk_New (Message);\n Attach (Grid, Message, 0, 3, 1, 2);\n Return_Handlers.Connect\n ( Window,\n \"delete_event\",\n Return_Handlers.To_Marshaller (Delete_Event'Access)\n );\n Handlers.Connect\n ( Window,\n \"destroy\",\n Handlers.To_Marshaller (Destroy'Access)\n );\n Handlers.Connect\n ( Button,\n \"clicked\",\n Handlers.To_Marshaller (Clicked'Access)\n );\n Show_All (Grid);\n Show (Window);\n \n Gtk.Main.Main;\nend Graphic_Input;\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":87} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\n\nprocedure Caesar is\n\n type modulo26 is modulo 26;\n\n function modulo26 (Character: Character; ","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":88} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Lcm_Test is\n function Gcd (A, B : Integer) return Integer is\n M : Integer := A;\n N : Integer := B;\n T : Integer;\n begin\n while N \/= 0 loop\n T := M;\n M := N;\n N := T mod N;\n end loop;\n return M;\n end Gcd;\n\n function Lcm (A, B : Integer) return Integer is\n begin\n if A = 0 or B = 0 then\n return 0;\n end if;\n return abs (A) * (abs (B) \/ Gcd (A, B));\n end Lcm;\nbegin\n Put_Line (\"LCM of 12, 18 is\" & Integer'Image (Lcm (12, 18)));\n Put_Line (\"LCM of -6, 14 is\" & Integer'Image (Lcm (-6, 14)));\n Put_Line (\"LCM of 35, 0 is\" & Integer'Image (Lcm (35, 0)));\nend Lcm_Test;\n\n\nLCM of 12, 18 is 36\nLCM of -6, 14 is 42\nLCM of 35, 0 is 0\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that is a factor of both m and n. If either m or n is zero, the LCM is zero. The LCM can be found by iterating all multiples of m until a multiple of n is found, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of m and n.","id":89} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\n\nprocedure Cusip_Test is\n use Ada.Text_IO;\n\n subtype Cusip is String (1 .. 9);\n\n function Check_Cusip (Code : Cusip) return Boolean is\n Sum : Integer := 0;\n V : Integer;\n\n begin\n for I in Code'First .. Code'Last - 1 loop\n case Code (I) is\n when '0' .. '9' =>\n V := Character'Pos (Code (I)) - Character'Pos ('0');\n when 'A' .. 'Z' =>\n V := Character'Pos (Code (I)) - Character'Pos ('A') + 10;\n when '*' => V := 36;\n when '@' => V := 37;\n when '#' => V := 38;\n when others => return False;\n end case;\n\n if I mod 2 = 0 then\n V := V * 2;\n end if;\n\n Sum := Sum + V \/ 10 + (V mod 10);\n end loop;\n\n return (10 - (Sum mod 10)) mod 10 =\n Character'Pos (Code (Code'Last)) - Character'Pos ('0');\n end Check_Cusip;\n\n type Cusip_Array is array (Natural range <>) of Cusip;\n\n Test_Array : Cusip_Array :=\n (\"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\");\nbegin\n for I in Test_Array'Range loop\n Put (Test_Array (I) & \": \");\n if Check_Cusip (Test_Array (I)) then\n Put_Line (\"valid\");\n else\n Put_Line (\"not valid\");\n end if;\n end loop;\nend Cusip_Test;\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":90} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\nwith System; use System;\n\nprocedure Host_Introspection is\nbegin\n Put_Line (\"Word size\" & Integer'Image (Word_Size));\n Put_Line (\"Endianness \" & Bit_Order'Image (Default_Bit_Order));\nend Host_Introspection;\n\n\nSample output on a Pentium machine:\nWord size 32\nEndianness LOW_ORDER_FIRST\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":91} {"lang_cluster":"Ada","source_code":"\nLibrary: AWS\nwith Ada.Integer_Text_IO; use Ada.Integer_Text_IO;\nwith Ada.Strings.Fixed; use Ada.Strings.Fixed;\nwith Ada.Strings.Unbounded; use Ada.Strings.Unbounded;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nwith Ada.Containers.Ordered_Sets;\nwith Ada.Strings.Less_Case_Insensitive;\n\nwith AWS.Client;\nwith AWS.Response;\n\nprocedure Test is\n\n use Ada.Strings;\n\n function \"+\" (S : String) return Unbounded_String renames To_Unbounded_String;\n\n type A_Language_Count is\n record\n Count : Integer := 0;\n Language : Unbounded_String;\n end record;\n\n function \"=\" (L, R : A_Language_Count) return Boolean is\n begin\n return L.Language = R.Language;\n end \"=\";\n\n function \"<\" (L, R : A_Language_Count) return Boolean is\n begin\n -- Sort by 'Count' and then by Language name\n return L.Count < R.Count\n or else (L.Count = R.Count\n and then Less_Case_Insensitive (Left => To_String (L.Language),\n Right => To_String (R.Language)));\n end \"<\";\n\n package Sets is new Ada.Containers.Ordered_Sets (A_Language_Count);\n use Sets;\n\n Counts : Set;\n\n procedure Find_Counts (S : String) is\n Title_Str : constant String := \"title=\"\"Category:\";\n End_A_Str : constant String := \"<\/a> (\";\n\n Title_At : constant Natural := Index (S, Title_Str);\n begin\n if Title_At \/= 0 then\n declare\n Bracket_At : constant Natural := Index (S (Title_At + Title_Str'Length .. S'Last), \">\");\n End_A_At : constant Natural := Index (S (Bracket_At + 1 .. S'Last), End_A_Str);\n Space_At : constant Natural := Index (S (End_A_At + End_A_Str'Length .. S'Last), \" \");\n Count : constant Natural := Natural'Value (S (End_A_At + End_A_Str'Length .. Space_At - 1));\n Language : constant String := S (Title_At + Title_Str'Length .. Bracket_At - 2);\n begin\n if Bracket_At \/= 0 and then End_A_At \/= 0 and then Space_At \/= 0 then\n begin\n Counts.Insert (New_Item => (Count, +Language));\n exception\n when Constraint_Error =>\n Put_Line (Standard_Error, \"Warning: repeated language: \" & Language);\n -- Ignore repeated results.\n null;\n end;\n end if;\n -- Recursively parse the string for languages and counts\n Find_Counts (S (Space_At + 1 .. S'Last));\n end;\n end if;\n\n end Find_Counts;\n\n Place : Natural := 1;\n\n procedure Display (C : Cursor) is\n begin\n Put (Place, Width => 1); Put (\". \");\n Put (Element (C).Count, Width => 1); Put (\" - \");\n Put_Line (To_String (Element (C).Language));\n Place := Place + 1;\n end Display;\n \n Http_Source : constant AWS.Response.Data :=\n AWS.Client.Get (\"http:\/\/rosettacode.org\/mw\/index.php?title=Special:Categories&limit=5000\");\nbegin\n Find_Counts (AWS.Response.Message_Body (Http_Source));\n Counts.Reverse_Iterate (Display'Access);\nend Test;\n\n","human_summarization":"sort the most popular computer programming languages based on the number of members in Rosetta Code categories. It fetches data either through web scraping or using the API method. The code also has the functionality to filter incorrect results. The final output is a ranked list of all programming languages.","id":92} {"lang_cluster":"Ada","source_code":"\nwith Ada.Integer_Text_IO;\nuse Ada.Integer_Text_IO;\n\nprocedure For_Each is\n\n A : array (1..5) of Integer := (-1, 0, 1, 2, 3);\n\nbegin\n\n for Num in A'Range loop\n Put( A (Num) );\n end loop;\n\nend For_Each;\n\n\n for Item of A loop\n Put( Item );\n end loop;\n\nWorks with: Ada 2005\nwith Ada.Integer_Text_IO, Ada.Containers.Doubly_Linked_Lists;\nuse Ada.Integer_Text_IO, Ada.Containers;\n\nprocedure Doubly_Linked_List is\n\n package DL_List_Pkg is new Doubly_Linked_Lists (Integer);\n use DL_List_Pkg;\n\n procedure Print_Node (Position : Cursor) is\n begin\n Put (Element (Position));\n end Print_Node;\n \n DL_List : List;\n \nbegin\n \n DL_List.Append (1);\n DL_List.Append (2);\n DL_List.Append (3);\n \n -- Iterates through every node of the list.\n DL_List.Iterate (Print_Node'Access);\n \nend Doubly_Linked_List;\n\nWorks with: Ada 2005\nwith Ada.Integer_Text_IO, Ada.Containers.Vectors;\nuse Ada.Integer_Text_IO, Ada.Containers;\n\nprocedure Vector_Example is\n\n package Vector_Pkg is new Vectors (Natural, Integer);\n use Vector_Pkg;\n\n procedure Print_Element (Position : Cursor) is\n begin\n Put (Element (Position));\n end Print_Element;\n \n V : Vector;\n \nbegin\n \n V.Append (1);\n V.Append (2);\n V.Append (3);\n \n -- Iterates through every element of the vector.\n V.Iterate (Print_Element'Access);\n \nend Vector_Example;\n\n","human_summarization":"Iterates through each element in a collection in order using a \"for each\" loop or an alternative loop and prints them. This is implemented in Ada 2012.","id":93} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO, Ada.Containers.Indefinite_Vectors, Ada.Strings.Fixed, Ada.Strings.Maps;\nuse Ada.Text_IO, Ada.Containers, Ada.Strings, Ada.Strings.Fixed, Ada.Strings.Maps;\n\nprocedure Tokenize is\n package String_Vectors is new Indefinite_Vectors (Positive, String);\n use String_Vectors;\n Input : String := \"Hello,How,Are,You,Today\";\n Start : Positive := Input'First;\n Finish : Natural := 0;\n Output : Vector := Empty_Vector;\nbegin\n while Start <= Input'Last loop\n Find_Token (Input, To_Set (','), Start, Outside, Start, Finish);\n exit when Start > Finish;\n Output.Append (Input (Start .. Finish));\n Start := Finish + 1;\n end loop;\n for S of Output loop\n Put (S & \".\");\n end loop;\nend Tokenize;\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":94} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_Io; use Ada.Text_Io;\n\nprocedure Gcd_Test is\n function Gcd (A, B : Integer) return Integer is\n M : Integer := A;\n N : Integer := B;\n T : Integer;\n begin\n while N \/= 0 loop\n T := M;\n M := N;\n N := T mod N;\n end loop;\n return M;\n end Gcd;\n \nbegin\n Put_Line(\"GCD of 100, 5 is\" & Integer'Image(Gcd(100, 5)));\n Put_Line(\"GCD of 5, 100 is\" & Integer'Image(Gcd(5, 100)));\n Put_Line(\"GCD of 7, 23 is\" & Integer'Image(Gcd(7, 23)));\nend Gcd_Test;\n\n\nGCD of 100, 5 is 5\nGCD of 5, 100 is 5\nGCD of 7, 23 is 1\n\n","human_summarization":"find the greatest common divisor (GCD), also known as greatest common factor (gcf) or greatest common measure, of two integers.","id":95} {"lang_cluster":"Ada","source_code":"\nWorks with: GNAT\n\nwith Ada.Text_IO;\nwith Ada.IO_Exceptions;\nwith GNAT.Sockets;\nprocedure Echo_Server is\n Receiver : GNAT.Sockets.Socket_Type;\n Connection : GNAT.Sockets.Socket_Type;\n Client : GNAT.Sockets.Sock_Addr_Type;\n Channel : GNAT.Sockets.Stream_Access;\nbegin\n GNAT.Sockets.Create_Socket (Socket => Receiver);\n GNAT.Sockets.Set_Socket_Option\n (Socket => Receiver,\n Level => GNAT.Sockets.Socket_Level,\n Option => (Name => GNAT.Sockets.Reuse_Address, Enabled => True));\n GNAT.Sockets.Bind_Socket\n (Socket => Receiver,\n Address => (Family => GNAT.Sockets.Family_Inet,\n Addr => GNAT.Sockets.Inet_Addr (\"127.0.0.1\"),\n Port => 12321));\n GNAT.Sockets.Listen_Socket (Socket => Receiver);\n loop\n GNAT.Sockets.Accept_Socket\n (Server => Receiver,\n Socket => Connection,\n Address => Client);\n Ada.Text_IO.Put_Line\n (\"Client connected from \" & GNAT.Sockets.Image (Client));\n Channel := GNAT.Sockets.Stream (Connection);\n begin\n loop\n Character'Output (Channel, Character'Input (Channel));\n end loop;\n exception\n when Ada.IO_Exceptions.End_Error =>\n null;\n end;\n GNAT.Sockets.Close_Socket (Connection);\n end loop;\nend Echo_Server;\n\n\nwith Ada.Text_IO;\nwith Ada.IO_Exceptions;\nwith GNAT.Sockets;\nprocedure echo_server_multi is\n-- Multiple socket connections example based on Rosetta Code echo server.\n\n Tasks_To_Create : constant := 3; -- simultaneous socket connections.\n\n-------------------------------------------------------------------------------\n-- Use stack to pop the next free task index. When a task finishes its\n-- asynchronous (no rendezvous) phase, it pushes the index back on the stack.\n type Integer_List is array (1..Tasks_To_Create) of integer;\n subtype Counter is integer range 0 .. Tasks_To_Create;\n subtype Index is integer range 1 .. Tasks_To_Create;\n protected type Info is\n procedure Push_Stack (Return_Task_Index : in Index);\n procedure Initialize_Stack;\n entry Pop_Stack (Get_Task_Index : out Index);\n private\n Task_Stack : Integer_List; -- Stack of free-to-use tasks.\n Stack_Pointer: Counter := 0;\n end Info;\n\n protected body Info is\n procedure Push_Stack (Return_Task_Index : in Index) is\n begin -- Performed by tasks that were popped, so won't overflow.\n Stack_Pointer := Stack_Pointer + 1;\n Task_Stack(Stack_Pointer) := Return_Task_Index;\n end;\n\n entry Pop_Stack (Get_Task_Index : out Index) when Stack_Pointer \/= 0 is\n begin -- guarded against underflow.\n Get_Task_Index := Task_Stack(Stack_Pointer);\n Stack_Pointer := Stack_Pointer - 1;\n end; \n\n procedure Initialize_Stack is\n begin\n for I in Task_Stack'range loop\n Push_Stack (I);\n end loop;\n end;\n end Info;\n\n Task_Info : Info;\n \n-------------------------------------------------------------------------------\n task type SocketTask is\n -- Rendezvous the setup, which sets the parameters for entry Echo.\n entry Setup (Connection : GNAT.Sockets.Socket_Type;\n Client : GNAT.Sockets.Sock_Addr_Type;\n Channel : GNAT.Sockets.Stream_Access;\n Task_Index : Index);\n -- Echo accepts the asynchronous phase, i.e. no rendezvous. When the\n -- communication is over, push the task number back on the stack.\n entry Echo;\n end SocketTask;\n\n task body SocketTask is\n my_Connection : GNAT.Sockets.Socket_Type;\n my_Client : GNAT.Sockets.Sock_Addr_Type;\n my_Channel : GNAT.Sockets.Stream_Access;\n my_Index : Index;\n begin\n loop -- Infinitely reusable\n accept Setup (Connection : GNAT.Sockets.Socket_Type; \n Client : GNAT.Sockets.Sock_Addr_Type; \n Channel : GNAT.Sockets.Stream_Access;\n Task_Index : Index) do\n -- Store parameters and mark task busy.\n my_Connection := Connection;\n my_Client := Client;\n my_Channel := Channel;\n my_Index := Task_Index;\n end;\n \n accept Echo; -- Do the echo communications.\n begin\n Ada.Text_IO.Put_Line (\"Task \" & integer'image(my_Index));\n loop\n Character'Output (my_Channel, Character'Input(my_Channel));\n end loop;\n exception\n when Ada.IO_Exceptions.End_Error =>\n Ada.Text_IO.Put_Line (\"Echo \" & integer'image(my_Index) & \" end\");\n when others => \n Ada.Text_IO.Put_Line (\"Echo \" & integer'image(my_Index) & \" err\");\n end;\n GNAT.Sockets.Close_Socket (my_Connection);\n Task_Info.Push_Stack (my_Index); -- Return to stack of unused tasks.\n end loop;\n end SocketTask;\n\n-------------------------------------------------------------------------------\n-- Setup the socket receiver, initialize the task stack, and then loop,\n-- blocking on Accept_Socket, using Pop_Stack for the next free task from the\n-- stack, waiting if necessary.\n task type SocketServer (my_Port : GNAT.Sockets.Port_Type) is\n entry Listen;\n end SocketServer;\n\n task body SocketServer is\n Receiver : GNAT.Sockets.Socket_Type;\n Connection : GNAT.Sockets.Socket_Type;\n Client : GNAT.Sockets.Sock_Addr_Type;\n Channel : GNAT.Sockets.Stream_Access;\n Worker : array (1..Tasks_To_Create) of SocketTask;\n Use_Task : Index;\n\n begin\n accept Listen;\n GNAT.Sockets.Create_Socket (Socket => Receiver);\n GNAT.Sockets.Set_Socket_Option\n (Socket => Receiver,\n Level => GNAT.Sockets.Socket_Level,\n Option => (Name => GNAT.Sockets.Reuse_Address, Enabled => True));\n GNAT.Sockets.Bind_Socket\n (Socket => Receiver,\n Address => (Family => GNAT.Sockets.Family_Inet,\n Addr => GNAT.Sockets.Inet_Addr (\"127.0.0.1\"),\n Port => my_Port));\n GNAT.Sockets.Listen_Socket (Socket => Receiver);\n Task_Info.Initialize_Stack;\nFind: loop -- Block for connection and take next free task.\n GNAT.Sockets.Accept_Socket\n (Server => Receiver,\n Socket => Connection,\n Address => Client);\n Ada.Text_IO.Put_Line (\"Connect \" & GNAT.Sockets.Image(Client));\n Channel := GNAT.Sockets.Stream (Connection);\n Task_Info.Pop_Stack(Use_Task); -- Protected guard waits if full house.\n -- Setup the socket in this task in rendezvous.\n Worker(Use_Task).Setup(Connection,Client, Channel,Use_Task);\n -- Run the asynchronous task for the socket communications.\n Worker(Use_Task).Echo; -- Start echo loop.\n end loop Find;\n end SocketServer;\n\n Echo_Server : SocketServer(my_Port => 12321);\n\n-------------------------------------------------------------------------------\nbegin\n Echo_Server.Listen;\nend echo_server_multi;\n\n","human_summarization":"The code creates an echo server that listens on TCP port 12321, accepts and handles simultaneous connections from multiple clients, specifically from localhost. It echoes back complete lines received from clients. The server supports both single-threaded and multi-threaded operations, with the latter allowing a maximum of about 2000 threads per process on OS X 10.10.5 with gcc 4.9.1. Connection information is logged to standard output. The server remains responsive to other clients even if one client sends a partial line or stops reading responses.","id":96} {"lang_cluster":"Ada","source_code":"\n\npackage Numeric_Tests is\n function Is_Numeric (Item : in String) return Boolean;\nend Numeric_Tests;\n\n\npackage body Numeric_Tests is\n function Is_Numeric (Item : in String) return Boolean is\n Dummy : Float;\n begin\n Dummy := Float'Value (Item);\n return True;\n exception\n when others =>\n return False;\n end Is_Numeric;\nend Numeric_Tests;\n\n\nwith Ada.Text_Io; use Ada.Text_Io;\nwith Numeric_Tests; use Numeric_Tests; \n\nprocedure Is_Numeric_Test is\n S1 : String := \"152\";\n S2 : String := \"-3.1415926\";\n S3 : String := \"Foo123\";\nbegin\n Put_Line(S1 & \" results in \" & Boolean'Image(Is_Numeric(S1)));\n Put_Line(S2 & \" results in \" & Boolean'Image(Is_Numeric(S2)));\n Put_Line(S3 & \" results in \" & Boolean'Image(Is_Numeric(S3)));\nend Is_Numeric_Test;\n\n\n","human_summarization":"The following codes define a boolean function named Is_Numeric. This function takes a string as input and checks if it is a numeric string, including floating point and negative numbers. The implementation of this function is found in a separate package body file. An additional file demonstrates how to call the Is_Numeric function.","id":97} {"lang_cluster":"Ada","source_code":"\nLibrary: AWS\n\nwith AWS.Client;\nwith AWS.Response;\nwith Ada.Text_IO; use Ada.Text_IO;\nprocedure GetHttps is\nbegin\n Put_Line (AWS.Response.Message_Body (AWS.Client.Get (\n URL => \"https:\/\/sourceforge.net\/\")));\nend GetHttps;\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the response to the console without authentication. The functionality is similar to the HTTP task with openssl support in AWS.","id":98} {"lang_cluster":"Ada","source_code":"\nwith Ada.Containers.Doubly_Linked_Lists;\nwith Ada.Text_IO;\n\nprocedure Main is\n package FIO is new Ada.Text_IO.Float_IO (Float);\n\n type Point is record\n X, Y : Float;\n end record;\n\n function \"-\" (Left, Right : Point) return Point is\n begin\n return (Left.X - Right.X, Left.Y - Right.Y);\n end \"-\";\n\n type Edge is array (1 .. 2) of Point;\n\n package Point_Lists is new Ada.Containers.Doubly_Linked_Lists\n (Element_Type => Point);\n use type Point_Lists.List;\n subtype Polygon is Point_Lists.List;\n\n function Inside (P : Point; E : Edge) return Boolean is\n begin\n return (E (2).X - E (1).X) * (P.Y - E (1).Y) >\n (E (2).Y - E (1).Y) * (P.X - E (1).X);\n end Inside;\n\n function Intersecton (P1, P2 : Point; E : Edge) return Point is\n DE : Point := E (1) - E (2);\n DP : Point := P1 - P2;\n N1 : Float := E (1).X * E (2).Y - E (1).Y * E (2).X;\n N2 : Float := P1.X * P2.Y - P1.Y * P2.X;\n N3 : Float := 1.0 \/ (DE.X * DP.Y - DE.Y * DP.X);\n begin\n return ((N1 * DP.X - N2 * DE.X) * N3, (N1 * DP.Y - N2 * DE.Y) * N3);\n end Intersecton;\n\n function Clip (P, C : Polygon) return Polygon is\n use Point_Lists;\n A, B, S, E : Cursor;\n Inputlist : List;\n Outputlist : List := P;\n AB : Edge;\n begin\n A := C.First;\n B := C.Last;\n while A \/= No_Element loop\n AB := (Element (B), Element (A));\n Inputlist := Outputlist;\n Outputlist.Clear;\n S := Inputlist.Last;\n E := Inputlist.First;\n while E \/= No_Element loop\n if Inside (Element (E), AB) then\n if not Inside (Element (S), AB) then\n Outputlist.Append\n (Intersecton (Element (S), Element (E), AB));\n end if;\n Outputlist.Append (Element (E));\n elsif Inside (Element (S), AB) then\n Outputlist.Append\n (Intersecton (Element (S), Element (E), AB));\n end if;\n S := E;\n E := Next (E);\n end loop;\n B := A;\n A := Next (A);\n end loop;\n return Outputlist;\n end Clip;\n\n procedure Print (P : Polygon) is\n use Point_Lists;\n C : Cursor := P.First;\n begin\n Ada.Text_IO.Put_Line (\"{\");\n while C \/= No_Element loop\n Ada.Text_IO.Put (\" (\");\n FIO.Put (Element (C).X, Exp => 0);\n Ada.Text_IO.Put (',');\n FIO.Put (Element (C).Y, Exp => 0);\n Ada.Text_IO.Put (')');\n C := Next (C);\n if C \/= No_Element then\n Ada.Text_IO.Put (',');\n end if;\n Ada.Text_IO.New_Line;\n end loop;\n Ada.Text_IO.Put_Line (\"}\");\n end Print;\n\n Source : Polygon;\n Clipper : Polygon;\n Result : Polygon;\nbegin\n Source.Append ((50.0, 150.0));\n Source.Append ((200.0, 50.0));\n Source.Append ((350.0, 150.0));\n Source.Append ((350.0, 300.0));\n Source.Append ((250.0, 300.0));\n Source.Append ((200.0, 250.0));\n Source.Append ((150.0, 350.0));\n Source.Append ((100.0, 250.0));\n Source.Append ((100.0, 200.0));\n Clipper.Append ((100.0, 100.0));\n Clipper.Append ((300.0, 100.0));\n Clipper.Append ((300.0, 300.0));\n Clipper.Append ((100.0, 300.0));\n Result := Clip (Source, Clipper);\n Print (Result);\nend Main;\n\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":99} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Numerics.Elementary_Functions;\nuse Ada.Numerics.Elementary_Functions;\nwith Ada.Float_Text_Io; use Ada.Float_Text_Io;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Trig is\n Degrees_Cycle : constant Float := 360.0;\n Radians_Cycle : constant Float := 2.0 * Ada.Numerics.Pi;\n Angle_Degrees : constant Float := 45.0;\n Angle_Radians : constant Float := Ada.Numerics.Pi \/ 4.0;\n procedure Put (V1, V2 : Float) is\n begin\n Put (V1, Aft => 5, Exp => 0);\n Put (\" \");\n Put (V2, Aft => 5, Exp => 0);\n New_Line;\n end Put;\nbegin\n Put (Sin (Angle_Degrees, Degrees_Cycle), \n Sin (Angle_Radians, Radians_Cycle));\n Put (Cos (Angle_Degrees, Degrees_Cycle), \n Cos (Angle_Radians, Radians_Cycle));\n Put (Tan (Angle_Degrees, Degrees_Cycle), \n Tan (Angle_Radians, Radians_Cycle));\n Put (Cot (Angle_Degrees, Degrees_Cycle), \n Cot (Angle_Radians, Radians_Cycle));\n Put (ArcSin (Sin (Angle_Degrees, Degrees_Cycle), Degrees_Cycle), \n ArcSin (Sin (Angle_Radians, Radians_Cycle), Radians_Cycle));\n Put (Arccos (Cos (Angle_Degrees, Degrees_Cycle), Degrees_Cycle), \n Arccos (Cos (Angle_Radians, Radians_Cycle), Radians_Cycle));\n Put (Arctan (Y => Tan (Angle_Degrees, Degrees_Cycle)),\n Arctan (Y => Tan (Angle_Radians, Radians_Cycle)));\n Put (Arccot (X => Cot (Angle_Degrees, Degrees_Cycle)), \n Arccot (X => Cot (Angle_Degrees, Degrees_Cycle)));\nend Trig;\n\n\n","human_summarization":"demonstrate the use of trigonometric functions such as sine, cosine, tangent, and their inverses in a specific programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the arguments evaluate to the same angle. For inverse functions, the same number is used and its answer is converted to radians and degrees. If the language lacks certain trigonometric functions, the code provides custom functions based on known approximations or identities. The Ada language's library trig functions, which default to radians, are also demonstrated with examples specifying cycles for degrees and radians. The inverse trig functions' output is in units of the specified cycle.","id":100} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Interrupts; use Ada.Interrupts;\nwith Ada.Interrupts.Names; use Ada.Interrupts.Names;\n\npackage Sigint_Handler is\n protected Handler is\n entry Wait;\n procedure Handle;\n pragma Interrupt_Handler(Handle);\n pragma Attach_Handler(Handle, Sigint);\n private\n Call_Count : Natural := 0;\n end Handler;\n\nend Sigint_Handler;\n\npackage body Sigint_Handler is\n\n -------------\n -- Handler --\n -------------\n\n protected body Handler is\n\n ----------\n -- Wait --\n ----------\n\n entry Wait when Call_Count > 0 is\n begin\n Call_Count := Call_Count - 1;\n end Wait;\n\n ------------\n -- Handle --\n ------------\n\n procedure Handle is\n begin\n Call_Count := Call_Count + 1;\n end Handle;\n\n end Handler;\n\nend Sigint_Handler;\n\n\nwith Ada.Calendar; use Ada.Calendar;\nwith Ada.Text_Io; use Ada.Text_Io;\nwith Sigint_Handler; use Sigint_Handler;\n\nprocedure Signals is\n task Counter is\n entry Stop;\n end Counter;\n task body Counter is\n Current_Count : Natural := 0;\n begin\n loop\n select\n accept Stop;\n exit;\n or delay 0.5;\n end select;\n Current_Count := Current_Count + 1;\n Put_Line(Natural'Image(Current_Count));\n end loop;\n end Counter;\n task Sig_Handler;\n \n task body Sig_Handler is\n Start_Time : Time := Clock;\n Sig_Time : Time;\n begin\n Handler.Wait;\n Sig_Time := Clock;\n Counter.Stop;\n Put_Line(\"Program execution took\" & Duration'Image(Sig_Time - Start_Time) & \" seconds\");\n end Sig_Handler;\n \nbegin\n null;\n \nend Signals;\n\n\n","human_summarization":"The code outputs an integer every half second. It also includes a signal handler for the SIGINT signal, often generated by user's ctrl-C command. On receiving this signal, the program stops outputting integers, displays the total runtime in seconds, and then terminates. The signal handler is defined at the library level and is executed when the SIGINT signal is received.","id":101} {"lang_cluster":"Ada","source_code":"\n\nS : String := \"12345\";\nS := Ada.Strings.Fixed.Trim(Source => Integer'Image(Integer'Value(S) + 1), Side => Ada.Strings.Both);\n\n","human_summarization":"\"Increments a numerical string using the Ada.Strings.Fixed package's function for trimming blanks.\"","id":102} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_Common_Path is\n function \"rem\" (A, B : String) return String is\n Slash : Integer := A'First; -- At the last slash seen in A\n At_A : Integer := A'first;\n At_B : Integer := B'first;\n begin\n loop\n if At_A > A'Last then\n if At_B > B'Last or else B (At_B) = '\/' then\n return A;\n else\n return A (A'First..Slash - 1);\n end if;\n elsif At_B > B'Last then\n if A (At_A) = '\/' then -- A cannot be shorter than B here\n return B;\n else\n return A (A'First..Slash - 1);\n end if;\n elsif A (At_A) \/= B (At_B) then\n return A (A'First..Slash - 1);\n elsif A (At_A) = '\/' then\n Slash := At_A;\n end if;\n At_A := At_A + 1;\n At_B := At_B + 1;\n end loop; \n end \"rem\";\nbegin\n Put_Line\n ( \"\/home\/user1\/tmp\/coverage\/test\" rem\n \"\/home\/user1\/tmp\/covert\/operator\" rem\n \"\/home\/user1\/tmp\/coven\/members\"\n );\nend Test_Common_Path;\n\n\n\/home\/user1\/tmp\n\n","human_summarization":"\"Code generates a common directory path from a set of directory paths using a specified directory separator character. It identifies the common part of the directory tree in all directories, not just the longest common string. The code also includes a test case using '\/' as the separator and three specific directory paths.\"","id":103} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO, Ada.Float_Text_IO;\n\nprocedure FindMedian is\n\n f: array(1..10) of float := ( 4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5 );\n min_idx: integer;\n min_val, median_val, swap: float;\n\nbegin\n for i in f'range loop\n min_idx := i;\n min_val := f(i);\n for j in i+1 .. f'last loop\n if f(j) < min_val then\n min_idx := j;\n min_val := f(j);\n end if; \n end loop;\n swap := f(i); f(i) := f(min_idx); f(min_idx) := swap;\n end loop; \n\n if f'length mod 2 \/= 0 then\n median_val := f( f'length\/2+1 );\n else\n median_val := ( f(f'length\/2) + f(f'length\/2+1) ) \/ 2.0;\n end if;\n \n Ada.Text_IO.Put( \"Median value: \" );\n Ada.Float_Text_IO.Put( median_val );\n Ada.Text_IO.New_line; \nend FindMedian;\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.","id":104} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n \nprocedure Fizzbuzz is\nbegin\n for I in 1..100 loop\n if I mod 15 = 0 then\n Put_Line(\"FizzBuzz\");\n elsif I mod 5 = 0 then\n Put_Line(\"Buzz\");\n elsif I mod 3 = 0 then\n Put_Line(\"Fizz\");\n else\n Put_Line(Integer'Image(I));\n end if;\n end loop;\nend Fizzbuzz;\n\n\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":105} {"lang_cluster":"Ada","source_code":"\nLibrary: Lumen\n\nwith Lumen.Binary;\npackage body Mandelbrot is\n function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor is\n use type Lumen.Binary.Byte;\n Result : Lumen.Image.Descriptor;\n X0, Y0 : Float;\n X, Y, Xtemp : Float;\n Iteration : Float;\n Max_Iteration : constant Float := 1000.0;\n Color : Lumen.Binary.Byte;\n begin\n Result.Width := Width;\n Result.Height := Height;\n Result.Complete := True;\n Result.Values := new Lumen.Image.Pixel_Matrix (1 .. Width, 1 .. Height);\n for Screen_X in 1 .. Width loop\n for Screen_Y in 1 .. Height loop\n X0 := -2.5 + (3.5 \/ Float (Width) * Float (Screen_X));\n Y0 := -1.0 + (2.0 \/ Float (Height) * Float (Screen_Y));\n X := 0.0;\n Y := 0.0;\n Iteration := 0.0;\n while X * X + Y * Y <= 4.0 and then Iteration < Max_Iteration loop\n Xtemp := X * X - Y * Y + X0;\n Y := 2.0 * X * Y + Y0;\n X := Xtemp;\n Iteration := Iteration + 1.0;\n end loop;\n if Iteration = Max_Iteration then\n Color := 255;\n else\n Color := 0;\n end if;\n Result.Values (Screen_X, Screen_Y) := (R => Color, G => Color, B => Color, A => 0);\n end loop;\n end loop;\n return Result;\n end Create_Image;\n\nend Mandelbrot;\n\n\nwith Lumen.Image;\n\npackage Mandelbrot is\n\n function Create_Image (Width, Height : Natural) return Lumen.Image.Descriptor;\n\nend Mandelbrot;\n\n\nwith System.Address_To_Access_Conversions;\nwith Lumen.Window;\nwith Lumen.Image;\nwith Lumen.Events;\nwith GL;\nwith Mandelbrot;\n\nprocedure Test_Mandelbrot is\n\n Program_End : exception;\n\n Win : Lumen.Window.Handle;\n Image : Lumen.Image.Descriptor;\n Tx_Name : aliased GL.GLuint;\n Wide, High : Natural := 400;\n\n -- Create a texture and bind a 2D image to it\n procedure Create_Texture is\n use GL;\n\n package GLB is new System.Address_To_Access_Conversions (GLubyte);\n\n IP : GLpointer;\n begin -- Create_Texture\n -- Allocate a texture name\n glGenTextures (1, Tx_Name'Unchecked_Access);\n\n -- Bind texture operations to the newly-created texture name\n glBindTexture (GL_TEXTURE_2D, Tx_Name);\n\n -- Select modulate to mix texture with color for shading\n glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);\n\n -- Wrap textures at both edges\n glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n\n -- How the texture behaves when minified and magnified\n glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\n -- Create a pointer to the image. This sort of horror show is going to\n -- be disappearing once Lumen includes its own OpenGL bindings.\n IP := GLB.To_Pointer (Image.Values.all'Address).all'Unchecked_Access;\n\n -- Build our texture from the image we loaded earlier\n glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, GLsizei (Image.Width), GLsizei (Image.Height), 0,\n GL_RGBA, GL_UNSIGNED_BYTE, IP);\n end Create_Texture;\n\n -- Set or reset the window view parameters\n procedure Set_View (W, H : in Natural) is\n use GL;\n begin -- Set_View\n GL.glEnable (GL.GL_TEXTURE_2D);\n glClearColor (0.8, 0.8, 0.8, 1.0);\n\n glMatrixMode (GL_PROJECTION);\n glLoadIdentity;\n glViewport (0, 0, GLsizei (W), GLsizei (H));\n glOrtho (0.0, GLdouble (W), GLdouble (H), 0.0, -1.0, 1.0);\n\n glMatrixMode (GL_MODELVIEW);\n glLoadIdentity;\n end Set_View;\n\n -- Draw our scene\n procedure Draw is\n use GL;\n begin -- Draw\n -- clear the screen\n glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);\n GL.glBindTexture (GL.GL_TEXTURE_2D, Tx_Name);\n\n -- fill with a single textured quad\n glBegin (GL_QUADS);\n begin\n glTexCoord2f (1.0, 0.0);\n glVertex2i (GLint (Wide), 0);\n\n glTexCoord2f (0.0, 0.0);\n glVertex2i (0, 0);\n\n glTexCoord2f (0.0, 1.0);\n glVertex2i (0, GLint (High));\n\n glTexCoord2f (1.0, 1.0);\n glVertex2i (GLint (Wide), GLint (High));\n end;\n glEnd;\n\n -- flush rendering pipeline\n glFlush;\n\n -- Now show it\n Lumen.Window.Swap (Win);\n end Draw;\n\n -- Simple event handler routine for keypresses and close-window events\n procedure Quit_Handler (Event : in Lumen.Events.Event_Data) is\n begin -- Quit_Handler\n raise Program_End;\n end Quit_Handler;\n\n -- Simple event handler routine for Exposed events\n procedure Expose_Handler (Event : in Lumen.Events.Event_Data) is\n pragma Unreferenced (Event);\n begin -- Expose_Handler\n Draw;\n end Expose_Handler;\n\n -- Simple event handler routine for Resized events\n procedure Resize_Handler (Event : in Lumen.Events.Event_Data) is\n begin -- Resize_Handler\n Wide := Event.Resize_Data.Width;\n High := Event.Resize_Data.Height;\n Set_View (Wide, High);\n-- Image\u00a0:= Mandelbrot.Create_Image (Width => Wide, Height => High);\n-- Create_Texture;\n Draw;\n end Resize_Handler;\n\nbegin\n -- Create Lumen window, accepting most defaults; turn double buffering off\n -- for simplicity\n Lumen.Window.Create (Win => Win,\n Name => \"Mandelbrot fractal\",\n Width => Wide,\n Height => High,\n Events => (Lumen.Window.Want_Exposure => True,\n Lumen.Window.Want_Key_Press => True,\n others => False));\n\n -- Set up the viewport and scene parameters\n Set_View (Wide, High);\n\n -- Now create the texture and set up to use it\n Image := Mandelbrot.Create_Image (Width => Wide, Height => High);\n Create_Texture;\n\n -- Enter the event loop\n declare\n use Lumen.Events;\n begin\n Select_Events (Win => Win,\n Calls => (Key_Press => Quit_Handler'Unrestricted_Access,\n Exposed => Expose_Handler'Unrestricted_Access,\n Resized => Resize_Handler'Unrestricted_Access,\n Close_Window => Quit_Handler'Unrestricted_Access,\n others => No_Callback));\n end;\nexception\n when Program_End =>\n null;\nend Test_Mandelbrot;\n\n\n","human_summarization":"The code generates and draws the Mandelbrot set using various algorithms and functions. The code is written in Ada and is divided into three parts: mandelbrot.adb, mandelbrot.ads, and test_mandelbrot.adb. The content is sourced from the Wikipedia page on the Mandelbrot set.","id":106} {"lang_cluster":"Ada","source_code":"\ntype Int_Array is array(Integer range <>) of Integer;\n\narray : Int_Array := (1,2,3,4,5,6,7,8,9,10);\nSum : Integer := 0;\nfor I in array'range loop\n Sum := Sum + array(I);\nend loop;\n\n\nfunction Product(Item : Int_Array) return Integer is\n Prod : Integer := 1;\nbegin\n for I in Item'range loop\n Prod := Prod * Item(I);\n end loop;\n return Prod;\nend Product;\n\n\n","human_summarization":"calculate the sum and product of an array of integers. If the product exceeds the maximum value of an integer, a Constraint_Error exception is raised.","id":107} {"lang_cluster":"Ada","source_code":"\n-- Incomplete code, just a sniplet to do the task. Can be used in any package or method.\n-- Adjust the type of Year if you use a different one.\nfunction Is_Leap_Year (Year : Integer) return Boolean is\nbegin\n if Year rem 100 = 0 then\n return Year rem 400 = 0;\n else\n return Year rem 4 = 0;\n end if;\nend Is_Leap_Year;\n\n\n-- An enhanced, more efficient version:\n-- This version only does the 2 bit comparison (rem 4) if false.\n-- It then checks rem 16 (a 4 bit comparison), and only if those are not\n-- conclusive, calls rem 100, which is the most expensive operation.\n-- I failed to be convinced of the accuracy of the algorithm at first,\n-- so I rephrased it below.\n-- FYI: 400 is evenly divisible by 16 whereas 100,200 and 300 are not. Ergo, the\n-- set of integers evenly divisible by 16 and 100 are all evenly divisible by 400.\n-- 1. If a year is not divisible by 4 => not a leap year. Skip other checks.\n-- 2. If a year is evenly divisible by 16, it is either evenly divisible by 400 or \n-- not evenly divisible by 100 => leap year. Skip further checks.\n-- 3. If a year evenly divisible by 100 => not a leap year. \n-- 4. Otherwise a leap year. \n \nfunction Is_Leap_Year (Year : Integer) return Boolean is\nbegin\n return (Year rem 4 = 0) and then ((Year rem 16 = 0) or else (Year rem 100 \/= 0));\nend Is_Leap_Year;\n\n\n\n-- To improve speed a bit more, use with\npragma Inline (Is_Leap_Year);\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":108} {"lang_cluster":"Ada","source_code":"\n\npackage MD5 is\n\n type Int32 is mod 2 ** 32;\n type MD5_Hash is array (1 .. 4) of Int32;\n function MD5 (Input : String) return MD5_Hash;\n\n -- 32 hexadecimal characters + '0x' prefix\n subtype MD5_String is String (1 .. 34);\n function To_String (Item : MD5_Hash) return MD5_String;\n\nend MD5;\n\n\nwith Ada.Unchecked_Conversion;\n\npackage body MD5 is\n type Int32_Array is array (Positive range <>) of Int32;\n\n function Rotate_Left (Value : Int32; Count : Int32) return Int32 is\n Bit : Boolean;\n Result : Int32 := Value;\n begin\n for I in 1 .. Count loop\n Bit := (2 ** 31 and Result) = 2 ** 31;\n Result := Result * 2;\n if Bit then\n Result := Result + 1;\n end if;\n end loop;\n return Result;\n end Rotate_Left;\n\n function Pad_String (Item : String) return Int32_Array is\n -- always pad positive amount of Bytes\n Padding_Bytes : Positive := 64 - Item'Length mod 64;\n subtype String4 is String (1 .. 4);\n function String4_To_Int32 is new Ada.Unchecked_Conversion\n (Source => String4,\n Target => Int32);\n begin\n if Padding_Bytes <= 2 then\n Padding_Bytes := Padding_Bytes + 64;\n end if;\n declare\n Result : Int32_Array (1 .. (Item'Length + Padding_Bytes) \/ 4);\n Current_Index : Positive := 1;\n begin\n for I in 1 .. Item'Length \/ 4 loop\n Result (I) :=\n String4_To_Int32 (Item (4 * (I - 1) + 1 .. 4 * I));\n Current_Index := Current_Index + 1;\n end loop;\n\n declare\n Last_String : String4 := (others => Character'Val (0));\n Chars_Left : constant Natural := Item'Length mod 4;\n begin\n Last_String (1 .. Chars_Left) :=\n Item (Item'Last - Chars_Left + 1 .. Item'Last);\n Last_String (Chars_Left + 1) := Character'Val (2#1000_0000#);\n Result (Current_Index) := String4_To_Int32 (Last_String);\n Current_Index := Current_Index + 1;\n end;\n\n Result (Current_Index .. Result'Last) := (others => 0);\n -- append length as bit count\n Result (Result'Last - 1) := Item'Length * 2 ** 3; -- mod 2 ** 32;\n Result (Result'Last) := Item'Length \/ 2 ** (32 - 3);\n return Result;\n end;\n end Pad_String;\n\n function Turn_Around (X : Int32) return Int32 is\n Result : Int32 := 0;\n begin\n for Byte in 1 .. 4 loop\n Result := Result * 16#100#;\n Result := Result + (X \/ (2 ** (8 * (Byte - 1)))) mod 16#100#;\n end loop;\n return Result;\n end Turn_Around;\n\n function MD5 (Input : String) return MD5_Hash is\n function F (X, Y, Z : Int32) return Int32 is\n begin\n return Z xor (X and (Y xor Z));\n end F;\n function G (X, Y, Z : Int32) return Int32 is\n begin\n return (X and Z) or (Y and (not Z));\n end G;\n function H (X, Y, Z : Int32) return Int32 is\n begin\n return X xor Y xor Z;\n end H;\n function I (X, Y, Z : Int32) return Int32 is\n begin\n return Y xor (X or (not Z));\n end I;\n T : constant Int32_Array :=\n (16#d76aa478#, 16#e8c7b756#, 16#242070db#, 16#c1bdceee#,\n 16#f57c0faf#, 16#4787c62a#, 16#a8304613#, 16#fd469501#,\n 16#698098d8#, 16#8b44f7af#, 16#ffff5bb1#, 16#895cd7be#,\n 16#6b901122#, 16#fd987193#, 16#a679438e#, 16#49b40821#,\n 16#f61e2562#, 16#c040b340#, 16#265e5a51#, 16#e9b6c7aa#,\n 16#d62f105d#, 16#02441453#, 16#d8a1e681#, 16#e7d3fbc8#,\n 16#21e1cde6#, 16#c33707d6#, 16#f4d50d87#, 16#455a14ed#,\n 16#a9e3e905#, 16#fcefa3f8#, 16#676f02d9#, 16#8d2a4c8a#,\n 16#fffa3942#, 16#8771f681#, 16#6d9d6122#, 16#fde5380c#,\n 16#a4beea44#, 16#4bdecfa9#, 16#f6bb4b60#, 16#bebfbc70#,\n 16#289b7ec6#, 16#eaa127fa#, 16#d4ef3085#, 16#04881d05#,\n 16#d9d4d039#, 16#e6db99e5#, 16#1fa27cf8#, 16#c4ac5665#,\n 16#f4292244#, 16#432aff97#, 16#ab9423a7#, 16#fc93a039#,\n 16#655b59c3#, 16#8f0ccc92#, 16#ffeff47d#, 16#85845dd1#,\n 16#6fa87e4f#, 16#fe2ce6e0#, 16#a3014314#, 16#4e0811a1#,\n 16#f7537e82#, 16#bd3af235#, 16#2ad7d2bb#, 16#eb86d391#);\n A : Int32 := 16#67452301#;\n B : Int32 := 16#EFCDAB89#;\n C : Int32 := 16#98BADCFE#;\n D : Int32 := 16#10325476#;\n Padded_String : constant Int32_Array := Pad_String (Input);\n begin\n for Block512 in 1 .. Padded_String'Length \/ 16 loop\n declare\n Words : constant Int32_Array (1 .. 16) :=\n Padded_String (16 * (Block512 - 1) + 1 .. 16 * Block512);\n AA : constant Int32 := A;\n BB : constant Int32 := B;\n CC : constant Int32 := C;\n DD : constant Int32 := D;\n begin\n -- round 1\n A := B + Rotate_Left ((A + F (B, C, D) + Words (1) + T (1)), 7);\n D := A + Rotate_Left ((D + F (A, B, C) + Words (2) + T (2)), 12);\n C := D + Rotate_Left ((C + F (D, A, B) + Words (3) + T (3)), 17);\n B := C + Rotate_Left ((B + F (C, D, A) + Words (4) + T (4)), 22);\n A := B + Rotate_Left ((A + F (B, C, D) + Words (5) + T (5)), 7);\n D := A + Rotate_Left ((D + F (A, B, C) + Words (6) + T (6)), 12);\n C := D + Rotate_Left ((C + F (D, A, B) + Words (7) + T (7)), 17);\n B := C + Rotate_Left ((B + F (C, D, A) + Words (8) + T (8)), 22);\n A := B + Rotate_Left ((A + F (B, C, D) + Words (9) + T (9)), 7);\n D := A + Rotate_Left ((D + F (A, B, C) + Words (10) + T (10)), 12);\n C := D + Rotate_Left ((C + F (D, A, B) + Words (11) + T (11)), 17);\n B := C + Rotate_Left ((B + F (C, D, A) + Words (12) + T (12)), 22);\n A := B + Rotate_Left ((A + F (B, C, D) + Words (13) + T (13)), 7);\n D := A + Rotate_Left ((D + F (A, B, C) + Words (14) + T (14)), 12);\n C := D + Rotate_Left ((C + F (D, A, B) + Words (15) + T (15)), 17);\n B := C + Rotate_Left ((B + F (C, D, A) + Words (16) + T (16)), 22);\n -- round 2\n A := B + Rotate_Left ((A + G (B, C, D) + Words (2) + T (17)), 5);\n D := A + Rotate_Left ((D + G (A, B, C) + Words (7) + T (18)), 9);\n C := D + Rotate_Left ((C + G (D, A, B) + Words (12) + T (19)), 14);\n B := C + Rotate_Left ((B + G (C, D, A) + Words (1) + T (20)), 20);\n A := B + Rotate_Left ((A + G (B, C, D) + Words (6) + T (21)), 5);\n D := A + Rotate_Left ((D + G (A, B, C) + Words (11) + T (22)), 9);\n C := D + Rotate_Left ((C + G (D, A, B) + Words (16) + T (23)), 14);\n B := C + Rotate_Left ((B + G (C, D, A) + Words (5) + T (24)), 20);\n A := B + Rotate_Left ((A + G (B, C, D) + Words (10) + T (25)), 5);\n D := A + Rotate_Left ((D + G (A, B, C) + Words (15) + T (26)), 9);\n C := D + Rotate_Left ((C + G (D, A, B) + Words (4) + T (27)), 14);\n B := C + Rotate_Left ((B + G (C, D, A) + Words (9) + T (28)), 20);\n A := B + Rotate_Left ((A + G (B, C, D) + Words (14) + T (29)), 5);\n D := A + Rotate_Left ((D + G (A, B, C) + Words (3) + T (30)), 9);\n C := D + Rotate_Left ((C + G (D, A, B) + Words (8) + T (31)), 14);\n B := C + Rotate_Left ((B + G (C, D, A) + Words (13) + T (32)), 20);\n -- round 3\n A := B + Rotate_Left ((A + H (B, C, D) + Words (6) + T (33)), 4);\n D := A + Rotate_Left ((D + H (A, B, C) + Words (9) + T (34)), 11);\n C := D + Rotate_Left ((C + H (D, A, B) + Words (12) + T (35)), 16);\n B := C + Rotate_Left ((B + H (C, D, A) + Words (15) + T (36)), 23);\n A := B + Rotate_Left ((A + H (B, C, D) + Words (2) + T (37)), 4);\n D := A + Rotate_Left ((D + H (A, B, C) + Words (5) + T (38)), 11);\n C := D + Rotate_Left ((C + H (D, A, B) + Words (8) + T (39)), 16);\n B := C + Rotate_Left ((B + H (C, D, A) + Words (11) + T (40)), 23);\n A := B + Rotate_Left ((A + H (B, C, D) + Words (14) + T (41)), 4);\n D := A + Rotate_Left ((D + H (A, B, C) + Words (1) + T (42)), 11);\n C := D + Rotate_Left ((C + H (D, A, B) + Words (4) + T (43)), 16);\n B := C + Rotate_Left ((B + H (C, D, A) + Words (7) + T (44)), 23);\n A := B + Rotate_Left ((A + H (B, C, D) + Words (10) + T (45)), 4);\n D := A + Rotate_Left ((D + H (A, B, C) + Words (13) + T (46)), 11);\n C := D + Rotate_Left ((C + H (D, A, B) + Words (16) + T (47)), 16);\n B := C + Rotate_Left ((B + H (C, D, A) + Words (3) + T (48)), 23);\n -- round 4\n A := B + Rotate_Left ((A + I (B, C, D) + Words (1) + T (49)), 6);\n D := A + Rotate_Left ((D + I (A, B, C) + Words (8) + T (50)), 10);\n C := D + Rotate_Left ((C + I (D, A, B) + Words (15) + T (51)), 15);\n B := C + Rotate_Left ((B + I (C, D, A) + Words (6) + T (52)), 21);\n A := B + Rotate_Left ((A + I (B, C, D) + Words (13) + T (53)), 6);\n D := A + Rotate_Left ((D + I (A, B, C) + Words (4) + T (54)), 10);\n C := D + Rotate_Left ((C + I (D, A, B) + Words (11) + T (55)), 15);\n B := C + Rotate_Left ((B + I (C, D, A) + Words (2) + T (56)), 21);\n A := B + Rotate_Left ((A + I (B, C, D) + Words (9) + T (57)), 6);\n D := A + Rotate_Left ((D + I (A, B, C) + Words (16) + T (58)), 10);\n C := D + Rotate_Left ((C + I (D, A, B) + Words (7) + T (59)), 15);\n B := C + Rotate_Left ((B + I (C, D, A) + Words (14) + T (60)), 21);\n A := B + Rotate_Left ((A + I (B, C, D) + Words (5) + T (61)), 6);\n D := A + Rotate_Left ((D + I (A, B, C) + Words (12) + T (62)), 10);\n C := D + Rotate_Left ((C + I (D, A, B) + Words (3) + T (63)), 15);\n B := C + Rotate_Left ((B + I (C, D, A) + Words (10) + T (64)), 21);\n -- increment\n A := A + AA;\n B := B + BB;\n C := C + CC;\n D := D + DD;\n end;\n end loop;\n return\n (Turn_Around (A),\n Turn_Around (B),\n Turn_Around (C),\n Turn_Around (D));\n end MD5;\n\n function To_String (Item : MD5_Hash) return MD5_String is\n Hex_Chars : constant array (0 .. 15) of Character :=\n ('0', '1', '2', '3', '4', '5', '6', '7',\n '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');\n Result : MD5_String := (1 => '0',\n 2 => 'x',\n others => '0');\n Temp : Int32;\n Position : Natural := Result'Last;\n begin\n for Part in reverse Item'Range loop\n Temp := Item (Part);\n while Position > Result'Last - (5 - Part) * 8 loop\n Result (Position) := Hex_Chars (Natural (Temp mod 16));\n Position := Position - 1;\n Temp := Temp \/ 16;\n end loop;\n end loop;\n return Result;\n end To_String;\n\nend MD5;\n\n\nwith Ada.Strings.Unbounded;\nwith Ada.Text_IO;\nwith MD5;\n\nprocedure Tester is\n use Ada.Strings.Unbounded;\n type String_Array is array (Positive range <>) of Unbounded_String;\n Sources : constant String_Array :=\n (To_Unbounded_String (\"\"),\n To_Unbounded_String (\"a\"),\n To_Unbounded_String (\"abc\"),\n To_Unbounded_String (\"message digest\"),\n To_Unbounded_String (\"abcdefghijklmnopqrstuvwxyz\"),\n To_Unbounded_String\n (\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"),\n To_Unbounded_String\n (\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\")\n );\n Digests : constant String_Array :=\n (To_Unbounded_String (\"0xd41d8cd98f00b204e9800998ecf8427e\"),\n To_Unbounded_String (\"0x0cc175b9c0f1b6a831c399e269772661\"),\n To_Unbounded_String (\"0x900150983cd24fb0d6963f7d28e17f72\"),\n To_Unbounded_String (\"0xf96b697d7cb7938d525a2f31aaf161d0\"),\n To_Unbounded_String (\"0xc3fcd3d76192e4007dfb496cca67e13b\"),\n To_Unbounded_String (\"0xd174ab98d277d9f5a5611c2c9f419d9f\"),\n To_Unbounded_String (\"0x57edf4a22be3c955ac49da2e2107b67a\"));\nbegin\n for I in Sources'Range loop\n Ada.Text_IO.Put_Line (\"MD5 (\"\"\" & To_String (Sources (I)) & \"\"\"):\");\n Ada.Text_IO.Put_Line\n (MD5.To_String (MD5.MD5 (To_String (Sources (I)))));\n Ada.Text_IO.Put_Line (To_String (Digests (I)) & \" (correct value)\");\n end loop;\nend Tester;\n\n\nMD5 (\"\"):\n0xd41d8cd98f00b204e9800998ecf8427e\n0xd41d8cd98f00b204e9800998ecf8427e (correct value)\nMD5 (\"a\"):\n0x0cc175b9c0f1b6a831c399e269772661\n0x0cc175b9c0f1b6a831c399e269772661 (correct value)\nMD5 (\"abc\"):\n0x900150983cd24fb0d6963f7d28e17f72\n0x900150983cd24fb0d6963f7d28e17f72 (correct value)\nMD5 (\"message digest\"):\n0xf96b697d7cb7938d525a2f31aaf161d0\n0xf96b697d7cb7938d525a2f31aaf161d0 (correct value)\nMD5 (\"abcdefghijklmnopqrstuvwxyz\"):\n0xc3fcd3d76192e4007dfb496cca67e13b\n0xc3fcd3d76192e4007dfb496cca67e13b (correct value)\nMD5 (\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"):\n0xd174ab98d277d9f5a5611c2c9f419d9f\n0xd174ab98d277d9f5a5611c2c9f419d9f (correct value)\nMD5 (\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"):\n0x57edf4a22be3c955ac49da2e2107b67a\n0x57edf4a22be3c955ac49da2e2107b67a (correct value)\n","human_summarization":"implement the MD5 Message Digest Algorithm without using any built-in or external hashing libraries. The implementation focuses on producing a correct message digest for an input string. It includes challenges faced, implementation choices made, and any limitations. The codes do not mimic all calling modes but provide practical illustrations of bit manipulation, unsigned integers, and working with little-endian data. It also includes verification strings and hashes from RFC 1321. The MD5 algorithm was developed by RSA Data Security, Inc. in 1991. However, MD5 is not recommended for applications requiring high security.","id":109} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\n\nprocedure Department_Numbers is\n use Ada.Text_IO;\nbegin\n Put_Line (\" P S F\");\n for Police in 2 .. 6 loop\n for Sanitation in 1 .. 7 loop\n for Fire in 1 .. 7 loop\n if\n Police mod 2 = 0 and\n Police + Sanitation + Fire = 12 and\n Sanitation \/= Police and\n Sanitation \/= Fire and\n Police \/= Fire\n then\n Put_Line (Police'Image & Sanitation'Image & Fire'Image);\n end if;\n end loop;\n end loop;\n end loop;\nend Department_Numbers;\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":110} {"lang_cluster":"Ada","source_code":"\n\nSrc : String := \"Hello\";\nDest : String := Src;\n\n\nSrc : String := \"Rosetta Stone\";\nDest : String := Src(1..7); -- Assigns \"Rosetta\" to Dest\nDest2 : String := Src(9..13); -- Assigns \"Stone\" to Dest2\n\n-- Instantiate the generic package Ada.Strings.Bounded.Generic_Bounded_Length with a maximum length of 80 characters\npackage Flexible_String is new Ada.Strings.Bounded.Generic_Bounded_Length(80);\nuse Flexible_String;\n\nSrc : Bounded_String := To_Bounded_String(\"Hello\");\nDest : Bounded_String := Src;\n\n\n-- The package Ada.Strings.Unbounded contains the definition of the Unbounded_String type and all its methods\nSrc : Unbounded_String := To_Unbounded_String(\"Hello\");\nDest : Unbounded_String := Src;\n\n","human_summarization":"The code implements the task of copying a string in Ada programming language. It differentiates between copying the actual content of a string and creating an additional reference to an existing string. It utilizes three types of strings provided by Ada: fixed length String, Bounded_String with variable length up to a maximum size, and Unbounded_String with no maximum size. The code also manipulates slices of strings, particularly with the Bounded_String type.","id":111} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_Io; use Ada.Text_Io; \nprocedure Mutual_Recursion is\n function M(N : Integer) return Integer;\n function F(N : Integer) return Integer is\n begin\n if N = 0 then\n return 1;\n else\n return N - M(F(N - 1));\n end if;\n end F;\n function M(N : Integer) return Integer is\n begin\n if N = 0 then\n return 0;\n else\n return N - F(M(N-1));\n end if;\n end M;\nbegin\n for I in 0..19 loop\n Put_Line(Integer'Image(F(I)));\n end loop;\n New_Line;\n for I in 0..19 loop\n Put_Line(Integer'Image(M(I)));\n end loop;\nend Mutual_recursion;\n\nWorks with: Ada 2012\nwith Ada.Text_Io; use Ada.Text_Io;\nprocedure Mutual_Recursion is\n function M(N: Natural) return Natural;\n function F(N: Natural) return Natural;\n \n function M(N: Natural) return Natural is\n (if N = 0 then 0 else N \u2013 F(M(N\u20131)));\n \n function F(N: Natural) return Natural is\n (if N =0 then 1 else N \u2013 M(F(N\u20131)));\nbegin\n for I in 0..19 loop\n Put_Line(Integer'Image(F(I)));\n end loop;\n New_Line;\n for I in 0..19 loop\n Put_Line(Integer'Image(M(I)));\n end loop;\n \nend Mutual_recursion;\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":112} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO, Ada.Numerics.Float_Random;\n\nprocedure Pick_Random_Element is\n\n package Rnd renames Ada.Numerics.Float_Random;\n Gen: Rnd.Generator; -- used globally\n\n type Char_Arr is array (Natural range <>) of Character;\n\n function Pick_Random(A: Char_Arr) return Character is\n -- Chooses one of the characters of A (uniformly distributed)\n begin\n return A(A'First + Natural(Rnd.Random(Gen) * Float(A'Last)));\n end Pick_Random;\n\n Vowels : Char_Arr := ('a', 'e', 'i', 'o', 'u');\n Consonants: Char_Arr := ('t', 'n', 's', 'h', 'r', 'd', 'l');\n Specials : Char_Arr := (',', '.', '?', '!');\n\nbegin\n Rnd.Reset(Gen);\n for J in 1 .. 3 loop\n for I in 1 .. 10 loop\n Ada.Text_IO.Put(Pick_Random(Consonants));\n Ada.Text_IO.Put(Pick_Random(Vowels));\n end loop;\n Ada.Text_IO.Put(Pick_Random(Specials) & \" \");\n end loop;\n Ada.Text_IO.New_Line;\nend Pick_Random_Element;\n\n\n","human_summarization":"\"Code generates three 20-letter words by randomly picking each vowel and consonant from a respective list.\"","id":113} {"lang_cluster":"Ada","source_code":"\nLibrary: AWS\nwith AWS.URL;\nwith Ada.Text_IO; use Ada.Text_IO;\nprocedure Decode is\n Encoded : constant String := \"http%3A%2F%2Ffoo%20bar%2F\";\nbegin\n Put_Line (AWS.URL.Decode (Encoded));\nend Decode;\n\n\npackage URL is\n function Decode (URL : in String) return String;\nend URL;\n\npackage body URL is\n function Decode (URL : in String) return String is\n Buffer : String (1 .. URL'Length);\n Filled : Natural := 0;\n Position : Positive := URL'First;\n begin\n while Position in URL'Range loop\n Filled := Filled + 1;\n \n case URL (Position) is\n when '+' =>\n Buffer (Filled) := ' ';\n Position := Position + 1;\n when '%' =>\n Buffer (Filled) :=\n Character'Val\n (Natural'Value\n (\"16#\" & URL (Position + 1 .. Position + 2) & \"#\"));\n Position := Position + 3;\n when others =>\n Buffer (Filled) := URL (Position);\n Position := Position + 1;\n end case;\n end loop;\n\n return Buffer (1 .. Filled);\n end Decode;\nend URL;\n\nwith Ada.Command_Line,\n Ada.Text_IO;\n\nwith URL;\n\nprocedure Test_URL_Decode is\n use Ada.Command_Line, Ada.Text_IO;\nbegin\n if Argument_Count = 0 then\n Put_Line (URL.Decode (\"http%3A%2F%2Ffoo%20bar%2F\"));\n else\n for I in 1 .. Argument_Count loop\n Put_Line (URL.Decode (Argument (I)));\n end loop;\n end if;\nend Test_URL_Decode;\n\n","human_summarization":"Implement a function to convert URL-encoded strings back into their original unencoded form. This includes handling special characters and not mistaking encoded representations for actual characters.","id":114} {"lang_cluster":"Ada","source_code":"\n\nRecursive\n\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_Recursive_Binary_Search is\n Not_Found : exception;\n \n generic\n type Index is range <>;\n type Element is private;\n type Array_Of_Elements is array (Index range <>) of Element;\n with function \"<\" (L, R : Element) return Boolean is <>;\n function Search (Container : Array_Of_Elements; Value : Element) return Index;\n\n function Search (Container : Array_Of_Elements; Value : Element) return Index is\n Mid : Index;\n begin\n if Container'Length > 0 then\n Mid := (Container'First + Container'Last) \/ 2;\n if Value < Container (Mid) then\n if Container'First \/= Mid then\n return Search (Container (Container'First..Mid - 1), Value);\n end if;\n elsif Container (Mid) < Value then\n if Container'Last \/= Mid then\n return Search (Container (Mid + 1..Container'Last), Value);\n end if;\n else\n return Mid;\n end if;\n end if;\n raise Not_Found;\n end Search;\n\n type Integer_Array is array (Positive range <>) of Integer;\n function Find is new Search (Positive, Integer, Integer_Array);\n \n procedure Test (X : Integer_Array; E : Integer) is\n begin\n New_Line;\n for I in X'Range loop\n Put (Integer'Image (X (I)));\n end loop;\n Put (\" contains\" & Integer'Image (E) & \" at\" & Integer'Image (Find (X, E)));\n exception\n when Not_Found =>\n Put (\" does not contain\" & Integer'Image (E));\n end Test;\nbegin\n Test ((2, 4, 6, 8, 9), 2);\n Test ((2, 4, 6, 8, 9), 1);\n Test ((2, 4, 6, 8, 9), 8);\n Test ((2, 4, 6, 8, 9), 10);\n Test ((2, 4, 6, 8, 9), 9);\n Test ((2, 4, 6, 8, 9), 5);\nend Test_Recursive_Binary_Search;\n\nIterative\n\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_Binary_Search is\n Not_Found : exception;\n \n generic\n type Index is range <>;\n type Element is private;\n type Array_Of_Elements is array (Index range <>) of Element;\n with function \"<\" (L, R : Element) return Boolean is <>;\n function Search (Container : Array_Of_Elements; Value : Element) return Index;\n\n function Search (Container : Array_Of_Elements; Value : Element) return Index is\n Low : Index := Container'First;\n High : Index := Container'Last;\n Mid : Index;\n begin\n if Container'Length > 0 then\n loop\n Mid := (Low + High) \/ 2;\n if Value < Container (Mid) then\n exit when Low = Mid;\n High := Mid - 1;\n elsif Container (Mid) < Value then\n exit when High = Mid;\n Low := Mid + 1;\n else\n return Mid;\n end if;\n end loop;\n end if;\n raise Not_Found;\n end Search;\n\n type Integer_Array is array (Positive range <>) of Integer;\n function Find is new Search (Positive, Integer, Integer_Array);\n \n procedure Test (X : Integer_Array; E : Integer) is\n begin\n New_Line;\n for I in X'Range loop\n Put (Integer'Image (X (I)));\n end loop;\n Put (\" contains\" & Integer'Image (E) & \" at\" & Integer'Image (Find (X, E)));\n exception\n when Not_Found =>\n Put (\" does not contain\" & Integer'Image (E));\n end Test;\nbegin\n Test ((2, 4, 6, 8, 9), 2);\n Test ((2, 4, 6, 8, 9), 1);\n Test ((2, 4, 6, 8, 9), 8);\n Test ((2, 4, 6, 8, 9), 10);\n Test ((2, 4, 6, 8, 9), 9);\n Test ((2, 4, 6, 8, 9), 5);\nend Test_Binary_Search;\n\n\n 2 4 6 8 9 contains 2 at 1\n 2 4 6 8 9 does not contain 1\n 2 4 6 8 9 contains 8 at 4\n 2 4 6 8 9 does not contain 10\n 2 4 6 8 9 contains 9 at 5\n 2 4 6 8 9 does not contain 5\n\n","human_summarization":"The code implements a binary search algorithm that divides a range of values into halves to find a specific \"secret value\". The algorithm can be recursive or iterative and works with a sorted integer array. It also handles cases where there are multiple values equal to the given value and returns the index of the found element. The code also includes variants that return the leftmost and rightmost insertion points for the given value. Additionally, the code handles potential overflow bugs.","id":115} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Command_line; use Ada.Command_Line;\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Print_Commands is\nbegin\n -- The number of command line arguments is retrieved from the function Argument_Count\n -- The actual arguments are retrieved from the function Argument\n -- The program name is retrieved from the function Command_Name\n Put(Command_Name & \" \");\n for Arg in 1..Argument_Count loop\n Put(Argument(Arg) & \" \");\n end loop;\n New_Line;\nend Print_Commands;\n\n\nwith Ada.Wide_Wide_Text_IO;\n\nwith League.Application;\nwith League.Strings;\n\nprocedure Main is\nbegin\n for J in 1 .. League.Application.Arguments.Length loop\n Ada.Wide_Wide_Text_IO.Put_Line\n (League.Application.Arguments.Element (J).To_Wide_Wide_String);\n end loop;\nend Main;\n\n","human_summarization":"The code retrieves the list of command-line arguments provided to the program. It prints the arguments only when the program is run directly. The code uses the Ada.Command_Line package in Ada95 and later versions for this task, while in Ada83, the implementation is dependent. It uses Matreshka for parsing command-line arguments intelligently. For example, for the command line \"myprogram -c \"alpha beta\" -h \"gamma\"\", it retrieves and processes the arguments \"-c\", \"alpha beta\", \"-h\", \"gamma\".","id":116} {"lang_cluster":"Ada","source_code":"\n\ngeneric\n type Float_Type is digits <>;\n Gravitation : Float_Type;\npackage Pendulums is\n type Pendulum is private;\n function New_Pendulum (Length : Float_Type;\n Theta0 : Float_Type) return Pendulum;\n function Get_X (From : Pendulum) return Float_Type;\n function Get_Y (From : Pendulum) return Float_Type;\n procedure Update_Pendulum (Item : in out Pendulum; Time : in Duration);\nprivate\n type Pendulum is record\n Length : Float_Type;\n Theta : Float_Type;\n X : Float_Type;\n Y : Float_Type;\n Velocity : Float_Type;\n end record;\nend Pendulums;\n\n\nwith Ada.Numerics.Generic_Elementary_Functions;\npackage body Pendulums is\n package Math is new Ada.Numerics.Generic_Elementary_Functions (Float_Type);\n\n function New_Pendulum (Length : Float_Type;\n Theta0 : Float_Type) return Pendulum is\n Result : Pendulum;\n begin\n Result.Length := Length;\n Result.Theta := Theta0 \/ 180.0 * Ada.Numerics.Pi;\n Result.X := Math.Sin (Theta0) * Length;\n Result.Y := Math.Cos (Theta0) * Length;\n Result.Velocity := 0.0;\n return Result;\n end New_Pendulum;\n\n function Get_X (From : Pendulum) return Float_Type is\n begin\n return From.X;\n end Get_X;\n\n function Get_Y (From : Pendulum) return Float_Type is\n begin\n return From.Y;\n end Get_Y;\n\n procedure Update_Pendulum (Item : in out Pendulum; Time : in Duration) is\n Acceleration : constant Float_Type := Gravitation \/ Item.Length *\n Math.Sin (Item.Theta);\n begin\n Item.X := Math.Sin (Item.Theta) * Item.Length;\n Item.Y := Math.Cos (Item.Theta) * Item.Length;\n Item.Velocity := Item.Velocity +\n Acceleration * Float_Type (Time);\n Item.Theta := Item.Theta +\n Item.Velocity * Float_Type (Time);\n end Update_Pendulum;\nend Pendulums;\n\n\nwith Ada.Text_IO;\nwith Ada.Calendar;\nwith Pendulums;\n\nprocedure Main is\n package Float_Pendulum is new Pendulums (Float, -9.81);\n use Float_Pendulum;\n use type Ada.Calendar.Time;\n\n My_Pendulum : Pendulum := New_Pendulum (10.0, 30.0);\n Now, Before : Ada.Calendar.Time;\nbegin\n Before := Ada.Calendar.Clock;\n loop\n Delay 0.1;\n Now := Ada.Calendar.Clock;\n Update_Pendulum (My_Pendulum, Now - Before);\n Before := Now;\n -- output positions relative to origin\n -- replace with graphical output if wanted\n Ada.Text_IO.Put_Line (\" X: \" & Float'Image (Get_X (My_Pendulum)) &\n \" Y: \" & Float'Image (Get_Y (My_Pendulum)));\n end loop;\nend Main;\n\n\n","human_summarization":"simulate a gravity pendulum system, animate its movement, and print out the relative positions of the pendulum to the anchor. The codes do not involve a GUI and the output method can be replaced with graphical update methods.","id":117} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\nwith GNATCOLL.JSON;\n \nprocedure JSON_Test is\n use Ada.Text_IO;\n use GNATCOLL.JSON;\n \n JSON_String : constant String := \"{\"\"name\"\":\"\"Pingu\"\",\"\"born\"\":1986}\";\n \n Penguin : JSON_Value := Create_Object;\n Parents : JSON_Array;\nbegin\n Penguin.Set_Field (Field_Name => \"name\", \n Field => \"Linux\");\n \n Penguin.Set_Field (Field_Name => \"born\",\n Field => 1992);\n \n Append (Parents, Create (\"Linus Torvalds\"));\n Append (Parents, Create (\"Alan Cox\"));\n Append (Parents, Create (\"Greg Kroah-Hartman\"));\n \n Penguin.Set_Field (Field_Name => \"parents\",\n Field => Parents);\n \n Put_Line (Penguin.Write);\n\n Penguin := Read (JSON_String, \"json.errors\");\n \n Penguin.Set_Field (Field_Name => \"born\",\n Field => 1986);\n \n Parents := Empty_Array;\n Append (Parents, Create (\"Otmar Gutmann\"));\n Append (Parents, Create (\"Silvio Mazzola\")); \n \n Penguin.Set_Field (Field_Name => \"parents\",\n Field => Parents);\n \n Put_Line (Penguin.Write);\nend JSON_Test;\n\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":118} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_Nth_Root is\n generic\n type Real is digits <>;\n function Nth_Root (Value : Real; N : Positive) return Real;\n \n function Nth_Root (Value : Real; N : Positive) return Real is\n type Index is mod 2;\n X : array (Index) of Real := (Value, Value);\n K : Index := 0;\n begin\n loop\n X (K + 1) := ( (Real (N) - 1.0) * X (K) + Value \/ X (K) ** (N-1) ) \/ Real (N);\n exit when X (K + 1) >= X (K);\n K := K + 1;\n end loop;\n return X (K + 1);\n end Nth_Root;\n\n function Long_Nth_Root is new Nth_Root (Long_Float);\nbegin\n Put_Line (\"1024.0 10th =\" & Long_Float'Image (Long_Nth_Root (1024.0, 10)));\n Put_Line (\" 27.0 3rd =\" & Long_Float'Image (Long_Nth_Root (27.0, 3)));\n Put_Line (\" 2.0 2nd =\" & Long_Float'Image (Long_Nth_Root (2.0, 2)));\n Put_Line (\"5642.0 125th =\" & Long_Float'Image (Long_Nth_Root (5642.0, 125)));\nend Test_Nth_Root;\n\n\n1024.0 10th = 2.00000000000000E+00\n 27.0 3rd = 3.00000000000000E+00\n 2.0 2nd = 1.41421356237310E+00\n5642.0 125th = 1.07154759194477E+00\n\n","human_summarization":"implement a generic algorithm to compute the principal nth root of a positive real number, as per the method explained on Wikipedia. The algorithm works with any floating-point type and converges when the iteration condition gets violated.","id":119} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO; use Ada.Text_IO;\nwith GNAT.Sockets;\n\nprocedure Demo is\nbegin\n Put_Line (GNAT.Sockets.Host_Name);\nend Demo;\n\n","human_summarization":"The code retrieves the hostname of the system where the routine is being executed, compatible with GCC\/GNAT.","id":120} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Leonardo is\n\n function Leo\n (N : Natural;\n Step : Natural := 1;\n First : Natural := 1;\n Second : Natural := 1) return Natural is \n L : array (0..1) of Natural := (First, Second);\n\tbegin\n\t\tfor i in 1 .. N loop\n\t\t\tL := (L(1), L(0)+L(1)+Step);\n\t\tend loop;\n\t\treturn L (0);\n\tend Leo;\n\nbegin\n Put_Line (\"First 25 Leonardo numbers:\");\n for I in 0 .. 24 loop\n Put (Integer'Image (Leo (I)));\n end loop;\n New_Line;\n Put_Line (\"First 25 Leonardo numbers with L(0) = 0, L(1) = 1, \" &\n \"step = 0 (fibonacci numbers):\");\n for I in 0 .. 24 loop\n Put (Integer'Image (Leo (I, 0, 0, 1)));\n end loop;\n New_Line;\nend Leonardo;\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":121} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Float_Text_IO;\nwith Ada.Text_IO;\nwith Ada.Numerics.Discrete_Random;\nprocedure Game_24 is\n subtype Digit is Character range '1' .. '9';\n package Random_Digit is new Ada.Numerics.Discrete_Random (Digit);\n Exp_Error : exception;\n Digit_Generator : Random_Digit.Generator;\n Given_Digits : array (1 .. 4) of Digit;\n Float_Value : constant array (Digit) of Float :=\n (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0);\n function Apply_Op (L, R : Float; Op : Character) return Float is\n begin\n case Op is\n when '+' =>\n return L + R;\n when '-' =>\n return L - R;\n when '*' =>\n return L * R;\n when '\/' =>\n return L \/ R;\n when others =>\n Ada.Text_IO.Put_Line (\"Unexpected operator: \" & Op);\n raise Exp_Error;\n end case;\n end Apply_Op;\n function Eval_Exp (E : String) return Float is\n Flt : Float;\n First : Positive := E'First;\n Last : Positive;\n function Match_Paren (Start : Positive) return Positive is\n Pos : Positive := Start + 1;\n Level : Natural := 1;\n begin\n loop\n if Pos > E'Last then\n Ada.Text_IO.Put_Line (\"Unclosed parentheses.\");\n raise Exp_Error;\n elsif E (Pos) = '(' then\n Level := Level + 1;\n elsif E (Pos) = ')' then\n Level := Level - 1;\n exit when Level = 0;\n end if;\n Pos := Pos + 1;\n end loop;\n return Pos;\n end Match_Paren;\n begin\n if E (First) = '(' then\n Last := Match_Paren (First);\n Flt := Eval_Exp (E (First + 1 .. Last - 1));\n elsif E (First) in Digit then\n Last := First;\n Flt := Float_Value (E (First));\n else\n Ada.Text_IO.Put_Line (\"Unexpected character: \" & E (First));\n raise Exp_Error;\n end if;\n loop\n if Last = E'Last then\n return Flt;\n elsif Last = E'Last - 1 then\n Ada.Text_IO.Put_Line (\"Unexpected end of expression.\");\n raise Exp_Error;\n end if;\n First := Last + 2;\n if E (First) = '(' then\n Last := Match_Paren (First);\n Flt := Apply_Op (Flt, Eval_Exp (E (First + 1 .. Last - 1)),\n Op => E (First - 1));\n elsif E (First) in Digit then\n Last := First;\n Flt := Apply_Op (Flt, Float_Value (E (First)),\n Op => E (First - 1));\n else\n Ada.Text_IO.Put_Line (\"Unexpected character: \" & E (First));\n raise Exp_Error;\n end if;\n end loop;\n end Eval_Exp;\nbegin\n Ada.Text_IO.Put_Line (\"24 Game\");\n Ada.Text_IO.Put_Line (\"- Enter Q to Quit\");\n Ada.Text_IO.Put_Line (\"- Enter N for New digits\");\n Ada.Text_IO.Put_Line (\"Note: Operators are evaluated left-to-right\");\n Ada.Text_IO.Put_Line (\" (use parentheses to override)\");\n Random_Digit.Reset (Digit_Generator);\n <>\n Ada.Text_IO.Put_Line (\"Generating 4 digits...\");\n for I in Given_Digits'Range loop\n Given_Digits (I) := Random_Digit.Random (Digit_Generator);\n end loop;\n <>\n Ada.Text_IO.Put (\"Your Digits:\");\n for I in Given_Digits'Range loop\n Ada.Text_IO.Put (\" \" & Given_Digits (I));\n end loop;\n Ada.Text_IO.New_Line;\n Ada.Text_IO.Put (\"Enter your Expression: \");\n declare\n Value : Float;\n Response : constant String := Ada.Text_IO.Get_Line;\n Prev_Ch : Character := ' ';\n Unused_Digits : array (Given_Digits'Range) of Boolean :=\n (others => True);\n begin\n if Response = \"n\" or Response = \"N\" then\n goto GEN_DIGITS;\n end if;\n if Response = \"q\" or Response = \"Q\" then\n return;\n end if;\n -- check input\n for I in Response'Range loop\n declare\n Ch : constant Character := Response (I);\n Found : Boolean;\n begin\n if Ch in Digit then\n if Prev_Ch in Digit then\n Ada.Text_IO.Put_Line (\"Illegal multi-digit number used.\");\n goto GET_EXP;\n end if;\n Found := False;\n for J in Given_Digits'Range loop\n if Unused_Digits (J) and then\n Given_Digits (J) = Ch then\n Unused_Digits (J) := False;\n Found := True;\n exit;\n end if;\n end loop;\n if not Found then\n Ada.Text_IO.Put_Line (\"Illegal number used: \" & Ch);\n goto GET_EXP;\n end if;\n elsif Ch \/= '(' and Ch \/= ')' and Ch \/= '+' and\n Ch \/= '-' and Ch \/= '*' and Ch \/= '\/' then\n Ada.Text_IO.Put_Line (\"Illegal character used: \" & Ch);\n goto GET_EXP;\n end if;\n Prev_Ch := Ch;\n end;\n end loop;\n -- check all digits used\n for I in Given_Digits'Range loop\n if Unused_Digits (I) then\n Ada.Text_IO.Put_Line (\"Digit not used: \" & Given_Digits (I));\n goto GET_EXP;\n end if;\n end loop;\n -- check value\n begin\n Value := Eval_Exp (Response);\n exception\n when Exp_Error =>\n goto GET_EXP; -- Message displayed by Eval_Exp;\n end;\n if abs (Value - 24.0) > 0.001 then\n Ada.Text_IO.Put (\"Value \");\n Ada.Float_Text_IO.Put (Value, Fore => 0, Aft => 3, Exp => 0);\n Ada.Text_IO.Put_Line (\" is not 24!\");\n goto GET_EXP;\n else\n Ada.Text_IO.Put_Line (\"You won!\");\n Ada.Text_IO.Put_Line (\"Enter N for a new game, or try another solution.\");\n goto GET_EXP;\n end if;\n end;\nend Game_24;\n\n\n","human_summarization":"The code is for a game called \"24 Game\" that tests a player's mental arithmetic skills. It randomly selects and displays four digits from 1 to 9, and prompts the player to form an arithmetic expression using these digits exactly once each. The goal is to create an expression that evaluates to 24 using only multiplication, division, addition, and subtraction. The code checks and evaluates the player's input expression. Division is performed using floating point or rational arithmetic to preserve remainders, and brackets are allowed. The code does not allow forming multiple digit numbers from the given digits. The order of the digits does not have to be preserved. The code does not generate the expression or test its possibility.","id":122} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Ada.Strings.Fixed; use Ada.Strings.Fixed;\nprocedure Test_Run_Length_Encoding is\n function Encode (Data : String) return String is\n begin\n if Data'Length = 0 then\n return \"\";\n else\n declare\n Code : constant Character := Data (Data'First);\n Index : Integer := Data'First + 1;\n begin\n while Index <= Data'Last and then Code = Data (Index) loop\n Index := Index + 1;\n end loop;\n declare\n Prefix : constant String := Integer'Image (Index - Data'First);\n begin\n return Prefix (2..Prefix'Last) & Code & Encode (Data (Index..Data'Last));\n end;\n end;\n end if;\n end Encode;\n function Decode (Data : String) return String is\n begin\n if Data'Length = 0 then\n return \"\";\n else\n declare\n Index : Integer := Data'First;\n Count : Natural := 0;\n begin\n while Index < Data'Last and then Data (Index) in '0'..'9' loop\n Count := Count * 10 + Character'Pos (Data (Index)) - Character'Pos ('0');\n Index := Index + 1;\n end loop;\n if Index > Data'First then\n return Count * Data (Index) & Decode (Data (Index + 1..Data'Last));\n else\n return Data;\n end if;\n end;\n end if;\n end Decode;\nbegin\n Put_Line (Encode (\"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"));\n Put_Line (Decode (\"12W1B12W3B24W1B14W\"));\nend Test_Run_Length_Encoding;\n\n\n12W1B12W3B24W1B14W\nWWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\n\n","human_summarization":"implement a run-length encoding algorithm that compresses a string of uppercase characters by storing the length of repeated characters. It also provides a function to reverse the compression. The output can be used to recreate the original input string.","id":123} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure String_Concatenation is\n S1 : constant String := \"Hello\";\n S2 : constant String := S1 & \" literal\";\nbegin\n Put_Line (S1);\n Put_Line (S2);\nend String_Concatenation;\n\n\nSample output:\nHello\nHello literal\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":124} {"lang_cluster":"Ada","source_code":"\nLibrary: AWS\nwith AWS.URL;\nwith Ada.Text_IO; use Ada.Text_IO;\nprocedure Encode is\n Normal : constant String := \"http:\/\/foo bar\/\";\nbegin\n Put_Line (AWS.URL.Encode (Normal));\nend Encode;\n\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":125} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_Io;\nwith Ada.Containers.Vectors;\n\nprocedure Sorted is\n\n package Integer_Vectors is\n new Ada.Containers.Vectors (Index_Type => Positive,\n Element_Type => Integer);\n use Integer_Vectors;\n\n package Vector_Sorting is\n new Integer_Vectors.Generic_Sorting;\n use Vector_Sorting;\n\n procedure Unique (Vec : in out Vector) is\n Res : Vector;\n begin\n for E of Vec loop\n if Res.Is_Empty or else Res.Last_Element \/= E then\n Res.Append (E);\n end if;\n end loop;\n Vec := Res;\n end Unique;\n\n procedure Put (Vec : Vector) is\n use Ada.Text_Io;\n begin\n Put (\"[\");\n for E of Vec loop\n Put (E'Image); Put (\" \");\n end loop;\n Put (\"]\");\n New_Line;\n end Put;\n\n A : constant Vector := 5 & 1 & 3 & 8 & 9 & 4 & 8 & 7;\n B : constant Vector := 3 & 5 & 9 & 8 & 4;\n C : constant Vector := 1 & 3 & 7 & 9;\n R : Vector := A & B & C;\nbegin\n Sort (R);\n Unique (R);\n Put (R);\nend Sorted;\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":126} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\nwith Ada.Float_Text_IO;\nwith Ada.Strings.Unbounded;\n \nprocedure Knapsack_Continuous is\n package US renames Ada.Strings.Unbounded;\n \n type Item is record\n Name : US.Unbounded_String;\n Weight : Float;\n Value : Positive;\n Taken : Float;\n end record;\n \n function \"<\" (Left, Right : Item) return Boolean is\n begin\n return Float (Left.Value) \/ Left.Weight <\n Float (Right.Value) \/ Right.Weight;\n end \"<\";\n \n type Item_Array is array (Positive range <>) of Item;\n \n function Total_Weight (Items : Item_Array) return Float is\n Sum : Float := 0.0;\n begin\n for I in Items'Range loop\n Sum := Sum + Items (I).Taken;\n end loop;\n return Sum;\n end Total_Weight;\n \n function Total_Value (Items : Item_Array) return Float is\n Sum : Float := 0.0;\n begin\n for I in Items'Range loop\n Sum := Sum + Float (Items (I).Value) \/ Items(I).Weight * Items (I).Taken;\n end loop;\n return Sum;\n end Total_Value;\n \n procedure Solve_Knapsack_Continuous\n (Items : in out Item_Array;\n Weight_Limit : Float)\n is\n begin\n -- order items by value per weight unit\n Sorting : declare\n An_Item : Item;\n J : Natural;\n begin\n for I in Items'First + 1 .. Items'Last loop\n An_Item := Items (I);\n J := I - 1;\n while J in Items'Range and then Items (J) < An_Item loop\n Items (J + 1) := Items (J);\n J := J - 1;\n end loop;\n Items (J + 1) := An_Item;\n end loop;\n end Sorting;\n declare\n Rest : Float := Weight_Limit;\n begin\n for I in Items'Range loop\n if Items (I).Weight <= Rest then\n Items (I).Taken := Items (I).Weight;\n else\n Items (I).Taken := Rest;\n end if;\n Rest := Rest - Items (I).Taken;\n exit when Rest <= 0.0;\n end loop;\n end;\n end Solve_Knapsack_Continuous;\n All_Items : Item_Array :=\n ((US.To_Unbounded_String (\"beef\"), 3.8, 36, 0.0),\n (US.To_Unbounded_String (\"pork\"), 5.4, 43, 0.0),\n (US.To_Unbounded_String (\"ham\"), 3.6, 90, 0.0),\n (US.To_Unbounded_String (\"greaves\"), 2.4, 45, 0.0),\n (US.To_Unbounded_String (\"flitch\"), 4.0, 30, 0.0),\n (US.To_Unbounded_String (\"brawn\"), 2.5, 56, 0.0),\n (US.To_Unbounded_String (\"welt\"), 3.7, 67, 0.0),\n (US.To_Unbounded_String (\"salami\"), 3.0, 95, 0.0),\n (US.To_Unbounded_String (\"sausage\"), 5.9, 98, 0.0));\n \nbegin\n Solve_Knapsack_Continuous (All_Items, 15.0);\n Ada.Text_IO.Put (\"Total Weight: \");\n Ada.Float_Text_IO.Put (Total_Weight (All_Items), 0, 2, 0);\n Ada.Text_IO.New_Line;\n Ada.Text_IO.Put (\"Total Value: \");\n Ada.Float_Text_IO.Put (Total_Value (All_Items), 0, 2, 0);\n Ada.Text_IO.New_Line;\n Ada.Text_IO.Put_Line (\"Items:\");\n for I in All_Items'Range loop\n if All_Items (I).Taken > 0.0 then\n Ada.Text_IO.Put (\" \");\n Ada.Float_Text_IO.Put (All_Items (I).Taken, 0, 2, 0);\n Ada.Text_IO.Put_Line (\" of \" & US.To_String (All_Items (I).Name));\n end if;\n end loop;\nend Knapsack_Continuous;\n\n\n","human_summarization":"determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.","id":127} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n\nwith Ada.Containers.Indefinite_Ordered_Maps;\nwith Ada.Containers.Indefinite_Ordered_Sets;\n\nprocedure Words_Of_Equal_Characters is\n package Set_Of_Words is new Ada.Containers.Indefinite_Ordered_Sets (String);\n use Ada.Containers, Set_Of_Words;\n package Anagrams is new Ada.Containers.Indefinite_Ordered_Maps (String, Set);\n use Anagrams;\n\n File : File_Type;\n Result : Map;\n Max : Count_Type := 1;\n\n procedure Put (Position : Anagrams.Cursor) is\n First : Boolean := True;\n List : Set renames Element (Position);\n procedure Put (Position : Set_Of_Words.Cursor) is\n begin\n if First then\n First := False;\n else\n Put (',');\n end if;\n Put (Element (Position));\n end Put;\n begin\n if List.Length = Max then\n Iterate (List, Put'Access);\n New_Line;\n end if;\n end Put;\n\nbegin\n Open (File, In_File, \"unixdict.txt\");\n loop\n declare\n Word : constant String := Get_Line (File);\n Key : String (Word'Range) := (others => Character'Last);\n List : Set;\n Position : Anagrams.Cursor;\n begin\n for I in Word'Range loop\n for J in Word'Range loop\n if Key (J) > Word (I) then\n Key (J + 1..I) := Key (J..I - 1);\n Key (J) := Word (I);\n exit;\n end if;\n end loop;\n end loop;\n Position := Find (Result, Key);\n if Has_Element (Position) then\n List := Element (Position);\n Insert (List, Word);\n Replace_Element (Result, Position, List);\n else\n Insert (List, Word);\n Include (Result, Key, List);\n end if;\n Max := Count_Type'Max (Max, Length (List));\n end;\n end loop;\nexception\n when End_Error =>\n Iterate (Result, Put'Access);\n Close (File);\nend Words_Of_Equal_Characters;\n\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":128} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_Io; use Ada.Text_Io;\n\nprocedure Sierpinski_Carpet is\n subtype Index_Type is Integer range 1..81;\n type Pattern_Array is array(Index_Type range <>, Index_Type range <>) of Boolean;\n Pattern : Pattern_Array(1..81,1..81) := (Others =>(others => true));\n procedure Clear_Center(P : in out Pattern_Array; X1 : Index_Type; X2 : Index_Type;\n Y1 : Index_Type; Y2 : Index_Type) is\n Xfirst : Index_Type;\n Xlast : Index_Type;\n Yfirst : Index_Type;\n Ylast : Index_Type;\n Diff : Integer;\n begin\n Xfirst :=(X2 - X1 + 1) \/ 3 + X1;\n Diff := Xfirst - X1;\n Xlast := Xfirst + Diff;\n Yfirst := (Y2 - Y1) \/ 3 + Y1;\n YLast := YFirst + Diff;\n\n for I in XFirst..XLast loop\n for J in YFirst..YLast loop\n P(I, J) := False;\n end loop;\n end loop;\n end Clear_Center;\n \n procedure Print(P : Pattern_Array) is\n begin\n for I in P'range(1) loop\n for J in P'range(2) loop\n if P(I,J) then\n Put('*');\n else\n Put(' ');\n end if;\n end loop;\n New_Line;\n end loop;\n end Print;\n \n procedure Divide_Square(P : in out Pattern_Array; Order : Positive) is\n Factor : Natural := 0;\n X1, X2 : Index_Type;\n Y1, Y2 : Index_Type;\n Division : Index_Type;\n Num_Sections : Index_Type;\n begin\n while Factor < Order loop\n Num_Sections := 3**Factor;\n Factor := Factor + 1;\n X1 := P'First;\n Division := P'Last \/ Num_Sections;\n X2 := Division;\n Y1 := X1;\n Y2 := X2;\n loop\n loop\n Clear_Center(P, X1, X2, Y1, Y2);\n exit when X2 = P'Last;\n X1 := X2;\n X2 := X2 + Division;\n end loop;\n exit when Y2 = P'Last;\n Y1 := Y2;\n Y2 := Y2 + Division;\n X1 := P'First;\n X2 := Division;\n end loop;\n end loop;\n end Divide_Square;\n \nbegin\n Divide_Square(Pattern, 3);\n Print(Pattern);\nend Sierpinski_Carpet;\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":129} {"lang_cluster":"Ada","source_code":"\nWorks with: Ada 2005\n\nwith Ada.Containers.Indefinite_Ordered_Maps;\nwith Ada.Containers.Ordered_Maps;\nwith Ada.Finalization;\ngeneric\n type Symbol_Type is private;\n with function \"<\" (Left, Right : Symbol_Type) return Boolean is <>;\n with procedure Put (Item : Symbol_Type);\n type Symbol_Sequence is array (Positive range <>) of Symbol_Type;\n type Frequency_Type is private;\n with function \"+\" (Left, Right : Frequency_Type) return Frequency_Type\n is <>;\n with function \"<\" (Left, Right : Frequency_Type) return Boolean is <>;\npackage Huffman is\n -- bits = booleans (true\/false = 1\/0)\n type Bit_Sequence is array (Positive range <>) of Boolean;\n Zero_Sequence : constant Bit_Sequence (1 .. 0) := (others => False);\n -- output the sequence\n procedure Put (Code : Bit_Sequence);\n\n -- type for freqency map\n package Frequency_Maps is new Ada.Containers.Ordered_Maps\n (Element_Type => Frequency_Type,\n Key_Type => Symbol_Type);\n\n type Huffman_Tree is private;\n -- create a huffman tree from frequency map\n procedure Create_Tree\n (Tree : out Huffman_Tree;\n Frequencies : Frequency_Maps.Map);\n -- encode a single symbol\n function Encode\n (Tree : Huffman_Tree;\n Symbol : Symbol_Type)\n return Bit_Sequence;\n -- encode a symbol sequence\n function Encode\n (Tree : Huffman_Tree;\n Symbols : Symbol_Sequence)\n return Bit_Sequence;\n -- decode a bit sequence\n function Decode\n (Tree : Huffman_Tree;\n Code : Bit_Sequence)\n return Symbol_Sequence;\n -- dump the encoding table\n procedure Dump_Encoding (Tree : Huffman_Tree);\nprivate\n -- type for encoding map\n package Encoding_Maps is new Ada.Containers.Indefinite_Ordered_Maps\n (Element_Type => Bit_Sequence,\n Key_Type => Symbol_Type);\n\n type Huffman_Node;\n type Node_Access is access Huffman_Node;\n -- a node is either internal (left_child\/right_child used)\n -- or a leaf (left_child\/right_child are null)\n type Huffman_Node is record\n Frequency : Frequency_Type;\n Left_Child : Node_Access := null;\n Right_Child : Node_Access := null;\n Symbol : Symbol_Type;\n end record;\n -- create a leaf node\n function Create_Node\n (Symbol : Symbol_Type;\n Frequency : Frequency_Type)\n return Node_Access;\n -- create an internal node\n function Create_Node (Left, Right : Node_Access) return Node_Access;\n -- fill the encoding map\n procedure Fill\n (The_Node : Node_Access;\n Map : in out Encoding_Maps.Map;\n Prefix : Bit_Sequence);\n\n -- huffman tree has a tree and an encoding map\n type Huffman_Tree is new Ada.Finalization.Controlled with record\n Tree : Node_Access := null;\n Map : Encoding_Maps.Map := Encoding_Maps.Empty_Map;\n end record;\n -- free memory after finalization\n overriding procedure Finalize (Object : in out Huffman_Tree);\nend Huffman;\n\n\nwith Ada.Text_IO;\nwith Ada.Unchecked_Deallocation;\nwith Ada.Containers.Vectors;\npackage body Huffman is\n package Node_Vectors is new Ada.Containers.Vectors\n (Element_Type => Node_Access,\n Index_Type => Positive);\n\n function \"<\" (Left, Right : Node_Access) return Boolean is\n begin\n -- compare frequency\n if Left.Frequency < Right.Frequency then\n return True;\n elsif Right.Frequency < Left.Frequency then\n return False;\n end if;\n -- same frequency, choose leaf node\n if Left.Left_Child = null and then Right.Left_Child \/= null then\n return True;\n elsif Left.Left_Child \/= null and then Right.Left_Child = null then\n return False;\n end if;\n -- same frequency, same node type (internal\/leaf)\n if Left.Left_Child \/= null then\n -- for internal nodes, compare left children, then right children\n if Left.Left_Child < Right.Left_Child then\n return True;\n elsif Right.Left_Child < Left.Left_Child then\n return False;\n else\n return Left.Right_Child < Right.Right_Child;\n end if;\n else\n -- for leaf nodes, compare symbol\n return Left.Symbol < Right.Symbol;\n end if;\n end \"<\";\n package Node_Vector_Sort is new Node_Vectors.Generic_Sorting;\n\n procedure Create_Tree\n (Tree : out Huffman_Tree;\n Frequencies : Frequency_Maps.Map) is\n Node_Queue : Node_Vectors.Vector := Node_Vectors.Empty_Vector;\n begin\n -- insert all leafs into the queue\n declare\n use Frequency_Maps;\n Position : Cursor := Frequencies.First;\n The_Node : Node_Access := null;\n begin\n while Position \/= No_Element loop\n The_Node :=\n Create_Node\n (Symbol => Key (Position),\n Frequency => Element (Position));\n Node_Queue.Append (The_Node);\n Next (Position);\n end loop;\n end;\n -- sort by frequency (see \"<\")\n Node_Vector_Sort.Sort (Node_Queue);\n -- iterate over all elements\n while not Node_Queue.Is_Empty loop\n declare\n First : constant Node_Access := Node_Queue.First_Element;\n begin\n Node_Queue.Delete_First;\n -- if we only have one node left, it is the root node of the tree\n if Node_Queue.Is_Empty then\n Tree.Tree := First;\n else\n -- create new internal node with two smallest frequencies\n declare\n Second : constant Node_Access := Node_Queue.First_Element;\n begin\n Node_Queue.Delete_First;\n Node_Queue.Append (Create_Node (First, Second));\n end;\n Node_Vector_Sort.Sort (Node_Queue);\n end if;\n end;\n end loop;\n -- fill encoding map\n Fill (The_Node => Tree.Tree, Map => Tree.Map, Prefix => Zero_Sequence);\n end Create_Tree;\n\n -- create leaf node\n function Create_Node\n (Symbol : Symbol_Type;\n Frequency : Frequency_Type)\n return Node_Access\n is\n Result : Node_Access := new Huffman_Node;\n begin\n Result.Frequency := Frequency;\n Result.Symbol := Symbol;\n return Result;\n end Create_Node;\n\n -- create internal node\n function Create_Node (Left, Right : Node_Access) return Node_Access is\n Result : Node_Access := new Huffman_Node;\n begin\n Result.Frequency := Left.Frequency + Right.Frequency;\n Result.Left_Child := Left;\n Result.Right_Child := Right;\n return Result;\n end Create_Node;\n\n -- fill encoding map\n procedure Fill\n (The_Node : Node_Access;\n Map : in out Encoding_Maps.Map;\n Prefix : Bit_Sequence) is\n begin\n if The_Node.Left_Child \/= null then\n -- append false (0) for left child\n Fill (The_Node.Left_Child, Map, Prefix & False);\n -- append true (1) for right child\n Fill (The_Node.Right_Child, Map, Prefix & True);\n else\n -- leaf node reached, prefix = code for symbol\n Map.Insert (The_Node.Symbol, Prefix);\n end if;\n end Fill;\n\n -- free memory after finalization\n overriding procedure Finalize (Object : in out Huffman_Tree) is\n procedure Free is new Ada.Unchecked_Deallocation\n (Name => Node_Access,\n Object => Huffman_Node);\n -- recursively free all nodes\n procedure Recursive_Free (The_Node : in out Node_Access) is\n begin\n -- free node if it is a leaf\n if The_Node.Left_Child = null then\n Free (The_Node);\n else\n -- free left and right child if node is internal\n Recursive_Free (The_Node.Left_Child);\n Recursive_Free (The_Node.Right_Child);\n -- free node afterwards\n Free (The_Node);\n end if;\n end Recursive_Free;\n begin\n -- recursively free root node\n Recursive_Free (Object.Tree);\n end Finalize;\n\n -- encode single symbol\n function Encode\n (Tree : Huffman_Tree;\n Symbol : Symbol_Type)\n return Bit_Sequence\n is\n begin\n -- simply lookup in map\n return Tree.Map.Element (Symbol);\n end Encode;\n\n -- encode symbol sequence\n function Encode\n (Tree : Huffman_Tree;\n Symbols : Symbol_Sequence)\n return Bit_Sequence\n is\n begin\n -- only one element\n if Symbols'Length = 1 then\n -- see above\n return Encode (Tree, Symbols (Symbols'First));\n else\n -- encode first element, append result of recursive call\n return Encode (Tree, Symbols (Symbols'First)) &\n Encode (Tree, Symbols (Symbols'First + 1 .. Symbols'Last));\n end if;\n end Encode;\n\n -- decode a bit sequence\n function Decode\n (Tree : Huffman_Tree;\n Code : Bit_Sequence)\n return Symbol_Sequence\n is\n -- maximum length = code length\n Result : Symbol_Sequence (1 .. Code'Length);\n -- last used index of result\n Last : Natural := 0;\n The_Node : Node_Access := Tree.Tree;\n begin\n -- iterate over the code\n for I in Code'Range loop\n -- if current element is true, descent the right branch\n if Code (I) then\n The_Node := The_Node.Right_Child;\n else\n -- false: descend left branch\n The_Node := The_Node.Left_Child;\n end if;\n if The_Node.Left_Child = null then\n -- reached leaf node: append symbol to result\n Last := Last + 1;\n Result (Last) := The_Node.Symbol;\n -- reset current node to root\n The_Node := Tree.Tree;\n end if;\n end loop;\n -- return subset of result array\n return Result (1 .. Last);\n end Decode;\n\n -- output a bit sequence\n procedure Put (Code : Bit_Sequence) is\n package Int_IO is new Ada.Text_IO.Integer_IO (Integer);\n begin\n for I in Code'Range loop\n if Code (I) then\n -- true = 1\n Int_IO.Put (1, 0);\n else\n -- false = 0\n Int_IO.Put (0, 0);\n end if;\n end loop;\n Ada.Text_IO.New_Line;\n end Put;\n\n -- dump encoding map\n procedure Dump_Encoding (Tree : Huffman_Tree) is\n use type Encoding_Maps.Cursor;\n Position : Encoding_Maps.Cursor := Tree.Map.First;\n begin\n -- iterate map\n while Position \/= Encoding_Maps.No_Element loop\n -- key\n Put (Encoding_Maps.Key (Position));\n Ada.Text_IO.Put (\" = \");\n -- code\n Put (Encoding_Maps.Element (Position));\n Encoding_Maps.Next (Position);\n end loop;\n end Dump_Encoding;\nend Huffman;\n\n\nwith Ada.Text_IO;\nwith Huffman;\nprocedure Main is\n package Char_Natural_Huffman_Tree is new Huffman\n (Symbol_Type => Character,\n Put => Ada.Text_IO.Put,\n Symbol_Sequence => String,\n Frequency_Type => Natural);\n Tree : Char_Natural_Huffman_Tree.Huffman_Tree;\n Frequencies : Char_Natural_Huffman_Tree.Frequency_Maps.Map;\n Input_String : constant String :=\n \"this is an example for huffman encoding\";\nbegin\n -- build frequency map\n for I in Input_String'Range loop\n declare\n use Char_Natural_Huffman_Tree.Frequency_Maps;\n Position : constant Cursor := Frequencies.Find (Input_String (I));\n begin\n if Position = No_Element then\n Frequencies.Insert (Key => Input_String (I), New_Item => 1);\n else\n Frequencies.Replace_Element\n (Position => Position,\n New_Item => Element (Position) + 1);\n end if;\n end;\n end loop;\n\n -- create huffman tree\n Char_Natural_Huffman_Tree.Create_Tree\n (Tree => Tree,\n Frequencies => Frequencies);\n\n -- dump encodings\n Char_Natural_Huffman_Tree.Dump_Encoding (Tree => Tree);\n\n -- encode example string\n declare\n Code : constant Char_Natural_Huffman_Tree.Bit_Sequence :=\n Char_Natural_Huffman_Tree.Encode\n (Tree => Tree,\n Symbols => Input_String);\n begin\n Char_Natural_Huffman_Tree.Put (Code);\n Ada.Text_IO.Put_Line\n (Char_Natural_Huffman_Tree.Decode (Tree => Tree, Code => Code));\n end;\nend Main;\n\n\n","human_summarization":"The code implements Huffman encoding algorithm. It takes a string input, calculates the frequency of each character, and creates a priority queue with each character as a leaf node. It then constructs a binary tree by removing nodes with the highest priority (lowest probability) and creating new internal nodes with the sum of the probabilities of the two nodes. The code traverses the binary tree from root to leaves, assigning '0' for one branch and '1' for the other, accumulating these at each leaf to generate a Huffman encoding for each character. The output is a table of characters from the input string and their corresponding Huffman encodings.","id":130} {"lang_cluster":"Ada","source_code":"\nLibrary: GTK\u00a0version GtkAda\nLibrary: GtkAda\n\nwith Gdk.Event; use Gdk.Event;\nwith Gtk.Button; use Gtk.Button;\nwith Gtk.Label; use Gtk.Label;\nwith Gtk.Window; use Gtk.Window;\nwith Gtk.Widget; use Gtk.Widget;\nwith Gtk.Table; use Gtk.Table;\n\nwith Gtk.Handlers;\nwith Gtk.Main;\n\nprocedure Simple_Windowed_Application is\n Window : Gtk_Window;\n Grid : Gtk_Table;\n Button : Gtk_Button;\n Label : Gtk_Label;\n Count : Natural := 0;\n\n package Handlers is new Gtk.Handlers.Callback (Gtk_Widget_Record);\n package Return_Handlers is\n new Gtk.Handlers.Return_Callback (Gtk_Widget_Record, Boolean);\n\n function Delete_Event (Widget : access Gtk_Widget_Record'Class)\n return Boolean is\n begin\n return False;\n end Delete_Event;\n\n procedure Destroy (Widget : access Gtk_Widget_Record'Class) is\n begin\n Gtk.Main.Main_Quit;\n end Destroy;\n\n procedure Clicked (Widget : access Gtk_Widget_Record'Class) is\n begin\n Count := Count + 1;\n Set_Text (Label, \"The button clicks:\" & Natural'Image (Count));\n end Clicked;\n\nbegin\n Gtk.Main.Init;\n Gtk.Window.Gtk_New (Window);\n Gtk_New (Grid, 1, 2, False);\n Add (Window, Grid);\n Gtk_New (Label, \"There have been no clicks yet\");\n Attach (Grid, Label, 0, 1, 0, 1);\n Gtk_New (Button, \"Click me\");\n Attach (Grid, Button, 0, 1, 1, 2);\n Return_Handlers.Connect\n ( Window,\n \"delete_event\",\n Return_Handlers.To_Marshaller (Delete_Event'Access)\n );\n Handlers.Connect\n ( Window,\n \"destroy\",\n Handlers.To_Marshaller (Destroy'Access)\n );\n Handlers.Connect\n ( Button,\n \"clicked\",\n Handlers.To_Marshaller (Clicked'Access)\n );\n Show_All (Grid);\n Show (Window);\n\n Gtk.Main.Main;\nend Simple_Windowed_Application;\n\n","human_summarization":"create a GTK+ windowed application in Ada language. The application features a label initially displaying \"There have been no clicks yet\" and a button labeled \"click me\". Upon clicking the button, the label updates to show the total number of button clicks.","id":131} {"lang_cluster":"Ada","source_code":"\nfor I in reverse 0..10 loop\n Put_Line(Integer'Image(I));\nend loop;\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":132} {"lang_cluster":"Ada","source_code":"\nWITH Ada.Text_IO, Ada.Characters.Handling;\nUSE Ada.Text_IO, Ada.Characters.Handling;\n\nPROCEDURE Main IS\n SUBTYPE Alpha IS Character RANGE 'A' .. 'Z';\n TYPE Ring IS MOD (Alpha'Range_length);\n TYPE Seq IS ARRAY (Integer RANGE <>) OF Ring;\n \n FUNCTION \"+\" (S, Key : Seq) RETURN Seq IS\n R : Seq (S'Range);\n BEGIN\n FOR I IN R'Range LOOP\n R (I) := S (I) + Key (Key'First + (I - R'First) MOD Key'Length);\n END LOOP;\n RETURN R;\n END \"+\";\n \n FUNCTION \"-\" (S : Seq) RETURN Seq IS\n R : Seq (S'Range);\n BEGIN\n FOR I IN R'Range LOOP\n R (I) := - S (I);\n END LOOP; \n RETURN R;\n END \"-\";\n \n FUNCTION To_Seq (S : String) RETURN Seq IS\n R : Seq (S'Range);\n I : Integer := R'First;\n BEGIN\n FOR C OF To_Upper (S) LOOP\n IF C IN Alpha THEN\n R (I) := Ring'Mod (Alpha'Pos (C) - Alpha'Pos (Alpha'First));\n I := I + 1;\n END IF;\n END LOOP;\n RETURN R (R'First .. I - 1);\n END To_Seq;\n \n FUNCTION To_String (S : Seq ) RETURN String IS\n R : String (S'Range);\n BEGIN\n FOR I IN R'Range LOOP\n R (I) := Alpha'Val ( Integer (S (I)) + Alpha'Pos (Alpha'First));\n END LOOP;\n RETURN R;\n END To_String;\n \n Input : Seq := To_Seq (Get_Line);\n Key : Seq := To_Seq (Get_Line);\n Crypt : Seq := Input + Key;\nBEGIN\n Put_Line (\"Encrypted: \" & To_String (Crypt));\n Put_Line (\"Decrypted: \" & To_String (Crypt + (-Key)));\nEND Main;\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":133} {"lang_cluster":"Ada","source_code":"\n\nwith Loopers;\nuse Loopers;\n\n\nprocedure For_Main is\nbegin\n Looper_1;\n Looper_2;\n Looper_3;\nend For_Main;\n\n\npackage Loopers is\n procedure Looper_1;\n procedure Looper_2;\n procedure Looper_3;\nend Loopers;\n\nwith Ada.Text_IO, Ada.Integer_Text_IO;\nuse Ada.Text_IO, Ada.Integer_Text_IO;\n\npackage body Loopers is\n procedure Looper_1 is\n Values : array(1..5) of Integer := (2,4,6,8,10);\n begin\n for I in Values'Range loop\n Put(Values(I),0);\n if I = Values'Last then\n Put_Line(\".\");\n else\n Put(\",\");\n end if;\n end loop;\n end Looper_1;\n\n procedure Looper_2 is\n E : Integer := 5;\n begin\n for I in 1..E loop\n Put(I*2,0);\n if I = E then\n Put_Line(\".\");\n else\n Put(\",\");\n end if;\n end loop;\n end Looper_2;\n\n procedure Looper_3 is\n Values : array(1..10) of Integer := (1,2,3,4,5,6,7,8,9,10);\n Indices : array(1..5) of Integer := (2,4,6,8,10);\n begin\n for I in Indices'Range loop\n Put(Values(Indices(I)),0);\n if I = Indices'Last then\n Put_Line(\".\");\n else\n Put(\",\");\n end if;\n end loop;\n end Looper_3;\n\nend Loopers;\n\n","human_summarization":"demonstrate three versions of a for-loop in Ada where the step-value is greater than one. The first version goes through a range of even values, the second version multiplies each value by two, and the third version uses a second range for the indices.","id":134} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Jensen_Device is\n function Sum\n ( I : not null access Float;\n Lo, Hi : Float;\n F : access function return Float\n ) return Float is\n Temp : Float := 0.0;\n begin\n I.all := Lo;\n while I.all <= Hi loop\n Temp := Temp + F.all;\n I.all := I.all + 1.0;\n end loop;\n return Temp;\n end Sum;\n\n I : aliased Float;\n function Inv_I return Float is\n begin\n return 1.0 \/ I;\n end Inv_I;\nbegin\n Put_Line (Float'Image (Sum (I'Access, 1.0, 100.0, Inv_I'Access)));\nend Jensen_Device;\n\n 5.18738E+00\n\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":135} {"lang_cluster":"Ada","source_code":"\nLibrary: GtkAda\n\nwith Cairo; use Cairo;\nwith Cairo.Png; use Cairo.Png;\nwith Cairo.Image_Surface; use Cairo.Image_Surface;\nprocedure XorPattern is\n type xorable is mod 256;\n Surface : Cairo_Surface;\n Data : RGB24_Array_Access;\n Status : Cairo_Status;\n Num : Byte;\nbegin\n Data := new RGB24_Array(0..256*256-1);\n for x in Natural range 0..255 loop\n for y in Natural range 0..255 loop\n Num := Byte(xorable(x) xor xorable(y));\n Data(x+256*y) := RGB24_Data'(Num,0,Num);\n end loop;\n end loop;\n Surface := Create_For_Data_RGB24(Data, 256, 256);\n Status := Write_To_Png (Surface, \"AdaXorPattern.png\");\n pragma Assert (Status = Cairo_Status_Success);\nend XorPattern;\n\n\n","human_summarization":"Creates a graphical pattern with pixel color determined by the 'x xor y' value from a color table, using the Cairo component of GtkAda, and saves the pattern as a PNG file.","id":136} {"lang_cluster":"Ada","source_code":"\nWorks with: Ada 2005\nWorks with: GNAT\n\ngeneric\n Height : Positive;\n Width : Positive;\npackage Mazes is\n\n type Maze_Grid is private;\n\n procedure Initialize (Maze : in out Maze_Grid);\n\n procedure Put (Item : Maze_Grid);\n\nprivate\n\n type Directions is (North, South, West, East);\n\n type Cell_Walls is array (Directions) of Boolean;\n type Cells is record\n Walls : Cell_Walls := (others => True);\n Visited : Boolean := False;\n end record;\n\n subtype Height_Type is Positive range 1 .. Height;\n subtype Width_Type is Positive range 1 .. Width;\n\n type Maze_Grid is array (Height_Type, Width_Type) of Cells;\n\nend Mazes;\n\n\nwith Ada.Numerics.Discrete_Random;\nwith Ada.Text_IO;\n \npackage body Mazes is\n package RNG is new Ada.Numerics.Discrete_Random (Positive);\n package Random_Direction is new Ada.Numerics.Discrete_Random (Directions);\n \n Generator : RNG.Generator;\n Dir_Generator : Random_Direction.Generator;\n \n function \"-\" (Dir : Directions) return Directions is\n begin\n case Dir is\n when North =>\n return South;\n when South =>\n return North;\n when East =>\n return West;\n when West =>\n return East;\n end case;\n end \"-\";\n \n procedure Move\n (Row : in out Height_Type;\n Column : in out Width_Type;\n Direction : Directions;\n Valid_Move : out Boolean)\n is\n begin\n Valid_Move := False;\n case Direction is\n when North =>\n if Row > Height_Type'First then\n Valid_Move := True;\n Row := Row - 1;\n end if;\n when East =>\n if Column < Width_Type'Last then\n Valid_Move := True;\n Column := Column + 1;\n end if;\n when West =>\n if Column > Width_Type'First then\n Valid_Move := True;\n Column := Column - 1;\n end if;\n when South =>\n if Row < Height_Type'Last then\n Valid_Move := True;\n Row := Row + 1;\n end if;\n end case;\n end Move;\n \n procedure Depth_First_Algorithm\n (Maze : in out Maze_Grid;\n Row : Height_Type;\n Column : Width_Type)\n is\n Next_Row : Height_Type;\n Next_Column : Width_Type;\n Next_Direction : Directions;\n Valid_Direction : Boolean;\n Tested_Wall : array (Directions) of Boolean := (others => False);\n All_Tested : Boolean;\n begin\n -- mark as visited\n Maze (Row, Column).Visited := True;\n loop\n -- use random direction\n loop\n Next_Direction := Random_Direction.Random (Dir_Generator);\n exit when not Tested_Wall (Next_Direction);\n end loop;\n Next_Row := Row;\n Next_Column := Column;\n Move (Next_Row, Next_Column, Next_Direction, Valid_Direction);\n if Valid_Direction then\n if not Maze (Next_Row, Next_Column).Visited then\n -- connect the two cells\n Maze (Row, Column).Walls (Next_Direction) :=\n False;\n Maze (Next_Row, Next_Column).Walls (-Next_Direction) :=\n False;\n Depth_First_Algorithm (Maze, Next_Row, Next_Column);\n end if;\n end if;\n Tested_Wall (Next_Direction) := True;\n -- continue as long as there are unvisited neighbours left\n All_Tested := True;\n for D in Directions loop\n All_Tested := All_Tested and Tested_Wall (D);\n end loop;\n -- all directions are either visited (from here,\n -- or previously visited), or invalid.\n exit when All_Tested;\n end loop;\n end Depth_First_Algorithm;\n \n procedure Initialize (Maze : in out Maze_Grid) is\n Row, Column : Positive;\n begin\n -- initialize random generators\n RNG.Reset (Generator);\n Random_Direction.Reset (Dir_Generator);\n -- choose starting cell\n Row := RNG.Random (Generator) mod Height + 1;\n Column := RNG.Random (Generator) mod Width + 1;\n Ada.Text_IO.Put_Line\n (\"Starting generation at \" &\n Positive'Image (Row) &\n \" x\" &\n Positive'Image (Column));\n Depth_First_Algorithm (Maze, Row, Column);\n end Initialize;\n \n procedure Put (Item : Maze_Grid) is\n begin\n for Row in Item'Range (1) loop\n if Row = Item'First (1) then\n Ada.Text_IO.Put ('+');\n for Col in Item'Range (2) loop\n if Item (Row, Col).Walls (North) then\n Ada.Text_IO.Put (\"---+\");\n else\n Ada.Text_IO.Put (\" +\");\n end if;\n end loop;\n Ada.Text_IO.New_Line;\n end if;\n for Col in Item'Range (2) loop\n if Col = Item'First (2) then\n if Item (Row, Col).Walls (West) then\n Ada.Text_IO.Put ('|');\n else\n Ada.Text_IO.Put (' ');\n end if;\n elsif Item (Row, Col).Walls (West)\n and then Item (Row, Col - 1).Walls (East)\n then\n Ada.Text_IO.Put ('|');\n elsif Item (Row, Col).Walls (West)\n or else Item (Row, Col - 1).Walls (East)\n then\n Ada.Text_IO.Put ('>');\n else\n Ada.Text_IO.Put (' ');\n end if;\n if Item (Row, Col).Visited then\n Ada.Text_IO.Put (\" \");\n else\n Ada.Text_IO.Put (\"???\");\n end if;\n end loop;\n if Item (Row, Item'Last (2)).Walls (East) then\n Ada.Text_IO.Put_Line (\"|\");\n else\n Ada.Text_IO.Put_Line (\" \");\n end if;\n Ada.Text_IO.Put ('+');\n for Col in Item'Range (2) loop\n if Item (Row, Col).Walls (South) then\n Ada.Text_IO.Put (\"---+\");\n else\n Ada.Text_IO.Put (\" +\");\n end if;\n end loop;\n Ada.Text_IO.New_Line;\n end loop;\n end Put;\nend Mazes;\n\n\nwith Mazes;\nprocedure Main is\n package Small_Mazes is new Mazes (Height => 8, Width => 11);\n My_Maze : Small_Mazes.Maze_Grid;\nbegin\n Small_Mazes.Initialize (My_Maze);\n Small_Mazes.Put (My_Maze);\nend Main;\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts at a random cell, marks it as visited, and retrieves a list of its neighboring cells. For each neighbor, it removes the wall between the current cell and the unvisited neighbor, then recursively applies the same process with the neighbor as the current cell.","id":137} {"lang_cluster":"Ada","source_code":"\nWorks with: Ada 2005\nLibrary: GMP\n\npi_digits.adb\n\nwith Ada.Command_Line;\nwith Ada.Text_IO;\nwith GNU_Multiple_Precision.Big_Integers;\nwith GNU_Multiple_Precision.Big_Rationals;\nuse GNU_Multiple_Precision;\n\nprocedure Pi_Digits is\n type Int is mod 2 ** 64;\n package Int_To_Big is new Big_Integers.Modular_Conversions (Int);\n\n -- constants\n Zero : constant Big_Integer := Int_To_Big.To_Big_Integer (0);\n One : constant Big_Integer := Int_To_Big.To_Big_Integer (1);\n Two : constant Big_Integer := Int_To_Big.To_Big_Integer (2);\n Three : constant Big_Integer := Int_To_Big.To_Big_Integer (3);\n Four : constant Big_Integer := Int_To_Big.To_Big_Integer (4);\n Ten : constant Big_Integer := Int_To_Big.To_Big_Integer (10);\n\n -- type LFT = (Integer, Integer, Integer, Integer\n type LFT is record\n Q, R, S, T : Big_Integer;\n end record;\n\n -- extr\u00a0:: LFT -> Integer -> Rational\n function Extr (T : LFT; X : Big_Integer) return Big_Rational is\n use Big_Integers;\n Result : Big_Rational;\n begin\n -- extr (q,r,s,t) x = ((fromInteger q) * x + (fromInteger r)) \/\n -- ((fromInteger s) * x + (fromInteger t))\n Big_Rationals.Set_Numerator (Item => Result,\n New_Value => T.Q * X + T.R,\n Canonicalize => False);\n Big_Rationals.Set_Denominator (Item => Result,\n New_Value => T.S * X + T.T);\n return Result;\n end Extr;\n\n -- unit\u00a0:: LFT\n function Unit return LFT is\n begin\n -- unit = (1,0,0,1)\n return LFT'(Q => One, R => Zero, S => Zero, T => One);\n end Unit;\n\n -- comp\u00a0:: LFT -> LFT -> LFT\n function Comp (T1, T2 : LFT) return LFT is\n use Big_Integers;\n begin\n -- comp (q,r,s,t) (u,v,w,x) = (q*u+r*w,q*v+r*x,s*u+t*w,s*v+t*x)\n return LFT'(Q => T1.Q * T2.Q + T1.R * T2.S,\n R => T1.Q * T2.R + T1.R * T2.T,\n S => T1.S * T2.Q + T1.T * T2.S,\n T => T1.S * T2.R + T1.T * T2.T);\n end Comp;\n\n -- lfts = [(k, 4*k+2, 0, 2*k+1) | k<-[1..]\n K : Big_Integer := Zero;\n function LFTS return LFT is\n use Big_Integers;\n begin\n K := K + One;\n return LFT'(Q => K,\n R => Four * K + Two,\n S => Zero,\n T => Two * K + One);\n end LFTS;\n\n -- next z = floor (extr z 3)\n function Next (T : LFT) return Big_Integer is\n begin\n return Big_Rationals.To_Big_Integer (Extr (T, Three));\n end Next;\n\n -- safe z n = (n == floor (extr z 4)\n function Safe (T : LFT; N : Big_Integer) return Boolean is\n begin\n return N = Big_Rationals.To_Big_Integer (Extr (T, Four));\n end Safe;\n\n -- prod z n = comp (10, -10*n, 0, 1)\n function Prod (T : LFT; N : Big_Integer) return LFT is\n use Big_Integers;\n begin\n return Comp (LFT'(Q => Ten, R => -Ten * N, S => Zero, T => One), T);\n end Prod;\n\n procedure Print_Pi (Digit_Count : Positive) is\n Z : LFT := Unit;\n Y : Big_Integer;\n Count : Natural := 0;\n begin\n loop\n Y := Next (Z);\n if Safe (Z, Y) then\n Count := Count + 1;\n Ada.Text_IO.Put (Big_Integers.Image (Y));\n exit when Count >= Digit_Count;\n Z := Prod (Z, Y);\n else\n Z := Comp (Z, LFTS);\n end if;\n end loop;\n end Print_Pi;\n\n N : Positive := 250;\nbegin\n if Ada.Command_Line.Argument_Count = 1 then\n N := Positive'Value (Ada.Command_Line.Argument (1));\n end if;\n Print_Pi (N);\nend Pi_Digits;\n\n\n 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 5 0 2 8 8 4 1 9 7 1 6 9 3 9 9 3 7 5 1 0 5 8 2 0 9 7 4 9 4 4 5 9 2 3 0 7 8 1 6 4 0 6 2 8 6 2 0 8 9 9 8 6 2 8 0 3 4 8 2 5 3 4 2 1 1 7 0 6 7\n","human_summarization":"The code continually calculates and outputs the next decimal digit of Pi, starting from 3.14159265. The process continues indefinitely until the user aborts it. The calculation of Pi is based on the algorithm used in the Go solution from a specified source.","id":138} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO; use Ada.Text_IO;\nprocedure Order is\n\n type IntArray is array (Positive range <>) of Integer;\n List1 : IntArray := (1, 2, 3, 4, 5);\n List2 : IntArray := (1, 2, 1, 5, 2, 2);\n List3 : IntArray := (1, 2, 1, 5, 2);\n List4 : IntArray := (1, 2, 1, 5, 2);\n\n type Animal is (Rat, Cat, Elephant);\n type AnimalArray is array (Positive range <>) of Animal;\n List5 : AnimalArray := (Cat, Elephant, Rat, Cat);\n List6 : AnimalArray := (Cat, Elephant, Rat);\n List7 : AnimalArray := (Cat, Cat, Elephant);\n\nbegin\n Put_Line (Boolean'Image (List1 > List2)); -- True\n Put_Line (Boolean'Image (List2 > List3)); -- True\n Put_Line (Boolean'Image (List3 > List4)); -- False, equal\n Put_Line (Boolean'Image (List5 > List6)); -- True\n Put_Line (Boolean'Image (List6 > List7)); -- True\nend Order;\n\n\n","human_summarization":"The function takes two numerical lists as input, compares them lexicographically, and returns true if the first list should be ordered before the second, otherwise returns false. If any list runs out of elements, it returns true for the first list and false for the second list or both. It handles arrays of user-defined types as well.","id":139} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_Ackermann is\n function Ackermann (M, N : Natural) return Natural is\n begin\n if M = 0 then\n return N + 1;\n elsif N = 0 then\n return Ackermann (M - 1, 1);\n else\n return Ackermann (M - 1, Ackermann (M, N - 1));\n end if;\n end Ackermann;\nbegin\n for M in 0..3 loop\n for N in 0..6 loop\n Put (Natural'Image (Ackermann (M, N)));\n end loop;\n New_Line;\n end loop;\nend Test_Ackermann;\n\n\n\n","human_summarization":"Implement the Ackermann function, a non-primitive recursive function that grows rapidly in value and call tree size. The function takes two non-negative arguments and always terminates. It is defined as follows: if m=0, return n+1; if m>0 and n=0, return A(m-1, 1); if m>0 and n>0, return A(m-1, A(m, n-1)). The function doesn't require arbitrary precision.","id":140} {"lang_cluster":"Ada","source_code":"\n\nfunction Gamma (X : Long_Float) return Long_Float is\n A : constant array (0..29) of Long_Float :=\n ( 1.00000_00000_00000_00000,\n 0.57721_56649_01532_86061,\n -0.65587_80715_20253_88108,\n -0.04200_26350_34095_23553,\n 0.16653_86113_82291_48950,\n -0.04219_77345_55544_33675,\n -0.00962_19715_27876_97356,\n 0.00721_89432_46663_09954,\n -0.00116_51675_91859_06511,\n -0.00021_52416_74114_95097,\n 0.00012_80502_82388_11619,\n -0.00002_01348_54780_78824,\n -0.00000_12504_93482_14267,\n 0.00000_11330_27231_98170,\n -0.00000_02056_33841_69776,\n 0.00000_00061_16095_10448,\n 0.00000_00050_02007_64447,\n -0.00000_00011_81274_57049,\n 0.00000_00001_04342_67117,\n 0.00000_00000_07782_26344,\n -0.00000_00000_03696_80562,\n 0.00000_00000_00510_03703,\n -0.00000_00000_00020_58326,\n -0.00000_00000_00005_34812,\n 0.00000_00000_00001_22678,\n -0.00000_00000_00000_11813,\n 0.00000_00000_00000_00119,\n 0.00000_00000_00000_00141,\n -0.00000_00000_00000_00023,\n 0.00000_00000_00000_00002\n );\n Y : constant Long_Float := X - 1.0;\n Sum : Long_Float := A (A'Last);\nbegin\n for N in reverse A'First..A'Last - 1 loop\n Sum := Sum * Y + A (N);\n end loop;\n return 1.0 \/ Sum;\nend Gamma;\n\n\nwith Ada.Text_IO; use Ada.Text_IO;\nwith Gamma;\n\nprocedure Test_Gamma is\nbegin\n for I in 1..10 loop\n Put_Line (Long_Float'Image (Gamma (Long_Float (I) \/ 3.0)));\n end loop;\nend Test_Gamma;\n\n\n","human_summarization":"Implement and compare the Gamma function using various algorithms such as numerical integration, Lanczos approximation, and Stirling's approximation. The implementation also utilizes Taylor series coefficients taken from a mathematical functions reference. The functionality of the Gamma function is tested and compared with built-in or library functions if available.","id":141} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Queens is\n Board : array (1..8, 1..8) of Boolean := (others => (others => False));\n function Test (Row, Column : Integer) return Boolean is\n begin\n for J in 1..Column - 1 loop\n if ( Board (Row, J)\n or else\n (Row > J and then Board (Row - J, Column - J))\n or else\n (Row + J <= 8 and then Board (Row + J, Column - J))\n ) then\n return False;\n end if;\n end loop;\n return True;\n end Test;\n function Fill (Column : Integer) return Boolean is\n begin\n for Row in Board'Range (1) loop\n if Test (Row, Column) then\n Board (Row, Column) := True;\n if Column = 8 or else Fill (Column + 1) then\n return True;\n end if;\n Board (Row, Column) := False;\n end if;\n end loop;\n return False;\n end Fill;\nbegin\n if not Fill (1) then\n raise Program_Error;\n end if;\n for I in Board'Range (1) loop\n Put (Integer'Image (9 - I));\n for J in Board'Range (2) loop\n if Board (I, J) then\n Put (\"|Q\");\n elsif (I + J) mod 2 = 1 then\n Put (\"|\/\");\n else\n Put (\"| \");\n end if;\n end loop;\n Put_Line (\"|\");\n end loop;\n Put_Line (\" A B C D E F G H\");\nend Queens;\n\n\n","human_summarization":"solve the N-queens problem, extending the eight queens puzzle to a board of size NxN. The codes count the number of solutions for small values of N (refer OEIS: A000170) and provide the flexibility to perform different operations for each solution.","id":142} {"lang_cluster":"Ada","source_code":"\n\ntype T is array (Positive range <>) of Integer;\nX : T := (1, 2, 3);\nY : T := X & (4, 5, 6); -- Concatenate X and (4, 5, 6)\n\n","human_summarization":"demonstrate how to concatenate two arrays in Ada using the & operation.","id":143} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\nwith Ada.Strings.Unbounded;\n\nprocedure Knapsack_01 is\n package US renames Ada.Strings.Unbounded;\n\n type Item is record\n Name : US.Unbounded_String;\n Weight : Positive;\n Value : Positive;\n Taken : Boolean;\n end record;\n\n type Item_Array is array (Positive range <>) of Item;\n\n function Total_Weight (Items : Item_Array; Untaken : Boolean := False) return Natural is\n Sum : Natural := 0;\n begin\n for I in Items'Range loop\n if Untaken or else Items (I).Taken then\n Sum := Sum + Items (I).Weight;\n end if;\n end loop;\n return Sum;\n end Total_Weight;\n\n function Total_Value (Items : Item_Array; Untaken : Boolean := False) return Natural is\n Sum : Natural := 0;\n begin\n for I in Items'Range loop\n if Untaken or else Items (I).Taken then\n Sum := Sum + Items (I).Value;\n end if;\n end loop;\n return Sum;\n end Total_Value;\n\n function Max (Left, Right : Natural) return Natural is\n begin\n if Right > Left then\n return Right;\n else\n return Left;\n end if;\n end Max;\n\n procedure Solve_Knapsack_01 (Items : in out Item_Array;\n Weight_Limit : Positive := 400) is\n type W_Array is array (0..Items'Length, 0..Weight_Limit) of Natural;\n W : W_Array := (others => (others => 0));\n begin\n -- fill W\n for I in Items'Range loop\n for J in 1 .. Weight_Limit loop\n if Items (I).Weight > J then\n W (I, J) := W (I - 1, J);\n else\n W (I, J) := Max (W (I - 1, J),\n W (I - 1, J - Items (I).Weight) + Items (I).Value);\n end if;\n end loop;\n end loop;\n declare\n Rest : Natural := Weight_Limit;\n begin\n for I in reverse Items'Range loop\n if W (I, Rest) \/= W (I - 1, Rest) then\n Items (I).Taken := True;\n Rest := Rest - Items (I).Weight;\n end if;\n end loop;\n end;\n end Solve_Knapsack_01;\n\n All_Items : Item_Array :=\n ( (US.To_Unbounded_String (\"map\"), 9, 150, False),\n (US.To_Unbounded_String (\"compass\"), 13, 35, False),\n (US.To_Unbounded_String (\"water\"), 153, 200, False),\n (US.To_Unbounded_String (\"sandwich\"), 50, 160, False),\n (US.To_Unbounded_String (\"glucose\"), 15, 60, False),\n (US.To_Unbounded_String (\"tin\"), 68, 45, False),\n (US.To_Unbounded_String (\"banana\"), 27, 60, False),\n (US.To_Unbounded_String (\"apple\"), 39, 40, False),\n (US.To_Unbounded_String (\"cheese\"), 23, 30, False),\n (US.To_Unbounded_String (\"beer\"), 52, 10, False),\n (US.To_Unbounded_String (\"suntan cream\"), 11, 70, False),\n (US.To_Unbounded_String (\"camera\"), 32, 30, False),\n (US.To_Unbounded_String (\"t-shirt\"), 24, 15, False),\n (US.To_Unbounded_String (\"trousers\"), 48, 10, False),\n (US.To_Unbounded_String (\"umbrella\"), 73, 40, False),\n (US.To_Unbounded_String (\"waterproof trousers\"), 42, 70, False),\n (US.To_Unbounded_String (\"waterproof overclothes\"), 43, 75, False),\n (US.To_Unbounded_String (\"note-case\"), 22, 80, False),\n (US.To_Unbounded_String (\"sunglasses\"), 7, 20, False),\n (US.To_Unbounded_String (\"towel\"), 18, 12, False),\n (US.To_Unbounded_String (\"socks\"), 4, 50, False),\n (US.To_Unbounded_String (\"book\"), 30, 10, False) );\n\nbegin\n Solve_Knapsack_01 (All_Items, 400);\n Ada.Text_IO.Put_Line (\"Total Weight: \" & Natural'Image (Total_Weight (All_Items)));\n Ada.Text_IO.Put_Line (\"Total Value: \" & Natural'Image (Total_Value (All_Items)));\n Ada.Text_IO.Put_Line (\"Items:\");\n for I in All_Items'Range loop\n if All_Items (I).Taken then\n Ada.Text_IO.Put_Line (\" \" & US.To_String (All_Items (I).Name));\n end if;\n end loop;\nend Knapsack_01;\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":144} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Test_Short_Circuit is\n function A (Value : Boolean) return Boolean is\n begin\n Put (\" A=\" & Boolean'Image (Value));\n return Value;\n end A;\n function B (Value : Boolean) return Boolean is\n begin\n Put (\" B=\" & Boolean'Image (Value));\n return Value;\n end B;\nbegin\n for I in Boolean'Range loop\n for J in Boolean'Range loop\n Put (\" (A and then B)=\" & Boolean'Image (A (I) and then B (J)));\n New_Line;\n end loop;\n end loop;\n for I in Boolean'Range loop\n for J in Boolean'Range loop\n Put (\" (A or else B)=\" & Boolean'Image (A (I) or else B (J)));\n New_Line;\n end loop;\n end loop;\nend Test_Short_Circuit;\n\n\nSample output:\n A=FALSE (A and then B)=FALSE\n A=FALSE (A and then B)=FALSE\n A=TRUE B=FALSE (A and then B)=FALSE\n A=TRUE B=TRUE (A and then B)=TRUE\n A=FALSE B=FALSE (A or else B)=FALSE\n A=FALSE B=TRUE (A or else B)=TRUE\n A=TRUE (A or else B)=TRUE\n A=TRUE (A or else B)=TRUE\n\n","human_summarization":"The code creates two functions, 'a' and 'b', which accept and return the same boolean value, and print their name when called. The code then calculates the values of 'x' and 'y' using the 'and' and 'or' operators respectively, ensuring that function 'b' is only called when necessary. This is achieved through short-circuit evaluation, or if not supported, through nested 'if' statements. In the case of Ada, built-in short-circuit operations 'then' and 'or else' are used.","id":145} {"lang_cluster":"Ada","source_code":"\n\npackage Morse is\n\n type Symbols is (Nul, '-', '.', ' ');\n -- Nul is the letter separator, space the word separator;\n Dash : constant Symbols := '-';\n Dot : constant Symbols := '.';\n type Morse_Str is array (Positive range <>) of Symbols;\n pragma Pack (Morse_Str);\n\n function Convert (Input : String) return Morse_Str;\n procedure Morsebeep (Input : Morse_Str);\n\nprivate\n subtype Reschars is Character range ' ' .. 'Z';\n -- restricted set of characters from 16#20# to 16#60#\n subtype Length is Natural range 1 .. 5;\n subtype Codes is Morse_Str (Length);\n -- using the current ITU standard with 5 signs\n -- only alphanumeric characters are taken into consideration\n\n type Codings is record\n L : Length;\n Code : Codes;\n end record;\n Table : constant array (Reschars) of Codings :=\n ('A' => (2, \".- \"), 'B' => (4, \"-... \"), 'C' => (4, \"-.-. \"),\n 'D' => (3, \"-.. \"), 'E' => (1, \". \"), 'F' => (4, \"..-. \"),\n 'G' => (3, \"--. \"), 'H' => (4, \".... \"), 'I' => (2, \".. \"),\n 'J' => (4, \".--- \"), 'K' => (3, \"-.- \"), 'L' => (4, \".-.. \"),\n 'M' => (2, \"-- \"), 'N' => (2, \"-. \"), 'O' => (3, \"--- \"),\n 'P' => (4, \".--. \"), 'Q' => (4, \"--.- \"), 'R' => (3, \".-. \"),\n 'S' => (3, \"... \"), 'T' => (1, \"- \"), 'U' => (3, \"..- \"),\n 'V' => (4, \"...- \"), 'W' => (3, \".-- \"), 'X' => (4, \"-..- \"),\n 'Y' => (4, \"-.-- \"), 'Z' => (4, \"--.. \"), '1' => (5, \".----\"),\n '2' => (5, \"..---\"), '3' => (5, \"...--\"), '4' => (5, \"....-\"),\n '5' => (5, \".....\"), '6' => (5, \"-....\"), '7' => (5, \"--...\"),\n '8' => (5, \"---..\"), '9' => (5, \"----.\"), '0' => (5, \"-----\"),\n others => (1, \" \")); -- Dummy => Other characters do not need code.\n\nend Morse;\n\nwith Ada.Strings.Maps, Ada.Characters.Handling, Interfaces.C;\nuse Ada, Ada.Strings, Ada.Strings.Maps, Interfaces;\n\npackage body Morse is\n\n Dit, Dah, Lettergap, Wordgap : Duration; -- in seconds\n Dit_ms, Dah_ms : C.unsigned; -- durations expressed in ms\n Freq : constant C.unsigned := 1280; -- in Herz\n\n Morse_Sequence : constant Character_Sequence :=\n \" ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n Morse_charset : constant Character_Set := To_Set (Morse_Sequence);\n\n function Convert (Input : String) return Morse_Str is\n Cap_String : constant String := Characters.Handling.To_Upper (Input);\n Result : Morse_Str (1 .. 7 * Input'Length); -- Upper Capacity\n First, Last : Natural := 0;\n Char_code : Codings;\n begin\n for I in Cap_String'Range loop\n if Is_In (Cap_String (I), Morse_charset) then\n First := Last + 1;\n if Cap_String (I) = ' ' then\n Result (First) := ' ';\n Last := Last + 1;\n else\n Char_code := Table (Reschars (Cap_String (I)));\n Last := First + Char_code.L - 1;\n Result (First .. Last) := Char_code.Code (1 .. Char_code.L);\n Last := Last + 1;\n Result (Last) := Nul;\n end if;\n end if;\n end loop;\n if Result (Last) \/= ' ' then\n Last := Last + 1;\n Result (Last) := ' ';\n end if;\n return Result (1 .. Last);\n end Convert;\n\n procedure Morsebeep (Input : Morse_Str) is\n -- Beep is not portable\u00a0: adapt to your OS\/sound board\n -- Implementation for Windows XP \/ interface to fn in stdlib\n procedure win32xp_beep\n (dwFrequency : C.unsigned;\n dwDuration : C.unsigned);\n pragma Import (C, win32xp_beep, \"_beep\");\n begin\n for I in Input'Range loop\n case Input (I) is\n when Nul =>\n delay Lettergap;\n when Dot =>\n win32xp_beep (Freq, Dit_ms);\n delay Dit;\n when Dash =>\n win32xp_beep (Freq, Dah_ms);\n delay Dit;\n when ' ' =>\n delay Wordgap;\n end case;\n end loop;\n end Morsebeep;\nbegin\n Dit := 0.20;\n Lettergap := 2 * Dit;\n Dah := 3 * Dit;\n Wordgap := 4 * Dit;\n Dit_ms := C.unsigned (Integer (Dit * 1000));\n Dah_ms := C.unsigned (Integer (Dah * 1000));\nend Morse;\n\n\nwith Morse; use Morse;\nprocedure Morse_Tx is\nbegin\n Morsebeep (Convert (\"Science sans Conscience\"));\nend Morse_Tx;\n\n","human_summarization":"\"Code outputs audible Morse code from a given string to an audio device, such as a PC speaker. It ignores unknown characters or indicates them with a different pitch. It is compatible with Ada95 and works on Windows 32 XP, but not on Vista due to the ineffectiveness of the Beep function.\"","id":146} {"lang_cluster":"Ada","source_code":"\nBuild with gnatchop abc.ada; gnatmake abc_problem\n\nwith Ada.Characters.Handling;\nuse Ada.Characters.Handling;\n\n\npackage Abc is\n type Block_Faces is array(1..2) of Character;\n type Block_List is array(positive range <>) of Block_Faces;\n function Can_Make_Word(W: String; Blocks: Block_List) return Boolean;\nend Abc;\n\n\npackage body Abc is\n\nfunction Can_Make_Word(W: String; Blocks: Block_List) return Boolean is\n Used : array(Blocks'Range) of Boolean := (Others => False);\n subtype wIndex is Integer range W'First..W'Last;\n wPos : wIndex;\nbegin\n if W'Length = 0 then\n return True;\n end if;\n wPos := W'First;\n while True loop\n declare\n C : Character := To_Upper(W(wPos));\n X : constant wIndex := wPos;\n begin\n for I in Blocks'Range loop\n if (not Used(I)) then\n if C = To_Upper(Blocks(I)(1)) or C = To_Upper(Blocks(I)(2)) then\n Used(I) := True;\n if wPos = W'Last then\n return True;\n end if;\n wPos := wIndex'Succ(wPos);\n exit;\n end if;\n end if;\n end loop;\n if X = wPos then\n return False;\n end if;\n end;\n end loop;\n return False;\nend Can_Make_Word;\n\nend Abc;\n\nwith Ada.Text_IO, Ada.Strings.Unbounded, Abc;\nuse Ada.Text_IO, Ada.Strings.Unbounded, Abc;\n\nprocedure Abc_Problem is\n Blocks : Block_List := (\n ('B','O'), ('X','K'), ('D','Q'), ('C','P')\n , ('N','A'), ('G','T'), ('R','E'), ('T','G')\n , ('Q','D'), ('F','S'), ('J','W'), ('H','U')\n , ('V','I'), ('A','N'), ('O','B'), ('E','R')\n , ('F','S'), ('L','Y'), ('P','C'), ('Z','M')\n );\n function \"+\" (S : String) return Unbounded_String renames To_Unbounded_String;\n words : array(positive range <>) of Unbounded_String := (\n +\"A\"\n , +\"BARK\"\n , +\"BOOK\"\n , +\"TREAT\"\n , +\"COMMON\"\n , +\"SQUAD\"\n , +\"CONFUSE\"\n -- Border cases:\n -- , +\"CONFUSE2\"\n -- , +\"\"\n );\nbegin\n for I in words'Range loop\n Put_Line ( To_String(words(I)) & \": \" & Boolean'Image(Can_Make_Word(To_String(words(I)),Blocks)) );\n end loop;\nend Abc_Problem;\n\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":147} {"lang_cluster":"Ada","source_code":"\nWorks with: GNAT\nwith Ada.Text_IO; use Ada.Text_IO;\nwith GNAT.MD5;\n\nprocedure MD5_Digest is\nbegin\n Put(GNAT.MD5.Digest(\"Foo bar baz\"));\nend MD5_Digest;\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":148} {"lang_cluster":"Ada","source_code":"\nWorks with: Ada version 2012\nwith Ada.Containers.Generic_Array_Sort;\nwith Ada.Strings.Fixed;\nwith Ada.Strings.Unbounded; use Ada.Strings.Unbounded;\nwith Ada.Text_IO;\nwith Ada.Unchecked_Deallocation;\n\nprocedure Sort_List_Identifiers is\n type Natural_Array is array (Positive range <>) of Natural;\n type Unbounded_String_Array is array(Positive range <>) of Unbounded_String;\n\n function To_Natural_Array(input : in String) return Natural_Array\n is\n target : Natural_Array(1 .. Ada.Strings.Fixed.Count(input, \".\") + 1);\n from : Natural := input'First;\n to : Natural := Ada.Strings.Fixed.Index(input, \".\");\n index : Positive := target'First;\n begin\n while to \/= 0 loop\n target(index) := Natural'Value(input(from .. to - 1));\n from := to + 1;\n index := index + 1;\n to := Ada.Strings.Fixed.Index(input, \".\", from);\n end loop;\n target(index) := Natural'Value(input(from .. input'Last));\n return target;\n end To_Natural_Array;\n\n function Lesser(Left, Right : in Unbounded_String) return Boolean is\n begin\n return To_Natural_Array(To_String(Left)) < To_Natural_Array(To_String(Right));\n end Lesser;\n\n procedure Sort is new Ada.Containers.Generic_Array_Sort\n (Index_Type => Positive,\n Element_Type => Unbounded_String,\n Array_Type => Unbounded_String_Array,\n \"<\" => Lesser);\n\n table : Unbounded_String_Array :=\n (To_Unbounded_String(\"1.3.6.1.4.1.11.2.17.19.3.4.0.10\"),\n To_Unbounded_String(\"1.3.6.1.4.1.11.2.17.5.2.0.79\"),\n To_Unbounded_String(\"1.3.6.1.4.1.11.2.17.19.3.4.0.4\"),\n To_Unbounded_String(\"1.3.6.1.4.1.11150.3.4.0.1\"),\n To_Unbounded_String(\"1.3.6.1.4.1.11.2.17.19.3.4.0.1\"),\n To_Unbounded_String(\"1.3.6.1.4.1.11150.3.4.0\"));\nbegin\n Sort(table);\n for element of table loop\n Ada.Text_IO.Put_Line(To_String(element));\n end loop;\nend Sort_List_Identifiers;\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":149} {"lang_cluster":"Ada","source_code":"\nLibrary: GNAT RTL\nwith GNAT.Sockets; use GNAT.Sockets;\n\nprocedure Socket_Send is\n Client : Socket_Type;\nbegin\n Initialize;\n Create_Socket (Socket => Client);\n Connect_Socket (Socket => Client,\n Server => (Family => Family_Inet,\n Addr => Inet_Addr (\"127.0.0.1\"),\n Port => 256));\n String'Write (Stream (Client), \"hello socket world\");\n Close_Socket (Client);\nend Socket_Send;\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":150} {"lang_cluster":"Ada","source_code":"\nLibrary: AWS\nwith AWS.SMTP, AWS.SMTP.Client, AWS.SMTP.Authentication.Plain;\nwith Ada.Text_IO;\nuse Ada, AWS;\n\nprocedure Sendmail is\n Status : SMTP.Status;\n Auth : aliased constant SMTP.Authentication.Plain.Credential :=\n SMTP.Authentication.Plain.Initialize (\"id\", \"password\");\n Isp : SMTP.Receiver;\nbegin\n Isp :=\n SMTP.Client.Initialize\n (\"smtp.mail.com\",\n Port => 5025,\n Credential => Auth'Unchecked_Access);\n SMTP.Client.Send\n (Isp,\n From => SMTP.E_Mail (\"Me\", \"me@some.org\"),\n To => SMTP.E_Mail (\"You\", \"you@any.org\"),\n Subject => \"subject\",\n Message => \"Here is the text\",\n Status => Status);\n if not SMTP.Is_Ok (Status) then\n Text_IO.Put_Line\n (\"Can't send message\u00a0:\" & SMTP.Status_Message (Status));\n end if;\nend Sendmail;\n\n","human_summarization":"Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.","id":151} {"lang_cluster":"Ada","source_code":"\nwith Ada.Text_IO;\n\nprocedure Octal is\n package IIO is new Ada.Text_IO.Integer_IO(Integer);\nbegin\n for I in 0 .. Integer'Last loop\n IIO.Put(I, Base => 8);\n Ada.Text_IO.New_Line;\n end loop;\nend Octal;\n\n\n 8#0#\n 8#1#\n 8#2#\n 8#3#\n 8#4#\n 8#5#\n 8#6#\n 8#7#\n 8#10#\n 8#11#\n 8#12#\n 8#13#\n 8#14#\n 8#15#\n 8#16#\n 8#17#\n 8#20#\n","human_summarization":"\"Generate a sequential count in octal format starting from zero, incrementing by one, each number appearing on a single line, until the program is terminated or the maximum numeric value is reached.\"","id":152} {"lang_cluster":"Ada","source_code":"\n\ngeneric\n type Swap_Type is private; -- Generic parameter\nprocedure Generic_Swap (Left, Right : in out Swap_Type);\n\nprocedure Generic_Swap (Left, Right : in out Swap_Type) is\n Temp : constant Swap_Type := Left;\nbegin\n Left := Right;\n Right := Temp;\nend Generic_Swap;\n\n\nwith Generic_Swap;\n...\ntype T is ...\nprocedure T_Swap is new Generic_Swap (Swap_Type => T);\nA, B : T;\n...\nT_Swap (A, B);\n\n","human_summarization":"implement a generic swap function that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with some constraints for compatibility in typed languages. The function also addresses challenges in generic programming, parametric polymorphism, and destructive operations in functional languages. In Ada, the generic parameters are defined in a procedure specification and the algorithm in a procedure body. The procedure needs to be instantiated for each intended use type.","id":153} {"lang_cluster":"Ada","source_code":"\nfunction Palindrome (Text : String) return Boolean is\nbegin\n for Offset in 0..Text'Length \/ 2 - 1 loop\n if Text (Text'First + Offset) \/= Text (Text'Last - Offset) then\n return False;\n end if;\n end loop;\n return True;\nend Palindrome;\n\n\n\nfunction Palindrome (Text : String) return Boolean is\n(for all i in Text'Range => Text(i)= Text(Text'Last-i+Text'First));\n\n","human_summarization":"The code checks if a given sequence of characters is a palindrome. It supports Unicode characters and also detects inexact palindromes by ignoring white-space, punctuation, and case. It uses a function to reverse a string for the task.","id":154} {"lang_cluster":"Ada","source_code":"\n\nwith Ada.Environment_Variables; use Ada.Environment_Variables;\nwith Ada.Text_Io; use Ada.Text_Io;\n\nprocedure Print_Path is\nbegin\n Put_Line(\"Path\u00a0: \" & Value(\"PATH\"));\nend Print_Path;\n\n\nwith Ada.Environment_Variables; use Ada.Environment_Variables;\nwith Ada.Text_Io; use Ada.Text_Io;\n\nprocedure Env_Vars is\n procedure Print_Vars(Name, Value : in String) is\n begin\n Put_Line(Name & \"\u00a0: \" & Value);\n end Print_Vars;\nbegin\n Iterate(Print_Vars'access);\nend Env_Vars;\n\n\n\nwith Ada.Wide_Wide_Text_IO;\n\nwith League.Application;\nwith League.Strings;\n\nprocedure Main is\n\n function \"+\"\n (Item : Wide_Wide_String) return League.Strings.Universal_String\n renames League.Strings.To_Universal_String;\n\nbegin\n Ada.Wide_Wide_Text_IO.Put_Line\n (League.Application.Environment.Value (+\"HOME\").To_Wide_Wide_String);\nend Main;\n\n","human_summarization":"demonstrate how to retrieve a specific environment variable and print all environment variables using Matreshka in a Unix system.","id":155} {"lang_cluster":"Ada","source_code":"with Ada.Text_IO; use Ada.Text_IO;\n\nprocedure Sudan_Function is\n\n function F (N, X, Y : Natural) return Natural\n is (if N = 0 then X + Y\n elsif Y = 0 then X\n else F (N => N - 1,\n X => F (N, X, Y - 1),\n Y => F (N, X, Y - 1) + Y));\n\nbegin\n Put_Line (\"F0 (0, 0) = \" & F (0, 0, 0)'Image);\n Put_Line (\"F1 (1, 1) = \" & F (1, 1, 1)'Image);\n Put_Line (\"F1 (3, 3) = \" & F (1, 3, 3)'Image);\n Put_Line (\"F2 (1, 1) = \" & F (2, 1, 1)'Image);\n Put_Line (\"F2 (2, 1) = \" & F (2, 2, 1)'Image);\n Put_Line (\"F3 (1, 1) = \" & F (3, 1, 1)'Image);\nend Sudan_Function;\n\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.","id":156} {"lang_cluster":"Objective-C","source_code":"\n\nNSMutableArray *stack = [NSMutableArray array]; \/\/ creating\n\n[stack addObject:value]; \/\/ pushing\n\nid value = [stack lastObject];\n[stack removeLastObject]; \/\/ popping\n\n[stack count] == 0 \/\/ is empty?\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and allows access to the topmost element without modifying the stack. It is used for resource management, particularly memory, in programming and is common in processors. The stack can also be used for implementing local variables of a recursive subprogram and is used in various algorithms in pattern matching, compiler construction, and machine learning. The stack is implemented using a NSMutableArray.","id":157} {"lang_cluster":"Objective-C","source_code":"\n-(long)fibonacci:(int)position\n{\n long result = 0;\n if (position < 2) {\n result = position;\n } else {\n result = [self fibonacci:(position -1)] + [self fibonacci:(position -2)];\n }\n return result; \n}\n+(long)fibonacci:(int)index {\n long beforeLast = 0, last = 1;\n while (index > 0) {\n last += beforeLast;\n beforeLast = last - beforeLast;\n --index;\n }\n return last;\n}\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":158} {"lang_cluster":"Objective-C","source_code":"\nWorks with: Cocoa version Mac OS X 10.6+\nNSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],\n [NSNumber numberWithInt:2],\n [NSNumber numberWithInt:3],\n [NSNumber numberWithInt:4],\n [NSNumber numberWithInt:5], nil];\nNSArray *evens = [numbers objectsAtIndexes:[numbers indexesOfObjectsPassingTest:\n ^BOOL(id obj, NSUInteger idx, BOOL *stop) { return [obj intValue] % 2 == 0; } ]];\n\nWorks with: Cocoa version Mac OS X 10.5+\nNSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],\n [NSNumber numberWithInt:2],\n [NSNumber numberWithInt:3],\n [NSNumber numberWithInt:4],\n [NSNumber numberWithInt:5], nil];\nNSPredicate *isEven = [NSPredicate predicateWithFormat:@\"modulus:by:(SELF, 2) == 0\"];\nNSArray *evens = [numbers filteredArrayUsingPredicate:isEven];\nWorks with: GNUstep\n#import \n\n@interface NSNumber ( ExtFunc )\n-(int) modulo2;\n@end\n\n@implementation NSNumber ( ExtFunc )\n-(int) modulo2\n{\n return [self intValue]\u00a0% 2;\n}\n@end\n\nint main()\n{\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n\n NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],\n [NSNumber numberWithInt:2],\n [NSNumber numberWithInt:3],\n [NSNumber numberWithInt:4],\n [NSNumber numberWithInt:5], nil];\n\n NSPredicate *isEven = [NSPredicate predicateWithFormat:@\"modulo2 == 0\"];\n NSArray *evens = [numbers filteredArrayUsingPredicate:isEven];\n\n NSLog(@\"%@\", evens);\n\n\n [pool release];\n return 0;\n}\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":159} {"lang_cluster":"Objective-C","source_code":"\n\n#import \n\n@interface NSString (Extended)\n-(NSString *)reverseString;\n@end\n\n@implementation NSString (Extended)\n-(NSString *) reverseString\n{\n NSUInteger len = [self length];\n NSMutableString *rtr=[NSMutableString stringWithCapacity:len];\n \/\/ unichar buf[1];\n \n while (len > (NSUInteger)0) { \n unichar uch = [self characterAtIndex:--len]; \n [rtr appendString:[NSString stringWithCharacters:&uch length:1]];\n }\n return rtr;\n}\n@end\n\nint main()\n{\n @autoreleasepool {\n \n NSString *test = [@\"!A string to be reverted!\" reverseString];\n \n NSLog(@\"%@\", test);\n \n }\n return 0;\n}\n\n#import \n\n@interface NSString (Extended)\n-(NSString *)reverseString;\n@end\n\n@implementation NSString (Extended)\n-(NSString *)reverseString\n{\n\tNSInteger l = [self length] - 1;\n\tNSMutableString *ostr = [NSMutableString stringWithCapacity:[self length]];\n\twhile (l >= 0)\n\t{\n\t\tNSRange range = [self rangeOfComposedCharacterSequenceAtIndex:l];\n\t\t[ostr appendString:[self substringWithRange:range]];\n\t\tl -= range.length;\n\t}\n\treturn ostr;\n}\n@end\n\nint main()\n{\n @autoreleasepool {\n \n NSString *test = [@\"as\u20dddf\u0305\" reverseString];\n \n NSLog(@\"%@\", test);\n \n }\n return 0;\n}\n","human_summarization":"\"Implements a function to reverse a given string, while preserving Unicode combining characters. For instance, it transforms \"asdf\" into \"fdsa\" and \"as\u20dddf\u0305\" into \"f\u0305ds\u20dda\". This function extends the NSString object with a reverseString class method.\"","id":160} {"lang_cluster":"Objective-C","source_code":"\n\nThis example is incomplete. It is missing an @interface for AVLTree and also missing any @interface or @implementation for AVLTreeNode. Please ensure that it meets all task requirements and remove this message.\n\n@implementation AVLTree\n\n-(BOOL)insertWithKey:(NSInteger)key {\n \n if (self.root == nil) {\n self.root = [[AVLTreeNode alloc]initWithKey:key andParent:nil];\n } else {\n \n AVLTreeNode *n = self.root;\n AVLTreeNode *parent;\n \n while (true) {\n \n if (n.key == key) {\n return false;\n }\n \n parent = n;\n \n BOOL goLeft = n.key > key;\n n = goLeft ? n.left : n.right;\n \n if (n == nil) {\n \n if (goLeft) {\n parent.left = [[AVLTreeNode alloc]initWithKey:key andParent:parent];\n } else {\n parent.right = [[AVLTreeNode alloc]initWithKey:key andParent:parent];\n }\n [self rebalanceStartingAtNode:parent];\n break;\n }\n }\n }\n \n return true;\n}\n\n-(void)rebalanceStartingAtNode:(AVLTreeNode*)n {\n \n [self setBalance:@[n]];\n \n if (n.balance == -2) {\n if ([self height:(n.left.left)] >= [self height:n.left.right]) {\n n = [self rotateRight:n];\n } else {\n n = [self rotateLeftThenRight:n];\n }\n } else if (n.balance == 2) {\n if ([self height:n.right.right] >= [self height:n.right.left]) {\n n = [self rotateLeft:n];\n } else {\n n = [self rotateRightThenLeft:n];\n }\n }\n \n if (n.parent != nil) {\n [self rebalanceStartingAtNode:n.parent];\n } else {\n self.root = n;\n }\n}\n\n\n-(AVLTreeNode*)rotateRight:(AVLTreeNode*)a {\n \n AVLTreeNode *b = a.left;\n b.parent = a.parent;\n \n a.left = b.right;\n \n if (a.left != nil) {\n a.left.parent = a;\n }\n \n b.right = a;\n a.parent = b;\n \n if (b.parent != nil) {\n if (b.parent.right == a) {\n b.parent.right = b;\n } else {\n b.parent.left = b;\n }\n }\n \n [self setBalance:@[a,b]];\n return b;\n \n}\n\n-(AVLTreeNode*)rotateLeftThenRight:(AVLTreeNode*)n {\n \n n.left = [self rotateLeft:n.left];\n return [self rotateRight:n];\n \n}\n\n-(AVLTreeNode*)rotateRightThenLeft:(AVLTreeNode*)n {\n \n n.right = [self rotateRight:n.right];\n return [self rotateLeft:n];\n}\n\n-(AVLTreeNode*)rotateLeft:(AVLTreeNode*)a {\n \n \/\/set a's right node as b\n AVLTreeNode* b = a.right;\n \/\/set b's parent as a's parent (which could be nil)\n b.parent = a.parent;\n \/\/in case b had a left child transfer it to a\n a.right = b.left;\n \n \/\/ after changing a's reference to the right child, make sure the parent is set too\n if (a.right != nil) {\n a.right.parent = a;\n }\n \n \/\/ switch a over to the left to be b's left child\n b.left = a;\n a.parent = b;\n \n if (b.parent != nil) {\n if (b.parent.right == a) {\n b.parent.right = b;\n } else {\n b.parent.right = b;\n }\n }\n \n [self setBalance:@[a,b]];\n \n return b;\n \n}\n\n\n\n-(void) setBalance:(NSArray*)nodesArray {\n \n for (AVLTreeNode* n in nodesArray) {\n \n n.balance = [self height:n.right] - [self height:n.left];\n }\n \n}\n\n-(int)height:(AVLTreeNode*)n {\n \n if (n == nil) {\n return -1;\n }\n \n return 1 + MAX([self height:n.left], [self height:n.right]);\n}\n\n-(void)printKey:(AVLTreeNode*)n {\n if (n != nil) {\n [self printKey:n.left];\n NSLog(@\"%ld\", n.key);\n [self printKey:n.right];\n }\n}\n\n-(void)printBalance:(AVLTreeNode*)n {\n if (n != nil) {\n [self printBalance:n.left];\n NSLog(@\"%ld\", n.balance);\n [self printBalance:n.right];\n }\n}\n@end\n-- test \n\nint main(int argc, const char * argv[]) {\n @autoreleasepool {\n\n AVLTree *tree = [AVLTree new];\n NSLog(@\"inserting values 1 to 6\");\n [tree insertWithKey:1];\n [tree insertWithKey:2];\n [tree insertWithKey:3];\n [tree insertWithKey:4];\n [tree insertWithKey:5];\n [tree insertWithKey:6];\n \n NSLog(@\"printing balance: \");\n [tree printBalance:tree.root];\n \n NSLog(@\"printing key: \");\n [tree printKey:tree.root];\n }\n return 0;\n}\n\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.","id":161} {"lang_cluster":"Objective-C","source_code":"\n#import \n\nint main (int argc, const char *argv[]) {\n @autoreleasepool {\n \n NSSet *s1 = [NSSet setWithObjects:@\"a\", @\"b\", @\"c\", @\"d\", @\"e\", nil];\n NSSet *s2 = [NSSet setWithObjects:@\"b\", @\"c\", @\"d\", @\"e\", @\"f\", @\"h\", nil];\n NSSet *s3 = [NSSet setWithObjects:@\"b\", @\"c\", @\"d\", nil];\n NSSet *s4 = [NSSet setWithObjects:@\"b\", @\"c\", @\"d\", nil];\n NSLog(@\"s1:\u00a0%@\", s1);\n NSLog(@\"s2:\u00a0%@\", s2);\n NSLog(@\"s3:\u00a0%@\", s3);\n NSLog(@\"s4:\u00a0%@\", s4);\n \n \/\/ Membership\n NSLog(@\"b in s1: %d\", [s1 containsObject:@\"b\"]);\n NSLog(@\"f in s1: %d\", [s1 containsObject:@\"f\"]);\n \n \/\/ Union\n NSMutableSet *s12 = [NSMutableSet setWithSet:s1];\n [s12 unionSet:s2];\n NSLog(@\"s1 union s2:\u00a0%@\", s12);\n \n \/\/ Intersection\n NSMutableSet *s1i2 = [NSMutableSet setWithSet:s1];\n [s1i2 intersectSet:s2];\n NSLog(@\"s1 intersect s2:\u00a0%@\", s1i2);\n \n \/\/ Difference\n NSMutableSet *s1_2 = [NSMutableSet setWithSet:s1];\n [s1_2 minusSet:s2];\n NSLog(@\"s1 - s2:\u00a0%@\", s1_2);\n \n \/\/ Subset of\n NSLog(@\"s3 subset of s1: %d\", [s3 isSubsetOfSet:s1]);\n \n \/\/ Equality\n NSLog(@\"s3 = s4: %d\", [s3 isEqualToSet:s4]);\n \n \/\/ Cardinality\n NSLog(@\"size of s1: %lu\", [s1 count]);\n \n \/\/ Has intersection (not disjoint)\n NSLog(@\"does s1 intersect s2? %d\", [s1 intersectsSet:s2]);\n \n \/\/ Adding and removing elements from a mutable set\n NSMutableSet *mut_s1 = [NSMutableSet setWithSet:s1];\n [mut_s1 addObject:@\"g\"];\n NSLog(@\"mut_s1 after adding g:\u00a0%@\", mut_s1);\n [mut_s1 addObject:@\"b\"];\n NSLog(@\"mut_s1 after adding b again:\u00a0%@\", mut_s1);\n [mut_s1 removeObject:@\"c\"];\n NSLog(@\"mut_s1 after removing c:\u00a0%@\", mut_s1);\n \n }\n return 0;\n}\n\n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":162} {"lang_cluster":"Objective-C","source_code":"\nWorks with: GNUstep\nWorks with: Cocoa\n#import \n\nint main()\n{\n @autoreleasepool {\n for(NSUInteger i=2008; i<2121; i++)\n {\n NSCalendarDate *d = [[NSCalendarDate alloc] \n initWithYear: i\n month: 12\n day: 25\n hour: 0 minute: 0 second:0 \n timeZone: [NSTimeZone timeZoneWithAbbreviation:@\"CET\"] ];\n if ( [d dayOfWeek] == 0 )\n { \n printf(\"25 Dec %u is Sunday\\n\", i);\n }\n }\n \n }\n return 0;\n}\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":163} {"lang_cluster":"Objective-C","source_code":"\nNSArray *items = [NSArray arrayWithObjects:@\"A\", @\"B\", @\"C\", @\"B\", @\"A\", nil];\n\nNSSet *unique = [NSSet setWithArray:items];\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":164} {"lang_cluster":"Objective-C","source_code":"\n\nvoid quicksortInPlace(NSMutableArray *array, NSInteger first, NSInteger last, NSComparator comparator) {\n if (first >= last) return;\n id pivot = array[(first + last) \/ 2];\n NSInteger left = first;\n NSInteger right = last;\n while (left <= right) {\n while (comparator(array[left], pivot) == NSOrderedAscending)\n left++;\n while (comparator(array[right], pivot) == NSOrderedDescending)\n right--;\n if (left <= right)\n [array exchangeObjectAtIndex:left++ withObjectAtIndex:right--];\n }\n quicksortInPlace(array, first, right, comparator);\n quicksortInPlace(array, left, last, comparator);\n}\n\nNSArray* quicksort(NSArray *unsorted, NSComparator comparator) {\n NSMutableArray *a = [NSMutableArray arrayWithArray:unsorted];\n quicksortInPlace(a, 0, a.count - 1, comparator);\n return a;\n}\n\nint main(int argc, const char * argv[]) {\n @autoreleasepool {\n NSArray *a = @[ @1, @3, @5, @7, @9, @8, @6, @4, @2 ];\n NSLog(@\"Unsorted:\u00a0%@\", a);\n NSLog(@\"Sorted:\u00a0%@\", quicksort(a, ^(id x, id y) { return [x compare:y]; }));\n NSArray *b = @[ @\"Emil\", @\"Peg\", @\"Helen\", @\"Juergen\", @\"David\", @\"Rick\", @\"Barb\", @\"Mike\", @\"Tom\" ];\n NSLog(@\"Unsorted:\u00a0%@\", b);\n NSLog(@\"Sorted:\u00a0%@\", quicksort(b, ^(id x, id y) { return [x compare:y]; }));\n }\n return 0;\n}\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by selecting a pivot element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then recursively sorted. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot element selection method is not specified and can vary. The codes assume the latest XCode compiler with ARC enabled.","id":165} {"lang_cluster":"Objective-C","source_code":"\nNSLog(@\"%@\", [NSDate date]);\nNSLog(@\"%@\", [[NSDate date] descriptionWithCalendarFormat:@\"%Y-%m-%d\" timeZone:nil locale:nil]);\nNSLog(@\"%@\", [[NSDate date] descriptionWithCalendarFormat:@\"%A, %B %d, %Y\" timeZone:nil locale:nil]);\n\nWorks with: Mac OS X version 10.4+\nWorks with: iOS\nNSLog(@\"%@\", [NSDate date]);\nNSDateFormatter *dateFormatter = [[NSDateFormat alloc] init];\n[dateFormatter setDateFormat:@\"yyyy-MM-dd\"];\nNSLog(@\"%@\", [dateFormatter stringFromDate:[NSDate date]]);\n[dateFormatter setDateFormat:@\"EEEE, MMMM d, yyyy\"];\nNSLog(@\"%@\", [dateFormatter stringFromDate:[NSDate date]]);\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":166} {"lang_cluster":"Objective-C","source_code":"\n#import \n\n+ (NSArray *)powerSetForArray:(NSArray *)array {\n\tUInt32 subsetCount = 1 << array.count;\n\tNSMutableArray *subsets = [NSMutableArray arrayWithCapacity:subsetCount];\n\tfor(int subsetIndex = 0; subsetIndex < subsetCount; subsetIndex++) {\n\t\tNSMutableArray *subset = [[NSMutableArray alloc] init];\n\t\tfor (int itemIndex = 0; itemIndex < array.count; itemIndex++) {\n\t\t\tif((subsetIndex >> itemIndex) & 0x1) {\n\t\t\t\t[subset addObject:array[itemIndex]];\n\t\t\t}\n\t\t}\t\t\n\t\t[subsets addObject:subset];\n\t}\n\treturn subsets;\n}\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":167} {"lang_cluster":"Objective-C","source_code":"\n\/\/ NSArrays are ordered collections of NSObject subclasses only.\n\n\/\/ Create an array of NSString objects.\nNSArray *firstArray = [[NSArray alloc] initWithObjects:@\"Hewey\", @\"Louie\", @\"Dewey\", nil];\n\n\/\/ NSArrays are immutable; it does have a mutable subclass, however - NSMutableArray.\n\/\/ Let's instantiate one with a mutable copy of our array.\n\/\/ We can do this by sending our first array a -mutableCopy message.\nNSMutableArray *secondArray = [firstArray mutableCopy];\n\n\/\/ Replace Louie with Launchpad McQuack.\n[secondArray replaceObjectAtIndex:1 withObject:@\"Launchpad\"];\n\n\/\/ Display the first object in the array.\nNSLog(@\"%@\", [secondArray objectAtIndex:0]);\n\n\/\/ In non-ARC or non-GC environments, retained objects must be released later.\n[firstArray release];\n[secondArray release];\n\n\/\/ There is also a modern syntax which allows convenient creation of autoreleased immutable arrays.\n\/\/ No nil termination is then needed.\nNSArray *thirdArray = @[ @\"Hewey\", @\"Louie\", @\"Dewey\", @1, @2, @3 ];\n","human_summarization":"demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and includes the functionality of pushing a value into the array.","id":168} {"lang_cluster":"Objective-C","source_code":"\n\n[[NSFileManager defaultManager] copyItemAtPath:@\"input.txt\" toPath:@\"output.txt\" error:NULL];\n\nNSData *data = [NSData dataWithContentsOfFile:@\"input.txt\"];\n\n[data writeToFile:@\"output.txt\" atomically:YES];\n\n","human_summarization":"demonstrate how to create a file named \"output.txt\" and populate it with the contents of \"input.txt\" using an intermediate variable. The process involves reading from a file into a variable and then writing the variable's contents into another file. It also includes a method for copying files using NSFileManager. The code is designed to write the content to a temporary file first, then rename the temporary file to the destination file, replacing the existing file. Error checking and failure handling are also considered in the code.","id":169} {"lang_cluster":"Objective-C","source_code":"\nWorks with: GNUstep\nWorks with: Cocoa\nNSLog(@\"%@\", @\"alphaBETA\".uppercaseString);\nNSLog(@\"%@\", @\"alphaBETA\".lowercaseString);\n\nNSLog(@\"%@\", @\"foO BAr\".capitalizedString); \/\/ \"Foo Bar\"\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":170} {"lang_cluster":"Objective-C","source_code":"\n#import \n#import \n\n@interface Point : NSObject {\n double xCoord, yCoord;\n}\n+ (instancetype)x: (double)x y: (double)y;\n- (instancetype)initWithX: (double)x andY: (double)y;\n- (double)x;\n- (double)y;\n- (double)dist: (Point *)pt;\n- (NSComparisonResult)compareX: (Point *)pt;\n- (NSComparisonResult)compareY: (Point *)pt;\n@end\n\n@implementation Point\n\n+ (instancetype)x: (double)x y: (double)y {\n return [[self alloc] initWithX: x andY: y];\n}\n\n- (instancetype)initWithX: (double)x andY: (double)y {\n if ((self = [super init])) {\n xCoord = x;\n yCoord = y;\n }\n return self;\n}\n\n- (double)x { return xCoord; }\n- (double)y { return yCoord; }\n\n- (double)dist: (Point *)pt {\n return hypot([self x] - [pt x], [self y] - [pt y]);\n}\n\n- (NSComparisonResult)compareX: (Point *)pt {\n if ( [self x] < [pt x] ) return NSOrderedAscending;\n else if ( [self x] > [pt x] ) return NSOrderedDescending;\n else return NSOrderedSame;\n}\n\n- (NSComparisonResult)compareY: (Point *)pt {\n if ( [self y] < [pt y] ) return NSOrderedAscending;\n else if ( [self y] > [pt y] ) return NSOrderedDescending;\n else return NSOrderedSame;\n}\n@end\n\n@interface ClosestPair : NSObject\n+ (NSArray *)closestPairSimple: (NSArray *)pts;\n+ (NSArray *)closestPair: (NSArray *)pts;\n+ (NSArray *)closestPairPriv: (NSArray *)xP and: (NSArray *)yP;\n+ (id)minBetween: (id)minA and: (id)minB;\n@end\n\n@implementation ClosestPair\n\n+ (NSArray *)closestPairSimple: (NSArray *)pts {\n if ( [pts count] < 2 ) return @[ @HUGE_VAL ];\n double c = [ pts[0] dist: pts[1] ];\n NSArray *r = @[ @(c), pts[0], pts[1] ];\n for(int i=0; i < ([pts count] - 1); i++) {\n for(int j=i+1; j < [pts count]; j++) {\n double t = [ pts[i] dist: pts[j] ];\n if ( t < c ) {\n c = t;\n r = @[ @(t), pts[i], pts[j] ];\n }\n }\n }\n return r;\n}\n\n+ (NSArray *)closestPair: (NSArray *)pts {\n return [self closestPairPriv: [pts sortedArrayUsingSelector: @selector(compareX:)]\n and: [pts sortedArrayUsingSelector: @selector(compareY:)]\n ];\n}\n\n+ (NSArray *)closestPairPriv: (NSArray *)xP and: (NSArray *)yP {\n int nP, k;\n\n if ( [xP count] <= 3 ) {\n return [self closestPairSimple: xP];\n } else {\n int midx = ceil([xP count]\/2.0);\n NSArray *pL = [xP subarrayWithRange: NSMakeRange(0, midx)];\n NSArray *pR = [xP subarrayWithRange: NSMakeRange(midx, [xP count] - midx)];\n NSMutableArray *yL = [[NSMutableArray alloc] init];\n NSMutableArray *yR = [[NSMutableArray alloc] init];\n double middleVLine = [pL[midx-1] x];\n for(int i=0; i < [yP count]; i++) {\n if ( [yP[i] x] <= middleVLine ) {\n [yL addObject: yP[i]];\n } else {\n [yR addObject: yP[i]];\n }\n }\n NSArray *minR = [ClosestPair closestPairPriv: pR and: yR];\n NSArray *minL = [ClosestPair closestPairPriv: pL and: yL];\n NSMutableArray *minDist = [ClosestPair minBetween: minR and: minL];\n NSMutableArray *joiningStrip = [NSMutableArray arrayWithCapacity: [xP count]];\n for(int i=0; i < [yP count]; i++) {\n if ( fabs([yP[i] x] - middleVLine) <\n [minDist[0] doubleValue] ) {\n [joiningStrip addObject: yP[i]];\n }\n }\n NSMutableArray *tDist = minDist;\n int nP = [joiningStrip count];\n for(int i=0; i < (nP - 1); i++) {\n int k = i + 1;\n while( (k < nP) &&\n ( ([joiningStrip[k] y] - [joiningStrip[i] y]) < [minDist[0] doubleValue] ) ) {\n double d = [joiningStrip[i] dist: joiningStrip[k]];\n if ( d < [tDist[0] doubleValue] ) {\n tDist = @[ @(d), joiningStrip[i], joiningStrip[k] ];\n }\n k++;\n }\n }\n return tDist;\n }\n}\n\n+ (id)minBetween: (id)minA and: (id)minB {\n if ( [minA[0] doubleValue] < [minB[0] doubleValue] ) {\n return minA;\n } else {\n return minB;\n }\n}\n\n@end\n","human_summarization":"The code provides two functions to solve the Closest Pair of Points problem in a planar case. The first function uses a brute-force algorithm with a time complexity of O(n^2) to find the closest pair of points in a given set. The second function uses a recursive divide and conquer approach with a time complexity of O(n log n) to find the closest pair of points in a set sorted by x and y coordinates.","id":171} {"lang_cluster":"Objective-C","source_code":"\n\na set: a collection of unique elements (like mathematical set). Possible operations on a set are not shown;\na counted set (also known as bag): each elements have a counter that says how many time that element appears;\na dictionary: pairs key-value.\n\n#import \n\nvoid show_collection(id coll)\n{\n for ( id el in coll )\n {\n if ( [coll isKindOfClass: [NSCountedSet class]] ) {\n NSLog(@\"%@ appears %lu times\", el, [coll countForObject: el]);\n } else if ( [coll isKindOfClass: [NSDictionary class]] ) {\n NSLog(@\"%@ ->\u00a0%@\", el, coll[el]);\n } else {\n NSLog(@\"%@\", el);\n }\n }\n printf(\"\\n\");\n}\n\nint main()\n{\n @autoreleasepool {\n \n \/\/ create an empty set\n NSMutableSet *set = [[NSMutableSet alloc] init];\n \/\/ populate it\n [set addObject: @\"one\"];\n [set addObject: @10];\n [set addObjectsFromArray: @[@\"one\", @20, @10, @\"two\"] ];\n \/\/ let's show it\n show_collection(set);\n\n \/\/ create an empty counted set (a bag)\n NSCountedSet *cset = [[NSCountedSet alloc] init];\n \/\/ populate it\n [cset addObject: @\"one\"];\n [cset addObject: @\"one\"];\n [cset addObject: @\"two\"];\n \/\/ show it\n show_collection(cset);\n\n \/\/ create a dictionary\n NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];\n \/\/ populate it\n dict[@\"four\"] = @4;\n dict[@\"eight\"] = @8;\n \/\/ show it\n show_collection(dict);\n\n }\n return EXIT_SUCCESS;\n}\n\n","human_summarization":"The code creates a collection in a statically-typed language, adds a few values of a common data type to it, and reviews the programming examples to ensure they meet the task requirements. It also explores different collection classes in OpenStep, GNUstep, and Cocoa, excluding arrays indexed by an integer.","id":172} {"lang_cluster":"Objective-C","source_code":"\n[@\"abcd\" hasPrefix:@\"ab\"] \/\/returns true\n[@\"abcd\" hasSuffix:@\"zn\"] \/\/returns false\nint loc = [@\"abab\" rangeOfString:@\"bb\"].location \/\/returns -1\nloc = [@\"abab\" rangeOfString:@\"ab\"].location \/\/returns 0\nloc = [@\"abab\" rangeOfString:@\"ab\" options:0 range:NSMakeRange(loc+1, [@\"abab\" length]-(loc+1))].location \/\/returns 2\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":173} {"lang_cluster":"Objective-C","source_code":"\nWorks with: GNUstep\nWorks with: Cocoa\n\n#include \n#include \n\n@interface Win\u00a0: NSWindow\n{\n}\n- (void)applicationDidFinishLaunching: (NSNotification *)notification;\n- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification;\n@end\n\n\n@implementation Win\u00a0: NSWindow\n-(instancetype) init\n{\n if ((self = [super \n initWithContentRect: NSMakeRect(0, 0, 800, 600)\n styleMask: (NSTitledWindowMask | NSClosableWindowMask)\n backing: NSBackingStoreBuffered\n defer: NO])) {\n\n [self setTitle: @\"A Window\"];\n [self center];\n }\n return self;\n}\n\n- (void)applicationDidFinishLaunching: (NSNotification *)notification\n{\n [self orderFront: self];\n}\n\n- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification\n{\n return YES;\n}\n@end\n\nint main()\n{\n @autoreleasepool {\n\n [NSApplication sharedApplication];\n Win *mywin = [[Win alloc] init];\n [NSApp setDelegate: mywin];\n [NSApp runModalForWindow: mywin];\n\n }\n return EXIT_SUCCESS;\n}\n\n","human_summarization":"create and display an empty 800x600 GUI window titled \"A Window\", centered on the screen, and respond to close requests.","id":174} {"lang_cluster":"Objective-C","source_code":"\n#import \n\nint main (int argc, const char *argv[]) {\n @autoreleasepool {\n\n NSData *data = [NSData dataWithContentsOfFile:@(argv[1])];\n NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];\n NSCountedSet *countedSet = [[NSCountedSet alloc] init];\n NSUInteger len = [string length];\n for (NSUInteger i = 0; i < len; i++) {\n unichar c = [string characterAtIndex:i];\n if ([[NSCharacterSet letterCharacterSet] characterIsMember:c])\n [countedSet addObject:@(c)];\n }\n for (NSNumber *chr in countedSet) {\n NSLog(@\"%C => %lu\", (unichar)[chr integerValue], [countedSet countForObject:chr]);\n }\n \n }\n return 0;\n}\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":175} {"lang_cluster":"Objective-C","source_code":"\n#import \n\n@interface RCListElement : NSObject\n{\n RCListElement *next;\n T datum;\n}\n- (RCListElement *)next;\n- (T)datum;\n- (RCListElement *)setNext: (RCListElement *)nx;\n- (void)setDatum: (T)d;\n@end\n\n@implementation RCListElement\n- (RCListElement *)next\n{\n return next;\n}\n- (id)datum\n{\n return datum;\n}\n- (RCListElement *)setNext: (RCListElement *)nx\n{\n RCListElement *p = next;\n next = nx;\n return p;\n}\n- (void)setDatum: (id)d\n{\n datum = d;\n}\n@end\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":176} {"lang_cluster":"Objective-C","source_code":"\n@interface Pair\u00a0: NSObject {\n NSString *name;\n NSString *value;\n}\n+(instancetype)pairWithName:(NSString *)n value:(NSString *)v;\n-(instancetype)initWithName:(NSString *)n value:(NSString *)v;\n-(NSString *)name;\n-(NSString *)value;\n@end\n\n@implementation Pair\n+(instancetype)pairWithName:(NSString *)n value:(NSString *)v {\n return [[self alloc] initWithName:n value:v];\n}\n-(instancetype)initWithName:(NSString *)n value:(NSString *)v {\n if ((self = [super init])) {\n name = n;\n value = v;\n }\n return self;\n}\n-(NSString *)name { return name; }\n-(NSString *)value { return value; }\n-(NSString *)description {\n return [NSString stringWithFormat:@\"<\u00a0%@ ->\u00a0%@ >\", name, value];\n}\n@end\n\nint main() {\n @autoreleasepool {\n\n NSArray *pairs = @[\n [Pair pairWithName:@\"06-07\" value:@\"Ducks\"],\n [Pair pairWithName:@\"00-01\" value:@\"Avalanche\"],\n [Pair pairWithName:@\"02-03\" value:@\"Devils\"],\n [Pair pairWithName:@\"01-02\" value:@\"Red Wings\"],\n [Pair pairWithName:@\"03-04\" value:@\"Lightning\"],\n [Pair pairWithName:@\"04-05\" value:@\"lockout\"],\n [Pair pairWithName:@\"05-06\" value:@\"Hurricanes\"],\n [Pair pairWithName:@\"99-00\" value:@\"Devils\"],\n [Pair pairWithName:@\"07-08\" value:@\"Red Wings\"],\n [Pair pairWithName:@\"08-09\" value:@\"Penguins\"]];\n\n \/\/ optional 3rd arg: you can also specify a selector to compare the keys\n NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@\"name\" ascending:YES];\n\n \/\/ it takes an array of sort descriptors, and it will be ordered by the\n \/\/ first one, then if it's a tie by the second one, etc.\n NSArray *sorted = [pairs sortedArrayUsingDescriptors:@[sd]];\n NSLog(@\"%@\", sorted);\n\n }\n\n return 0;\n}\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":177} {"lang_cluster":"Objective-C","source_code":"\nWorks with: Cocoa and Works with: GNUstep\n\nNSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:\n @\"Joe Doe\", @\"name\",\n [NSNumber numberWithUnsignedInt:42], @\"age\",\n [NSNull null], @\"extra\",\n nil];\n\nNSDictionary *dict = @{\n @\"name\": @\"Joe Doe\",\n @\"age\": @42,\n @\"extra\": [NSNull null],\n };\n\nNSMutableDictionary *dict = [NSMutableDictionary dictionary];\n[dict setObject:@\"Joe Doe\" forKey:@\"name\"];\n[dict setObject:[NSNumber numberWithInt:42] forKey:@\"age\"];\n\nNSString *name = [dict objectForKey:@\"name\"];\nunsigned age = [dict objectForKey:@\"age\"] unsignedIntValue];\nid missing = [dict objectForKey:@\"missing\"];\n","human_summarization":"create an associative array, or dictionary, using either NSDictionary for an immutable hash or NSMutableDictionary for a mutable dictionary. It only stores objects, so non-objects like integers must be boxed in NSNumber. The value can be accessed with objectForKey:, returning nil if the key does not exist. This is applicable in clang 3.1+ \/ Apple LLVM Compiler 4.0+ (XCode 4.4+).","id":178} {"lang_cluster":"Objective-C","source_code":"\n\n#import \n\nBOOL iseven(int x)\n{\n return (x&1) == 0;\n}\n\n@interface EthiopicMult\u00a0: NSObject\n+ (int)mult: (int)plier by: (int)plicand;\n+ (int)halve: (int)a;\n+ (int)double: (int)a;\n@end\n\n@implementation EthiopicMult\n+ (int)mult: (int)plier by: (int)plicand\n{\n int r = 0;\n while(plier >= 1) {\n if ( !iseven(plier) ) r += plicand;\n plier = [EthiopicMult halve: plier];\n plicand = [EthiopicMult double: plicand];\n }\n return r;\n}\n\n+ (int)halve: (int)a\n{\n return (a>>1);\n}\n\n+ (int)double: (int)a\n{\n return (a<<1);\n}\n@end\n\nint main()\n{\n @autoreleasepool {\n printf(\"%d\\n\", [EthiopicMult mult: 17 by: 34]);\n }\n return 0;\n}\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are then used to implement the Ethiopian multiplication method, which multiplies two numbers using only addition, doubling, and halving operations. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":179} {"lang_cluster":"Objective-C","source_code":"\n#import \n#import \n#import \n#import \n#import \n\n\/\/ this class exists to return a result between two\n\/\/ vectors: if vectors have different \"size\", valid\n\/\/ must be NO\n@interface VResult\u00a0: NSObject\n{\n @private\n double value;\n BOOL valid;\n}\n+(instancetype)new: (double)v isValid: (BOOL)y;\n-(instancetype)init: (double)v isValid: (BOOL)y;\n-(BOOL)isValid;\n-(double)value;\n@end\n\n@implementation VResult\n+(instancetype)new: (double)v isValid: (BOOL)y\n{\n return [[self alloc] init: v isValid: y];\n}\n-(instancetype)init: (double)v isValid: (BOOL)y\n{\n if ((self == [super init])) {\n value = v;\n valid = y;\n }\n return self;\n}\n-(BOOL)isValid { return valid; }\n-(double)value { return value; }\n@end\n\n\n@interface RCVector\u00a0: NSObject\n{\n @private\n double *vec;\n uint32_t size;\n}\n+(instancetype)newWithArray: (double *)v ofLength: (uint32_t)l; \n-(instancetype)initWithArray: (double *)v ofLength: (uint32_t)l;\n-(VResult *)dotProductWith: (RCVector *)v;\n-(uint32_t)size;\n-(double *)array;\n-(void)free;\n@end\n\n@implementation RCVector\n+(instancetype)newWithArray: (double *)v ofLength: (uint32_t)l\n{\n return [[self alloc] initWithArray: v ofLength: l];\n}\n-(instancetype)initWithArray: (double *)v ofLength: (uint32_t)l\n{\n if ((self = [super init])) {\n size = l;\n vec = malloc(sizeof(double) * l);\n if ( vec == NULL )\n return nil;\n memcpy(vec, v, sizeof(double)*l);\n }\n return self;\n}\n-(void)dealloc\n{\n free(vec);\n}\n-(uint32_t)size { return size; }\n-(double *)array { return vec; }\n-(VResult *)dotProductWith: (RCVector *)v\n{\n double r = 0.0;\n uint32_t i, s;\n double *v1;\n if ( [self size] != [v size] ) return [VResult new: r isValid: NO];\n s = [self size];\n v1 = [v array];\n for(i = 0; i < s; i++) {\n r += vec[i] * v1[i];\n }\n return [VResult new: r isValid: YES];\n}\n@end\n\ndouble val1[] = { 1, 3, -5 };\ndouble val2[] = { 4,-2, -1 }; \n\nint main()\n{\n @autoreleasepool {\n RCVector *v1 = [RCVector newWithArray: val1 ofLength: sizeof(val1)\/sizeof(double)];\n RCVector *v2 = [RCVector newWithArray: val2 ofLength: sizeof(val1)\/sizeof(double)];\n VResult *r = [v1 dotProductWith: v2];\n if ( [r isValid] ) {\n printf(\"%lf\\n\", [r value]);\n } else {\n fprintf(stderr, \"length of vectors differ\\n\");\n }\n }\n return 0;\n}\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":180} {"lang_cluster":"Objective-C","source_code":"\nNSLog(@\"%@\", [NSDate date]);\nor (deprecated)NSLog(@\"%@\", [NSCalendarDate calendarDate]);\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":181} {"lang_cluster":"Objective-C","source_code":"\nWorks with: Mac OS X version 10.5+\nWorks with: iOS version 1.0\n@interface NSString (StripCharacters)\n- (NSString *) stripCharactersInSet: (NSCharacterSet *) chars;\n@end\n\n@implementation NSString (StripCharacters)\n- (NSString *) stripCharactersInSet: (NSCharacterSet *) chars {\n return [[self componentsSeparatedByCharactersInSet:chars] componentsJoinedByString:@\"\"];\n}\n@end\n\n\nTo use:\n NSString *aString = @\"She was a soul stripper. She took my heart!\";\n NSCharacterSet* chars = [NSCharacterSet characterSetWithCharactersInString:@\"aei\"];\n\n \/\/ Display the NSString.\n NSLog(@\"%@\", [aString stripCharactersInSet:chars]);\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":182} {"lang_cluster":"Objective-C","source_code":"\n#import \n\nint main(int argc, const char * argv[])\n{\n\n @autoreleasepool {\n \n NSLog(@\"I'm thinking of a number between 1 - 10. Can you guess what it is?\\n\");\n \n int rndNumber = arc4random_uniform(10) + 1;\n \n \/\/ Debug (Show rndNumber in console)\n \/\/NSLog(@\"Random number is %i\", rndNumber);\n \n int userInput;\n \n do {\n \n NSLog(@\"Input the number below\\n\");\n scanf(\"%i\", &userInput);\n \n if (userInput > 10) {\n \n NSLog(@\"Please enter a number less than 10\\n\");\n }\n \n if (userInput > 10 || userInput != rndNumber) {\n \n NSLog(@\"Your guess %i is incorrect, please try again\", userInput);\n \n } else {\n \n NSLog(@\"Your guess %i is correct!\", userInput);\n }\n \n } while (userInput > 10 || userInput != rndNumber);\n }\n return 0;\n}\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":183} {"lang_cluster":"Objective-C","source_code":"\n+ (double) distanceBetweenLat1:(double)lat1 lon1:(double)lon1\n lat2:(double)lat2 lon2:(double)lon2 {\n \/\/degrees to radians\n double lat1rad = lat1 * M_PI\/180; \n double lon1rad = lon1 * M_PI\/180;\n double lat2rad = lat2 * M_PI\/180;\n double lon2rad = lon2 * M_PI\/180;\n \n \/\/deltas\n double dLat = lat2rad - lat1rad;\n double dLon = lon2rad - lon1rad;\n\n double a = sin(dLat\/2) * sin(dLat\/2) + sin(dLon\/2) * sin(dLon\/2) * cos(lat1rad) * cos(lat2rad);\n double c = 2 * asin(sqrt(a));\n double R = 6372.8;\n return R * c;\n}\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":184} {"lang_cluster":"Objective-C","source_code":"\n#import \n\nint main (int argc, const char * argv[]) {\n @autoreleasepool {\n\n NSError *error;\n NSURLResponse *response;\n NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@\"http:\/\/rosettacode.org\"]]\n returningResponse:&response\n error:&error];\n\n NSLog(@\"%@\", [[NSString alloc] initWithData:data\n encoding:NSUTF8StringEncoding]);\n\n }\n return 0;\n}\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":185} {"lang_cluster":"Objective-C","source_code":"\n- (NSArray *) toCharArray {\n\t\n\tNSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[self length]];\n\tfor (int i=0; i < [self length]; i++) {\n\t\tNSString *ichar = [NSString stringWithFormat:@\"%C\", [self characterAtIndex:i]];\n\t\t[characters addObject:ichar];\n\t}\n\t\n\treturn characters;\n}\n\n+ (BOOL) luhnCheck:(NSString *)stringToTest {\n\t\n\tNSArray *stringAsChars = [stringToTest toCharArray];\n\t\n\tBOOL isOdd = YES;\n\tint oddSum = 0;\n\tint evenSum = 0;\n\t\n\tfor (int i = [stringToTest length] - 1; i >= 0; i--) {\n\t\t\n\t\tint digit = [(NSString *)stringAsChars[i] intValue];\n\t\t\n\t\tif (isOdd) \n\t\t\toddSum += digit;\n\t\telse \n\t\t\tevenSum += digit\/5 + (2*digit) % 10;\n\t\t\t\n\t\tisOdd = !isOdd;\t\t\t\t \n\t}\n\t\n\treturn ((oddSum + evenSum) % 10 == 0);\n}\n\nBOOL test0 = [self luhnCheck:@\"49927398716\"]; \/\/Result = YES\nBOOL test1 = [self luhnCheck:@\"49927398717\"]; \/\/Result = NO\nBOOL test2 = [self luhnCheck:@\"1234567812345678\"]; \/\/Result = NO\t\t\t\t \nBOOL test3 = [self luhnCheck:@\"1234567812345670\"]; \/\/Result = YES\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":186} {"lang_cluster":"Objective-C","source_code":"\n\n@interface NSString (RosettaCodeAddition)\n- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times;\n@end\n\n@implementation NSString (RosettaCodeAddition)\n- (NSString *) repeatStringByNumberOfTimes: (NSUInteger) times {\n return [@\"\" stringByPaddingToLength:[self length]*times withString:self startingAtIndex:0];\n}\n@end\n\n \/\/ Instantiate an NSString by sending an NSString literal our new\n \/\/ -repeatByNumberOfTimes: selector.\n NSString *aString = [@\"ha\" repeatStringByNumberOfTimes:5];\n\n \/\/ Display the NSString.\n NSLog(@\"%@\", aString);\n","human_summarization":"extend the NSString class in Objective-C to include a method that repeats a given string or character a specified number of times. This is achieved using the language feature of categories, which allows for the addition of methods to existing classes without the need for subclassing. The method is applicable to all instances of the class and its subclasses. An example use case is repeating the string \"ha\" 5 times or the character \"*\" 5 times.","id":187} {"lang_cluster":"Objective-C","source_code":"\n\nWorks with: Mac OS X version 10.4+\nWorks with: iOS version 3.0+\nNSString *str = @\"I am a string\";\nNSString *regex = @\".*string$\";\n\n\/\/ Note: the MATCHES operator matches the entire string, necessitating the \".*\"\nNSPredicate *pred = [NSPredicate predicateWithFormat:@\"SELF MATCHES\u00a0%@\", regex];\n\nif ([pred evaluateWithObject:str]) {\n NSLog(@\"ends with 'string'\");\n}\n\n\n\nWorks with: Mac OS X version 10.7+\nWorks with: iOS version 3.2+\nNSString *str = @\"I am a string\";\nif ([str rangeOfString:@\"string$\" options:NSRegularExpressionSearch].location != NSNotFound) {\n NSLog(@\"Ends with 'string'\");\n}\n\n\nWorks with: Mac OS X version 10.7+\nWorks with: iOS version 4.0+ undocumented\nNSString *orig = @\"I am the original string\";\nNSString *result = [orig stringByReplacingOccurrencesOfString:@\"original\"\n withString:@\"modified\"\n options:NSRegularExpressionSearch\n range:NSMakeRange(0, [orig length])];\nNSLog(@\"%@\", result);\n\nWorks with: Mac OS X version 10.7+\nWorks with: iOS version 4.0+\n\nNSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@\"string$\"\n options:0\n error:NULL];\nNSString *str = @\"I am a string\";\nif ([regex rangeOfFirstMatchInString:str\n options:0\n range:NSMakeRange(0, [str length])\n ].location != NSNotFound) {\n NSLog(@\"Ends with 'string'\");\n}\n\n\nfor (NSTextCheckingResult *match in [regex matchesInString:str\n options:0\n range:NSMakeRange(0, [str length])\n ]) {\n \/\/ match.range gives the range of the whole match\n \/\/ [match rangeAtIndex:i] gives the range of the i'th capture group (starting from 1)\n}\n\n\nNSString *orig = @\"I am the original string\";\nNSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@\"original\"\n options:0\n error:NULL];\nNSString *result = [regex stringByReplacingMatchesInString:orig\n options:0\n range:NSMakeRange(0, [orig length])\n withTemplate:@\"modified\"];\nNSLog(@\"%@\", result);\n\n","human_summarization":"\"Matches a string against a regular expression, identifies the location of the match, performs substitution on part of the string using the regular expression, and loops through all matches for substitution.\"","id":188} {"lang_cluster":"Objective-C","source_code":"\n\n@interface NSString (CountSubstrings)\n- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr;\n@end\n\n@implementation NSString (CountSubstrings)\n- (NSUInteger)occurrencesOfSubstring:(NSString *)subStr {\n return [[self componentsSeparatedByString:subStr] count] - 1;\n}\n@end\n\nint main(int argc, const char *argv[]) {\n @autoreleasepool {\n\n NSLog(@\"%lu\", [@\"the three truths\" occurrencesOfSubstring:@\"th\"]);\n NSLog(@\"%lu\", [@\"ababababab\" occurrencesOfSubstring:@\"abab\"]);\n NSLog(@\"%lu\", [@\"abaabba*bbaba*bbab\" occurrencesOfSubstring:@\"a*b\"]);\n \n }\n return 0;\n}\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two parameters: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function does not count overlapping substrings and aims to yield the highest number of non-overlapping matches, either from left-to-right or right-to-left.","id":189} {"lang_cluster":"Objective-C","source_code":"\n\nWorks with: GNUstep\n\n#import \n\n@interface TowersOfHanoi: NSObject {\n\tint pegFrom;\n\tint pegTo;\n\tint pegVia;\n\tint numDisks;\n}\n\n-(void) setPegFrom: (int) from andSetPegTo: (int) to andSetPegVia: (int) via andSetNumDisks: (int) disks;\n-(void) movePegFrom: (int) from andMovePegTo: (int) to andMovePegVia: (int) via andWithNumDisks: (int) disks;\n@end\n\n#import \"TowersOfHanoi.h\"\n@implementation TowersOfHanoi\n\n-(void) setPegFrom: (int) from andSetPegTo: (int) to andSetPegVia: (int) via andSetNumDisks: (int) disks {\n\tpegFrom = from;\n\tpegTo = to;\n\tpegVia = via;\n\tnumDisks = disks;\n}\n\n-(void) movePegFrom: (int) from andMovePegTo: (int) to andMovePegVia: (int) via andWithNumDisks: (int) disks {\n\tif (disks == 1) {\n printf(\"Move disk from pole %i to pole %i\\n\", from, to);\n } else {\n \t\t\t[self movePegFrom: from andMovePegTo: via andMovePegVia: to andWithNumDisks: disks-1];\n\t\t\t[self movePegFrom: from andMovePegTo: to andMovePegVia: via andWithNumDisks: 1];\n\t\t\t[self movePegFrom: via andMovePegTo: to andMovePegVia: from andWithNumDisks: disks-1];\n }\n}\n\n@end\n\n#import \n#import \"TowersOfHanoi.h\"\n\nint main( int argc, const char *argv[] ) {\n\t@autoreleasepool {\n\n\t\tTowersOfHanoi *tower = [[TowersOfHanoi alloc] init];\n\n\t\tint from = 1;\n\t\tint to = 3;\n\t\tint via = 2;\n\t\tint disks = 3;\n\n\t\t[tower setPegFrom: from andSetPegTo: to andSetPegVia: via andSetNumDisks: disks];\n\n\t\t[tower movePegFrom: from andMovePegTo: to andMovePegVia: via andWithNumDisks: disks];\n\n\t}\n\treturn 0;\n}\n","human_summarization":"The following codes implement a recursive solution to the Towers of Hanoi problem. The codes are compatible with XCode\/Cocoa on MacOS. It includes three parts: the interface in TowersOfHanoi.h, the implementation in TowersOfHanoi.m, and the test code in TowersTest.m.","id":190} {"lang_cluster":"Objective-C","source_code":"\n\n\n\/\/ Return the length in characters\n\/\/ XXX: does not (always) count Unicode characters (code points)! \nunsigned int numberOfCharacters = [@\"m\u00f8\u00f8se\" length]; \/\/ 5\n\nint realCharacterCount = [s lengthOfBytesUsingEncoding: NSUTF32StringEncoding] \/ 4;\n\nint byteCount = [@\"m\u00f8\u00f8se\" length] * 2; \/\/ 10\n\n\/\/ Return the number of bytes depending on the encoding,\n\/\/ here explicitly UTF-8\nunsigned numberOfBytes =\n [@\"m\u00f8\u00f8se\" lengthOfBytesUsingEncoding: NSUTF8StringEncoding]; \/\/ 7\n","human_summarization":"determine the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. The character length is based on individual Unicode code points, not user-visible graphemes. The codes also handle non-BMP code points correctly. The byte length is calculated by encoding the string in UTF-32 and dividing by 4 or by doubling the number of 16-bit values used to encode a string in UTF-16. The codes also provide the string length in graphemes if the language supports it. The encoding used is explicitly specified to avoid ambiguity.","id":191} {"lang_cluster":"Objective-C","source_code":"\n#import \n\n@interface NSMutableArray (KnuthShuffle)\n- (void)knuthShuffle;\n@end\n@implementation NSMutableArray (KnuthShuffle)\n- (void)knuthShuffle {\n for (NSUInteger i = self.count-1; i > 0; i--) {\n NSUInteger j = arc4random_uniform(i+1);\n [self exchangeObjectAtIndex:i withObjectAtIndex:j];\n }\n}\n@end\n\nint main() {\n @autoreleasepool {\n NSMutableArray *x = [NSMutableArray arrayWithObjects:@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, nil];\n [x knuthShuffle];\n NSLog(@\"%@\", x);\n }\n return 0;\n}\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":192} {"lang_cluster":"Objective-C","source_code":"\n\nswitch (NSHostByteOrder()) {\n case NS_BigEndian:\n NSLog(@\"%@\", @\"Big Endian\");\n break;\n case NS_LittleEndian:\n NSLog(@\"%@\", @\"Little Endian\");\n break;\n case NS_UnknownByteOrder:\n NSLog(@\"%@\", @\"endianness unknown\");\n break;\n}\n\n\nswitch ([NSRunningApplication currentApplication].executableArchitecture) {\n case NSBundleExecutableArchitectureI386:\n NSLog(@\"%@\", @\"i386 32-bit\");\n break;\n\n case NSBundleExecutableArchitectureX86_64:\n NSLog(@\"%@\", @\"x86_64 64-bit\");\n break;\n\n case NSBundleExecutableArchitecturePPC:\n NSLog(@\"%@\", @\"PPC 32-bit\");\n break;\n\n case NSBundleExecutableArchitecturePPC64:\n NSLog(@\"%@\", @\"PPC64 64-bit\");\n break;\n\n default:\n NSLog(@\"%@\", @\"Unknown\");\n break;\n}\n\n","human_summarization":"\"Code prints the word size and endianness of the host machine, specifically designed for Mac OS X 10.6+ architecture.\"","id":193} {"lang_cluster":"Objective-C","source_code":"\nWorks with: Objective-C version 2.0+\nWorks with: GNUstep\nWorks with: Cocoa\nNSArray *collect;\n\/\/...\nfor(Type i in collect){\n NSLog(@\"%@\", i);\n}\n\nWorks with: Objective-C version <2.0\nNSArray *collect;\n\/\/...\nNSEnumerator *enm = [collect objectEnumerator];\nid i;\nwhile( (i = [enm nextObject]) ) {\n \/\/ do something with object i\n}\n","human_summarization":"Iterates and prints each element in a collection in order using a \"for each\" loop or another loop if \"for each\" isn't available. The collection can be any object that adopts the NSFastEnumeration protocol, always using OpenStep compatible frameworks.","id":194} {"lang_cluster":"Objective-C","source_code":"\nWorks with: GNUstep\nWorks with: Cocoa\nNSString *text = @\"Hello,How,Are,You,Today\";\nNSArray *tokens = [text componentsSeparatedByString:@\",\"];\nNSString *result = [tokens componentsJoinedByString:@\".\"];\nNSLog(result);\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":195} {"lang_cluster":"Objective-C","source_code":"\nWorks with: GCC\nWorks with: OpenStep\nWorks with: GNUstep\n\nif( [[NSScanner scannerWithString:@\"-123.4e5\"] scanFloat:NULL] )\n\tNSLog( @\"\\\"-123.4e5\\\" is numeric\" );\nelse\n\tNSLog( @\"\\\"-123.4e5\\\" is not numeric\" );\nif( [[NSScanner scannerWithString:@\"Not a number\"] scanFloat:NULL] )\n\tNSLog( @\"\\\"Not a number\\\" is numeric\" );\nelse\n\tNSLog( @\"\\\"Not a number\\\" is not numeric\" );\n\/\/ prints: \"-123.4e5\" is numeric\n\/\/ prints: \"Not a number\" is not numeric\n\n\nBOOL isNumeric(NSString *s)\n{\n NSScanner *sc = [NSScanner scannerWithString: s];\n if ( [sc scanFloat:NULL] )\n {\n return [sc isAtEnd];\n }\n return NO;\n}\n\n\nBOOL isNumericI(NSString *s)\n{\n NSUInteger len = [s length];\n NSUInteger i;\n BOOL status = NO;\n \n for(i=0; i < len; i++)\n {\n unichar singlechar = [s characterAtIndex: i];\n if ( (singlechar == ' ') && (!status) )\n {\n continue;\n }\n if ( ( singlechar == '+' ||\n singlechar == '-' ) && (!status) ) { status=YES; continue; }\n if ( ( singlechar >= '0' ) &&\n ( singlechar <= '9' ) )\n {\n status = YES;\n } else {\n return NO;\n }\n }\n return (i == len) && status;\n}\n\n\n","human_summarization":"The code creates a boolean function that checks if a given string is numeric, including floating point and negative numbers. It uses the NSScanner class to scan the string and the scanFloat method to determine if the string is numeric. The function also checks if the scanner has reached the end of the string after parsing the float, ensuring the string is completely numeric. It also includes a manual scan function to check if the number is a positive or negative integer, allowing for spaces before the number but not after, and only allowing '+' or '-' symbols attached directly to the number.","id":196} {"lang_cluster":"Objective-C","source_code":"\nNSString *s = @\"12345\";\nint i = [s intValue] + 1;\ns = [NSString stringWithFormat:@\"%i\", i]\n","human_summarization":"\"Increments a given numerical string.\"","id":197} {"lang_cluster":"Objective-C","source_code":"\n#import \n\n@interface NSMutableArray (SattoloCycle)\n- (void)sattoloCycle;\n@end\n@implementation NSMutableArray (SattoloCycle)\n- (void)sattoloCycle {\n for (NSUInteger i = self.count-1; i > 0; i--) {\n NSUInteger j = arc4random_uniform(i);\n [self exchangeObjectAtIndex:i withObjectAtIndex:j];\n }\n}\n@end\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":198} {"lang_cluster":"Objective-C","source_code":"\n\/\/ FizzBuzz in Objective-C\n#import \n\nint main(int argc, char* argv[]) {\n\tfor (NSInteger i=1; I <= 101; i++) {\n\t\tif (i\u00a0% 15 == 0) {\n\t\t NSLog(@\"FizzBuzz\\n\");\n\t\t} else if (i\u00a0% 3 == 0) {\n\t\t NSLog(@\"Fizz\\n\");\n\t\t} else if (i\u00a0% 5 == 0) {\n\t\t NSLog(@\"Buzz\\n\");\n\t\t} else {\n\t\t NSLog(@\"%li\\n\", i);\n\t\t}\n\t}\n}\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":199} {"lang_cluster":"Objective-C","source_code":"\nWorks with: GCC version 4.0.1 (apple)\n\n- (float) sum:(NSMutableArray *)array\n{ \n\tint i, sum, value;\n\tsum = 0;\n\tvalue = 0;\n\t\n\tfor (i = 0; i < [array count]; i++) {\n\t\tvalue = [[array objectAtIndex: i] intValue];\n\t\tsum += value;\n\t}\n\t\n\treturn suml;\n}\n\n\n- (float) prod:(NSMutableArray *)array\n{ \n\tint i, prod, value;\n\tprod = 0;\n\tvalue = 0;\n\t\n\tfor (i = 0; i < [array count]; i++) {\n\t\tvalue = [[array objectAtIndex: i] intValue];\n\t\tprod *= value;\n\t}\n\t\n\treturn suml;\n}\n\n","human_summarization":"Calculates the sum and product of all integers in an array.","id":200} {"lang_cluster":"Objective-C","source_code":"\n\nNSString *original = @\"Literal String\";\nNSString *new = [original copy];\nNSString *anotherNew = [NSString stringWithString:original];\nNSString *newMutable = [original mutableCopy];\n\n\nNSMutableString *original = [NSMutableString stringWithString:@\"Literal String\"];\nNSString *immutable = [original copy];\nNSString *anotherImmutable = [NSString stringWithString:original];\nNSMutableString *mutable = [original mutableCopy];\n\n\nconst char *cstring = \"I'm a plain C string\";\nNSString *string = [NSString stringWithUTF8String:cstring];\n\n\nchar bytes[] = \"some data\";\nNSString *string = [[NSString alloc] initWithBytes:bytes length:9 encoding:NSASCIIStringEncoding];\n\n\n","human_summarization":"The code implements the task of copying a string. It differentiates between copying the string's content and creating an additional reference to the existing string. For immutable strings, it either increases the reference count or creates a mutable copy. The code also handles mutable strings, creating either a new mutable or immutable string. It also includes functionality for copying a CString into an NSString, and copying from data that may not be null-terminated. If a C string is needed, it utilizes standard functions like strcpy.","id":201} {"lang_cluster":"Objective-C","source_code":"\n\n#import \n\n@interface Hofstadter\u00a0: NSObject\n+ (int)M: (int)n;\n+ (int)F: (int)n;\n@end\n\n@implementation Hofstadter\n+ (int)M: (int)n\n{\n if ( n == 0 ) return 0;\n return n - [self F: [self M: (n-1)]];\n}\n+ (int)F: (int)n\n{\n if ( n == 0 ) return 1;\n return n - [self M: [self F: (n-1)]];\n}\n@end\n\nint main()\n{\n int i;\n\n for(i=0; i < 20; i++) {\n printf(\"%3d \", [Hofstadter F: i]);\n }\n printf(\"\\n\");\n for(i=0; i < 20; i++) {\n printf(\"%3d \", [Hofstadter M: i]);\n }\n printf(\"\\n\");\n return 0;\n}\n\n","human_summarization":"implement two mutually recursive functions to calculate the Hofstadter Female and Male sequences. The functions follow the rules of mutual recursion, where the first function calls the second, and the second function calls the first. The sequences are defined with specific base cases and recursive cases. The code also considers the language-specific rules for prior declaration in Objective-C.","id":202} {"lang_cluster":"Objective-C","source_code":"\nNSString *encoded = @\"http%3A%2F%2Ffoo%20bar%2F\";\nNSString *normal = [encoded stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];\nNSLog(@\"%@\", normal);\n\nWorks with: Mac OS X version 10.9+Works with: iOS version 7+\nNSString *encoded = @\"http%3A%2F%2Ffoo%20bar%2F\";\nNSString *normal = [encoded stringByRemovingPercentEncoding];\nNSLog(@\"%@\", normal);\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":203} {"lang_cluster":"Objective-C","source_code":"\n\n#import \n\n@interface NSArray (BinarySearch)\n\/\/ Requires all elements of this array to implement a -compare: method which\n\/\/ returns a NSComparisonResult for comparison.\n\/\/ Returns NSNotFound when not found\n- (NSInteger) binarySearch:(id)key;\n@end\n\n@implementation NSArray (BinarySearch)\n- (NSInteger) binarySearch:(id)key {\n NSInteger lo = 0;\n NSInteger hi = [self count] - 1;\n while (lo <= hi) {\n NSInteger mid = lo + (hi - lo) \/ 2;\n id midVal = self[mid];\n switch ([midVal compare:key]) {\n case NSOrderedAscending:\n lo = mid + 1;\n break;\n case NSOrderedDescending:\n hi = mid - 1;\n break;\n case NSOrderedSame:\n return mid;\n }\n }\n return NSNotFound;\n}\n@end\n\nint main()\n{\n @autoreleasepool {\n\n NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10];\n NSLog(@\"6 is at position %d\", [a binarySearch:@6]); \/\/ prints 4\n\n }\n return 0;\n}\n\n#import \n\n@interface NSArray (BinarySearchRecursive)\n\/\/ Requires all elements of this array to implement a -compare: method which\n\/\/ returns a NSComparisonResult for comparison.\n\/\/ Returns NSNotFound when not found\n- (NSInteger) binarySearch:(id)key inRange:(NSRange)range;\n@end\n\n@implementation NSArray (BinarySearchRecursive)\n- (NSInteger) binarySearch:(id)key inRange:(NSRange)range {\n if (range.length == 0)\n return NSNotFound;\n NSInteger mid = range.location + range.length \/ 2;\n id midVal = self[mid];\n switch ([midVal compare:key]) {\n case NSOrderedAscending:\n return [self binarySearch:key\n inRange:NSMakeRange(mid + 1, NSMaxRange(range) - (mid + 1))];\n case NSOrderedDescending:\n return [self binarySearch:key\n inRange:NSMakeRange(range.location, mid - range.location)];\n default:\n return mid;\n }\n}\n@end\n\nint main()\n{\n @autoreleasepool {\n\n NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10];\n NSLog(@\"6 is at position %d\", [a binarySearch:@6]); \/\/ prints 4\n\n }\n return 0;\n}\n\nWorks with: Mac OS X version 10.6+\n#import \n\nint main()\n{\n @autoreleasepool {\n\n NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10];\n NSLog(@\"6 is at position %lu\", [a indexOfObject:@6\n inSortedRange:NSMakeRange(0, [a count])\n options:0\n usingComparator:^(id x, id y){ return [x compare: y]; }]); \/\/ prints 4\n\n }\n return 0;\n}\n\n#import \n\nCFComparisonResult myComparator(const void *x, const void *y, void *context) {\n return [(__bridge id)x compare:(__bridge id)y];\n}\n\nint main(int argc, const char *argv[]) {\n @autoreleasepool {\n\n NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10];\n NSLog(@\"6 is at position %ld\", CFArrayBSearchValues((__bridge CFArrayRef)a,\n CFRangeMake(0, [a count]),\n (__bridge const void *)@6,\n myComparator,\n NULL)); \/\/ prints 4\n\n }\n return 0;\n}\n","human_summarization":"The code implements a binary search algorithm, which is used to find a specific value in a sorted integer array. The algorithm divides the array into halves and continues to narrow down the search range until the target value is found. The code provides both recursive and iterative implementations of the binary search. It also handles cases where there are multiple values equal to the target value and returns the index of the target value if found. Additionally, the code includes variations of the binary search algorithm that return the leftmost and rightmost insertion points for the target value. The code is also designed to avoid overflow bugs.","id":204} {"lang_cluster":"Objective-C","source_code":"\n\nNSArray *args = [[NSProcessInfo processInfo] arguments];\nNSLog(@\"This program is named\u00a0%@.\", [args objectAtIndex:0]);\nNSLog(@\"There are %d arguments.\", [args count] - 1);\nfor (i = 1; i < [args count]; ++i){\n NSLog(@\"the argument #%d is\u00a0%@\", i, [args objectAtIndex:i]);\n}\n\n","human_summarization":"retrieve and print the command-line arguments given to the program. It uses both the regular C mechanism and an additional Objective-C method to get the arguments as string objects inside an array. The example command line used is 'myprogram -c \"alpha beta\" -h \"gamma\"'. The program also includes functionality for parsing these arguments intelligently.","id":205} {"lang_cluster":"Objective-C","source_code":"\nWorks with: 10.7+ version Xcode 4.4+\nNSString *jsonString = @\"{ \\\"foo\\\": 1, \\\"bar\\\": [10, \\\"apples\\\"] }\";\nid obj = [NSJSONSerialization \n JSONObjectWithData: [jsonString dataUsingEncoding: NSUTF8StringEncoding]\n options: 0\n error: NULL];\nNSLog(@\"%@\", obj);\n\nNSDictionary *dict = @{ @\"blue\": @[@1, @2], @\"ocean\": @\"water\"};\nNSData *jsonData = [NSJSONSerialization dataWithJSONObject: dict\n options: 0\n error: NULL];\nNSString *jsonString2 = [[NSString alloc] initWithData: jsonData\n encoding: NSUTF8StringEncoding];\nNSLog(@\"%@\", jsonString2);\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":206} {"lang_cluster":"Objective-C","source_code":"\n\nNSLog(@\"%@\", [[NSProcessInfo processInfo] hostName]);\n\n\n2010-09-16 16:20:00.000 Playground[1319:a0f] sierra117.local \/\/ Hostname is sierra117.local.\n\n","human_summarization":"finds the hostname of the current system where the routine is running in Cocoa \/ Cocoa Touch \/ GNUstep.","id":207} {"lang_cluster":"Objective-C","source_code":"\n#import \n\n@interface RCRunLengthEncoder : NSObject {\n\n NSMutableArray *contents;\n NSMutableArray *counters;\n} + (instancetype)encoderWithData: (NSData *)data; - (instancetype)initWithData: (NSData *)data; - (void)addByte: (char)aByte; - (void)addByte: (char)aByte repeated: (int)repetitionCount; - (void)addData: (NSData *)data; - (NSData *)data; - (NSArray *)counters; - (NSArray *)contents; @end\n\n\n@implementation RCRunLengthEncoder + (instancetype)encoderWithData: (NSData *)data {\n\n return [[self alloc] initWithData: data];\n}\n\n- (instancetype)initWithData: (NSData *)data {\n\n if ((self = [self init]) != nil) {\n [self addData: data];\n }\n return self;\n}\n\n- (instancetype)init {\n\n if ((self = [super init]) != nil) {\n contents = [[NSMutableArray alloc] init];\n counters = [[NSMutableArray alloc] init];\n }\n return self;\n}\n\n- (void)addByte: (char)aByte {\n\n [self addByte: aByte repeated: 1];\n}\n\n- (void)addByte: (char)aByte repeated: (int)repetitionCount {\n\n if ( ([contents count] == 0) || ([[contents lastObject] charValue] != aByte) ) {\n [contents addObject: @(aByte)];\n [counters addObject: @(repetitionCount)];\n } else {\n int a = [[counters lastObject] intValue];\n [counters removeLastObject];\n [counters addObject: @(a + repetitionCount)];\n }\n}\n\n- (void)addData: (NSData *)data {\n\n const char *d = [data bytes];\n NSUInteger i;\n for(i=0; i < [data length]; i++) [self addByte: d[i]];\n}\n\n- (NSArray *)contents {\n\n return contents;\n}\n\n- (NSArray *)counters {\n\n return counters;\n}\n\n- (NSData *)data {\n\n NSMutableData *d = [[NSMutableData alloc] initWithCapacity: 256];\n char buf[256];\n int i;\n for(i=0; i < [contents count]; i++) {\n char c = [contents[i] charValue];\n int n = [counters[i] intValue];\n memset(buf, c, 256);\n while ( n > 0 ) {\n [d appendBytes: buf length: MIN(256, n)];\n n -= 256;\n }\n }\n return d;\n} @end<\/lang>\n","human_summarization":"implement run-length encoding and decoding functions for strings containing uppercase characters. The encoding function compresses repeated characters by storing the length of the run, and the decoding function reverses this compression.","id":208} {"lang_cluster":"Objective-C","source_code":"\n#import \n\nint main()\n{\n @autoreleasepool {\n\n NSString *s = @\"hello\";\n printf(\"%s%s\\n\", [s UTF8String], \" literal\");\n \n NSString *s2 = [s stringByAppendingString:@\" literal\"];\n \/\/ or, NSString *s2 = [NSString stringWithFormat:@\"%@%@\", s, @\" literal\"];\n puts([s2 UTF8String]);\n \/* or *\/\n NSMutableString *s3 = [NSMutableString stringWithString: s];\n [s3 appendString: @\" literal\"];\n puts([s3 UTF8String]);\n \n }\n return 0;\n}\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":209} {"lang_cluster":"Objective-C","source_code":"\nNSString *normal = @\"http:\/\/foo bar\/\";\nNSString *encoded = [normal stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];\nNSLog(@\"%@\", encoded);\n\n\nWorks with: Mac OS X version 10.9+\nWorks with: iOS version 7+\nNSString *normal = @\"http:\/\/foo bar\/\";\nNSString *encoded = [normal stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];\nNSLog(@\"%@\", encoded);\n\n\n","human_summarization":"The code provides a function to convert a given string into its URL encoding representation. It converts special, control, and extended characters into a percent symbol followed by a two-digit hexadecimal code. For instance, a space character is encoded as %20. The code adheres to the rule that every character except 0-9, A-Z, and a-z requires conversion. It also supports variations like lowercase escapes and different encodings for special characters as per different standards like RFC 3986 and HTML 5. Optionally, it allows the use of an exception string with symbols that don't need conversion. It also provides options for encoding different parts of the URL using various allowed character sets.","id":210} {"lang_cluster":"Objective-C","source_code":"\n#import \n\n\n@interface HuffmanTree\u00a0: NSObject {\n\tint freq;\n}\n-(instancetype)initWithFreq:(int)f;\n@property (nonatomic, readonly) int freq;\n@end\n\n@implementation HuffmanTree\n@synthesize freq; \/\/ the frequency of this tree\n-(instancetype)initWithFreq:(int)f {\n\tif (self = [super init]) {\n\t\tfreq = f;\n\t}\n\treturn self;\n}\n@end\n\n\nconst void *HuffmanRetain(CFAllocatorRef allocator, const void *ptr) {\n\treturn (__bridge_retained const void *)(__bridge id)ptr;\n}\nvoid HuffmanRelease(CFAllocatorRef allocator, const void *ptr) {\n\t(void)(__bridge_transfer id)ptr;\n}\nCFComparisonResult HuffmanCompare(const void *ptr1, const void *ptr2, void *unused) {\n\tint f1 = ((__bridge HuffmanTree *)ptr1).freq;\n\tint f2 = ((__bridge HuffmanTree *)ptr2).freq;\n\tif (f1 == f2)\n\t\treturn kCFCompareEqualTo;\n\telse if (f1 > f2)\n\t\treturn kCFCompareGreaterThan;\n\telse\n\t\treturn kCFCompareLessThan;\n}\n\n\n@interface HuffmanLeaf\u00a0: HuffmanTree {\n\tchar value; \/\/ the character this leaf represents\n}\n@property (readonly) char value;\n-(instancetype)initWithFreq:(int)f character:(char)c;\n@end\n\n@implementation HuffmanLeaf\n@synthesize value;\n-(instancetype)initWithFreq:(int)f character:(char)c {\n\tif (self = [super initWithFreq:f]) {\n\t\tvalue = c;\n\t}\n\treturn self;\n}\n@end\n\n\n@interface HuffmanNode\u00a0: HuffmanTree {\n\tHuffmanTree *left, *right; \/\/ subtrees\n}\n@property (readonly) HuffmanTree *left, *right;\n-(instancetype)initWithLeft:(HuffmanTree *)l right:(HuffmanTree *)r;\n@end\n\n@implementation HuffmanNode\n@synthesize left, right;\n-(instancetype)initWithLeft:(HuffmanTree *)l right:(HuffmanTree *)r {\n\tif (self = [super initWithFreq:l.freq+r.freq]) {\n\t\tleft = l;\n\t\tright = r;\n\t}\n\treturn self;\n}\n@end\n\n\nHuffmanTree *buildTree(NSCountedSet *chars) {\n\t\n\tCFBinaryHeapCallBacks callBacks = {0, HuffmanRetain, HuffmanRelease, NULL, HuffmanCompare};\n\tCFBinaryHeapRef trees = CFBinaryHeapCreate(NULL, 0, &callBacks, NULL);\n\n\t\/\/ initially, we have a forest of leaves\n\t\/\/ one for each non-empty character\n\tfor (NSNumber *ch in chars) {\n\t\tint freq = [chars countForObject:ch];\n\t\tif (freq > 0)\n\t\t\tCFBinaryHeapAddValue(trees, (__bridge const void *)[[HuffmanLeaf alloc] initWithFreq:freq character:(char)[ch intValue]]);\n\t}\n\t\n\tNSCAssert(CFBinaryHeapGetCount(trees) > 0, @\"String must have at least one character\");\n\t\/\/ loop until there is only one tree left\n\twhile (CFBinaryHeapGetCount(trees) > 1) {\n\t\t\/\/ two trees with least frequency\n\t\tHuffmanTree *a = (__bridge HuffmanTree *)CFBinaryHeapGetMinimum(trees);\n\t\tCFBinaryHeapRemoveMinimumValue(trees);\n\t\tHuffmanTree *b = (__bridge HuffmanTree *)CFBinaryHeapGetMinimum(trees);\n\t\tCFBinaryHeapRemoveMinimumValue(trees);\n\t\t\n\t\t\/\/ put into new node and re-insert into queue\n\t\tCFBinaryHeapAddValue(trees, (__bridge const void *)[[HuffmanNode alloc] initWithLeft:a right:b]);\n\t}\n\tHuffmanTree *result = (__bridge HuffmanTree *)CFBinaryHeapGetMinimum(trees);\n\tCFRelease(trees);\n\treturn result;\n}\n\nvoid printCodes(HuffmanTree *tree, NSMutableString *prefix) {\n\tNSCAssert(tree != nil, @\"tree must not be nil\");\n\tif ([tree isKindOfClass:[HuffmanLeaf class]]) {\n\t\tHuffmanLeaf *leaf = (HuffmanLeaf *)tree;\n\t\t\n\t\t\/\/ print out character, frequency, and code for this leaf (which is just the prefix)\n\t\tNSLog(@\"%c\\t%d\\t%@\", leaf.value, leaf.freq, prefix);\n\t\t\n\t} else if ([tree isKindOfClass:[HuffmanNode class]]) {\n\t\tHuffmanNode *node = (HuffmanNode *)tree;\n\t\t\n\t\t\/\/ traverse left\n\t\t[prefix appendString:@\"0\"];\n\t\tprintCodes(node.left, prefix);\n\t\t[prefix deleteCharactersInRange:NSMakeRange([prefix length]-1, 1)];\n\t\t\n\t\t\/\/ traverse right\n\t\t[prefix appendString:@\"1\"];\n\t\tprintCodes(node.right, prefix);\n\t\t[prefix deleteCharactersInRange:NSMakeRange([prefix length]-1, 1)];\n\t}\n}\n\nint main(int argc, const char * argv[]) {\n @autoreleasepool {\n\n\tNSString *test = @\"this is an example for huffman encoding\";\n\t\n\t\/\/ read each character and record the frequencies\n\tNSCountedSet *chars = [[NSCountedSet alloc] init];\n\tint n = [test length];\n\tfor (int i = 0; i < n; i++)\n\t\t[chars addObject:@([test characterAtIndex:i])];\n\t\n\t\/\/ build tree\n\tHuffmanTree *tree = buildTree(chars);\n\t\n\t\/\/ print out results\n\tNSLog(@\"SYMBOL\\tWEIGHT\\tHUFFMAN CODE\");\n\tprintCodes(tree, [NSMutableString string]);\n\t\n }\n return 0;\n}\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in a given string. It first creates a priority queue with a leaf node for each symbol. It then constructs a binary tree by continuously removing the two nodes with the highest priority and creating a new internal node with these two nodes as children. The final node is the root of the tree. The code then traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute the Huffman encoding for the corresponding symbol. This code uses Apple's Core Foundation library for its binary heap and is compatible with Mac OS X.","id":211} {"lang_cluster":"Objective-C","source_code":"\nWorks with: GNUstep\n#include \n#include \n\n@interface ClickMe\u00a0: NSWindow\n{\n NSButton *_button;\n NSTextField *_text;\n int _counter;\n}\n- (void)applicationDidFinishLaunching: (NSNotification *)notification;\n- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification;\n- (void)advanceCounter: (id)sender;\n@end\n\n@implementation ClickMe\u00a0: NSWindow\n-(instancetype) init\n{\n NSButton *button = [[NSButton alloc] init];\n [button setButtonType: NSToggleButton];\n [button setTitle: @\"Click Me\"];\n [button sizeToFit];\n [button setTarget: self];\n [button setAction: @selector(advanceCounter:)];\n NSRect buttonRect = [button frame];\n\n NSTextField *text = [[NSTextField alloc] \n\t initWithFrame: NSMakeRect(buttonRect.origin.x, buttonRect.size.height,\n\t\t\t\t buttonRect.size.width, buttonRect.size.height)];\n [text setAlignment: NSCenterTextAlignment];\n [text setEditable: NO];\n [text setStringValue: @\"There have been no clicks yet\"];\n [text sizeToFit];\n\n \/\/ reset size of button according to size of (larger...?) text\n [button \n setFrameSize: NSMakeSize( [text frame].size.width, buttonRect.size.height ) ];\n\n int totalWindowHeight = buttonRect.size.height + [text frame].size.height;\n \n if ((self = [super initWithContentRect: NSMakeRect(100, 100, \n\t\t\t\t [text frame].size.width, totalWindowHeight)\n styleMask: (NSTitledWindowMask | NSClosableWindowMask)\n backing: NSBackingStoreBuffered\n defer: NO])) {\n _counter = 0;\n _button = button;\n _text = text;\n\n [[self contentView] addSubview: _text];\n [[self contentView] addSubview: _button];\n\n [self setTitle: @\"Click Me!\"];\n [self center];\n }\n return self;\n}\n\n\n- (void)applicationDidFinishLaunching: (NSNotification *)notification\n{\n [self orderFront: self];\n}\n\n- (BOOL)applicationShouldTerminateAfterLastWindowClosed: (NSNotification *)notification\n{\n return YES;\n}\n\n- (void)advanceCounter: (id)sender\n{\n [_text setStringValue: [NSString stringWithFormat: @\"Clicked %d times\", ++_counter]];\n}\n@end\n\n\nint main()\n{\n @autoreleasepool {\n NSApplication *app = [NSApplication sharedApplication];\n ClickMe *clickme = [[ClickMe alloc] init];\n [app setDelegate: clickme];\n [app run];\n }\n return 0;\n}\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":212} {"lang_cluster":"Objective-C","source_code":"\n\nNSArray *arr1 = @[@1, @2, @3];\nNSArray *arr2 = @[@4, @5, @6];\nNSArray *arr3 = [arr1 arrayByAddingObjectsFromArray:arr2];\n\nNSArray *arr1 = @[@1, @2, @3];\nNSArray *arr2 = @[@4, @5, @6];\nNSMutableArray *arr3 = [NSMutableArray arrayWithArray:arr1];\n[arr3 addObjectsFromArray:arr2];\n","human_summarization":"demonstrate how to concatenate two arrays, including both mutable and immutable arrays, in the given programming language.","id":213} {"lang_cluster":"Objective-C","source_code":"\nWorks with: XCode 4.5.1\n\n\/\/--------------------------------------------------------------------\n\/\/ Person class\n\n@interface Person\u00a0: NSObject {\n NSUInteger _candidateIndex;\n}\n@property (nonatomic, strong) NSString* name;\n@property (nonatomic, strong) NSArray* prefs;\n@property (nonatomic, weak) Person* fiance;\n@end\n\n@implementation Person\n+ (instancetype)named:(NSString *)name {\n return [[self alloc] initWithName:name];\n}\n- (instancetype)initWithName:(NSString *)name {\n if ((self = [super init])) {\n _name = name;\n _prefs = nil;\n _fiance = nil;\n _candidateIndex = 0;\n }\n return self;\n}\n- (BOOL)prefers:(Person *)p {\n return [_prefs indexOfObject:p] < [_prefs indexOfObject:_fiance];\n}\n- (Person *)nextCandidateNotYetProposedTo {\n if (_candidateIndex >= _prefs.count) return nil;\n return _prefs[_candidateIndex++];\n}\n- (void)engageTo:(Person *)p {\n if (p.fiance) p.fiance.fiance = nil;\n p.fiance = self;\n if (self.fiance) self.fiance.fiance = nil;\n self.fiance = p;\n}\n- (NSString *)description {\n return _name;\n}\n@end\n\n\/\/--------------------------------------------------------------------\n\nBOOL isStable(NSArray *men) {\n NSArray *women = ((Person *)men[0]).prefs;\n for (Person *guy in men) {\n for (Person *gal in women) {\n if ([guy prefers:gal] && [gal prefers:guy])\n return NO;\n }\n }\n return YES;\n}\n\n\/\/--------------------------------------------------------------------\n\nvoid doMarriage() {\n Person *abe = [Person named:@\"abe\"];\n Person *bob = [Person named:@\"bob\"];\n Person *col = [Person named:@\"col\"];\n Person *dan = [Person named:@\"dan\"];\n Person *ed = [Person named:@\"ed\"];\n Person *fred = [Person named:@\"fred\"];\n Person *gav = [Person named:@\"gav\"];\n Person *hal = [Person named:@\"hal\"];\n Person *ian = [Person named:@\"ian\"];\n Person *jon = [Person named:@\"jon\"];\n Person *abi = [Person named:@\"abi\"];\n Person *bea = [Person named:@\"bea\"];\n Person *cath = [Person named:@\"cath\"];\n Person *dee = [Person named:@\"dee\"];\n Person *eve = [Person named:@\"eve\"];\n Person *fay = [Person named:@\"fay\"];\n Person *gay = [Person named:@\"gay\"];\n Person *hope = [Person named:@\"hope\"];\n Person *ivy = [Person named:@\"ivy\"];\n Person *jan = [Person named:@\"jan\"];\n \n abe.prefs = @[ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay ];\n bob.prefs = @[ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay ];\n col.prefs = @[ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan ];\n dan.prefs = @[ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ];\n ed.prefs = @[ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay ];\n fred.prefs = @[ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay ];\n gav.prefs = @[ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay ];\n hal.prefs = @[ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ];\n ian.prefs = @[ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve ];\n jon.prefs = @[ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope ];\n abi.prefs = @[ bob, fred, jon, gav, ian, abe, dan, ed, col, hal ];\n bea.prefs = @[ bob, abe, col, fred, gav, dan, ian, ed, jon, hal ];\n cath.prefs = @[ fred, bob, ed, gav, hal, col, ian, abe, dan, jon ];\n dee.prefs = @[ fred, jon, col, abe, ian, hal, gav, dan, bob, ed ];\n eve.prefs = @[ jon, hal, fred, dan, abe, gav, col, ed, ian, bob ];\n fay.prefs = @[ bob, abe, ed, ian, jon, dan, fred, gav, col, hal ];\n gay.prefs = @[ jon, gav, hal, fred, bob, abe, col, ed, dan, ian ];\n hope.prefs = @[ gav, jon, bob, abe, ian, dan, hal, ed, col, fred ];\n ivy.prefs = @[ ian, col, hal, gav, fred, bob, abe, ed, jon, dan ];\n jan.prefs = @[ ed, hal, gav, abe, bob, jon, col, ian, fred, dan ];\n \n NSArray *men = abi.prefs;\n \n NSUInteger freeMenCount = men.count;\n while (freeMenCount > 0) {\n for (Person *guy in men) {\n if (guy.fiance == nil) {\n Person *gal = [guy nextCandidateNotYetProposedTo];\n if (gal.fiance == nil) {\n [guy engageTo:gal];\n freeMenCount--;\n } else if ([gal prefers:guy]) {\n [guy engageTo:gal];\n }\n }\n }\n }\n \n for (Person *guy in men) {\n printf(\"%s is engaged to %s\\n\", [guy.name UTF8String], [guy.fiance.name UTF8String]);\n }\n printf(\"Stable = %d\\n\", (int)isStable(men));\n\n printf(\"\\nSwitching fred & jon's partners\\n\");\n [fred engageTo:abi];\n [jon engageTo:bea];\n printf(\"Stable = %d\\n\", (int)isStable(men));\n}\n\n\/\/--------------------------------------------------------------------\n\nint main(int argc, const char * argv[])\n{\n @autoreleasepool {\n doMarriage();\n }\n return 0;\n}\n\n\n","human_summarization":"The code implements the Gale-Shapley algorithm to solve the Stable Marriage Problem. It takes as input a list of ten men and ten women along with their ranked preferences for each other. The code generates a stable set of engagements based on these preferences. It then perturbs this stable set to create an unstable set of engagements and checks the stability of this new set.","id":214} {"lang_cluster":"Objective-C","source_code":"\nWorks with: GNUstep only; not Cocoa\nNSString *myString = @\"The quick brown fox jumped over the lazy dog's back\";\nNSData *digest = [[myString dataUsingEncoding:NSUTF8StringEncoding] md5Digest]; \/\/ or another encoding of your choosing\nNSLog(@\"%@\", [digest hexadecimalRepresentation]);\n\nWorks with: iPhone\nWorks with: Mac OS X\n#import \n\nNSString *myString = @\"The quick brown fox jumped over the lazy dog's back\";\nNSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding]; \/\/ or another encoding of your choosing\nunsigned char digest[CC_MD5_DIGEST_LENGTH];\nif (CC_MD5([data bytes], [data length], digest)) {\n NSMutableString *hex = [NSMutableString string];\n for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {\n [hex appendFormat: @\"%02x\", (int)(digest[i])];\n }\n NSLog(@\"%@\", hex);\n}\n\nWorks with: Mac OS X (need to include \"libcrypto.dylib\" framework)\n#include \n\nNSString *myString = @\"The quick brown fox jumped over the lazy dog's back\";\nNSData *data = [myString dataUsingEncoding:NSUTF8StringEncoding]; \/\/ or another encoding of your choosing\nunsigned char digest[MD5_DIGEST_LENGTH];\nif (MD5([data bytes], [data length], digest)) {\n NSMutableString *hex = [NSMutableString string];\n for (int i = 0; i < MD5_DIGEST_LENGTH; i++) {\n [hex appendFormat: @\"%02x\", (int)(digest[i])];\n }\n NSLog(@\"%@\", hex);\n}\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":215} {"lang_cluster":"Objective-C","source_code":"\n\n\/\/ declare the class to conform to NSStreamDelegate protocol\n\n\/\/ in some method\nNSOutputStream *oStream;\n[NSStream getStreamsToHost:[NSHost hostWithName:@\"localhost\"] port:256 inputStream:NULL outputStream:&oStream];\n[oStream setDelegate:self];\n[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];\n[oStream open];\n\n\n\/\/ later, in the same class:\n- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)streamEvent {\n NSOutputStream *oStream = (NSOutputStream *)aStream;\n if (streamEvent == NSStreamEventHasBytesAvailable) {\n NSString *str = @\"hello socket world\";\n const char *rawstring = [str UTF8String];\n [oStream write:rawstring maxLength:strlen(rawstring)];\n [oStream close];\n }\n}\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket. Error handling is not implemented.","id":216} {"lang_cluster":"Objective-C","source_code":"\n\n[[[NSProcessInfo processInfo] environment] objectForKey:@\"HOME\"]\n\n","human_summarization":"demonstrate how to retrieve a specific environment variable from the process's environment using the NSProcessInfo processInfo method in Unix systems. The variables that can be retrieved include PATH, HOME, and USER.","id":217} {"lang_cluster":"Java","source_code":"\n\nimport java.util.Stack;\n\npublic class StackTest {\n public static void main( final String[] args ) {\n final Stack stack = new Stack();\n\n System.out.println( \"New stack empty? \" + stack.empty() );\n\n stack.push( \"There can be only one\" );\n System.out.println( \"Pushed stack empty? \" + stack.empty() );\n System.out.println( \"Popped single entry: \" + stack.pop() );\n\n stack.push( \"First\" );\n stack.push( \"Second\" );\n System.out.println( \"Popped entry should be second: \" + stack.pop() );\n\n \/\/ Popping an empty stack will throw...\n stack.pop();\n stack.pop();\n }\n}\n\n\n","human_summarization":"implement a stack data structure with basic operations such as push (to add an element to the top of the stack), pop (to remove and return the last added element from the stack), and empty (to check if the stack has no elements). The stack follows a Last In, First Out (LIFO) access policy.","id":218} {"lang_cluster":"Java","source_code":"\npublic static long itFibN(int n)\n{\n if (n < 2)\n return n;\n long ans = 0;\n long n1 = 0;\n long n2 = 1;\n for(n--; n > 0; n--)\n {\n ans = n1 + n2;\n n1 = n2;\n n2 = ans;\n }\n return ans;\n}\n\/**\n * O(log(n))\n *\/\npublic static long fib(long n) {\n if (n <= 0)\n\treturn 0;\n\n long i = (int) (n - 1);\n long a = 1, b = 0, c = 0, d = 1, tmp1,tmp2;\n\n while (i > 0) {\n\tif (i\u00a0% 2\u00a0!= 0) {\n tmp1 = d * b + c * a;\n\t tmp2 = d * (b + a) + c * b;\n\t a = tmp1;\n\t b = tmp2;\n\t}\n\n tmp1 = (long) (Math.pow(c, 2) + Math.pow(d, 2));\n tmp2 = d * (2 * c + d);\n\t\t\t\n c = tmp1;\n d = tmp2;\n\n i = i \/ 2;\n }\n return a + b;\n}\npublic static long recFibN(final int n)\n{\n return (n < 2)\u00a0? n\u00a0: recFibN(n - 1) + recFibN(n - 2);\n}\n\npublic class Fibonacci {\n\n static final Map cache = new HashMap<>();\n static {\n cache.put(1, 1L);\n cache.put(2, 1L);\n }\n\n public static long get(int n)\n {\n return (n < 2)\u00a0? n\u00a0: impl(n);\n }\n \n private static long impl(int n)\n {\n return cache.computeIfAbsent(n, k -> impl(k-1) + impl(k-2));\n }\n}\n\npublic static long anFibN(final long n)\n{\n double p = (1 + Math.sqrt(5)) \/ 2;\n double q = 1 \/ p;\n return (long) ((Math.pow(p, n) + Math.pow(q, n)) \/ Math.sqrt(5));\n}\npublic static long fibTailRec(final int n)\n{\n return fibInner(0, 1, n);\n}\n\nprivate static long fibInner(final long a, final long b, final int n)\n{\n return n < 1\u00a0? a\u00a0: n == 1\u00a0? b\u00a0: fibInner(b, a + b, n - 1);\n}\nimport java.util.function.LongUnaryOperator;\nimport java.util.stream.LongStream;\n\npublic class FibUtil {\n public static LongStream fibStream() {\n return LongStream.iterate( 1l, new LongUnaryOperator() {\n private long lastFib = 0;\n @Override public long applyAsLong( long operand ) {\n long ret = operand + lastFib;\n lastFib = operand;\n return ret;\n }\n });\n }\n public static long fib(long n) {\n return fibStream().limit( n ).reduce((prev, last) -> last).getAsLong();\n }\n}\n","human_summarization":"generate the nth Fibonacci number using either an iterative or recursive approach. The recursive method includes a caching mechanism to store previous results, improving time complexity from O(n2) to O(n). The function supports positive Fibonacci sequence, with optional support for negative numbers. However, it can only calculate up to the 92nd Fibonacci number due to range limitations.","id":219} {"lang_cluster":"Java","source_code":"\nint[] array = {1, 2, 3, 4, 5 };\nList evensList = new ArrayList();\nfor (int i: array) {\n if (i % 2 == 0) evensList.add(i);\n}\nint[] evens = evensList.toArray(new int[0]);\n\n\n\npublic static T[] filter(T[] input, Predicate filterMethod) {\n return Arrays.stream(input)\n .filter(filterMethod)\n .toArray(size -> (T[]) Array.newInstance(input.getClass().getComponentType(), size));\n}\n\n\nInteger[] array = {1, 2, 3, 4, 5};\nInteger[] result = filter(array, i -> (i % 2) == 0);\n\n\n","human_summarization":"select specific elements from an array, in this case, all even numbers, and place them into a new array. There's also an alternative solution that modifies the original array instead of creating a new one. The solution is implemented in Java 8 using streams and generic types. However, it doesn't work with primitive types and requires the use of a wrapper class for such arrays.","id":220} {"lang_cluster":"Java","source_code":"\npublic static String Substring(String str, int n, int m){\n return str.substring(n, n+m);\n}\npublic static String Substring(String str, int n){\n return str.substring(n);\n}\npublic static String Substring(String str){\n return str.substring(0, str.length()-1);\n}\npublic static String Substring(String str, char c, int m){\n return str.substring(str.indexOf(c), str.indexOf(c)+m+1);\n}\npublic static String Substring(String str, String sub, int m){\n return str.substring(str.indexOf(sub), str.indexOf(sub)+m+1);\n}\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":221} {"lang_cluster":"Java","source_code":"\n\nString reversed = new StringBuilder(\"as\u20dddf\u0305\").reverse().toString(); \/\/ fd\u20ddsa\nString reversed = new StringBuffer(\"as\u20dddf\u0305\").reverse().toString(); \/\/ fd\u20ddsa\n\nString string = \"as\u20dddf\u0305\";\nStringBuilder reversed = new StringBuilder();\nfor (int index = string.length() - 1; index >= 0; index--)\n reversed.append(string.charAt(index));\nreversed; \/\/ fd\u20ddsa\n\nimport java.text.BreakIterator;\n\npublic class Reverse {\n \/* works with Java 20+ only\n * cf. https:\/\/bugs.openjdk.org\/browse\/JDK-8291660\n *\/\n public static StringBuilder graphemeReverse(String text) {\n BreakIterator boundary = BreakIterator.getCharacterInstance();\n boundary.setText(text);\n StringBuilder reversed = new StringBuilder();\n int end = boundary.last();\n int start = boundary.previous();\n while (start\u00a0!= BreakIterator.DONE) {\n reversed.append(text.substring(start, end));\n end = start;\n start = boundary.previous();\n }\n return reversed;\n }\n public static void main(String[] args) throws Exception {\n String a = \"as\u20dddf\u0305\";\n System.out.println(graphemeReverse(a)); \/\/ f\u0305ds\u20dda\n }\n}\n","human_summarization":"The code takes an input string and returns its reverse. It also handles Unicode combining characters correctly, preserving their order in the reversed string. The code uses either a for-loop, ICU4J, java.util.regex.Pattern.compile(\"\\\\X\") (for JDK 15 and above), or java.text.BreakIterator (for JDK 20 and above) to parse graphemes and reverse them correctly.","id":222} {"lang_cluster":"Java","source_code":"\nimport java.awt.Point;\nimport java.util.Scanner;\n\npublic class PlayfairCipher {\n private static char[][] charTable;\n private static Point[] positions;\n\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n\n String key = prompt(\"Enter an encryption key (min length 6): \", sc, 6);\n String txt = prompt(\"Enter the message: \", sc, 1);\n String jti = prompt(\"Replace J with I? y\/n: \", sc, 1);\n\n boolean changeJtoI = jti.equalsIgnoreCase(\"y\");\n\n createTable(key, changeJtoI);\n\n String enc = encode(prepareText(txt, changeJtoI));\n\n System.out.printf(\"%nEncoded message: %n%s%n\", enc);\n System.out.printf(\"%nDecoded message: %n%s%n\", decode(enc));\n }\n\n private static String prompt(String promptText, Scanner sc, int minLen) {\n String s;\n do {\n System.out.print(promptText);\n s = sc.nextLine().trim();\n } while (s.length() < minLen);\n return s;\n }\n\n private static String prepareText(String s, boolean changeJtoI) {\n s = s.toUpperCase().replaceAll(\"[^A-Z]\", \"\");\n return changeJtoI ? s.replace(\"J\", \"I\") : s.replace(\"Q\", \"\");\n }\n\n private static void createTable(String key, boolean changeJtoI) {\n charTable = new char[5][5];\n positions = new Point[26];\n\n String s = prepareText(key + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", changeJtoI);\n\n int len = s.length();\n for (int i = 0, k = 0; i < len; i++) {\n char c = s.charAt(i);\n if (positions[c - 'A'] == null) {\n charTable[k \/ 5][k % 5] = c;\n positions[c - 'A'] = new Point(k % 5, k \/ 5);\n k++;\n }\n }\n }\n\n private static String encode(String s) {\n StringBuilder sb = new StringBuilder(s);\n\n for (int i = 0; i < sb.length(); i += 2) {\n\n if (i == sb.length() - 1)\n sb.append(sb.length() % 2 == 1 ? 'X' : \"\");\n\n else if (sb.charAt(i) == sb.charAt(i + 1))\n sb.insert(i + 1, 'X');\n }\n return codec(sb, 1);\n }\n\n private static String decode(String s) {\n return codec(new StringBuilder(s), 4);\n }\n\n private static String codec(StringBuilder text, int direction) {\n int len = text.length();\n for (int i = 0; i < len; i += 2) {\n char a = text.charAt(i);\n char b = text.charAt(i + 1);\n\n int row1 = positions[a - 'A'].y;\n int row2 = positions[b - 'A'].y;\n int col1 = positions[a - 'A'].x;\n int col2 = positions[b - 'A'].x;\n\n if (row1 == row2) {\n col1 = (col1 + direction) % 5;\n col2 = (col2 + direction) % 5;\n\n } else if (col1 == col2) {\n row1 = (row1 + direction) % 5;\n row2 = (row2 + direction) % 5;\n\n } else {\n int tmp = col1;\n col1 = col2;\n col2 = tmp;\n }\n\n text.setCharAt(i, charTable[row1][col1]);\n text.setCharAt(i + 1, charTable[row2][col2]);\n }\n return text.toString();\n }\n}\n\nimport java.util.Scanner;\n \npublic class PlayfairCipherEncryption\n{\n private String KeyWord = new String();\n private String Key = new String();\n private char matrix_arr[][] = new char[5][5];\n \n public void setKey(String k)\n {\n String K_adjust = new String();\n boolean flag = false;\n K_adjust = K_adjust + k.charAt(0);\n for (int i = 1; i < k.length(); i++)\n {\n for (int j = 0; j < K_adjust.length(); j++)\n {\n if (k.charAt(i) == K_adjust.charAt(j))\n {\n flag = true;\n }\n }\n if (flag == false)\n K_adjust = K_adjust + k.charAt(i);\n flag = false;\n }\n KeyWord = K_adjust;\n }\n \n public void KeyGen()\n {\n boolean flag = true;\n char current;\n Key = KeyWord;\n for (int i = 0; i < 26; i++)\n {\n current = (char) (i + 97);\n if (current == 'j')\n continue;\n for (int j = 0; j < KeyWord.length(); j++)\n {\n if (current == KeyWord.charAt(j))\n {\n flag = false;\n break;\n }\n }\n if (flag)\n Key = Key + current;\n flag = true;\n }\n System.out.println(Key);\n matrix();\n }\n \n private void matrix()\n {\n int counter = 0;\n for (int i = 0; i < 5; i++)\n {\n for (int j = 0; j < 5; j++)\n {\n matrix_arr[i][j] = Key.charAt(counter);\n System.out.print(matrix_arr[i][j] + \" \");\n counter++;\n }\n System.out.println();\n }\n }\n \n private String format(String old_text)\n {\n int i = 0;\n int len = 0;\n String text = new String();\n len = old_text.length();\n for (int tmp = 0; tmp < len; tmp++)\n {\n if (old_text.charAt(tmp) == 'j')\n {\n text = text + 'i';\n }\n else\n text = text + old_text.charAt(tmp);\n }\n len = text.length();\n for (i = 0; i < len; i = i + 2)\n {\n if (text.charAt(i + 1) == text.charAt(i))\n {\n text = text.substring(0, i + 1) + 'x' + text.substring(i + 1);\n }\n }\n return text;\n }\n \n private String[] Divid2Pairs(String new_string)\n {\n String Original = format(new_string);\n int size = Original.length();\n if (size % 2 != 0)\n {\n size++;\n Original = Original + 'x';\n }\n String x[] = new String[size \/ 2];\n int counter = 0;\n for (int i = 0; i < size \/ 2; i++)\n {\n x[i] = Original.substring(counter, counter + 2);\n counter = counter + 2;\n }\n return x;\n }\n \n public int[] GetDiminsions(char letter)\n {\n int[] key = new int[2];\n if (letter == 'j')\n letter = 'i';\n for (int i = 0; i < 5; i++)\n {\n for (int j = 0; j < 5; j++)\n {\n if (matrix_arr[i][j] == letter)\n {\n key[0] = i;\n key[1] = j;\n break;\n }\n }\n }\n return key;\n }\n \n public String encryptMessage(String Source)\n {\n String src_arr[] = Divid2Pairs(Source);\n String Code = new String();\n char one;\n char two;\n int part1[] = new int[2];\n int part2[] = new int[2];\n for (int i = 0; i < src_arr.length; i++)\n {\n one = src_arr[i].charAt(0);\n two = src_arr[i].charAt(1);\n part1 = GetDiminsions(one);\n part2 = GetDiminsions(two);\n if (part1[0] == part2[0])\n {\n if (part1[1] < 4)\n part1[1]++;\n else\n part1[1] = 0;\n if (part2[1] < 4)\n part2[1]++;\n else\n part2[1] = 0;\n }\n else if (part1[1] == part2[1])\n {\n if (part1[0] < 4)\n part1[0]++;\n else\n part1[0] = 0;\n if (part2[0] < 4)\n part2[0]++;\n else\n part2[0] = 0;\n }\n else\n {\n int temp = part1[1];\n part1[1] = part2[1];\n part2[1] = temp;\n }\n Code = Code + matrix_arr[part1[0]][part1[1]]\n + matrix_arr[part2[0]][part2[1]];\n }\n return Code;\n }\n \n public static void main(String[] args)\n {\n PlayfairCipherEncryption x = new PlayfairCipherEncryption();\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter a keyword:\");\n String keyword = sc.next();\n x.setKey(keyword);\n x.KeyGen();\n System.out\n .println(\"Enter word to encrypt: (Make sure length of message is even)\");\n String key_input = sc.next();\n if (key_input.length() % 2 == 0)\n {\n System.out.println(\"Encryption: \" + x.encryptMessage(key_input));\n }\n else\n {\n System.out.println(\"Message length should be even\");\n }\n sc.close();\n }\n}\n\n","human_summarization":"Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.","id":223} {"lang_cluster":"Java","source_code":"\n\nimport java.io.*;\nimport java.util.*;\n\npublic class Dijkstra {\n private static final Graph.Edge[] GRAPH = {\n new Graph.Edge(\"a\", \"b\", 7),\n new Graph.Edge(\"a\", \"c\", 9),\n new Graph.Edge(\"a\", \"f\", 14),\n new Graph.Edge(\"b\", \"c\", 10),\n new Graph.Edge(\"b\", \"d\", 15),\n new Graph.Edge(\"c\", \"d\", 11),\n new Graph.Edge(\"c\", \"f\", 2),\n new Graph.Edge(\"d\", \"e\", 6),\n new Graph.Edge(\"e\", \"f\", 9),\n };\n private static final String START = \"a\";\n private static final String END = \"e\";\n \n public static void main(String[] args) {\n Graph g = new Graph(GRAPH);\n g.dijkstra(START);\n g.printPath(END);\n \/\/g.printAllPaths();\n }\n}\n\nclass Graph {\n private final Map graph; \/\/ mapping of vertex names to Vertex objects, built from a set of Edges\n \n \/** One edge of the graph (only used by Graph constructor) *\/\n public static class Edge {\n public final String v1, v2;\n public final int dist;\n public Edge(String v1, String v2, int dist) {\n this.v1 = v1;\n this.v2 = v2;\n this.dist = dist;\n }\n }\n \n \/** One vertex of the graph, complete with mappings to neighbouring vertices *\/\n public static class Vertex implements Comparable{\n\tpublic final String name;\n\tpublic int dist = Integer.MAX_VALUE; \/\/ MAX_VALUE assumed to be infinity\n\tpublic Vertex previous = null;\n\tpublic final Map neighbours = new HashMap<>();\n\n\tpublic Vertex(String name)\n\t{\n\t\tthis.name = name;\n\t}\n\n\tprivate void printPath()\n\t{\n\t\tif (this == this.previous)\n\t\t{\n\t\t\tSystem.out.printf(\"%s\", this.name);\n\t\t}\n\t\telse if (this.previous == null)\n\t\t{\n\t\t\tSystem.out.printf(\"%s(unreached)\", this.name);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.previous.printPath();\n\t\t\tSystem.out.printf(\" -> %s(%d)\", this.name, this.dist);\n\t\t}\n\t}\n\n\tpublic int compareTo(Vertex other)\n\t{\n\t\tif (dist == other.dist)\n\t\t\treturn name.compareTo(other.name);\n\n\t\treturn Integer.compare(dist, other.dist);\n\t}\n\n\t@Override public String toString()\n\t{\n\t\treturn \"(\" + name + \", \" + dist + \")\";\n\t}\n}\n \n \/** Builds a graph from a set of edges *\/\n public Graph(Edge[] edges) {\n graph = new HashMap<>(edges.length);\n \n \/\/one pass to find all vertices\n for (Edge e : edges) {\n if (!graph.containsKey(e.v1)) graph.put(e.v1, new Vertex(e.v1));\n if (!graph.containsKey(e.v2)) graph.put(e.v2, new Vertex(e.v2));\n }\n \n \/\/another pass to set neighbouring vertices\n for (Edge e : edges) {\n graph.get(e.v1).neighbours.put(graph.get(e.v2), e.dist);\n \/\/graph.get(e.v2).neighbours.put(graph.get(e.v1), e.dist); \/\/ also do this for an undirected graph\n }\n }\n \n \/** Runs dijkstra using a specified source vertex *\/ \n public void dijkstra(String startName) {\n if (!graph.containsKey(startName)) {\n System.err.printf(\"Graph doesn't contain start vertex \\\"%s\\\"\\n\", startName);\n return;\n }\n final Vertex source = graph.get(startName);\n NavigableSet q = new TreeSet<>();\n \n \/\/ set-up vertices\n for (Vertex v : graph.values()) {\n v.previous = v == source ? source : null;\n v.dist = v == source ? 0 : Integer.MAX_VALUE;\n q.add(v);\n }\n \n dijkstra(q);\n }\n \n \/** Implementation of dijkstra's algorithm using a binary heap. *\/\n private void dijkstra(final NavigableSet q) { \n Vertex u, v;\n while (!q.isEmpty()) {\n \n u = q.pollFirst(); \/\/ vertex with shortest distance (first iteration will return source)\n if (u.dist == Integer.MAX_VALUE) break; \/\/ we can ignore u (and any other remaining vertices) since they are unreachable\n \n \/\/look at distances to each neighbour\n for (Map.Entry a : u.neighbours.entrySet()) {\n v = a.getKey(); \/\/the neighbour in this iteration\n \n final int alternateDist = u.dist + a.getValue();\n if (alternateDist < v.dist) { \/\/ shorter path to neighbour found\n q.remove(v);\n v.dist = alternateDist;\n v.previous = u;\n q.add(v);\n } \n }\n }\n }\n \n \/** Prints a path from the source to the specified vertex *\/\n public void printPath(String endName) {\n if (!graph.containsKey(endName)) {\n System.err.printf(\"Graph doesn't contain end vertex \\\"%s\\\"\\n\", endName);\n return;\n }\n \n graph.get(endName).printPath();\n System.out.println();\n }\n \/** Prints the path from the source to every vertex (output order is not guaranteed) *\/\n public void printAllPaths() {\n for (Vertex v : graph.values()) {\n v.printPath();\n System.out.println();\n }\n }\n}\n\n","human_summarization":"Implement Dijkstra's algorithm to find the shortest path from a source node to all other reachable nodes in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges that depict the shortest path to each destination node. The algorithm is tested with a directed graph starting at node 'a', and the shortest path from node 'a' to nodes 'e' and 'f' is determined. The vertices can be identified by either numbers or names. The algorithm's performance is optimized by storing vertices in a TreeSet for efficient removal of any element.","id":224} {"lang_cluster":"Java","source_code":"\n\npublic class AVLtree {\n\n private Node root;\n\n private static class Node {\n private int key;\n private int balance;\n private int height;\n private Node left;\n private Node right;\n private Node parent;\n\n Node(int key, Node parent) {\n this.key = key;\n this.parent = parent;\n }\n }\n\n public boolean insert(int key) {\n if (root == null) {\n root = new Node(key, null);\n return true;\n }\n\n Node n = root;\n while (true) {\n if (n.key == key)\n return false;\n\n Node parent = n;\n\n boolean goLeft = n.key > key;\n n = goLeft ? n.left : n.right;\n\n if (n == null) {\n if (goLeft) {\n parent.left = new Node(key, parent);\n } else {\n parent.right = new Node(key, parent);\n }\n rebalance(parent);\n break;\n }\n }\n return true;\n }\n\n private void delete(Node node) {\n if (node.left == null && node.right == null) {\n if (node.parent == null) {\n root = null;\n } else {\n Node parent = node.parent;\n if (parent.left == node) {\n parent.left = null;\n } else {\n parent.right = null;\n }\n rebalance(parent);\n }\n return;\n }\n\n if (node.left != null) {\n Node child = node.left;\n while (child.right != null) child = child.right;\n node.key = child.key;\n delete(child);\n } else {\n Node child = node.right;\n while (child.left != null) child = child.left;\n node.key = child.key;\n delete(child);\n }\n }\n\n public void delete(int delKey) {\n if (root == null)\n return;\n\n Node child = root;\n while (child != null) {\n Node node = child;\n child = delKey >= node.key ? node.right : node.left;\n if (delKey == node.key) {\n delete(node);\n return;\n }\n }\n }\n\n private void rebalance(Node n) {\n setBalance(n);\n\n if (n.balance == -2) {\n if (height(n.left.left) >= height(n.left.right))\n n = rotateRight(n);\n else\n n = rotateLeftThenRight(n);\n\n } else if (n.balance == 2) {\n if (height(n.right.right) >= height(n.right.left))\n n = rotateLeft(n);\n else\n n = rotateRightThenLeft(n);\n }\n\n if (n.parent != null) {\n rebalance(n.parent);\n } else {\n root = n;\n }\n }\n\n private Node rotateLeft(Node a) {\n\n Node b = a.right;\n b.parent = a.parent;\n\n a.right = b.left;\n\n if (a.right != null)\n a.right.parent = a;\n\n b.left = a;\n a.parent = b;\n\n if (b.parent != null) {\n if (b.parent.right == a) {\n b.parent.right = b;\n } else {\n b.parent.left = b;\n }\n }\n\n setBalance(a, b);\n\n return b;\n }\n\n private Node rotateRight(Node a) {\n\n Node b = a.left;\n b.parent = a.parent;\n\n a.left = b.right;\n\n if (a.left != null)\n a.left.parent = a;\n\n b.right = a;\n a.parent = b;\n\n if (b.parent != null) {\n if (b.parent.right == a) {\n b.parent.right = b;\n } else {\n b.parent.left = b;\n }\n }\n\n setBalance(a, b);\n\n return b;\n }\n\n private Node rotateLeftThenRight(Node n) {\n n.left = rotateLeft(n.left);\n return rotateRight(n);\n }\n\n private Node rotateRightThenLeft(Node n) {\n n.right = rotateRight(n.right);\n return rotateLeft(n);\n }\n\n private int height(Node n) {\n if (n == null)\n return -1;\n return n.height;\n }\n\n private void setBalance(Node... nodes) {\n for (Node n : nodes) {\n reheight(n);\n n.balance = height(n.right) - height(n.left);\n }\n }\n\n public void printBalance() {\n printBalance(root);\n }\n\n private void printBalance(Node n) {\n if (n != null) {\n printBalance(n.left);\n System.out.printf(\"%s \", n.balance);\n printBalance(n.right);\n }\n }\n\n private void reheight(Node node) {\n if (node != null) {\n node.height = 1 + Math.max(height(node.left), height(node.right));\n }\n }\n\n public static void main(String[] args) {\n AVLtree tree = new AVLtree();\n\n System.out.println(\"Inserting values 1 to 10\");\n for (int i = 1; i < 10; i++)\n tree.insert(i);\n\n System.out.print(\"Printing balance: \");\n tree.printBalance();\n }\n}\n\nInserting values 1 to 10\nPrinting balance: 0 0 0 1 0 1 0 0 0\n\n","human_summarization":"Implement an AVL tree with basic operations. The AVL tree is a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The tree rebalances itself after each insertion or deletion to maintain this property. The basic operations including lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree is compared to red-black trees in terms of operations and time complexity.","id":225} {"lang_cluster":"Java","source_code":"import java.util.Objects;\n\npublic class Circles {\n private static class Point {\n private final double x, y;\n\n public Point(Double x, Double y) {\n this.x = x;\n this.y = y;\n }\n\n public double distanceFrom(Point other) {\n double dx = x - other.x;\n double dy = y - other.y;\n return Math.sqrt(dx * dx + dy * dy);\n }\n\n @Override\n public boolean equals(Object other) {\n if (this == other) return true;\n if (other == null || getClass() != other.getClass()) return false;\n Point point = (Point) other;\n return x == point.x && y == point.y;\n }\n\n @Override\n public String toString() {\n return String.format(\"(%.4f,\u00a0%.4f)\", x, y);\n }\n }\n\n private static Point[] findCircles(Point p1, Point p2, double r) {\n if (r < 0.0) throw new IllegalArgumentException(\"the radius can't be negative\");\n if (r == 0.0 && p1 != p2) throw new IllegalArgumentException(\"no circles can ever be drawn\");\n if (r == 0.0) return new Point[]{p1, p1};\n if (Objects.equals(p1, p2)) throw new IllegalArgumentException(\"an infinite number of circles can be drawn\");\n double distance = p1.distanceFrom(p2);\n double diameter = 2.0 * r;\n if (distance > diameter) throw new IllegalArgumentException(\"the points are too far apart to draw a circle\");\n Point center = new Point((p1.x + p2.x) \/ 2.0, (p1.y + p2.y) \/ 2.0);\n if (distance == diameter) return new Point[]{center, center};\n double mirrorDistance = Math.sqrt(r * r - distance * distance \/ 4.0);\n double dx = (p2.x - p1.x) * mirrorDistance \/ distance;\n double dy = (p2.y - p1.y) * mirrorDistance \/ distance;\n return new Point[]{\n new Point(center.x - dy, center.y + dx),\n new Point(center.x + dy, center.y - dx)\n };\n }\n\n public static void main(String[] args) {\n Point[] p = new Point[]{\n new Point(0.1234, 0.9876),\n new Point(0.8765, 0.2345),\n new Point(0.0000, 2.0000),\n new Point(0.0000, 0.0000)\n };\n Point[][] points = new Point[][]{\n {p[0], p[1]},\n {p[2], p[3]},\n {p[0], p[0]},\n {p[0], p[1]},\n {p[0], p[0]},\n };\n double[] radii = new double[]{2.0, 1.0, 2.0, 0.5, 0.0};\n for (int i = 0; i < radii.length; ++i) {\n Point p1 = points[i][0];\n Point p2 = points[i][1];\n double r = radii[i];\n System.out.printf(\"For points %s and %s with radius %f\\n\", p1, p2, r);\n try {\n Point[] circles = findCircles(p1, p2, r);\n Point c1 = circles[0];\n Point c2 = circles[1];\n if (Objects.equals(c1, c2)) {\n System.out.printf(\"there is just one circle with center at %s\\n\", c1);\n } else {\n System.out.printf(\"there are two circles with centers at %s and %s\\n\", c1, c2);\n }\n } catch (IllegalArgumentException ex) {\n System.out.println(ex.getMessage());\n }\n System.out.println();\n }\n }\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":226} {"lang_cluster":"Java","source_code":"\nimport java.util.Random;\n\nRandom rand = new Random();\nwhile(true){\n int a = rand.nextInt(20);\n System.out.println(a);\n if(a == 10) break;\n int b = rand.nextInt(20);\n System.out.println(b);\n}\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":227} {"lang_cluster":"Java","source_code":"\nimport java.math.BigInteger;\n\nclass MersenneFactorCheck\n{\n\n private final static BigInteger TWO = BigInteger.valueOf(2);\n \n public static boolean isPrime(long n)\n {\n if (n == 2)\n return true;\n if ((n < 2) || ((n & 1) == 0))\n return false;\n long maxFactor = (long)Math.sqrt((double)n);\n for (long possibleFactor = 3; possibleFactor <= maxFactor; possibleFactor += 2)\n if ((n % possibleFactor) == 0)\n return false;\n return true;\n }\n \n public static BigInteger findFactorMersenneNumber(int primeP)\n {\n if (primeP <= 0)\n throw new IllegalArgumentException();\n BigInteger bigP = BigInteger.valueOf(primeP);\n BigInteger m = BigInteger.ONE.shiftLeft(primeP).subtract(BigInteger.ONE);\n \/\/ There are more complicated ways of getting closer to sqrt(), but not that important here, so go with simple\n BigInteger maxFactor = BigInteger.ONE.shiftLeft((primeP + 1) >>> 1);\n BigInteger twoP = BigInteger.valueOf(primeP << 1);\n BigInteger possibleFactor = BigInteger.ONE;\n int possibleFactorBits12 = 0;\n int twoPBits12 = primeP & 3;\n \n while ((possibleFactor = possibleFactor.add(twoP)).compareTo(maxFactor) <= 0)\n {\n possibleFactorBits12 = (possibleFactorBits12 + twoPBits12) & 3;\n \/\/ \"Furthermore, q must be 1 or 7 mod 8\". We know it's odd due to the +1 done above, so bit 0 is set. Therefore, we only care about bits 1 and 2 equaling 00 or 11\n if ((possibleFactorBits12 == 0) || (possibleFactorBits12 == 3))\n if (TWO.modPow(bigP, possibleFactor).equals(BigInteger.ONE))\n return possibleFactor;\n }\n return null;\n }\n \n public static void checkMersenneNumber(int p)\n {\n if (!isPrime(p))\n {\n System.out.println(\"M\" + p + \" is not prime\");\n return;\n }\n BigInteger factor = findFactorMersenneNumber(p);\n if (factor == null)\n System.out.println(\"M\" + p + \" is prime\");\n else\n System.out.println(\"M\" + p + \" is not prime, has factor \" + factor);\n return;\n }\n\n public static void main(String[] args)\n {\n for (int p = 1; p <= 50; p++)\n checkMersenneNumber(p);\n checkMersenneNumber(929);\n return;\n }\n \n}\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":228} {"lang_cluster":"Java","source_code":"\nimport java.io.StringReader;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.xpath.XPath;\nimport javax.xml.xpath.XPathConstants;\nimport javax.xml.xpath.XPathFactory;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\nimport org.xml.sax.InputSource;\n\npublic class XMLParser {\n\tfinal static String xmlStr = \n\t\t\t \"\"\n\t\t\t+ \"
\"\n\t\t\t+ \" \"\n\t\t\t+ \" Invisibility Cream<\/name>\"\n\t\t\t+ \" 14.50<\/price>\"\n\t\t\t+ \" Makes you invisible<\/description>\"\n\t\t\t+ \" <\/item>\"\n\t\t\t+ \" \"\n\t\t\t+ \" Levitation Salve<\/name>\"\n\t\t\t+ \" 23.99<\/price>\"\n\t\t\t+ \" Levitate yourself for up to 3 hours per application<\/description>\"\n\t\t\t+ \" <\/item>\"\n\t\t\t+ \" <\/section>\"\n\t\t\t+ \"
\"\n\t\t\t+ \" \"\n\t\t\t+ \" Blork and Freen Instameal<\/name>\"\n\t\t\t+ \" 4.95<\/price>\"\n\t\t\t+ \" A tasty meal in a tablet; just add water<\/description>\"\n\t\t\t+ \" <\/item>\"\n\t\t\t+ \" \"\n\t\t\t+ \" Grob winglets<\/name>\"\n\t\t\t+ \" 3.56<\/price>\"\n\t\t\t+ \" Tender winglets of Grob. Just add priwater<\/description>\"\n\t\t\t+ \" <\/item>\"\n\t\t\t+ \" <\/section>\" \n\t\t\t+ \"<\/inventory>\";\n\n\tpublic static void main(String[] args) {\n\t\ttry {\n\t\t\tDocument doc = DocumentBuilderFactory.newInstance()\n\t\t\t\t\t.newDocumentBuilder()\n\t\t\t\t\t.parse(new InputSource(new StringReader(xmlStr)));\n\t\t\tXPath xpath = XPathFactory.newInstance().newXPath();\n\t\t\t\/\/ 1\n\t\t\tSystem.out.println(((Node) xpath.evaluate(\n\t\t\t\t\t\"\/inventory\/section\/item[1]\", doc, XPathConstants.NODE))\n\t\t\t\t\t.getAttributes().getNamedItem(\"upc\"));\n\t\t\t\/\/ 2, 3\n\t\t\tNodeList nodes = (NodeList) xpath.evaluate(\n\t\t\t\t\t\"\/inventory\/section\/item\/price\", doc,\n\t\t\t\t\tXPathConstants.NODESET);\n\t\t\tfor (int i = 0; i < nodes.getLength(); i++)\n\t\t\t\tSystem.out.println(nodes.item(i).getTextContent());\n\t\t} catch (Exception e) {\n\t\t\tSystem.out.println(\"Error ocurred while parsing XML.\");\n\t\t}\n\t}\n}\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":229} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 7+\n\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Set;\nimport java.util.TreeSet;\n\npublic class Sets {\n public static void main(String[] args){\n Set a = new TreeSet<>();\n \/\/TreeSet sorts on natural ordering (or an optional comparator)\n \/\/other options: HashSet (hashcode)\n \/\/ LinkedHashSet (insertion order)\n \/\/ EnumSet (optimized for enum values)\n \/\/others at: http:\/\/download.oracle.com\/javase\/7\/docs\/api\/java\/util\/Set.html\n Set b = new TreeSet<>();\n Set c = new TreeSet<>();\n Set d = new TreeSet<>();\n \n a.addAll(Arrays.asList(1, 2, 3, 4, 5));\n b.addAll(Arrays.asList(2, 3, 4, 5, 6, 8));\n c.addAll(Arrays.asList(2, 3, 4));\n d.addAll(Arrays.asList(2, 3, 4));\n System.out.println(\"a: \" + a);\n System.out.println(\"b: \" + b);\n System.out.println(\"c: \" + c);\n System.out.println(\"d: \" + d);\n \n System.out.println(\"2 in a: \" + a.contains(2));\n System.out.println(\"6 in a: \" + a.contains(6));\n \n Set ab = new TreeSet<>();\n ab.addAll(a);\n ab.addAll(b);\n System.out.println(\"a union b: \" + ab);\n \n Set a_b = new TreeSet<>();\n a_b.addAll(a);\n a_b.removeAll(b);\n System.out.println(\"a - b: \" + a_b);\n \n System.out.println(\"c subset of a: \" + a.containsAll(c));\n \/\/use a.conatins() for single elements\n \n System.out.println(\"c = d: \" + c.equals(d));\n System.out.println(\"d = c: \" + d.equals(c));\n \n Set aib = new TreeSet<>();\n aib.addAll(a);\n aib.retainAll(b);\n System.out.println(\"a intersect b: \" + aib);\n \n System.out.println(\"add 7 to a: \" + a.add(7));\n System.out.println(\"add 2 to a again: \" + a.add(2));\n \n \/\/other noteworthy things related to sets:\n Set empty = Collections.EMPTY_SET; \/\/immutable empty set\n \/\/empty.add(2); would fail\n empty.isEmpty(); \/\/test if a set is empty\n empty.size();\n Collections.disjoint(a, b); \/\/returns true if the sets have no common elems (based on their .equals() methods)\n Collections.unmodifiableSet(a); \/\/returns an immutable copy of a\n }\n}\n\n\n","human_summarization":"The code implements various set operations including set creation, checking if an element is part of a set, union, intersection, difference, subset, and equality of two sets. It also optionally demonstrates other set operations and methods to modify a mutable set. The set can be implemented using an associative array, a binary search tree, a hash table, or an ordered array of binary bits. The code also provides the time complexity for the basic test operation. The code is compatible with Java 5 by replacing \"<>\" with \"\".","id":230} {"lang_cluster":"Java","source_code":"\nimport static java.util.Calendar.*;\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\n\npublic class Yuletide{\n\tpublic static void main(String[] args) {\n\t\tCalendar calendar;\n int count = 1;\n for (int year = 2008; year <= 2121; year++) {\n calendar = new GregorianCalendar(year, DECEMBER, 25);\n if (calendar.get(DAY_OF_WEEK) == SUNDAY) {\n if (count != 1)\n System.out.print(\", \");\n System.out.printf(\"%d\", calendar.get(YEAR));\n count++;\n }\n }\n\t}\n}\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":231} {"lang_cluster":"Java","source_code":"\n\nimport Jama.Matrix;\nimport Jama.QRDecomposition;\n\npublic class Decompose {\n public static void main(String[] args) {\n var matrix = new Matrix(new double[][] {\n {12, -51, 4},\n { 6, 167, -68},\n {-4, 24, -41},\n });\n\n var qr = new QRDecomposition(matrix);\n qr.getQ().print(10, 4);\n qr.getR().print(10, 4);\n }\n}\n\n\n","human_summarization":"The code performs QR decomposition on a given matrix using the method of Householder reflections. It decomposes the matrix into a product of an orthogonal matrix and an upper triangular matrix. The code also demonstrates the usage of QR decomposition for solving linear least squares problems. It includes steps to handle cases where the matrix is not square by cutting off zero-padded bottom rows. The solution is then obtained by back substitution. The code is compatible with various libraries such as JAMA, Colt, Apache Commons Math, and la4j.","id":232} {"lang_cluster":"Java","source_code":"\n\nimport java.util.ArrayList;\nimport java.util.Iterator;\nimport java.util.LinkedHashSet;\nimport java.util.List;\nimport java.util.Set;\n\n\nint[] removeDuplicates(int[] values) {\n \/* use a LinkedHashSet to preserve order *\/\n Set set = new LinkedHashSet<>();\n for (int value : values)\n set.add(value);\n values = new int[set.size()];\n Iterator iterator = set.iterator();\n int index = 0;\n while (iterator.hasNext())\n values[index++] = iterator.next();\n return values;\n}\n\n\nint[] removeDuplicates(int[] values) {\n List list = new ArrayList<>();\n for (int value : values)\n if (!list.contains(value)) list.add(value);\n values = new int[list.size()];\n int index = 0;\n for (int value : list)\n values[index++] = value;\n return values;\n}\n\n[2, 1, 4, 1, 1, 3, 1, 3, 1, 4, 3, 2, 3, 4, 3, 2, 2, 3, 3, 3]\n[2, 1, 4, 3]\n\n[2, 4, 1, 4, 1, 4, 3, 1, 1, 3, 4, 4, 4, 4, 2, 1, 1, 2, 3, 2]\n[2, 4, 1, 3]\n\n\nWorks with: Java version 1.5\nimport java.util.*;\n\nclass Test {\n\n public static void main(String[] args) {\n\n Object[] data = {1, 1, 2, 2, 3, 3, 3, \"a\", \"a\", \"b\", \"b\", \"c\", \"d\"};\n Set uniqueSet = new HashSet(Arrays.asList(data));\n for (Object o : uniqueSet)\n System.out.printf(\"%s \", o);\n }\n}\n\n1 a 2 b 3 c d\nWorks with: Java version 8\nimport java.util.*;\n\nclass Test {\n\n public static void main(String[] args) {\n\n Object[] data = {1, 1, 2, 2, 3, 3, 3, \"a\", \"a\", \"b\", \"b\", \"c\", \"d\"};\n Arrays.stream(data).distinct().forEach((o) -> System.out.printf(\"%s \", o));\n }\n}\n\n1 2 3 a b c d\n","human_summarization":"\"Implement methods to remove duplicate elements from an array. This can be achieved through three approaches: using a hash table, sorting elements and removing consecutive duplicates, or iterating through the list and discarding any repeating elements. The code also includes an alternative method of adding values to a Set object or a mutable List for uniqueness.\"","id":233} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+public static > List quickSort(List arr) {\n if (arr.isEmpty())\n return arr;\n else {\n E pivot = arr.get(0);\n\n List less = new LinkedList();\n List pivotList = new LinkedList();\n List more = new LinkedList();\n\n \/\/ Partition\n for (E i: arr) {\n if (i.compareTo(pivot) < 0)\n less.add(i);\n else if (i.compareTo(pivot) > 0)\n more.add(i);\n else\n pivotList.add(i);\n }\n\n \/\/ Recursively sort sublists\n less = quickSort(less);\n more = quickSort(more);\n\n \/\/ Concatenate results\n less.addAll(pivotList);\n less.addAll(more);\n return less;\n }\n}\n\nWorks with: Java version 1.8\npublic static > List sort(List col) {\n if (col == null || col.isEmpty())\n return Collections.emptyList();\n else {\n E pivot = col.get(0);\n Map> grouped = col.stream()\n .collect(Collectors.groupingBy(pivot::compareTo));\n return Stream.of(sort(grouped.get(1)), grouped.get(0), sort(grouped.get(-1)))\n .flatMap(Collection::stream).collect(Collectors.toList());\n }\n}\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":234} {"lang_cluster":"Java","source_code":"\npublic static void main(String[] args) {\n long millis = System.currentTimeMillis();\n System.out.printf(\"%tF%n\", millis);\n System.out.printf(\"%tA, %1$tB %1$td, %1$tY%n\", millis);\n}\n\n2023-05-10\nWednesday, May 10, 2023\n\n\nimport java.util.Calendar;\nimport java.util.GregorianCalendar;\nimport java.text.DateFormatSymbols;\nimport java.text.DateFormat;\npublic class Dates{\n public static void main(String[] args){\n Calendar now = new GregorianCalendar(); \/\/months are 0 indexed, dates are 1 indexed\n DateFormatSymbols symbols = new DateFormatSymbols(); \/\/names for our months and weekdays\n\n \/\/plain numbers way\n System.out.println(now.get(Calendar.YEAR) + \"-\" + (now.get(Calendar.MONTH) + 1) + \"-\" + now.get(Calendar.DATE));\n\n \/\/words way\n System.out.print(symbols.getWeekdays()[now.get(Calendar.DAY_OF_WEEK)] + \", \");\n System.out.print(symbols.getMonths()[now.get(Calendar.MONTH)] + \" \");\n System.out.println(now.get(Calendar.DATE) + \", \" + now.get(Calendar.YEAR));\n }\n}\n\n\nimport java.time.LocalDate;\nimport java.time.format.DateTimeFormatter;\npublic class Dates\n{\n public static void main(final String[] args)\n {\n \/\/using DateTimeFormatter\n LocalDate date = LocalDate.now();\n DateTimeFormatter dtFormatter = DateTimeFormatter.ofPattern(\"yyyy MM dd\");\n\n System.out.println(dtFormatter.format(date));\n }\n}\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\npublic class DateFormat {\n public static void main(String[]args){\n SimpleDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd\");\n SimpleDateFormat formatLong = new SimpleDateFormat(\"EEEE, MMMM dd, yyyy\");\n System.out.println(format.format(new Date()));\n System.out.println(formatLong.format(new Date()));\n }\n}\n\n","human_summarization":"display the current date in the formats \"2007-11-23\" and \"Friday, November 23, 2007\". An alternate demonstration uses the ThreeTen library.","id":235} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\n\npublic static ArrayList getpowerset(int a[],int n,ArrayList ps)\n {\n if(n<0)\n {\n return null;\n }\n if(n==0)\n {\n if(ps==null)\n ps=new ArrayList();\n ps.add(\" \");\n return ps;\n }\n ps=getpowerset(a, n-1, ps);\n ArrayList tmp=new ArrayList();\n for(String s:ps)\n {\n if(s.equals(\" \"))\n tmp.add(\"\"+a[n-1]);\n else\n tmp.add(s+a[n-1]);\n }\n ps.addAll(tmp);\n return ps;\n }\n\n\npublic static List> powerset(Collection list) {\n List> ps = new ArrayList>();\n ps.add(new ArrayList()); \/\/ add the empty set\n\n \/\/ for every item in the original list\n for (T item : list) {\n List> newPs = new ArrayList>();\n\n for (List subset : ps) {\n \/\/ copy all of the current powerset's subsets\n newPs.add(subset);\n\n \/\/ plus the subsets appended with the current item\n List newSubset = new ArrayList(subset);\n newSubset.add(item);\n newPs.add(newSubset);\n }\n\n \/\/ powerset is now powerset of list.subList(0, list.indexOf(item)+1)\n ps = newPs;\n }\n return ps;\n}\n\n\npublic static > LinkedList> BinPowSet(\n\t\tLinkedList A){\n\tLinkedList> ans= new LinkedList>();\n\tint ansSize = (int)Math.pow(2, A.size());\n\tfor(int i= 0;i< ansSize;++i){\n\t\tString bin= Integer.toBinaryString(i); \/\/convert to binary\n\t\twhile(bin.length() < A.size()) bin = \"0\" + bin; \/\/pad with 0's\n\t\tLinkedList thisComb = new LinkedList(); \/\/place to put one combination\n\t\tfor(int j= 0;j< A.size();++j){\n\t\t\tif(bin.charAt(j) == '1')thisComb.add(A.get(j));\n\t\t}\n\t\tCollections.sort(thisComb); \/\/sort it for easy checking\n\t\tans.add(thisComb); \/\/put this set in the answer list\n\t}\n\treturn ans;\n}\n\n","human_summarization":"The code defines a function that takes a set as input and generates its power set. The power set includes all possible subsets of the input set, including the empty set and the set itself. The function can handle edge cases like an empty set and a set containing only the empty set. It uses a binary string representation to determine the inclusion of each element in the original set for each subset. The code preserves the input and does not sort the entire list of subsets.","id":236} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\npublic class RN {\n\n enum Numeral {\n I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);\n int weight;\n\n Numeral(int weight) {\n this.weight = weight;\n }\n };\n\n public static String roman(long n) {\n \n if( n <= 0) {\n throw new IllegalArgumentException();\n }\n \n StringBuilder buf = new StringBuilder();\n\n final Numeral[] values = Numeral.values();\n for (int i = values.length - 1; i >= 0; i--) {\n while (n >= values[i].weight) {\n buf.append(values[i]);\n n -= values[i].weight;\n }\n }\n return buf.toString();\n }\n\n public static void test(long n) {\n System.out.println(n + \" = \" + roman(n));\n }\n\n public static void main(String[] args) {\n test(1999);\n test(25);\n test(944);\n test(0);\n }\n\n}\n\n\n","human_summarization":"The code defines a function that converts a positive integer into its equivalent Roman numeral representation. It expresses each digit separately, starting from the leftmost digit and ignoring any digit with a value of zero. For example, it converts 1990 to MCMXC, 2008 to MMVIII, and 1666 to MDCLXVI. The function throws an IllegalArgumentException for non-positive numbers.","id":237} {"lang_cluster":"Java","source_code":"\n\nString[] strings;\nint[] values;\n\nString strings[];\nint values[];\n\nString[] strings = new String[] { \"rosetta\", \"code\" };\nint[] values = new int[] { 1, 2, 3 };\nString[] strings;\nstrings = new String[] { \"rosetta\", \"code\" };\nint[] values;\nvalues = new int[] { 1, 2, 3 };\n\nString[] strings = new String[2];\nint[] values = new int[3];\n\nString string = strings[0];\nint value = values[2];\n\nString[] strings = new String[2];\nstrings[0] = \"rosetta\";\nstrings[1] = \"code\";\nString string = strings[0] + \" \" + strings[1];\n\nrosetta code\n\n\nint[] values = new int[10];\nArrays.fill(values, 100);\n\nArrays.toString(values);\n\n[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]\n\nList strings;\nList values;\n\nList strings = new ArrayList<>();\nList values = new ArrayList<>();\n\nstrings.add(\"rosetta\");\nstrings.add(\"code\");\nvalues.add(1);\nvalues.add(2);\nvalues.add(3);\n\nstrings.add(\"code\");\nstrings.add(0, \"rosetta\");\n\nstrings.set(0, \"ROSETTA\");\nstrings.set(1, \"CODE\");\n\nDeque strings = new ArrayDeque<>();\n\nstrings.push(\"code\");\nstrings.push(\"rosetta\");\n\nstrings.pop();\n","human_summarization":"demonstrate how to create, assign values to, and retrieve elements from both fixed-length and dynamic arrays in Java. The codes show how to use square brackets for array declaration and initialization, and how to access elements using indices. The codes also illustrate the use of the Arrays class for array-related operations such as filling an array with a specified value and printing array contents. Additionally, the codes demonstrate the use of dynamic, mutable arrays under the Java Collections Framework List and Deque interfaces, specifically using ArrayList and ArrayDeque. The codes show how to add and mutate elements in these dynamic arrays, and how to use a LIFO operation pattern with ArrayDeque.","id":238} {"lang_cluster":"Java","source_code":"\nWorks with: GCJ version 4.1.2\n\nimport java.io.*;\n\npublic class FileIODemo {\n public static void main(String[] args) {\n try {\n FileInputStream in = new FileInputStream(\"input.txt\");\n FileOutputStream out = new FileOutputStream(\"ouput.txt\");\n int c;\n while ((c = in.read()) != -1) {\n out.write(c);\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e){\n e.printStackTrace();\n }\n }\n}\n\n\nimport java.io.*;\n\npublic class FileIODemo2 {\n public static void main(String args[]) {\n try {\n \/\/ Probably should wrap with a BufferedInputStream\n final InputStream in = new FileInputStream(\"input.txt\");\n try {\n \/\/ Probably should wrap with a BufferedOutputStream\n final OutputStream out = new FileOutputStream(\"output.txt\");\n try {\n int c;\n while ((c = in.read()) != -1) {\n out.write(c);\n }\n }\n finally {\n out.close();\n }\n }\n finally {\n in.close();\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e){\n e.printStackTrace();\n }\n }\n}\n\nWorks with: Java version 1.4\n\nimport java.io.*;\nimport java.nio.channels.*;\n\npublic class FileIODemo3 {\n public static void main(String args[]) {\n try {\n final FileChannel in = new FileInputStream(\"input.txt\").getChannel();\n try {\n final FileChannel out = new FileOutputStream(\"output.txt\").getChannel();\n try {\n out.transferFrom(in, 0, in.size());\n }\n finally {\n out.close();\n }\n }\n finally {\n in.close();\n }\n }\n catch (Exception e) {\n System.err.println(\"Exception while trying to copy: \"+e);\n e.printStackTrace(); \/\/ stack trace of place where it happened\n }\n }\n}\n\n\nimport java.io.*;\npublic class Test {\n public static void main (String[] args) throws IOException {\n BufferedReader br = new BufferedReader(new FileReader(\"input.txt\"));\n BufferedWriter bw = new BufferedWriter(new FileWriter(\"output.txt\"));\n String line;\n while ((line = br.readLine()) != null) {\n bw.write(line);\n bw.newLine();\n }\n br.close();\n bw.close();\n }\n}\n\nWorks with: Java version 7+\nimport java.nio.file.*;\npublic class Copy{\n public static void main(String[] args) throws Exception{\n FileSystem fs = FileSystems.getDefault();\n Path in = fs.getPath(\"input.txt\");\n Path out = fs.getPath(\"output.txt\");\n Files.copy(in, out, StandardCopyOption.REPLACE_EXISTING);\n }\n}\n\n","human_summarization":"The code reads the contents of \"input.txt\" file into an intermediate variable, then writes the contents of this variable into a new file called \"output.txt\". It demonstrates file reading and writing operations in Java, handling any errors by throwing them to the console. It also ensures both files are closed after operations, without relying on the operating system.","id":239} {"lang_cluster":"Java","source_code":"\n\nString string = \"alphaBETA\".toUpperCase();\n\nString string = \"alphaBETA\".toLowerCase();\n\n\nString str = \"alphaBETA\";\nSystem.out.println(str.toUpperCase());\nSystem.out.println(str.toLowerCase());\n\/\/Also works with non-English characters with no modification\nSystem.out.println(\"\u00e4\u00e0\u00e2\u00e1\u00e7\u00f1\u00df\u00e6\u03b5\u0431\u1ebf\".toUpperCase());\nSystem.out.println(\"\u00c4\u00c0\u00c2\u00c1\u00c7\u00d1SS\u00c6\u0395\u0411\u1ebe\".toLowerCase()); \/\/does not transalate \"SS\" to \"\u00df\"\n\n\n","human_summarization":"demonstrate the conversion of a string \"alphaBETA\" to upper-case and lower-case using the default encoding. It also shows additional case conversion functions if available in the language library. If not, a swapCase method can be created using Character.isLowerCase(), Character.isUpperCase(), and Character.isLetter() functions.","id":240} {"lang_cluster":"Java","source_code":"\n\nimport java.util.*;\n\npublic class ClosestPair\n{\n public static class Point\n {\n public final double x;\n public final double y;\n \n public Point(double x, double y)\n {\n this.x = x;\n this.y = y;\n }\n \n public String toString()\n { return \"(\" + x + \", \" + y + \")\"; }\n }\n \n public static class Pair\n {\n public Point point1 = null;\n public Point point2 = null;\n public double distance = 0.0;\n \n public Pair()\n { }\n \n public Pair(Point point1, Point point2)\n {\n this.point1 = point1;\n this.point2 = point2;\n calcDistance();\n }\n \n public void update(Point point1, Point point2, double distance)\n {\n this.point1 = point1;\n this.point2 = point2;\n this.distance = distance;\n }\n \n public void calcDistance()\n { this.distance = distance(point1, point2); }\n \n public String toString()\n { return point1 + \"-\" + point2 + \"\u00a0: \" + distance; }\n }\n \n public static double distance(Point p1, Point p2)\n {\n double xdist = p2.x - p1.x;\n double ydist = p2.y - p1.y;\n return Math.hypot(xdist, ydist);\n }\n \n public static Pair bruteForce(List points)\n {\n int numPoints = points.size();\n if (numPoints < 2)\n return null;\n Pair pair = new Pair(points.get(0), points.get(1));\n if (numPoints > 2)\n {\n for (int i = 0; i < numPoints - 1; i++)\n {\n Point point1 = points.get(i);\n for (int j = i + 1; j < numPoints; j++)\n {\n Point point2 = points.get(j);\n double distance = distance(point1, point2);\n if (distance < pair.distance)\n pair.update(point1, point2, distance);\n }\n }\n }\n return pair;\n }\n \n public static void sortByX(List points)\n {\n Collections.sort(points, new Comparator() {\n public int compare(Point point1, Point point2)\n {\n if (point1.x < point2.x)\n return -1;\n if (point1.x > point2.x)\n return 1;\n return 0;\n }\n }\n );\n }\n \n public static void sortByY(List points)\n {\n Collections.sort(points, new Comparator() {\n public int compare(Point point1, Point point2)\n {\n if (point1.y < point2.y)\n return -1;\n if (point1.y > point2.y)\n return 1;\n return 0;\n }\n }\n );\n }\n \n public static Pair divideAndConquer(List points)\n {\n List pointsSortedByX = new ArrayList(points);\n sortByX(pointsSortedByX);\n List pointsSortedByY = new ArrayList(points);\n sortByY(pointsSortedByY);\n return divideAndConquer(pointsSortedByX, pointsSortedByY);\n }\n \n private static Pair divideAndConquer(List pointsSortedByX, List pointsSortedByY)\n {\n int numPoints = pointsSortedByX.size();\n if (numPoints <= 3)\n return bruteForce(pointsSortedByX);\n \n int dividingIndex = numPoints >>> 1;\n List leftOfCenter = pointsSortedByX.subList(0, dividingIndex);\n List rightOfCenter = pointsSortedByX.subList(dividingIndex, numPoints);\n \n List tempList = new ArrayList(leftOfCenter);\n sortByY(tempList);\n Pair closestPair = divideAndConquer(leftOfCenter, tempList);\n \n tempList.clear();\n tempList.addAll(rightOfCenter);\n sortByY(tempList);\n Pair closestPairRight = divideAndConquer(rightOfCenter, tempList);\n \n if (closestPairRight.distance < closestPair.distance)\n closestPair = closestPairRight;\n \n tempList.clear();\n double shortestDistance =closestPair.distance;\n double centerX = rightOfCenter.get(0).x;\n for (Point point : pointsSortedByY)\n if (Math.abs(centerX - point.x) < shortestDistance)\n tempList.add(point);\n \n for (int i = 0; i < tempList.size() - 1; i++)\n {\n Point point1 = tempList.get(i);\n for (int j = i + 1; j < tempList.size(); j++)\n {\n Point point2 = tempList.get(j);\n if ((point2.y - point1.y) >= shortestDistance)\n break;\n double distance = distance(point1, point2);\n if (distance < closestPair.distance)\n {\n closestPair.update(point1, point2, distance);\n shortestDistance = distance;\n }\n }\n }\n return closestPair;\n }\n \n public static void main(String[] args)\n {\n int numPoints = (args.length == 0) ? 1000 : Integer.parseInt(args[0]);\n List points = new ArrayList();\n Random r = new Random();\n for (int i = 0; i < numPoints; i++)\n points.add(new Point(r.nextDouble(), r.nextDouble()));\n System.out.println(\"Generated \" + numPoints + \" random points\");\n long startTime = System.currentTimeMillis();\n Pair bruteForceClosestPair = bruteForce(points);\n long elapsedTime = System.currentTimeMillis() - startTime;\n System.out.println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair);\n startTime = System.currentTimeMillis();\n Pair dqClosestPair = divideAndConquer(points);\n elapsedTime = System.currentTimeMillis() - startTime;\n System.out.println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair);\n if (bruteForceClosestPair.distance != dqClosestPair.distance)\n System.out.println(\"MISMATCH\");\n }\n}\n\n\n","human_summarization":"implement two methods to solve the Closest Pair of Points problem in a two-dimensional space. The first method is a brute-force approach with a time complexity of O(n^2), which finds the closest pair by comparing the distance between every pair of points. The second method is a more efficient divide-and-conquer approach with a time complexity of O(n log n), which sorts the points by x and y coordinates, then recursively divides the problem into smaller parts until it is solvable by the brute-force algorithm.","id":241} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\n\nList arrayList = new ArrayList();\narrayList.add(new Integer(0));\n\/\/ alternative with primitive autoboxed to an Integer object automatically\narrayList.add(0); \n\n\/\/other features of ArrayList\n\/\/define the type in the arraylist, you can substitute a proprietary class in the \"<>\"\nList myarrlist = new ArrayList();\n\n\/\/add several values to the arraylist to be summed later\nint sum;\nfor(int i = 0; i < 10; i++) {\n myarrlist.add(i);\n}\n\n\/\/loop through myarrlist to sum each entry\nfor ( i = 0; i < myarrlist.size(); i++) {\n sum += myarrlist.get(i);\n}\n\n\nfor(int i : myarrlist) {\n sum += i;\n}\n\n\/\/remove the last entry in the ArrayList\nmyarrlist.remove(myarrlist.size()-1)\n\n\/\/clear the ArrayList\nmyarrlist.clear();\n\n\n\n\nCollection class\n\nrandom access\n\norder\n\niterator direction\n\n\nHashMap\n\nby key\n\nhash\n\nforward (separate iterators for entries, keys and values)\n\n\nTreeMap\n\nby key\n\nascending(key)\n\nforward (separate iterators for entries, keys and values)\n\n\nLinkedHashMap\n\nby key\n\ninsertion\n\nforward (separate iterators for entries, keys and values)\n\n\nLinkedList\n\nby index\n\ninsertion\/to index\n\nboth\n\n\nArrayList\n\nby index\n\ninsertion\/to index (ArrayList also has a defined but expandable size)\n\nboth\n\n\nHashSet\n\nonly remove (returns the element that was removed)\n\nhash\n\nforward\n\n\nTreeSet\n\nonly remove (returns the element that was removed)\n\nascending(element)\n\nforward\n\nThe Scala libraries are valid Java byte-code libraries. The collection part of these are rich because the multiple inheritance by traits. E.g. an ArrayBuffer has properties inherent of 9 traits such as Buffer[A], IndexedSeqOptimized[A, ArrayBuffer[A]], Builder[A, ArrayBuffer[A]], ResizableArray[A] and Serializable. Another collection e.g. TrieMap uses some of these and other added traits. A TrieMap -a hashmap- is the most advanced of all. It supports parallel processing without blocking.import scala.Tuple2;\nimport scala.collection.concurrent.TrieMap;\nimport scala.collection.immutable.HashSet;\nimport scala.collection.mutable.ArrayBuffer;\n\npublic class Collections {\n\n\tpublic static void main(String[] args) {\n\t\tArrayBuffer myarrlist = new ArrayBuffer();\n\t\tArrayBuffer myarrlist2 = new ArrayBuffer(20);\n\n\t\tmyarrlist.$plus$eq(new Integer(42)); \/\/ $plus$eq is Scala += operator\n\t\tmyarrlist.$plus$eq(13); \/\/ to add an element.\n\t\tmyarrlist.$plus$eq(-1);\n\n\t\tmyarrlist2 = (ArrayBuffer) myarrlist2.$minus(-1);\n\n\t\tfor (int i = 0; i < 10; i++)\n\t\t\tmyarrlist2.$plus$eq(i);\n\n\t\t\/\/ loop through myarrlist to sum each entry\n\t\tint sum = 0;\n\t\tfor (int i = 0; i < myarrlist2.size(); i++) {\n\t\t\tsum += myarrlist2.apply(i);\n\t\t}\n\t\tSystem.out.println(\"List is: \" + myarrlist2 + \" with head: \"\n\t\t\t\t+ myarrlist2.head() + \" sum is: \" + sum);\n\t\tSystem.out.println(\"Third element is: \" + myarrlist2.apply$mcII$sp(2));\n\n\t\tTuple2 tuple = new Tuple2(\"US\",\n\t\t\t\t\"Washington\");\n\t\tSystem.out.println(\"Tuple2 is\u00a0: \" + tuple);\n\n\t\tArrayBuffer> capList = new ArrayBuffer>();\n\t\tcapList.$plus$eq(new Tuple2(\"US\", \"Washington\"));\n\t\tcapList.$plus$eq(new Tuple2(\"France\", \"Paris\"));\n\t\tSystem.out.println(capList);\n\n\t\tTrieMap trieMap = new TrieMap();\n\t\ttrieMap.put(\"US\", \"Washington\");\n\t\ttrieMap.put(\"France\", \"Paris\");\n\n\t\tHashSet set = new HashSet();\n\n\t\tArrayBuffer> capBuffer = new ArrayBuffer>();\n\t\ttrieMap.put(\"US\", \"Washington\");\n\n\t\tSystem.out.println(trieMap);\n\t}\n}\n\n","human_summarization":"The code creates a collection and adds a few values to it. It demonstrates good practice in Java by using a List variable type and a List subclass for the new object. This allows for easy type changes and ensures compatibility with all methods. The code does not use any methods specific to the List type chosen. It also provides a reference table for characteristics of commonly used Collections classes.","id":242} {"lang_cluster":"Java","source_code":"\n\npackage hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.text.*;\n\npublic class UnboundedKnapsack {\n\n protected Item [] items = {\n new Item(\"panacea\", 3000, 0.3, 0.025),\n new Item(\"ichor\" , 1800, 0.2, 0.015),\n new Item(\"gold\" , 2500, 2.0, 0.002)\n };\n protected final int n = items.length; \/\/ the number of items\n protected Item sack = new Item(\"sack\" , 0, 25.0, 0.250);\n protected Item best = new Item(\"best\" , 0, 0.0, 0.000);\n protected int [] maxIt = new int [n]; \/\/ maximum number of items\n protected int [] iIt = new int [n]; \/\/ current indexes of items\n protected int [] bestAm = new int [n]; \/\/ best amounts\n\n public UnboundedKnapsack() {\n \/\/ initializing:\n for (int i = 0; i < n; i++) {\n maxIt [i] = Math.min(\n (int)(sack.getWeight() \/ items[i].getWeight()),\n (int)(sack.getVolume() \/ items[i].getVolume())\n );\n } \/\/ for (i)\n\n \/\/ calc the solution:\n calcWithRecursion(0);\n\n \/\/ Print out the solution:\n NumberFormat nf = NumberFormat.getInstance();\n System.out.println(\"Maximum value achievable is: \" + best.getValue());\n System.out.print(\"This is achieved by carrying (one solution): \");\n for (int i = 0; i < n; i++) {\n System.out.print(bestAm[i] + \" \" + items[i].getName() + \", \");\n }\n System.out.println();\n System.out.println(\"The weight to carry is: \" + nf.format(best.getWeight()) +\n \" and the volume used is: \" + nf.format(best.getVolume())\n );\n\n }\n\n \/\/ calculation the solution with recursion method\n \/\/ item\u00a0: the number of item in the \"items\" array\n public void calcWithRecursion(int item) {\n for (int i = 0; i <= maxIt[item]; i++) {\n iIt[item] = i;\n if (item < n-1) {\n calcWithRecursion(item+1);\n } else {\n int currVal = 0; \/\/ current value\n double currWei = 0.0; \/\/ current weight\n double currVol = 0.0; \/\/ current Volume\n for (int j = 0; j < n; j++) {\n currVal += iIt[j] * items[j].getValue();\n currWei += iIt[j] * items[j].getWeight();\n currVol += iIt[j] * items[j].getVolume();\n }\n\n if (currVal > best.getValue()\n &&\n currWei <= sack.getWeight()\n &&\n currVol <= sack.getVolume()\n )\n {\n best.setValue (currVal);\n best.setWeight(currWei);\n best.setVolume(currVol);\n for (int j = 0; j < n; j++) bestAm[j] = iIt[j];\n } \/\/ if (...)\n } \/\/ else\n } \/\/ for (i)\n } \/\/ calcWithRecursion()\n\n \/\/ the main() function:\n public static void main(String[] args) {\n new UnboundedKnapsack();\n } \/\/ main()\n\n} \/\/ class\n\npackage hu.pj.obj;\n\npublic class Item {\n protected String name = \"\";\n protected int value = 0;\n protected double weight = 0;\n protected double volume = 0;\n\n public Item() {\n }\n\n public Item(String name, int value, double weight, double volume) {\n setName(name);\n setValue(value);\n setWeight(weight);\n setVolume(volume);\n }\n\n public int getValue() {\n return value;\n }\n\n public void setValue(int value) {\n this.value = Math.max(value, 0);\n }\n\n public double getWeight() {\n return weight;\n }\n\n public void setWeight(double weight) {\n this.weight = Math.max(weight, 0);\n }\n\n public double getVolume() {\n return volume;\n }\n\n public void setVolume(double volume) {\n this.volume = Math.max(volume, 0);\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n} \/\/ class\n\n\nMaximum value achievable is: 54500\nThis is achieved by carrying (one solution): 0 panacea, 15 ichor, 11 gold, \nThe weight to carry is: 25 and the volume used is: 0,247\n","human_summarization":"The code calculates the maximum value the traveler can carry in his knapsack by selecting whole units of available items (panacea, ichor, gold) considering their weight, volume and value. It uses recursion to find the optimal combination of items. Only one of the four possible optimal solutions is returned.","id":243} {"lang_cluster":"Java","source_code":"\npublic static void main(String[] args) {\n for (int i = 1; ; i++) {\n System.out.print(i);\n if (i == 10)\n break;\n System.out.print(\", \");\n }\n System.out.println();\n}\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":244} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 7\nimport java.util.*;\n\npublic class TopologicalSort {\n\n public static void main(String[] args) {\n String s = \"std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05,\"\n + \"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys\";\n\n Graph g = new Graph(s, new int[][]{\n {2, 0}, {2, 14}, {2, 13}, {2, 4}, {2, 3}, {2, 12}, {2, 1},\n {3, 1}, {3, 10}, {3, 11},\n {4, 1}, {4, 10},\n {5, 0}, {5, 14}, {5, 10}, {5, 4}, {5, 3}, {5, 1}, {5, 11},\n {6, 1}, {6, 3}, {6, 10}, {6, 11},\n {7, 1}, {7, 10},\n {8, 1}, {8, 10},\n {9, 1}, {9, 10},\n {10, 1},\n {11, 1},\n {12, 0}, {12, 1},\n {13, 1}\n });\n\n System.out.println(\"Topologically sorted order: \");\n System.out.println(g.topoSort());\n }\n}\n\nclass Graph {\n String[] vertices;\n boolean[][] adjacency;\n int numVertices;\n\n public Graph(String s, int[][] edges) {\n vertices = s.split(\",\");\n numVertices = vertices.length;\n adjacency = new boolean[numVertices][numVertices];\n\n for (int[] edge : edges)\n adjacency[edge[0]][edge[1]] = true;\n }\n\n List topoSort() {\n List result = new ArrayList<>();\n List todo = new LinkedList<>();\n\n for (int i = 0; i < numVertices; i++)\n todo.add(i);\n\n try {\n outer:\n while (!todo.isEmpty()) {\n for (Integer r : todo) {\n if (!hasDependency(r, todo)) {\n todo.remove(r);\n result.add(vertices[r]);\n \/\/ no need to worry about concurrent modification\n continue outer;\n }\n }\n throw new Exception(\"Graph has cycles\");\n }\n } catch (Exception e) {\n System.out.println(e);\n return null;\n }\n return result;\n }\n\n boolean hasDependency(Integer r, List todo) {\n for (Integer c : todo) {\n if (adjacency[r][c])\n return true;\n }\n return false;\n }\n}\n\n[std, ieee, dware, dw02, dw05, dw06, dw07, gtech, dw01, dw04, ramlib, std_cell_lib, synopsys, des_system_lib, dw03]\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":245} {"lang_cluster":"Java","source_code":"\n\nString string = \"string matching\";\nString suffix = \"ing\";\n\n\nstring.startsWith(suffix)\n\n\nstring.substring(0, suffix.length()).equals(suffix)\n\n\nstring.contains(suffix)\n\n\nstring.indexOf(suffix) != -1\n\n\nstring.endsWith(suffix);\n\n\nstring.substring(string.length() - suffix.length()).equals(suffix)\n\n\nint indexOf;\nint offset = 0;\nwhile ((indexOf = string.indexOf(suffix, offset)) != -1) {\n System.out.printf(\"'%s' @ %d to %d%n\", suffix, indexOf, indexOf + suffix.length() - 1);\n offset = indexOf + 1;\n}\n\n'ing' @ 3 to 5\n'ing' @ 12 to 14\n\n\n\"abcd\".startsWith(\"ab\") \/\/returns true\n\"abcd\".endsWith(\"zn\") \/\/returns false\n\"abab\".contains(\"bb\") \/\/returns false\n\"abab\".contains(\"ab\") \/\/returns true\nint loc = \"abab\".indexOf(\"bb\") \/\/returns -1\nloc = \"abab\".indexOf(\"ab\") \/\/returns 0\nloc = \"abab\".indexOf(\"ab\",loc+1) \/\/returns 2\n\npublic class JavaApplication6 {\n public static void main(String[] args) {\n String strOne = \"complexity\";\n String strTwo = \"udacity\";\n stringMatch(strOne, strTwo);\n }\n\n public static void stringMatch(String one, String two) {\n boolean match = false;\n if (one.charAt(0) == two.charAt(0)) {\n System.out.println(match = true); \/\/ returns true\n } else {\n System.out.println(match); \/\/ returns false\n }\n for (int i = 0; i < two.length(); i++) { \n int temp = i;\n for (int x = 0; x < one.length(); x++) {\n if (two.charAt(temp) == one.charAt(x)) {\n System.out.println(match = true); \/\/returns true\n i = two.length();\n }\n }\n }\n int num1 = one.length() - 1;\n int num2 = two.length() - 1;\n if (one.charAt(num1) == two.charAt(num2)) {\n System.out.println(match = true);\n } else {\n System.out.println(match = false);\n }\n }\n}\n\n","human_summarization":"The code performs three types of string matching operations: checking if the first string starts with the second string, checking if the first string contains the second string at any location, and checking if the first string ends with the second string. It uses methods like String.startsWith, String.contains, and String.endsWith for these operations. Additionally, it prints the location of the match and handles multiple occurrences of a string.","id":246} {"lang_cluster":"Java","source_code":"\n\nimport java.util.Arrays;\n\npublic class FourSquares {\n public static void main(String[] args) {\n fourSquare(1, 7, true, true);\n fourSquare(3, 9, true, true);\n fourSquare(0, 9, false, false);\n }\n\n private static void fourSquare(int low, int high, boolean unique, boolean print) {\n int count = 0;\n\n if (print) {\n System.out.println(\"a b c d e f g\");\n }\n for (int a = low; a <= high; ++a) {\n for (int b = low; b <= high; ++b) {\n if (notValid(unique, a, b)) continue;\n\n int fp = a + b;\n for (int c = low; c <= high; ++c) {\n if (notValid(unique, c, a, b)) continue;\n for (int d = low; d <= high; ++d) {\n if (notValid(unique, d, a, b, c)) continue;\n if (fp != b + c + d) continue;\n\n for (int e = low; e <= high; ++e) {\n if (notValid(unique, e, a, b, c, d)) continue;\n for (int f = low; f <= high; ++f) {\n if (notValid(unique, f, a, b, c, d, e)) continue;\n if (fp != d + e + f) continue;\n\n for (int g = low; g <= high; ++g) {\n if (notValid(unique, g, a, b, c, d, e, f)) continue;\n if (fp != f + g) continue;\n\n ++count;\n if (print) {\n System.out.printf(\"%d %d %d %d %d %d %d%n\", a, b, c, d, e, f, g);\n }\n }\n }\n }\n }\n }\n }\n }\n if (unique) {\n System.out.printf(\"There are %d unique solutions in [%d, %d]%n\", count, low, high);\n } else {\n System.out.printf(\"There are %d non-unique solutions in [%d, %d]%n\", count, low, high);\n }\n }\n\n private static boolean notValid(boolean unique, int needle, int... haystack) {\n return unique && Arrays.stream(haystack).anyMatch(p -> p == needle);\n }\n}\n\n\n","human_summarization":"The code replaces the letters a through g with decimal digits ranging from a low to a high value. It finds all possible combinations where the sum of the digits in each of the four squares is equal. It displays all unique solutions for the ranges 1-7 and 3-9, and the total number of solutions for the range 0-9, where digits can be repeated. The code uses Java 8 features.","id":247} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 8\nimport java.awt.*;\nimport java.awt.event.*;\nimport static java.lang.Math.*;\nimport java.time.LocalTime;\nimport javax.swing.*;\n\nclass Clock extends JPanel {\n\n final float degrees06 = (float) (PI \/ 30);\n final float degrees30 = degrees06 * 5;\n final float degrees90 = degrees30 * 3;\n\n final int size = 590;\n final int spacing = 40;\n final int diameter = size - 2 * spacing;\n final int cx = diameter \/ 2 + spacing;\n final int cy = diameter \/ 2 + spacing;\n\n public Clock() {\n setPreferredSize(new Dimension(size, size));\n setBackground(Color.white);\n\n new Timer(1000, (ActionEvent e) -> {\n repaint();\n }).start();\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n drawFace(g);\n\n final LocalTime time = LocalTime.now();\n int hour = time.getHour();\n int minute = time.getMinute();\n int second = time.getSecond();\n\n float angle = degrees90 - (degrees06 * second);\n drawHand(g, angle, diameter \/ 2 - 30, Color.red);\n\n float minsecs = (minute + second \/ 60.0F);\n angle = degrees90 - (degrees06 * minsecs);\n drawHand(g, angle, diameter \/ 3 + 10, Color.black);\n\n float hourmins = (hour + minsecs \/ 60.0F);\n angle = degrees90 - (degrees30 * hourmins);\n drawHand(g, angle, diameter \/ 4 + 10, Color.black);\n }\n\n private void drawFace(Graphics2D g) {\n g.setStroke(new BasicStroke(2));\n g.setColor(Color.white);\n g.fillOval(spacing, spacing, diameter, diameter);\n g.setColor(Color.black);\n g.drawOval(spacing, spacing, diameter, diameter);\n }\n\n private void drawHand(Graphics2D g, float angle, int radius, Color color) {\n int x = cx + (int) (radius * cos(angle));\n int y = cy - (int) (radius * sin(angle));\n g.setColor(color);\n g.drawLine(cx, cy, x, y);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Clock\");\n f.setResizable(false);\n f.add(new Clock(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}\n\n","human_summarization":"illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.","id":248} {"lang_cluster":"Java","source_code":"\nBrute force[edit]Theoretically, this can go \"forever\", but it takes a while, so only the minimum is shown. Luckily, BigInteger has a GCD method built in.\nimport java.math.BigInteger;\nimport static java.math.BigInteger.ONE;\n\npublic class PythTrip{\n\n public static void main(String[] args){\n long tripCount = 0, primCount = 0;\n\n \/\/change this to whatever perimeter limit you want;the RAM's the limit\n BigInteger periLimit = BigInteger.valueOf(100),\n peri2 = periLimit.divide(BigInteger.valueOf(2)),\n peri3 = periLimit.divide(BigInteger.valueOf(3));\n\n for(BigInteger a = ONE; a.compareTo(peri3) < 0; a = a.add(ONE)){\n BigInteger aa = a.multiply(a);\n \n for(BigInteger b = a.add(ONE);\n b.compareTo(peri2) < 0; b = b.add(ONE)){\n BigInteger bb = b.multiply(b);\n BigInteger ab = a.add(b);\n BigInteger aabb = aa.add(bb);\n \n for(BigInteger c = b.add(ONE);\n c.compareTo(peri2) < 0; c = c.add(ONE)){\n\n int compare = aabb.compareTo(c.multiply(c));\n \/\/if a+b+c > periLimit\n if(ab.add(c).compareTo(periLimit) > 0){\n break;\n }\n \/\/if a^2 + b^2\u00a0!= c^2\n if(compare < 0){\n break;\n }else if (compare == 0){\n tripCount++;\n System.out.print(a + \", \" + b + \", \" + c);\n\n \/\/does binary GCD under the hood\n if(a.gcd(b).equals(ONE)){\n System.out.print(\" primitive\");\n primCount++;\n }\n System.out.println();\n }\n }\n }\n }\n System.out.println(\"Up to a perimeter of \" + periLimit + \", there are \"\n + tripCount + \" triples, of which \" + primCount + \" are primitive.\");\n }\n}\n\n\n3, 4, 5 primitive\n5, 12, 13 primitive\n6, 8, 10\n7, 24, 25 primitive\n8, 15, 17 primitive\n9, 12, 15\n9, 40, 41 primitive\n10, 24, 26\n12, 16, 20\n12, 35, 37 primitive\n15, 20, 25\n15, 36, 39\n16, 30, 34\n18, 24, 30\n20, 21, 29 primitive\n21, 28, 35\n24, 32, 40\nUp to a perimeter of 100, there are 17 triples, of which 7 are primitive.\nWorks with: Java version 1.5+\n\nimport java.math.BigInteger;\n\npublic class Triples{\n public static BigInteger LIMIT;\n public static final BigInteger TWO = BigInteger.valueOf(2);\n public static final BigInteger THREE = BigInteger.valueOf(3);\n public static final BigInteger FOUR = BigInteger.valueOf(4);\n public static final BigInteger FIVE = BigInteger.valueOf(5);\n public static long primCount = 0;\n public static long tripCount = 0;\n\n \/\/I don't know Japanese :p\n public static void parChild(BigInteger a, BigInteger b, BigInteger c){\n BigInteger perim = a.add(b).add(c);\n if(perim.compareTo(LIMIT) > 0) return;\n primCount++; tripCount += LIMIT.divide(perim).longValue();\n BigInteger a2 = TWO.multiply(a), b2 = TWO.multiply(b), c2 = TWO.multiply(c),\n c3 = THREE.multiply(c);\n parChild(a.subtract(b2).add(c2),\n a2.subtract(b).add(c2),\n a2.subtract(b2).add(c3));\n parChild(a.add(b2).add(c2),\n a2.add(b).add(c2),\n a2.add(b2).add(c3));\n parChild(a.negate().add(b2).add(c2),\n a2.negate().add(b).add(c2),\n a2.negate().add(b2).add(c3));\n }\n\n public static void main(String[] args){\n for(long i = 100; i <= 10000000; i*=10){\n LIMIT = BigInteger.valueOf(i);\n primCount = tripCount = 0;\n parChild(THREE, FOUR, FIVE);\n System.out.println(LIMIT + \": \" + tripCount + \" triples, \" + primCount + \" primitive.\");\n }\n }\n}\n\n\n100: 17 triples, 7 primitive.\n1000: 325 triples, 70 primitive.\n10000: 4858 triples, 703 primitive.\n100000: 64741 triples, 7026 primitive.\n1000000: 808950 triples, 70229 primitive.\n10000000: 9706567 triples, 702309 primitive.\n","human_summarization":"The code calculates the number of Pythagorean triples (sets of three positive integers a, b, and c where a < b < c and a^2 + b^2 = c^2) with a perimeter no larger than 100. It also counts how many of these triples are primitive, meaning the numbers are co-prime. The code is also designed to handle large values, up to a maximum perimeter of 100,000,000.","id":249} {"lang_cluster":"Java","source_code":"\nLibrary: Swing\nimport javax.swing.JFrame;\n\npublic class Main {\n public static void main(String[] args) throws Exception {\n JFrame w = new JFrame(\"Title\");\n w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n w.setSize(800,600);\n w.setVisible(true);\n }\n}\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":250} {"lang_cluster":"Java","source_code":"\n\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic static void main(String[] args) throws IOException {\n Map frequencies = frequencies(\"src\/LetterFrequency.java\");\n System.out.println(print(frequencies));\n}\n\nstatic String print(Map frequencies) {\n StringBuilder string = new StringBuilder();\n int key;\n for (Map.Entry entry : frequencies.entrySet()) {\n key = entry.getKey();\n string.append(\"%,-8d\".formatted(entry.getValue()));\n \/* display the hexadecimal value for non-printable characters *\/\n if ((key >= 0 && key < 32) || key == 127) {\n string.append(\"%02x%n\".formatted(key));\n } else {\n string.append(\"%s%n\".formatted((char) key));\n }\n }\n return string.toString();\n}\n\nstatic Map frequencies(String path) throws IOException {\n try (InputStreamReader reader = new InputStreamReader(new FileInputStream(path))) {\n \/* key = character, and value = occurrences *\/\n Map map = new HashMap<>();\n int value;\n while ((value = reader.read()) != -1) {\n if (map.containsKey(value)) {\n map.put(value, map.get(value) + 1);\n } else {\n map.put(value, 1);\n }\n }\n return map;\n }\n}\n\n44 0a\n463 \n1 \u00a0!\n8 \"\n5 \u00a0%\n2 &\n33 (\n33 )\n4 *\n1 +\n9 ,\n3 -\n29 .\n5 \/\n2 0\n4 1\n3 2\n1 3\n1 7\n1 8\n1 \u00a0:\n19 \u00a0;\n7 <\n12 =\n7 >\n2 B\n4 E\n4 F\n2 H\n18 I\n2 K\n2 L\n8 M\n3 O\n3 R\n13 S\n1 V\n1 [\n1 ]\n73 a\n3 b\n28 c\n19 d\n121 e\n13 f\n25 g\n11 h\n53 i\n6 j\n8 k\n25 l\n22 m\n67 n\n24 o\n44 p\n8 q\n81 r\n30 s\n87 t\n34 u\n15 v\n7 w\n5 x\n20 y\n11 {\n2 |\n11 }\n\n\nWorks with: Java version 5+\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\n\npublic class LetterFreq {\n\tpublic static int[] countLetters(String filename) throws IOException{\n\t\tint[] freqs = new int[26];\n\t\tBufferedReader in = new BufferedReader(new FileReader(filename));\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tin.close();\n\t\treturn freqs;\n\t}\n\t\n\tpublic static void main(String[] args) throws IOException{\n\t\tSystem.out.println(Arrays.toString(countLetters(\"filename.txt\")));\n\t}\n}\n\nWorks with: Java version 7+\n\npublic static int[] countLetters(String filename) throws IOException{\n\tint[] freqs = new int[26];\n\ttry(BufferedReader in = new BufferedReader(new FileReader(filename))){\n\t\tString line;\n\t\twhile((line = in.readLine()) != null){\n\t\t\tline = line.toUpperCase();\n\t\t\tfor(char ch:line.toCharArray()){\n\t\t\t\tif(Character.isLetter(ch)){\n\t\t\t\t\tfreqs[ch - 'A']++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn freqs;\n}\n\nWorks with: Java version 8+\n\npublic static Map countLetters(String filename) throws IOException {\n return Files.lines(Paths.get(filename))\n .flatMapToInt(String::chars)\n .filter(Character::isLetter)\n .boxed()\n .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));\n}\n\n","human_summarization":"open a text file and count the frequency of each letter, including punctuation. It is implemented in both Java 7, using try with resources, and Java 8, using streams. The Java 8 implementation also handles unicode codepoints.","id":251} {"lang_cluster":"Java","source_code":"\n\nclass Link\n{\n Link next;\n int data;\n}\n\n\nclass Link\n{\n Link next;\n int data;\n Link(int a_data, Link a_next) { next = a_next; data = a_data; }\n}\n\n\n Link small_primes = new Link(2, new Link(3, new Link(5, new Link(7, null))));\n\nWorks with: Java version 1.5+\n\nclass Link\n{\n Link next;\n T data;\n Link(T a_data, Link a_next) { next = a_next; data = a_data; }\n}\n\n","human_summarization":"define a data structure for a singly-linked list element. This element holds a numeric value and a mutable link to the next element. The code also includes a constructor to simplify the initialization of links. The data type can be made generic, but only works on reference types.","id":252} {"lang_cluster":"Java","source_code":"\nLibrary: Swing Library: AWT\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class FractalTree extends JFrame {\n\n public FractalTree() {\n super(\"Fractal Tree\");\n setBounds(100, 100, 800, 600);\n setResizable(false);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n }\n\n private void drawTree(Graphics g, int x1, int y1, double angle, int depth) {\n if (depth == 0) return;\n int x2 = x1 + (int) (Math.cos(Math.toRadians(angle)) * depth * 10.0);\n int y2 = y1 + (int) (Math.sin(Math.toRadians(angle)) * depth * 10.0);\n g.drawLine(x1, y1, x2, y2);\n drawTree(g, x2, y2, angle - 20, depth - 1);\n drawTree(g, x2, y2, angle + 20, depth - 1);\n }\n\n @Override\n public void paint(Graphics g) {\n g.setColor(Color.BLACK);\n drawTree(g, 400, 500, -90, 9);\n }\n\n public static void main(String[] args) {\n new FractalTree().setVisible(true);\n }\n}\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":253} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 5+\npublic static TreeSet factors(long n)\n{\n TreeSet factors = new TreeSet();\n factors.add(n);\n factors.add(1L);\n for(long test = n - 1; test >= Math.sqrt(n); test--)\n if(n % test == 0)\n {\n factors.add(test);\n factors.add(n \/ test);\n }\n return factors;\n}\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":254} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 7\nLibrary: Apache Commons Lang\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.apache.commons.lang3.StringUtils;\n\n\/**\n * Aligns fields into columns, separated by \"|\"\n *\/\npublic class ColumnAligner {\n private List words = new ArrayList<>();\n private int columns = 0;\n private List columnWidths = new ArrayList<>();\n\n \/**\n * Initialize columns aligner from lines in a single string\n * \n * @param s\n * lines in a single string. Empty string does form a column.\n *\/\n public ColumnAligner(String s) {\n String[] lines = s.split(\"\\\\n\");\n for (String line : lines) {\n processInputLine(line);\n }\n }\n\n \/**\n * Initialize columns aligner from lines in a list of strings\n * \n * @param lines\n * lines in a single string. Empty string does form a column.\n *\/\n public ColumnAligner(List lines) {\n for (String line : lines) {\n processInputLine(line);\n }\n }\n\n private void processInputLine(String line) {\n String[] lineWords = line.split(\"\\\\$\");\n words.add(lineWords);\n columns = Math.max(columns, lineWords.length);\n for (int i = 0; i < lineWords.length; i++) {\n String word = lineWords[i];\n if (i >= columnWidths.size()) {\n columnWidths.add(word.length());\n } else {\n columnWidths.set(i, Math.max(columnWidths.get(i), word.length()));\n }\n }\n }\n\n interface AlignFunction {\n String align(String s, int length);\n }\n\n \/**\n * Left-align all columns\n * \n * @return Lines, terminated by \"\\n\" of columns, separated by \"|\"\n *\/\n public String alignLeft() {\n return align(new AlignFunction() {\n @Override\n public String align(String s, int length) {\n return StringUtils.rightPad(s, length);\n }\n });\n }\n\n \/**\n * Right-align all columns\n * \n * @return Lines, terminated by \"\\n\" of columns, separated by \"|\"\n *\/\n public String alignRight() {\n return align(new AlignFunction() {\n @Override\n public String align(String s, int length) {\n return StringUtils.leftPad(s, length);\n }\n });\n }\n\n \/**\n * Center-align all columns\n * \n * @return Lines, terminated by \"\\n\" of columns, separated by \"|\"\n *\/\n public String alignCenter() {\n return align(new AlignFunction() {\n @Override\n public String align(String s, int length) {\n return StringUtils.center(s, length);\n }\n });\n }\n\n private String align(AlignFunction a) {\n StringBuilder result = new StringBuilder();\n for (String[] lineWords : words) {\n for (int i = 0; i < lineWords.length; i++) {\n String word = lineWords[i];\n if (i == 0) {\n result.append(\"|\");\n }\n result.append(a.align(word, columnWidths.get(i)) + \"|\");\n }\n result.append(\"\\n\");\n }\n return result.toString();\n }\n\n public static void main(String args[]) throws IOException {\n if (args.length < 1) {\n System.out.println(\"Usage: ColumnAligner file [left|right|center]\");\n return;\n }\n String filePath = args[0];\n String alignment = \"left\";\n if (args.length >= 2) {\n alignment = args[1];\n }\n ColumnAligner ca = new ColumnAligner(Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8));\n switch (alignment) {\n case \"left\":\n System.out.print(ca.alignLeft());\n break;\n case \"right\":\n System.out.print(ca.alignRight());\n break;\n case \"center\":\n System.out.print(ca.alignCenter());\n break;\n default:\n System.err.println(String.format(\"Error! Unknown alignment: '%s'\", alignment));\n break;\n }\n }\n}\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":255} {"lang_cluster":"Java","source_code":"\n\nWorks with: Java version 8\nimport java.awt.*;\nimport java.awt.event.*;\nimport static java.lang.Math.*;\nimport javax.swing.*;\n\npublic class Cuboid extends JPanel {\n double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1},\n {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};\n\n int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},\n {6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}};\n\n int mouseX, prevMouseX, mouseY, prevMouseY;\n\n public Cuboid() {\n setPreferredSize(new Dimension(640, 640));\n setBackground(Color.white);\n\n scale(80, 120, 160);\n rotateCube(PI \/ 5, PI \/ 9);\n\n addMouseListener(new MouseAdapter() {\n @Override\n public void mousePressed(MouseEvent e) {\n mouseX = e.getX();\n mouseY = e.getY();\n }\n });\n\n addMouseMotionListener(new MouseAdapter() {\n @Override\n public void mouseDragged(MouseEvent e) {\n prevMouseX = mouseX;\n prevMouseY = mouseY;\n mouseX = e.getX();\n mouseY = e.getY();\n\n double incrX = (mouseX - prevMouseX) * 0.01;\n double incrY = (mouseY - prevMouseY) * 0.01;\n\n rotateCube(incrX, incrY);\n repaint();\n }\n });\n }\n\n private void scale(double sx, double sy, double sz) {\n for (double[] node : nodes) {\n node[0] *= sx;\n node[1] *= sy;\n node[2] *= sz;\n }\n }\n\n private void rotateCube(double angleX, double angleY) {\n double sinX = sin(angleX);\n double cosX = cos(angleX);\n\n double sinY = sin(angleY);\n double cosY = cos(angleY);\n\n for (double[] node : nodes) {\n double x = node[0];\n double y = node[1];\n double z = node[2];\n\n node[0] = x * cosX - z * sinX;\n node[2] = z * cosX + x * sinX;\n\n z = node[2];\n\n node[1] = y * cosY - z * sinY;\n node[2] = z * cosY + y * sinY;\n }\n }\n\n void drawCube(Graphics2D g) {\n g.translate(getWidth() \/ 2, getHeight() \/ 2);\n\n for (int[] edge : edges) {\n double[] xy1 = nodes[edge[0]];\n double[] xy2 = nodes[edge[1]];\n g.drawLine((int) round(xy1[0]), (int) round(xy1[1]),\n (int) round(xy2[0]), (int) round(xy2[1]));\n }\n\n for (double[] node : nodes) {\n g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8);\n }\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n drawCube(g);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Cuboid\");\n f.setResizable(false);\n f.add(new Cuboid(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":256} {"lang_cluster":"Java","source_code":"\n\nimport java.io.IOException;\nimport org.apache.directory.api.ldap.model.exception.LdapException;\nimport org.apache.directory.ldap.client.api.LdapConnection;\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection;\n\npublic class LdapConnectionDemo {\n\n public static void main(String[] args) throws LdapException, IOException {\n try (LdapConnection connection = new LdapNetworkConnection(\"localhost\", 10389)) {\n connection.bind();\n connection.unBind();\n }\n }\n}\n\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server using the Apache Directory third-party library.","id":257} {"lang_cluster":"Java","source_code":"\nimport java.io.*;\n\npublic class Rot13 {\n\n public static void main(String[] args) throws IOException {\n if (args.length >= 1) {\n for (String file : args) {\n try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {\n rot13(in, System.out);\n }\n }\n } else {\n rot13(System.in, System.out);\n }\n }\n\n private static void rot13(InputStream in, OutputStream out) throws IOException {\n int ch;\n while ((ch = in.read()) != -1) {\n out.write(rot13((char) ch));\n }\n }\n\n private static char rot13(char ch) {\n if (ch >= 'A' && ch <= 'Z') {\n return (char) (((ch - 'A') + 13) % 26 + 'A');\n }\n if (ch >= 'a' && ch <= 'z') {\n return (char) (((ch - 'a') + 13) % 26 + 'a');\n }\n return ch;\n }\n}\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":258} {"lang_cluster":"Java","source_code":"\nimport java.util.Arrays;\nimport java.util.Comparator;\n\npublic class SortComp {\n public static class Pair {\n public String name;\n public String value;\n public Pair(String n, String v) {\n name = n;\n value = v;\n }\n }\n\n public static void main(String[] args) {\n Pair[] pairs = {new Pair(\"06-07\", \"Ducks\"), new Pair(\"00-01\", \"Avalanche\"),\n new Pair(\"02-03\", \"Devils\"), new Pair(\"01-02\", \"Red Wings\"),\n new Pair(\"03-04\", \"Lightning\"), new Pair(\"04-05\", \"lockout\"),\n new Pair(\"05-06\", \"Hurricanes\"), new Pair(\"99-00\", \"Devils\"),\n new Pair(\"07-08\", \"Red Wings\"), new Pair(\"08-09\", \"Penguins\")};\n\n sortByName(pairs);\n for (Pair p : pairs) {\n System.out.println(p.name + \" \" + p.value);\n }\n }\n\n public static void sortByName(Pair[] pairs) {\n Arrays.sort(pairs, new Comparator() {\n public int compare(Pair p1, Pair p2) {\n return p1.name.compareTo(p2.name);\n }\n });\n }\n}\n\n\n00-01 Avalanche\n01-02 Red Wings\n02-03 Devils\n03-04 Lightning\n04-05 lockout\n05-06 Hurricanes\n06-07 Ducks\n07-08 Red Wings\n08-09 Penguins\n99-00 Devils\n\nWorks with: Java version 8+\n public static void sortByName(Pair[] pairs) {\n Arrays.sort(pairs, (p1, p2) -> p1.name.compareTo(p2.name));\n }\n\n\nWorks with: Java version 8+\n public static void sortByName(Pair[] pairs) {\n Arrays.sort(pairs, Comparator.comparing(p -> p.name));\n }\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator in Java 8. The comparator is constructed using a \"key\" function via Comparator.comparing().","id":259} {"lang_cluster":"Java","source_code":"\nfor (int i = 0; i < 5; i++) {\n for (int j = 0; j <= i; j++) {\n System.out.print(\"*\");\n }\n System.out.println();\n}\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":260} {"lang_cluster":"Java","source_code":"\n\n\n\n\nMap map = new HashMap<>();\n\n\nmap.put(\"rosetta\", 100);\nmap.put(\"code\", 200);\n\n\nint valueA = map.get(\"rosetta\");\nint valueB = map.get(\"code\");\n\n\nmap.replace(\"rosetta\", 300);\n\n\nboolean replaced = map.replace(\"rosetta\", 100, 300);\n\n\nboolean contains = map.containsKey(\"rosetta\");\n\n\nboolean contains = map.containsValue(100);\n\n\nMap map = new LinkedHashMap<>();\nmap.put(\"rosetta\", 100);\nmap.put(\"code\", 200);\n\n\nMap map = new TreeMap<>();\nmap.put(\"rosetta\", 100);\nmap.put(\"code\", 200);\n\n\nComparator comparator = new Comparator() {\n public int compare(String stringA, String stringB) {\n if (stringA.compareTo(stringB) > 0) {\n return -1;\n } else if (stringA.compareTo(stringB) < 0) {\n return 1;\n }\n return 0;\n }\n};\n\n\nMap map = new TreeMap<>(comparator);\n\n\nComparator comparator = (stringA, stringB) -> {\n if (stringA.compareTo(stringB) > 0) {\n return -1;\n } else if (stringA.compareTo(stringB) < 0) {\n return 1;\n }\n return 0;\n};\n\n","human_summarization":"demonstrate how to create and manipulate various types of associative arrays in Java, including HashMap, LinkedHashMap, and TreeMap. The codes show how to add, get, replace, and check for keys and values in these arrays. The TreeMap implementation also includes the use of a custom comparator.","id":261} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 8\nimport java.util.stream.IntStream;\nimport static java.util.stream.IntStream.iterate;\n\npublic class LinearCongruentialGenerator {\n final static int mask = (1 << 31) - 1;\n\n public static void main(String[] args) {\n System.out.println(\"BSD:\");\n randBSD(0).limit(10).forEach(System.out::println);\n\n System.out.println(\"\\nMS:\");\n randMS(0).limit(10).forEach(System.out::println);\n }\n\n static IntStream randBSD(int seed) {\n return iterate(seed, s -> (s * 1_103_515_245 + 12_345) & mask).skip(1);\n }\n\n static IntStream randMS(int seed) {\n return iterate(seed, s -> (s * 214_013 + 2_531_011) & mask).skip(1)\n .map(i -> i >> 16);\n }\n}\n\nBSD:\n12345\n1406932606\n654583775\n1449466924\n229283573\n1109335178\n1051550459\n1293799192\n794471793\n551188310\n\nMS:\n38\n7719\n21238\n2437\n8855\n11797\n8365\n32285\n10450\n30612\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":262} {"lang_cluster":"Java","source_code":"\n\nvoid insertNode(Node anchor_node, Node new_node)\n{\n new_node.next = anchor_node.next;\n anchor_node.next = new_node;\n}\n\nWorks with: Java version 1.5+\n\n","human_summarization":"The code defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element 'C' into a list containing elements 'A' and 'B', after element 'A'. The code uses Java's generics feature, which only works on reference types, not primitive types.","id":263} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Scanner;\npublic class Mult{\n public static void main(String[] args){\n Scanner sc = new Scanner(System.in);\n int first = sc.nextInt();\n int second = sc.nextInt();\n\n if(first < 0){\n first = -first;\n second = -second;\n }\n\n Map columns = new HashMap();\n columns.put(first, second);\n int sum = isEven(first)? 0 : second;\n do{\n first = halveInt(first);\n second = doubleInt(second);\n columns.put(first, second);\n if(!isEven(first)){\n sum += second;\n }\n }while(first > 1);\n \n System.out.println(sum);\n }\n\n public static int doubleInt(int doubleMe){\n return doubleMe << 1; \/\/shift left\n }\n\n public static int halveInt(int halveMe){\n return halveMe >>> 1; \/\/shift right\n }\n\n public static boolean isEven(int num){\n return (num & 1) == 0;\n }\n}\nAn optimised variant using the three helper functions from the other example.\/**\n * This method will use ethiopian styled multiplication.\n * @param a Any non-negative integer.\n * @param b Any integer.\n * @result a multiplied by b\n *\/\npublic static int ethiopianMultiply(int a, int b) {\n if(a==0 || b==0) {\n return 0;\n }\n int result = 0;\n while(a>=1) {\n if(!isEven(a)) {\n result+=b;\n }\n b = doubleInt(b);\n a = halveInt(a);\n }\n return result;\n}\n\n\/**\n * This method is an improved version that will use\n * ethiopian styled multiplication, and also\n * supports negative parameters.\n * @param a Any integer.\n * @param b Any integer.\n * @result a multiplied by b\n *\/\npublic static int ethiopianMultiplyWithImprovement(int a, int b) {\n if(a==0 || b==0) {\n return 0;\n }\n if(a<0) {\n a=-a;\n b=-b;\n } else if(b>0 && a>b) {\n int tmp = a;\n a = b;\n b = tmp;\n }\n int result = 0;\n while(a>=1) {\n if(!isEven(a)) {\n result+=b;\n }\n b = doubleInt(b);\n a = halveInt(a);\n }\n return result;\n}\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":264} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 7\n\nimport java.util.*;\n\npublic class Game24Player {\n final String[] patterns = {\"nnonnoo\", \"nnonono\", \"nnnoono\", \"nnnonoo\",\n \"nnnnooo\"};\n final String ops = \"+-*\/^\";\n\n String solution;\n List digits;\n\n public static void main(String[] args) {\n new Game24Player().play();\n }\n\n void play() {\n digits = getSolvableDigits();\n\n Scanner in = new Scanner(System.in);\n while (true) {\n System.out.print(\"Make 24 using these digits: \");\n System.out.println(digits);\n System.out.println(\"(Enter 'q' to quit, 's' for a solution)\");\n System.out.print(\"> \");\n\n String line = in.nextLine();\n if (line.equalsIgnoreCase(\"q\")) {\n System.out.println(\"\\nThanks for playing\");\n return;\n }\n\n if (line.equalsIgnoreCase(\"s\")) {\n System.out.println(solution);\n digits = getSolvableDigits();\n continue;\n }\n\n char[] entry = line.replaceAll(\"[^*+-\/)(\\\\d]\", \"\").toCharArray();\n\n try {\n validate(entry);\n\n if (evaluate(infixToPostfix(entry))) {\n System.out.println(\"\\nCorrect! Want to try another? \");\n digits = getSolvableDigits();\n } else {\n System.out.println(\"\\nNot correct.\");\n }\n\n } catch (Exception e) {\n System.out.printf(\"%n%s Try again.%n\", e.getMessage());\n }\n }\n }\n\n void validate(char[] input) throws Exception {\n int total1 = 0, parens = 0, opsCount = 0;\n\n for (char c : input) {\n if (Character.isDigit(c))\n total1 += 1 << (c - '0') * 4;\n else if (c == '(')\n parens++;\n else if (c == ')')\n parens--;\n else if (ops.indexOf(c) != -1)\n opsCount++;\n if (parens < 0)\n throw new Exception(\"Parentheses mismatch.\");\n }\n\n if (parens != 0)\n throw new Exception(\"Parentheses mismatch.\");\n\n if (opsCount != 3)\n throw new Exception(\"Wrong number of operators.\");\n\n int total2 = 0;\n for (int d : digits)\n total2 += 1 << d * 4;\n\n if (total1 != total2)\n throw new Exception(\"Not the same digits.\");\n }\n\n boolean evaluate(char[] line) throws Exception {\n Stack s = new Stack<>();\n try {\n for (char c : line) {\n if ('0' <= c && c <= '9')\n s.push((float) c - '0');\n else\n s.push(applyOperator(s.pop(), s.pop(), c));\n }\n } catch (EmptyStackException e) {\n throw new Exception(\"Invalid entry.\");\n }\n return (Math.abs(24 - s.peek()) < 0.001F);\n }\n\n float applyOperator(float a, float b, char c) {\n switch (c) {\n case '+':\n return a + b;\n case '-':\n return b - a;\n case '*':\n return a * b;\n case '\/':\n return b \/ a;\n default:\n return Float.NaN;\n }\n }\n\n List randomDigits() {\n Random r = new Random();\n List result = new ArrayList<>(4);\n for (int i = 0; i < 4; i++)\n result.add(r.nextInt(9) + 1);\n return result;\n }\n\n List getSolvableDigits() {\n List result;\n do {\n result = randomDigits();\n } while (!isSolvable(result));\n return result;\n }\n\n boolean isSolvable(List digits) {\n Set> dPerms = new HashSet<>(4 * 3 * 2);\n permute(digits, dPerms, 0);\n\n int total = 4 * 4 * 4;\n List> oPerms = new ArrayList<>(total);\n permuteOperators(oPerms, 4, total);\n\n StringBuilder sb = new StringBuilder(4 + 3);\n\n for (String pattern : patterns) {\n char[] patternChars = pattern.toCharArray();\n\n for (List dig : dPerms) {\n for (List opr : oPerms) {\n\n int i = 0, j = 0;\n for (char c : patternChars) {\n if (c == 'n')\n sb.append(dig.get(i++));\n else\n sb.append(ops.charAt(opr.get(j++)));\n }\n\n String candidate = sb.toString();\n try {\n if (evaluate(candidate.toCharArray())) {\n solution = postfixToInfix(candidate);\n return true;\n }\n } catch (Exception ignored) {\n }\n sb.setLength(0);\n }\n }\n }\n return false;\n }\n\n String postfixToInfix(String postfix) {\n class Expression {\n String op, ex;\n int prec = 3;\n\n Expression(String e) {\n ex = e;\n }\n\n Expression(String e1, String e2, String o) {\n ex = String.format(\"%s %s %s\", e1, o, e2);\n op = o;\n prec = ops.indexOf(o) \/ 2;\n }\n }\n\n Stack expr = new Stack<>();\n\n for (char c : postfix.toCharArray()) {\n int idx = ops.indexOf(c);\n if (idx != -1) {\n\n Expression r = expr.pop();\n Expression l = expr.pop();\n\n int opPrec = idx \/ 2;\n\n if (l.prec < opPrec)\n l.ex = '(' + l.ex + ')';\n\n if (r.prec <= opPrec)\n r.ex = '(' + r.ex + ')';\n\n expr.push(new Expression(l.ex, r.ex, \"\" + c));\n } else {\n expr.push(new Expression(\"\" + c));\n }\n }\n return expr.peek().ex;\n }\n\n char[] infixToPostfix(char[] infix) throws Exception {\n StringBuilder sb = new StringBuilder();\n Stack s = new Stack<>();\n try {\n for (char c : infix) {\n int idx = ops.indexOf(c);\n if (idx != -1) {\n if (s.isEmpty())\n s.push(idx);\n else {\n while (!s.isEmpty()) {\n int prec2 = s.peek() \/ 2;\n int prec1 = idx \/ 2;\n if (prec2 >= prec1)\n sb.append(ops.charAt(s.pop()));\n else\n break;\n }\n s.push(idx);\n }\n } else if (c == '(') {\n s.push(-2);\n } else if (c == ')') {\n while (s.peek() != -2)\n sb.append(ops.charAt(s.pop()));\n s.pop();\n } else {\n sb.append(c);\n }\n }\n while (!s.isEmpty())\n sb.append(ops.charAt(s.pop()));\n\n } catch (EmptyStackException e) {\n throw new Exception(\"Invalid entry.\");\n }\n return sb.toString().toCharArray();\n }\n\n void permute(List lst, Set> res, int k) {\n for (int i = k; i < lst.size(); i++) {\n Collections.swap(lst, i, k);\n permute(lst, res, k + 1);\n Collections.swap(lst, k, i);\n }\n if (k == lst.size())\n res.add(new ArrayList<>(lst));\n }\n\n void permuteOperators(List> res, int n, int total) {\n for (int i = 0, npow = n * n; i < total; i++)\n res.add(Arrays.asList((i \/ npow), (i % npow) \/ n, i % n));\n }\n}\n\n\n","human_summarization":"The code takes four digits as input, either provided by the user or generated randomly, and computes arithmetic expressions according to the rules of the 24 game. It also includes examples of the solutions it generates. The code does not extend to different digit ranges.","id":265} {"lang_cluster":"Java","source_code":"\npackage programas;\n\nimport java.math.BigInteger;\nimport java.util.InputMismatchException;\nimport java.util.Scanner;\n\npublic class IterativeFactorial {\n\n public BigInteger factorial(BigInteger n) {\n if ( n == null ) {\n throw new IllegalArgumentException();\n }\n else if ( n.signum() == - 1 ) {\n \/\/ negative\n throw new IllegalArgumentException(\"Argument must be a non-negative integer\");\n }\n else {\n BigInteger factorial = BigInteger.ONE;\n for ( BigInteger i = BigInteger.ONE; i.compareTo(n) < 1; i = i.add(BigInteger.ONE) ) {\n factorial = factorial.multiply(i);\n }\n return factorial;\n }\n }\n\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n BigInteger number, result;\n boolean error = false;\n System.out.println(\"FACTORIAL OF A NUMBER\");\n do {\n System.out.println(\"Enter a number:\");\n try {\n number = scanner.nextBigInteger();\n result = new IterativeFactorial().factorial(number);\n error = false;\n System.out.println(\"Factorial of \" + number + \": \" + result);\n }\n catch ( InputMismatchException e ) {\n error = true;\n scanner.nextLine();\n }\n\n catch ( IllegalArgumentException e ) {\n error = true;\n scanner.nextLine();\n }\n }\n while ( error );\n scanner.close();\n }\n\n}\npackage programas;\n\nimport java.math.BigInteger;\nimport java.util.InputMismatchException;\nimport java.util.Scanner;\n\npublic class RecursiveFactorial {\n\n public BigInteger factorial(BigInteger n) {\n if ( n == null ) {\n throw new IllegalArgumentException();\n }\n\n else if ( n.equals(BigInteger.ZERO) ) {\n return BigInteger.ONE;\n }\n else if ( n.signum() == - 1 ) {\n \/\/ negative\n throw new IllegalArgumentException(\"Argument must be a non-negative integer\");\n }\n else {\n return n.equals(BigInteger.ONE)\n \u00a0? BigInteger.ONE\n \u00a0: factorial(n.subtract(BigInteger.ONE)).multiply(n);\n }\n }\n\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n BigInteger number, result;\n boolean error = false;\n System.out.println(\"FACTORIAL OF A NUMBER\");\n do {\n System.out.println(\"Enter a number:\");\n try {\n number = scanner.nextBigInteger();\n result = new RecursiveFactorial().factorial(number);\n error = false;\n System.out.println(\"Factorial of \" + number + \": \" + result);\n }\n catch ( InputMismatchException e ) {\n error = true;\n scanner.nextLine();\n }\n\n catch ( IllegalArgumentException e ) {\n error = true;\n scanner.nextLine();\n }\n }\n while ( error );\n scanner.close();\n\n }\n\n}\nimport java.math.BigInteger;\nimport java.util.InputMismatchException;\nimport java.util.Scanner;\n\npublic class LargeFactorial {\n public static long userInput;\n public static void main(String[]args){\n Scanner input = new Scanner(System.in);\n System.out.println(\"Input factorial integer base: \");\n try {\n userInput = input.nextLong();\n System.out.println(userInput + \"! is\\n\" + factorial(userInput) + \" using standard factorial method.\");\n System.out.println(userInput + \"! is\\n\" + factorialRec(userInput) + \" using recursion method.\");\n }catch(InputMismatchException x){\n System.out.println(\"Please give integral numbers.\");\n }catch(StackOverflowError ex){\n if(userInput > 0) {\n System.out.println(\"Number too big.\");\n }else{\n System.out.println(\"Please give non-negative(positive) numbers.\");\n }\n }finally {\n System.exit(0);\n }\n }\n public static BigInteger factorialRec(long n){\n BigInteger result = BigInteger.ONE;\n return n == 0\u00a0? result\u00a0: result.multiply(BigInteger.valueOf(n)).multiply(factorial(n-1));\n }\n public static BigInteger factorial(long n){\n BigInteger result = BigInteger.ONE;\n for(int i = 1; i <= n; i++){\n result = result.multiply(BigInteger.valueOf(i));\n }\n return result;\n }\n}\n","human_summarization":"The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.","id":266} {"lang_cluster":"Java","source_code":"\nimport java.util.InputMismatchException;\nimport java.util.Random;\nimport java.util.Scanner;\n\npublic class BullsAndCows{\n\tpublic static void main(String[] args){\n\t\tRandom gen= new Random();\n\t\tint target;\n\t\twhile(hasDupes(target= (gen.nextInt(9000) + 1000)));\n\t\tString targetStr = target +\"\";\n\t\tboolean guessed = false;\n\t\tScanner input = new Scanner(System.in);\n\t\tint guesses = 0;\n\t\tdo{\n\t\t\tint bulls = 0;\n\t\t\tint cows = 0;\n\t\t\tSystem.out.print(\"Guess a 4-digit number with no duplicate digits: \");\n\t\t\tint guess;\n\t\t\ttry{\n\t\t\t\tguess = input.nextInt();\n\t\t\t\tif(hasDupes(guess) || guess < 1000) continue;\n\t\t\t}catch(InputMismatchException e){\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguesses++;\n\t\t\tString guessStr = guess + \"\";\n\t\t\tfor(int i= 0;i < 4;i++){\n\t\t\t\tif(guessStr.charAt(i) == targetStr.charAt(i)){\n\t\t\t\t\tbulls++;\n\t\t\t\t}else if(targetStr.contains(guessStr.charAt(i)+\"\")){\n\t\t\t\t\tcows++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(bulls == 4){\n\t\t\t\tguessed = true;\n\t\t\t}else{\n\t\t\t\tSystem.out.println(cows+\" Cows and \"+bulls+\" Bulls.\");\n\t\t\t}\n\t\t}while(!guessed);\n\t\tSystem.out.println(\"You won after \"+guesses+\" guesses!\");\n\t}\n\n\tpublic static boolean hasDupes(int num){\n\t\tboolean[] digs = new boolean[10];\n\t\twhile(num > 0){\n\t\t\tif(digs[num%10]) return true;\n\t\t\tdigs[num%10] = true;\n\t\t\tnum\/= 10;\n\t\t}\n\t\treturn false;\n\t}\n}\n\n\nGuess a 4-digit number with no duplicate digits: 5834\n2 Cows and 0 Bulls.\nGuess a 4-digit number with no duplicate digits: 1234\n1 Cows and 0 Bulls.\nGuess a 4-digit number with no duplicate digits: 4321\n1 Cows and 0 Bulls.\nGuess a 4-digit number with no duplicate digits: 3421\n0 Cows and 1 Bulls.\nGuess a 4-digit number with no duplicate digits: 8412\n0 Cows and 0 Bulls.\nGuess a 4-digit number with no duplicate digits: 3560\n1 Cows and 1 Bulls.\nGuess a 4-digit number with no duplicate digits: 3650\n0 Cows and 2 Bulls.\nGuess a 4-digit number with no duplicate digits: 3759\n2 Cows and 2 Bulls.\nGuess a 4-digit number with no duplicate digits: 3975\n2 Cows and 2 Bulls.\nGuess a 4-digit number with no duplicate digits: 3957\nYou won after 10 guesses!\n","human_summarization":"generate a unique four-digit number, accept user guesses, validate these guesses, and score them based on the number of correctly guessed digits and their positions. The game ends when the user correctly guesses the number.","id":267} {"lang_cluster":"Java","source_code":"\ndouble[] list = new double[1000];\ndouble mean = 1.0, std = 0.5;\nRandom rng = new Random();\nfor(int i = 0;i\n\n Some text here<\/element>\n<\/root>\n\n","human_summarization":"generate a simple DOM and serialize it to XML format using Java's XML DOM tools, with the output equivalent to the specified XML structure. The tools do not allow complete control of the output format by default.","id":271} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\npublic class SystemTime{\n public static void main(String[] args){\n System.out.format(\"%tc%n\", System.currentTimeMillis());\n }\n}\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. It may also use a Calendar object to retrieve specific fields of the date. The related task is date formatting and for more information, refer to the wiki on retrieving system time.","id":272} {"lang_cluster":"Java","source_code":"\nimport java.util.Scanner;\n\npublic class SEDOL{\n\tpublic static void main(String[] args){\n\t\tScanner sc = new Scanner(System.in);\n\t\twhile(sc.hasNext()){\n\t\t\tString sedol = sc.next();\n\t\t\tSystem.out.println(sedol + getSedolCheckDigit(sedol));\n\t\t}\n\t}\n\t\n\tprivate static final int[] mult = {1, 3, 1, 7, 3, 9};\n\t\n\tpublic static int getSedolCheckDigit(String str){\n\t if(!validateSedol(str)){\n\t \tSystem.err.println(\"SEDOL strings must contain six characters with no vowels.\");\n\t \treturn -1;\n\t }\n\t str = str.toUpperCase();\n\t int total = 0;\n\t for(int i = 0;i < 6; i++){\n\t char s = str.charAt(i);\n\t total += Character.digit(s, 36) * mult[i];\n\t }\n\t return (10 - (total % 10)) % 10;\n\t}\n\n\tpublic static boolean validateSedol(String str){\n\t\treturn (str.length() == 6) && !str.toUpperCase().matches(\".*?[AEIOU].*?\");\n\t}\n}\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":273} {"lang_cluster":"Java","source_code":"public class Sphere{\n static char[] shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'};\n\n static double[] light = { 30, 30, -50 };\n private static void normalize(double[] v){\n double len = Math.sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n v[0] \/= len; v[1] \/= len; v[2] \/= len;\n }\n\n private static double dot(double[] x, double[] y){\n double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n return d < 0 ? -d : 0;\n }\n\n public static void drawSphere(double R, double k, double ambient){\n double[] vec = new double[3];\n for(int i = (int)Math.floor(-R); i <= (int)Math.ceil(R); i++){\n double x = i + .5;\n for(int j = (int)Math.floor(-2 * R); j <= (int)Math.ceil(2 * R); j++){\n double y = j \/ 2. + .5;\n if(x * x + y * y <= R * R) {\n vec[0] = x;\n vec[1] = y;\n vec[2] = Math.sqrt(R * R - x * x - y * y);\n normalize(vec);\n double b = Math.pow(dot(light, vec), k) + ambient;\n int intensity = (b <= 0) ?\n shades.length - 2 :\n (int)Math.max((1 - b) * (shades.length - 1), 0);\n System.out.print(shades[intensity]);\n } else\n System.out.print(' ');\n }\n System.out.println();\n }\n }\n\n public static void main(String[] args){\n normalize(light);\n drawSphere(20, 4, .1);\n drawSphere(10, 2, .4);\n }\n}\n\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":274} {"lang_cluster":"Java","source_code":"\npublic class Nth {\n\tpublic static String ordinalAbbrev(int n){\n\t\tString ans = \"th\"; \/\/most of the time it should be \"th\"\n\t\tif(n % 100 \/ 10 == 1) return ans; \/\/teens are all \"th\"\n\t\tswitch(n % 10){\n\t\t\tcase 1: ans = \"st\"; break;\n\t\t\tcase 2: ans = \"nd\"; break;\n\t\t\tcase 3: ans = \"rd\"; break;\n\t\t}\n\t\treturn ans;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tfor(int i = 0; i <= 25;i++){\n\t\t\tSystem.out.print(i + ordinalAbbrev(i) + \" \");\n\t\t}\n\t\tSystem.out.println();\n\t\tfor(int i = 250; i <= 265;i++){\n\t\t\tSystem.out.print(i + ordinalAbbrev(i) + \" \");\n\t\t}\n\t\tSystem.out.println();\n\t\tfor(int i = 1000; i <= 1025;i++){\n\t\t\tSystem.out.print(i + ordinalAbbrev(i) + \" \");\n\t\t}\n\t}\n}\n\nWorks with: Java version 8+\npackage nth;\n\nimport java.util.stream.IntStream;\nimport java.util.stream.Stream;\n\npublic interface Nth {\n public static String suffix(int n){\n if(n % 100 \/ 10 == 1){\n return \"th\"; \/\/teens are all \"th\"\n }\n switch(n % 10){\n case 1: return \"st\";\n case 2: return \"nd\";\n case 3: return \"rd\";\n default: return \"th\"; \/\/most of the time it should be \"th\"\n }\n }\n\n public static void print(int start, int end) {\n IntStream.rangeClosed(start, end)\n .parallel()\n .mapToObj(i -> i + suffix(i) + \" \")\n .reduce(String::concat)\n .ifPresent(System.out::println)\n ;\n }\n\n public static void print(int[] startAndEnd) {\n print(startAndEnd[0], startAndEnd[1]);\n }\n\n public static int[] startAndEnd(int start, int end) {\n return new int[] {\n start,\n end\n };\n }\n \n public static void main(String... arguments){\n Stream.of(\n startAndEnd(0, 25),\n startAndEnd(250, 265),\n startAndEnd(1000, 1025)\n )\n .forEach(Nth::print)\n ;\n }\n}\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":275} {"lang_cluster":"Java","source_code":"\n\nString stripCharacters(String string, String characters) {\n for (char character : characters.toCharArray())\n string = string.replace(String.valueOf(character), \"\");\n return string;\n}\n\n\nString stripCharacters(String string, String characters) {\n StringBuilder stripped = new StringBuilder(string);\n \/* traversing the string backwards is necessary to avoid collision *\/\n for (int index = string.length() - 1; index >= 0; index--) {\n if (characters.contains(String.valueOf(string.charAt(index))))\n stripped.deleteCharAt(index);\n }\n return stripped.toString();\n}\n\n\nstatic String stripCharacters(String string, String characters) {\n \/* be sure to 'quote' the 'characters' to avoid pattern collision *\/\n characters = Pattern.quote(characters);\n string = string.replaceAll(\"[%s]\".formatted(characters), \"\");\n return string;\n}\n\n\nSh ws soul strppr. Sh took my hrt!\n\n","human_summarization":"\"Defines a function that removes a specified set of characters from a given string using String.replace, StringBuilder.deleteCharAt, or String.replaceAll methods.\"","id":276} {"lang_cluster":"Java","source_code":"\npublic class FizzBuzz {\n\n public static void main(String[] args) {\n Sound[] sounds = {new Sound(3, \"Fizz\"), new Sound(5, \"Buzz\"), new Sound(7, \"Baxx\")};\n for (int i = 1; i <= 20; i++) {\n StringBuilder sb = new StringBuilder();\n for (Sound sound : sounds) {\n sb.append(sound.generate(i));\n }\n System.out.println(sb.length() == 0 ? i : sb.toString());\n }\n }\n\n private static class Sound {\n private final int trigger;\n private final String onomatopoeia;\n\n public Sound(int trigger, String onomatopoeia) {\n this.trigger = trigger;\n this.onomatopoeia = onomatopoeia;\n }\n\n public String generate(int i) {\n return i % trigger == 0 ? onomatopoeia : \"\";\n }\n\n }\n\n}\n\n\nimport java.util.stream.*;\nimport java.util.function.*;\nimport java.util.*;\npublic class fizzbuzz_general {\n \/**\n * To run: java fizzbuzz_general.java 3=Fizz 5=Buzz 7=Baxx 100\n *\n *\/\n public static void main(String[] args) {\n Function> make_cycle_function = \n parts -> j -> j%(Integer.parseInt(parts[0]))==0?parts[1]:\"\";\n List> cycle_functions = Stream.of(args)\n .map(arg -> arg.split(\"=\"))\n .filter(parts->parts.length==2)\n .map(make_cycle_function::apply)\n .collect(Collectors.toList());\n Function moduloTesters = i -> cycle_functions.stream()\n .map(fcn->fcn.apply(i))\n .collect(Collectors.joining());\n BiFunction formatter = \n (i,printThis) -> \"\".equals(printThis)?Integer.toString(i):printThis; \n Function fizzBuzz = i -> formatter.apply(i,moduloTesters.apply(i));\n \n IntStream.rangeClosed(0,Integer.parseInt(args[args.length-1]))\n .mapToObj(Integer::valueOf)\n .map(fizzBuzz::apply)\n .forEach(System.out::println);\n }\n}\n\n","human_summarization":"The code takes a maximum number and a list of factors with corresponding words as input from the user. It then prints numbers from 1 to the maximum number, replacing multiples of the factors with their corresponding words. If a number is a multiple of more than one factor, it prints all corresponding words in the order of the factors.","id":277} {"lang_cluster":"Java","source_code":"\n\nString string = \"def\";\nstring = \"abc\" + string;\n\n\nString string = \"def\";\nstring = \"abc\".concat(string);\n\n\nStringBuilder string = new StringBuilder();\nstring.append(\"def\");\nstring.insert(0, \"abc\");\n\n\nString string = \"def\";\nstring = String.format(\"abc%s\", string);\n\nString string = \"def\";\nstring = \"abc%s\".formatted(string);\n\n\nabcdef\n\n","human_summarization":"create a string variable and prepend it with another string literal using various methods such as basic concatenation, String.concat, StringBuilder.insert, and String.format or String.formatted methods. Java does not have a built-in prepend method. The code demonstrates all these operations and shows the resulting string.","id":278} {"lang_cluster":"Java","source_code":"\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.util.*;\nimport javax.swing.JFrame;\n\npublic class DragonCurve extends JFrame {\n\n private List turns;\n private double startingAngle, side;\n\n public DragonCurve(int iter) {\n super(\"Dragon Curve\");\n setBounds(100, 100, 800, 600);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n turns = getSequence(iter);\n startingAngle = -iter * (Math.PI \/ 4);\n side = 400 \/ Math.pow(2, iter \/ 2.);\n }\n\n public List getSequence(int iterations) {\n List turnSequence = new ArrayList();\n for (int i = 0; i < iterations; i++) {\n List copy = new ArrayList(turnSequence);\n Collections.reverse(copy);\n turnSequence.add(1);\n for (Integer turn : copy) {\n turnSequence.add(-turn);\n }\n }\n return turnSequence;\n }\n\n @Override\n public void paint(Graphics g) {\n g.setColor(Color.BLACK);\n double angle = startingAngle;\n int x1 = 230, y1 = 350;\n int x2 = x1 + (int) (Math.cos(angle) * side);\n int y2 = y1 + (int) (Math.sin(angle) * side);\n g.drawLine(x1, y1, x2, y2);\n x1 = x2;\n y1 = y2;\n for (Integer turn : turns) {\n angle += turn * (Math.PI \/ 2);\n x2 = x1 + (int) (Math.cos(angle) * side);\n y2 = y1 + (int) (Math.sin(angle) * side);\n g.drawLine(x1, y1, x2, y2);\n x1 = x2;\n y1 = y2;\n }\n }\n\n public static void main(String[] args) {\n new DragonCurve(14).setVisible(true);\n }\n}\n\n","human_summarization":"generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.","id":279} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 6+\npublic class Guessing {\n public static void main(String[] args) throws NumberFormatException{\n int n = (int)(Math.random() * 10 + 1);\n System.out.print(\"Guess the number between 1 and 10: \");\n while(Integer.parseInt(System.console().readLine()) != n){\n System.out.print(\"Wrong! Guess again: \");\n }\n System.out.println(\"Well guessed!\");\n }\n}\n\n\n","human_summarization":"The code generates a random number between 1 and 10. It then prompts the user to guess the number. If the guess is incorrect, the user is prompted to guess again. This process continues until the user guesses the correct number. Once the correct number is guessed, the program displays a \"Well guessed!\" message and terminates. For versions prior to Java 6, input is handled via a Scanner or BufferedReader instead of System.console().","id":280} {"lang_cluster":"Java","source_code":"\nchar[] lowerAlphabet() {\n char[] letters = new char[26];\n for (int code = 97; code < 123; code++)\n letters[code - 97] = (char) code;\n return letters;\n}\n\nabcdefghijklmnopqrstuvwxyz\n\n\npublic class LowerAscii {\n\n public static void main(String[] args) {\n StringBuilder sb = new StringBuilder(26);\n for (char ch = 'a'; ch <= 'z'; ch++)\n sb.append(ch);\n System.out.printf(\"lower ascii: %s, length: %s\", sb, sb.length());\n }\n}\n\n\nlower ascii: abcdefghijklmnopqrstuvwxyz, length: 26\n","human_summarization":"generates a sequence of all lower case ASCII characters from a to z, either through accessing a standard library or creating a similar sequence. The coding style used is robust and suitable for large programs, and strong typing is used if available. The code avoids manually enumerating all lowercase characters to prevent bugs.","id":281} {"lang_cluster":"Java","source_code":"\n\nInteger.toBinaryString(5);\n\nInteger.toBinaryString(50);\n\nInteger.toBinaryString(9000);\n\n\n101\n110010\n10001100101000\n\n","human_summarization":"The code takes a non-negative integer as input and outputs its binary representation. It uses either built-in radix functions or a user-defined function to achieve this. The output is a sequence of binary digits followed by a newline, with no whitespace, radix, sign markers, or leading zeros. The Integer class's toBinaryString method is used for this conversion.","id":282} {"lang_cluster":"Java","source_code":"\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.DoubleSummaryStatistics;\nimport java.util.List;\n\npublic final class MergeAndAggregateDatasets {\n\n\tpublic static void main(String[] args) {\n\t\tList patients = Arrays.asList(\n\t\t\tnew Patient(\"1001\", \"Hopper\"),\n\t\t\tnew Patient(\"4004\", \"Wirth\"),\n\t\t\tnew Patient(\"3003\", \"Kemeny\"),\n\t\t\tnew Patient(\"2002\", \"Gosling\"),\n\t\t\tnew Patient(\"5005\", \"Kurtz\") );\n\n\t\tList visits = Arrays.asList(\t\t\t\t\n\t\t new Visit(\"2002\", \"2020-09-10\", 6.8),\n\t\t new Visit(\"1001\", \"2020-09-17\", 5.5),\n\t\t new Visit(\"4004\", \"2020-09-24\", 8.4),\n\t\t new Visit(\"2002\", \"2020-10-08\", null),\n\t\t new Visit(\"1001\", \"\" , 6.6),\n\t\t new Visit(\"3003\", \"2020-11-12\", null),\n\t\t new Visit(\"4004\", \"2020-11-05\", 7.0),\n\t\t new Visit(\"1001\", \"2020-11-19\", 5.3) );\n\t\t\n\t\tCollections.sort(patients, Comparator.comparing(Patient::patientID));\t\t\n\t\tSystem.out.println(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\t\t\n\t for ( Patient patient : patients ) {\t \t\n\t \tList patientVisits = visits.stream().filter( v -> v.visitID == patient.patientID() ).toList();\n\t \tString lastVisit = patientVisits.stream()\n\t \t\t.map( v -> v.visitDate ).max(Comparator.naturalOrder()).orElseGet( () -> \" None \" );\t \t\n\t \tDoubleSummaryStatistics statistics = patientVisits.stream()\n\t \t\t.filter( v -> v.score != null ).mapToDouble(Visit::score).summaryStatistics();\t \t\t \t\n\t \tdouble scoreSum = statistics.getSum();\n\t \tdouble scoreAverage = statistics.getAverage();\t \t\n\t \tString patientDetails = String.format(\"%12s%11s%13s%12.2f%12.2f\", \n\t \t\tpatient.patientID, patient.lastName, lastVisit, scoreSum, scoreAverage);\t \t\n\t \tSystem.out.println(patientDetails);\n\t }\n\n private static record Patient(String patientID, String lastName) {};\n\t private static record Visit(String visitID, String visitDate, Double score) {};\n\n\t} \n\n}\n\n\n","human_summarization":"\"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file.\"","id":283} {"lang_cluster":"Java","source_code":"\n\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport javax.swing.JFrame;\n\npublic class DrawAPixel extends JFrame{\n\tpublic DrawAPixel() {\n\t\tsuper(\"Red Pixel\");\n\t\tsetSize(320, 240);\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\tsetVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics g) {\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n\n\nimport java.awt.Color;\nimport java.awt.Graphics;\nimport java.awt.image.BufferedImage;\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\npublic class DrawAPixel extends JPanel{\t\n\tprivate BufferedImage puffer;\n\tprivate JFrame window;\n\tprivate Graphics g;\n\tpublic DrawAPixel() {\n\t\twindow = new JFrame(\"Red Pixel\");\n\t\twindow.setSize(320, 240);\n\t\twindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\t\twindow.setLayout(null);\n\t\tsetBounds(0, 0, 320, 240);\n\t\twindow.add(this);\n\t\twindow.setVisible(true);\n\t}\n\t@Override\n\tpublic void paint(Graphics gr) {\n\t\tif(g == null) {\n\t\t\tpuffer = (BufferedImage) createImage(getWidth(), getHeight());\n\t\t\tg = puffer.getGraphics();\n\t\t}\n\t\tg.setColor(new Color(255, 0, 0));\n\t\tg.drawRect(100, 100, 1, 1);\n\t\tgr.drawImage(puffer, 0, 0, this);\n\t}\n\tpublic static void main(String[] args) {\n\t\tnew DrawAPixel();\n\t}\n}\n\n","human_summarization":"create a 320x240 window and draw a red pixel at the position (100,100). The implementation is done via subclasses of JFrame and JPanel.","id":284} {"lang_cluster":"Java","source_code":"\n\nimport java.io.BufferedReader;\nimport java.io.FileReader;\nimport java.io.IOException;\nimport java.util.Arrays;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class ConfigReader {\n private static final Pattern LINE_PATTERN = Pattern.compile( \"([^ =]+)[ =]?(.*)\" );\n private static final Map DEFAULTS = new HashMap() {{\n put( \"needspeeling\", false );\n put( \"seedsremoved\", false );\n }};\n\n public static void main( final String[] args ) {\n System.out.println( parseFile( args[ 0 ] ) );\n }\n\n public static Map parseFile( final String fileName ) {\n final Map result = new HashMap( DEFAULTS );\n \/*v*\/ BufferedReader reader = null;\n\n try {\n reader = new BufferedReader( new FileReader( fileName ) );\n for ( String line; null != ( line = reader.readLine() ); ) {\n parseLine( line, result );\n }\n } catch ( final IOException x ) {\n throw new RuntimeException( \"Oops: \" + x, x );\n } finally {\n if ( null != reader ) try {\n reader.close();\n } catch ( final IOException x2 ) {\n System.err.println( \"Could not close \" + fileName + \" - \" + x2 );\n }\n }\n\n return result;\n }\n\n private static void parseLine( final String line, final Map map ) {\n if ( \"\".equals( line.trim() ) || line.startsWith( \"#\" ) || line.startsWith( \";\" ) )\n return;\n\n final Matcher matcher = LINE_PATTERN.matcher( line );\n\n if ( ! matcher.matches() ) {\n System.err.println( \"Bad config line: \" + line );\n return;\n }\n\n final String key = matcher.group( 1 ).trim().toLowerCase();\n final String value = matcher.group( 2 ).trim();\n\n if ( \"\".equals( value ) ) {\n map.put( key, true );\n } else if ( -1 == value.indexOf( ',' ) ) {\n map.put( key, value );\n } else {\n final String[] values = value.split( \",\" );\n\n for ( int i = 0; i < values.length; i++ ) {\n values[ i ] = values[ i ].trim();\n }\n map.put( key, Arrays.asList( values ) );\n }\n }\n}\n\n\n","human_summarization":"The code reads a standard configuration file, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration entries, treats boolean values accordingly, and handles multiple parameters as an array. It does not rely on the Properties.load(InputStream) method due to the optional equals sign in the data format. The code uses a functional and concise approach with Java 8.","id":285} {"lang_cluster":"Java","source_code":"public class Haversine {\n public static final double R = 6372.8; \/\/ In kilometers\n\n public static double haversine(double lat1, double lon1, double lat2, double lon2) {\n lat1 = Math.toRadians(lat1);\n lat2 = Math.toRadians(lat2);\n double dLat = lat2 - lat1;\n double dLon = Math.toRadians(lon2 - lon1);\n\n double a = Math.pow(Math.sin(dLat \/ 2), 2) + Math.pow(Math.sin(dLon \/ 2), 2) * Math.cos(lat1) * Math.cos(lat2);\n double c = 2 * Math.asin(Math.sqrt(a));\n return R * c;\n }\n\n public static void main(String[] args) {\n System.out.println(haversine(36.12, -86.67, 33.94, -118.40));\n }\n}\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":286} {"lang_cluster":"Java","source_code":"\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\n\nvoid printContent(String address) throws URISyntaxException, IOException {\n URL url = new URI(address).toURL();\n try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) {\n String line;\n while ((line = reader.readLine()) != null)\n System.out.println(line);\n }\n}\n\n\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.Charset;\n\npublic class Main {\n public static void main(String[] args) {\n var request = HttpRequest.newBuilder(URI.create(\"https:\/\/www.rosettacode.org\"))\n .GET()\n .build();\n\n HttpClient.newHttpClient()\n .sendAsync(request, HttpResponse.BodyHandlers.ofString(Charset.defaultCharset()))\n .thenApply(HttpResponse::body)\n .thenAccept(System.out::println)\n .join();\n }\n}\n\nLibrary: Apache Commons IO\nimport org.apache.commons.io.IOUtils;\nimport java.net.URL;\n\npublic class Main {\t\n public static void main(String[] args) throws Exception {\n IOUtils.copy(new URL(\"http:\/\/rosettacode.org\").openStream(),System.out); \t \t \t\t \n }\n}\n\n","human_summarization":"Access and print the content of a URL using the openStream method of the URL class and the standard Java 11 HTTP Client. Note that this does not cover HTTPS requests.","id":287} {"lang_cluster":"Java","source_code":"\npublic class Luhn {\n public static void main(String[] args) {\n System.out.println(luhnTest(\"49927398716\"));\n System.out.println(luhnTest(\"49927398717\"));\n System.out.println(luhnTest(\"1234567812345678\"));\n System.out.println(luhnTest(\"1234567812345670\"));\n }\n \n public static boolean luhnTest(String number){\n int s1 = 0, s2 = 0;\n String reverse = new StringBuffer(number).reverse().toString();\n for(int i = 0 ;i < reverse.length();i++){\n int digit = Character.digit(reverse.charAt(i), 10);\n if(i % 2 == 0){\/\/this is for odd digits, they are 1-indexed in the algorithm\n s1 += digit;\n }else{\/\/add 2 * digit for 0-4, add 2 * digit - 9 for 5-9\n s2 += 2 * digit;\n if(digit >= 5){\n s2 -= 9;\n }\n }\n }\n return (s1 + s2) % 10 == 0;\n }\n}\n\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":288} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\nimport java.util.ArrayList;\n\npublic class Josephus {\n public static int execute(int n, int k){\n int killIdx = 0;\n ArrayList prisoners = new ArrayList(n);\n for(int i = 0;i < n;i++){\n prisoners.add(i);\n }\n System.out.println(\"Prisoners executed in order:\");\n while(prisoners.size() > 1){\n killIdx = (killIdx + k - 1) % prisoners.size();\n System.out.print(prisoners.get(killIdx) + \" \");\n prisoners.remove(killIdx);\n }\n System.out.println();\n return prisoners.get(0);\n }\n \n public static ArrayList executeAllButM(int n, int k, int m){\n int killIdx = 0;\n ArrayList prisoners = new ArrayList(n);\n for(int i = 0;i < n;i++){\n prisoners.add(i);\n }\n System.out.println(\"Prisoners executed in order:\");\n while(prisoners.size() > m){\n killIdx = (killIdx + k - 1) % prisoners.size();\n System.out.print(prisoners.get(killIdx) + \" \");\n prisoners.remove(killIdx);\n }\n System.out.println();\n return prisoners;\n }\n \n public static void main(String[] args){\n System.out.println(\"Survivor: \" + execute(41, 3));\n System.out.println(\"Survivors: \" + executeAllButM(41, 3, 3));\n }\n}\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":289} {"lang_cluster":"Java","source_code":"\n\n\"ha\".repeat(5);\n\n\nString[] strings = new String[5];\nArrays.fill(strings, \"ha\");\nStringBuilder repeated = new StringBuilder();\nfor (String string\u00a0: strings)\n repeated.append(string);\n\nString string = \"ha\";\nStringBuilder repeated = new StringBuilder();\nint count = 5;\nwhile (count-- > 0)\n repeated.append(string);\n\nWorks with: Java version 1.5+\n\npublic static String repeat(String str, int times) {\n StringBuilder sb = new StringBuilder(str.length() * times);\n for (int i = 0; i < times; i++)\n sb.append(str);\n return sb.toString();\n}\n\npublic static void main(String[] args) {\n System.out.println(repeat(\"ha\", 5));\n}\n\npublic static String repeat(String str, int times) {\n return new String(new char[times]).replace(\"\\0\", str);\n}\n\n","human_summarization":"implement a function to repeat a given string a specific number of times. It also demonstrates different methods to repeat a single character to form a new string. The methods include using Java 11's String.repeat, Arrays.fill, and a for-loop. It also mentions the use of StringUtils.repeat() method from Apache Commons Lang for versions before Java 11.","id":290} {"lang_cluster":"Java","source_code":"\n\/* match entire string against a pattern *\/\nboolean isNumber = \"-1234.567\".matches(\"-?\\\\d+(?:\\\\.\\\\d+)?\");\n\n\/* substitute part of string using a pattern *\/\nString reduceSpaces = \"a b c d e f\".replaceAll(\" +\", \" \");\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n...\n\/* group capturing example *\/\nPattern pattern = Pattern.compile(\"(?:(https?):\/\/)?([^\/]+)\/(?:([^#]+)(?:#(.+))?)?\");\nMatcher matcher = pattern.matcher(\"https:\/\/rosettacode.org\/wiki\/Regular_expressions#Java\");\nif (matcher.find()) {\n String protocol = matcher.group(1);\n String authority = matcher.group(2);\n String path = matcher.group(3);\n String fragment = matcher.group(4);\n}\n\n\/* split a string using a pattern *\/\nString[] strings = \"abc\\r\\ndef\\r\\nghi\".split(\"\\r\\n?\");\n\n\nWorks with: Java version 1.4+\n\nString str = \"I am a string\";\nif (str.matches(\".*string\")) { \/\/ note: matches() tests if the entire string is a match\n System.out.println(\"ends with 'string'\");\n}\n\n\nimport java.util.regex.*;\nPattern p = Pattern.compile(\"a*b\");\nMatcher m = p.matcher(str);\nwhile (m.find()) {\n \/\/ use m.group() to extract matches\n}\n\n\nString orig = \"I am the original string\";\nString result = orig.replaceAll(\"original\", \"modified\");\n\/\/ result is now \"I am the modified string\"\n\n","human_summarization":"\"Matches a string against a regular expression and substitutes part of the string using the matched regular expression.\"","id":291} {"lang_cluster":"Java","source_code":"\nimport java.util.Scanner;\n\npublic class IntegerArithmetic {\n public static void main(String[] args) {\n \/\/ Get the 2 numbers from command line arguments\n Scanner sc = new Scanner(System.in);\n int a = sc.nextInt();\n int b = sc.nextInt();\n\n int sum = a + b; \/\/ The result of adding 'a' and 'b' (Note: integer addition is discouraged in print statements due to confusion with string concatenation)\n int difference = a - b; \/\/ The result of subtracting 'b' from 'a'\n int product = a * b; \/\/ The result of multiplying 'a' and 'b'\n int division = a \/ b; \/\/ The result of dividing 'a' by 'b' (Note: 'division' does not contain the fractional result)\n int remainder = a % b; \/\/ The remainder of dividing 'a' by 'b'\n\n System.out.println(\"a + b = \" + sum);\n System.out.println(\"a - b = \" + difference);\n System.out.println(\"a * b = \" + product);\n System.out.println(\"quotient of a \/ b = \" + division); \/\/ truncates towards 0\n System.out.println(\"remainder of a \/ b = \" + remainder); \/\/ same sign as first operand\n }\n}\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":292} {"lang_cluster":"Java","source_code":"\n\nint countSubstring(String string, String substring) {\n substring = Pattern.quote(substring);\n Pattern pattern = Pattern.compile(substring);\n Matcher matcher = pattern.matcher(string);\n int count = 0;\n while (matcher.find())\n count++;\n return count;\n}\n\n\nWorks with: Java version 1.5+\n\npublic class CountSubstring {\n\tpublic static int countSubstring(String subStr, String str){\n\t\treturn (str.length() - str.replace(subStr, \"\").length()) \/ subStr.length();\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tSystem.out.println(countSubstring(\"th\", \"the three truths\"));\n\t\tSystem.out.println(countSubstring(\"abab\", \"ababababab\"));\n\t\tSystem.out.println(countSubstring(\"a*b\", \"abaabba*bbaba*bbab\"));\n\t}\n}\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of the substring's non-overlapping occurrences. The function works by matching from left to right or right to left, ensuring the highest number of non-overlapping matches. The code may use methods such as regular expression pattern matching, the \"remove and count the difference\" method, the \"split and count\" method, or manual looping.","id":293} {"lang_cluster":"Java","source_code":"\npublic void move(int n, int from, int to, int via) {\n if (n == 1) {\n System.out.println(\"Move disk from pole \" + from + \" to pole \" + to);\n } else {\n move(n - 1, from, via, to);\n move(1, from, to, via);\n move(n - 1, via, to, from);\n }\n}\n\n\n\nExample use:\nmove(3, 1, 2, 3);\n\n\n","human_summarization":"Implement a recursive solution for the Towers of Hanoi problem, where n represents the number of disks to move between three poles: from, to, and via.","id":294} {"lang_cluster":"Java","source_code":"\npublic class Binomial {\n\n \/\/ precise, but may overflow and then produce completely incorrect results\n private static long binomialInt(int n, int k) {\n if (k > n - k)\n k = n - k;\n\n long binom = 1;\n for (int i = 1; i <= k; i++)\n binom = binom * (n + 1 - i) \/ i;\n return binom;\n }\n\n \/\/ same as above, but with overflow check\n private static Object binomialIntReliable(int n, int k) {\n if (k > n - k)\n k = n - k;\n\n long binom = 1;\n for (int i = 1; i <= k; i++) {\n try {\n binom = Math.multiplyExact(binom, n + 1 - i) \/ i;\n } catch (ArithmeticException e) {\n return \"overflow\";\n }\n }\n return binom;\n }\n\n \/\/ using floating point arithmetic, larger numbers can be calculated,\n \/\/ but with reduced precision\n private static double binomialFloat(int n, int k) {\n if (k > n - k)\n k = n - k;\n\n double binom = 1.0;\n for (int i = 1; i <= k; i++)\n binom = binom * (n + 1 - i) \/ i;\n return binom;\n }\n\n \/\/ slow, hard to read, but precise\n private static BigInteger binomialBigInt(int n, int k) {\n if (k > n - k)\n k = n - k;\n\n BigInteger binom = BigInteger.ONE;\n for (int i = 1; i <= k; i++) {\n binom = binom.multiply(BigInteger.valueOf(n + 1 - i));\n binom = binom.divide(BigInteger.valueOf(i));\n }\n return binom;\n }\n\n private static void demo(int n, int k) {\n List data = Arrays.asList(\n n,\n k,\n binomialInt(n, k),\n binomialIntReliable(n, k),\n binomialFloat(n, k),\n binomialBigInt(n, k));\n\n System.out.println(data.stream().map(Object::toString).collect(Collectors.joining(\"\\t\")));\n }\n\n public static void main(String[] args) {\n demo(5, 3);\n demo(1000, 300);\n }\n}\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is capable of outputting the binomial coefficient of (5,3) which is 10. The code also handles tasks related to combinations and permutations, both with and without replacement. It includes a recursive version without an overflow check.","id":295} {"lang_cluster":"Java","source_code":"\npublic static void shell(int[] a) {\n\tint increment = a.length \/ 2;\n\twhile (increment > 0) {\n\t\tfor (int i = increment; i < a.length; i++) {\n\t\t\tint j = i;\n\t\t\tint temp = a[i];\n\t\t\twhile (j >= increment && a[j - increment] > temp) {\n\t\t\t\ta[j] = a[j - increment];\n\t\t\t\tj = j - increment;\n\t\t\t}\n\t\t\ta[j] = temp;\n\t\t}\n\t\tif (increment == 2) {\n\t\t\tincrement = 1;\n\t\t} else {\n\t\t\tincrement *= (5.0 \/ 11);\n\t\t}\n\t}\n}\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell in 1959, uses a diminishing increment sort and a sequence of interleaved insertion sorts. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, which is the best case scenario for insertion sort. The method sorts the array in place, so a copy should be used if the original array needs to be preserved. It has been found that a geometric increment sequence with a ratio of about 2.2 works well in practice.","id":296} {"lang_cluster":"Java","source_code":"\nvoid convertToGrayscale(final BufferedImage image){\n for(int i=0; i> 24) & 255;\n int red = (color >> 16) & 255;\n int green = (color >> 8) & 255;\n int blue = (color) & 255;\n\n final int lum = (int)(0.2126 * red + 0.7152 * green + 0.0722 * blue);\n\n alpha = (alpha << 24);\n red = (lum << 16);\n green = (lum << 8);\n blue = lum;\n\n color = alpha + red + green + blue;\n\n image.setRGB(i,j,color);\n }\n }\n}\n\n","human_summarization":"extend the data storage type to support grayscale images, define operations to convert a color image to grayscale and vice versa using the CIE recommended formula for luminance, and ensure no rounding errors or distorted results occur when storing calculated luminance as an unsigned integer.","id":297} {"lang_cluster":"Java","source_code":"\nLibrary: Swing\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.event.WindowAdapter;\nimport java.awt.event.WindowEvent;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.WindowConstants;\n\npublic class Rotate {\n\n private static class State {\n private final String text = \"Hello World! \";\n private int startIndex = 0;\n private boolean rotateRight = true;\n }\n\n public static void main(String[] args) {\n State state = new State();\n\n JLabel label = new JLabel(state.text);\n label.addMouseListener(new MouseAdapter() {\n @Override\n public void mouseClicked(MouseEvent event) {\n state.rotateRight = !state.rotateRight;\n }\n });\n\n TimerTask task = new TimerTask() {\n public void run() {\n int delta = state.rotateRight ? 1 : -1;\n state.startIndex = (state.startIndex + state.text.length() + delta) % state.text.length();\n label.setText(rotate(state.text, state.startIndex));\n }\n };\n Timer timer = new Timer(false);\n timer.schedule(task, 0, 500);\n\n JFrame rot = new JFrame();\n rot.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);\n rot.add(label);\n rot.pack();\n rot.setLocationRelativeTo(null);\n rot.addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosed(WindowEvent e) {\n timer.cancel();\n }\n });\n rot.setVisible(true);\n }\n\n private static String rotate(String text, int startIdx) {\n char[] rotated = new char[text.length()];\n for (int i = 0; i < text.length(); i++) {\n rotated[i] = text.charAt((i + startIdx) % text.length());\n }\n return String.valueOf(rotated);\n }\n}\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":298} {"lang_cluster":"Java","source_code":"\nint val = 0;\ndo{\n val++;\n System.out.println(val);\n}while(val % 6 != 0);\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":299} {"lang_cluster":"Java","source_code":"\n\nString s = \"Hello, world!\"; \nint byteCountUTF16 = s.getBytes(\"UTF-16\").length; \/\/ Incorrect: it yields 28 (that is with the BOM)\nint byteCountUTF16LE = s.getBytes(\"UTF-16LE\").length; \/\/ Correct: it yields 26\nint byteCountUTF8 = s.getBytes(\"UTF-8\").length; \/\/ yields 13\n\n\nString s = \"Hello, world!\";\nint not_really_the_length = s.length(); \/\/ XXX: does not (always) count Unicode characters (code points)!\n\n\nString str = \"\\uD834\\uDD2A\"; \/\/U+1D12A\nint not_really__the_length = str.length(); \/\/ value is 2, which is not the length in characters\nint actual_length = str.codePointCount(0, str.length()); \/\/ value is 1, which is the length in characters\n\n\nimport java.text.BreakIterator;\n\npublic class Grapheme {\n public static void main(String[] args) {\n printLength(\"m\u00f8\u00f8se\");\n printLength(\"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\");\n printLength(\"J\u0332o\u0332s\u0332\u00e9\u0332\");\n }\n \n public static void printLength(String s) {\n BreakIterator it = BreakIterator.getCharacterInstance();\n it.setText(s);\n int count = 0;\n while (it.next() != BreakIterator.DONE) {\n count++;\n }\n System.out.println(\"Grapheme length: \" + count+ \" \" + s);\n }\n}\n\n\nGrapheme length: 5 m\u00f8\u00f8se\nGrapheme length: 7 \ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\nGrapheme length: 4 J\u0332o\u0332s\u0332\u00e9\u0332\n\n","human_summarization":"determine the character and byte length of a string, considering UTF-8 and UTF-16 encodings. The character length is defined by Unicode code points, not user-visible graphemes or code unit counts. The codes also handle non-BMP code points correctly. For strings encoded in UTF-16, the codes determine the actual number of characters by calling the codePointCount method, not the length method of String objects. The byte length can be determined by specifying the desired charset.","id":300} {"lang_cluster":"Java","source_code":"\nimport java.security.SecureRandom;\n\npublic class RandomExample {\n public static void main(String[] args) {\n SecureRandom rng = new SecureRandom();\n\n \/* Prints a random signed 32-bit integer. *\/\n System.out.println(rng.nextInt());\n }\n}\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.","id":301} {"lang_cluster":"Java","source_code":"\n\npublic class RM_chars {\n public static void main( String[] args ){\n System.out.println( \"knight\".substring( 1 ) );\n System.out.println( \"socks\".substring( 0, 4 ) );\n System.out.println( \"brooms\".substring( 1, 5 ) );\n \/\/ first, do this by selecting a specific substring\n \/\/ to exclude the first and last characters\n \n System.out.println( \"knight\".replaceAll( \"^.\", \"\" ) );\n System.out.println( \"socks\".replaceAll( \".$\", \"\" ) );\n System.out.println( \"brooms\".replaceAll( \"^.|.$\", \"\" ) );\n \/\/ then do this using a regular expressions\n }\n}\n\n\nnight\nsock\nroom\nnight\nsock\nroom\n\npublic class SubstringTopAndTail {\n public static void main( String[] args ){\n var s = \"\\uD83D\\uDC0Eabc\\uD83D\\uDC0E\"; \/\/ Horse emoji, a, b, c, horse emoji: \"\ud83d\udc0eabc\ud83d\udc0e\"\n\n var sizeOfFirstChar = Character.isSurrogate(s.charAt(0)) ? 2 : 1;\n var sizeOfLastChar = Character.isSurrogate(s.charAt(s.length() - 1)) ? 2 : 1;\n\n var removeFirst = s.substring(sizeOfFirstChar);\n var removeLast = s.substring(0, s.length() - sizeOfLastChar);\n var removeBoth = s.substring(sizeOfFirstChar, s.length() - sizeOfLastChar);\n\n System.out.println(removeFirst);\n System.out.println(removeLast);\n System.out.println(removeBoth);\n }\n}\n\n\nabc\ud83d\udc0e\n\ud83d\udc0eabc\nabc\n","human_summarization":"demonstrate how to remove the first and last characters from a string. It supports both UTF-8 and UTF-16 encodings and works with any valid Unicode code point. The program uses logical characters (code points) instead of 8-bit or 16-bit code units. The code provides solutions using both substring method and regular expressions.","id":302} {"lang_cluster":"Java","source_code":"\nimport java.io.IOException;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.net.UnknownHostException;\n \npublic class SingletonApp\n{\n private static final int PORT = 65000; \/\/ random large port number\n private static ServerSocket s;\n\n \/\/ static initializer\n static {\n try {\n s = new ServerSocket(PORT, 10, InetAddress.getLocalHost());\n } catch (UnknownHostException e) {\n \/\/ shouldn't happen for localhost\n } catch (IOException e) {\n \/\/ port taken, so app is already running\n System.out.print(\"Application is already running,\");\n System.out.println(\" so terminating this instance.\");\n System.exit(0);\n }\n }\n\n public static void main(String[] args) {\n System.out.print(\"OK, only this instance is running\");\n System.out.println(\" but will terminate in 10 seconds.\");\n try {\n Thread.sleep(10000);\n if (s != null && !s.isClosed()) s.close();\n } catch (Exception e) {\n System.err.println(e);\n }\n }\n}\n\n","human_summarization":"\"Check if an application instance is already running, display a message if so, and terminate the program.\"","id":303} {"lang_cluster":"Java","source_code":"\nimport java.awt.*;\nimport javax.swing.JFrame;\n\npublic class Test extends JFrame {\n\n public static void main(String[] args) {\n new Test();\n }\n\n Test() {\n Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n Dimension screenSize = toolkit.getScreenSize();\n System.out.println(\"Physical screen size: \" + screenSize);\n\n Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration());\n System.out.println(\"Insets: \" + insets);\n\n screenSize.width -= (insets.left + insets.right);\n screenSize.height -= (insets.top + insets.bottom);\n System.out.println(\"Max available: \" + screenSize);\n }\n}\n\n\nPhysical screen size: java.awt.Dimension[width=1920,height=1080]\nInsets: java.awt.Insets[top=0,left=0,bottom=30,right=0]\nMax available: java.awt.Dimension[width=1920,height=1050]\n","human_summarization":"determine the maximum height and width of a window that can fit on the screen's physical display area, considering window decorations, menubars, multiple monitors, and tiling window managers.","id":304} {"lang_cluster":"Java","source_code":"\npublic class Sudoku\n{\n private int mBoard[][];\n private int mBoardSize;\n private int mBoxSize;\n private boolean mRowSubset[][];\n private boolean mColSubset[][];\n private boolean mBoxSubset[][];\n \n public Sudoku(int board[][]) {\n mBoard = board;\n mBoardSize = mBoard.length;\n mBoxSize = (int)Math.sqrt(mBoardSize);\n initSubsets();\n }\n \n public void initSubsets() {\n mRowSubset = new boolean[mBoardSize][mBoardSize];\n mColSubset = new boolean[mBoardSize][mBoardSize];\n mBoxSubset = new boolean[mBoardSize][mBoardSize];\n for(int i = 0; i < mBoard.length; i++) {\n for(int j = 0; j < mBoard.length; j++) {\n int value = mBoard[i][j];\n if(value != 0) {\n setSubsetValue(i, j, value, true);\n }\n }\n }\n }\n \n private void setSubsetValue(int i, int j, int value, boolean present) {\n mRowSubset[i][value - 1] = present;\n mColSubset[j][value - 1] = present;\n mBoxSubset[computeBoxNo(i, j)][value - 1] = present;\n }\n \n public boolean solve() {\n return solve(0, 0);\n }\n \n public boolean solve(int i, int j) {\n if(i == mBoardSize) {\n i = 0;\n if(++j == mBoardSize) {\n return true;\n }\n }\n if(mBoard[i][j] != 0) {\n return solve(i + 1, j);\n }\n for(int value = 1; value <= mBoardSize; value++) {\n if(isValid(i, j, value)) {\n mBoard[i][j] = value;\n setSubsetValue(i, j, value, true);\n if(solve(i + 1, j)) {\n return true;\n }\n setSubsetValue(i, j, value, false);\n }\n }\n \n mBoard[i][j] = 0;\n return false;\n }\n \n private boolean isValid(int i, int j, int val) {\n val--;\n boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];\n return !isPresent;\n }\n \n private int computeBoxNo(int i, int j) {\n int boxRow = i \/ mBoxSize;\n int boxCol = j \/ mBoxSize;\n return boxRow * mBoxSize + boxCol;\n }\n \n public void print() {\n for(int i = 0; i < mBoardSize; i++) {\n if(i % mBoxSize == 0) {\n System.out.println(\" -----------------------\");\n }\n for(int j = 0; j < mBoardSize; j++) {\n if(j % mBoxSize == 0) {\n System.out.print(\"| \");\n }\n System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : \"-\");\n System.out.print(' ');\n }\n \n System.out.println(\"|\");\n }\n \n System.out.println(\" -----------------------\");\n }\n\n public static void main(String[] args) {\n int[][] board = { \n {8, 5, 0, 0, 0, 2, 4, 0, 0},\n {7, 2, 0, 0, 0, 0, 0, 0, 9},\n {0, 0, 4, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 1, 0, 7, 0, 0, 2},\n {3, 0, 5, 0, 0, 0, 9, 0, 0},\n {0, 4, 0, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 8, 0, 0, 7, 0},\n {0, 1, 7, 0, 0, 0, 0, 0, 0},\n {0, 0, 0, 0, 3, 6, 0, 4, 0}\n };\n Sudoku s = new Sudoku(board);\n System.out.print(\"Starting grid:\\n\");\n s.print(); \n if (s.solve()) {\n System.out.print(\"\\nSolution:\\n\");\n s.print();\n } else {\n System.out.println(\"\\nUnsolvable!\");\n }\n }\n}\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":305} {"lang_cluster":"Java","source_code":"\nimport java.util.Random;\n\npublic static final Random gen = new Random();\n\n\/\/ version for array of ints\npublic static void shuffle (int[] array) {\n int n = array.length;\n while (n > 1) {\n int k = gen.nextInt(n--); \/\/decrements after using the value\n int temp = array[n];\n array[n] = array[k];\n array[k] = temp;\n }\n}\n\/\/ version for array of references\npublic static void shuffle (Object[] array) {\n int n = array.length;\n while (n > 1) {\n int k = gen.nextInt(n--); \/\/decrements after using the value\n Object temp = array[n];\n array[n] = array[k];\n array[k] = temp;\n }\n}\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":306} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\nimport java.text.*;\nimport java.util.*;\n\npublic class LastFridays {\n\n public static void main(String[] args) throws Exception {\n int year = Integer.parseInt(args[0]);\n GregorianCalendar c = new GregorianCalendar(year, 0, 1);\n\n for (String mon : new DateFormatSymbols(Locale.US).getShortMonths()) {\n if (!mon.isEmpty()) {\n int totalDaysOfMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);\n c.set(Calendar.DAY_OF_MONTH, totalDaysOfMonth);\n\n int daysToRollBack = (c.get(Calendar.DAY_OF_WEEK) + 1) % 7;\n\n int day = totalDaysOfMonth - daysToRollBack;\n c.set(Calendar.DAY_OF_MONTH, day);\n\n System.out.printf(\"%d %s %d\\n\", year, mon, day);\n\n c.set(year, c.get(Calendar.MONTH) + 1, 1);\n }\n }\n }\n}\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":307} {"lang_cluster":"Java","source_code":"\npublic class HelloWorld\n{\n public static void main(String[] args)\n {\n System.out.print(\"Goodbye, World!\");\n }\n}\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":308} {"lang_cluster":"Java","source_code":"\nLibrary: Swing\nimport javax.swing.*;\n\npublic class GetInputSwing {\n public static void main(String[] args) throws Exception {\n int number = Integer.parseInt(\n JOptionPane.showInputDialog (\"Enter an Integer\"));\n String string = JOptionPane.showInputDialog (\"Enter a String\");\n }\n}\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":309} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\npublic class Cipher {\n public static void main(String[] args) {\n\n String str = \"The quick brown fox Jumped over the lazy Dog\";\n\n System.out.println( Cipher.encode( str, 12 ));\n System.out.println( Cipher.decode( Cipher.encode( str, 12), 12 ));\n }\n\n public static String decode(String enc, int offset) {\n return encode(enc, 26-offset);\n }\n\n public static String encode(String enc, int offset) {\n offset = offset % 26 + 26;\n StringBuilder encoded = new StringBuilder();\n for (char i : enc.toCharArray()) {\n if (Character.isLetter(i)) {\n if (Character.isUpperCase(i)) {\n encoded.append((char) ('A' + (i - 'A' + offset) % 26 ));\n } else {\n encoded.append((char) ('a' + (i - 'a' + offset) % 26 ));\n }\n } else {\n encoded.append(i);\n }\n }\n return encoded.toString();\n }\n}\n\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":310} {"lang_cluster":"Java","source_code":"\nimport java.util.Scanner;\n\npublic class LCM{\n public static void main(String[] args){\n Scanner aScanner = new Scanner(System.in);\n \n \/\/prompts user for values to find the LCM for, then saves them to m and n\n System.out.print(\"Enter the value of m:\");\n int m = aScanner.nextInt();\n System.out.print(\"Enter the value of n:\");\n int n = aScanner.nextInt();\n int lcm = (n == m || n == 1) ? m :(m == 1 ? n : 0);\n \/* this section increases the value of mm until it is greater \n \/ than or equal to nn, then does it again when the lesser \n \/ becomes the greater--if they aren't equal. If either value is 1,\n \/ no need to calculate*\/\n if (lcm == 0) {\n int mm = m, nn = n;\n while (mm != nn) {\n while (mm < nn) { mm += m; }\n while (nn < mm) { nn += n; }\n } \n lcm = mm;\n }\n System.out.println(\"lcm(\" + m + \", \" + n + \") = \" + lcm);\n }\n}\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":311} {"lang_cluster":"Java","source_code":"\nimport java.util.List;\n\npublic class Cusip {\n private static Boolean isCusip(String s) {\n if (s.length() != 9) return false;\n int sum = 0;\n for (int i = 0; i <= 7; i++) {\n char c = s.charAt(i);\n\n int v;\n if (c >= '0' && c <= '9') {\n v = c - 48;\n } else if (c >= 'A' && c <= 'Z') {\n v = c - 55; \/\/ lower case letters apparently invalid\n } else if (c == '*') {\n v = 36;\n } else if (c == '@') {\n v = 37;\n } else if (c == '#') {\n v = 38;\n } else {\n return false;\n }\n if (i % 2 == 1) v *= 2; \/\/ check if odd as using 0-based indexing\n sum += v \/ 10 + v % 10;\n }\n return s.charAt(8) - 48 == (10 - (sum % 10)) % 10;\n }\n\n public static void main(String[] args) {\n List candidates = List.of(\n \"037833100\", \"17275R102\", \"38259P508\", \"594918104\", \"68389X106\", \"68389X105\", \"EXTRACRD8\",\n \"EXTRACRD9\", \"BADCUSIP!\", \"683&9X106\", \"68389x105\", \"683$9X106\", \"68389}105\", \"87264ABE4\"\n );\n for (String candidate : candidates) {\n System.out.printf(\"%s -> %s%n\", candidate, isCusip(candidate) ? \"correct\" : \"incorrect\");\n }\n }\n}\n\n\n","human_summarization":"The code validates the last digit (check digit) of a CUSIP code, a nine-character alphanumeric identifier for North American financial securities. It uses an algorithm that calculates the sum of the values of each character in the CUSIP code, with special conditions for digits, letters, and special characters. The check digit is then verified against this calculated sum. The code is written in Java 9.","id":312} {"lang_cluster":"Java","source_code":"\n\nWorks with: Java version 1.4\nimport java.nio.ByteOrder;\n\npublic class ShowByteOrder {\n public static void main(String[] args) {\n \/\/ Print \"BIG_ENDIAN\" or \"LITTLE_ENDIAN\".\n System.out.println(ByteOrder.nativeOrder());\n }\n}\n\n\nSystem.out.println(\"word size: \"+System.getProperty(\"sun.arch.data.model\"));\nSystem.out.println(\"endianness: \"+System.getProperty(\"sun.cpu.endian\"));\n\n","human_summarization":"determine and print the word size and endianness of the host machine using Java's native byte order property.","id":313} {"lang_cluster":"Java","source_code":"\n\nimport java.net.URL;\nimport java.net.URLConnection;\nimport java.io.*;\nimport java.util.*;\n\npublic class GetRCLanguages\n{\n \/\/ Custom sort Comparator for sorting the language list\n \/\/ assumes the first character is the page count and the rest is the language name\n private static class LanguageComparator implements Comparator\n {\n public int compare( String a, String b )\n {\n \/\/ as we \"know\" we will be comparaing languages, we will assume the Strings have the appropriate format\n int result = ( b.charAt( 0 ) - a.charAt( 0 ) );\n if( result == 0 )\n {\n \/\/ the counts are the same - compare the names\n result = a.compareTo( b );\n } \/\/ if result == 0\n return result;\n } \/\/ compare\n } \/\/ LanguageComparator\n\n \/\/ get the string following marker in text\n private static String after( String text, int marker )\n {\n String result = \"\";\n int pos = text.indexOf( marker );\n if( pos >= 0 )\n {\n \/\/ the marker is in the string\n result = text.substring( pos + 1 );\n } \/\/ if pos >= 0\n return result;\n } \/\/ after\n\n \/\/ read and parse the content of path\n \/\/ results returned in gcmcontinue and languageList\n public static void parseContent( String path\n , String[] gcmcontinue\n , ArrayList languageList\n )\n {\n try\n {\n\n URL url = new URL( path );\n URLConnection rc = url.openConnection();\n \/\/ Rosetta Code objects to the default Java user agant so use a blank one\n rc.setRequestProperty( \"User-Agent\", \"\" );\n BufferedReader bfr = new BufferedReader( new InputStreamReader( rc.getInputStream() ) );\n \n gcmcontinue[0] = \"\";\n String languageName = \"?\";\n String line = bfr.readLine();\n while( line != null )\n {\n line = line.trim();\n if ( line.startsWith( \"[title]\" ) )\n {\n \/\/ have a programming language - should look like \"[title] => Category:languageName\"\n languageName = after( line, ':' ).trim();\n }\n else if( line.startsWith( \"[pages]\" ) )\n {\n \/\/ number of pages the language has (probably)\n String pageCount = after( line, '>' ).trim();\n if( pageCount.compareTo( \"Array\" ) != 0 )\n {\n \/\/ haven't got \"[pages] => Array\" - must be a number of pages\n languageList.add( ( (char) Integer.parseInt( pageCount ) ) + languageName );\n languageName = \"?\";\n } \/\/ if [pageCount.compareTo( \"Array\" )\u00a0!= 0\n }\n else if( line.startsWith( \"[gcmcontinue]\" ) )\n {\n \/\/ have an indication of wether there is more data or not\n gcmcontinue[0] = after( line, '>' ).trim();\n } \/\/ if various line starts\n line = bfr.readLine();\n } \/\/ while line\u00a0!= null\n bfr.close();\n }\n catch( Exception e )\n {\n e.printStackTrace();\n } \/\/ try-catch\n } \/\/ parseContent\n\n public static void main( String[] args )\n {\n \/\/ get the languages\n ArrayList languageList = new ArrayList( 1000 );\n String[] gcmcontinue = new String[1];\n gcmcontinue[0] = \"\";\n do\n {\n String path = ( \"http:\/\/www.rosettacode.org\/mw\/api.php?action=query\"\n + \"&generator=categorymembers\"\n + \"&gcmtitle=Category:Programming%20Languages\"\n + \"&gcmlimit=500\"\n + ( gcmcontinue[0].compareTo( \"\" ) == 0 ? \"\" : ( \"&gcmcontinue=\" + gcmcontinue[0] ) )\n + \"&prop=categoryinfo\"\n + \"&format=txt\"\n );\n parseContent( path, gcmcontinue, languageList );\n }\n while( gcmcontinue[0].compareTo( \"\" ) != 0 );\n \/\/ sort the languages\n String[] languages = languageList.toArray(new String[]{});\n Arrays.sort( languages, new LanguageComparator() );\n \/\/ print the languages\n int lastTie = -1;\n int lastCount = -1;\n for( int lPos = 0; lPos < languages.length; lPos ++ )\n {\n int count = (int) ( languages[ lPos ].charAt( 0 ) );\n System.out.format( \"%4d: %4d: %s\\n\"\n , 1 + ( count == lastCount ? lastTie : lPos )\n , count\n , languages[ lPos ].substring( 1 )\n );\n if( count != lastCount )\n {\n lastTie = lPos;\n lastCount = count;\n } \/\/ if count\u00a0!= lastCount\n } \/\/ for lPos\n } \/\/ main\n} \/\/ GetRCLanguages\n\n\n","human_summarization":"The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It accesses data either through web scraping or the API method. The code also has the option to filter incorrect results. The final output is a complete ranked list of all programming languages.","id":314} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\nIterable collect;\n...\nfor(Type i:collect){\n System.out.println(i);\n}\n\n\nWorks with: Java version 1.8+\nIterable collect;\n...\ncollect.forEach(o -> System.out.println(o));\n\n\n","human_summarization":"Iterates and prints each element in a collection in order using a \"for each\" loop or another loop if \"for each\" is not available. It works with any Iterable and all Collections, but not with arrays.","id":315} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.0+\n\nWorks with: Java version 1.8+\nString toTokenize = \"Hello,How,Are,You,Today\";\nSystem.out.println(String.join(\".\", toTokenize.split(\",\")));\n\nWorks with: Java version 1.4+\nString toTokenize = \"Hello,How,Are,You,Today\";\n\nString words[] = toTokenize.split(\",\");\/\/splits on one comma, multiple commas yield multiple splits\n \/\/toTokenize.split(\",+\") if you want to ignore empty fields\nfor(int i=0; i 1;loop--){\n if(a % loop == 0 && b % loop == 0){\n return loop;\n }\n }\n return 1;\n}\n\npublic static int gcd(int a, int b) \/\/valid for positive integers.\n{\n\twhile(b > 0)\n\t{\n\t\tint c = a % b;\n\t\ta = b;\n\t\tb = c;\n\t}\n\treturn a;\n}\n\nOptimized static int gcd(int a,int b)\n\t{\n\t\tint min=a>b?b:a,max=a+b-min, div=min;\n\t\tfor(int i=1;i>= 1; v >>= 1;\n }\n \n t = (u & 1) != 0 ? -v : u;\n while (t != 0){\n while ((t & 1) == 0) t >>= 1;\n \n if (t > 0)\n u = t;\n else\n v = -t;\n \n t = u - v;\n }\n return u * k;\n}\n\npublic static long gcd(long a, long b){\n if(a == 0) return b;\n if(b == 0) return a;\n if(a > b) return gcd(b, a % b);\n return gcd(a, b % a);\n}\n\nimport java.math.BigInteger;\n\npublic static long gcd(long a, long b){\n return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue();\n}\n\n","human_summarization":"implement a function to find the greatest common divisor (GCD), also known as the greatest common factor (gcf) or greatest common measure, of two integers. This is related to finding the least common multiple. Refer to MathWorld and Wikipedia for more information on the greatest common divisor. The code uses javax.swing.table.DefaultTableModel.","id":317} {"lang_cluster":"Java","source_code":"\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.OutputStreamWriter;\nimport java.io.PrintWriter;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\n\npublic class EchoServer {\n\n public static void main(String[] args) throws IOException {\n try (ServerSocket listener = new ServerSocket(12321)) {\n while (true) {\n Socket conn = listener.accept();\n Thread clientThread = new Thread(() -> handleClient(conn));\n clientThread.start();\n }\n }\n }\n\n private static void handleClient(Socket connArg) {\n Charset utf8 = StandardCharsets.UTF_8;\n\n try (Socket conn = connArg) {\n BufferedReader in = new BufferedReader(\n new InputStreamReader(conn.getInputStream(), utf8));\n\n PrintWriter out = new PrintWriter(\n new OutputStreamWriter(conn.getOutputStream(), utf8),\n true);\n\n String line;\n while ((line = in.readLine()) != null) {\n out.println(line);\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":318} {"lang_cluster":"Java","source_code":"\n\nInteger.parseInt(\"12345\")\n\nFloat.parseFloat(\"123.456\")\n\n\npublic static void main(String[] args) {\n String value;\n value = \"1234567\";\n System.out.printf(\"%-10s %b%n\", value, isInteger(value));\n value = \"12345abc\";\n System.out.printf(\"%-10s %b%n\", value, isInteger(value));\n value = \"-123.456\";\n System.out.printf(\"%-10s %b%n\", value, isFloatingPoint(value));\n value = \"-.456\";\n System.out.printf(\"%-10s %b%n\", value, isFloatingPoint(value));\n value = \"123.\";\n System.out.printf(\"%-10s %b%n\", value, isFloatingPoint(value));\n value = \"123.abc\";\n System.out.printf(\"%-10s %b%n\", value, isFloatingPoint(value));\n}\n\nstatic boolean isInteger(String string) {\n String digits = \"0123456789\";\n for (char character : string.toCharArray()) {\n if (!digits.contains(String.valueOf(character)))\n return false;\n }\n return true;\n}\n\nstatic boolean isFloatingPoint(String string) {\n \/* at least one decimal-point *\/\n int indexOf = string.indexOf('.');\n if (indexOf == -1)\n return false;\n \/* assure only 1 decimal-point *\/\n if (indexOf != string.lastIndexOf('.'))\n return false;\n if (string.charAt(0) == '-' || string.charAt(0) == '+') {\n string = string.substring(1);\n indexOf--;\n }\n String integer = string.substring(0, indexOf);\n if (!integer.isEmpty()) {\n if (!isInteger(integer))\n return false;\n }\n String decimal = string.substring(indexOf + 1);\n if (!decimal.isEmpty())\n return isInteger(decimal);\n return true;\n}\n\n1234567 true\n12345abc false\n-123.456 true\n-.456 true\n123. true\n123.abc false\n\n\npublic boolean isNumeric(String input) {\n try {\n Integer.parseInt(input);\n return true;\n }\n catch (NumberFormatException e) {\n \/\/ s is not numeric\n return false;\n }\n}\n\n\nprivate static final boolean isNumeric(final String s) {\n if (s == null || s.isEmpty()) return false;\n for (int x = 0; x < s.length(); x++) {\n final char c = s.charAt(x);\n if (x == 0 && (c == '-')) continue; \/\/ negative\n if ((c >= '0') && (c <= '9')) continue; \/\/ 0 - 9\n return false; \/\/ invalid\n }\n return true; \/\/ valid\n}\n\n\npublic static boolean isNumeric(String inputData) {\n return inputData.matches(\"[-+]?\\\\d+(\\\\.\\\\d+)?\");\n}\n\n\npublic static boolean isNumeric(String inputData) {\n NumberFormat formatter = NumberFormat.getInstance();\n ParsePosition pos = new ParsePosition(0);\n formatter.parse(inputData, pos);\n return inputData.length() == pos.getIndex();\n}\n\n\npublic static boolean isNumeric(String inputData) {\n Scanner sc = new Scanner(inputData);\n return sc.hasNextInt();\n}\n\n\n","human_summarization":"The code defines a boolean function to check if a given string is numeric, including floating point and negative numbers. It uses different alternatives such as parsing methods from Integer, Long, Float, or Double class, checking each character in the string, using a regular expression, using the positional parser in the java.text.NumberFormat object, and using the java.util.Scanner object. It also handles exceptions and considers performance implications.","id":319} {"lang_cluster":"Java","source_code":"\n\nURL url = new URL(\"https:\/\/sourceforge.net\");\nHttpsURLConnection connection = (HttpsURLConnection) url.openConnection();\nScanner scanner = new Scanner(connection.getInputStream());\n\nwhile (scanner.hasNext()) {\n System.out.println(scanner.next());\n}\n\n\nimport java.net.URI;\nimport java.net.http.HttpClient;\nimport java.net.http.HttpRequest;\nimport java.net.http.HttpResponse;\nimport java.nio.charset.Charset;\n\npublic class Main {\n public static void main(String[] args) {\n var request = HttpRequest.newBuilder(URI.create(\"https:\/\/sourceforge.net\"))\n .GET()\n .build();\n\n HttpClient.newHttpClient()\n .sendAsync(request, HttpResponse.BodyHandlers.ofString(Charset.defaultCharset()))\n .thenApply(HttpResponse::body)\n .thenAccept(System.out::println)\n .join();\n }\n}\n\n","human_summarization":"send a GET request to the URL \"https:\/\/www.w3.org\/\" and print the response to the console without authentication, also check the host certificate for validity using Java 11 HTTP Client and javax.net.ssl.HttpsURLConnection interface.","id":320} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 7\nimport java.awt.*;\nimport java.awt.geom.Line2D;\nimport java.util.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class SutherlandHodgman extends JFrame {\n\n SutherlandHodgmanPanel panel;\n\n public static void main(String[] args) {\n JFrame f = new SutherlandHodgman();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setVisible(true);\n }\n\n public SutherlandHodgman() {\n Container content = getContentPane();\n content.setLayout(new BorderLayout());\n panel = new SutherlandHodgmanPanel();\n content.add(panel, BorderLayout.CENTER);\n setTitle(\"SutherlandHodgman\");\n pack();\n setLocationRelativeTo(null);\n }\n}\n\nclass SutherlandHodgmanPanel extends JPanel {\n List subject, clipper, result;\n\n public SutherlandHodgmanPanel() {\n setPreferredSize(new Dimension(600, 500));\n\n \/\/ these subject and clip points are assumed to be valid\n double[][] subjPoints = {{50, 150}, {200, 50}, {350, 150}, {350, 300},\n {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}};\n\n double[][] clipPoints = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n subject = new ArrayList<>(Arrays.asList(subjPoints));\n result = new ArrayList<>(subject);\n clipper = new ArrayList<>(Arrays.asList(clipPoints));\n\n clipPolygon();\n }\n\n private void clipPolygon() {\n int len = clipper.size();\n for (int i = 0; i < len; i++) {\n\n int len2 = result.size();\n List input = result;\n result = new ArrayList<>(len2);\n\n double[] A = clipper.get((i + len - 1) % len);\n double[] B = clipper.get(i);\n\n for (int j = 0; j < len2; j++) {\n\n double[] P = input.get((j + len2 - 1) % len2);\n double[] Q = input.get(j);\n\n if (isInside(A, B, Q)) {\n if (!isInside(A, B, P))\n result.add(intersection(A, B, P, Q));\n result.add(Q);\n } else if (isInside(A, B, P))\n result.add(intersection(A, B, P, Q));\n }\n }\n }\n\n private boolean isInside(double[] a, double[] b, double[] c) {\n return (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0]);\n }\n\n private double[] intersection(double[] a, double[] b, double[] p, double[] q) {\n double A1 = b[1] - a[1];\n double B1 = a[0] - b[0];\n double C1 = A1 * a[0] + B1 * a[1];\n\n double A2 = q[1] - p[1];\n double B2 = p[0] - q[0];\n double C2 = A2 * p[0] + B2 * p[1];\n\n double det = A1 * B2 - A2 * B1;\n double x = (B2 * C1 - B1 * C2) \/ det;\n double y = (A1 * C2 - A2 * C1) \/ det;\n\n return new double[]{x, y};\n }\n\n @Override\n public void paintComponent(Graphics g) {\n super.paintComponent(g);\n Graphics2D g2 = (Graphics2D) g;\n g2.translate(80, 60);\n g2.setStroke(new BasicStroke(3));\n g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n\n drawPolygon(g2, subject, Color.blue);\n drawPolygon(g2, clipper, Color.red);\n drawPolygon(g2, result, Color.green);\n }\n\n private void drawPolygon(Graphics2D g2, List points, Color color) {\n g2.setColor(color);\n int len = points.size();\n Line2D line = new Line2D.Double();\n for (int i = 0; i < len; i++) {\n double[] p1 = points.get(i);\n double[] p2 = points.get((i + 1) % len);\n line.setLine(p1[0], p1[1], p2[0], p2[1]);\n g2.draw(line);\n }\n }\n}\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":321} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 8\nimport java.util.*;\n\npublic class RankingMethods {\n\n final static String[] input = {\"44 Solomon\", \"42 Jason\", \"42 Errol\",\n \"41 Garry\", \"41 Bernard\", \"41 Barry\", \"39 Stephen\"};\n\n public static void main(String[] args) {\n int len = input.length;\n\n Map map = new TreeMap<>((a, b) -> b.compareTo(a));\n for (int i = 0; i < len; i++) {\n String key = input[i].split(\"\\\\s+\")[0];\n int[] arr;\n if ((arr = map.get(key)) == null)\n arr = new int[]{i, 0};\n arr[1]++;\n map.put(key, arr);\n }\n int[][] groups = map.values().toArray(new int[map.size()][]);\n\n standardRanking(len, groups);\n modifiedRanking(len, groups);\n denseRanking(len, groups);\n ordinalRanking(len);\n fractionalRanking(len, groups);\n }\n\n private static void standardRanking(int len, int[][] groups) {\n System.out.println(\"\\nStandard ranking\");\n for (int i = 0, rank = 0, group = 0; i < len; i++) {\n if (group < groups.length && i == groups[group][0]) {\n rank = i + 1;\n group++;\n }\n System.out.printf(\"%d %s%n\", rank, input[i]);\n }\n }\n\n private static void modifiedRanking(int len, int[][] groups) {\n System.out.println(\"\\nModified ranking\");\n for (int i = 0, rank = 0, group = 0; i < len; i++) {\n if (group < groups.length && i == groups[group][0])\n rank += groups[group++][1];\n System.out.printf(\"%d %s%n\", rank, input[i]);\n }\n }\n\n private static void denseRanking(int len, int[][] groups) {\n System.out.println(\"\\nDense ranking\");\n for (int i = 0, rank = 0; i < len; i++) {\n if (rank < groups.length && i == groups[rank][0])\n rank++;\n System.out.printf(\"%d %s%n\", rank, input[i]);\n }\n }\n\n private static void ordinalRanking(int len) {\n System.out.println(\"\\nOrdinal ranking\");\n for (int i = 0; i < len; i++)\n System.out.printf(\"%d %s%n\", i + 1, input[i]);\n }\n\n private static void fractionalRanking(int len, int[][] groups) {\n System.out.println(\"\\nFractional ranking\");\n float rank = 0;\n for (int i = 0, tmp = 0, group = 0; i < len; i++) {\n if (group < groups.length && i == groups[group][0]) {\n tmp += groups[group++][1];\n rank = (i + 1 + tmp) \/ 2.0F;\n }\n System.out.printf(\"%2.1f %s%n\", rank, input[i]);\n }\n }\n}\n\nStandard ranking\n1 44 Solomon\n2 42 Jason\n2 42 Errol\n4 41 Garry\n4 41 Bernard\n4 41 Barry\n7 39 Stephen\n\nModified ranking\n1 44 Solomon\n3 42 Jason\n3 42 Errol\n6 41 Garry\n6 41 Bernard\n6 41 Barry\n7 39 Stephen\n\nDense ranking\n1 44 Solomon\n2 42 Jason\n2 42 Errol\n3 41 Garry\n3 41 Bernard\n3 41 Barry\n4 39 Stephen\n\nOrdinal ranking\n1 44 Solomon\n2 42 Jason\n3 42 Errol\n4 41 Garry\n5 41 Bernard\n6 41 Barry\n7 39 Stephen\n\nFractional ranking\n1,0 44 Solomon\n2,5 42 Jason\n2,5 42 Errol\n5,0 41 Garry\n5,0 41 Bernard\n5,0 41 Barry\n7,0 39 Stephen\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":322} {"lang_cluster":"Java","source_code":"\n\npublic class Trig {\n public static void main(String[] args) {\n \/\/Pi \/ 4 is 45 degrees. All answers should be the same.\n double radians = Math.PI \/ 4;\n double degrees = 45.0;\n \/\/sine\n System.out.println(Math.sin(radians) + \" \" + Math.sin(Math.toRadians(degrees)));\n \/\/cosine\n System.out.println(Math.cos(radians) + \" \" + Math.cos(Math.toRadians(degrees)));\n \/\/tangent\n System.out.println(Math.tan(radians) + \" \" + Math.tan(Math.toRadians(degrees)));\n \/\/arcsine\n double arcsin = Math.asin(Math.sin(radians));\n System.out.println(arcsin + \" \" + Math.toDegrees(arcsin));\n \/\/arccosine\n double arccos = Math.acos(Math.cos(radians));\n System.out.println(arccos + \" \" + Math.toDegrees(arccos));\n \/\/arctangent\n double arctan = Math.atan(Math.tan(radians));\n System.out.println(arctan + \" \" + Math.toDegrees(arctan));\n }\n}\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions such as sine, cosine, tangent, and their inverses in a given programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the same angle is used for each radian\/degree pair. For inverse functions, the same number is used and its answer is converted to both radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities. In the case of Java, the Math class, which contains all six functions and accepts only radians, is utilized.","id":323} {"lang_cluster":"Java","source_code":"\n\npackage hu.pj.alg.test;\n\nimport hu.pj.alg.BoundedKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class BoundedKnapsackForTourists {\n public BoundedKnapsackForTourists() {\n BoundedKnapsack bok = new BoundedKnapsack(400); \/\/ 400 dkg = 400 dag = 4 kg\n\n \/\/ making the list of items that you want to bring\n bok.add(\"map\", 9, 150, 1);\n bok.add(\"compass\", 13, 35, 1);\n bok.add(\"water\", 153, 200, 3);\n bok.add(\"sandwich\", 50, 60, 2);\n bok.add(\"glucose\", 15, 60, 2);\n bok.add(\"tin\", 68, 45, 3);\n bok.add(\"banana\", 27, 60, 3);\n bok.add(\"apple\", 39, 40, 3);\n bok.add(\"cheese\", 23, 30, 1);\n bok.add(\"beer\", 52, 10, 3);\n bok.add(\"suntan cream\", 11, 70, 1);\n bok.add(\"camera\", 32, 30, 1);\n bok.add(\"t-shirt\", 24, 15, 2);\n bok.add(\"trousers\", 48, 10, 2);\n bok.add(\"umbrella\", 73, 40, 1);\n bok.add(\"waterproof trousers\", 42, 70, 1);\n bok.add(\"waterproof overclothes\", 43, 75, 1);\n bok.add(\"note-case\", 22, 80, 1);\n bok.add(\"sunglasses\", 7, 20, 1);\n bok.add(\"towel\", 18, 12, 2);\n bok.add(\"socks\", 4, 50, 1);\n bok.add(\"book\", 30, 10, 2);\n\n \/\/ calculate the solution:\n List itemList = bok.calcSolution();\n\n \/\/ write out the solution in the standard output\n if (bok.isCalculated()) {\n NumberFormat nf = NumberFormat.getInstance();\n\n System.out.println(\n \"Maximal weight = \" +\n nf.format(bok.getMaxWeight() \/ 100.0) + \" kg\"\n );\n System.out.println(\n \"Total weight of solution = \" +\n nf.format(bok.getSolutionWeight() \/ 100.0) + \" kg\"\n );\n System.out.println(\n \"Total value = \" +\n bok.getProfit()\n );\n System.out.println();\n System.out.println(\n \"You can carry te following materials \" +\n \"in the knapsack:\"\n );\n for (Item item : itemList) {\n if (item.getInKnapsack() > 0) {\n System.out.format(\n \"%1$-10s %2$-23s %3$-3s %4$-5s %5$-15s \\n\",\n item.getInKnapsack() + \" unit(s) \",\n item.getName(),\n item.getInKnapsack() * item.getWeight(), \"dag \",\n \"(value = \" + item.getInKnapsack() * item.getValue() + \")\"\n );\n }\n }\n } else {\n System.out.println(\n \"The problem is not solved. \" +\n \"Maybe you gave wrong data.\"\n );\n }\n\n }\n\n public static void main(String[] args) {\n new BoundedKnapsackForTourists();\n }\n} \/\/ class\n\npackage hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.util.*;\n\npublic class BoundedKnapsack extends ZeroOneKnapsack {\n public BoundedKnapsack() {}\n\n public BoundedKnapsack(int _maxWeight) {\n setMaxWeight(_maxWeight);\n }\n\n public BoundedKnapsack(List _itemList) {\n setItemList(_itemList);\n }\n\n public BoundedKnapsack(List _itemList, int _maxWeight) {\n setItemList(_itemList);\n setMaxWeight(_maxWeight);\n }\n\n @Override\n public List calcSolution() {\n int n = itemList.size();\n\n \/\/ add items to the list, if bounding > 1\n for (int i = 0; i < n; i++) {\n Item item = itemList.get(i);\n if (item.getBounding() > 1) {\n for (int j = 1; j < item.getBounding(); j++) {\n add(item.getName(), item.getWeight(), item.getValue());\n }\n }\n }\n \n super.calcSolution();\n\n \/\/ delete the added items, and increase the original items\n while (itemList.size() > n) {\n Item lastItem = itemList.get(itemList.size() - 1);\n if (lastItem.getInKnapsack() == 1) {\n for (int i = 0; i < n; i++) {\n Item iH = itemList.get(i);\n if (lastItem.getName().equals(iH.getName())) {\n iH.setInKnapsack(1 + iH.getInKnapsack());\n break;\n }\n }\n }\n itemList.remove(itemList.size() - 1);\n }\n\n return itemList;\n }\n\n \/\/ add an item to the item list\n public void add(String name, int weight, int value, int bounding) {\n if (name.equals(\"\"))\n name = \"\" + (itemList.size() + 1);\n itemList.add(new Item(name, weight, value, bounding));\n setInitialStateForCalculation();\n }\n} \/\/ class\n\npackage hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.util.*;\n\npublic class ZeroOneKnapsack {\n protected List itemList = new ArrayList();\n protected int maxWeight = 0;\n protected int solutionWeight = 0;\n protected int profit = 0;\n protected boolean calculated = false;\n\n public ZeroOneKnapsack() {}\n\n public ZeroOneKnapsack(int _maxWeight) {\n setMaxWeight(_maxWeight);\n }\n\n public ZeroOneKnapsack(List _itemList) {\n setItemList(_itemList);\n }\n\n public ZeroOneKnapsack(List _itemList, int _maxWeight) {\n setItemList(_itemList);\n setMaxWeight(_maxWeight);\n }\n\n \/\/ calculte the solution of 0-1 knapsack problem with dynamic method:\n public List calcSolution() {\n int n = itemList.size();\n\n setInitialStateForCalculation();\n if (n > 0 && maxWeight > 0) {\n List< List > c = new ArrayList< List >();\n List curr = new ArrayList();\n\n c.add(curr);\n for (int j = 0; j <= maxWeight; j++)\n curr.add(0);\n for (int i = 1; i <= n; i++) {\n List prev = curr;\n c.add(curr = new ArrayList());\n for (int j = 0; j <= maxWeight; j++) {\n if (j > 0) {\n int wH = itemList.get(i-1).getWeight();\n curr.add(\n (wH > j)\n ?\n prev.get(j)\n :\n Math.max(\n prev.get(j),\n itemList.get(i-1).getValue() + prev.get(j-wH)\n )\n );\n } else {\n curr.add(0);\n }\n } \/\/ for (j...)\n } \/\/ for (i...)\n profit = curr.get(maxWeight);\n\n for (int i = n, j = maxWeight; i > 0 && j >= 0; i--) {\n int tempI = c.get(i).get(j);\n int tempI_1 = c.get(i-1).get(j);\n if (\n (i == 0 && tempI > 0)\n ||\n (i > 0 && tempI != tempI_1)\n )\n {\n Item iH = itemList.get(i-1);\n int wH = iH.getWeight();\n iH.setInKnapsack(1);\n j -= wH;\n solutionWeight += wH;\n }\n } \/\/ for()\n calculated = true;\n } \/\/ if()\n return itemList;\n }\n\n \/\/ add an item to the item list\n public void add(String name, int weight, int value) {\n if (name.equals(\"\"))\n name = \"\" + (itemList.size() + 1);\n itemList.add(new Item(name, weight, value));\n setInitialStateForCalculation();\n }\n\n \/\/ add an item to the item list\n public void add(int weight, int value) {\n add(\"\", weight, value); \/\/ the name will be \"itemList.size() + 1\"!\n }\n\n \/\/ remove an item from the item list\n public void remove(String name) {\n for (Iterator it = itemList.iterator(); it.hasNext(); ) {\n if (name.equals(it.next().getName())) {\n it.remove();\n }\n }\n setInitialStateForCalculation();\n }\n\n \/\/ remove all items from the item list\n public void removeAllItems() {\n itemList.clear();\n setInitialStateForCalculation();\n }\n\n public int getProfit() {\n if (!calculated)\n calcSolution();\n return profit;\n }\n\n public int getSolutionWeight() {return solutionWeight;}\n public boolean isCalculated() {return calculated;}\n public int getMaxWeight() {return maxWeight;}\n\n public void setMaxWeight(int _maxWeight) {\n maxWeight = Math.max(_maxWeight, 0);\n }\n\n public void setItemList(List _itemList) {\n if (_itemList != null) {\n itemList = _itemList;\n for (Item item : _itemList) {\n item.checkMembers();\n }\n }\n }\n\n \/\/ set the member with name \"inKnapsack\" by all items:\n private void setInKnapsackByAll(int inKnapsack) {\n for (Item item : itemList)\n if (inKnapsack > 0)\n item.setInKnapsack(1);\n else\n item.setInKnapsack(0);\n }\n\n \/\/ set the data members of class in the state of starting the calculation:\n protected void setInitialStateForCalculation() {\n setInKnapsackByAll(0);\n calculated = false;\n profit = 0;\n solutionWeight = 0;\n }\n} \/\/ class\n\npackage hu.pj.obj;\n\npublic class Item {\n protected String name = \"\";\n protected int weight = 0;\n protected int value = 0;\n protected int bounding = 1; \/\/ the maximal limit of item's pieces\n protected int inKnapsack = 0; \/\/ the pieces of item in solution\n\n public Item() {}\n\n public Item(Item item) {\n setName(item.name);\n setWeight(item.weight);\n setValue(item.value);\n setBounding(item.bounding);\n }\n\n public Item(int _weight, int _value) {\n setWeight(_weight);\n setValue(_value);\n }\n\n public Item(int _weight, int _value, int _bounding) {\n setWeight(_weight);\n setValue(_value);\n setBounding(_bounding);\n }\n\n public Item(String _name, int _weight, int _value) {\n setName(_name);\n setWeight(_weight);\n setValue(_value);\n }\n\n public Item(String _name, int _weight, int _value, int _bounding) {\n setName(_name);\n setWeight(_weight);\n setValue(_value);\n setBounding(_bounding);\n }\n\n public void setName(String _name) {name = _name;}\n public void setWeight(int _weight) {weight = Math.max(_weight, 0);}\n public void setValue(int _value) {value = Math.max(_value, 0);}\n\n public void setInKnapsack(int _inKnapsack) {\n inKnapsack = Math.min(getBounding(), Math.max(_inKnapsack, 0));\n }\n\n public void setBounding(int _bounding) {\n bounding = Math.max(_bounding, 0);\n if (bounding == 0)\n inKnapsack = 0;\n }\n\n public void checkMembers() {\n setWeight(weight);\n setValue(value);\n setBounding(bounding);\n setInKnapsack(inKnapsack);\n }\n\n public String getName() {return name;}\n public int getWeight() {return weight;}\n public int getValue() {return value;}\n public int getInKnapsack() {return inKnapsack;}\n public int getBounding() {return bounding;}\n} \/\/ class\n\n\n","human_summarization":"The code implements a solution to the bounded Knapsack problem. It helps a tourist to determine the optimal combination of items to carry on a trip, given a maximum weight limit of 4 kg. The items each have a weight, value, and quantity. The goal is to maximize the total value of items in the knapsack without exceeding the weight limit. The code uses a dynamic programming approach based on the method of Knapsack problem\/0-1.","id":324} {"lang_cluster":"Java","source_code":"\n\nimport sun.misc.Signal;\nimport sun.misc.SignalHandler;\n\npublic class ExampleSignalHandler {\n public static void main(String... args) throws InterruptedException {\n final long start = System.nanoTime();\n Signal.handle(new Signal(\"INT\"), new SignalHandler() {\n public void handle(Signal sig) {\n System.out.format(\"\\nProgram execution took %f seconds\\n\", (System.nanoTime() - start) \/ 1e9f);\n System.exit(0);\n }\n });\n int counter = 0;\n while(true) {\n System.out.println(counter++);\n Thread.sleep(500);\n }\n }\n}\n\n\npublic class ExampleSignalHandler {\n public static void main(String... args) throws InterruptedException {\n final long start = System.nanoTime();\n Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {\n public void run() {\n System.out.format(\"\\nProgram execution took %f seconds\\n\", (System.nanoTime() - start) \/ 1e9f);\n }\n }));\n int counter = 0;\n while(true) {\n System.out.println(counter++);\n Thread.sleep(500);\n }\n }\n}\n\n\n","human_summarization":"The code outputs an integer every half second. It handles SIGINT or SIGQUIT signals, typically generated by user input such as ctrl-C or ctrl-\\, to stop the output, display the runtime duration in seconds, and terminate the program. It may use sun.misc.SignalHandler to specify the signal to catch or a generic shutdown hook, although the latter doesn't provide a specific signal reference.","id":325} {"lang_cluster":"Java","source_code":"\n\nString s = \"12345\";\ns = String.valueOf(Integer.parseInt(s) + 1);\n\n\nString s = \"123456789012345678901234567890.12345\";\ns = new BigDecimal(s).add(BigDecimal.ONE).toString();\n\n","human_summarization":"Increments a numerical string, handles big decimal numbers, and trims spaces to prevent parseInt Exception.","id":326} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\n\npublic class CommonPath {\n\tpublic static String commonPath(String... paths){\n\t\tString commonPath = \"\";\n\t\tString[][] folders = new String[paths.length][];\n\t\tfor(int i = 0; i < paths.length; i++){\n\t\t\tfolders[i] = paths[i].split(\"\/\"); \/\/split on file separator\n\t\t}\n\t\tfor(int j = 0; j < folders[0].length; j++){\n\t\t\tString thisFolder = folders[0][j]; \/\/grab the next folder name in the first path\n\t\t\tboolean allMatched = true; \/\/assume all have matched in case there are no more paths\n\t\t\tfor(int i = 1; i < folders.length && allMatched; i++){ \/\/look at the other paths\n\t\t\t\tif(folders[i].length < j){ \/\/if there is no folder here\n\t\t\t\t\tallMatched = false; \/\/no match\n\t\t\t\t\tbreak; \/\/stop looking because we've gone as far as we can\n\t\t\t\t}\n\t\t\t\t\/\/otherwise\n\t\t\t\tallMatched &= folders[i][j].equals(thisFolder); \/\/check if it matched\n\t\t\t}\n\t\t\tif(allMatched){ \/\/if they all matched this folder name\n\t\t\t\tcommonPath += thisFolder + \"\/\"; \/\/add it to the answer\n\t\t\t}else{\/\/otherwise\n\t\t\t\tbreak;\/\/stop looking\n\t\t\t}\n\t\t}\n\t\treturn commonPath;\n\t}\n\t\n\tpublic static void main(String[] args){\n\t\tString[] paths = { \"\/home\/user1\/tmp\/coverage\/test\",\n\t\t\t\t \"\/home\/user1\/tmp\/covert\/operator\",\n\t\t\t\t \"\/home\/user1\/tmp\/coven\/members\"};\n\t\tSystem.out.println(commonPath(paths));\n\t\t\n\t\tString[] paths2 = { \"\/hame\/user1\/tmp\/coverage\/test\",\n\t\t\t\t \"\/home\/user1\/tmp\/covert\/operator\",\n\t\t\t\t \"\/home\/user1\/tmp\/coven\/members\"};\n\t\tSystem.out.println(commonPath(paths2));\n\t}\n}\n\n\n\/home\/user1\/tmp\/\n\/\n\n\tstatic String commonPath(String... paths){\n\t\tString commonPath = \"\";\n\t\tString[][] folders = new String[paths.length][];\n\t\t\n\t\tfor(int i=0; i 0; i--) {\n int j = rng.nextInt(i);\n Object tmp = items[i];\n items[i] = items[j];\n items[j] = tmp;\n }\n}\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":328} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\n\ndouble median(List values) {\n \/* copy, as to prevent modifying 'values' *\/\n List list = new ArrayList<>(values);\n Collections.sort(list);\n \/* 'mid' will be truncated *\/\n int mid = list.size() \/ 2;\n return switch (list.size() % 2) {\n case 0 -> {\n double valueA = list.get(mid);\n double valueB = list.get(mid + 1);\n yield (valueA + valueB) \/ 2;\n }\n case 1 -> list.get(mid);\n default -> 0;\n };\n}\n\nWorks with: Java version 1.5+\n\npublic static double median2(List list) {\n PriorityQueue pq = new PriorityQueue(list);\n int n = list.size();\n for (int i = 0; i < (n - 1) \/ 2; i++)\n pq.poll(); \/\/ discard first half\n if (n % 2 != 0) \/\/ odd length\n return pq.poll();\n else\n return (pq.poll() + pq.poll()) \/ 2.0;\n}\n\nWorks with: Java version 1.8+\n\n@FunctionalInterface\ninterface MedianFinder extends Function, R> {\n @Override\n R apply(Collection data);\n}\n\nclass MedianFinderImpl implements MedianFinder {\n private final Supplier ifEmpty;\n private final Function ifOdd;\n private final Function, R> ifEven;\n\n MedianFinderImpl(Supplier ifEmpty, Function ifOdd, Function, R> ifEven) {\n this.ifEmpty = ifEmpty;\n this.ifOdd = ifOdd;\n this.ifEven = ifEven;\n }\n\n @Override\n public R apply(Collection data) {\n return Objects.requireNonNull(data, \"data must not be null\").isEmpty()\n \u00a0? ifEmpty.get()\n \u00a0: (data.size() & 1) == 0\n \u00a0? ifEven.apply(data.stream().sorted()\n .skip(data.size() \/ 2 - 1)\n .limit(2).toList())\n \u00a0: ifOdd.apply(data.stream().sorted()\n .skip(data.size() \/ 2)\n .limit(1).findFirst().get());\n }\n}\n\npublic class MedianOf {\n private static final MedianFinder INTEGERS = new MedianFinderImpl<>(() -> 0, n -> n, pair -> (pair.get(0) + pair.get(1)) \/ 2);\n private static final MedianFinder INTEGERS_AS_FLOAT = new MedianFinderImpl<>(() -> 0f, n -> n * 1f, pair -> (pair.get(0) + pair.get(1)) \/ 2f);\n private static final MedianFinder INTEGERS_AS_DOUBLE = new MedianFinderImpl<>(() -> 0d, n -> n * 1d, pair -> (pair.get(0) + pair.get(1)) \/ 2d);\n private static final MedianFinder FLOATS = new MedianFinderImpl<>(() -> 0f, n -> n, pair -> (pair.get(0) + pair.get(1)) \/ 2);\n private static final MedianFinder DOUBLES = new MedianFinderImpl<>(() -> 0d, n -> n, pair -> (pair.get(0) + pair.get(1)) \/ 2);\n private static final MedianFinder BIG_INTEGERS = new MedianFinderImpl<>(() -> BigInteger.ZERO, n -> n, pair -> pair.get(0).add(pair.get(1)).divide(BigInteger.TWO));\n private static final MedianFinder BIG_INTEGERS_AS_BIG_DECIMAL = new MedianFinderImpl<>(() -> BigDecimal.ZERO, BigDecimal::new, pair -> new BigDecimal(pair.get(0).add(pair.get(1))).divide(BigDecimal.valueOf(2), RoundingMode.FLOOR));\n private static final MedianFinder BIG_DECIMALS = new MedianFinderImpl<>(() -> BigDecimal.ZERO, n -> n, pair -> pair.get(0).add(pair.get(1)).divide(BigDecimal.valueOf(2), RoundingMode.FLOOR));\n\n public static Integer integers(Collection integerCollection) { return INTEGERS.apply(integerCollection); }\n public static Float integersAsFloat(Collection integerCollection) { return INTEGERS_AS_FLOAT.apply(integerCollection); }\n public static Double integersAsDouble(Collection integerCollection) { return INTEGERS_AS_DOUBLE.apply(integerCollection); }\n public static Float floats(Collection floatCollection) { return FLOATS.apply(floatCollection); }\n public static Double doubles(Collection doubleCollection) { return DOUBLES.apply(doubleCollection); }\n public static BigInteger bigIntegers(Collection bigIntegerCollection) { return BIG_INTEGERS.apply(bigIntegerCollection); }\n public static BigDecimal bigIntegersAsBigDecimal(Collection bigIntegerCollection) { return BIG_INTEGERS_AS_BIG_DECIMAL.apply(bigIntegerCollection); }\n public static BigDecimal bigDecimals(Collection bigDecimalCollection) { return BIG_DECIMALS.apply(bigDecimalCollection); }\n}\n","human_summarization":"\"Code calculates the median of a vector of floating-point numbers, handling even number of elements by returning the average of two middle values. It implements the selection algorithm for efficient computation. It also includes tasks for calculating various statistical measures like mean, mode, standard deviation, and different types of averages such as arithmetic, geometric, harmonic, quadratic, and circular. The code also demonstrates the use of a priority queue for sorting.\"","id":329} {"lang_cluster":"Java","source_code":"\npublic class FizzBuzz {\n public static void main(String[] args) {\n for (int number = 1; number <= 100; number++) {\n if (number\u00a0% 15 == 0) {\n System.out.println(\"FizzBuzz\");\n } else if (number\u00a0% 3 == 0) {\n System.out.println(\"Fizz\");\n } else if (number\u00a0% 5 == 0) {\n System.out.println(\"Buzz\");\n } else {\n System.out.println(number);\n }\n }\n }\n}\n\npublic class FizzBuzz {\n public static void main(String[] args) {\n int number = 1;\n while (number <= 100) {\n if (number\u00a0% 15 == 0) {\n System.out.println(\"FizzBuzz\");\n } else if (number\u00a0% 3 == 0) {\n System.out.println(\"Fizz\");\n } else if (number\u00a0% 5 == 0) {\n System.out.println(\"Buzz\");\n } else {\n System.out.println(number);\n }\n number++;\n }\n }\n}\n\npublic class FizzBuzz {\n public static void main(String[] args) {\n int number = 1;\n while (number <= 100) {\n System.out.println(number\u00a0% 15 == 0\u00a0? \"FizzBuzz\"\u00a0: number\u00a0% 3 == 0\u00a0? \"Fizz\"\u00a0: number\u00a0% 5 == 0\u00a0? \"Buzz\"\u00a0: number);\n number++;\n }\n }\n}\n\nimport java.util.stream.IntStream;\nclass FizzBuzzJdk12 {\n public static void main(String[] args) {\n IntStream.range(1,101)\n .mapToObj(i->switch (i%15) {\n case 0 -> \"FizzBuzz\";\n case 3, 6, 9, 12 -> \"Fizz\";\n case 5, 10 -> \"Buzz\";\n default -> Integer.toString(i);\n })\n .forEach(System.out::println)\n \u00a0;\n }\n}\n\nimport java.util.stream.IntStream;\n\nclass FizzBuzzJdk12 {\n static final int FIZZ_FLAG = 0x8000_0000;\n static final int BUZZ_FLAG = 0x4000_0000;\n static final int FIZZ_BUZZ_FLAG = FIZZ_FLAG|BUZZ_FLAG;\n static final int[] FLAGS = new int[] {\n FIZZ_BUZZ_FLAG|0, 1, 2, FIZZ_FLAG|3, 4, \n BUZZ_FLAG|5, FIZZ_FLAG|6, 7, 8, FIZZ_FLAG|9,\n BUZZ_FLAG|10, 11, FIZZ_FLAG|12, 13, 14\n };\n public static void main(String[] args) {\n IntStream.iterate(0,i->++i)\n .flatMap(i -> IntStream.range(0,15).map(j->FLAGS[j]+15*i))\n .mapToObj(\n \/\/ JDK12 switch expression ...\n n-> switch(n & FIZZ_BUZZ_FLAG) {\n case FIZZ_BUZZ_FLAG -> \"fizzbuzz\";\n case FIZZ_FLAG -> \"fizz\";\n case BUZZ_FLAG -> \"buzz\";\n default -> Integer.toString(~FIZZ_BUZZ_FLAG & n);\n }\n )\n .skip(1)\n .limit(100)\n .forEach(System.out::println)\n \u00a0;\n }\n}\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both with 'FizzBuzz'.","id":330} {"lang_cluster":"Java","source_code":"\nLibrary: Swing Library: AWT\nimport java.awt.Graphics;\nimport java.awt.image.BufferedImage;\nimport javax.swing.JFrame;\n\npublic class Mandelbrot extends JFrame {\n\n private final int MAX_ITER = 570;\n private final double ZOOM = 150;\n private BufferedImage I;\n private double zx, zy, cX, cY, tmp;\n\n public Mandelbrot() {\n super(\"Mandelbrot Set\");\n setBounds(100, 100, 800, 600);\n setResizable(false);\n setDefaultCloseOperation(EXIT_ON_CLOSE);\n I = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);\n for (int y = 0; y < getHeight(); y++) {\n for (int x = 0; x < getWidth(); x++) {\n zx = zy = 0;\n cX = (x - 400) \/ ZOOM;\n cY = (y - 300) \/ ZOOM;\n int iter = MAX_ITER;\n while (zx * zx + zy * zy < 4 && iter > 0) {\n tmp = zx * zx - zy * zy + cX;\n zy = 2.0 * zx * zy + cY;\n zx = tmp;\n iter--;\n }\n I.setRGB(x, y, iter | (iter << 8));\n }\n }\n }\n\n @Override\n public void paint(Graphics g) {\n g.drawImage(I, 0, 0, this);\n }\n\n public static void main(String[] args) {\n new Mandelbrot().setVisible(true);\n }\n}\n\nLibrary: AWT Library: Swing\nimport static java.awt.Color.HSBtoRGB;\nimport static java.awt.Color.black;\nimport static java.awt.event.KeyEvent.VK_BACK_SLASH;\nimport static java.awt.event.KeyEvent.VK_ESCAPE;\nimport static java.awt.image.BufferedImage.TYPE_INT_RGB;\nimport static java.lang.Integer.signum;\nimport static java.lang.Math.abs;\nimport static java.lang.Math.max;\nimport static java.lang.Math.min;\nimport static java.lang.System.currentTimeMillis;\nimport static java.util.Locale.ROOT;\n\nimport java.awt.Dimension;\nimport java.awt.Graphics;\nimport java.awt.Insets;\nimport java.awt.event.KeyAdapter;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.MouseAdapter;\nimport java.awt.event.MouseEvent;\nimport java.awt.image.BufferedImage;\nimport java.util.function.Consumer;\nimport java.util.function.Predicate;\n\nimport javax.swing.JFrame;\n\n\/* \n * click: point to center\n * ctrl-click: point to origin\n * drag: point to mouse release point\n * ctrl-drag: point to origin + zoom\n * back-slash: back to previous point \n * esc: back to previous zoom point - zoom \n *\/\n\npublic class Mandelbrot extends JFrame {\n\tprivate static final long serialVersionUID = 1L;\n\t\n\tprivate Insets insets;\n\tprivate int width, height;\n\tprivate double widthHeightRatio;\n\tprivate int minX, minY;\n\tprivate double Zoom;\n\t\t\n\tprivate int mpX, mpY, mdX, mdY;\n\tprivate boolean isCtrlDown, ctrl;\n\tprivate Stack stack = new Stack();\n\t\n\tprivate BufferedImage image;\n\tprivate boolean newImage = true;\n\t\n\tpublic static void main(String[] args) {\n\t\tnew Mandelbrot(800, 600); \/\/ (800, 600), (1024, 768), (1600, 900), (1920, 1080)\n\t\t\/\/new Mandelbrot(800, 600, 4.5876514379235943e-09, -0.6092161175392330, -0.4525577210859453);\n\t\t\/\/new Mandelbrot(800, 600, 5.9512354925205320e-10, -0.6092146769531246, -0.4525564820098262);\n\t\t\/\/new Mandelbrot(800, 600, 6.7178527589983420e-08, -0.7819036465400592, -0.1298363433443265);\n\t\t\/\/new Mandelbrot(800, 600, 4.9716091454775210e-09, -0.7818800036717134, -0.1298044093748981);\n\t\t\/\/new Mandelbrot(800, 600, 7.9333341281639390e-06, -0.7238770725243187, -0.2321214232559487); \n\t\t\/*\n\t\tnew Mandelbrot(800, 600, new double[][] {\n\t\t\t{5.0000000000000000e-03, -2.6100000000000000, -1.4350000000000000}, \/\/ done!\n\t\t\t{3.5894206549118390e-04, -0.7397795969773300, -0.4996473551637279}, \/\/ done!\n\t\t\t{3.3905106941862460e-05, -0.6270410477828043, -0.4587021918164572}, \/\/ done!\n\t\t\t{6.0636337351945460e-06, -0.6101531446039512, -0.4522561221394852}, \/\/ done!\n\t\t\t{1.5502741161769430e-06, -0.6077214060084073, -0.4503995886987711}, \/\/ done!\n\t\t});\n\t\t\/\/*\/\n\t}\n\t\n\tpublic Mandelbrot(int width, int height) {\n\t\tthis(width, height, .005, -2.61, -1.435);\n\t}\n\t\n\tpublic Mandelbrot(int width, int height, double Zoom, double r, double i) {\n\t\tthis(width, height, new double[] {Zoom, r, i});\n\t}\n\t\n\tpublic Mandelbrot(int width, int height, double[] ... points) {\n\t\tsuper(\"Mandelbrot Set\");\n\t\tsetResizable(false);\n\t\tsetDefaultCloseOperation(EXIT_ON_CLOSE);\n\t\tDimension screen = getToolkit().getScreenSize();\n\t\tsetBounds(\n\t\t\trint((screen.getWidth() - width) \/ 2),\n\t\t\trint((screen.getHeight() - height) \/ 2),\n\t\t\twidth,\n\t\t\theight\n\t\t);\n\t\taddMouseListener(mouseAdapter);\n\t\taddMouseMotionListener(mouseAdapter);\n\t\taddKeyListener(keyAdapter);\n\t\tPoint point = stack.push(points);\n\t\tthis.Zoom = point.Zoom;\n\t\tthis.minX = point.minX;\n\t\tthis.minY = point.minY;\n\t\tsetVisible(true);\n\t\tinsets = getInsets();\n\t\tthis.width = width -= insets.left + insets.right;\n\t\tthis.height = height -= insets.top + insets.bottom;\n\t\twidthHeightRatio = (double) width \/ height;\n\t}\n\t\n\tprivate int rint(double d) {\n\t\treturn (int) Math.rint(d); \/\/ half even\n\t}\n\n\tprivate void repaint(boolean newImage) {\n\t\tthis.newImage = newImage;\n\t\trepaint();\n\t}\n\n\tprivate MouseAdapter mouseAdapter = new MouseAdapter() {\n\t\tpublic void mouseClicked(MouseEvent e) {\n\t\t\tstack.push(false);\n\t\t\tif (!ctrl) {\n\t\t\t\tminX -= width \/ 2 ;\n\t\t\t\tminY -= height \/ 2;\n\t\t\t}\n\t\t\tminX += e.getX() - insets.left;\n\t\t\tminY += e.getY() - insets.top;\n\t\t\tctrl = false;\n\t\t\trepaint(true);\n\t \t}\n\t\tpublic void mousePressed(MouseEvent e) {\n\t\t\tmpX = e.getX();\n\t\t\tmpY = e.getY();\n\t\t\tctrl = isCtrlDown;\n\t\t}\n\t\tpublic void mouseDragged(MouseEvent e) {\n\t\t\tif (!ctrl) return;\n\t\t\tsetMdCoord(e);\n\t\t\trepaint();\n\t\t}\n\t\tprivate void setMdCoord(MouseEvent e) {\n\t\t\tint dx = e.getX() - mpX;\n\t\t\tint dy = e.getY() - mpY;\n\t\t\tmdX = mpX + max(abs(dx), rint(abs(dy) * widthHeightRatio) * signum(dx));\n\t\t\tmdY = mpY + max(abs(dy), rint(abs(dx) \/ widthHeightRatio) * signum(dy));\n\t\t\tacceptIf(insets.left, ge(mdX), setMdXY); \n\t\t\tacceptIf(insets.top, ge(mdY), setMdYX);\n\t\t\tacceptIf(insets.left+width-1, le(mdX), setMdXY); \n\t\t\tacceptIf(insets.top+height-1, le(mdY), setMdYX);\n\t\t}\n\t\tprivate void acceptIf(int value, Predicate p, Consumer c) { if (p.test(value)) c.accept(value); }\n\t\tprivate Predicate ge(int md) { return v-> v >= md; }\n\t\tprivate Predicate le(int md) { return v-> v <= md; }\n\t\tprivate Consumer setMdXY = v-> mdY = mpY + rint(abs((mdX=v)-mpX) \/ widthHeightRatio) * signum(mdY-mpY);\n\t\tprivate Consumer setMdYX = v-> mdX = mpX + rint(abs((mdY=v)-mpY) * widthHeightRatio) * signum(mdX-mpX);\n\t\tpublic void mouseReleased(MouseEvent e) {\n\t\t\tif (e.getX() == mpX && e.getY() == mpY) return; \n\t\t\tstack.push(ctrl);\n\t\t\tif (!ctrl) {\n\t\t\t\tminX += mpX - (mdX = e.getX());\n\t\t\t\tminY += mpY - (mdY = e.getY());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsetMdCoord(e);\n\t\t\t\tif (mdX < mpX) { int t=mpX; mpX=mdX; mdX=t; } \n\t\t\t\tif (mdY < mpY) { int t=mpY; mpY=mdY; mdY=t; } \n\t\t\t\tminX += mpX - insets.left;\n\t\t\t\tminY += mpY - insets.top;\n\t\t\t\tdouble rZoom = (double) width \/ abs(mdX - mpX);\n\t\t\t\tminX *= rZoom;\n\t\t\t\tminY *= rZoom;\n\t\t\t\tZoom \/= rZoom;\n\t\t\t}\n\t\t\tctrl = false;\n\t\t\trepaint(true);\t\t\n\t\t}\n\t};\n\t\n\tprivate KeyAdapter keyAdapter = new KeyAdapter() {\n\t\tpublic void keyPressed(KeyEvent e) {\n\t\t\tisCtrlDown = e.isControlDown();\n\t\t}\n\t\tpublic void keyReleased(KeyEvent e) {\n\t\t\tisCtrlDown = e.isControlDown();\n\t\t}\n\t\tpublic void keyTyped(KeyEvent e) {\n\t\t\tchar c = e.getKeyChar();\n\t\t\tboolean isEsc = c == VK_ESCAPE;\n\t\t\tif (!isEsc && c != VK_BACK_SLASH) return;\n\t\t\trepaint(stack.pop(isEsc));\n\t\t}\n\t};\n\t\n\tprivate class Point {\n\t\tpublic boolean type;\n\t\tpublic double Zoom;\n\t\tpublic int minX;\n\t\tpublic int minY;\n\t\tPoint(boolean type, double Zoom, int minX, int minY) {\n\t\t\tthis.type = type;\n\t\t\tthis.Zoom = Zoom;\n\t\t\tthis.minX = minX;\n\t\t\tthis.minY = minY;\n\t\t}\n\t}\n\tprivate class Stack extends java.util.Stack {\n\t\tprivate static final long serialVersionUID = 1L;\n\t\tpublic Point push(boolean type) {\n\t\t\treturn push(type, Zoom, minX, minY);\n\t\t}\n\t\tpublic Point push(boolean type, double ... point) {\n\t\t\tdouble Zoom = point[0];\n\t\t\treturn push(type, Zoom, rint(point[1]\/Zoom), rint(point[2]\/Zoom));\n\t\t}\n\t\tpublic Point push(boolean type, double Zoom, int minX, int minY) {\n\t\t\treturn push(new Point(type, Zoom, minX, minY));\n\t\t}\n\t\tpublic Point push(double[] ... points) {\n\t\t\tPoint lastPoint = push(false, points[0]);\n\t\t\tfor (int i=0, e=points.length-1; i red yellow green cian blue magenta <- reverse \n\t\t\t\timage.setRGB(x-minX, y-minY, color(r, i, 360, false, 2\/3f));\n\t\t\t}\n\t\t}\n\t\tnewImage = false;\n\t\tdone(milli);\n\t}\n\n\tprivate long printPoint() {\n\t\treturn printPoint(Zoom, minX, minY);\n\t}\n\tprivate long printPoint(Point point) {\n\t\treturn printPoint(point.Zoom, point.minX, point.minY);\n\t}\n\tprivate long printPoint(double Zoom, int minX, int minY) {\n\t\treturn printPoint(Zoom, minX*Zoom, minY*Zoom);\n\t}\n\tprivate long printPoint(Object ... point) {\n\t\tSystem.out.printf(ROOT,\t\"{%.16e,\u00a0%.16g,\u00a0%.16g},\", point);\n\t\treturn currentTimeMillis();\n\t}\n\t\n\tprivate void done(long milli) {\n\t\tmilli = currentTimeMillis() - milli;\n\t\tSystem.out.println(\" \/\/ \" + milli + \"ms done!\");\n\t}\n\n\tprivate int color(double r0, double i0, int max, boolean straight, float shift) {\n\t\tint n = -1;\n\t\tdouble r=0, i=0, r2=0, i2=0;\n\t\tdo {\n\t\t\ti = r*(i+i) + i0;\n\t\t\tr = r2-i2 + r0;\n\t\t\tr2 = r*r;\n\t\t\ti2 = i*i;\n\t\t}\n\t\twhile (++n < max && r2 + i2 < 4); \n\t\treturn n == max\n\t\t\t? black.getRGB()\n\t\t\t: HSBtoRGB(shift + (float) (straight ? n : max-n) \/ max * 11\/12f + (straight ? 0f : 1\/12f), 1, 1)\n\t\t;\t\t\n\t}\n}\n\n","human_summarization":"generate and draw the Mandelbrot set using various available algorithms and functions.","id":331} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\npublic class SumProd\n{\n public static void main(final String[] args)\n {\n int sum = 0;\n int prod = 1;\n int[] arg = {1,2,3,4,5};\n for (int i : arg)\n {\n sum += i;\n prod *= i;\n }\n }\n}\n\nWorks with: Java version 1.8+\nimport java.util.Arrays;\n\npublic class SumProd\n{\n public static void main(final String[] args)\n {\n int[] arg = {1,2,3,4,5};\n System.out.printf(\"sum = %d\\n\", Arrays.stream(arg).sum());\n System.out.printf(\"sum = %d\\n\", Arrays.stream(arg).reduce(0, (a, b) -> a + b));\n System.out.printf(\"product = %d\\n\", Arrays.stream(arg).reduce(1, (a, b) -> a * b));\n }\n}\n\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":332} {"lang_cluster":"Java","source_code":"\n\nimport java.util.GregorianCalendar;\nimport java.text.MessageFormat;\n\npublic class Leapyear{\n public static void main(String[] argv){\n int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100};\n GregorianCalendar cal = new GregorianCalendar();\n for(int year : yrs){\n System.err.println(MessageFormat.format(\"The year {0,number,#} is leaper: {1} \/ {2}.\",\n year, cal.isLeapYear(year), isLeapYear(year)));\n }\n\n }\n public static boolean isLeapYear(int year){\n return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0);\n }\n}\n\n\n","human_summarization":"determine if a given year is a leap year in the Gregorian calendar, using both the GregorianCalendar class and an algorithm from the wiki. The program switches from the Julian calendar to the Gregorian calendar at 15 October 1582 by default. Both results are printed in the output.","id":333} {"lang_cluster":"Java","source_code":"\n\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.util.Random;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class OneTimePad {\n\n public static void main(String[] args) {\n String controlName = \"AtomicBlonde\";\n generatePad(controlName, 5, 60, 65, 90);\n String text = \"IT WAS THE BEST OF TIMES IT WAS THE WORST OF TIMES\";\n String encrypted = parse(true, controlName, text.replaceAll(\" \", \"\"));\n String decrypted = parse(false, controlName, encrypted);\n System.out.println(\"Input text = \" + text);\n System.out.println(\"Encrypted text = \" + encrypted);\n System.out.println(\"Decrypted text = \" + decrypted);\n\n controlName = \"AtomicBlondeCaseSensitive\";\n generatePad(controlName, 5, 60, 32, 126);\n text = \"It was the best of times, it was the worst of times.\";\n encrypted = parse(true, controlName, text);\n decrypted = parse(false, controlName, encrypted);\n System.out.println();\n System.out.println(\"Input text = \" + text);\n System.out.println(\"Encrypted text = \" + encrypted);\n System.out.println(\"Decrypted text = \" + decrypted);\n }\n \n private static String parse(boolean encryptText, String controlName, String text) {\n StringBuilder sb = new StringBuilder();\n int minCh = 0;\n int maxCh = 0;\n Pattern minChPattern = Pattern.compile(\"^# MIN_CH = ([\\\\d]+)$\");\n Pattern maxChPattern = Pattern.compile(\"^# MAX_CH = ([\\\\d]+)$\");\n boolean validated = false;\n try (BufferedReader in = new BufferedReader(new FileReader(getFileName(controlName))); ) {\n String inLine = null;\n while ( (inLine = in.readLine()) != null ) {\n Matcher minMatcher = minChPattern.matcher(inLine);\n if ( minMatcher.matches() ) {\n minCh = Integer.parseInt(minMatcher.group(1));\n continue;\n }\n Matcher maxMatcher = maxChPattern.matcher(inLine);\n if ( maxMatcher.matches() ) {\n maxCh = Integer.parseInt(maxMatcher.group(1));\n continue;\n }\n if ( ! validated && minCh > 0 && maxCh > 0 ) {\n validateText(text, minCh, maxCh);\n validated = true;\n }\n \/\/ # is comment. - is used key. \n if ( inLine.startsWith(\"#\") || inLine.startsWith(\"-\") ) {\n continue;\n }\n \/\/ Have encryption key.\n String key = inLine;\n if ( encryptText ) {\n for ( int i = 0 ; i < text.length(); i++) {\n sb.append((char) (((text.charAt(i) - minCh + key.charAt(i) - minCh) % (maxCh - minCh + 1)) + minCh));\n }\n }\n else {\n for ( int i = 0 ; i < text.length(); i++) {\n int decrypt = text.charAt(i) - key.charAt(i);\n if ( decrypt < 0 ) {\n decrypt += maxCh - minCh + 1;\n }\n decrypt += minCh;\n sb.append((char) decrypt);\n }\n }\n break;\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return sb.toString();\n }\n\n private static void validateText(String text, int minCh, int maxCh) {\n \/\/ Validate text is in range\n for ( char ch : text.toCharArray() ) {\n if ( ch != ' ' && (ch < minCh || ch > maxCh) ) {\n throw new IllegalArgumentException(\"ERROR 103: Invalid text.\");\n }\n }\n \n }\n \n private static String getFileName(String controlName) {\n return controlName + \".1tp\";\n }\n \n private static void generatePad(String controlName, int keys, int keyLength, int minCh, int maxCh) {\n Random random = new Random();\n try ( BufferedWriter writer = new BufferedWriter(new FileWriter(getFileName(controlName), false)); ) {\n writer.write(\"# Lines starting with '#' are ignored.\");\n writer.newLine();\n writer.write(\"# Lines starting with '-' are previously used.\");\n writer.newLine();\n writer.write(\"# MIN_CH = \" + minCh);\n writer.newLine();\n writer.write(\"# MAX_CH = \" + maxCh);\n writer.newLine();\n for ( int line = 0 ; line < keys ; line++ ) {\n StringBuilder sb = new StringBuilder();\n for ( int ch = 0 ; ch < keyLength ; ch++ ) {\n sb.append((char) (random.nextInt(maxCh - minCh + 1) + minCh));\n }\n writer.write(sb.toString());\n writer.newLine();\n }\n writer.write(\"# EOF\");\n writer.newLine();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n}\n\n\n","human_summarization":"The code implements a One-time pad for encrypting and decrypting messages using only letters. It generates data for the pad based on user-specified filename and length, ensuring the use of true random numbers. It also reuses elements of the Vigen\u00e8re cipher for encryption\/decryption operations. The code supports management of One-time pads, allowing users to list, mark as used, delete, and keep track of pads. Pad files have a \".1tp\" extension and can contain metadata or be marked as \"used\". The implementation supports multiple pads and includes start and end ASCII characters. It demonstrates the generation of a pad supporting uppercase only and another supporting lowercase, uppercase, symbols, and spaces.","id":334} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\n\nclass MD5\n{\n\n private static final int INIT_A = 0x67452301;\n private static final int INIT_B = (int)0xEFCDAB89L;\n private static final int INIT_C = (int)0x98BADCFEL;\n private static final int INIT_D = 0x10325476;\n \n private static final int[] SHIFT_AMTS = {\n 7, 12, 17, 22,\n 5, 9, 14, 20,\n 4, 11, 16, 23,\n 6, 10, 15, 21\n };\n \n private static final int[] TABLE_T = new int[64];\n static\n {\n for (int i = 0; i < 64; i++)\n TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));\n }\n \n public static byte[] computeMD5(byte[] message)\n {\n int messageLenBytes = message.length;\n int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;\n int totalLen = numBlocks << 6;\n byte[] paddingBytes = new byte[totalLen - messageLenBytes];\n paddingBytes[0] = (byte)0x80;\n \n long messageLenBits = (long)messageLenBytes << 3;\n for (int i = 0; i < 8; i++)\n {\n paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits;\n messageLenBits >>>= 8;\n }\n \n int a = INIT_A;\n int b = INIT_B;\n int c = INIT_C;\n int d = INIT_D;\n int[] buffer = new int[16];\n for (int i = 0; i < numBlocks; i ++)\n {\n int index = i << 6;\n for (int j = 0; j < 64; j++, index++)\n buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8);\n int originalA = a;\n int originalB = b;\n int originalC = c;\n int originalD = d;\n for (int j = 0; j < 64; j++)\n {\n int div16 = j >>> 4;\n int f = 0;\n int bufferIndex = j;\n switch (div16)\n {\n case 0:\n f = (b & c) | (~b & d);\n break;\n \n case 1:\n f = (b & d) | (c & ~d);\n bufferIndex = (bufferIndex * 5 + 1) & 0x0F;\n break;\n \n case 2:\n f = b ^ c ^ d;\n bufferIndex = (bufferIndex * 3 + 5) & 0x0F;\n break;\n \n case 3:\n f = c ^ (b | ~d);\n bufferIndex = (bufferIndex * 7) & 0x0F;\n break;\n }\n int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);\n a = d;\n d = c;\n c = b;\n b = temp;\n }\n \n a += originalA;\n b += originalB;\n c += originalC;\n d += originalD;\n }\n \n byte[] md5 = new byte[16];\n int count = 0;\n for (int i = 0; i < 4; i++)\n {\n int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));\n for (int j = 0; j < 4; j++)\n {\n md5[count++] = (byte)n;\n n >>>= 8;\n }\n }\n return md5;\n }\n \n public static String toHexString(byte[] b)\n {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < b.length; i++)\n {\n sb.append(String.format(\"%02X\", b[i] & 0xFF));\n }\n return sb.toString();\n }\n\n public static void main(String[] args)\n {\n String[] testStrings = { \"\", \"a\", \"abc\", \"message digest\", \"abcdefghijklmnopqrstuvwxyz\", \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\" };\n for (String s : testStrings)\n System.out.println(\"0x\" + toHexString(computeMD5(s.getBytes())) + \" <== \\\"\" + s + \"\\\"\");\n return;\n }\n \n}\n\n\n0xD41D8CD98F00B204E9800998ECF8427E <== \"\"\n0x0CC175B9C0F1B6A831C399E269772661 <== \"a\"\n0x900150983CD24FB0D6963F7D28E17F72 <== \"abc\"\n0xF96B697D7CB7938D525A2F31AAF161D0 <== \"message digest\"\n0xC3FCD3D76192E4007DFB496CCA67E13B <== \"abcdefghijklmnopqrstuvwxyz\"\n0xD174AB98D277D9F5A5611C2C9F419D9F <== \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\n0x57EDF4A22BE3C955AC49DA2E2107B67A <== \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"\n\nWorks with: Java version 1.5+\n\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\nclass MD5\n{\n\n private static final int INIT_A = 0x67452301;\n private static final int INIT_B = (int)0xEFCDAB89L;\n private static final int INIT_C = (int)0x98BADCFEL;\n private static final int INIT_D = 0x10325476;\n \n private static final int[] SHIFT_AMTS = {\n 7, 12, 17, 22,\n 5, 9, 14, 20,\n 4, 11, 16, 23,\n 6, 10, 15, 21\n };\n \n private static final int[] TABLE_T = new int[64];\n static\n {\n for (int i = 0; i < 64; i++)\n TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));\n }\n \n public static byte[] computeMD5(byte[] message)\n {\n ByteBuffer padded = ByteBuffer.allocate((((message.length + 8) \/ 64) + 1) * 64).order(ByteOrder.LITTLE_ENDIAN);\n padded.put(message);\n padded.put((byte)0x80);\n long messageLenBits = (long)message.length * 8;\n padded.putLong(padded.capacity() - 8, messageLenBits);\n\n padded.rewind();\n\n int a = INIT_A;\n int b = INIT_B;\n int c = INIT_C;\n int d = INIT_D;\n while (padded.hasRemaining()) {\n \/\/ obtain a slice of the buffer from the current position,\n \/\/ and view it as an array of 32-bit ints\n IntBuffer chunk = padded.slice().order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();\n int originalA = a;\n int originalB = b;\n int originalC = c;\n int originalD = d;\n for (int j = 0; j < 64; j++)\n {\n int div16 = j >>> 4;\n int f = 0;\n int bufferIndex = j;\n switch (div16)\n {\n case 0:\n f = (b & c) | (~b & d);\n break;\n \n case 1:\n f = (b & d) | (c & ~d);\n bufferIndex = (bufferIndex * 5 + 1) & 0x0F;\n break;\n \n case 2:\n f = b ^ c ^ d;\n bufferIndex = (bufferIndex * 3 + 5) & 0x0F;\n break;\n \n case 3:\n f = c ^ (b | ~d);\n bufferIndex = (bufferIndex * 7) & 0x0F;\n break;\n }\n int temp = b + Integer.rotateLeft(a + f + chunk.get(bufferIndex) + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);\n a = d;\n d = c;\n c = b;\n b = temp;\n }\n \n a += originalA;\n b += originalB;\n c += originalC;\n d += originalD;\n padded.position(padded.position() + 64);\n }\n \n ByteBuffer md5 = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN);\n for (int n : new int[]{a, b, c, d})\n {\n md5.putInt(n);\n }\n return md5.array();\n }\n \n public static String toHexString(byte[] b)\n {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < b.length; i++)\n {\n sb.append(String.format(\"%02X\", b[i] & 0xFF));\n }\n return sb.toString();\n }\n\n public static void main(String[] args)\n {\n String[] testStrings = { \"\", \"a\", \"abc\", \"message digest\", \"abcdefghijklmnopqrstuvwxyz\", \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\" };\n for (String s : testStrings)\n System.out.println(\"0x\" + toHexString(computeMD5(s.getBytes())) + \" <== \\\"\" + s + \"\\\"\");\n return;\n }\n \n}\n\n\n0xD41D8CD98F00B204E9800998ECF8427E <== \"\"\n0x0CC175B9C0F1B6A831C399E269772661 <== \"a\"\n0x900150983CD24FB0D6963F7D28E17F72 <== \"abc\"\n0xF96B697D7CB7938D525A2F31AAF161D0 <== \"message digest\"\n0xC3FCD3D76192E4007DFB496CCA67E13B <== \"abcdefghijklmnopqrstuvwxyz\"\n0xD174AB98D277D9F5A5611C2C9F419D9F <== \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\n0x57EDF4A22BE3C955AC49DA2E2107B67A <== \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"\n\n","human_summarization":"implement the MD5 Message Digest Algorithm directly without using any built-in or external hashing libraries. The implementation produces a correct message digest for an input string and does not mimic all calling modes. It also includes any challenges faced during implementation, choices made, or limitations. The code does not use built-in MD5 functions or library routines written in other languages. It provides practical illustrations of bit manipulation, unsigned integers, and working with little-endian data. The code also includes verification strings and hashes from RFC 1321. However, it does not guarantee security as MD5 has been broken.","id":335} {"lang_cluster":"Java","source_code":"public class DepartmentNumbers {\n public static void main(String[] args) {\n System.out.println(\"Police Sanitation Fire\");\n System.out.println(\"------ ---------- ----\");\n int count = 0;\n for (int i = 2; i <= 6; i += 2) {\n for (int j = 1; j <= 7; ++j) {\n if (j == i) continue;\n for (int k = 1; k <= 7; ++k) {\n if (k == i || k == j) continue;\n if (i + j + k != 12) continue;\n System.out.printf(\" %d %d %d\\n\", i, j, k);\n count++;\n }\n }\n }\n System.out.printf(\"\\n%d valid combinations\", count);\n }\n}\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":336} {"lang_cluster":"Java","source_code":"\n\nString src = \"Hello\";\nString newAlias = src;\nString strCopy = new String(src);\n\n\/\/\"newAlias == src\" is true\n\/\/\"strCopy == src\" is false\n\/\/\"strCopy.equals(src)\" is true\n\n\nStringBuffer srcCopy = new StringBuffer(\"Hello\");\n\n","human_summarization":"create a copy of a string or make an additional reference to an existing string in Java, considering the immutability of Strings and the potential use of StringBuffer for mutable strings.","id":337} {"lang_cluster":"Java","source_code":"\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class MutualRecursion {\n\n public static void main(final String args[]) {\n int max = 20;\n System.out.printf(\"First %d values of the Female sequence: %n\", max);\n for (int i = 0; i < max; i++) {\n System.out.printf(\" f(%d) = %d%n\", i, f(i));\n }\n System.out.printf(\"First %d values of the Male sequence: %n\", max);\n for (int i = 0; i < 20; i++) {\n System.out.printf(\" m(%d) = %d%n\", i, m(i));\n }\n }\n\n private static Map F_MAP = new HashMap<>();\n\n private static int f(final int n) {\n if ( F_MAP.containsKey(n) ) {\n return F_MAP.get(n);\n }\n int fn = n == 0 ? 1 : n - m(f(n - 1));\n F_MAP.put(n, fn);\n return fn;\n }\n\n private static Map M_MAP = new HashMap<>();\n\n private static int m(final int n) {\n if ( M_MAP.containsKey(n) ) {\n return M_MAP.get(n);\n }\n int mn = n == 0 ? 0 : n - f(m(n - 1));\n M_MAP.put(n, mn);\n return mn;\n }\n \n\n}\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions handle base cases for n=0 and use the formula n-M(F(n-1)) for the female sequence and n-F(M(n-1)) for the male sequence for n>0. The functions also print the first 20 values of both sequences.","id":338} {"lang_cluster":"Java","source_code":"\nimport java.util.Random;\n...\nint[] array = {1,2,3};\nreturn array[new Random().nextInt(array.length)]; \/\/ if done multiple times, the Random object should be re-used\n\n\n","human_summarization":"demonstrate how to select a random element from a list. If the order of the list is not important, the list is shuffled and the first element is selected. This process is repeated each time unless the selected item is removed from the list.","id":339} {"lang_cluster":"Java","source_code":"\n\nimport java.net.URLDecoder;\nimport java.nio.charset.StandardCharsets;\n\nURLDecoder.decode(\"http%3A%2F%2Ffoo%20bar%2F\", StandardCharsets.UTF_8)\n\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nString decode(String string) {\n Pattern pattern = Pattern.compile(\"%([A-Za-z\\\\d]{2})\");\n Matcher matcher = pattern.matcher(string);\n StringBuilder decoded = new StringBuilder(string);\n char character;\n int start, end, offset = 0;\n while (matcher.find()) {\n character = (char) Integer.parseInt(matcher.group(1), 16);\n \/* offset the matched index since were adjusting the string *\/\n start = matcher.start() - offset;\n end = matcher.end() - offset;\n decoded.replace(start, end, String.valueOf(character));\n offset += 2;\n }\n return decoded.toString();\n}\n\nhttp:\/\/foo bar\/\ngoogle.com\/search?q=`Abdu'l-Bah\u00c3\u00a1\n\n","human_summarization":"provide a function to convert URL-encoded strings back to their original unencoded form, using either Java's URLDecoder and URLEncoder classes or a regular expression. The function correctly handles cases like \"%25%32%35\" reverting to \"%25\" instead of \"%\".","id":340} {"lang_cluster":"Java","source_code":"\n\npublic class BinarySearchIterative {\n\n public static int binarySearch(int[] nums, int check) {\n int hi = nums.length - 1;\n int lo = 0;\n while (hi >= lo) {\n int guess = (lo + hi) >>> 1; \/\/ from OpenJDK\n if (nums[guess] > check) {\n hi = guess - 1;\n } else if (nums[guess] < check) {\n lo = guess + 1;\n } else {\n return guess;\n }\n }\n return -1;\n }\n\n public static void main(String[] args) {\n int[] haystack = {1, 5, 6, 7, 8, 11};\n int needle = 5;\n int index = binarySearch(haystack, needle);\n if (index == -1) {\n System.out.println(needle + \" is not in the array\");\n } else {\n System.out.println(needle + \" is at index \" + index);\n }\n }\n}\n\n\npublic class BinarySearchRecursive {\n\n public static int binarySearch(int[] haystack, int needle, int lo, int hi) {\n if (hi < lo) {\n return -1;\n }\n int guess = (hi + lo) \/ 2;\n if (haystack[guess] > needle) {\n return binarySearch(haystack, needle, lo, guess - 1);\n } else if (haystack[guess] < needle) {\n return binarySearch(haystack, needle, guess + 1, hi);\n }\n return guess;\n }\n\n public static void main(String[] args) {\n int[] haystack = {1, 5, 6, 7, 8, 11};\n int needle = 5;\n\n int index = binarySearch(haystack, needle, 0, haystack.length);\n\n if (index == -1) {\n System.out.println(needle + \" is not in the array\");\n } else {\n System.out.println(needle + \" is at index \" + index);\n }\n }\n}\n\n\nimport java.util.Arrays;\n\nint index = Arrays.binarySearch(array, thing);\nint index = Arrays.binarySearch(array, startIndex, endIndex, thing);\n\n\/\/ for objects, also optionally accepts an additional comparator argument:\nint index = Arrays.binarySearch(array, thing, comparator);\nint index = Arrays.binarySearch(array, startIndex, endIndex, thing, comparator);\n\n\nimport java.util.Collections;\n\nint index = Collections.binarySearch(list, thing);\nint index = Collections.binarySearch(list, thing, comparator);\n\n","human_summarization":"The code implements a binary search algorithm on a sorted integer array. It takes the starting point, ending point, and a \"secret value\" as inputs. The algorithm divides the range into halves and continues to narrow down the search field until the secret value is found. It can be implemented both recursively and iteratively. The code also handles multiple values equal to the given value and returns the index of the secret value if found. Additionally, it provides the \"insertion point\" for the secret value if it's not found in the array. The code also avoids overflow bugs by calculating the mid-point in a safe manner.","id":341} {"lang_cluster":"Java","source_code":"\n\npublic static void main(String[] args)\n\n\nmyprogram -c \"alpha beta\" -h \"gamma\"\n\n\n-c\nalpha beta\n-h\ngamma\n\n\npublic class Arguments {\n public static void main(String[] args) {\n System.out.println(\"There are \" + args.length + \" arguments given.\");\n for(int i = 0; i < args.length; i++) \n System.out.println(\"The argument #\" + (i+1) + \" is \" + args[i] + \" and is at index \" + i);\n }\n}\n\n\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program. It parses these arguments intelligently and passes them to the main function as the only parameter. The code demonstrates how to use the Apache Commons CLI library for more sophisticated command-line option and argument parsing.","id":342} {"lang_cluster":"Java","source_code":"\nLibrary: Swing Library: AWT\nimport java.awt.*;\nimport javax.swing.*;\n\npublic class Pendulum extends JPanel implements Runnable {\n\n private double angle = Math.PI \/ 2;\n private int length;\n\n public Pendulum(int length) {\n this.length = length;\n setDoubleBuffered(true);\n }\n\n @Override\n public void paint(Graphics g) {\n g.setColor(Color.WHITE);\n g.fillRect(0, 0, getWidth(), getHeight());\n g.setColor(Color.BLACK);\n int anchorX = getWidth() \/ 2, anchorY = getHeight() \/ 4;\n int ballX = anchorX + (int) (Math.sin(angle) * length);\n int ballY = anchorY + (int) (Math.cos(angle) * length);\n g.drawLine(anchorX, anchorY, ballX, ballY);\n g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n g.fillOval(ballX - 7, ballY - 7, 14, 14);\n }\n\n public void run() {\n double angleAccel, angleVelocity = 0, dt = 0.1;\n while (true) {\n angleAccel = -9.81 \/ length * Math.sin(angle);\n angleVelocity += angleAccel * dt;\n angle += angleVelocity * dt;\n repaint();\n try { Thread.sleep(15); } catch (InterruptedException ex) {}\n }\n }\n\n @Override\n public Dimension getPreferredSize() {\n return new Dimension(2 * length + 50, length \/ 2 * 3);\n }\n\n public static void main(String[] args) {\n JFrame f = new JFrame(\"Pendulum\");\n Pendulum p = new Pendulum(200);\n f.add(p);\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.pack();\n f.setVisible(true);\n new Thread(p).start();\n }\n}\n\n","human_summarization":"create and animate a simple physical model of a gravity pendulum.","id":343} {"lang_cluster":"Java","source_code":"\n\/\/ Parse JSON\n\/\/\n\/\/ Nigel Galloway - April 27th., 2012\n\/\/\ngrammar JSON ;\n@members {\nString Indent = \"\";\n}\nNumber\t:\t(('0')|('-'? ('1'..'9') ('0'..'9')*)) ('.' ('0'..'9')+)? (('e'|'E') ('+'|'-')? ('0'..'9')+)?;\nWS\t:\t(' ' | '\\t' | '\\r' |'\\n') {skip();};\nTz\t:\t' ' .. '!' | '#' .. '[' | ']' .. '~';\nControl\t:\t'\\\\' ('\"'|'\\\\'|'\/'|'b'|'f'|'n'|'r'|'t'|UCode);\nUCode\t:\t'u' ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F');\nKeyword\t:\t'true' | 'false' | 'null';\nString\t:\t'\"' (Control? Tz)* '\"';\nobject\t: '{' {System.out.println(Indent + \"{Object}\"); Indent += \" \";} (pair (',' pair*)*)? '}' {Indent = Indent.substring(4);};\npair\t:\te = String {System.out.println(Indent + \"{Property}\\t\" + $e.text);} ':' value;\nvalue\t:\tNumber {System.out.println(Indent + \"{Number} \\t\" + $Number.text);}\n\t|\tobject\n\t|\tString {System.out.println(Indent + \"{String} \\t\" + $String.text);}\n\t|\tKeyword {System.out.println(Indent + \"{Keyword} \\t\" + $Keyword.text);}\n\t|\tarray;\narray\t:\t'[' {System.out.println(Indent + \"Array\"); Indent += \" \";} (value (',' value)*)? ']' {Indent = Indent.substring(4);};\n\n\n>java Test\n{\n \"Nigel\"\n \u00a0:\n -110.2e-13\n ,\n \"Fred\"\n \u00a0:\n {\n \"Joe\"\n \u00a0:\n [3,true,\"Nigel\"]\n }\n \"Harry\"\n \u00a0:\n [23,\"Hello\"]\n}\n^Z\n{Object}\n {Property} \"Nigel\"\n {Number} -110.2e-13\n {Property} \"Fred\"\n {Object}\n {Property} \"Joe\"\n Array\n {Number} 3\n {Keyword} true\n {String} \"Nigel\"\n {Property} \"Harry\"\n Array\n {Number} 23\n {String} \"Hello\"\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON using objects and arrays.\"","id":344} {"lang_cluster":"Java","source_code":"public static double nthroot(int n, double A) {\n\treturn nthroot(n, A, .001);\n}\npublic static double nthroot(int n, double A, double p) {\n\tif(A < 0) {\n\t\tSystem.err.println(\"A < 0\");\/\/ we handle only real positive numbers\n\t\treturn -1;\n\t} else if(A == 0) {\n\t\treturn 0;\n\t}\n\tdouble x_prev = A;\n\tdouble x = A \/ n; \/\/ starting \"guessed\" value...\n\twhile(Math.abs(x - x_prev) > p) {\n\t\tx_prev = x;\n\t\tx = ((n - 1.0) * x + A \/ Math.pow(x, n - 1.0)) \/ n;\n\t}\n\treturn x;\n}\npublic static double nthroot(int n, double x) {\n assert (n > 1 && x > 0);\n int np = n - 1;\n double g1 = x;\n double g2 = iter(g1, np, n, x);\n while (g1 != g2) {\n g1 = iter(g1, np, n, x);\n g2 = iter(iter(g2, np, n, x), np, n, x);\n }\n return g1;\n}\n\nprivate static double iter(double g, int np, int n, double x) {\n return (np * g + x \/ Math.pow(g, np)) \/ n;\n}\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":345} {"lang_cluster":"Java","source_code":"\nimport java.net.InetAddress;\nimport java.net.UnknownHostException;\n\nvoid printHostname() throws UnknownHostException {\n InetAddress localhost = InetAddress.getLocalHost();\n System.out.println(localhost.getHostName());\n}\n\npenguin\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":346} {"lang_cluster":"Java","source_code":"import java.util.Arrays;\nimport java.util.List;\n\n@SuppressWarnings(\"SameParameterValue\")\npublic class LeonardoNumbers {\n private static List leonardo(int n) {\n return leonardo(n, 1, 1, 1);\n }\n\n private static List leonardo(int n, int l0, int l1, int add) {\n Integer[] leo = new Integer[n];\n leo[0] = l0;\n leo[1] = l1;\n for (int i = 2; i < n; i++) {\n leo[i] = leo[i - 1] + leo[i - 2] + add;\n }\n return Arrays.asList(leo);\n }\n\n public static void main(String[] args) {\n System.out.println(\"The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:\");\n System.out.println(leonardo(25));\n System.out.println(\"\\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:\");\n System.out.println(leonardo(25, 0, 1, 0));\n }\n}\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":347} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 7\nimport java.util.*;\n\npublic class Game24 {\n static Random r = new Random();\n\n public static void main(String[] args) {\n\n int[] digits = randomDigits();\n Scanner in = new Scanner(System.in);\n\n System.out.print(\"Make 24 using these digits: \");\n System.out.println(Arrays.toString(digits));\n System.out.print(\"> \");\n\n Stack s = new Stack<>();\n long total = 0;\n for (char c : in.nextLine().toCharArray()) {\n if ('0' <= c && c <= '9') {\n int d = c - '0';\n total += (1 << (d * 5));\n s.push((float) d);\n } else if (\"+\/-*\".indexOf(c) != -1) {\n s.push(applyOperator(s.pop(), s.pop(), c));\n }\n }\n if (tallyDigits(digits) != total)\n System.out.print(\"Not the same digits. \");\n else if (Math.abs(24 - s.peek()) < 0.001F)\n System.out.println(\"Correct!\");\n else\n System.out.print(\"Not correct.\");\n }\n\n static float applyOperator(float a, float b, char c) {\n switch (c) {\n case '+':\n return a + b;\n case '-':\n return b - a;\n case '*':\n return a * b;\n case '\/':\n return b \/ a;\n default:\n return Float.NaN;\n }\n }\n\n static long tallyDigits(int[] a) {\n long total = 0;\n for (int i = 0; i < 4; i++)\n total += (1 << (a[i] * 5));\n return total;\n }\n\n static int[] randomDigits() { \n int[] result = new int[4];\n for (int i = 0; i < 4; i++)\n result[i] = r.nextInt(9) + 1;\n return result;\n }\n}\n\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":348} {"lang_cluster":"Java","source_code":"\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nString encode(String string) {\n Pattern pattern = Pattern.compile(\"(.)\\\\1*\");\n Matcher matcher = pattern.matcher(string);\n StringBuilder encoded = new StringBuilder();\n while (matcher.find()) {\n encoded.append(matcher.group().length());\n encoded.append(matcher.group().charAt(0));\n }\n return encoded.toString();\n}\n\nString decode(String string) {\n Pattern pattern = Pattern.compile(\"(\\\\d+)(.)\");\n Matcher matcher = pattern.matcher(string);\n StringBuilder decoded = new StringBuilder();\n int count;\n while (matcher.find()) {\n count = Integer.parseInt(matcher.group(1));\n decoded.append(matcher.group(2).repeat(count));\n }\n return decoded.toString();\n}\n\nstring = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nencoded = 12W1B12W3B24W1B14W\ndecoded = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nstring.equals(decoded) = true\n\nstring = https:\/\/www.rosettacode.org\/\nencoded = 1h2t1p1s1:2\/3w1.1r1o1s1e2t1a1c1o1d1e1.1o1r1g1\/\ndecoded = https:\/\/www.rosettacode.org\/\nstring.equals(decoded) = true\n\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class RunLengthEncoding {\n\n public static String encode(String source) {\n StringBuffer dest = new StringBuffer();\n for (int i = 0; i < source.length(); i++) {\n int runLength = 1;\n while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {\n runLength++;\n i++;\n }\n dest.append(runLength);\n dest.append(source.charAt(i));\n }\n return dest.toString();\n }\n\n public static String decode(String source) {\n StringBuffer dest = new StringBuffer();\n Pattern pattern = Pattern.compile(\"[0-9]+|[a-zA-Z]\");\n Matcher matcher = pattern.matcher(source);\n while (matcher.find()) {\n int number = Integer.parseInt(matcher.group());\n matcher.find();\n while (number-- != 0) {\n dest.append(matcher.group());\n }\n }\n return dest.toString();\n }\n\n public static void main(String[] args) {\n String example = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\";\n System.out.println(encode(example));\n System.out.println(decode(\"1W1B1W1B1W1B1W1B1W1B1W1B1W1B\"));\n }\n}\n\n\nLibrary: JUnit\nimport static org.junit.Assert.assertEquals;\n\nimport org.junit.Test;\n\npublic class RunLengthEncodingTest {\n\tprivate RLE = new RunLengthEncoding();\n\n\t@Test\n\tpublic void encodingTest() {\n\t\tassertEquals(\"1W\", RLE.encode(\"W\"));\n\t\tassertEquals(\"4W\", RLE.encode(\"WWWW\"));\n\t\tassertEquals(\"5w4i7k3i6p5e4d2i1a\",\n\t\t\t\tRLE.encode(\"wwwwwiiiikkkkkkkiiippppppeeeeeddddiia\"));\n\t\tassertEquals(\"12B1N12B3N24B1N14B\",\n\t\t\t\tRLE.encode(\"BBBBBBBBBBBBNBBBBBBBBBBBBNNNBBBBBBBBBBBBBBBBBBBBBBBBNBBBBBBBBBBBBBB\"));\n\t\tassertEquals(\"12W1B12W3B24W1B14W\",\n\t\t\t\tRLE.encode(\"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"));\n\t\tassertEquals(\"1W1B1W1B1W1B1W1B1W1B1W1B1W1B\", RLE.encode(\"WBWBWBWBWBWBWB\"));\n\n\t}\n\n\t@Test\n\tpublic void decodingTest() {\n\t\tassertEquals(\"W\", RLE.decode(\"1W\"));\n\t\tassertEquals(\"WWWW\", RLE.decode(\"4W\"));\n\t\tassertEquals(\"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\",\n\t\t\t\tRLE.decode(\"12W1B12W3B24W1B14W\"));\n\t\tassertEquals(\"WBWBWBWBWBWBWB\", RLE.decode(\"1W1B1W1B1W1B1W1B1W1B1W1B1W1B\"));\n\t\tassertEquals(\"WBWBWBWBWBWBWB\", RLE.decode(\"1W1B1W1B1W1B1W1B1W1B1W1B1W1B\"));\n\n\t}\n}\n\n","human_summarization":"implement a run-length encoding and decoding system. The codes take a string of uppercase characters, compresses repeated sequences of the same character by recording the length of the sequence, and provides a function to reverse the compression. The output format is flexible as long as the original input can be recreated. The codes also include a demonstration of how this can be achieved using regular expressions.","id":349} {"lang_cluster":"Java","source_code":"\n\nString string = \"abc\" + \"def\";\n\n\nString string = \"abc\";\nstring += \"def\";\n\n\nString string = \"abc\".concat(\"def\");\n\n\nStringBuilder string = new StringBuilder();\nstring.append(\"abc\").append(\"def\");\n\n\nStringBuilder string = new StringBuilder();\nstring.append(\"abc\");\nstring.insert(3, \"def\");\n\n\nString string = String.format(\"%s%s\", \"abc\", \"def\");\n\nString string = \"%s%s\".formatted(\"abc\", \"def\");\n\n\nabcdef\n\n\npublic class Str{\n public static void main(String[] args){\n String s = \"hello\";\n System.out.println(s + \" literal\");\n String s2 = s + \" literal\";\n System.out.println(s2);\n }\n}\n\n\n","human_summarization":"create two string variables, one with a text value and the other concatenating the original string with another string literal. The code demonstrates various methods of string concatenation in Java, including the use of the plus operator, the String.concat method, StringBuilder, and the String.format or String.formatted methods. The result of each method is displayed.","id":350} {"lang_cluster":"Java","source_code":"\n\nimport java.net.URLEncoder;\nimport java.nio.charset.StandardCharsets;\n\nURLEncoder.encode(\"http:\/\/foo bar\/\", StandardCharsets.UTF_8)\n\n\nString encode(String string) {\n StringBuilder encoded = new StringBuilder();\n for (char character : string.toCharArray()) {\n switch (character) {\n \/* rfc3986 and html5 *\/\n case '-', '.', '_', '~', '*' -> encoded.append(character);\n case ' ' -> encoded.append('+');\n default -> {\n if (alphanumeric(character))\n encoded.append(character);\n else {\n encoded.append(\"%\");\n encoded.append(\"%02x\".formatted((int) character));\n }\n }\n }\n }\n return encoded.toString();\n}\n\nboolean alphanumeric(char character) {\n return (character >= 'A' && character <= 'Z')\n || (character >= 'a' && character <= 'z')\n || (character >= '0' && character <= '9');\n}\n\nhttp%3a%2f%2ffoo+bar%2f\n\n","human_summarization":"provide a function to convert a given string into URL encoding format. It replaces special, control, and extended characters with a percent symbol followed by a two-digit hexadecimal code. The conversion applies to all characters except 0-9, A-Z, and a-z. An exception string can be used to specify symbols that don't need conversion. The function can be implemented using Java's URLEncoder and URLDecoder classes or a basic for-loop.","id":351} {"lang_cluster":"Java","source_code":"\n\npackage hu.pj.alg.test;\n\nimport hu.pj.alg.ContinuousKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ContinousKnapsackForRobber {\n final private double tolerance = 0.0005;\n\n public ContinousKnapsackForRobber() {\n ContinuousKnapsack cok = new ContinuousKnapsack(15); \/\/ 15 kg\n\n \/\/ making the list of items that you want to bring\n cok.add(\"beef\", 3.8, 36); \/\/ marhah\u00fas\n cok.add(\"pork\", 5.4, 43); \/\/ diszn\u00f3h\u00fas\n cok.add(\"ham\", 3.6, 90); \/\/ sonka\n cok.add(\"greaves\", 2.4, 45); \/\/ tepert\u0151\n cok.add(\"flitch\", 4.0, 30); \/\/ oldalas\n cok.add(\"brawn\", 2.5, 56); \/\/ diszn\u00f3sajt\n cok.add(\"welt\", 3.7, 67); \/\/ hurka\n cok.add(\"salami\", 3.0, 95); \/\/ szal\u00e1mi\n cok.add(\"sausage\", 5.9, 98); \/\/ kolb\u00e1sz\n\n \/\/ calculate the solution:\n List itemList = cok.calcSolution();\n\n \/\/ write out the solution in the standard output\n if (cok.isCalculated()) {\n NumberFormat nf = NumberFormat.getInstance();\n\n System.out.println(\n \"Maximal weight = \" +\n nf.format(cok.getMaxWeight()) + \" kg\"\n );\n System.out.println(\n \"Total weight of solution = \" +\n nf.format(cok.getSolutionWeight()) + \" kg\"\n );\n System.out.println(\n \"Total value (profit) = \" +\n nf.format(cok.getProfit())\n );\n System.out.println();\n System.out.println(\n \"You can carry the following materials \" +\n \"in the knapsack:\"\n );\n for (Item item : itemList) {\n if (item.getInKnapsack() > tolerance) {\n System.out.format(\n \"%1$-10s %2$-15s %3$-15s \\n\",\n nf.format(item.getInKnapsack()) + \" kg \",\n item.getName(),\n \"(value = \" + nf.format(item.getInKnapsack() *\n (item.getValue() \/ item.getWeight())) + \")\"\n );\n }\n }\n } else {\n System.out.println(\n \"The problem is not solved. \" +\n \"Maybe you gave wrong data.\"\n );\n }\n\n }\n\n public static void main(String[] args) {\n new ContinousKnapsackForRobber();\n }\n\n} \/\/ class\n\npackage hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.util.*;\n\npublic class ContinuousKnapsack {\n\n protected List itemList = new ArrayList();\n protected double maxWeight = 0;\n protected double solutionWeight = 0;\n protected double profit = 0;\n protected boolean calculated = false;\n\n public ContinuousKnapsack() {}\n\n public ContinuousKnapsack(double _maxWeight) {\n setMaxWeight(_maxWeight);\n }\n\n public List calcSolution() {\n int n = itemList.size();\n\n setInitialStateForCalculation();\n if (n > 0 && maxWeight > 0) {\n Collections.sort(itemList);\n for (int i = 0; (maxWeight - solutionWeight) > 0.0 && i < n; i++) {\n Item item = itemList.get(i);\n if (item.getWeight() >= (maxWeight - solutionWeight)) {\n item.setInKnapsack(maxWeight - solutionWeight);\n solutionWeight = maxWeight;\n profit += item.getInKnapsack() \/ item.getWeight() * item.getValue();\n break;\n } else {\n item.setInKnapsack(item.getWeight());\n solutionWeight += item.getInKnapsack();\n profit += item.getValue();\n }\n }\n calculated = true;\n }\n \n return itemList;\n }\n\n \/\/ add an item to the item list\n public void add(String name, double weight, double value) {\n if (name.equals(\"\"))\n name = \"\" + (itemList.size() + 1);\n itemList.add(new Item(name, weight, value));\n setInitialStateForCalculation();\n }\n\n public double getMaxWeight() {return maxWeight;}\n public double getProfit() {return profit;}\n public double getSolutionWeight() {return solutionWeight;}\n public boolean isCalculated() {return calculated;}\n\n public void setMaxWeight(double _maxWeight) {\n maxWeight = Math.max(_maxWeight, 0);\n }\n\n \/\/ set the member with name \"inKnapsack\" by all items:\n private void setInKnapsackByAll(double inKnapsack) {\n for (Item item : itemList)\n item.setInKnapsack(inKnapsack);\n }\n\n \/\/ set the data members of class in the state of starting the calculation:\n protected void setInitialStateForCalculation() {\n setInKnapsackByAll(-0.0001);\n calculated = false;\n profit = 0.0;\n solutionWeight = 0.0;\n }\n\n} \/\/ class\n\npackage hu.pj.obj;\n\npublic class Item implements Comparable {\n\n protected String name = \"\";\n protected double weight = 0;\n protected double value = 0;\n protected double inKnapsack = 0; \/\/ the weight of item in solution\n\n public Item() {}\n\n public Item(Item item) {\n setName(item.name);\n setWeight(item.weight);\n setValue(item.value);\n }\n\n public Item(double _weight, double _value) {\n setWeight(_weight);\n setValue(_value);\n }\n\n public Item(String _name, double _weight, double _value) {\n setName(_name);\n setWeight(_weight);\n setValue(_value);\n }\n\n public void setName(String _name) {name = _name;}\n public void setWeight(double _weight) {weight = Math.max(_weight, 0);}\n public void setValue(double _value) {value = Math.max(_value, 0);}\n\n public void setInKnapsack(double _inKnapsack) {\n inKnapsack = Math.max(_inKnapsack, 0);\n }\n\n public void checkMembers() {\n setWeight(weight);\n setValue(value);\n setInKnapsack(inKnapsack);\n }\n\n public String getName() {return name;}\n public double getWeight() {return weight;}\n public double getValue() {return value;}\n public double getInKnapsack() {return inKnapsack;}\n\n \/\/ implementing of Comparable interface:\n public int compareTo(Object item) {\n int result = 0;\n Item i2 = (Item)item;\n double rate1 = value \/ weight;\n double rate2 = i2.value \/ i2.weight;\n if (rate1 > rate2) result = -1; \/\/ if greater, put it previously\n else if (rate1 < rate2) result = 1;\n return result;\n }\n\n} \/\/ class\n\n\nMaximal weight = 15 kg\nTotal weight of solution = 15 kg\nTotal value (profit) = 349,378\n\nYou can carry the following materials in the knapsack:\n3 kg salami (value = 95) \n3,6 kg ham (value = 90) \n2,5 kg brawn (value = 56) \n2,4 kg greaves (value = 45) \n3,5 kg welt (value = 63,378)\n","human_summarization":"implement a solution for the continuous knapsack problem. The program takes a list of items available in a butcher's shop with their weights and prices, and determines the optimal selection of items for a thief to maximize his profit while not exceeding a total weight of 15 kg. The program allows for items to be cut, with the price of the cut item being proportional to its mass. The output shows the items the thief should carry in his knapsack.","id":352} {"lang_cluster":"Java","source_code":"\n\nWorks with: Java version 1.5+\nimport java.net.*;\nimport java.io.*;\nimport java.util.*;\n \npublic class WordsOfEqChars {\n public static void main(String[] args) throws IOException {\n URL url = new URL(\"http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt\");\n InputStreamReader isr = new InputStreamReader(url.openStream());\n BufferedReader reader = new BufferedReader(isr);\n\n Map> anagrams = new HashMap>();\n String word;\n int count = 0;\n while ((word = reader.readLine()) != null) {\n char[] chars = word.toCharArray();\n Arrays.sort(chars);\n String key = new String(chars);\n if (!anagrams.containsKey(key))\n anagrams.put(key, new ArrayList());\n anagrams.get(key).add(word);\n count = Math.max(count, anagrams.get(key).size());\n }\n\n reader.close();\n\n for (Collection ana : anagrams.values())\n if (ana.size() >= count)\n System.out.println(ana);\n } \n}\n\nWorks with: Java version 1.8+\nimport java.net.*;\nimport java.io.*;\nimport java.util.*;\nimport java.util.concurrent.*;\nimport java.util.function.*;\n\npublic interface Anagram {\n public static Supplier tryWithResources(Callable callable, Function> function, Supplier defaultSupplier) {\n return () -> {\n try (AUTOCLOSEABLE autoCloseable = callable.call()) {\n return function.apply(autoCloseable).get();\n } catch (Throwable throwable) {\n return defaultSupplier.get();\n }\n };\n }\n\n public static Function function(Supplier supplier) {\n return i -> supplier.get();\n }\n\n public static void main(String... args) {\n Map> anagrams = new ConcurrentSkipListMap<>();\n int count = tryWithResources(\n () -> new BufferedReader(\n new InputStreamReader(\n new URL(\n \"http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt\"\n ).openStream()\n )\n ),\n reader -> () -> reader.lines()\n .parallel()\n .mapToInt(word -> {\n char[] chars = word.toCharArray();\n Arrays.parallelSort(chars);\n String key = Arrays.toString(chars);\n Collection collection = anagrams.computeIfAbsent(\n key, function(ArrayList::new)\n );\n collection.add(word);\n return collection.size();\n })\n .max()\n .orElse(0),\n () -> 0\n ).get();\n anagrams.values().stream()\n .filter(ana -> ana.size() >= count)\n .forEach(System.out::println)\n ;\n }\n}\n\n\n","human_summarization":"The code sorts the characters in each word from a dictionary, identifies sets of words that are anagrams (i.e., composed of the same characters but in different orders), and finds the sets with the most words. It uses a quicksort algorithm to sort the letters in each word and maps the anagrams under a key composed of the sorted characters. The dictionary used for this task is located at http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt.","id":353} {"lang_cluster":"Java","source_code":"public static boolean inCarpet(long x, long y) {\n while (x!=0 && y!=0) {\n if (x % 3 == 1 && y % 3 == 1)\n return false;\n x \/= 3;\n y \/= 3;\n }\n return true;\n}\n \npublic static void carpet(final int n) {\n final double power = Math.pow(3,n);\n for(long i = 0; i < power; i++) {\n for(long j = 0; j < power; j++) {\n System.out.print(inCarpet(i, j) ? \"*\" : \" \");\n }\n System.out.println();\n }\n}\n\n\nWorks with: java version 8\nimport java.awt.*;\nimport java.awt.event.ActionEvent;\nimport javax.swing.*;\n\npublic class SierpinskiCarpet extends JPanel {\n private final int dim = 513;\n private final int margin = 20;\n\n private int limit = dim;\n\n public SierpinskiCarpet() {\n setPreferredSize(new Dimension(dim + 2 * margin, dim + 2 * margin));\n setBackground(Color.white);\n setForeground(Color.orange);\n\n new Timer(2000, (ActionEvent e) -> {\n limit \/= 3;\n if (limit <= 3)\n limit = dim;\n repaint();\n }).start();\n }\n\n void drawCarpet(Graphics2D g, int x, int y, int size) {\n if (size < limit)\n return;\n size \/= 3;\n for (int i = 0; i < 9; i++) {\n if (i == 4) {\n g.fillRect(x + size, y + size, size, size);\n } else {\n drawCarpet(g, x + (i % 3) * size, y + (i \/ 3) * size, size);\n }\n }\n }\n\n @Override\n public void paintComponent(Graphics gg) {\n super.paintComponent(gg);\n Graphics2D g = (Graphics2D) gg;\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON);\n g.translate(margin, margin);\n drawCarpet(g, 0, 0, dim);\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(() -> {\n JFrame f = new JFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setTitle(\"Sierpinski Carpet\");\n f.setResizable(false);\n f.add(new SierpinskiCarpet(), BorderLayout.CENTER);\n f.pack();\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n });\n }\n}\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":354} {"lang_cluster":"Java","source_code":"\n\nimport java.util.*;\n\nabstract class HuffmanTree implements Comparable {\n public final int frequency; \/\/ the frequency of this tree\n public HuffmanTree(int freq) { frequency = freq; }\n\n \/\/ compares on the frequency\n public int compareTo(HuffmanTree tree) {\n return frequency - tree.frequency;\n }\n}\n\nclass HuffmanLeaf extends HuffmanTree {\n public final char value; \/\/ the character this leaf represents\n \n public HuffmanLeaf(int freq, char val) {\n super(freq);\n value = val;\n }\n}\n\nclass HuffmanNode extends HuffmanTree {\n public final HuffmanTree left, right; \/\/ subtrees\n \n public HuffmanNode(HuffmanTree l, HuffmanTree r) {\n super(l.frequency + r.frequency);\n left = l;\n right = r;\n }\n}\n\npublic class HuffmanCode {\n \/\/ input is an array of frequencies, indexed by character code\n public static HuffmanTree buildTree(int[] charFreqs) {\n PriorityQueue trees = new PriorityQueue();\n \/\/ initially, we have a forest of leaves\n \/\/ one for each non-empty character\n for (int i = 0; i < charFreqs.length; i++)\n if (charFreqs[i] > 0)\n trees.offer(new HuffmanLeaf(charFreqs[i], (char)i));\n\n assert trees.size() > 0;\n \/\/ loop until there is only one tree left\n while (trees.size() > 1) {\n \/\/ two trees with least frequency\n HuffmanTree a = trees.poll();\n HuffmanTree b = trees.poll();\n\n \/\/ put into new node and re-insert into queue\n trees.offer(new HuffmanNode(a, b));\n }\n return trees.poll();\n }\n\n public static void printCodes(HuffmanTree tree, StringBuffer prefix) {\n assert tree != null;\n if (tree instanceof HuffmanLeaf) {\n HuffmanLeaf leaf = (HuffmanLeaf)tree;\n\n \/\/ print out character, frequency, and code for this leaf (which is just the prefix)\n System.out.println(leaf.value + \"\\t\" + leaf.frequency + \"\\t\" + prefix);\n\n } else if (tree instanceof HuffmanNode) {\n HuffmanNode node = (HuffmanNode)tree;\n\n \/\/ traverse left\n prefix.append('0');\n printCodes(node.left, prefix);\n prefix.deleteCharAt(prefix.length()-1);\n\n \/\/ traverse right\n prefix.append('1');\n printCodes(node.right, prefix);\n prefix.deleteCharAt(prefix.length()-1);\n }\n }\n\n public static void main(String[] args) {\n String test = \"this is an example for huffman encoding\";\n\n \/\/ we will assume that all our characters will have\n \/\/ code less than 256, for simplicity\n int[] charFreqs = new int[256];\n \/\/ read each character and record the frequencies\n for (char c : test.toCharArray())\n charFreqs[c]++;\n\n \/\/ build tree\n HuffmanTree tree = buildTree(charFreqs);\n\n \/\/ print out results\n System.out.println(\"SYMBOL\\tWEIGHT\\tHUFFMAN CODE\");\n printCodes(tree, new StringBuffer());\n }\n}\n\n\n","human_summarization":"The code takes a string input, calculates the frequency of each character, and generates a Huffman encoding for each character. It constructs a binary tree where each node represents a character and its frequency, with higher frequency characters closer to the root. The code then traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute the Huffman encoding for the corresponding character. The output is a table of characters and their Huffman encodings.","id":355} {"lang_cluster":"Java","source_code":"\nLibrary: AWT\nLibrary: Swing\nimport java.awt.BorderLayout;\nimport java.awt.Dimension;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.SwingUtilities;\npublic class Clicks extends JFrame{\n\tprivate long clicks = 0;\n\n\tpublic Clicks(){\n\t\tsuper(\"Clicks\");\/\/set window title\n\t\tJLabel label = new JLabel(\"There have been no clicks yet\");\n\t\tJButton clicker = new JButton(\"click me\");\n\t\tclicker.addActionListener(\/\/listen to the button\n\t\t\tnew ActionListener(){\n\t\t\t\t@Override\n\t\t\t\tpublic void actionPerformed(ActionEvent e) {\n\t\t\t\t\tlabel.setText(\"There have been \" + (++clicks) + \" clicks\");\/\/change the text\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t\tsetLayout(new BorderLayout());\/\/handles placement of components\n\t\tadd(label,BorderLayout.CENTER);\/\/add the label to the biggest section\n\t\tadd(clicker,BorderLayout.SOUTH);\/\/put the button underneath it\n\t\tlabel.setPreferredSize(new Dimension(300,100));\/\/nice big label\n\t\tlabel.setHorizontalAlignment(JLabel.CENTER);\/\/text not up against the side\n\t\tpack();\/\/fix layout\n\t\tsetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\/\/stop the program on \"X\"\n\t\tsetVisible(true);\/\/show it\n\t}\n\tpublic static void main(String[] args){\n\t\tSwingUtilities.invokeLater( \/\/Swing UI updates should not happen on the main thread\n\t\t\t() -> new Clicks() \/\/call the constructor where all the magic happens\n\t\t);\n\t}\n}\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":356} {"lang_cluster":"Java","source_code":"\nfor (int i = 10; i >= 0; i--) {\n System.out.println(i);\n}\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":357} {"lang_cluster":"Java","source_code":"public class VigenereCipher {\n public static void main(String[] args) {\n String key = \"VIGENERECIPHER\";\n String ori = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n String enc = encrypt(ori, key);\n System.out.println(enc);\n System.out.println(decrypt(enc, key));\n }\n\n static String encrypt(String text, final String key) {\n String res = \"\";\n text = text.toUpperCase();\n for (int i = 0, j = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (c < 'A' || c > 'Z') continue;\n res += (char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A');\n j = ++j % key.length();\n }\n return res;\n }\n\n static String decrypt(String text, final String key) {\n String res = \"\";\n text = text.toUpperCase();\n for (int i = 0, j = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n if (c < 'A' || c > 'Z') continue;\n res += (char)((c - key.charAt(j) + 26) % 26 + 'A');\n j = ++j % key.length();\n }\n return res;\n }\n}\n\nWMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\nBEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\nimport com.google.common.collect.Streams;\nimport java.util.function.Supplier;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\nimport static java.nio.charset.StandardCharsets.US_ASCII;\n\npublic class VigenereCipher {\n private final static int LOWER = 'A';\n private final static int UPPER = 'Z';\n private final static int SIZE = UPPER - LOWER + 1;\n private final Supplier> maskStream;\n\n public VigenereCipher(final String key) {\n final String mask = new String(key.getBytes(US_ASCII)).toUpperCase();\n maskStream = () ->\n Stream.iterate(0, i -> (i+1) % mask.length()).map(mask::charAt);\n }\n\n private String transform(final String text, final boolean encode) {\n final Stream textStream = text.toUpperCase().chars().boxed()\n .filter(i -> i >= LOWER && i <= UPPER);\n return Streams.zip(textStream, maskStream.get(), (c, m) ->\n encode ? c + m - 2 * LOWER : c - m + SIZE)\n .map(c -> Character.toString(c % SIZE + LOWER))\n .collect(Collectors.joining());\n }\n\n public String encrypt(final String plaintext) {\n return transform(plaintext,true);\n }\n\n public String decrypt(final String ciphertext) {\n return transform(ciphertext,false);\n }\n}\n\nimport org.junit.jupiter.api.DisplayName;\nimport org.junit.jupiter.api.Test;\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nclass VigenereCipherTest {\n private static final VigenereCipher Vigenere = new VigenereCipher(\"VIGENERECIPHER\");\n\n @Test\n @DisplayName(\"encipher\/decipher round-trip succeeds\")\n void vigenereCipherTest() {\n final String input = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n final String expectEncrypted = \"WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\";\n final String expectDecrypted = \"BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\";\n\n final String ciphertext = Vigenere.encrypt(input);\n assertEquals(expectEncrypted, ciphertext);\n\n final String plaintext = Vigenere.decrypt(ciphertext);\n assertEquals(expectDecrypted, plaintext);\n }\n\n}\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":358} {"lang_cluster":"Java","source_code":"\nfor(int i = 2; i <= 8;i += 2){\n System.out.print(i + \", \");\n}\nSystem.out.println(\"who do we appreciate?\");\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":359} {"lang_cluster":"Java","source_code":"\n\nimport java.util.function.*;\nimport java.util.stream.*;\n\npublic class Jensen {\n static double sum(int lo, int hi, IntToDoubleFunction f) {\n return IntStream.rangeClosed(lo, hi).mapToDouble(f).sum();\n }\n \n public static void main(String args[]) {\n System.out.println(sum(1, 100, (i -> 1.0\/i)));\n }\n}\n\n\npublic class Jensen2 {\n\n interface IntToDoubleFunction {\n double apply(int n);\n }\n\n static double sum(int lo, int hi, IntToDoubleFunction f) {\n double res = 0;\n for (int i = lo; i <= hi; i++)\n res += f.apply(i);\n return res;\n\n }\n public static void main(String args[]) {\n System.out.println(\n sum(1, 100,\n new IntToDoubleFunction() {\n public double apply(int i) { return 1.0\/i;}\n }));\n }\n}\n\n","human_summarization":"The code is an implementation of Jensen's Device, a programming technique devised by J\u00f8rn Jensen. It uses the call by name method to compute the 100th harmonic number. The program exploits call by name to produce the correct answer by re-evaluating an expression passed as an actual parameter in the caller's context every time the corresponding formal parameter's value is required. The first parameter to the sum function, representing the \"bound\" variable of the summation, is also passed by name to ensure changes to it are visible in the caller's context. The program prints '5.187377517639621'.","id":360} {"lang_cluster":"Java","source_code":"\nLibrary: Swing\n\nimport java.awt.Color;\nimport java.awt.Graphics;\n\nimport javax.swing.JFrame;\nimport javax.swing.JPanel;\n\npublic class XorPattern extends JFrame{\n private JPanel xorPanel;\n\n public XorPattern(){\n xorPanel = new JPanel(){\n @Override\n public void paint(Graphics g) {\n for(int y = 0; y < getHeight();y++){\n for(int x = 0; x < getWidth();x++){\n g.setColor(new Color(0, (x ^ y) % 256, 0));\n g.drawLine(x, y, x, y);\n }\n }\n }\n };\n add(xorPanel);\n setSize(300, 300);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setVisible(true);\n }\n\n public static void main(String[] args){\n new XorPattern();\n }\n}\n\n\n","human_summarization":"generates a repeating graphical pattern by coloring each pixel based on the 'x xor y' value from a specified color table, and adapts to window size changes.","id":361} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\npackage org.rosettacode;\n\nimport java.util.Collections;\nimport java.util.Arrays;\n\n\/*\n * recursive backtracking algorithm\n * shamelessly borrowed from the ruby at\n * http:\/\/weblog.jamisbuck.org\/2010\/12\/27\/maze-generation-recursive-backtracking\n *\/\npublic class MazeGenerator {\n\tprivate final int x;\n\tprivate final int y;\n\tprivate final int[][] maze;\n\n\tpublic MazeGenerator(int x, int y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tmaze = new int[this.x][this.y];\n\t\tgenerateMaze(0, 0);\n\t}\n\n\tpublic void display() {\n\t\tfor (int i = 0; i < y; i++) {\n\t\t\t\/\/ draw the north edge\n\t\t\tfor (int j = 0; j < x; j++) {\n\t\t\t\tSystem.out.print((maze[j][i] & 1) == 0 ? \"+---\" : \"+ \");\n\t\t\t}\n\t\t\tSystem.out.println(\"+\");\n\t\t\t\/\/ draw the west edge\n\t\t\tfor (int j = 0; j < x; j++) {\n\t\t\t\tSystem.out.print((maze[j][i] & 8) == 0 ? \"| \" : \" \");\n\t\t\t}\n\t\t\tSystem.out.println(\"|\");\n\t\t}\n\t\t\/\/ draw the bottom line\n\t\tfor (int j = 0; j < x; j++) {\n\t\t\tSystem.out.print(\"+---\");\n\t\t}\n\t\tSystem.out.println(\"+\");\n\t}\n\n\tprivate void generateMaze(int cx, int cy) {\n\t\tDIR[] dirs = DIR.values();\n\t\tCollections.shuffle(Arrays.asList(dirs));\n\t\tfor (DIR dir : dirs) {\n\t\t\tint nx = cx + dir.dx;\n\t\t\tint ny = cy + dir.dy;\n\t\t\tif (between(nx, x) && between(ny, y)\n\t\t\t\t\t&& (maze[nx][ny] == 0)) {\n\t\t\t\tmaze[cx][cy] |= dir.bit;\n\t\t\t\tmaze[nx][ny] |= dir.opposite.bit;\n\t\t\t\tgenerateMaze(nx, ny);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static boolean between(int v, int upper) {\n\t\treturn (v >= 0) && (v < upper);\n\t}\n\n\tprivate enum DIR {\n\t\tN(1, 0, -1), S(2, 0, 1), E(4, 1, 0), W(8, -1, 0);\n\t\tprivate final int bit;\n\t\tprivate final int dx;\n\t\tprivate final int dy;\n\t\tprivate DIR opposite;\n\n\t\t\/\/ use the static initializer to resolve forward references\n\t\tstatic {\n\t\t\tN.opposite = S;\n\t\t\tS.opposite = N;\n\t\t\tE.opposite = W;\n\t\t\tW.opposite = E;\n\t\t}\n\n\t\tprivate DIR(int bit, int dx, int dy) {\n\t\t\tthis.bit = bit;\n\t\t\tthis.dx = dx;\n\t\t\tthis.dy = dy;\n\t\t}\n\t};\n\n\tpublic static void main(String[] args) {\n\t\tint x = args.length >= 1 ? (Integer.parseInt(args[0])) : 8;\n\t\tint y = args.length == 2 ? (Integer.parseInt(args[1])) : 8;\n\t\tMazeGenerator maze = new MazeGenerator(x, y);\n\t\tmaze.display();\n\t}\n\n}\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":362} {"lang_cluster":"Java","source_code":"import java.math.BigInteger ;\n\npublic class Pi {\n final BigInteger TWO = BigInteger.valueOf(2) ;\n final BigInteger THREE = BigInteger.valueOf(3) ;\n final BigInteger FOUR = BigInteger.valueOf(4) ;\n final BigInteger SEVEN = BigInteger.valueOf(7) ;\n\n BigInteger q = BigInteger.ONE ;\n BigInteger r = BigInteger.ZERO ;\n BigInteger t = BigInteger.ONE ;\n BigInteger k = BigInteger.ONE ;\n BigInteger n = BigInteger.valueOf(3) ;\n BigInteger l = BigInteger.valueOf(3) ;\n\n public void calcPiDigits(){\n BigInteger nn, nr ;\n boolean first = true ;\n while(true){\n if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){\n System.out.print(n) ;\n if(first){System.out.print(\".\") ; first = false ;}\n nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ;\n n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ;\n q = q.multiply(BigInteger.TEN) ;\n r = nr ;\n System.out.flush() ;\n }else{\n nr = TWO.multiply(q).add(r).multiply(l) ;\n nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ;\n q = q.multiply(k) ;\n t = t.multiply(l) ;\n l = l.add(TWO) ;\n k = k.add(BigInteger.ONE) ;\n n = nn ;\n r = nr ;\n }\n }\n }\n\n public static void main(String[] args) {\n Pi p = new Pi() ;\n p.calcPiDigits() ;\n }\n}\n\n\n3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480 ...\n","human_summarization":"continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the program is manually terminated by the user.","id":363} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class ListOrder{\n\tpublic static boolean ordered(double[] first, double[] second){\n\t\tif(first.length == 0) return true;\n\t\tif(second.length == 0) return false;\n\t\tif(first[0] == second[0])\n\t\t\treturn ordered(Arrays.copyOfRange(first, 1, first.length),\n\t\t\t\t\tArrays.copyOfRange(second, 1, second.length));\n\t\treturn first[0] < second[0];\n\t}\n\t\n\tpublic static > boolean ordered(List first, List second){\n\t\tint i = 0;\n\t\tfor(; i < first.size() && i < second.size();i++){\n\t\t\tint cmp = first.get(i).compareTo(second.get(i));\n\t\t\tif(cmp == 0) continue;\n\t\t\tif(cmp < 0) return true;\n\t\t\treturn false;\n\t\t}\n\t\treturn i == first.size();\n\t}\n\t\n\tpublic static boolean ordered2(double[] first, double[] second){\n\t\tint i = 0;\n\t\tfor(; i < first.length && i < second.length;i++){\n\t\t\tif(first[i] == second[i]) continue;\n\t\t\tif(first[i] < second[i]) return true;\n\t\t\treturn false;\n\t\t}\n\t\treturn i == first.length;\n\t}\n}\n\n","human_summarization":"\"Implement a function that compares two numerical lists or arrays lexicographically. The function returns true if the first list should be ordered before the second, and false otherwise. If a list runs out of elements, it's considered to be ordered before the other. The function 'ordered' is a translation from Common Lisp, while the other two methods are adapted from Tcl.\"","id":364} {"lang_cluster":"Java","source_code":"\nimport java.math.BigInteger;\n\npublic static BigInteger ack(BigInteger m, BigInteger n) {\n return m.equals(BigInteger.ZERO)\n ? n.add(BigInteger.ONE)\n : ack(m.subtract(BigInteger.ONE),\n n.equals(BigInteger.ZERO) ? BigInteger.ONE : ack(m, n.subtract(BigInteger.ONE)));\n}\n\nWorks with: Java version 8+\n@FunctionalInterface\npublic interface FunctionalField> {\n public Object untypedField(FIELD field);\n\n @SuppressWarnings(\"unchecked\")\n public default VALUE field(FIELD field) {\n return (VALUE) untypedField(field);\n }\n}\n\nimport java.util.function.BiFunction;\nimport java.util.function.Function;\nimport java.util.function.Predicate;\nimport java.util.function.UnaryOperator;\nimport java.util.stream.Stream;\n\npublic interface TailRecursive {\n public static Function new_(Function toIntermediary, UnaryOperator unaryOperator, Predicate predicate, Function toOutput) {\n return input ->\n $.new_(\n Stream.iterate(\n toIntermediary.apply(input),\n unaryOperator\n ),\n predicate,\n toOutput\n )\n ;\n }\n\n public static BiFunction new_(BiFunction toIntermediary, UnaryOperator unaryOperator, Predicate predicate, Function toOutput) {\n return (input1, input2) ->\n $.new_(\n Stream.iterate(\n toIntermediary.apply(input1, input2),\n unaryOperator\n ),\n predicate,\n toOutput\n )\n ;\n }\n\n public enum $ {\n $$;\n\n private static OUTPUT new_(Stream stream, Predicate predicate, Function function) {\n return stream\n .filter(predicate)\n .map(function)\n .findAny()\n .orElseThrow(RuntimeException::new)\n ;\n }\n }\n}\n\nimport java.math.BigInteger;\nimport java.util.Stack;\nimport java.util.function.BinaryOperator;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic interface Ackermann {\n public static Ackermann new_(BigInteger number1, BigInteger number2, Stack stack, boolean flag) {\n return $.new_(number1, number2, stack, flag);\n }\n public static void main(String... arguments) {\n $.main(arguments);\n }\n public BigInteger number1();\n public BigInteger number2();\n\n public Stack stack();\n\n public boolean flag();\n\n public enum $ {\n $$;\n\n private static final BigInteger ZERO = BigInteger.ZERO;\n private static final BigInteger ONE = BigInteger.ONE;\n private static final BigInteger TWO = BigInteger.valueOf(2);\n private static final BigInteger THREE = BigInteger.valueOf(3);\n private static final BigInteger FOUR = BigInteger.valueOf(4);\n\n private static Ackermann new_(BigInteger number1, BigInteger number2, Stack stack, boolean flag) {\n return (FunctionalAckermann) field -> {\n switch (field) {\n case number1: return number1;\n case number2: return number2;\n case stack: return stack;\n case flag: return flag;\n default: throw new UnsupportedOperationException(\n field instanceof Field\n ? \"Field checker has not been updated properly.\"\n : \"Field is not of the correct type.\"\n );\n }\n };\n }\n\n private static final BinaryOperator ACKERMANN = \n TailRecursive.new_(\n (BigInteger number1, BigInteger number2) ->\n new_(\n number1,\n number2,\n Stream.of(number1).collect(\n Collectors.toCollection(Stack::new)\n ),\n false\n )\n ,\n ackermann -> {\n BigInteger number1 = ackermann.number1();\n BigInteger number2 = ackermann.number2();\n Stack stack = ackermann.stack();\n if (!stack.empty() && !ackermann.flag()) {\n number1 = stack.pop();\n }\n switch (number1.intValue()) {\n case 0:\n return new_(\n number1,\n number2.add(ONE),\n stack,\n false\n );\n case 1:\n return new_(\n number1,\n number2.add(TWO),\n stack,\n false\n );\n case 2:\n return new_(\n number1,\n number2.multiply(TWO).add(THREE),\n stack,\n false\n );\n default:\n if (ZERO.equals(number2)) {\n return new_(\n number1.subtract(ONE),\n ONE,\n stack,\n true\n );\n } else {\n stack.push(number1.subtract(ONE));\n return new_(\n number1,\n number2.subtract(ONE),\n stack,\n true\n );\n }\n }\n },\n ackermann -> ackermann.stack().empty(),\n Ackermann::number2\n )::apply\n ;\n\n private static void main(String... arguments) {\n System.out.println(ACKERMANN.apply(FOUR, TWO));\n }\n\n private enum Field {\n number1,\n number2,\n stack,\n flag\n }\n\n @FunctionalInterface\n private interface FunctionalAckermann extends FunctionalField, Ackermann {\n @Override\n public default BigInteger number1() {\n return field(Field.number1);\n }\n\n @Override\n public default BigInteger number2() {\n return field(Field.number2);\n }\n\n @Override\n public default Stack stack() {\n return field(Field.stack);\n }\n\n @Override\n public default boolean flag() {\n return field(Field.flag);\n }\n }\n }\n}\n\n\n\/*\n * Source https:\/\/stackoverflow.com\/a\/51092690\/5520417\n *\/\n\npackage matematicas;\n\nimport java.math.BigInteger;\nimport java.util.HashMap;\nimport java.util.Stack;\n\n\/**\n * @author rodri\n *\n *\/\n\npublic class IterativeAckermannMemoryOptimization extends Thread {\n\n \/**\n * Max percentage of free memory that the program will use. Default is 10% since\n * the majority of the used devices are mobile and therefore it is more likely\n * that the user will have more opened applications at the same time than in a\n * desktop device\n *\/\n private static Double SYSTEM_MEMORY_LIMIT_PERCENTAGE = 0.1;\n\n \/**\n * Attribute of the type IterativeAckermann\n *\/\n private IterativeAckermann iterativeAckermann;\n\n \/**\n * @param iterativeAckermann\n *\/\n public IterativeAckermannMemoryOptimization(IterativeAckermann iterativeAckermann) {\n super();\n this.iterativeAckermann = iterativeAckermann;\n }\n\n \/**\n * @return\n *\/\n public IterativeAckermann getIterativeAckermann() {\n return iterativeAckermann;\n }\n\n \/**\n * @param iterativeAckermann\n *\/\n public void setIterativeAckermann(IterativeAckermann iterativeAckermann) {\n this.iterativeAckermann = iterativeAckermann;\n }\n\n public static Double getSystemMemoryLimitPercentage() {\n return SYSTEM_MEMORY_LIMIT_PERCENTAGE;\n }\n\n \/**\n * Principal method of the thread. Checks that the memory used doesn't exceed or\n * equal the limit, and informs the user when that happens.\n *\/\n @Override\n public void run() {\n String operating_system = System.getProperty(\"os.name\").toLowerCase();\n if ( operating_system.equals(\"windows\") || operating_system.equals(\"linux\") || operating_system.equals(\"macintosh\") ) {\n SYSTEM_MEMORY_LIMIT_PERCENTAGE = 0.25;\n }\n\n while ( iterativeAckermann.getConsumed_heap() >= SYSTEM_MEMORY_LIMIT_PERCENTAGE * Runtime.getRuntime().freeMemory() ) {\n try {\n wait();\n }\n catch ( InterruptedException e ) {\n \/\/ TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n if ( ! iterativeAckermann.isAlive() )\n iterativeAckermann.start();\n else\n notifyAll();\n\n }\n\n}\n\n\npublic class IterativeAckermann extends Thread {\n\n \/*\n * Adjust parameters conveniently\n *\/\n \/**\n * \n *\/\n private static final int HASH_SIZE_LIMIT = 636;\n\n \/**\n * \n *\/\n private BigInteger m;\n\n \/**\n * \n *\/\n private BigInteger n;\n\n \/**\n * \n *\/\n private Integer hash_size;\n\n \/**\n * \n *\/\n private Long consumed_heap;\n\n \/**\n * @param m\n * @param n\n * @param invalid\n * @param invalid2\n *\/\n public IterativeAckermann(BigInteger m, BigInteger n, Integer invalid, Long invalid2) {\n super();\n this.m = m;\n this.n = n;\n this.hash_size = invalid;\n this.consumed_heap = invalid2;\n }\n\n \/**\n * \n *\/\n public IterativeAckermann() {\n \/\/ TODO Auto-generated constructor stub\n super();\n m = null;\n n = null;\n hash_size = 0;\n consumed_heap = 0l;\n }\n\n \/**\n * @return\n *\/\n public static BigInteger getLimit() {\n return LIMIT;\n }\n\n \/**\n * @author rodri\n *\n * @param \n * @param \n *\/\n \/**\n * @author rodri\n *\n * @param \n * @param \n *\/\n static class Pair {\n\n \/**\n * \n *\/\n \/**\n * \n *\/\n T1 x;\n\n \/**\n * \n *\/\n \/**\n * \n *\/\n T2 y;\n\n \/**\n * @param x_\n * @param y_\n *\/\n \/**\n * @param x_\n * @param y_\n *\/\n Pair(T1 x_, T2 y_) {\n x = x_;\n y = y_;\n }\n\n \/**\n *\n *\/\n \/**\n *\n *\/\n @Override\n public int hashCode() {\n return x.hashCode() ^ y.hashCode();\n }\n\n \/**\n *\n *\/\n \/**\n *\n *\/\n @Override\n public boolean equals(Object o_) {\n\n if ( o_ == null ) {\n return false;\n }\n if ( o_.getClass() != this.getClass() ) {\n return false;\n }\n Pair o = (Pair) o_;\n return x.equals(o.x) && y.equals(o.y);\n }\n }\n\n \/**\n * \n *\/\n private static final BigInteger LIMIT = new BigInteger(\"6\");\n\n \/**\n * @param m\n * @param n\n * @return\n *\/\n\n \/**\n *\n *\/\n @Override\n public void run() {\n while ( hash_size >= HASH_SIZE_LIMIT ) {\n try {\n this.wait();\n }\n catch ( InterruptedException e ) {\n \/\/ TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n for ( BigInteger i = BigInteger.ZERO; i.compareTo(LIMIT) == - 1; i = i.add(BigInteger.ONE) ) {\n for ( BigInteger j = BigInteger.ZERO; j.compareTo(LIMIT) == - 1; j = j.add(BigInteger.ONE) ) {\n IterativeAckermann iterativeAckermann = new IterativeAckermann(i, j, null, null);\n System.out.printf(\"Ackmermann(%d, %d) = %d\\n\", i, j, iterativeAckermann.iterative_ackermann(i, j));\n\n }\n }\n }\n\n \/**\n * @return\n *\/\n public BigInteger getM() {\n return m;\n }\n\n \/**\n * @param m\n *\/\n public void setM(BigInteger m) {\n this.m = m;\n }\n\n \/**\n * @return\n *\/\n public BigInteger getN() {\n return n;\n }\n\n \/**\n * @param n\n *\/\n public void setN(BigInteger n) {\n this.n = n;\n }\n\n \/**\n * @return\n *\/\n public Integer getHash_size() {\n return hash_size;\n }\n\n \/**\n * @param hash_size\n *\/\n public void setHash_size(Integer hash_size) {\n this.hash_size = hash_size;\n }\n\n \/**\n * @return\n *\/\n public Long getConsumed_heap() {\n return consumed_heap;\n }\n\n \/**\n * @param consumed_heap\n *\/\n public void setConsumed_heap(Long consumed_heap) {\n this.consumed_heap = consumed_heap;\n }\n\n \/**\n * @param m\n * @param n\n * @return\n *\/\n public BigInteger iterative_ackermann(BigInteger m, BigInteger n) {\n if ( m.compareTo(BigInteger.ZERO) != - 1 && m.compareTo(BigInteger.ZERO) != - 1 )\n try {\n HashMap, BigInteger> solved_set = new HashMap, BigInteger>(900000);\n Stack> to_solve = new Stack>();\n to_solve.push(new Pair(m, n));\n\n while ( ! to_solve.isEmpty() ) {\n Pair head = to_solve.peek();\n if ( head.x.equals(BigInteger.ZERO) ) {\n solved_set.put(head, head.y.add(BigInteger.ONE));\n to_solve.pop();\n }\n else if ( head.y.equals(BigInteger.ZERO) ) {\n Pair next = new Pair(head.x.subtract(BigInteger.ONE), BigInteger.ONE);\n BigInteger result = solved_set.get(next);\n if ( result == null ) {\n to_solve.push(next);\n }\n else {\n solved_set.put(head, result);\n to_solve.pop();\n }\n }\n else {\n Pair next0 = new Pair(head.x, head.y.subtract(BigInteger.ONE));\n BigInteger result0 = solved_set.get(next0);\n if ( result0 == null ) {\n to_solve.push(next0);\n }\n else {\n Pair next = new Pair(head.x.subtract(BigInteger.ONE), result0);\n BigInteger result = solved_set.get(next);\n if ( result == null ) {\n to_solve.push(next);\n }\n else {\n solved_set.put(head, result);\n to_solve.pop();\n }\n }\n }\n }\n this.hash_size = solved_set.size();\n System.out.println(\"Hash Size: \" + hash_size);\n consumed_heap = (Runtime.getRuntime().totalMemory() \/ (1024 * 1024));\n System.out.println(\"Consumed Heap: \" + consumed_heap + \"m\");\n setHash_size(hash_size);\n setConsumed_heap(consumed_heap);\n return solved_set.get(new Pair(m, n));\n\n }\n catch ( OutOfMemoryError e ) {\n \/\/ TODO: handle exception\n e.printStackTrace();\n }\n throw new IllegalArgumentException(\"The arguments must be non-negative integers.\");\n }\n\n \/**\n * @param args\n *\/\n \/**\n * @param args\n *\/\n public static void main(String[] args) {\n IterativeAckermannMemoryOptimization iterative_ackermann_memory_optimization = new IterativeAckermannMemoryOptimization(\n new IterativeAckermann());\n iterative_ackermann_memory_optimization.start();\n }\n}\n\n","human_summarization":"Implement the Ackermann function, a non-primitive recursive function that takes two non-negative arguments and returns a rapidly growing value. The function should ideally support arbitrary precision due to the fast growth of the function's output.","id":365} {"lang_cluster":"Java","source_code":"\n\npublic class GammaFunction {\n\n\tpublic double st_gamma(double x){\n\t\treturn Math.sqrt(2*Math.PI\/x)*Math.pow((x\/Math.E), x);\n\t}\n\t\n\tpublic double la_gamma(double x){\n\t\tdouble[] p = {0.99999999999980993, 676.5203681218851, -1259.1392167224028,\n\t\t\t \t 771.32342877765313, -176.61502916214059, 12.507343278686905,\n\t\t\t \t -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};\n\t\tint g = 7;\n\t\tif(x < 0.5) return Math.PI \/ (Math.sin(Math.PI * x)*la_gamma(1-x));\n\n\t\tx -= 1;\n\t\tdouble a = p[0];\n\t\tdouble t = x+g+0.5;\n\t\tfor(int i = 1; i < p.length; i++){\n\t\t\ta += p[i]\/(x+i);\n\t\t}\n\t\t\n\t\treturn Math.sqrt(2*Math.PI)*Math.pow(t, x+0.5)*Math.exp(-t)*a;\n\t}\n\t\n\tpublic static void main(String[] args) {\n\t\tGammaFunction test = new GammaFunction();\n\t\tSystem.out.println(\"Gamma \\t\\tStirling \\t\\tLanczos\");\n\t\tfor(double i = 1; i <= 20; i += 1){\n\t\t\tSystem.out.println(\"\" + i\/10.0 + \"\\t\\t\" + test.st_gamma(i\/10.0) + \"\\t\" + test.la_gamma(i\/10.0));\n\t\t}\n\t}\n}\n\n\n","human_summarization":"implement the Gamma function using numerical integration, Lanczos approximation, and Stirling's approximation. The results are then compared with the built-in\/library function for the Gamma function.","id":366} {"lang_cluster":"Java","source_code":"\npublic class NQueens {\n\n private static int[] b = new int[8];\n private static int s = 0;\n\n static boolean unsafe(int y) {\n int x = b[y];\n for (int i = 1; i <= y; i++) {\n int t = b[y - i];\n if (t == x ||\n t == x - i ||\n t == x + i) {\n return true;\n }\n }\n\n return false;\n }\n\n public static void putboard() {\n System.out.println(\"\\n\\nSolution \" + (++s));\n for (int y = 0; y < 8; y++) {\n for (int x = 0; x < 8; x++) {\n System.out.print((b[y] == x) ? \"|Q\" : \"|_\");\n }\n System.out.println(\"|\");\n }\n }\n\n public static void main(String[] args) {\n int y = 0;\n b[0] = -1;\n while (y >= 0) {\n do {\n b[y]++;\n } while ((b[y] < 8) && unsafe(y));\n if (b[y] < 8) {\n if (y < 7) {\n b[++y] = -1;\n } else {\n putboard();\n }\n } else {\n y--;\n }\n }\n }\n}\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":367} {"lang_cluster":"Java","source_code":"\n\nint[] concat(int[] arrayA, int[] arrayB) {\n int[] array = new int[arrayA.length + arrayB.length];\n System.arraycopy(arrayA, 0, array, 0, arrayA.length);\n System.arraycopy(arrayB, 0, array, arrayA.length, arrayB.length);\n return array;\n}\n\n\nint[] concat(int[] arrayA, int[] arrayB) {\n int[] array = new int[arrayA.length + arrayB.length];\n for (int index = 0; index < arrayA.length; index++)\n array[index] = arrayA[index];\n for (int index = 0; index < arrayB.length; index++)\n array[index + arrayA.length] = arrayB[index];\n return array;\n}\n\n\nint[] concat(int[] arrayA, int[] arrayB) {\n List list = new ArrayList<>();\n for (int value : arrayA) list.add(value);\n for (int value : arrayB) list.add(value);\n int[] array = new int[list.size()];\n for (int index = 0; index < list.size(); index++)\n array[index] = list.get(index);\n return array;\n}\n\n","human_summarization":"demonstrate how to concatenate two arrays in Java. Due to the immutability of arrays in Java, a new array is created and the contents of the two arrays are copied into it using the System.arraycopy method. Alternatively, for-loops or Lists (mutable arrays) can be used. The Java Collections Framework's List class, although primarily designed for Objects, can still be used for primitives despite the somewhat complex conversion process. Performance-wise, both arrays and Lists are equally efficient.","id":368} {"lang_cluster":"Java","source_code":"\n\npackage hu.pj.alg.test;\n\nimport hu.pj.alg.ZeroOneKnapsack;\nimport hu.pj.obj.Item;\nimport java.util.*;\nimport java.text.*;\n\npublic class ZeroOneKnapsackForTourists {\n\n public ZeroOneKnapsackForTourists() {\n ZeroOneKnapsack zok = new ZeroOneKnapsack(400); \/\/ 400 dkg = 400 dag = 4 kg\n\n \/\/ making the list of items that you want to bring\n zok.add(\"map\", 9, 150);\n zok.add(\"compass\", 13, 35);\n zok.add(\"water\", 153, 200);\n zok.add(\"sandwich\", 50, 160);\n zok.add(\"glucose\", 15, 60);\n zok.add(\"tin\", 68, 45);\n zok.add(\"banana\", 27, 60);\n zok.add(\"apple\", 39, 40);\n zok.add(\"cheese\", 23, 30);\n zok.add(\"beer\", 52, 10);\n zok.add(\"suntan cream\", 11, 70);\n zok.add(\"camera\", 32, 30);\n zok.add(\"t-shirt\", 24, 15);\n zok.add(\"trousers\", 48, 10);\n zok.add(\"umbrella\", 73, 40);\n zok.add(\"waterproof trousers\", 42, 70);\n zok.add(\"waterproof overclothes\", 43, 75);\n zok.add(\"note-case\", 22, 80);\n zok.add(\"sunglasses\", 7, 20);\n zok.add(\"towel\", 18, 12);\n zok.add(\"socks\", 4, 50);\n zok.add(\"book\", 30, 10);\n\n \/\/ calculate the solution:\n List itemList = zok.calcSolution();\n\n \/\/ write out the solution in the standard output\n if (zok.isCalculated()) {\n NumberFormat nf = NumberFormat.getInstance();\n\n System.out.println(\n \"Maximal weight = \" +\n nf.format(zok.getMaxWeight() \/ 100.0) + \" kg\"\n );\n System.out.println(\n \"Total weight of solution = \" +\n nf.format(zok.getSolutionWeight() \/ 100.0) + \" kg\"\n );\n System.out.println(\n \"Total value = \" +\n zok.getProfit()\n );\n System.out.println();\n System.out.println(\n \"You can carry the following materials \" +\n \"in the knapsack:\"\n );\n for (Item item : itemList) {\n if (item.getInKnapsack() == 1) {\n System.out.format(\n \"%1$-23s %2$-3s %3$-5s %4$-15s \\n\",\n item.getName(),\n item.getWeight(), \"dag \",\n \"(value = \" + item.getValue() + \")\"\n );\n }\n }\n } else {\n System.out.println(\n \"The problem is not solved. \" +\n \"Maybe you gave wrong data.\"\n );\n }\n\n }\n\n public static void main(String[] args) {\n new ZeroOneKnapsackForTourists();\n }\n\n} \/\/ class\n\npackage hu.pj.alg;\n\nimport hu.pj.obj.Item;\nimport java.util.*;\n\npublic class ZeroOneKnapsack {\n\n protected List itemList = new ArrayList();\n protected int maxWeight = 0;\n protected int solutionWeight = 0;\n protected int profit = 0;\n protected boolean calculated = false;\n\n public ZeroOneKnapsack() {}\n\n public ZeroOneKnapsack(int _maxWeight) {\n setMaxWeight(_maxWeight);\n }\n\n public ZeroOneKnapsack(List _itemList) {\n setItemList(_itemList);\n }\n\n public ZeroOneKnapsack(List _itemList, int _maxWeight) {\n setItemList(_itemList);\n setMaxWeight(_maxWeight);\n }\n\n \/\/ calculte the solution of 0-1 knapsack problem with dynamic method:\n public List calcSolution() {\n int n = itemList.size();\n\n setInitialStateForCalculation();\n if (n > 0 && maxWeight > 0) {\n List< List > c = new ArrayList< List >();\n List curr = new ArrayList();\n\n c.add(curr);\n for (int j = 0; j <= maxWeight; j++)\n curr.add(0);\n for (int i = 1; i <= n; i++) {\n List prev = curr;\n c.add(curr = new ArrayList());\n for (int j = 0; j <= maxWeight; j++) {\n if (j > 0) {\n int wH = itemList.get(i-1).getWeight();\n curr.add(\n (wH > j)\n ?\n prev.get(j)\n :\n Math.max(\n prev.get(j),\n itemList.get(i-1).getValue() + prev.get(j-wH)\n )\n );\n } else {\n curr.add(0);\n }\n } \/\/ for (j...)\n } \/\/ for (i...)\n profit = curr.get(maxWeight);\n\n for (int i = n, j = maxWeight; i > 0 && j >= 0; i--) {\n int tempI = c.get(i).get(j);\n int tempI_1 = c.get(i-1).get(j);\n if (\n (i == 0 && tempI > 0)\n ||\n (i > 0 && tempI != tempI_1)\n )\n {\n Item iH = itemList.get(i-1);\n int wH = iH.getWeight();\n iH.setInKnapsack(1);\n j -= wH;\n solutionWeight += wH;\n }\n } \/\/ for()\n calculated = true;\n } \/\/ if()\n return itemList;\n }\n\n \/\/ add an item to the item list\n public void add(String name, int weight, int value) {\n if (name.equals(\"\"))\n name = \"\" + (itemList.size() + 1);\n itemList.add(new Item(name, weight, value));\n setInitialStateForCalculation();\n }\n\n \/\/ add an item to the item list\n public void add(int weight, int value) {\n add(\"\", weight, value); \/\/ the name will be \"itemList.size() + 1\"!\n }\n\n \/\/ remove an item from the item list\n public void remove(String name) {\n for (Iterator it = itemList.iterator(); it.hasNext(); ) {\n if (name.equals(it.next().getName())) {\n it.remove();\n }\n }\n setInitialStateForCalculation();\n }\n\n \/\/ remove all items from the item list\n public void removeAllItems() {\n itemList.clear();\n setInitialStateForCalculation();\n }\n\n public int getProfit() {\n if (!calculated)\n calcSolution();\n return profit;\n }\n\n public int getSolutionWeight() {return solutionWeight;}\n public boolean isCalculated() {return calculated;}\n public int getMaxWeight() {return maxWeight;}\n\n public void setMaxWeight(int _maxWeight) {\n maxWeight = Math.max(_maxWeight, 0);\n }\n\n public void setItemList(List _itemList) {\n if (_itemList != null) {\n itemList = _itemList;\n for (Item item : _itemList) {\n item.checkMembers();\n }\n }\n }\n\n \/\/ set the member with name \"inKnapsack\" by all items:\n private void setInKnapsackByAll(int inKnapsack) {\n for (Item item : itemList)\n if (inKnapsack > 0)\n item.setInKnapsack(1);\n else\n item.setInKnapsack(0);\n }\n\n \/\/ set the data members of class in the state of starting the calculation:\n protected void setInitialStateForCalculation() {\n setInKnapsackByAll(0);\n calculated = false;\n profit = 0;\n solutionWeight = 0;\n }\n\n} \/\/ class\n\npackage hu.pj.obj;\n\npublic class Item {\n\n protected String name = \"\";\n protected int weight = 0;\n protected int value = 0;\n protected int bounding = 1; \/\/ the maximal limit of item's pieces\n protected int inKnapsack = 0; \/\/ the pieces of item in solution\n\n public Item() {}\n\n public Item(Item item) {\n setName(item.name);\n setWeight(item.weight);\n setValue(item.value);\n setBounding(item.bounding);\n }\n\n public Item(int _weight, int _value) {\n setWeight(_weight);\n setValue(_value);\n }\n\n public Item(int _weight, int _value, int _bounding) {\n setWeight(_weight);\n setValue(_value);\n setBounding(_bounding);\n }\n\n public Item(String _name, int _weight, int _value) {\n setName(_name);\n setWeight(_weight);\n setValue(_value);\n }\n\n public Item(String _name, int _weight, int _value, int _bounding) {\n setName(_name);\n setWeight(_weight);\n setValue(_value);\n setBounding(_bounding);\n }\n\n public void setName(String _name) {name = _name;}\n public void setWeight(int _weight) {weight = Math.max(_weight, 0);}\n public void setValue(int _value) {value = Math.max(_value, 0);}\n\n public void setInKnapsack(int _inKnapsack) {\n inKnapsack = Math.min(getBounding(), Math.max(_inKnapsack, 0));\n }\n\n public void setBounding(int _bounding) {\n bounding = Math.max(_bounding, 0);\n if (bounding == 0)\n inKnapsack = 0;\n }\n\n public void checkMembers() {\n setWeight(weight);\n setValue(value);\n setBounding(bounding);\n setInKnapsack(inKnapsack);\n }\n\n public String getName() {return name;}\n public int getWeight() {return weight;}\n public int getValue() {return value;}\n public int getInKnapsack() {return inKnapsack;}\n public int getBounding() {return bounding;}\n\n} \/\/ class\n\n\n","human_summarization":"The code implements a solution for the 0-1 Knapsack problem. It helps a tourist to determine the combination of items he can carry in his knapsack, with a maximum weight limit of 4kg, in a way that the total value of the items is maximized. The items cannot be divided and only one unit of each item is available. The items, their weights, and values are provided in a list.","id":369} {"lang_cluster":"Java","source_code":"\n\nimport java.util.*;\n\npublic class Stable {\n static List guys = Arrays.asList(\n new String[]{\n \"abe\", \"bob\", \"col\", \"dan\", \"ed\", \"fred\", \"gav\", \"hal\", \"ian\", \"jon\"});\n static List girls = Arrays.asList(\n new String[]{\n \"abi\", \"bea\", \"cath\", \"dee\", \"eve\", \"fay\", \"gay\", \"hope\", \"ivy\", \"jan\"});\n static Map> guyPrefers =\n new HashMap>(){{\n put(\"abe\",\n Arrays.asList(\"abi\", \"eve\", \"cath\", \"ivy\", \"jan\", \"dee\", \"fay\",\n \"bea\", \"hope\", \"gay\"));\n put(\"bob\",\n Arrays.asList(\"cath\", \"hope\", \"abi\", \"dee\", \"eve\", \"fay\", \"bea\",\n \"jan\", \"ivy\", \"gay\"));\n put(\"col\",\n Arrays.asList(\"hope\", \"eve\", \"abi\", \"dee\", \"bea\", \"fay\", \"ivy\",\n \"gay\", \"cath\", \"jan\"));\n put(\"dan\",\n Arrays.asList(\"ivy\", \"fay\", \"dee\", \"gay\", \"hope\", \"eve\", \"jan\",\n \"bea\", \"cath\", \"abi\"));\n put(\"ed\",\n Arrays.asList(\"jan\", \"dee\", \"bea\", \"cath\", \"fay\", \"eve\", \"abi\",\n \"ivy\", \"hope\", \"gay\"));\n put(\"fred\",\n Arrays.asList(\"bea\", \"abi\", \"dee\", \"gay\", \"eve\", \"ivy\", \"cath\",\n \"jan\", \"hope\", \"fay\"));\n put(\"gav\",\n Arrays.asList(\"gay\", \"eve\", \"ivy\", \"bea\", \"cath\", \"abi\", \"dee\",\n \"hope\", \"jan\", \"fay\"));\n put(\"hal\",\n Arrays.asList(\"abi\", \"eve\", \"hope\", \"fay\", \"ivy\", \"cath\", \"jan\",\n \"bea\", \"gay\", \"dee\"));\n put(\"ian\",\n Arrays.asList(\"hope\", \"cath\", \"dee\", \"gay\", \"bea\", \"abi\", \"fay\",\n \"ivy\", \"jan\", \"eve\"));\n put(\"jon\",\n Arrays.asList(\"abi\", \"fay\", \"jan\", \"gay\", \"eve\", \"bea\", \"dee\",\n \"cath\", \"ivy\", \"hope\"));\n }};\n static Map> girlPrefers =\n new HashMap>(){{\n put(\"abi\",\n Arrays.asList(\"bob\", \"fred\", \"jon\", \"gav\", \"ian\", \"abe\", \"dan\",\n \"ed\", \"col\", \"hal\"));\n put(\"bea\",\n Arrays.asList(\"bob\", \"abe\", \"col\", \"fred\", \"gav\", \"dan\", \"ian\",\n \"ed\", \"jon\", \"hal\"));\n put(\"cath\",\n Arrays.asList(\"fred\", \"bob\", \"ed\", \"gav\", \"hal\", \"col\", \"ian\",\n \"abe\", \"dan\", \"jon\"));\n put(\"dee\",\n Arrays.asList(\"fred\", \"jon\", \"col\", \"abe\", \"ian\", \"hal\", \"gav\",\n \"dan\", \"bob\", \"ed\"));\n put(\"eve\",\n Arrays.asList(\"jon\", \"hal\", \"fred\", \"dan\", \"abe\", \"gav\", \"col\",\n \"ed\", \"ian\", \"bob\"));\n put(\"fay\",\n Arrays.asList(\"bob\", \"abe\", \"ed\", \"ian\", \"jon\", \"dan\", \"fred\",\n \"gav\", \"col\", \"hal\"));\n put(\"gay\",\n Arrays.asList(\"jon\", \"gav\", \"hal\", \"fred\", \"bob\", \"abe\", \"col\",\n \"ed\", \"dan\", \"ian\"));\n put(\"hope\",\n Arrays.asList(\"gav\", \"jon\", \"bob\", \"abe\", \"ian\", \"dan\", \"hal\",\n \"ed\", \"col\", \"fred\"));\n put(\"ivy\",\n Arrays.asList(\"ian\", \"col\", \"hal\", \"gav\", \"fred\", \"bob\", \"abe\",\n \"ed\", \"jon\", \"dan\"));\n put(\"jan\",\n Arrays.asList(\"ed\", \"hal\", \"gav\", \"abe\", \"bob\", \"jon\", \"col\",\n \"ian\", \"fred\", \"dan\"));\n }};\n public static void main(String[] args){\n Map matches = match(guys, guyPrefers, girlPrefers);\n for(Map.Entry couple:matches.entrySet()){\n System.out.println(\n couple.getKey() + \" is engaged to \" + couple.getValue());\n }\n if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){\n System.out.println(\"Marriages are stable\");\n }else{\n System.out.println(\"Marriages are unstable\");\n }\n String tmp = matches.get(girls.get(0));\n matches.put(girls.get(0), matches.get(girls.get(1)));\n matches.put(girls.get(1), tmp);\n System.out.println(\n girls.get(0) +\" and \" + girls.get(1) + \" have switched partners\");\n if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){\n System.out.println(\"Marriages are stable\");\n }else{\n System.out.println(\"Marriages are unstable\");\n }\n }\n\n private static Map match(List guys,\n Map> guyPrefers,\n Map> girlPrefers){\n Map engagedTo = new TreeMap();\n List freeGuys = new LinkedList();\n freeGuys.addAll(guys);\n while(!freeGuys.isEmpty()){\n String thisGuy = freeGuys.remove(0); \/\/get a load of THIS guy\n List thisGuyPrefers = guyPrefers.get(thisGuy);\n for(String girl:thisGuyPrefers){\n if(engagedTo.get(girl) == null){\/\/girl is free\n engagedTo.put(girl, thisGuy); \/\/awww\n break;\n }else{\n String otherGuy = engagedTo.get(girl);\n List thisGirlPrefers = girlPrefers.get(girl);\n if(thisGirlPrefers.indexOf(thisGuy) <\n thisGirlPrefers.indexOf(otherGuy)){\n \/\/this girl prefers this guy to the guy she's engaged to\n engagedTo.put(girl, thisGuy);\n freeGuys.add(otherGuy);\n break;\n }\/\/else no change...keep looking for this guy\n }\n }\n }\n return engagedTo;\n }\n\n private static boolean checkMatches(List guys, List girls,\n Map matches, Map> guyPrefers,\n Map> girlPrefers) {\n if(!matches.keySet().containsAll(girls)){\n return false;\n }\n\n if(!matches.values().containsAll(guys)){\n return false;\n }\n\n Map invertedMatches = new TreeMap();\n for(Map.Entry couple:matches.entrySet()){\n invertedMatches.put(couple.getValue(), couple.getKey());\n }\n\n for(Map.Entry couple:matches.entrySet()){\n List shePrefers = girlPrefers.get(couple.getKey());\n List sheLikesBetter = new LinkedList();\n sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(couple.getValue())));\n List hePrefers = guyPrefers.get(couple.getValue());\n List heLikesBetter = new LinkedList();\n heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(couple.getKey())));\n\n for(String guy : sheLikesBetter){\n String guysFinace = invertedMatches.get(guy);\n List thisGuyPrefers = guyPrefers.get(guy);\n if(thisGuyPrefers.indexOf(guysFinace) >\n thisGuyPrefers.indexOf(couple.getKey())){\n System.out.printf(\"%s likes %s better than %s and %s\"\n + \" likes %s better than their current partner\\n\",\n couple.getKey(), guy, couple.getValue(),\n guy, couple.getKey());\n return false;\n }\n }\n\n for(String girl : heLikesBetter){\n String girlsFinace = matches.get(girl);\n List thisGirlPrefers = girlPrefers.get(girl);\n if(thisGirlPrefers.indexOf(girlsFinace) >\n thisGirlPrefers.indexOf(couple.getValue())){\n System.out.printf(\"%s likes %s better than %s and %s\"\n + \" likes %s better than their current partner\\n\",\n couple.getValue(), girl, couple.getKey(),\n girl, couple.getValue());\n return false;\n }\n }\n }\n return true;\n }\n}\n\n\n","human_summarization":"The code implements the Gale\/Shapley algorithm to solve the Stable Marriage Problem. It takes as input a list of ten males and ten females along with their ranked preferences for each other. The code then finds a stable set of engagements where no individual prefers someone else over their current partner. It also includes a functionality to perturb this stable set to form an unstable set, and then checks this new set for stability.","id":370} {"lang_cluster":"Java","source_code":"\n\npublic class ShortCirc {\n public static void main(String[] args){\n System.out.println(\"F and F = \" + (a(false) && b(false)) + \"\\n\");\n System.out.println(\"F or F = \" + (a(false) || b(false)) + \"\\n\");\n\n System.out.println(\"F and T = \" + (a(false) && b(true)) + \"\\n\");\n System.out.println(\"F or T = \" + (a(false) || b(true)) + \"\\n\");\n\n System.out.println(\"T and F = \" + (a(true) && b(false)) + \"\\n\");\n System.out.println(\"T or F = \" + (a(true) || b(false)) + \"\\n\");\n\n System.out.println(\"T and T = \" + (a(true) && b(true)) + \"\\n\");\n System.out.println(\"T or T = \" + (a(true) || b(true)) + \"\\n\");\n }\n\n public static boolean a(boolean a){\n System.out.println(\"a\");\n return a;\n }\n\n public static boolean b(boolean b){\n System.out.println(\"b\");\n return b;\n }\n}\n\n\n","human_summarization":"The code defines two functions, a and b, which return the same boolean value they receive as input and print their names when called. It then calculates and assigns the values of two boolean expressions to variables x and y. The expressions are designed to utilize short-circuit evaluation, ensuring that function b is only called when necessary. If the programming language does not support short-circuit evaluation, this is achieved using nested if statements. In Java, the boolean operators && and || are used for short-circuit evaluation.","id":371} {"lang_cluster":"Java","source_code":"\nWorks with: java version 7\nimport java.util.*;\n\npublic class MorseCode {\n\n final static String[][] code = {\n {\"A\", \".- \"}, {\"B\", \"-... \"}, {\"C\", \"-.-. \"}, {\"D\", \"-.. \"},\n {\"E\", \". \"}, {\"F\", \"..-. \"}, {\"G\", \"--. \"}, {\"H\", \".... \"},\n {\"I\", \".. \"}, {\"J\", \".--- \"}, {\"K\", \"-.- \"}, {\"L\", \".-.. \"},\n {\"M\", \"-- \"}, {\"N\", \"-. \"}, {\"O\", \"--- \"}, {\"P\", \".--. \"},\n {\"Q\", \"--.- \"}, {\"R\", \".-. \"}, {\"S\", \"... \"}, {\"T\", \"- \"},\n {\"U\", \"..- \"}, {\"V\", \"...- \"}, {\"W\", \".- - \"}, {\"X\", \"-..- \"},\n {\"Y\", \"-.-- \"}, {\"Z\", \"--.. \"}, {\"0\", \"----- \"}, {\"1\", \".---- \"},\n {\"2\", \"..--- \"}, {\"3\", \"...-- \"}, {\"4\", \"....- \"}, {\"5\", \"..... \"},\n {\"6\", \"-.... \"}, {\"7\", \"--... \"}, {\"8\", \"---.. \"}, {\"9\", \"----. \"},\n {\"'\", \".----. \"}, {\":\", \"---... \"}, {\",\", \"--..-- \"}, {\"-\", \"-....- \"},\n {\"(\", \"-.--.- \"}, {\".\", \".-.-.- \"}, {\"?\", \"..--.. \"}, {\";\", \"-.-.-. \"},\n {\"\/\", \"-..-. \"}, {\"-\", \"..--.- \"}, {\")\", \"---.. \"}, {\"=\", \"-...- \"},\n {\"@\", \".--.-. \"}, {\"\\\"\", \".-..-.\"}, {\"+\", \".-.-. \"}, {\" \", \"\/\"}}; \/\/ cheat a little\n\n final static Map map = new HashMap<>();\n\n static {\n for (String[] pair : code)\n map.put(pair[0].charAt(0), pair[1].trim());\n }\n\n public static void main(String[] args) {\n printMorse(\"sos\");\n printMorse(\" Hello World!\");\n printMorse(\"Rosetta Code\");\n }\n\n static void printMorse(String input) {\n System.out.printf(\"%s %n\", input);\n\n input = input.trim().replaceAll(\"[ ]+\", \" \").toUpperCase();\n for (char c : input.toCharArray()) {\n String s = map.get(c);\n if (s != null)\n System.out.printf(\"%s \", s);\n }\n System.out.println(\"\\n\");\n }\n}\n\nsos \n... --- ... \n\n Hello World! \n.... . .-.. .-.. --- \/ .- - --- .-. .-.. -.. \n\nRosetta Code \n.-. --- ... . - - .- \/ -.-. --- -.. . \n","human_summarization":" convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":372} {"lang_cluster":"Java","source_code":"Works with: Java version 1.6+\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class ABC {\n\n public static void main(String[] args) {\n List blocks = Arrays.asList(\n \"BO\", \"XK\", \"DQ\", \"CP\", \"NA\",\n \"GT\", \"RE\", \"TG\", \"QD\", \"FS\",\n \"JW\", \"HU\", \"VI\", \"AN\", \"OB\",\n \"ER\", \"FS\", \"LY\", \"PC\", \"ZM\");\n\n for (String word : Arrays.asList(\"\", \"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"CONFUSE\")) {\n System.out.printf(\"%s: %s%n\", word.isEmpty() ? \"\\\"\\\"\" : word, canMakeWord(word, blocks));\n }\n }\n\n public static boolean canMakeWord(String word, List blocks) {\n if (word.isEmpty())\n return true;\n\n char c = word.charAt(0);\n for (int i = 0; i < blocks.size(); i++) {\n String b = blocks.get(i);\n if (b.charAt(0) != c && b.charAt(1) != c)\n continue;\n Collections.swap(blocks, 0, i);\n if (canMakeWord(word.substring(1), blocks.subList(1, blocks.size())))\n return true;\n Collections.swap(blocks, 0, i);\n }\n\n return false;\n }\n}\n\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":373} {"lang_cluster":"Java","source_code":"\nimport java.nio.charset.StandardCharsets;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class Digester {\n\n public static void main(String[] args) {\n System.out.println(hexDigest(\"Rosetta code\", \"MD5\"));\n }\n\n static String hexDigest(String str, String digestName) {\n try {\n MessageDigest md = MessageDigest.getInstance(digestName);\n byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));\n char[] hex = new char[digest.length * 2];\n for (int i = 0; i < digest.length; i++) {\n hex[2 * i] = \"0123456789abcdef\".charAt((digest[i] & 0xf0) >> 4);\n hex[2 * i + 1] = \"0123456789abcdef\".charAt(digest[i] & 0x0f);\n }\n return new String(hex);\n } catch (NoSuchAlgorithmException e) {\n throw new IllegalStateException(e);\n }\n }\n}\n\n\n","human_summarization":"The code implements the MD5 encoding algorithm on a given string. It also includes an optional validation process using test values from IETF RFC 1321. The code warns about the known weaknesses of MD5 and suggests stronger alternatives for production-grade cryptography. It also provides options for other digest algorithms and encoding options. If the solution is a library, it directs to an MD5\/Implementation for a scratch implementation.","id":374} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 8 or higher\npackage com.rosettacode;\n\nimport java.util.Comparator;\nimport java.util.stream.Stream;\n\npublic class OIDListSorting {\n\n public static void main(String[] args) {\n\n final String dot = \"\\\\.\";\n\n final Comparator oids_comparator = (o1, o2) -> {\n final String[] o1Numbers = o1.split(dot), o2Numbers = o2.split(dot);\n for (int i = 0; ; i++) {\n if (i == o1Numbers.length && i == o2Numbers.length)\n return 0;\n if (i == o1Numbers.length)\n return -1;\n if (i == o2Numbers.length)\n return 1;\n final int nextO1Number = Integer.valueOf(o1Numbers[i]), nextO2Number = Integer.valueOf(o2Numbers[i]);\n final int result = Integer.compare(nextO1Number, nextO2Number);\n if (result != 0)\n return result;\n }\n };\n\n Stream.of(\"1.3.6.1.4.1.11.2.17.19.3.4.0.10\", \"1.3.6.1.4.1.11.2.17.5.2.0.79\", \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\",\n \"1.3.6.1.4.1.11150.3.4.0.1\", \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\", \"1.3.6.1.4.1.11150.3.4.0\")\n .sorted(oids_comparator)\n .forEach(System.out::println);\n }\n}\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":375} {"lang_cluster":"Java","source_code":"\nimport java.io.IOException;\nimport java.net.*;\npublic class SocketSend {\n public static void main(String args[]) throws IOException {\n sendData(\"localhost\", \"hello socket world\");\n }\n\n public static void sendData(String host, String msg) throws IOException {\n Socket sock = new Socket( host, 256 );\n sock.getOutputStream().write(msg.getBytes());\n sock.getOutputStream().flush();\n sock.close();\n }\n}\n\n\n","human_summarization":"The code opens a socket connection to localhost on port 256, sends the message \"hello socket world\", and then closes the socket. It may also encapsulate the Socket's OutputStream in a PrintStream or PrintWriter for easier handling of data or text.","id":376} {"lang_cluster":"Java","source_code":"\nimport java.util.Properties;\n\nimport javax.mail.MessagingException;\nimport javax.mail.Session;\nimport javax.mail.Transport;\nimport javax.mail.Message.RecipientType;\nimport javax.mail.internet.InternetAddress;\nimport javax.mail.internet.MimeMessage;\n\n\/**\n * Mail\n *\/\npublic class Mail\n{\n \/**\n * Session\n *\/\n protected Session session;\n\n \/**\n * Mail constructor.\n * \n * @param host Host\n *\/\n public Mail(String host)\n {\n Properties properties = new Properties();\n properties.put(\"mail.smtp.host\", host);\n session = Session.getDefaultInstance(properties);\n }\n\n \/**\n * Send email message.\n *\n * @param from From\n * @param tos Recipients\n * @param ccs CC Recipients\n * @param subject Subject\n * @param text Text\n * @throws MessagingException\n *\/\n public void send(String from, String tos[], String ccs[], String subject,\n String text)\n throws MessagingException\n {\n MimeMessage message = new MimeMessage(session);\n message.setFrom(new InternetAddress(from));\n for (String to : tos)\n message.addRecipient(RecipientType.TO, new InternetAddress(to));\n for (String cc : ccs)\n message.addRecipient(RecipientType.TO, new InternetAddress(cc));\n message.setSubject(subject);\n message.setText(text);\n Transport.send(message);\n }\n}\n\n","human_summarization":"Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.","id":377} {"lang_cluster":"Java","source_code":"\nvoid printCount() {\n for (int value = 0; value <= 20; value++) {\n \/* the 'o' specifier will print the octal integer *\/\n System.out.printf(\"%o%n\", value);\n }\n}\n\n0\n1\n2\n3\n4\n5\n6\n7\n10\n11\n12\n13\n14\n15\n16\n17\n20\n21\n22\n23\n24\n\n\npublic class Count{\n public static void main(String[] args){\n for(int i = 0;i >= 0;i++){\n System.out.println(Integer.toOctalString(i)); \/\/optionally use \"Integer.toString(i, 8)\"\n }\n }\n}\n\n","human_summarization":"generate a sequential count in octal, starting from zero with an increment of one for each consecutive number. Each number is printed on a separate line. The program continues until it is terminated or the maximum value of the numeric type in use is reached.","id":378} {"lang_cluster":"Java","source_code":"\nWorks with: Java version 1.5+\n\nclass Pair {\n T first;\n T second;\n}\npublic static void swap(Pair p) {\n T temp = p.first;\n p.first = p.second;\n p.second = temp;\n}\n\n","human_summarization":"implement a generic swap function or operator that exchanges the values of two variables or storage places, regardless of their types. The function handles the constraints of statically typed languages and dynamically typed languages, and also addresses issues related to parametric polymorphism. However, it doesn't support swapping values of two variables that don't belong to a class in Java due to its use of references.","id":379} {"lang_cluster":"Java","source_code":"\n\npublic static boolean pali(String testMe){\n\tStringBuilder sb = new StringBuilder(testMe);\n\treturn testMe.equals(sb.reverse().toString());\n}\n\n\npublic static boolean isPalindrome(String input) {\n\tfor (int i = 0, j = input.length() - 1; i < j; i++, j--) {\n\t\tchar startChar = input.charAt(i);\n\t\tchar endChar = input.charAt(j);\n\n\t\t\/\/ Handle surrogate pairs in UTF-16\n\t\tif (Character.isLowSurrogate(endChar)) {\n\t\t\tif (startChar\u00a0!= input.charAt(--j)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (input.charAt(++i)\u00a0!= endChar) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else if (startChar\u00a0!= endChar) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}\n\npublic static boolean rPali(String testMe){\n\tif(testMe.length()<=1){\n\t\treturn true;\n\t}\n\tif(!(testMe.charAt(0)+\"\").equals(testMe.charAt(testMe.length()-1)+\"\")){\n\t\treturn false;\n\t}\n\treturn rPali(testMe.substring(1, testMe.length()-1));\n}\n\npublic static boolean rPali(String testMe){\n\tint strLen = testMe.length();\n\treturn rPaliHelp(testMe, strLen-1, strLen\/2, 0);\n}\n\npublic static boolean rPaliHelp(String testMe, int strLen, int testLen, int index){\n\tif(index > testLen){\n\t\treturn true;\n\t}\n\tif(testMe.charAt(index)\u00a0!= testMe.charAt(strLen-index)){\n\t\treturn false;\n\t}\n\treturn rPaliHelp(testMe, strLen, testLen, index + 1);\n}\n\npublic static boolean pali(String testMe){\n\treturn testMe.matches(\"|(?:(.)(?<=(?=^.*?(\\\\1\\\\2?)$).*))+(?<=(?=^\\\\2$).*)\");\n}\n","human_summarization":"The code includes functions to check if a given sequence of characters is a palindrome. It supports Unicode characters and can also detect inexact palindromes by ignoring white-space, punctuation, and case. The code uses both non-recursive and recursive methods, with some versions not supporting upper-plane Unicode. It also demonstrates how to reverse a string and test a function.","id":380} {"lang_cluster":"Java","source_code":"\nSystem.getenv(\"HOME\") \/\/ get env var\nSystem.getenv() \/\/ get the entire environment as a Map of keys to values\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":381} {"lang_cluster":"Java","source_code":"\/\/Aamrun, 11th July 2022\n\npublic class Main {\n\n private static int F(int n,int x,int y) {\n \tif (n == 0) {\n \treturn x + y;\n \t}\n \n \t else if (y == 0) {\n \treturn x;\n \t}\n \n \treturn F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y);\n }\n\n public static void main(String[] args) {\n System.out.println(\"F(1,3,3) = \" + F(1,3,3));\n }\n}\n\n\nF(1,3,3) = 35\n\n","human_summarization":"implement the Sudan function, a recursive function that takes two parameters, x and y, and returns the value of F(x, y). The function follows specific rules for calculation based on the values of x and y.","id":382} {"lang_cluster":"Swift","source_code":"\n\nstruct Stack {\n var items = [T]()\n var empty:Bool {\n return items.count == 0\n }\n \n func peek() -> T {\n return items[items.count - 1]\n }\n \n mutating func pop() -> T {\n return items.removeLast()\n }\n \n mutating func push(obj:T) {\n items.append(obj)\n }\n}\n\nvar stack = Stack()\nstack.push(1)\nstack.push(2)\nprintln(stack.pop())\nprintln(stack.peek())\nstack.pop()\nprintln(stack.empty)\n\n","human_summarization":"implement a stack data structure with last in, first out (LIFO) access policy. The stack supports basic operations such as push (adding an element to the top of the stack), pop (removing the last added element from the stack), and empty (checking if the stack is empty). The topmost element can be accessed without modifying the stack. This stack implementation is commonly used in programming for resource management, particularly memory.","id":383} {"lang_cluster":"Swift","source_code":"\nimport Cocoa\n\nfunc fibonacci(n: Int) -> Int {\n let square_root_of_5 = sqrt(5.0)\n let p = (1 + square_root_of_5) \/ 2\n let q = 1 \/ p\n return Int((pow(p,CDouble(n)) + pow(q,CDouble(n))) \/ square_root_of_5 + 0.5)\n}\n\nfor i in 1...30 {\n println(fibonacci(i))\n}\nfunc fibonacci(n: Int) -> Int {\n if n < 2 {\n return n\n }\n var fibPrev = 1\n var fib = 1\n for num in 2...n {\n (fibPrev, fib) = (fib, fib + fibPrev)\n }\n return fib\n}\n\nfunc fibonacci() -> SequenceOf {\n return SequenceOf {() -> GeneratorOf in\n var window: (UInt, UInt, UInt) = (0, 0, 1)\n return GeneratorOf {\n window = (window.1, window.2, window.1 + window.2)\n return window.0\n }\n }\n}\nfunc fibonacci(n: Int) -> Int {\n if n < 2 {\n return n\n } else {\n return fibonacci(n-1) + fibonacci(n-2)\n }\n}\n\nprintln(fibonacci(30))\n","human_summarization":"generate the nth Fibonacci number, supporting both positive and negative indices. The function can be either iterative or recursive.","id":384} {"lang_cluster":"Swift","source_code":"\nlet numbers = [1,2,3,4,5,6]\nlet even_numbers = numbers.filter { $0\u00a0% 2 == 0 }\nprintln(even_numbers)\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":385} {"lang_cluster":"Swift","source_code":"\nlet string = \"Hello, Swift language\"\nlet (n, m) = (5, 4)\n\n\/\/ Starting from `n` characters in and of `m` length.\ndo {\n let start = string.startIndex.advancedBy(n)\n let end = start.advancedBy(m)\n \/\/ Pure-Swift (standard library only):\n _ = string[start.. String {\n return String(s.characters.reverse())\n}\nprint(reverseString(\"asdf\"))\nprint(reverseString(\"as\u20dddf\u0305\"))\nWorks with: Swift version 1.x\nfunc reverseString(s: String) -> String {\n return String(reverse(s))\n}\nprintln(reverseString(\"asdf\"))\nprintln(reverseString(\"as\u20dddf\u0305\"))\n\n","human_summarization":"are designed to reverse a given string, preserving any Unicode combining characters. For instance, the string \"asdf\" will be reversed to \"fdsa\" and \"as\u20dddf\u0305\" will be reversed to \"f\u0305ds\u20dda\". This is achieved by iterating through Swift's strings by Characters, which represent \"Unicode grapheme clusters\".","id":387} {"lang_cluster":"Swift","source_code":"\ntypealias WeightedEdge = (Int, Int, Int)\n\nstruct Grid {\n var nodes: [Node]\n\n mutating func addNode(data: T) -> Int {\n nodes.append(Node(data: data, edges: []))\n\n return nodes.count - 1\n }\n\n mutating func createEdges(weights: [WeightedEdge]) {\n for (start, end, weight) in weights {\n nodes[start].edges.append((end, weight))\n nodes[end].edges.append((start, weight))\n }\n }\n\n func findPath(start: Int, end: Int) -> ([Int], Int)? {\n var dist = Array(repeating: (Int.max, nil as Int?), count: nodes.count)\n var heap = Heap(sort: { $0.cost < $1.cost })\n\n dist[start] = (0, nil)\n heap.insert(State(node: start, cost: 0))\n\n while let state = heap.remove(at: 0) {\n if state.node == end {\n var path = [end]\n var currentDist = dist[end]\n\n while let prev = currentDist.1 {\n path.append(prev)\n currentDist = dist[prev]\n }\n\n return (path.reversed(), state.cost)\n }\n\n guard state.cost <= dist[state.node].0 else {\n continue\n }\n\n for edge in nodes[state.node].edges {\n let next = State(node: edge.0, cost: state.cost + edge.1)\n\n if next.cost < dist[next.node].0 {\n dist[next.node] = (next.cost, state.node)\n heap.insert(next)\n }\n }\n }\n\n return nil\n }\n}\n\nstruct Node {\n var data: T\n var edges: [(Int, Int)]\n}\n\nstruct State {\n var node: Int\n var cost: Int\n}\n\nvar grid = Grid(nodes: [])\n\nlet (a, b, c, d, e, f) = (\n grid.addNode(data: \"a\"),\n grid.addNode(data: \"b\"),\n grid.addNode(data: \"c\"),\n grid.addNode(data: \"d\"),\n grid.addNode(data: \"e\"),\n grid.addNode(data: \"f\")\n)\n\ngrid.createEdges(weights: [\n (a, b, 7), (a, c, 9), (a, f, 14),\n (b, c, 10), (b, d, 15), (c, d, 11),\n (c, f, 2), (d, e, 6), (e, f, 9)\n])\n\nguard let (path, cost) = grid.findPath(start: a, end: e) else {\n fatalError(\"Could not find path\")\n}\n\nprint(\"Cost: \\(cost)\")\nprint(path.map({ grid.nodes[$0].data }).joined(separator: \" -> \"))\n\n\n","human_summarization":"The code implements Dijkstra's algorithm to find the shortest path from a single source to all other vertices in a given graph. The graph is represented by an adjacency matrix or list, and the algorithm operates on a directed and weighted graph with non-negative edge path costs. The output is a set of edges depicting the shortest path to each reachable node from the source. The code also includes a function to interpret the output and determine the shortest path from the source node to specific nodes.","id":388} {"lang_cluster":"Swift","source_code":"import Foundation\n\nstruct Point: Equatable {\n var x: Double\n var y: Double\n}\n\nstruct Circle {\n var center: Point\n var radius: Double\n\n static func circleBetween(\n _ p1: Point,\n _ p2: Point,\n withRadius radius: Double\n ) -> (Circle, Circle?)? {\n func applyPoint(_ p1: Point, _ p2: Point, op: (Double, Double) -> Double) -> Point {\n return Point(x: op(p1.x, p2.x), y: op(p1.y, p2.y))\n }\n\n func mul2(_ p: Point, mul: Double) -> Point {\n return Point(x: p.x * mul, y: p.y * mul)\n }\n\n func div2(_ p: Point, div: Double) -> Point {\n return Point(x: p.x \/ div, y: p.y \/ div)\n }\n\n func norm(_ p: Point) -> Point {\n return div2(p, div: (p.x * p.x + p.y * p.y).squareRoot())\n }\n\n guard radius != 0, p1 != p2 else {\n return nil\n }\n\n let diameter = 2 * radius\n let pq = applyPoint(p1, p2, op: -)\n let magPQ = (pq.x * pq.x + pq.y * pq.y).squareRoot()\n\n guard diameter >= magPQ else {\n return nil\n }\n\n let midpoint = div2(applyPoint(p1, p2, op: +), div: 2)\n let halfPQ = magPQ \/ 2\n let magMidC = abs(radius * radius - halfPQ * halfPQ).squareRoot()\n let midC = mul2(norm(Point(x: -pq.y, y: pq.x)), mul: magMidC)\n let center1 = applyPoint(midpoint, midC, op: +)\n let center2 = applyPoint(midpoint, midC, op: -)\n\n if center1 == center2 {\n return (Circle(center: center1, radius: radius), nil)\n } else {\n return (Circle(center: center1, radius: radius), Circle(center: center2, radius: radius))\n }\n }\n}\n\nlet testCases = [\n (Point(x: 0.1234, y: 0.9876), Point(x: 0.8765, y: 0.2345), 2.0),\n (Point(x: 0.0000, y: 2.0000), Point(x: 0.0000, y: 0.0000), 1.0),\n (Point(x: 0.1234, y: 0.9876), Point(x: 0.1234, y: 0.9876), 2.0),\n (Point(x: 0.1234, y: 0.9876), Point(x: 0.8765, y: 0.2345), 0.5),\n (Point(x: 0.1234, y: 0.9876), Point(x: 0.1234, y: 0.9876), 0.0)\n]\n\nfor testCase in testCases {\n switch Circle.circleBetween(testCase.0, testCase.1, withRadius: testCase.2) {\n case nil:\n print(\"No ans\")\n case (let circle1, nil)?:\n print(\"One ans: \\(circle1)\")\n case (let circle1, let circle2?)?:\n print(\"Two ans: \\(circle1) \\(circle2)\")\n }\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":389} {"lang_cluster":"Swift","source_code":"\nwhile true\n{\n let a = Int(arc4random())\u00a0% (20)\n print(\"a: \\(a)\",terminator: \" \")\n if (a == 10)\n {\n break\n }\n let b = Int(arc4random())\u00a0% (20)\n print(\"b: \\(b)\")\n}\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":390} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nextension BinaryInteger {\n var isPrime: Bool {\n if self == 0 || self == 1 {\n return false\n } else if self == 2 {\n return true\n }\n\n let max = Self(ceil((Double(self).squareRoot())))\n\n for i in stride(from: 2, through: max, by: 1) where self % i == 0 {\n return false\n }\n\n return true\n }\n\n func modPow(exp: Self, mod: Self) -> Self {\n guard exp != 0 else {\n return 1\n }\n\n var res = Self(1)\n var base = self % mod\n var exp = exp\n\n while true {\n if exp & 1 == 1 {\n res *= base\n res %= mod\n }\n\n if exp == 1 {\n return res\n }\n\n exp >>= 1\n base *= base\n base %= mod\n }\n }\n}\n\nfunc mFactor(exp: Int) -> Int? {\n for k in 0..<16384 {\n let q = 2*exp*k + 1\n\n if !q.isPrime {\n continue\n } else if q % 8 != 1 && q % 8 != 7 {\n continue\n } else if 2.modPow(exp: exp, mod: q) == 1 {\n return q\n }\n }\n\n return nil\n}\n\nprint(mFactor(exp: 929)!)\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":391} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 1.2+\nvar s1 : Set = [1, 2, 3, 4]\nlet s2 : Set = [3, 4, 5, 6]\nprintln(s1.union(s2)) \/\/ union; prints \"[5, 6, 2, 3, 1, 4]\"\nprintln(s1.intersect(s2)) \/\/ intersection; prints \"[3, 4]\"\nprintln(s1.subtract(s2)) \/\/ difference; prints \"[2, 1]\"\nprintln(s1.isSubsetOf(s1)) \/\/ subset; prints \"true\"\nprintln(Set([3, 1]).isSubsetOf(s1)) \/\/ subset; prints \"true\"\nprintln(s1.isStrictSubsetOf(s1)) \/\/ proper subset; prints \"false\"\nprintln(Set([3, 1]).isStrictSubsetOf(s1)) \/\/ proper subset; prints \"true\"\nprintln(Set([3, 2, 4, 1]) == s1) \/\/ equality; prints \"true\"\nprintln(s1 == s2) \/\/ equality; prints \"false\"\nprintln(s1.contains(2)) \/\/ membership; prints \"true\"\nprintln(Set([1, 2, 3, 4]).isSupersetOf(s1)) \/\/ superset; prints \"true\"\nprintln(Set([1, 2, 3, 4]).isStrictSupersetOf(s1)) \/\/ proper superset; prints \"false\"\nprintln(Set([1, 2, 3, 4, 5]).isStrictSupersetOf(s1)) \/\/ proper superset; prints \"true\"\nprintln(s1.exclusiveOr(s2)) \/\/ symmetric difference; prints \"[5, 6, 2, 1]\"\nprintln(s1.count) \/\/ cardinality; prints \"4\"\ns1.insert(99) \/\/ mutability\nprintln(s1) \/\/ prints \"[99, 2, 3, 1, 4]\"\ns1.remove(99) \/\/ mutability\nprintln(s1) \/\/ prints \"[2, 3, 1, 4]\"\ns1.unionInPlace(s2) \/\/ mutability\nprintln(s1) \/\/ prints \"[5, 6, 2, 3, 1, 4]\"\ns1.subtractInPlace(s2) \/\/ mutability\nprintln(s1) \/\/ prints \"[2, 1]\"\ns1.exclusiveOrInPlace(s2) \/\/ mutability\nprintln(s1) \/\/ prints \"[5, 6, 2, 3, 1, 4]\"\n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":392} {"lang_cluster":"Swift","source_code":"\nimport Cocoa\n\nvar year=2008\nlet formatter=DateFormatter()\nformatter.dateFormat = \"yyyy-MM-dd\"\n\nlet gregorian:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)\nwhile (year<2122){\n var date:NSDate!=formatter.date(from: String(year)+\"-12-25\") as NSDate?\n var components=gregorian.components(NSCalendar.Unit.weekday, from: date as Date)\n var dayOfWeek:NSInteger=components.weekday!\n if(dayOfWeek==1){\n print(year)\n }\n year+=1 \n}\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":393} {"lang_cluster":"Swift","source_code":"\n\nWorks with: Swift version 1.2+\nprintln(Array(Set([3,2,1,2,3,4])))\n\n","human_summarization":"\"Implements three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Checking each element against the rest of the array. The first method requires elements to be hashable, the second requires elements to be comparable, and the third only requires elements to be equatable.\"","id":394} {"lang_cluster":"Swift","source_code":"\nfunc quicksort(inout elements: [T], range: Range) {\n if (range.endIndex - range.startIndex > 1) {\n let pivotIndex = partition(&elements, range)\n quicksort(&elements, range.startIndex ..< pivotIndex)\n quicksort(&elements, pivotIndex+1 ..< range.endIndex)\n }\n}\n\nfunc quicksort(inout elements: [T]) {\n quicksort(&elements, indices(elements))\n}\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":395} {"lang_cluster":"Swift","source_code":"\nimport Foundation\nextension String {\n func toStandardDateWithDateFormat(format: String) -> String {\n let dateFormatter = NSDateFormatter()\n dateFormatter.dateFormat = format\n dateFormatter.dateStyle = .LongStyle\n return dateFormatter.stringFromDate(dateFormatter.dateFromString(self)!)\n }\n}\n\nlet date = \"2015-08-28\".toStandardDateWithDateFormat(\"yyyy-MM-dd\")\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":396} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version Revision 4 - tested with Xcode 9.2 playground\nfunc powersetFrom(_ elements: Set) -> Set> {\n guard elements.count > 0 else {\n return [[]]\n }\n var powerset: Set> = [[]]\n for element in elements {\n for subset in powerset {\n powerset.insert(subset.union([element]))\n }\n }\n return powerset\n}\n\n\/\/ Example:\npowersetFrom([1, 2, 4])\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":397} {"lang_cluster":"Swift","source_code":"\nfunc ator(var n: Int) -> String {\n\n var result = \"\"\n \n for (value, letter) in\n [( 1000, \"M\"),\n ( 900, \"CM\"),\n ( 500, \"D\"),\n ( 400, \"CD\"),\n ( 100, \"C\"),\n ( 90, \"XC\"),\n ( 50, \"L\"),\n ( 40, \"XL\"),\n ( 10, \"X\"),\n ( 9, \"IX\"),\n ( 5, \"V\"),\n ( 4, \"IV\"),\n ( 1, \"I\")]\n {\n while n >= value {\n result += letter\n n -= value\n }\n }\n return result\n}\n\nWorks with: Swift version 1.x\nprintln(ator(1666)) \/\/ MDCLXVI\nWorks with: Swift version 2.0\nprint(ator(1666)) \/\/ MDCLXVI\n\n","human_summarization":"The function takes a positive integer as input and returns its equivalent in Roman numerals. It handles each digit separately, starting from the leftmost digit and ignoring zeros. For example, it converts 1990 to MCMXC, 2008 to MMVIII, and 1666 to MDCLXVI.","id":398} {"lang_cluster":"Swift","source_code":"\n\/\/ Arrays are typed in Swift, however, using the Any object we can add any type. Swift does not support fixed length arrays\nvar anyArray = [Any]()\nanyArray.append(\"foo\") \/\/ Adding to an Array\nanyArray.append(1) \/\/ [\"foo\", 1]\nanyArray.removeAtIndex(1) \/\/ Remove object\nanyArray[0] = \"bar\" \/\/ [\"bar\"]\n","human_summarization":"demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and includes the functionality of pushing a value into the array.","id":399} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nprintln(\"alphaBETA\".uppercaseString)\nprintln(\"alphaBETA\".lowercaseString)\nprintln(\"foO BAr\".capitalizedString)\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":400} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nstruct Point {\n var x: Double\n var y: Double\n\n func distance(to p: Point) -> Double {\n let x = pow(p.x - self.x, 2)\n let y = pow(p.y - self.y, 2)\n \n return (x + y).squareRoot()\n }\n}\n\nextension Collection where Element == Point {\n func closestPair() -> (Point, Point)? {\n let (xP, xY) = (sorted(by: { $0.x < $1.x }), sorted(by: { $0.y < $1.y }))\n \n return Self.closestPair(xP, xY)?.1\n }\n \n static func closestPair(_ xP: [Element], _ yP: [Element]) -> (Double, (Point, Point))? {\n guard xP.count > 3 else { return xP.closestPairBruteForce() }\n \n let half = xP.count \/ 2\n let xl = Array(xP[.. xm {\n cur.1.append(el)\n } else {\n cur.0.append(el)\n }\n })\n \n guard let (distanceL, pairL) = closestPair(xl, yl) else { return nil }\n guard let (distanceR, pairR) = closestPair(xr, yr) else { return nil }\n \n let (dMin, pairMin) = distanceL > distanceR ? (distanceR, pairR) : (distanceL, pairL)\n \n let ys = yP.filter({ abs(xm - $0.x) < dMin })\n \n var (closest, pairClosest) = (dMin, pairMin)\n \n for i in 0.. (Double, (Point, Point))? {\n guard count >= 2 else { return nil }\n \n var closestPoints = (self.first!, self[index(after: startIndex)])\n var minDistance = abs(closestPoints.0.distance(to: closestPoints.1))\n \n guard count != 2 else { return (minDistance, closestPoints) }\n \n for i in 0.. [String: Library] {\n var libraries = [String: Library]()\n\n for (name, parents) in input {\n var numParents = 0\n\n for parent in parents where parent != name {\n numParents += 1\n\n libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name)\n }\n\n libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents\n }\n\n return libraries\n}\n\nfunc topologicalSort(libs: [String: Library]) -> [String]? {\n var libs = libs\n var needsProcessing = Set(libs.keys)\n var options = libs.compactMap({ $0.value.numParents == 0 ? $0.key : nil })\n var sorted = [String]()\n\n while let cur = options.popLast() {\n for children in libs[cur]?.children ?? [] {\n libs[children]?.numParents -= 1\n\n if libs[children]?.numParents == 0 {\n options.append(libs[children]!.name)\n }\n }\n\n libs[cur]?.children.removeAll()\n\n sorted.append(cur)\n needsProcessing.remove(cur)\n }\n\n guard needsProcessing.isEmpty else {\n return nil\n }\n\n return sorted\n}\n\nprint(topologicalSort(libs: buildLibraries(libs))!)\n\n\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":403} {"lang_cluster":"Swift","source_code":"\nvar str = \"Hello, playground\"\nstr.hasPrefix(\"Hell\") \/\/True\nstr.hasPrefix(\"hell\") \/\/False\n\nstr.containsString(\"llo\") \/\/True\nstr.containsString(\"xxoo\") \/\/False\n\nstr.hasSuffix(\"playground\") \/\/True\nstr.hasSuffix(\"world\") \/\/False\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":404} {"lang_cluster":"Swift","source_code":"var total = 0\nvar prim = 0\nvar maxPeri = 100\n\nfunc newTri(s0:Int, _ s1:Int, _ s2: Int) -> () {\n \n let p = s0 + s1 + s2\n if p <= maxPeri {\n prim += 1\n total += maxPeri \/ p\n newTri( s0 + 2*(-s1+s2), 2*( s0+s2) - s1, 2*( s0-s1+s2) + s2)\n newTri( s0 + 2*( s1+s2), 2*( s0+s2) + s1, 2*( s0+s1+s2) + s2)\n newTri(-s0 + 2*( s1+s2), 2*(-s0+s2) + s1, 2*(-s0+s1+s2) + s2)\n }\n}\n\nwhile maxPeri <= 100_000_000 {\n prim = 0\n total = 0\n newTri(3, 4, 5)\n print(\"Up to \\(maxPeri)\u00a0: \\(total) triples \\( prim) primitives.\")\n maxPeri *= 10\n}\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":405} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nlet dictPath: String\n\nswitch CommandLine.arguments.count {\ncase 2:\n dictPath = CommandLine.arguments[1]\ncase _:\n dictPath = \"\/usr\/share\/dict\/words\"\n}\n\nlet wordsData = FileManager.default.contents(atPath: dictPath)!\nlet allWords = String(data: wordsData, encoding: .utf8)!\nlet words = allWords.components(separatedBy: \"\\n\")\nlet counts = words.flatMap({ $0.map({ ($0, 1) }) }).reduce(into: [:], { $0[$1.0, default: 0] += $1.1 })\n\nfor (char, count) in counts {\n print(\"\\(char): \\(count)\")\n}\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":406} {"lang_cluster":"Swift","source_code":"\nclass Node{\n var data: T = nil\n var next: Node? = nil\n init(input: T){\n data = input\n next = nil\n }\n}\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":407} {"lang_cluster":"Swift","source_code":"\n\nextension CGFloat {\n func degrees_to_radians() -> CGFloat {\n return CGFloat(M_PI) * self \/ 180.0\n }\n}\n\nextension Double {\n func degrees_to_radians() -> Double {\n return Double(M_PI) * self \/ 180.0\n }\n}\n\n\nclass Tree: UIView {\n \n \n func drawTree(x1: CGFloat, y1: CGFloat, angle: CGFloat, depth:Int){\n if depth == 0 {\n return\n }\n let ang = angle.degrees_to_radians()\n let x2:CGFloat = x1 + ( cos(ang) as CGFloat) * CGFloat(depth) * (self.frame.width \/ 60)\n let y2:CGFloat = y1 + ( sin(ang) as CGFloat) * CGFloat(depth) * (self.frame.width \/ 60)\n \n let line = drawLine(x1, y1: y1, x2: x2, y2: y2)\n \n line.stroke()\n drawTree(x2, y1: y2, angle: angle - 20, depth: depth - 1)\n drawTree(x2, y1: y2, angle: angle + 20, depth: depth - 1)\n }\n \n func drawLine(x1:CGFloat, y1:CGFloat, x2:CGFloat, y2:CGFloat) -> UIBezierPath\n {\n \n let path = UIBezierPath()\n path.moveToPoint(CGPoint(x: x1,y: y1))\n path.addLineToPoint(CGPoint(x: x2,y: y2))\n path.lineWidth = 1\n return path\n }\n \n override func drawRect(rect: CGRect) {\n \n let color = UIColor(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)\n color.set()\n drawTree(self.frame.width \/ 2 , y1: self.frame.height * 0.8, angle: -90 , depth: 9 )\n }\n}\n\n\nlet tree = Tree(frame: CGRectMake(0, 0, 300, 300))\ntree\n\n","human_summarization":"Generates and draws a fractal tree by first drawing the trunk, then splitting the end of the trunk by a certain angle to draw two branches, and repeating this process until a sufficient level of branching is achieved.","id":408} {"lang_cluster":"Swift","source_code":"\n\nfunc factors(n: Int) -> [Int] {\n \n return filter(1...n) { n\u00a0% $0 == 0 }\n}\n\nimport func Darwin.sqrt\n\nfunc sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }\n\nfunc factors(n: Int) -> [Int] {\n \n var result = [Int]()\n \n for factor in filter (1...sqrt(n), { n\u00a0% $0 == 0 }) {\n \n result.append(factor)\n\n if n\/factor\u00a0!= factor { result.append(n\/factor) }\n }\n \n return sorted(result)\n \n}\n\nprintln(factors(4))\nprintln(factors(1))\nprintln(factors(25))\nprintln(factors(63))\nprintln(factors(19))\nprintln(factors(768))\n\n","human_summarization":"calculate the factors of a given positive integer, excluding zero and negative integers. The factors are the positive integers that can divide the given number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":409} {"lang_cluster":"Swift","source_code":"import Foundation\n\nextension String {\n func dropLastIf(_ char: Character) -> String {\n if last == char {\n return String(dropLast())\n } else {\n return self\n }\n }\n}\n\nenum Align {\n case left, center, right\n}\n\nfunc getLines(input: String) -> [String] {\n input\n .components(separatedBy: \"\\n\")\n .map({ $0.replacingOccurrences(of: \" \", with: \"\").dropLastIf(\"$\") })\n}\n\nfunc getColWidths(from: String) -> [Int] {\n var widths = [Int]()\n let lines = getLines(input: from)\n\n for line in lines {\n let lens = line.components(separatedBy: \"$\").map({ $0.count })\n\n for (i, len) in lens.enumerated() {\n if i < widths.count {\n widths[i] = max(widths[i], len)\n } else {\n widths.append(len)\n }\n }\n }\n\n return widths\n}\n\nfunc alignCols(input: String, align: Align = .left) -> String {\n let widths = getColWidths(from: input)\n let lines = getLines(input: input)\n var res = \"\"\n\n for line in lines {\n for (str, width) in zip(line.components(separatedBy: \"$\"), widths) {\n let blanks = width - str.count\n let pre: Int, post: Int\n\n switch align {\n case .left:\n (pre, post) = (0, blanks)\n case .center:\n (pre, post) = (blanks \/ 2, (blanks + 1) \/ 2)\n case .right:\n (pre, post) = (blanks, 0)\n }\n\n res += String(repeating: \" \", count: pre)\n res += str\n res += String(repeating: \" \", count: post)\n res += \" \"\n }\n\n res += \"\\n\"\n }\n\n return res\n}\n\nlet input = \"\"\"\n Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n are$delineated$by$a$single$'dollar'$character,$write$a$program\n that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n column$are$separated$by$at$least$one$space.\n Further,$allow$for$each$word$in$a$column$to$be$either$left$\n justified,$right$justified,$or$center$justified$within$its$column.\n \"\"\"\n\nprint(alignCols(input: input))\nprint()\nprint(alignCols(input: input, align: .center))\nprint()\nprint(alignCols(input: input, align: .right))\n\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":410} {"lang_cluster":"Swift","source_code":"\nfunc rot13char(c: UnicodeScalar) -> UnicodeScalar {\n switch c {\n case \"A\"...\"M\", \"a\"...\"m\":\n return UnicodeScalar(UInt32(c) + 13)\n case \"N\"...\"Z\", \"n\"...\"z\":\n return UnicodeScalar(UInt32(c) - 13)\n default:\n return c\n }\n}\n\nfunc rot13(str: String) -> String {\n return String(map(str.unicodeScalars){ c in Character(rot13char(c)) })\n}\n\nprintln(rot13(\"The quick brown fox jumps over the lazy dog\"))\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":411} {"lang_cluster":"Swift","source_code":"\nextension Sequence {\n func sorted(\n on: KeyPath,\n using: (Value, Value) -> Bool\n ) -> [Element] where Value: Comparable {\n return withoutActuallyEscaping(using, do: {using -> [Element] in\n return self.sorted(by: { using($0[keyPath: on], $1[keyPath: on]) })\n })\n }\n}\n\nstruct Person {\n var name: String\n var role: String\n}\n\nlet a = Person(name: \"alice\", role: \"manager\")\nlet b = Person(name: \"bob\", role: \"worker\")\nlet c = Person(name: \"charlie\", role: \"driver\")\n\nprint([c, b, a].sorted(on: \\.name, using: <))\n\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":412} {"lang_cluster":"Swift","source_code":"\nfor i in 1...5 {\n for _ in 1...i {\n print(\"*\", terminator: \"\")\n }\n print()\n}\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":413} {"lang_cluster":"Swift","source_code":"\n\/\/ make an empty map\nvar a = [String: Int]()\n\/\/ or\nvar b: [String: Int] = [:]\n\n\/\/ make an empty map with an initial capacity\nvar c = [String: Int](minimumCapacity: 42)\n\n\/\/ set a value\nc[\"foo\"] = 3\n\n\/\/ make a map with a literal\nvar d = [\"foo\": 2, \"bar\": 42, \"baz\": -1]\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":414} {"lang_cluster":"Swift","source_code":"\nimport Cocoa\n\nclass LinearCongruntialGenerator {\n \n var state = 0 \/\/seed of 0 by default\n let a, c, m, shift: Int\n \n \/\/we will use microsoft random by default\n init() {\n self.a = 214013\n self.c = 2531011\n self.m = Int(pow(2.0, 31.0)) \/\/2^31 or 2147483648\n self.shift = 16\n }\n \n init(a: Int, c: Int, m: Int, shift: Int) {\n self.a = a\n self.c = c\n self.m = m \/\/2^31 or 2147483648\n self.shift = shift\n }\n \n func seed(seed: Int) -> Void {\n state = seed;\n }\n \n func random() -> Int {\n state = (a * state + c) % m\n return state >> shift\n }\n}\n\nlet microsoftLinearCongruntialGenerator = LinearCongruntialGenerator()\nlet BSDLinearCongruntialGenerator = LinearCongruntialGenerator(a: 1103515245, c: 12345, m: 2147483648, shift: 0)\n\nprint(\"Microsft Rand:\")\nfor(var i = 0; i < 10; i++)\n{\n print(microsoftLinearCongruntialGenerator.random())\n}\n\nprint(\"\") \/\/new line for readability\nprint(\"BSD Rand:\")\nfor(var i = 0; i < 10; i++)\n{\n print(BSDLinearCongruntialGenerator.random())\n}\n\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":415} {"lang_cluster":"Swift","source_code":"\nimport Darwin\n\nfunc ethiopian(var #int1:Int, var #int2:Int) -> Int {\n var lhs = [int1], rhs = [int2]\n \n func isEven(#n:Int) -> Bool {return n\u00a0% 2 == 0}\n func double(#n:Int) -> Int {return n * 2}\n func halve(#n:Int) -> Int {return n \/ 2}\n \n while int1\u00a0!= 1 {\n lhs.append(halve(n: int1))\n rhs.append(double(n: int2))\n int1 = halve(n: int1)\n int2 = double(n: int2)\n }\n \n var returnInt = 0\n for (a,b) in zip(lhs, rhs) {\n if (!isEven(n: a)) {\n returnInt += b\n }\n }\n return returnInt\n}\n\nprintln(ethiopian(int1: 17, int2: 34))\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":416} {"lang_cluster":"Swift","source_code":"\nimport Darwin\nimport Foundation\n\nvar solution = \"\"\n\nprintln(\"24 Game\")\nprintln(\"Generating 4 digits...\")\n\nfunc randomDigits() -> [Int] {\n var result = [Int]()\n for i in 0 ..< 4 {\n result.append(Int(arc4random_uniform(9)+1))\n }\n return result\n}\n\n\/\/ Choose 4 digits\nlet digits = randomDigits()\n\nprint(\"Make 24 using these digits\u00a0: \")\n\nfor digit in digits {\n print(\"\\(digit) \")\n}\nprintln()\n\n\/\/ get input from operator\nvar input = NSString(data:NSFileHandle.fileHandleWithStandardInput().availableData, encoding:NSUTF8StringEncoding)!\n\nvar enteredDigits = [Double]()\n\nvar enteredOperations = [Character]()\n\nlet inputString = input as String\n\n\/\/ store input in the appropriate table\nfor character in inputString {\n switch character {\n case \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\":\n let digit = String(character)\n enteredDigits.append(Double(digit.toInt()!))\n case \"+\", \"-\", \"*\", \"\/\":\n enteredOperations.append(character)\n case \"\\n\":\n println()\n default:\n println(\"Invalid expression\")\n }\n}\n\n\/\/ check value of expression provided by the operator\nvar value = 0.0\n\nif enteredDigits.count == 4 && enteredOperations.count == 3 {\n value = enteredDigits[0]\n for (i, operation) in enumerate(enteredOperations) {\n switch operation {\n case \"+\":\n value = value + enteredDigits[i+1]\n case \"-\":\n value = value - enteredDigits[i+1]\n case \"*\":\n value = value * enteredDigits[i+1]\n case \"\/\":\n value = value \/ enteredDigits[i+1]\n default:\n println(\"This message should never happen!\")\n }\n }\n}\n\nfunc evaluate(dPerm: [Double], oPerm: [String]) -> Bool {\n var value = 0.0\n \n if dPerm.count == 4 && oPerm.count == 3 {\n value = dPerm[0]\n for (i, operation) in enumerate(oPerm) {\n switch operation {\n case \"+\":\n value = value + dPerm[i+1]\n case \"-\":\n value = value - dPerm[i+1]\n case \"*\":\n value = value * dPerm[i+1]\n case \"\/\":\n value = value \/ dPerm[i+1]\n default:\n println(\"This message should never happen!\")\n }\n }\n }\n return (abs(24 - value) < 0.001)\n}\n\nfunc isSolvable(inout digits: [Double]) -> Bool {\n \n var result = false\n var dPerms = [[Double]]()\n permute(&digits, &dPerms, 0)\n \n let total = 4 * 4 * 4\n var oPerms = [[String]]()\n permuteOperators(&oPerms, 4, total)\n \n \n for dig in dPerms {\n for opr in oPerms {\n var expression = \"\"\n \n if evaluate(dig, opr) {\n for digit in dig {\n expression += \"\\(digit)\"\n }\n \n for oper in opr {\n expression += oper\n }\n \n solution = beautify(expression)\n result = true\n }\n }\n }\n return result\n}\n\nfunc permute(inout lst: [Double], inout res: [[Double]], k: Int) -> Void {\n for i in k ..< lst.count {\n swap(&lst[i], &lst[k])\n permute(&lst, &res, k + 1)\n swap(&lst[k], &lst[i])\n }\n if k == lst.count {\n res.append(lst)\n }\n}\n\n\/\/ n=4, total=64, npow=16\nfunc permuteOperators(inout res: [[String]], n: Int, total: Int) -> Void {\n let posOperations = [\"+\", \"-\", \"*\", \"\/\"]\n let npow = n * n\n for i in 0 ..< total {\n res.append([posOperations[(i \/ npow)], posOperations[((i % npow) \/ n)], posOperations[(i % n)]])\n }\n}\n\nfunc beautify(infix: String) -> String {\n let newString = infix as NSString\n \n var solution = \"\"\n \n solution += newString.substringWithRange(NSMakeRange(0, 1))\n solution += newString.substringWithRange(NSMakeRange(12, 1))\n solution += newString.substringWithRange(NSMakeRange(3, 1))\n solution += newString.substringWithRange(NSMakeRange(13, 1))\n solution += newString.substringWithRange(NSMakeRange(6, 1))\n solution += newString.substringWithRange(NSMakeRange(14, 1))\n solution += newString.substringWithRange(NSMakeRange(9, 1))\n \n return solution\n}\n\nif value != 24 {\n println(\"The value of the provided expression is \\(value) instead of 24!\")\n if isSolvable(&enteredDigits) {\n println(\"A possible solution could have been \" + solution)\n } else {\n println(\"Anyway, there was no known solution to this one.\")\n }\n} else {\n println(\"Congratulations, you found a solution!\")\n}\n\n\n","human_summarization":"The code accepts four digits, either from user input or randomly generated, and calculates arithmetic expressions following the 24 game rules. It also displays examples of the solutions it generates.","id":417} {"lang_cluster":"Swift","source_code":"\nfunc factorial(_ n: Int) -> Int {\n\treturn n < 2\u00a0? 1\u00a0: (2...n).reduce(1, *)\n}\nfunc factorial(_ n: Int) -> Int {\n\treturn n < 2\u00a0? 1\u00a0: n * factorial(n - 1)\n}\n","human_summarization":"The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.","id":418} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 5.7\n\nfunc generateRandomNumArray(numDigits: Int = 4) -> [Character]\n{\n\tguard (1 ... 9).contains(numDigits) else { fatalError(\"number out of range\") }\n\n\treturn Array(\"123456789\".shuffled()[0 ..< numDigits])\n}\n\nfunc parseGuess(_ guess: String, numDigits: Int = 4) -> String?\n{\n\tguard guess.count == numDigits else { return nil }\n \/\/ Only digits 0 to 9 allowed, no Unicode fractions or numbers from other languages\n\tlet guessArray = guess.filter{ $0.isASCII && $0.isWholeNumber }\n\n \tguard Set(guessArray).count == numDigits else { return nil }\n\n \treturn guessArray\n}\n\nfunc pluralIfNeeded(_ count: Int, _ units: String) -> String\n{\n\treturn \"\\(count) \" + units + (count == 1 ? \"\" : \"s\")\n}\n\nvar guessAgain = \"y\"\nwhile guessAgain == \"y\"\n{\n \tlet num = generateRandomNumArray()\n \tvar bulls = 0\n \tvar cows = 0\n\n \tprint(\"Please enter a 4 digit number with digits between 1-9, no repetitions: \")\n\n \tif let guessStr = readLine(strippingNewline: true), let guess = parseGuess(guessStr)\n\t{\n\t\tfor (guess, actual) in zip(guess, num)\n\t\t{\n\t\t\tif guess == actual\n\t\t\t{\n\t \t\t\tbulls += 1\n\t\t\t}\n\t\t\telse if num.contains(guess)\n\t\t\t{\n\t \t\t\tcows += 1\n\t\t\t}\n \t\t}\n\n\t\tprint(\"Actual number: \" + num)\n\t\tprint(\"Your score: \\(pluralIfNeeded(bulls, \"bull\")) and \\(pluralIfNeeded(cows, \"cow\"))\\n\")\n\t\tprint(\"Would you like to play again? (y): \")\n\n\t\tguessAgain = readLine(strippingNewline: true)?.lowercased() ?? \"n\"\n\t}\n\telse\n\t{\n\t\tprint(\"Invalid input\")\n \t}\n}\n\nimport Foundation\n\nfunc generateRandomNumArray(numDigits: Int = 4) -> [Int] {\n guard numDigits > 0 else {\n return []\n }\n\n let needed = min(9, numDigits)\n var nums = Set()\n\n repeat {\n nums.insert(.random(in: 1...9))\n } while nums.count != needed\n\n return Array(nums)\n}\n\nfunc parseGuess(_ guess: String) -> [Int]? {\n guard guess.count == 4 else {\n return nil\n }\n\n let guessArray = guess.map(String.init).map(Int.init).compactMap({ $0 })\n\n guard Set(guessArray).count == 4 else {\n return nil\n }\n\n return guessArray\n}\n\nwhile true {\n let num = generateRandomNumArray()\n var bulls = 0\n var cows = 0\n\n print(\"Please enter a 4 digit number with digits between 1-9, no repetitions: \")\n\n guard let guessStr = readLine(strippingNewline: true), let guess = parseGuess(guessStr) else {\n print(\"Invalid input\")\n continue\n }\n\n for (guess, actual) in zip(guess, num) {\n if guess == actual {\n bulls += 1\n } else if num.contains(guess) {\n cows += 1\n }\n }\n\n print(\"Actual number: \\(num.map(String.init).joined())\")\n print(\"Your score: \\(bulls) bulls and \\(cows) cows\\n\")\n print(\"Would you like to play again? (y): \")\n\n guard readLine(strippingNewline: true)!.lowercased() == \"y\" else {\n exit(0)\n }\n}\n\n\n","human_summarization":"The code generates a unique four-digit random number from 1 to 9. It prompts the user for guesses, rejects malformed inputs, and calculates a score based on the guess. The user wins if the guess matches the random number. The score is determined by the number of 'bulls' (correct digits in the correct position) and 'cows' (correct digits in the wrong position). The game ends when the user guesses the number correctly. The code is optimized using Swift 5's standard library.","id":419} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 1.2+\nfunc dot(v1: [Double], v2: [Double]) -> Double {\n return reduce(lazy(zip(v1, v2)).map(*), 0, +)\n}\n\nprintln(dot([1, 3, -5], [4, -2, -1]))\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":420} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nvar \u231a\ufe0f = NSDate()\nprintln(\u231a\ufe0f)\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":421} {"lang_cluster":"Swift","source_code":"\n\nclass Sphere: UIView{\n \n override func drawRect(rect: CGRect)\n {\n let context = UIGraphicsGetCurrentContext()\n let locations: [CGFloat] = [0.0, 1.0]\n \n let colors = [UIColor.whiteColor().CGColor,\n UIColor.blueColor().CGColor]\n \n let colorspace = CGColorSpaceCreateDeviceRGB()\n \n let gradient = CGGradientCreateWithColors(colorspace,\n colors, locations)\n \n var startPoint = CGPoint()\n var endPoint = CGPoint()\n startPoint.x = self.center.x - (self.frame.width * 0.1)\n startPoint.y = self.center.y - (self.frame.width * 0.15)\n endPoint.x = self.center.x\n endPoint.y = self.center.y\n let startRadius: CGFloat = 0\n let endRadius: CGFloat = self.frame.width * 0.38\n \n CGContextDrawRadialGradient (context, gradient, startPoint,\n startRadius, endPoint, endRadius,\n 0)\n }\n}\n\nvar s = Sphere(frame: CGRectMake(0, 0, 200, 200))\n\n\nstruct ContentView: View {\n\n var body: some View {\n\n let gradient = RadialGradient(gradient: Gradient(colors:[.white, .black]),\n center: .init(x: 0.4, y: 0.4), startRadius: 10, endRadius: 100)\n \n return Circle()\n .fill(gradient)\n .frame(width: 200, height: 200)\n\n }\n}\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection, using SwiftUI in Playground.\"","id":422} {"lang_cluster":"Swift","source_code":"\nfunc addSuffix(n:Int) -> String {\n if n % 100 \/ 10 == 1 {\n return \"th\"\n }\n \n switch n % 10 {\n case 1:\n return \"st\"\n case 2:\n return \"nd\"\n case 3:\n return \"rd\"\n default:\n return \"th\"\n }\n}\n\nfor i in 0...25 {\n print(\"\\(i)\\(addSuffix(i)) \")\n}\nprintln()\nfor i in 250...265 {\n print(\"\\(i)\\(addSuffix(i)) \")\n}\nprintln()\nfor i in 1000...1025 {\n print(\"\\(i)\\(addSuffix(i)) \")\n}\nprintln()\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":423} {"lang_cluster":"Swift","source_code":"\nextension String {\n func stripCharactersInSet(chars: [Character]) -> String {\n return String(seq: filter(self) {find(chars, $0) == nil})\n }\n}\n\nlet aString = \"She was a soul stripper. She took my heart!\"\nlet chars: [Character] = [\"a\", \"e\", \"i\"]\n\nprintln(aString.stripCharactersInSet(chars))\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":424} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nprint(\"Input max number: \", terminator: \"\")\n\nguard let maxN = Int(readLine()\u00a0?? \"0\"), maxN > 0 else {\n fatalError(\"Please input a number greater than 0\")\n}\n\nfunc getFactor() -> (Int, String) {\n print(\"Enter a factor and phrase: \", terminator: \"\")\n\n guard let factor1Input = readLine() else {\n fatalError(\"Please enter a factor\")\n }\n\n let sep1 = factor1Input.components(separatedBy: \" \")\n let phrase = sep1.dropFirst().joined(separator: \" \")\n\n guard let factor = Int(sep1[0]), factor\u00a0!= 0, !phrase.isEmpty else {\n fatalError(\"Please enter a factor and phrase\")\n }\n\n return (factor, phrase)\n}\n\nlet (factor1, phrase1) = getFactor()\nlet (factor2, phrase2) = getFactor()\nlet (factor3, phrase3) = getFactor()\n\nfor i in 1...maxN {\n let factors = [\n (i.isMultiple(of: factor1), phrase1),\n (i.isMultiple(of: factor2), phrase2),\n (i.isMultiple(of: factor3), phrase3)\n ].filter({ $0.0 }).map({ $0.1 }).joined()\n\n print(\"\\(factors.isEmpty\u00a0? String(i)\u00a0: factors)\")\n}\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":425} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 5\nvar str = \", World\"\nstr = \"Hello\" + str\nprint(str)\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":426} {"lang_cluster":"Swift","source_code":"\nimport Cocoa\n\nvar found = false\nlet randomNum = Int(arc4random_uniform(10) + 1)\n\nprintln(\"Guess a number between 1 and 10\\n\")\nwhile (!found) {\n var fh = NSFileHandle.fileHandleWithStandardInput()\n \n println(\"Enter a number: \")\n let data = fh.availableData\n var str = NSString(data: data, encoding: NSUTF8StringEncoding)\n if (str?.integerValue == randomNum) {\n found = true\n println(\"Well guessed!\")\n }\n}\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":427} {"lang_cluster":"Swift","source_code":"\nvar letters = [Character]()\n\nfor i in 97...122 {\n let char = Character(UnicodeScalar(i))\n letters.append(char)\n}\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":428} {"lang_cluster":"Swift","source_code":"\nfor num in [5, 50, 9000] {\n println(String(num, radix: 2))\n}\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":429} {"lang_cluster":"Swift","source_code":"import Foundation\n\nfunc haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double) -> Double {\n let lat1rad = lat1 * Double.pi\/180\n let lon1rad = lon1 * Double.pi\/180\n let lat2rad = lat2 * Double.pi\/180\n let lon2rad = lon2 * Double.pi\/180\n \n let dLat = lat2rad - lat1rad\n let dLon = lon2rad - lon1rad\n let a = sin(dLat\/2) * sin(dLat\/2) + sin(dLon\/2) * sin(dLon\/2) * cos(lat1rad) * cos(lat2rad)\n let c = 2 * asin(sqrt(a))\n let R = 6372.8\n \n return R * c\n}\n\nprint(haversine(lat1:36.12, lon1:-86.67, lat2:33.94, lon2:-118.40))\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":430} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nlet request = NSURLRequest(URL: NSURL(string: \"http:\/\/rosettacode.org\/\")!)\n\n\/\/ Using trailing closure\nNSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in\n \n \/\/ data is binary\n if (data\u00a0!= nil) {\n let string = NSString(data: data!, encoding: NSUTF8StringEncoding)\n println(string)\n }\n}\n\nCFRunLoopRun() \/\/ dispatch\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":431} {"lang_cluster":"Swift","source_code":"\nfunc luhn(_ number: String) -> Bool {\n return number.reversed().enumerated().map({\n let digit = Int(String($0.element))!\n let even = $0.offset\u00a0% 2 == 0\n return even\u00a0? digit\u00a0: digit == 9\u00a0? 9\u00a0: digit * 2\u00a0% 9\n }).reduce(0, +)\u00a0% 10 == 0\n}\n\nluhn(\"49927398716\") \/\/ true\nluhn(\"49927398717\") \/\/ false\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":432} {"lang_cluster":"Swift","source_code":"\nclass Josephus {\n \n class func lineUp(#numberOfPeople:Int) -> [Int] {\n var people = [Int]()\n for (var i = 0; i < numberOfPeople; i++) {\n people.append(i)\n }\n return people\n }\n \n class func execute(#numberOfPeople:Int, spacing:Int) -> Int {\n var killIndex = 0\n var people = self.lineUp(numberOfPeople: numberOfPeople)\n \n println(\"Prisoners executed in order:\")\n while (people.count > 1) {\n killIndex = (killIndex + spacing - 1) % people.count\n executeAndRemove(&people, killIndex: killIndex)\n }\n println()\n return people[0]\n }\n \n class func executeAndRemove(inout people:[Int], killIndex:Int) {\n print(\"\\(people[killIndex]) \")\n people.removeAtIndex(killIndex)\n }\n\n class func execucteAllButM(#numberOfPeople:Int, spacing:Int, save:Int) -> [Int] {\n var killIndex = 0\n var people = self.lineUp(numberOfPeople: numberOfPeople)\n \n println(\"Prisoners executed in order:\")\n while (people.count > save) {\n killIndex = (killIndex + spacing - 1) % people.count\n executeAndRemove(&people, killIndex: killIndex)\n }\n println()\n return people\n }\n}\n\nprintln(\"Josephus is number: \\(Josephus.execute(numberOfPeople: 41, spacing: 3))\")\nprintln()\nprintln(\"Survivors: \\(Josephus.execucteAllButM(numberOfPeople: 41, spacing: 3, save: 3))\")\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":433} {"lang_cluster":"Swift","source_code":"\nprint(String(repeating:\"*\", count: 5))\n\n","human_summarization":"The code repeats a given string or character a specified number of times. It uses the String.extend() method for faster evaluation and includes an optimized version that uses bit operations and iterative doubling for efficient repetition of larger strings. The efficiency of repeating a single character and a string of one character is almost the same.","id":434} {"lang_cluster":"Swift","source_code":"\n\nimport Foundation\n\nlet str = \"I am a string\"\nif let range = str.rangeOfString(\"string$\", options: .RegularExpressionSearch) {\n println(\"Ends with 'string'\")\n}\n\nimport Foundation\n\nlet orig = \"I am the original string\"\nlet result = orig.stringByReplacingOccurrencesOfString(\"original\", withString: \"modified\", options: .RegularExpressionSearch)\nprintln(result)\n\nimport Foundation\n\nif let regex = NSRegularExpression(pattern: \"string$\", options: nil, error: nil) {\n let str = \"I am a string\"\n if let result = regex.firstMatchInString(str, options: nil, range: NSRange(location: 0, length: count(str.utf16))) {\n println(\"Ends with 'string'\")\n }\n}\n\n for x in regex.matchesInString(str, options: nil, range: NSRange(location: 0, length: count(str.utf16))) {\n let match = x as! NSTextCheckingResult\n \/\/ match.range gives the range of the whole match\n \/\/ match.rangeAtIndex(i) gives the range of the i'th capture group (starting from 1)\n }\n\nimport Foundation\n\nlet orig = \"I am the original string\"\nif let regex = NSRegularExpression(pattern: \"original\", options: nil, error: nil) {\nlet result = regex.stringByReplacingMatchesInString(orig, options: nil, range: NSRange(location: 0, length: count(orig.utf16)), withTemplate: \"modified\")\n println(result)\n}\n","human_summarization":"- Matches a string with a regular expression\n- Loops through matches\n- Substitutes a part of the string using a regular expression\n- Tests the substitution functionality\n- Tests the undocumented substitution functionality.","id":435} {"lang_cluster":"Swift","source_code":"\nlet a = 6 \nlet b = 4\n\nprint(\"sum =\\(a+b)\")\nprint(\"difference = \\(a-b)\")\nprint(\"product = \\(a*b)\")\nprint(\"Integer quotient = \\(a\/b)\")\nprint(\"Remainder = (a%b)\")\nprint(\"No operator for Exponential\")\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":436} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nfunc countSubstring(str: String, substring: String) -> Int {\n return str.components(separatedBy: substring).count - 1\n}\n\nprint(countSubstring(str: \"the three truths\", substring: \"th\"))\nprint(countSubstring(str: \"ababababab\", substring: \"abab\"))\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":437} {"lang_cluster":"Swift","source_code":"func hanoi(n:Int, a:String, b:String, c:String) {\n if (n > 0) {\n hanoi(n - 1, a, c, b)\n println(\"Move disk from \\(a) to \\(c)\")\n hanoi(n - 1, b, a, c)\n }\n}\n\nhanoi(4, \"A\", \"B\", \"C\")\n\nfunc hanoi(n:Int, a:String, b:String, c:String) {\n if (n > 0) {\n hanoi(n - 1, a: a, b: c, c: b)\n print(\"Move disk from \\(a) to \\(c)\")\n hanoi(n - 1, a: b, b: a, c: c)\n }\n}\n \nhanoi(4, a:\"A\", b:\"B\", c:\"C\")\n","human_summarization":"Implement a recursive solution to the Towers of Hanoi problem in Swift 2.1.","id":438} {"lang_cluster":"Swift","source_code":"\nfunc factorial(_ n: T) -> T {\n guard n\u00a0!= 0 else {\n return 1\n }\n\n return stride(from: n, to: 0, by: -1).reduce(1, *)\n}\n\nfunc binomial(_ x: (n: T, k: T)) -> T {\n let nFac = factorial(x.n)\n let kFac = factorial(x.k)\n\n return nFac \/ (factorial(x.n - x.k) * kFac)\n}\n\nprint(\"binomial(\\(5), \\(3)) = \\(binomial((5, 3)))\")\nprint(\"binomial(\\(20), \\(11)) = \\(binomial((20, 11)))\")\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":439} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 2.1\nfunc shellsort(inout seq: [T]) {\n var inc = seq.count \/ 2\n while inc > 0 {\n for (var i, el) in EnumerateSequence(seq) {\n while i >= inc && seq[i - inc] > el {\n seq[i] = seq[i - inc]\n i -= inc\n }\n seq[i] = el\n }\n if inc == 2 {\n inc = 1\n } else {\n inc = inc * 5 \/ 11\n }\n }\n}\n\n\nInput:\nvar data = [22, 7, 2, -5, 8, 4]\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":440} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 3.x+\nvar val = 0\nrepeat {\n val += 1\n print(val)\n} while val\u00a0% 6\u00a0!= 0\nWorks with: Swift version 2.x\nvar val = 0\nrepeat {\n val++\n print(val)\n} while val\u00a0% 6\u00a0!= 0\nWorks with: Swift version 1.x\nvar val = 0\ndo {\n val++\n println(val)\n} while val\u00a0% 6\u00a0!= 0\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":441} {"lang_cluster":"Swift","source_code":"\n\nWorks with: Swift version 2.x\nlet numberOfCharacters = \"m\u00f8\u00f8se\".characters.count \/\/ 5\nWorks with: Swift version 1.2\nlet numberOfCharacters = count(\"m\u00f8\u00f8se\") \/\/ 5\nWorks with: Swift version 1.0-1.1\nlet numberOfCharacters = countElements(\"m\u00f8\u00f8se\") \/\/ 5\n\nWorks with: Swift version 2.x\nlet numberOfCodePoints = \"m\u00f8\u00f8se\".unicodeScalars.count \/\/ 5\nWorks with: Swift version 1.2\nlet numberOfCodePoints = count(\"m\u00f8\u00f8se\".unicodeScalars) \/\/ 5\nWorks with: Swift version 1.0-1.1\nlet numberOfCodePoints = countElements(\"m\u00f8\u00f8se\".unicodeScalars) \/\/ 5\n\nWorks with: Swift version 2.x\nlet numberOfBytesUTF8 = \"m\u00f8\u00f8se\".utf8.count \/\/ 7\nWorks with: Swift version 1.2\nlet numberOfBytesUTF8 = count(\"m\u00f8\u00f8se\".utf8) \/\/ 7\nWorks with: Swift version 1.0-1.1\nlet numberOfBytesUTF8 = countElements(\"m\u00f8\u00f8se\".utf8) \/\/ 7\n\nWorks with: Swift version 2.x\nlet numberOfBytesUTF16 = \"m\u00f8\u00f8se\".utf16.count * 2 \/\/ 10\nWorks with: Swift version 1.2\nlet numberOfBytesUTF16 = count(\"m\u00f8\u00f8se\".utf16) * 2 \/\/ 10\nWorks with: Swift version 1.0-1.1\nlet numberOfBytesUTF16 = countElements(\"m\u00f8\u00f8se\".utf16) * 2 \/\/ 10\n","human_summarization":"determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. It handles Unicode code points, grapheme clusters and non-BMP code points correctly. The code also provides the functionality to count the number of UTF-8 and UTF-16 code units.","id":442} {"lang_cluster":"Swift","source_code":"\n\nlet txt = \"0123456789\"\nprintln(dropFirst(txt))\nprintln(dropLast(txt))\nprintln(dropFirst(dropLast(txt)))\n\n\n","human_summarization":"demonstrate how to remove the first and last characters from a string in Swift. The program works with any valid Unicode code point and references logical characters, not 8-bit or 16-bit code units. The methods used include generic functions from Swift standard library, slicing by range subscripting, mutating the string, and extending String type to define BASIC-style functions. The functions return the characters they remove.","id":443} {"lang_cluster":"Swift","source_code":"\n\nimport Foundation\n\nlet globalCenter = NSDistributedNotificationCenter.defaultCenter()\nlet time = NSDate().timeIntervalSince1970\n\nglobalCenter.addObserverForName(\"OnlyOne\", object: nil, queue: NSOperationQueue.mainQueue()) {not in\n if let senderTime = not.userInfo?[\"time\"] as? NSTimeInterval where senderTime != time {\n println(\"More than one running\")\n exit(0)\n } else {\n println(\"Only one\")\n }\n}\n\nfunc send() {\n globalCenter.postNotificationName(\"OnlyOne\", object: nil, userInfo: [\"time\": time])\n \n let waitTime = dispatch_time(DISPATCH_TIME_NOW, Int64(3 * NSEC_PER_SEC))\n \n dispatch_after(waitTime, dispatch_get_main_queue()) {\n send()\n }\n}\n\nsend()\nCFRunLoopRun()\n\n","human_summarization":"ensure that only one instance of an application is running at a time. If another instance is detected, a message is displayed and the program exits. The code utilizes NSDistributedNotificationCenter and is compatible with Swift 1.2.","id":444} {"lang_cluster":"Swift","source_code":"import Foundation\n\ntypealias SodukuPuzzle = [[Int]]\n\nclass Soduku {\n let mBoardSize:Int!\n let mBoxSize:Int!\n var mBoard:SodukuPuzzle!\n var mRowSubset:[[Bool]]!\n var mColSubset:[[Bool]]!\n var mBoxSubset:[[Bool]]!\n \n init(board:SodukuPuzzle) {\n mBoard = board\n mBoardSize = board.count\n mBoxSize = Int(sqrt(Double(mBoardSize)))\n mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false))\n mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false))\n mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false))\n initSubsets()\n }\n \n func computeBoxNo(i:Int, _ j:Int) -> Int {\n let boxRow = i \/ mBoxSize\n let boxCol = j \/ mBoxSize\n \n return boxRow * mBoxSize + boxCol\n }\n \n func initSubsets() {\n for i in 0.. Bool {\n val--\n let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val]\n return !isPresent\n }\n \n func printBoard() {\n for i in 0.. Bool {\n if i == mBoardSize {\n i = 0\n j++\n if j == mBoardSize {\n return true\n }\n }\n \n if mBoard[i][j] != 0 {\n return solve(i + 1, j)\n }\n \n for value in 1...mBoardSize {\n if isValid(i, j, value) {\n mBoard[i][j] = value\n setSubsetValue(i, j, value, true)\n \n if solve(i + 1, j) {\n return true\n }\n \n setSubsetValue(i, j, value, false)\n }\n }\n \n mBoard[i][j] = 0\n return false\n }\n}\n\nlet board = [\n [4, 0, 0, 0, 0, 0, 0, 6, 0],\n [5, 0, 0, 0, 8, 0, 9, 0, 0],\n [3, 0, 0, 0, 0, 1, 0, 0, 0],\n [0, 2, 0, 7, 0, 0, 0, 0, 1],\n [0, 9, 0, 0, 0, 0, 0, 4, 0],\n [8, 0, 0, 0, 0, 3, 0, 5, 0],\n [0, 0, 0, 2, 0, 0, 0, 0, 7],\n [0, 0, 6, 0, 5, 0, 0, 0, 8],\n [0, 1, 0, 0, 0, 0, 0, 0, 6]\n]\n\nlet puzzle = Soduku(board: board)\npuzzle.solve()\npuzzle.printBoard()\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":445} {"lang_cluster":"Swift","source_code":"\n\nextension BidirectionalCollection where Self: MutableCollection\n{\n\tmutating func shuffleInPlace()\n\t{\n\t\tvar index = self.index(before: self.endIndex)\n\t\twhile index\u00a0!= self.startIndex\n\t\t{\n\t\t\t\/\/ Note the use of ... below. This makes the current element eligible for being selected\n\t\t\tlet randomInt = Int.random(in: 0 ... self.distance(from: startIndex, to: index))\n\t\t\tlet randomIndex = self.index(startIndex, offsetBy: randomInt)\n\t\t\tself.swapAt(index, randomIndex)\n\t\t\tindex = self.index(before: index)\n\t\t}\n\t}\n}\n\nvar a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\na.shuffleInPlace()\nprint(a)\n\n","human_summarization":"Implement the Knuth shuffle algorithm, also known as the Fisher-Yates shuffle, which randomly shuffles the elements of an array. The algorithm works by iterating from the last element of the array down to the first, each time selecting a random element from the untraversed part of the array and swapping it with the current element. The algorithm modifies the input array in-place, but can be adjusted to return a new array if necessary. The code is designed to work with any mutable bidirectional collection in Swift 5.x and above, and can be further generalized to work with any mutable collection with a random-access index type.","id":446} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nfunc lastFridays(of year: Int) -> [Date] {\n\t\n\tlet calendar = Calendar.current\n\tvar dates = [Date]()\n\t\n\tfor month in 2...13 {\n\t\t\n\t\tlet lastDayOfMonth = DateComponents(calendar: calendar,\n\t\t year: year,\n\t\t month: month,\n\t\t day: 0,\n\t\t hour: 12)\n\t\t\n\t\tlet date = calendar.date(from: lastDayOfMonth)!\n\t\t\n\t\tlet isFriday = calendar.component(.weekday, from: date) == 6\n\t\t\n\t\tif isFriday {\n\t\t\t\n\t\t\tdates.append(calendar.date(from: lastDayOfMonth)!)\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\tlet lastWeekofMonth = calendar.ordinality(of: .weekOfMonth,\n\t\t\t in: .month,\n\t\t\t for: date)!\n\t\t\t\n\t\t\tlet lastWithFriday = lastWeekofMonth - (calendar.component(.weekday, from: date) > 6 ? 0 : 1)\n\t\t\t\n\t\t\tlet lastFridayOfMonth = DateComponents(calendar: calendar,\n\t\t\t year: year,\n\t\t\t month: month - 1,\n\t\t\t hour: 12,\n\t\t\t weekday: 6,\n\t\t\t weekOfMonth: lastWithFriday)\n\t\t\t\n\t\t\tdates.append(calendar.date(from: lastFridayOfMonth)!)\n\t\t}\n\t}\n\treturn dates\n}\n\nvar dateFormatter = DateFormatter()\ndateFormatter.dateStyle = .short\n\nprint(lastFridays(of: 2013).map(dateFormatter.string).joined(separator: \"\\n\"))\n\n1\/27\/12\n2\/24\/12\n3\/30\/12\n4\/27\/12\n5\/25\/12\n6\/29\/12\n7\/27\/12\n8\/31\/12\n9\/28\/12\n10\/26\/12\n11\/30\/12\n12\/28\/12\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":447} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 2.x+\nprint(\"Goodbye, World!\", terminator: \"\")\nWorks with: Swift version 1.x\nprint(\"Goodbye, World!\")\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":448} {"lang_cluster":"Swift","source_code":"\nfunc usage(_ e:String) {\n print(\"error: \\(e)\")\n print(\".\/caeser -e 19 a-secret-string\")\n print(\".\/caeser -d 19 tskxvjxlskljafz\")\n}\n\nfunc charIsValid(_ c:Character) -> Bool {\n return c.isASCII && ( c.isLowercase || 45 == c.asciiValue ) \/\/ '-' = 45\n}\n\nfunc charRotate(_ c:Character, _ by:Int) -> Character {\n var cv:UInt8! = c.asciiValue\n if 45 == cv { cv = 96 } \/\/ if '-', set it to 'a'-1\n cv += UInt8(by)\n if 122 < cv { cv -= 27 } \/\/ if larget than 'z', reduce by 27\n if 96 == cv { cv = 45 } \/\/ restore '-'\n return Character(UnicodeScalar(cv))\n}\n\nfunc caesar(_ enc:Bool, _ key:Int, _ word:String) -> String {\n let r = enc\u00a0? key\u00a0: 27 - key\n func charRotateWithKey(_ c:Character) -> Character {\n return charRotate(c,r)\n }\n return String(word.map(charRotateWithKey))\n}\n\nfunc main() {\n var encrypt = true\n\n if 4\u00a0!= CommandLine.arguments.count {\n return usage(\"caesar expects exactly three arguments\")\n }\n\n switch ( CommandLine.arguments[1] ) {\n case \"-e\":\n encrypt = true\n case \"-d\":\n encrypt = false\n default:\n return usage(\"first argument must be -e (encrypt) or -d (decrypt)\")\n }\n\n guard let key = Int(CommandLine.arguments[2]) else {\n return usage(\"second argument not a number (must be in range 0-26)\")\n }\n\n if key < 0 || 26 < key {\n return usage(\"second argument not in range 0-26\")\n }\n\n if !CommandLine.arguments[3].allSatisfy(charIsValid) {\n return usage(\"third argument must only be lowercase ascii characters, or -\")\n }\n\n let ans = caesar(encrypt,key,CommandLine.arguments[3])\n print(\"\\(ans)\")\n}\n\nfunc test() {\n if ( Character(\"a\")\u00a0!= charRotate(Character(\"a\"),0) ) {\n print(\"Test Fail 1\")\n }\n if ( Character(\"-\")\u00a0!= charRotate(Character(\"-\"),0) ) {\n print(\"Test Fail 2\")\n }\n if ( Character(\"-\")\u00a0!= charRotate(Character(\"z\"),1) ) {\n print(\"Test Fail 3\")\n }\n if ( Character(\"z\")\u00a0!= charRotate(Character(\"-\"),26)) {\n print(\"Test Fail 4\")\n }\n if ( \"ihgmkzma\"\u00a0!= caesar(true,8,\"a-zecret\") ) {\n print(\"Test Fail 5\")\n }\n if ( \"a-zecret\"\u00a0!= caesar(false,8,\"ihgmkzma\") ) {\n print(\"Test Fail 6\")\n }\n}\n\ntest()\nmain()\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":449} {"lang_cluster":"Swift","source_code":"\n\nfunc lcm(a:Int, b:Int) -> Int {\n return abs(a * b) \/ gcd_rec(a, b)\n}\n\n","human_summarization":"The code calculates the least common multiple (LCM) of two integers, m and n. It identifies the smallest positive integer that is a factor of both m and n. If either m or n is zero, the LCM is zero. The code can calculate the LCM by iterating all multiples of m until it finds one that is also a multiple of n, or by using the formula lcm(m, n) = |m x n|\/gcd(m, n), where gcd is the greatest common divisor. Additionally, the code can find the LCM by merging the prime decompositions of both m and n. This code uses the Swift GCD function.","id":450} {"lang_cluster":"Swift","source_code":"\nstruct CUSIP {\n var value: String\n\n private static let alphabet = Array(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\n init?(value: String) {\n if value.count == 9 && String(value.last!) == CUSIP.checkDigit(cusipString: String(value.dropLast())) {\n self.value = value\n } else if value.count == 8, let checkDigit = CUSIP.checkDigit(cusipString: value) {\n self.value = value + checkDigit\n } else {\n return nil\n }\n }\n\n static func checkDigit(cusipString: String) -> String? {\n guard cusipString.count == 8, cusipString.allSatisfy({ $0.isASCII }) else {\n return nil\n }\n\n let sum = cusipString.uppercased().enumerated().reduce(0, {sum, pair in\n let (i, char) = pair\n var v: Int\n\n switch char {\n case \"*\":\n v = 36\n case \"@\":\n v = 37\n case \"#\":\n v = 38\n case _ where char.isNumber:\n v = char.wholeNumberValue!\n case _:\n v = Int(char.asciiValue! - 65) + 10\n }\n\n if i & 1 == 1 {\n v *= 2\n }\n\n return sum + (v \/ 10) + (v % 10)\n })\n\n return String((10 - (sum % 10)) % 10)\n }\n}\n\nlet testCases = [\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n]\n\nfor potentialCUSIP in testCases {\n print(\"\\(potentialCUSIP) -> \", terminator: \"\")\n\n switch CUSIP(value: potentialCUSIP) {\n case nil:\n print(\"Invalid\")\n case _:\n print(\"Valid\")\n }\n}\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":451} {"lang_cluster":"Swift","source_code":"\nfor i in [1,2,3] {\n print(i)\n}\n\nWorks with: Swift version 2.x+\n[1,2,3].forEach {\n print($0)\n}\n","human_summarization":"Iterates through and prints each element in a collection in order using a \"for each\" loop or an alternative loop if \"for each\" is not available. The code is applicable to any type that conforms to the SequenceType protocol, including arrays, collections, generators, and ranges.","id":452} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 3.x\nlet text = \"Hello,How,Are,You,Today\"\nlet tokens = text.components(separatedBy: \",\") \/\/ for single or multi-character separator\nprint(tokens)\nlet result = tokens.joined(separator: \".\")\nprint(result)\nWorks with: Swift version 2.x\nlet text = \"Hello,How,Are,You,Today\"\nlet tokens = text.characters.split(\",\").map{String($0)} \/\/ for single-character separator\nprint(tokens)\nlet result = tokens.joinWithSeparator(\".\")\nprint(result)\nWorks with: Swift version 1.x\nlet text = \"Hello,How,Are,You,Today\"\nlet tokens = split(text, { $0 == \",\" }) \/\/ for single-character separator\nprintln(tokens)\nlet result = \".\".join(tokens)\nprintln(result)\nFor multi-character separators:import Foundation\n\nlet text = \"Hello,How,Are,You,Today\"\nlet tokens = text.componentsSeparatedByString(\",\")\nprint(tokens)\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":453} {"lang_cluster":"Swift","source_code":"\n\/\/ Iterative\n\nfunc gcd(a: Int, b: Int) -> Int {\n \n var a = abs(a)\n var b = abs(b)\n \n if (b > a) { swap(&a, &b) }\n\n while (b > 0) { (a, b) = (b, a\u00a0% b) }\n \n return a\n}\n\n\/\/ Recursive\n\nfunc gcdr (a: Int, b: Int) -> Int {\n \n var a = abs(a)\n var b = abs(b)\n\n if (b > a) { swap(&a, &b) }\n \n return gcd_rec(a,b)\n}\n\n\nprivate func gcd_rec(a: Int, b: Int) -> Int {\n \n return b == 0\u00a0? a\u00a0: gcd_rec(b, a\u00a0% b)\n}\n\n\nfor (a,b) in [(1,1), (100, -10), (10, -100), (-36, -17), (27, 18), (30, -42)] {\n \n println(\"Iterative: GCD of \\(a) and \\(b) is \\(gcd(a, b))\")\n println(\"Recursive: GCD of \\(a) and \\(b) is \\(gcdr(a, b))\")\n}\n\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":454} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 2.x+\nfunc isNumeric(a: String) -> Bool {\n return Double(a)\u00a0!= nil\n}\nWorks with: Swift version 1.x\n\nfunc isNumeric(a: String) -> Bool {\n return a.toInt()\u00a0!= nil\n}\n","human_summarization":"\"Create a function that checks if a given string can be interpreted as a numeric value, including floating point and negative numbers.\"","id":455} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\n\/\/ With https\nlet request = NSURLRequest(URL: NSURL(string: \"https:\/\/sourceforge.net\")!)\n\nNSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {res, data, err in \/\/ callback\n \n \/\/ data is binary\n if (data != nil) {\n let string = NSString(data: data!, encoding: NSUTF8StringEncoding)\n println(string)\n }\n}\n\nCFRunLoopRun() \/\/ dispatch\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":456} {"lang_cluster":"Swift","source_code":"struct Point {\n var x: Double\n var y: Double\n}\n\nstruct Polygon {\n var points: [Point]\n\n init(points: [Point]) {\n self.points = points\n }\n\n init(points: [(Double, Double)]) {\n self.init(points: points.map({ Point(x: $0.0, y: $0.1) }))\n }\n}\n\nfunc isInside(_ p1: Point, _ p2: Point, _ p3: Point) -> Bool {\n (p3.x - p2.x) * (p1.y - p2.y) > (p3.y - p2.y) * (p1.x - p2.x)\n}\n\nfunc computeIntersection(_ p1: Point, _ p2: Point, _ s: Point, _ e: Point) -> Point {\n let dc = Point(x: p1.x - p2.x, y: p1.y - p2.y)\n let dp = Point(x: s.x - e.x, y: s.y - e.y)\n let n1 = p1.x * p2.y - p1.y * p2.x\n let n2 = s.x * e.y - s.y * e.x\n let n3 = 1.0 \/ (dc.x * dp.y - dc.y * dp.x)\n\n return Point(x: (n1 * dp.x - n2 * dc.x) * n3, y: (n1 * dp.y - n2 * dc.y) * n3)\n}\n\nfunc sutherlandHodgmanClip(subjPoly: Polygon, clipPoly: Polygon) -> Polygon {\n var ring = subjPoly.points\n var p1 = clipPoly.points.last!\n\n for p2 in clipPoly.points {\n let input = ring\n var s = input.last!\n\n ring = []\n\n for e in input {\n if isInside(e, p1, p2) {\n if !isInside(s, p1, p2) {\n ring.append(computeIntersection(p1, p2, s, e))\n }\n\n ring.append(e)\n } else if isInside(s, p1, p2) {\n ring.append(computeIntersection(p1, p2, s, e))\n }\n\n s = e\n }\n\n p1 = p2\n }\n\n return Polygon(points: ring)\n}\n\nlet subj = Polygon(points: [\n (50.0, 150.0),\n (200.0, 50.0),\n (350.0, 150.0),\n (350.0, 300.0),\n (250.0, 300.0),\n (200.0, 250.0),\n (150.0, 350.0),\n (100.0, 250.0),\n (100.0, 200.0)\n])\n\nlet clip = Polygon(points: [\n (100.0, 100.0),\n (300.0, 100.0),\n (300.0, 300.0),\n (100.0, 300.0)\n])\n\nprint(sutherlandHodgmanClip(subjPoly: subj, clipPoly: clip))\n\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":457} {"lang_cluster":"Swift","source_code":"public struct KnapsackItem: Hashable {\n public var name: String\n public var weight: Int\n public var value: Int\n\n public init(name: String, weight: Int, value: Int) {\n self.name = name\n self.weight = weight\n self.value = value\n }\n}\n\npublic func knapsack(items: [KnapsackItem], limit: Int) -> [KnapsackItem] {\n var table = Array(repeating: Array(repeating: 0, count: limit + 1), count: items.count + 1)\n\n for j in 1...items.count {\n let item = items[j-1]\n\n for w in 1...limit {\n if item.weight > w {\n table[j][w] = table[j-1][w]\n } else {\n table[j][w] = max(table[j-1][w], table[j-1][w-item.weight] + item.value)\n }\n }\n }\n\n var result = [KnapsackItem]()\n var w = limit\n\n for j in stride(from: items.count, to: 0, by: -1) where table[j][w] != table[j-1][w] {\n let item = items[j-1]\n\n result.append(item)\n\n w -= item.weight\n }\n\n return result\n}\n\ntypealias GroupedItem = (name: String, weight: Int, val: Int, n: Int)\n\nlet groupedItems: [GroupedItem] = [\n (\"map\", 9, 150, 1),\n (\"compass\", 13, 35, 1),\n (\"water\", 153, 200, 3),\n (\"sandwich\", 50, 60, 2),\n (\"glucose\", 15, 60, 2),\n (\"tin\", 68, 45, 3),\n (\"banana\", 27, 60, 3),\n (\"apple\", 39, 40, 3),\n (\"cheese\", 23, 30, 1),\n (\"beer\", 52, 10, 3),\n (\"suntan cream\", 11, 70, 1),\n (\"camera\", 32, 30, 1),\n (\"t-shirt\", 24, 15, 2),\n (\"trousers\", 48, 10, 2),\n (\"umbrella\", 73, 40, 1),\n (\"waterproof trousers\", 42, 70, 1),\n (\"waterproof overclothes\", 43, 75, 1),\n (\"note-case\", 22, 80, 1),\n (\"sunglasses\", 7, 20, 1),\n (\"towel\", 18, 12, 2),\n (\"socks\", 4, 50, 1),\n (\"book\", 30, 10, 2)\n]\n\nlet items = groupedItems.flatMap({item in\n (0.. String? {\n var common:String = text[0]\n for i in text {\n common = i.commonPrefix(with: common)\n }\n return common\n}\n\nvar test = [\"\/home\/user1\/tmp\/coverage\/test\", \n \"\/home\/user1\/tmp\/covert\/operator\",\n \"\/home\/user1\/tmp\/coven\/members\"]\n\nvar output:String = getPrefix(test)!\nprint(output)\n\n","human_summarization":"The code creates a function that identifies and returns the common directory path from a given set of directory paths, using a specified directory separator. It is tested using the forward slash as the directory separator and three specific string paths as input. The function ensures the returned path is a valid directory, not just the longest common string. It's designed to work specifically in Swift on Linux.","id":461} {"lang_cluster":"Swift","source_code":"\nextension Array {\n public mutating func satalloShuffle() {\n for i in stride(from: index(before: endIndex), through: 1, by: -1) {\n swapAt(i, .random(in: 0.. [Element] {\n var arr = Array(self)\n\n arr.satalloShuffle()\n\n return arr\n }\n}\n\nlet testCases = [\n [],\n [10, 20],\n [10, 20, 30],\n [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]\n]\n\nfor testCase in testCases {\n let shuffled = testCase.satalloShuffled()\n\n guard zip(testCase, shuffled).allSatisfy(!=) else {\n fatalError(\"satallo shuffle failed\")\n }\n\n print(\"\\(testCase) shuffled = \\(shuffled)\")\n}\n\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":462} {"lang_cluster":"Swift","source_code":"\nfor i in 1...100 {\n switch (i\u00a0% 3, i\u00a0% 5) {\n case (0, 0):\n print(\"FizzBuzz\")\n case (0, _):\n print(\"Fizz\")\n case (_, 0):\n print(\"Buzz\")\n default:\n print(i)\n }\n}\nfor i in 1...100{\n var s:String?\n if i%3==0{s=\"Fizz\"}\n if i%5==0{s=(s\u00a0?? \"\")+\"Buzz\"}\n print(s\u00a0?? i)\n}\nimport Foundation\n\nlet formats: [String] = [\n \"%d\",\n \"%d\",\n \"fizz\",\n \"%d\",\n \"buzz\",\n \"fizz\",\n \"%d\",\n \"%d\",\n \"fizz\",\n \"buzz\",\n \"%d\",\n \"fizz\",\n \"%d\",\n \"%d\",\n \"fizzbuzz\",\n]\n\nvar count = 0\nvar index = 0\nwhile count < 100 {\n count += 1\n print(String(format: formats[index], count))\n index += 1\n index\u00a0%= 15\n}\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":463} {"lang_cluster":"Swift","source_code":"\n\nimport Foundation\nimport Numerics\nimport QDBMP\n\npublic typealias Color = (red: UInt8, green: UInt8, blue: UInt8)\n\npublic class BitmapDrawer {\n public let imageHeight: Int\n public let imageWidth: Int\n\n var grid: [[Color?]]\n\n private let bmp: OpaquePointer\n\n public init(height: Int, width: Int) {\n self.imageHeight = height\n self.imageWidth = width\n self.grid = [[Color?]](repeating: [Color?](repeating: nil, count: height), count: width)\n self.bmp = BMP_Create(UInt(width), UInt(height), 24)\n\n checkError()\n }\n\n deinit {\n BMP_Free(bmp)\n }\n\n private func checkError() {\n let err = BMP_GetError()\n\n guard err == BMP_STATUS(0) else {\n fatalError(\"\\(err)\")\n }\n }\n\n public func save(to path: String = \"~\/Desktop\/out.bmp\") {\n for x in 0.. 2 {\n break\n }\n\n z = z * z + c\n i = t\n }\n\n canvas.setPixel(x: x, y: y, to: Color(red: UInt8(i), green: UInt8(i), blue: UInt8(i)))\n }\n}\n\ncanvas.save()\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions, utilizing the Swift Numerics package and the Quick 'N Dirty BMP C library imported in Swift.","id":464} {"lang_cluster":"Swift","source_code":"\nlet a = [1, 2, 3, 4, 5]\nprintln(a.reduce(0, +)) \/\/ prints 15\nprintln(a.reduce(1, *)) \/\/ prints 120\n\nprintln(reduce(a, 0, +)) \/\/ prints 15\nprintln(reduce(a, 1, *)) \/\/ prints 120\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":465} {"lang_cluster":"Swift","source_code":"\nfunc isLeapYear(year: Int) -> Bool {\n return year.isMultiple(of: 100)\u00a0? year.isMultiple(of: 400)\u00a0: year.isMultiple(of: 4)\n}\n\n[1900, 1994, 1996, 1997, 2000].forEach { year in\n print(\"\\(year): \\(isLeapYear(year: year)\u00a0? \"YES\"\u00a0: \"NO\")\")\n}\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":466} {"lang_cluster":"Swift","source_code":"\n\n import Foundation\n public class MD5 {\n \/** specifies the per-round shift amounts *\/\n private let s: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]\n \n \/** binary integer part of the sines of integers (Radians) *\/\n private let K: [UInt32] = (0 ..< 64).map { UInt32(0x100000000 * abs(sin(Double($0 + 1)))) }\n \n let a0: UInt32 = 0x67452301\n let b0: UInt32 = 0xefcdab89\n let c0: UInt32 = 0x98badcfe\n let d0: UInt32 = 0x10325476\n \n private var message: NSData\n \n \/\/MARK: Public\n \n public init(_ message: NSData) {\n self.message = message\n }\n \n public func calculate() -> NSData? {\n var tmpMessage: NSMutableData = NSMutableData(data: message)\n let wordSize = sizeof(UInt32)\n \n var aa = a0\n var bb = b0\n var cc = c0\n var dd = d0\n \n \/\/ Step 1. Append Padding Bits\n tmpMessage.appendBytes([0x80]) \/\/ append one bit (Byte with one bit) to message\n \n \/\/ append \"0\" bit until message length in bits \u2261 448 (mod 512)\n while tmpMessage.length % 64 != 56 {\n tmpMessage.appendBytes([0x00])\n }\n \n \/\/ Step 2. Append Length a 64-bit representation of lengthInBits\n var lengthInBits = (message.length * 8)\n var lengthBytes = lengthInBits.bytes(64 \/ 8)\n tmpMessage.appendBytes(reverse(lengthBytes));\n \n \/\/ Process the message in successive 512-bit chunks:\n let chunkSizeBytes = 512 \/ 8\n var leftMessageBytes = tmpMessage.length\n for var i = 0; i < tmpMessage.length; i = i + chunkSizeBytes, leftMessageBytes -= chunkSizeBytes {\n let chunk = tmpMessage.subdataWithRange(NSRange(location: i, length: min(chunkSizeBytes,leftMessageBytes)))\n \n \/\/ break chunk into sixteen 32-bit words M[j], 0 \u2264 j \u2264 15\n \/\/ println(\"wordSize \\(wordSize)\");\n var M:[UInt32] = [UInt32](count: 16, repeatedValue: 0)\n for x in 0.. NSData?\n {\n return MD5(message).calculate();\n }\n \n \/\/MARK: Private\n private func rotateLeft(x:UInt32, _ n:UInt32) -> UInt32 {\n return (x &<< n) | (x &>> (32 - n))\n }\n }\n\n\nimport Foundation\n\nlet shift : [UInt32] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21]\nlet table: [UInt32] = (0 ..< 64).map { UInt32(0x100000000 * abs(sin(Double($0 + 1)))) }\n\nfunc md5(var message: [UInt8]) -> [UInt8] {\n var messageLenBits = UInt64(message.count) * 8\n message.append(0x80)\n while message.count % 64 != 56 {\n message.append(0)\n }\n \n var lengthBytes = [UInt8](count: 8, repeatedValue: 0)\n UnsafeMutablePointer(lengthBytes).memory = messageLenBits.littleEndian\n message += lengthBytes\n \n var a : UInt32 = 0x67452301\n var b : UInt32 = 0xEFCDAB89\n var c : UInt32 = 0x98BADCFE\n var d : UInt32 = 0x10325476\n for chunkOffset in stride(from: 0, to: message.count, by: 64) {\n let chunk = UnsafePointer(UnsafePointer(message) + chunkOffset)\n let originalA = a\n let originalB = b\n let originalC = c\n let originalD = d\n for j in 0 ..< 64 {\n var f : UInt32 = 0\n var bufferIndex = j\n let round = j >> 4\n switch round {\n case 0:\n f = (b & c) | (~b & d)\n case 1:\n f = (b & d) | (c & ~d)\n bufferIndex = (bufferIndex*5 + 1) & 0x0F\n case 2:\n f = b ^ c ^ d\n bufferIndex = (bufferIndex*3 + 5) & 0x0F\n case 3:\n f = c ^ (b | ~d)\n bufferIndex = (bufferIndex * 7) & 0x0F\n default:\n assert(false)\n }\n let sa = shift[(round<<2)|(j&3)]\n let tmp = a &+ f &+ UInt32(littleEndian: chunk[bufferIndex]) &+ table[j]\n a = d\n d = c\n c = b\n b = b &+ (tmp << sa | tmp >> (32-sa))\n }\n a = a &+ originalA\n b = b &+ originalB\n c = c &+ originalC\n d = d &+ originalD\n }\n \n var result = [UInt8](count: 16, repeatedValue: 0)\n for (i, n) in enumerate([a, b, c, d]) {\n UnsafeMutablePointer(result)[i] = n.littleEndian\n }\n return result\n}\n\nfunc toHexString(bytes: [UInt8]) -> String {\n return \"\".join(bytes.map { String(format:\"%02x\", $0) })\n}\n\nfor (hashCode, string) in [\n (\"d41d8cd98f00b204e9800998ecf8427e\", \"\"),\n (\"0cc175b9c0f1b6a831c399e269772661\", \"a\"),\n (\"900150983cd24fb0d6963f7d28e17f72\", \"abc\"),\n (\"f96b697d7cb7938d525a2f31aaf161d0\", \"message digest\"),\n (\"c3fcd3d76192e4007dfb496cca67e13b\", \"abcdefghijklmnopqrstuvwxyz\"),\n (\"d174ab98d277d9f5a5611c2c9f419d9f\",\n \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"),\n (\"57edf4a22be3c955ac49da2e2107b67a\", \"12345678901234567890\" +\n \"123456789012345678901234567890123456789012345678901234567890\")] {\n println(hashCode)\n println(toHexString(md5(Array(string.utf8))))\n println()\n}\n\n\n","human_summarization":"The code is a direct implementation of the MD5 Message Digest Algorithm, which generates a correct message digest for an input string without using any built-in or external hashing libraries. The implementation does not mimic all calling modes, but focuses on key functionality. It also includes notes on challenges, implementation choices, and limitations. The code provides practical examples of bit manipulation, working with little-endian data, and handling boundary conditions. It also includes verification strings and hashes from RFC 1321 for validation. The implementation is based on the pseudo-code from the Wikipedia article and does not rely on any external libraries.","id":467} {"lang_cluster":"Swift","source_code":"\n\nlet res = [2, 4, 6].map({x in\n return (1...7)\n .filter({ $0 != x })\n .map({y -> (Int, Int, Int)? in\n let z = 12 - (x + y)\n\n guard y != z && 1 <= z && z <= 7 else {\n return nil\n }\n\n return (x, y, z)\n }).compactMap({ $0 })\n}).flatMap({ $0 })\n\nfor result in res {\n print(result)\n}\n\n\nvar res = [(Int, Int, Int)]()\n\nfor x in [2, 4, 6] {\n for y in 1...7 where x != y {\n let z = 12 - (x + y)\n\n guard y != z && 1 <= z && z <= 7 else {\n continue\n }\n\n res.append((x, y, z))\n }\n}\n\nfor result in res {\n print(result)\n}\n\n\n","human_summarization":"The code generates all valid combinations of numbers between 1 and 7 (inclusive) for the police, sanitation, and fire departments in a city. The numbers for each department are unique and add up to 12. The police department number is always even.","id":468} {"lang_cluster":"Swift","source_code":"\n\nvar src = \"Hello\"\nvar dst = src\n\n","human_summarization":"demonstrate how to copy a string in Swift by assigning its value, highlighting the difference between copying the string's content and creating an additional reference to the existing string.","id":469} {"lang_cluster":"Swift","source_code":"\n\nfunc F(n: Int) -> Int {\n return n == 0\u00a0? 1\u00a0: n - M(F(n-1))\n}\n\nfunc M(n: Int) -> Int {\n return n == 0\u00a0? 0\u00a0: n - F(M(n-1))\n}\n\nfor i in 0..20 {\n print(\"\\(F(i)) \")\n}\nprintln()\nfor i in 0..20 {\n print(\"\\(M(i)) \")\n}\nprintln()\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions use each other to calculate the sequence values based on the given formulas. If the programming language does not support mutual recursion, this is stated explicitly. No special pre-declaration is required for the functions.","id":470} {"lang_cluster":"Swift","source_code":"\nimport Darwin\n\nlet myList = [1, 2, 4, 5, 62, 234, 1, -1]\nprint(myList[Int(arc4random_uniform(UInt32(myList.count)))])\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":471} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nlet encoded = \"http%3A%2F%2Ffoo%20bar%2F\"\nif let normal = encoded.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {\n println(normal)\n}\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":472} {"lang_cluster":"Swift","source_code":"\n\nfunc binarySearch(xs: [T], x: T) -> Int? {\n var recurse: ((Int, Int) -> Int?)!\n recurse = {(low, high) in switch (low + high) \/ 2 {\n case _ where high < low: return nil\n case let mid where xs[mid] > x: return recurse(low, mid - 1)\n case let mid where xs[mid] < x: return recurse(mid + 1, high)\n case let mid: return mid\n }}\n return recurse(0, xs.count - 1)\n}\n\nfunc binarySearch(xs: [T], x: T) -> Int? {\n var (low, high) = (0, xs.count - 1)\n while low <= high {\n switch (low + high) \/ 2 {\n case let mid where xs[mid] > x: high = mid - 1\n case let mid where xs[mid] < x: low = mid + 1\n case let mid: return mid\n }\n }\n return nil\n}\n\nfunc testBinarySearch(n: Int) {\n let odds = Array(stride(from: 1, through: n, by: 2))\n let result = flatMap(0...n) {binarySearch(odds, $0)}\n assert(result == Array(0..(source: [T], transform: (T) -> U?) -> [U] {\n return source.reduce([]) {(var xs, x) in if let x = transform(x) {xs.append(x)}; return xs}\n}\n\n[1, 3, 5, 7, 9, 11] are odd natural numbers\n0 is ordinal of 1\n1 is ordinal of 3\n2 is ordinal of 5\n3 is ordinal of 7\n4 is ordinal of 9\n5 is ordinal of 11\n","human_summarization":"The code implements a binary search algorithm to find a specific number in a sorted integer array. It takes the starting and ending points of a range, and a secret value as inputs. The search can be performed both recursively and iteratively. The code also handles multiple values equal to the given value and returns the index of the found element. If the element is not found, it returns the insertion point. The code also includes variations of the algorithm that return the leftmost and rightmost insertion points. It also ensures there are no overflow bugs when calculating the midpoint of the range.","id":473} {"lang_cluster":"Swift","source_code":"\nlet args = Process.arguments\nprintln(\"This program is named \\(args[0]).\")\nprintln(\"There are \\(args.count-1) arguments.\")\nfor i in 1.. Self {\n var res = Self(1)\n\n for _ in 0.. Self {\n var d = Self(0)\n var res = Self(1)\n\n guard self != 0 else {\n return 0\n }\n\n guard n >= 1 else {\n return .nan\n }\n\n repeat {\n d = (self \/ res.power(n - 1) - res) \/ Self(n)\n res += d\n } while d >= epsilon * 10 || d <= -epsilon * 10\n\n return res\n }\n}\n\nprint(81.root(n: 4))\nprint(13.root(n: 5))\n\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":476} {"lang_cluster":"Swift","source_code":"\n\nprint(ProcessInfo.processInfo.hostName)\n","human_summarization":"\"Determines and returns the hostname of the system where the Swift 3 program is running.\"","id":477} {"lang_cluster":"Swift","source_code":"\nstruct Leonardo: Sequence, IteratorProtocol {\n private let add : Int\n private var n0: Int\n private var n1: Int\n \n init(n0: Int = 1, n1: Int = 1, add: Int = 1) {\n self.n0 = n0\n self.n1 = n1\n self.add = add\n }\n \n mutating func next() -> Int? {\n let n = n0\n n0 = n1\n n1 += n + add\n return n\n }\n}\n\nprint(\"First 25 Leonardo numbers:\")\nprint(Leonardo().prefix(25).map{String($0)}.joined(separator: \" \"))\n\nprint(\"First 25 Fibonacci numbers:\")\nprint(Leonardo(n0: 0, add: 0).prefix(25).map{String($0)}.joined(separator: \" \"))\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":478} {"lang_cluster":"Swift","source_code":"\nimport Darwin\nimport Foundation\n\nprintln(\"24 Game\")\nprintln(\"Generating 4 digits...\")\n\nfunc randomDigits() -> Int[] {\n var result = Int[]();\n for var i = 0; i < 4; i++ {\n result.append(Int(arc4random_uniform(9)+1))\n }\n return result;\n}\n\n\/\/ Choose 4 digits\nlet digits = randomDigits()\n\nprint(\"Make 24 using these digits\u00a0: \")\n\nfor digit in digits {\n print(\"\\(digit) \")\n}\nprintln()\n\n\/\/ get input from operator\nvar input = NSString(data:NSFileHandle.fileHandleWithStandardInput().availableData, encoding:NSUTF8StringEncoding)\n\nvar enteredDigits = Int[]()\n\nvar enteredOperations = Character[]()\n\nlet inputString = input as String\n\n\/\/ store input in the appropriate table\nfor character in inputString {\n switch character {\n case \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\":\n let digit = String(character)\n enteredDigits.append(digit.toInt()!)\n case \"+\", \"-\", \"*\", \"\/\":\n enteredOperations.append(character)\n case \"\\n\":\n println()\n default:\n println(\"Invalid expression\")\n }\n}\n\n\/\/ check value of expression provided by the operator\nvar value = Int()\n\nif enteredDigits.count == 4 && enteredOperations.count == 3 {\n value = enteredDigits[0]\n for (i, operation) in enumerate(enteredOperations) {\n switch operation {\n case \"+\":\n value = value + enteredDigits[i+1]\n case \"-\":\n value = value - enteredDigits[i+1]\n case \"*\":\n value = value * enteredDigits[i+1]\n case \"\/\":\n value = value \/ enteredDigits[i+1]\n default:\n println(\"This message should never happen!\")\n }\n }\n}\n\nif value != 24 {\n println(\"The value of the provided expression is \\(value) instead of 24!\")\n} else {\n println(\"Congratulations, you found a solution!\")\n}\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":479} {"lang_cluster":"Swift","source_code":"\n\nimport Foundation\n\n\/\/ \"WWWBWW\" -> [(3, W), (1, B), (2, W)]\nfunc encode(input: String) -> [(Int, Character)] {\n return input.characters.reduce([(Int, Character)]()) {\n if $0.last?.1 == $1 { var r = $0; r[r.count - 1].0++; return r }\n return $0 + [(1, $1)]\n }\n}\n\n\/\/ [(3, W), (1, B), (2, W)] -> \"WWWBWW\"\nfunc decode(encoded: [(Int, Character)]) -> String {\n return encoded.reduce(\"\") { $0 + String(count: $1.0, repeatedValue: $1.1) }\n}\n\nlet input = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\nlet output = decode(encode(input))\nprint(output == input)\n\n","human_summarization":"\"Implement a run-length encoding function that compresses a string of uppercase characters by storing the length of repeated characters. Also, provide a function to reverse the compression. The output can be any format that can be used to recreate the original input. An example of this is converting 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' to '12W1B12W3B24W1B14W'. The function also includes the ability to convert the encoded array back into the string using NSScanner.\"","id":480} {"lang_cluster":"Swift","source_code":"\nlet s = \"hello\"\nprintln(s + \" literal\")\nlet s1 = s + \" literal\"\nprintln(s1)\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":481} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift 2.0\nimport Foundation\n\nlet wordsURL = NSURL(string: \"http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt\")!\n\nlet wordsstring = try NSString(contentsOfURL:wordsURL , encoding: NSUTF8StringEncoding)\nlet allwords = wordsstring.componentsSeparatedByString(\"\\n\")\n\nlet words = allwords\/\/[0..<100] \/\/ used to limit the size while testing\n\nextension String {\n var charactersAscending\u00a0: String {\n return String(Array(characters).sort())\n }\n}\n\nvar charsToWords = [String:Set]()\n\nvar biggest = 0\nvar biggestlists = [Set]()\n\nfor thisword in words {\n let chars = thisword.charactersAscending\n \n var knownwords = charsToWords[chars]\u00a0?? Set()\n knownwords.insert(thisword)\n charsToWords[chars] = knownwords\n\n if knownwords.count > biggest {\n biggest = knownwords.count\n\n biggestlists = [knownwords]\n }\n else if knownwords.count == biggest {\n biggestlists.append(knownwords)\n }\n}\n\nprint(\"Found \\(biggestlists.count) sets of anagrams with \\(biggest) members each\")\nfor (i, thislist) in biggestlists.enumerate() {\n print(\"set \\(i): \\(thislist.sort())\")\n}\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":482} {"lang_cluster":"Swift","source_code":"import Foundation\nfunc sierpinski_carpet(n:Int) -> String {\n func middle(str:String) -> String {\n let spacer = str.stringByReplacingOccurrencesOfString(\"#\", withString:\" \", options:nil, range:nil)\n return str + spacer + str\n }\n \n var carpet = [\"#\"]\n for i in 1...n {\n let a = carpet.map{$0 + $0 + $0}\n let b = carpet.map(middle)\n carpet = a + b + a\n }\n return \"\\n\".join(carpet)\n}\n\nprintln(sierpinski_carpet(3))\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":483} {"lang_cluster":"Swift","source_code":"\n\nWorks with: Swift version 2+\nenum HuffmanTree {\n case Leaf(T)\n indirect case Node(HuffmanTree, HuffmanTree)\n \n func printCodes(prefix: String) {\n switch(self) {\n case let .Leaf(c):\n print(\"\\(c)\\t\\(prefix)\")\n case let .Node(l, r):\n l.printCodes(prefix + \"0\")\n r.printCodes(prefix + \"1\")\n }\n }\n}\n\nfunc buildTree(freqs: [(T, Int)]) -> HuffmanTree {\n assert(freqs.count > 0, \"must contain at least one character\")\n \/\/ leaves sorted by increasing frequency\n let leaves : [(Int, HuffmanTree)] = freqs.sort { (p1, p2) in p1.1 < p2.1 }.map { (x, w) in (w, .Leaf(x)) }\n \/\/ nodes sorted by increasing frequency\n var nodes = [(Int, HuffmanTree)]()\n \/\/ iterate through leaves and nodes in order of increasing frequency\n for var i = 0, j = 0; ; {\n assert(i < leaves.count || j < nodes.count)\n \/\/ get subtree of least frequency\n var e1 : (Int, HuffmanTree)\n if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 {\n e1 = leaves[i]\n i++\n } else {\n e1 = nodes[j]\n j++\n }\n \n \/\/ if there's no subtrees left, then that one was the answer\n if i == leaves.count && j == nodes.count {\n return e1.1\n }\n \n \/\/ get next subtree of least frequency\n var e2 : (Int, HuffmanTree)\n if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 {\n e2 = leaves[i]\n i++\n } else {\n e2 = nodes[j]\n j++\n }\n \/\/ create node from two subtrees\n nodes.append((e1.0 + e2.0, .Node(e1.1, e2.1)))\n }\n}\n\nfunc getFreqs(seq: S) -> [(S.Generator.Element, Int)] {\n var freqs : [S.Generator.Element : Int] = [:]\n for c in seq {\n freqs[c] = (freqs[c] ?? 0) + 1\n }\n return Array(freqs)\n}\n\nlet str = \"this is an example for huffman encoding\"\nlet charFreqs = getFreqs(str.characters)\nlet tree = buildTree(charFreqs)\nprint(\"Symbol\\tHuffman code\")\ntree.printCodes(\"\")\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in a given string. It first creates a tree of nodes based on the frequency of each character. It then traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for the character. The code uses two sorted lists, one for leaves and one for nodes, and merges them as it iterates through them.","id":484} {"lang_cluster":"Swift","source_code":"\nfor i in stride(from: 10, through: 0, by: -1) {\n println(i)\n}\n\nfor i in lazy(0...10).reverse() {\n println(i)\n}\n\nfor i in reverse(0 ... 10) {\n println(i)\n}\n\nfor var i = 10; i >= 0; i-- {\n println(i)\n}\n\nfor i in (0...10).reversed() {\n print(i)\n}\n","human_summarization":"The code executes a downward for loop, counting down from 10 to 0.","id":485} {"lang_cluster":"Swift","source_code":"\n\npublic func convertToUnicodeScalars(\n str: String,\n minChar: UInt32,\n maxChar: UInt32\n) -> [UInt32] {\n var scalars = [UInt32]()\n\n for scalar in str.unicodeScalars {\n let val = scalar.value\n\n guard val >= minChar && val <= maxChar else {\n continue\n }\n\n scalars.append(val)\n }\n\n return scalars\n}\n\npublic struct Vigenere {\n private let keyScalars: [UInt32]\n private let smallestScalar: UInt32\n private let largestScalar: UInt32\n private let sizeAlphabet: UInt32\n\n public init?(key: String, smallestCharacter: Character = \"A\", largestCharacter: Character = \"Z\") {\n let smallScalars = smallestCharacter.unicodeScalars\n let largeScalars = largestCharacter.unicodeScalars\n\n guard smallScalars.count == 1, largeScalars.count == 1 else {\n return nil\n }\n\n self.smallestScalar = smallScalars.first!.value\n self.largestScalar = largeScalars.first!.value\n self.sizeAlphabet = (largestScalar - smallestScalar) + 1\n\n let scalars = convertToUnicodeScalars(str: key, minChar: smallestScalar, maxChar: largestScalar)\n\n guard !scalars.isEmpty else {\n return nil\n }\n\n self.keyScalars = scalars\n\n }\n\n public func decrypt(_ str: String) -> String? {\n let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)\n\n guard !txtBytes.isEmpty else {\n return nil\n }\n\n var res = \"\"\n\n for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar {\n guard let char =\n UnicodeScalar((c &+ sizeAlphabet &- keyScalars[i % keyScalars.count]) % sizeAlphabet &+ smallestScalar)\n else {\n return nil\n }\n\n res += String(char)\n }\n\n return res\n }\n\n public func encrypt(_ str: String) -> String? {\n let txtBytes = convertToUnicodeScalars(str: str, minChar: smallestScalar, maxChar: largestScalar)\n\n guard !txtBytes.isEmpty else {\n return nil\n }\n\n var res = \"\"\n\n for (i, c) in txtBytes.enumerated() where c >= smallestScalar && c <= largestScalar {\n guard let char =\n UnicodeScalar((c &+ keyScalars[i % keyScalars.count] &- 2 &* smallestScalar) % sizeAlphabet &+ smallestScalar)\n else {\n return nil\n }\n\n res += String(char)\n }\n\n return res\n }\n}\n\nlet text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\nlet key = \"VIGENERECIPHER\";\nlet cipher = Vigenere(key: key)!\n\nprint(\"Key: \\(key)\")\nprint(\"Plain Text: \\(text)\")\n\nlet encoded = cipher.encrypt(text.uppercased())!\n\nprint(\"Cipher Text: \\(encoded)\")\n\nlet decoded = cipher.decrypt(encoded)!\n\nprint(\"Decoded: \\(decoded)\")\n\nprint(\"\\nLarger set:\")\n\nlet key2 = \"Vigen\u00e8re cipher\"\nlet text2 = \"This is a \u00fcnicode string \ud83d\ude03\"\n\nlet cipher2 = Vigenere(key: key2, smallestCharacter: \" \", largestCharacter: \"\ud83d\udef9\")!\n\nprint(\"Key: \\(key2)\")\nprint(\"Plain Text: \\(text2)\")\n\nlet encoded2 = cipher2.encrypt(text2)!\n\nprint(\"Cipher Text: \\(encoded2)\")\n\nlet decoded2 = cipher2.decrypt(encoded2)!\n\nprint(\"Decoded: \\(decoded2)\")\n\n\n","human_summarization":"\"Implements Vigen\u00e8re cipher for both encryption and decryption, handling keys and text of unequal length. The code capitalizes all characters and discards non-alphabetic ones. It can also support a larger range of characters if needed.\"","id":486} {"lang_cluster":"Swift","source_code":"\n\nfor i in stride(from: 1, to: 10, by: 2) {\n print(i)\n}\n\nfor var i = 1; i < 10; i += 2 {\n print(i)\n}\n","human_summarization":"demonstrate a for-loop with a step-value greater than one, printing all odd digits. Note that an alternate method was removed in Swift 3.","id":487} {"lang_cluster":"Swift","source_code":"\nvar i = 42 \/\/ initial value doesn't matter\n\nfunc sum(inout i: Int, lo: Int, hi: Int, @autoclosure term: () -> Double) -> Double {\n var result = 0.0\n for i = lo; i <= hi; i++ {\n result += term()\n }\n return result\n}\n\nprintln(sum(&i, 1, 100, 1 \/ Double(i)))\n\n\n\n","human_summarization":"implement Jensen's Device, a computer programming technique developed by J\u00f8rn Jensen. The technique is an exercise in call by name, demonstrated through a program that calculates the 100th harmonic number. The program utilizes the assumption that an expression passed as an actual parameter to a procedure will be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. This is particularly important for the first parameter to the sum function, which must be passed by name or by reference to ensure changes to it are visible in the caller's context. The global variable does not need to use the same identifier as the formal parameter.","id":488} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 3\nimport Foundation\n\nextension Array {\n mutating func shuffle() {\n guard count > 1 else { return }\n\n for i in 0.. Bool {\n return inBounds(value:testX, upper:self.x) && inBounds(value:testY, upper:self.y)\n }\n\n private func inBounds(value:Int, upper:Int) -> Bool {\n return (value >= 0) && (value < upper)\n }\n\n func display() {\n let cellWidth = 3\n for j in 0.. String {\n var line = \"\"\n for direction in Direction.allDirections {\n if (value & direction.rawValue) != 0 {\n line += direction.char\n }\n }\n return line\n }\n}\n\n\nlet x = 20\nlet y = 10\nlet maze = MazeGenerator(x, y)\nmaze.display()\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":489} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift 4.2\n\/\/\n\/\/ main.swift\n\/\/ pi digits\n\/\/\n\/\/ Created by max goren on 11\/11\/21.\n\/\/ Copyright \u00a9 2021 maxcodes. All rights reserved.\n\/\/\n\nimport Foundation\n\nvar r = [Int]()\nvar i = 0\nvar k = 2800\nvar b = 0\nvar c = 0\nvar d = 0\n\nfor _ in 0...2800 {\n r.append(2000);\n}\nwhile k > 0 {\n d = 0;\n i = k;\n while (true) {\n d = d + r[i] * 10000\n b = 2 * i - 1\n r[i] = d % b\n d = d \/ b\n i = i - 1\n if i == 0 {\n break;\n }\n d = d * i;\n }\n print(c + d \/ 10000, \"\")\n c = d % 10000\n k = k - 14\n}\n\n","human_summarization":"are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.","id":490} {"lang_cluster":"Swift","source_code":"\nlet a = [1,2,1,3,2]\nlet b = [1,2,0,4,4,0,0,0]\nprintln(lexicographicalCompare(a, b)) \/\/ this is \"less than\"\n\n\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise.\"","id":491} {"lang_cluster":"Swift","source_code":"\nfunc ackerman(m:Int, n:Int) -> Int {\n if m == 0 {\n return n+1\n } else if n == 0 {\n return ackerman(m-1, 1)\n } else {\n return ackerman(m-1, ackerman(m, n-1))\n }\n}\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":492} {"lang_cluster":"Swift","source_code":"\n\n\tlet maxn = 31\n\n\tfunc nq(n: Int) -> Int {\n\t var cols = Array(repeating: 0, count: maxn)\n\t var diagl = Array(repeating: 0, count: maxn)\n\t var diagr = Array(repeating: 0, count: maxn)\n\t var posibs = Array(repeating: 0, count: maxn)\n\t var num = 0\n\t for q0 in 0...n-3 {\n\t\tfor q1 in q0+2...n-1 {\n\t\t let bit0: Int = 1<>1|bit1)>>1\n\n\t\t var posib: Int = ~(cols[0] | diagl[0] | diagr[0])\n\n\t\t while (d >= 0) {\n\t\t\twhile(posib\u00a0!= 0) {\n\t\t\t let bit: Int = posib & -posib\n\t\t\t let ncols: Int = cols[d] | bit\n\t\t\t let ndiagl: Int = (diagl[d] | bit) << 1;\n\t\t\t let ndiagr: Int = (diagr[d] | bit) >> 1;\n\t\t\t let nposib: Int = ~(ncols | ndiagl | ndiagr);\n\t\t\t posib^=bit\n\t\t\t num += (ncols == -1\u00a0? 1\u00a0: 0)\n\t\t\t if (nposib\u00a0!= 0){\n\t\t\t\tif(posib\u00a0!= 0) {\n\t\t\t\t posibs[d] = posib\n\t\t\t\t d += 1\n\t\t\t\t}\n\t\t\t\tcols[d] = ncols\n\t\t\t\tdiagl[d] = ndiagl\n\t\t\t\tdiagr[d] = ndiagr\n\t\t\t\tposib = nposib\n\t\t\t }\n\t\t\t}\n\t\t\td -= 1\n\t\t\tposib = d<0\u00a0? n\u00a0: posibs[d]\n\n\t\t }\n\t\t}\n\n\t }\n\t return num*2\n\t}\n\tif(CommandLine.arguments.count == 2) {\n\n\t let board_size: Int = Int(CommandLine.arguments[1])!\n\t print (\"Number of solutions for board size \\(board_size) is: \\(nq(n:board_size))\")\n\n\t} else {\n\t print(\"Usage: 8q \")\n\t}\n","human_summarization":"solve the N-queens problem, extending the eight queens puzzle to a board of size NxN. It also provides the number of solutions for small values of N (refer OEIS: A000170). This is a port of an optimized C code.","id":493} {"lang_cluster":"Swift","source_code":"\nlet array1 = [1,2,3]\nlet array2 = [4,5,6]\nlet array3 = array1 + array2\n","human_summarization":"demonstrate how to concatenate two arrays.","id":494} {"lang_cluster":"Swift","source_code":"struct KnapsackItem {\n var name: String\n var weight: Int\n var value: Int\n}\n\nfunc knapsack(items: [KnapsackItem], limit: Int) -> [KnapsackItem] {\n var table = Array(repeating: Array(repeating: 0, count: limit + 1), count: items.count + 1)\n \n for j in 1.. w {\n table[j][w] = table[j-1][w]\n } else {\n table[j][w] = max(table[j-1][w], table[j-1][w-item.weight] + item.value)\n }\n }\n }\n \n var result = [KnapsackItem]()\n var w = limit\n \n for j in stride(from: items.count, to: 0, by: -1) where table[j][w]\u00a0!= table[j-1][w] {\n let item = items[j-1]\n \n result.append(item)\n \n w -= item.weight\n }\n \n return result\n}\n\nlet items = [\n KnapsackItem(name: \"map\", weight: 9, value: 150), KnapsackItem(name: \"compass\", weight: 13, value: 35),\n KnapsackItem(name: \"water\", weight: 153, value: 200), KnapsackItem(name: \"sandwich\", weight: 50, value: 160),\n KnapsackItem(name: \"glucose\", weight: 15, value: 60), KnapsackItem(name: \"tin\", weight: 68, value: 45),\n KnapsackItem(name: \"banana\", weight: 27, value: 60), KnapsackItem(name: \"apple\", weight: 39, value: 40),\n KnapsackItem(name: \"cheese\", weight: 23, value: 30), KnapsackItem(name: \"beer\", weight: 52, value: 10),\n KnapsackItem(name: \"suntan cream\", weight: 11, value: 70), KnapsackItem(name: \"camera\", weight: 32, value: 30),\n KnapsackItem(name: \"t-shirt\", weight: 24, value: 15), KnapsackItem(name: \"trousers\", weight: 48, value: 10),\n KnapsackItem(name: \"umbrella\", weight: 73, value: 40), KnapsackItem(name: \"waterproof trousers\", weight: 42, value: 70),\n KnapsackItem(name: \"waterproof overclothes\", weight: 43, value: 75), KnapsackItem(name: \"note-case\", weight: 22, value: 80),\n KnapsackItem(name: \"sunglasses\", weight: 7, value: 20), KnapsackItem(name: \"towel\", weight: 18, value: 12),\n KnapsackItem(name: \"socks\", weight: 4, value: 50), KnapsackItem(name: \"book\", weight: 30, value: 10)\n]\n\nlet kept = knapsack(items: items, limit: 400)\n\nprint(\"Kept: \")\n\nfor item in kept {\n print(\" \\(item.name)\")\n}\n\nlet (tValue, tWeight) = kept.reduce((0, 0), { ($0.0 + $1.value, $0.1 + $1.weight) })\n\nprint(\"For a total value of \\(tValue) and a total weight of \\(tWeight)\")\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":495} {"lang_cluster":"Swift","source_code":"class Person {\n let name:String\n var candidateIndex = 0\n var fiance:Person?\n var candidates = [Person]()\n \n init(name:String) {\n self.name = name\n }\n \n func rank(p:Person) -> Int {\n for (i, candidate) in enumerate(self.candidates) {\n if candidate === p {\n return i\n }\n }\n return self.candidates.count + 1\n }\n \n func prefers(p:Person) -> Bool {\n if let fiance = self.fiance {\n return self.rank(p) < self.rank(fiance)\n }\n return false\n }\n \n func nextCandidate() -> Person? {\n if self.candidateIndex >= self.candidates.count {\n return nil\n }\n return self.candidates[candidateIndex++]\n }\n \n func engageTo(p:Person) {\n p.fiance?.fiance = nil\n p.fiance = self\n self.fiance?.fiance = nil\n self.fiance = p\n }\n \n func swapWith(p:Person) {\n let thisFiance = self.fiance\n let pFiance = p.fiance\n println(\"\\(self.name) swapped partners with \\(p.name)\")\n if pFiance != nil && thisFiance != nil {\n self.engageTo(pFiance!)\n p.engageTo(thisFiance!)\n }\n }\n}\n\nfunc isStable(guys:[Person], gals:[Person]) -> Bool {\n for guy in guys {\n for gal in gals {\n if guy.prefers(gal) && gal.prefers(guy) {\n return false\n }\n }\n }\n return true\n}\n\nfunc engageEveryone(guys:[Person]) {\n var done = false\n while !done {\n done = true\n for guy in guys {\n if guy.fiance == nil {\n done = false\n if let gal = guy.nextCandidate() {\n if gal.fiance == nil || gal.prefers(guy) {\n guy.engageTo(gal)\n }\n }\n }\n }\n }\n}\n\nfunc doMarriage() {\n let abe = Person(name: \"Abe\")\n let bob = Person(name: \"Bob\")\n let col = Person(name: \"Col\")\n let dan = Person(name: \"Dan\")\n let ed = Person(name: \"Ed\")\n let fred = Person(name: \"Fred\")\n let gav = Person(name: \"Gav\")\n let hal = Person(name: \"Hal\")\n let ian = Person(name: \"Ian\")\n let jon = Person(name: \"Jon\")\n let abi = Person(name: \"Abi\")\n let bea = Person(name: \"Bea\")\n let cath = Person(name: \"Cath\")\n let dee = Person(name: \"Dee\")\n let eve = Person(name: \"Eve\")\n let fay = Person(name: \"Fay\")\n let gay = Person(name: \"Gay\")\n let hope = Person(name: \"Hope\")\n let ivy = Person(name: \"Ivy\")\n let jan = Person(name: \"Jan\")\n \n abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]\n bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]\n col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]\n dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]\n ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]\n fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]\n gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]\n hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]\n ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]\n jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]\n abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal]\n bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal]\n cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon]\n dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed]\n eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob]\n fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal]\n gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian]\n hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred]\n ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan]\n jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan]\n \n let guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon]\n let gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan]\n \n engageEveryone(guys)\n \n for guy in guys {\n println(\"\\(guy.name) is engaged to \\(guy.fiance!.name)\")\n }\n \n println(\"Stable = \\(isStable(guys, gals))\")\n jon.swapWith(fred)\n println(\"Stable = \\(isStable(guys, gals))\")\n \n}\n\ndoMarriage()\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":496} {"lang_cluster":"Swift","source_code":"\n\nfunc a(v: Bool) -> Bool {\n print(\"a\")\n return v\n}\n\nfunc b(v: Bool) -> Bool {\n print(\"b\")\n return v\n}\n\nfunc test(i: Bool, j: Bool) {\n println(\"Testing a(\\(i)) && b(\\(j))\")\n print(\"Trace: \")\n println(\"\\nResult: \\(a(i) && b(j))\")\n \n println(\"Testing a(\\(i)) || b(\\(j))\")\n print(\"Trace: \")\n println(\"\\nResult: \\(a(i) || b(j))\")\n \n println()\n}\n\ntest(false, false)\ntest(false, true)\ntest(true, false)\ntest(true, true)\n\n\n","human_summarization":"The code defines two functions, a and b, which return and print the same boolean value. The code then calculates and assigns the values of two equations, x = a(i) and b(j), and y = a(i) or b(j), using short-circuit evaluation to ensure function b is only called when necessary. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.","id":497} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nfunc Blockable(str: String) -> Bool {\n\n var blocks = [\n \"BO\", \"XK\", \"DQ\", \"CP\", \"NA\", \"GT\", \"RE\", \"TG\", \"QD\", \"FS\",\n \"JW\", \"HU\", \"VI\", \"AN\", \"OB\", \"ER\", \"FS\", \"LY\", \"PC\", \"ZM\" ]\n\n var strUp = str.uppercaseString\n var final = \"\"\n\n for char: Character in strUp {\n var CharString: String = \"\"; CharString.append(char)\n for j in 0.. String {\n return can\u00a0? \"can\"\u00a0: \"cannot\"\n}\n\nfor str in [ \"A\", \"BARK\", \"BooK\", \"TrEaT\", \"comMON\", \"sQuAd\", \"Confuse\" ] {\n println(\"'\\(str)' \\(CanOrNot(Blockable(str))) be spelled with blocks.\")\n}\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":498} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\npublic struct OID {\n public var val: String\n\n public init(_ val: String) {\n self.val = val\n }\n}\n\nextension OID: CustomStringConvertible {\n public var description: String {\n return val\n }\n}\n\nextension OID: Comparable {\n public static func < (lhs: OID, rhs: OID) -> Bool {\n let split1 = lhs.val.components(separatedBy: \".\").compactMap(Int.init)\n let split2 = rhs.val.components(separatedBy: \".\").compactMap(Int.init)\n let minSize = min(split1.count, split2.count)\n\n for i in 0.. split2[i] {\n return false\n }\n }\n\n return split1.count < split2.count\n }\n\n public static func == (lhs: OID, rhs: OID) -> Bool {\n return lhs.val == rhs.val\n }\n}\n\nlet ids = [\n \"1.3.6.1.4.1.11.2.17.19.3.4.0.10\", \n \"1.3.6.1.4.1.11.2.17.5.2.0.79\", \n \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\", \n \"1.3.6.1.4.1.11150.3.4.0.1\", \n \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\", \n \"1.3.6.1.4.1.11150.3.4.0\"\n].map(OID.init)\n\nfor id in ids.sorted() {\n print(id)\n}\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":499} {"lang_cluster":"Swift","source_code":"\nimport Foundation\n\nfunc octalSuccessor(value: String) -> String {\n if value.isEmpty {\n return \"1\"\n } else {\n let i = value.startIndex, j = value.endIndex.predecessor()\n switch (value[j]) {\n case \"0\": return value[i..(inout a: T, inout b: T) {\n (a, b) = (b, a)\n}\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function should be able to handle both statically and dynamically typed languages, and account for potential restrictions in type compatibility and language support for parametric polymorphism. It is noted that destructive operations like swapping may not be allowed in some functional languages. The Swift standard library's existing swap function is also acknowledged.","id":501} {"lang_cluster":"Swift","source_code":"\nWorks with: Swift version 1.2\nimport Foundation\n\n\/\/ Allow for easy character checking\nextension String {\n subscript (i: Int) -> String {\n return String(Array(self)[i])\n }\n}\n\nfunc isPalindrome(str:String) -> Bool {\n if (count(str) == 0 || count(str) == 1) {\n return true\n }\n let removeRange = Range(start: advance(str.startIndex, 1), end: advance(str.endIndex, -1))\n if (str[0] == str[count(str) - 1]) {\n return isPalindrome(str.substringWithRange(removeRange))\n }\n return false\n}\nWorks with: Swift version 2.0\nfunc isPal(str: String) -> Bool {\n let c = str.characters\n return lazy(c).reverse()\n .startsWith(c[c.startIndex...advance(c.startIndex, c.count \/ 2)])\n}\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":502} {"lang_cluster":"Swift","source_code":"\nprint(\"USER: \\(ProcessInfo.processInfo.environment[\"USER\"] ?? \"Not set\")\")\nprint(\"PATH: \\(ProcessInfo.processInfo.environment[\"PATH\"] ?? \"Not set\")\")\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":503} {"lang_cluster":"Swift","source_code":"\n\/\/Aamrun, 3rd February 2023\n\nfunc F(n: Int,x: Int,y: Int) -> Int {\n if (n == 0) {\n return x + y;\n }\n\n else if (y == 0) {\n return x;\n }\n\n return F(n: n - 1, x: F(n: n, x: x, y: y - 1), y: F(n: n, x: x, y: y - 1) + y);\n}\n\nprint(\"F1(3,3) = \" + String(F(n: 1,x: 3,y: 3)));\n\n\/\/Aamrun, 3rd February 2023\n\nfunc F(n: Int,x: Int,y: Int) -> Int {\n if n == 0 {\n return x + y\n }\n\n else if y == 0 {\n return x\n }\n\n return F(n: n - 1, x: F(n: n, x: x, y: y - 1), y: F(n: n, x: x, y: y - 1) + y)\n}\n\nprint(\"F1(3,3) = \" + String(F(n: 1,x: 3,y: 3)))\n\n\n\n","human_summarization":"implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns their sum if the function is called with zero recursion depth. If the recursion depth is greater than zero and y is zero, it returns x. Otherwise, it recursively calls itself with modified arguments. The implementation is provided in both C-like and pure Swift syntax.","id":504} {"lang_cluster":"Scheme","source_code":"\n\n(define (make-stack)\n (let ((st '()))\n (lambda (message . args)\n (case message\n ((empty?) (null? st))\n ((top) (if (null? st)\n 'empty\n (car st)))\n ((push) (set! st (cons (car args) st)))\n ((pop) (if (null? st)\n 'empty\n (let ((result (car st)))\n (set! st (cdr st))\n result)))\n (else 'badmsg)))))\n","human_summarization":"implement a stack data structure with basic operations such as push (adding an element to the top of the stack), pop (removing the topmost element from the stack and returning it), and empty (checking if the stack is empty). The stack follows a last in, first out (LIFO) access policy.","id":505} {"lang_cluster":"Scheme","source_code":"\n(define (fib-iter n)\n (do ((num 2 (+ num 1))\n (fib-prev 1 fib)\n (fib 1 (+ fib fib-prev)))\n ((>= num n) fib)))\n(define (fib-rec n)\n (if (< n 2)\n n\n (+ (fib-rec (- n 1))\n (fib-rec (- n 2)))))\n\n(define (fib n)\n (let loop ((a 0) (b 1) (n n))\n (if (= n 0) a\n (loop b (+ a b) (- n 1)))))\n\n(define (fib)\n (define (nxt lv nv) (cons nv (lambda () (nxt nv (+ lv nv)))))\n (cons 0 (lambda () (nxt 0 1))))\n\n;;; test...\n(define (show-stream-take n strm)\n (define (shw-nxt n strm) (begin (display (car strm))\n (if (> n 1) (begin (display \" \") (shw-nxt (- n 1) ((cdr strm)))) (display \")\"))))\n (begin (display \"(\") (shw-nxt n strm)))\n(show-stream-take 30 (fib))\n\n","human_summarization":"The code is a function that generates the nth Fibonacci number. It can implement this either iteratively or recursively, though the latter is generally slower. The function also optionally supports negative numbers. The code is efficient and uses a tail recursive version, generating only the final nth Fibonacci number without wasteful repeated calls. It also includes a procedure that generates the Fibonacci sequence using a simplified version of a lazy list\/stream, using almost no memory during sequence generation.","id":506} {"lang_cluster":"Scheme","source_code":"\n\n(define filter\n (lambda (fn lst)\n (let iter ((lst lst) (result '()))\n (if (null? lst)\n (reverse result)\n (let ((item (car lst))\n (rest (cdr lst)))\n (if (fn item)\n (iter rest (cons item result))\n (iter rest result)))))))\n\n> (filter even? '(1 2 3 4 5 6 7 8 9 10))\n(2 4 6 8 10)\n\n(define (select-even lst)\n (filter even? lst))\n\n(select-even '(1 2 3 4 5 6 7 8 9 10))\n","human_summarization":"\"Implements a generic filter function to select certain elements from an array into a new array, demonstrated by selecting all even numbers. Additionally, provides a destructive filter solution that modifies the original array instead of creating a new one.\"","id":507} {"lang_cluster":"Scheme","source_code":"\nWorks with: Guile\n(define s \"Hello, world!\")\n(define n 5)\n(define m (+ n 6))\n\n(display (substring s n m))\n(newline)\n\n(display (substring s n))\n(newline)\n\n(display (substring s 0 (- (string-length s) 1)))\n(newline)\n\n(display (substring s (string-index s #\\o) m))\n(newline)\n\n(display (substring s (string-contains s \"lo\") m))\n(newline)\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":508} {"lang_cluster":"Scheme","source_code":"\n(define (string-reverse s)\n (list->string (reverse (string->list s))))\n> (string-reverse \"asdf\")\n\"fdsa\"\n\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":509} {"lang_cluster":"Scheme","source_code":"\nWorks with: CHICKEN version 5.3.0\nLibrary: r7rs\n\n(cond-expand\n (r7rs)\n (chicken (import r7rs)))\n\n(define-library (avl-trees)\n\n ;;\n ;; This library implements \u2018persistent\u2019 (that is, \u2018immutable\u2019) AVL\n ;; trees for R7RS Scheme.\n ;;\n ;; Included are generators of the key-data pairs in a tree. Because\n ;; the trees are persistent (\u2018immutable\u2019), these generators are safe\n ;; from alterations of the tree.\n ;;\n ;; References:\n ;;\n ;; * Niklaus Wirth, 1976. Algorithms + Data Structures =\n ;; Programs. Prentice-Hall, Englewood Cliffs, New Jersey.\n ;;\n ;; * Niklaus Wirth, 2004. Algorithms and Data Structures. Updated\n ;; by Fyodor Tkachov, 2014.\n ;;\n ;; Note that the references do not discuss persistent\n ;; implementations. It seems worthwhile to compare the methods of\n ;; implementation.\n ;;\n\n (export avl)\n (export alist->avl)\n (export avl->alist)\n (export avl?)\n (export avl-empty?)\n (export avl-size)\n (export avl-insert)\n (export avl-delete)\n (export avl-delete-values)\n (export avl-has-key?)\n (export avl-search)\n (export avl-search-values)\n (export avl-make-generator)\n (export avl-pretty-print)\n (export avl-check-avl-condition)\n (export avl-check-usage)\n\n (import (scheme base))\n (import (scheme case-lambda))\n (import (scheme process-context))\n (import (scheme write))\n\n (cond-expand\n (chicken\n (import (only (chicken base) define-record-printer))\n (import (only (chicken format) format))) ; For debugging.\n (else))\n\n (begin\n\n ;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n ;;\n ;; Tools for making generators. These use call\/cc and so might be\n ;; inefficient in your Scheme. I am using CHICKEN, in which\n ;; call\/cc is not so inefficient.\n ;;\n ;; Often I have made &fail a unique object rather than #f, but in\n ;; this case #f will suffice.\n ;;\n\n (define &fail #f)\n\n (define *suspend*\n (make-parameter (lambda (x) x)))\n\n (define (suspend v)\n ((*suspend*) v))\n\n (define (fail-forever)\n (let loop ()\n (suspend &fail)\n (loop)))\n\n (define (make-generator-procedure thunk)\n ;; Make a suspendable procedure that takes no arguments. The\n ;; result is a simple generator of values. (This can be\n ;; elaborated upon for generators to take values on resumption,\n ;; in the manner of Icon co-expressions.)\n (define (next-run return)\n (define (my-suspend v)\n (set! return (call\/cc (lambda (resumption-point)\n (set! next-run resumption-point)\n (return v)))))\n (parameterize ((*suspend* my-suspend))\n (suspend (thunk))\n (fail-forever)))\n (lambda () (call\/cc next-run)))\n\n ;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n (define-syntax avl-check-usage\n (syntax-rules ()\n ((_ pred msg)\n (or pred (usage-error msg)))))\n\n ;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n (define-record-type \n (%avl key data bal left right)\n avl?\n (key %key)\n (data %data)\n (bal %bal)\n (left %left)\n (right %right))\n\n (cond-expand\n (chicken (define-record-printer ( rt out)\n (display \"#\" out)))\n (else))\n\n ;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n (define avl\n (case-lambda\n (() (%avl #f #f #f #f #f))\n ((predavl predavl predavl expects a procedure as first argument\")\n (let loop ((tree (avl))\n (lst alst))\n (if (null? lst)\n tree\n (let ((head (car lst)))\n (loop (avl-insert predalist tree)\n ;; Go from AVL tree to association list. The output will be in\n ;; order.\n (define (traverse p lst)\n ;; Reverse in-order traversal of the tree, to produce an\n ;; in-order cons-list.\n (if (not p)\n lst\n (traverse (%left p) (cons (cons (%key p) (%data p))\n (traverse (%right p) lst)))))\n (if (avl-empty? tree)\n '()\n (traverse tree '())))\n\n (define (avl-insert predalist tree) (cdr p)))\n ((null? p))\n (display-key-data (caar p) (cdar p))\n (newline)))\n\n (define (error-stop)\n (display \"*** ERROR STOP ***\\n\" (current-error-port))\n (emergency-exit 1))\n\n (define n 20)\n (define keys (make-vector (+ n 1)))\n (do ((i 0 (+ i 1)))\n ((= i n))\n ;; To keep things more like Fortran, do not use index zero.\n (vector-set! keys (+ i 1) (+ i 1)))\n\n (fisher-yates-shuffle keys)\n\n ;; Insert key-data pairs in the shuffled order.\n (define tree (avl))\n (avl-check-avl-condition tree)\n (do ((i 1 (+ i 1)))\n ((= i (+ n 1)))\n (let ((ix (vector-ref keys i)))\n (set! tree (avl-insert < tree ix (inexact ix)))\n (avl-check-avl-condition tree)\n (do ((j 1 (+ j 1)))\n ((= j (+ n 1)))\n (let*-values (((k) (vector-ref keys j))\n ((has-key?) (avl-has-key? < tree k))\n ((data) (avl-search < tree k))\n ((data^ has-key?^)\n (avl-search-values < tree k)))\n (unless (exact? k) (error-stop))\n (if (<= j i)\n (unless (and has-key? data data^ has-key?^\n (inexact? data) (= data k)\n (inexact? data^) (= data^ k))\n (error-stop))\n (when (or has-key? data data^ has-key?^)\n (error-stop)))))))\n\n (display \"----------------------------------------------------------------------\\n\") \n (display \"keys = \")\n (write (cdr (vector->list keys)))\n (newline)\n (display \"----------------------------------------------------------------------\\n\")\n (avl-pretty-print tree)\n (display \"----------------------------------------------------------------------\\n\")\n (display \"tree size = \")\n (display (avl-size tree))\n (newline)\n (display-tree-contents tree)\n (display \"----------------------------------------------------------------------\\n\")\n\n ;;\n ;; Reshuffle the keys, and change the data from inexact numbers\n ;; to strings.\n ;;\n\n (fisher-yates-shuffle keys)\n\n (do ((i 1 (+ i 1)))\n ((= i (+ n 1)))\n (let ((ix (vector-ref keys i)))\n (set! tree (avl-insert < tree ix (number->string ix)))\n (avl-check-avl-condition tree)))\n\n (avl-pretty-print tree)\n (display \"----------------------------------------------------------------------\\n\")\n (display \"tree size = \")\n (display (avl-size tree))\n (newline)\n (display-tree-contents tree)\n (display \"----------------------------------------------------------------------\\n\")\n\n ;;\n ;; Reshuffle the keys, and delete the contents of the tree, but\n ;; also keep the original tree by saving it in a variable. Check\n ;; persistence of the tree.\n ;;\n\n (fisher-yates-shuffle keys)\n\n (define saved-tree tree)\n\n (do ((i 1 (+ i 1)))\n ((= i (+ n 1)))\n (let ((ix (vector-ref keys i)))\n (set! tree (avl-delete < tree ix))\n (avl-check-avl-condition tree)\n (unless (= (avl-size tree) (- n i)) (error-stop))\n ;; Try deleting a second time.\n (set! tree (avl-delete < tree ix))\n (avl-check-avl-condition tree)\n (unless (= (avl-size tree) (- n i)) (error-stop))\n (do ((j 1 (+ j 1)))\n ((= j (+ n 1)))\n (let ((jx (vector-ref keys j)))\n (unless (eq? (avl-has-key? < tree jx) (< i j))\n (error-stop))\n (let ((data (avl-search < tree jx)))\n (unless (eq? (not (not data)) (< i j))\n (error-stop))\n (unless (or (not data)\n (= (string->number data) jx))\n (error-stop)))\n (let-values (((data found?)\n (avl-search-values < tree jx)))\n (unless (eq? found? (< i j)) (error-stop))\n (unless (or (and (not data) (<= j i))\n (and data (= (string->number data) jx)))\n (error-stop)))))))\n (do ((i 1 (+ i 1)))\n ((= i (+ n 1)))\n ;; Is save-tree the persistent value of the tree we just\n ;; deleted?\n (let ((ix (vector-ref keys i)))\n (unless (equal? (avl-search < saved-tree ix)\n (number->string ix))\n (error-stop))))\n\n (display \"forwards generator:\\n\")\n (let ((gen (avl-make-generator saved-tree)))\n (do ((pair (gen) (gen)))\n ((not pair))\n (display-key-data (car pair) (cdr pair))\n (newline)))\n\n (display \"----------------------------------------------------------------------\\n\")\n\n (display \"backwards generator:\\n\")\n (let ((gen (avl-make-generator saved-tree -1)))\n (do ((pair (gen) (gen)))\n ((not pair))\n (display-key-data (car pair) (cdr pair))\n (newline)))\n\n (display \"----------------------------------------------------------------------\\n\")\n\n ))\n (else))\n\n\n","human_summarization":"implement an AVL tree with basic operations. The AVL tree is a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The tree is rebalanced after insertions and deletions to maintain this property. The operations of lookup, insertion, and deletion all take O(log n) time. The tree does not allow duplicate node keys. The code also includes a comparison function for matching keys. The demonstration of the AVL tree is randomized and the tree is pretty printed in a unique way.","id":510} {"lang_cluster":"Scheme","source_code":"\n(import (scheme base)\n (scheme inexact)\n (scheme write))\n\n;; c1 and c2 are pairs (x y), r a positive radius\n(define (find-circles c1 c2 r)\n (define x-coord car) ; for easier to read coordinate extraction from list\n (define y-coord cadr)\n (define (approx= a b) (< (- a b) 0.000001)) ; equal within tolerance\n (define (avg a b) (\/ (+ a b) 2))\n (define (distance pt1 pt2)\n (sqrt (+ (square (- (x-coord pt1) (x-coord pt2)))\n (square (- (y-coord pt1) (y-coord pt2))))))\n (define (equal-points? pt1 pt2)\n (and (approx= (x-coord pt1) (x-coord pt2))\n (approx= (y-coord pt1) (y-coord pt2))))\n (define (delete-duplicate pts) ; assume no more than two points in list\n (if (and (= 2 (length pts))\n (equal-points? (car pts) (cadr pts)))\n (list (car pts)) ; keep the first only\n pts))\n ;\n (let ((d (distance c1 c2)))\n (cond ((equal-points? c1 c2) ; coincident points\n (if (> r 0)\n 'infinite ; r > 0\n (list c1))) ; else r = 0\n ((< (* 2 r) d) \n '()) ; circle cannot reach both points, as too far apart\n ((approx= r 0.0) ; r = 0, no circles, as points differ\n '()) \n (else ; find up to two circles meeting c1 and c2\n (let* ((mid-pt (list (avg (x-coord c1) (x-coord c2))\n (avg (y-coord c1) (y-coord c2))))\n (offset (sqrt (- (square r) \n (square (* 0.5 d)))))\n (delta-cx (\/ (- (x-coord c1) (x-coord c2)) d))\n (delta-cy (\/ (- (y-coord c1) (y-coord c2)) d)))\n (delete-duplicate\n (list (list (- (x-coord mid-pt) (* offset delta-cx))\n (+ (y-coord mid-pt) (* offset delta-cy)))\n (list (+ (x-coord mid-pt) (* offset delta-cx))\n (- (y-coord mid-pt) (* offset delta-cy))))))))))\n\n;; work through the input examples, outputting results\n(for-each \n (lambda (c1 c2 r)\n (let ((result (find-circles c1 c2 r)))\n (display \"p1: \") (display c1)\n (display \" p2: \") (display c2)\n (display \" r: \") (display (number->string r))\n (display \" => \")\n (cond ((eq? result 'infinite)\n (display \"Infinite number of circles\"))\n ((null? result)\n (display \"No circles\"))\n (else\n (display result)))\n (newline)))\n '((0.1234 0.9876) (0.0000 2.0000) (0.1234 0.9876) (0.1234 0.9876) (0.1234 0.9876))\n '((0.8765 0.2345) (0.0000 0.0000) (0.1234 0.9876) (0.8765 0.2345) (0.1234 0.9876))\n '(2.0 1.0 2.0 0.5 0.0))\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":511} {"lang_cluster":"Scheme","source_code":"\n(let loop ((first (random 20)))\n (print first)\n (if (not (= first 10))\n (begin\n (print (random 20))\n (loop (random 20)))))\n\n(call\/cc \n (lambda (break)\n (let loop ((first (random 20)))\n (print first)\n (if (= first 10)\n (break))\n (print (random 20))\n (loop (random 20)))))\n","human_summarization":"generates and prints random numbers from 0 to 19. If the generated number is 10, the loop stops. If not, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":512} {"lang_cluster":"Scheme","source_code":"\n\n#lang scheme\n\n;;; this needs to be changed for other R6RS implementations\n(require rnrs\/arithmetic\/bitwise-6)\n\n;;; modpow, as per the task description.\n(define (modpow exponent base)\n (let loop ([square 1] [index (- (bitwise-length exponent) 1)])\n (if (< index 0)\n square\n (loop (modulo (* (if (bitwise-bit-set? exponent index) 2 1)\n square square) base)\n (- index 1)))))\n\n;;; search through all integers from 1 on to find the first divisor\n;;; returns #f if 2^p-1 is prime\n(define (mersenne-factor p)\n (for\/first ((i (in-range 1 (floor (expt 2 (quotient p 2))) (* 2 p)))\n #:when (and (or (= 1 (modulo i 8)) (= 7 (modulo i 8)))\n (= 1 (modpow p i))))\n i))\n\n\n","human_summarization":"The code implements an algorithm to find a factor of a Mersenne number (in this case, 2^929-1). It uses the properties of Mersenne numbers and the modPow operation to efficiently determine if a number divides the Mersenne number. The algorithm stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":513} {"lang_cluster":"Scheme","source_code":"\n\n(define (element? a lst)\n (and (not (null? lst))\n (or (eq? a (car lst))\n\t (element? a (cdr lst)))))\n\n; util, not strictly needed\n(define (uniq lst)\n (if (null? lst) lst\n (let ((a (car lst)) (b (cdr lst)))\n (if (element? a b)\n\t(uniq b)\n\t(cons a (uniq b))))))\n\n(define (intersection a b)\n (cond ((null? a) '())\n\t((null? b) '())\n\t(else\n\t (append (intersection (cdr a) b)\n\t\t (if (element? (car a) b)\n\t\t (list (car a))\n\t\t '())))))\n\n(define (union a b)\n (if (null? a) b\n (union (cdr a)\n\t (if (element? (car a) b)\n\t b\n\t (cons (car a) b)))))\n\n(define (diff a b) ; a - b\n (if (null? a) '()\n (if (element? (car a) b)\n (diff (cdr a) b)\n (cons (car a) (diff (cdr a) b)))))\n\n(define (subset? a b) ; A \u2286 B\n (if (null? a) #t\n (and (element? (car a) b)\n\t (subset? (cdr a) b))))\n\n(define (set-eq? a b)\n (and (subset? a b)\n (subset? b a)))\n\n","human_summarization":"implement various set operations including set creation, testing if an element is in a set, union, intersection, difference, subset, and equality of two sets. The code also provides options for additional set operations and modifications to a mutable set. The set is implemented using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also includes efficiency considerations for large sets.","id":514} {"lang_cluster":"Scheme","source_code":"\n(define (day-of-week year month day)\n(if (< month 3)\n (begin (set! month (+ month 12)) (set! year (- year 1))))\n(+ 1\n (remainder (+ 5 day (quotient (* (+ 1 month) 13) 5)\n year (quotient year 4) (* (quotient year 100) 6) (quotient year 400))\n 7)))\n\n(define (task)\n(let loop ((y 2121) (v '()))\n(if (< y 2008)\n v\n (loop (- y 1)\n (if (= 7 (day-of-week y 12 25))\n (cons y v)\n v)))))\n\n(task)\n; (2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118)\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":515} {"lang_cluster":"Scheme","source_code":"\n(define (remove-duplicates l)\n (cond ((null? l)\n '())\n ((member (car l) (cdr l))\n (remove-duplicates (cdr l)))\n (else\n (cons (car l) (remove-duplicates (cdr l))))))\n\n(remove-duplicates '(1 2 1 3 2 4 5))\n(1 3 2 4 5)\n\n(define (remove-duplicates l)\n (do ((a '() (if (member (car l) a) a (cons (car l) a)))\n (l l (cdr l)))\n ((null? l) (reverse a))))\n\n(remove-duplicates '(1 2 1 3 2 4 5))\n(1 2 3 4 5)\n\n","human_summarization":"\"Implements a function to remove duplicate elements from an array using three possible methods: 1) Utilizing a hash table to automatically discard duplicates with a complexity of O(n) on average, 2) Sorting the elements and removing consecutive duplicates with a complexity of O(n log n), 3) Iterating through the list and discarding any element if it appears again with a complexity of O(n^2). Also, an alternative approach using the 'delete-duplicates' function from srfi-1 is available.\"","id":516} {"lang_cluster":"Scheme","source_code":"\n(define (split-by l p k)\n (let loop ((low '())\n (high '())\n (l l))\n (cond ((null? l)\n (k low high))\n ((p (car l))\n (loop low (cons (car l) high) (cdr l)))\n (else\n (loop (cons (car l) low) high (cdr l))))))\n \n(define (quicksort l gt?)\n (if (null? l)\n '()\n (split-by (cdr l) \n (lambda (x) (gt? x (car l)))\n (lambda (low high)\n (append (quicksort low gt?)\n (list (car l))\n (quicksort high gt?))))))\n\n(quicksort '(1 3 5 7 9 8 6 4 2) >)\n\n(define (quicksort l gt?)\n (if (null? l)\n '()\n (append (quicksort (filter (lambda (x) (gt? (car l) x)) (cdr l)) gt?)\n (list (car l))\n (quicksort (filter (lambda (x) (not (gt? (car l) x))) (cdr l)) gt?))))\n\n(quicksort '(1 3 5 7 9 8 6 4 2) >)\n\nWorks with: Chibi Scheme\nWorks with: Gauche Scheme\nWorks with: CHICKEN Scheme version 5.3.0\nFor CHICKEN:Library: r7rs\n\n;;;-------------------------------------------------------------------\n;;;\n;;; Quicksort in R7RS Scheme, working in-place on vectors (that is,\n;;; arrays). I closely follow the \"better quicksort algorithm\"\n;;; pseudocode, and thus the code is more \"procedural\" than\n;;; \"functional\".\n;;;\n;;; I use a random pivot. If you can generate a random number quickly,\n;;; this is a good method, but for this demonstration I have taken a\n;;; fast linear congruential generator and made it brutally slow. It's\n;;; just a demonstration.\u00a0:)\n;;;\n\n(import (scheme base))\n(import (scheme case-lambda))\n(import (scheme write))\n\n;;;-------------------------------------------------------------------\n;;;\n;;; Add \"while\" loops to the language.\n;;;\n\n(define-syntax while\n (syntax-rules ()\n ((_ pred? body ...)\n (let loop ()\n (when pred?\n (begin body ...)\n (loop))))))\n\n;;;-------------------------------------------------------------------\n;;;\n;;; In-place quicksort.\n;;;\n\n(define vector-quicksort!\n (case-lambda\n\n \u00a0;; Use a default pivot selector.\n (( n 1)\n (let* ((pivot (pivot-select vec i-first i-last)))\n (let ((left i-first)\n (right i-last))\n (while (<= left right)\n (while (< (vector-ref vec left) pivot)\n (set! left (+ left 1)))\n (while (> (vector-ref vec right) pivot)\n (set! right (- right 1)))\n (when (<= left right)\n (let ((lft (vector-ref vec left))\n (rgt (vector-ref vec right)))\n (vector-set! vec left rgt)\n (vector-set! vec right lft)\n (set! left (+ left 1))\n (set! right (- right 1)))))\n (quicksort! i-first right)\n (quicksort! left i-last)))))))))\n\n;;;-------------------------------------------------------------------\n;;;\n;;; A simple linear congruential generator, attributed by\n;;; https:\/\/en.wikipedia.org\/w\/index.php?title=Linear_congruential_generator&oldid=1083800601\n;;; to glibc and GCC. No attempt has been made to optimize this code.\n;;;\n\n(define seed 1)\n(define two**31 (expt 2 31))\n(define (random-integer)\n (let* ((s0 seed)\n (s1 (truncate-remainder (+ (* 1103515245 s0) 12345)\n two**31)))\n (set! seed s1)\n s0))\n(define randint\n (case-lambda\n ((n) (truncate-remainder (random-integer) n))\n ((i-first i-last) (+ i-first (randint (- i-last i-first -1))))))\n\n;;;-------------------------------------------------------------------\n;;;\n;;; A demonstration of in-place vector quicksort.\n;;;\n\n(define vec1 (vector-copy #(60 53 100 72 19 67 14\n 31 4 1 5 9 2 6 5 3 5 8\n 28 9 95 22 67 55 20 41\n 42 29 20 74 39)))\n(vector-quicksort! < vec1)\n(write vec1)\n(newline)\n\n;;;-------------------------------------------------------------------\n\n","human_summarization":"implement the Quicksort algorithm. The algorithm sorts an array or list of elements with a strict weak order. It works by choosing a pivot from the array, dividing the remaining elements into two partitions (one with elements less than the pivot and one with elements greater), then recursively sorting these partitions. The sorted partitions are then joined together with the pivot. The algorithm also includes a version that works in place by swapping elements within the array to avoid additional memory allocation. The pivot selection method is not specified and can vary.","id":517} {"lang_cluster":"Scheme","source_code":"\nWorks with: Guile version 2.0.13\n(define short-date\n (lambda (lt)\n (strftime \"%Y-%m-%d\" (localtime lt))))\n\n(define long-date\n (lambda (lt)\n (strftime \"%A, %B %d, %Y\" (localtime lt))))\n\n(define main\n (lambda (args)\n ;; Current date\n (let ((dt (car (gettimeofday))))\n ;; Short style\n (display (short-date dt))(newline)\n ;; Long style\n (display (long-date dt))(newline))))\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":518} {"lang_cluster":"Scheme","source_code":"(define (power-set set)\n (if (null? set)\n '(())\n (let ((rest (power-set (cdr set))))\n (append (map (lambda (element) (cons (car set) element))\n rest)\n rest))))\n\n(display (power-set (list 1 2 3)))\n(newline)\n\n(display (power-set (list \"A\" \"C\" \"E\")))\n(newline)\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":519} {"lang_cluster":"Scheme","source_code":"\n\n(define (to-roman n)\n (format \"~@r\" n))\n\n(define roman-decimal\n '((\"M\" . 1000)\n (\"CM\" . 900)\n (\"D\" . 500)\n (\"CD\" . 400)\n (\"C\" . 100)\n (\"XC\" . 90)\n (\"L\" . 50)\n (\"XL\" . 40)\n (\"X\" . 10)\n (\"IX\" . 9)\n (\"V\" . 5)\n (\"IV\" . 4)\n (\"I\" . 1)))\n\n(define (to-roman value)\n (apply string-append\n (let loop ((v value)\n (decode roman-decimal))\n (let ((r (caar decode))\n (d (cdar decode)))\n (cond\n ((= v 0) '())\n ((>= v d) (cons r (loop (- v d) decode)))\n (else (loop v (cdr decode))))))))\n\n\n(let loop ((n '(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 25 30 40 \n 50 60 69 70 80 90 99 100 200 300 400 500 600 666 700 800 900 \n 1000 1009 1444 1666 1945 1997 1999 2000 2008 2010 2011 2500 \n 3000 3999)))\n (unless (null? n)\n (printf \"~a ~a\\n\" (car n) (to-roman (car n)))\n (loop (cdr n))))\n","human_summarization":"The code defines a function that takes a positive integer as input and returns the Roman numeral representation of that integer. It follows the modern Roman numeral system where each digit is expressed separately, starting from the leftmost digit and excluding any digit with a value of zero. For example, 1990 is represented as MCMXC, 2008 as MMVIII, and 1666 as MDCLXVI.","id":520} {"lang_cluster":"Scheme","source_code":"\n\n(let ((array #(1 2 3 4 5)) \u00a0; vector literal\n (array2 (make-vector 5)) \u00a0; default is unspecified\n (array3 (make-vector 5 0)))\u00a0; default 0\n (vector-set! array 0 3)\n (vector-ref array 0)) \u00a0; 3\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, with an example of pushing a value into the array.","id":521} {"lang_cluster":"Scheme","source_code":"\nCharacter by character copy; Open ports for the input and output files\n(define in-file (open-input-file \"input.txt\"))\n(define out-file (open-output-file \"output.txt\"))\n\n; Read and write characters from the input file\n; to the output file one by one until end of file\n(do ((c (read-char in-file) (read-char in-file)))\n ((eof-object? c))\n (write-char c out-file))\n\n; Close the ports\n(close-input-port in-file)\n(close-output-port out-file)\n","human_summarization":"demonstrate reading the contents of \"input.txt\" file into a variable and then writing this variable's contents into a new file called \"output.txt\".","id":522} {"lang_cluster":"Scheme","source_code":"\n(define s \"alphaBETA\")\n(list->string (map char-upcase (string->list s)))\n(list->string (map char-downcase (string->list s)))\n\n> (define s \"alphaBETA gammaDELTA\")\n> (string-upcase s) \u00a0;; turn all into upper case\n\"ALPHABETA GAMMADELTA\"\n> (string-downcase s) \u00a0;; turn all into lower case\n\"alphabeta gammadelta\"\n> (string-titlecase s) \u00a0;; capitalise start of each word\n\"Alphabeta Gammadelta\"\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal encoding or plain ASCII. It also showcases additional case conversion functions available in the language's library, such as swapping case or capitalizing the first letter. Note that in some languages, the toLower and toUpper functions may not be reversible. The code uses SRFI-13 for this task.","id":523} {"lang_cluster":"Scheme","source_code":"\n(list obj ...)\n\n(display (list 1 2 3))\n(newline)\n(display (list))\n(newline)\n\n","human_summarization":"create a collection and populate it with a set of values. The code also includes examples of returning newly allocated lists with various modifications such as prepending objects and appending elements from other lists.","id":524} {"lang_cluster":"Scheme","source_code":"\n\n(call-with-current-continuation\n (lambda (esc)\n (do ((i 1 (+ 1 i))) (#f)\n (display i)\n (if (= i 10) (esc (newline)))\n (display \", \"))))\n\n(let loop ((i 0))\n (display i)\n (if (= i 10)\n (newline)\n (begin\n (display \", \")\n (loop (+ 1 i)))))\n","human_summarization":"demonstrate a loop that outputs a comma-separated list from 1 to 10. Each number and comma are printed using separate output statements within the loop body. Tail recursion is used to achieve this.","id":525} {"lang_cluster":"Scheme","source_code":"(import (chezscheme))\n(import (srfi srfi-1))\n\n\n(define (remove-self-dependency pair)\n (let ((key (car pair))\n (value (cdr pair)))\n (cons key (remq key value))))w\n\n(define (remove-self-dependencies alist)\n (map remove-self-dependency alist))\n\n(define (add-missing-items dependencies)\n (let loop ((items (delete-duplicates (append-map cdr dependencies) eq?))\n (out dependencies))\n (if (null? items)\n out\n (let ((item (car items)))\n (if (assq item out)\n (loop (cdr items) out)\n (loop (cdr items) (cons (cons item '()) out)))))))\n\n(define (lift dependencies batch)\n (let loop ((dependencies dependencies)\n (out '()))\n (if (null? dependencies)\n out\n (let ((key (caar dependencies))\n (value (cdar dependencies)))\n (if (null? value)\n (loop (cdr dependencies) out)\n (loop (cdr dependencies)\n (cons (cons key (lset-difference eq? value batch))\n out)))))))\n\n(define (topological-sort dependencies)\n (let* ((dependencies (remove-self-dependencies dependencies))\n (dependencies (add-missing-items dependencies)))\n (let loop ((out '())\n (dependencies dependencies))\n (if (null? dependencies)\n (reverse out)\n (let ((batch (map car (filter (lambda (pair) (null? (cdr pair))) dependencies))))\n (if (null? batch)\n #f\n (loop (cons batch out) (lift dependencies batch))))))))\n\n\n(define example\n '((des_system_lib . (std synopsys std_cell_lib des_system_lib dw02\n dw01 ramlib ieee))\n (dw01 . (ieee dw01 dware gtech))\n (dw02 . (ieee dw02 dware))\n (dw03 . (std synopsys dware dw03 dw02 dw01 ieee gtech))\n (dw04 . (dw04 ieee dw01 dware gtech))\n (dw05 . (dw05 ieee dware))\n (dw06 . (dw06 ieee dware))\n (dw07 . (ieee dware))\n (dware . (ieee dware))\n (gtech . (ieee gtech))\n (ramlib . (std ieee))\n (std_cell_lib . (ieee std_cell_lib))\n (synopsys . ())))\n\n(write (topological-sort example))\n\n\n(define unsortable\n '((des_system_lib . (std synopsys std_cell_lib des_system_lib dw02\n dw01 ramlib ieee))\n (dw01 . (ieee dw01 dware gtech dw04))\n (dw02 . (ieee dw02 dware))\n (dw03 . (std synopsys dware dw03 dw02 dw01 ieee gtech))\n (dw04 . (dw04 ieee dw01 dware gtech))\n (dw05 . (dw05 ieee dware))\n (dw06 . (dw06 ieee dware))\n (dw07 . (ieee dware))\n (dware . (ieee dware))\n (gtech . (ieee gtech))\n (ramlib . (std ieee))\n (std_cell_lib . (ieee std_cell_lib))\n (synopsys . ())))\n\n(newline)\n(write (topological-sort unsortable))\n\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":526} {"lang_cluster":"Scheme","source_code":"\n(import (scheme base)\n (scheme write)\n (srfi 1))\n\n;; return all combinations of size elements from given set\n(define (combinations size set unique?)\n (if (zero? size)\n (list '())\n (let loop ((base-combns (combinations (- size 1) set unique?))\n (results '())\n (items set))\n (cond ((null? base-combns) ; end, as no base-combinations to process\n results)\n ((null? items) ; check next base-combination\n (loop (cdr base-combns)\n results\n set))\n ((and unique? ; ignore if wanting list unique\n (member (car items) (car base-combns) =))\n (loop base-combns\n results\n (cdr items)))\n (else ; keep the new combination\n (loop base-combns\n (cons (cons (car items) (car base-combns))\n results)\n (cdr items)))))))\n\n;; checks if all 4 sums are the same\n(define (solution? a b c d e f g)\n (= (+ a b)\n (+ b c d)\n (+ d e f)\n (+ f g)))\n\n;; Tasks\n(display \"Solutions: LOW=1 HIGH=7\\n\")\n(display (filter (lambda (combination) (apply solution? combination))\n (combinations 7 (iota 7 1) #t))) (newline)\n\n(display \"Solutions: LOW=3 HIGH=9\\n\")\n(display (filter (lambda (combination) (apply solution? combination))\n (combinations 7 (iota 7 3) #t))) (newline)\n\n(display \"Solution count: LOW=0 HIGH=9 non-unique\\n\")\n(display (count (lambda (combination) (apply solution? combination))\n (combinations 7 (iota 10 0) #f))) (newline)\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":527} {"lang_cluster":"Scheme","source_code":"\nLibrary: Scheme\/PsTk\n\n(import (scheme base)\n (scheme inexact)\n (scheme time)\n (pstk))\n\n(define PI 3.1415927)\n\n;; Draws the hands on the canvas using the current time, and repeats each second\n(define (hands canvas)\n (canvas 'delete 'withtag \"hands\")\n\n (let* ((time (current-second)) ; no time locality used, so displays time in GMT\n (hours (floor (\/ time 3600)))\n (rem (- time (* hours 3600)))\n (mins (floor (\/ rem 60)))\n (secs (- rem (* mins 60)))\n (second-angle (* secs (* 2 PI 1\/60)))\n (minute-angle (* mins (* 2 PI 1\/60)))\n (hour-angle (* hours (* 2 PI 1\/12))))\n (canvas 'create 'line ; second hand\n 100 100 \n (+ 100 (* 90 (sin second-angle)))\n (- 100 (* 90 (cos second-angle)))\n 'width: 1 'tags: \"hands\")\n (canvas 'create 'line ; minute hand\n 100 100 \n (+ 100 (* 85 (sin minute-angle)))\n (- 100 (* 85 (cos minute-angle)))\n 'width: 3 \n 'capstyle: \"projecting\"\n 'tags: \"hands\")\n (canvas 'create 'line ; hour hand\n 100 100 \n (+ 100 (* 60 (sin hour-angle)))\n (- 100 (* 60 (cos hour-angle)))\n 'width: 7 \n 'capstyle: \"projecting\"\n 'tags: \"hands\"))\n (tk\/after 1000 (lambda () (hands canvas))))\n\n;; Create the initial frame, clock frame and hours\n(let ((tk (tk-start)))\n (tk\/wm 'title tk \"GMT Clock\")\n\n (let ((canvas (tk 'create-widget 'canvas)))\n (tk\/pack canvas)\n (canvas 'configure 'height: 200 'width: 200)\n (canvas 'create 'oval 2 2 198 198 'fill: \"white\" 'outline: \"black\")\n (do ((h 1 (+ 1 h)))\n ((> h 12) )\n (let ((angle (- (\/ PI 2) (* h PI 1\/6))))\n (canvas 'create 'text \n (+ 100 (* 90 (cos angle)))\n (- 100 (* 90 (sin angle)))\n 'text: (number->string h)\n 'font: \"{Helvetica -12}\")))\n\n (hands canvas))\n (tk-event-loop tk))\n\n","human_summarization":"The code creates a simple, animated time-keeping device that updates every second. It can be any form of clock, such as a stopwatch, hourglass, sundial, etc., but it must clearly display the change in seconds. The code is designed to be efficient, not overusing CPU resources by unnecessary polling of the system timer. It is also written to be clear and concise, avoiding unnecessary complexity. The code includes a translation of a Tcl example that displays an analogue clock with three hands.","id":528} {"lang_cluster":"Scheme","source_code":"\nWorks with: Gauche Scheme\n(use srfi-42)\n\n(define (py perim)\n (define prim 0)\n (values\n (sum-ec\n (: c perim) (: b c) (: a b)\n (if (and (<= (+ a b c) perim)\n (= (square c) (+ (square b) (square a)))))\n (begin (when (= 1 (gcd a b)) (inc! prim)))\n 1)\n prim))\n\n\ngosh> (py 100)\n17\n7\n\n","human_summarization":"\"Output: The code calculates the number of Pythagorean triples with a perimeter no larger than 100 and the number of these that are primitive. It also handles large values up to a maximum perimeter of 100,000,000.\"","id":529} {"lang_cluster":"Scheme","source_code":"\nLibrary: Scheme\/PsTk\n#!r6rs\n\n;; PS-TK example: display simple frame\n\n(import (rnrs) \n (lib pstk main) ; change this to refer to your installation of PS\/Tk\n )\n\n(define tk (tk-start))\n(tk\/wm 'title tk \"PS-Tk Example: Frame\")\n\n(tk-event-loop tk)\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":530} {"lang_cluster":"Scheme","source_code":"\n\n(use-modules (ice-9 format))\n\n(define (char-freq port table)\n (if\n (eof-object? (peek-char port))\n table\n (char-freq port (add-char (read-char port) table))))\n\n(define (add-char char table)\n (cond\n ((null? table) (list (list char 1)))\n ((eq? (caar table) char) (cons (list char (+ (cadar table) 1)) (cdr table)))\n (#t (cons (car table) (add-char char (cdr table))))))\n\n(define (format-table table)\n (for-each (lambda (t) (format #t \"~10s~10d~%\" (car t) (cadr t))) table))\n\n(define (print-freq filename)\n (format-table (char-freq (open-input-file filename) '())))\n\n(print-freq \"letter-frequency.scm\")\n\n\n#\\( 45\n#\\u 5\n#\\s 9\n#\\e 47\n#\\- 19\n#\\m 9\n#\\o 16\n#\\d 19\n#\\l 25\n#\\space 83\n#\\i 15\n#\\c 28\n#\\9 1\n#\\f 20\n#\\r 39\n#\\a 47\n#\\t 36\n#\\) 45\n#\\newline 21\n#\\n 15\n#\\h 14\n#\\q 7\n#\\p 9\n#\\b 16\n#\\j 1\n#\\? 3\n#\\k 1\n#\\1 4\n#\\+ 1\n#\\# 2\n#\\\" 4\n#\\~ 3\n#\\0 2\n#\\% 1\n#\\' 1\n#\\y 1\n#\\. 1\n\n\n(with-input-from-string \"foobar\"\n (lambda ()\n (port-fold (lambda (x s)\n (alist-update x\n (add1 (alist-ref x s eq? 0))\n s))\n '()\n read-char)))\n\n\n","human_summarization":"The code opens a text file and counts the frequency of each letter. It may count all characters, including punctuation, or only letters from A to Z. The code is implemented in Guile Scheme 2.0.11 and CHICKEN Scheme, and the output is displayed in no particular order. An example output from reading its own source is shown as ((#\\f . 1) (#\\o . 2) (#\\b . 1) (#\\a . 1) (#\\r . 1)).","id":531} {"lang_cluster":"Scheme","source_code":"\n\n(cons value next)\n\n\n(car my-list) ; returns the first element of the list\n(cdr my-list) ; returns the remainder of the list\n\n\n(set-car! my-list new-elem)\n(set-cdr! my-list new-next)\n\n","human_summarization":"define a data structure for a singly-linked list element. This element holds a numeric value and a mutable link to the next element. The element, also known as a cons-pair in Lisp dialects, can be constructed, deconstructed, and mutated using specific functions.","id":532} {"lang_cluster":"Scheme","source_code":"\n\n(import (scheme base)\n (scheme file)\n (scheme inexact)\n (scheme write))\n\n(define *scale* 10) ; controls overall size of tree\n(define *split* 20) ; controls angle of split (in degrees)\n\n;; construct lines for tree as list of 5-tuples (x1 y1 x2 y2 depth)\n;; - x1 y1 is start point\n;; - angle of this line, in radians\n;; - depth, depth within tree (controls length of line)\n(define (create-tree x1 y1 angle depth)\n (define (degrees->radians d)\n (let ((pi 3.14159265358979323846264338327950288419716939937510582097))\n (* d pi 1\/180)))\n ;\n (if (zero? depth)\n '()\n (let ((x2 (+ x1 (* (cos (degrees->radians angle)) depth *scale*)))\n (y2 (+ y1 (* (sin (degrees->radians angle)) depth *scale*))))\n (append (list (map truncate (list x1 y1 x2 y2 depth)))\n (create-tree x2 y2 (- angle *split*) (- depth 1))\n (create-tree x2 y2 (+ angle *split*) (- depth 1))))))\n\n;; output the tree to an eps file\n(define (output-tree-as-eps filename tree)\n (when (file-exists? filename) (delete-file filename))\n (with-output-to-file\n filename\n (lambda ()\n (display \"%!PS-Adobe-3.0 EPSF-3.0\\n%%BoundingBox: 0 0 800 800\\n\") \n\n ;; add each line - sets linewidth based on depth in tree\n (for-each (lambda (line)\n (display\n (string-append \"newpath\\n\"\n (number->string (list-ref line 0)) \" \"\n (number->string (list-ref line 1)) \" \"\n \"moveto\\n\"\n (number->string (list-ref line 2)) \" \"\n (number->string (list-ref line 3)) \" \"\n \"lineto\\n\"\n (number->string (truncate (\/ (list-ref line 4) 2)))\n \" setlinewidth\\n\"\n \"stroke\\n\"\n )))\n tree)\n (display \"\\n%%EOF\"))))\n\n(output-tree-as-eps \"fractal.eps\" (create-tree 400 200 90 9))\n\n","human_summarization":"The code generates a fractal tree by drawing a trunk, splitting it at the end at a certain angle to form branches, and repeating this process until a desired level of branching is reached. The tree is represented as a list of line segments and is output to an EPS file.","id":533} {"lang_cluster":"Scheme","source_code":"\n\n(define (factors n)\n (define (*factors d)\n (cond ((> d n) (list))\n ((= (modulo n d) 0) (cons d (*factors (+ d 1))))\n (else (*factors (+ d 1)))))\n (*factors 1))\n\n(display (factors 1111111))\n(newline)\n\n","human_summarization":"calculate the factors of a positive integer using a trial division algorithm. The factors are the positive integers that can divide the input number to yield a positive integer result. The code does not handle cases of zero or negative integers. For prime numbers, the factors will be 1 and the number itself.","id":534} {"lang_cluster":"Scheme","source_code":"\n(import (scheme base)\n (scheme write)\n (srfi 1)\n (except (srfi 13) string-for-each string-map)\n (srfi 14))\n\n;; text is a list of lines, alignment is left\/right\/center\n;; displays the aligned text in columns with a single space gap\n(define (align-columns text alignment)\n (define (split line) ; splits string on $ into list of strings\n (string-tokenize line (char-set-complement (->char-set \"$\"))))\n (define (extend lst n) ; extends list to length n, by adding \"\" to end\n (append lst (make-list (- n (length lst)) \"\")))\n (define (align-word word width) ; align single word to fit width\n (case alignment\n ((left) (string-pad-right word width))\n ((right) (string-pad word width))\n ((center) (let ((rem (- width (string-length word))))\n (string-pad-right (string-pad word (- width (truncate (\/ rem 2))))\n width)))))\n ;\n (display alignment) (newline)\n (let* ((text-list (map split text))\n (max-line-len (fold (lambda (text val) (max (length text) val)) 0 text-list))\n (text-lines (map (lambda (line) (extend line max-line-len)) text-list))\n (min-col-widths (map (lambda (col) \n (fold (lambda (line val) \n (max (string-length (list-ref line col))\n val)) \n 0 \n text-lines))\n (iota max-line-len))))\n (map (lambda (line) \n (map (lambda (word width) \n (display (string-append (align-word word width)\n \" \")))\n line min-col-widths)\n (newline))\n text-lines))\n (newline))\n\n;; show example\n(define *example* \n '(\"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n \"are$delineated$by$a$single$'dollar'$character,$write$a$program\"\n \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n \"column$are$separated$by$at$least$one$space.\"\n \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\n \"justified,$right$justified,$or$center$justified$within$its$column.\"))\n\n(align-columns *example* 'left)\n(align-columns *example* 'center)\n(align-columns *example* 'right)\n\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":535} {"lang_cluster":"Scheme","source_code":"\n(define (rot13 str)\n (define (rot13-char c)\n (integer->char (+ (char->integer c)\n (cond ((and (char>=? c #\\a) (char=? c #\\A) (char=? c #\\n) (char<=? c #\\z))\n -13)\n ((and (char>=? c #\\N) (char<=? c #\\Z))\n -13)\n (else\n 0)))))\n (list->string (map rot13-char (string->list str))))\nWorks with: Chibi-Scheme\nWorks with: Chicken Scheme\nWorks with: Gambit Scheme\nWorks with: Gauche\nWorks with: Guile\n\nfewer redundant tests\nloops over input lines\nconforms to R7RS\n;; Works with: chibi, csi, gosh, gsi, guile\n(cond-expand\n (r7rs (import (scheme base)\n (scheme write)))\n (gambit)\n (chicken (import (r7rs))))\n\n(define char-rot13\n (let* ((A (char->integer #\\A))\n (N (char->integer #\\N))\n (Z (char->integer #\\Z))\n (a (char->integer #\\a))\n (n (char->integer #\\n))\n (z (char->integer #\\z))\n (inc 13)\n (dec (- inc))\n (rot (lambda (c direction)\n (integer->char (+ c direction)))))\n (lambda (ch)\n (let ((c (char->integer ch)))\n (if (>= c A)\n (if (< c N)\n (rot c inc)\n (if (<= c Z)\n (rot c dec)\n (if (>= c a)\n (if (< c n)\n (rot c inc)\n (if (<= c z)\n (rot c dec)\n ch))))))))))\n\n(define (string-rot13 str)\n (string-map char-rot13 str))\n\n(if (not (and (string=? (string-rot13 \"abcdefghijklmnopqrstuvwxyz\")\n \"nopqrstuvwxyzabcdefghijklm\")\n (string=? (string-rot13 \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n \"NOPQRSTUVWXYZABCDEFGHIJKLM\")))\n (error \"Test failed.\"))\n\n(let loop ((line (read-line)))\n (if (string? line)\n (begin\n (display (string-rot13 line))\n (newline)\n (loop (read-line)))))\n","human_summarization":"The code implements a rot-13 function, which is a simple mono-alphabetic substitution cipher that replaces each letter of the ASCII alphabet with the letter rotated 13 characters around the 26 letter alphabet. The function preserves case and passes all non-alphabetic characters in the input stream through without alteration. It can be optionally wrapped in a utility program that performs line-by-line rot-13 encoding of every line of input from specified files or standard input, similar to a common UNIX utility. This function is commonly used for obfuscating text to prevent casual reading of spoilers or offensive material.","id":536} {"lang_cluster":"Scheme","source_code":"\n(do ((i 1 (+ i 1)))\n ((> i 5))\n (do ((j 1 (+ j 1)))\n ((> j i))\n (display \"*\"))\n (newline))\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":537} {"lang_cluster":"Scheme","source_code":"\n\n(define my-dict '((a b) (1 hello) (\"c\" (a b c)))\n(assoc 'a my-dict) \u00a0; evaluates to '(a b)\n\n(define my-alist '((a b) (1 hello) (\"c\" (a b c)))\n(define my-hash (alist->hash-table my-alist))\n\n#!r6rs\n\n(import (rnrs base)\n (rnrs hashtables (6)))\n\n(define my-hash (make-hashtable equal-hash equal?))\n(hashtable-set! my-hash 'a 'b)\n(hashtable-set! my-hash 1 'hello)\n(hashtable-set! my-hash \"c\" '(a b c))\nWorks with: CHICKEN version 5.3.0\nLibrary: r7rs\nLibrary: srfi-1\nLibrary: srfi-151\n\n(cond-expand\n (r7rs)\n (chicken (import r7rs)))\n\n(define-library (avl-trees)\n\n \u00a0;;\n \u00a0;; This library implements \u2018persistent\u2019 (that is, \u2018immutable\u2019) AVL\n \u00a0;; trees for R7RS Scheme.\n \u00a0;;\n \u00a0;; References:\n \u00a0;;\n \u00a0;; * Niklaus Wirth, 1976. Algorithms + Data Structures =\n \u00a0;; Programs. Prentice-Hall, Englewood Cliffs, New Jersey.\n \u00a0;;\n \u00a0;; * Niklaus Wirth, 2004. Algorithms and Data Structures. Updated\n \u00a0;; by Fyodor Tkachov, 2014.\n \u00a0;;\n \u00a0;; THIS IS A TRIMMED-DOWN VERSION OF MY SOLUTION TO THE AVL TREES\n \u00a0;; TASK: https:\/\/rosettacode.org\/wiki\/AVL_tree#Scheme\n \u00a0;;\n\n (export avl)\n (export avl?)\n (export avl-empty?)\n (export avl-insert)\n (export avl-search-values)\n (export avl-check-usage)\n\n (import (scheme base))\n (import (scheme case-lambda))\n (import (scheme process-context))\n (import (scheme write))\n\n (begin\n\n (define-syntax avl-check-usage\n (syntax-rules ()\n ((_ pred msg)\n (or pred (usage-error msg)))))\n\n (define-record-type \n (%avl key data bal left right)\n avl?\n (key %key)\n (data %data)\n (bal %bal)\n (left %left)\n (right %right))\n\n (define (avl)\n (%avl #f #f #f #f #f))\n\n (define (avl-empty? tree)\n (avl-check-usage\n (avl? tree)\n \"avl-empty? expects an AVL tree as argument\")\n (not (%bal tree)))\n\n (define (avl-search-values pred\n (%assoc-array hashfunc pred=? default table)\n assoc-array?\n (hashfunc %hashfunc)\n (pred=? %pred=?)\n (default %default)\n (table %table))\n\n (define assoc-array\n \u00a0;; Create an associative array.\n (case-lambda\n ((hashfunc)\n (let ((pred=? equal?)\n (default #f))\n (assoc-array hashfunc pred=? default)))\n ((hashfunc pred=?)\n (let ((default #f))\n (assoc-array hashfunc pred=? default)))\n ((hashfunc pred=? default)\n (%assoc-array hashfunc pred=? default (avl)))))\n\n (define (assoc-array-set array key data)\n \u00a0;; Produce a new associative array that is the same as the input\n \u00a0;; array except for the given key-data association. The input\n \u00a0;; array is left unchanged (which is why the procedure is called\n \u00a0;; \u2018assoc-array-set\u2019 rather than \u2018assoc-array-set!\u2019).\n (let ((hashfunc (%hashfunc array))\n (pred=? (%pred=? array))\n (default (%default array))\n (table (%table array)))\n (let ((hash-value (hashfunc key)))\n \u00a0;; The following could be made more efficient by combining\n \u00a0;; the \u2018search\u2019 and \u2018insert\u2019 operations for the AVL tree.\n (let*-values\n (((alst found?) (avl-search-values < table hash-value)))\n (cond\n (found?\n \u00a0;; Add a new entry to the association list. Removal of\n \u00a0;; any old associations with the key is not strictly\n \u00a0;; necessary, but without it the associative array will\n \u00a0;; grow every time you replace an\n \u00a0;; association. (Alternatively, you could occasionally\n \u00a0;; clean the associative array of shadowed key\n \u00a0;; associations.)\n (let* ((alst (alist-delete key alst pred=?))\n (alst `((,key . ,data) . ,alst))\n (table (avl-insert < table hash-value alst)))\n (%assoc-array hashfunc pred=? default table)))\n (else\n \u00a0;; Start a new association list.\n (let* ((alst `((,key . ,data)))\n (table (avl-insert < table hash-value alst)))\n (%assoc-array hashfunc pred=? default table))))))))\n\n (define (assoc-array-ref array key)\n \u00a0;; Return the data associated with the key. If the key is not in\n \u00a0;; the table, return the associative array\u2019s default data.\n (let* ((hashfunc (%hashfunc array))\n (hash-value (hashfunc key)))\n (let*-values\n (((alst found?)\n (avl-search-values < (%table array) hash-value)))\n (if found?\n (let ((pair (assoc key alst (%pred=? array))))\n (if pair\n (cdr pair)\n (%default array)))\n (%default array)))))\n\n ))\u00a0;; end library (associative-arrays)\n\n\n(cond-expand\n (DEMONSTRATION\n (begin\n (import (scheme base))\n (import (scheme write))\n (import (srfi 151))\n (import (associative-arrays))\n\n \u00a0;; I like SpookyHash, but for this demonstration I shall use the\n \u00a0;; simpler \u2018ElfHash\u2019 and define it only for strings. See\n \u00a0;; https:\/\/en.wikipedia.org\/w\/index.php?title=PJW_hash_function&oldid=997863283\n (define (hashfunc s)\n (let ((n (string-length s))\n (h 0))\n (do ((i 0 (+ i 1)))\n ((= i n))\n (let* ((ch\n \u00a0;; If the character is outside the 8-bit range,\n \u00a0;; probably I should break it into four bytes, each\n \u00a0;; incorporated separately into the hash. For this\n \u00a0;; demonstration, I shall simply discard the higher\n \u00a0;; bits.\n (bitwise-and (char->integer (string-ref s i))\n #xFF))\n (h^ (+ (arithmetic-shift h 4) ch))\n (high^ (bitwise-and h^ #xF0000000)))\n (unless (zero? high^)\n (set! h^\n (bitwise-xor h^ (arithmetic-shift high^ -24))))\n (set! h (bitwise-and h^ (bitwise-not high^)))))\n h))\n\n (let* ((a1 (assoc-array hashfunc))\n (a2 (assoc-array-set a1 \"A\" #\\A))\n (a3 (assoc-array-set a2 \"B\" #x42))\u00a0; ASCII \u2018B\u2019.\n (a4 (assoc-array-set a3 \"C\" \"C\")))\n (write (assoc-array-ref a1 \"A\")) (newline)\n (write (assoc-array-ref a1 \"B\")) (newline)\n (write (assoc-array-ref a1 \"C\")) (newline)\n (write (assoc-array-ref a2 \"A\")) (newline)\n (write (assoc-array-ref a2 \"B\")) (newline)\n (write (assoc-array-ref a2 \"C\")) (newline)\n (write (assoc-array-ref a3 \"A\")) (newline)\n (write (assoc-array-ref a3 \"B\")) (newline)\n (write (assoc-array-ref a3 \"C\")) (newline)\n (write (assoc-array-ref a4 \"A\")) (newline)\n (write (assoc-array-ref a4 \"B\")) (newline)\n (write (assoc-array-ref a4 \"C\")) (newline))\n\n ))\n (else))\n\n","human_summarization":"create an associative array or dictionary. The implementation is persistent and immutable, using AVL Tree task code. It also includes generators or iterators that are executable procedures. This is not a native feature of Scheme but a library add-on. The performance is logarithmic on average due to the nature of the AVL Tree.","id":538} {"lang_cluster":"Scheme","source_code":"\n\n(import (scheme base)\n (scheme write))\n\n(define ((bsd-rand state))\n (set! state (remainder (+ (* 1103515245 state) 12345) 2147483648))\n state)\n\n(define ((msvcrt-rand state))\n (set! state (remainder (+ (* 214013 state) 2531011) 2147483648))\n (quotient state 65536))\n\n; auxiliary function to get a list of 'n random numbers from generator 'r\n(define (rand-list r n)\n (if (zero? n) '() (cons (r) (rand-list r (- n 1)))))\n\n(display (rand-list (bsd-rand 0) 10))\n; (12345 1406932606 654583775 1449466924 229283573 1109335178 1051550459 1293799192 794471793 551188310)\n\n(newline)\n\n(display (rand-list (msvcrt-rand 0) 10))\n; (38 7719 21238 2437 8855 11797 8365 32285 10450 30612)\n\n","human_summarization":"The code replicates two historic random number generators - the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). It uses the linear congruential generator formula to generate a sequence of random numbers, given a seed. The generated sequence matches the sequence produced by the original generators when starting from the same seed. The BSD formula generates random numbers in the range 0 to 2147483647, while the Microsoft formula generates random numbers in the range 0 to 32767.","id":539} {"lang_cluster":"Scheme","source_code":"\n\n(define (insert-after a b lst)\n (if (null? lst)\n lst ; This should be an error, but we will just return the list untouched\n (let ((c (car lst))\n (cs (cdr lst)))\n (if (equal? a c)\n (cons a (cons b cs))\n (cons c (insert-after a b cs))))))\n\n\n(define (insert-after! a b lst)\n (let ((pos (member a lst)))\n (if pos\n (set-cdr! pos (cons b (cdr pos))))))\n\n","human_summarization":"\"Implement a method to insert an element into a singly-linked list after a given element. Specifically, the code inserts element C into a list of elements A->B, following element A.\"","id":540} {"lang_cluster":"Scheme","source_code":"\n\n(define (halve num)\n (quotient num 2))\n\n(define (double num)\n (* num 2))\n\n(define (*mul-eth plier plicand acc)\n (cond ((zero? plier) acc)\n ((even? plier) (*mul-eth (halve plier) (double plicand) acc))\n (else (*mul-eth (halve plier) (double plicand) (+ acc plicand)))))\n\n(define (mul-eth plier plicand)\n (*mul-eth plier plicand 0))\n\n(display (mul-eth 17 34))\n(newline)\n\n578\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method that multiplies two integers using only addition, doubling, and halving. The multiplication process involves creating a table where the left column repeatedly halves a number until it reaches 1, and the right column doubles a number in sync. Rows where the left column has an even number are discarded, and the remaining values in the right column are summed to get the multiplication result.","id":541} {"lang_cluster":"Scheme","source_code":"\n\n#!r6rs\n\n(import (rnrs)\n (rnrs eval)\n (only (srfi :1 lists) append-map delete-duplicates iota))\n\n(define (map* fn . lis)\n (if (null? lis)\n (list (fn))\n (append-map (lambda (x)\n (apply map*\n (lambda xs (apply fn x xs))\n (cdr lis)))\n (car lis))))\n\n(define (insert x li n)\n (if (= n 0)\n (cons x li)\n (cons (car li) (insert x (cdr li) (- n 1)))))\n\n(define (permutations li)\n (if (null? li)\n (list ())\n (map* insert (list (car li)) (permutations (cdr li)) (iota (length li)))))\n\n(define (evaluates-to-24 expr)\n (guard (e ((assertion-violation? e) #f))\n (= 24 (eval expr (environment '(rnrs base))))))\n\n(define (tree n o0 o1 o2 xs)\n (list-ref\n (list\n `(,o0 (,o1 (,o2 ,(car xs) ,(cadr xs)) ,(caddr xs)) ,(cadddr xs))\n `(,o0 (,o1 (,o2 ,(car xs) ,(cadr xs)) ,(caddr xs)) ,(cadddr xs))\n `(,o0 (,o1 ,(car xs) (,o2 ,(cadr xs) ,(caddr xs))) ,(cadddr xs))\n `(,o0 (,o1 ,(car xs) ,(cadr xs)) (,o2 ,(caddr xs) ,(cadddr xs)))\n `(,o0 ,(car xs) (,o1 (,o2 ,(cadr xs) ,(caddr xs)) ,(cadddr xs)))\n `(,o0 ,(car xs) (,o1 ,(cadr xs) (,o2 ,(caddr xs) ,(cadddr xs)))))\n n))\n\n(define (solve a b c d)\n (define ops '(+ - * \/))\n (define perms (delete-duplicates (permutations (list a b c d))))\n (delete-duplicates\n (filter evaluates-to-24\n (map* tree (iota 6) ops ops ops perms))))\n\n\n> (solve 1 3 5 7)\n((* (+ 1 5) (- 7 3))\n (* (+ 5 1) (- 7 3))\n (* (+ 5 7) (- 3 1))\n (* (+ 7 5) (- 3 1))\n (* (- 3 1) (+ 5 7))\n (* (- 3 1) (+ 7 5))\n (* (- 7 3) (+ 1 5))\n (* (- 7 3) (+ 5 1)))\n> (solve 3 3 8 8)\n((\/ 8 (- 3 (\/ 8 3))))\n> (solve 3 4 9 10)\n()\n\n","human_summarization":"The code takes four digits as input, either from the user or generated randomly, and computes arithmetic expressions according to the rules of the 24 game. It also provides examples of solutions it has generated. The code outputs an S-expression that evaluates to 24.","id":542} {"lang_cluster":"Scheme","source_code":"\n(define (factorial n)\n (if (<= n 0)\n 1\n (* n (factorial (- n 1)))))\n\n(define (factorial n)\n (let loop ((i 1)\n (accum 1))\n (if (> i n)\n accum\n (loop (+ i 1) (* accum i)))))\n(define (factorial n)\n (do ((i 1 (+ i 1))\n (accum 1 (* accum i)))\n ((> i n) accum)))\n;Using a generator and a function that apply generated values to a function taking two arguments\n\n;A generator knows commands 'next? and 'next\n(define (range a b)\n(let ((k a))\n(lambda (msg)\n(cond\n\t((eq? msg 'next?) (<= k b))\n\t((eq? msg 'next)\n\t(cond\n\t\t((<= k b) (set! k (+ k 1)) (- k 1))\n\t\t(else 'nothing-left)))))))\n\n;Similar to List.fold_left in OCaml, but uses a generator\n(define (fold fun a gen)\n(let aux ((a a))\n\t(if (gen 'next?) (aux (fun a (gen 'next))) a)))\n\n;Now the factorial function\n(define (factorial n) (fold * 1 (range 1 n)))\n\n(factorial 8)\n;40320\n","human_summarization":"\"Function to calculate the factorial of a number using either iterative or recursive methods, with optional error handling for negative input values.\"","id":543} {"lang_cluster":"Scheme","source_code":"\nWorks with: any R6RS Scheme\n;generate a random non-repeating list of 4 digits, 1-9 inclusive\n(define (get-num)\n (define (gen lst)\n (if (= (length lst) 4) lst\n (let ((digit (+ (random 9) 1)))\n (if (member digit lst) ;make sure the new digit isn't in the\n ;list\n (gen lst)\n (gen (cons digit lst))))))\n (string->list (apply string-append (map number->string (gen '())))))\n\n;is g a valid guess (that is, non-repeating, four digits 1-9\n;inclusive?)\n(define (valid-guess? g)\n (let ((g-num (string->number (apply string g))))\n ;does the same digit appear twice in lst?\n (define (repeats? lst)\n (cond ((null? lst) #f)\n ((member (car lst) (cdr lst)) #t)\n (else (repeats? (cdr lst)))))\n (and g-num\n (> g-num 1233)\n (< g-num 9877)\n (not (repeats? g)))))\n\n;return '(cows bulls) for the given guess\n(define (score answer guess)\n ;total cows + bulls\n (define (cows&bulls a g)\n (cond ((null? a) 0)\n ((member (car a) g) (+ 1 (cows&bulls (cdr a) g)))\n (else (cows&bulls (cdr a) g))))\n ;bulls only\n (define (bulls a g)\n (cond ((null? a) 0)\n ((equal? (car a) (car g)) (+ 1 (bulls (cdr a) (cdr g))))\n (else (bulls (cdr a) (cdr g)))))\n (list (- (cows&bulls answer guess) (bulls answer guess)) (bulls answer guess)))\n\n;play the game\n(define (bull-cow answer)\n ;get the user's guess as a list\n (define (get-guess)\n (let ((e (read)))\n (if (number? e)\n (string->list (number->string e))\n (string->list (symbol->string e)))))\n (display \"Enter a guess: \")\n (let ((guess (get-guess)))\n (if (valid-guess? guess)\n (let ((bulls (cadr (score answer guess)))\n (cows (car (score answer guess))))\n (if (= bulls 4)\n (display \"You win!\\n\")\n (begin\n (display bulls)\n (display \" bulls, \")\n (display cows)\n (display \" cows.\\n\")\n (bull-cow answer))))\n (begin\n (display \"Invalid guess.\\n\")\n (bull-cow answer)))))\n\n(bull-cow (get-num))\n\nEnter a guess: 1234\n0 bulls, 1 cows.\nEnter a guess: 2345\n1 bulls, 0 cows.\nEnter a guess: 2346\n1 bulls, 1 cows.\nEnter a guess: 2367\n0 bulls, 1 cows.\nEnter a guess: 2647\n1 bulls, 1 cows.\nEnter a guess: 2648\n2 bulls, 1 cows.\nEnter a guess: 2468\n1 bulls, 2 cows.\nEnter a guess: 1468\n1 bulls, 2 cows.\nEnter a guess: 2684\n0 bulls, 3 cows.\nEnter a guess: 6248\n3 bulls, 0 cows.\nEnter a guess: 6948\nYou win!\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":544} {"lang_cluster":"Scheme","source_code":"\n; linear congruential generator given in C99 section 7.20.2.1\n(define ((c-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) (quotient seed 65536))\n\n; uniform real numbers in open interval (0, 1)\n(define (unif-rand seed) (let ((r (c-rand seed))) (lambda () (\/ (+ (r) 1) 32769.0))))\n\n; Box-Muller method to generate normal distribution\n(define (normal-rand unif m s)\n(let ((? #t) (! 0.0) (twopi (* 2.0 (acos -1.0))))\n(lambda ()\n (set! ? (not ?))\n (if ? !\n (let ((a (sqrt (* -2.0 (log (unif))))) (b (* twopi (unif))))\n (set! ! (+ m (* s a (sin b))))\n (+ m (* s a (cos b))))))))\n\n(define rnorm (normal-rand (unif-rand 0) 1.0 0.5))\n\n; auxiliary function to get a list of 'n random numbers from generator 'r\n(define (rand-list r n) = (if (zero? n) '() (cons (r) (rand-list r (- n 1)))))\n\n(define v (rand-list rnorm 1000))\n\nv\n#|\n(-0.27965824722565835\n -0.8870860825789542\n 0.6499618744638194\n 0.31336141955110863\n ...\n 0.5648743998193049\n 0.8282656735558756\n 0.6399951934564637\n 0.7699535302478072)\n|#\n\n; check mean and standard deviation\n(define (mean-sdev v)\n(let loop ((v v) (a 0) (b 0) (n 0))\n(if (null? v)\n (let ((mean (\/ a n)))\n (list mean (sqrt (\/ (- b (* n mean mean)) (- n 1)))))\n (let ((x (car v)))\n (loop (cdr v) (+ a x) (+ b (* x x)) (+ n 1))))))\n\n(mean-sdev v)\n; (0.9562156817697293 0.5097087109575911)\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":545} {"lang_cluster":"Scheme","source_code":"\nWorks with: Scheme version R\n\n\n\n\n\n5\n\n\n\n{\\displaystyle ^5}\n\nRS\n(define (dot-product a b)\n (apply + (map * a b)))\n\n(display (dot-product '(1 3 -5) '(4 -2 -1)))\n(newline)\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":546} {"lang_cluster":"Scheme","source_code":"\nWorks with: Chicken Scheme(use posix)\n(seconds->string (current-seconds))\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":547} {"lang_cluster":"Scheme","source_code":"\n\n(import (scheme base)\n (scheme write)\n (only (srfi 13) string-delete)\n (only (srfi 14) ->char-set))\n\n;; implementation in plain Scheme\n(define (strip-chars str chars)\n (let ((char-list (string->list chars)))\n (define (do-strip str-list result)\n (cond ((null? str-list)\n (reverse result))\n ((member (car str-list) char-list char=?)\n (do-strip (cdr str-list) result))\n (else\n (do-strip (cdr str-list) (cons (car str-list) result)))))\n (list->string\n (do-strip (string->list str) '()))))\n\n(display (strip-chars \"She was a soul stripper. She took my heart!\" \"aei\"))\n(newline)\n\n;; using functions in SRFI 13 and SRFI 14\n(define (strip-chars2 str chars)\n (string-delete (->char-set chars) str))\n\n(display (strip-chars2 \"She was a soul stripper. She took my heart!\" \"aei\"))\n(newline)\n\n\n","human_summarization":"The code defines a function that removes a specified set of characters from a given string. It takes two arguments: the original string and a string of characters to be removed. The function then returns the original string with all instances of the specified characters removed. Two methods are used: one using a basic loop structure, and another utilizing the SRFI libraries to create a character set and delete those characters from the string.","id":548} {"lang_cluster":"Scheme","source_code":"\nWorks with: Chicken Scheme\nWorks with: Guile\n(define (guess) \n (define number (random 11))\n (display \"Pick a number from 1 through 10.\\n> \")\n (do ((guess (read) (read)))\n ((= guess number) (display \"Well guessed!\\n\"))\n (display \"Guess again.\\n\")))\n\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":549} {"lang_cluster":"Scheme","source_code":"\nWorks with: Gauche Scheme\n(map integer->char (iota 26 (char->integer #\\a)))\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":550} {"lang_cluster":"Scheme","source_code":"\n(display (number->string 5 2)) (newline)\n(display (number->string 50 2)) (newline)\n(display (number->string 9000 2)) (newline)\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":551} {"lang_cluster":"Scheme","source_code":"\n(define earth-radius 6371)\n(define pi (acos -1))\n\n(define (distance lat1 long1 lat2 long2)\n(define (h a b) (expt (sin (\/ (- b a) 2)) 2))\n(* 2 earth-radius (asin (sqrt (+ (h lat1 lat2) (* (cos lat1) (cos lat2) (h long1 long2)))))))\n\n(define (deg-to-rad d m s) (* (\/ pi 180) (+ d (\/ m 60) (\/ s 3600))))\n\n(distance (deg-to-rad 36 7.2 0) (deg-to-rad 86 40.2 0)\n (deg-to-rad 33 56.4 0) (deg-to-rad 118 24.0 0))\n; 2886.444442837984\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":552} {"lang_cluster":"Scheme","source_code":"\nWorks with: Guile\n; Use the regular expression module to parse the url (included with Guile)\n(use-modules (ice-9 regex))\n\n; Set the url and parse the hostname, port, and path into variables\n(define url \"http:\/\/www.rosettacode.org\/wiki\/HTTP\")\n(define r (make-regexp \"^(http:\/\/)?([^:\/]+)(:)?(([0-9])+)?(\/.*)?\" regexp\/icase))\n(define host (match:substring (regexp-exec r url) 2))\n(define port (match:substring (regexp-exec r url) 4))\n(define path (match:substring (regexp-exec r url) 6))\n\n; Set port to 80 if it wasn't set above and convert from a string to a number\n(if (eq? port #f) (define port \"80\"))\n(define port (string->number port))\n\n; Connect to remote host on specified port\n(let ((s (socket PF_INET SOCK_STREAM 0)))\n (connect s AF_INET (car (hostent:addr-list (gethostbyname host))) port)\n\n; Send a HTTP request for the specified path\n (display \"GET \" s)\n (display path s)\n (display \" HTTP\/1.0\\r\\n\\r\\n\" s)\n\n; Display the received HTML\n (do ((c (read-char s) (read-char s))) ((eof-object? c))\n (display c)))\nWorks with: Chicken Scheme\n\n(use http-client)\n(print\n (with-input-from-request \"http:\/\/google.com\/\"\n #f read-string))\n","human_summarization":"Accesses and prints the content of a specified URL using the http-client library. Note: This does not handle HTTPS requests.","id":553} {"lang_cluster":"Scheme","source_code":"\n(define luhn\n (lambda (n)\n (let loop ((number n)\n (index 0)\n (result 0))\n (if (= 0 number)\n (= 0 (remainder result 10))\n (loop (quotient number 10)\n (+ index 1)\n (+ result\n (if (even? index)\n (remainder number 10)\n (let ((part (* 2 (remainder number 10))))\n (+ (remainder part 10) (quotient part 10))))))))))\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":554} {"lang_cluster":"Scheme","source_code":"\n(define (string-repeat n str)\n (apply string-append (vector->list (make-vector n str))))\n\n(define (string-repeat n str)\n\t(fold string-append \"\" (make-list n str)))\n(string-repeat 5 \"ha\") ==> \"hahahahaha\"\n\n(make-string 5 #\\*)\n","human_summarization":"The code takes a string or a single character and repeats it a specified number of times. For example, it can turn \"ha\" repeated 5 times into \"hahahahaha\", or \"*\" repeated 5 times into \"*****\". It uses SRFI 1 for repeating a single character.","id":555} {"lang_cluster":"Scheme","source_code":"\n(define (arithmetic x y)\n (for-each (lambda (op)\n (write (list op x y))\n (display \" => \")\n (write ((eval op) x y))\n (newline))\n '(+ - * \/ quotient remainder modulo max min gcd lcm)))\n \n(arithmetic 8 12)\n\n prints this:\n\n(+ 8 12) => 20\n(- 8 12) => -4\n(* 8 12) => 96\n(\/ 8 12) => 2\/3\n(quotient 8 12) => 0\n(remainder 8 12) => 8\n(modulo 8 12) => 8\n(max 8 12) => 12\n(min 8 12) => 8\n(gcd 8 12) => 4\n(lcm 8 12) => 24\n\n","human_summarization":"take two integers as input, calculate and display their sum, difference, product, integer quotient, remainder, and exponentiation. The quotient is rounded towards zero and the remainder's sign matches the sign of the first operand. The code also includes an example of the `divmod` operator.","id":556} {"lang_cluster":"Scheme","source_code":"\nWorks with: Gauche Scheme\ngosh> (use gauche.lazy)\n#\ngosh> (length (lrxmatch \"th\" \"the three truths\"))\n3\ngosh> (length (lrxmatch \"abab\" \"ababababab\"))\n2\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":557} {"lang_cluster":"Scheme","source_code":"\n\n(define (towers-of-hanoi n from to spare)\n (define (print-move from to)\n (display \"Move[\")\n (display from)\n (display \", \")\n (display to)\n (display \"]\")\n (newline))\n (cond ((= n 0) \"done\")\n (else\n (towers-of-hanoi (- n 1) from spare to)\n (print-move from to)\n (towers-of-hanoi (- n 1) spare to from))))\n\n(towers-of-hanoi 3 \"A\" \"B\" \"C\")\n\n","human_summarization":"The following codes solve the Towers of Hanoi problem using a recursive process.","id":558} {"lang_cluster":"Scheme","source_code":"\nWorks with: Scheme version R\n\n\n\n\n\n5\n\n\n\n{\\displaystyle ^5}\n\nRS\n(define (factorial n)\n (define (*factorial n acc)\n (if (zero? n)\n acc\n (*factorial (- n 1) (* acc n))))\n (*factorial n 1))\n\n(define (choose n k)\n (\/ (factorial n) (* (factorial k) (factorial (- n k)))))\n\n(display (choose 5 3))\n(newline)\n\n\n","human_summarization":"\"Calculate any binomial coefficient using the provided formula, with specific functionality to output the binomial coefficient of (5,3). The code also includes tasks for combinations, permutations, and their respective versions with replacements, utilizing both direct calculation and recursive methods based on Pascal's Triangle.\"","id":559} {"lang_cluster":"Scheme","source_code":"\n(let loop ((i 1))\n (display i)\n (if (positive? (modulo i 6))\n (loop (+ i 1))))\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":560} {"lang_cluster":"Scheme","source_code":"\nWorks with: Gauche version 0.8.7 [utf-8,pthreads]\n\n(string-size \"Hello world\")\nWorks with: PLT Scheme version 4.2.4\n(bytes-length #\"Hello world\")\nWorks with: Gauche version 0.8.7 [utf-8,pthreads]\n\n (string-length \"Hello world\")\n","human_summarization":"determine the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. The codes handle non-BMP code points correctly and provide the actual character counts in code points, not in code unit counts. The codes also provide the string length in graphemes if possible. The functions used include the Gauche function 'string-size' and the R5RS, R6RS 'string-length' function.","id":561} {"lang_cluster":"Scheme","source_code":"\n(define (string-top s)\n (if (string=? s \"\") s (substring s 0 (- (string-length s) 1))))\n\n(define (string-tail s)\n (if (string=? s \"\") s (substring s 1 (string-length s))))\n\n(define (string-top-tail s)\n (string-tail (string-top s)))\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":562} {"lang_cluster":"Scheme","source_code":"\n\n#!r6rs\n(import (rnrs base (6))\n (srfi :27 random-bits))\n\n(define (semireverse li n)\n (define (continue front back n)\n (cond\n ((null? back) front)\n ((zero? n) (cons (car back) (append front (cdr back))))\n (else (continue (cons (car back) front) (cdr back) (- n 1)))))\n (continue '() li n))\n\n(define (shuffle li)\n (if (null? li)\n ()\n (let\n ((li-prime (semireverse li (random-integer (length li)))))\n (cons (car li-prime) (shuffle (cdr li-prime))))))\n\n#!r6rs\n(import (rnrs base (6))\n (srfi :27 random-bits))\n\n(define (vector-swap! vec i j)\n (let\n ((temp (vector-ref vec i)))\n (vector-set! vec i (vector-ref vec j))\n (vector-set! vec j temp)))\n\n(define (countdown n)\n (if (zero? n)\n ()\n (cons n (countdown (- n 1)))))\n\n(define (vector-shuffle! vec)\n (for-each\n (lambda (i)\n (let\n ((j (random-integer i)))\n (vector-swap! vec (- i 1) j)))\n (countdown (vector-length vec))))\n","human_summarization":"implement the Knuth shuffle (also known as Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an input array in-place, but can be modified to return a new array if necessary. The shuffling process involves iterating through the array from the last index to the first, generating a random integer within the current index range, and swapping the current element with the element at the randomly generated index. The algorithm can also be adjusted to iterate from left to right.","id":563} {"lang_cluster":"Scheme","source_code":"\n(display \"Goodbye, World!\")\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":564} {"lang_cluster":"Scheme","source_code":"\n;\n; Works with R7RS-compatible Schemes (e.g. Chibi).\n; Also current versions of Chicken, Gauche and Kawa.\n;\n(cond-expand\n (chicken (use srfi-13))\n (gauche (use srfi-13))\n (kawa (import (srfi :13)))\n (else (import (scheme base) (scheme write))))\u00a0; R7RS\n\n\n(define msg \"The quick brown fox jumps over the lazy dog.\")\n(define key 13)\n\n(define (caesar char)\n (define A (char->integer #\\A))\n (define Z (char->integer #\\Z))\n (define a (char->integer #\\a))\n (define z (char->integer #\\z))\n (define c (char->integer char))\n (integer->char\n (cond ((<= A c Z) (+ A (modulo (+ key (- c A)) 26)))\n ((<= a c z) (+ a (modulo (+ key (- c a)) 26)))\n (else c))))\u00a0; Return other characters verbatim.\n\n(display (string-map caesar msg))\n(newline)\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":565} {"lang_cluster":"Scheme","source_code":"\n>(define gcd (lambda (a b)\n (if (zero? b)\n a\n (gcd b (remainder a b)))))\n>(define lcm (lambda (a b)\n (if (or (zero? a) (zero? b))\n 0\n (abs (* b (floor (\/ a (gcd a b))))))))\n>(lcm 12 18)\n36\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":566} {"lang_cluster":"Scheme","source_code":"\nWorks with: Chicken Scheme(define host-info\n (begin\n (display \"Endianness: \")\n (display (machine-byte-order))\n (newline)\n (display \"Word Size: \")\n (display (if (fixnum? (expt 2 33)) 64 32))\n (newline)))\n\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":567} {"lang_cluster":"Scheme","source_code":"\n\n(for-each\n (lambda (i) (display i) (newline))\n the_list)\n","human_summarization":"Iterates and prints each element in a collection in order using a \"for each\" loop or an alternative loop if \"for each\" is not available.","id":568} {"lang_cluster":"Scheme","source_code":"\nWorks with: Guile\n(use-modules (ice-9 regex))\n(define s \"Hello,How,Are,You,Today\")\n(define words (map match:substring (list-matches \"[^,]+\" s)))\n\n(do ((n 0 (+ n 1))) ((= n (length words)))\n (display (list-ref words n))\n (if (< n (- (length words) 1))\n (display \".\")))\n\n(define s \"Hello,How,Are,You,Today\")\n(define words (string-tokenize s (char-set-complement (char-set #\\,))))\n(define t (string-join words \".\"))\nWorks with: Gauche Scheme\n(print\n (string-join\n (string-split \"Hello,How,Are,You,Today\" #\\,)\n \".\"))\n\n","human_summarization":"Tokenizes the string \"Hello,How,Are,You,Today\" into an array by separating it at commas, and displays the words to the user, separated by a period, including a trailing period.","id":569} {"lang_cluster":"Scheme","source_code":"\n(define (gcd a b)\n (if (= b 0)\n a\n (gcd b (modulo a b))))\n\n(gcd a b)\n","human_summarization":"find the greatest common divisor (GCD), also known as the greatest common factor (gcf) or greatest common measure, of two integers. It may also relate to finding the least common multiple. The code might utilize a standard function included with Scheme that can take any number of arguments.","id":570} {"lang_cluster":"Scheme","source_code":"\nWorks with: Guile\n\n; Needed in Guile for read-line\n(use-modules (ice-9 rdelim))\n\n; Variable used to hold child PID returned from forking\n(define child #f)\n\n; Start listening on port 12321 for connections from any address\n(let ((s (socket PF_INET SOCK_STREAM 0)))\n (setsockopt s SOL_SOCKET SO_REUSEADDR 1)\n (bind s AF_INET INADDR_ANY 12321)\n (listen s 5) ; Queue size of 5\n\n (simple-format #t \"Listening for clients in pid: ~S\" (getpid))\n (newline)\n\n; Wait for connections forever\n (while #t\n (let* ((client-connection (accept s))\n (client-details (cdr client-connection))\n (client (car client-connection)))\n; Once something connects fork\n (set! child (primitive-fork))\n (if (zero? child)\n (begin\n; Then have child fork to avoid zombie children (grandchildren aren't our responsibility)\n (set! child (primitive-fork))\n (if (zero? child)\n (begin\n; Display some connection details\n (simple-format #t \"Got new client connection: ~S\" client-details)\n (newline)\n (simple-format #t \"Client address: ~S\"\n (gethostbyaddr (sockaddr:addr client-details)))\n (newline)\n; Wait for input from client and then echo the input back forever (or until client quits)\n (do ((line (read-line client)(read-line client))) ((zero? 1))\n (display line client)(newline client))))\n; Child exits after spawning grandchild.\n (primitive-exit))\n; Parent waits for child to finish spawning grandchild\n (waitpid child)))))\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts connections, and echoes back complete lines to clients. The server is designed to handle multiple simultaneous connections and will not stop responding to other clients if one client sends a partial line or stops reading responses. It also logs connection information to standard output. The server only needs to support connections from localhost for testing purposes. The solution may be multi-threaded or multi-process.","id":571} {"lang_cluster":"Scheme","source_code":"\n\n(define (numeric? s) (string->number s))\n","human_summarization":"The function checks if a given string can be converted to a numeric value (including floating point and negative numbers) and returns a boolean value accordingly. If the string is not numeric, it returns false, otherwise, it returns true.","id":572} {"lang_cluster":"Scheme","source_code":"Works with: Guile version at least 2.0\nWorks with: Gauche Scheme version 0.9.12\nWorks with: CHICKEN Scheme version 5.3.0\nWorks with: Gambit Scheme version 4.9.4\n;;; Sutherland-Hodgman polygon clipping.\n\n(define (evaluate-line x1 y1 x2 y2 x)\n ;; Given the straight line between (x1,y1) and (x2,y2), evaluate it\n ;; at x.\n (let ((dy (- y2 y1))\n (dx (- x2 x1)))\n (let ((slope (\/ dy dx))\n (intercept (\/ (- (* dx y1) (* dy x1)) dx)))\n (+ (* slope x) intercept))))\n\n(define (intersection-of-lines x1 y1 x2 y2 x3 y3 x4 y4)\n ;; Given the line between (x1,y1) and (x2,y2), and the line between\n ;; (x3,y3) and (x4,y4), find their intersection.\n (cond ((= x1 x2) (list x1 (evaluate-line x3 y3 x4 y4 x1)))\n ((= x3 x4) (list x3 (evaluate-line x1 y1 x2 y2 x3)))\n (else (let ((denominator (- (* (- x1 x2) (- y3 y4))\n (* (- y1 y2) (- x3 x4))))\n (x1*y2-y1*x2 (- (* x1 y2) (* y1 x2)))\n (x3*y4-y3*x4 (- (* x3 y4) (* y3 x4))))\n (let ((xnumerator (- (* x1*y2-y1*x2 (- x3 x4))\n (* (- x1 x2) x3*y4-y3*x4)))\n (ynumerator (- (* x1*y2-y1*x2 (- y3 y4))\n (* (- y1 y2) x3*y4-y3*x4))))\n (list (\/ xnumerator denominator)\n (\/ ynumerator denominator)))))))\n\n(define (intersection-of-edges e1 e2)\n ;;\n ;; A point is a list of two coordinates, and an edge is a list of\n ;; two points.\n ;;\n ;; I am not using any SRFI-9 records, or the like, that define\n ;; actual new types, although I would do so if writing a more\n ;; serious implementation. Also, I am not using any pattern matcher.\n ;; A pattern matcher would make this code less tedious with\n ;; \"cadaddaddr\" notations.\n (let ((point1 (car e1))\n (point2 (cadr e1))\n (point3 (car e2))\n (point4 (cadr e2)))\n (let ((x1 (car point1))\n (y1 (cadr point1))\n (x2 (car point2))\n (y2 (cadr point2))\n (x3 (car point3))\n (y3 (cadr point3))\n (x4 (car point4))\n (y4 (cadr point4)))\n (intersection-of-lines x1 y1 x2 y2 x3 y3 x4 y4))))\n\n(define (point-is-left-of-edge? pt edge)\n (let ((x (car pt))\n (y (cadr pt))\n (x1 (caar edge))\n (y1 (cadar edge))\n (x2 (caadr edge))\n (y2 (cadadr edge)))\n ;; Outer product of the vectors (x1,y1)-->(x,y) and\n ;; (x1,y1)-->(x2,y2)\n (negative? (- (* (- x x1) (- y2 y1))\n (* (- x2 x1) (- y y1))))))\n\n(define (clip-subject-edge subject-edge clip-edge accum)\n (define left-of? point-is-left-of-edge?)\n (define (intersection)\n (intersection-of-edges subject-edge clip-edge))\n (let ((s1 (car subject-edge))\n (s2 (cadr subject-edge)))\n (let ((s2-is-inside? (left-of? s2 clip-edge))\n (s1-is-inside? (left-of? s1 clip-edge)))\n (if s2-is-inside?\n (if s1-is-inside?\n (cons s2 accum)\n (cons s2 (cons (intersection) accum)))\n (if s1-is-inside?\n (cons (intersection) accum)\n accum)))))\n\n(define (for-each-subject-edge i subject-points clip-edge accum)\n (define n (vector-length subject-points))\n (if (= i n)\n (list->vector (reverse accum))\n (let ((s2 (vector-ref subject-points i))\n (s1 (vector-ref subject-points\n (- (if (zero? i) n i) 1))))\n (let ((accum (clip-subject-edge (list s1 s2)\n clip-edge accum)))\n (for-each-subject-edge (+ i 1) subject-points\n clip-edge accum)))))\n\n(define (for-each-clip-edge i subject-points clip-points)\n (define n (vector-length clip-points))\n (if (= i n)\n subject-points\n (let ((c2 (vector-ref clip-points i))\n (c1 (vector-ref clip-points (- (if (zero? i) n i) 1))))\n (let ((subject-points\n (for-each-subject-edge 0 subject-points\n (list c1 c2) '())))\n (for-each-clip-edge (+ i 1) subject-points clip-points)))))\n\n(define (clip subject-points clip-points)\n (for-each-clip-edge 0 subject-points clip-points))\n\n(define (write-eps subject-points clip-points result-points)\n\n ;; I use only some of the most basic output procedures. Schemes tend\n ;; to include more advanced means to write output, often resembling\n ;; those of Common Lisp.\n\n (define (x pt) (exact->inexact (car pt)))\n (define (y pt) (exact->inexact (cadr pt)))\n\n (define (moveto pt)\n (display (x pt))\n (display \" \")\n (display (y pt))\n (display \" moveto\")\n (newline))\n\n (define (lineto pt)\n (display (x pt))\n (display \" \")\n (display (y pt))\n (display \" lineto\")\n (newline))\n\n (define (setrgbcolor rgb)\n (display rgb)\n (display \" setrgbcolor\")\n (newline))\n\n (define (simple-word word)\n (lambda ()\n (display word)\n (newline)))\n\n (define closepath (simple-word \"closepath\"))\n (define fill (simple-word \"fill\"))\n (define stroke (simple-word \"stroke\"))\n (define gsave (simple-word \"gsave\"))\n (define grestore (simple-word \"grestore\"))\n\n (define (showpoly poly line-color fill-color)\n (define n (vector-length poly))\n (moveto (vector-ref poly 0))\n (do ((i 1 (+ i 1)))\n ((= i n))\n (lineto (vector-ref poly i)))\n (closepath)\n (setrgbcolor line-color)\n (gsave)\n (setrgbcolor fill-color)\n (fill)\n (grestore)\n (stroke))\n\n (define (code s)\n (display s)\n (newline))\n\n (code \"%!PS-Adobe-3.0 EPSF-3.0\")\n (code \"%%BoundingBox: 40 40 360 360\")\n (code \"0 setlinewidth\")\n (showpoly clip-points \".5 0 0\" \"1 .7 .7\")\n (showpoly subject-points \"0 .2 .5\" \".4 .7 1\")\n (code \"2 setlinewidth\")\n (code \"[10 8] 0 setdash\")\n (showpoly result-points \".5 0 .5\" \".7 .3 .8\")\n (code \"%%EOF\"))\n\n(define (write-eps-to-file outfile subject-points clip-points\n result-points)\n (with-output-to-file outfile\n (lambda ()\n (write-eps subject-points clip-points result-points))))\n\n(define subject-points\n #((50 150)\n (200 50)\n (350 150)\n (350 300)\n (250 300)\n (200 250)\n (150 350)\n (100 250)\n (100 200)))\n\n(define clip-points\n #((100 100)\n (300 100)\n (300 300)\n (100 300)))\n\n(define result-points (clip subject-points clip-points))\n\n(display result-points)\n(newline)\n(write-eps-to-file \"sutherland-hodgman.eps\"\n subject-points clip-points result-points)\n(display \"Wrote sutherland-hodgman.eps\")\n(newline)\n\n\n","human_summarization":"Implement the Sutherland-Hodgman polygon clipping algorithm to find the intersection between a given polygon and a rectangle. The code takes a polygon defined by specific points and clips it by a rectangle defined by another set of points. The sequence of points defining the resulting clipped polygon is then printed. Additionally, for extra credit, the code also displays all three polygons on a graphical surface, each in a different color, and fills the resulting polygon. The origin for display can be either north-west or south-west, based on the convenience of the display mechanism.","id":573} {"lang_cluster":"Scheme","source_code":"\n(define pi (* 4 (atan 1)))\n\n(define radians (\/ pi 4))\n(define degrees 45)\n\n(display (sin radians))\n(display \" \")\n(display (sin (* degrees (\/ pi 180))))\n(newline)\n\n(display (cos radians))\n(display \" \")\n(display (cos (* degrees (\/ pi 180))))\n(newline)\n\n(display (tan radians))\n(display \" \")\n(display (tan (* degrees (\/ pi 180))))\n(newline)\n \n(define arcsin (asin (sin radians)))\n(display arcsin)\n(display \" \")\n(display (* arcsin (\/ 180 pi)))\n(newline)\n\n(define arccos (acos (cos radians)))\n(display arccos)\n(display \" \")\n(display (* arccos (\/ 180 pi)))\n(newline)\n\n(define arctan (atan (tan radians)))\n(display arctan)\n(display \" \")\n(display (* arctan (\/ 180 pi)))\n(newline)\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":574} {"lang_cluster":"Scheme","source_code":"\n(number->string (+ 1 (string->number \"1234\")))\n","human_summarization":"\"Increments a given numerical string.\"","id":575} {"lang_cluster":"Scheme","source_code":"\n(define (median l)\n (* (+ (list-ref (bubble-sort l >) (round (\/ (- (length l) 1) 2)))\n (list-ref (bubble-sort l >) (round (\/ (length l) 2)))) 0.5))\n\n(define (median l)\n (* (+ (list-ref (sort l less?) (round (\/ (- (length l) 1) 2)))\n (list-ref (sort l less?) (round (\/ (length l) 2)))) 0.5))\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers, handling cases with even numbers of elements by returning the average of the two middle values. It uses the selection algorithm for efficiency. It also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation. The code utilizes Rosetta Code's bubble-sort function and SRFI-95.","id":576} {"lang_cluster":"Scheme","source_code":"\n(do ((i 1 (+ i 1)))\n ((> i 100))\n (display\n (cond ((= 0 (modulo i 15)) \"FizzBuzz\")\n ((= 0 (modulo i 3)) \"Fizz\")\n ((= 0 (modulo i 5)) \"Buzz\")\n (else i)))\n (newline))\n\n(define (fizzbuzz x y)\n (println\n (cond (( = (modulo x 15) 0 ) \"FizzBuzz\")\n (( = (modulo x 3) 0 ) \"Fizz\")\n (( = (modulo x 5) 0 ) \"Buzz\")\n (else x)))\n\n (if (< x y) (fizzbuzz (+ x 1) y)))\n\n(fizzbuzz 1 100)\n\n(define (fizzbuzz x)\n (let ([words '((3 . \"Fizz\")\n (5 . \"Buzz\"))])\n (define (fbm x)\n (let ([w (map cdr (filter (lambda (wo) (= 0 (modulo x (car wo)))) words))])\n (if (null? w) x (apply string-append w))))\n (for-each (cut format #t \"~a~%\" <>) (map fbm (iota x 1 1)))))\n\n(fizzbuzz 15)\n","human_summarization":"\"Output integers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'. The code uses a recursive procedure and implements maps and filters for easier modification but less readability.\"","id":577} {"lang_cluster":"Scheme","source_code":"\n\n(define x-centre -0.5)\n(define y-centre 0.0)\n(define width 4.0)\n(define i-max 800)\n(define j-max 600)\n(define n 100)\n(define r-max 2.0)\n(define file \"out.pgm\")\n(define colour-max 255)\n(define pixel-size (\/ width i-max))\n(define x-offset (- x-centre (* 0.5 pixel-size (+ i-max 1))))\n(define y-offset (+ y-centre (* 0.5 pixel-size (+ j-max 1))))\n\n(define (inside? z)\n (define (*inside? z-0 z n)\n (and (< (magnitude z) r-max)\n (or (= n 0)\n (*inside? z-0 (+ (* z z) z-0) (- n 1)))))\n (*inside? z 0 n))\n\n(define (boolean->integer b)\n (if b colour-max 0))\n\n(define (pixel i j)\n (boolean->integer\n (inside?\n (make-rectangular (+ x-offset (* pixel-size i))\n (- y-offset (* pixel-size j))))))\n\n(define (plot)\n (with-output-to-file file\n (lambda ()\n (begin (display \"P2\") (newline)\n (display i-max) (newline)\n (display j-max) (newline)\n (display colour-max) (newline)\n (do ((j 1 (+ j 1))) ((> j j-max))\n (do ((i 1 (+ i 1))) ((> i i-max))\n (begin (display (pixel i j)) (newline))))))))\n\n(plot)Works with: CHICKEN Scheme version 5.3.0\n\n;; A program written for CHICKEN Scheme version 5.3.0 and various\n;; eggs.\n\n(import (r7rs))\n(import (scheme base))\n(import (scheme case-lambda))\n(import (scheme inexact))\n\n(import (prefix sdl2 \"sdl2:\"))\n(import (prefix imlib2 \"imlib2:\"))\n\n(import (format))\n(import (matchable))\n(import (simple-exceptions))\n\n(define sdl2-subsystems-used '(events video))\n\n;; ------------------------------\n;; Basics for using the sdl2 egg:\n(sdl2:set-main-ready!)\n(sdl2:init! sdl2-subsystems-used)\n(on-exit sdl2:quit!)\n(current-exception-handler\n (let ((original-handler (current-exception-handler)))\n (lambda (exception)\n (sdl2:quit!)\n (original-handler exception))))\n;; ------------------------------\n\n(define-record-type \n (%%make-mandel-params)\n mandel-params?\n (window ref-window set-window!)\n (xcenter ref-xcenter set-xcenter!)\n (ycenter ref-ycenter set-ycenter!)\n (pixels-per-unit ref-pixels-per-unit set-pixels-per-unit!)\n (pixels-per-event-check ref-pixels-per-event-check\n set-pixels-per-event-check!)\n (max-escape-time ref-max-escape-time set-max-escape-time!))\n\n(define initial-width 400)\n(define initial-height 400)\n(define initial-xcenter -3\/4)\n(define initial-ycenter 0)\n(define initial-pixels-per-unit 150)\n(define initial-pixels-per-event-check 1000)\n(define initial-max-escape-time 1000)\n\n(define (make-mandel-params window)\n (let ((params (%%make-mandel-params)))\n (set-window! params window)\n (set-xcenter! params initial-xcenter)\n (set-ycenter! params initial-ycenter)\n (set-pixels-per-unit! params initial-pixels-per-unit)\n (set-pixels-per-event-check! params\n initial-pixels-per-event-check)\n (set-max-escape-time! params initial-max-escape-time)\n params))\n\n(define window (sdl2:create-window! \"mandelbrot set task\"\n 'centered 'centered\n initial-width initial-height\n '()))\n(define params (make-mandel-params window))\n\n(define empty-color (sdl2:make-color 200 200 200))\n\n(define (clear-mandel!)\n (sdl2:fill-rect! (sdl2:window-surface (ref-window params))\n #f empty-color)\n (sdl2:update-window-surface! window))\n\n(define drawing? #t)\n(define redraw? #f)\n\n(define (draw-mandel! event-checker)\n (clear-mandel!)\n (let repeat ()\n (let*-values\n (((window) (ref-window params))\n ((width height) (sdl2:window-size window)))\n (let* ((xcenter (ref-xcenter params))\n (ycenter (ref-ycenter params))\n (pixels-per-unit (ref-pixels-per-unit params))\n (pixels-per-event-check\n (ref-pixels-per-event-check params))\n (max-escape-time (ref-max-escape-time params))\n (step (\/ 1.0 pixels-per-unit))\n (xleft (- xcenter (\/ width (* 2.0 pixels-per-unit))))\n (ytop (+ ycenter (\/ height (* 2.0 pixels-per-unit))))\n (pixel-count 0))\n (do ((j 0 (+ j 1))\n (cy ytop (- cy step)))\n ((= j height))\n (do ((i 0 (+ i 1))\n (cx xleft (+ cx step)))\n ((= i width))\n (let* ((color (compute-color-by-escape-time-algorithm\n cx cy max-escape-time)))\n (sdl2:surface-set! (sdl2:window-surface window)\n i j color)\n (if (= pixel-count pixels-per-event-check)\n (let ((event-checker (call\/cc event-checker)))\n (cond (redraw?\n (set! redraw? #f)\n (clear-mandel!)\n (repeat)))\n (set! pixel-count 0))\n (set! pixel-count (+ pixel-count 1)))))\n \u00a0;; Display a row.\n (sdl2:update-window-surface! window))))\n (set! drawing? #f)\n (repeat))) \n\n(define (compute-color-by-escape-time-algorithm\n cx cy max-escape-time)\n (escape-time->color (compute-escape-time cx cy max-escape-time)\n max-escape-time))\n\n(define (compute-escape-time cx cy max-escape-time)\n (let loop ((x 0.0)\n (y 0.0)\n (iter 0))\n (if (= iter max-escape-time)\n iter\n (let ((xsquared (* x x))\n (ysquared (* y y)))\n (if (< 4 (+ xsquared ysquared))\n iter\n (let ((x (+ cx (- xsquared ysquared)))\n (y (+ cy (* (+ x x) y))))\n (loop x y (+ iter 1))))))))\n\n(define (escape-time->color escape-time max-escape-time)\n \u00a0;; This is a very naive and ad hoc algorithm for choosing colors,\n \u00a0;; but hopefully will suffice for the task. With this algorithm, at\n \u00a0;; least one can zoom in and see some of the fractal-like structures\n \u00a0;; out on the filaments.\n (let* ((initial-ppu initial-pixels-per-unit)\n (ppu (ref-pixels-per-unit params))\n (fraction (* (\/ (log escape-time) (log max-escape-time))))\n (fraction (if (= fraction 1.0)\n fraction\n (* fraction\n (\/ (log initial-ppu)\n (log (max initial-ppu (* 0.05 ppu)))))))\n (value (- 255 (min 255 (exact-rounded (* fraction 255))))))\n (sdl2:make-color value value value)))\n\n(define (exact-rounded x)\n (exact (round x)))\n\n(define (event-loop)\n (define event (sdl2:make-event))\n (define painter draw-mandel!)\n (define zoom-ratio 2)\n\n (define (recenter! xcoord ycoord)\n (let*-values\n (((window) (ref-window params))\n ((width height) (sdl2:window-size window))\n ((ppu) (ref-pixels-per-unit params)))\n (set-xcenter! params\n (+ (ref-xcenter params)\n (\/ (- (* 2.0 xcoord) width) (* 2.0 ppu))))\n (set-ycenter! params\n (+ (ref-ycenter params)\n (\/ (- height (* 2.0 ycoord)) (* 2.0 ppu))))))\n\n (define (zoom-in!)\n (let* ((ppu (ref-pixels-per-unit params))\n (ppu (* ppu zoom-ratio)))\n (set-pixels-per-unit! params ppu)))\n\n (define (zoom-out!)\n (let* ((ppu (ref-pixels-per-unit params))\n (ppu (* (\/ 1.0 zoom-ratio) ppu)))\n (set-pixels-per-unit! params (max 1 ppu))))\n\n (define (restore-original-settings!)\n (set-xcenter! params initial-xcenter)\n (set-ycenter! params initial-ycenter)\n (set-pixels-per-unit! params initial-pixels-per-unit)\n (set-pixels-per-event-check!\n params initial-pixels-per-event-check)\n (set-max-escape-time! params initial-max-escape-time)\n (set! zoom-ratio 2))\n\n (define dump-image! \u00a0; Really this should put up a dialog.\n (let ((dump-number 1))\n (lambda ()\n (let*-values\n (((window) (ref-window params))\n ((width height) (sdl2:window-size window))\n ((surface) (sdl2:window-surface window)))\n (let ((filename (string-append \"mandelbrot-image-\"\n (number->string dump-number)\n \".png\"))\n (img (imlib2:image-create width height)))\n (do ((j 0 (+ j 1)))\n ((= j height))\n (do ((i 0 (+ i 1)))\n ((= i width))\n (let-values\n (((r g b a) (sdl2:color->values\n (sdl2:surface-ref surface i j))))\n (imlib2:image-draw-pixel\n img (imlib2:color\/rgba r g b a) i j))))\n (imlib2:image-alpha-set! img #f)\n (imlib2:image-save img filename)\n (format #t \"~a written~%\" filename)\n (set! dump-number (+ dump-number 1)))))))\n \n (let loop ()\n (when redraw?\n (set! drawing? #t))\n (when drawing?\n (set! painter (call\/cc painter)))\n (set! redraw? #f)\n (if (not (sdl2:poll-event! event))\n (loop)\n (begin\n (match (sdl2:event-type event)\n ('quit) \u00a0; Quit by leaving the loop.\n ('window\n (match (sdl2:window-event-event event)\n \u00a0;; It should be possible to resize the window, but I\n \u00a0;; have not yet figured out how to do this with SDL2\n \u00a0;; and not crash sometimes.\n ((or 'exposed 'restored)\n (sdl2:update-window-surface! (ref-window params))\n (loop))\n (_ (loop))))\n ('mouse-button-down\n (recenter! (sdl2:mouse-button-event-x event)\n (sdl2:mouse-button-event-y event))\n (set! redraw? #t)\n (loop))\n ('key-down\n (match (sdl2:keyboard-event-sym event)\n ('q 'quit-by-leaving-the-loop)\n ((or 'plus 'kp-plus)\n (zoom-in!)\n (set! redraw? #t)\n (loop))\n ((or 'minus 'kp-minus)\n (zoom-out!)\n (set! redraw? #t)\n (loop))\n ((or 'n-2 'kp-2)\n (set! zoom-ratio 2)\n (loop))\n ((or 'n-3 'kp-3)\n (set! zoom-ratio 3)\n (loop))\n ((or 'n-4 'kp-4)\n (set! zoom-ratio 4)\n (loop))\n ((or 'n-5 'kp-5)\n (set! zoom-ratio 5)\n (loop))\n ((or 'n-6 'kp-6)\n (set! zoom-ratio 6)\n (loop))\n ((or 'n-7 'kp-7)\n (set! zoom-ratio 7)\n (loop))\n ((or 'n-8 'kp-8)\n (set! zoom-ratio 8)\n (loop))\n ((or 'n-9 'kp-9)\n (set! zoom-ratio 9)\n (loop))\n ('o\n (restore-original-settings!)\n (set! redraw? #t)\n (loop))\n ('p\n (dump-image!)\n (loop))\n (some-key-in-which-we-are-not-interested\n (loop))))\n (some-event-in-which-we-are-not-interested\n (loop)))))))\n\n;; At the least this legend should go in a window, but printing it to\n;; the terminal will, hopefully, suffice for the task.\n(format #t \"~%~8tACTIONS~%\")\n(format #t \"~8t-------~%\")\n(define fmt \"~2t~a~15t: ~a~%\")\n(format #t fmt \"Q key\" \"quit\")\n(format #t fmt \"mouse button\" \"recenter\")\n(format #t fmt \"+ key\" \"zoom in\")\n(format #t fmt \"- key\" \"zoom in\")\n(format #t fmt \"2 .. 9 key\" \"set zoom ratio\")\n(format #t fmt \"O key\" \"restore original\")\n(format #t fmt \"P key\" \"dump to a PNG\")\n(format #t \"~%\")\n\n(event-loop)\n\n","human_summarization":"The code generates and draws the Mandelbrot set, using specific algorithms and functions. It writes the image of the Mandelbrot set to a plain pgm file, with the set drawn in white and the exterior in black. The code requires several CHICKEN \"eggs\" and can be compiled with csc -O3 mandelbrot_task_CHICKEN.scm. It also provides an example of a PNG dumped by the program during a zoom-in operation.","id":578} {"lang_cluster":"Scheme","source_code":"\n(apply + '(1 2 3 4 5))\n(apply * '(1 2 3 4 5))\n\n(define (reduce f i l)\n (if (null? l)\n i\n (reduce f (f i (car l)) (cdr l))))\n\n(reduce + 0 '(1 2 3 4 5))\u00a0;; 0 is unit for +\n(reduce * 1 '(1 2 3 4 5))\u00a0;; 1 is unit for *\n","human_summarization":"calculate the sum and product of an array of integers using a tail-recursive solution in Scheme, leveraging tail call optimization for space efficiency.","id":579} {"lang_cluster":"Scheme","source_code":"\n(define (leap-year? n)\n(apply (lambda (a b c) (or a (and (not b) c)))\n (map (lambda (m) (zero? (remainder n m)))\n '(400 100 4))))\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":580} {"lang_cluster":"Scheme","source_code":"\n(define dst (string-copy src))\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":581} {"lang_cluster":"Scheme","source_code":"\n\n(define (F n)\n (if (= n 0) 1\n (- n (M (F (- n 1))))))\n\n(define (M n)\n (if (= n 0) 0\n (- n (F (M (- n 1))))))\n\n(letrec ((F (lambda (n)\n (if (= n 0) 1\n (- n (M (F (- n 1)))))))\n (M (lambda (n)\n (if (= n 0) 0\n (- n (F (M (- n 1))))))))\n (F 19)) # evaluates to 12\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions are defined such that F(0) = 1, M(0) = 0, F(n) = n - M(F(n-1)) for n > 0, and M(n) = n - F(M(n-1)) for n > 0. If the programming language does not support mutual recursion, this should be stated instead of providing an alternative solution. The functions are defined within a letrec block to enable mutual recursion.","id":582} {"lang_cluster":"Scheme","source_code":"\n\n(define (binary-search value vector)\n (let helper ((low 0)\n (high (- (vector-length vector) 1)))\n (if (< high low)\n #f\n (let ((middle (quotient (+ low high) 2)))\n (cond ((> (vector-ref vector middle) value)\n (helper low (- middle 1)))\n ((< (vector-ref vector middle) value)\n (helper (+ middle 1) high))\n (else middle))))))\n\n> (binary-search 6 '#(1 3 4 5 6 7 8 9 10))\n4\n> (binary-search 2 '#(1 3 4 5 6 7 8 9 10))\n#f\n\n\n","human_summarization":"Code summarization: The given code implements a binary search algorithm, which can be either recursive or iterative. The algorithm searches for a specific \"secret value\" within a sorted integer array, starting from a specified range. It returns the index of the secret value if found, or indicates its absence. The code also handles multiple equal values and potential overflow bugs. Additionally, it provides variations of the algorithm to find the leftmost and rightmost insertion points for the secret value.","id":583} {"lang_cluster":"Scheme","source_code":"\n (define (main args)\n (for-each (lambda (arg) (display arg) (newline)) args))\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c \"alpha beta\" -h \"gamma\"'. It also includes functionalities for intelligent parsing of these arguments.","id":584} {"lang_cluster":"Scheme","source_code":"\nLibrary: Scheme\/PsTk\n#!r6rs\n\n;;; R6RS implementation of Pendulum Animation\n\n(import (rnrs)\n (lib pstk main) ; change this for your pstk installation\n )\n\n(define PI 3.14159)\n(define *conv-radians* (\/ PI 180))\n(define *theta* 45.0)\n(define *d-theta* 0.0)\n(define *length* 150)\n(define *home-x* 160)\n(define *home-y* 25)\n\n;;; estimates new angle of pendulum\n(define (recompute-angle)\n (define (avg a b) (\/ (+ a b) 2))\n (let* ((scaling (\/ 3000.0 (* *length* *length*)))\n ; first estimate\n (first-dd-theta (- (* (sin (* *theta* *conv-radians*)) scaling)))\n (mid-d-theta (+ *d-theta* first-dd-theta))\n (mid-theta (+ *theta* (avg *d-theta* mid-d-theta)))\n ; second estimate\n (mid-dd-theta (- (* (sin (* mid-theta *conv-radians*)) scaling)))\n (mid-d-theta-2 (+ *d-theta* (avg first-dd-theta mid-dd-theta)))\n (mid-theta-2 (+ *theta* (avg *d-theta* mid-d-theta-2)))\n ; again first\n (mid-dd-theta-2 (- (* (sin (* mid-theta-2 *conv-radians*)) scaling)))\n (last-d-theta (+ mid-d-theta-2 mid-dd-theta-2))\n (last-theta (+ mid-theta-2 (avg mid-d-theta-2 last-d-theta)))\n ; again second\n (last-dd-theta (- (* (sin (* last-theta *conv-radians*)) scaling)))\n (last-d-theta-2 (+ mid-d-theta-2 (avg mid-dd-theta-2 last-dd-theta)))\n (last-theta-2 (+ mid-theta-2 (avg mid-d-theta-2 last-d-theta-2))))\n ; put values back in globals\n (set! *d-theta* last-d-theta-2)\n (set! *theta* last-theta-2)))\n\n;;; The main event loop and graphics context\n(let ((tk (tk-start)))\n (tk\/wm 'title tk \"Pendulum Animation\")\n (let ((canvas (tk 'create-widget 'canvas)))\n\n ;;; redraw the pendulum on canvas\n ;;; - uses angle and length to compute new (x,y) position of bob\n (define (show-pendulum canvas)\n (let* ((pendulum-angle (* *conv-radians* *theta*))\n (x (+ *home-x* (* *length* (sin pendulum-angle))))\n (y (+ *home-y* (* *length* (cos pendulum-angle)))))\n (canvas 'coords 'rod *home-x* *home-y* x y)\n (canvas 'coords 'bob (- x 15) (- y 15) (+ x 15) (+ y 15))))\n\n ;;; move the pendulum and repeat after 20ms\n (define (animate)\n (recompute-angle)\n (show-pendulum canvas)\n (tk\/after 20 animate))\n\n ;; layout the canvas\n (tk\/grid canvas 'column: 0 'row: 0)\n (canvas 'create 'line 0 25 320 25 'tags: 'plate 'width: 2 'fill: 'grey50)\n (canvas 'create 'oval 155 20 165 30 'tags: 'pivot 'outline: \"\" 'fill: 'grey50)\n (canvas 'create 'line 1 1 1 1 'tags: 'rod 'width: 3 'fill: 'black)\n (canvas 'create 'oval 1 1 2 2 'tags: 'bob 'outline: 'black 'fill: 'yellow)\n\n ;; get everything started\n (show-pendulum canvas)\n (tk\/after 500 animate)\n (tk-event-loop tk)))\n\n\n#!\/usr\/bin\/env gosh\n#| -*- mode: scheme; coding: utf-8; -*- |#\n(use gl)\n(use gl.glut)\n(use gl.simple.viewer)\n(use math.const)\n(define (deg->rad degree) (* (\/ degree 180) pi))\n(define (rad->deg radians) (* (\/ radians pi) 180))\n(define (main args)\n (glut-init args)\n (let* ((\u03c6 (deg->rad 179)) (l 0.5) (bob 0.02) (q (make ))\n\t (draw-pendulum (lambda()\n \t\t\t (gl-push-matrix*\n\t\t\t (gl-scale 4 4 4)\n\t\t\t (gl-translate 0 l 0)\n\t\t\t (gl-rotate (rad->deg \u03c6) 0 0 1)\n\t\t\t (gl-begin GL_LINES)\n\t\t\t (gl-vertex 0 0)\n\t\t\t (gl-vertex 0 (- l))\n\t\t\t (gl-end)\n\t\t\t (gl-translate 0 (- l) 0)\n\t\t\t (glu-sphere q bob 10 10))))\n\t (g 9.81)\n\t (\u03c6\u0307 0)\n\t (euler-step (lambda(h)\n\t\t (inc! \u03c6\u0307 (* (- (* (\/ g l) (sin \u03c6))) h))\n\t\t (inc! \u03c6 (* \u03c6\u0307 h)))))\n (simple-viewer-display\n (lambda ()\n ;; I hope sync to VBLANK aka VSYNC works and the display has ~60Hz\n (euler-step 1\/60)\n (draw-pendulum)\n (glut-post-redisplay))))\n (simple-viewer-window 'pendulum)\n (glut-full-screen)\n (simple-viewer-run :rescue-errors #f))\n\n","human_summarization":"simulate and animate a simple gravity pendulum using a physical model. The animation is created using Scheme + PS\/Tk, based on a direct translation from the Ruby\/Tk example. An alternative version uses gauche scheme.","id":585} {"lang_cluster":"Scheme","source_code":"\nWorks with: Chicken Scheme\nUsing the json egg: (use json)\n(define object-example\n (with-input-from-string \"{\\\"foo\\\": \\\"bar\\\", \\\"baz\\\": [1, 2, 3]}\"\n json-read))\n(pp object-example)\n; this prints #((\"foo\" . \"bar\") (\"baz\" 1 2 3))\n\n(json-write #([foo . bar]\n [baz 1 2 3]\n [qux . #((rosetta . code))]))\n; this writes the following:\n; {\"foo\": \"bar\", \"baz\": [1, 2, 3], \"qux\": {\"foo\": \"bar\"}}\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":586} {"lang_cluster":"Scheme","source_code":"\n(define (root number degree tolerance)\n (define (good-enough? next guess)\n (< (abs (- next guess)) tolerance))\n (define (improve guess)\n (\/ (+ (* (- degree 1) guess) (\/ number (expt guess (- degree 1)))) degree))\n (define (*root guess)\n (let ((next (improve guess)))\n (if (good-enough? next guess)\n guess\n (*root next))))\n (*root 1.0))\n\n(display (root (expt 2 10) 10 0.1))\n(newline)\n(display (root (expt 2 10) 10 0.01))\n(newline)\n(display (root (expt 2 10) 10 0.001))\n(newline)\n\n\n2.04732932236839\n2.00463204835482\n2.00004786858167\n\n","human_summarization":"implement the principal nth root computation algorithm for a positive real number A.","id":587} {"lang_cluster":"Scheme","source_code":"\nWorks with: Chicken Scheme\n(use posix)\n(get-host-name)\n\nWorks with: Guile\n(gethostname)\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":588} {"lang_cluster":"Scheme","source_code":"\nWorks with: PLT Scheme version 4\n\n#lang scheme\n(require srfi\/27 srfi\/1) ;; random-integer, every\n\n(define (play)\n (let* ([numbers (build-list 4 (lambda (n)\n (add1 (random-integer 9))))]\n [valid? (curryr valid? numbers)])\n (printf startup-message numbers)\n (let loop ([exp (read)])\n (with-handlers ([exn:fail? (lambda (err)\n (printf error-message exp (exn-message err))\n (loop (read)))])\n (cond [(eq? exp '!) (play)]\n \n [(or (eq? exp 'q)\n (eof-object? exp)) (printf quit-message)]\n \n [(not (valid? exp))\n (printf bad-exp-message exp)\n (loop (read))]\n \n [(not (= (eval exp) 24))\n (printf bad-result-message exp (eval exp))\n (loop (read))]\n \n [else (printf winning-message)])))))\n\n(define (valid? exp numbers)\n ;; must contain each number exactly once and only valid symbols\n (define (valid-symbol? sym)\n ;; only +, -, *, and \/ are valid\n (case sym\n [(+ - * \/) #t]\n [else #f]))\n \n (let* ([ls (flatten exp)]\n [numbers* (filter number? ls)]\n [symbols (remove number? ls)])\n (and (equal? (sort numbers <)\n (sort numbers* <))\n (every valid-symbol? symbols))))\n\n(define startup-message \"\nWrite a lisp expression that evaluates to 24\nusing only (, ), +, -, *, \/\nand these four numbers: ~a\n\nor '!' to get a new set of numbers\nor 'q' to quit\")\n\n(define error-message \"\nYour expression ~a raised an exception:\n\n \\\"~a\\\"\n\nPlease try again\")\n\n(define bad-exp-message \"Sorry, ~a is a bad expression.\")\n(define bad-result-message \"Sorry, ~a evaluates to ~a, not 24.\")\n(define quit-message \"Thanks for playing...\")\n(define winning-message \"You win!\")\n\n(provide play)\n\n\n","human_summarization":"The code generates four random digits from 1 to 9 and prompts the user to form an arithmetic expression using these digits exactly once, with the aim to achieve a total of 24. The code checks and evaluates the user's input expression, allowing operations of addition, subtraction, multiplication, and division (with remainders preserved). The code does not allow the formation of multiple-digit numbers from the provided digits. The order of the digits does not need to be preserved in the expression. The code does not generate or test the validity of the expression.","id":589} {"lang_cluster":"Scheme","source_code":"\n(define (run-length-decode v)\n (apply string-append (map (lambda (p) (make-string (car p) (cdr p))) v)))\n\n(define (run-length-encode s)\n(let ((n (string-length s)))\n(let loop ((i (- n 2)) (c (string-ref s (- n 1))) (k 1) (v '()))\n(if (negative? i) (cons (cons k c) v)\n (let ((x (string-ref s i)))\n (if (char=? c x) (loop (- i 1) c (+ k 1) v)\n (loop (- i 1) x 1 (cons (cons k c) v))))))))\n\n(run-length-encode \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\")\n; ((12 . #\\W) (1 . #\\B) (12 . #\\W) (3 . #\\B) (24 . #\\W) (1 . #\\B) (14 . #\\W))\n(run-length-decode '((12 . #\\W) (1 . #\\B) (12 . #\\W) (3 . #\\B) (24 . #\\W) (1 . #\\B) (14 . #\\W)))\n; \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":590} {"lang_cluster":"Scheme","source_code":"\n(define s \"hello\")\n(display (string-append s \" literal\"))\n(newline)\n(define s1 (string-append s \" literal\"))\n(display s1)\n(newline)\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":591} {"lang_cluster":"Scheme","source_code":"\n\n(import (scheme base)\n (scheme char)\n (scheme file)\n (scheme write)\n (srfi 125) \u00a0; hash tables\n (srfi 132))\u00a0; sorting library\n\n;; read in the words\n(define (read-groups)\n (with-input-from-file \n \"unixdict.txt\"\n (lambda () \n (let ((groups (hash-table string=?)))\n (do ((line (read-line) (read-line)))\n ((eof-object? line) groups)\n (let* ((key (list->string (list-sort charlist line))))\n (val (hash-table-ref\/default groups key '())))\n (hash-table-set! groups key (cons line val))))))))\n\n;; extract the longest values from given hash-table of groups\n(define (largest-groups groups)\n (define (find-largest grps n sofar)\n (cond ((null? grps)\n sofar)\n ((> (length (car grps)) n)\n (find-largest (cdr grps) (length (car grps)) (list (car grps))))\n ((= (length (car grps)) n)\n (find-largest (cdr grps) n (cons (car grps) sofar)))\n (else \n (find-largest (cdr grps) n sofar))))\n (find-largest (hash-table-values groups) 0 '()))\n\n;; print results\n(for-each \n (lambda (group)\n (display \"[ \")\n (for-each (lambda (word) (display word) (display \" \")) group)\n (display \"]\\n\"))\n (list-sort (lambda (a b) (string= i 9)) \u00a0; exit condition\n (display i) \u00a0; body\n (newline))\n\n(let loop ((i 2)) \u00a0; function name, parameters and starting values\n (cond ((< i 9)\n (display i)\n (newline)\n (loop (+ i 2)))))) \u00a0; tail-recursive call, won't create a new stack frame\n\n(define (for-loop start end step func)\n (let loop ((i start))\n (cond ((< i end)\n\t (func i)\n\t (loop (+ i step))))))\n\n(for-loop 2 9 2\n (lambda (i)\n (display i)\n (newline)))\n\n(define-syntax for-loop\n (syntax-rules () \n ((for-loop index start end step body ...)\n (let ((evaluated-end end) (evaluated-step step))\n (let loop ((i start))\n (if (< i evaluated-end)\n ((lambda (index) body ... (loop (+ i evaluated-step))) i)))))))\n\n(for-loop i 2 9 2\n (display i)\n (newline))\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one, using the built-in 'do' form in Scheme. It also shows the use of the more flexible 'named let' form. Additionally, it illustrates how to add to the language by wrapping the loop in a function or a macro, making the lambda implicit.","id":597} {"lang_cluster":"Scheme","source_code":"\n\n(define-syntax sum\n (syntax-rules ()\n ((sum var low high . body)\n (let loop ((var low)\n (result 0))\n (if (> var high)\n result\n (loop (+ var 1)\n (+ result . body)))))))\n\n(exact->inexact (sum i 1 100 (\/ 1 i)))\n5.18737751763962\n\n","human_summarization":"The code is an implementation of Jensen's Device, a programming technique devised by J\u00f8rn Jensen. It uses the call by name method to compute the 100th harmonic number. The technique relies on the re-evaluation of an expression passed as an actual parameter every time the formal parameter's value is needed. This implementation also demonstrates the importance of passing the first parameter by name or reference to ensure changes made within the sum are visible in the caller's context.","id":598} {"lang_cluster":"Scheme","source_code":"\n(import (rnrs))\n\n(define (calc-pi yield)\n (let loop ((q 1) (r 0) (t 1) (k 1) (n 3) (l 3))\n (if (< (- (+ (* 4 q) r) t) (* n t))\n (begin\n (yield n)\n (loop (* q 10)\n (* 10 (- r (* n t)))\n t\n k\n (- (div (* 10 (+ (* 3 q) r)) t) (* 10 n))\n l))\n (begin\n (loop (* q k)\n (* (+ (* 2 q) r) l)\n (* t l)\n (+ k 1)\n (div (+ (* q (* 7 k)) 2 (* r l)) (* t l))\n (+ l 2))))))\n\n(let ((i 0))\n (calc-pi\n (lambda (d)\n (display d)\n (set! i (+ i 1))\n (if (= 40 i)\n (begin\n (newline)\n (set! i 0))))))\n\n\n3141592653589793238462643383279502884197\n1693993751058209749445923078164062862089\n9862803482534211706798214808651328230664\n7093844609550582231725359408128481117450\n2841027019385211055596446229489549303819\n6442881097566593344612847564823378678316\n5271201909145648566923460348610454326648\n2133936072602491412737245870066063155881\n7488152092096282925409171536436789259036\n0011330530548820466521384146951941511609\n4330572703657595919530921861173819326117\n9310511854807446237996274956735188575272\n4891227938183011949129833673362440656643\n0860213949463952247371907021798609437027\n7053921717629317675238467481846766940513\n2000568127145263560827785771342757789609\n...\n","human_summarization":"continuously calculate and display the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The task is about calculating Pi, not using built-in constants.","id":599} {"lang_cluster":"Scheme","source_code":"\n(define (lex i 2.01) )\n (display (string-append \"Gamma (\"\n (number->string i)\n \"): \"\n \"\\n --- Lanczos\u00a0: \"\n (number->string (gamma-lanczos i))\n \"\\n --- Stirling: \"\n (number->string (gamma-stirling i))\n \"\\n --- Taylor \u00a0: \"\n (number->string (gamma-taylor i))\n \"\\n\")))\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":602} {"lang_cluster":"Scheme","source_code":"\n\n(import (scheme base)\n (scheme write)\n (srfi 1))\n\n;; return list of solutions to n-queens problem\n(define (n-queens n)\u00a0; breadth-first solution\n (define (place-initial-row)\u00a0; puts a queen on each column of row 0\n (list-tabulate n (lambda (col) (list (cons 0 col)))))\n (define (place-on-row soln-so-far row)\n (define (invalid? col)\n (any (lambda (posn) \n (or (= col (cdr posn))\u00a0; on same column\n (= (abs (- row (car posn)))\u00a0; on same diagonal\n (abs (- col (cdr posn))))))\n soln-so-far))\n \u00a0;\n (do ((col 0 (+ 1 col))\n (res '() (if (invalid? col)\n res\n (cons (cons (cons row col) soln-so-far)\n res))))\n ((= col n) res)))\n \u00a0;\n (do ((res (place-initial-row) \n (apply append \n (map (lambda (soln-so-far) (place-on-row soln-so-far row))\n res)))\n (row 1 (+ 1 row)))\n ((= row n) res)))\n\n;; display solutions in 2-d array form\n(define (pretty-print solutions n)\n (define (posn->index posn)\n (+ (* n (cdr posn))\n (car posn)))\n (define (pp solution)\n (let ((board (make-vector (square n) \".\")))\n (for-each (lambda (queen) (vector-set! board \n (posn->index queen)\n \"Q\"))\n solution)\n (let loop ((row 0)\n (col 0))\n (cond ((= row n) \n (newline))\n ((= col n) \n (newline)\n (loop (+ 1 row) 0))\n (else\n (display (vector-ref board (posn->index (cons row col))))\n (loop row (+ 1 col)))))))\n \u00a0;\n (display (string-append \"Found \"\n (number->string (length solutions))\n \" solutions for n=\"\n (number->string n)\n \"\\n\\n\"))\n (for-each pp solutions))\n\n;; create table of number of solutions\n(do ((n 1 (+ 1 n)))\n ((> n 10) )\n (display n)\n (display \" \")\n (display (length (n-queens n)))\n (newline))\n\n;; show some examples\n(pretty-print (n-queens 1) 1)\n(pretty-print (n-queens 2) 2)\n(pretty-print (n-queens 3) 3)\n(pretty-print (n-queens 4) 4)\n(pretty-print (n-queens 5) 5)\n(pretty-print (n-queens 8) 8)\n\n","human_summarization":"implement a solution to the N-queens problem using a breadth-first technique, which can solve the puzzle for a board of any size NxN and retrieve all possible solutions. The code also provides the number of solutions for small values of N as per OEIS: A000170.","id":603} {"lang_cluster":"Scheme","source_code":"\n; in r5rs, there is append for lists, but we'll need to define vector-append\n(define (vector-append . arg) (list->vector (apply append (map vector->list arg))))\n\n(vector-append #(1 2 3 4) #(5 6 7) #(8 9 10))\n; #(1 2 3 4 5 6 7 8 9 10)\n\nWorks with: Gauche Scheme\n(use gauche.array)\n\n(define (print-matrix m)\n (define row-num #f)\n (array-for-each-index m\n (lambda (row col)\n (when (and row-num (not (= row-num row))) (newline))\n (format #t \"~a \" (array-ref m row col))\n (set! row-num row)))\n (newline))\n\n(define a\n #,( (0 3 0 2)\n a b\n c d\n e f))\n\n(define b\n #,( (0 3 0 2)\n 1 2\n 3 4\n 5 6))\n\n(print-matrix (array-concatenate a b))\n(print-matrix (array-concatenate a b 1))\n\n","human_summarization":"demonstrate how to concatenate two arrays in the given programming language, possibly using a simple addition operation or the vector-append function defined in SRFI-43.","id":604} {"lang_cluster":"Scheme","source_code":"\n>(define (a x)\n (display \"a\\n\")\n x)\n>(define (b x)\n (display \"b\\n\")\n x)\n>(for-each (lambda (i)\n (for-each (lambda (j)\n (display i) (display \" and \") (display j) (newline)\n (and (a i) (b j))\n (display i) (display \" or \") (display j) (newline)\n (or (a i) (b j))\n ) '(#t #f))\n ) '(#t #f))\n#t and #t\na\nb\n#t or #t\na\n#t and #f\na\nb\n#t or #f\na\n#f and #t\na\n#f or #t\na\nb\n#f and #f\na\n#f or #f\na\nb\n\n","human_summarization":"create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.","id":605} {"lang_cluster":"Scheme","source_code":"\n\n(define *blocks*\n '((#\\B #\\O) (#\\X #\\K) (#\\D #\\Q) (#\\C #\\P) (#\\N #\\A)\n (#\\G #\\T) (#\\R #\\E) (#\\T #\\G) (#\\Q #\\D) (#\\F #\\S)\n (#\\J #\\W) (#\\H #\\U) (#\\V #\\I) (#\\A #\\N) (#\\O #\\B)\n (#\\E #\\R) (#\\F #\\S) (#\\L #\\Y) (#\\P #\\C) (#\\Z #\\M)))\n\n(define (exists p? li)\n (and (not (null? li))\n (or (p? (car li))\n (exists p? (cdr li)))))\n\n(define (remove-one x li)\n (cond\n ((null? li) '())\n ((equal? (car li) x) (cdr li))\n (else (cons (car li) (remove-one x (cdr li))))))\n\n(define (can-make-list? li blocks)\n (or (null? li)\n (exists\n (lambda (block)\n (and\n (member (char-upcase (car li)) block)\n (can-make-list? (cdr li) (remove-one block blocks))))\n blocks)))\n\n(define (can-make-word? word)\n (can-make-list? (string->list word) *blocks*))\n \n \n(define *words*\n '(\"A\" \"Bark\" \"book\" \"TrEaT\" \"COMMON\" \"squaD\" \"CONFUSE\"))\n \n(for-each\n (lambda (word)\n (display (if (can-make-word? word)\n \" Can make word: \"\n \"Cannot make word: \"))\n (display word)\n (newline))\n *words*)\n\n","human_summarization":"The code is a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed. The function is tested with seven different words.","id":606} {"lang_cluster":"Scheme","source_code":"\nWorks with: Guile version 1.8.8Works with: Chicken Scheme version 4.6.0\n(let ((s (socket PF_INET SOCK_STREAM 0)))\n (connect s AF_INET (inet-pton AF_INET \"127.0.0.1\") 256)\n (display \"hello socket world\" s))\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":607} {"lang_cluster":"Scheme","source_code":"\n(do ((i 0 (+ i 1))) (#f) (display (number->string i 8)) (newline))\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":608} {"lang_cluster":"Scheme","source_code":"\n; swap elements of a vector\n; vector-swap! is not part of r5rs, so we define it\n(define (vector-swap! v i j)\n(let ((a (vector-ref v i)) (b (vector-ref v j)))\n(vector-set! v i b)\n(vector-set! v j a)))\n\n(let ((vec (vector 1 2 3 4 5)))\n (vector-swap! vec 0 4)\n vec)\n; #(5 2 3 4 1)\n\n\n; we can swap also in lists\n(define (list-swap! v i j)\n(let* ((x (list-tail v i))\n (y (list-tail v j))\n (a (car x))\n (b (car y)))\n(set-car! x b)\n(set-car! y a)))\n\n(let ((lis (list 1 2 3 4 5)))\n (list-swap! lis 0 4)\n lis)\n; (5 2 3 4 1)\n\n\n; using macros (will work on variables, not on vectors or lists)\n(define-syntax swap!\n(syntax-rules ()\n((_ a b)\n (let ((tmp a))\n (set! a b)\n (set! b tmp)))))\n\n; try it\n(let ((a 1) (b 2)) (swap! a b) (list a b))\n; (2 1)\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.","id":609} {"lang_cluster":"Scheme","source_code":"\n\n(define (palindrome? s)\n (let ((chars (string->list s)))\n (equal? chars (reverse chars))))\n\n(define (palindrome? s)\n (let loop ((i 0)\n (j (- (string-length s) 1)))\n (or (>= i j)\n (and (char=? (string-ref s i) (string-ref s j))\n (loop (+ i 1) (- j 1))))))\n\n;; Or:\n(define (palindrome? s)\n (let loop ((s (string->list s))\n (r (reverse (string->list s))))\n (or (null? s)\n (and (char=? (car s) (car r))\n (loop (cdr s) (cdr r))))))\n\n> (palindrome? \"ingirumimusnocteetconsumimurigni\")\n#t\n> (palindrome? \"This is not a palindrome\")\n#f\n>\n","human_summarization":"The code includes a function that checks if a given sequence of characters is a palindrome. It supports Unicode characters and has an additional function to detect inexact palindromes, ignoring white-space, punctuation, and case. The code utilizes string reversal and includes both non-recursive and recursive methods.","id":610} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nWorks with: Visual Basic .NET version 9.0+\nModule Filter\n\n Sub Main()\n Dim array() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n Dim newEvenArray() As Integer\n\n Console.WriteLine(\"Current Array:\")\n For Each i As Integer In array\n Console.WriteLine(i)\n Next\n\n newEvenArray = filterArrayIntoNewArray(array)\n\n Console.WriteLine(\"New Filtered Array:\")\n For Each i As Integer In newEvenArray\n Console.WriteLine(i)\n Next\n\n array = changeExistingArray(array)\n\n Console.WriteLine(\"Orginal Array After Filtering:\")\n For Each i As Integer In array\n Console.WriteLine(i)\n Next\n End Sub\n\n Private Function changeExistingArray(array() As Integer) As Integer()\n Return filterArrayIntoNewArray(array)\n End Function\n\n Private Function filterArrayIntoNewArray(array() As Integer) As Integer()\n Dim result As New List(Of Integer)\n For Each element As Integer In array\n If element Mod 2 = 0 Then\n result.Add(element)\n End If\n Next\n Return result.ToArray\n End Function\n\nEnd Module\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":611} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\n#Const REDIRECTOUT = True\n\nModule Program\n Const OUTPATH = \"out.txt\"\n\n ReadOnly TestCases As String() = {\"asdf\", \"as\u20dddf\u0305\", \"Les Mis\u00e9rables\"}\n\n ' SIMPLE VERSION\n Function Reverse(s As String) As String\n Dim t = s.ToCharArray()\n Array.Reverse(t)\n Return New String(t)\n End Function\n\n ' EXTRA CREDIT VERSION\n Function ReverseElements(s As String) As String\n ' In .NET, a text element is series of code units that is displayed as one character, and so reversing the text\n ' elements of the string correctly handles combining character sequences and surrogate pairs.\n Dim elements = Globalization.StringInfo.GetTextElementEnumerator(s)\n Return String.Concat(AsEnumerable(elements).OfType(Of String).Reverse())\n End Function\n\n ' Wraps an IEnumerator, allowing it to be used as an IEnumerable.\n Iterator Function AsEnumerable(enumerator As IEnumerator) As IEnumerable\n Do While enumerator.MoveNext()\n Yield enumerator.Current\n Loop\n End Function\n\n Sub Main()\n Const INDENT = \" \"\n\n#If REDIRECTOUT Then\n Const OUTPATH = \"out.txt\"\n Using s = IO.File.Open(OUTPATH, IO.FileMode.Create),\n sw As New IO.StreamWriter(s)\n Console.SetOut(sw)\n#Else\n Try\n Console.OutputEncoding = Text.Encoding.ASCII\n Console.OutputEncoding = Text.Encoding.UTF8\n Console.OutputEncoding = Text.Encoding.Unicode\n Catch ex As Exception\n Console.WriteLine(\"Failed to set console encoding to Unicode.\" & vbLf)\n End Try\n#End If\n For Each c In TestCases\n Console.WriteLine(c)\n Console.WriteLine(INDENT & \"SIMPLE: \" & Reverse(c))\n Console.WriteLine(INDENT & \"ELEMENTS: \" & ReverseElements(c))\n Console.WriteLine()\n Next\n#If REDIRECTOUT Then\n End Using\n#End If\n End Sub\nEnd Module\n\nOutput (copied from Notepad):\n\nasdf\n SIMPLE: fdsa\n ELEMENTS: fdsa\n\nas\u20dddf\u0305\n SIMPLE: \u0305fd\u20ddsa\n ELEMENTS: f\u0305ds\u20dda\n\nLes Mis\u00e9rables\n SIMPLE: selba\u0155esiM seL\n ELEMENTS: selbar\u00e9siM seL\n","human_summarization":"implement a string reversal function in Visual Basic 2012 or later, with support for Unicode combining characters. The function also includes an option to redirect output to a file due to potential lack of Unicode support in the windows console, and uses a non-fixed-width typeface for correct display of combining characters.","id":612} {"lang_cluster":"Visual_Basic_.NET","source_code":"Public Class CirclesOfGivenRadiusThroughTwoPoints\n Public Shared Sub Main()\n For Each valu In New Double()() {\n New Double() {0.1234, 0.9876, 0.8765, 0.2345, 2},\n New Double() {0.0, 2.0, 0.0, 0.0, 1},\n New Double() {0.1234, 0.9876, 0.1234, 0.9876, 2},\n New Double() {0.1234, 0.9876, 0.8765, 0.2345, 0.5},\n New Double() {0.1234, 0.9876, 0.1234, 0.9876, 0},\n New Double() {0.1234, 0.9876, 0.2345, 0.8765, 0}}\n Dim p = New Point(valu(0), valu(1)), q = New Point(valu(2), valu(3))\n Console.WriteLine($\"Points {p} and {q} with radius {valu(4)}:\")\n Try\n Console.WriteLine(vbTab & String.Join(\" and \", FindCircles(p, q, valu(4))))\n Catch ex As Exception\n Console.WriteLine(vbTab & ex.Message)\n End Try\n Next\n If System.Diagnostics.Debugger.IsAttached Then Console.ReadKey()\n End Sub\n\n Private Shared Function FindCircles(ByVal p As Point, ByVal q As Point, ByVal rad As Double) As Point()\n If rad < 0 Then Throw New ArgumentException(\"Negative radius.\")\n If rad = 0 Then Throw New InvalidOperationException(If(p = q,\n String.Format(\"{0} (degenerate circle)\", {p}), \"No circles.\"))\n If p = q Then Throw New InvalidOperationException(\"Infinite number of circles.\")\n Dim dist As Double = Point.Distance(p, q), sqDist As Double = dist * dist,\n sqDiam As Double = 4 * rad * rad\n If sqDist > sqDiam Then Throw New InvalidOperationException(\n String.Format(\"Points are too far apart (by {0}).\", sqDist - sqDiam))\n Dim midPoint As Point = New Point((p.X + q.X) \/ 2, (p.Y + q.Y) \/ 2)\n If sqDist = sqDiam Then Return {midPoint}\n Dim d As Double = Math.Sqrt(rad * rad - sqDist \/ 4),\n a As Double = d * (q.X - p.X) \/ dist, b As Double = d * (q.Y - p.Y) \/ dist\n Return {New Point(midPoint.X - b, midPoint.Y + a), New Point(midPoint.X + b, midPoint.Y - a)}\n End Function\n\n Public Structure Point\n Public ReadOnly Property X As Double\n Public ReadOnly Property Y As Double\n\n Public Sub New(ByVal ix As Double, ByVal iy As Double)\n Me.New() : X = ix : Y = iy\n End Sub\n\n Public Shared Operator =(ByVal p As Point, ByVal q As Point) As Boolean\n Return p.X = q.X AndAlso p.Y = q.Y\n End Operator\n\n Public Shared Operator <>(ByVal p As Point, ByVal q As Point) As Boolean\n Return p.X <> q.X OrElse p.Y <> q.Y\n End Operator\n\n Public Shared Function SquaredDistance(ByVal p As Point, ByVal q As Point) As Double\n Dim dx As Double = q.X - p.X, dy As Double = q.Y - p.Y\n Return dx * dx + dy * dy\n End Function\n\n Public Shared Function Distance(ByVal p As Point, ByVal q As Point) As Double\n Return Math.Sqrt(SquaredDistance(p, q))\n End Function\n\n Public Overrides Function ToString() As String\n Return $\"({X}, {Y})\"\n End Function\n End Structure\nEnd Class\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":613} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Program\n Sub Main()\n ' Initialize with seed 0 to get deterministic output (may vary across .NET versions, though).\n Dim rand As New Random(0)\n\n Do\n Dim first = rand.Next(20) ' Upper bound is exclusive.\n Console.Write(first & \" \")\n\n If first = 10 Then Exit Do\n\n Dim second = rand.Next(20)\n Console.Write(second & \" \")\n Loop\n End Sub\nEnd Module\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":614} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nDim first_item = xml.XPathSelectElement(\"\/\/item\")\nConsole.WriteLine(first_item)\n \nFor Each price In xml.XPathSelectElements(\"\/\/price\")\n Console.WriteLine(price.Value)\nNext\n \nDim names = (From item In xml.XPathSelectElements(\"\/\/name\") Select item.Value).ToArray\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":615} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n'Example of array of 10 int types: \nDim numbers As Integer() = New Integer(9) {}\n'Example of array of 4 string types: \nDim words As String() = {\"hello\", \"world\", \"from\", \"mars\"}\n'You can also declare the size of the array and initialize the values at the same time: \nDim more_numbers As Integer() = New Integer(2) {21, 14, 63}\n\n'For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration. \n'The following creates a 3x2 int matrix \nDim number_matrix As Integer(,) = New Integer(2, 1) {}\n\n\n'As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces. \nDim string_matrix As String(,) = {{\"I\", \"swam\"}, {\"in\", \"the\"}, {\"freezing\", \"water\"}}\n'or\nDim funny_matrix As String(,) = New String(1, 1) {{\"clowns\", \"are\"}, {\"not\", \"funny\"}}\n\nDim array As Integer() = New Integer(9) {}\narray(0) = 1\narray(1) = 3\nConsole.WriteLine(array(0))\n\n\n'Dynamic\nImports System\nImports System.Collections.Generic\nDim list As New List(Of Integer)()\nlist.Add(1)\nlist.Add(3)\nlist(0) = 2\nConsole.WriteLine(list(0))\n","human_summarization":"demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and includes the functionality of pushing a value into the array.","id":616} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nDim toys As New List(Of String)\ntoys.Add(\"Car\")\ntoys.Add(\"Boat\")\ntoys.Add(\"Train\")\n","human_summarization":"Create and populate a collection in a statically-typed language. Review and ensure the code examples meet the task requirements.","id":617} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\n' Adapted from:\n' http:\/\/tawani.blogspot.com\/2009\/02\/topological-sorting-and-cyclic.html\n' added\/changed:\n' - conversion to VB.Net (.Net 2 framework)\n' - added Rosetta Code dependency format parsing\n' - check & removal of self-dependencies before sorting\nModule Program\n\tSub Main()\n\t\tDim Fields As New List(Of Field)()\n\t\t' You can also add Dependson using code like:\n\t\t' .DependsOn = New String() {\"ieee\", \"dw01\", \"dware\"} _\n\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"des_system_lib\", _\n\t\t\t.DependsOn = Split(\"std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\", \" \") _\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"dw01\", _\n\t\t\t.DependsOn = Split(\"ieee dw01 dware gtech\", \" \") _\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"dw02\", _\n\t\t\t.DependsOn = Split(\"ieee dw02 dware\", \" \") _\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"dw03\", _\n\t\t\t.DependsOn = Split(\"std synopsys dware dw03 dw02 dw01 ieee gtech\", \" \") _\t\t\t\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"dw04\", _\n\t\t\t.DependsOn = Split(\"dw04 ieee dw01 dware gtech\", \" \") _\t\t\t\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"dw05\", _\n\t\t\t.DependsOn = Split(\"dw05 ieee dware\", \" \") _\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"dw06\", _\n\t\t\t.DependsOn = Split(\"dw06 ieee dware\", \" \") _\t\t\t\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"dw07\", _\n\t\t\t.DependsOn = Split(\"ieee dware\", \" \") _\t\t\t\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"dware\", _\n\t\t\t.DependsOn = Split(\"ieee dware\", \" \") _\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"gtech\", _\n\t\t\t.DependsOn = Split(\"ieee gtech\", \" \") _\t\t\t\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"ramlib\", _\n\t\t\t.DependsOn = Split(\"std ieee\", \" \") _\t\t\t\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"std_cell_lib\", _\n\t\t\t.DependsOn = Split(\"ieee std_cell_lib\", \" \") _\t\t\t\n\t\t})\n\t\tfields.Add(New Field() With { _\n\t\t\t.Name = \"synopsys\" _\n\t\t})\t\t\n\t\tConsole.WriteLine(\"Input:\")\n\t\tFor Each ThisField As field In fields\n\t\t\tConsole.WriteLine(ThisField.Name)\n\t\t\tIf ThisField.DependsOn IsNot Nothing Then\n\t\t\t\tFor Each item As String In ThisField.DependsOn\n\t\t\t\t\tConsole.WriteLine(\" -{0}\", item)\n\t\t\t\tNext\n\t\t\tEnd If\n\t\tNext\n\n\t\tConsole.WriteLine(vbLf & \"...Sorting...\" & vbLf)\n\n\t\tDim sortOrder As Integer() = getTopologicalSortOrder(fields)\n\n\t\tFor i As Integer = 0 To sortOrder.Length - 1\n\t\t\tDim field = fields(sortOrder(i))\n\t\t\tConsole.WriteLine(field.Name)\n\t\t\t' Write up dependencies, too:\n\t\t\t'If field.DependsOn IsNot Nothing Then\n\t\t\t'\tFor Each item As String In field.DependsOn\n\t\t\t'\t\tConsole.WriteLine(\" -{0}\", item)\n\t\t\t'\tNext\n\t\t\t'End If\n\t\tNext\n\t\tConsole.Write(\"Press any key to continue . . . \")\n\t\tConsole.ReadKey(True)\n\tEnd Sub\n\t\n\tPrivate Sub CheckDependencies (ByRef Fields As List(Of Field))\n\t\t' Make sure all objects we depend on are part of the field list\n\t\t' themselves, as there may be dependencies that are not specified as fields themselves.\n\t\t' Remove dependencies on fields themselves.Y\t\t\t\n\t\tDim AField As Field, ADependency As String\n\t\t\n\t\tFor i As Integer = Fields.Count - 1 To 0 Step -1\n\t\t\tAField=fields(i)\n\t\t\tIf AField.DependsOn IsNot Nothing then\n\t\t\t\tFor j As Integer = 0 To Ubound(AField.DependsOn)\n\t\t\t\t\tADependency = Afield.DependsOn(j)\n\t\t\t\t\t' We ignore fields that depends on themselves:\n\t\t\t\t\tIf AField.Name <> ADependency then\n\t\t\t\t\t\tIf ListContainsVertex(fields, ADependency) = False Then\n\t\t\t\t\t\t\t' Add the dependent object to the field list, as it\n\t\t\t\t\t\t\t' needs to be there, without any dependencies\n\t\t\t\t\t\t\tFields.Add(New Field() With { _\n\t\t\t\t\t\t\t\t.Name = ADependency _\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\tEnd If\n\t\t\t\t\tEnd If\n\t\t\t\tNext j\n\t\t\tEnd If\n\t\tNext i\t\n\tEnd Sub\n\t\n\tPrivate Sub RemoveSelfDependencies (ByRef Fields As List(Of Field))\n\t\t' Make sure our fields don't depend on themselves.\n\t\t' If they do, remove the dependency.\n\t\tDim InitialUbound as Integer\n\t\tFor Each AField As Field In Fields\t\t\t\n\t\t\tIf AField.DependsOn IsNot Nothing Then\n\t\t\t\tInitialUbound = Ubound(AField.DependsOn)\n\t\t\t\tFor i As Integer = InitialUbound to 0 Step - 1\n\t\t\t\t\tIf Afield.DependsOn(i) = Afield.Name Then\n\t\t\t\t\t\t' This field depends on itself, so remove\n\t\t\t\t\t\tFor j as Integer = i To UBound(AField.DependsOn)-1\n\t\t\t\t\t\t\tAfield.DependsOn(j)=Afield.DependsOn(j+1)\n\t\t\t\t\t\tNext\n\t\t\t\t\t\tReDim Preserve Afield.DependsOn(UBound(Afield.DependsOn)-1)\n\t\t\t\t\tEnd If\n\t\t\t\tNext\n\t\t\tEnd If\t\t\t\n\t\tNext\n\tEnd Sub\t\n\t\t\t\n\tPrivate Function ListContainsVertex(Fields As List(Of Field), VertexName As String) As Boolean\n\t' Check to see if the list of Fields already contains a vertext called VertexName\n\tDim Found As Boolean = False\n\t\tFor i As Integer = 0 To fields.Count - 1\n\t\t\tIf Fields(i).Name = VertexName Then\n\t\t\t\tFound = True\n\t\t\t\tExit For\n\t\t\tEnd If\n\t\tNext\n\t\tReturn Found\n\tEnd Function\n\n\tPrivate Function getTopologicalSortOrder(ByRef Fields As List(Of Field)) As Integer()\n\t\t' Gets sort order. Will also add required dependencies to\n\t\t' Fields.\n\t\t\n\t\t' Make sure we don't have dependencies on ourselves.\n\t\t' We'll just get rid of them.\n\t\tRemoveSelfDependencies(Fields)\n\t\t\n\t\t'First check depencies, add them to Fields if required:\n\t\tCheckDependencies(Fields)\n\t\t' Now we have the correct Fields list, so we can proceed:\n\t\tDim g As New TopologicalSorter(fields.Count)\n\t\tDim _indexes As New Dictionary(Of String, Integer)(fields.count)\n\n\t\t'add vertex names to our lookup dictionaey\n\t\tFor i As Integer = 0 To fields.Count - 1\n\t\t\t_indexes(fields(i).Name.ToLower()) = g.AddVertex(i)\n\t\tNext\n\n\t\t'add edges\n\t\tFor i As Integer = 0 To fields.Count - 1\n\t\t\tIf fields(i).DependsOn IsNot Nothing Then\n\t\t\t\tFor j As Integer = 0 To fields(i).DependsOn.Length - 1\n\t\t\t\t\tg.AddEdge(i, _indexes(fields(i).DependsOn(j).ToLower()))\n\t\t\t\tNext\n\t\t\tEnd If\n\t\tNext\n\n\t\tDim result As Integer() = g.Sort()\n\t\tReturn result\n\tEnd Function\n\n\tPrivate Class Field\n\t\tPublic Property Name() As String\n\t\t\tGet\n\t\t\t\tReturn m_Name\n\t\t\tEnd Get\n\t\t\tSet\n\t\t\t\tm_Name = Value\n\t\t\tEnd Set\n\t\tEnd Property\n\t\tPrivate m_Name As String\n\t\tPublic Property DependsOn() As String()\n\t\t\tGet\n\t\t\t\tReturn m_DependsOn\n\t\t\tEnd Get\n\t\t\tSet\n\t\t\t\tm_DependsOn = Value\n\t\t\tEnd Set\n\t\tEnd Property\n\t\tPrivate m_DependsOn As String()\n\tEnd Class\nEnd Module\nClass TopologicalSorter\n\t''source adapted from:\n\t''http:\/\/tawani.blogspot.com\/2009\/02\/topological-sorting-and-cyclic.html\n\t''which was adapted from:\n\t''http:\/\/www.java2s.com\/Code\/Java\/Collections-Data-Structure\/Topologicalsorting.htm\n\t#Region \"- Private Members -\"\n\n\tPrivate ReadOnly _vertices As Integer()\n\t' list of vertices\n\tPrivate ReadOnly _matrix As Integer(,)\n\t' adjacency matrix\n\tPrivate _numVerts As Integer\n\t' current number of vertices\n\tPrivate ReadOnly _sortedArray As Integer()\n\t' Sorted vertex labels\n\n\t#End Region\n\n\t#Region \"- CTors -\"\n\n\tPublic Sub New(size As Integer)\n\t\t_vertices = New Integer(size - 1) {}\n\t\t_matrix = New Integer(size - 1, size - 1) {}\n\t\t_numVerts = 0\n\t\tFor i As Integer = 0 To size - 1\n\t\t\tFor j As Integer = 0 To size - 1\n\t\t\t\t_matrix(i, j) = 0\n\t\t\tNext\n\t\tNext\n\t\t\t' sorted vert labels\n\t\t_sortedArray = New Integer(size - 1) {}\n\tEnd Sub\n\n\t#End Region\n\n\t#Region \"- Public Methods -\"\n\n\tPublic Function AddVertex(vertex As Integer) As Integer\n\t\t_vertices(System.Threading.Interlocked.Increment(_numVerts)-1) = vertex\n\t\tReturn _numVerts - 1\n\tEnd Function\n\n\tPublic Sub AddEdge(start As Integer, [end] As Integer)\n\t\t_matrix(start, [end]) = 1\n\tEnd Sub\n\n\tPublic Function Sort() As Integer()\n\t' Topological sort\n\t\tWhile _numVerts > 0\n\t\t\t' while vertices remain,\n\t\t\t' get a vertex with no successors, or -1\n\t\t\tDim currentVertex As Integer = noSuccessors()\n\t\t\tIf currentVertex = -1 Then\n\t\t\t\t' must be a cycle\n\t\t\t\tThrow New Exception(\"Graph has cycles\")\n\t\t\tEnd If\n\n\t\t\t' insert vertex label in sorted array (start at end)\n\t\t\t_sortedArray(_numVerts - 1) = _vertices(currentVertex)\n\n\t\t\t\t' delete vertex\n\t\t\tdeleteVertex(currentVertex)\n\t\tEnd While\n\n\t\t' vertices all gone; return sortedArray\n\t\tReturn _sortedArray\n\tEnd Function\n\n\t#End Region\n\n\t#Region \"- Private Helper Methods -\"\n\n\t' returns vert with no successors (or -1 if no such verts)\n\tPrivate Function noSuccessors() As Integer\n\t\tFor row As Integer = 0 To _numVerts - 1\n\t\t\tDim isEdge As Boolean = False\n\t\t\t' edge from row to column in adjMat\n\t\t\tFor col As Integer = 0 To _numVerts - 1\n\t\t\t\tIf _matrix(row, col) > 0 Then\n\t\t\t\t\t' if edge to another,\n\t\t\t\t\tisEdge = True\n\t\t\t\t\t\t' this vertex has a successor try another\n\t\t\t\t\tExit For\n\t\t\t\tEnd If\n\t\t\tNext\n\t\t\tIf Not isEdge Then\n\t\t\t\t' if no edges, has no successors\n\t\t\t\tReturn row\n\t\t\tEnd If\n\t\tNext\n\t\tReturn -1\n\t\t' no\n\tEnd Function\n\n\tPrivate Sub deleteVertex(delVert As Integer)\n\t\t' if not last vertex, delete from vertexList\n\t\tIf delVert <> _numVerts - 1 Then\n\t\t\tFor j As Integer = delVert To _numVerts - 2\n\t\t\t\t_vertices(j) = _vertices(j + 1)\n\t\t\tNext\n\n\t\t\tFor row As Integer = delVert To _numVerts - 2\n\t\t\t\tmoveRowUp(row, _numVerts)\n\t\t\tNext\n\n\t\t\tFor col As Integer = delVert To _numVerts - 2\n\t\t\t\tmoveColLeft(col, _numVerts - 1)\n\t\t\tNext\n\t\tEnd If\n\t\t_numVerts -= 1\n\t\t' one less vertex\n\tEnd Sub\n\n\tPrivate Sub moveRowUp(row As Integer, length As Integer)\n\t\tFor col As Integer = 0 To length - 1\n\t\t\t_matrix(row, col) = _matrix(row + 1, col)\n\t\tNext\n\tEnd Sub\n\n\tPrivate Sub moveColLeft(col As Integer, length As Integer)\n\t\tFor row As Integer = 0 To length - 1\n\t\t\t_matrix(row, col) = _matrix(row, col + 1)\n\t\tNext\n\tEnd Sub\n\n\t#End Region\nEnd Class\n\nInput:\ndes_system_lib\n -std\n -synopsys\n -std_cell_lib\n -des_system_lib\n -dw02\n -dw01\n -ramlib\n -ieee\ndw01\n -ieee\n -dw01\n -dware\n -gtech\ndw02\n -ieee\n -dw02\n -dware\ndw03\n -std\n -synopsys\n -dware\n -dw03\n -dw02\n -dw01\n -ieee\n -gtech\ndw04\n -dw04\n -ieee\n -dw01\n -dware\n -gtech\ndw05\n -dw05\n -ieee\n -dware\ndw06\n -dw06\n -ieee\n -dware\ndw07\n -ieee\n -dware\ndware\n -ieee\n -dware\ngtech\n -ieee\n -gtech\nramlib\n -std\n -ieee\nstd_cell_lib\n -ieee\n -std_cell_lib\nsynopsys\n\n...Sorting...\n\ndes_system_lib\nramlib\ndw03\nstd\nstd_cell_lib\ndw04\ndw01\ngtech\ndw07\ndw06\ndw05\ndw02\ndware\nieee\nsynopsys\nPress any key to continue . . .\n\n","human_summarization":"The code is a function that performs a topological sort on VHDL libraries based on their dependencies. It returns a valid compile order ensuring no library is compiled before its dependencies. The function handles self-dependencies and flags un-orderable dependencies. It assumes library names are single words and considers items with no dependents. The sorting is based on Kahn's 1962 topological sort or depth-first search algorithm.","id":618} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\nModule Module1\n\n Dim CA As Char() = \"0123456789ABC\".ToCharArray()\n\n Sub FourSquare(lo As Integer, hi As Integer, uni As Boolean, sy As Char())\n If sy IsNot Nothing Then Console.WriteLine(\"a b c d e f g\" & vbLf & \"-------------\")\n Dim r = Enumerable.Range(lo, hi - lo + 1).ToList(), u As New List(Of Integer),\n t As Integer, cn As Integer = 0\n For Each a In r\n u.Add(a)\n For Each b In r\n If uni AndAlso u.Contains(b) Then Continue For\n u.Add(b)\n t = a + b\n For Each c In r : If uni AndAlso u.Contains(c) Then Continue For\n u.Add(c)\n For d = a - c To a - c\n If d < lo OrElse d > hi OrElse uni AndAlso u.Contains(d) OrElse\n t <> b + c + d Then Continue For\n u.Add(d)\n For Each e In r\n If uni AndAlso u.Contains(e) Then Continue For\n u.Add(e)\n For f = b + c - e To b + c - e\n If f < lo OrElse f > hi OrElse uni AndAlso u.Contains(f) OrElse\n t <> d + e + f Then Continue For\n u.Add(f)\n For g = t - f To t - f : If g < lo OrElse g > hi OrElse\n uni AndAlso u.Contains(g) Then Continue For\n cn += 1 : If sy IsNot Nothing Then _\n Console.WriteLine(\"{0} {1} {2} {3} {4} {5} {6}\",\n sy(a), sy(b), sy(c), sy(d), sy(e), sy(f), sy(g))\n Next : u.Remove(f) : Next : u.Remove(e) : Next : u.Remove(d)\n Next : u.Remove(c) : Next : u.Remove(b) : Next : u.Remove(a)\n Next : Console.WriteLine(\"{0} {1}unique solutions for [{2},{3}]{4}\",\n cn, If(uni, \"\", \"non-\"), lo, hi, vbLf)\n End Sub\n\n Sub main()\n fourSquare(1, 7, True, CA)\n fourSquare(3, 9, True, CA)\n fourSquare(0, 9, False, Nothing)\n fourSquare(5, 12, True, CA)\n End Sub\n\nEnd Module\n\n\n","human_summarization":"The code solves the 4-rings or 4-squares puzzle by replacing the letters a to g with decimal digits ranging from a low to high value. It ensures that the sum of the letters inside each of the four large squares is equal. It displays all unique solutions for the ranges 1-7 and 3-9, and the total number of solutions, including non-unique ones, for the range 0-9. The code uses a brute-force algorithm with enhancements such as a \"used\" list to check for overlapping variables and constrains the loops for variables d, f, and g based on other variables. It also solves a related task, the no connection puzzle.","id":619} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\nWorks with: .NET Core version 2.1\n\nOPTION COMPARE BINARY\nOPTION EXPLICIT ON\nOPTION INFER ON\nOPTION STRICT ON\n\nIMPORTS SYSTEM.GLOBALIZATION\nIMPORTS SYSTEM.TEXT\nIMPORTS SYSTEM.RUNTIME.INTEROPSERVICES\nIMPORTS SYSTEM.RUNTIME.COMPILERSERVICES\n\nMODULE ARGHELPER\n READONLY _ARGDICT AS NEW DICTIONARY(OF STRING, STRING)()\n\n DELEGATE FUNCTION TRYPARSE(OF T, TRESULT)(VALUE AS T, BYREF RESULT AS TRESULT) AS BOOLEAN\n\n SUB INITIALIZEARGUMENTS(ARGS AS STRING())\n FOR EACH ITEM IN ARGS\n ITEM = ITEM.TOUPPERINVARIANT()\n\n IF ITEM.LENGTH > 0 ANDALSO ITEM(0) <> \"\"\"\"C THEN\n DIM COLONPOS = ITEM.INDEXOF(\":\"C, STRINGCOMPARISON.ORDINAL)\n\n IF COLONPOS <> -1 THEN\n ' SPLIT ARGUMENTS WITH COLUMNS INTO KEY(PART BEFORE COLON) \/ VALUE(PART AFTER COLON) PAIRS.\n _ARGDICT.ADD(ITEM.SUBSTRING(0, COLONPOS), ITEM.SUBSTRING(COLONPOS + 1, ITEM.LENGTH - COLONPOS - 1))\n END IF\n END IF\n NEXT\n END SUB\n\n SUB FROMARGUMENT(OF T)(\n KEY AS STRING,\n BYREF VAR AS T,\n GETDEFAULT AS FUNC(OF T),\n TRYPARSE AS TRYPARSE(OF STRING, T),\n OPTIONAL VALIDATE AS PREDICATE(OF T) = NOTHING)\n\n DIM VALUE AS STRING = NOTHING\n IF _ARGDICT.TRYGETVALUE(KEY.TOUPPERINVARIANT(), VALUE) THEN\n IF NOT (TRYPARSE(VALUE, VAR) ANDALSO (VALIDATE IS NOTHING ORELSE VALIDATE(VAR))) THEN\n CONSOLE.WRITELINE($\"INVALID VALUE FOR {KEY}: {VALUE}\")\n ENVIRONMENT.EXIT(-1)\n END IF\n ELSE\n VAR = GETDEFAULT()\n END IF\n END SUB\nEND MODULE\n\nMODULE PROGRAM\n SUB MAIN(ARGS AS STRING())\n DIM DT AS DATE\n DIM COLUMNS, ROWS, MONTHSPERROW AS INTEGER\n DIM VERTSTRETCH, HORIZSTRETCH, RESIZEWINDOW AS BOOLEAN\n\n INITIALIZEARGUMENTS(ARGS)\n FROMARGUMENT(\"DATE\", DT, FUNCTION() NEW DATE(1969, 1, 1), ADDRESSOF DATE.TRYPARSE)\n FROMARGUMENT(\"COLS\", COLUMNS, FUNCTION() 80, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 20)\n FROMARGUMENT(\"ROWS\", ROWS, FUNCTION() 43, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V >= 0)\n FROMARGUMENT(\"MS\/ROW\", MONTHSPERROW, FUNCTION() 0, ADDRESSOF INTEGER.TRYPARSE, FUNCTION(V) V <= 12 ANDALSO V <= COLUMNS \\ 20)\n FROMARGUMENT(\"VSTRETCH\", VERTSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n FROMARGUMENT(\"HSTRETCH\", HORIZSTRETCH, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n FROMARGUMENT(\"WSIZE\", RESIZEWINDOW, FUNCTION() TRUE, ADDRESSOF BOOLEAN.TRYPARSE)\n\n ' THE SCROLL BAR IN COMMAND PROMPT SEEMS TO TAKE UP PART OF THE LAST COLUMN.\n IF RESIZEWINDOW THEN\n CONSOLE.WINDOWWIDTH = COLUMNS + 1\n CONSOLE.WINDOWHEIGHT = ROWS\n END IF\n\n IF MONTHSPERROW < 1 THEN MONTHSPERROW = MATH.MAX(COLUMNS \\ 22, 1)\n\n FOR EACH ROW IN GETCALENDARROWS(DT:=DT, WIDTH:=COLUMNS, HEIGHT:=ROWS, MONTHSPERROW:=MONTHSPERROW, VERTSTRETCH:=VERTSTRETCH, HORIZSTRETCH:=HORIZSTRETCH)\n CONSOLE.WRITE(ROW)\n NEXT\n END SUB\n\n ITERATOR FUNCTION GETCALENDARROWS(\n DT AS DATE,\n WIDTH AS INTEGER,\n HEIGHT AS INTEGER,\n MONTHSPERROW AS INTEGER,\n VERTSTRETCH AS BOOLEAN,\n HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n\n DIM YEAR = DT.YEAR\n DIM CALENDARROWCOUNT AS INTEGER = CINT(MATH.CEILING(12 \/ MONTHSPERROW))\n ' MAKE ROOM FOR THE THREE EMPTY LINES ON TOP.\n DIM MONTHGRIDHEIGHT AS INTEGER = HEIGHT - 3\n\n YIELD \"[SNOOPY]\".PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n YIELD YEAR.TOSTRING(CULTUREINFO.INVARIANTCULTURE).PADCENTER(WIDTH) & ENVIRONMENT.NEWLINE\n YIELD ENVIRONMENT.NEWLINE\n\n DIM MONTH = 0\n DO WHILE MONTH < 12\n DIM ROWHIGHESTMONTH = MATH.MIN(MONTH + MONTHSPERROW, 12)\n\n DIM CELLWIDTH = WIDTH \\ MONTHSPERROW\n DIM CELLCONTENTWIDTH = IF(MONTHSPERROW = 1, CELLWIDTH, (CELLWIDTH * 19) \\ 20)\n\n DIM CELLHEIGHT = MONTHGRIDHEIGHT \\ CALENDARROWCOUNT\n DIM CELLCONTENTHEIGHT = (CELLHEIGHT * 19) \\ 20\n\n ' CREATES A MONTH CELL FOR THE SPECIFIED MONTH (1-12).\n DIM GETMONTHFROM =\n FUNCTION(M AS INTEGER) BUILDMONTH(\n DT:=NEW DATE(DT.YEAR, M, 1),\n WIDTH:=CELLCONTENTWIDTH,\n HEIGHT:=CELLCONTENTHEIGHT,\n VERTSTRETCH:=VERTSTRETCH,\n HORIZSTRETCH:=HORIZSTRETCH).SELECT(FUNCTION(X) X.PADCENTER(CELLWIDTH))\n\n ' THE MONTHS IN THIS ROW OF THE CALENDAR.\n DIM MONTHSTHISROW AS IENUMERABLE(OF IENUMERABLE(OF STRING)) =\n ENUMERABLE.SELECT(ENUMERABLE.RANGE(MONTH + 1, ROWHIGHESTMONTH - MONTH), GETMONTHFROM)\n\n DIM CALENDARROW AS IENUMERABLE(OF STRING) =\n INTERLEAVED(\n MONTHSTHISROW,\n USEINNERSEPARATOR:=FALSE,\n USEOUTERSEPARATOR:=TRUE,\n OUTERSEPARATOR:=ENVIRONMENT.NEWLINE)\n\n DIM EN = CALENDARROW.GETENUMERATOR()\n DIM HASNEXT = EN.MOVENEXT()\n DO WHILE HASNEXT\n\n DIM CURRENT AS STRING = EN.CURRENT\n\n ' TO MAINTAIN THE (NOT STRICTLY NEEDED) CONTRACT OF YIELDING COMPLETE ROWS, KEEP THE NEWLINE AFTER\n ' THE CALENDAR ROW WITH THE LAST TERMINAL ROW OF THE ROW.\n HASNEXT = EN.MOVENEXT()\n YIELD IF(HASNEXT, CURRENT, CURRENT & ENVIRONMENT.NEWLINE)\n LOOP\n\n MONTH += MONTHSPERROW\n LOOP\n END FUNCTION\n\n ''' \n ''' INTERLEAVES THE ELEMENTS OF THE SPECIFIED SUB-SOURCES BY MAKING SUCCESSIVE PASSES THROUGH THE SOURCE\n ''' ENUMERABLE, YIELDING A SINGLE ELEMENT FROM EACH SUB-SOURCE IN SEQUENCE IN EACH PASS, OPTIONALLY INSERTING A\n ''' SEPARATOR BETWEEN ELEMENTS OF ADJACENT SUB-SOURCES AND OPTIONALLY A DIFFERENT SEPARATOR AT THE END OF EACH\n ''' PASS THROUGH ALL THE SOURCES. (I.E., BETWEEN ELEMENTS OF THE LAST AND FIRST SOURCE)\n ''' <\/SUMMARY>\n ''' THE TYPE OF THE ELEMENTS OF THE SUB-SOURCES.<\/TYPEPARAM>\n ''' A SEQUENCE OF THE SEQUENCES WHOSE ELEMENTS ARE TO BE INTERLEAVED.<\/PARAM>\n ''' WHETHER TO INSERT BETWEEN THE ELEMENTS OFADJACENT SUB-SOURCES.<\/PARAM>\n ''' THE SEPARATOR BETWEEN ELEMENTS OF ADJACENT SUB-SOURCES.<\/PARAM>\n ''' WHETHER TO INSERT BETWEEN THE ELEMENTS OF THE LAST AND FIRST SUB-SOURCES.<\/PARAM>\n ''' THE SEPARATOR BETWEEN ELEMENTS OF THE LAST AND FIRST SUB-SOURCE.<\/PARAM>\n ''' IF , THE ENUMERATION CONTINUES UNTIL EVERY GIVEN SUBSOURCE IS EMPTY;\n ''' IF , THE ENUMERATION STOPS AS SOON AS ANY ENUMERABLE NO LONGER HAS AN ELEMENT TO SUPPLY FOR THE NEXT PASS.<\/PARAM>\n ITERATOR FUNCTION INTERLEAVED(OF T)(\n SOURCES AS IENUMERABLE(OF IENUMERABLE(OF T)),\n OPTIONAL USEINNERSEPARATOR AS BOOLEAN = FALSE,\n OPTIONAL INNERSEPARATOR AS T = NOTHING,\n OPTIONAL USEOUTERSEPARATOR AS BOOLEAN = FALSE,\n OPTIONAL OUTERSEPARATOR AS T = NOTHING,\n OPTIONAL WHILEANY AS BOOLEAN = TRUE) AS IENUMERABLE(OF T)\n DIM SOURCEENUMERATORS AS IENUMERATOR(OF T)() = NOTHING\n\n TRY\n SOURCEENUMERATORS = SOURCES.SELECT(FUNCTION(X) X.GETENUMERATOR()).TOARRAY()\n DIM NUMSOURCES = SOURCEENUMERATORS.LENGTH\n DIM ENUMERATORSTATES(NUMSOURCES - 1) AS BOOLEAN\n\n DIM ANYPREVITERS AS BOOLEAN = FALSE\n DO\n ' INDICES OF FIRST AND LAST SUB-SOURCES THAT HAVE ELEMENTS.\n DIM FIRSTACTIVE = -1, LASTACTIVE = -1\n\n ' DETERMINE WHETHER EACH SUB-SOURCE THAT STILL HAVE ELEMENTS.\n FOR I = 0 TO NUMSOURCES - 1\n ENUMERATORSTATES(I) = SOURCEENUMERATORS(I).MOVENEXT()\n IF ENUMERATORSTATES(I) THEN\n IF FIRSTACTIVE = -1 THEN FIRSTACTIVE = I\n LASTACTIVE = I\n END IF\n NEXT\n\n ' DETERMINE WHETHER TO YIELD ANYTHING IN THIS ITERATION BASED ON WHETHER WHILEANY IS TRUE.\n ' NOT YIELDING ANYTHING THIS ITERATION IMPLIES THAT THE ENUMERATION HAS ENDED.\n DIM THISITERHASRESULTS AS BOOLEAN = IF(WHILEANY, FIRSTACTIVE <> -1, FIRSTACTIVE = 0 ANDALSO LASTACTIVE = NUMSOURCES - 1)\n IF NOT THISITERHASRESULTS THEN EXIT DO\n\n ' DON'T INSERT A SEPARATOR ON THE FIRST PASS.\n IF ANYPREVITERS THEN\n IF USEOUTERSEPARATOR THEN YIELD OUTERSEPARATOR\n ELSE\n ANYPREVITERS = TRUE\n END IF\n\n ' GO THROUGH AND YIELD FROM THE SUB-SOURCES THAT STILL HAVE ELEMENTS.\n FOR I = 0 TO NUMSOURCES - 1\n IF ENUMERATORSTATES(I) THEN\n ' DON'T INSERT A SEPARATOR BEFORE THE FIRST ELEMENT.\n IF I > FIRSTACTIVE ANDALSO USEINNERSEPARATOR THEN YIELD INNERSEPARATOR\n YIELD SOURCEENUMERATORS(I).CURRENT\n END IF\n NEXT\n LOOP\n\n FINALLY\n IF SOURCEENUMERATORS ISNOT NOTHING THEN\n FOR EACH EN IN SOURCEENUMERATORS\n EN.DISPOSE()\n NEXT\n END IF\n END TRY\n END FUNCTION\n\n ''' \n ''' RETURNS THE ROWS REPRESENTING ONE MONTH CELL WITHOUT TRAILING NEWLINES. APPROPRIATE LEADING AND TRAILING\n ''' WHITESPACE IS ADDED SO THAT EVERY ROW HAS THE LENGTH OF WIDTH.\n ''' <\/SUMMARY>\n ''' A DATE WITHIN THE MONTH TO REPRESENT.<\/PARAM>\n ''' THE WIDTH OF THE CELL.<\/PARAM>\n ''' THE HEIGHT.<\/PARAM>\n ''' IF , BLANK ROWS ARE INSERTED TO FIT THE AVAILABLE HEIGHT.\n ''' OTHERWISE, THE CELL HAS A CONSTANT HEIGHT OF <\/PARAM>\n ''' IF , THE SPACING BETWEEN INDIVIDUAL DAYS IS INCREASED TO\n ''' FIT THE AVAILABLE WIDTH. OTHERWISE, THE CELL HAS A CONSTANT WIDTH OF 20 CHARACTERS AND IS PADDED TO BE IN\n ''' THE CENTER OF THE EXPECTED WIDTH.<\/PARAM>\n ITERATOR FUNCTION BUILDMONTH(DT AS DATE, WIDTH AS INTEGER, HEIGHT AS INTEGER, VERTSTRETCH AS BOOLEAN, HORIZSTRETCH AS BOOLEAN) AS IENUMERABLE(OF STRING)\n CONST DAY_WDT = 2 ' WIDTH OF A DAY.\n CONST ALLDAYS_WDT = DAY_WDT * 7 ' WIDTH OF AL LDAYS COMBINED.\n\n ' NORMALIZE THE DATE TO JANUARY 1.\n DT = NEW DATE(DT.YEAR, DT.MONTH, 1)\n\n ' HORIZONTAL WHITESPACE BETWEEN DAYS OF THE WEEK. CONSTANT OF 6 REPRESENTS 6 SEPARATORS PER LINE.\n DIM DAYSEP AS NEW STRING(\" \"C, MATH.MIN((WIDTH - ALLDAYS_WDT) \\ 6, IF(HORIZSTRETCH, INTEGER.MAXVALUE, 1)))\n ' NUMBER OF BLANK LINES BETWEEN ROWS.\n DIM VERTBLANKCOUNT = IF(NOT VERTSTRETCH, 0, (HEIGHT - 8) \\ 7)\n\n ' WIDTH OF EACH DAY * 7 DAYS IN ONE ROW + DAY SEPARATOR LENGTH * 6 SEPARATORS PER LINE.\n DIM BLOCKWIDTH = ALLDAYS_WDT + DAYSEP.LENGTH * 6\n\n ' THE WHITESPACE AT THE BEGINNING OF EACH LINE.\n DIM LEFTPAD AS NEW STRING(\" \"C, (WIDTH - BLOCKWIDTH) \\ 2)\n ' THE WHITESPACE FOR BLANK LINES.\n DIM FULLPAD AS NEW STRING(\" \"C, WIDTH)\n\n ' LINES ARE \"STAGED\" IN THE STRINGBUILDER.\n DIM SB AS NEW STRINGBUILDER(LEFTPAD)\n DIM NUMLINES = 0\n\n ' GET THE CURRENT LINE SO FAR FORM THE STRINGBUILDER AND BEGIN A NEW LINE.\n ' RETURNS THE CURRENT LINE AND TRAILING BLANK LINES USED FOR VERTICAL PADDING (IF ANY).\n ' RETURNS EMPTY ENUMERABLE IF THE HEIGHT REQUIREMENT HAS BEEN REACHED.\n DIM ENDLINE =\n FUNCTION() AS IENUMERABLE(OF STRING)\n DIM FINISHEDLINE AS STRING = SB.TOSTRING().PADRIGHT(WIDTH)\n SB.CLEAR()\n SB.APPEND(LEFTPAD)\n\n ' USE AN INNER ITERATOR TO PREVENT LAZY EXECUTION OF SIDE EFFECTS OF OUTER FUNCTION.\n RETURN IF(NUMLINES >= HEIGHT,\n ENUMERABLE.EMPTY(OF STRING)(),\n ITERATOR FUNCTION() AS IENUMERABLE(OF STRING)\n YIELD FINISHEDLINE\n NUMLINES += 1\n\n FOR I = 1 TO VERTBLANKCOUNT\n IF NUMLINES >= HEIGHT THEN RETURN\n YIELD FULLPAD\n NUMLINES += 1\n NEXT\n END FUNCTION())\n END FUNCTION\n\n ' YIELD THE MONTH NAME.\n SB.APPEND(PADCENTER(DT.TOSTRING(\"MMMM\", CULTUREINFO.INVARIANTCULTURE), BLOCKWIDTH).TOUPPER())\n FOR EACH L IN ENDLINE()\n YIELD L\n NEXT\n\n ' YIELD THE HEADER OF WEEKDAY NAMES.\n DIM WEEKNMABBREVS = [ENUM].GETNAMES(GETTYPE(DAYOFWEEK)).SELECT(FUNCTION(X) X.SUBSTRING(0, 2).TOUPPER())\n SB.APPEND(STRING.JOIN(DAYSEP, WEEKNMABBREVS))\n FOR EACH L IN ENDLINE()\n YIELD L\n NEXT\n\n ' DAY OF WEEK OF FIRST DAY OF MONTH.\n DIM STARTWKDY = CINT(DT.DAYOFWEEK)\n\n ' INITIALIZE WITH EMPTY SPACE FOR THE FIRST LINE.\n DIM FIRSTPAD AS NEW STRING(\" \"C, (DAY_WDT + DAYSEP.LENGTH) * STARTWKDY)\n SB.APPEND(FIRSTPAD)\n\n DIM D = DT\n DO WHILE D.MONTH = DT.MONTH\n SB.APPENDFORMAT(CULTUREINFO.INVARIANTCULTURE, $\"{{0,{DAY_WDT}}}\", D.DAY)\n\n ' EACH ROW ENDS ON SATURDAY.\n IF D.DAYOFWEEK = DAYOFWEEK.SATURDAY THEN\n FOR EACH L IN ENDLINE()\n YIELD L\n NEXT\n ELSE\n SB.APPEND(DAYSEP)\n END IF\n\n D = D.ADDDAYS(1)\n LOOP\n\n ' KEEP ADDING EMPTY LINES UNTIL THE HEIGHT QUOTA IS MET.\n DIM NEXTLINES AS IENUMERABLE(OF STRING)\n DO\n NEXTLINES = ENDLINE()\n FOR EACH L IN NEXTLINES\n YIELD L\n NEXT\n LOOP WHILE NEXTLINES.ANY()\n END FUNCTION\n\n ''' \n ''' RETURNS A NEW STRING THAT CENTER-ALIGNS THE CHARACTERS IN THIS STRING BY PADDING TO THE LEFT AND RIGHT WITH\n ''' THE SPECIFIED CHARACTER TO A SPECIFIED TOTAL LENGTH.\n ''' <\/SUMMARY>\n ''' THE STRING TO CENTER-ALIGN.<\/PARAM>\n ''' THE NUMBER OF CHARACTERS IN THE RESULTING STRING.<\/PARAM>\n ''' THE PADDING CHARACTER.<\/PARAM>\n \n PRIVATE FUNCTION PADCENTER(S AS STRING, TOTALWIDTH AS INTEGER, OPTIONAL PADDINGCHAR AS CHAR = \" \"C) AS STRING\n RETURN S.PADLEFT(((TOTALWIDTH - S.LENGTH) \\ 2) + S.LENGTH, PADDINGCHAR).PADRIGHT(TOTALWIDTH, PADDINGCHAR)\n END FUNCTION\nEND MODULE\n\n\nOutput \u00a0\u2014\u00a0 for input COLS:132 ROWS:25 MS\/ROW:6 HSTRETCH:FALSE VSTRETCH:FALSE:\n [SNOOPY] \n 1969 \n\n JANUARY FEBRUARY MARCH APRIL MAY JUNE \n SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA \n 1 2 3 4 1 1 1 2 3 4 5 1 2 3 1 2 3 4 5 6 7 \n 5 6 7 8 9 10 11 2 3 4 5 6 7 8 2 3 4 5 6 7 8 6 7 8 9 10 11 12 4 5 6 7 8 9 10 8 9 10 11 12 13 14 \n 12 13 14 15 16 17 18 9 10 11 12 13 14 15 9 10 11 12 13 14 15 13 14 15 16 17 18 19 11 12 13 14 15 16 17 15 16 17 18 19 20 21 \n 19 20 21 22 23 24 25 16 17 18 19 20 21 22 16 17 18 19 20 21 22 20 21 22 23 24 25 26 18 19 20 21 22 23 24 22 23 24 25 26 27 28 \n 26 27 28 29 30 31 23 24 25 26 27 28 23 24 25 26 27 28 29 27 28 29 30 25 26 27 28 29 30 31 29 30 \n 30 31 \n \n \n JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER \n SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA SU MO TU WE TH FR SA \n 1 2 3 4 5 1 2 1 2 3 4 5 6 1 2 3 4 1 1 2 3 4 5 6 \n 6 7 8 9 10 11 12 3 4 5 6 7 8 9 7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8 7 8 9 10 11 12 13 \n 13 14 15 16 17 18 19 10 11 12 13 14 15 16 14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15 14 15 16 17 18 19 20 \n 20 21 22 23 24 25 26 17 18 19 20 21 22 23 21 22 23 24 25 26 27 19 20 21 22 23 24 25 16 17 18 19 20 21 22 21 22 23 24 25 26 27 \n 27 28 29 30 31 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29 28 29 30 31 \n 31 30 \n \n \n\n","human_summarization":"The code provides an algorithm that generates a calendar, formatted to fit a page that is 132 characters wide. The entire code is written in uppercase, inspired by the programming practices of the 1960s. It does not include Snoopy generation, but instead outputs a placeholder. The code is written in Roslyn Visual Basic language version 15.8 or higher.","id":620} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n Dim newForm as new Form\n newForm.Text = \"It's a new window\"\n \n newForm.Show()\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":621} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nModule Module1\n Private Delegate Function Justification(s As String, width As Integer) As String\n\n Private Function AlignColumns(lines As String(), justification As Justification) As String()\n Const Separator As Char = \"$\"c\n ' build input container table and calculate columns count\n Dim containerTbl As String()() = New String(lines.Length - 1)() {}\n Dim columns As Integer = 0\n For i As Integer = 0 To lines.Length - 1\n Dim row As String() = lines(i).TrimEnd(Separator).Split(Separator)\n If columns < row.Length Then\n columns = row.Length\n End If\n containerTbl(i) = row\n Next\n ' create formatted container table\n Dim formattedTable As String()() = New String(containerTbl.Length - 1)() {}\n For i As Integer = 0 To formattedTable.Length - 1\n formattedTable(i) = New String(columns - 1) {}\n Next\n For j As Integer = 0 To columns - 1\n ' get max column width\n Dim columnWidth As Integer = 0\n For i As Integer = 0 To containerTbl.Length - 1\n If j < containerTbl(i).Length AndAlso columnWidth < containerTbl(i)(j).Length Then\n columnWidth = containerTbl(i)(j).Length\n End If\n Next\n ' justify column cells\n For i As Integer = 0 To formattedTable.Length - 1\n If j < containerTbl(i).Length Then\n formattedTable(i)(j) = justification(containerTbl(i)(j), columnWidth)\n Else\n formattedTable(i)(j) = New [String](\" \"c, columnWidth)\n End If\n Next\n Next\n ' create result\n Dim result As String() = New String(formattedTable.Length - 1) {}\n For i As Integer = 0 To result.Length - 1\n result(i) = [String].Join(\" \", formattedTable(i))\n Next\n Return result\n End Function\n\n Private Function JustifyLeft(s As String, width As Integer) As String\n Return s.PadRight(width)\n End Function\n Private Function JustifyRight(s As String, width As Integer) As String\n Return s.PadLeft(width)\n End Function\n Private Function JustifyCenter(s As String, width As Integer) As String\n Return s.PadLeft((width + s.Length) \/ 2).PadRight(width)\n End Function\n\n Sub Main()\n Dim input As String() = {\"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\", \"are$delineated$by$a$single$'dollar'$character,$write$a$program\", \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\", \"column$are$separated$by$at$least$one$space.\", \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\", \"justified,$right$justified,$or$center$justified$within$its$column.\"}\n\n For Each line As String In AlignColumns(input, AddressOf JustifyLeft)\n Console.WriteLine(line)\n Next\n Console.ReadLine()\n End Sub\n\nEnd Module\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":622} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\nWorks with: Visual Basic .NET version 9.0+\nModule Module1\n\n Private Function rot13(ByVal str As String) As String\n Dim newChars As Char(), i, j As Integer, original, replacement As String\n\n original = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n replacement = \"NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm\"\n\n newChars = str.ToCharArray()\n\n For i = 0 To newChars.Length - 1\n For j = 0 To 51\n If newChars(i) = original(j) Then\n newChars(i) = replacement(j)\n Exit For\n End If\n Next\n Next\n\n Return New String(newChars)\n End Function\n\nEnd Module\n\n","human_summarization":"Implement a rot-13 function or procedure that can be called in the programming environment. This function can optionally be wrapped in a utility program that performs a line-by-line rot-13 encoding of every line of input from each file listed on its command line or acts as a filter on its standard input. The rot-13 encoding replaces every letter of the ASCII alphabet with the letter rotated 13 characters around the 26 letter alphabet. The implementation should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream without alteration. The solution uses simple textual substitution.","id":623} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nImports System\nImports System.Text.RegularExpressions\n\nModule Bulls_and_Cows\n Function CreateNumber() As String\n Dim random As New Random()\n Dim sequence As Char() = {\"1\"c, \"2\"c, \"3\"c, \"4\"c, \"5\"c, \"6\"c, \"7\"c, \"8\"c, \"9\"c}\n\n For i As Integer = 0 To sequence.Length - 1\n Dim j As Integer = random.Next(sequence.Length)\n Dim temp As Char = sequence(i) : sequence(i) = sequence(j) : sequence(j) = temp\n Next\n\n Return New String(sequence, 0, 4)\n End Function\n\n Function IsFourDigitNumber(ByVal number As String) As Boolean\n Return Regex.IsMatch(number, \"^[1-9]{4}$\")\n End Function\n\n Sub Main()\n Dim chosenNumber As String = CreateNumber()\n Dim attempt As Integer = 0\n Console.WriteLine(\"Number is chosen\")\n Dim gameOver As Boolean = False\n Do\n attempt += 1\n Console.WriteLine(\"Attempt #{0}. Enter four digit number: \", attempt)\n Dim number As String = Console.ReadLine()\n Do While Not IsFourDigitNumber(number)\n Console.WriteLine(\"Invalid number: type four characters. Every character must digit be between '1' and '9'.\")\n number = Console.ReadLine()\n Loop\n\n Dim bulls As Integer = 0\n Dim cows As Integer = 0\n\n For i As Integer = 0 To number.Length - 1\n Dim j As Integer = chosenNumber.IndexOf(number(i))\n If i = j Then\n bulls += 1\n ElseIf j >= 0 Then\n cows += 1\n End If\n Next\n\n If bulls < chosenNumber.Length Then\n Console.WriteLine(\"The number '{0}' has {1} bulls and {2} cows\", _\n number, bulls, cows)\n Else\n gameOver = True\n End If\n Loop Until gameOver\n Console.WriteLine(\"The number was guessed in {0} attempts. Congratulations!\", attempt)\n End Sub\nEnd Module\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":624} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Module1\n\n Function DotProduct(a As Decimal(), b As Decimal()) As Decimal\n Return a.Zip(b, Function(x, y) x * y).Sum()\n End Function\n\n Sub Main()\n Console.WriteLine(DotProduct({1, 3, -5}, {4, -2, -1}))\n Console.ReadLine()\n End Sub\n\nEnd Module\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":625} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\nSub Consume(ByVal stream As IO.StreamReader)\n Dim line = stream.ReadLine\n Do Until line Is Nothing\n Console.WriteLine(line)\n line = stream.ReadLine\n Loop\nEnd Sub\n","human_summarization":"\"The code reads a text stream either word-by-word or line-by-line until there's no more data, then outputs each line to the screen.\"","id":626} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nImports System.Globalization\n\nModule Program\n Sub Main()\n Console.Write(\"Max: \")\n Dim max = Integer.Parse(Console.ReadLine(), CultureInfo.InvariantCulture)\n\n Dim factors As New SortedDictionary(Of Integer, String)\n\n Const NUM_FACTORS = 3\n For i = 1 To NUM_FACTORS\n Console.Write(\"Factor {0}: \", i)\n Dim input = Console.ReadLine().Split()\n factors.Add(Integer.Parse(input(0), CultureInfo.InvariantCulture), input(1))\n Next\n\n For i = 1 To max\n Dim anyMatches = False\n For Each factor In factors\n If i Mod factor.Key = 0 Then\n Console.Write(factor.Value)\n anyMatches = True\n End If\n Next\n If Not anyMatches Then Console.Write(i)\n Console.WriteLine()\n Next\n End Sub\nEnd Module\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":627} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nModule Guess_the_Number\n Sub Main()\n Dim random As New Random()\n Dim secretNum As Integer = random.Next(10) + 1\n Dim gameOver As Boolean = False\n Console.WriteLine(\"I am thinking of a number from 1 to 10. Can you guess it?\")\n Do\n Dim guessNum As Integer\n Console.Write(\"Enter your guess: \")\n\n If Not Integer.TryParse(Console.ReadLine(), guessNum) Then\n Console.WriteLine(\"You should enter a number from 1 to 10. Try again!\")\n Continue Do\n End If\n\n If guessNum = secretNum Then\n Console.WriteLine(\"Well guessed!\")\n gameOver = True\n Else\n Console.WriteLine(\"Incorrect. Try again!\")\n End If\n Loop Until gameOver\n End Sub\nEnd Module\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":628} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nWorks with: Visual Basic .NET version 9.0+\n\nModule LowerASCII\n\n Sub Main()\n Dim alphabets As New List(Of Char)\n For i As Integer = Asc(\"a\") To Asc(\"z\")\n alphabets.Add(Chr(i))\n Next\n Console.WriteLine(String.Join(\"\", alphabets.ToArray))\n End Sub\n\nEnd Module\n\n","human_summarization":"generates a sequence of all lower case ASCII characters from 'a' to 'z' using a reliable coding style suitable for large programs. It avoids manual enumeration of characters to prevent bugs. The Asc and Chr functions are used to convert characters to integers and vice versa. The String.Join() function is used to print the list without looping through it.","id":629} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nModule Program\n Sub Main\n For Each number In {5, 50, 9000}\n Console.WriteLine(Convert.ToString(number, 2))\n Next\n End Sub\nEnd Module\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":630} {"lang_cluster":"Visual_Basic_.NET","source_code":"Imports System.Math\n\nModule Module1\n\n Const deg2rad As Double = PI \/ 180\n\n Structure AP_Loc\n Public IATA_Code As String, Lat As Double, Lon As Double\n\n Public Sub New(ByVal iata_code As String, ByVal lat As Double, ByVal lon As Double)\n Me.IATA_Code = iata_code\u00a0: Me.Lat = lat * deg2rad\u00a0: Me.Lon = lon * deg2rad\n End Sub\n\n Public Overrides Function ToString() As String\n Return String.Format(\"{0}: ({1}, {2})\", IATA_Code, Lat \/ deg2rad, Lon \/ deg2rad)\n End Function\n End Structure\n\n Function Sin2(ByVal x As Double) As Double\n Return Pow(Sin(x \/ 2), 2)\n End Function\n\n Function calculate(ByVal one As AP_Loc, ByVal two As AP_Loc) As Double\n Dim R As Double = 6371, ' In kilometers, (as recommended by the International Union of Geodesy and Geophysics)\n a As Double = Sin2(two.Lat - one.Lat) + Sin2(two.Lon - one.Lon) * Cos(one.Lat) * Cos(two.Lat)\n Return R * 2 * Asin(Sqrt(a))\n End Function\n\n Sub ShowOne(pntA As AP_Loc, pntB as AP_Loc)\n Dim adst As Double = calculate(pntA, pntB), sfx As String = \"km\"\n If adst < 1000 Then adst *= 1000\u00a0: sfx = \"m\"\n Console.WriteLine(\"The approximate distance between airports {0} and {1} is {2:n2} {3}.\", pntA, pntB, adst, sfx)\n Console.WriteLine(\"The uncertainty is under 0.5%, or {0:n1} {1}.\" & vbLf, adst \/ 200, sfx)\n End Sub\n\n' Airport coordinate data excerpted from the data base at http:\/\/www.partow.net\/miscellaneous\/airportdatabase\/\n\n' The four additional airports are the furthest and closest pairs, according to the \"Fun Facts...\" section.\n\n' KBNA, BNA, NASHVILLE INTERNATIONAL, NASHVILLE, USA, 036, 007, 028, N, 086, 040, 041, W, 00183, 36.124, -86.678\n' KLAX, LAX, LOS ANGELES INTERNATIONAL, LOS ANGELES, USA, 033, 056, 033, N, 118, 024, 029, W, 00039, 33.942, -118.408\n' SKNV, NVA, BENITO SALAS, NEIVA, COLOMBIA, 002, 057, 000, N, 075, 017, 038, W, 00439, 2.950, -75.294\n' WIPP, PLM, SULTAN MAHMUD BADARUDDIN II, PALEMBANG, INDONESIA, 002, 053, 052, S, 104, 042, 004, E, 00012, -2.898, 104.701 \n' LOWL, LNZ, HORSCHING INTERNATIONAL AIRPORT (AUS - AFB), LINZ, AUSTRIA, 048, 014, 000, N, 014, 011, 000, E, 00096, 48.233, 14.183\n' LOXL, N\/A, LINZ, LINZ, AUSTRIA, 048, 013, 059, N, 014, 011, 015, E, 00299, 48.233, 14.188\n\n Sub Main()\n ShowOne(New AP_Loc(\"BNA\", 36.124, -86.678), New AP_Loc(\"LAX\", 33.942, -118.408))\n ShowOne(New AP_Loc(\"NVA\", 2.95, -75.294), New AP_Loc(\"PLM\", -2.898, 104.701))\n ShowOne(New AP_Loc(\"LNZ\", 48.233, 14.183), New AP_Loc(\"N\/A\", 48.233, 14.188))\n End Sub\nEnd Module\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":631} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nImports System.Net\n\nDim client As WebClient = New WebClient()\nDim content As String = client.DownloadString(\"http:\/\/www.google.com\")\nConsole.WriteLine(content)\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":632} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n Imports System.Linq\n Function ValidLuhn(value As String)\n Return value.Select(Function(c, i) (AscW(c) - 48) << ((value.Length - i - 1) And 1)).Sum(Function(n) If(n > 9, n - 9, n)) Mod 10 = 0\n End Function\n Sub Main()\n Console.WriteLine(ValidLuhn(\"49927398716\"))\n Console.WriteLine(ValidLuhn(\"49927398717\"))\n Console.WriteLine(ValidLuhn(\"1234567812345678\"))\n Console.WriteLine(ValidLuhn(\"1234567812345670\"))\n End Sub\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":633} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\nDebug.Print(Replace(Space(5), \" \", \"Ha\"))\n\n","human_summarization":"\"Implements functionality to repeat a given string or a single character a specified number of times.\"","id":634} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nImports System.Console\nModule Module1\n Sub Main\n Dim a = CInt(ReadLine)\n Dim b = CInt(ReadLine)\n WriteLine(\"Sum \" & a + b)\n WriteLine(\"Difference \" & a - b)\n WriteLine(\"Product \" & a - b)\n WriteLine(\"Quotient \" & a \/ b)\n WriteLine(\"Integer Quotient \" & a \\ b)\n WriteLine(\"Remainder \" & a Mod b)\n WriteLine(\"Exponent \" & a ^ b)\n End Sub\nEnd Module\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":635} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nModule Count_Occurrences_of_a_Substring\n Sub Main()\n Console.WriteLine(CountSubstring(\"the three truths\", \"th\"))\n Console.WriteLine(CountSubstring(\"ababababab\", \"abab\"))\n Console.WriteLine(CountSubstring(\"abaabba*bbaba*bbab\", \"a*b\"))\n Console.WriteLine(CountSubstring(\"abc\", \"\"))\n End Sub\n\n Function CountSubstring(str As String, substr As String) As Integer\n Dim count As Integer = 0\n If (Len(str) > 0) And (Len(substr) > 0) Then\n Dim p As Integer = InStr(str, substr)\n Do While p <> 0\n p = InStr(p + Len(substr), str, substr)\n count += 1\n Loop\n End If\n Return count\n End Function\nEnd Module\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":636} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nModule TowersOfHanoi\n Sub MoveTowerDisks(ByVal disks As Integer, ByVal fromTower As Integer, ByVal toTower As Integer, ByVal viaTower As Integer)\n If disks > 0 Then\n MoveTowerDisks(disks - 1, fromTower, viaTower, toTower)\n System.Console.WriteLine(\"Move disk {0} from {1} to {2}\", disks, fromTower, toTower)\n MoveTowerDisks(disks - 1, viaTower, toTower, fromTower)\n End If\n End Sub\n\n Sub Main()\n MoveTowerDisks(4, 1, 2, 3)\n End Sub\nEnd Module\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":637} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\nImports System.Drawing.Imaging\n\n Public Function Grayscale(ByVal Map As Bitmap) As Bitmap\n\n Dim oData() As Integer = GetData(Map)\n Dim oReturn As New Bitmap(Map.Width, Map.Height, Map.PixelFormat)\n Dim a As Integer = 0\n Dim r As Integer = 0\n Dim g As Integer = 0\n Dim b As Integer = 0\n Dim l As Integer = 0\n\n For i As Integer = 0 To oData.GetUpperBound(0)\n a = (oData(i) >> 24)\n r = (oData(i) >> 16) And 255\n g = (oData(i) >> 8) And 255\n b = oData(i) And 255\n\n l = CInt(r * 0.2126F + g * 0.7152F + b * 0.0722F)\n\n oData(i) = (a << 24) Or (l << 16) Or (l << 8) Or l\n Next\n\n SetData(oReturn, oData)\n\n Return oReturn\n\n End Function\n\n Private Function GetData(ByVal Map As Bitmap) As Integer()\n\n Dim oBMPData As BitmapData = Nothing\n Dim oData() As Integer = Nothing\n\n oBMPData = Map.LockBits(New Rectangle(0, 0, Map.Width, Map.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)\n\n Array.Resize(oData, Map.Width * Map.Height)\n\n Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0, oData, 0, oData.Length)\n\n Map.UnlockBits(oBMPData)\n\n Return oData\n\n End Function\n\n Private Sub SetData(ByVal Map As Bitmap, ByVal Data As Integer())\n\n Dim oBMPData As BitmapData = Nothing\n\n oBMPData = Map.LockBits(New Rectangle(0, 0, Map.Width, Map.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)\n\n Runtime.InteropServices.Marshal.Copy(Data, 0, oBMPData.Scan0, Data.Length)\n\n Map.UnlockBits(oBMPData)\n\n End Sub\n\n","human_summarization":"extend the data storage type to support grayscale images, convert a color image to a grayscale image and vice versa using the CIE recommended formula for luminance, and ensure no rounding errors cause run-time problems or distorted results when storing calculated luminance as an unsigned integer. The code also includes a function to convert a Bitmap to Grayscale.","id":638} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\n\nModule ByteLength\n Function GetByteLength(s As String, encoding As Text.Encoding) As Integer\n Return encoding.GetByteCount(s)\n End Function\nEnd Module\n\nModule CharacterLength\n Function GetUTF16CodeUnitsLength(s As String) As Integer\n Return s.Length\n End Function\n\n Private Function GetUTF16SurrogatePairCount(s As String) As Integer\n GetUTF16SurrogatePairCount = 0\n For i = 1 To s.Length - 1\n If Char.IsSurrogatePair(s(i - 1), s(i)) Then GetUTF16SurrogatePairCount += 1\n Next\n End Function\n\n Function GetCharacterLength_FromUTF16(s As String) As Integer\n Return GetUTF16CodeUnitsLength(s) - GetUTF16SurrogatePairCount(s)\n End Function\n\n Function GetCharacterLength_FromUTF32(s As String) As Integer\n Return GetByteLength(s, Text.Encoding.UTF32) \\ 4\n End Function\nEnd Module\n\nModule GraphemeLength\n ' Wraps an IEnumerator, allowing it to be used as an IEnumerable.\n Private Iterator Function AsEnumerable(enumerator As IEnumerator) As IEnumerable\n Do While enumerator.MoveNext()\n Yield enumerator.Current\n Loop\n End Function\n\n Function GraphemeCount(s As String) As Integer\n Dim elements = Globalization.StringInfo.GetTextElementEnumerator(s)\n Return AsEnumerable(elements).OfType(Of String).Count()\n End Function\nEnd Module\n\n#Const PRINT_TESTCASE = True\n\nModule Program\n ReadOnly TestCases As String() =\n {\n \"Hello, world!\",\n \"m\u00f8\u00f8se\",\n \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\", ' String normalization of the file makes the e and diacritic in \u00e9\u0332 one character, so use VB's char \"escapes\"\n $\"J{ChrW(&H332)}o{ChrW(&H332)}s{ChrW(&H332)}e{ChrW(&H301)}{ChrW(&H332)}\"\n }\n\n Sub Main()\n Const INDENT = \" \"\n Console.OutputEncoding = Text.Encoding.Unicode\n\n Dim writeResult = Sub(s As String, result As Integer) Console.WriteLine(\"{0}{1,-20}{2}\", INDENT, s, result)\n\n For i = 0 To TestCases.Length - 1\n Dim c = TestCases(i)\n\n Console.Write(\"Test case \" & i)\n#If PRINT_TESTCASE Then\n Console.WriteLine(\": \" & c)\n#Else\n Console.WriteLine()\n#End If\n writeResult(\"graphemes\", GraphemeCount(c))\n writeResult(\"UTF-16 units\", GetUTF16CodeUnitsLength(c))\n writeResult(\"Cd pts from UTF-16\", GetCharacterLength_FromUTF16(c))\n writeResult(\"Cd pts from UTF-32\", GetCharacterLength_FromUTF32(c))\n Console.WriteLine()\n writeResult(\"bytes (UTF-8)\", GetByteLength(c, Text.Encoding.UTF8))\n writeResult(\"bytes (UTF-16)\", GetByteLength(c, Text.Encoding.Unicode))\n writeResult(\"bytes (UTF-32)\", GetByteLength(c, Text.Encoding.UTF32))\n Console.WriteLine()\n Next\n\n End Sub\nEnd Module\n\n","human_summarization":"The code calculates the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. It correctly handles non-BMP code points and provides the actual character counts in code points, not in code unit counts. The code also provides the string length in graphemes if the language supports it. It uses .NET's System.Text.Encoding for encoding and decoding strings to byte arrays and System.Globalization.StringInfo for enumerating the text elements of a string. The byte length in UTF-16 is always twice the length of a string due to .NET strings using UTF-16.","id":639} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\nWorks with: .NET Framework version 4.7.2 (simple enough that it should probably work on every Framework version--.NET Core 3.0 will support Windows Forms on Windows only)\n\nLibrary: GDI+ (managed interface) [System.Drawing]\nLibrary: Windows Forms [System.Windows.Forms]\n\nImports System.Drawing\nImports System.Windows.Forms\n\nModule Program\n Sub Main()\n Dim bounds As Rectangle = Screen.PrimaryScreen.Bounds\n Console.WriteLine($\"Primary screen bounds: {bounds.Width}x{bounds.Height}\")\n\n Dim workingArea As Rectangle = Screen.PrimaryScreen.WorkingArea\n Console.WriteLine($\"Primary screen working area: {workingArea.Width}x{workingArea.Height}\")\n End Sub\nEnd Module\n\n\n","human_summarization":"The code determines the maximum height and width of a window that can fit within the physical display area of a screen without scrolling, considering window decorations and menubars. It also takes into account the conditions for multiple monitors and tiling window managers. The code uses Roslyn Visual Basic and references the screen's dimensions and working area, or alternatively, the dimensions of a borderless form with WindowState set to FormWindowState.Maximized.","id":640} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nModule Module1\n\n Sub Main()\n Console.Write(\"Goodbye, World!\")\n End Sub\n\nEnd Module\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":641} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Module1\n\n Function Encrypt(ch As Char, code As Integer) As Char\n If Not Char.IsLetter(ch) Then\n Return ch\n End If\n\n Dim offset = AscW(If(Char.IsUpper(ch), \"A\"c, \"a\"c))\n Dim test = (AscW(ch) + code - offset) Mod 26 + offset\n Return ChrW(test)\n End Function\n\n Function Encrypt(input As String, code As Integer) As String\n Return New String(input.Select(Function(ch) Encrypt(ch, code)).ToArray())\n End Function\n\n Function Decrypt(input As String, code As Integer) As String\n Return Encrypt(input, 26 - code)\n End Function\n\n Sub Main()\n Dim str = \"Pack my box with five dozen liquor jugs.\"\n\n Console.WriteLine(str)\n str = Encrypt(str, 5)\n Console.WriteLine(\"Encrypted: {0}\", str)\n str = Decrypt(str, 5)\n Console.WriteLine(\"Decrypted: {0}\", str)\n End Sub\n\nEnd Module\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":642} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nWorks with: Visual Basic .NET version 2005\nDim Value As String = \"+123\"\n\nIf IsNumeric(Value) Then\n PRINT \"It is numeric.\"\nEnd If\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":643} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nImports System.Net\n\nDim client As WebClient = New WebClient()\nDim content As String = client.DownloadString(\"https:\/\/sourceforge.net\")\nConsole.WriteLine(content)\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":644} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Module1\n\n Sub Main()\n Console.WriteLine(\"=== radians ===\")\n Console.WriteLine(\" sin (pi\/3) = {0}\", Math.Sin(Math.PI \/ 3))\n Console.WriteLine(\" cos (pi\/3) = {0}\", Math.Cos(Math.PI \/ 3))\n Console.WriteLine(\" tan (pi\/3) = {0}\", Math.Tan(Math.PI \/ 3))\n Console.WriteLine(\"arcsin (1\/2) = {0}\", Math.Asin(0.5))\n Console.WriteLine(\"arccos (1\/2) = {0}\", Math.Acos(0.5))\n Console.WriteLine(\"arctan (1\/2) = {0}\", Math.Atan(0.5))\n Console.WriteLine()\n Console.WriteLine(\"=== degrees ===\")\n Console.WriteLine(\" sin (60) = {0}\", Math.Sin(60 * Math.PI \/ 180))\n Console.WriteLine(\" cos (60) = {0}\", Math.Cos(60 * Math.PI \/ 180))\n Console.WriteLine(\" tan (60) = {0}\", Math.Tan(60 * Math.PI \/ 180))\n Console.WriteLine(\"arcsin (1\/2) = {0}\", Math.Asin(0.5) * 180 \/ Math.PI)\n Console.WriteLine(\"arccos (1\/2) = {0}\", Math.Acos(0.5) * 180 \/ Math.PI)\n Console.WriteLine(\"arctan (1\/2) = {0}\", Math.Atan(0.5) * 180 \/ Math.PI)\n End Sub\n\nEnd Module\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":645} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Module1\n Dim startTime As Date\n\n Sub Main()\n startTime = Date.Now\n ' Add event handler for Cntrl+C command\n AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress\n\n Dim counter = 0\n While True\n counter += 1\n Console.WriteLine(counter)\n Threading.Thread.Sleep(500)\n End While\n End Sub\n\n Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)\n Dim stopTime = Date.Now\n Console.WriteLine(\"This program ran for {0:000.000} seconds\", (stopTime - startTime).TotalMilliseconds \/ 1000)\n Environment.Exit(0)\n End Sub\n\nEnd Module\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.","id":646} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n Dim s As String = \"123\"\n\n s = CStr(CInt(\"123\") + 1)\n ' or\n s = (CInt(\"123\") + 1).ToString\n","human_summarization":"\"Increments a given numerical string.\"","id":647} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nFOR A = 1 TO 100\n IF A MOD 15 = 0 THEN\n PRINT \"FizzBuzz\"\n ELSE IF A MOD 3 = 0 THEN\n PRINT \"Fizz\"\n ELSE IF A MOD 5 = 0 THEN\n PRINT \"Buzz\"\n ELSE\n PRINT A\n END IF\nNEXT A","human_summarization":"print integers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":648} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Program\n Sub Main()\n Dim arg As Integer() = {1, 2, 3, 4, 5}\n Dim sum = arg.Sum()\n Dim prod = arg.Aggregate(Function(runningProduct, nextFactor) runningProduct * nextFactor)\n End Sub\nEnd Module\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":649} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Module1\n\n Sub Main()\n For p = 2 To 7 Step 2\n For s = 1 To 7\n Dim f = 12 - p - s\n If s >= f Then\n Exit For\n End If\n If f > 7 Then\n Continue For\n End If\n If s = p OrElse f = p Then\n Continue For 'not even necessary\n End If\n Console.WriteLine($\"Police:{p}, Sanitation:{s}, Fire:{f}\")\n Console.WriteLine($\"Police:{p}, Sanitation:{f}, Fire:{s}\")\n Next\n Next\n End Sub\n\nEnd Module\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":650} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\nWorks with: Visual Basic .NET version 9.0+\n'Immutable Strings\nDim a = \"Test string\"\nDim b = a 'reference to same string\nDim c = New String(a.ToCharArray) 'new string, normally not used\n\n'Mutable Strings\nDim x As New Text.StringBuilder(\"Test string\")\nDim y = x 'reference\nDim z = New Text.StringBuilder(x.ToString) 'new string\n\nDim a As String = \"Test String\"\nDim b As String = String.Copy(a) ' New string\n","human_summarization":"implement the functionality of copying a string's content and creating an additional reference to an existing string in the .NET framework.","id":651} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Program\n Sub Main()\n Dim list As New List(Of Integer)({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})\n Dim rng As New Random()\n Dim randomElement = list(rng.Next(list.Count)) ' Upper bound is exclusive.\n Console.WriteLine(\"I picked element {0}\", randomElement)\n End Sub\nEnd Module\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":652} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\nSub Main(ByVal args As String())\n For Each token In args\n Console.WriteLine(token)\n Next\nEnd Sub\n","human_summarization":"The code retrieves and prints the list of command-line arguments given to the program. It tokenizes the command line arguments, normally delimited by spaces, but also considers spaces within quotes as part of a token. It provides an example command line with arguments. Additionally, it includes functionality for intelligent parsing of these arguments.","id":653} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Module1\n\n Iterator Function Leonardo(Optional L0 = 1, Optional L1 = 1, Optional add = 1) As IEnumerable(Of Integer)\n While True\n Yield L0\n Dim t = L0 + L1 + add\n L0 = L1\n L1 = t\n End While\n End Function\n\n Sub Main()\n Console.WriteLine(String.Join(\" \", Leonardo().Take(25)))\n Console.WriteLine(String.Join(\" \", Leonardo(0, 1, 0).Take(25)))\n End Sub\n\nEnd Module\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":654} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n\nWorks with: Visual Basic .NET version 9.0+\ns = \"Hello\"\nConsole.WriteLine(s & \" literal\")\ns1 = s + \" literal\"\nConsole.WriteLine(s1)\n","human_summarization":"Creates two string variables, concatenates the second string with the first one, and displays the content of the variables in .NET platform.","id":655} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nImports System.IO\nImports System.Collections.ObjectModel\n\nModule Module1\n\n Dim sWords As New Dictionary(Of String, Collection(Of String))\n\n Sub Main()\n\n Dim oStream As StreamReader = Nothing\n Dim sLines() As String = Nothing\n Dim sSorted As String = Nothing\n Dim iHighCount As Integer = 0\n Dim iMaxKeyLength As Integer = 0\n Dim sOutput As String = \"\"\n\n oStream = New StreamReader(\"unixdict.txt\")\n sLines = oStream.ReadToEnd.Split(New String() {vbCrLf}, StringSplitOptions.RemoveEmptyEntries)\n oStream.Close()\n\n For i As Integer = 0 To sLines.GetUpperBound(0)\n sSorted = SortCharacters(sLines(i))\n\n If Not sWords.ContainsKey(sSorted) Then sWords.Add(sSorted, New Collection(Of String))\n\n sWords(sSorted).Add(sLines(i))\n\n If sWords(sSorted).Count > iHighCount Then\n iHighCount = sWords(sSorted).Count\n\n If sSorted.Length > iMaxKeyLength Then iMaxKeyLength = sSorted.Length\n End If\n Next\n\n For Each sKey As String In sWords.Keys\n If sWords(sKey).Count = iHighCount Then\n sOutput &= \"[\" & sKey.ToUpper & \"]\" & Space(iMaxKeyLength - sKey.Length + 1) & String.Join(\", \", sWords(sKey).ToArray()) & vbCrLf\n End If\n Next\n\n Console.WriteLine(sOutput)\n Console.ReadKey()\n\n End Sub\n\n Private Function SortCharacters(ByVal s As String) As String\n\n Dim sReturn() As Char = s.ToCharArray()\n Dim sTemp As Char = Nothing\n\n For i As Integer = 0 To sReturn.GetUpperBound(0) - 1\n If (sReturn(i + 1)) < (sReturn(i)) Then\n sTemp = sReturn(i)\n sReturn(i) = sReturn(i + 1)\n sReturn(i + 1) = sTemp\n i = -1\n End If\n Next\n\n Return CStr(sReturn)\n\n End Function\n\nEnd Module\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":656} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nImports System\nImports System.Numerics\n\t\t\t\t\nPublic Module Module1\n\tPublic Sub Main()\n Dim two, three, four, seven, ten, k, q, t, l, n, r, nn, nr As BigInteger,\n first As Boolean = True\n two = New BigInteger(2) : three = New BigInteger(3) : four = two + two\n seven = three + four : ten = three + seven : k = BigInteger.One\n q = k : t = k : l = three : n = three : r = BigInteger.Zero\n While True\n If four * q + r - t < n * t Then\n Console.Write(n) : If first Then Console.Write(\".\") : first = False\n nr = ten * (r - n * t) : n = ten * (three * q + r) \/ t - ten * n\n q *= ten\n Else\n nr = (two * q + r) * l : nn = (q * seven * k + two + r * l) \/ (t * l)\n q *= k : t *= l : l += two : k += BigInteger.One : n = nn\n End If\n r = nr\n End While\n End Sub\n\nEnd Module\n\n\n","human_summarization":"The code continually calculates and outputs the next decimal digit of Pi, starting from 3.14159265. It uses the System.Numerics library and an algorithm that may produce results faster but is not fully proven. The process continues indefinitely until manually stopped by the user.","id":657} {"lang_cluster":"Visual_Basic_.NET","source_code":"'N-queens problem - non recursive & structured - vb.net - 26\/02\/2017\nModule Mod_n_queens\n Sub n_queens()\n Const l = 15 'number of queens\n Const b = False 'print option\n Dim a(l), s(l), u(4 * l - 2)\n Dim n, m, i, j, p, q, r, k, t, z\n Dim w As String\n For i = 1 To UBound(a)\u00a0: a(i) = i\u00a0: Next i\n For n = 1 To l\n m = 0\n i = 1\n j = 0\n r = 2 * n - 1\n Do\n i = i - 1\n j = j + 1\n p = 0\n q = -r\n Do\n i = i + 1\n u(p) = 1\n u(q + r) = 1\n z = a(j)\u00a0: a(j) = a(i)\u00a0: a(i) = z 'Swap a(i), a(j)\n p = i - a(i) + n\n q = i + a(i) - 1\n s(i) = j\n j = i + 1\n Loop Until j > n Or u(p) Or u(q + r)\n If u(p) = 0 Then\n If u(q + r) = 0 Then\n m = m + 1 'm: number of solutions\n If b Then\n Debug.Print(\"n=\" & n & \" m=\" & m)\u00a0: w = \"\"\n For k = 1 To n\n For t = 1 To n\n w = w & If(a(n - k + 1) = t, \"Q\", \".\")\n Next t\n Debug.Print(w)\n Next k\n End If\n End If\n End If\n j = s(i)\n Do While j >= n And i <> 0\n Do\n z = a(j)\u00a0: a(j) = a(i)\u00a0: a(i) = z 'Swap a(i), a(j)\n j = j - 1\n Loop Until j < i\n i = i - 1\n p = i - a(i) + n\n q = i + a(i) - 1\n j = s(i)\n u(p) = 0\n u(q + r) = 0\n Loop\n Loop Until i = 0\n Debug.Print(n & vbTab & m) 'number of queens, number of solutions\n Next n\n End Sub 'n_queens\nEnd Module\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":658} {"lang_cluster":"Visual_Basic_.NET","source_code":"\n Dim iArray1() As Integer = {1, 2, 3}\n Dim iArray2() As Integer = {4, 5, 6}\n Dim iArray3() As Integer = Nothing\n\n iArray3 = iArray1.Concat(iArray2).ToArray\n","human_summarization":"demonstrate how to concatenate two arrays.","id":659} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nWorks with: Visual Basic .NET version 2013\n'Knapsack problem\/0-1 - 12\/02\/2017\nPublic Class KnapsackBin\n Const knam = 0, kwei = 1, kval = 2\n Const maxWeight = 400\n Dim xList(,) As Object = { _\n {\"map\", 9, 150}, _\n {\"compass\", 13, 35}, _\n {\"water\", 153, 200}, _\n {\"sandwich\", 50, 160}, _\n {\"glucose\", 15, 60}, _\n {\"tin\", 68, 45}, _\n {\"banana\", 27, 60}, _\n {\"ChoiceBinle\", 39, 40}, _\n {\"cheese\", 23, 30}, _\n {\"beer\", 52, 10}, _\n {\"suntan cream\", 11, 70}, _\n {\"camera\", 32, 30}, _\n {\"T-shirt\", 24, 15}, _\n {\"trousers\", 48, 10}, _\n {\"umbrella\", 73, 40}, _\n {\"waterproof trousers\", 42, 70}, _\n {\"waterproof overclothes\", 43, 75}, _\n {\"note-case\", 22, 80}, _\n {\"sunglasses\", 7, 20}, _\n {\"towel\", 18, 12}, _\n {\"socks\", 4, 50}, _\n {\"book\", 30, 10}}\n Dim s, xss As String, xwei, xval, nn As Integer\n\n Private Sub KnapsackBin_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n Dim i As Integer\n xListView.View = View.Details\n xListView.Columns.Add(\"item\", 120, HorizontalAlignment.Left)\n xListView.Columns.Add(\"weight\", 50, HorizontalAlignment.Right)\n xListView.Columns.Add(\"value\", 50, HorizontalAlignment.Right)\n For i = 0 To UBound(xList, 1)\n xListView.Items.Add(New ListViewItem(New String() {xList(i, 0), _\n xList(i, 1).ToString, xList(i, 2).ToString}))\n Next i\n End Sub 'KnapsackBin_Load\n\n Private Sub cmdOK_Click(sender As Object, e As EventArgs) Handles cmdOK.Click\n Dim i, j, nItems As Integer\n For i = xListView.Items.Count - 1 To 0 Step -1\n xListView.Items.RemoveAt(i)\n Next i\n Me.Refresh()\n nItems = UBound(xList, 1) + 1\n s = \"\"\n For i = 1 To nItems\n s = s & Chr(i - 1)\n Next\n nn = 0\n Call ChoiceBin(1, \"\")\n For i = 1 To Len(xss)\n j = Asc(Mid(xss, i, 1))\n xListView.Items.Add(New ListViewItem(New String() {xList(j, 0), _\n xList(j, 1).ToString, xList(j, 2).ToString}))\n Next i\n xListView.Items.Add(New ListViewItem(New String() {\"*Total*\", xwei, xval}))\n End Sub 'cmdOK_Click\n\n Private Sub ChoiceBin(n As String, ss As String)\n Dim r As String, i, j, iwei, ival As Integer\n Dim ipct As Integer\n If n = Len(s) + 1 Then\n iwei = 0\u00a0: ival = 0\n For i = 1 To Len(ss)\n j = Asc(Mid(ss, i, 1))\n iwei = iwei + xList(j, 1)\n ival = ival + xList(j, 2)\n Next\n If iwei <= maxWeight And ival > xval Then\n xss = ss\u00a0: xwei = iwei\u00a0: xval = ival\n End If\n Else\n r = Mid(s, n, 1)\n Call ChoiceBin(n + 1, ss & r)\n Call ChoiceBin(n + 1, ss)\n End If\n End Sub 'ChoiceBin\n\nEnd Class 'KnapsackBin\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":660} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Module1\n\n Function A(v As Boolean) As Boolean\n Console.WriteLine(\"a\")\n Return v\n End Function\n\n Function B(v As Boolean) As Boolean\n Console.WriteLine(\"b\")\n Return v\n End Function\n\n Sub Test(i As Boolean, j As Boolean)\n Console.WriteLine(\"{0} and {1} = {2} (eager evaluation)\", i, j, A(i) And B(j))\n Console.WriteLine(\"{0} or {1} = {2} (eager evaluation)\", i, j, A(i) Or B(j))\n Console.WriteLine(\"{0} and {1} = {2} (lazy evaluation)\", i, j, A(i) AndAlso B(j))\n Console.WriteLine(\"{0} or {1} = {2} (lazy evaluation)\", i, j, A(i) OrElse B(j))\n\n Console.WriteLine()\n End Sub\n\n Sub Main()\n Test(False, False)\n Test(False, True)\n Test(True, False)\n Test(True, True)\n End Sub\n\nEnd Module\n\n\n","human_summarization":"create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.","id":661} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Module1\n\n Sub Main()\n Dim word = \"sos\"\n Dim codes As New Dictionary(Of String, String) From {\n {\"a\", \".- \"}, {\"b\", \"-... \"}, {\"c\", \"-.-. \"}, {\"d\", \"-.. \"},\n {\"e\", \". \"}, {\"f\", \"..-. \"}, {\"g\", \"--. \"}, {\"h\", \".... \"},\n {\"i\", \".. \"}, {\"j\", \".--- \"}, {\"k\", \"-.- \"}, {\"l\", \".-.. \"},\n {\"m\", \"-- \"}, {\"n\", \"-. \"}, {\"o\", \"--- \"}, {\"p\", \".--. \"},\n {\"q\", \"--.- \"}, {\"r\", \".-. \"}, {\"s\", \"... \"}, {\"t\", \"- \"},\n {\"u\", \"..- \"}, {\"v\", \"...- \"}, {\"w\", \".-- \"}, {\"x\", \"-..- \"},\n {\"y\", \"-.-- \"}, {\"z\", \"--.. \"}, {\"0\", \"-----\"}, {\"1\", \".----\"},\n {\"2\", \"..---\"}, {\"3\", \"...--\"}, {\"4\", \"....-\"}, {\"5\", \".....\"},\n {\"6\", \"-....\"}, {\"7\", \"--...\"}, {\"8\", \"---..\"}, {\"9\", \"----.\"}\n }\n\n For Each c In word.ToCharArray\n Dim rslt = codes(c).Trim\n For Each c2 In rslt.ToCharArray\n If c2 = \".\" Then\n Console.Beep(1000, 250)\n Else\n Console.Beep(1000, 750)\n End If\n System.Threading.Thread.Sleep(50)\n Next\n Next\n End Sub\n\nEnd Module\n\n","human_summarization":" convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":662} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nWorks with: Visual Basic .NET version 9.0+\nImports System.Security.Cryptography\nImports System.Text\n\nModule MD5hash\n Sub Main(args As String())\n Console.WriteLine(GetMD5(\"Visual Basic .Net\"))\n End Sub\n\n Private Function GetMD5(plainText As String) As String\n Dim hash As String = \"\"\n\n Using hashObject As MD5 = MD5.Create()\n Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))\n Dim hashBuilder As New StringBuilder\n\n For i As Integer = 0 To ptBytes.Length - 1\n hashBuilder.Append(ptBytes(i).ToString(\"X2\"))\n Next\n hash = hashBuilder.ToString\n End Using\n\n Return hash\n End Function\n\nEnd Module\n\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":663} {"lang_cluster":"Visual_Basic_.NET","source_code":"\nImports System\nImports System.IO\nImports System.Net.Sockets\n\nPublic Class Program \n Public Shared Sub Main(ByVal args As String[])\n Dim tcp As New TcpClient(\"localhost\", 256)\n Dim writer As New StreamWriter(tcp.GetStream())\n\n writer.Write(\"hello socket world\")\n writer.Flush()\n\n tcp.Close()\n End Sub\nEnd Class\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":664} {"lang_cluster":"Visual_Basic_.NET","source_code":"Module Module1\n\n Function IsPalindrome(p As String) As Boolean\n Dim temp = p.ToLower().Replace(\" \", \"\")\n Return StrReverse(temp) = temp\n End Function\n\n Sub Main()\n Console.WriteLine(IsPalindrome(\"In girum imus nocte et consumimur igni\"))\n End Sub\n\nEnd Module\n\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":665} {"lang_cluster":"ColdFusion","source_code":"\n\n\t\n\t\n\t\n\n\t\n\t#mid( str, n, m )#\n\t\n\t\n\t#right( str, countFromRight )#\n\t\n\t\n\t#left( str, allButLast )#\n\t\n\t\n\t#mid( str, startingIndex, m )#\n\t\n\t\n\t#mid( str, startingIndexSubString, m )#\n\n<\/cfoutput>\n\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":666} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n\n","human_summarization":"The code reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" into \"fdsa\" and \"as\u20dddf\u0305\" into \"f\u0305ds\u20dda\". It can also reverse any text that can be written to the document in hashmarks such as strings, numbers, and time functions.","id":667} {"lang_cluster":"ColdFusion","source_code":"\n\n\n \n #randNum#<\/Cfoutput>\n <\/Cfif>\n #RandRange(0, 19)#<\/Cfoutput>\n
\n<\/cfloop>\n\n\n","human_summarization":"Generates and prints random numbers from 0 to 19. If the generated number is 10, the loop stops. If not, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop continues indefinitely.","id":668} {"lang_cluster":"ColdFusion","source_code":"\n\n\n<\/cfsavecontent>\n\n\n\n\n\n\n\n\n\n #priceSearch[i].xmlText#\n<\/cfloop>\n\n\n\n\n\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":669} {"lang_cluster":"ColdFusion","source_code":"\n\n \n \n December 25th falls on a Sunday in #i#<\/cfoutput>
\n <\/cfif>\n<\/cfloop>\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":670} {"lang_cluster":"ColdFusion","source_code":"\n\n #dateFormat(Now(), \"YYYY-MM-DD\")#
\n #dateFormat(Now(), \"DDDD, MMMM DD, YYYY\")#\n<\/cfoutput>\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":671} {"lang_cluster":"ColdFusion","source_code":"\n\npublic array function powerset(required array data)\n{\n var ps = [\"\"];\n var d = arguments.data;\n var lenData = arrayLen(d);\n var lenPS = 0;\n for (var i=1; i LTE lenData; i++)\n {\n lenPS = arrayLen(ps);\n for (var j = 1; j LTE lenPS; j++)\n {\n arrayAppend(ps, listAppend(ps[j], d[i]));\n }\n }\n return ps;\n}\n\nvar res = powerset([1,2,3,4]);\n\n\n","human_summarization":"The code takes a set S as input and generates its power set. The power set includes all subsets of S, even the empty set. The code also demonstrates the ability to handle edge cases, such as the power set of an empty set and the power set of a set containing only the empty set. The code is a port from a JavaScript version and is compatible with ColdFusion 8+ or Railo 3+.","id":672} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n\n\n arr2 = ArrayNew(2);\n<\/cfscript>\n\n\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. They show how to create both fixed-length and dynamic arrays, assign values to them, and retrieve elements. The codes also illustrate the creation of one-dimensional and two-dimensional arrays, specifically in CFScript where arrays start at index 1, not 0. The codes also incorporate elements from obsolete tasks related to array creation, value assignment, and element retrieval.","id":673} {"lang_cluster":"ColdFusion","source_code":"\n\n \n \n<\/cfif>\n\n","human_summarization":"demonstrate reading the contents of \"input.txt\" file into a variable and then writing this variable's contents into a new file called \"output.txt\".","id":674} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n\n\n\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default encoding or ASCII. The codes also showcase additional case conversion functions such as swapping case or capitalizing the first letter. The conversion is performed on both string literals and variable values.","id":675} {"lang_cluster":"ColdFusion","source_code":"\n\n\n #i#\n \n \n <\/cfif>\n , \n<\/cfloop>\n\n\n\n for( i = 1; i <= 10; i++ ) \/\/note: the ++ notation works only on version 8 up, otherwise use i=i+1\n {\n writeOutput( i );\n \n if( i == 10 )\n {\n break;\n }\n writeOutput( \", \" );\n }\n<\/cfscript>\n\n","human_summarization":"generate a comma-separated list from 1 to 10, using separate output statements for the numbers and the commas in a loop. The last iteration only outputs the number, not the comma.","id":676} {"lang_cluster":"ColdFusion","source_code":"\n\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server.","id":677} {"lang_cluster":"ColdFusion","source_code":"\n\n\n \n *\n <\/cfloop>\n < br \/>\n<\/cfloop>\n\n\n\n for( i = 1; i <= 5; i++ )\n {\n for( j = 1; j <= i; j++ )\n {\n writeOutput( \"*\" );\n }\n writeOutput( \"< br \/>\" );\n }\n<\/cfscript>\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations of the inner loop is controlled by the outer loop. The pattern printed consists of increasing numbers of asterisks on each line.","id":678} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n\n\n\n","human_summarization":"Create an associative array, dictionary, map, or hash in ColdFusion using java.util.HashMap.","id":679} {"lang_cluster":"ColdFusion","source_code":"\n\n\n \n\t\n \n<\/cffunction>\n\n\n \n\t\n \n<\/cffunction>\n\n\n \n\t\n \n<\/cffunction>\n\n\n \n \n \n \n \n \n \n <\/cfif>\n \n \n <\/cfloop>\n \n<\/cffunction>\n\n\n#ethiopian(17,34)#<\/cfoutput>\nVersion with display pizza:\n\n\n\n\n \n\t\n \n<\/cffunction>\n\n\n \n\t\n \n<\/cffunction>\n\n\n \n\t\n \n<\/cffunction>\n\n\n\n\nEthiopian multiplication of #Number_A# and #Number_B#...\n
\n\n\n\n\n\n\n\n \n \t\n \n \n\t\n <\/cfif>\n\n \n
#Number_A#<\/td>\n #Number_B#<\/td>\n #Action#<\/td>\n <\/tr>\n \n \n \n \n<\/cfloop> \n \n<\/table>\n\n...equals #Result#\n\n<\/cfoutput>\n\nSample output:Ethiopian multiplication of 17 and 34...\n17 \t34 \tKeep\n8 \t68 \tStrike\n4 \t136 \tStrike\n2 \t272 \tStrike\n1 \t544 \tKeep\n...equals 578 \n\n","human_summarization":"The code defines three functions to perform Ethiopian multiplication. The first function halves an integer, the second function doubles an integer, and the third function checks if an integer is even. These functions are then used to create a fourth function that performs Ethiopian multiplication by repeatedly halving the first number, doubling the second number, discarding rows where the first number is even, and summing the remaining values in the second column.","id":680} {"lang_cluster":"ColdFusion","source_code":"\n\n \/\/ Date Time\n currentTime = Now();\n writeOutput( currentTime );\n\n \/\/ Epoch\n \/\/ Credit for Epoch time should go to Ben Nadel\n \/\/ bennadel.com is his blog\n utcDate = dateConvert( \"local2utc\", currentTime );\n writeOutput( utcDate.getTime() );\n<\/cfscript>\n\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":681} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n \n<\/Cfloop>\n#theString#<\/Cfoutput>\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":682} {"lang_cluster":"ColdFusion","source_code":"\n\n\t\n\t#\"Hello \" & who#\n<\/cfoutput>\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":683} {"lang_cluster":"ColdFusion","source_code":"\n \n #result.FileContent#<\/cfoutput>\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":684} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n#word#<\/Cfloop>\n<\/Cfoutput>\n\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":685} {"lang_cluster":"ColdFusion","source_code":"\n\n value = 0;\n do\n {\n value += 1;\n writeOutput( value );\n } while( value % 6 != 0 );\t\t\t\n<\/cfscript>\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":686} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n\n

#arrayLen(t)#<\/p>\n<\/cfoutput>\n\n#len(\"Hello World\")#\n\n","human_summarization":"calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.","id":687} {"lang_cluster":"ColdFusion","source_code":"\n\n #i#!<\/Cfoutput>\n<\/Cfloop>\n\n","human_summarization":"Iterates through each element in a collection in order and prints it, using a \"for each\" loop or another loop if \"for each\" is not available in the language.","id":688} {"lang_cluster":"ColdFusion","source_code":"\n\n \n #Replace( wordListTag, \",\", \".\", \"all\" )#\n<\/cfoutput>\n\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":689} {"lang_cluster":"ColdFusion","source_code":"\n\n\n TestValue: #TestValue#<\/cfoutput>
\n\n is Numeric.\n\n is NOT Numeric.\n<\/cfif>\n\n\n TestValue: #TestValue#<\/cfoutput>
\n\n is Numeric.\n\n is NOT Numeric.\n<\/cfif>\n\n#isNumeric(42)#<\/cfoutput>\n\n","human_summarization":"Implement a boolean function to check if a given string is a numeric string, including floating point and negative numbers, in the syntax used by Adobe's ColdFusion for numeric literals or numbers converted from strings.","id":690} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n\n","human_summarization":"The code establishes a SOAP client to access and call the functions soapFunc() and anotherSoapFunc() from the WSDL located at http:\/\/example.com\/soap\/wsdl. Note, the task and corresponding code may require further clarification.","id":691} {"lang_cluster":"ColdFusion","source_code":"\n\n FizzBuzz\n Fizz\n Buzz\n #i# <\/Cfoutput>\n <\/Cfif> \n<\/Cfloop>\n\n\n\nresult = \"\";\n for(i=1;i<=100;i++){\n result=ListAppend(result, (i%15==0) ? \"FizzBuzz\": (i%5==0) ? \"Buzz\" : (i%3 eq 0)? \"Fizz\" : i );\n }\n WriteOutput(result);\n<\/cfscript>\n\n","human_summarization":"The code prints integers from 1 to 100. It replaces multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":692} {"lang_cluster":"ColdFusion","source_code":"\n\n\n#ArraySum(Variables.myArray)#<\/cfoutput>\n\n\n\n\n\n \n<\/cfloop>\n#Variables.Product#<\/cfoutput>\n\n","human_summarization":"\"Calculates the sum and product of all integers in an array.\"","id":693} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n","human_summarization":"implement the functionality of copying a string in ColdFusion. It differentiates between copying the contents of a string and making an additional reference to an existing string. Since only complex data types are passed by reference in ColdFusion, all string copy operations are performed by value.","id":694} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n\n\n\n\n\n\n\n\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":695} {"lang_cluster":"ColdFusion","source_code":"\n\n\n #i#\n<\/cfloop>\n\n\n\n for( i = 10; i <= 0; i-- )\n {\n writeOutput( i );\n }\n<\/cfscript>\n\n","human_summarization":"implement a countdown from 10 to 0 using a for loop.","id":696} {"lang_cluster":"ColdFusion","source_code":"\n\n #i#<\/Cfoutput>\n<\/cfloop>\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":697} {"lang_cluster":"ColdFusion","source_code":"\nPERSON.CFC\n\ncomponent displayName=\"Person\" accessors=\"true\" {\n property name=\"Name\" type=\"string\";\n property name=\"MrOrMrsGoodEnough\" type=\"Person\";\n property name=\"UnrealisticExpectations\" type=\"array\";\n property name=\"PersonalHistory\" type=\"array\";\n\n public Person function init( required String name ) {\n setName( arguments.name );\n setPersonalHistory([ getName() & \" is on the market.\" ]);\n this.HotnessScale = 0;\n return this;\n }\n\n public Boolean function hasSettled() {\n \/\/ if we have settled, return true;\n return isInstanceOf( getMrOrMrsGoodEnough(), \"Person\" );\n }\n\n public Person function getBestOfWhatIsLeft() {\n \/\/ increment the hotness scale...1 is best, 10 is...well...VERY settling.\n this.HotnessScale++;\n \/\/ get the match from the current rung in the barrel\n var bestChoice = getUnrealisticExpectations()[ this.HotnessScale ];\n return bestChoice;\n }\n\n public Boolean function wouldRatherBeWith( required Person person ) {\n \/\/ only compare if we've already settled on a potential mate\n if( isInstanceOf( this.getMrOrMrsGoodEnough(), \"Person\" ) ) {\n \/\/ if the new person's hotness is greater (numerically smaller) than our current beau...\n return getHotness( this, arguments.person ) < getHotness( this, this.getMrOrMrsGoodEnough() );\n }\n return false; \n }\n\n public Void function settle( required Person person ) {\n if( person.hasSettled() ) {\n \/\/ this is the match we want. Force a break up of a previous relationship (sorry!)\n dumpLikeATonOfBricks( person );\n }\n person.setMrOrMrsGoodEnough( this );\n if( hasSettled() ) {\n \/\/ this is the match we want, so write a dear john to our current match\n dumpLikeATonOfBricks( this );\n }\n logHookup( arguments.person );\n \/\/ we've found the mate of our dreams!\n setMrOrMrsGoodEnough( arguments.person );\n }\n\n public Void function swing( required Person person ) {\n \/\/ get our spouses\n var mySpouse = getMrOrMrsGoodEnough();\n var notMySpouse = arguments.person.getMrOrMrsGoodEnough();\n \/\/ swap em'\n setMrOrMrsGoodEnough( notMySpouse );\n person.setMrOrMrsGoodEnough( mySpouse );\n }\n\n public Void function dumpLikeATonOfBricks( required Person person ) {\n logBreakup( arguments.person );\n person.getMrOrMrsGoodEnough().setMrOrMrsGoodEnough( JavaCast( \"null\", \"\" ) );\n }\n\n public String function psychoAnalyze() {\n logNuptuals();\n logRegrets();\n var personalJourney = \"\";\n for( var entry in getPersonalHistory() ) {\n personalJourney = personalJourney & entry & \"
\";\n }\n return personalJourney;\n }\n\n private Numeric function getHotness( required Person pursuer, required Person pursued ) {\n var pursuersExpectations = pursuer.getUnrealisticExpectations();\n var hotnessFactor = 1;\n for( var hotnessFactor=1; hotnessFactor<=arrayLen( pursuersExpectations ); hotnessFactor++ ) {\n if( pursuersExpectations[ hotnessFactor ].getName()==arguments.pursued.getName() ) {\n return hotnessFactor;\n }\n }\n }\n\n private Void function logRegrets() {\n var spouse = getMrOrMrsGoodEnough();\n var spouseHotness = getHotness( this, spouse );\n var myHotness = getHotness( spouse, this );\n if( spouseHotness == 1 && myHotness == 1 ) {\n arrayAppend( getPersonalHistory(), \"Yes, yes, the beautiful people always find happy endings: #getName()# (her ###myHotness#), #spouse.getName()# (his ###spouseHotness#)\");\n }\n else if( spouseHotness == myHotness ) {\n arrayAppend( getPersonalHistory(), \"#getName()# (her ###myHotness#) was made for #spouse.getName()# (his ###spouseHotness#). How precious.\");\n }\n else if( spouseHotness > myHotness ) {\n arrayAppend( getPersonalHistory(), \"#getName()# (her ###myHotness#) could have done better than #spouse.getName()# (his ###spouseHotness#). Poor slob.\");\n }\n else {\n arrayAppend( getPersonalHistory(), \"#getName()# (her ###myHotness#) is a lucky bastard to have landed #spouse.getName()# (his ###spouseHotness#).\");\n }\n }\n\n private Void function logNuptuals() {\n arrayAppend( getPersonalHistory(), \"#getName()# has settled for #getMrOrMrsGoodEnough().getName()#.\" );\n }\n\n private Void function logHookup( required Person person ) {\n var winnerHotness = getHotness( this, arguments.person );\n var myHotness = getHotness( arguments.person, this );\n arrayAppend( getPersonalHistory(), \"#getName()# (her ###myHotness#) is checking out #arguments.person.getName()# (his ###winnerHotness#), but wants to keep his options open.\");\n }\n\n private Void function logBreakup( required Person person ) {\n var scrub = person.getMrOrMrsGoodEnough();\n var scrubHotness = getHotness( person, scrub );\n var myHotness = getHotness( person, this );\n arrayAppend( getPersonalHistory(), \"#getName()# is so hot (her ###myHotness#) that #person.getName()# is dumping #scrub.getName()# (her ###scrubHotness#)\");\n }\n}\n\nINDEX.CFM\n\n\n \/**\n * Let's get these crazy kids married!\n * @men.hint The men who want to get married\n *\/\n function doCreepyMassMarriages( required Array men ) {\n marriagesAreStable = false;\n while( !marriagesAreStable ) {\n marriagesAreStable = true;\n for( man in men ) {\n if( !man.hasSettled() ) {\n marriagesAreStable = false;\n sexyLady = man.getBestOfWhatIsLeft();\n if( !sexyLady.hasSettled() || sexyLady.wouldRatherBeWith( man ) ) {\n man.settle( sexyLady );\n }\n }\n }\n }\n return men;\n }\n\n \/**\n * We played God...now let's see if society is going to survive\n * @men.hint The married men\n * @women.hint The married women\n *\/\n function isSocietyStable( required Array men, required Array women ) {\n \/\/ loop over married men\n for( var man in arguments.men ) {\n \/\/ loop over married women\n for( var woman in arguments.women ) {\n \/\/ if the man does not prefer this woman to his current spouse, and the women\n \/\/ doesn't prefer the man to her current spouse, this is the best possible match\n if( man.wouldRatherBeWith( woman ) && woman.wouldRatherBeWith( man ) ) {\n return false;\n }\n }\n }\n return true;\n }\n\n \/\/ the men\n abe = new Person( \"Abe\" );\n bob = new Person( \"Bob\" );\n col = new Person( \"Col\" );\n dan = new Person( \"Dan\" );\n ed = new Person( \"Ed\" );\n fred = new Person( \"Fred\" );\n gav = new Person( \"Gav\" );\n hal = new Person( \"Hal\" );\n ian = new Person( \"Ian\" );\n jon = new Person( \"Jon\" );\n\n men = [ abe, bob, col, dan, ed, fred, gav, hal, ian, jon ];\n\n \/\/ the women\n abi = new Person( \"Abi\" );\n bea = new Person( \"Bea\" );\n cath = new Person( \"Cath\" );\n dee = new Person( \"Dee\" );\n eve = new Person( \"Eve\" );\n fay = new Person( \"Fay\" );\n gay = new Person( \"Gay\" );\n hope = new Person( \"Hope\" );\n ivy = new Person( \"Ivy\" );\n jan = new Person( \"Jan\" );\n\n women = [ abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan ];\n\n \/\/ set unrealistic expectations for the men\n abe.setUnrealisticExpectations([ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay ]);\n bob.setUnrealisticExpectations([ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay ]);\n col.setUnrealisticExpectations([ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan ]);\n dan.setUnrealisticExpectations([ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ]);\n ed.setUnrealisticExpectations([ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay ]);\n fred.setUnrealisticExpectations([ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay ]);\n gav.setUnrealisticExpectations([ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay ]);\n hal.setUnrealisticExpectations([ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ]);\n ian.setUnrealisticExpectations([ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve ]);\n jon.setUnrealisticExpectations([ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope ]);\n \/\/ set unrealistic expectations for the women\n abi.setUnrealisticExpectations([ bob, fred, jon, gav, ian, abe, dan, ed, col, hal ]);\n bea.setUnrealisticExpectations([ bob, abe, col, fred, gav, dan, ian, ed, jon, hal ]);\n cath.setUnrealisticExpectations([ fred, bob, ed, gav, hal, col, ian, abe, dan, jon ]);\n dee.setUnrealisticExpectations([ fred, jon, col, abe, ian, hal, gav, dan, bob, ed ]);\n eve.setUnrealisticExpectations([ jon, hal, fred, dan, abe, gav, col, ed, ian, bob ]);\n fay.setUnrealisticExpectations([ bob, abe, ed, ian, jon, dan, fred, gav, col, hal ]);\n gay.setUnrealisticExpectations([ jon, gav, hal, fred, bob, abe, col, ed, dan, ian ]);\n hope.setUnrealisticExpectations([ gav, jon, bob, abe, ian, dan, hal, ed, col, fred ]);\n ivy.setUnrealisticExpectations([ ian, col, hal, gav, fred, bob, abe, ed, jon, dan ]);\n jan.setUnrealisticExpectations([ ed, hal, gav, abe, bob, jon, col, ian, fred, dan ]);\n\n \/\/ here comes the bride, duhn, duhn, duh-duhn\n possiblyHappilyMarriedMen = doCreepyMassMarriages( men );\n \/\/ let's see who shacked up!\n for( man in possiblyHappilyMarriedMen ) {\n writeoutput( man.psychoAnalyze() & \"
\" );\n }\n \/\/ check if society is stable\n if( isSocietyStable( men, women ) ) {\n writeoutput( \"Hey, look at that. Creepy social engineering works. Sort of...

\" );\n }\n \/\/ what happens if couples start swingin'?\n jon.swing( fred );\n writeoutput( \"Swapping Jon and Fred's wives...will society survive?

\" );\n \/\/ check if society is still stable after the swingers\n if( !isSocietyStable( men, women ) ) {\n writeoutput( \"Nope, now everything is broken. Sharing spouses doesn't work, kids.
\" );\n }\n<\/cfscript>\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":698} {"lang_cluster":"ColdFusion","source_code":"\n\n\n\n\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, irrespective of their types. The function is designed to work in both statically and dynamically typed languages, with certain constraints for type compatibility in statically typed languages. The function may not support the swapping of a string and integer value if the language does not permit such an exchange. The function also addresses challenges in generic programming, particularly in static languages with limited support for parametric polymorphism.","id":699} {"lang_cluster":"ARM_Assembly","source_code":"\n\nSTMFD sp!,{r0-r12,lr} ;push r0 thru r12 and the link register\nLDMFD sp!,{r0-r12,pc} ;pop r0 thru r12, and the value that was in the link register is put into the program counter. \n ;This acts as a pop and return command all-in-one. (Most programs use bx lr to return.)\n\nLDR r0,[sp] ;load the top of the stack into r0\n\n;this example uses VASM syntax which considers a \"word\" to be 16-bit regardless of the architecture\nInitStackPointer: .long 0x3FFFFFFF ;other assemblers would call this a \"word\"\n\nMOV R1,#InitStackPointer\nLDR SP,[R1] ;set up the stack pointer\nLDR R2,[R1] ;also load it into R2\n;There's no point in checking since we haven't pushed\/popped anything but just for demonstration purposes we'll check now\nCMP SP,R2\nBEQ StackIsEmpty\n\n","human_summarization":"implement a stack with basic operations such as push, pop, and empty. The stack uses a last in, first out (LIFO) access policy and allows for both immutable and mutable access to the last pushed element. The stack can be held in any register, not limited to SP. The stack pointer can work with any operation the other registers can. The codes also provide functionality to check if the stack is empty.","id":700} {"lang_cluster":"ARM_Assembly","source_code":"\n\nfibonacci:\n push {r1-r3}\n mov r1, #0\n mov r2, #1\n \nfibloop:\n mov r3, r2\n add r2, r1, r2\n mov r1, r3\n sub r0, r0, #1\n cmp r0, #1\n bne fibloop\n \n mov r0, r2\n pop {r1-r3}\n mov pc, lr\n","human_summarization":"implement a function that generates the nth Fibonacci number, using either an iterative or recursive approach. The function accepts an input n and returns the corresponding Fibonacci number. It also has the optional feature to calculate Fibonacci numbers for negative n values. The input and output are handled through register R0.","id":701} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI *\/\n\/* program filterdes.s *\/\n\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n\/* for constantes see task include a file in arm assembly *\/\n.include \"..\/constantes.inc\"\n\n\/************************************\/\n\/* Initialized data *\/\n\/************************************\/\n.data\nszMessResult: .asciz \"Start array\u00a0: \"\nszMessResultFil: .asciz \"Filter array\u00a0: \"\nszMessResultdest: .asciz \"Same array\u00a0: \"\nszMessStart: .asciz \"Program 32 bits start.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n.align 4\narrayNumber: .int 1,2,3,4,5,6,7,8,9,10\n.equ LGARRAY, (. - arrayNumber) \/ 4\n\/************************************\/\n\/* UnInitialized data *\/\n\/************************************\/\n.bss \n.align 4\narrayNumberFil: .skip 4 * LGARRAY @ result array\nsZoneConv: .skip 24\n\/************************************\/\n\/* code section *\/\n\/************************************\/\n.text\n.global main \nmain:\n ldr r0,iAdrszMessStart @ display start message\n bl affichageMess\n ldr r0,iAdrszMessResult @ display message\n bl affichageMess\n ldr r5,iAdrarrayNumber @ start array address\n mov r4,#0 @ index\n \n1:\n ldr r0,[r5,r4,lsl #2] @ load a value\n ldr r1,iAdrsZoneConv\n bl conversion10 @ d\u00e9cimal conversion\n add r1,r1,r0 @ compute address end number\n add r1,#2 @ add two characters \n mov r0,#0 @ for limit the size of display number\n strb r0,[r1] @ to store a final zero\n ldr r0,iAdrsZoneConv\n bl affichageMess @ display value\n add r4,r4,#1 @ increment index\n cmp r4,#LGARRAY @ end array\u00a0?\n blt 1b @ no -> loop\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n \n ldr r6,iAdrarrayNumberFil @ adrress result array\n mov r4,#0 @ index\n mov r3,#0 @ index result\n2:\n ldr r0,[r5,r4,lsl #2] @ load a value\n tst r0,#1 @ odd\u00a0?\n streq r0,[r6,r3,lsl #2] @ no -> store in result array\n addeq r3,r3,#1 @ and increment result index\n add r4,r4,#1 @ increment array index\n cmp r4,#LGARRAY @ end\u00a0?\n blt 2b @ no -> loop\n \n ldr r0,iAdrszMessResultFil \n bl affichageMess\n mov r4,#0 @ init index\n \n3: @ display filter result array\n ldr r0,[r6,r4,lsl #2]\n ldr r1,iAdrsZoneConv\n bl conversion10\n add r1,r1,r0\n add r1,#2\n mov r0,#0\n strb r0,[r1]\n ldr r0,iAdrsZoneConv\n bl affichageMess\n add r4,r4,#1\n cmp r4,r3\n blt 3b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n \n @ array destruction\n mov r4,#0 @ index\n mov r3,#0 @ index result\n4:\n ldr r0,[r5,r4,lsl #2] @ load a value\n tst r0,#1 @ even\u00a0?\n bne 6f\n cmp r3,r4 @ index = no store\n beq 5f\n str r0,[r5,r3,lsl #2] @ store in free item on same array\n5:\n add r3,r3,#1 @ and increment result index\n6:\n add r4,r4,#1 @ increment array index\n cmp r4,#LGARRAY @ end\u00a0?\n blt 4b @ no -> loop\n \n ldr r0,iAdrszMessResultdest \n bl affichageMess\n mov r4,#0 @ init index\n \n7: @ display array\n ldr r0,[r5,r4,lsl #2]\n ldr r1,iAdrsZoneConv\n bl conversion10\n add r1,r1,r0\n add r1,#2\n mov r0,#0\n strb r0,[r1]\n ldr r0,iAdrsZoneConv\n bl affichageMess\n add r4,r4,#1\n cmp r4,r3\n blt 7b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n \n\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform the system call\niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessStart: .int szMessStart\niAdrarrayNumber: .int arrayNumber\niAdrszMessResult: .int szMessResult\niAdrarrayNumberFil: .int arrayNumberFil\niAdrszMessResultFil: .int szMessResultFil\niAdrszMessResultdest: .int szMessResultdest\niAdrsZoneConv: .int sZoneConv\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n\/* for this file see task include a file in language ARM assembly*\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":702} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program substring.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n.equ BUFFERSIZE, 100\n\n\/* Initialized data *\/\n.data\nszMessString: .asciz \"Result\u00a0: \" \nszString1: .asciz \"abcdefghijklmnopqrstuvwxyz\"\nszStringStart: .asciz \"abcdefg\"\nszCarriageReturn: .asciz \"\\n\"\n\n\/* UnInitialized data *\/\n.bss \nszSubString: .skip 500 @ buffer result\n\n\n\/* code section *\/\n.text\n.global main \nmain: \n\n ldr r0,iAdrszString1 @ address input string\n ldr r1,iAdrszSubString @ address output string\n mov r2,#22 @ location\n mov r3,#4 @ length\n bl subStringNbChar @ starting from n characters in and of m length\n ldr r0,iAdrszMessString @ display message\n bl affichageMess\n ldr r0,iAdrszSubString @ display substring result\n bl affichageMess\n ldr r0,iAdrszCarriageReturn @ display line return\n bl affichageMess\n @\n ldr r0,iAdrszString1\n ldr r1,iAdrszSubString\n mov r2,#15 @ location\n bl subStringEnd @starting from n characters in, up to the end of the string\n ldr r0,iAdrszMessString @ display message\n bl affichageMess\n ldr r0,iAdrszSubString\n bl affichageMess\n ldr r0,iAdrszCarriageReturn @ display line return\n bl affichageMess\n @\n ldr r0,iAdrszString1\n ldr r1,iAdrszSubString\n bl subStringMinus @ whole string minus last character\n ldr r0,iAdrszMessString @ display message\n bl affichageMess\n ldr r0,iAdrszSubString\n bl affichageMess\n ldr r0,iAdrszCarriageReturn @ display line return\n bl affichageMess\n @\n ldr r0,iAdrszString1\n ldr r1,iAdrszSubString\n mov r2,#'c' @ start character\n mov r3,#5 @ length\n bl subStringStChar @starting from a known character within the string and of m length\n cmp r0,#-1 @ error\u00a0?\n beq 2f\n ldr r0,iAdrszMessString @ display message\n bl affichageMess\n ldr r0,iAdrszSubString\n bl affichageMess\n ldr r0,iAdrszCarriageReturn @ display line return\n bl affichageMess\n @\n2:\n ldr r0,iAdrszString1\n ldr r1,iAdrszSubString\n ldr r2,iAdrszStringStart @ sub string to start\n mov r3,#10 @ length\n bl subStringStString @ starting from a known substring within the string and of m length\n cmp r0,#-1 @ error\u00a0?\n beq 3f\n ldr r0,iAdrszMessString @ display message\n bl affichageMess\n ldr r0,iAdrszSubString\n bl affichageMess\n ldr r0,iAdrszCarriageReturn @ display line return\n bl affichageMess\n3:\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\niAdrszMessString: .int szMessString\niAdrszString1: .int szString1\niAdrszSubString: .int szSubString\niAdrszStringStart: .int szStringStart\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* sub strings index start number of characters *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the input string *\/\n\/* r1 contains the address of the output string *\/\n\/* r2 contains the start index *\/\n\/* r3 contains numbers of characters to extract *\/\n\/* r0 returns number of characters or -1 if error *\/\nsubStringNbChar:\n push {r1-r5,lr} @ save registers \n mov r4,#0 @ counter byte output string \n1:\n ldrb r5,[r0,r2] @ load byte string input\n cmp r5,#0 @ zero final\u00a0?\n beq 2f\n strb r5,[r1,r4] @ store byte output string\n add r2,#1 @ increment counter\n add r4,#1\n cmp r4,r3 @ end\u00a0?\n blt 1b @ no -> loop\n2:\n mov r5,#0\n strb r5,[r1,r4] @ load byte string 2\n mov r0,r4\n100:\n pop {r1-r5,lr} @ restaur registers\n bx lr @ return\n\/******************************************************************\/\n\/* sub strings index start at end of string *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the input string *\/\n\/* r1 contains the address of the output string *\/\n\/* r2 contains the start index *\/\n\/* r0 returns number of characters or -1 if error *\/\nsubStringEnd:\n push {r1-r5,lr} @ save registers \n mov r4,#0 @ counter byte output string \n1:\n ldrb r5,[r0,r2] @ load byte string 1\n cmp r5,#0 @ zero final\u00a0?\n beq 2f\n strb r5,[r1,r4]\n add r2,#1\n add r4,#1\n b 1b @ loop\n2:\n mov r5,#0\n strb r5,[r1,r4] @ load byte string 2\n mov r0,r4\n100:\n pop {r1-r5,lr} @ restaur registers\n bx lr \n\/******************************************************************\/\n\/* whole string minus last character *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the input string *\/\n\/* r1 contains the address of the output string *\/\n\/* r0 returns number of characters or -1 if error *\/\nsubStringMinus:\n push {r1-r5,lr} @ save registers \n mov r2,#0 @ counter byte input string\n mov r4,#0 @ counter byte output string \n1:\n ldrb r5,[r0,r2] @ load byte string \n cmp r5,#0 @ zero final\u00a0?\n beq 2f\n strb r5,[r1,r4]\n add r2,#1\n add r4,#1\n b 1b @ loop\n2:\n sub r4,#1\n mov r5,#0\n strb r5,[r1,r4] @ load byte string 2\n mov r0,r4\n100:\n pop {r1-r5,lr} @ restaur registers\n bx lr \n\/******************************************************************\/\n\/* starting from a known character within the string and of m length *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the input string *\/\n\/* r1 contains the address of the output string *\/\n\/* r2 contains the character *\/\n\/* r3 contains the length\n\/* r0 returns number of characters or -1 if error *\/\nsubStringStChar:\n push {r1-r5,lr} @ save registers \n mov r6,#0 @ counter byte input string\n mov r4,#0 @ counter byte output string \n\n1:\n ldrb r5,[r0,r6] @ load byte string \n cmp r5,#0 @ zero final\u00a0?\n streqb r5,[r1,r4]\n moveq r0,#-1\n beq 100f\n cmp r5,r2\n beq 2f\n add r6,#1\n b 1b @ loop\n2:\n strb r5,[r1,r4]\n add r6,#1\n add r4,#1\n cmp r4,r3\n bge 3f\n ldrb r5,[r0,r6] @ load byte string \n cmp r5,#0\n bne 2b\n3:\n mov r5,#0\n strb r5,[r1,r4] @ load byte string 2\n mov r0,r4\n100:\n pop {r1-r5,lr} @ restaur registers\n bx lr \n\n\/******************************************************************\/\n\/* starting from a known substring within the string and of m length *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the input string *\/\n\/* r1 contains the address of the output string *\/\n\/* r2 contains the address of string to start *\/\n\/* r3 contains the length\n\/* r0 returns number of characters or -1 if error *\/\nsubStringStString:\n push {r1-r8,lr} @ save registers \n mov r7,r0 @ save address\n mov r8,r1 @ counter byte string \n mov r1,r2\n bl searchSubString\n cmp r0,#-1\n beq 100f\n mov r6,r0 @ counter byte input string\n mov r4,#0\n1:\n ldrb r5,[r7,r6] @ load byte string \n strb r5,[r8,r4]\n cmp r5,#0 @ zero final\u00a0?\n moveq r0,r4\n beq 100f\n add r4,#1\n cmp r4,r3\n addlt r6,#1\n blt 1b @ loop\n mov r5,#0\n strb r5,[r8,r4]\n mov r0,r4\n100:\n pop {r1-r8,lr} @ restaur registers\n bx lr \n\n\/******************************************************************\/\n\/* search a substring in the string *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the input string *\/\n\/* r1 contains the address of substring *\/\n\/* r0 returns index of substring in string or -1 if not found *\/\nsearchSubString:\n push {r1-r6,lr} @ save registers \n mov r2,#0 @ counter byte input string\n mov r3,#0 @ counter byte string \n mov r6,#-1 @ index found\n ldrb r4,[r1,r3]\n1:\n ldrb r5,[r0,r2] @ load byte string \n cmp r5,#0 @ zero final\u00a0?\n moveq r0,#-1 @ yes returns error\n beq 100f\n cmp r5,r4 @ compare character \n beq 2f\n mov r6,#-1 @ no equals - > raz index \n mov r3,#0 @ and raz counter byte\n add r2,#1 @ and increment counter byte\n b 1b @ and loop\n2: @ characters equals\n cmp r6,#-1 @ first characters equals\u00a0?\n moveq r6,r2 @ yes -> index begin in r6\n add r3,#1 @ increment counter substring\n ldrb r4,[r1,r3] @ and load next byte\n cmp r4,#0 @ zero final\u00a0?\n beq 3f @ yes -> end search\n add r2,#1 @ else increment counter string\n b 1b @ and loop\n3:\n mov r0,r6\n100:\n pop {r1-r6,lr} @ restaur registers\n bx lr \n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registers \n mov r2,#0 @ counter length *\/\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call system\n pop {r0,r1,r2,r7,lr} @ restaur registers\n bx lr @ return\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":703} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program avltree2.s *\/\n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\n\/*******************************************\/\n\/* Constantes *\/\n\/*******************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ BRK, 0x2d @ Linux syscall\n.equ CHARPOS, '@'\n\n.equ NBVAL, 12\n\n\/*******************************************\/\n\/* Structures *\/\n\/********************************************\/\n\/* structure tree *\/\n .struct 0\ntree_root: @ root pointer (or node right)\n .struct tree_root + 4 \ntree_size: @ number of element of tree\n .struct tree_size + 4 \ntree_suite:\n .struct tree_suite + 12 @ for alignement to node\ntree_fin:\n\/* structure node tree *\/\n .struct 0\nnode_right: @ right pointer\n .struct node_right + 4 \nnode_left: @ left pointer\n .struct node_left + 4 \nnode_value: @ element value\n .struct node_value + 4 \nnode_height: @ element value\n .struct node_height + 4 \nnode_parent: @ element value\n .struct node_parent + 4 \nnode_fin:\n\/* structure queue*\/\n .struct 0\nqueue_begin: @ next pointer\n .struct queue_begin + 4 \nqueue_end: @ element value\n .struct queue_end + 4 \nqueue_fin:\n\/* structure node queue *\/\n .struct 0\nqueue_node_next: @ next pointer\n .struct queue_node_next + 4 \nqueue_node_value: @ element value\n .struct queue_node_value + 4 \nqueue_node_fin:\n\/*******************************************\/\n\/* Initialized data *\/\n\/*******************************************\/\n.data\nszMessPreOrder: .asciz \"PreOrder\u00a0:\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\/* datas error display *\/\nszMessErreur: .asciz \"Error detected.\\n\"\nszMessKeyDbl: .asciz \"Key exists in tree.\\n\"\nszMessInsInv: .asciz \"Insertion in inverse order.\\n\"\n\/* datas message display *\/\nszMessResult: .asciz \"Ele: @ G: @ D: @ val @ h @ pere @\\n\"\nsValue: .space 12,' '\n .asciz \"\\n\"\n\/*******************************************\/\n\/* UnInitialized data *\/\n\/*******************************************\/\n.bss \nsZoneConv: .skip 24\nstTree: .skip tree_fin @ place to structure tree\nstTree1: .skip tree_fin @ place to structure tree\nstQueue: .skip queue_fin @ place to structure queue\n\/*******************************************\/\n\/* code section *\/\n\/*******************************************\/\n.text\n.global main \nmain: \n mov r8,#1 @ node tree value\n1: @ loop insertion in order\n ldr r0,iAdrstTree @ structure tree address\n mov r1,r8\n bl insertElement @ add element value r1\n cmp r0,#-1\n beq 99f\n \/\/ldr r3,iAdrstTree @ tree root address (begin structure)\n \/\/ldr r0,[r3,#tree_root]\n \/\/ldr r1,iAdrdisplayElement @ function to execute\n \/\/bl preOrder\n add r8,#1 @ increment value\n cmp r8,#NBVAL @ end\u00a0?\n ble 1b @ no -> loop\n\n ldr r0,iAdrstTree @ structure tree address\n mov r1,#11 @ verif key dobble\n bl insertElement @ add element value r1\n cmp r0,#-1\n bne 2f\n ldr r0,iAdrszMessErreur\n bl affichageMess\n2:\n ldr r0,iAdrszMessPreOrder @ load verification\n bl affichageMess\n ldr r3,iAdrstTree @ tree root address (begin structure)\n ldr r0,[r3,#tree_root]\n ldr r1,iAdrdisplayElement @ function to execute\n bl preOrder\n \n\n ldr r0,iAdrszMessInsInv\n bl affichageMess\n mov r8,#NBVAL @ node tree value\n3: @ loop insertion inverse order\n ldr r0,iAdrstTree1 @ structure tree address\n mov r1,r8\n bl insertElement @ add element value r1\n cmp r0,#-1\n beq 99f\n sub r8,#1 @ increment value\n cmp r8,#0 @ end\u00a0?\n bgt 3b @ no -> loop\n\n ldr r0,iAdrszMessPreOrder @ load verification\n bl affichageMess\n ldr r3,iAdrstTree1 @ tree root address (begin structure)\n ldr r0,[r3,#tree_root]\n ldr r1,iAdrdisplayElement @ function to execute\n bl preOrder\n\n @ search value\n ldr r0,iAdrstTree1 @ tree root address (begin structure)\n mov r1,#11 @ value to search\n bl searchTree\n cmp r0,#-1\n beq 100f\n mov r2,r0\n ldr r0,iAdrszMessKeyDbl @ key exists\n bl affichageMess\n @ suppresssion previous value\n mov r0,r2\n ldr r1,iAdrstTree1\n bl supprimer\n\n ldr r0,iAdrszMessPreOrder @ verification\n bl affichageMess\n ldr r3,iAdrstTree1 @ tree root address (begin structure)\n ldr r0,[r3,#tree_root]\n ldr r1,iAdrdisplayElement @ function to execute\n bl preOrder\n\n b 100f\n99: @ display error\n ldr r0,iAdrszMessErreur\n bl affichageMess\n100: @ standard end of the program\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\niAdrszMessPreOrder: .int szMessPreOrder\niAdrszMessErreur: .int szMessErreur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrstTree: .int stTree\niAdrstTree1: .int stTree1\niAdrstQueue: .int stQueue\niAdrdisplayElement: .int displayElement\niAdrszMessInsInv: .int szMessInsInv\n\/******************************************************************\/\n\/* insert element in the tree *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the tree structure *\/\n\/* r1 contains the value of element *\/\n\/* r0 returns address of element or - 1 if error *\/\ninsertElement: @ INFO: insertElement\n push {r1-r8,lr} @ save registers \n mov r7,r0 @ save head\n mov r0,#node_fin @ reservation place one element\n bl allocHeap\n cmp r0,#-1 @ allocation error\n beq 100f\n mov r5,r0\n str r1,[r5,#node_value] @ store value in address heap\n mov r3,#0\n str r3,[r5,#node_left] @ init left pointer with zero\n str r3,[r5,#node_right] @ init right pointer with zero\n str r3,[r5,#node_height] @ init balance with zero\n ldr r2,[r7,#tree_size] @ load tree size\n cmp r2,#0 @ 0 element\u00a0?\n bne 1f\n str r5,[r7,#tree_root] @ yes -> store in root\n b 4f\n1: @ else search free address in tree\n ldr r3,[r7,#tree_root] @ start with address root\n2: @ begin loop to insertion\n ldr r4,[r3,#node_value] @ load key \n cmp r1,r4\n beq 6f @ key equal\n blt 3f @ key <\n @ key > insertion right\n ldr r8,[r3,#node_right] @ node empty\u00a0?\n cmp r8,#0\n movne r3,r8 @ no -> next node\n bne 2b @ and loop\n str r5,[r3,#node_right] @ store node address in right pointer\n b 4f\n3: @ left\n ldr r8,[r3,#node_left] @ left pointer empty\u00a0?\n cmp r8,#0\n movne r3,r8 @\n bne 2b @ no -> loop\n str r5,[r3,#node_left] @ store node address in left pointer\n4:\n str r3,[r5,#node_parent] @ store parent\n mov r4,#1\n str r4,[r5,#node_height] @ store height = 1\n mov r0,r5 @ begin node to requilbrate\n mov r1,r7 @ head address\n bl equilibrer\n\n5:\n add r2,#1 @ increment tree size\n str r2,[r7,#tree_size]\n mov r0,#0\n b 100f\n6: @ key equal\u00a0?\n ldr r0,iAdrszMessKeyDbl\n bl affichageMess\n mov r0,#-1\n b 100f\n100:\n pop {r1-r8,lr} @ restaur registers\n bx lr @ return\niAdrszMessKeyDbl: .int szMessKeyDbl\n\/******************************************************************\/\n\/* equilibrer after insertion *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the node *\/\n\/* r1 contains the address of head *\/\nequilibrer: @ INFO: equilibrer\n push {r1-r8,lr} @ save registers \n mov r3,#0 @ balance factor\n1: @ begin loop\n ldr r5,[r0,#node_parent] @ load father\n cmp r5,#0 @ end\u00a0?\n beq 5f\n cmp r3,#2 @ right tree too long\n beq 5f\n cmp r3,#-2 @ left tree too long\n beq 5f\n mov r6,r0 @ s = current\n ldr r0,[r6,#node_parent] @ current = father\n ldr r7,[r0,#node_left]\n cmp r7,#0\n ldrne r8,[r7,#node_height] @ height left tree \n moveq r8,#0\n ldr r7,[r0,#node_right]\n cmp r7,#0\n ldrne r9,[r7,#node_height] @ height right tree \n moveq r9,#0\n cmp r8,r9\n addgt r8,#1\n strgt r8,[r0,#node_height]\n addle r9,#1\n strle r9,[r0,#node_height]\n \/\/\n ldr r7,[r0,#node_right]\n cmp r7,#0\n ldrne r8,[r7,#node_height]\n moveq r8,#0\n ldr r7,[r0,#node_left]\n cmp r7,#0\n ldrne r9,[r7,#node_height]\n moveq r9,#0\n sub r3,r8,r9 @ compute balance factor\n b 1b\n5:\n cmp r3,#2\n beq 6f\n cmp r3,#-2\n beq 6f\n b 100f\n6:\n mov r3,r1\n mov r4,r0\n mov r1,r6\n bl equiUnSommet\n @ change head address\u00a0?\n ldr r2,[r3,#tree_root]\n cmp r2,r4\n streq r6,[r3,#tree_root]\n100:\n pop {r1-r8,lr} @ restaur registers\n bx lr @ return\n\/******************************************************************\/\n\/* equilibre 1 sommet *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the node *\/\n\/* r1 contains the address of the node *\/\nequiUnSommet: @ INFO: equiUnSommet\n push {r1-r9,lr} @ save registers \n mov r5,r0 @ save p\n mov r6,r1 \/\/ s\n ldr r2,[r5,#node_left]\n cmp r2,r6\n bne 5f\n ldr r7,[r5,#node_right]\n cmp r7,#0\n moveq r8,#0\n ldrne r8,[r7,#node_height]\n ldr r7,[r5,#node_left]\n cmp r7,#0\n moveq r9,#0\n ldrne r9,[r7,#node_height]\n sub r3,r8,r9\n cmp r3,#-2\n bne 100f\n ldr r7,[r6,#node_right]\n cmp r7,#0\n moveq r8,#0\n ldrne r8,[r7,#node_height]\n ldr r7,[r6,#node_left]\n cmp r7,#0\n moveq r9,#0\n ldrne r9,[r7,#node_height]\n sub r3,r8,r9\n cmp r3,#1\n bge 2f\n mov r0,r5\n bl rotRight\n b 100f\n2:\n mov r0,r6\n bl rotLeft\n mov r0,r5\n bl rotRight\n b 100f\n\n5:\n ldr r7,[r5,#node_right]\n cmp r7,#0\n moveq r8,#0\n ldrne r8,[r7,#node_height]\n ldr r7,[r5,#node_left]\n cmp r7,#0\n moveq r9,#0\n ldrne r9,[r7,#node_height]\n sub r3,r8,r9\n cmp r3,#2\n bne 100f\n ldr r7,[r6,#node_right]\n cmp r7,#0\n moveq r8,#0\n ldrne r8,[r7,#node_height]\n ldr r7,[r6,#node_left]\n cmp r7,#0\n moveq r9,#0\n ldrne r9,[r7,#node_height]\n sub r3,r8,r9\n cmp r3,#-1\n ble 2f\n mov r0,r5\n bl rotLeft\n b 100f\n2:\n mov r0,r6\n bl rotRight\n mov r0,r5\n bl rotLeft\n b 100f\n\n100:\n pop {r1-r9,lr} @ restaur registers\n bx lr @ return\n\/******************************************************************\/\n\/* right rotation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the node *\/\nrotRight: @ INFO: rotRight \n push {r1-r5,lr} @ save registers \n \/\/ r2 r2\n \/\/ r0 r1\n \/\/ r1 r0\n \/\/ r3 r3\n ldr r1,[r0,#node_left] @ load left children\n ldr r2,[r0,#node_parent] @ load father\n cmp r2,#0 @ no father\u00a0???\n beq 2f\n ldr r3,[r2,#node_left] @ load left node father\n cmp r3,r0 @ equal current node\u00a0?\n streq r1,[r2,#node_left] @ yes store left children\n strne r1,[r2,#node_right] @ no store right\n2:\n str r2,[r1,#node_parent] @ change parent\n str r1,[r0,#node_parent]\n ldr r3,[r1,#node_right]\n str r3,[r0,#node_left]\n cmp r3,#0\n strne r0,[r3,#node_parent] @ change parent node left\n str r0,[r1,#node_right]\n\n ldr r3,[r0,#node_left] @ compute newbalance factor \n cmp r3,#0\n moveq r4,#0\n ldrne r4,[r3,#node_height]\n ldr r3,[r0,#node_right]\n cmp r3,#0\n moveq r5,#0\n ldrne r5,[r3,#node_height]\n cmp r4,r5\n addgt r4,#1\n strgt r4,[r0,#node_height]\n addle r5,#1\n strle r5,[r0,#node_height]\n\/\/\n ldr r3,[r1,#node_left] @ compute new balance factor\n cmp r3,#0\n moveq r4,#0\n ldrne r4,[r3,#node_height]\n ldr r3,[r1,#node_right]\n cmp r3,#0\n moveq r5,#0\n ldrne r5,[r3,#node_height]\n cmp r4,r5\n addgt r4,#1\n strgt r4,[r1,#node_height]\n addle r5,#1\n strle r5,[r1,#node_height]\n100:\n pop {r1-r5,lr} @ restaur registers\n bx lr\n\/******************************************************************\/\n\/* left rotation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the node sommet *\/\nrotLeft: @ INFO: rotLeft \n push {r1-r5,lr} @ save registers \n \/\/ r2 r2\n \/\/ r0 r1\n \/\/ r1 r0\n \/\/ r3 r3\n ldr r1,[r0,#node_right] @ load right children\n ldr r2,[r0,#node_parent] @ load father (racine)\n cmp r2,#0 @ no father\u00a0???\n beq 2f\n ldr r3,[r2,#node_left] @ load left node father\n cmp r3,r0 @ equal current node\u00a0?\n streq r1,[r2,#node_left] @ yes store left children\n strne r1,[r2,#node_right] @ no store to right\n2:\n str r2,[r1,#node_parent] @ change parent of right children\n str r1,[r0,#node_parent] @ change parent of sommet\n ldr r3,[r1,#node_left] @ left children \n str r3,[r0,#node_right] @ left children pivot exists\u00a0? \n cmp r3,#0\n strne r0,[r3,#node_parent] @ yes store in \n str r0,[r1,#node_left]\n\/\/\n ldr r3,[r0,#node_left] @ compute new height for old summit\n cmp r3,#0\n moveq r4,#0\n ldrne r4,[r3,#node_height] @ left height\n ldr r3,[r0,#node_right]\n cmp r3,#0\n moveq r5,#0\n ldrne r5,[r3,#node_height] @ right height\n cmp r4,r5\n addgt r4,#1\n strgt r4,[r0,#node_height] @ if right > left\n addle r5,#1\n strle r5,[r0,#node_height] @ if left > right\n\/\/\n ldr r3,[r1,#node_left] @ compute new height for new\n cmp r3,#0\n moveq r4,#0\n ldrne r4,[r3,#node_height]\n ldr r3,[r1,#node_right]\n cmp r3,#0\n moveq r5,#0\n ldrne r5,[r3,#node_height]\n cmp r4,r5\n addgt r4,#1\n strgt r4,[r1,#node_height]\n addle r5,#1\n strle r5,[r1,#node_height]\n100:\n pop {r1-r5,lr} @ restaur registers\n bx lr\n\/******************************************************************\/\n\/* search value in tree *\/ \n\/******************************************************************\/\n\/* r0 contains the address of structure of tree *\/\n\/* r1 contains the value to search *\/\nsearchTree: @ INFO: searchTree\n push {r1-r4,lr} @ save registers \n ldr r2,[r0,#tree_root]\n\n1: @ begin loop\n ldr r4,[r2,#node_value] @ load key \n cmp r1,r4\n beq 3f @ key equal\n blt 2f @ key <\n @ key > insertion right\n ldr r3,[r2,#node_right] @ node empty\u00a0?\n cmp r3,#0\n movne r2,r3 @ no -> next node\n bne 1b @ and loop\n mov r0,#-1 @ not find\n b 100f\n2: @ left\n ldr r3,[r2,#node_left] @ left pointer empty\u00a0?\n cmp r3,#0\n movne r2,r3 @\n bne 1b @ no -> loop\n mov r0,#-1 @ not find\n b 100f\n3:\n mov r0,r2 @ return node address\n100:\n pop {r1-r4,lr} @ restaur registers\n bx lr\n\/******************************************************************\/\n\/* suppression node *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the node *\/\n\/* r1 contains structure tree address *\/\nsupprimer: @ INFO: supprimer\n push {r1-r8,lr} @ save registers \n ldr r1,[r0,#node_left]\n cmp r1,#0\n bne 5f\n ldr r1,[r0,#node_right]\n cmp r1,#0\n bne 5f\n @ is a leaf\n mov r4,#0\n ldr r3,[r0,#node_parent] @ father\n cmp r3,#0\n streq r4,[r1,#tree_root]\n beq 100f\n ldr r1,[r3,#node_left]\n cmp r1,r0\n bne 2f\n str r4,[r3,#node_left] @ suppression left children\n ldr r5,[r3,#node_right]\n cmp r5,#0\n moveq r6,#0\n ldrne r6,[r5,#node_height]\n add r6,#1\n str r6,[r3,#node_height]\n b 3f\n2: @ suppression right children\n str r4,[r3,#node_right]\n ldr r5,[r3,#node_left]\n cmp r5,#0\n moveq r6,#0\n ldrne r6,[r5,#node_height]\n add r6,#1\n str r6,[r3,#node_height]\n3: @ new balance\n mov r0,r3\n bl equilibrerSupp\n b 100f\n5: @ is not \u00e0 leaf\n ldr r7,[r0,#node_right]\n cmp r7,#0\n beq 7f\n mov r8,r0\n mov r0,r7\n6:\n ldr r6,[r0,#node_left]\n cmp r6,#0\n movne r0,r6\n bne 6b\n b 9f\n7:\n ldr r7,[r0,#node_left] @ search the litle element\n cmp r7,#0\n beq 9f\n mov r8,r0\n mov r0,r7\n8:\n ldr r6,[r0,#node_right] @ search the great element\n cmp r6,#0\n movne r0,r6\n bne 8b\n9:\n ldr r5,[r0,#node_value] @ copy value\n str r5,[r8,#node_value]\n bl supprimer @ suppression node r0\n100:\n pop {r1-r8,lr} @ restaur registers\n bx lr\n\n\/******************************************************************\/\n\/* equilibrer after suppression *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the node *\/\n\/* r1 contains the address of head *\/\nequilibrerSupp: @ INFO: equilibrerSupp\n push {r1-r8,lr} @ save registers \n mov r3,#1 @ balance factor\n ldr r2,[r1,#tree_root]\n1:\n ldr r5,[r0,#node_parent] @ load father\n cmp r5,#0 @ no father \n beq 100f\n cmp r3,#0 @ balance equilibred\n beq 100f\n mov r6,r0 @ save entry node\n ldr r0,[r6,#node_parent] @ current = father\n ldr r7,[r0,#node_left]\n cmp r7,#0\n ldrne r8,[r7,#node_height] @ height left tree \n moveq r8,#0\n ldr r7,[r0,#node_right]\n cmp r7,#0\n ldrne r9,[r7,#node_height] @ height right tree \n moveq r9,#0\n cmp r8,r9\n addgt r8,#1\n strgt r8,[r0,#node_height]\n addle r9,#1\n strle r9,[r0,#node_height]\n \/\/\n ldr r7,[r0,#node_right]\n cmp r7,#0\n ldrne r8,[r7,#node_height]\n moveq r8,#0\n ldr r7,[r0,#node_left]\n cmp r7,#0\n ldrne r9,[r7,#node_height]\n moveq r9,#0\n sub r3,r8,r9 @ compute balance factor\n mov r2,r1\n mov r4,r0 @ save current\n mov r1,r6\n bl equiUnSommet\n @ change head address\u00a0?\n cmp r2,r4\n streq r6,[r3,#tree_root]\n mov r0,r4 @ restaur current\n b 1b\n\n100:\n pop {r1-r8,lr} @ restaur registers\n bx lr @ return\n\/******************************************************************\/\n\/* preOrder *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the node *\/\n\/* r1 function address *\/\npreOrder: @ INFO: preOrder\n push {r1-r2,lr} @ save registers \n cmp r0,#0\n beq 100f\n mov r2,r0\n blx r1 @ call function\n\n ldr r0,[r2,#node_left]\n bl preOrder\n ldr r0,[r2,#node_right]\n bl preOrder\n100:\n pop {r1-r2,lr} @ restaur registers\n bx lr \n\n\/******************************************************************\/\n\/* display node *\/ \n\/******************************************************************\/\n\/* r0 contains node address *\/\ndisplayElement: @ INFO: displayElement\n push {r1,r2,r3,lr} @ save registers \n mov r2,r0\n ldr r1,iAdrsZoneConv\n bl conversion16\n mov r4,#0\n strb r4,[r1,r0]\n ldr r0,iAdrszMessResult\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc\n mov r3,r0\n ldr r0,[r2,#node_left]\n ldr r1,iAdrsZoneConv\n bl conversion16\n mov r4,#0\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc\n mov r3,r0\n ldr r0,[r2,#node_right]\n ldr r1,iAdrsZoneConv\n bl conversion16\n mov r4,#0\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc\n mov r3,r0\n ldr r0,[r2,#node_value]\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r4,#0\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc\n mov r3,r0\n ldr r0,[r2,#node_height]\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r4,#0\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc\n mov r3,r0\n ldr r0,[r2,#node_parent]\n ldr r1,iAdrsZoneConv\n bl conversion16\n mov r4,#0\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc\n bl affichageMess\n100:\n pop {r1,r2,r3,lr} @ restaur registers\n bx lr @ return\niAdrszMessResult: .int szMessResult\niAdrsZoneConv: .int sZoneConv\niAdrsValue: .int sValue\n\n\/******************************************************************\/\n\/* memory allocation on the heap *\/ \n\/******************************************************************\/\n\/* r0 contains the size to allocate *\/\n\/* r0 returns address of memory heap or - 1 if error *\/\n\/* CAUTION\u00a0: The size of the allowance must be a multiple of 4 *\/\nallocHeap:\n push {r5-r7,lr} @ save registers \n @ allocation\n mov r6,r0 @ save size\n mov r0,#0 @ read address start heap\n mov r7,#0x2D @ call system 'brk'\n svc #0\n mov r5,r0 @ save address heap for return\n add r0,r6 @ reservation place for size\n mov r7,#0x2D @ call system 'brk'\n svc #0\n cmp r0,#-1 @ allocation error\n movne r0,r5 @ return address memory heap\n pop {r5-r7,lr} @ restaur registers\n bx lr @ return\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.","id":704} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program loopbreak.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessEndLoop: .asciz \"loop break with value\u00a0: \\n\"\nszMessResult: .ascii \"Resultat = \" @ message result\nsMessValeur: .fill 12, 1, ' '\n .asciz \"\\n\"\n.align 4\niGraine: .int 123456\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n push {fp,lr} @ saves 2 registers \n1: @ begin loop \n mov r4,#20\n2:\n mov r0,#19\n bl genereraleas @ generate number\n cmp r0,#10 @ compar value\n beq 3f @ break if equal\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n subs r4,#1 @ decrement counter\n bgt 2b @ loop if greather\n b 1b @ begin loop one\n\t\n3:\n mov r2,r0 @ save value\n ldr r0,iAdrszMessEndLoop\n bl affichageMess @ display message\n mov r0,r2\n ldr r1,iAdrsMessValeur \n bl conversion10 @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrszMessResult: .int szMessResult\niAdrszMessEndLoop: .int szMessEndLoop\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 \t\t\t@ address message in r1 \n mov r0,#STDOUT \t\t@ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#10\n\n1:\t @ start loop\n bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\t\n strb r1,[r3,r2] @ store digit on area\n sub r2,#1 @ previous position\n cmp r0,#0 @ stop if quotient = 0 *\/\n bne 1b\t @ else loop\n @ and move spaces in first on area\n mov r1,#' ' @ space\t\n2:\t\n strb r1,[r3,r2] @ store space in area\n subs r2,#1 @ @ previous position\n bge 2b @ loop if r2 >= z\u00e9ro \n\n100:\t\n pop {r1-r4,lr} @ restaur registres \n bx lr\t @return\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save registers *\/\n mov r4,r0 \n mov r3,#0x6667 @ r3 <- magic_number lower\n movt r3,#0x6666 @ r3 <- magic_number upper\n smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) \n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n\n\/***************************************************\/\n\/* Generation random number *\/\n\/***************************************************\/\n\/* r0 contains limit *\/\ngenereraleas:\n push {r1-r4,lr} @ save registers \n ldr r4,iAdriGraine\n ldr r2,[r4]\n ldr r3,iNbDep1\n mul r2,r3,r2\n ldr r3,iNbDep1\n add r2,r2,r3\n str r2,[r4] @ maj de la graine pour l appel suivant \n\n mov r1,r0 @ divisor\n mov r0,r2 @ dividende\n bl division\n mov r0,r3 @ r\u00e9sult = remainder\n \n100: @ end function\n pop {r1-r4,lr} @ restaur registers\n bx lr @ return\n\/********************************************************************\/\niAdriGraine: .int iGraine\t\niNbDep1: .int 0x343FD\niNbDep2: .int 0x269EC3 \n\/***************************************************\/\n\/* integer division unsigned *\/\n\/***************************************************\/\ndivision:\n \/* r0 contains dividend *\/\n \/* r1 contains divisor *\/\n \/* r2 returns quotient *\/\n \/* r3 returns remainder *\/\n push {r4, lr}\n mov r2, #0 @ init quotient\n mov r3, #0 @ init remainder\n mov r4, #32 @ init counter bits\n b 2f\n1: @ loop \n movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)\n adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3 <- (r3 << 1) + C \n cmp r3, r1 @ compute r3 - r1 and update cpsr \n subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1 \n adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C \n2:\n subs r4, r4, #1 @ r4 <- r4 - 1 \n bpl 1b @ if r4 >= 0 (N=0) then loop\n pop {r4, lr}\n bx lr\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":705} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program xpathXml.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n.equ NBMAXELEMENTS, 100\n\n\/*******************************************\/\n\/* Structures *\/\n\/********************************************\/\n\/* structure xmlNode*\/\n .struct 0\nxmlNode_private: @ application data\n .struct xmlNode_private + 4 \nxmlNode_type: @ type number, must be second\u00a0!\n .struct xmlNode_type + 4 \nxmlNode_name: @ the name of the node, or the entity\n .struct xmlNode_name + 4 \nxmlNode_children: @ parent->childs link\n .struct xmlNode_children + 4 \nxmlNode_last: @ last child link\n .struct xmlNode_last + 4 \nxmlNode_parent: @ child->parent link \n .struct xmlNode_parent + 4 \nxmlNode_next: @ next sibling link\n .struct xmlNode_next + 4 \nxmlNode_prev: @ previous sibling link \n .struct xmlNode_prev + 4 \nxmlNode_doc: @ the containing document\n .struct xmlNode_doc + 4 \nxmlNode_ns: @ pointer to the associated namespace\n .struct xmlNode_ns + 4 \nxmlNode_content: @ the content\n .struct xmlNode_content + 4 \nxmlNode_properties: @ properties list\n .struct xmlNode_properties + 4\nxmlNode_nsDef: @ namespace definitions on this node \n .struct xmlNode_nsDef + 4\nxmlNode_psvi: @ for type\/PSVI informations\n .struct xmlNode_psvi + 4\nxmlNode_line: @ line number\n .struct xmlNode_line + 4\nxmlNode_extra: @ extra data for XPath\/XSLT\n .struct xmlNode_extra + 4\nxmlNode_fin:\n\/********************************************\/\n\/* structure xmlNodeSet*\/\n .struct 0\nxmlNodeSet_nodeNr: @ number of nodes in the set\n .struct xmlNodeSet_nodeNr + 4 \nxmlNodeSet_nodeMax: @ size of the array as allocated \n .struct xmlNodeSet_nodeMax + 4 \nxmlNodeSet_nodeTab: @ array of nodes in no particular order\n .struct xmlNodeSet_nodeTab + 4 \nxmlNodeSet_fin:\n\/********************************************\/\n\/* structure xmlXPathObject*\/\n .struct 0\nxmlPathObj_type: @\n .struct xmlPathObj_type + 4 \nxmlPathObj_nodesetval: @\n .struct xmlPathObj_nodesetval + 4 \nxmlPathObj_boolval: @\n .struct xmlPathObj_boolval + 4 \nxmlPathObj_floatval: @\n .struct xmlPathObj_floatval + 4 \nxmlPathObj_stringval: @\n .struct xmlPathObj_stringval + 4 \nxmlPathObj_user: @\n .struct xmlPathObj_user + 4 \nxmlPathObj_index: @\n .struct xmlPathObj_index + 4 \nxmlPathObj_user2: @\n .struct xmlPathObj_user2 + 4 \nxmlPathObj_index2: @\n .struct xmlPathObj_index2 + 4 \n\n\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessEndpgm: .asciz \"\\nNormal end of program.\\n\" \nszMessDisVal: .asciz \"\\nDisplay set values.\\n\" \nszMessDisArea: .asciz \"\\nDisplay area values.\\n\" \nszFileName: .asciz \"testXml.xml\" \nszMessError: .asciz \"Error detected\u00a0!!!!. \\n\"\n\n\nszLibName: .asciz \"name\"\nszLibPrice: .asciz \"\/\/price\"\nszLibExtName: .asciz \"\/\/name\"\nszCarriageReturn: .asciz \"\\n\"\n\n\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n.align 4\ntbExtract: .skip 4 * NBMAXELEMENTS @ result extract area\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdrszFileName \n bl xmlParseFile @ create doc\n mov r9,r0 @ doc address\n mov r0,r9 @ doc\n bl xmlDocGetRootElement @ get root\n bl xmlFirstElementChild @ get first section\n bl xmlFirstElementChild @ get first item\n bl xmlFirstElementChild @ get first name\n bl xmlNodeGetContent @ extract content\n bl affichageMess @ for display\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n\n ldr r0,iAdrszMessDisVal\n bl affichageMess\n mov r0,r9\n ldr r1,iAdrszLibPrice @ extract prices\n bl extractValue\n mov r0,r9\n ldr r1,iAdrszLibExtName @ extact names\n bl extractValue\n ldr r0,iAdrszMessDisArea\n bl affichageMess\n mov r4,#0 @ display string result area\n ldr r5,iAdrtbExtract\n1:\n ldr r0,[r5,r4,lsl #2]\n cmp r0,#0\n beq 2f\n bl affichageMess\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n add r4,#1\n b 1b\n\n2:\n mov r0,r9\n bl xmlFreeDoc\n bl xmlCleanupParser\n ldr r0,iAdrszMessEndpgm\n bl affichageMess\n b 100f\n99:\n @ error\n ldr r0,iAdrszMessError\n bl affichageMess \n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrszMessError: .int szMessError\niAdrszMessEndpgm: .int szMessEndpgm\niAdrszLibName: .int szLibName\niAdrszLibPrice: .int szLibPrice\niAdrszCarriageReturn: .int szCarriageReturn\niAdrszFileName: .int szFileName\niAdrszLibExtName: .int szLibExtName\niAdrtbExtract: .int tbExtract\niAdrszMessDisVal: .int szMessDisVal\niAdrszMessDisArea: .int szMessDisArea\n\/******************************************************************\/\n\/* extract value of set *\/ \n\/******************************************************************\/\n\/* r0 contains the doc address\n\/* r1 contains the address of the libel to extract *\/\nextractValue:\n push {r1-r10,lr} @ save registres\n mov r4,r1 @ save address libel\n mov r9,r0 @ save doc\n ldr r8,iAdrtbExtract\n bl xmlXPathNewContext @ create context\n mov r10,r0\n mov r1,r0\n mov r0,r4\n bl xmlXPathEvalExpression\n mov r5,r0\n mov r0,r10\n bl xmlXPathFreeContext @ free context\n cmp r5,#0\n beq 100f\n ldr r4,[r5,#xmlPathObj_nodesetval] @ values set\n ldr r6,[r4,#xmlNodeSet_nodeNr] @ set size\n mov r7,#0 @ index\n ldr r4,[r4,#xmlNodeSet_nodeTab] @ area of nods\n1: @ start loop \n ldr r3,[r4,r7,lsl #2] @ load node\n mov r0,r9\n ldr r1,[r3,#xmlNode_children] @ load string value\n mov r2,#1\n bl xmlNodeListGetString\n str r0,[r8,r7,lsl #2] @ store string pointer in area\n bl affichageMess @ and display string result\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n add r7,#1\n cmp r7,r6\n blt 1b\n100:\n pop {r1-r10,lr} @ restaur registers *\/ \n bx lr @ return \n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur registers *\/ \n bx lr @ return\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":706} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program quickSort.s *\/\n\/* look pseudo code in wikipedia quicksort *\/\n\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessSortOk: .asciz \"Table sorted.\\n\"\nszMessSortNok: .asciz \"Table not sorted\u00a0!!!!!.\\n\"\nsMessResult: .ascii \"Value \u00a0: \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\nszCarriageReturn: .asciz \"\\n\"\n \n.align 4\niGraine: .int 123456\n.equ NBELEMENTS, 10\n#TableNumber:\t .int 9,5,6,1,2,3,10,8,4,7\n#TableNumber:\t .int 1,3,5,2,4,6,10,8,4,7\n#TableNumber:\t .int 1,3,5,2,4,6,10,8,4,7\n#TableNumber:\t .int 1,2,3,4,5,6,10,8,4,7\nTableNumber:\t .int 10,9,8,7,6,5,4,3,2,1\n#TableNumber:\t .int 13,12,11,10,9,8,7,6,5,4,3,2,1\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n \n1:\n ldr r0,iAdrTableNumber @ address number table\n\n mov r1,#0 @ indice first item\n mov r2,#NBELEMENTS @ number of \u00e9lements \n bl triRapide @ call quicksort\n ldr r0,iAdrTableNumber @ address number table\n bl displayTable\n \n ldr r0,iAdrTableNumber @ address number table\n mov r1,#NBELEMENTS @ number of \u00e9lements \n bl isSorted @ control sort\n cmp r0,#1 @ sorted\u00a0?\n beq 2f \n ldr r0,iAdrszMessSortNok @ no\u00a0!! error sort\n bl affichageMess\n b 100f\n2: @ yes\n ldr r0,iAdrszMessSortOk\n bl affichageMess\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrsMessValeur: .int sMessValeur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdrTableNumber: .int TableNumber\niAdrszMessSortOk: .int szMessSortOk\niAdrszMessSortNok: .int szMessSortNok\n\/******************************************************************\/\n\/* control sorted table *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains the number of elements > 0 *\/\n\/* r0 return 0 if not sorted 1 if sorted *\/\nisSorted:\n push {r2-r4,lr} @ save registers\n mov r2,#0\n ldr r4,[r0,r2,lsl #2]\n1:\n add r2,#1\n cmp r2,r1\n movge r0,#1\n bge 100f\n ldr r3,[r0,r2, lsl #2]\n cmp r3,r4\n movlt r0,#0\n blt 100f\n mov r4,r3\n b 1b\n100:\n pop {r2-r4,lr}\n bx lr @ return \n\n\n\/***************************************************\/\n\/* Appel r\u00e9cursif Tri Rapide quicksort *\/\n\/***************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains index of first item *\/\n\/* r2 contains the number of elements > 0 *\/\ntriRapide:\n push {r2-r5,lr} @ save registers\n sub r2,#1 @ last item index\n cmp r1,r2 @ first > last\u00a0? \n bge 100f @ yes -> end\n mov r4,r0 @ save r0\n mov r5,r2 @ save r2\n bl partition1 @ cutting into 2 parts\n mov r2,r0 @ index partition\n mov r0,r4 @ table address\n bl triRapide @ sort lower part\n add r1,r2,#1 @ index begin = index partition + 1\n add r2,r5,#1 @ number of elements\n bl triRapide @ sort higter part\n \n 100: @ end function\n pop {r2-r5,lr} @ restaur registers \n bx lr @ return\n\n\n\/******************************************************************\/\n\/* Partition table elements *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains index of first item *\/\n\/* r2 contains index of last item *\/\n\npartition1:\n push {r1-r7,lr} @ save registers\n ldr r3,[r0,r2,lsl #2] @ load value last index\n mov r4,r1 @ init with first index\n mov r5,r1 @ init with first index\n1: @ begin loop\n ldr r6,[r0,r5,lsl #2] @ load value\n cmp r6,r3 @ compare value\n ldrlt r7,[r0,r4,lsl #2] @ if < swap value table\n strlt r6,[r0,r4,lsl #2]\n strlt r7,[r0,r5,lsl #2]\n addlt r4,#1 @ and increment index 1\n add r5,#1 @ increment index 2\n cmp r5,r2 @ end\u00a0?\n blt 1b @ no loop\n ldr r7,[r0,r4,lsl #2] @ swap value\n str r3,[r0,r4,lsl #2]\n str r7,[r0,r2,lsl #2]\n mov r0,r4 @ return index partition\n100:\n pop {r1-r7,lr}\n bx lr\n\n\/******************************************************************\/\n\/* Display table elements *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\ndisplayTable:\n push {r0-r3,lr} @ save registers\n mov r2,r0 @ table address\n mov r3,#0\n1: @ loop display table\n ldr r0,[r2,r3,lsl #2]\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n add r3,#1\n cmp r3,#NBELEMENTS - 1\n ble 1b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n100:\n pop {r0-r3,lr}\n bx lr\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal unsigned *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\n\/* r0 return size of result (no zero final in area) *\/\n\/* area size => 11 bytes *\/\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n \n1:\t @ start loop\n bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b\t @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n \n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n \n\/***************************************************\/\n\/* division par 10 unsigned *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n \/\/mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3\n \/\/movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: \t.int 0xCCCCCCCD\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":707} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program dateFormat.s *\/\n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\n\/*******************************************\/\n\/* Constantes *\/\n\/*******************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ BRK, 0x2d @ Linux syscall\n.equ CHARPOS, '@'\n\n.equ GETTIME, 0x4e @ call system linux gettimeofday\n\n\/*******************************************\/\n\/* Structures *\/\n\/********************************************\/\n\/* example structure time *\/\n .struct 0\ntimeval_sec: @\n .struct timeval_sec + 4 \ntimeval_usec: @\n .struct timeval_usec + 4 \ntimeval_end:\n .struct 0\ntimezone_min: @\n .struct timezone_min + 4 \ntimezone_dsttime: @ \n .struct timezone_dsttime + 4 \ntimezone_end:\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessError: .asciz \"Error detected\u00a0!!!!. \\n\"\nszMessResult: .asciz \"Date\u00a0: @\/@\/@ \\n\" @ message result\nszMessResult1: .asciz \"Date day\u00a0: @ @ @ @ \\n\" @ message result\nszJan: .asciz \"Janvier\"\nszFev: .asciz \"F\u00e9vrier\"\nszMars: .asciz \"Mars\"\nszAvril: .asciz \"Avril\"\nszMai: .asciz \"Mai\"\nszJuin: .asciz \"Juin\"\nszJuil: .asciz \"Juillet\"\nszAout: .asciz \"Aout\"\nszSept: .asciz \"Septembre\"\nszOct: .asciz \"Octobre\"\nszNov: .asciz \"Novembre\"\nszDec: .asciz \"D\u00e9cembre\"\nszLundi: .asciz \"Lundi\"\nszMardi: .asciz \"Mardi\"\nszMercredi: .asciz \"Mercredi\"\nszJeudi: .asciz \"Jeudi\"\nszVendredi: .asciz \"Vendredi\"\nszSamedi: .asciz \"Samedi\"\nszDimanche: .asciz \"Dimanche\"\nszCarriageReturn: .asciz \"\\n\"\n.align 4\ntbDayMonthYear: .int 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335\n .int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700\n .int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065\n .int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430\ntbMonthName: .int szJan\n .int szFev\n .int szMars\n .int szAvril\n .int szMai\n .int szJuin\n .int szJuil\n .int szAout\n .int szSept\n .int szOct\n .int szNov\n .int szDec\ntbDayName: .int szLundi\n .int szMardi\n .int szMercredi\n .int szJeudi\n .int szVendredi\n .int szSamedi\n .int szDimanche\n\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n.align 4\nstTVal: .skip timeval_end\nstTZone: .skip timezone_end\nsZoneConv: .skip 100\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdrstTVal\n ldr r1,iAdrstTZone\n mov r7,#GETTIME\n svc 0\n cmp r0,#-1 @ error\u00a0?\n beq 99f\n ldr r1,iAdrstTVal\n ldr r0,[r1,#timeval_sec] @ timestemp in second\n bl dateFormatNum\n ldr r0,[r1,#timeval_sec] @ timestemp in second\n bl dateFormatAlpha\n ldr r0,iTStest1\n bl dateFormatNum\n ldr r0,iTStest1\n bl dateFormatAlpha\n ldr r0,iTStest2\n bl dateFormatNum\n ldr r0,iTStest2\n bl dateFormatAlpha\n ldr r0,iTStest3\n bl dateFormatNum\n ldr r0,iTStest3\n bl dateFormatAlpha\n b 100f\n99:\n ldr r0,iAdrszMessError\n bl affichageMess \n100: @ standard end of the program \n mov r0,#0 @ return code\n mov r7,#EXIT @ request to exit program\n svc 0 @ perform the system call\n\niAdrszMessError: .int szMessError\niAdrstTVal: .int stTVal\niAdrstTZone: .int stTZone\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsZoneConv: .int sZoneConv\niTStest1: .int 1609508339 @ 01\/01\/2021\niTStest2: .int 1657805939 @ 14\/07\/2022\niTStest3: .int 1767221999 @ 31\/12\/2025\n\/******************************************************************\/\n\/* date format numeric *\/ \n\/******************************************************************\/\n\/* r0 contains the timestamp in seconds *\/\ndateFormatNum:\n push {r1-r11,lr} @ save registers \n ldr r2,iSecJan2020\n sub r0,r0,r2 @ total secondes to 01\/01\/2020\n mov r1,#60\n bl division\n mov r0,r2\n mov r6,r3 @ compute secondes\n mov r1,#60\n bl division\n mov r7,r3 @ compute minutes\n mov r0,r2\n mov r1,#24\n bl division\n mov r8,r3 @ compute hours\n mov r0,r2\n mov r11,r0\n mov r1,#(365 * 4 + 1)\n bl division\n lsl r9,r2,#2 @ multiply by 4 = year1\n mov r1,#(365 * 4 + 1)\n mov r0,r11\n bl division\n mov r10,r3\n\n ldr r1,iAdrtbDayMonthYear\n mov r2,#3\n mov r3,#12\n1:\n mul r11,r3,r2\n ldr r4,[r1,r11,lsl #2] @ load days by year\n cmp r10,r4\n bge 2f\n sub r2,r2,#1\n cmp r2,#0\n bne 1b\n2: @ r2 = year2\n mov r5,#11\n mul r11,r3,r2\n lsl r11,#2\n add r11,r1 @ table address \n3:\n ldr r4,[r11,r5,lsl #2] @ load days by month\n cmp r10,r4\n bge 4f\n subs r5,r5,#1\n bne 3b\n4: @ r5 = month - 1\n mul r11,r3,r2\n add r11,r5\n ldr r1,iAdrtbDayMonthYear\n ldr r3,[r1,r11,lsl #2]\n sub r0,r10,r3\n add r0,r0,#1 @ final compute day\n ldr r1,iAdrsZoneConv\n bl conversion10 @ this function do not zero final\n mov r11,#0 @ store zero final\n strb r11,[r1,r0]\n ldr r0,iAdrszMessResult\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at first @ character\n mov r3,r0\n add r0,r5,#1 @ final compute month\n cmp r0,#12\n subgt r0,#12\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r11,#0 @ store zero final\n strb r11,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at next @ character\n mov r3,r0\n ldr r11,iYearStart\n add r0,r9,r11\n add r0,r0,r2 @ final compute year = 2020 + year1 + year2\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r11,#0 @ store zero final\n strb r11,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at next @ character\n bl affichageMess \n100:\n pop {r1-r11,lr} @ restaur registers\n bx lr @ return\niAdrszMessResult: .int szMessResult\n\/******************************************************************\/\n\/* date format alphanumeric *\/ \n\/******************************************************************\/\n\/* r0 contains the timestamp in seconds *\/\ndateFormatAlpha:\n push {r1-r10,lr} @ save registers \n ldr r2,iSecJan2020\n sub r0,r0,r2 @ total secondes to 01\/01\/2020\n mov r6,r0\n mov r1,#60\n bl division\n mov r0,r2\n mov r1,#60\n bl division\n mov r0,r2\n mov r1,#24\n bl division\n mov r0,r2\n mov r8,r0\n mov r1,#(365 * 4 + 1)\n bl division\n lsl r9,r2,#2 @ multiply by 4 = year1\n mov r1,#(365 * 4 + 1)\n mov r0,r8\n bl division\n mov r10,r3 @ reste\n\n ldr r1,iAdrtbDayMonthYear\n mov r7,#3\n mov r3,#12\n1:\n mul r8,r3,r7\n ldr r4,[r1,r8,lsl #2] @ load days by year\n cmp r10,r4\n bge 2f\n sub r7,r7,#1\n cmp r7,#0\n bne 1b\n2: @ r7 = year2\n mov r5,#11\n mul r8,r3,r7\n lsl r8,#2\n add r8,r1\n3:\n ldr r4,[r8,r5,lsl #2] @ load days by month\n cmp r10,r4\n bge 4f\n subs r5,r5,#1\n bne 3b\n4: @ r5 = month - 1\n\n mov r0,r6 @ number secondes depuis 01\/01\/2020\n ldr r1,iNbSecByDay\n bl division\n mov r0,r2\n mov r1,#7\n bl division\n add r2,r3,#2\n cmp r2,#7\n subge r2,#7\n ldr r1,iAdrtbDayName\n ldr r1,[r1,r2,lsl #2]\n ldr r0,iAdrszMessResult1\n bl strInsertAtCharInc @ insert result at next @ character\n mov r3,r0\n mov r8,#12\n mul r11,r8,r7\n add r11,r5\n ldr r1,iAdrtbDayMonthYear\n ldr r8,[r1,r11,lsl #2]\n sub r0,r10,r8\n add r0,r0,#1 @ final compute day\n ldr r1,iAdrsZoneConv\n bl conversion10 @ this function do not zero final\n mov r8,#0 @ store zero final\n strb r8,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at first @ character\n mov r3,r0\n ldr r1,iAdrtbMonthName\n cmp r5,#12\n subge r5,#12\n ldr r1,[r1,r5,lsl #2] @ month name\n mov r0,r3\n bl strInsertAtCharInc @ insert result at first @ character\n mov r3,r0\n ldr r0,iYearStart\n add r0,r7\n add r0,r9 @ final compute year = 2020 + year1 + year2\n\n ldr r1,iAdrsZoneConv\n bl conversion10 @ this function do not zero final\n mov r8,#0 @ store zero final\n strb r8,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at first @ character\n bl affichageMess \n100:\n pop {r1-r10,lr} @ restaur registers\n bx lr @ return\niAdrszMessResult1: .int szMessResult1\niSecJan2020: .int 1577836800\niAdrtbDayMonthYear: .int tbDayMonthYear\niYearStart: .int 2020\niAdrtbMonthName: .int tbMonthName\niAdrtbDayName: .int tbDayName\niNbSecByDay: .int 3600 * 24\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":708} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program areaString.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/* Initialized data *\/\n.data\nszMessStringsch: .ascii \"The string is at item\u00a0: \"\nsZoneconv:\t\t .fill 12,1,' '\nszCarriageReturn: .asciz \"\\n\"\nszMessStringNfound: .asciz \"The string is not found in this area.\\n\"\n\n\/* areas strings *\/\nszString1: .asciz \"Apples\"\nszString2: .asciz \"Oranges\"\nszString3: .asciz \"Pommes\"\nszString4: .asciz \"Raisins\"\nszString5: .asciz \"Abricots\"\n\n\/* pointer items area 1*\/\ntablesPoi1:\npt1_1:\t .int szString1\npt1_2:\t .int szString2\npt1_3:\t .int szString3\npt1_4:\t .int szString4\nptVoid_1: .int 0\nptVoid_2: .int 0\nptVoid_3: .int 0\nptVoid_4: .int 0\nptVoid_5: .int 0\n\nszStringSch:\t.asciz \"Raisins\"\nszStringSch1:\t.asciz \"Ananas\"\n\n\/* UnInitialized data *\/\n.bss \n\n\/* code section *\/\n.text\n.global main \nmain: \/* entry of program *\/\n push {fp,lr} \/* saves 2 registers *\/\n\t\n @@@@@@@@@@@@@@@@@@@@@@@@\n @ add string 5 to area\n @@@@@@@@@@@@@@@@@@@@@@@@\n ldr r1,iAdrtablesPoi1 @ begin pointer area 1\n mov r0,#0 @ counter\n1: @ search first void pointer\n ldr r2,[r1,r0,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)\n cmp r2,#0 @ is null\u00a0?\n addne r0,#1 @ no increment counter\n bne 1b @ and loop\n \n @ store pointer string 5 in area at position r0\n ldr r2,iAdrszString5 @ address string 5\n str r2,[r1,r0,lsl #2] @ store address \n\t\n @@@@@@@@@@@@@@@@@@@@@@@@\n @ display string at item 3\n @@@@@@@@@@@@@@@@@@@@@@@@\n mov r2,#2 @ pointers begin in position 0 \n ldr r1,iAdrtablesPoi1 @ begin pointer area 1\n ldr r0,[r1,r2,lsl #2]\n bl affichageMess\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n\t\n @@@@@@@@@@@@@@@@@@@@@@@@\n @ search string in area \n @@@@@@@@@@@@@@@@@@@@@@@@\n ldr r1,iAdrszStringSch\n \/\/ldr r1,iAdrszStringSch1 @ uncomment for other search\u00a0: not found\u00a0!!\n ldr r2,iAdrtablesPoi1 @ begin pointer area 1\n mov r3,#0 \n2: @ search \n ldr r0,[r2,r3,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)\n cmp r0,#0 @ is null\u00a0?\n beq 3f @ end search\n bl comparaison\n cmp r0,#0 @ string =\u00a0?\n addne r3,#1 @ no increment counter\n bne 2b @ and loop\n mov r0,r3 @ position item string\n ldr r1,iAdrsZoneconv @ conversion decimal\n bl conversion10S\n ldr r0,iAdrszMessStringsch\n bl affichageMess\n b 100f\n3: @ end search string not found\n ldr r0,iAdrszMessStringNfound\n bl affichageMess\n\t\n100: \/* standard end of the program *\/\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrtablesPoi1:\t\t.int tablesPoi1\niAdrszMessStringsch: .int szMessStringsch\niAdrszString5:\t\t.int szString5\niAdrszStringSch:\t.int szStringSch\niAdrszStringSch1: .int szStringSch1\niAdrsZoneconv: .int sZoneconv\niAdrszMessStringNfound: .int szMessStringNfound\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {fp,lr} \t\t\t\/* save registres *\/ \n push {r0,r1,r2,r7} \t\t\/* save others registers *\/\n mov r2,#0 \t\t\t\t\/* counter length *\/\n1: \t\/* loop length calculation *\/\n ldrb r1,[r0,r2] \t\t\t\/* read octet start position + index *\/\n cmp r1,#0 \t\t\t\/* if 0 its over *\/\n addne r2,r2,#1 \t\t\t\/* else add 1 in the length *\/\n bne 1b \t\t\t\/* and loop *\/\n \/* so here r2 contains the length of the message *\/\n mov r1,r0 \t\t\t\/* address message in r1 *\/\n mov r0,#STDOUT \t\t\/* code to write to the standard output Linux *\/\n mov r7, #WRITE \/* code call system \"write\" *\/\n swi #0 \/* call systeme *\/\n pop {r0,r1,r2,r7} \t\t\/* restaur others registers *\/\n pop {fp,lr} \t\t\t\t\/* restaur des 2 registres *\/ \n bx lr\t \t\t\t\/* return *\/\n\/***************************************************\/\n\/* conversion register signed d\u00e9cimal *\/\n\/***************************************************\/\n\/* r0 contient le registre *\/\n\/* r1 contient l adresse de la zone de conversion *\/\nconversion10S:\n push {r0-r5,lr} \/* save des registres *\/\n mov r2,r1 \/* debut zone stockage *\/\n mov r5,#'+' \/* par defaut le signe est + *\/\n cmp r0,#0 \/* nombre n\u00e9gatif\u00a0? *\/\n movlt r5,#'-' \/* oui le signe est - *\/\n mvnlt r0,r0 \/* et inversion en valeur positive *\/\n addlt r0,#1\n mov r4,#10 \/* longueur de la zone *\/\n1: \/* debut de boucle de conversion *\/\n bl divisionpar10 \/* division *\/\n add r1,#48 \/* ajout de 48 au reste pour conversion ascii *\/\t\n strb r1,[r2,r4] \/* stockage du byte en d\u00e9but de zone r5 + la position r4 *\/\n sub r4,r4,#1 \/* position pr\u00e9cedente *\/\n cmp r0,#0 \n bne 1b\t \/* boucle si quotient different de z\u00e9ro *\/\n strb r5,[r2,r4] \/* stockage du signe \u00e0 la position courante *\/\n subs r4,r4,#1 \/* position pr\u00e9cedente *\/\n blt 100f \/* si r4 < 0 fin *\/\n \/* sinon il faut completer le debut de la zone avec des blancs *\/\n mov r3,#' ' \/* caractere espace *\/\t\n2:\n strb r3,[r2,r4] \/* stockage du byte *\/\n subs r4,r4,#1 \/* position pr\u00e9cedente *\/\n bge 2b \/* boucle si r4 plus grand ou egal a zero *\/\n100: \/* fin standard de la fonction *\/\n pop {r0-r5,lr} \/*restaur desregistres *\/\n bx lr \n\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 contient le dividende *\/\n\/* r0 retourne le quotient *\/\t\n\/* r1 retourne le reste *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save registers *\/\n mov r4,r0 \n ldr r3, .Ls_magic_number_10 \/* r1 <- magic_number *\/\n smull r1, r2, r3, r0 \/* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) *\/\n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n bx lr \/* leave function *\/\n.Ls_magic_number_10: .word 0x66666667\n","human_summarization":"demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and includes the functionality of pushing a value into the array.","id":709} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program readwrtfile.s *\/\n\n\/*********************************************\/\n\/*constantes *\/\n\/********************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ READ, 3\n.equ WRITE, 4\n.equ OPEN, 5\n.equ CLOSE, 6\n.equ CREATE, 8\n\/* file *\/\n.equ O_RDWR,\t0x0002\t\t@ open for reading and writing \n\n.equ TAILLEBUF, 1000\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessErreur: .asciz \"Erreur ouverture fichier input.\\n\"\nszMessErreur4: .asciz \"Erreur cr\u00e9ation fichier output.\\n\"\nszMessErreur1: .asciz \"Erreur fermeture fichier.\\n\"\nszMessErreur2: .asciz \"Erreur lecture fichier.\\n\"\nszMessErreur3: .asciz \"Erreur d'\u00e9criture dans fichier de sortie.\\n\"\nszRetourligne: .asciz \"\\n\"\nszMessErr: .ascii\t\"Error code\u00a0: \"\nsDeci: .space 15,' '\n .asciz \"\\n\"\n\nszNameFileInput:\t.asciz \"input.txt\"\nszNameFile","human_summarization":"demonstrate reading the contents of \"input.txt\" file into a variable and then writing this variable's contents into a new file called \"output.txt\".","id":710} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program loopnplusone.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessResult: .ascii \"\" @ message result\nsMessValeur: .fill 11, 1, ' '\nszMessComma: .asciz \",\"\nszCarriageReturn: .asciz \"\\n\"\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n mov r4,#1 @ loop counter\n1: @ begin loop \n mov r0,r4\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ decimal conversion\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n ldr r0,iAdrszMessComma\n bl affichageMess @ display comma\n add r4,#1 @ increment counter\n cmp r4,#10 @ end\u00a0?\n blt 1b @ no ->begin loop one\n mov r0,r4\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ decimal conversion\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n ldr r0,iAdrszCarriageReturn\n bl affichageMess @ display return line\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrszMessResult: .int szMessResult\niAdrszMessComma: .int szMessComma\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur registers *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n\n1: @ start loop\n bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n sub r2,#1 @ previous position\n cmp r0,#0 @ stop if quotient = 0 \n bne 1b @ else loop\n @ end replaces digit in front of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2] \n strb r1,[r3,r4] @ store in area begin\n add r4,#1\n add r2,#1 @ previous position\n cmp r2,#LGZONECAL @ end\n ble 2b @ loop\n mov r1,#0 @ final zero \n strb r1,[r3,r4]\n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} @ save registers *\/\n mov r4,r0 \n mov r3,#0x6667 @ r3 <- magic_number lower\n movt r3,#0x6666 @ r3 <- magic_number upper\n smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) \n mov r2, r2, ASR #2 @ r2 <- r2 >> 2\n mov r1, r0, LSR #31 @ r1 <- r0 >> 31\n add r0, r2, r1 @ r0 <- r2 + r1 \n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2-r4}\n bx lr @ return\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":711} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program strMatching.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n\/* Initialized data *\/\n.data\nszMessFound: .asciz \"String found. \\n\" \nszMessNotFound: .asciz \"String not found. \\n\" \nszString: .asciz \"abcdefghijklmnopqrstuvwxyz\"\nszString2: .asciz \"abc\"\nszStringStart: .asciz \"abcd\"\nszStringEnd: .asciz \"xyz\"\nszStringStart2: .asciz \"abcd\"\nszStringEnd2: .asciz \"xabc\"\nszCarriageReturn: .asciz \"\\n\"\n\n\/* UnInitialized data *\/\n.bss \n\n\/* code section *\/\n.text\n.global main \nmain: \n\n ldr r0,iAdrszString @ address input string\n ldr r1,iAdrszStringStart @ address search string\n\n bl searchStringDeb @ Determining if the first string starts with second string\n cmp r0,#0\n ble 1f\n ldr r0,iAdrszMessFound @ display message\n bl affichageMess\n b 2f\n1:\n ldr r0,iAdrszMessNotFound\n bl affichageMess\n2:\n ldr r0,iAdrszString @ address input string\n ldr r1,iAdrszStringEnd @ address search string\n bl searchStringFin @ Determining if the first string ends with the second string\n cmp r0,#0\n ble 3f\n ldr r0,iAdrszMessFound @ display message\n bl affichageMess\n b 4f\n3:\n ldr r0,iAdrszMessNotFound\n bl affichageMess\n4:\n ldr r0,iAdrszString2 @ address input string\n ldr r1,iAdrszStringStart2 @ address search string\n\n bl searchStringDeb @ \n cmp r0,#0\n ble 5f\n ldr r0,iAdrszMessFound @ display message\n bl affichageMess\n b 6f\n5:\n ldr r0,iAdrszMessNotFound\n bl affichageMess\n6:\n ldr r0,iAdrszString2 @ address input string\n ldr r1,iAdrszStringEnd2 @ address search string\n bl searchStringFin\n cmp r0,#0\n ble 7f\n ldr r0,iAdrszMessFound @ display message\n bl affichageMess\n b 8f\n7:\n ldr r0,iAdrszMessNotFound\n bl affichageMess\n8:\n ldr r0,iAdrszString @ address input string\n ldr r1,iAdrszStringEnd @ address search string\n bl searchSubString @ Determining if the first string contains the second string at any location\n cmp r0,#0\n ble 9f\n ldr r0,iAdrszMessFound @ display message\n bl affichageMess\n b 10f\n9:\n ldr r0,iAdrszMessNotFound @ display substring result\n bl affichageMess\n10:\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\niAdrszMessFound: .int szMessFound\niAdrszMessNotFound: .int szMessNotFound\niAdrszString: .int szString\niAdrszString2: .int szString2\niAdrszStringStart: .int szStringStart\niAdrszStringEnd: .int szStringEnd\niAdrszStringStart2: .int szStringStart2\niAdrszStringEnd2: .int szStringEnd2\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* search substring at begin of input string *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the input string *\/\n\/* r1 contains the address of substring *\/\n\/* r0 returns 1 if find or 0 if not or -1 if error *\/\nsearchStringDeb:\n push {r1-r4,lr} @ save registers \n mov r3,#0 @ counter byte string \n ldrb r4,[r1,r3] @ load first byte of substring\n cmp r4,#0 @ empty string\u00a0?\n moveq r0,#-1 @ error\n beq 100f\n1:\n ldrb r2,[r0,r3] @ load byte string input\n cmp r2,#0 @ zero final\u00a0?\n moveq r0,#0 @ not find\n beq 100f\n cmp r4,r2 @ bytes equals\u00a0?\n movne r0,#0 @ no not find\n bne 100f\n add r3,#1 @ increment counter\n ldrb r4,[r1,r3] @ and load next byte of substring\n cmp r4,#0 @ zero final\u00a0?\n bne 1b @ no -> loop\n mov r0,#1 @ yes is ok \n100:\n pop {r1-r4,lr} @ restaur registers\n bx lr @ return\n\n\/******************************************************************\/\n\/* search substring at end of input string *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the input string *\/\n\/* r1 contains the address of substring *\/\n\/* r0 returns 1 if find or 0 if not or -1 if error *\/\nsearchStringFin:\n push {r1-r5,lr} @ save registers \n mov r3,#0 @ counter byte string \n @ search the last character of substring\n1: \n ldrb r4,[r1,r3] @ load byte of substring\n cmp r4,#0 @ zero final\u00a0?\n addne r3,#1 @ no increment counter\n bne 1b @ and loop\n cmp r3,#0 @ empty string\u00a0?\n moveq r0,#-1 @ error\n beq 100f\n sub r3,#1 @ index of last byte\n ldrb r4,[r1,r3] @ load last byte of substring\n @ search the last character of string\n mov r2,#0 @ index last character\n2: \n ldrb r5,[r0,r2] @ load first byte of substring\n cmp r5,#0 @ zero final\u00a0?\n addne r2,#1 @ no -> increment counter\n bne 2b @ and loop\n cmp r2,#0 @ empty input string\u00a0?\n moveq r0,#0 @ yes -> not found\n beq 100f\n sub r2,#1 @ index last character\n3:\n ldrb r5,[r0,r2] @ load byte string input\n cmp r4,r5 @ bytes equals\u00a0?\n movne r0,#0 @ no -> not found\n bne 100f\n subs r3,#1 @ decrement counter\n movlt r0,#1 @ if zero -> ok found\n blt 100f \n subs r2,#1 @ decrement counter input string\n movlt r0,#0 @ if zero -> not found\n blt 100f\n ldrb r4,[r1,r3] @ load previous byte of substring\n b 3b @ and loop\n \n100:\n pop {r1-r5,lr} @ restaur registers\n bx lr @ return\n\n\/******************************************************************\/\n\/* search a substring in the string *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the input string *\/\n\/* r1 contains the address of substring *\/\n\/* r0 returns index of substring in string or -1 if not found *\/\nsearchSubString:\n push {r1-r6,lr} @ save registers \n mov r2,#0 @ counter byte input string\n mov r3,#0 @ counter byte string \n mov r6,#-1 @ index found\n ldrb r4,[r1,r3]\n1:\n ldrb r5,[r0,r2] @ load byte string \n cmp r5,#0 @ zero final\u00a0?\n moveq r0,#-1 @ yes returns error\n beq 100f\n cmp r5,r4 @ compare character \n beq 2f\n mov r6,#-1 @ no equals - > raz index \n mov r3,#0 @ and raz counter byte\n add r2,#1 @ and increment counter byte\n b 1b @ and loop\n2: @ characters equals\n cmp r6,#-1 @ first characters equals\u00a0?\n moveq r6,r2 @ yes -> index begin in r6\n add r3,#1 @ increment counter substring\n ldrb r4,[r1,r3] @ and load next byte\n cmp r4,#0 @ zero final\u00a0?\n beq 3f @ yes -> end search\n add r2,#1 @ else increment counter string\n b 1b @ and loop\n3:\n mov r0,r6\n100:\n pop {r1-r6,lr} @ restaur registers\n bx lr \n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registers \n mov r2,#0 @ counter length *\/\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call system\n pop {r0,r1,r2,r7,lr} @ restaur registers\n bx lr @ return\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":712} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program square4.s *\/\n \n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n.equ NBBOX, 7\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nsMessDeb: .ascii \"a=\"\nsMessValeur_a: .fill 11, 1, ' ' @ size => 11\n .ascii \"b=\"\nsMessValeur_b: .fill 11, 1, ' ' @ size => 11\n .ascii \"c=\"\nsMessValeur_c: .fill 11, 1, ' ' @ size => 11\n .ascii \"d=\"\nsMessValeur_d: .fill 11, 1, ' ' @ size => 11\n .ascii \"\\n\"\n .ascii \"e=\"\nsMessValeur_e: .fill 11, 1, ' ' @ size => 11\n .ascii \"f=\"\nsMessValeur_f: .fill 11, 1, ' ' @ size => 11\n .ascii \"g=\"\nsMessValeur_g: .fill 11, 1, ' ' @ size => 11\n\nszCarriageReturn: .asciz \"\\n************************\\n\"\n\nsMessNbSolution: .ascii \"Number of solutions\u00a0:\"\nsMessCounter: .fill 11, 1, ' ' @ size => 11\n .asciz \"\\n\\n\\n\"\n\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n.align 4\niValues_a: .skip 4 * NBBOX\niValues_b: .skip 4 * NBBOX - 1\niValues_c: .skip 4 * NBBOX - 2\niValues_d: .skip 4 * NBBOX - 3\niValues_e: .skip 4 * NBBOX - 4\niValues_f: .skip 4 * NBBOX - 5\niValues_g: .skip 4 * NBBOX - 6\niCounterSol: .skip 4\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n mov r0,#1\n mov r1,#7\n mov r2,#3 @ 0 = rien 1 = display 2 = count 3 = les deux\n bl searchPb\n mov r0,#3\n mov r1,#9\n mov r2,#3 @ 0 = rien 1 = display 2 = count 3 = les deux\n bl searchPb\n mov r0,#0\n mov r1,#9\n mov r2,#2 @ 0 = rien 1 = display 2 = count 3 = les deux\n bl prepSearchNU\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\n\n\/******************************************************************\/\n\/* search probl\u00e8m value not unique *\/ \n\/******************************************************************\/\n\/* r0 contains start digit *\/\n\/* r1 contains end digit *\/\n\/* r2 contains action (0 display 1 count) *\/\nprepSearchNU:\n push {r3-r12,lr} @ save registers\n mov r5,#0 @ counter\n mov r12,r0 @ a\n1:\n mov r11,r0 @ b\n2:\n mov r10,r0 @ c\n3:\n mov r9,r0 @ d\n4:\n add r4,r12,r11 @ a + b reference\n add r3,r11,r10\n add r3,r9 @ b + c + d\n cmp r4,r3\n bne 10f\n mov r8,r0 @ e\n5:\n mov r7,r0 @ f\n6:\n add r3,r9,r8\n add r3,r7 @ d + e + f\n cmp r3,r4\n bne 9f\n mov r6,r0 @ g\n7:\n add r3,r7,r6 @ f + g\n cmp r3,r4\n bne 8f @ not OK\n @ OK\n add r5,#1 @ increment counter\n\n8:\n add r6,#1 @ increment g\n cmp r6,r1\n ble 7b\n9:\n add r7,#1 @ increment f\n cmp r7,r1\n ble 6b\n add r8,#1 @ increment e\n cmp r8,r1\n ble 5b\n10:\n add r9,#1 @ increment d\n cmp r9,r1\n ble 4b\n add r10,#1 @ increment c\n cmp r10,r1\n ble 3b\n add r11,#1 @ increment b\n cmp r11,r1\n ble 2b\n add r12,#1 @ increment a\n cmp r12,r1\n ble 1b\n\n @ end\n tst r2,#0b10 @ print count\u00a0?\n beq 100f\n mov r0,r5 @ counter\n ldr r1,iAdrsMessCounter\n bl conversion10\n ldr r0,iAdrsMessNbSolution\n bl affichageMess\n\n100:\n pop {r3-r12,lr} @ restaur registers \n bx lr @return\niAdrsMessCounter: .int sMessCounter\niAdrsMessNbSolution: .int sMessNbSolution\n\n\/******************************************************************\/\n\/* search problem unique solution *\/ \n\/******************************************************************\/\n\/* r0 contains start digit *\/\n\/* r1 contains end digit *\/\n\/* r2 contains action (0 display 1 count) *\/\nsearchPb:\n push {r0-r12,lr} @ save registers\n @ init\n ldr r3,iAdriValues_a @ area value a\n mov r4,#0\n1: @ loop init value a\n str r0,[r3,r4,lsl #2]\n add r4,#1\n add r0,#1\n cmp r0,r1\n ble 1b\n\n mov r5,#0 @ solution counter\n mov r12,#-1\n2:\n add r12,#1 @ increment indice a\n cmp r12,#NBBOX-1\n bgt 90f\n ldr r0,iAdriValues_a @ area value a\n ldr r1,iAdriValues_b @ area value b\n mov r2,r12 @ indice a\n mov r3,#NBBOX @ number of origin values \n bl prepValues\n mov r11,#-1\n3:\n add r11,#1 @ increment indice b\n cmp r11,#NBBOX - 2\n bgt 2b\n ldr r0,iAdriValues_b @ area value b\n ldr r1,iAdriValues_c @ area value c\n mov r2,r11 @ indice b\n mov r3,#NBBOX -1 @ number of origin values\n bl prepValues\n mov r10,#-1\n4:\n add r10,#1\n cmp r10,#NBBOX - 3\n bgt 3b\n ldr r0,iAdriValues_c\n ldr r1,iAdriValues_d\n mov r2,r10\n mov r3,#NBBOX - 2\n bl prepValues\n mov r9,#-1\n5:\n add r9,#1\n cmp r9,#NBBOX - 4\n bgt 4b\n @ control 2 firsts squares\n ldr r0,iAdriValues_a\n ldr r0,[r0,r12,lsl #2]\n ldr r1,iAdriValues_b\n ldr r1,[r1,r11,lsl #2]\n add r4,r0,r1 @ a + b value first square\n ldr r0,iAdriValues_c\n ldr r0,[r0,r10,lsl #2]\n add r7,r1,r0 @ b + c\n ldr r1,iAdriValues_d\n ldr r1,[r1,r9,lsl #2]\n add r7,r1 @ b + c + d\n cmp r7,r4 @ equal first square\u00a0?\n bne 5b\n ldr r0,iAdriValues_d\n ldr r1,iAdriValues_e\n mov r2,r9\n mov r3,#NBBOX - 3\n bl prepValues\n mov r8,#-1\n6:\n add r8,#1\n cmp r8,#NBBOX - 5\n bgt 5b\n ldr r0,iAdriValues_e\n ldr r1,iAdriValues_f\n mov r2,r8\n mov r3,#NBBOX - 4\n bl prepValues\n mov r7,#-1\n7:\n add r7,#1\n cmp r7,#NBBOX - 6\n bgt 6b\n ldr r0,iAdriValues_d\n ldr r0,[r0,r9,lsl #2]\n ldr r1,iAdriValues_e\n ldr r1,[r1,r8,lsl #2]\n add r3,r0,r1 @ d + e\n ldr r1,iAdriValues_f\n ldr r1,[r1,r7,lsl #2]\n add r3,r1 @ de + e + f\n cmp r3,r4 @ equal first square\u00a0?\n bne 7b\n ldr r0,iAdriValues_f\n ldr r1,iAdriValues_g\n mov r2,r7\n mov r3,#NBBOX - 5\n bl prepValues\n mov r6,#-1\n8:\n add r6,#1\n cmp r6,#NBBOX - 7\n bgt 7b\n ldr r0,iAdriValues_f\n ldr r0,[r0,r7,lsl #2]\n ldr r1,iAdriValues_g\n ldr r1,[r1,r6,lsl #2]\n add r3,r0,r1 @ f +g \n cmp r4,r3 @ equal first square\u00a0?\n bne 8b\n add r5,#1 @ increment counter\n ldr r0,[sp,#8] @ load action for two parameter in stack\n tst r0,#0b1\n beq 9f @ display solution\u00a0?\n ldr r0,iAdriValues_a\n ldr r0,[r0,r12,lsl #2]\n ldr r1,iAdrsMessValeur_a\n bl conversion10\n ldr r0,iAdriValues_b\n ldr r0,[r0,r11,lsl #2]\n ldr r1,iAdrsMessValeur_b\n bl conversion10\n ldr r0,iAdriValues_c\n ldr r0,[r0,r10,lsl #2]\n ldr r1,iAdrsMessValeur_c\n bl conversion10\n ldr r0,iAdriValues_d\n ldr r0,[r0,r9,lsl #2]\n ldr r1,iAdrsMessValeur_d\n bl conversion10\n ldr r0,iAdriValues_e\n ldr r0,[r0,r8,lsl #2]\n ldr r1,iAdrsMessValeur_e\n bl conversion10\n ldr r0,iAdriValues_f\n ldr r0,[r0,r7,lsl #2]\n ldr r1,iAdrsMessValeur_f\n bl conversion10\n ldr r0,iAdriValues_g\n ldr r0,[r0,r6,lsl #2]\n ldr r1,iAdrsMessValeur_g\n bl conversion10\n ldr r0,iAdrsMessDeb\n bl affichageMess\n9:\n b 8b @ suite \n\n90:\n ldr r0,[sp,#8] @ load action for two parameter in stack\n tst r0,#0b10\n beq 100f @ display counter\u00a0?\n mov r0,r5\n ldr r1,iAdrsMessCounter\n bl conversion10\n ldr r0,iAdrsMessNbSolution\n bl affichageMess\n100:\n pop {r0-r12,lr} @ restaur registers \n bx lr @return\niAdriValues_a: .int iValues_a\niAdriValues_b: .int iValues_b\niAdriValues_c: .int iValues_c\niAdriValues_d: .int iValues_d\niAdriValues_e: .int iValues_e\niAdriValues_f: .int iValues_f\niAdriValues_g: .int iValues_g\n\niAdrsMessValeur_a: .int sMessValeur_a\niAdrsMessValeur_b: .int sMessValeur_b\niAdrsMessValeur_c: .int sMessValeur_c\niAdrsMessValeur_d: .int sMessValeur_d\niAdrsMessValeur_e: .int sMessValeur_e\niAdrsMessValeur_f: .int sMessValeur_f\niAdrsMessValeur_g: .int sMessValeur_g\niAdrsMessDeb: .int sMessDeb\niAdriCounterSol: .int iCounterSol\n\/******************************************************************\/\n\/* copy value area and substract value of indice *\/ \n\/******************************************************************\/\n\/* r0 contains the address of values origin *\/\n\/* r1 contains the address of values destination *\/\n\/* r2 contains value indice to substract *\/\n\/* r3 contains origin values number *\/\nprepValues:\n push {r1-r6,lr} @ save registres\n mov r4,#0 @ indice origin value\n mov r5,#0 @ indice destination value\n1:\n cmp r4,r2 @ substract indice\u00a0?\n beq 2f @ yes -> jump\n ldr r6,[r0,r4,lsl #2] @ no -> copy value\n str r6,[r1,r5,lsl #2]\n add r5,#1 @ increment destination indice\n2:\n add r4,#1 @ increment origin indice\n cmp r4,r3 @ end\u00a0?\n blt 1b\n100:\n pop {r1-r6,lr} @ restaur registres \n bx lr @return\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal unsigned *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\n\/* r0 return size of result (no zero final in area) *\/\n\/* area size => 11 bytes *\/\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n1: @ start loop\n bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n \n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n \n\/***************************************************\/\n\/* division par 10 unsigned *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\n\/* r1 remainder *\/\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: \t.int 0xCCCCCCCD\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":713} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program defList.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ READ, 3\n.equ WRITE, 4\n\n.equ NBELEMENTS, 100 @ list size\n\n\/*******************************************\/\n\/* Structures *\/\n\/********************************************\/\n\/* structure linkedlist*\/\n .struct 0\nllist_next: @ next element\n .struct llist_next + 4 \nllist_value: @ element value\n .struct llist_value + 4 \nllist_fin:\n\/* Initialized data *\/\n.data\nszMessInitListe: .asciz \"List initialized.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\/* datas error display *\/\nszMessErreur: .asciz \"Error detected.\\n\"\n\n\/* UnInitialized data *\/\n.bss \nlList1: .skip llist_fin * NBELEMENTS @ list memory place \n\n\/* code section *\/\n.text\n.global main \nmain: \n ldr r0,iAdrlList1\n mov r1,#0\n str r1,[r0,#llist_next]\n ldr r0,iAdrszMessInitListe\n bl affichageMess\n\n100: @ standard end of the program\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\niAdrszMessInitListe: .int szMessInitListe\niAdrszMessErreur: .int szMessErreur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrlList1: .int lList1\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registers \n mov r2,#0 @ counter length *\/\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call system\n pop {r0,r1,r2,r7,lr} @ restaur registers\n bx lr @ return\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":714} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program factorst.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/* Initialized data *\/\n.data\nszMessDeb: .ascii \"Factors of\u00a0:\"\nsMessValeur: .fill 12, 1, ' '\n .asciz \"are\u00a0: \\n\"\nsMessFactor: .fill 12, 1, ' '\n .asciz \"\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\n\/* UnInitialized data *\/\n.bss \n\n\/* code section *\/\n.text\n.global main \nmain: \/* entry of program *\/\n push {fp,lr} \/* saves 2 registers *\/\n \n mov r0,#100\n bl factors\n mov r0,#97\n bl factors\n ldr r0,iNumber\n bl factors\n\n \n100: \/* standard end of the program *\/\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\n\niNumber: .int 32767\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* calcul factors of number *\/ \n\/******************************************************************\/\n\/* r0 contains the number *\/\nfactors:\n push {fp,lr} \t\t\t\/* save registres *\/ \n push {r1-r6} \t\t\/* save others registers *\/\n mov r5,r0 @ limit calcul\n ldr r1,iAdrsMessValeur @ conversion register in decimal string\n bl conversion10S\n ldr r0,iAdrszMessDeb @ display message\n bl affichageMess\n mov r6,#1 @ counter loop\n1: @ loop \n mov r0,r5 @ dividende\n mov r1,r6 @ divisor\n bl division\n cmp r3,#0 @ remainder = zero\u00a0?\n bne 2f\n @ display result if yes\n mov r0,r6\n ldr r1,iAdrsMessFactor\n bl conversion10S\n ldr r0,iAdrsMessFactor\n bl affichageMess\n2:\n add r6,#1 @ add 1 to loop counter\n cmp r6,r5 @ <= number\u00a0?\n ble 1b @ yes loop\n100:\n pop {r1-r6} \t\t\/* restaur others registers *\/\n pop {fp,lr} \t\t\t\t\/* restaur des 2 registres *\/ \n bx lr\t \t\t\t\/* return *\/\niAdrsMessValeur: .int sMessValeur\niAdrszMessDeb: .int szMessDeb\niAdrsMessFactor: .int sMessFactor\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {fp,lr} \t\t\t\/* save registres *\/ \n push {r0,r1,r2,r7} \t\t\/* save others registers *\/\n mov r2,#0 \t\t\t\t\/* counter length *\/\n1: \t\/* loop length calculation *\/\n ldrb r1,[r0,r2] \t\t\t\/* read octet start position + index *\/\n cmp r1,#0 \t\t\t\/* if 0 its over *\/\n addne r2,r2,#1 \t\t\t\/* else add 1 in the length *\/\n bne 1b \t\t\t\/* and loop *\/\n \/* so here r2 contains the length of the message *\/\n mov r1,r0 \t\t\t\/* address message in r1 *\/\n mov r0,#STDOUT \t\t\/* code to write to the standard output Linux *\/\n mov r7, #WRITE \/* code call system \"write\" *\/\n swi #0 \/* call systeme *\/\n pop {r0,r1,r2,r7} \t\t\/* restaur others registers *\/\n pop {fp,lr} \t\t\t\t\/* restaur des 2 registres *\/ \n bx lr\t \t\t\t\/* return *\/\n\/*=============================================*\/\n\/* division integer unsigned *\/\n\/*============================================*\/\ndivision:\n \/* r0 contains N *\/\n \/* r1 contains D *\/\n \/* r2 contains Q *\/\n \/* r3 contains R *\/\n push {r4, lr}\n mov r2, #0 \/* r2\u00a0? 0 *\/\n mov r3, #0 \/* r3\u00a0? 0 *\/\n mov r4, #32 \/* r4\u00a0? 32 *\/\n b 2f\n1:\n movs r0, r0, LSL #1 \/* r0\u00a0? r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) *\/\n adc r3, r3, r3 \/* r3\u00a0? r3 + r3 + C. This is equivalent to r3\u00a0? (r3 << 1) + C *\/\n \n cmp r3, r1 \/* compute r3 - r1 and update cpsr *\/\n subhs r3, r3, r1 \/* if r3 >= r1 (C=1) then r3\u00a0? r3 - r1 *\/\n adc r2, r2, r2 \/* r2\u00a0? r2 + r2 + C. This is equivalent to r2\u00a0? (r2 << 1) + C *\/\n2:\n subs r4, r4, #1 \/* r4\u00a0? r4 - 1 *\/\n bpl 1b \/* if r4 >= 0 (N=0) then branch to .Lloop1 *\/\n \n pop {r4, lr}\n bx lr\t\n\n\/***************************************************\/\n\/* conversion register in string d\u00e9cimal signed *\/\n\/***************************************************\/\n\/* r0 contains the register *\/\n\/* r1 contains address of conversion area *\/\nconversion10S:\n push {fp,lr} \/* save registers frame and return *\/\n push {r0-r5} \/* save other registers *\/\n mov r2,r1 \/* early storage area *\/\n mov r5,#'+' \/* default sign is + *\/\n cmp r0,#0 \/* n\u00e9gatif number\u00a0? *\/\n movlt r5,#'-' \/* yes sign is - *\/\n mvnlt r0,r0 \/* and inverse in positive value *\/\n addlt r0,#1\n mov r4,#10 \/* area length *\/\n1: \/* conversion loop *\/\n bl divisionpar10 \/* division *\/\n add r1,#48 \/* add 48 at remainder for conversion ascii *\/\t\n strb r1,[r2,r4] \/* store byte area r5 + position r4 *\/\n sub r4,r4,#1 \/* previous position *\/\n cmp r0,#0 \n bne 1b\t \/* loop if quotient not equal z\u00e9ro *\/\n strb r5,[r2,r4] \/* store sign at current position *\/\n subs r4,r4,#1 \/* previous position *\/\n blt 100f \/* if r4 < 0 end *\/\n \/* else complete area with space *\/\n mov r3,#' ' \/* character space *\/\t\n2:\n strb r3,[r2,r4] \/* store byte *\/\n subs r4,r4,#1 \/* previous position *\/\n bge 2b \/* loop if r4 greather or equal zero *\/\n100: \/* standard end of function *\/\n pop {r0-r5} \/*restaur others registers *\/\n pop {fp,lr} \/* restaur des 2 registers frame et return *\/\n bx lr \n\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 contient le dividende *\/\n\/* r0 retourne le quotient *\/\t\n\/* r1 retourne le reste *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save autres registres *\/\n mov r4,r0 \n ldr r3, .Ls_magic_number_10 \/* r1 <- magic_number *\/\n smull r1, r2, r3, r0 \/* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) *\/\n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n .align 4\n.Ls_magic_number_10: .word 0x66666667\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":715} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI *\/\n\/* program alignColumn.s *\/\n \n \/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n.equ BUFFERSIZE, 20 * 10\n \n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessLeft: .asciz \"LEFT\u00a0:\\n\"\nszMessRight: .asciz \"\\nRIGHT\u00a0:\\n\" \nszMessCenter: .asciz \"\\nCENTER\u00a0:\\n\" \nszCarriageReturn: .asciz \"\\n\"\n\nszLine1: .asciz \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\nszLine2: .asciz \"are$delineated$by$a$single$'dollar'$character,$write$a$program\"\nszLine3: .asciz \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\nszLine4: .asciz \"column$are$separated$by$at$least$one$space.\"\nszLine5: .asciz \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\"\nszLine6: .asciz \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\nitbPtLine: .int szLine1,szLine2,szLine3,szLine4,szLine5,szLine6\n .equ NBLINES, (. - itbPtLine) \/ 4\n \n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdritbPtLine\n bl computeMaxiLengthWords\n mov r10,r0 @ column counter\n ldr r0,iAdrszMessLeft\n bl affichageMess\n ldr r0,iAdritbPtLine\n mov r1,r10 @ column size\n bl alignLeft\n ldr r0,iAdrszMessRight\n bl affichageMess\n ldr r0,iAdritbPtLine\n mov r1,r10 @ column size\n bl alignRight\n ldr r0,iAdrszMessCenter\n bl affichageMess\n ldr r0,iAdritbPtLine\n mov r1,r10 @ column size\n bl alignCenter\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessLeft: .int szMessLeft\niAdrszMessRight: .int szMessRight\niAdrszMessCenter: .int szMessCenter\niAdritbPtLine: .int itbPtLine\n\/******************************************************************\/\n\/* compute maxi words *\/ \n\/******************************************************************\/\n\/* r0 contains adresse pointer array *\/\ncomputeMaxiLengthWords:\n push {r1-r6,lr} @ save registers\n mov r2,#0 @ indice pointer array\n mov r3,#0 @ maxi length words\n1:\n ldr r1,[r0,r2,lsl #2] @ load pointer\n mov r4,#0 @ length words counter\n mov r5,#0 @ indice line character\n2:\n ldrb r6,[r1,r5] @ load a line character\n cmp r6,#0 @ line end\u00a0?\n beq 4f\n cmp r6,#'$' @ separator\u00a0?\n bne 3f\n cmp r4,r3\n movgt r3,r4 @ ig greather replace maxi\n mov r4,#-1 @ raz length counter\n3:\n add r4,r4,#1\n add r5,r5,#1 @ increment character indice\n b 2b @ and loop\n4: @ end line\n cmp r4,r3 @ compare word counter and maxi\n movgt r3,r4 @ if greather replace maxi\n add r2,r2,#1 @ increment indice line pointer\n cmp r2,#NBLINES @ maxi\u00a0?\n blt 1b @ no -> loop\n\n mov r0,r3 @ return maxi length counter\n100:\n pop {r1-r6,pc}\n\n\/******************************************************************\/\n\/* align left *\/ \n\/******************************************************************\/\n\/* r0 contains the address of pointer array*\/\n\/* r1 contains column size *\/\nalignLeft:\n push {r4-r7,fp,lr} @ save registers\n sub sp,sp,#BUFFERSIZE @ reserve place for output buffer\n mov fp,sp\n mov r5,r0 @ array address\n mov r2,#0 @ indice array\n1:\n ldr r3,[r5,r2,lsl #2] @ load line pointer\n mov r4,#0 @ line character indice\n mov r7,#0 @ output buffer character indice\n mov r6,#0 @ word lenght \n2:\n ldrb r0,[r3,r4] @ load a character line\n strb r0,[fp,r7] @ store in buffer\n cmp r0,#0 @ line end\u00a0?\n beq 6f\n cmp r0,#'$' @ separator\u00a0?\n bne 5f\n mov r0,#' '\n strb r0,[fp,r7] @ replace $ by space\n3:\n cmp r6,r1 @ length word >= length column\n bge 4f\n add r7,r7,#1\n mov r0,#' '\n strb r0,[fp,r7] @ add space to buffer\n add r6,r6,#1\n b 3b @ and loop\n4:\n mov r6,#-1 @ raz word length\n5:\n add r4,r4,#1 @ increment line indice\n add r7,r7,#1 @ increment buffer indice\n add r6,r6,#1 @ increment word length\n b 2b\n \n6:\n mov r0,#'\\n'\n strb r0,[fp,r7] @ return line\n add r7,r7,#1\n mov r0,#0\n strb r0,[fp,r7] @ final z\u00e9ro\n mov r0,fp\n bl affichageMess @ display output buffer\n add r2,r2,#1\n cmp r2,#NBLINES\n blt 1b\n \n100:\n add sp,sp,#BUFFERSIZE\n pop {r4-r7,fp,pc}\n\/******************************************************************\/\n\/* align right *\/ \n\/******************************************************************\/\n\/* r0 contains the address of pointer array*\/\n\/* r1 contains column size *\/\nalignRight:\n push {r4-r9,fp,lr} @ save registers\n sub sp,sp,#BUFFERSIZE @ reserve place for output buffer\n mov fp,sp\n mov r5,r0 @ array address\n mov r2,#0 @ indice array\n1:\n ldr r3,[r5,r2,lsl #2] @ load line pointer\n mov r4,#0 @ line character indice\n mov r7,#0 @ output buffer character indice\n mov r6,#0 @ word lenght \n mov r8,r3 @ word begin address\n2: @ compute word length\n ldrb r0,[r3,r4] @ load a character line\n cmp r0,#0 @ line end\u00a0?\n beq 3f\n cmp r0,#'$' @ separator\u00a0?\n beq 3f\n add r4,r4,#1 @ increment line indice\n add r6,r6,#1 @ increment word length\n b 2b\n\n3:\n cmp r6,#0\n beq 4f\n sub r6,r1,r6 @ compute left spaces to add\n4: @ loop add spaces to buffer\n cmp r6,#0\n blt 5f\n mov r0,#' '\n strb r0,[fp,r7] @ add space to buffer\n add r7,r7,#1\n sub r6,r6,#1\n b 4b @ and loop\n5:\n mov r9,#0\n6: @ copy loop word to buffer\n ldrb r0,[r8,r9]\n cmp r0,#'$'\n beq 7f\n cmp r0,#0 @ line end\n beq 8f\n strb r0,[fp,r7]\n add r7,r7,#1\n add r9,r9,#1\n b 6b\n7:\n add r8,r8,r9\n add r8,r8,#1 @ new word begin\n mov r6,#0 @ raz word length\n add r4,r4,#1 @ increment line indice\n b 2b\n \n8:\n mov r0,#'\\n'\n strb r0,[fp,r7] @ return line\n add r7,r7,#1\n mov r0,#0\n strb r0,[fp,r7] @ final z\u00e9ro\n mov r0,fp\n bl affichageMess @ display output buffer\n add r2,r2,#1\n cmp r2,#NBLINES\n blt 1b\n \n100:\n add sp,sp,#BUFFERSIZE\n pop {r4-r9,fp,pc}\n\/******************************************************************\/\n\/* align center *\/ \n\/******************************************************************\/\n\/* r0 contains the address of pointer array*\/\n\/* r1 contains column size *\/\nalignCenter:\n push {r4-r12,lr} @ save registers\n sub sp,sp,#BUFFERSIZE @ reserve place for output buffer\n mov fp,sp\n mov r5,r0 @ array address\n mov r2,#0 @ indice array\n1:\n ldr r3,[r5,r2,lsl #2] @ load line pointer\n mov r4,#0 @ line character indice\n mov r7,#0 @ output buffer character indice\n mov r6,#0 @ word length\n mov r8,r3 @ word begin address\n2: @ compute word length\n ldrb r0,[r3,r4] @ load a character line\n cmp r0,#0 @ line end\u00a0?\n beq 3f\n cmp r0,#'$' @ separator\u00a0?\n beq 3f\n add r4,r4,#1 @ increment line indice\n add r6,r6,#1 @ increment word length\n b 2b\n3:\n cmp r6,#0\n beq 5f\n sub r6,r1,r6 @ total spaces number to add\n mov r12,r6\n lsr r6,r6,#1 @ divise by 2 = left spaces number\n4:\n cmp r6,#0\n blt 5f\n mov r0,#' '\n strb r0,[fp,r7] @ add space to buffer\n add r7,r7,#1 @ increment output indice\n sub r6,r6,#1 @ decrement number space\n b 4b @ and loop\n5:\n mov r9,#0\n6: @ copy loop word to buffer\n ldrb r0,[r8,r9]\n cmp r0,#'$' @ s\u00e9parator\u00a0?\n beq 7f\n cmp r0,#0 @ line end\u00a0?\n beq 10f\n strb r0,[fp,r7]\n add r7,r7,#1\n add r9,r9,#1\n b 6b\n7:\n lsr r6,r12,#1 @ divise total spaces by 2\n sub r6,r12,r6 @ and compute number spaces to right side\n8: @ loop to add right spaces \n cmp r6,#0\n ble 9f\n mov r0,#' '\n strb r0,[fp,r7] @ add space to buffer\n add r7,r7,#1\n sub r6,r6,#1\n b 8b @ and loop\n\n9:\n add r8,r8,r9\n add r8,r8,#1 @ new address word begin\n mov r6,#0 @ raz word length\n add r4,r4,#1 @ increment line indice\n b 2b @ and loop new word\n \n10:\n mov r0,#'\\n'\n strb r0,[fp,r7] @ return line\n add r7,r7,#1\n mov r0,#0\n strb r0,[fp,r7] @ final z\u00e9ro\n mov r0,fp\n bl affichageMess @ display output buffer\n add r2,r2,#1 @ increment line indice\n cmp r2,#NBLINES @ maxi\u00a0?\n blt 1b @ loop\n \n100:\n add sp,sp,#BUFFERSIZE\n pop {r4-r12,pc}\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\nLEFT\u00a0:\nGiven a text file of many lines, where fields within a line\nare delineated by a single 'dollar' character, write a program\nthat aligns each column of fields by ensuring that words in each\ncolumn are separated by at least one space.\nFurther, allow for each word in a column to be either left\njustified, right justified, or center justified within its column.\n\nRIGHT\u00a0:\n Given a text file of many lines, where fields within a line\n are delineated by a single 'dollar' character, write a program\n that aligns each column of fields by ensuring that words in each\n column are separated by at least one space.\n Further, allow for each word in a column to be either left\n justified, right justified, or center justified within its column.\n\nCENTER\u00a0:\n Given a text file of many lines, where fields within a line\n are delineated by a single 'dollar' character, write a program\n that aligns each column of fields by ensuring that words in each\n column are separated by at least one space.\n Further, allow for each word in a column to be either left\n justified, right justified, or center justified within its column.\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":716} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI *\/\n\/* program rot13.s *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n\n.equ STRINGSIZE, 500\n\/************************************\/\n\/* Initialized data *\/\n\/************************************\/\n.data\nszMessString: .asciz \"String\u00a0:\\n\"\nszMessEncrip: .asciz \"\\nEncrypted\u00a0:\\n\"\nszMessDecrip: .asciz \"\\nDecrypted\u00a0:\\n\"\nszString1: .asciz \"{NOWHERE! abcd xyz 1234}\"\n\nszCarriageReturn: .asciz \"\\n\"\n\/************************************\/\n\/* UnInitialized data *\/\n\/************************************\/\n.bss \nszString2: .skip STRINGSIZE\nszString3: .skip STRINGSIZE\n\/************************************\/\n\/* code section *\/\n\/************************************\/\n.text\n.global main \nmain: \n\n ldr r0,iAdrszMessString @ display message\n bl affichageMess\n ldr r0,iAdrszString1 @ display string\n bl affichageMess\n ldr r0,iAdrszString1\n ldr r1,iAdrszString2\n bl encryptRot13\n ldr r0,iAdrszMessEncrip\n bl affichageMess\n ldr r0,iAdrszString2 @ display string\n bl affichageMess \n ldr r0,iAdrszString2\n ldr r1,iAdrszString3\n bl decryptRot13\n ldr r0,iAdrszMessDecrip\n bl affichageMess\n ldr r0,iAdrszString3 @ display string\n bl affichageMess \n ldr r0,iAdrszCarriageReturn\n bl affichageMess \n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\niAdrszMessString: .int szMessString\niAdrszMessDecrip: .int szMessDecrip\niAdrszMessEncrip: .int szMessEncrip\niAdrszString1: .int szString1\niAdrszString2: .int szString2\niAdrszString3: .int szString3\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* encrypt strings *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the string1 *\/\n\/* r1 contains the address of the encrypted string *\/\nencryptRot13:\n push {r3,r4,lr} @ save registers \n mov r3,#0 @ counter byte string 1\n mov r2,#13 @ rot characters number\n1:\n ldrb r4,[r0,r3] @ load byte string 1\n cmp r4,#0 @ zero final\u00a0?\n streqb r4,[r1,r3]\n moveq r0,r3\n beq 100f\n cmp r4,#65 @ < A\u00a0?\n strltb r4,[r1,r3]\n addlt r3,#1\n blt 1b\n cmp r4,#90 @ > Z\n bgt 2f\n add r4,r2 @ add key\n cmp r4,#90 @ > Z\n subgt r4,#26\n strb r4,[r1,r3]\n add r3,#1\n b 1b\n2:\n cmp r4,#97 @ < a\u00a0?\n strltb r4,[r1,r3]\n addlt r3,#1\n blt 1b\n cmp r4,#122 @> z\n strgtb r4,[r1,r3]\n addgt r3,#1\n bgt 1b\n add r4,r2\n cmp r4,#122\n subgt r4,#26\n strb r4,[r1,r3]\n add r3,#1\n b 1b\n\n100:\n pop {r3,r4,lr} @ restaur registers\n bx lr @ return\n\/******************************************************************\/\n\/* decrypt strings *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the encrypted string1 *\/\n\/* r1 contains the address of the decrypted string *\/\ndecryptRot13:\n push {r3,r4,lr} @ save registers \n mov r3,#0 @ counter byte string 1\n mov r2,#13 @ rot characters number\n1:\n ldrb r4,[r0,r3] @ load byte string 1\n cmp r4,#0 @ zero final\u00a0?\n streqb r4,[r1,r3]\n moveq r0,r3\n beq 100f\n cmp r4,#65 @ < A\u00a0?\n strltb r4,[r1,r3]\n addlt r3,#1\n blt 1b\n cmp r4,#90 @ > Z\n bgt 2f\n sub r4,r2 @ substract key\n cmp r4,#65 @ < A\n addlt r4,#26\n strb r4,[r1,r3]\n add r3,#1\n b 1b\n2:\n cmp r4,#97 @ < a\u00a0?\n strltb r4,[r1,r3]\n addlt r3,#1\n blt 1b\n cmp r4,#122 @ > z\n strgtb r4,[r1,r3]\n addgt r3,#1\n bgt 1b\n sub r4,r2 @ substract key\n cmp r4,#97 @ < a\n addlt r4,#26\n strb r4,[r1,r3]\n add r3,#1\n b 1b\n\n100:\n pop {r3,r4,lr} @ restaur registers\n bx lr @ return\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n\/* for this file see task include a file in language ARM assembly*\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":717} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program compositeSort.s *\/ \n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n\n\/*******************************************\/\n\/* Structures *\/\n\/********************************************\/\n\/* city structure *\/\n .struct 0\ncity_name: @ \n .struct city_name + 4 \ncity_habitants: @ \n .struct city_habitants + 4 \ncity_end:\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nsMessResult: .asciz \"Name\u00a0: @ number habitants\u00a0: @ \\n\"\nszMessSortHab: .asciz \"Sort table for number of habitants\u00a0:\\n\"\nszMessSortName: .asciz \"Sort table for name of city\u00a0:\\n\"\nszCarriageReturn: .asciz \"\\n\"\n \n\/\/ cities name\nszCeret: .asciz \"Ceret\"\nszMaureillas: .asciz \"Maureillas\"\nszTaillet: .asciz \"Taillet\"\nszReynes: .asciz \"Reynes\"\nszVives: .asciz \"Viv\u00e9s\"\nszBoulou: .asciz \"Le Boulou\"\nszSaintJean: .asciz \"Saint Jean Pla de Corts\"\nszCluses: .asciz \"Les Cluses\"\nszAlbere: .asciz \"L'Alb\u00e8re\"\nszPerthus: .asciz \"Le Perthus\"\n.align 4\n\nTableCities: \n .int szCluses @ address name string\n .int 251 @ number of habitants\n .int szCeret\n .int 7705\n .int szMaureillas\n .int 2596\n .int szBoulou \n .int 5554\n .int szSaintJean\n .int 2153\n .int szAlbere\n .int 83\n .int szVives\n .int 174\n .int szTaillet\n .int 115\n .int szPerthus\n .int 586\n .int szReynes\n .int 1354\n.equ NBELEMENTS, (. - TableCities) \/ city_end\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\nsZoneConv: .skip 24\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n \n ldr r0,iAdrszMessSortHab \n bl affichageMess\n\n ldr r0,iAdrTableCities @ address city table\n mov r1,#0 @ not use in routine\n mov r2,#NBELEMENTS @ number of \u00e9lements \n mov r3,#city_habitants @ sort by number habitants\n mov r4,#'N' @ Alphanumeric\n bl shellSort\n ldr r0,iAdrTableCities @ address number table\n bl displayTable\n \n ldr r0,iAdrszMessSortName \n bl affichageMess\n \n ldr r0,iAdrTableCities @ address city table\n mov r1,#0 @ not use in routine\n mov r2,#NBELEMENTS @ number of \u00e9lements \n mov r3,#city_name @ sort by name\n mov r4,#'A' @ Alphanumeric\n bl shellSort\n ldr r0,iAdrTableCities @ address number table\n bl displayTable\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdrTableCities: .int TableCities\niAdrszMessSortHab: .int szMessSortHab\niAdrszMessSortName: .int szMessSortName\n\/***************************************************\/\n\/* shell Sort *\/\n\/***************************************************\/\n\n\/* r0 contains the address of table *\/\n\/* r1 contains the first element but not use\u00a0!! *\/\n\/* this routine use first element at index zero\u00a0!!! *\/\n\/* r2 contains the number of element *\/\n\/* r3 contains the offset of sort zone *\/\n\/* r4 contains type of sort zone N = numeric A = alphanumeric *\/\nshellSort:\n push {r0-r12,lr} @ save registers\n sub sp,#city_end @ reserve area on stack\n mov fp,sp @ frame pointer = stack\n mov r8,r3 @ save offser area sort\n mov r9,r4 @ save type sort\n mov r7,#city_end @ element size\n \/\/vidregtit debut\n sub r12,r2,#1 @ index last item\n mov r6,r12 @ init gap = last item\n1: @ start loop 1\n lsrs r6,#1 @ gap = gap \/ 2\n beq 100f @ if gap = 0 -> end\n mov r3,r6 @ init loop indice 1 \n2: @ start loop 2\n mul r1,r3,r7 @ offset \u00e9lement\n mov r2,fp @ save on stack\n bl saveElement \n add r1,r8 @ + offset sort zone\n ldr r4,[r0,r1] @ load first value\n mov r5,r3 @ init loop indice 2\n3: @ start loop 3\n cmp r5,r6 @ indice < gap\n blt 8f @ yes -> end loop 2\n sub r10,r5,r6 @ index = indice - gap\n mul r1,r10,r7 @ offset \u00e9lement\n add r10,r1,r8 @ + offset sort zone\n ldr r2,[r0,r10] @ load second value\n push {r3,r5} @ save registrars because not enought register\n cmp r9,#'A' @ sort area alapha\u00a0?\n beq 4f @ yes\n cmp r4,r2 @ else compare numeric values\n bge 7f @ highter\n b 6f @ lower\n4: @ compare area alphanumeric\n mov r10,#0 @ counter\n5:\n ldrb r3,[r4,r10] @ byte string 1\n ldrb r5,[r2,r10] @ byte string 2\n cmp r3,r5\n bgt 7f \n blt 6f\n\n cmp r3,#0 @ end string 1\n beq 7f @ ens comparaison\n add r10,r10,#1 @ else add 1 in counter\n b 5b @ and loop\n \n6:\n pop {r3,r5} @ restaur registers\n mul r2,r5,r7 @ offset \u00e9lement\n bl copyElement @ copy element r1 to element r2\n sub r5,r6 @ indice = indice - gap\n b 3b @ and loop\n7:\n pop {r3,r5}\n8: @ end loop 3\n mul r1,r5,r7 @ offset destination \u00e9lement \n mov r2,fp @ restaur element in table\n bl restaurElement \n add r3,#1 @ increment indice 1\n cmp r3,r12 @ end\u00a0?\n ble 2b @ no -> loop 2\n b 1b @ yes loop for new gap\n \n100: @ end function\n add sp,#city_end \n pop {r0-r12,lr} @ restaur registers\n bx lr @ return \n\/******************************************************************\/\n\/* copy table element *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 offset origin element *\/\n\/* r2 offset destination element *\/\ncopyElement:\n push {r0-r4,lr} @ save registers\n \/\/vidregtit copy\n mov r3,#0\n add r1,r0\n add r2,r0\n1:\n ldrb r4,[r1,r3]\n strb r4,[r2,r3]\n add r3,#1\n cmp r3,#city_end\n blt 1b\n100:\n pop {r0-r4,lr}\n bx lr\n\/******************************************************************\/\n\/* save element *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 offset origin element *\/\n\/* r2 address destination *\/\nsaveElement:\n push {r0-r4,lr} @ save registers\n mov r3,#0\n add r1,r0\n1:\n ldrb r4,[r1,r3]\n strb r4,[r2,r3]\n add r3,#1\n cmp r3,#city_end\n blt 1b\n100:\n pop {r0-r4,lr}\n bx lr\n\/******************************************************************\/\n\/* restaur element *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 offset destination element *\/\n\/* r2 address origine *\/\nrestaurElement:\n push {r0-r4,lr} @ save registers\n mov r3,#0\n add r1,r0\n1:\n ldrb r4,[r2,r3]\n strb r4,[r1,r3]\n add r3,#1\n cmp r3,#city_end\n blt 1b\n100:\n pop {r0-r4,lr}\n bx lr\n\/******************************************************************\/\n\/* Display table elements *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\ndisplayTable:\n push {r0-r6,lr} @ save registers\n mov r2,r0 @ table address\n mov r3,#0\n mov r6,#city_end\n1: @ loop display table\n mul r4,r3,r6\n add r4,#city_name\n ldr r1,[r2,r4]\n ldr r0,iAdrsMessResult\n bl strInsertAtCharInc @ put name in message\n mov r5,r0 @ save address of new message\n mul r4,r3,r6\n add r4,#city_habitants @ and load value\n ldr r0,[r2,r4]\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n mov r0,r5\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess @ display message\n add r3,#1\n cmp r3,#NBELEMENTS - 1\n ble 1b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n100:\n pop {r0-r6,lr}\n bx lr\niAdrsZoneConv: .int sZoneConv\n\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\nSort table for number of habitants\u00a0:\nName\u00a0: L'Alb\u00e8re number habitants\u00a0: 83\nName\u00a0: Taillet number habitants\u00a0: 115\nName\u00a0: Viv\u00e9s number habitants\u00a0: 174\nName\u00a0: Les Cluses number habitants\u00a0: 251\nName\u00a0: Le Perthus number habitants\u00a0: 586\nName\u00a0: Reynes number habitants\u00a0: 1354\nName\u00a0: Saint Jean Pla de Corts number habitants\u00a0: 2153\nName\u00a0: Maureillas number habitants\u00a0: 2596\nName\u00a0: Le Boulou number habitants\u00a0: 5554\nName\u00a0: Ceret number habitants\u00a0: 7705\n\nSort table for name of city\u00a0:\nName\u00a0: Ceret number habitants\u00a0: 7705\nName\u00a0: L'Alb\u00e8re number habitants\u00a0: 83\nName\u00a0: Le Boulou number habitants\u00a0: 5554\nName\u00a0: Le Perthus number habitants\u00a0: 586\nName\u00a0: Les Cluses number habitants\u00a0: 251\nName\u00a0: Maureillas number habitants\u00a0: 2596\nName\u00a0: Reynes number habitants\u00a0: 1354\nName\u00a0: Saint Jean Pla de Corts number habitants\u00a0: 2153\nName\u00a0: Taillet number habitants\u00a0: 115\nName\u00a0: Viv\u00e9s number habitants\u00a0: 174\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":718} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program loop1.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/* Initialized data *\/\n.data\nszMessX: .asciz \"X\"\nszCarriageReturn: .asciz \"\\n\"\n\n\/* UnInitialized data *\/\n.bss \n\n\/* code section *\/\n.text\n.global main \nmain: \/* entry of program *\/\n push {fp,lr} \/* saves 2 registers *\/\n\n mov r2,#0 @ counter loop 1\n1: @ loop start 1\n mov r1,#0 @ counter loop 2\n2: @ loop start 2\n ldr r0,iAdrszMessX\n bl affichageMess\n add r1,#1 @ r1 + 1\n cmp r1,r2 @ compare r1 r2\n ble 2b @ loop label 2 before\n ldr r0,iAdrszCarriageReturn \n bl affichageMess\n add r2,#1 @ r2 + 1\n cmp r2,#5 @ for five loop\n blt 1b @ loop label 1 before\n\n\n100: \/* standard end of the program *\/\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\n\niAdrszMessX: .int szMessX\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {fp,lr} \t\t\t\/* save registres *\/ \n push {r0,r1,r2,r7} \t\t\/* save others registers *\/\n mov r2,#0 \t\t\t\t\/* counter length *\/\n1: \t\/* loop length calculation *\/\n ldrb r1,[r0,r2] \t\t\t\/* read octet start position + index *\/\n cmp r1,#0 \t\t\t\/* if 0 its over *\/\n addne r2,r2,#1 \t\t\t\/* else add 1 in the length *\/\n bne 1b \t\t\t\/* and loop *\/\n \/* so here r2 contains the length of the message *\/\n mov r1,r0 \t\t\t\/* address message in r1 *\/\n mov r0,#STDOUT \t\t\/* code to write to the standard output Linux *\/\n mov r7, #WRITE \/* code call system \"write\" *\/\n swi #0 \/* call systeme *\/\n pop {r0,r1,r2,r7} \t\t\/* restaur others registers *\/\n pop {fp,lr} \t\t\t\t\/* restaur des 2 registres *\/ \n bx lr\t \t\t\t\/* return *\/\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":719} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI or android 32 bits *\/\n\/* program hashmap.s *\/ \n\n\/* *\/\n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n.equ MAXI, 10 @ size hashmap\n.equ HEAPSIZE,20000\n.equ LIMIT, 10 @ key characters number for compute index\n.equ COEFF, 80 @ filling rate 80 = 80%\n\n\n\/*******************************************\/\n\/* Structures *\/\n\/********************************************\/\n\/* structure hashMap *\/\n .struct 0\nhash_count: \/\/ stored values counter\n .struct hash_count + 4\nhash_key: \/\/ key\n .struct hash_key + (4 * MAXI)\nhash_data: \/\/ data\n .struct hash_data + (4 * MAXI)\nhash_fin:\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessFin: .asciz \"End program.\\n\"\nszCarriageReturn: .asciz \"\\n\"\nszMessNoP: .asciz \"Key not found\u00a0!!!\\n\"\nszKey1: .asciz \"one\"\nszData1: .asciz \"Ceret\"\nszKey2: .asciz \"two\"\nszData2: .asciz \"Maureillas\"\nszKey3: .asciz \"three\"\nszData3: .asciz \"Le Perthus\"\nszKey4: .asciz \"four\"\nszData4: .asciz \"Le Boulou\"\n\n.align 4\niptZoneHeap: .int sZoneHeap \/\/ start heap address\niptZoneHeapEnd: .int sZoneHeap + HEAPSIZE \/\/ end heap address\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\n\/\/sZoneConv: .skip 24\ntbHashMap1: .skip hash_fin @ hashmap\nsZoneHeap: .skip HEAPSIZE @ heap\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n \n ldr r0,iAdrtbHashMap1\n bl hashInit @ init hashmap\n ldr r0,iAdrtbHashMap1\n ldr r1,iAdrszKey1 @ store key one\n ldr r2,iAdrszData1\n bl hashInsert\n cmp r0,#0 @ error\u00a0?\n bne 100f\n ldr r0,iAdrtbHashMap1\n ldr r1,iAdrszKey2 @ store key two\n ldr r2,iAdrszData2\n bl hashInsert\n cmp r0,#0\n bne 100f\n ldr r0,iAdrtbHashMap1\n ldr r1,iAdrszKey3 @ store key three\n ldr r2,iAdrszData3\n bl hashInsert\n cmp r0,#0\n bne 100f\n ldr r0,iAdrtbHashMap1\n ldr r1,iAdrszKey4 @ store key four\n ldr r2,iAdrszData4\n bl hashInsert\n cmp r0,#0\n bne 100f\n \n ldr r0,iAdrtbHashMap1\n ldr r1,iAdrszKey2 @ remove key two\n bl hashRemoveKey\n cmp r0,#0\n bne 100f\n \n ldr r0,iAdrtbHashMap1\n ldr r1,iAdrszKey1 @ search key\n bl searchKey\n cmp r0,#-1\n beq 1f\n bl affichageMess\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n b 2f\n1:\n ldr r0,iAdrszMessNoP\n bl affichageMess\n2:\n ldr r0,iAdrtbHashMap1\n ldr r1,iAdrszKey2\n bl searchKey\n cmp r0,#-1\n beq 3f\n bl affichageMess\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n b 4f\n3:\n ldr r0,iAdrszMessNoP\n bl affichageMess\n4:\n ldr r0,iAdrtbHashMap1\n ldr r1,iAdrszKey4\n bl searchKey\n cmp r0,#-1\n beq 5f\n bl affichageMess\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n b 6f\n5:\n ldr r0,iAdrszMessNoP\n bl affichageMess\n6:\n ldr r0,iAdrszMessFin\n bl affichageMess\n \n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessFin: .int szMessFin\niAdrtbHashMap1: .int tbHashMap1\niAdrszKey1: .int szKey1\niAdrszData1: .int szData1\niAdrszKey2: .int szKey2\niAdrszData2: .int szData2\niAdrszKey3: .int szKey3\niAdrszData3: .int szData3\niAdrszKey4: .int szKey4\niAdrszData4: .int szData4\niAdrszMessNoP: .int szMessNoP\n\/***************************************************\/\n\/* init hashMap *\/\n\/***************************************************\/\n\/\/ r0 contains address to hashMap\nhashInit:\n push {r1-r3,lr} @ save registers \n mov r1,#0\n mov r2,#0\n str r2,[r0,#hash_count] @ init counter\n add r0,r0,#hash_key @ start zone key\/value\n1:\n lsl r3,r1,#3\n add r3,r3,r0\n str r2,[r3,#hash_key]\n str r2,[r3,#hash_data]\n add r1,r1,#1\n cmp r1,#MAXI\n blt 1b\n100:\n pop {r1-r3,pc} @ restaur registers\n\/***************************************************\/\n\/* insert key\/datas *\/\n\/***************************************************\/\n\/\/ r0 contains address to hashMap\n\/\/ r1 contains address to key\n\/\/ r2 contains address to datas\nhashInsert:\n push {r1-r8,lr} @ save registers \n mov r6,r0 @ save address \n bl hashIndex @ search void key or identical key\n cmp r0,#0 @ error\u00a0?\n blt 100f\n \n ldr r3,iAdriptZoneHeap\n ldr r3,[r3]\n ldr r8,iAdriptZoneHeapEnd\n ldr r8,[r8]\n sub r8,r8,#50\n lsl r0,r0,#2 @ 4 bytes\n add r7,r6,#hash_key @ start zone key\/value\n ldr r4,[r7,r0]\n cmp r4,#0 @ key already stored\u00a0?\n bne 1f\n ldr r4,[r6,#hash_count] @ no -> increment counter\n add r4,r4,#1\n cmp r4,#(MAXI * COEFF \/ 100)\n bge 98f\n str r4,[r6,#hash_count]\n1:\n str r3,[r7,r0]\n mov r4,#0\n2: @ copy key loop in heap\n ldrb r5,[r1,r4]\n strb r5,[r3,r4]\n cmp r5,#0\n add r4,r4,#1\n bne 2b\n add r3,r3,r4\n cmp r3,r8\n bge 99f\n add r7,r6,#hash_data\n str r3,[r7,r0]\n mov r4,#0\n3: @ copy data loop in heap\n ldrb r5,[r2,r4]\n strb r5,[r3,r4]\n cmp r5,#0\n add r4,r4,#1\n bne 3b\n add r3,r3,r4\n cmp r3,r8\n bge 99f\n ldr r0,iAdriptZoneHeap\n str r3,[r0] @ new heap address\n \n mov r0,#0 @ insertion OK\n b 100f\n98: @ error hashmap\n adr r0,szMessErrInd\n bl affichageMess\n mov r0,#-1\n b 100f\n99: @ error heap\n adr r0,szMessErrHeap\n bl affichageMess\n mov r0,#-1\n100:\n pop {r1-r8,lr} @ restaur registers\n bx lr @ return\nszMessErrInd: .asciz \"Error\u00a0: HashMap size Filling rate Maxi\u00a0!!\\n\"\nszMessErrHeap: .asciz \"Error\u00a0: Heap size Maxi\u00a0!!\\n\"\n.align 4\niAdriptZoneHeap: .int iptZoneHeap\niAdriptZoneHeapEnd: .int iptZoneHeapEnd\n\/***************************************************\/\n\/* search void index in hashmap *\/\n\/***************************************************\/\n\/\/ r0 contains hashMap address \n\/\/ r1 contains key address\nhashIndex:\n push {r1-r4,lr} @ save registers \n add r4,r0,#hash_key\n mov r2,#0 @ index\n mov r3,#0 @ characters sum \n1: @ loop to compute characters sum \n ldrb r0,[r1,r2]\n cmp r0,#0 @ string end\u00a0?\n beq 2f\n add r3,r3,r0 @ add to sum\n add r2,r2,#1\n cmp r2,#LIMIT\n blt 1b\n2:\n mov r5,r1 @ save key address\n mov r0,r3\n mov r1,#MAXI\n bl division @ compute remainder -> r3\n mov r1,r5 @ key address\n \n3:\n ldr r0,[r4,r3,lsl #2] @ loak key for computed index \n cmp r0,#0 @ void key\u00a0?\n beq 4f \n bl comparStrings @ identical key\u00a0?\n cmp r0,#0\n beq 4f @ yes\n add r3,r3,#1 @ no search next void key\n cmp r3,#MAXI @ maxi\u00a0?\n movge r3,#0 @ restart to index 0\n b 3b\n4:\n mov r0,r3 @ return index void array or key equal\n100:\n pop {r1-r4,pc} @ restaur registers\n\n\/***************************************************\/\n\/* search key in hashmap *\/\n\/***************************************************\/\n\/\/ r0 contains hash map address\n\/\/ r1 contains key address\nsearchKey:\n push {r1-r2,lr} @ save registers \n mov r2,r0\n bl hashIndex\n lsl r0,r0,#2\n add r1,r0,#hash_key\n ldr r1,[r2,r1]\n cmp r1,#0\n moveq r0,#-1\n beq 100f\n add r1,r0,#hash_data\n ldr r0,[r2,r1]\n100:\n pop {r1-r2,pc} @ restaur registers\n\/***************************************************\/\n\/* remove key in hashmap *\/\n\/***************************************************\/\n\/\/ r0 contains hash map address\n\/\/ r1 contains key address\nhashRemoveKey: @ INFO: hashRemoveKey\n push {r1-r3,lr} @ save registers \n mov r2,r0\n bl hashIndex\n lsl r0,r0,#2\n add r1,r0,#hash_key\n ldr r3,[r2,r1]\n cmp r3,#0\n beq 2f\n add r3,r2,r1\n mov r1,#0 @ raz key address\n str r1,[r3] \n add r1,r0,#hash_data\n add r3,r2,r1\n mov r1,#0\n str r1,[r3] @ raz datas address\n mov r0,#0\n b 100f\n2:\n adr r0,szMessErrRemove\n bl affichageMess\n mov r0,#-1\n100:\n pop {r1-r3,pc} @ restaur registers\nszMessErrRemove: .asciz \"\\033[31mError remove key\u00a0!!\\033[0m\\n\"\n.align 4\n\/************************************\/ \n\/* Strings case sensitive comparisons *\/\n\/************************************\/\t \n\/* r0 et r1 contains the address of strings *\/\n\/* return 0 in r0 if equals *\/\n\/* return -1 if string r0 < string r1 *\/\n\/* return 1 if string r0 > string r1 *\/\ncomparStrings:\n push {r1-r4} @ save des registres\n mov r2,#0 @ characters counter\n1:\n ldrb r3,[r0,r2] @ byte string 1\n ldrb r4,[r1,r2] @ byte string 2\n cmp r3,r4\n movlt r0,#-1 @ smaller\n movgt r0,#1\t @ greather\n bne 100f @ not equals\n cmp r3,#0 @ 0 end string\u00a0?\n moveq r0,#0 @ equals\n beq 100f @ end string\n add r2,r2,#1 @ else add 1 in counter\n b 1b @ and loop\n100:\n pop {r1-r4}\n bx lr \n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":720} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program insertList.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ READ, 3\n.equ WRITE, 4\n\n.equ NBELEMENTS, 100 @ list size\n\n\n\/*******************************************\/\n\/* Structures *\/\n\/********************************************\/\n\/* structure linkedlist*\/\n .struct 0\nllist_next: @ next element\n .struct llist_next + 4 \nllist_value: @ element value\n .struct llist_value + 4 \nllist_fin:\n\/* Initialized data *\/\n.data\nszMessInitListe: .asciz \"List initialized.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\/* datas error display *\/\nszMessErreur: .asciz \"Error detected.\\n\"\n\/* datas message display *\/\nszMessResult: .ascii \"Element No\u00a0:\"\nsNumElement: .space 12,' '\n .ascii \" value\u00a0: \"\nsValue: .space 12,' '\n .asciz \"\\n\"\n\n\/* UnInitialized data *\/\n.bss \nlList1: .skip llist_fin * NBELEMENTS @ list memory place \n\/* code section *\/\n.text\n.global main \nmain: \n ldr r0,iAdrlList1\n mov r1,#0 @ list init\n str r1,[r0,#llist_next]\n ldr r0,iAdrszMessInitListe\n bl affichageMess\n ldr r0,iAdrlList1\n mov r1,#2\n bl insertElement @ add element value 2\n ldr r0,iAdrlList1\n mov r1,#5\n bl insertElement @ add element value 5\n ldr r3,iAdrlList1\n mov r2,#0 @ ident element\n1:\n ldr r0,[r3,#llist_next] @ end list\u00a0?\n cmp r0,#0\n beq 100f @ yes\n add r2,#1\n mov r0,r2 @ display No element and value\n ldr r1,iAdrsNumElement\n bl conversion10S\n ldr r0,[r3,#llist_value]\n ldr r1,iAdrsValue\n bl conversion10S\n ldr r0,iAdrszMessResult\n bl affichageMess\n ldr r3,[r3,#llist_next] @ next element\n b 1b @ and loop\n100: @ standard end of the program\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\niAdrszMessInitListe: .int szMessInitListe\niAdrszMessErreur: .int szMessErreur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrlList1: .int lList1\niAdrszMessResult: .int szMessResult\niAdrsNumElement: .int sNumElement\niAdrsValue: .int sValue\n\n\/******************************************************************\/\n\/* insert element at end of list *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the list *\/\n\/* r1 contains the value of element *\/\n\/* r0 returns address of element or - 1 if error *\/\ninsertElement:\n push {r1-r3,lr} @ save registers \n mov r2,#llist_fin * NBELEMENTS\n add r2,r0 @ compute address end list\n1: @ start loop \n ldr r3,[r0,#llist_next] @ load next pointer\n cmp r3,#0 @ = zero\n movne r0,r3 @ no -> loop with pointer\n bne 1b\n add r3,r0,#llist_fin @ yes -> compute next free address\n cmp r3,r2 @ > list end \n movge r0,#-1 @ yes -> error\n bge 100f\n str r3,[r0,#llist_next] @ store next address in current pointer\n str r1,[r0,#llist_value] @ store element value\n mov r1,#0\n str r1,[r3,#llist_next] @ init next pointer in next address\n\n100:\n pop {r1-r3,lr} @ restaur registers\n bx lr @ return\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registers \n mov r2,#0 @ counter length *\/\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call system\n pop {r0,r1,r2,r7,lr} @ restaur registers\n bx lr @ return\n\/***************************************************\/\n\/* Converting a register to a signed decimal *\/\n\/***************************************************\/\n\/* r0 contains value and r1 area address *\/\nconversion10S:\n push {r0-r4,lr} @ save registers\n mov r2,r1 @ debut zone stockage\n mov r3,#'+' @ par defaut le signe est +\n cmp r0,#0 @ negative number\u00a0? \n movlt r3,#'-' @ yes\n mvnlt r0,r0 @ number inversion\n addlt r0,#1\n mov r4,#10 @ length area\n1: @ start loop\n bl divisionpar10U\n add r1,#48 @ digit\n strb r1,[r2,r4] @ store digit on area\n sub r4,r4,#1 @ previous position\n cmp r0,#0 @ stop if quotient = 0\n bne 1b\t\n\n strb r3,[r2,r4] @ store signe \n subs r4,r4,#1 @ previous position\n blt 100f @ if r4 < 0 -> end\n\n mov r1,#' ' @ space\n2:\n strb r1,[r2,r4] @store byte space\n subs r4,r4,#1 @ previous position\n bge 2b @ loop if r4 > 0\n100: \n pop {r0-r4,lr} @ restaur registers\n bx lr \n\/***************************************************\/\n\/* division par 10 unsigned *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\n\/* r1 remainder *\/\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n \/\/mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3\n \/\/movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: \t.int 0xCCCCCCCD\n","human_summarization":"\"Defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element C into a list of elements A->B, after element A.\"","id":721} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI *\/\n\/* program multieth.s *\/\n\n \/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessResult: .asciz \"Result\u00a0: \"\nszMessStart: .asciz \"Program 32 bits start.\\n\"\nszCarriageReturn: .asciz \"\\n\"\nszMessErreur: .asciz \"Error overflow. \\n\"\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\nsZoneConv: .skip 24\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdrszMessStart\n bl affichageMess\n mov r0,#17\n mov r1,#34\n bl multEthiop\n ldr r1,iAdrsZoneConv\n bl conversion10 @ decimal conversion\n mov r0,#3 @ number string to display\n ldr r1,iAdrszMessResult\n ldr r2,iAdrsZoneConv @ insert conversion in message\n ldr r3,iAdrszCarriageReturn\n bl displayStrings @ display message\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsZoneConv: .int sZoneConv\niAdrszMessResult: .int szMessResult\niAdrszMessErreur: .int szMessErreur\niAdrszMessStart: .int szMessStart\n\/******************************************************************\/\n\/* Ethiopian multiplication *\/ \n\/******************************************************************\/\n\/* r0 first factor *\/\n\/* r1 2th factor *\/\n\/* r0 return r\u00e9sult *\/\nmultEthiop:\n push {r1-r3,lr} @ save registers\n mov r2,#0 @ init result\n 1: @ loop\n cmp r0,#1 @ end\u00a0?\n blt 3f\n ands r3,r0,#1 @ \n addne r2,r1 @ add factor2 to result\n lsr r0,#1 @ divide factor1 by 2\n lsls r1,#1 @ multiply factor2 by 2\n bcs 2f @ overflow\u00a0?\n b 1b @ or loop\n 2: @ error display \n ldr r0,iAdrszMessErreur\n bl affichageMess\n mov r2,#0\n 3:\n mov r0,r2 @ return result\n pop {r1-r3,pc}\n\/***************************************************\/\n\/* display multi strings *\/\n\/***************************************************\/\n\/* r0 contains number strings address *\/\n\/* r1 address string1 *\/\n\/* r2 address string2 *\/\n\/* r3 address string3 *\/\n\/* other address on the stack *\/\n\/* thinck to add number other address * 4 to add to the stack *\/\ndisplayStrings: @ INFO: displayStrings\n push {r1-r4,fp,lr} @ save des registres\n add fp,sp,#24 @ save param\u00e9ters address (6 registers saved * 4 bytes)\n mov r4,r0 @ save strings number\n cmp r4,#0 @ 0 string -> end\n ble 100f\n mov r0,r1 @ string 1\n bl affichageMess\n cmp r4,#1 @ number > 1\n ble 100f\n mov r0,r2\n bl affichageMess\n cmp r4,#2\n ble 100f\n mov r0,r3\n bl affichageMess\n cmp r4,#3\n ble 100f\n mov r3,#3\n sub r2,r4,#4\n1: @ loop extract address string on stack\n ldr r0,[fp,r2,lsl #2]\n bl affichageMess\n subs r2,#1\n bge 1b\n100:\n pop {r1-r4,fp,pc}\n\n\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":722} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program game24Solver.s *\/ \n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n.equ STDIN, 0 @ Linux input console\n.equ READ, 3 @ Linux syscall\n.equ NBDIGITS, 4 @ digits number\n.equ TOTAL, 24\n.equ BUFFERSIZE, 80\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessRules: .ascii \"24 Game\\n\"\n .ascii \"The program will display four randomly-generated \\n\"\n .asciz \"single-digit numbers and search a solution for a total to 24\\n\\n\"\n\nszMessDigits: .asciz \"The four digits are @ @ @ @ and the score is 24. \\n\"\nszMessOK: .asciz \"Solution\u00a0: \\n\"\nszMessNotOK: .asciz \"No solution for this problem\u00a0!! \\n\"\nszMessNewGame: .asciz \"New game (y\/n)\u00a0? \\n\"\nszCarriageReturn: .asciz \"\\n\"\n.align 4\niGraine: .int 123456\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\n.align 4\nsZoneConv: .skip 24\nsBuffer: .skip BUFFERSIZE\niTabDigit: .skip 4 * NBDIGITS @ digits table\niTabOperand1: .skip 4 * NBDIGITS @ operand 1 table \niTabOperand2: .skip 4 * NBDIGITS @ operand 2 table\niTabOperation: .skip 4 * NBDIGITS @ operator table\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n \n ldr r0,iAdrszMessRules @ display rules\n bl affichageMess\n1:\n mov r3,#0\n ldr r12,iAdriTabDigit\n ldr r5,iAdrszMessDigits\n2: @ loop generate random digits \n mov r0,#8\n bl genereraleas \n add r0,r0,#1\n str r0,[r12,r3,lsl #2] @ store in table\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n mov r2,#0\n strb r2,[r1,r0] @ reduce size display area with z\u00e9ro final\n mov r0,r5\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n mov r5,r0\n add r3,r3,#1\n cmp r3,#NBDIGITS @ end\u00a0?\n blt 2b @ no -> loop\n mov r0,r5\n bl affichageMess\n \n mov r0,#0 @ start leval\n mov r1,r12 @ address digits table\n bl searchSoluce\n cmp r0,#-1 @ solution\u00a0?\n bne 3f @ no \n ldr r0,iAdrszMessOK\n bl affichageMess\n bl writeSoluce @ yes -> write solution in buffer \n ldr r0,iAdrsBuffer @ and display buffer\n bl affichageMess\n b 10f\n3: @ display message no solution\n ldr r0,iAdrszMessNotOK\n bl affichageMess\n\n\n10: @ display new game\u00a0?\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n ldr r0,iAdrszMessNewGame\n bl affichageMess\n bl saisie\n cmp r0,#'y'\n beq 1b\n cmp r0,#'Y'\n beq 1b\n \n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessRules: .int szMessRules\niAdrszMessDigits: .int szMessDigits\niAdrszMessNotOK: .int szMessNotOK\niAdrszMessOK: .int szMessOK\niAdrszMessNewGame: .int szMessNewGame\niAdrsZoneConv: .int sZoneConv\niAdriTabDigit: .int iTabDigit\n\/******************************************************************\/\n\/* recherche solution *\/ \n\/******************************************************************\/\n\/* r0 level *\/\n\/* r1 table value address *\/\n\/* r0 return -1 if ok *\/\nsearchSoluce:\n push {r1-r12,lr} @ save registers\n sub sp,#4* NBDIGITS @ reserve size new digits table\n mov fp,sp @ frame pointer = address stack\n mov r10,r1 @ save table\n add r9,r0,#1 @ new level\n rsb r3,r9,#NBDIGITS @ last element digits table\n ldr r4,[r1,r3,lsl #2] @ load last element\n cmp r4,#TOTAL @ equal to total to search\u00a0?\n bne 0f @ no\n cmp r9,#NBDIGITS @ all digits are used\u00a0?\n bne 0f @ no\n mov r0,#-1 @ yes -> it is ok -> end\n b 100f\n0:\n mov r5,#0 @ indice loop 1\n1: @ begin loop 1\n cmp r5,r3\n bge 9f\n ldr r4,[r10,r5,lsl #2] @ load first operand\n ldr r8,iAdriTabOperand1\n str r4,[r8,r9,lsl #2] @ and store in operand1 table\n add r6,r5,#1 @ indice loop 2\n2: @ begin loop 2\n cmp r6,r3\n bgt 8f\n ldr r12,[r10,r6,lsl #2] @ load second operand\n ldr r8,iAdriTabOperand2\n str r12,[r8,r9,lsl #2] @ and store in operand2 table\n mov r7,#0 @ k\n mov r8,#0 @ n\n3: \n cmp r7,r5\n beq 4f\n cmp r7,r6\n beq 4f\n ldr r0,[r10,r7,lsl #2] @ copy other digits in new table on stack\n str r0,[fp,r8,lsl #2]\n add r8,r8,#1\n4:\n add r7,r7,#1\n cmp r7,r3\n ble 3b\n\n add r7,r4,r12 @ addition test\n str r7,[fp,r8,lsl #2] @ store result of addition\n mov r7,#'+'\n ldr r0,iAdriTabOperation\n str r7,[r0,r9,lsl #2] @ store operator\n mov r0,r9 @ pass new level\n mov r1,fp @ pass new table address on stack\n bl searchSoluce\n cmp r0,#0\n blt 100f\n @ soustraction test\n cmp r4,r12\n subgt r7,r4,r12\n suble r7,r12,r4\n str r7,[fp,r8,lsl #2]\n mov r7,#'-'\n ldr r0,iAdriTabOperation\n str r7,[r0,r9,lsl #2]\n mov r0,r9\n mov r1,fp\n bl searchSoluce\n cmp r0,#0\n blt 100f\n \n mul r7,r4,r12 @ multiplication test\n str r7,[fp,r8,lsl #2]\n mov r7,#'*'\n \/\/vidregtit mult\n ldr r0,iAdriTabOperation\n str r7,[r0,r9,lsl #2]\n mov r0,r9\n mov r1,fp\n bl searchSoluce\n cmp r0,#0\n blt 100f\n5: @ division test\n push {r1-r3}\n mov r0,r4\n mov r1,r12\n bl division\n \/\/ mov r7,r9\n cmp r3,#0\n bne 6f\n str r2,[fp,r8,lsl #2]\n mov r7,#'\/'\n ldr r0,iAdriTabOperation\n str r7,[r0,r9,lsl #2]\n mov r0,r9\n mov r1,fp\n bl searchSoluce\n b 7f\n6:\n mov r0,r12\n mov r1,r4\n bl division\n cmp r3,#0\n bne 7f\n str r2,[fp,r8,lsl #2]\n mov r7,#'\/'\n ldr r0,iAdriTabOperation\n str r7,[r0,r9,lsl #2]\n mov r0,r9\n mov r1,fp\n bl searchSoluce\n7:\n pop {r1-r3}\n cmp r0,#0\n blt 100f\n \n add r6,r6,#1 @ increment indice loop 2\n b 2b\n\n8:\n add r5,r5,#1 @ increment indice loop 1\n b 1b\n9:\n \n100:\n add sp,#4* NBDIGITS @ stack alignement\n pop {r1-r12,lr}\n bx lr @ return \niAdriTabOperand1: .int iTabOperand1\niAdriTabOperand2: .int iTabOperand2\niAdriTabOperation: .int iTabOperation\n\/******************************************************************\/\n\/* write solution *\/ \n\/******************************************************************\/\nwriteSoluce:\n push {r1-r12,lr} @ save registers\n ldr r6,iAdriTabOperand1\n ldr r7,iAdriTabOperand2\n ldr r8,iAdriTabOperation\n ldr r10,iAdrsBuffer\n mov r4,#0 @ buffer indice\n mov r9,#1\n1:\n ldr r5,[r6,r9,lsl #2] @ operand 1\n ldr r11,[r7,r9,lsl #2] @ operand 2\n ldr r12,[r8,r9,lsl #2] @ operator\n cmp r12,#'-'\n beq 2f\n cmp r12,#'\/'\n beq 2f\n b 3f\n2: @ if division or soustraction\n cmp r5,r11 @ reverse operand if operand 1 is < operand 2\n movlt r2,r5\n movlt r5,r11\n movlt r11,r2\n3: @ conversion operand 1 = r0\n mov r0,r5\n mov r1,#10\n bl division\n cmp r2,#0\n addne r2,r2,#0x30\n strneb r2,[r10,r4]\n addne r4,r4,#1\n add r3,r3,#0x30\n strb r3,[r10,r4]\n add r4,r4,#1\n ldr r2,[r7,r9,lsl #2]\n\n strb r12,[r10,r4] @ operator\n add r4,r4,#1\n \n mov r0,r11 @ conversion operand 2\n mov r1,#10\n bl division\n cmp r2,#0\n addne r2,r2,#0x30\n strneb r2,[r10,r4]\n addne r4,r4,#1\n add r3,r3,#0x30\n strb r3,[r10,r4]\n add r4,r4,#1\n \n mov r0,#'='\n str r0,[r10,r4] @ conversion sous total\n add r4,r4,#1\n cmp r12,#'+'\n addeq r0,r5,r11\n cmp r12,#'-'\n subeq r0,r5,r11\n cmp r12,#'*'\n muleq r0,r5,r11\n cmp r12,#'\/'\n udiveq r0,r5,r11\n\n mov r1,#10\n bl division\n cmp r2,#0\n addne r2,r2,#0x30\n strneb r2,[r10,r4]\n addne r4,r4,#1\n add r3,r3,#0x30\n strb r3,[r10,r4]\n add r4,r4,#1\n mov r0,#'\\n'\n str r0,[r10,r4]\n add r4,r4,#1\n \n add r9,#1\n cmp r9,#NBDIGITS\n blt 1b\n mov r1,#0\n strb r1,[r10,r4] @ store 0 final\n \n100:\n pop {r1-r12,lr}\n bx lr @ return \niAdrsBuffer: .int sBuffer\n\n\/******************************************************************\/\n\/* string entry *\/ \n\/******************************************************************\/\n\/* r0 return the first character of human entry *\/\nsaisie:\n push {r1-r7,lr} @ save registers\n mov r0,#STDIN @ Linux input console\n ldr r1,iAdrsBuffer @ buffer address \n mov r2,#BUFFERSIZE @ buffer size \n mov r7,#READ @ request to read datas\n svc 0 @ call system\n ldr r1,iAdrsBuffer @ buffer address \n ldrb r0,[r1] @ load first character\n100:\n pop {r1-r7,lr}\n bx lr @ return \n\/***************************************************\/\n\/* Generation random number *\/\n\/***************************************************\/\n\/* r0 contains limit *\/\ngenereraleas:\n push {r1-r4,lr} @ save registers \n ldr r4,iAdriGraine\n ldr r2,[r4]\n ldr r3,iNbDep1\n mul r2,r3,r2\n ldr r3,iNbDep2\n add r2,r2,r3\n str r2,[r4] @ maj de la graine pour l appel suivant \n cmp r0,#0\n beq 100f\n add r1,r0,#1 @ divisor\n mov r0,r2 @ dividende\n bl division\n mov r0,r3 @ r\u00e9sult = remainder\n \n100: @ end function\n pop {r1-r4,lr} @ restaur registers\n bx lr @ return\n\/*****************************************************\/\niAdriGraine: .int iGraine\niNbDep1: .int 0x343FD\niNbDep2: .int 0x269EC3 \n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"The code accepts four digits, either from user input or randomly generated, and calculates arithmetic expressions following the 24 game rules. It also displays examples of the solutions it generates.","id":723} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program factorial.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessLargeNumber: .asciz \"Number N to large. \\n\"\nszMessNegNumber: .asciz \"Number N is negative. \\n\"\n\nszMessResult: .ascii \"Resultat = \" @ message result\nsMessValeur: .fill 12, 1, ' '\n .asciz \"\\n\"\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n push {fp,lr} @ saves 2 registers \n\n mov r0,#-5\n bl factorial\n mov r0,#10\n bl factorial\n mov r0,#20\n bl factorial\n\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\n\n\n\/********************************************\/\n\/* calculation *\/\n\/********************************************\/\n\/* r0 contains number N *\/\nfactorial:\n push {r1,r2,lr} \t@ save registres \n cmp r0,#0\n blt 99f\n beq 100f\n cmp r0,#1\n beq 100f\n bl calFactorial\n cmp r0,#-1 @ overflow\u00a0?\n beq 98f\n ldr r1,iAdrsMessValeur \n bl conversion10 @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n b 100f\n\n98: @ display error message\n ldr r0,iAdrszMessLargeNumber\n bl affichageMess\n b 100f\n99: @ display error message\n ldr r0,iAdrszMessNegNumber\n bl affichageMess\n\n100:\n pop {r1,r2,lr} \t\t\t@ restaur registers \n bx lr\t \t\t\t@ return \niAdrszMessNegNumber: .int szMessNegNumber\niAdrszMessLargeNumber:\t .int szMessLargeNumber\niAdrsMessValeur: .int sMessValeur\t\niAdrszMessResult: .int szMessResult\n\/******************************************************************\/\n\/* calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the number N *\/\ncalFactorial:\n cmp r0,#1 @ N = 1\u00a0?\n bxeq lr @ yes -> return \n push {fp,lr} \t\t@ save registers \n sub sp,#4 @ 4 byte on the stack \n mov fp,sp @ fp <- start address stack\n str r0,[fp] @ fp contains N\n sub r0,#1 @ call function with N - 1\n bl calFactorial\n cmp r0,#-1 @ error overflow\u00a0?\n beq 100f @ yes -> return\n ldr r1,[fp] @ load N\n umull r0,r2,r1,r0 @ multiply result by N \n cmp r2,#0 @ r2 is the hi rd if <> 0 overflow\n movne r0,#-1 @ if overflow -1 -> r0\n\n100:\n add sp,#4 @ free 4 bytes on stack\n pop {fp,lr} \t\t\t@ restau2 registers \n bx lr\t \t\t@ return \n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {fp,lr} \t\t\t\/* save registres *\/ \n push {r0,r1,r2,r7} \t\t\/* save others registers *\/\n mov r2,#0 \t\t\t\t\/* counter length *\/\n1: \t\/* loop length calculation *\/\n ldrb r1,[r0,r2] \t\t\t\/* read octet start position + index *\/\n cmp r1,#0 \t\t\t\/* if 0 its over *\/\n addne r2,r2,#1 \t\t\t\/* else add 1 in the length *\/\n bne 1b \t\t\t\/* and loop *\/\n \/* so here r2 contains the length of the message *\/\n mov r1,r0 \t\t\t\/* address message in r1 *\/\n mov r0,#STDOUT \t\t\/* code to write to the standard output Linux *\/\n mov r7, #WRITE \/* code call system \"write\" *\/\n swi #0 \/* call systeme *\/\n pop {r0,r1,r2,r7} \t\t\/* restaur others registers *\/\n pop {fp,lr} \t\t\t\t\/* restaur des 2 registres *\/ \n bx lr\t \t\t\t\/* return *\/\n\/******************************************************************\/\n\/* Converting a register to a decimal *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\nconversion10:\n push {r1-r4,lr} \/* save registers *\/ \n mov r3,r1\n mov r2,#10\n\n1:\t @ start loop\n bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\t\n strb r1,[r3,r2] @ store digit on area\n sub r2,#1 @ previous position\n cmp r0,#0 @ stop if quotient = 0 *\/\n bne 1b\t @ else loop\n @ and move spaves in first on area\n mov r1,#' ' @ space\t\n2:\t\n strb r1,[r3,r2] @ store space in area\n subs r2,#1 @ @ previous position\n bge 2b @ loop if r2 >= z\u00e9ro \n\n100:\t\n pop {r1-r4,lr} @ restaur registres \n bx lr\t @return\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save registers *\/\n mov r4,r0 \n ldr r3, .Ls_magic_number_10 \/* r1 <- magic_number *\/\n smull r1, r2, r3, r0 \/* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) *\/\n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n .align 4\n.Ls_magic_number_10: .word 0x66666667\n","human_summarization":"The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.","id":724} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program inputLoop.s *\/\n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\n\/*********************************************\/\n\/*constantes *\/\n\/********************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ READ, 3\n.equ WRITE, 4\n.equ OPEN, 5\n.equ CLOSE, 6\n.equ CREATE, 8\n\/* file *\/\n.equ O_RDONLY, 0x0 @ open for reading only\n\n.equ BUFSIZE, 10000\n.equ LINESIZE, 100\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessErreur: .asciz \"Erreur ouverture fichier input.\\n\"\nszMessErreur1: .asciz \"Erreur fermeture fichier.\\n\"\nszMessErreur2: .asciz \"Erreur lecture fichier.\\n\"\nszCarriageReturn: .asciz \"\\n\"\nszMessEndLine: .asciz \"<<<<<< End line.\\n\"\n\nszNameFileInput: .asciz \"input.txt\"\n\n\/*******************************************\/\n\/* DONNEES NON INITIALISEES *\/\n\/*******************************************\/ \n.bss\nsBuffer: .skip BUFSIZE \nsBufferWord: .skip LINESIZE\n\/**********************************************\/\n\/* -- Code section *\/\n\/**********************************************\/\n.text \n.global main \nmain:\n \/* open file *\/\n ldr r0,iAdrszNameFileInput @ file name\n mov r1,#O_RDONLY @ flags \n mov r2,#0 @ mode \n mov r7,#OPEN @ call system OPEN\n svc #0 \n cmp r0,#0 @ open error\u00a0?\n ble erreur\n \/* read file *\/\n mov r9,r0 @ save File Descriptor\n ldr r1,iAdrsBuffer @ buffer address \n mov r2,#BUFSIZE @ buffer size\n mov r7, #READ @ call system READ\n svc 0 \n cmp r0,#0 @ read error\u00a0?\n ble erreur2\n mov r2,r0 @ length read characters\n \/* buffer analyze *\/\n ldr r3,iAdrsBuffer @ buffer address\n ldr r5,iAdrsBufferWord @ buffer address\n mov r7,#0 @ word byte counter\n mov r4,#0 @ byte counter\n1:\n ldrb r6,[r3,r4] @ load byte buffer\n cmp r6,#' ' @ space\u00a0?\n moveq r8,#0 @ yes\n beq 2f\n cmp r6,#0xA @ end line\u00a0?\n moveq r8,#1\n beq 2f\n cmp r6,#0xD @ end line\u00a0?\n beq 3f\n strb r6,[r5,r7] @ store byte\n add r7,#1 @ increment word byte counter\n b 4f\n2: @ word end\n cmp r7,#0\n beq 3f\n mov r6,#0 @ store 0 final\n strb r6,[r5,r7]\n mov r0,r5 @ display word\n bl affichageMess\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n mov r7,#0 @ raz word byte counter \n3:\n cmp r8,#1 @ end line\u00a0?\n bne 4f\n ldr r0,iAdrszMessEndLine\n bl affichageMess\n4: \n add r4,#1 @ increment read buffer counter\n cmp r4,r2 @ end bytes\u00a0?\n blt 1b @ no -> loop \n\n4:\n \/* close imput file *\/\n mov r0,r9 @ Fd\n mov r7, #CLOSE @ call system CLOSE\n svc 0 \n cmp r0,#0 @ close error\u00a0?\n blt erreur1\n\n\n mov r0,#0 @ return code OK\n b 100f\nerreur:\n ldr r1,iAdrszMessErreur \n bl displayError\n mov r0,#1 @ error return code\n b 100f\nerreur1: \n ldr r1,iAdrszMessErreur1 \n bl displayError\n mov r0,#1 @ error return code\n b 100f\nerreur2:\n ldr r1,iAdrszMessErreur2 \n bl displayError\n mov r0,#1 @ error return code\n b 100f\n\n\n100: @ end program\n mov r7, #EXIT \n svc 0 \niAdrszNameFileInput: .int szNameFileInput\niAdrszMessErreur: .int szMessErreur\niAdrszMessErreur1: .int szMessErreur1\niAdrszMessErreur2: .int szMessErreur2\niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessEndLine: .int szMessEndLine\niAdrsBuffer: .int sBuffer\niAdrsBufferWord: .int sBufferWord\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"\"Continuously read words or lines from a text stream until there is no more data available.\"","id":725} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program createXml.s *\/\n\/* install package libxml++2.6-dev *\/\n\/* link with gcc option -lxml2 *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessEndpgm: .asciz \"Normal end of program.\\n\" \nszFileName: .asciz \"file1.xml\" \nszFileMode: .asciz \"w\"\nszMessError: .asciz \"Error detected\u00a0!!!!. \\n\"\n\nszVersDoc: .asciz \"1.0\"\nszLibRoot: .asciz \"root\"\nszLibElement: .asciz \"element\"\nszText: .asciz \"some text here\"\nszCarriageReturn: .asciz \"\\n\"\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n.align 4\n\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdrszVersDoc\n bl xmlNewDoc @ create doc\n mov r9,r0 @ doc address\n mov r0,#0\n ldr r1,iAdrszLibRoot\n bl xmlNewNode @ create root node\n mov r8,r0 @ node root address\n mov r0,r9\n mov r1,r8\n bl xmlDocSetRootElement\n@TODO voir la gestion des erreurs\n\n mov r0,#0\n ldr r1,iAdrszLibElement\n bl xmlNewNode @ create element node\n mov r7,r0 @ node element address\n ldr r0,iAdrszText\n bl xmlNewText @ create text\n mov r6,r0 @ text address\n mov r0,r7 @ node element address\n mov r1,r6 @ text address\n bl xmlAddChild @ add text to element node\n mov r0,r8 @ node root address\n mov r1,r7 @ node element address\n bl xmlAddChild @ add node elemeny to root node\n ldr r0,iAdrszFileName\n ldr r1,iAdrszFileMode\n bl fopen @ file open\n cmp r0,#0\n blt 99f\n mov r5,r0 @ File descriptor\n mov r1,r9 @ doc\n mov r2,r8 @ root\n bl xmlElemDump @ write xml file\n cmp r0,#0\n blt 99f\n mov r0,r5\n bl fclose @ file close\n mov r0,r9\n bl xmlFreeDoc\n bl xmlCleanupParser\n ldr r0,iAdrszMessEndpgm\n bl affichageMess\n b 100f\n99:\n @ error\n ldr r0,iAdrszMessError\n bl affichageMess \n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrszMessError: .int szMessError\niAdrszMessEndpgm: .int szMessEndpgm\niAdrszVersDoc: .int szVersDoc\niAdrszLibRoot: .int szLibRoot\niAdrszLibElement: .int szLibElement\niAdrszText: .int szText\niAdrszFileName: .int szFileName\niAdrszFileMode: .int szFileMode\niAdrszCarriageReturn: .int szCarriageReturn\n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur registers *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n1: @ start loop\n bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ previous position \n bne 1b @ else loop\n @ end replaces digit in front of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2] \n strb r1,[r3,r4] @ store in area begin\n add r4,#1\n add r2,#1 @ previous position\n cmp r2,#LGZONECAL @ end\n ble 2b @ loop\n mov r1,#' '\n3:\n strb r1,[r3,r4]\n add r4,#1\n cmp r4,#LGZONECAL @ end\n ble 3b\n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\n\/* r1 remainder *\/\ndivisionpar10:\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} @ save registers *\/\n mov r4,r0 \n mov r3,#0x6667 @ r3 <- magic_number lower\n movt r3,#0x6666 @ r3 <- magic_number upper\n smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) \n mov r2, r2, ASR #2 @ r2 <- r2 >> 2\n mov r1, r0, LSR #31 @ r1 <- r0 >> 31\n add r0, r2, r1 @ r0 <- r2 + r1 \n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2-r4}\n bx lr @ return\n","human_summarization":"Create a simple DOM and serialize it into the specified XML format.","id":726} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program sysTime.s *\/\n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\n\/*******************************************\/\n\/* Constantes *\/\n\/*******************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ BRK, 0x2d @ Linux syscall\n.equ CHARPOS, '@'\n\n.equ GETTIME, 0x4e @ call system linux gettimeofday\n\n\/*******************************************\/\n\/* Structures *\/\n\/********************************************\/\n\/* example structure time *\/\n .struct 0\ntimeval_sec: @\n .struct timeval_sec + 4 \ntimeval_usec: @\n .struct timeval_usec + 4 \ntimeval_end:\n .struct 0\ntimezone_min: @\n .struct timezone_min + 4 \ntimezone_dsttime: @ \n .struct timezone_dsttime + 4 \ntimezone_end:\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessError: .asciz \"Error detected\u00a0!!!!. \\n\"\nszMessResult: .asciz \"GMT: @\/@\/@ @:@:@ @ms\\n\" @ message result\n \nszCarriageReturn: .asciz \"\\n\"\n.align 4\ntbDayMonthYear: .int 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335\n .int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700\n .int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065\n .int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n.align 4\nstTVal: .skip timeval_end\nstTZone: .skip timezone_end\nsZoneConv: .skip 100\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdrstTVal\n ldr r1,iAdrstTZone\n mov r7,#GETTIME\n svc 0\n cmp r0,#-1 @ error\u00a0?\n beq 99f\n ldr r0,iAdrstTVal\n ldr r1,[r0,#timeval_sec] @ timestemp in second\n \/\/ldr r1,iTStest1\n \/\/ldr r1,iTStest2\n \/\/ldr r1,iTStest3\n ldr r2,iSecJan2020\n sub r0,r1,r2 @ total secondes to 01\/01\/2020\n mov r1,#60\n bl division\n mov r0,r2\n mov r6,r3 @ compute secondes\n mov r1,#60\n bl division\n mov r7,r3 @ compute minutes\n mov r0,r2\n mov r1,#24\n bl division\n mov r8,r3 @ compute hours\n mov r0,r2\n mov r11,r0\n mov r1,#(365 * 4 + 1)\n bl division\n lsl r9,r2,#2 @ multiply by 4 = year1\n mov r1,#(365 * 4 + 1)\n mov r0,r11\n bl division\n mov r10,r3\n ldr r1,iAdrtbDayMonthYear\n mov r2,#3\n mov r3,#12\n1:\n mul r11,r3,r2\n ldr r12,[r1,r11,lsl #2] @ load days by year\n cmp r10,r12\n bge 2f\n sub r2,r2,#1\n cmp r2,#0\n bne 1b\n2: @ r2 = year2\n mov r5,#11\n mul r4,r3,r2\n lsl r4,#2\n add r4,r1\n3:\n ldr r12,[r4,r5,lsl #2] @ load days by month\n cmp r10,r12\n bge 4f\n subs r5,r5,#1\n bne 3b\n4: @ r5 = month - 1\n mul r11,r3,r2\n add r11,r5\n ldr r1,iAdrtbDayMonthYear\n ldr r3,[r1,r11,lsl #2]\n sub r0,r10,r3\n\n add r0,r0,#1 @ final compute day\n ldr r1,iAdrsZoneConv\n bl conversion10 @ this function do not zero final\n mov r4,#0 @ store zero final\n strb r4,[r1,r0]\n ldr r0,iAdrszMessResult\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at first @ character\n mov r3,r0\n add r0,r5,#1 @ final compute month\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r4,#0 @ store zero final\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at next @ character\n mov r3,r0\n ldr r11,iYearStart\n add r0,r9,r11\n add r0,r0,r2 @ final compute year = 2020 + year1 + year2\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r4,#0 @ store zero final\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at next @ character\n mov r3,r0\n mov r0,r8 @ hours\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r4,#0 @ store zero final\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at next @ character\n mov r3,r0\n mov r0,r7 @ minutes\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r4,#0 @ store zero final\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at next @ character\n mov r3,r0\n mov r0,r6 @ secondes\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r4,#0 @ store zero final\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at next @ character\n mov r3,r0\n ldr r1,iAdrstTVal\n ldr r0,[r1,#timeval_usec] @ millisecondes\n ldr r1,iAdrsZoneConv\n bl conversion10\n mov r4,#0 @ store zero final\n strb r4,[r1,r0]\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc @ insert result at next @ character\n bl affichageMess \n b 100f\n99:\n ldr r0,iAdrszMessError\n bl affichageMess \n100: @ standard end of the program \n mov r0,#0 @ return code\n mov r7,#EXIT @ request to exit program\n svc 0 @ perform the system call\n\niAdrszMessError: .int szMessError\niAdrstTVal: .int stTVal\niAdrstTZone: .int stTZone\niAdrszMessResult: .int szMessResult\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsZoneConv: .int sZoneConv\niSecJan2020: .int 1577836800\niAdrtbDayMonthYear: .int tbDayMonthYear\niYearStart: .int 2020\niTStest1: .int 1609508339 @ 01\/01\/2021\niTStest2: .int 1657805939 @ 14\/07\/2022\niTStest3: .int 1767221999 @ 31\/12\/2025\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":727} {"lang_cluster":"ARM_Assembly","source_code":"\nProgramStart:\n\tmov sp,#0x03000000\t\t\t;Init Stack Pointer\n\t\n\tmov r4,#0x04000000 \t\t ;DISPCNT -LCD Control\n\tmov r2,#0x403 \t\t\t;4= Layer 2 on \/ 3= ScreenMode 3\n\tstr r2,[r4] \t ;hardware specific routine, activates Game Boy's bitmap mode\n\n\tmov r0,#0x61\t\t\t\t;ASCII \"a\"\n\tmov r2,#ramarea\n\tmov r1,#26\t\t\t\t\t\n\t\nrep_inc_stosb: ;repeatedly store a byte into memory, incrementing the destination and the value stored\n \u00a0; each time.\n\tstrB r0,[r2]\n\tadd r0,r0,#1\n\tadd r2,r2,#1\n\tsubs r1,r1,#1\n\tbne rep_inc_stosb\n\tmov r0,#255\t\t\n\tstrB r0,[r2]\t\t\t\t;store a 255 terminator into r1\n\t\n\tmov r1,#ramarea\n\tbl PrintString ;Prints a 255-terminated string using a pre-defined bitmap font. Code omitted for brevity\n\nforever:\n b forever ;halt the cpu\n\n","human_summarization":"generate an array or list of all lower case ASCII characters from 'a' to 'z'. The code also demonstrates how to access a similar sequence from the standard library, if available. The coding style used is reliable and suitable for large programs, with strong typing implemented where possible. The code avoids manually enumerating all lowercase characters to prevent bugs. It also includes a feature to print the generated string of lower case ASCII characters to the screen. The code is written in VASM syntax and is designed for the Game Boy Advance hardware.","id":728} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program binarydigit.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1\n.equ WRITE, 4\n.equ EXIT, 1\n\/* Initialized data *\/\n.data\n\nsMessAffBin: .ascii \"The decimal value \"\nsZoneDec: .space 12,' '\n .ascii \" should produce an output of \"\nsZoneBin: .space 36,' '\n .asciz \"\\n\"\n\n\/* code section *\/\n.text\n.global main \nmain: \/* entry of program *\/\n push {fp,lr} \/* save des 2 registres *\/\n mov r0,#5\n ldr r1,iAdrsZoneDec\n bl conversion10S @ decimal conversion\n bl conversion2 @ binary conversion and display r\u00e9sult\n mov r0,#50\n ldr r1,iAdrsZoneDec\n bl conversion10S\n bl conversion2\n mov r0,#-1\n ldr r1,iAdrsZoneDec\n bl conversion10S\n bl conversion2\n mov r0,#1\n ldr r1,iAdrsZoneDec\n bl conversion10S\n bl conversion2\n\n100: \/* standard end of the program *\/\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrsZoneDec: .int sZoneDec\n\/******************************************************************\/\n\/* register conversion in binary *\/ \n\/******************************************************************\/\n\/* r0 contains the register *\/\nconversion2:\n push {r0,lr} \/* save registers *\/ \n push {r1-r5} \/* save others registers *\/\n ldr r1,iAdrsZoneBin @ address reception area\n clz r2,r0 @ number of left zeros bits \n rsb r2,#32 @ number of significant bits\n mov r4,#' ' @ space\n add r3,r2,#1 @ position counter in reception area\n1:\n strb r4,[r1,r3] @ space in other location of reception area\n add r3,#1\n cmp r3,#32 @ end of area\u00a0?\n ble 1b @ no! loop\n mov r3,r2 @ position counter of the written character\n2: @ loop \n lsrs r0,#1 @ shift right one bit with flags\n movcc r4,#48 @ carry clear => character 0\n movcs r4,#49 @ carry set => character 1 \n strb r4,[r1,r3] @ character in reception area at position counter\n sub r3,r3,#1 @ \n subs r2,r2,#1 @ 0 bits\u00a0?\n bgt 2b @ no! loop\n \n ldr r0,iAdrsZoneMessBin\n bl affichageMess\n \n100:\n pop {r1-r5} \/* restaur others registers *\/\n pop {r0,lr}\n bx lr\t\niAdrsZoneBin: .int sZoneBin\t \niAdrsZoneMessBin: .int sMessAffBin\n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {fp,lr} \t\t\t\/* save registres *\/ \n push {r0,r1,r2,r7} \t\t\/* save others registres *\/\n mov r2,#0 \t\t\t\t\/* counter length *\/\n1: \t\/* loop length calculation *\/\n ldrb r1,[r0,r2] \t\t\t\/* read octet start position + index *\/\n cmp r1,#0 \t\t\t\/* if 0 its over *\/\n addne r2,r2,#1 \t\t\t\/* else add 1 in the length *\/\n bne 1b \t\t\t\/* and loop *\/\n \/* so here r2 contains the length of the message *\/\n mov r1,r0 \t\t\t\/* address message in r1 *\/\n mov r0,#STDOUT \t\t\/* code to write to the standard output Linux *\/\n mov r7, #WRITE \/* code call system \"write\" *\/\n swi #0 \/* call systeme *\/\n pop {r0,r1,r2,r7} \t\t\/* restaur others registres *\/\n pop {fp,lr} \t\t\t\t\/* restaur des 2 registres *\/ \n bx lr\t \t\t\t\/* return *\/\t\n\/***************************************************\/\n\/* conversion registre en d\u00e9cimal sign\u00e9 *\/\n\/***************************************************\/\n\/* r0 contient le registre *\/\n\/* r1 contient l adresse de la zone de conversion *\/\nconversion10S:\n push {fp,lr} \/* save des 2 registres frame et retour *\/\n push {r0-r5} \/* save autres registres *\/\n mov r2,r1 \/* debut zone stockage *\/\n mov r5,#'+' \/* par defaut le signe est + *\/\n cmp r0,#0 \/* nombre n\u00e9gatif\u00a0? *\/\n movlt r5,#'-' \/* oui le signe est - *\/\n mvnlt r0,r0 \/* et inversion en valeur positive *\/\n addlt r0,#1\n mov r4,#10 \/* longueur de la zone *\/\n1: \/* debut de boucle de conversion *\/\n bl divisionpar10 \/* division *\/\n add r1,#48 \/* ajout de 48 au reste pour conversion ascii *\/\t\n strb r1,[r2,r4] \/* stockage du byte en d\u00e9but de zone r5 + la position r4 *\/\n sub r4,r4,#1 \/* position pr\u00e9cedente *\/\n cmp r0,#0 \n bne 1b\t \/* boucle si quotient different de z\u00e9ro *\/\n strb r5,[r2,r4] \/* stockage du signe \u00e0 la position courante *\/\n subs r4,r4,#1 \/* position pr\u00e9cedente *\/\n blt 100f \/* si r4 < 0 fin *\/\n \/* sinon il faut completer le debut de la zone avec des blancs *\/\n mov r3,#' ' \/* caractere espace *\/\t\n2:\n strb r3,[r2,r4] \/* stockage du byte *\/\n subs r4,r4,#1 \/* position pr\u00e9cedente *\/\n bge 2b \/* boucle si r4 plus grand ou egal a zero *\/\n100: \/* fin standard de la fonction *\/\n pop {r0-r5} \/*restaur des autres registres *\/\n pop {fp,lr} \/* restaur des 2 registres frame et retour *\/\n bx lr \n\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 contient le dividende *\/\n\/* r0 retourne le quotient *\/\t\n\/* r1 retourne le reste *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save others registers *\/\n mov r4,r0 \n ldr r3, .Ls_magic_number_10 \/* r1 <- magic_number *\/\n smull r1, r2, r3, r0 \/* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) *\/\n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n .align 4\n.Ls_magic_number_10: .word 0x66666667\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":729} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program dpixel.s *\/\n\n\/* compile with as *\/\n\/* link with gcc and options -lX11 -L\/usr\/lpp\/X11\/lib *\/\n\n\/********************************************\/\n\/*Constantes *\/\n\/********************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/* constantes X11 *\/\n.equ KeyPressed, 2\n.equ ButtonPress, 4\n.equ MotionNotify, 6\n.equ EnterNotify, 7\n.equ LeaveNotify, 8\n.equ Expose, 12\n.equ ClientMessage, 33\n.equ KeyPressMask, 1\n.equ ButtonPressMask, 4\n.equ ButtonReleaseMask, 8\n.equ ExposureMask, 1<<15\n.equ StructureNotifyMask, 1<<17\n.equ EnterWindowMask, 1<<4\n.equ LeaveWindowMask, 1<<5 \n.equ ConfigureNotify, 22\n\n\n\/*******************************************\/\n\/* DONNEES INITIALISEES *\/\n\/*******************************************\/ \n.data\nszWindowName: .asciz \"Windows Raspberry\"\nszRetourligne: .asciz \"\\n\"\nszMessDebutPgm: .asciz \"Program start. \\n\"\nszMessErreur: .asciz \"Server X not found.\\n\"\nszMessErrfen: .asciz \"Can not create window.\\n\"\nszMessErreurX11: .asciz \"Error call function X11. \\n\"\nszMessErrGc: .asciz \"Can not create graphics context.\\n\"\nszTitreFenRed: .asciz \"Pi\" \nszTexte1: .asciz \"<- red pixel is here\u00a0!!\"\n.equ LGTEXTE1, . - szTexte1\nszTexte2: .asciz \"Press q for close window or clic X in system menu.\"\n.equ LGTEXTE2, . - szTexte2\nszLibDW: .asciz \"WM_DELETE_WINDOW\" @ special label for correct close error\n\n\/*************************************************\/\nszMessErr: .ascii\t\"Error code hexa\u00a0: \"\nsHexa: .space 9,' '\n .ascii \" decimal\u00a0: \"\nsDeci: .space 15,' '\n .asciz \"\\n\"\n\n\/*******************************************\/\n\/* DONNEES NON INITIALISEES *\/\n\/*******************************************\/ \n.bss\n.align 4\nptDisplay: .skip 4 @ pointer display\nptEcranDef: .skip 4 @ pointer screen default\nptFenetre: .skip 4 @ pointer window\nptGC: .skip 4 @ pointer graphic context\nptGC1: .skip 4 @ pointer graphic context1\nkey: .skip 4 @ key code\nwmDeleteMessage: .skip 8 @ ident close message\nevent: .skip 400 @ TODO event size\u00a0??\nPrpNomFenetre: .skip 100 @ window name proprety\nbuffer: .skip 500 \niWhite: .skip 4 @ rgb code for white pixel\niBlack: .skip 4 @ rgb code for black pixel\n\/**********************************************\/\n\/* -- Code section *\/\n\/**********************************************\/\n.text\n.global main\n\nmain: @ entry of program \n ldr r0,iAdrszMessDebutPgm @\n bl affichageMess @ display start message on console linux\n \/* attention r6 pointer display*\/\n \/* attention r8 pointer graphic context *\/\n \/* attention r9 ident window *\/\n \/*****************************\/\n \/* OPEN SERVER X11 *\/\n \/*****************************\/\n mov r0,#0\n bl XOpenDisplay @ open X server\n cmp r0,#0 @ error\u00a0?\n beq erreurServeur\n ldr r1,iAdrptDisplay\n str r0,[r1] @ store display address \n mov r6,r0 @ and in register r6\n ldr r2,[r0,#+132] @ load default_screen\n ldr r1,iAdrptEcranDef\n str r2,[r1] @ store default_screen\n mov r2,r0\n ldr r0,[r2,#+140] @ load pointer screen list\n ldr r5,[r0,#+52] @ load value white pixel\n ldr r4,iAdrWhite @ and store in memory\n str r5,[r4]\n ldr r3,[r0,#+56] @ load value black pixel\n ldr r4,iAdrBlack @ and store in memory\n str r3,[r4]\n ldr r4,[r0,#+28] @ load bits par pixel\n ldr r1,[r0,#+8] @ load root windows\n \/**************************\/\n \/* CREATE WINDOW *\/\n \/**************************\/\n mov r0,r6 @ address display\n mov r2,#0 @ window position X\n mov r3,#0 @ window position Y\n mov r8,#0 @ for stack alignement\n push {r8}\n push {r3} @ background = black pixel\n push {r5} @ border = white pixel\n mov r8,#2 @ border size\n push {r8}\n mov r8,#240 @ hauteur\n push {r8}\n mov r8,#320 @ largeur \n push {r8} \n bl XCreateSimpleWindow\n add sp,#24 @ stack alignement 6 push (4 bytes * 6)\n cmp r0,#0 @ error\u00a0?\n beq erreurF\n\n ldr r1,iAdrptFenetre\n str r0,[r1] @ store window address in memory\n mov r9,r0 @ and in register r9\n \/*****************************\/\n \/* add window property *\/\n \/*****************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n ldr r2,iAdrszWindowName @ window name\n ldr r3,iAdrszTitreFenRed @ window name reduced\n mov r4,#0\n push {r4} @ parameters not use\n push {r4}\n push {r4}\n push {r4}\n bl XSetStandardProperties\n add sp,sp,#16 @ stack alignement for 4 push\n \/**************************************\/\n \/* for correction window close error *\/\n \/**************************************\/\n mov r0,r6 @ display address\n ldr r1,iAdrszLibDW @ atom address\n mov r2,#1 @ False cr\u00e9ate atom if not exists\n bl XInternAtom\n cmp r0,#0 @ error X11\u00a0?\n ble erreurX11\n ldr r1,iAdrwmDeleteMessage @ recept address\n str r0,[r1]\n mov r2,r1 @ return address\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n mov r3,#1 @ number of protocols\n bl XSetWMProtocols\n cmp r0,#0 @ error X11\u00a0?\n ble erreurX11\n \/**********************************\/\n \/* create graphic context *\/\n \/**********************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n mov r2,#0 @ not use for simply context\n mov r3,#0\n bl XCreateGC\n cmp r0,#0 @ error\u00a0?\n beq erreurGC\n ldr r1,iAdrptGC\n str r0,[r1] @ store address graphic context\n mov r8,r0 @ and in r8\n @ create other GC\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n mov r2,#0 @ not use for simply context\n mov r3,#0\n bl XCreateGC\n cmp r0,#0 @ error\u00a0?\n beq erreurGC\n ldr r1,iAdrptGC1\n str r0,[r1] @ store address graphic context 1\n mov r1,r0\n mov r0,r6\n mov r2,#0xFF0000 @ color red\n bl XSetForeground\n cmp r0,#0\n beq erreurGC\n \/****************************\/\n \/* modif window background *\/\n \/****************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n ldr r2,iGris1 @ background color\n bl XSetWindowBackground \n cmp r0,#0 @ error\u00a0?\n ble erreurX11\n \/***************************\/\n \/* OUF!! window display *\/\n \/***************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n bl XMapWindow\n \/****************************\/\n \/* Write text1 in the window *\/\n \/****************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n mov r2,r8 @ address graphic context\n mov r3,#105 @ position x \n sub sp,#4 @ stack alignement\n mov r4,#LGTEXTE1 - 1 @ size string \n push {r4} @ on the stack\n ldr r4,iAdrszTexte1 @ string address\n push {r4}\n mov r4,#105 @ position y \n push {r4}\n bl XDrawString\n add sp,sp,#16 @ stack alignement 3 push and 1 stack alignement\n cmp r0,#0 @ error\u00a0?\n blt erreurX11\n \/****************************\/\n \/* Write text2 in the window *\/\n \/****************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n mov r2,r8 @ address graphic context\n mov r3,#10 @ position x \n sub sp,#4 @ stack alignement\n mov r4,#LGTEXTE2 - 1 @ size string \n push {r4} @ on the stack\n ldr r4,iAdrszTexte2 @ string address\n push {r4}\n mov r4,#200 @ position y \n push {r4}\n bl XDrawString\n add sp,sp,#16 @ stack alignement 3 push and 1 stack alignement\n cmp r0,#0 @ error\u00a0?\n blt erreurX11\n \/****************************************\/\n \/* draw pixel *\/\n \/****************************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n ldr r2,iAdrptGC1\n ldr r2,[r2] @ address graphic context 1\n mov r3,#100 @ position x\n sub sp,sp,#4 @ stack alignement\n mov r4,#100 @ position y\n push {r4} @ on the stack\n bl XDrawPoint\n add sp,sp,#8 @ stack alignement 1 push and 1 stack alignement\n\n cmp r0,#0 @ error\u00a0?\n blt erreurX11\n \/****************************\/\n \/* Autorisations *\/\n \/****************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n ldr r2,iFenetreMask @ autorisation mask\n bl XSelectInput\n cmp r0,#0 @ error\u00a0?\n ble erreurX11\n \/****************************\/\n \/* Events loop *\/\n \/****************************\/\n1:\n mov r0,r6 @ display address\n ldr r1,iAdrevent @ events address\n bl XNextEvent @ event\u00a0?\n ldr r0,iAdrevent\n ldr r0,[r0] @ code event\n cmp r0,#KeyPressed @ key\u00a0?\n bne 2f\n ldr r0,iAdrevent @ yes read key in buffer\n ldr r1,iAdrbuffer\n mov r2,#255\n ldr r3,iAdrkey\n mov r4,#0\n push {r4} @ stack alignement\n push {r4}\n bl XLookupString \n add sp,#8 @ stack alignement 2 push\n cmp r0,#1 @ is character key\u00a0?\n bne 2f\n ldr r0,iAdrbuffer @ yes -> load first buffer character\n ldrb r0,[r0]\n cmp r0,#0x71 @ character q for quit\n beq 5f @ yes -> end\n b 4f\n2:\n \/* *\/\n \/* for example clic mouse button *\/\n \/************************************\/\n cmp r0,#ButtonPress @ clic mouse buton\n bne 3f\n ldr r0,iAdrevent\n ldr r1,[r0,#+32] @ position X mouse clic\n ldr r2,[r0,#+36] @ position Y\n @ etc for eventuel use\n b 4f\n3:\n cmp r0,#ClientMessage @ code for close window within error\n bne 4f\n ldr r0,iAdrevent\n ldr r1,[r0,#+28] @ code message address \n ldr r2,iAdrwmDeleteMessage @ equal code window cr\u00e9ate\u00a0???\n ldr r2,[r2]\n cmp r1,r2\n beq 5f @ yes -> end window \n\n4: @ loop for other event\n b 1b\n \/***********************************\/\n \/* Close window -> free ressources *\/\n \/***********************************\/\n5:\n mov r0,r6 @ display address\n ldr r1,iAdrptGC\n ldr r1,[r1] @ load context graphic address \n bl XFreeGC\n cmp r0,#0\n blt erreurX11\n mov r0,r6 @ display address \n mov r1,r9 @ window address\n bl XDestroyWindow\n cmp r0,#0\n blt erreurX11\n mov r0,r6 @ display address\n bl XCloseDisplay\n cmp r0,#0\n blt erreurX11\n mov r0,#0 @ return code OK\n b 100f\nerreurF: @ create error window but possible not necessary. Display error by server\n ldr r1,iAdrszMessErrfen\n bl displayError\n mov r0,#1 @ return error code\n b 100f\nerreurGC: @ error create graphic context\n ldr r1,iAdrszMessErrGc\n bl displayError\n mov r0,#1\n b 100f\nerreurX11: @ erreur X11\n ldr r1,iAdrszMessErreurX11\n bl displayError\n mov r0,#1\n b 100f\nerreurServeur: @ error no found X11 server see doc putty and Xming\n ldr r1,iAdrszMessErreur\n bl displayError\n mov r0,#1\n b 100f\n\n100: @ standard end of the program \n mov r7, #EXIT\n svc 0 \niFenetreMask: .int KeyPressMask|ButtonPressMask|StructureNotifyMask\niGris1: .int 0xFFA0A0A0\niAdrWhite: .int iWhite\niAdrBlack: .int iBlack\niAdrptDisplay: .int ptDisplay\niAdrptEcranDef: .int ptEcranDef\niAdrptFenetre: .int ptFenetre\niAdrptGC: .int ptGC\niAdrptGC1: .int ptGC1\niAdrevent: .int event\niAdrbuffer: .int buffer\niAdrkey: .int key\niAdrszLibDW: .int szLibDW\niAdrszMessDebutPgm: .int szMessDebutPgm\niAdrszMessErreurX11: .int szMessErreurX11\niAdrszMessErrGc: .int szMessErrGc\niAdrszMessErreur: .int szMessErreur\niAdrszMessErrfen: .int szMessErrfen\niAdrszWindowName: .int szWindowName\niAdrszTitreFenRed: .int szTitreFenRed\niAdrszTexte1: .int szTexte1\niAdrszTexte2: .int szTexte2\niAdrPrpNomFenetre: .int PrpNomFenetre\niAdrwmDeleteMessage: .int wmDeleteMessage\n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur registers\n bx lr @ return\n\/***************************************************\/\n\/* display error message *\/\n\/***************************************************\/\n\/* r0 contains error code r1\u00a0: message address *\/\ndisplayError:\n push {r0-r2,lr} @ save registers\n mov r2,r0 @ save error code\n mov r0,r1\n bl affichageMess\n mov r0,r2 @ error code\n ldr r1,iAdrsHexa\n bl conversion16 @ conversion hexa\n mov r0,r2 @ error code\n ldr r1,iAdrsDeci @ result address\n bl conversion10 @ conversion decimale\n ldr r0,iAdrszMessErr @ display error message\n bl affichageMess\n100:\n pop {r0-r2,lr} @ restaur registers\n bx lr @ return \niAdrszMessErr: .int szMessErr\niAdrsHexa: .int sHexa\niAdrsDeci: .int sDeci\n\/******************************************************************\/\n\/* Converting a register to hexadecimal *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\nconversion16:\n push {r1-r4,lr} @ save registers\n mov r2,#28 @ start bit position\n mov r4,#0xF0000000 @ mask\n mov r3,r0 @ save entry value\n1: @ start loop\n and r0,r3,r4 @value register and mask\n lsr r0,r2 @ move right \n cmp r0,#10 @ compare value\n addlt r0,#48 @ <10 ->digit\t\n addge r0,#55 @ >10 ->letter A-F\n strb r0,[r1],#1 @ store digit on area and + 1 in area address\n lsr r4,#4 @ shift mask 4 positions\n subs r2,#4 @ counter bits - 4 <= zero \u00a0?\n bge 1b @ no -> loop\n\n100:\n pop {r1-r4,lr} @ restaur registers \n bx lr @return\n\/******************************************************************\/\n\/* Converting a register to a decimal unsigned *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\n\/* r0 return size of result (no zero final in area) *\/\n\/* area size => 11 bytes *\/\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n1: @ start loop\n bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n \n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n \n\/***************************************************\/\n\/* division par 10 unsigned *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\n\/* r1 remainder *\/\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: \t.int 0xCCCCCCCD\n\/***************************************************\/\n\/* integer division unsigned *\/\n\/***************************************************\/\ndivision:\n \/* r0 contains dividend *\/\n \/* r1 contains divisor *\/\n \/* r2 returns quotient *\/\n \/* r3 returns remainder *\/\n push {r4, lr}\n mov r2, #0 @ init quotient\n mov r3, #0 @ init remainder\n mov r4, #32 @ init counter bits\n b 2f\n1: @ loop \n movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)\n adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3\u00a0? (r3 << 1) + C \n cmp r3, r1 @ compute r3 - r1 and update cpsr \n subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1 \n adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C \n2:\n subs r4, r4, #1 @ r4 <- r4 - 1 \n bpl 1b @ if r4 >= 0 (N=0) then loop\n pop {r4, lr}\n bx lr\n","human_summarization":"\"Creates a 320x240 window and draws a single red pixel at position (100, 100).\"","id":730} {"lang_cluster":"ARM_Assembly","source_code":"\n.text\n.global _start\n_start:\n ldr r0, =example_numbers\n bl test_number\n\n add r1, r0, #1\n bl length\n add r0, r1, r0\n bl test_number\n \n add r1, r0, #1\n bl length\n add r0, r1, r0\n bl test_number\n \n add r1, r0, #1\n bl length\n add r0, r1, r0\n bl test_number\n\n mov r0, #0\n mov r7, #1\n swi 0\n\ntest_number:\n push {r0, lr}\n bl print_string\n\n bl luhn_test\n cmp r0, #1\n ldreq r0, =valid_message\n ldrne r0, =invalid_message\n bl print_string\n pop {r0, lr}\n mov pc, lr\n\n\n\nprint_string:\n push {r0-r7, lr}\n mov r1, r0 @ string to print\n bl length\n mov r2, r0 @ length of string\n mov r0, #1 @ write to stdout\n mov r7, #4 @ SYS_WRITE\n swi 0 @ call system interupt\n pop {r0-r7, lr}\n mov pc, lr\n\n@ r0 address of credit card number string\n@ returns result in r0\nluhn_test:\n push {r1-r7, lr}\n mov r1, r0\n bl isNumerical @ check if string is a number\n cmp r0, #1\n bne .luhn_test_end @ exit if not number\n mov r0, r1 \n ldr r1, =reversed_string @ address to store reversed string\n bl reverse @ reverse string\n push {r0}\n bl length @ get length of string\n mov r4, r0 @ store string length in r4 \n pop {r0}\n mov r2, #0 @ string index\n mov r6, #0 @ sum of odd digits\n mov r7, #0 @ sum of even digits\n .loadNext:\n ldrb r3, [r1, r2] @ load byte into r3\n sub r3, #'0' @ convert letter to digit\n and r5, r2, #1 @ test if index is even or odd\n cmp r5, #0\n beq .odd_digit\n bne .even_digit\n .odd_digit:\n add r6, r3 @ add digit to sum if odd\n b .continue @ skip next step\n .even_digit:\n lsl r3, #1 @ multiply digit by 2\n cmp r3, #10 @ sum digits\n subge r3, #10 @ get digit in 1s place\n addge r3, #1 @ add 1 for the 10s place\n add r7, r3 @ add digit sum to the total\n \n .continue: \n add r2, #1 @ increment digit index\n cmp r2, r4 @ check if at end of string\n blt .loadNext\n\n add r0, r6, r7 @ add even and odd sum\n mov r3, r0 @ copy sum to r3\n ldr r1, =429496730 @ (2^32-1)\/10\n sub r0, r0, r0, lsr #30 @ divide by 10\n umull r2, r0, r1, r0\n mov r1, #10\n mul r0, r1 @ multiply the r0 by 10 to see if divisible\n cmp r0, r3 @ compare with the original value in r3\n .luhn_test_end:\n movne r0, #0 @ return false if invalid card number\n moveq r0, #1 @ return true if valid card number\n pop {r1-r7, lr}\n mov pc, lr\n \nlength:\n push {r1-r2, lr}\n mov r2, r0 @ start of string address\n .loop:\n ldrb r1, [r2], #1 @ load byte from address r2 and increment\n cmp r1, #0 @ check for end of string\n bne .loop @ load next byte if not 0\n sub r0, r2, r0 @ subtract end of string address from start\n sub r0, #1 @ end of line from count\n pop {r1-r2, lr}\n mov pc, lr\n\n@ reverses a string\n@ r0 address of string to reverse\n@ r1 address to store reversed string\nreverse:\n push {r0-r5, lr}\n push {r0, lr}\n bl length @ get length of string to reverse\n mov r3, r0 @ backword index\n pop {r0, lr}\n mov r4, #0 @ fowrard index\n .reverse_next:\n sub r3, #1 @ decrement backword index\n ldrb r5, [r0, r3] @ load byte from original string at index\n strb r5, [r1, r4] @ copy byte to reversed string\n add r4, #1 @ increment fowrard index\n cmp r3, #0 @ check if any characters are left\n bge .reverse_next\n\n mov r5, #0\n strb r5, [r1, r4] @ write null byte to terminate reversed string\n pop {r0-r5, lr}\n mov pc, lr\n\nisNumerical:\n push {r1, lr}\n .isNumerical_checkNext:\n ldrb r1, [r0], #1\n cmp r1, #0\n beq .isNumerical_true\n cmp r1, #'0'\n blt .isNumerical_false\n cmp r1, #'9'\n bgt .isNumerical_false\n b .isNumerical_checkNext\n .isNumerical_false:\n mov r0, #0\n b .isNumerical_end\n .isNumerical_true:\n mov r0, #1\n .isNumerical_end:\n pop {r1, lr}\n mov pc, lr\n\n\n.data\nvalid_message:\n .asciz \" valid card number\\n\"\ninvalid_message:\n .asciz \" invalid card number\\n\"\n\nreversed_string:\n .space 32\n\nexample_numbers:\n .asciz \"49927398716\"\n .asciz \"49927398717\"\n .asciz \"1234567812345678\"\n .asciz \"1234567812345670\"\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":731} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly AARCH64 Raspberry PI 3B *\/\n\/* ARM assembly Raspberry PI *\/\n\/* program josephus.s *\/\n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\n\/*******************************************\/\n\/* Constantes *\/\n\/*******************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ BRK, 0x2d @ Linux syscall\n.equ CHARPOS, '@'\n\n.equ FIRSTNODE, 0 \/\/identification first node \n\n\/*******************************************\/\n\/* Structures *\/\n\/********************************************\/\n\/* structure linkedlist*\/\n .struct 0\nllist_next: \/\/ next element\n .struct llist_next + 4\nllist_value: \/\/ element value\n .struct llist_value + 4\nllist_fin:\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessDebutPgm: .asciz \"Start program.\\n\"\nszMessFinPgm: .asciz \"Program End ok.\\n\"\nszRetourLigne: .asciz \"\\n\"\nszMessValElement: .asciz \"Value\u00a0: @ \\n\"\nszMessListeVide: .asciz \"List empty.\\n\"\nszMessImpElement: .asciz \"Node display: @ Value\u00a0: @ Next @ \\n\"\nszMessErrComm: .asciz \"Incomplete Command line \u00a0: josephus \\n\"\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \nsZoneConv: .skip 24\n.align 4\nqDebutListe1: .skip llist_fin\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: \/\/ entry of program \n mov fp,sp \/\/ copy stack address register r29 fp\n ldr r0,iAdrszMessDebutPgm\n bl affichageMess\n ldr r0,[fp] \/\/ parameter number command line\n cmp r0,#2 \/\/ correct\u00a0?\n ble erreurCommande \/\/ error\n\n add r0,fp,#8 \/\/ address parameter 2\n ldr r0,[r0]\n bl conversionAtoD\n add r2,r0,#FIRSTNODE \/\/ save maxi\n add r0,fp,#12 \/\/ address parameter 3\n ldr r0,[r0]\n bl conversionAtoD\n mov r8,r0 \/\/ save gap\n\n mov r0,#FIRSTNODE \/\/ create first node\n mov r1,#0\n bl createNode\n mov r5,r0 \/\/ first node address\n mov r6,r0\n mov r4,#FIRSTNODE + 1\n mov r3,#1\n1: \/\/ loop create others nodes\n mov r0,r4 \/\/ key value\n mov r1,#0\n bl createNode\n str r0,[r6,#llist_next] \/\/ store current node address in prev node\n mov r6,r0\n add r4,r4,#1\n add r3,r3,#1\n cmp r3,r2 \/\/ maxi\u00a0?\n blt 1b\n str r5,[r6,#llist_next] \/\/ store first node address in last pointer\n mov r4,r6\n2:\n mov r2,#1 \/\/ counter for gap\n3:\n ldr r4,[r4,#llist_next]\n add r2,r2,#1\n cmp r2,r8 \/\/ intervalle\u00a0?\n blt 3b\n ldr r5,[r4,#llist_next] \/\/ removing the node from the list\n ldr r2,[r5,#llist_value]\n ldr r7,[r5,#llist_next] \/\/ load pointer next\n str r7,[r4,#llist_next] \/\/ ans store in prev node\n \/\/mov r0,r25\n \/\/bl displayNode\n cmp r7,r4\n moveq r4,r7\n bne 2b \/\/ and loop\n \n mov r0,r4\n bl displayNode \/\/ display last node\n\n b 100f\nerreurCommande:\n ldr r0,iAdrszMessErrComm\n bl affichageMess\n mov r0,#1 \/\/ error code\n b 100f\n100: \/\/ program end standard \n ldr r0,iAdrszMessFinPgm\n bl affichageMess\n mov r0,#0 \/\/ return code Ok\n mov r7,#EXIT \/\/ system call \"Exit\"\n svc #0\n\niAdrszMessDebutPgm: .int szMessDebutPgm\niAdrszMessFinPgm: .int szMessFinPgm\niAdrszRetourLigne: .int szRetourLigne\niAdrqDebutListe1: .int qDebutListe1\niAdrszMessErrComm: .int szMessErrComm\n\n\/******************************************************************\/\n\/* create node *\/ \n\/******************************************************************\/\n\/* r0 contains key *\/\n\/* r1 contains zero or address next node *\/\n\/* r0 returns address heap node *\/\ncreateNode:\n push {r1-r11,lr} \/\/ save registers \n mov r9,r0 \/\/ save key\n mov r10,r1 \/\/ save key\n mov r0,#0 \/\/ allocation place heap\n mov r7,#BRK \/\/ call system 'brk'\n svc #0\n mov r11,r0 \/\/ save address heap for node\n add r0,r0,#llist_fin \/\/ reservation place node length\n mov r7,#BRK \/\/ call system 'brk'\n svc #0\n cmp r0,#-1 \/\/ allocation error\n beq 100f\n\n str r9,[r11,#llist_value]\n str r10,[r11,#llist_next]\n mov r0,r11\n100:\n pop {r1-r11,lr} \/\/ restaur registers\n bx lr \/\/ return\n\n\/******************************************************************\/\n\/* display infos node *\/ \n\/******************************************************************\/\n\/* r0 contains node address *\/\ndisplayNode:\n push {r1-r4,lr} \/\/ save registers \n mov r2,r0\n ldr r1,iAdrsZoneConv\n bl conversion16\n mov r4,#0\n strb r4,[r1,r0] \/\/ store zero final\n ldr r0,iAdrszMessImpElement\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc\n mov r3,r0\n ldr r0,[r2,#llist_value]\n ldr r1,iAdrsZoneConv\n bl conversion10S\n mov r4,#0\n strb r4,[r1,r0] \/\/ store zero final\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc\n mov r3,r0\n ldr r0,[r2,#llist_next]\n ldr r1,iAdrsZoneConv\n bl conversion16\n mov r4,#0\n strb r4,[r1,#8] \/\/ store zero final\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl strInsertAtCharInc\n bl affichageMess\n\n100:\n pop {r1-r4,lr} \/\/ restaur registers\n bx lr \/\/ return\niAdrsZoneConv: .int sZoneConv\niAdrszMessImpElement: .int szMessImpElement\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\npi@raspberrypi:~\/asm32\/rosetta32\/ass6 $ josephus 41 3\nStart program.\nNode display: 00F880F0 Value\u00a0: +30 Next 00F880F0\nProgram End ok.\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":732} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program arith.s *\/\n\/* Constantes *\/\n.equ STDOUT, 1\n.equ WRITE, 4\n.equ EXIT, 1\n\n\/***********************\/\n\/* Initialized data *\/\n\/***********************\/\n.data\nszMessError: .asciz \" Two numbers in command line please\u00a0! \\n\" @ message\nszRetourLigne: .asciz \"\\n\"\nszMessResult: .asciz \"Resultat \" @ message result\nsMessValeur: .fill 12, 1, ' '\n .asciz \"\\n\"\nszMessAddition: .asciz \"addition\u00a0:\"\nszMessSoustraction: .asciz \"soustraction\u00a0:\"\nszMessMultiplication: .asciz \"multiplication\u00a0:\"\nszMessDivision: .asciz \"division\u00a0:\"\nszMessReste: .asciz \"reste\u00a0:\"\n \n\/***********************\/\t\t\t\t \n\/* No Initialized data *\/\n\/***********************\/\n.bss\niValeur: .skip 4 @ reserve 4 bytes in memory\n\n.text\n.global main \nmain:\n push {fp,lr} @ save des 2 registres\n add fp,sp,#8 @ fp <- adresse d\u00e9but\n ldr r0,[fp] @ recup number of parameter in command line\n cmp r0,#3\n blt error\n ldr r0,[fp,#8] @ adresse of 1er number\n bl conversionAtoD\n mov r3,r0\n ldr r0,[fp,#12] @ adresse of 2eme number\n bl conversionAtoD\n mov r4,r0\n @ addition\n add r0,r3,r4\n ldr r1,iAdrsMessValeur @ result in r0\n bl conversion10S @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n ldr r0,iAdrszMessAddition\n bl affichageMess @ display message\n ldr r0,iAdrsMessValeur\n bl affichageMess @ display message\n @ soustraction\n sub r0,r3,r4\n ldr r1,=sMessValeur \n bl conversion10S @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n ldr r0,iAdrszMessSoustraction\n bl affichageMess @ display message\n ldr r0,iAdrsMessValeur\n bl affichageMess @ display message\n\n @ multiplication\n mul r0,r3,r4\n ldr r1,=sMessValeur \n bl conversion10S @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n ldr r0,iAdrszMessMultiplication\n bl affichageMess @ display message\n ldr r0,iAdrsMessValeur\n bl affichageMess @ display message\n \n @ division \n mov r0,r3\n mov r1,r4\n bl division\n mov r0,r2 @ quotient\n ldr r1,=sMessValeur \n bl conversion10S @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n ldr r0,iAdrszMessDivision\n bl affichageMess @ display message\n ldr r0,iAdrsMessValeur\n bl affichageMess @ display message\n\n mov r0,r3 @ remainder\n ldr r1,=sMessValeur \n bl conversion10S @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n ldr r0,iAdrszMessReste\n bl affichageMess @ display message\n ldr r0,iAdrsMessValeur\n bl affichageMess @ display message\n \n mov r0, #0 @ return code\n b 100f\nerror:\n ldr r0,iAdrszMessError\n bl affichageMess @ call function with 1 parameter (r0)\n mov r0, #1 @ return code\n100: \/* end of program *\/\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrsMessValeur: .int sMessValeur\t\niAdrszMessResult: .int szMessResult\niAdrszMessError: .int szMessError\niAdrszMessAddition: .int szMessAddition\niAdrszMessSoustraction: .int szMessSoustraction\niAdrszMessMultiplication: .int szMessMultiplication\niAdrszMessDivision: .int szMessDivision\niAdrszMessReste: .int szMessReste\n\/******************************************************************\/\n\/* affichage des messages avec calcul longueur *\/ \n\/******************************************************************\/\n\/* r0 contient l adresse du message *\/\naffichageMess:\n push {fp,lr} \/* save des 2 registres *\/ \n push {r0,r1,r2,r7} \/* save des autres registres *\/\n mov r2,#0 \/* compteur longueur *\/\n1: \/*calcul de la longueur *\/\n ldrb r1,[r0,r2] \/* recup octet position debut + indice *\/\n cmp r1,#0 \/* si 0 c est fini *\/\n beq 1f\n add r2,r2,#1 \/* sinon on ajoute 1 *\/\n b 1b\n1: \/* donc ici r2 contient la longueur du message *\/\n mov r1,r0 \/* adresse du message en r1 *\/\n mov r0,#STDOUT \/* code pour \u00e9crire sur la sortie standard Linux *\/\n mov r7, #WRITE \/* code de l appel systeme 'write' *\/\n swi #0 \/* appel systeme *\/\n pop {r0,r1,r2,r7} \/* restaur des autres registres *\/\n pop {fp,lr} \/* restaur des 2 registres *\/ \n bx lr\t \/* retour procedure *\/\t\n\/***************************************************\/\n\/* conversion registre en d\u00e9cimal sign\u00e9 *\/\n\/***************************************************\/\n\/* r0 contient le registre *\/\n\/* r1 contient l adresse de la zone de conversion *\/\nconversion10S:\n push {fp,lr} \/* save des 2 registres frame et retour *\/\n push {r0-r5} \/* save autres registres *\/\n mov r2,r1 \/* debut zone stockage *\/\n mov r5,#'+' \/* par defaut le signe est + *\/\n cmp r0,#0 \/* nombre n\u00e9gatif\u00a0? *\/\n movlt r5,#'-' \/* oui le signe est - *\/\n mvnlt r0,r0 \/* et inversion en valeur positive *\/\n addlt r0,#1\n mov r4,#10 \/* longueur de la zone *\/\n1: \/* debut de boucle de conversion *\/\n bl divisionpar10 \/* division *\/\n add r1,#48 \/* ajout de 48 au reste pour conversion ascii *\/\t\n strb r1,[r2,r4] \/* stockage du byte en d\u00e9but de zone r5 + la position r4 *\/\n sub r4,r4,#1 \/* position pr\u00e9cedente *\/\n cmp r0,#0 \n bne 1b\t \/* boucle si quotient different de z\u00e9ro *\/\n strb r5,[r2,r4] \/* stockage du signe \u00e0 la position courante *\/\n subs r4,r4,#1 \/* position pr\u00e9cedente *\/\n blt 100f \/* si r4 < 0 fin *\/\n \/* sinon il faut completer le debut de la zone avec des blancs *\/\n mov r3,#' ' \/* caractere espace *\/\t\n2:\n strb r3,[r2,r4] \/* stockage du byte *\/\n subs r4,r4,#1 \/* position pr\u00e9cedente *\/\n bge 2b \/* boucle si r4 plus grand ou egal a zero *\/\n100: \/* fin standard de la fonction *\/\n pop {r0-r5} \/*restaur des autres registres *\/\n pop {fp,lr} \/* restaur des 2 registres frame et retour *\/\n bx lr \n\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 contient le dividende *\/\n\/* r0 retourne le quotient *\/\t\n\/* r1 retourne le reste *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save autres registres *\/\n mov r4,r0 \n ldr r3, .Ls_magic_number_10 \/* r1 <- magic_number *\/\n smull r1, r2, r3, r0 \/* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) *\/\n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n .align 4\n.Ls_magic_number_10: .word 0x66666667\n\/******************************************************************\/\n\/* Conversion d une chaine en nombre stock\u00e9 dans un registre *\/ \n\/******************************************************************\/\n\/* r0 contient l adresse de la zone termin\u00e9e par 0 ou 0A *\/\nconversionAtoD:\n push {fp,lr} \/* save des 2 registres *\/ \n push {r1-r7} \/* save des autres registres *\/\n mov r1,#0\n mov r2,#10 \/* facteur *\/\n mov r3,#0 \/* compteur *\/\n mov r4,r0 \/* save de l adresse dans r4 *\/\n mov r6,#0 \/* signe positif par defaut *\/\n mov r0,#0 \/* initialisation \u00e0 0 *\/ \n1: \/* boucle d \u00e9limination des blancs du debut *\/\n ldrb r5,[r4,r3] \/* chargement dans r5 de l octet situ\u00e9 au debut + la position *\/\n cmp r5,#0 \/* fin de chaine -> fin routine *\/\n beq 100f\n cmp r5,#0x0A \/* fin de chaine -> fin routine *\/\n beq 100f\n cmp r5,#' ' \/* blanc au d\u00e9but *\/\n bne 1f \/* non on continue *\/\n add r3,r3,#1 \/* oui on boucle en avan\u00e7ant d un octet *\/\n b 1b\n1:\n cmp r5,#'-' \/* premier caracteres est - *\/\n moveq r6,#1 \/* maj du registre r6 avec 1 *\/\n beq 3f \/* puis on avance \u00e0 la position suivante *\/\n2: \/* debut de boucle de traitement des chiffres *\/\n cmp r5,#'0' \/* caractere n est pas un chiffre *\/\n blt 3f\n cmp r5,#'9' \/* caractere n est pas un chiffre *\/\n bgt 3f\n \/* caract\u00e8re est un chiffre *\/\n sub r5,#48\n ldr r1,iMaxi \/*verifier le d\u00e9passement du registre *\/ \n cmp r0,r1\n bgt 99f\n mul r0,r2,r0 \/* multiplier par facteur *\/\n add r0,r5 \/* ajout \u00e0 r0 *\/\n3:\n add r3,r3,#1 \/* avance \u00e0 la position suivante *\/\n ldrb r5,[r4,r3] \/* chargement de l octet *\/\n cmp r5,#0 \/* fin de chaine -> fin routine *\/\n beq 4f\n cmp r5,#10 \/* fin de chaine -> fin routine *\/\n beq 4f\n b 2b \/* boucler *\/ \n4:\n cmp r6,#1 \/* test du registre r6 pour le signe *\/\n bne 100f\n mov r1,#-1\n mul r0,r1,r0 \/* si negatif, on multiplie par -1 *\/\n b 100f\n99: \/* erreur de d\u00e9passement *\/\n ldr r1,=szMessErrDep\n bl afficheerreur \n mov r0,#0 \/* en cas d erreur on retourne toujours zero *\/\n100:\n pop {r1-r7} \/* restaur des autres registres *\/\n pop {fp,lr} \/* restaur des 2 registres *\/ \n bx lr \/* retour procedure *\/\t\n\/* constante programme *\/\t\niMaxi: .int 1073741824\t\nszMessErrDep: .asciz \"Nombre trop grand\u00a0: d\u00e9passement de capacite de 32 bits.\u00a0:\\n\"\n.align 4\n\/*=============================================*\/\n\/* division entiere non sign\u00e9e *\/\n\/*============================================*\/\ndivision:\n \/* r0 contains N *\/\n \/* r1 contains D *\/\n \/* r2 contains Q *\/\n \/* r3 contains R *\/\n push {r4, lr}\n mov r2, #0 \/* r2\u00a0? 0 *\/\n mov r3, #0 \/* r3\u00a0? 0 *\/\n mov r4, #32 \/* r4\u00a0? 32 *\/\n b 2f\n1:\n movs r0, r0, LSL #1 \/* r0\u00a0? r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) *\/\n adc r3, r3, r3 \/* r3\u00a0? r3 + r3 + C. This is equivalent to r3\u00a0? (r3 << 1) + C *\/\n \n cmp r3, r1 \/* compute r3 - r1 and update cpsr *\/\n subhs r3, r3, r1 \/* if r3 >= r1 (C=1) then r3\u00a0? r3 - r1 *\/\n adc r2, r2, r2 \/* r2\u00a0? r2 + r2 + C. This is equivalent to r2\u00a0? (r2 << 1) + C *\/\n2:\n subs r4, r4, #1 \/* r4\u00a0? r4 - 1 *\/\n bpl 1b \/* if r4 >= 0 (N=0) then branch to .Lloop1 *\/\n \n pop {r4, lr}\n bx lr\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":733} {"lang_cluster":"ARM_Assembly","source_code":"\n.text\n.global\t_start\n_start:\tmov\tr0,#4\t\t@ 4 disks,\n\tmov\tr1,#1\t\t@ from pole 1,\n\tmov\tr2,#2\t\t@ via pole 2,\n\tmov\tr3,#3\t\t@ to pole 3.\n\tbl\tmove\n\tmov\tr0,#0\t\t@ Exit to Linux afterwards\n\tmov\tr7,#1\n\tswi\t#0\n\t@@@\tMove r0 disks from r1 via r2 to r3\nmove:\tsubs\tr0,r0,#1\t@ One fewer disk in next iteration\n\tbeq\tshow\t\t@ If last disk, just print move\n\tpush\t{r0-r3,lr}\t@ Save all the registers incl. link register\n\teor\tr2,r2,r3\t@ Swap the 'to' and 'via' registers\n\teor\tr3,r2,r3\n\teor\tr2,r2,r3\n\tbl\tmove\t\t@ Recursive call\n\tpop\t{r0-r3}\t\t@ Restore all the registers except LR\n\tbl\tshow\t\t@ Show current move\n\teor\tr1,r1,r3\t@ Swap the 'to' and 'via' registers\n\teor\tr3,r1,r3\n\teor\tr1,r1,r3\n\tpop\t{lr}\t\t@ Restore link register\n\tb\tmove\t\t@ Tail call\n\t@@@\tShow move\nshow:\tpush\t{r0-r3,lr}\t@ Save all the registers\n\tadd\tr1,r1,#'0\t@ Write the source pole\n\tldr\tlr,=spole\n\tstrb\tr1,[lr] \n\tadd\tr3,r3,#'0\t@ Write the destination pole\n\tldr\tlr,=dpole\n\tstrb\tr3,[lr]\n\tmov\tr0,#1\t\t@ 1 = stdout\n\tldr\tr1,=moves\t@ Pointer to string\n\tldr\tr2,=mlen\t@ Length of string\n\tmov\tr7,#4\t\t@ 4 = Linux write syscall\n\tswi\t#0 \t\t@ Print the move\n\tpop\t{r0-r3,pc}\t@ Restore all the registers and return\n.data\nmoves:\t.ascii\t\"Move disk from pole \"\nspole:\t.ascii\t\"* to pole \"\ndpole:\t.ascii\t\"*\\n\"\nmlen\t=\t. - moves\n\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":734} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program shellSort.s *\/\n \n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessSortOk: .asciz \"Table sorted.\\n\"\nszMessSortNok: .asciz \"Table not sorted\u00a0!!!!!.\\n\"\nsMessResult: .ascii \"Value \u00a0: \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\nszCarriageReturn: .asciz \"\\n\"\n \n.align 4\niGraine: .int 123456\n.equ NBELEMENTS, 10\n#TableNumber: .int 1,3,6,2,5,9,10,8,4,7\nTableNumber: .int 10,9,8,7,6,5,4,3,2,1\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n \n1:\n ldr r0,iAdrTableNumber @ address number table\n mov r1,#0 @ not use in routine\n mov r2,#NBELEMENTS @ number of \u00e9lements \n bl shellSort\n ldr r0,iAdrTableNumber @ address number table\n bl displayTable\n \n ldr r0,iAdrTableNumber @ address number table\n mov r1,#NBELEMENTS @ number of \u00e9lements \n bl isSorted @ control sort\n cmp r0,#1 @ sorted\u00a0?\n beq 2f\n ldr r0,iAdrszMessSortNok @ no\u00a0!! error sort\n bl affichageMess\n b 100f\n2: @ yes\n ldr r0,iAdrszMessSortOk\n bl affichageMess\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrsMessValeur: .int sMessValeur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdrTableNumber: .int TableNumber\niAdrszMessSortOk: .int szMessSortOk\niAdrszMessSortNok: .int szMessSortNok\n\/******************************************************************\/\n\/* control sorted table *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains the number of elements > 0 *\/\n\/* r0 return 0 if not sorted 1 if sorted *\/\nisSorted:\n push {r2-r4,lr} @ save registers\n mov r2,#0\n ldr r4,[r0,r2,lsl #2]\n1:\n add r2,#1\n cmp r2,r1\n movge r0,#1\n bge 100f\n ldr r3,[r0,r2, lsl #2]\n cmp r3,r4\n movlt r0,#0\n blt 100f\n mov r4,r3\n b 1b\n100:\n pop {r2-r4,lr}\n bx lr @ return \n\/***************************************************\/\n\/* shell Sort *\/\n\/***************************************************\/\n\n\/* r0 contains the address of table *\/\n\/* r1 contains the first element but not use\u00a0!! *\/\n\/* this routine use first element at index zero\u00a0!!! *\/\n\/* r2 contains the number of element *\/\nshellSort:\n push {r0-r7,lr} @save registers\n\n sub r2,#1 @ index last item\n mov r1,r2 @ init gap = last item\n1: @ start loop 1\n lsrs r1,#1 @ gap = gap \/ 2\n beq 100f @ if gap = 0 -> end\n mov r3,r1 @ init loop indice 1 \n2: @ start loop 2\n ldr r4,[r0,r3,lsl #2] @ load first value\n mov r5,r3 @ init loop indice 2\n3: @ start loop 3\n cmp r5,r1 @ indice < gap\n blt 4f @ yes -> end loop 2\n sub r6,r5,r1 @ index = indice - gap\n ldr r7,[r0,r6,lsl #2] @ load second value\n cmp r4,r7 @ compare values\n strlt r7,[r0,r5,lsl #2] @ store if <\n sublt r5,r1 @ indice = indice - gap\n blt 3b @ and loop\n4: @ end loop 3\n str r4,[r0,r5,lsl #2] @ store value 1 at indice 2\n add r3,#1 @ increment indice 1\n cmp r3,r2 @ end\u00a0?\n ble 2b @ no -> loop 2\n b 1b @ yes loop for new gap\n \n100: @ end function\n pop {r0-r7,lr} @ restaur registers\n bx lr @ return \n\n\n\/******************************************************************\/\n\/* Display table elements *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\ndisplayTable:\n push {r0-r3,lr} @ save registers\n mov r2,r0 @ table address\n mov r3,#0\n1: @ loop display table\n ldr r0,[r2,r3,lsl #2]\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n add r3,#1\n cmp r3,#NBELEMENTS - 1\n ble 1b\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n100:\n pop {r0-r3,lr}\n bx lr\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal unsigned *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\n\/* r0 return size of result (no zero final in area) *\/\n\/* area size => 11 bytes *\/\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n \n1: @ start loop\n bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n \n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n \n\/***************************************************\/\n\/* division par 10 unsigned *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n \/\/mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3\n \/\/movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: \t.int 0xCCCCCCCD\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":735} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI or android 32 bits with termux application *\/\n\/* program animLetter.s *\/\n\n\/* compile with as *\/\n\/* link with gcc and options -lX11 -L\/usr\/lpp\/X11\/lib *\/\n\n\/* REMARK: This program was written for android with the termux app.\n It works very well on raspberry pi but in this case the memory access relocation instructions \n can be simplified.\n*\/\n\n \/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n\n\/********************************************\/\n\/*Constantes *\/\n\/********************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/* constantes X11 *\/\n.equ KeyPressed, 2\n.equ ButtonPress, 4\n.equ MotionNotify, 6\n.equ EnterNotify, 7\n.equ LeaveNotify, 8\n.equ Expose, 12\n.equ ClientMessage, 33\n.equ KeyPressMask, 1\n.equ ButtonPressMask, 4\n.equ ButtonReleaseMask, 8\n.equ ExposureMask, 1<<15\n.equ StructureNotifyMask, 1<<17\n.equ EnterWindowMask, 1<<4\n.equ LeaveWindowMask, 1<<5 \n.equ ConfigureNotify, 22\n\n.equ GCForeground, 1<<2\n.equ GCFont, 1<<14\n\n\/* constantes program *\/\n.equ WINDOWWIDTH, 400\n.equ WINDOWHEIGHT, 300\n\n\/*******************************************\/\n\/* DONNEES INITIALISEES *\/\n\/*******************************************\/ \n.data\nszWindowName: .asciz \"Windows Raspberry\"\nszRetourligne: .asciz \"\\n\"\nszMessDebutPgm: .asciz \"Program start. \\n\"\nszMessErreur: .asciz \"Server X not found.\\n\"\nszMessErrfen: .asciz \"Can not create window.\\n\"\nszMessErreurX11: .asciz \"Error call function X11. \\n\"\nszMessErrGc: .asciz \"Can not create graphics context.\\n\"\nszMessErrFont: .asciz \"Font not found.\\n\"\nszTitreFenRed: .asciz \"Pi\" \nszTexte1: .asciz \"Hello world! \"\n.equ LGTEXTE1, . - szTexte1\nszTexte2: .asciz \"Press q for close window or clic X in system menu.\"\n.equ LGTEXTE2, . - szTexte2\nszLibDW: .asciz \"WM_DELETE_WINDOW\" @ special label for correct close error\n\nszfontname: .asciz \"-*-helvetica-bold-*-normal-*-12-*\" @ for font test\nszfontname2: .asciz \"-*-fixed-*-*-*-*-13-*-*-*-*-*\"\n.align 4\nstXGCValues: .int 0,0,0xFFA0A0A0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 @ for foreground color gris1\n\/\/stXGCValues: .int 0,0,0x00000000,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 @ for foreground color black\nstXGCValues1: .int 0,0,0x00FFFFFF,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 @ for foreground color white\nstXGCValues2: .int 0,0,0x0000FF00,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 @ for foreground color green \n\/*******************************************\/\n\/* DONNEES NON INITIALISEES *\/\n\/*******************************************\/ \n.bss\n.align 4\nptDisplay: .skip 4 @ pointer display\nptEcranDef: .skip 4 @ pointer screen default\nptFenetre: .skip 4 @ pointer window\nptGC: .skip 4 @ pointer graphic context\nptGC1: .skip 4 @ pointer graphic context\nptFont: .skip 4 @ pointer font\nkey: .skip 4 @ key code\nwmDeleteMessage: .skip 8 @ ident close message\nevent: .skip 400 @ TODO: event size\u00a0??\nPrpNomFenetre: .skip 100 @ window name proprety\nbuffer: .skip 500 \nsbuffer1: .skip 500\niWhite: .skip 4 @ rgb code for white pixel\niBlack: .skip 4 @ rgb code for black pixel\niSens: .skip 4 @ direction of travel\n\/**********************************************\/\n\/* -- Code section *\/\n\/**********************************************\/\n.text\n.global main\niOfWhite: .int iWhite - .\niOfBlack: .int iBlack - .\niOfszMessDebutPgm: .int szMessDebutPgm - .\niOfptDisplay: .int ptDisplay - .\niOfptEcranDef: .int ptEcranDef - .\niOfszLibDW: .int szLibDW - .\nmain: @ entry of program \n adr r0,iOfszMessDebutPgm @\n ldr r1,[r0]\n add r0,r1\n bl affichageMess @ display start message on console linux\n \/* attention r6 pointer display*\/\n \/* attention r8 pointer graphic context 1 *\/\n \/* attention r9 ident window *\/\n \/* attention r10 pointer graphic context 2 *\/\n \/*****************************\/\n \/* OPEN SERVER X11 *\/\n \/*****************************\/\n mov r0,#0\n bl XOpenDisplay @ open X server\n cmp r0,#0 @ error\u00a0?\n beq erreurServeur\n adr r2,iOfptDisplay\n ldr r1,[r2]\n add r1,r2\n str r0,[r1] @ store display address \n\n mov r6,r0 @ and in register r6\n ldr r2,[r0,#+132] @ load default_screen\n adr r1,iOfptEcranDef\n ldr r3,[r1]\n add r1,r3\n str r2,[r1] @ store default_screen\n mov r2,r0\n ldr r0,[r2,#+140] @ load pointer screen list\n ldr r5,[r0,#+52] @ load value white pixel\n adr r4,iOfWhite @ and store in memory\n ldr r3,[r4]\n add r4,r3\n str r5,[r4]\n ldr r7,[r0,#+56] @ load value black pixel\n adr r4,iOfBlack @ and store in memory\n ldr r5,[r4]\n add r4,r5\n str r7,[r4]\n ldr r4,[r0,#+28] @ load bits par pixel\n ldr r1,[r0,#+8] @ load root windows\n \/**************************\/\n \/* CREATE WINDOW *\/\n \/**************************\/\n mov r0,r6 @ address display\n mov r2,#0 @ window position X\n mov r3,#0 @ window position Y\n mov r8,#0 @ for stack alignement\n push {r8}\n push {r7} @ background = black pixel\n push {r5} @ border = white pixel\n mov r8,#2 @ border size\n push {r8}\n mov r8,#WINDOWHEIGHT @ height\n push {r8}\n mov r8,#WINDOWWIDTH @ width\n push {r8} \n bl XCreateSimpleWindow\n add sp,#24 @ stack alignement 6 push (4 bytes * 6)\n cmp r0,#0 @ error\u00a0?\n beq erreurF\n\n adr r1,iOfptFenetre\n ldr r3,[r1]\n add r1,r3\n str r0,[r1] @ store window address in memory\n mov r9,r0 @ and in register r9\n \n \/*****************************\/\n \/* add window property *\/\n \/*****************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n adr r2,iOfszWindowName @ window name\n ldr r5,[r2]\n add r2,r5\n adr r3,iOfszTitreFenRed @ window name reduced\n ldr r5,[r3]\n add r3,r5\n mov r4,#0\n push {r4} @ parameters not use\n push {r4}\n push {r4}\n push {r4}\n bl XSetStandardProperties\n add sp,sp,#16 @ stack alignement for 4 push\n \/**************************************\/\n \/* for correction window close error *\/\n \/**************************************\/\n mov r0,r6 @ display address\n adr r1,iOfszLibDW @ atom address\n ldr r5,[r1]\n add r1,r5\n mov r2,#1 @ False cr\u00e9ate atom if not exists\n bl XInternAtom\n cmp r0,#0 @ error X11\u00a0?\n blt erreurX11 @ Modif avril 22 pour android (ble pour raspberry)\n adr r1,iOfwmDeleteMessage @ recept address\n ldr r5,[r1]\n add r1,r5\n str r0,[r1]\n mov r2,r1 @ return address\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n mov r3,#1 @ number of protocols\n bl XSetWMProtocols\n cmp r0,#0 @ error X11\u00a0?\n ble erreurX11\n \/***********************************\/\n \/* load font *\/\n \/* remark\u00a0: see font list X11 on your system *\/\n \/***********************************\/\n mov r0,r6 @ display address\n bl loadFont\n\n \/**********************************\/\n \/* create graphic context *\/\n \/**********************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n bl createContextGraphic\n \n\n \/****************************\/\n \/* modif window background *\/\n \/****************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n ldr r2,iGris1 @ background color\n bl XSetWindowBackground \n cmp r0,#0 @ error\u00a0?\n ble erreurX11\n \n \/***************************\/\n \/* OUF!! window display *\/\n \/***************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n bl XMapWindow\n \n @ copy text in buffer\n adr r0,iOfszTexte1 @ string address\n ldr r5,[r0]\n add r0,r5\n adr r1,iOfsbuffer1 @ buffer address\n ldr r5,[r1]\n add r1,r5\n mov r2,#0\n1: @ loop copy character\n ldrb r3,[r0,r2]\n strb r3,[r1,r2]\n cmp r3,#0\n addne r2,r2,#1\n bne 1b\n \n \/****************************\/\n \/* Autorisations *\/\n \/****************************\/\n mov r0,r6 @ display address\n mov r1,r9 @ window address\n ldr r2,iFenetreMask @ autorisation mask\n bl XSelectInput\n cmp r0,#0 @ error\u00a0?\n ble erreurX11\n \n \/****************************\/\n \/* Events loop *\/\n \/****************************\/\n1:\n mov r0,r6 @ display address\n bl XPending @ loading the number of events\n cmp r0,#0\n bne 2f @ a event is occurring\n adr r3,iOfsbuffer1\n ldr r5,[r3]\n add r3,r5\n mov r0,r6 @ display address\n mov r1,r9 @ window ident\n mov r2,r8 @ graphic context \n bl animate @ string display and move\n b 1b\n2:\n mov r0,r6 @ display address\n adr r1,iOfevent @ events address\n ldr r5,[r1]\n add r1,r5\n bl XNextEvent @ event\u00a0?\n adr r0,iOfevent\n ldr r5,[r0]\n add r0,r5\n ldr r0,[r0] @ code event\n cmp r0,#KeyPressed @ key\u00a0?\n bne 2f\n adr r0,iOfevent @ yes read key in buffer\n ldr r5,[r0]\n add r0,r5\n adr r1,iOfbuffer\n ldr r5,[r1]\n add r1,r5\n mov r2,#255\n adr r3,iOfkey\n ldr r5,[r3]\n add r3,r5\n mov r4,#0\n push {r4} @ stack alignement\n push {r4}\n bl XLookupString \n add sp,#8 @ stack alignement 2 push\n cmp r0,#1 @ is character key\u00a0?\n bne 2f\n adr r0,iOfbuffer @ yes -> load first buffer character\n ldr r5,[r0]\n add r0,r5\n ldrb r0,[r0]\n cmp r0,#0x71 @ character q for quit\n beq 5f @ yes -> end\n b 4f\n2:\n \/************************************\/\n \/* clic mouse button *\/\n \/************************************\/\n cmp r0,#ButtonPress @ clic mouse buton\n bne 3f\n adr r0,iOfevent\n ldr r5,[r0]\n add r0,r5\n ldr r1,[r0,#+32] @ position X mouse clic\n ldr r2,[r0,#+36] @ position Y\n cmp r1,#50 @ test if position clic is on the screen string approx.\n blt 4f\n cmp r1,#150\n bgt 4f\n cmp r2,#80\n blt 4f\n cmp r2,#105\n bgt 4f\n adr r1,iOfiSens @ load direction\n ldr r2,[r1]\n add r1,r2\n ldr r2,[r1]\n cmp r2,#0 @ direction inversion\n moveq r2,#1\n movne r2,#0\n str r2,[r1]\n b 4f\n3:\n cmp r0,#ClientMessage @ code for close window within error\n bne 4f\n adr r0,iOfevent\n ldr r5,[r0]\n add r0,r5\n ldr r1,[r0,#+28] @ code message address \n adr r2,iOfwmDeleteMessage @ equal code window cr\u00e9ate\u00a0???\n ldr r5,[r2]\n add r2,r5\n ldr r2,[r2]\n cmp r1,r2\n beq 5f @ yes -> end window \n\n4: @ loop for other event\n b 1b\niOfptFenetre: .int ptFenetre - .\niOfszWindowName: .int szWindowName - .\niOfszTitreFenRed: .int szTitreFenRed - .\n \/***********************************\/\n \/* Close window -> free ressources *\/\n \/***********************************\/\n5:\n mov r0,r6 @ display address\n adr r1,iOfptGC\n ldr r5,[r1]\n add r1,r5\n ldr r1,[r1] @ load context graphic address \n bl XFreeGC\n mov r0,r6 @ display address\n adr r1,iOfptGC1\n ldr r5,[r1]\n add r1,r5\n ldr r1,[r1] @ load context graphic address \n bl XFreeGC\n cmp r0,#0\n blt erreurX11\n mov r0,r6 @ display address \n mov r1,r9 @ window address\n bl XDestroyWindow\n cmp r0,#0\n blt erreurX11\n mov r0,r6 @ display address\n bl XCloseDisplay\n cmp r0,#0\n blt erreurX11\n mov r0,#0 @ return code OK\n b 100f\n\nerreurF: @ create error window but possible not necessary. Display error by server\n adr r1,iOfszMessErrfen\n ldr r5,[r1]\n add r1,r5\n bl displayError\n mov r0,#1 @ return error code\n b 100f\nerreurGC: @ error create graphic context\n adr r1,iOfszMessErrGc\n ldr r5,[r1]\n add r1,r5\n bl displayError\n mov r0,#1\n b 100f\nerreurX11: @ erreur X11\n adr r1,iOfszMessErreurX11\n ldr r5,[r1]\n add r1,r5\n bl displayError\n mov r0,#1\n b 100f\nerreurServeur: @ error no found X11 server see doc putty and Xming\n adr r1,iOfszMessErreur\n ldr r5,[r1]\n add r1,r5\n bl displayError\n mov r0,#1\n b 100f\n\n100: @ standard end of the program \n mov r7, #EXIT\n svc 0 \n\niOfevent: .int event - .\niOfbuffer: .int buffer - .\niOfsbuffer1: .int sbuffer1 - .\niOfkey: .int key - .\niOfszMessErreurX11: .int szMessErreurX11 - .\niOfszMessErreur: .int szMessErreur - .\niOfszMessErrfen: .int szMessErrfen - .\niOfszTexte1: .int szTexte1 - .\niOfszTexte2: .int szTexte2 - .\niOfPrpNomFenetre: .int PrpNomFenetre - .\niOfwmDeleteMessage: .int wmDeleteMessage - .\n\niFenetreMask: .int KeyPressMask|ButtonPressMask|StructureNotifyMask\niGris1: .int 0xFFA0A0A0\niOfiSens: .int iSens - .\n\/******************************************************************\/\n\/* load font *\/ \n\/******************************************************************\/\n\/* r0 contains display *\/\nloadFont:\n push {r1-r2,lr} @ save registers \n adr r1,iOfszfontname @ font name\n ldr r2,[r1]\n add r1,r2\n bl XLoadQueryFont\n cmp r0,#0\n beq 99f @ font not find\n adr r1,iOfptFont\n ldr r2,[r1]\n add r1,r2\n str r0,[r1]\n mov r0,#0\n b 100f\n99:\n adr r1,iOfszMessErrFont\n ldr r5,[r1]\n add r1,r5\n bl displayError\n mov r0,#1\n100:\n pop {r1-r2,pc} @ restaur registers\niOfszfontname: .int szfontname2 - .\niOfptFont: .int ptFont - .\niOfszMessErrFont: .int szMessErrFont - .\n\/******************************************************************\/\n\/* Context Graphic cr\u00e9ation *\/ \n\/******************************************************************\/\n\/* r0 contains display *\/\n\/* r1 window address *\/\n\/* REMARKS\u00a0: no standard use registers return GC1 in r8 and GC2 in r10 *\/ \ncreateContextGraphic:\n push {r1-r7,lr} @ save registers \n \/**********************************\/\n \/* create graphic context *\/\n \/**********************************\/\n mov r6,r0 @ save display address\n mov r7,r1 @ save window address\n adr r3,iOfptFont @ font pointer\n ldr r1,[r3]\n add r3,r1\n ldr r3,[r3]\n ldr r4,[r3,#4] @ load font ident\n adr r3,iOfstXGCValues2 @ green color in foreground\n ldr r5,[r3]\n add r3,r5 @ this parameter is used by XcreateGC\n str r4,[r3,#60] @ store ident font in offset 60 \n mov r0,r4\n mov r0,r6 @ display address\n mov r1,r7 @ window address\n mov r2,#GCForeground|GCFont @ @ green color in foreground and font\n bl XCreateGC\n cmp r0,#0 @ error\u00a0?\n beq 99f\n adr r1,iOfptGC\n ldr r5,[r1]\n add r1,r5\n str r0,[r1] @ store address graphic context\n mov r8,r0 @ and in r8\n \/**********************************\/\n \/* create 2 graphic context *\/\n \/**********************************\/\n mov r0,r6 @ display address\n mov r1,r7 @ window address\n mov r2,#GCForeground @ red color in Foreground\n adr r3,iOfstXGCValues\n ldr r5,[r3]\n add r3,r5\n bl XCreateGC\n cmp r0,#0 @ error\u00a0?\n beq erreurGC\n adr r1,iOfptGC1\n ldr r5,[r1]\n add r1,r5\n str r0,[r1] @ store address graphic context\n mov r10,r0 @ and in r10\n b 100f\n99: @ create error\n adr r1,iOfszMessErrGc\n ldr r5,[r1]\n add r1,r5\n bl displayError\n mov r0,#1\n100:\n pop {r1-r7,pc} @ restaur registers\niOfszMessErrGc: .int szMessErrGc - .\niOfptGC: .int ptGC - .\niOfptGC1: .int ptGC1 - .\niOfstXGCValues: .int stXGCValues - .\niOfstXGCValues1: .int stXGCValues1 - .\niOfstXGCValues2: .int stXGCValues2 - .\n\/******************************************************************\/\n\/* animation *\/ \n\/******************************************************************\/\n\/* r0 contains display *\/\n\/* r1 contains window ident *\/\n\/* r2 contains context graphic *\/\n\/* r3 string address *\/\nanimate:\n push {r2-r9,lr} @ save registers \n mov r5,r3 @ save string address\n mov r6,r0 @ save display\n mov r7,r1 @ save window\n mov r8,r2 @ save GC\n @ erase text in the windows\n mov r0,r6 @ display address\n mov r1,r7 @ window ident\n mov r2,r10 @ graphic context \n mov r3,#50 @ position x\n mov r4,#LGTEXTE1 - 1 @ string lenght\n push {r4} @ stack alignement\n push {r4} @ to stack parameter\n\n push {r5} @ string address\n mov r4,#100 @ position y\n push {r4}\n bl XDrawString\n add sp,sp,#16 @ stack alignement (4 push)\n\n mov r0,#LGTEXTE1 -2 @ string length\n adr r1,iOfiSens @ load direction\n ldr r2,[r1]\n add r1,r2\n ldr r2,[r1]\n cmp r2,#0 @ test direction\n bne 2f\n \n ldrb r9,[r5,r0] @ last character\n sub r1,r0,#1\n1: @ loop to move character one position\n ldrb r2,[r5,r1]\n strb r2,[r5,r0]\n sub r0,r0,#1\n subs r1,r1,#1\n bge 1b\n add r1,r1,#1\n strb r9,[r5,r1] @ last character -> first character\n b 4f\n2:\n ldrb r9,[r5] @ first character\n mov r1,#1\n sub r2,r1,#1\n3: @ loop to move character\n ldrb r3,[r5,r1]\n strb r3,[r5,r2]\n add r2,r2,#1\n add r1,r1,#1\n cmp r1,r0\n ble 3b\n strb r9,[r5,r2] @ first character -> last character\n \n4:\n @ write text in the windows\n mov r0,r6 @ display address\n mov r1,r7 @ window ident\n mov r2,r8 @ graphic context \n mov r3,#50 @ position x\n mov r4,#LGTEXTE1 - 1 @ string lenght\n push {r4} @ stack alignement\n push {r4} @ to stack parameter\n push {r5} @ string address\n mov r4,#100 @ position y\n push {r4}\n bl XDrawString\n add sp,sp,#16 @ stack alignement (4 push)\n mov r0,#20 @ timeout 5s approx.\n bl delay\n\n100:\n pop {r2-r9,pc} @ restaur registers\n\/******************************************************************\/\n\/* timeout *\/ \n\/******************************************************************\/\n\/* r0 contains delay *\/\n\ndelay:\n push {r1,lr} @ save registers \n ldr r1,iCst30000000\n mul r0,r1,r0\n1:\n subs r0,r0,#1\n bge 1b\n100:\n pop {r1,pc} @ restaur registers\niCst30000000: .int 30000000\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":736} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program loopdowhile.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessResult: .ascii \"Counter = \" @ message result\nsMessValeur: .fill 12, 1, ' '\n .asciz \"\\n\"\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n push {fp,lr} @ saves 2 registers \n mov r4,#0\n1: @ begin loop \n mov r0,r4\n\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n add r4,#1 @ increment counter\n mov r0,r4\n mov r1,#6 @ division conuter by 6\n bl division\n cmp r3,#0 @ remainder = z\u00e9ro\u00a0?\n bne 1b @ no ->begin loop one\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrszMessResult: .int szMessResult\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 \t\t\t@ address message in r1 \n mov r0,#STDOUT \t\t@ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#10\n\n1:\t @ start loop\n bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\t\n strb r1,[r3,r2] @ store digit on area\n sub r2,#1 @ previous position\n cmp r0,#0 @ stop if quotient = 0 *\/\n bne 1b\t @ else loop\n @ and move spaces in first on area\n mov r1,#' ' @ space\t\n2:\t\n strb r1,[r3,r2] @ store space in area\n subs r2,#1 @ @ previous position\n bge 2b @ loop if r2 >= z\u00e9ro \n\n100:\t\n pop {r1-r4,lr} @ restaur registres \n bx lr\t @return\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save registers *\/\n mov r4,r0 \n mov r3,#0x6667 @ r3 <- magic_number lower\n movt r3,#0x6666 @ r3 <- magic_number upper\n smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) \n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n\/***************************************************\/\n\/* integer division unsigned *\/\n\/***************************************************\/\ndivision:\n \/* r0 contains dividend *\/\n \/* r1 contains divisor *\/\n \/* r2 returns quotient *\/\n \/* r3 returns remainder *\/\n push {r4, lr}\n mov r2, #0 @ init quotient\n mov r3, #0 @ init remainder\n mov r4, #32 @ init counter bits\n b 2f\n1: @ loop \n movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)\n adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3\u00a0? (r3 << 1) + C \n cmp r3, r1 @ compute r3 - r1 and update cpsr \n subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3\u00a0? r3 - r1 \n adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C \n2:\n subs r4, r4, #1 @ r4 <- r4 - 1 \n bpl 1b @ if r4 >= 0 (N=0) then loop\n pop {r4, lr}\n bx lr\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":737} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program stringLength.s *\/ \n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nsMessResultByte: .asciz \"===Byte Length===\u00a0: @ \\n\"\nsMessResultChar: .asciz \"===Character Length===\u00a0: @ \\n\"\nszString1: .asciz \"m\u00f8\u00f8se\u20ac\"\nszCarriageReturn: .asciz \"\\n\"\n \n\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\nsZoneConv: .skip 24\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdrszString1\n bl affichageMess @ display string\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n \n ldr r0,iAdrszString1\n mov r1,#0\n1: @ loop compute length bytes\n ldrb r2,[r0,r1]\n cmp r2,#0\n addne r1,#1\n bne 1b\n \n mov r0,r1 @ result display\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n ldr r0,iAdrsMessResultByte\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n\n ldr r0,iAdrszString1\n mov r1,#0\n mov r3,#0\n2: @ loop compute length characters\n ldrb r2,[r0,r1]\n cmp r2,#0\n beq 6f\n and r2,#0b11100000 @ 3 bytes\u00a0?\n cmp r2,#0b11100000\n bne 3f\n add r3,#1\n add r1,#3\n b 2b\n3:\n and r2,#0b11000000 @ 2 bytes\u00a0?\n cmp r2,#0b11000000\n bne 4f\n add r3,#1\n add r1,#2\n b 2b\n4: @ else 1 byte\n add r3,#1\n add r1,#1\n b 2b\n\n6:\n mov r0,r3\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n ldr r0,iAdrsMessResultChar\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResultByte: .int sMessResultByte\niAdrsMessResultChar: .int sMessResultChar\niAdrszString1: .int szString1\niAdrsZoneConv: .int sZoneConv\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\nm\u00f8\u00f8se\u20ac\n===Byte Length===\u00a0: 10\n===Character Length===\u00a0: 6\n\n","human_summarization":"calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.","id":738} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program urandom.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ READ, 3\n.equ WRITE, 4\n.equ OPEN, 5\n.equ CLOSE, 6\n\n.equ O_RDONLY, 0 @ open for reading only\n\n.equ BUFFERSIZE, 4 @ random number 32 bits\n\n\/* Initialized data *\/\n.data\nszFileName: .asciz \"\/dev\/urandom\" @ see linux doc \nszCarriageReturn: .asciz \"\\n\"\n\/* datas error display *\/\nszMessErreur: .asciz \"Error detected.\\n\"\nszMessErr: .ascii \"Error code hexa\u00a0: \"\nsHexa: .space 9,' '\n .ascii \" decimal\u00a0: \"\nsDeci: .space 15,' '\n .asciz \"\\n\"\n\/* datas message display *\/\nszMessResult: .ascii \"Random number\u00a0:\"\nsValue: .space 12,' '\n .asciz \"\\n\"\n\/* UnInitialized data *\/\n.bss \nsBuffer: .skip BUFFERSIZE @ buffer result\n\n\/* code section *\/\n.text\n.global main \nmain: \n ldr r0,iAdrszFileName @ File name\n mov r1,#O_RDONLY @ flags\n mov r2,#0 @ mode\n mov r7,#OPEN @ open file\n svc #0 \n cmp r0,#0 @ error\u00a0?\n ble error\n mov r8,r0 @ save FD\n mov r4,#0 @ loop counter\n1:\n mov r0,r8 @ File Descriptor\n ldr r1,iAdrsBuffer @ buffer address\n mov r2,#BUFFERSIZE @ buffer size\n mov r7,#READ @ call system read file\n svc 0 \n cmp r0,#0 @ read error\u00a0?\n ble error\n ldr r1,iAdrsBuffer @ buffer address\n ldr r0,[r1] @ display buffer value\n ldr r1,iAdrsValue\n bl conversion10\n ldr r0,iAdrszMessResult\n bl affichageMess\n add r4,#1 @ increment counter\n cmp r4,#10 @ maxi\u00a0?\n blt 1b @ no -> loop\n\n\nend:\n mov r0,r8\n mov r7, #CLOSE @ call system close file\n svc #0 \n cmp r0,#0\n blt error\n mov r0,#0 @ return code\n b 100f\nerror:\n ldr r1,iAdrszMessErreur @ error message\n bl displayError\n mov r0,#1 @ return error code\n100: @ standard end of the program\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\niAdrsBuffer: .int sBuffer\niAdrsValue: .int sValue\niAdrszMessResult: .int szMessResult\niAdrszFileName: .int szFileName\niAdrszMessErreur: .int szMessErreur\niAdrszCarriageReturn: .int szCarriageReturn\n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registers \n mov r2,#0 @ counter length *\/\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call system\n pop {r0,r1,r2,r7,lr} @ restaur registers\n bx lr @ return\n\/***************************************************\/\n\/* display error message *\/\n\/***************************************************\/\n\/* r0 contains error code r1\u00a0: message address *\/\ndisplayError:\n push {r0-r2,lr} @ save registers\n mov r2,r0 @ save error code\n mov r0,r1\n bl affichageMess\n mov r0,r2 @ error code\n ldr r1,iAdrsHexa\n bl conversion16 @ conversion hexa\n mov r0,r2 @ error code\n ldr r1,iAdrsDeci @ result address\n bl conversion10S @ conversion decimale\n ldr r0,iAdrszMessErr @ display error message\n bl affichageMess\n100:\n pop {r0-r2,lr} @ restaur registers\n bx lr @ return \niAdrszMessErr: .int szMessErr\niAdrsHexa: .int sHexa\niAdrsDeci: .int sDeci\n\/******************************************************************\/\n\/* Converting a register to hexadecimal *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\nconversion16:\n push {r1-r4,lr} @ save registers\n mov r2,#28 @ start bit position\n mov r4,#0xF0000000 @ mask\n mov r3,r0 @ save entry value\n1: @ start loop\n and r0,r3,r4 @ value register and mask\n lsr r0,r2 @ move right \n cmp r0,#10 @ compare value\n addlt r0,#48 @ <10 ->digit\n addge r0,#55 @ >10 ->letter A-F\n strb r0,[r1],#1 @ store digit on area and + 1 in area address\n lsr r4,#4 @ shift mask 4 positions\n subs r2,#4 @ counter bits - 4 <= zero \u00a0?\n bge 1b @ no -> loop\n\n100:\n pop {r1-r4,lr} @ restaur registers \n bx lr \n\/***************************************************\/\n\/* Converting a register to a signed decimal *\/\n\/***************************************************\/\n\/* r0 contains value and r1 area address *\/\nconversion10S:\n push {r0-r4,lr} @ save registers\n mov r2,r1 @ debut zone stockage\n mov r3,#'+' @ par defaut le signe est +\n cmp r0,#0 @ negative number\u00a0? \n movlt r3,#'-' @ yes\n mvnlt r0,r0 @ number inversion\n addlt r0,#1\n mov r4,#10 @ length area\n1: @ start loop\n bl divisionpar10U\n add r1,#48 @ digit\n strb r1,[r2,r4] @ store digit on area\n sub r4,r4,#1 @ previous position\n cmp r0,#0 @ stop if quotient = 0\n bne 1b\t\n\n strb r3,[r2,r4] @ store signe \n subs r4,r4,#1 @ previous position\n blt 100f @ if r4 < 0 -> end\n\n mov r1,#' ' @ space\n2:\n strb r1,[r2,r4] @store byte space\n subs r4,r4,#1 @ previous position\n bge 2b @ loop if r4 > 0\n100: \n pop {r0-r4,lr} @ restaur registers\n bx lr \n\/***************************************************\/\n\/* division par 10 unsigned *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\n\/* r1 remainder *\/\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n \/\/mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3\n \/\/movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: \t.int 0xCCCCCCCD\n","human_summarization":"demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.","id":739} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program knuthShuffle.s *\/\n\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nsMessResult: .ascii \"Value \u00a0: \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\nszCarriageReturn: .asciz \"\\n\"\n\n.align 4\niGraine: .int 123456\n.equ NBELEMENTS, 10\nTableNumber:\t .int 1,2,3,4,5,6,7,8,9,10\n\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdrTableNumber @ address number table\n mov r1,#NBELEMENTS @ number of \u00e9lements \n bl knuthShuffle\n ldr r2,iAdrTableNumber\n mov r3,#0\n1: @ loop display table\n ldr r0,[r2,r3,lsl #2]\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n add r3,#1\n cmp r3,#NBELEMENTS - 1\n ble 1b\n\n ldr r0,iAdrszCarriageReturn\n bl affichageMess \n \/* 2e shuffle *\/\n ldr r0,iAdrTableNumber @ address number table\n mov r1,#NBELEMENTS @ number of \u00e9lements \n bl knuthShuffle\n ldr r2,iAdrTableNumber\n mov r3,#0\n2: @ loop display table\n ldr r0,[r2,r3,lsl #2]\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n add r3,#1\n cmp r3,#NBELEMENTS - 1\n ble 2b\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdrTableNumber: .int TableNumber\n\n\/******************************************************************\/\n\/* Knuth Shuffle *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains the number of elements *\/\nknuthShuffle:\n push {r2-r5,lr} @ save registers\n mov r5,r0 @ save table address\n mov r2,#0 @ start index\n1:\n mov r0,r2 @ generate aleas\n bl genereraleas\n ldr r3,[r5,r2,lsl #2] @ swap number on the table\n ldr r4,[r5,r0,lsl #2]\n str r4,[r5,r2,lsl #2]\n str r3,[r5,r0,lsl #2]\n add r2,#1 @ next number\n cmp r2,r1 @ end\u00a0?\n blt 1b @ no -> loop\n\n100:\n pop {r2-r5,lr}\n bx lr @ return \n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal unsigned *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\n\/* r0 return size of result (no zero final in area) *\/\n\/* area size => 11 bytes *\/\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n\n1:\t @ start loop\n bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b\t @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n\n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n\n\/***************************************************\/\n\/* division par 10 unsigned *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n \/\/mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3\n \/\/movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: \t.int 0xCCCCCCCD\n\/***************************************************\/\n\/* Generation random number *\/\n\/***************************************************\/\n\/* r0 contains limit *\/\ngenereraleas:\n push {r1-r4,lr} @ save registers \n ldr r4,iAdriGraine\n ldr r2,[r4]\n ldr r3,iNbDep1\n mul r2,r3,r2\n ldr r3,iNbDep1\n add r2,r2,r3\n str r2,[r4] @ maj de la graine pour l appel suivant \n cmp r0,#0\n beq 100f\n mov r1,r0 @ divisor\n mov r0,r2 @ dividende\n bl division\n mov r0,r3 @ r\u00e9sult = remainder\n \n100: @ end function\n pop {r1-r4,lr} @ restaur registers\n bx lr @ return\n\/*****************************************************\/\niAdriGraine: .int iGraine\t\niNbDep1: .int 0x343FD\niNbDep2: .int 0x269EC3 \n\/***************************************************\/\n\/* integer division unsigned *\/\n\/***************************************************\/\ndivision:\n \/* r0 contains dividend *\/\n \/* r1 contains divisor *\/\n \/* r2 returns quotient *\/\n \/* r3 returns remainder *\/\n push {r4, lr}\n mov r2, #0 @ init quotient\n mov r3, #0 @ init remainder\n mov r4, #32 @ init counter bits\n b 2f\n1: @ loop \n movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)\n adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3\u00a0? (r3 << 1) + C \n cmp r3, r1 @ compute r3 - r1 and update cpsr \n subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1 \n adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C \n2:\n subs r4, r4, #1 @ r4 <- r4 - 1 \n bpl 1b @ if r4 >= 0 (N=0) then loop\n pop {r4, lr}\n bx lr\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":740} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program caresarcode.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n.equ STRINGSIZE, 500\n\n\/* Initialized data *\/\n.data\nszMessString: .asciz \"String\u00a0:\\n\"\nszMessEncrip: .asciz \"\\nEncrypted\u00a0:\\n\"\nszMessDecrip: .asciz \"\\nDecrypted\u00a0:\\n\"\nszString1: .asciz \"Why study medicine because there is internet\u00a0?\"\n\nszCarriageReturn: .asciz \"\\n\"\n\n\/* UnInitialized data *\/\n.bss \nszString2: .skip STRINGSIZE\nszString3: .skip STRINGSIZE\n\/* code section *\/\n.text\n.global main \nmain: \n\n ldr r0,iAdrszMessString @ display message\n bl affichageMess\n ldr r0,iAdrszString1 @ display string\n bl affichageMess\n ldr r0,iAdrszString1\n ldr r1,iAdrszString2\n mov r2,#20 @ key\n bl encrypt\n ldr r0,iAdrszMessEncrip\n bl affichageMess\n ldr r0,iAdrszString2 @ display string\n bl affichageMess \n ldr r0,iAdrszString2\n ldr r1,iAdrszString3\n mov r2,#20 @ key\n bl decrypt\n ldr r0,iAdrszMessDecrip\n bl affichageMess\n ldr r0,iAdrszString3 @ display string\n bl affichageMess \n ldr r0,iAdrszCarriageReturn\n bl affichageMess \n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\niAdrszMessString: .int szMessString\niAdrszMessDecrip: .int szMessDecrip\niAdrszMessEncrip: .int szMessEncrip\niAdrszString1: .int szString1\niAdrszString2: .int szString2\niAdrszString3: .int szString3\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* encrypt strings *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the string1 *\/\n\/* r1 contains the address of the encrypted string *\/\n\/* r2 contains the key (1-25) *\/\nencrypt:\n push {r3,r4,lr} @ save registers \n mov r3,#0 @ counter byte string 1\n1:\n ldrb r4,[r0,r3] @ load byte string 1\n cmp r4,#0 @ zero final\u00a0?\n streqb r4,[r1,r3]\n moveq r0,r3\n beq 100f\n cmp r4,#65 @ < A\u00a0?\n strltb r4,[r1,r3]\n addlt r3,#1\n blt 1b\n cmp r4,#90 @ > Z\n bgt 2f\n add r4,r2 @ add key\n cmp r4,#90 @ > Z\n subgt r4,#26\n strb r4,[r1,r3]\n add r3,#1\n b 1b\n2:\n cmp r4,#97 @ < a\u00a0?\n strltb r4,[r1,r3]\n addlt r3,#1\n blt 1b\n cmp r4,#122 @> z\n strgtb r4,[r1,r3]\n addgt r3,#1\n bgt 1b\n add r4,r2\n cmp r4,#122\n subgt r4,#26\n strb r4,[r1,r3]\n add r3,#1\n b 1b\n\n100:\n pop {r3,r4,lr} @ restaur registers\n bx lr @ return\n\/******************************************************************\/\n\/* decrypt strings *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the encrypted string1 *\/\n\/* r1 contains the address of the decrypted string *\/\n\/* r2 contains the key (1-25) *\/\ndecrypt:\n push {r3,r4,lr} @ save registers \n mov r3,#0 @ counter byte string 1\n1:\n ldrb r4,[r0,r3] @ load byte string 1\n cmp r4,#0 @ zero final\u00a0?\n streqb r4,[r1,r3]\n moveq r0,r3\n beq 100f\n cmp r4,#65 @ < A\u00a0?\n strltb r4,[r1,r3]\n addlt r3,#1\n blt 1b\n cmp r4,#90 @ > Z\n bgt 2f\n sub r4,r2 @ substract key\n cmp r4,#65 @ < A\n addlt r4,#26\n strb r4,[r1,r3]\n add r3,#1\n b 1b\n2:\n cmp r4,#97 @ < a\u00a0?\n strltb r4,[r1,r3]\n addlt r3,#1\n blt 1b\n cmp r4,#122 @ > z\n strgtb r4,[r1,r3]\n addgt r3,#1\n bgt 1b\n sub r4,r2 @ substract key\n cmp r4,#97 @ < a\n addlt r4,#26\n strb r4,[r1,r3]\n add r3,#1\n b 1b\n\n100:\n pop {r3,r4,lr} @ restaur registers\n bx lr @ return\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registers \n mov r2,#0 @ counter length *\/\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call system\n pop {r0,r1,r2,r7,lr} @ restaur registers\n bx lr @ return\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":741} {"lang_cluster":"ARM_Assembly","source_code":"\n\nEndianTest:\nmov r0,#0xFF\nmov r1,#0x02000000 ;an arbitrary memory location on the Game Boy Advance. \n \u00a0;(The GBA is always little-endian but this test doesn't use that knowledge to prove it.)\nstr r0,[r1] ;on a little-endian CPU a hexdump of 0x02000000 would be: FF 00 00 00\n ;on a big-endian CPU it would be: 00 00 00 FF\nldrB r0,[r1] ;load just the byte at 0x02000000. If the machine is big-endian this will load 00; if little-endian, 0xFF.\ncmp r0,#0\nbeq isBigEndian\n;else, do whatever is needed to display \"little-endian\" to the screen. This part isn't implemented.\n","human_summarization":"determine and print the word size and endianness of the host machine, specifically for an ARM CPU which may be either little-endian or big-endian. The endianness is tested by writing a word to RAM and reading the 0th byte from that memory location.","id":742} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program strTokenize.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n.equ NBPOSTESECLAT, 20\n\n\/* Initialized data *\/\n.data\nszMessFinal: .asciz \"Words are\u00a0: \\n\"\n\nszString: .asciz \"Hello,How,Are,You,Today\"\nszMessError: .asciz \"Error tokenize\u00a0!!\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\n\/* UnInitialized data *\/\n.bss \n\n\/* code section *\/\n.text\n.global main \nmain: \n ldr r0,iAdrszString @ string address \n mov r1,#',' @ separator\n bl stTokenize\n cmp r0,#-1 @ error\u00a0?\n beq 99f\n mov r2,r0 @ table address\n ldr r0,iAdrszMessFinal @ display message\n bl affichageMess\n ldr r4,[r2] @ number of areas\n add r2,#4 @ first area\n mov r3,#0 @ loop counter\n1: @ display loop \n ldr r0,[r2,r3, lsl #2] @ address area\n bl affichageMess\n ldr r0,iAdrszCarriageReturn @ display carriage return\n bl affichageMess\n add r3,#1 @ counter + 1\n cmp r3,r4 @ end\u00a0?\n blt 1b @ no -> loop\n\n b 100f\n99: @ display error message\n ldr r0,iAdrszMessError\n bl affichageMess\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform the system call\niAdrszString: .int szString\niAdrszFinalString: .int szFinalString\niAdrszMessFinal: .int szMessFinal\niAdrszMessError: .int szMessError\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registers \n mov r2,#0 @ counter length *\/\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme\n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres\n bx lr @ return\n\/*******************************************************************\/\t \n\/* Separate string by separator into an array *\/\n\/* areas are store on the heap Linux *\/\n\/*******************************************************************\/\t \n\/* r0 contains string address *\/\n\/* r1 contains separator character (, or . or\u00a0: ) *\/\n\/* r0 returns table address with first item = number areas *\/\n\/* and other items contains pointer of each string *\/\nstTokenize:\n push {r1-r8,lr} @ save des registres\n mov r6,r0\n mov r8,r1 @ save separator\n bl strLength @ length string for place reservation on the heap\n mov r4,r0\n ldr r5,iTailleTable\n add r5,r0\n and r5,#0xFFFFFFFC\n add r5,#4 @ align word on the heap\n @ place reservation on the heap \n mov r0,#0 @ heap address\n mov r7, #0x2D @ call system linux 'brk'\n svc #0 @ call system\n cmp r0,#-1 @ error call system\n beq 100f\n mov r3,r0 @ save address heap begin\n add r0,r5 @ reserve r5 byte on the heap\n mov r7, #0x2D @ call system linux 'brk'\n svc #0\n cmp r0,#-1\n beq 100f\n @ string copy on the heap\n mov r0,r6\n mov r1,r3\n1: @ loop copy string\n ldrb r2,[r0],#1 @ read one byte and increment pointer one byte\n strb r2,[r1],#1 @ store one byte and increment pointer one byte\n cmp r2,#0 @ end of string\u00a0?\n bne 1b @ no -> loop \n\n add r4,r3 @ r4 contains address table begin\n mov r0,#0\n str r0,[r4]\n str r3,[r4,#4]\n mov r2,#1 @ areas counter\n2: @ loop load string character \n ldrb r0,[r3]\n cmp r0,#0\n beq 3f @ end string \n cmp r0,r8 @ separator\u00a0?\n addne r3,#1 @ no -> next location \n bne 2b @ and loop\n mov r0,#0 @ store zero final of string\n strb r0,[r3]\n add r3,#1 @ next character\n add r2,#1 @ areas counter + 1\n str r3,[r4,r2, lsl #2] @ store address area in the table at index r2\n b 2b @ and loop\n \n3:\n str r2,[r4] @ returns number areas\n mov r0,r4\n100:\n pop {r1-r8,lr}\n bx lr\niTailleTable: .int 4 * NBPOSTESECLAT\n\/***************************************************\/\n\/* calcul size string *\/\n\/***************************************************\/\n\/* r0 string address *\/\n\/* r0 returns size string *\/\nstrLength:\n push {r1,r2,lr}\n mov r1,#0 @ init counter\n1:\n ldrb r2,[r0,r1] @ load byte of string index r1\n cmp r2,#0 @ end string\u00a0?\n addne r1,#1 @ no -> +1 counter\n bne 1b @ and loop\n\n100:\n mov r0,r1\n pop {r1,r2,lr}\n bx lr\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":743} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program strNumber.s *\/\n\n\/* Constantes *\/\n.equ STDIN, 0 @ Linux input console\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ READ, 3 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n.equ BUFFERSIZE, 100\n\n\n\/* Initialized data *\/\n.data\nszMessNum: .asciz \"Enter number\u00a0: \\n\"\n\nszMessError: .asciz \"String is not a number\u00a0!!!\\n\"\nszMessInteger: .asciz \"String is a integer.\\n\"\nszMessFloat: .asciz \"String is a float.\\n\"\nszMessFloatExp: .asciz \"String is a float with exposant.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\n\/* UnInitialized data *\/\n.bss \nsBuffer: .skip BUFFERSIZE\n\n\/* code section *\/\n.text\n.global main \nmain: \n\nloop:\n ldr r0,iAdrszMessNum\n bl affichageMess\n mov r0,#STDIN @ Linux input console\n ldr r1,iAdrsBuffer @ buffer address \n mov r2,#BUFFERSIZE @ buffer size \n mov r7, #READ @ request to read datas\n swi 0 @ call system\n ldr r1,iAdrsBuffer @ buffer address \n mov r2,#0 @ end of string\n sub r0,#1 @ replace character 0xA\n strb r2,[r1,r0] @ store byte at the end of input string (r0 contains number of characters)\n ldr r0,iAdrsBuffer\n bl controlNumber @ call routine\n cmp r0,#0\n bne 1f\n ldr r0,iAdrszMessError @ not a number\n bl affichageMess\n b 5f\n1:\n cmp r0,#1\n bne 2f\n ldr r0,iAdrszMessInteger @ integer\n bl affichageMess\n b 5f\n2:\n cmp r0,#2\n bne 3f\n ldr r0,iAdrszMessFloat @ float\n bl affichageMess\n b 5f\n3:\n cmp r0,#3\n bne 5f\n ldr r0,iAdrszMessFloatExp @ float with exposant\n bl affichageMess\n5:\n b loop\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\niAdrszMessNum: .int szMessNum\niAdrszMessError: .int szMessError\niAdrszMessInteger: .int szMessInteger\niAdrszMessFloat: .int szMessFloat\niAdrszMessFloatExp: .int szMessFloatExp\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsBuffer: .int sBuffer\n\/******************************************************************\/\n\/* control if string is number *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the string *\/\n\/* r0 return 0 if not a number *\/\n\/* r0 return 1 if integer eq 12345 or -12345 *\/\n\/* r0 return 2 if float eq 123.45 or 123,45 or -123,45 *\/\n\/* r0 return 3 if float with exposant eq 123.45E30 or -123,45E-30 *\/\ncontrolNumber:\n push {r1-r4,lr} @ save registers \n mov r1,#0\n mov r3,#0 @ point counter \n1:\n ldrb r2,[r0,r1]\n cmp r2,#0\n beq 5f\n cmp r2,#' '\n addeq r1,#1\n beq 1b\n cmp r2,#'-' @ negative\u00a0?\n addeq r1,#1\n beq 2f\n cmp r2,#'+' @ positive\u00a0?\n addeq r1,#1\n2:\n ldrb r2,[r0,r1] @ control space\n cmp r2,#0 @ end\u00a0?\n beq 5f\n cmp r2,#' '\n addeq r1,#1\n beq 2b\n3:\n ldrb r2,[r0,r1]\n cmp r2,#0 @ end\u00a0?\n beq 10f\n cmp r2,#'E' @ exposant\u00a0?\n beq 6f\n cmp r2,#'e' @ exposant\u00a0?\n beq 6f\n cmp r2,#'.' @ point\u00a0?\n addeq r3,#1 @ yes increment counter\n addeq r1,#1\n beq 3b\n cmp r2,#',' @ comma\u00a0?\n addeq r3,#1 @ yes increment counter\n addeq r1,#1\n beq 3b\n cmp r2,#'0' @ control digit < 0\n blt 5f\n cmp r2,#'9' @ control digit > 0\n bgt 5f\n add r1,#1 @ no error loop digit\n b 3b\n5: @ error detected\n mov r0,#0\n b 100f\n6: @ float with exposant\n add r1,#1\n ldrb r2,[r0,r1]\n cmp r2,#0 @ end\u00a0?\n moveq r0,#0 @ error\n beq 100f\n cmp r2,#'-' @ negative exposant\u00a0?\n addeq r1,#1\n mov r4,#0 @ nombre de chiffres \n7:\n ldrb r2,[r0,r1]\n cmp r2,#0 @ end\u00a0?\n beq 9f\n cmp r2,#'0' @ control digit < 0\n blt 8f\n cmp r2,#'9' @ control digit > 0\n bgt 8f\n add r1,#1\n add r4,#1 @ counter digit\n b 7b\n8:\n mov r0,#0\n b 100f\n9:\n cmp r4,#0 @ number digit exposant = 0 -> error \n moveq r0,#0 @ erreur\n beq 100f\n cmp r4,#2 @ number digit exposant > 2 -> error \n movgt r0,#0 @ error\n bgt 100f\n mov r0,#3 @ valid float with exposant\n b 100f\n10:\n cmp r3,#0\n moveq r0,#1 @ valid integer\n beq 100f\n cmp r3,#1 @ number of point or comma = 1\u00a0?\n moveq r0,#2 @ valid float\n movgt r0,#0 @ error\n100:\n pop {r1-r4,lr} @ restaur des 2 registres\n bx lr @ return\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registers \n mov r2,#0 @ counter length *\/\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call system\n pop {r0,r1,r2,r7,lr} @ restaur registers\n bx lr @ return\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":744} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program incstring.s *\/\n\n\/* Constantes *\/\n.equ BUFFERSIZE, 100\n.equ STDIN, 0 @ Linux input console\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ READ, 3 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/* Initialized data *\/\n.data\nszMessNum: .asciz \"Enter number\u00a0: \\n\"\nszCarriageReturn: .asciz \"\\n\"\nszMessResult: .ascii \"Increment number is = \" @ message result\nsMessValeur: .fill 12, 1, ' '\n .asciz \"\\n\"\n\n\/* UnInitialized data *\/\n.bss \nsBuffer: .skip BUFFERSIZE\n\n\/* code section *\/\n.text\n.global main \nmain: \/* entry of program *\/\n push {fp,lr} \/* saves 2 registers *\/\n\n ldr r0,iAdrszMessNum\n bl affichageMess\n mov r0,#STDIN @ Linux input console\n ldr r1,iAdrsBuffer @ buffer address \n mov r2,#BUFFERSIZE @ buffer size \n mov r7, #READ @ request to read datas\n swi 0 @ call system\n ldr r1,iAdrsBuffer @ buffer address \n mov r2,#0 @ end of string\n strb r2,[r1,r0] @ store byte at the end of input string (r0\n @ \n ldr r0,iAdrsBuffer @ buffer address\n bl conversionAtoD @ conversion string in number in r0\n @ increment r0\n add r0,#1\n @ conversion register to string\n ldr r1,iAdrsMessValeur \n bl conversion10S @ call conversion\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n \n100: \/* standard end of the program *\/\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrszMessNum: .int szMessNum\niAdrsBuffer: .int sBuffer\niAdrszMessResult: .int szMessResult\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {fp,lr} \t\t\t\/* save registres *\/ \n push {r0,r1,r2,r7} \t\t\/* save others registers *\/\n mov r2,#0 \t\t\t\t\/* counter length *\/\n1: \/* loop length calculation *\/\n ldrb r1,[r0,r2] \t\t\t\/* read octet start position + index *\/\n cmp r1,#0 \t\t\t\/* if 0 its over *\/\n addne r2,r2,#1 \t\t\t\/* else add 1 in the length *\/\n bne 1b \t\t\t\/* and loop *\/\n \/* so here r2 contains the length of the message *\/\n mov r1,r0 \t\t\t\/* address message in r1 *\/\n mov r0,#STDOUT \t\t\/* code to write to the standard output Linux *\/\n mov r7, #WRITE \/* code call system \"write\" *\/\n swi #0 \/* call systeme *\/\n pop {r0,r1,r2,r7} \t\t\/* restaur others registers *\/\n pop {fp,lr} \t\t\t\t\/* restaur des 2 registres *\/ \n bx lr\t \t\t\t\/* return *\/\n\n \/******************************************************************\/\n\/* Convert a string to a number stored in a registry *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the area terminated by 0 or 0A *\/\n\/* r0 returns a number *\/\nconversionAtoD:\n push {fp,lr} @ save 2 registers \n push {r1-r7} @ save others registers \n mov r1,#0\n mov r2,#10 @ factor \n mov r3,#0 @ counter \n mov r4,r0 @ save address string -> r4 \n mov r6,#0 @ positive sign by default \n mov r0,#0 @ initialization to 0 \n1: \/* early space elimination loop *\/\n ldrb r5,[r4,r3] @ loading in r5 of the byte located at the beginning + the position \n cmp r5,#0 @ end of string -> end routine\n beq 100f\n cmp r5,#0x0A @ end of string -> end routine\n beq 100f\n cmp r5,#' ' @ space\u00a0? \n addeq r3,r3,#1 @ yes we loop by moving one byte \n beq 1b\n cmp r5,#'-' @ first character is - \n moveq r6,#1 @ 1 -> r6\n beq 3f @ then move on to the next position \n2: \/* beginning of digit processing loop *\/\n cmp r5,#'0' @ character is not a number \n blt 3f\n cmp r5,#'9' @ character is not a number\n bgt 3f\n \/* character is a number *\/\n sub r5,#48\n umull r0,r1,r2,r0 @ multiply par factor 10 \n\tcmp r1,#0 @ overflow\u00a0?\n bgt 99f @ overflow error\n add r0,r5 @ add to r0 \n3:\n add r3,r3,#1 @ advance to the next position \n ldrb r5,[r4,r3] @ load byte \n cmp r5,#0 @ end of string -> end routine\n beq 4f\n cmp r5,#0x0A @ end of string -> end routine\n beq 4f\n b 2b @ loop \n4:\n cmp r6,#1 @ test r6 for sign \n moveq r1,#-1\n muleq r0,r1,r0 @ if negatif, multiply par -1 \n b 100f\n99: \/* overflow error *\/\n ldr r0,=szMessErrDep\n bl affichageMess\n mov r0,#0 @ return zero if error\n100:\n pop {r1-r7} @ restaur other registers \n pop {fp,lr} @ restaur 2 registers \n bx lr @return procedure \n\/* constante program *\/\t\nszMessErrDep: .asciz \"Too large: overflow 32 bits.\\n\"\n.align 4\n\n\/***************************************************\/\n\/* Converting a register to a signed decimal *\/\n\/***************************************************\/\n\/* r0 contains value and r1 area address *\/\nconversion10S:\n push {r0-r4,lr} @ save registers\n mov r2,r1 \/* debut zone stockage *\/\n mov r3,#'+' \/* par defaut le signe est + *\/\n cmp r0,#0 @ negative number\u00a0? \n movlt r3,#'-' @ yes\n mvnlt r0,r0 @ number inversion\n addlt r0,#1 \n mov r4,#10 @ length area\n1: @ start loop\n bl divisionpar10\n add r1,#48 @ digit\n strb r1,[r2,r4] @ store digit on area\n sub r4,r4,#1 @ previous position\n cmp r0,#0 @ stop if quotient = 0\n bne 1b\t\n\n strb r3,[r2,r4] @ store signe \n subs r4,r4,#1 @ previous position\n blt 100f @ if r4 < 0 -> end\n\n mov r1,#' ' @ space\t\n2:\n strb r1,[r2,r4] @store byte space\n subs r4,r4,#1 @ previous position\n bge 2b @ loop if r4 > 0\n100: \n pop {r0-r4,lr} @ restaur registers\n bx lr \n\n\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save registers *\/\n mov r4,r0 \n ldr r3, .Ls_magic_number_10 \/* r1 <- magic_number *\/\n smull r1, r2, r3, r0 \/* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) *\/\n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n .align 4\n.Ls_magic_number_10: .word 0x66666667\n","human_summarization":"\"Increments a given numerical string.\"","id":745} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program sattolo.s *\/\n\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nsMessResult: .ascii \"Value \u00a0: \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\nszCarriageReturn: .asciz \"\\n\"\n\n.align 4\niGraine: .int 123456\n.equ NBELEMENTS, 9\nTableNumber:\t .int 4,6,7,10,11,15,22,30,35\n\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdrTableNumber @ address number table\n mov r1,#NBELEMENTS @ number of \u00e9lements \n bl satShuffle\n ldr r2,iAdrTableNumber\n mov r3,#0\n1: @ loop display table\n\tldr r0,[r2,r3,lsl #2]\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n add r3,#1\n cmp r3,#NBELEMENTS - 1\n ble 1b\n\n ldr r0,iAdrszCarriageReturn\n bl affichageMess \n \/* 2e shuffle *\/\n ldr r0,iAdrTableNumber @ address number table\n mov r1,#NBELEMENTS @ number of \u00e9lements \n bl satShuffle\n ldr r2,iAdrTableNumber\n mov r3,#0\n2: @ loop display table\n ldr r0,[r2,r3,lsl #2]\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n add r3,#1\n cmp r3,#NBELEMENTS - 1\n ble 2b\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdrTableNumber: .int TableNumber\n\n\/******************************************************************\/\n\/* Sattolo Shuffle *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains the number of elements *\/\nsatShuffle:\n push {r2-r6,lr} @ save registers\n mov r5,r0 @ save table address\n mov r2,#1 @ start index\n mov r4,r1 @ last index + 1\n1:\n sub r1,r2,#1 @ index - 1\n mov r0,r1 @ generate aleas\n bl genereraleas\n ldr r3,[r5,r1,lsl #2] @ swap number on the table\n ldr r6,[r5,r0,lsl #2]\n str r6,[r5,r1,lsl #2]\n str r3,[r5,r0,lsl #2]\n add r2,#1 @ next number\n cmp r2,r4 @ end\u00a0?\n ble 1b @ no -> loop\n\n100:\n pop {r2-r6,lr}\n bx lr @ return \n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal unsigned *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\n\/* r0 return size of result (no zero final in area) *\/\n\/* area size => 11 bytes *\/\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n\n1:\t @ start loop\n bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b\t @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n\n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n\n\/***************************************************\/\n\/* division par 10 unsigned *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n \/\/mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3\n \/\/movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: \t.int 0xCCCCCCCD\n\/***************************************************\/\n\/* Generation random number *\/\n\/***************************************************\/\n\/* r0 contains limit *\/\ngenereraleas:\n push {r1-r4,lr} @ save registers \n ldr r4,iAdriGraine\n ldr r2,[r4]\n ldr r3,iNbDep1\n mul r2,r3,r2\n ldr r3,iNbDep1\n add r2,r2,r3\n str r2,[r4] @ maj de la graine pour l appel suivant \n cmp r0,#0\n beq 100f\n mov r1,r0 @ divisor\n mov r0,r2 @ dividende\n bl division\n mov r0,r3 @ r\u00e9sult = remainder\n \n100: @ end function\n pop {r1-r4,lr} @ restaur registers\n bx lr @ return\n\/*****************************************************\/\niAdriGraine: .int iGraine\t\niNbDep1: .int 0x343FD\niNbDep2: .int 0x269EC3 \n\/***************************************************\/\n\/* integer division unsigned *\/\n\/***************************************************\/\ndivision:\n \/* r0 contains dividend *\/\n \/* r1 contains divisor *\/\n \/* r2 returns quotient *\/\n \/* r3 returns remainder *\/\n push {r4, lr}\n mov r2, #0 @ init quotient\n mov r3, #0 @ init remainder\n mov r4, #32 @ init counter bits\n b 2f\n1: @ loop \n movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)\n adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3\u00a0? (r3 << 1) + C \n cmp r3, r1 @ compute r3 - r1 and update cpsr \n subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3 <- r3 - r1 \n adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C \n2:\n subs r4, r4, #1 @ r4 <- r4 - 1 \n bpl 1b @ if r4 >= 0 (N=0) then loop\n pop {r4, lr}\n bx lr\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":746} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI *\/\n\/* program averageMed.s *\/\n\/* use quickselect look pseudo code in wikipedia quickselect *\/\n\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n\/* for constantes see task include a file in arm assembly *\/\n.include \"..\/constantes.inc\"\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessResultValue: .asciz \"Result \u00a0: \"\nszCarriageReturn: .asciz \"\\n\"\n \n.align 4\nTableNumber: .float 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2\n.equ NBELEMENTS, (. - TableNumber) \/ 4\nTableNumber2:\t .float 4.1, 7.2, 1.7, 9.3, 4.4, 3.2\n.equ NBELEMENTS2, (. - TableNumber2) \/ 4\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\nsZoneConv: .skip 24\nsZoneConv1: .skip 24\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n\n ldr r0,iAdrTableNumber @ address number table\n mov r1,#0 @ index first item\n mov r2,#NBELEMENTS -1 @ index last item \n bl searchMedian\n ldr r0,iAdrTableNumber2 @ address number table 2\n mov r1,#0 @ index first item\n mov r2,#NBELEMENTS2 -1 @ index last item \n bl searchMedian\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrTableNumber: .int TableNumber\niAdrTableNumber2: .int TableNumber2\niAdrsZoneConv: .int sZoneConv\niAdrszMessResultValue: .int szMessResultValue\n\/***************************************************\/\n\/* search median term in float array *\/\n\/***************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains index of first item *\/\n\/* r2 contains index of last item *\/\nsearchMedian:\n push {r1-r5,lr} @ save registers\n mov r5,r0 @ save array address\n add r4,r1,r2\n add r4,r4,#1 @ sum numbers terms\n tst r4,#1 @ odd\u00a0?\n bne 1f\n lsr r3,r4,#1 @ compute median index\n bl select @ call selection\n vmov s0,r0 @ save first result\n sub r3,r3,#1 @ second term\n mov r0,r5\n bl select @ call selection\n vmov s1,r0 @ save 2ieme r\u00e9sult\n vadd.f32 s0,s1 @ compute average two r\u00e9sults\n mov r0,#2\n vmov s1,r0\n vcvt.f32.u32 s1,s1 @ conversion integer -> float\n vdiv.f32 s0,s0,s1\n b 2f\n1: @ even\n lsr r3,r4,#1\n bl select @ call selection\n vmov s0,r0\n2:\n ldr r0,iAdrsZoneConv @ conversion float in decimal string \n bl convertirFloat\n mov r0,#3 @ and display result\n ldr r1,iAdrszMessResultValue\n ldr r2,iAdrsZoneConv\n ldr r3,iAdrszCarriageReturn\n bl displayStrings \n100: @ end function\n pop {r1-r5,pc} @ restaur register\n\/***************************************************\/\n\/* Appel r\u00e9cursif selection *\/\n\/***************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains index of first item *\/\n\/* r2 contains index of last item *\/\n\/* r3 contains search index *\/\n\/* r0 return final value in float *\/\n\/* remark\u00a0: the final result is a float returned in r0 register *\/\nselect:\n push {r1-r6,lr} @ save registers\n mov r6,r3 @ save search index\n cmp r1,r2 @ first = last\u00a0? \n ldreq r0,[r0,r1,lsl #2] @ return value of first index\n beq 100f @ yes -> end\n add r3,r1,r2\n lsr r3,r3,#1 @ compute median pivot \n mov r4,r0 @ save r0\n mov r5,r2 @ save r2\n bl partition @ cutting into 2 parts\n cmp r6,r0 @ pivot is ok\u00a0?\n ldreq r0,[r4,r0,lsl #2] @ return value\n beq 100f\n bgt 1f\n sub r2,r0,#1 @ index partition - 1 \n mov r0,r4 @ array address\n mov r3,r6 @ search index\n bl select @ select lower part\n b 100f\n1:\n add r1,r0,#1 @ index begin = index partition + 1\n mov r0,r4 @ array address\n mov r2,r5 @ last item\n mov r3,r6 @ search index\n bl select @ select higter part\n 100: @ end function\n pop {r1-r6,pc} @ restaur register\n\/******************************************************************\/\n\/* Partition table elements *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains index of first item *\/\n\/* r2 contains index of last item *\/\n\/* r3 contains index of pivot *\/\npartition:\n push {r1-r6,lr} @ save registers\n ldr r4,[r0,r3,lsl #2] @ load value of pivot\n ldr r5,[r0,r2,lsl #2] @ load value last index\n str r5,[r0,r3,lsl #2] @ swap value of pivot\n str r4,[r0,r2,lsl #2] @ and value last index\n mov r3,r1 @ init with first index\n1: @ begin loop\n ldr r6,[r0,r3,lsl #2] @ load value\n cmp r6,r4 @ compare loop value and pivot value\n ldrlt r5,[r0,r1,lsl #2] @ if < swap value table\n strlt r6,[r0,r1,lsl #2]\n strlt r5,[r0,r3,lsl #2]\n addlt r1,#1 @ and increment index 1\n add r3,#1 @ increment index 2\n cmp r3,r2 @ end\u00a0?\n blt 1b @ no loop\n ldr r5,[r0,r1,lsl #2] @ swap value\n str r4,[r0,r1,lsl #2]\n str r5,[r0,r2,lsl #2]\n mov r0,r1 @ return index partition\n100:\n pop {r1-r6,pc}\n \n\/***************************************************\/\n\/* display multi strings *\/\n\/***************************************************\/\n\/* r0 contains number strings address *\/\n\/* r1 address string1 *\/\n\/* r2 address string2 *\/\n\/* r3 address string3 *\/\n\/* other address on the stack *\/\n\/* thinck to add number other address * 4 to add to the stack *\/\ndisplayStrings: @ INFO: displayStrings\n push {r1-r4,fp,lr} @ save des registres\n add fp,sp,#24 @ save param\u00e9ters address (6 registers saved * 4 bytes)\n mov r4,r0 @ save strings number\n cmp r4,#0 @ 0 string -> end\n ble 100f\n mov r0,r1 @ string 1\n bl affichageMess\n cmp r4,#1 @ number > 1\n ble 100f\n mov r0,r2\n bl affichageMess\n cmp r4,#2\n ble 100f\n mov r0,r3\n bl affichageMess\n cmp r4,#3\n ble 100f\n mov r3,#3\n sub r2,r4,#4\n1: @ loop extract address string on stack\n ldr r0,[fp,r2,lsl #2]\n bl affichageMess\n subs r2,#1\n bge 1b\n100:\n pop {r1-r4,fp,pc}\n\/******************************************************************\/\n\/* Conversion Float *\/ \n\/******************************************************************\/\n\/* s0 contains Float *\/\n\/* r0 contains address conversion area mini 20 charact\u00e8rs*\/\n\/* r0 return result length *\/\n\/* see https:\/\/blog.benoitblanchon.fr\/lightweight-float-to-string\/ *\/\nconvertirFloat:\n push {r1-r7,lr}\n vpush {s0-s2}\n mov r6,r0 @ save area address\n vmov r0,s0\n mov r1,#0\n vmov s1,r1\n movs r7,#0 @ result length\n movs r3,#'+'\n strb r3,[r6] @ sign + forcing\n mov r2,r0\n lsls r2,#1 @ extraction bit 31\n bcc 1f @ positive\u00a0?\n lsrs r0,r2,#1 @ raz sign if negative\n movs r3,#'-' @ sign -\n strb r3,[r6]\n1:\n adds r7,#1 @ next position\n cmp r0,#0 @ case of positive or negative 0\n bne 2f\n movs r3,#'0'\n strb r3,[r6,r7] @ store character 0\n adds r7,#1 @ next position\n movs r3,#0\n strb r3,[r6,r7] @ store 0 final\n mov r0,r7 @ return length\n b 100f @ and end\n2: \n ldr r2,iMaskExposant\n mov r1,r0\n ands r1,r2 @ exposant = 255\u00a0?\n cmp r1,r2\n bne 4f\n lsls r0,#10 @ bit 22 \u00e0 0\u00a0?\n bcc 3f @ yes\n movs r2,#'N' @ case of Nan. store byte, if not possible store int \n strb r2,[r6] @ area no aligned\n movs r2,#'a'\n strb r2,[r6,#1] \n movs r2,#'n'\n strb r2,[r6,#2] \n movs r2,#0 @ 0 final\n strb r2,[r6,#3] \n movs r0,#3 @ return length 3\n b 100f\n3: @ case infini positive or n\u00e9gative\n movs r2,#'I'\n strb r2,[r6,r7] \n adds r7,#1\n movs r2,#'n'\n strb r2,[r6,r7] \n adds r7,#1\n movs r2,#'f'\n strb r2,[r6,r7] \n adds r7,#1\n movs r2,#0\n strb r2,[r6,r7]\n mov r0,r7\n b 100f\n4:\n bl normaliserFloat\n mov r5,r0 @ save exposant\n VCVT.U32.f32 s2,s0 @ integer value of integer part\n vmov r0,s2 @ integer part\n VCVT.F32.U32 s1,s2 @ conversion float\n vsub.f32 s1,s0,s1 @ extraction fract part\n vldr s2,iConst1\n vmul.f32 s1,s2,s1 @ to crop it in full\n\n VCVT.U32.f32 s1,s1 @ integer conversion\n vmov r4,s1 @ fract value\n @ integer conversion in r0\n mov r2,r6 @ save address area begin \n adds r6,r7\n mov r1,r6\n bl conversion10\n add r6,r0\n movs r3,#','\n strb r3,[r6]\n adds r6,#1\n \n mov r0,r4 @ conversion fractional part\n mov r1,r6\n bl conversion10SP @ sp\u00e9cial routine with conservation begin 0 \n add r6,r0\n subs r6,#1\n @ remove trailing zeros\n5:\n ldrb r0,[r6]\n cmp r0,#'0'\n bne 6f\n subs r6,#1\n b 5b\n6:\n cmp r0,#','\n bne 7f\n subs r6,#1\n7:\n adds r6,#1\n movs r3,#'E'\n strb r3,[r6]\n adds r6,#1\n mov r0,r5 @ conversion exposant\n mov r3,r0\n lsls r3,#1\n bcc 4f\n rsbs r0,r0,#0\n movs r3,#'-'\n strb r3,[r6]\n adds r6,#1\n4:\n mov r1,r6\n bl conversion10\n add r6,r0\n \n movs r3,#0\n strb r3,[r6]\n adds r6,#1\n mov r0,r6\n subs r0,r2 @ return length result\n subs r0,#1 @ - 0 final\n\n100:\n vpop {s0-s2}\n pop {r1-r7,pc}\niMaskExposant: .int 0xFF<<23\niConst1: .float 0f1E9\n\n\/***************************************************\/\n\/* normaliser float *\/\n\/***************************************************\/\n\/* r0 contain float value (always positive value and <> Nan) *\/\n\/* s0 return new value *\/\n\/* r0 return exposant *\/\nnormaliserFloat:\n push {lr} @ save registre\n vmov s0,r0 @ value float\n movs r0,#0 @ exposant\n vldr s1,iConstE7 @ no normalisation for value < 1E7\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n blo 10f @ if s0 < iConstE7\n \n vldr s1,iConstE32\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n blo 1f\n vldr s1,iConstE32\n vdiv.f32 s0,s0,s1\n adds r0,#32\n1:\n vldr s1,iConstE16\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n blo 2f\n vldr s1,iConstE16\n vdiv.f32 s0,s0,s1\n adds r0,#16\n2:\n vldr s1,iConstE8\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n blo 3f\n vldr s1,iConstE8\n vdiv.f32 s0,s0,s1\n adds r0,#8\n3:\n vldr s1,iConstE4\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n blo 4f\n vldr s1,iConstE4\n vdiv.f32 s0,s0,s1\n adds r0,#4\n4:\n vldr s1,iConstE2\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n blo 5f\n vldr s1,iConstE2\n vdiv.f32 s0,s0,s1\n adds r0,#2\n5:\n vldr s1,iConstE1\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n blo 10f\n vldr s1,iConstE1\n vdiv.f32 s0,s0,s1\n adds r0,#1\n\n10:\n vldr s1,iConstME5 @ pas de normalisation pour les valeurs > 1E-5\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n bhi 100f\n vldr s1,iConstME31\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n bhi 11f\n vldr s1,iConstE32\n\n vmul.f32 s0,s0,s1\n subs r0,#32\n11:\n vldr s1,iConstME15\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n bhi 12f\n vldr s1,iConstE16\n vmul.f32 s0,s0,s1\n subs r0,#16\n12:\n vldr s1,iConstME7\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n bhi 13f\n vldr s1,iConstE8\n vmul.f32 s0,s0,s1\n subs r0,#8\n13:\n vldr s1,iConstME3\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n bhi 14f\n vldr s1,iConstE4\n vmul.f32 s0,s0,s1\n subs r0,#4\n14:\n vldr s1,iConstME1\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n bhi 15f\n vldr s1,iConstE2\n vmul.f32 s0,s0,s1\n subs r0,#2\n15:\n vldr s1,iConstE0\n vcmp.f32 s0,s1\n vmrs APSR_nzcv,FPSCR\n bhi 100f\n vldr s1,iConstE1\n vmul.f32 s0,s0,s1\n subs r0,#1\n\n100: @ fin standard de la fonction\n pop {pc} @ restaur des registres\n.align 2\niConstE7: .float 0f1E7\niConstE32: .float 0f1E32\niConstE16: .float 0f1E16\niConstE8: .float 0f1E8\niConstE4: .float 0f1E4\niConstE2: .float 0f1E2\niConstE1: .float 0f1E1\niConstME5: .float 0f1E-5\niConstME31: .float 0f1E-31\niConstME15: .float 0f1E-15\niConstME7: .float 0f1E-7\niConstME3: .float 0f1E-3\niConstME1: .float 0f1E-1\niConstE0: .float 0f1E0 \n\/******************************************************************\/\n\/* D\u00e9cimal Conversion *\/ \n\/******************************************************************\/\n\/* r0 contain value et r1 address conversion area *\/\nconversion10SP:\n push {r1-r6,lr} @ save registers\n mov r5,r1\n mov r4,#8\n mov r2,r0\n mov r1,#10 @ conversion decimale\n1: @ begin loop\n mov r0,r2 @ copy number or quotients\n bl division @ r0 dividende r1 divisor r2 quotient r3 remainder\n add r3,#48 @ compute digit \n strb r3,[r5,r4] @ store byte area address (r5) + offset (r4)\n subs r4,r4,#1 @ position pr\u00e9cedente\n bge 1b @ and loop if not < zero\n mov r0,#8\n mov r3,#0\n strb r3,[r5,r0] @ store 0 final\n100: \n pop {r1-r6,pc} @ restaur registers \n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n\/* for this file see task include a file in language ARM assembly *\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.","id":747} {"lang_cluster":"ARM_Assembly","source_code":"\n\/ * linux GAS *\/\n\n.global _start\n\n.data\n\nFizz: .ascii \"Fizz\\n\"\nBuzz: .ascii \"Buzz\\n\"\nFizzAndBuzz: .ascii \"FizzBuzz\\n\"\n\nnumstr_buffer: .skip 3\nnewLine: .ascii \"\\n\"\n\n.text\n\n_start:\n\n bl FizzBuzz\n\n mov r7, #1\n mov r0, #0\n svc #0\n\nFizzBuzz:\n\n push {lr}\n mov r9, #100\n\n fizzbuzz_loop:\n\n mov r0, r9\n mov r1, #15\n bl divide\n cmp r1, #0\n ldreq r1, =FizzAndBuzz\n moveq r2, #9\n beq fizzbuzz_print\n\n mov r0, r9\n mov r1, #3\n bl divide\n cmp r1, #0\n ldreq r1, =Fizz\n moveq r2, #5\n beq fizzbuzz_print\n\n mov r0, r9\n mov r1, #5\n bl divide\n cmp r1, #0\n ldreq r1, =Buzz\n moveq r2, #5\n beq fizzbuzz_print\n\n mov r0, r9\n bl make_num\n mov r2, r1\n mov r1, r0\n\n fizzbuzz_print:\n\n mov r0, #1\n mov r7, #4\n svc #0\n\n sub r9, #1\n cmp r9, #0\n\n bgt fizzbuzz_loop\n\n pop {lr}\n mov pc, lr\n\nmake_num:\n\n push {lr}\n ldr r4, =numstr_buffer\n mov r5, #4\n mov r6, #1\n\n mov r1, #100\n bl divide\n\n cmp r0, #0\n subeq r5, #1\n movne r6, #0\n\n add r0, #48\n strb r0, [r4, #0]\n\n mov r0, r1\n mov r1, #10\n bl divide\n\n cmp r0, #0\n movne r6, #0\n cmp r6, #1\n subeq r5, #1\n\n add r0, #48\n strb r0, [r4, #1]\n\n add r1, #48\n strb r1, [r4, #2]\n\n mov r2, #4\n sub r0, r2, r5\n add r0, r4, r0\n mov r1, r5\n\n pop {lr}\n mov pc, lr\n\ndivide:\n udiv r2, r0, r1\n mul r3, r1, r2\n sub r1, r0, r3\n mov r0, r2\n mov pc, lr\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":748} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI *\/\n\/* program sumandproduct.s *\/\n\n \/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessSum: .asciz \"Sum = \"\nszMessProd: .asciz \"Product = \"\nszMessStart: .asciz \"Program 32 bits start.\\n\"\nszCarriageReturn: .asciz \"\\n\"\nszMessErreur: .asciz \"Overflow\u00a0! \\n\"\n\ntabArray: .int 2, 11, 19, 90, 55,1000\n.equ TABARRAYSIZE, (. - tabArray) \/ 4\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\nsZoneConv: .skip 24\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdrszMessStart\n bl affichageMess\n ldr r2,iAdrtabArray\n mov r1,#0 @ indice\n mov r0,#0 @ sum init \n1:\n ldr r3,[r2,r1,lsl #2]\n adds r0,r0,r3\n bcs 99f\n add r1,r1,#1\n cmp r1,#TABARRAYSIZE\n blt 1b\n \n ldr r1,iAdrsZoneConv\n bl conversion10 @ decimal conversion\n mov r3,#0\n strb r3,[r1,r0]\n mov r0,#3 @ number string to display\n ldr r1,iAdrszMessSum\n ldr r2,iAdrsZoneConv @ insert conversion in message\n ldr r3,iAdrszCarriageReturn\n bl displayStrings @ display message\n \n ldr r2,iAdrtabArray\n mov r1,#0 @ indice\n mov r0,#1 @ product init \n2:\n ldr r3,[r2,r1,lsl #2]\n umull r0,r4,r3,r0\n cmp r4,#0\n bne 99f\n add r1,r1,#1\n cmp r1,#TABARRAYSIZE\n blt 2b\n \n ldr r1,iAdrsZoneConv\n bl conversion10 @ decimal conversion\n mov r3,#0\n strb r3,[r1,r0]\n mov r0,#3 @ number string to display\n ldr r1,iAdrszMessProd\n ldr r2,iAdrsZoneConv @ insert conversion in message\n ldr r3,iAdrszCarriageReturn\n bl displayStrings @ display message\n b 100f\n99:\n ldr r0,iAdrszMessErreur\n bl affichageMess\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsZoneConv: .int sZoneConv\niAdrszMessSum: .int szMessSum\niAdrszMessProd: .int szMessProd\niAdrszMessErreur: .int szMessErreur\niAdrszMessStart: .int szMessStart\niAdrtabArray: .int tabArray\n\n\/***************************************************\/\n\/* display multi strings *\/\n\/***************************************************\/\n\/* r0 contains number strings address *\/\n\/* r1 address string1 *\/\n\/* r2 address string2 *\/\n\/* r3 address string3 *\/\n\/* other address on the stack *\/\n\/* thinck to add number other address * 4 to add to the stack *\/\ndisplayStrings: @ INFO: displayStrings\n push {r1-r4,fp,lr} @ save des registres\n add fp,sp,#24 @ save param\u00e9ters address (6 registers saved * 4 bytes)\n mov r4,r0 @ save strings number\n cmp r4,#0 @ 0 string -> end\n ble 100f\n mov r0,r1 @ string 1\n bl affichageMess\n cmp r4,#1 @ number > 1\n ble 100f\n mov r0,r2\n bl affichageMess\n cmp r4,#2\n ble 100f\n mov r0,r3\n bl affichageMess\n cmp r4,#3\n ble 100f\n mov r3,#3\n sub r2,r4,#4\n1: @ loop extract address string on stack\n ldr r0,[fp,r2,lsl #2]\n bl affichageMess\n subs r2,#1\n bge 1b\n100:\n pop {r1-r4,fp,pc}\n\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":749} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program copystr.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/* Initialized data *\/\n.data\nszString: .asciz \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\\n\"\n\n\/* UnInitialized data *\/\n.bss \n.align 4\niPtString: .skip 4\nszString1: .skip 80\n\n\/* code section *\/\n.text\n.global main \nmain: \/* entry of program *\/\n push {fp,lr} \/* saves 2 registers *\/\n\n @ display start string \n ldr r0,iAdrszString\n bl affichageMess\n @ copy pointer string\n ldr r0,iAdrszString\n ldr r1,iAdriPtString\n str r0,[r1]\n @ control\n ldr r1,iAdriPtString\n ldr r0,[r1]\n bl affichageMess\n @ copy string\n ldr r0,iAdrszString \n ldr r1,iAdrszString1\n1:\n ldrb r2,[r0],#1 @ read one byte and increment pointer one byte\n strb r2,[r1],#1 @ store one byte and increment pointer one byte\n cmp r2,#0 @ end of string\u00a0?\n bne 1b @ no -> loop \n @ control\n ldr r0,iAdrszString1\n bl affichageMess\n\n100: \/* standard end of the program *\/\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrszString:\t\t.int szString\niAdriPtString:\t\t.int iPtString\niAdrszString1:\t\t.int szString1\n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {fp,lr} \t\t\t\/* save registres *\/ \n push {r0,r1,r2,r7} \t\t\/* save others registers *\/\n mov r2,#0 \t\t\t\t\/* counter length *\/\n1: \t\/* loop length calculation *\/\n ldrb r1,[r0,r2] \t\t\t\/* read octet start position + index *\/\n cmp r1,#0 \t\t\t\/* if 0 its over *\/\n addne r2,r2,#1 \t\t\t\/* else add 1 in the length *\/\n bne 1b \t\t\t\/* and loop *\/\n \/* so here r2 contains the length of the message *\/\n mov r1,r0 \t\t\t\/* address message in r1 *\/\n mov r0,#STDOUT \t\t\/* code to write to the standard output Linux *\/\n mov r7, #WRITE \/* code call system \"write\" *\/\n swi #0 \/* call systeme *\/\n pop {r0,r1,r2,r7} \t\t\/* restaur others registers *\/\n pop {fp,lr} \t\t\t\t\/* restaur des 2 registres *\/ \n bx lr\t \t\t\t\/* return *\/\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":750} {"lang_cluster":"ARM_Assembly","source_code":"\n\n.text\n.global _start\n\t@@@\tImplementation of F(n), n in R0. n is considered unsigned.\nF:\ttst\tr0,r0\t\t@ n = 0?\n\tmoveq\tr0,#1\t\t@ In that case, the result is 1\n\tbxeq\tlr\t\t@ And we can return to the caller\n\tpush\t{r0,lr}\t\t@ Save link register and argument to stack\n\tsub\tr0,r0,#1\t@ r0 -= 1 = n-1\n\tbl\tF\t\t@ r0 = F(r0) = F(n-1)\n\tbl\tM\t\t@ r0 = M(r0) = M(F(n-1))\n\tpop\t{r1,lr}\t\t@ Restore link register and argument in r1\n\tsub\tr0,r1,r0\t@ Result is n-F(M(n-1))\n\tbx\tlr\t\t@ Return to caller.\n\n\t@@@\tImplementation of M(n), n in R0. n is considered unsigned.\nM:\ttst\tr0,r0\t\t@ n = 0?\n\tbxeq\tlr\t\t@ In that case the result is also 0; return.\n\tpush\t{r0,lr}\t\t@ Save link register and argument to stack\n\tsub\tr0,r0,#1\t@ r0 -= 1 = n-1\n\tbl\tM\t\t@ r0 = M(r0) = M(n-1)\n\tbl\tF\t\t@ r0 = M(r0) = F(M(n-1))\n\tpop\t{r1,lr}\t\t@ Restore link register and argument in r1\n\tsub\tr0,r1,r0\t@ Result is n-M(F(n-1))\n\tbx\tlr\t\t@ Return to caller\n\n\t@@@\tPrint F(0..15) and M(0..15)\n_start:\tldr\tr1,=fmsg\t@ Print values for F\n\tldr\tr4,=F\n\tbl\tprfn\n\tldr\tr1,=mmsg\t@ Print values for M\n\tldr\tr4,=M\n\tbl\tprfn\n\tmov\tr7,#1\t\t@ Exit process\n\tswi\t#0\n\t\n\t@@@\tHelper function for output: print [r1], then [r4](0..15)\n\t@@@\tThis assumes [r4] preserves r3 and r4; M and F do.\nprfn:\tpush\t{lr}\t\t@ Keep link register\n\tbl\tpstr\t\t@ Print the string\n\tmov\tr3,#0\t\t@ Start at 0\n1:\tmov\tr0,r3\t\t@ Call the function in r4 with current number\t\n\tblx\tr4\n\tadd\tr0,r0,#'0\t@ Make ASCII digit\n\tldr\tr1,=dgt\t\t@ Store in digit string\n\tstrb\tr0,[r1]\n\tldr\tr1,=dstr\t@ Print result\n\tbl\tpstr\n\tadd\tr3,r3,#1\t@ Next number\n\tcmp\tr3,#15\t\t@ Keep going up to and including 15\n\tbls\t1b\n\tldr\tr1,=nl\t\t@ Print newline afterwards\n\tbl\tpstr\n\tpop\t{pc}\t\t@ Return to address on stack\n\t@@@\tPrint length-prefixed string r1 to stdout\npstr:\tpush\t{lr}\t\t@ Keep link register\n\tmov\tr0,#1\t\t@ stdout = 1\n\tldrb\tr2,[r1],#1\t@ r2 = length prefix\n\tmov\tr7,#4\t\t@ 4 = write syscall\n\tswi\t#0\n\tpop\t{pc}\t\t@ Return to address on stack\n.data\nfmsg:\t.ascii\t\"\\3F: \"\nmmsg:\t.ascii\t\"\\3M: \"\ndstr:\t.ascii\t\"\\2\"\ndgt:\t.ascii\t\"* \"\nnl:\t.ascii \t\"\\1\\n\"\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions follow the defined rules: F(0) = 1, M(0) = 0, F(n) = n - M(F(n-1)) for n > 0, and M(n) = n - F(M(n-1)) for n > 0. The code also includes handling for ARM instruction set, which lacks specialized call and ret instructions. The program counter and stack pointer are managed manually, with r13 used as the system stack pointer and r14 storing the return address for a function. The code also includes implementation of push and pop instructions, and branch-and-link instructions for calling subroutines.","id":751} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program binsearch.s *\/\n\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nsMessResult: .ascii \"Value find at index\u00a0: \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\nszCarriageReturn: .asciz \"\\n\"\nsMessRecursif: .asciz \"Recursive search\u00a0: \\n\"\nsMessNotFound: .asciz \"Value not found. \\n\"\n\n.equ NBELEMENTS, 9\nTableNumber:\t .int 4,6,7,10,11,15,22,30,35\n\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n mov r0,#4 @ search first value\n ldr r1,iAdrTableNumber @ address number table\n mov r2,#NBELEMENTS @ number of \u00e9lements \n bl bSearch\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n\n mov r0,#11 @ search median value\n ldr r1,iAdrTableNumber\n mov r2,#NBELEMENTS\n bl bSearch\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n\n mov r0,#12 @value not found\n ldr r1,iAdrTableNumber\n mov r2,#NBELEMENTS\n bl bSearch\n cmp r0,#-1\n bne 2f\n ldr r0,iAdrsMessNotFound\n bl affichageMess \n b 3f\n2:\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n3:\n mov r0,#35 @ search last value\n ldr r1,iAdrTableNumber\n mov r2,#NBELEMENTS\n bl bSearch\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n\/****************************************\/\n\/* recursive *\/\n\/****************************************\/\n ldr r0,iAdrsMessRecursif\n bl affichageMess @ display message\n\n mov r0,#4 @ search first value\n ldr r1,iAdrTableNumber\n mov r2,#0 @ low index of elements\n mov r3,#NBELEMENTS - 1 @ high index of elements\n bl bSearchR\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n \n mov r0,#11\n ldr r1,iAdrTableNumber\n mov r2,#0\n mov r3,#NBELEMENTS - 1\n bl bSearchR\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n \n mov r0,#12\n ldr r1,iAdrTableNumber\n mov r2,#0\n mov r3,#NBELEMENTS - 1\n bl bSearchR\n cmp r0,#-1\n bne 2f\n ldr r0,iAdrsMessNotFound\n bl affichageMess \n b 3f\n2:\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n3:\n mov r0,#35\n ldr r1,iAdrTableNumber\n mov r2,#0\n mov r3,#NBELEMENTS - 1\n bl bSearchR\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdrsMessRecursif: .int sMessRecursif\niAdrsMessNotFound: .int sMessNotFound\niAdrTableNumber: .int TableNumber\n\n\/******************************************************************\/\n\/* binary search iterative *\/ \n\/******************************************************************\/\n\/* r0 contains the value to search *\/\n\/* r1 contains the adress of table *\/\n\/* r2 contains the number of elements *\/\n\/* r0 return index or -1 if not find *\/\nbSearch:\n push {r2-r5,lr} @ save registers\n mov r3,#0 @ low index\n sub r4,r2,#1 @ high index = number of elements - 1\n1:\n cmp r3,r4\n movgt r0,#-1 @not found\n bgt 100f\n add r2,r3,r4 @ compute (low + high) \/2\n lsr r2,#1\n ldr r5,[r1,r2,lsl #2] @ load value of table at index r2\n cmp r5,r0\n moveq r0,r2 @ find\u00a0!!!\n beq 100f\n addlt r3,r2,#1 @ lower -> index low = index + 1\n subgt r4,r2,#1 @ bigger -> index high = index - 1\n b 1b @ and loop\n100:\n pop {r2-r5,lr}\n bx lr @ return \n\/******************************************************************\/\n\/* binary search recursif *\/ \n\/******************************************************************\/\n\/* r0 contains the value to search *\/\n\/* r1 contains the adress of table *\/\n\/* r2 contains the low index of elements *\/\n\/* r3 contains the high index of elements *\/\n\/* r0 return index or -1 if not find *\/\nbSearchR:\n push {r2-r5,lr} @ save registers\n cmp r3,r2 @ index high < low\u00a0?\n movlt r0,#-1 @ yes -> not found\n blt 100f\n\n add r4,r2,r3 @ compute (low + high) \/2\n lsr r4,#1\n ldr r5,[r1,r4,lsl #2] @ load value of table at index r4\n cmp r5,r0\n moveq r0,r4 @ find\u00a0!!!\n beq 100f \n\n bgt 1f @ bigger\u00a0?\n add r2,r4,#1 @ no new search with low = index + 1\n bl bSearchR\n b 100f\n1: @ bigger\n sub r3,r4,#1 @ new search with high = index - 1\n bl bSearchR\n100:\n pop {r2-r5,lr}\n bx lr @ return \n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres\n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal unsigned *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\n\/* r0 return size of result (no zero final in area) *\/\n\/* area size => 11 bytes *\/\n.equ LGZONECAL, 10\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n\n1:\t @ start loop\n bl divisionpar10U @unsigned r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b\t @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n\n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n\n\/***************************************************\/\n\/* division par 10 unsigned *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10U:\n push {r2,r3,r4, lr}\n mov r4,r0 @ save value\n \/\/mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3\n \/\/movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3\n ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2\n umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0) \n mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3\n add r2,r0,r0, lsl #2 @ r2 <- r0 * 5 \n sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)\n pop {r2,r3,r4,lr}\n bx lr @ leave function \niMagicNumber: \t.int 0xCCCCCCCD\n","human_summarization":"The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It takes a sorted integer array, a starting point, an ending point, and a \"secret value\" as inputs. The algorithm can be either recursive or iterative and returns whether the number was in the array and its index if found. The code also includes variations of the binary search algorithm that return the leftmost or rightmost insertion point for the given value. It also handles potential overflow bugs.","id":752} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program commandLine.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/* Initialized data *\/\n.data\nszCarriageReturn: .asciz \"\\n\"\n\n\/* UnInitialized data *\/\n.bss \n.align 4\n\n\/* code section *\/\n.text\n.global main \nmain: @ entry of program\n push {fp,lr} @ saves registers\n add fp,sp,#8 @ fp <- start address\n ldr r4,[fp] @ number of Command line arguments\n add r5,fp,#4 @ first parameter address \n mov r2,#0 @ init loop counter\nloop:\n ldr r0,[r5,r2,lsl #2] @ string address parameter\n bl affichageMess @ display string\n ldr r0,iAdrszCarriageReturn\n bl affichageMess @ display carriage return\n add r2,#1 @ increment counter\n cmp r2,r4 @ number parameters\u00a0?\n blt loop @ loop\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n pop {fp,lr} @restaur registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\n\niAdrszCarriageReturn: .int szCarriageReturn\n\n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur 2 registres\n bx lr @ return\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c \"alpha beta\" -h \"gamma\"'. It also includes functionalities for intelligent parsing of these arguments.","id":753} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program nroot.s *\/\n\/* compile with option -mfpu=vfpv3 -mfloat-abi=hard *\/ \n\/* link with gcc. Use C function for display float *\/ \n\n\/* Constantes *\/\n.equ EXIT, 1 @ Linux syscall\n\n\/* Initialized data *\/\n.data\nszFormat1: .asciz \"\u00a0%+09.15f\\n\"\n.align 4\niNumberA: .int 1024\n\n\/* UnInitialized data *\/\n.bss \n.align 4\n\n\/* code section *\/\n.text\n.global main \nmain: @ entry of program\n push {fp,lr} @ saves registers\n\n \/* root 10ieme de 1024 *\/\n ldr r0,iAdriNumberA @ number address\n ldr r0,[r0]\n vmov s0,r0 @ \n vcvt.f64.s32 d0, s0 @conversion in float single pr\u00e9cision (32 bits)\n mov r0,#10 @ N\n bl nthRoot\n ldr r0,iAdrszFormat1 @ format\n vmov r2,r3,d0\n bl printf @ call C function\u00a0!!!\n @ Attention register dn lost\u00a0!!!\n \/* square root of 2 *\/ \n vmov.f64 d1,#2.0 @ conversion 2 in float register d1\n mov r0,#2 @ N\n bl nthRoot\n ldr r0,iAdrszFormat1 @ format\n vmov r2,r3,d0\n bl printf @ call C function\u00a0!!!\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n pop {fp,lr} @restaur registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\n\niAdrszFormat1: .int szFormat1\niAdriNumberA: .int iNumberA\n\n\/******************************************************************\/\n\/* compute nth root *\/ \n\/******************************************************************\/\n\/* r0 contains N *\/\n\/* d0 contains the value *\/\n\/* d0 return result *\/\nnthRoot:\n push {r1,r2,lr} @ save registers \n vpush {d1-d8} @ save float registers\n FMRX r1,FPSCR @ copy FPSCR into r1\n BIC r1,r1,#0x00370000 @ clears STRIDE and LEN\n FMXR FPSCR,r1 @ copy r1 back into FPSCR\n\n vmov s2,r0 @ \n vcvt.f64.s32 d6, s2 @ N conversion in float double pr\u00e9cision (64 bits)\n sub r1,r0,#1 @ N - 1\n vmov s8,r1 @ \n vcvt.f64.s32 d4, s8 @conversion in float double pr\u00e9cision (64 bits)\n vmov.f64 d2,d0 @ a = A\n vdiv.F64 d3,d0,d6 @ b = A\/n\n adr r2,dfPrec @ load pr\u00e9cision\n vldr d8,[r2] \n1: @ begin loop\n vmov.f64 d2,d3 @ a <- b\n vmul.f64 d5,d3,d4 @ (N-1)*b\n\n vmov.f64 d1,#1.0 @ constante 1 -> float\n mov r2,#0 @ loop indice\n2: @ compute pow (n-1)\n vmul.f64 d1,d1,d3 @ \n add r2,#1\n cmp r2,r1 @ n -1\u00a0?\n blt 2b @ no -> loop\n vdiv.f64 d7,d0,d1 @ A \/ b pow (n-1)\n vadd.f64 d7,d7,d5 @ + (N-1)*b\n vdiv.f64 d3,d7,d6 @ \/ N -> new b\n vsub.f64 d1,d3,d2 @ compute gap\n vabs.f64 d1,d1 @ absolute value\n vcmp.f64 d1,d8 @ compare float maj FPSCR\n fmstat @ transfert FPSCR -> APSR\n @ or use VMRS APSR_nzcv, FPSCR\n bgt 1b @ if gap > pr\u00e9cision -> loop \n vmov.f64 d0,d3 @ end return result in d0\n\n100:\n vpop {d1-d8} @ restaur float registers\n pop {r1,r2,lr} @ restaur arm registers\n bx lr\ndfPrec: .double 0f1E-10 @ pr\u00e9cision\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":754} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program game24.s *\/ \n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n.equ STDIN, 0 @ Linux input console\n.equ READ, 3 @ Linux syscall\n.equ NBDIGITS, 4 @ digits number\n.equ TOTAL, 24\n.equ BUFFERSIZE, 100\n.equ STACKSIZE, 10 @ operator and digits number items in stacks\n\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessRules: .ascii \"24 Game\\n\"\n .ascii \"The program will display four randomly-generated \\n\"\n .ascii \"single-digit numbers and will then prompt you to enter\\n\"\n .ascii \"an arithmetic expression followed by to sum \\n\"\n .ascii \"the given numbers to 24.\\n\"\n .asciz \"Exemple\u00a0: 9+8+3+4 or (7+5)+(3*4) \\n\\n\"\n\nszMessExpr: .asciz \"Enter your expression (or type (q)uit to exit or (n) for other digits): \\n\"\n\/\/szMessErrChoise: .asciz \"invalid choice.\\n \"\nszMessDigits: .asciz \"The four digits are @ @ @ @ and the score is 24. \\n\"\nszMessNoDigit: .asciz \"Error\u00a0: One digit is not in digits list\u00a0!! \\n\"\nszMessSameDigit: .asciz \"Error\u00a0: Two digits are same\u00a0!! \\n\"\nszMessOK: .asciz \"It is OK. \\n\"\nszMessNotOK: .asciz \"Error, it is not ok total = @ \\n\"\nszMessErrOper: .asciz \"Unknow Operator (+,-,$,\/,(,)) \\n\"\nszMessNoparen: .asciz \"no opening parenthesis\u00a0!! \\n\"\nszMessErrParen: .asciz \"Error parenthesis number\u00a0!! \\n\"\nszMessNoalldigits: .asciz \"One or more digits not used\u00a0!!\\n\"\nszMessNewGame: .asciz \"New game (y\/n)\u00a0? \\n\"\nszCarriageReturn: .asciz \"\\n\"\n.align 4\niGraine: .int 123456\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\nsZoneConv: .skip 24\nsBuffer: .skip BUFFERSIZE\niTabDigit: .skip 4 * NBDIGITS\niTabTopDigit: .skip 4 * NBDIGITS\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n \n ldr r0,iAdrszMessRules @ display rules\n bl affichageMess\n1:\n mov r3,#0\n ldr r12,iAdriTabDigit\n ldr r11,iAdriTabTopDigit\n ldr r5,iAdrszMessDigits\n2: @ loop generate random digits \n mov r0,#8\n bl genereraleas \n add r0,r0,#1\n str r0,[r12,r3,lsl #2] @ store in table\n mov r1,#0\n str r1,[r11,r3,lsl #2] @ raz top table\n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n mov r2,#0\n strb r2,[r1,r0] @ reduce size display area with z\u00e9ro final\n mov r0,r5\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n mov r5,r0\n add r3,r3,#1\n cmp r3,#NBDIGITS @ end\u00a0?\n blt 2b @ no -> loop\n mov r0,r5\n bl affichageMess\n3: @ loop human entry\n ldr r0,iAdrszMessExpr\n bl affichageMess\n bl saisie @ entry\n cmp r0,#'q'\n beq 100f\n cmp r0,#'Q'\n beq 100f\n cmp r0,#'n'\n beq 1b\n cmp r0,#'N'\n beq 1b\n \n bl evalExpr @ expression evaluation\n cmp r0,#0 @ ok ?\n bne 3b @ no - > loop\n\n10: @ display new game ?\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n ldr r0,iAdrszMessNewGame\n bl affichageMess\n bl saisie\n cmp r0,#'y'\n beq 1b\n cmp r0,#'Y'\n beq 1b\n \n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessRules: .int szMessRules\niAdrszMessDigits: .int szMessDigits\niAdrszMessExpr: .int szMessExpr\niAdrszMessNewGame: .int szMessNewGame\niAdrsZoneConv: .int sZoneConv\niAdriTabDigit: .int iTabDigit\niAdriTabTopDigit: .int iTabTopDigit\n\/******************************************************************\/\n\/* evaluation expression *\/ \n\/******************************************************************\/\n\/* r0 return 0 if ok -1 else *\/\nevalExpr:\n push {r1-r11,lr} @ save registers\n \n mov r0,#0\n ldr r1,iAdriTabTopDigit\n mov r2,#0\n1: @ loop init table top digits\n str r0,[r1,r2,lsl #2]\n add r2,r2,#1\n cmp r2,#NBDIGITS\n blt 1b\n \n sub sp,sp,#STACKSIZE * 4 @ stack operator\n mov fp,sp\n sub sp,sp,#STACKSIZE * 4 @ stack digit\n mov r1,sp\n ldr r10,iAdrsBuffer\n mov r8,#0 @ indice character in buffer\n mov r7,#0 @ indice digits stack\n mov r2,#0 @ indice operator stack\n1: @ begin loop\n ldrb r9,[r10,r8]\n cmp r9,#0xA @ end expression ?\n beq 90f\n cmp r9,#' ' @ space \u00a0?\n addeq r8,r8,#1 @ loop\n beq 1b\n cmp r9,#'(' @ left parenthesis -> store in operator stack\n streq r9,[fp,r2,lsl #2]\n addeq r2,r2,#1\n addeq r8,r8,#1 @ and loop\n beq 1b\n cmp r9,#')' @ right parenthesis\u00a0?\n bne 3f\n mov r0,fp @ compute operator stack until left parenthesis\n sub r2,r2,#1\n2:\n ldr r6,[fp,r2,lsl #2]\n cmp r6,#'(' @ left parenthesis\n addeq r8,r8,#1 @ end ?\n beq 1b @ and loop\n sub r7,r7,#1 @ last digit\n mov r3,r7\n bl compute\n sub r2,r2,#1\n cmp r2,#0\n bge 2b\n ldr r0,iAdrszMessNoparen @ no left parenthesis in stack\n bl affichageMess\n mov r0,#-1\n b 100f\n3:\n cmp r9,#'+' @ addition\n beq 4f\n cmp r9,#'-' @ soustraction\n beq 4f\n cmp r9,#'*' @ multiplication\n beq 4f\n cmp r9,#'\/' @ division\n beq 4f\n\n b 5f @ not operator\n\n4: @ control priority and depile stacks\n mov r0,fp\n mov r3,r7\n mov r4,r9\n bl depileOper\n mov r7,r3\n add r8,r8,#1\n b 1b @ and loop \n \n5: @ digit\n sub r9,r9,#0x30\n mov r0,r9\n bl digitControl\n cmp r0,#0 @ error ?\n bne 100f\n str r9,[r1,r7,lsl #2] @ store digit in digits stack\n add r7,r7,#1\n\n add r8,r8,#1\n beq 1b \n\n b 100f\n90: @ compute all stack operators\n mov r0,fp\n sub r7,r7,#1\n91:\n subs r2,r2,#1\n blt 92f\n mov r3,r7\n bl compute\n sub r7,r7,#1\n b 91b\n92: \n ldr r0,[r1] @ total = first value on digits stack\n cmp r0,#TOTAL @ control total \n beq 93f @ ok \n ldr r1,iAdrsZoneConv\n bl conversion10 @ call decimal conversion\n mov r2,#0\n strb r2,[r1,r0]\n ldr r0,iAdrszMessNotOK\n ldr r1,iAdrsZoneConv @ insert conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n mov r0,#-1\n b 100f\n93: @ control use all digits\n ldr r1,iAdriTabTopDigit\n mov r2,#0\n94: @ begin loop\n ldr r0,[r1,r2,lsl #2] @ load top\n cmp r0,#0 \n bne 95f\n ldr r0,iAdrszMessNoalldigits\n bl affichageMess\n mov r0,#-1\n b 100f\n95:\n add r2,r2,#1\n cmp r2,#NBDIGITS\n blt 94b\n96: @ display message OK\n ldr r0,iAdrszMessOK\n bl affichageMess\n mov r0,#0\n b 100f\n \n100:\n add sp,sp,#80 @ stack algnement\n pop {r1-r11,lr}\n bx lr @ return \niAdrszMessNoparen: .int szMessNoparen\niAdrszMessNotOK: .int szMessNotOK\niAdrszMessOK: .int szMessOK\niAdrszMessNoalldigits: .int szMessNoalldigits\n\/******************************************************************\/\n\/* depile operator *\/ \n\/******************************************************************\/\n\/* r0 operator stack address *\/\n\/* r1 digits stack address *\/\n\/* r2 operator indice *\/\n\/* r3 digits indice *\/\n\/* r4 operator *\/\n\/* r2 return a new operator indice *\/\n\/* r3 return a new digits indice *\/\ndepileOper:\n push {r4-r8,lr} @ save registers\n cmp r2,#0 @ first operator ?\n beq 60f\n sub r5,r2,#1\n1:\n ldr r6,[r0,r5,lsl #2] @ load stack operator\n cmp r6,r4 @ same operators\n beq 50f\n cmp r6,#'*' @ multiplication\n beq 50f\n cmp r6,#'\/' @ division\n beq 50f\n cmp r6,#'-' @ soustraction\n beq 50f\n \n b 60f\n50: @ depile operators stack and compute\n sub r2,r2,#1\n sub r3,r3,#1\n bl compute\n sub r5,r5,#1\n cmp r5,#0\n bge 1b\n60:\n str r4,[r0,r2,lsl #2] @ add operator in stack\n add r2,r2,#1\n \n100:\n pop {r4-r8,lr}\n bx lr @ return \n\/******************************************************************\/\n\/* compute *\/ \n\/******************************************************************\/\n\/* r0 operator stack address *\/\n\/* r1 digits stack address *\/\n\/* r2 operator indice *\/\n\/* r3 digits indice *\/\ncompute:\n push {r1-r8,lr} @ save registers\n ldr r6,[r1,r3,lsl #2] @ load second digit\n sub r5,r3,#1\n ldr r7,[r1,r5,lsl #2] @ load first digit\n \n ldr r8,[r0,r2,lsl #2] @ load operator\n cmp r8,#'+'\n bne 1f\n add r7,r7,r6 @ addition\n str r7,[r1,r5,lsl #2] \n b 100f\n1: \n cmp r8,#'-'\n bne 2f\n sub r7,r7,r6 @ soustaction\n str r7,[r1,r5,lsl #2] \n b 100f\n2:\n cmp r8,#'*'\n bne 3f @ multiplication\n mul r7,r6,r7\n str r7,[r1,r5,lsl #2] \n b 100f\n3:\n cmp r8,#'\/'\n bne 4f\n udiv r7,r7,r6 @ division\n str r7,[r1,r5,lsl #2]\n b 100f\n4:\n cmp r8,#'(' @ left parenthesis\u00a0?\n bne 5f\n ldr r0,iAdrszMessErrParen @ error \n bl affichageMess\n mov r0,#-1\n b 100f\n5:\n ldr r0,iAdrszMessErrOper\n bl affichageMess\n mov r0,#-1\n100:\n pop {r1-r8,lr}\n bx lr @ return \niAdrszMessErrOper: .int szMessErrOper\niAdrszMessErrParen: .int szMessErrParen\n\/******************************************************************\/\n\/* control digits *\/ \n\/******************************************************************\/\n\/* r0 return 0 if OK 1 if not digit *\/\ndigitControl:\n push {r1-r4,lr} @ save registers\n ldr r1,iAdriTabTopDigit\n ldr r2,iAdriTabDigit\n mov r3,#0\n1:\n ldr r4,[r2,r3,lsl #2] @ load digit\n cmp r0,r4 @ equal ?\n beq 2f @ yes\n add r3,r3,#1 @ no -> loop\n cmp r3,#NBDIGITS @ end\u00a0?\n blt 1b\n ldr r0,iAdrszMessNoDigit @ error\n bl affichageMess\n mov r0,#1\n b 100f\n2: @ control prev use \n ldr r4,[r1,r3,lsl #2]\n cmp r4,#0\n beq 3f\n add r3,r3,#1\n cmp r3,#NBDIGITS\n blt 1b\n ldr r0,iAdrszMessSameDigit\n bl affichageMess\n mov r0,#1\n b 100f\n3:\n mov r4,#1\n str r4,[r1,r3,lsl #2]\n mov r0,#0\n100:\n pop {r1-r4,lr}\n bx lr @ return \niAdrszMessNoDigit: .int szMessNoDigit\niAdrszMessSameDigit: .int szMessSameDigit\n\/******************************************************************\/\n\/* string entry *\/ \n\/******************************************************************\/\n\/* r0 return the first character of human entry *\/\nsaisie:\n push {r1-r7,lr} @ save registers\n mov r0,#STDIN @ Linux input console\n ldr r1,iAdrsBuffer @ buffer address \n mov r2,#BUFFERSIZE @ buffer size \n mov r7,#READ @ request to read datas\n svc 0 @ call system\n ldr r1,iAdrsBuffer @ buffer address \n ldrb r0,[r1] @ load first character\n100:\n pop {r1-r7,lr}\n bx lr @ return \niAdrsBuffer: .int sBuffer\n\/***************************************************\/\n\/* Generation random number *\/\n\/***************************************************\/\n\/* r0 contains limit *\/\ngenereraleas:\n push {r1-r4,lr} @ save registers \n ldr r4,iAdriGraine\n ldr r2,[r4]\n ldr r3,iNbDep1\n mul r2,r3,r2\n ldr r3,iNbDep2\n add r2,r2,r3\n str r2,[r4] @ maj de la graine pour l appel suivant \n cmp r0,#0\n beq 100f\n add r1,r0,#1 @ divisor\n mov r0,r2 @ dividende\n bl division\n mov r0,r3 @ r\u00e9sult = remainder\n \n100: @ end function\n pop {r1-r4,lr} @ restaur registers\n bx lr @ return\n\/*****************************************************\/\niAdriGraine: .int iGraine\niNbDep1: .int 0x343FD\niNbDep2: .int 0x269EC3 \n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n\n24 Game\nThe program will display four randomly-generated\nsingle-digit numbers and will then prompt you to enter\nan arithmetic expression followed by to sum\nthe given numbers to 24.\nExemple\u00a0: 9+8+3+4 or (7+5)+(3*4)\n\nThe four digits are 5 1 1 5 and the score is 24.\nEnter your expression (or type (q)uit to exit or (n) for other digits):\nn\nThe four digits are 8 2 5 3 and the score is 24.\nEnter your expression (or type (q)uit to exit or (n) for other digits):\n(8*2)+5+3\nIt is OK.\n\nNew game (y\/n)\u00a0?\n\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":755} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program strConcat.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\/* Initialized data *\/\n.data\nszMessFinal: .asciz \"The final string is \\n\"\n\nszString: .asciz \"Hello \"\nszString1: .asciz \" the world. \\n\"\n\n\/* UnInitialized data *\/\n.bss \nszFinalString: .skip 255\n\n\/* code section *\/\n.text\n.global main \nmain:\n @ load string \n ldr r1,iAdrszString\n\tldr r2,iAdrszFinalString\n mov r4,#0\n1:\n ldrb r0,[r1,r4] @ load byte of string\n strb r0,[r2,r4]\n cmp r0,#0 @ compar with zero\u00a0?\n addne r4,#1\n bne 1b\n ldr r1,iAdrszString1\n mov r3,#0\n2:\n ldrb r0,[r1,r3] @ load byte of string 1\n strb r0,[r2,r4]\n cmp r0,#0 @ compar with zero\u00a0?\n addne r4,#1\n addne r3,#1\n bne 2b\n mov r0,r2 @ display final string\n bl affichageMess\n100: @ standard end of the program *\/\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform the system call\niAdrszString: .int szString\niAdrszString1: .int szString1\niAdrszFinalString: .int szFinalString\niAdrszMessFinal: .int szMessFinal\n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registers \n mov r2,#0 @ counter length *\/\n1: @ loop length calculation\n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over\n addne r2,r2,#1 @ else add 1 in the length\n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux\n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme\n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres\n bx lr @ return\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":756} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI *\/\n\/* program anagram.s *\/\n\n \/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n \n.equ MAXI, 40000\n.equ BUFFERSIZE, 300000\n.equ READ, 3 @ system call \n.equ OPEN, 5 @ system call\n.equ CLOSE, 6 @ system call\n.equ O_RDWR, 0x0002 @ open for reading and writing\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszFileName: .asciz \".\/listword.txt\"\nszMessErreur: .asciz \"FILE ERROR.\"\nszCarriageReturn: .asciz \"\\n\"\nszMessSpace: .asciz \" \"\n\nptBuffer1: .int sBuffer1\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\nptTabBuffer: .skip 4 * MAXI\nptTabAna: .skip 4 * MAXI\ntbiCptAna: .skip 4 * MAXI\niNBword: .skip 4\nsBuffer: .skip BUFFERSIZE\nsBuffer1: .skip BUFFERSIZE\n\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n mov r4,#0 @ loop indice\n ldr r0,iAdrszFileName @ file name\n mov r1,#O_RDWR @ flags\n mov r2,#0 @ mode\n mov r7,#OPEN @ \n svc 0 \n cmp r0,#0 @ error open\n ble 99f\n mov r8,r0 @ FD save Fd\n ldr r1,iAdrsBuffer @ buffer address\n ldr r2,iSizeBuf @ buffersize\n mov r7, #READ\n svc 0 \n cmp r0,#0 @ error read\u00a0?\n blt 99f\n mov r5,r0 @ save size read bytes\n ldr r4,iAdrsBuffer @ buffer address\n ldr r0,iAdrsBuffer @ start word address\n mov r2,#0\n mov r1,#0 @ word length\n1:\n cmp r2,r5\n bge 2f\n ldrb r3,[r4,r2]\n cmp r3,#0xD @ end word\u00a0?\n addne r1,r1,#1 @ increment word length\n addne r2,r2,#1 @ increment indice\n bne 1b @ and loop\n mov r3,#0\n strb r3,[r4,r2] @ store final zero\n bl anaWord @ sort word letters\n add r2,r2,#2 @ jump OD and 0A \n add r0,r4,r2 @ new address begin word\n mov r1,#0 @ init length\n b 1b @ and loop\n \n2:\n mov r3,#0 @ last word\n strb r3,[r4,r2]\n bl anaWord\n \n mov r0,r8 @ file Fd\n mov r7, #CLOSE\n svc 0 \n cmp r0,#0 @ error close\u00a0?\n blt 99f\n \n ldr r0,iAdrptTabAna @ address sorted string area\n mov r1,#0 @ first indice\n ldr r2,iAdriNBword\n ldr r2,[r2] @ last indice\n ldr r3,iAdrptTabBuffer @ address sorted string area\n bl triRapide @ quick sort\n ldr r4,iAdrptTabAna @ address sorted string area\n ldr r7,iAdrptTabBuffer @ address sorted string area\n ldr r10,iAdrtbiCptAna @ address counter occurences\n mov r9,r2 @ size word array\n mov r8,#0 @ indice first occurence\n ldr r3,[r4,r8,lsl #2] @ load first value\n mov r2,#1 @ loop indice\n mov r6,#0 @ counter\n mov r12,#0 @ counter value max\n3:\n ldr r5,[r4,r2,lsl #2] @ load next value\n mov r0,r3\n mov r1,r5\n bl comparStrings\n cmp r0,#0 @ sorted strings equal\u00a0?\n bne 4f\n add r6,r6,#1 @ yes increment counter\n b 5f\n4: @ no\n str r6,[r10,r8,lsl #2] @ store counter in first occurence\n cmp r6,r12 @ counter > value max\n movgt r12,r6 @ yes counter -> value max\n mov r6,#0 @ raz counter\n mov r8,r2 @ init index first occurence\n mov r3,r5 @ init value first occurence\n5:\n add r2,r2,#1 @ increment indice\n cmp r2,r9 @ end word array\u00a0?\n blt 3b @ no -> loop\n \n mov r2,#0 @ raz indice\n6: @ display loop\n ldr r6,[r10,r2,lsl #2] @ load counter\n cmp r6,r12 @ equal to max value\u00a0?\n bne 8f\n ldr r0,[r7,r2,lsl #2] @ load address first word\n bl affichageMess\n add r3,r2,#1 @ increment new indixe\n mov r4,#0 @ counter\n7:\n ldr r0,iAdrszMessSpace\n bl affichageMess\n ldr r0,[r7,r3,lsl #2] @ load address other word\n bl affichageMess\n add r3,r3,#1 @ increment indice\n add r4,r4,#1 @ increment counter\n cmp r4,r6 @ max value\u00a0?\n blt 7b @ no loop\n ldr r0,iAdrszCarriageReturn\n bl affichageMess\n8:\n add r2,r2,#1 @ increment indice\n cmp r2,r9 @ maxi\u00a0?\n blt 6b @ no -> loop\n \n b 100f\n99: @ display error\n ldr r1,iAdrszMessErreur\n bl displayError\n \n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\niAdrszCarriageReturn: .int szCarriageReturn\niAdrszFileName: .int szFileName\niAdrszMessErreur: .int szMessErreur\niAdrsBuffer: .int sBuffer\niSizeBuf: .int BUFFERSIZE\niAdrszMessSpace: .int szMessSpace\niAdrtbiCptAna: .int tbiCptAna\n\/******************************************************************\/\n\/* analizing word *\/ \n\/******************************************************************\/\n\/* r0 word address *\/\n\/* r1 word length *\/\nanaWord:\n push {r1-r6,lr}\n mov r5,r0\n mov r6,r1\n ldr r1,iAdrptTabBuffer\n ldr r2,iAdriNBword\n ldr r3,[r2]\n str r0,[r1,r3,lsl #2]\n \n ldr r1,iAdrptTabAna\n ldr r4,iAdrptBuffer1\n ldr r0,[r4]\n add r6,r6,r0\n add r6,r6,#1\n str r6,[r4]\n str r0,[r1,r3,lsl #2]\n \n add r3,r3,#1\n str r3,[r2]\n mov r1,r0\n mov r0,r5\n bl triLetters @ sort word letters\n mov r2,#0\n100:\n pop {r1-r6,pc}\niAdrptTabBuffer: .int ptTabBuffer\niAdrptTabAna: .int ptTabAna\niAdriNBword: .int iNBword\niAdrptBuffer1: .int ptBuffer1\n\/******************************************************************\/\n\/* sort word letters *\/ \n\/******************************************************************\/\n\/* r0 address begin word *\/\n\/* r1 address recept array *\/\ntriLetters:\n push {r1-r7,lr}\n mov r2,#0\n1:\n ldrb r3,[r0,r2] @ load letter\n cmp r3,#0 @ end word\u00a0?\n beq 6f\n cmp r2,#0 @ first letter\u00a0?\n bne 2f\n strb r3,[r1,r2] @ yes store in first position\n add r2,r2,#1 @ increment indice\n b 1b @ and loop\n2:\n mov r4,#0\n3: @ begin loop to search insertion position\n ldrb r5,[r1,r4] @ load letter \n cmp r3,r5 @ compare\n blt 4f @ to low -> insertion\n add r4,r4,#1 @ increment indice\n cmp r4,r2 @ compare to letters number in place\n blt 3b @ search loop\n strb r3,[r1,r2] @ else store in last position\n add r2,r2,#1\n b 1b @ and loop\n4: @ move first letters in one position \n sub r6,r2,#1 @ start indice\n5:\n ldrb r5,[r1,r6] @ load letter\n add r7,r6,#1 @ store indice - 1\n strb r5,[r1,r7] @ store letter\n sub r6,r6,#1 @ decrement indice\n cmp r6,r4 @ end\u00a0?\n bge 5b @ no loop\n strb r3,[r1,r4] @ else store letter in free position\n add r2,r2,#1\n b 1b @ and loop\n6: \n mov r3,#0 @ final z\u00e9ro\n strb r3,[r1,r2]\n100:\n pop {r1-r7,pc}\n\/***************************************************\/\n\/* Appel r\u00e9cursif Tri Rapide quicksort *\/\n\/***************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains index of first item *\/\n\/* r2 contains the number of elements > 0 *\/\n\/* r3 contains the address of table 2 *\/\ntriRapide:\n push {r2-r6,lr} @ save registers\n mov r6,r3 \n sub r2,#1 @ last item index\n cmp r1,r2 @ first > last\u00a0? \n bge 100f @ yes -> end\n mov r4,r0 @ save r0\n mov r5,r2 @ save r2\n mov r3,r6\n bl partition1 @ cutting into 2 parts\n mov r2,r0 @ index partition\n mov r0,r4 @ table address\n bl triRapide @ sort lower part\n mov r0,r4 @ table address\n add r1,r2,#1 @ index begin = index partition + 1\n add r2,r5,#1 @ number of elements\n bl triRapide @ sort higter part\n \n 100: @ end function\n pop {r2-r6,lr} @ restaur registers \n bx lr @ return\n\n\/******************************************************************\/\n\/* Partition table elements *\/ \n\/******************************************************************\/\n\/* r0 contains the address of table *\/\n\/* r1 contains index of first item *\/\n\/* r2 contains index of last item *\/\n\/* r3 contains the address of table 2 *\/\npartition1:\n push {r1-r12,lr} @ save registers\n mov r8,r0 @ save address table 2\n mov r9,r1 \n ldr r10,[r8,r2,lsl #2] @ load string address last index\n mov r4,r9 @ init with first index\n mov r5,r9 @ init with first index\n1: @ begin loop\n ldr r6,[r8,r5,lsl #2] @ load string address\n mov r0,r6\n mov r1,r10\n bl comparStrings\n cmp r0,#0\n ldrlt r7,[r8,r4,lsl #2] @ if < swap value table\n strlt r6,[r8,r4,lsl #2]\n strlt r7,[r8,r5,lsl #2]\n ldrlt r7,[r3,r4,lsl #2] @ swap array 2\n ldrlt r12,[r3,r5,lsl #2]\n strlt r7,[r3,r5,lsl #2]\n strlt r12,[r3,r4,lsl #2]\n addlt r4,#1 @ and increment index 1\n add r5,#1 @ increment index 2\n cmp r5,r2 @ end\u00a0?\n blt 1b @ no -> loop\n ldr r7,[r8,r4,lsl #2] @ swap value\n str r10,[r8,r4,lsl #2]\n str r7,[r8,r2,lsl #2]\n ldr r7,[r3,r4,lsl #2] @ swap array 2\n ldr r12,[r3,r2,lsl #2]\n str r7,[r3,r2,lsl #2]\n str r12,[r3,r4,lsl #2]\n \n mov r0,r4 @ return index partition\n100:\n pop {r1-r12,lr}\n bx lr\n\/************************************\/ \n\/* Strings case sensitive comparisons *\/\n\/************************************\/ \n\/* r0 et r1 contains the address of strings *\/\n\/* return 0 in r0 if equals *\/\n\/* return -1 if string r0 < string r1 *\/\n\/* return 1 if string r0 > string r1 *\/\ncomparStrings:\n push {r1-r4} @ save des registres\n mov r2,#0 @ counter\n1: \n ldrb r3,[r0,r2] @ byte string 1\n ldrb r4,[r1,r2] @ byte string 2\n cmp r3,r4\n movlt r0,#-1 @ small\n movgt r0,#1 @ greather \n bne 100f @ not equals\n cmp r3,#0 @ 0 end string\n moveq r0,#0 @ equals\n beq 100f @ end string\n add r2,r2,#1 @ else add 1 in counter\n b 1b @ and loop\n100:\n pop {r1-r4}\n bx lr \n\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\nbale able bela abel elba\ncater carte crate caret trace\ngalen glean angle lange angel\nregal glare alger lager large\nlena lane lean elan neal\nveil levi live vile evil\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":757} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program loopdownward.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessResult: .ascii \"Counter = \" @ message result\nsMessValeur: .fill 12, 1, ' '\n .asciz \"\\n\"\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n push {fp,lr} @ saves 2 registers \n mov r4,#10\n1: @ begin loop \n mov r0,r4\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n subs r4,#1 @ decrement counter\n bge 1b @ loop if greather\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrszMessResult: .int szMessResult\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 \t\t\t@ address message in r1 \n mov r0,#STDOUT \t\t@ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#10\n\n1:\t @ start loop\n bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\t\n strb r1,[r3,r2] @ store digit on area\n sub r2,#1 @ previous position\n cmp r0,#0 @ stop if quotient = 0 *\/\n bne 1b\t @ else loop\n @ and move spaces in first on area\n mov r1,#' ' @ space\t\n2:\t\n strb r1,[r3,r2] @ store space in area\n subs r2,#1 @ @ previous position\n bge 2b @ loop if r2 >= z\u00e9ro \n\n100:\t\n pop {r1-r4,lr} @ restaur registres \n bx lr\t @return\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save registers *\/\n mov r4,r0 \n mov r3,#0x6667 @ r3 <- magic_number lower\n movt r3,#0x6666 @ r3 <- magic_number upper\n smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) \n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":758} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program loopstep2.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ MAXI, 20\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessResult: .ascii \"Counter = \" @ message result\nsMessValeur: .fill 12, 1, ' '\n .asciz \"\\n\"\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n push {fp,lr} @ saves 2 registers \n mov r4,#0\n1: @ begin loop \n mov r0,r4\n ldr r1,iAdrsMessValeur @ display value\n bl conversion10 @ call function with 2 parameter (r0,r1)\n ldr r0,iAdrszMessResult\n bl affichageMess @ display message\n add r4,#2 @ increment counter by 2\n cmp r4,#MAXI @\n ble 1b @ loop\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n\niAdrsMessValeur: .int sMessValeur\niAdrszMessResult: .int szMessResult\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 \t\t\t@ address message in r1 \n mov r0,#STDOUT \t\t@ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to a decimal *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\nconversion10:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#10\n\n1:\t @ start loop\n bl divisionpar10 @ r0 <- dividende. quotient ->r0 reste -> r1\n add r1,#48 @ digit\t\n strb r1,[r3,r2] @ store digit on area\n sub r2,#1 @ previous position\n cmp r0,#0 @ stop if quotient = 0 *\/\n bne 1b\t @ else loop\n @ and move spaces in first on area\n mov r1,#' ' @ space\t\n2:\t\n strb r1,[r3,r2] @ store space in area\n subs r2,#1 @ @ previous position\n bge 2b @ loop if r2 >= z\u00e9ro \n\n100:\t\n pop {r1-r4,lr} @ restaur registres \n bx lr\t @return\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 dividende *\/\n\/* r0 quotient *\/\t\n\/* r1 remainder *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save registers *\/\n mov r4,r0 \n mov r3,#0x6667 @ r3 <- magic_number lower\n movt r3,#0x6666 @ r3 <- magic_number upper\n smull r1, r2, r3, r0 @ r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) \n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n\/***************************************************\/\n\/* integer division unsigned *\/\n\/***************************************************\/\ndivision:\n \/* r0 contains dividend *\/\n \/* r1 contains divisor *\/\n \/* r2 returns quotient *\/\n \/* r3 returns remainder *\/\n push {r4, lr}\n mov r2, #0 @ init quotient\n mov r3, #0 @ init remainder\n mov r4, #32 @ init counter bits\n b 2f\n1: @ loop \n movs r0, r0, LSL #1 @ r0 <- r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1)\n adc r3, r3, r3 @ r3 <- r3 + r3 + C. This is equivalent to r3\u00a0? (r3 << 1) + C \n cmp r3, r1 @ compute r3 - r1 and update cpsr \n subhs r3, r3, r1 @ if r3 >= r1 (C=1) then r3\u00a0? r3 - r1 \n adc r2, r2, r2 @ r2 <- r2 + r2 + C. This is equivalent to r2 <- (r2 << 1) + C \n2:\n subs r4, r4, #1 @ r4 <- r4 - 1 \n bpl 1b @ if r4 >= 0 (N=0) then loop\n pop {r4, lr}\n bx lr\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":759} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program jensen.s *\/\n\/* compil as with option -mcpu= -mfpu=vfpv4 -mfloat-abi=hard *\/\n\/* link with gcc *\/\n\n\/* Constantes *\/\n.equ EXIT, 1 @ Linux syscall\n\/* Initialized data *\/\n.data\n\nszFormat: .asciz \"Result =\u00a0%.8f \\n\" \n.align 4\n\n\/* UnInitialized data *\/\n.bss \n\n\/* code section *\/\n.text\n.global main \nmain: \n mov r0,#1 @ first indice\n mov r1,#100 @ last indice\n adr r2,funcdiv @ address function\n bl funcSum\n vcvt.f64.f32 d1, s0 @ conversion double float for print by C\n ldr r0,iAdrszFormat @ display format\n vmov r2,r3,d1 @ parameter function printf for float double\n bl printf @ display float double\n\n100: @ standard end of the program\n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc 0 @ perform system call\n\niAdrszFormat: .int szFormat\n\/******************************************************************\/\n\/* function sum *\/ \n\/******************************************************************\/\n\/* r0 contains begin *\/\n\/* r1 contains end *\/\n\/* r2 contains address function *\/\n\n\/* r0 return result *\/\nfuncSum:\n push {r0,r3,lr} @ save registers \n mov r3,r0\n mov r0,#0 @ init r0\n vmov s3,r0 @ and s3\n vcvt.f32.s32 s3, s3 @ convert in float single pr\u00e9cision (32bits)\n1: @ begin loop\n mov r0,r3 @ loop indice -> parameter function\n blx r2 @ call function address in r2\n vadd.f32 s3,s0 @ addition float\n add r3,#1 @ increment indice\n cmp r3,r1 @ end\u00a0?\n ble 1b @ no loop\n vmov s0,s3 @ return float result in s0\n\n100:\n pop {r0,r3,lr} @ restaur registers\n bx lr @ return\n\/******************************************************************\/\n\/* compute 1\/r0 *\/ \n\/******************************************************************\/\n\/* r0 contains the value *\/\n\/* r0 return result *\/\nfuncdiv:\n push {r1,lr} @ save registers \n vpush {s1} @ save float registers\n cmp r0,#0 @ division by zero -> end\n beq 100f\n ldr r1,fUn @ load float constant 1.0\n vmov s0,r1 @ in float register s3\n vmov s1,r0 @ \n vcvt.f32.s32 s1, s1 @conversion in float single pr\u00e9cision (32 bits)\n vdiv.f32 s0,s0,s1 @ division 1\/r0\n @ and return result in s0\n100:\n vpop {s1} @ restaur float registers\n pop {r1,lr} @ restaur registers\n bx lr @ return\nfUn: .float 1\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":760} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program orderlist.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessResult1: .asciz \"List1 < List2 \\n\" @ message result\nszMessResult2: .asciz \"List1 => List2 \\n\" @ message result\nszCarriageReturn: .asciz \"\\n\"\n\niTabList1: .int 1,2,3,4,5\n.equ NBELEMENTS1, (. - iTabList1) \/4\niTabList2: .int 1,2,1,5,2,2\n.equ NBELEMENTS2, (. - iTabList2) \/4\niTabList3: .int 1,2,3,4,5\n.equ NBELEMENTS3, (. - iTabList3) \/4\niTabList4: .int 1,2,3,4,5,6\n.equ NBELEMENTS4, (. - iTabList4) \/4\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdriTabList1\n mov r1,#NBELEMENTS1\n ldr r2,iAdriTabList2\n mov r3,#NBELEMENTS2\n bl listeOrder\n cmp r0,#0 @ false\u00a0?\n beq 1f @ yes\n ldr r0,iAdrszMessResult1 @ list 1 < list 2\n bl affichageMess @ display message\n b 2f\n1:\n ldr r0,iAdrszMessResult2\n bl affichageMess @ display message\n\n2:\n ldr r0,iAdriTabList1\n mov r1,#NBELEMENTS1\n ldr r2,iAdriTabList3\n mov r3,#NBELEMENTS3\n bl listeOrder\n cmp r0,#0 @ false\u00a0?\n beq 3f @ yes\n ldr r0,iAdrszMessResult1 @ list 1 < list 2\n bl affichageMess @ display message\n b 4f\n3:\n ldr r0,iAdrszMessResult2\n bl affichageMess @ display message\n4:\n ldr r0,iAdriTabList1\n mov r1,#NBELEMENTS1\n ldr r2,iAdriTabList4\n mov r3,#NBELEMENTS4\n bl listeOrder\n cmp r0,#0 @ false\u00a0?\n beq 5f @ yes\n ldr r0,iAdrszMessResult1 @ list 1 < list 2\n bl affichageMess @ display message\n b 6f\n5:\n ldr r0,iAdrszMessResult2\n bl affichageMess @ display message\n6:\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\niAdriTabList1: .int iTabList1\niAdriTabList2: .int iTabList2\niAdriTabList3: .int iTabList3\niAdriTabList4: .int iTabList4\niAdrszMessResult1: .int szMessResult1\niAdrszMessResult2: .int szMessResult2\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of list 1 *\/\n\/* r1 contains list 1 size *\/\n\/* r2 contains the address of list 2 *\/\n\/* r3 contains list 2 size *\/\n\/* r0 returns 1 if list1 < list2 *\/\n\/* r0 returns 0 else *\/\nlisteOrder:\n push {r1-r7,lr} @ save registres\n cmp r1,#0 @ list 1 size = zero\u00a0?\n moveq r0,#-1 @ yes -> error\n beq 100f\n cmp r3,#0 @ list 2 size = zero\u00a0?\n moveq r0,#-2 @ yes -> error\n beq 100f\n mov r4,#0 @ index list 1\n mov r5,#0 @ index list 2\n1:\n ldr r6,[r0,r4,lsl #2] @ load list 1 element\n ldr r7,[r2,r5,lsl #2] @ load list 2 element\n cmp r6,r7 @ compar\n movgt r0,#0 @ list 1 > list 2\u00a0?\n bgt 100f\n beq 2f @ list 1 = list 2\n add r4,#1 @ increment index 1\n cmp r4,r1 @ end list\u00a0?\n movge r0,#1 @ yes -> ok list 1 < list 2\n bge 100f\n b 1b @ else loop\n2:\n add r4,#1 @ increment index 1\n cmp r4,r1 @ end list\u00a0?\n bge 3f @ yes -> verif size\n add r5,#1 @ else increment index 2\n cmp r5,r3 @ end list 2\u00a0?\n movge r0,#0 @ yes -> list 2 < list 1\n bge 100f\n b 1b @ else loop\n3:\n cmp r1,r3 @ compar size\n movge r0,#0 @ list 2 < list 1\n movlt r0,#1 @ list 1 < list 2\n100:\n pop {r1-r7,lr} @ restaur registers\n bx lr @ return \n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur registers *\/ \n bx lr @ return\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise.\"","id":761} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI or android 32 bits *\/\n\/* program ackermann.s *\/ \n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n.equ MMAXI, 4\n.equ NMAXI, 10\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nsMessResult: .asciz \"Result for @ @ \u00a0: @ \\n\"\nszMessError: .asciz \"Overflow\u00a0!!.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n \n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\nsZoneConv: .skip 24\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n mov r3,#0\n mov r4,#0\n1:\n mov r0,r3\n mov r1,r4\n bl ackermann\n mov r5,r0\n mov r0,r3\n ldr r1,iAdrsZoneConv @ else display odd message\n bl conversion10 @ call decimal conversion\n ldr r0,iAdrsMessResult\n ldr r1,iAdrsZoneConv @ insert value conversion in message\n bl strInsertAtCharInc\n mov r6,r0\n mov r0,r4\n ldr r1,iAdrsZoneConv @ else display odd message\n bl conversion10 @ call decimal conversion\n mov r0,r6\n ldr r1,iAdrsZoneConv @ insert value conversion in message\n bl strInsertAtCharInc\n mov r6,r0\n mov r0,r5\n ldr r1,iAdrsZoneConv @ else display odd message\n bl conversion10 @ call decimal conversion\n mov r0,r6\n ldr r1,iAdrsZoneConv @ insert value conversion in message\n bl strInsertAtCharInc\n bl affichageMess\n add r4,#1\n cmp r4,#NMAXI\n blt 1b\n mov r4,#0\n add r3,#1\n cmp r3,#MMAXI\n blt 1b\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\niAdrsZoneConv: .int sZoneConv\n\/***************************************************\/\n\/* fonction ackermann *\/\n\/***************************************************\/\n\/\/ r0 contains a number m\n\/\/ r1 contains a number n\n\/\/ r0 return r\u00e9sult\nackermann:\n push {r1-r2,lr} @ save registers \n cmp r0,#0\n beq 5f\n movlt r0,#-1 @ error\n blt 100f\n cmp r1,#0\n movlt r0,#-1 @ error\n blt 100f\n bgt 1f\n sub r0,r0,#1\n mov r1,#1\n bl ackermann\n b 100f\n1:\n mov r2,r0\n sub r1,r1,#1\n bl ackermann\n mov r1,r0\n sub r0,r2,#1\n bl ackermann\n b 100f\n5:\n adds r0,r1,#1\n bcc 100f\n ldr r0,iAdrszMessError\n bl affichageMess\n bkpt\n100:\n pop {r1-r2,lr} @ restaur registers\n bx lr @ return\niAdrszMessError: .int szMessError\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":762} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program concAreaString.s *\/\n\n\/* Constantes *\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n.equ NBMAXITEMS, 20 @ \n\/* Initialized data *\/\n.data\nszMessLenArea: .ascii \"The length of area 3 is\u00a0: \"\nsZoneconv:\t\t .fill 12,1,' '\nszCarriageReturn: .asciz \"\\n\"\n\n\/* areas strings *\/\nszString1: .asciz \"Apples\"\nszString2: .asciz \"Oranges\"\nszString3: .asciz \"Pommes\"\nszString4: .asciz \"Raisins\"\nszString5: .asciz \"Abricots\"\n\n\/* pointer items area 1*\/\ntablesPoi1:\npt1_1:\t\t.int szString1\npt1_2: .int szString2\nptVoid_1:\t\t.int 0\n\n\/* pointer items area 2*\/\ntablesPoi2:\npt2_1:\t\t.int szString3\npt2_2: \t.int szString4\npt2_3: \t.int szString5\nptVoid_2:\t\t.int 0\n\n\/* UnInitialized data *\/\n.bss \ntablesPoi3: .skip 4 * NBMAXITEMS\n\n\/* code section *\/\n.text\n.global main \nmain: \/* entry of program *\/\n push {fp,lr} \/* saves 2 registers *\/\n\n @ copy area 1 -> area 3\n ldr r1,iAdrtablesPoi1 @ begin pointer area 1\n ldr r3,iAdrtablesPoi3 @ begin pointer area 3\n mov r0,#0 @ counter\n1:\n ldr r2,[r1,r0,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)\n cmp r2,#0 @ is null\u00a0?\n strne r2,[r3,r0,lsl #2] @ no store pointer in area 3\n addne r0,#1 @ increment counter\n bne 1b @ and loop\n @ copy area 2 -> area 3\n ldr r1,iAdrtablesPoi2 @ begin pointer area 2\n ldr r3,iAdrtablesPoi3 @ begin pointer area 3\n mov r4,#0 @ counter area 2\n2: @ r0 contains the first void item in area 3\n ldr r2,[r1,r4,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)\n cmp r2,#0 @ is null\u00a0?\n strne r2,[r3,r0,lsl #2] @ no store pointer in area 3\n addne r0,#1 @ increment counter\n addne r4,#1 @ increment counter\n bne 2b @ and loop\n\t\n\t@ count items number in area 3 \n ldr r1,iAdrtablesPoi3 @ begin pointer table \n mov r0,#0 @ counter\n3: @ begin loop\n ldr r2,[r1,r0,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)\n cmp r2,#0 @ is null\u00a0?\n addne r0,#1 @ no increment counter\n bne 3b @ and loop\n \n ldr r1,iAdrsZoneconv @ conversion decimal\n bl conversion10S\n ldr r0,iAdrszMessLenArea\n bl affichageMess\n\n100: \/* standard end of the program *\/\n mov r0, #0 @ return code\n pop {fp,lr} @restaur 2 registers\n mov r7, #EXIT @ request to exit program\n swi 0 @ perform the system call\niAdrtablesPoi1:\t\t.int tablesPoi1\niAdrtablesPoi2:\t\t.int tablesPoi2\niAdrtablesPoi3:\t\t.int tablesPoi3\niAdrszMessLenArea: .int szMessLenArea\niAdrsZoneconv:\t\t.int sZoneconv\niAdrszCarriageReturn: .int szCarriageReturn\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {fp,lr} \t\t\t\/* save registres *\/ \n push {r0,r1,r2,r7} \t\t\/* save others registers *\/\n mov r2,#0 \t\t\t\t\/* counter length *\/\n1: \t\/* loop length calculation *\/\n ldrb r1,[r0,r2] \t\t\t\/* read octet start position + index *\/\n cmp r1,#0 \t\t\t\/* if 0 its over *\/\n addne r2,r2,#1 \t\t\t\/* else add 1 in the length *\/\n bne 1b \t\t\t\/* and loop *\/\n \/* so here r2 contains the length of the message *\/\n mov r1,r0 \t\t\t\/* address message in r1 *\/\n mov r0,#STDOUT \t\t\/* code to write to the standard output Linux *\/\n mov r7, #WRITE \/* code call system \"write\" *\/\n swi #0 \/* call systeme *\/\n pop {r0,r1,r2,r7} \t\t\/* restaur others registers *\/\n pop {fp,lr} \t\t\t\t\/* restaur des 2 registres *\/ \n bx lr\t \t\t\t\/* return *\/\n\n\/***************************************************\/\n\/* conversion register signed d\u00e9cimal *\/\n\/***************************************************\/\n\/* r0 contient le registre *\/\n\/* r1 contient l adresse de la zone de conversion *\/\nconversion10S:\n push {r0-r5,lr} \/* save des registres *\/\n mov r2,r1 \/* debut zone stockage *\/\n mov r5,#'+' \/* par defaut le signe est + *\/\n cmp r0,#0 \/* nombre n\u00e9gatif\u00a0? *\/\n movlt r5,#'-' \/* oui le signe est - *\/\n mvnlt r0,r0 \/* et inversion en valeur positive *\/\n addlt r0,#1\n mov r4,#10 \/* longueur de la zone *\/\n1: \/* debut de boucle de conversion *\/\n bl divisionpar10 \/* division *\/\n add r1,#48 \/* ajout de 48 au reste pour conversion ascii *\/\t\n strb r1,[r2,r4] \/* stockage du byte en d\u00e9but de zone r5 + la position r4 *\/\n sub r4,r4,#1 \/* position pr\u00e9cedente *\/\n cmp r0,#0 \n bne 1b\t \/* boucle si quotient different de z\u00e9ro *\/\n strb r5,[r2,r4] \/* stockage du signe \u00e0 la position courante *\/\n subs r4,r4,#1 \/* position pr\u00e9cedente *\/\n blt 100f \/* si r4 < 0 fin *\/\n \/* sinon il faut completer le debut de la zone avec des blancs *\/\n mov r3,#' ' \/* caractere espace *\/\t\n2:\n strb r3,[r2,r4] \/* stockage du byte *\/\n subs r4,r4,#1 \/* position pr\u00e9cedente *\/\n bge 2b \/* boucle si r4 plus grand ou egal a zero *\/\n100: \/* fin standard de la fonction *\/\n pop {r0-r5,lr} \/*restaur desregistres *\/\n bx lr \n\n\/***************************************************\/\n\/* division par 10 sign\u00e9 *\/\n\/* Thanks to http:\/\/thinkingeek.com\/arm-assembler-raspberry-pi\/* \n\/* and http:\/\/www.hackersdelight.org\/ *\/\n\/***************************************************\/\n\/* r0 contient le dividende *\/\n\/* r0 retourne le quotient *\/\t\n\/* r1 retourne le reste *\/\ndivisionpar10:\t\n \/* r0 contains the argument to be divided by 10 *\/\n push {r2-r4} \/* save registers *\/\n mov r4,r0 \n ldr r3, .Ls_magic_number_10 \/* r1 <- magic_number *\/\n smull r1, r2, r3, r0 \/* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) *\/\n mov r2, r2, ASR #2 \/* r2 <- r2 >> 2 *\/\n mov r1, r0, LSR #31 \/* r1 <- r0 >> 31 *\/\n add r0, r2, r1 \/* r0 <- r2 + r1 *\/\n add r2,r0,r0, lsl #2 \/* r2 <- r0 * 5 *\/\n sub r1,r4,r2, lsl #1 \/* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) *\/\n pop {r2-r4}\n bx lr \/* leave function *\/\n bx lr \/* leave function *\/\n.Ls_magic_number_10: .word 0x66666667\n","human_summarization":"demonstrate how to concatenate two arrays.","id":763} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program problemABC.s *\/ \n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n.equ TRUE, 1\n.equ FALSE, 0\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessTitre1: .asciz \"Can_make_word: @ \\n\"\nszMessTrue: .asciz \"True.\\n\"\nszMessFalse: .asciz \"False.\\n\"\nszCarriageReturn: .asciz \"\\n\"\n\nszTablBloc: .asciz \"BO\"\n .asciz \"XK\"\n .asciz \"DQ\"\n .asciz \"CP\"\n .asciz \"NA\"\n .asciz \"GT\"\n .asciz \"RE\"\n .asciz \"TG\"\n .asciz \"QD\"\n .asciz \"FS\"\n .asciz \"JW\"\n .asciz \"HU\"\n .asciz \"VI\"\n .asciz \"AN\"\n .asciz \"OB\"\n .asciz \"ER\"\n .asciz \"FS\"\n .asciz \"LY\"\n .asciz \"PC\"\n .asciz \"ZM\"\n .equ NBBLOC, (. - szTablBloc) \/ 3\n \nszWord1: .asciz \"A\"\nszWord2: .asciz \"BARK\"\nszWord3: .asciz \"BOOK\"\nszWord4: .asciz \"TREAT\"\nszWord5: .asciz \"COMMON\"\nszWord6: .asciz \"SQUAD\"\nszWord7: .asciz \"CONFUSE\"\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\n.align 4\nitabTopBloc: .skip 4 * NBBLOC\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n ldr r0,iAdrszWord1\n bl traitBlock @ control word\n\n ldr r0,iAdrszWord2\n bl traitBlock @ control word\n \n ldr r0,iAdrszWord3\n bl traitBlock @ control word\n \n ldr r0,iAdrszWord4\n bl traitBlock @ control word\n \n ldr r0,iAdrszWord5\n bl traitBlock @ control word\n \n ldr r0,iAdrszWord6\n bl traitBlock @ control word\n \n ldr r0,iAdrszWord7\n bl traitBlock @ control word\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrszWord1: .int szWord1\niAdrszWord2: .int szWord2\niAdrszWord3: .int szWord3\niAdrszWord4: .int szWord4\niAdrszWord5: .int szWord5\niAdrszWord6: .int szWord6\niAdrszWord7: .int szWord7\n\/******************************************************************\/\n\/* traitement *\/ \n\/******************************************************************\/\n\/* r0 contains word *\/\ntraitBlock:\n push {r1,lr} @ save registers\n mov r1,r0\n ldr r0,iAdrszMessTitre1 @ insertion word in message\n bl strInsertAtCharInc\n bl affichageMess @ display title message\n mov r0,r1\n bl controlBlock @ control \n cmp r0,#TRUE @ ok\u00a0?\n bne 1f\n ldr r0,iAdrszMessTrue @ yes\n bl affichageMess\n b 100f\n1: @ no\n ldr r0,iAdrszMessFalse\n bl affichageMess\n100:\n pop {r1,lr}\n bx lr @ return \niAdrszMessTitre1: .int szMessTitre1\niAdrszMessFalse: .int szMessFalse\niAdrszMessTrue: .int szMessTrue\n\/******************************************************************\/\n\/* control if letters are in block *\/ \n\/******************************************************************\/\n\/* r0 contains word *\/\ncontrolBlock:\n push {r1-r9,lr} @ save registers\n mov r5,r0 @ save word address\n ldr r4,iAdritabTopBloc\n ldr r6,iAdrszTablBloc\n mov r2,#0\n mov r3,#0\n1: @ init table top block used\n str r3,[r4,r2,lsl #2]\n add r2,r2,#1\n cmp r2,#NBBLOC\n blt 1b\n mov r2,#0\n2: @ loop to load letters \n ldrb r3,[r5,r2]\n cmp r3,#0\n beq 10f @ end\n and r3,r3,#0xDF @ transform in capital letter\n mov r8,#0\n3: @ begin loop control block\n ldr r7,[r4,r8,lsl #2] @ block already used\u00a0?\n cmp r7,#0\n bne 5f @ yes\n add r9,r8,r8,lsl #1 @ no -> index * 3\n ldrb r7,[r6,r9] @ first block letter\n cmp r3,r7 @ equal\u00a0?\n beq 4f\n add r9,r9,#1\n ldrb r7,[r6,r9] @ second block letter\n cmp r3,r7 @ equal\u00a0?\n beq 4f\n b 5f\n4:\n mov r7,#1 @ top block\n str r7,[r4,r8,lsl #2] @ block used\n add r2,r2,#1\n b 2b @ next letter\n5:\n add r8,r8,#1\n cmp r8,#NBBLOC\n blt 3b\n mov r0,#FALSE @ no letter find on block -> false\n b 100f \n10: @ all letters are ok\n mov r0,#TRUE\n100:\n pop {r1-r9,lr}\n bx lr @ return \niAdritabTopBloc: .int itabTopBloc\niAdrszTablBloc: .int szTablBloc\n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\nCan_make_word: A\nTrue.\nCan_make_word: BARK\nTrue.\nCan_make_word: BOOK\nFalse.\nCan_make_word: TREAT\nTrue.\nCan_make_word: COMMON\nFalse.\nCan_make_word: SQUAD\nTrue.\nCan_make_word: CONFUSE\nTrue.\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":764} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi or android 32 bits with application Termux\n\/* ARM assembly Raspberry PI *\/\n\/* program MD5.s *\/\n\n\/* REMARK 1\u00a0: this program use routines in a include file \n see task Include a file language arm assembly \n for the routine affichageMess conversion10 \n see at end of this program the instruction include *\/\n\/* for constantes see task include a file in arm assembly *\/\n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.include \"..\/constantes.inc\"\n\n.equ LGHASH, 16 \/\/ result length \n.equ ZWORKSIZE, 1000 \/\/ work area size\n\n\/*******************************************\/\n\/* Structures *\/\n\/********************************************\/\n\/* example structure variables *\/\n .struct 0\nvar_a: \/\/ a\n .struct var_a + 4\nvar_b: \/\/ b\n .struct var_b + 4\nvar_c: \/\/ c\n .struct var_c + 4\nvar_d: \/\/ d\n .struct var_d + 4\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nszMessTest1: .asciz \"abc\" \nszMessTest4: .asciz \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"\nszMessTest2: .asciz \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\nszMessTest3: .asciz \"abcdefghijklmnopqrstuvwxyz\"\nszMessFinPgm: .asciz \"Program End ok.\\n\"\nszMessResult: .asciz \"Result for \"\nszMessResult1: .asciz \" => \"\nszMessSizeError: .asciz \"\\033[31mWork area too small\u00a0!! \\033[0m \\n\"\nszCarriageReturn: .asciz \"\\n\"\n\n.align 4\n\/* array constantes K *\/\ntbConstK: .int 0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee\n .int 0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501\n .int 0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be\n .int 0x6b901122,0xfd987193,0xa679438e,0x49b40821\n .int 0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa\n .int 0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8\n .int 0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed\n .int 0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a\n .int 0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c\n .int 0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70\n .int 0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05\n .int 0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665\n .int 0xf4292244,0x432aff97,0xab9423a7,0xfc93a039\n .int 0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1\n .int 0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1\n .int 0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391 \n\n\/* array rotation coef R *\/\ntbRotaR: .int 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22\n .int 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20\n .int 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23\n .int 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21\n\ntbConstH: .int 0x67452301 \/\/ H0\n .int 0xEFCDAB89 \/\/ H1\n .int 0x98BADCFE \/\/ H2\n .int 0x10325476 \/\/ H3\n\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss\n.align 4\nsZoneConv: .skip 24\ntbH: .skip 4 * 4 @ 4 variables H\ntbabcd: .skip 4 * 4 @ 4 variables a b c d\nsZoneTrav: .skip 1000\n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n \n ldr r0,iAdrszMessTest1\n bl computeExemple\n \n ldr r0,iAdrszMessTest2\n bl computeExemple\n \n ldr r0,iAdrszMessTest3\n bl computeExemple\n \n ldr r0,iAdrszMessTest4\n bl computeExemple\n\n ldr r0,iAdrszMessFinPgm\n bl affichageMess @ display message\n\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrszCarriageReturn: .int szCarriageReturn\niAdrszMessResult: .int szMessResult\niAdrszMessResult1: .int szMessResult1\niAdrszMessTest1: .int szMessTest1\niAdrszMessTest2: .int szMessTest2\niAdrszMessTest3: .int szMessTest3\niAdrszMessTest4: .int szMessTest4\niAdrsZoneTrav: .int sZoneTrav\niAdrsZoneConv: .int sZoneConv\niAdrszMessFinPgm: .int szMessFinPgm\niAdrszMessSizeError: .int szMessSizeError\n\/***********************************************\/\n\/* compute exemple *\/ \n\/***********************************************\/\n\/* r0 contains the address of the message *\/\ncomputeExemple:\n push {r1,lr} @ save registres\n mov r1,r0\n bl computeMD5 @ call routine MD5\n \n ldr r0,iAdrszMessResult\n bl affichageMess\n mov r0,r1\n bl affichageMess \n ldr r0,iAdrszMessResult1\n bl affichageMess\n ldr r0, iAdrtbH\n bl displayMD5\n \n100:\n pop {r1,pc} @ restaur registers\n\n\/******************************************************************\/\n\/* compute MD5 *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\ncomputeMD5:\n push {r1-r12,lr} @ save registres\n ldr r1,iAdrsZoneTrav\n mov r2,#0 @ counter length \n1: @ copy string in work area\n cmp r2,#ZWORKSIZE @ maxi\u00a0?\n bge 99f @ error\n ldrb r3,[r0,r2]\n strb r3,[r1,r2]\n cmp r3,#0 \n addne r2,r2,#1\n bne 1b\n lsl r6,r2,#3 @ initial message length in bits \n mov r3,#0b10000000 @ add bit 1 at end of string\n strb r3,[r1,r2]\n add r2,r2,#1 @ length in bytes\n lsl r4,r2,#3 @ length in bits\n mov r3,#0\n2:\n lsr r5,r2,#6\n lsl r5,r5,#6\n sub r5,r2,r5\n cmp r5,#56\n beq 3f @ yes -> end add\n strb r3,[r1,r2] @ add zero at message end\n add r2,#1 @ increment lenght bytes \n add r4,#8 @ increment length in bits\n b 2b\n3:\n str r6,[r1,r2] @ and store length at end\n add r5,r2,#4\n str r3,[r1,r5] @ store zero in hight bits for 64 bits\n\n ldr r7,iAdrtbConstH @ constantes H address\n ldr r4,iAdrtbH @ start area H\n mov r5,#0\n4: @ init array H with start constantes\n ldr r6,[r7,r5,lsl #2] @ load constante\n str r6,[r4,r5,lsl #2] @ and store\n add r5,r5,#1\n cmp r5,#4\n blt 4b\n @ split into block of 64 bytes\n add r2,#4 @ TODO\u00a0: \u00e0 revoir\n lsr r4,r2,#6 @ blocks number\n\n ldr r0,iAdrtbH @ variables H\n ldr r1,iAdrsZoneTrav\n ldr r5,iAdrtbConstK\n ldr r3,iAdrtbRotaR\n ldr r8,iAdrtbabcd\n mov r7,#0 @ n\u00b0 de block et r1 contient l adresse zone de travail\n5: @ begin loop of each block of 64 bytes\n add r2,r1,r7,lsl #6 @ compute block begin indice * 4 * 16\n mov r6,#0 @ indice t\n \/* COMPUTING THE MESSAGE DIGEST *\/\n \/* r0 variables H address *\/\n \/* r1 work area *\/\n \/* r2 block work area begin address *\/\n \/* r3 address constantes rotate *\/\n \/* r4 block number *\/\n \/* r5 constance K address *\/\n \/* r6 counter t *\/\n \/* r7 block counter *\/\n \/* r8 addresse variables a b c d *\/\n @ init variable a b c d with variables H\n mov r10,#0\n6: @ loop init\n ldr r9,[r0,r10,lsl #2] @ variables H\n str r9,[r8,r10,lsl #2] @ variables a b c d\n add r10,r10,#1\n cmp r10,#4\n blt 6b\n \n7: @ loop begin\n cmp r6,#15\n bgt 8f\n @ cas 1 f\u00a0:= (b et c) ou ((non b) et d)\n @ g\u00a0:= i\n ldr r9,[r8,#var_b]\n ldr r10,[r8,#var_c]\n and r12,r10,r9\n mvn r9,r9\n ldr r10,[r8,#var_d]\n and r11,r9,r10\n orr r12,r12,r11 @ f\n mov r9,r6 @ g\n b 11f\n8:\n cmp r6,#31\n bgt 9f\n @ f\u00a0:= (d et b) ou ((non d) et c)\n @ g\u00a0:= (5\u00d7i + 1) mod 16\n ldr r9,[r8,#var_b]\n ldr r10,[r8,#var_d]\n and r12,r10,r9\n mvn r10,r10\n ldr r9,[r8,#var_c]\n and r11,r9,r10\n orr r12,r12,r11 @ f\n mov r9,#5\n mul r9,r6,r9\n add r9,r9,#1\n lsr r10,r9,#4\n lsl r10,r10,#4\n sub r9,r9,r10 @ g\n \n b 11f\n9:\n cmp r6,#47\n bgt 10f\n @ f\u00a0:= b xor c xor d\n @ g\u00a0:= (3\u00d7i + 5) mod 16\n ldr r9,[r8,#var_b]\n ldr r10,[r8,#var_c]\n eor r12,r10,r9\n ldr r10,[r8,#var_d]\n eor r12,r12,r10 @ f\n mov r9,#3\n mul r9,r6,r9\n add r9,r9,#5\n lsr r10,r9,#4\n lsl r10,r10,#4\n sub r9,r9,r10 @ g\n b 11f\n10:\n @ f\u00a0:= c xor (b ou (non d))\n @ g\u00a0:= (7\u00d7i) mod 16\n ldr r10,[r8,#var_d]\n mvn r12,r10\n ldr r10,[r8,#var_b] \n orr r12,r12,r10\n ldr r10,[r8,#var_c] \n eor r12,r12,r10 @ f\n mov r9,#7\n mul r9,r6,r9\n lsr r10,r9,#4\n lsl r10,r10,#4\n sub r9,r9,r10 @ g\n \n11:\n ldr r10,[r8,#var_d]\n mov r11,r10 @ save old d\n ldr r10,[r8,#var_c]\n str r10,[r8,#var_d] @ new d = c\n ldr r10,[r8,#var_b]\n str r10,[r8,#var_c] @ new c = b\n ldr r10,[r8,#var_a]\n add r12,r12,r10 @ a + f\n ldr r10,[r2,r9,lsl #2] \n add r12,r12,r10 @ + valeur bloc g\n ldr r10,[r5,r6,lsl #2]\n add r12,r12,r10 @ + valeur constante K de i\n ldr r10,[r3,r6,lsl #2] @ rotate left value\n rsb r10,r10,#32 @ compute right rotate\n ror r12,r12,r10\n ldr r10,[r8,#var_b]\n add r12,r12,r10\n str r12,[r8,#var_b] @ new b\n str r11,[r8,#var_a] @ new a = old d\n \n add r6,r6,#1\n cmp r6,#63\n ble 7b\n @ maj area H\n ldr r10,[r0] @ H0\n ldr r11,[r8,#var_a]\n add r10,r10,r11 @ + a\n str r10,[r0]\n ldr r10,[r0,#4] @ H1\n ldr r11,[r8,#var_b]\n add r10,r10,r11 @ + b\n str r10,[r0,#4]\n ldr r10,[r0,#8] @ H2\n ldr r11,[r8,#var_c]\n add r10,r10,r11 @ + c\n str r10,[r0,#8]\n ldr r10,[r0,#12] @ H3\n ldr r11,[r8,#var_d]\n add r10,r10,r11 @ + d\n str r10,[r0,#12]\n \n @ loop other block\n add r7,r7,#1 @ increment block\n cmp r7,r4 @ maxi\u00a0?\n ble 5b\n \n mov r9,#0 @ reverse bytes loop\n12:\n ldr r10,[r0,r9,lsl #2]\n rev r10,r10 @ reverse bytes\n str r10,[r0,r9,lsl #2]\n add r9,r9,#1\n cmp r9,#LGHASH \/ 4\n blt 12b\n mov r0,#0 @ routine OK\n b 100f\n99: @ size error\n ldr r0,iAdrszMessSizeError\n bl affichageMess\n mov r0,#-1 @ error routine\n \n100:\n pop {r1-r12,pc} @ restaur registers\niAdrtbConstH: .int tbConstH\niAdrtbConstK: .int tbConstK\niAdrtbRotaR: .int tbRotaR\niAdrtbH: .int tbH\niAdrtbabcd: .int tbabcd\n\n\/*************************************************\/\n\/* display hash MD5 *\/ \n\/*************************************************\/\n\/* r0 contains the address of hash *\/\ndisplayMD5:\n push {r1-r3,lr} @ save registres\n mov r3,r0\n mov r2,#0\n1:\n ldr r0,[r3,r2,lsl #2] @ load 4 bytes\n ldr r1,iAdrsZoneConv\n bl conversion16 @ conversion hexa\n ldr r0,iAdrsZoneConv\n bl affichageMess\n add r2,r2,#1\n cmp r2,#LGHASH \/ 4\n blt 1b @ and loop\n ldr r0,iAdrszCarriageReturn\n bl affichageMess @ display message\n100:\n pop {r1-r3,lr} @ restaur registers\n bx lr @ return \n\/***************************************************\/\n\/* ROUTINES INCLUDE *\/\n\/***************************************************\/\n.include \"..\/affichage.inc\"\nResult for abc => 900150983CD24FB0D6963F7D28E17F72\nResult for ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 => D174AB98D277D9F5A5611C2C9F419D9F\nResult for abcdefghijklmnopqrstuvwxyz => C3FCD3D76192E4007DFB496CCA67E13B\nResult for 12345678901234567890123456789012345678901234567890123456789012345678901234567890 => 57EDF4A22BE3C955AC49DA2E2107B67A\nProgram End ok.\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":765} {"lang_cluster":"ARM_Assembly","source_code":"\nWorks with: as version Raspberry Pi\n\/* ARM assembly Raspberry PI *\/\n\/* program countoctal.s *\/\n \n\/************************************\/\n\/* Constantes *\/\n\/************************************\/\n.equ STDOUT, 1 @ Linux output console\n.equ EXIT, 1 @ Linux syscall\n.equ WRITE, 4 @ Linux syscall\n\n\/*********************************\/\n\/* Initialized data *\/\n\/*********************************\/\n.data\nsMessResult: .ascii \"Count\u00a0: \"\nsMessValeur: .fill 11, 1, ' ' @ size => 11\nszCarriageReturn: .asciz \"\\n\"\n\n\n\/*********************************\/\n\/* UnInitialized data *\/\n\/*********************************\/\n.bss \n\/*********************************\/\n\/* code section *\/\n\/*********************************\/\n.text\n.global main \nmain: @ entry of program \n mov r4,#0 @ loop indice\n1: @ begin loop\n mov r0,r4\n ldr r1,iAdrsMessValeur\n bl conversion8 @ call conversion octal\n ldr r0,iAdrsMessResult\n bl affichageMess @ display message\n add r4,#1\n cmp r4,#64\n ble 1b\n\n\n100: @ standard end of the program \n mov r0, #0 @ return code\n mov r7, #EXIT @ request to exit program\n svc #0 @ perform the system call\n \niAdrsMessValeur: .int sMessValeur\niAdrszCarriageReturn: .int szCarriageReturn\niAdrsMessResult: .int sMessResult\n\n\/******************************************************************\/\n\/* display text with size calculation *\/ \n\/******************************************************************\/\n\/* r0 contains the address of the message *\/\naffichageMess:\n push {r0,r1,r2,r7,lr} @ save registres\n mov r2,#0 @ counter length \n1: @ loop length calculation \n ldrb r1,[r0,r2] @ read octet start position + index \n cmp r1,#0 @ if 0 its over \n addne r2,r2,#1 @ else add 1 in the length \n bne 1b @ and loop \n @ so here r2 contains the length of the message \n mov r1,r0 @ address message in r1 \n mov r0,#STDOUT @ code to write to the standard output Linux \n mov r7, #WRITE @ code call system \"write\" \n svc #0 @ call systeme \n pop {r0,r1,r2,r7,lr} @ restaur des 2 registres *\/ \n bx lr @ return \n\/******************************************************************\/\n\/* Converting a register to octal *\/ \n\/******************************************************************\/\n\/* r0 contains value and r1 address area *\/\n\/* r0 return size of result (no zero final in area) *\/\n\/* area size => 11 bytes *\/\n.equ LGZONECAL, 10\nconversion8:\n push {r1-r4,lr} @ save registers \n mov r3,r1\n mov r2,#LGZONECAL\n \n1: @ start loop\n mov r1,r0\n lsr r0,#3 @ \/ by 8\n sub r1,r0,lsl #3 @ compute remainder r1 - (r0 * 8)\n add r1,#48 @ digit\n strb r1,[r3,r2] @ store digit on area\n cmp r0,#0 @ stop if quotient = 0 \n subne r2,#1 @ else previous position\n bne 1b @ and loop\n @ and move digit from left of area\n mov r4,#0\n2:\n ldrb r1,[r3,r2]\n strb r1,[r3,r4]\n add r2,#1\n add r4,#1\n cmp r2,#LGZONECAL\n ble 2b\n @ and move spaces in end on area\n mov r0,r4 @ result length \n mov r1,#' ' @ space\n3:\n strb r1,[r3,r4] @ store space in area\n add r4,#1 @ next position\n cmp r4,#LGZONECAL\n ble 3b @ loop if r4 <= area size\n \n100:\n pop {r1-r4,lr} @ restaur registres \n bx lr @return\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":766} {"lang_cluster":"ARM_Assembly","source_code":"\n@ Check whether the ASCII string in [r0] is a palindrome\n@ Returns with zero flag set if palindrome.\npalin:\tmov\tr1,r0\t\t@ Find end of string\n1:\tldrb\tr2,[r1],#1\t@ Grab character and increment pointer\n\ttst\tr2,r2\t\t@ Zero yet?\n\tbne\t1b\t\t@ If not try next byte\n\tsub\tr1,r1,#2\t@ Move R1 to last actual character.\n2:\tcmp\tr0,r1\t\t@ When R0 >= R1,\n\tcmpgt\tr2,r2\t\t@ make sure zero is set,\n\tbxeq\tlr\t\t@ and stop (the string is a palindrome).\n\tldrb\tr2,[r1],#-1\t@ Grab [R1] (end) and decrement.\n\tldrb\tr3,[r0],#1\t@ Grab [R0] (begin) and increment\n\tcmp\tr2,r3\t\t@ Are they equal?\n\tbxne\tlr\t\t@ If not, it's not a palindrome.\n\tb\t2b\t\t@ Otherwise, try next pair.\n\t\n@ Try the function on a couple of strings\n.global _start\n_start:\tldr\tr8,=words\t@ Word pointer\n1:\tldr\tr9,[r8],#4\t@ Grab word and move pointer\n\ttst\tr9,r9\t\t@ Null?\n\tmoveq\tr7,#1\t\t@ Then we're done; syscall 1 = exit\n\tswieq\t#0\n\tmov\tr1,r9\t\t@ Print the word\n\tbl\tprint\t\t\n\tmov\tr0,r9\t\t@ Test if the word is a palindrome\n\tbl\tpalin\n\tldreq\tr1,=yes\t\t@ \"Yes\" if it is a palindrome\n\tldrne\tr1,=no\t\t@ \"No\" if it's not a palindrome\n\tbl\tprint\n\tb\t1b\t\t@ Next word \n\n@ Print zero-terminated string [r1] using Linux syscall\nprint:\tpush\t{r7,lr}\t\t@ Keep R7 and link register\n\tmov\tr2,r1\t\t@ Find end of string\n1:\tldrb\tr0,[r2],#1\t@ Grab character and increment pointer\n\ttst\tr0,r0\t\t@ Zero yet?\n\tbne\t1b\t\t@ If not, keep going\n\tsub\tr2,r2,r1\t@ Calculate length of string (bytes to write)\n\tmov\tr0,#1\t\t@ Stdout = 1\n\tmov\tr7,#4\t\t@ Syscall 4 = write\n\tswi\t#0\t\t@ Make the syscall\n\tpop\t{r7,lr}\t\t@ Restore R7 and link register\n\tbx\tlr\n\t\n@ Strings\nyes:\t.asciz\t\": yes\\n\"\t@ Output yes or no\nno:\t.asciz\t\": no\\n\"\nw1:\t.asciz\t\"rotor\"\t\t@ Words to test\nw2:\t.asciz\t\"racecar\"\nw3:\t.asciz\t\"level\"\nw4:\t.asciz\t\"redder\"\nw5:\t.asciz\t\"rosetta\"\nwords:\t.word\tw1,w2,w3,w4,w5,0\n\n\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":767} {"lang_cluster":"C++","source_code":"\nLibrary: STL\n\n#include \n\n\n#include \ntemplate >\nclass stack {\n friend bool operator== (const stack&, const stack&);\n friend bool operator< (const stack&, const stack&);\npublic:\n typedef typename Sequence::value_type value_type;\n typedef typename Sequence::size_type size_type;\n typedef Sequence container_type;\n typedef typename Sequence::reference reference;\n typedef typename Sequence::const_reference const_reference;\nprotected:\n Sequence seq;\npublic:\n stack() : seq() {}\n explicit stack(const Sequence& s0) : seq(s0) {}\n bool empty() const { return seq.empty(); }\n size_type size() const { return seq.size(); }\n reference top() { return seq.back(); }\n const_reference top() const { return seq.back(); }\n void push(const value_type& x) { seq.push_back(x); }\n void pop() { seq.pop_back(); }\n};\n\ntemplate \nbool operator==(const stack& x, const stack& y)\n{\n return x.seq == y.seq;\n}\ntemplate \nbool operator<(const stack& x, const stack& y)\n{\n return x.seq < y.seq;\n}\n\ntemplate \nbool operator!=(const stack& x, const stack& y)\n{\n return !(x == y);\n}\ntemplate \nbool operator>(const stack& x, const stack& y)\n{\n return y < x;\n}\ntemplate \nbool operator<=(const stack& x, const stack& y)\n{\n return !(y < x);\n}\ntemplate \nbool operator>=(const stack& x, const stack& y)\n{\n return !(x < y);\n}\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and allows access to the topmost element without modification. The stack is commonly used in programming for resource management, implementing local variables in recursive subprograms, and in various algorithms. The C++ standard library provides a ready-made stack class for use.","id":768} {"lang_cluster":"C++","source_code":"\n\n#include \n\nint main()\n{\n unsigned int a = 1, b = 1;\n unsigned int target = 48;\n for(unsigned int n = 3; n <= target; ++n)\n {\n unsigned int fib = a + b;\n std::cout << \"F(\"<< n << \") = \" << fib << std::endl;\n a = b;\n b = fib;\n }\n\n return 0;\n}\n\n\nLibrary: GMP\n\n#include \n#include \n\nint main()\n{\n mpz_class a = mpz_class(1), b = mpz_class(1);\n mpz_class target = mpz_class(100);\n for(mpz_class n = mpz_class(3); n <= target; ++n)\n {\n mpz_class fib = b + a;\n if ( fib < b )\n {\n std::cout << \"Overflow at \" << n << std::endl;\n break;\n }\n std::cout << \"F(\"<< n << \") = \" << fib << std::endl;\n a = b;\n b = fib;\n }\n return 0;\n}\n\n\n#include \n#include \n#include \n#include \n \nunsigned int fibonacci(unsigned int n) {\n if (n == 0) return 0;\n std::vector v(n+1);\n v[1] = 1;\n transform(v.begin(), v.end()-2, v.begin()+1, v.begin()+2, std::plus());\n \/\/ \"v\" now contains the Fibonacci sequence from 0 up\n return v[n];\n}\n\n#include \n#include \n#include \n#include \n\nunsigned int fibonacci(unsigned int n) {\n if (n == 0) return 0;\n std::vector v(n, 1);\n adjacent_difference(v.begin(), v.end()-1, v.begin()+1, std::plus());\n \/\/ \"array\" now contains the Fibonacci sequence from 1 up\n return v[n-1];\n}\n\n#include \n\ntemplate struct fibo\n{\n enum {value=fibo::value+fibo::value};\n};\n \ntemplate <> struct fibo<0>\n{\n enum {value=0};\n};\n\ntemplate <> struct fibo<1>\n{\n enum {value=1};\n};\n\n\nint main(int argc, char const *argv[])\n{\n std::cout<::value<::value<\n\ninline void fibmul(int* f, int* g)\n{\n int tmp = f[0]*g[0] + f[1]*g[1];\n f[1] = f[0]*g[1] + f[1]*(g[0] + g[1]);\n f[0] = tmp;\n}\n\nint fibonacci(int n)\n{\n int f[] = { 1, 0 };\n int g[] = { 0, 1 };\n while (n > 0)\n {\n if (n & 1) \/\/ n odd\n {\n fibmul(f, g);\n --n;\n }\n else\n {\n fibmul(g, g);\n n >>= 1;\n }\n }\n return f[1];\n}\n\nint main()\n{\n for (int i = 0; i < 20; ++i)\n std::cout << fibonacci(i) << \" \";\n std::cout << std::endl;\n}\n\n","human_summarization":"The code generates the nth Fibonacci number, either iteratively or recursively. It optionally supports negative n values by using an inverse definition. The code can overflow if unsigned int is used and n is greater than 48. Different versions of the code include using transform, adjacent_difference, compile-time computation with metaprogramming, and fast exponentiation. There's also a version that represents the nth Fibonacci number as a Zeckendorf number.","id":769} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n#include \n\nint main() {\n std::vector ary;\n for (int i = 0; i < 10; i++)\n ary.push_back(i);\n std::vector evens;\n std::remove_copy_if(ary.begin(), ary.end(), back_inserter(evens),\n std::bind2nd(std::modulus(), 2)); \/\/ filter copy\n std::copy(evens.begin(), evens.end(),\n std::ostream_iterator(std::cout, \"\\n\"));\n\n return 0;\n}\n\n\nWorks with: C++11\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nint main() {\n vector ary = {1, 2, 3, 4, 5, 6, 7, 8, 9};\n vector evens;\n\n copy_if(ary.begin(), ary.end(), back_inserter(evens),\n [](int i) { return i % 2 == 0; });\n\n \/\/ print result\n copy(evens.begin(), evens.end(), ostream_iterator(cout, \"\\n\"));\n}\n\n","human_summarization":"select certain elements from an array into a new array in a generic way, specifically all even numbers. Optionally, it also provides a destructive filtering solution that modifies the original array instead of creating a new one.","id":770} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main()\n{\n std::string s = \"0123456789\";\n\n int const n = 3;\n int const m = 4;\n char const c = '2';\n std::string const sub = \"456\";\n\n std::cout << s.substr(n, m)<< \"\\n\";\n std::cout << s.substr(n) << \"\\n\";\n std::cout << s.substr(0, s.size()-1) << \"\\n\";\n std::cout << s.substr(s.find(c), m) << \"\\n\";\n std::cout << s.substr(s.find(sub), m) << \"\\n\";\n}\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":771} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n\nint main() {\n std::string s;\n std::getline(std::cin, s);\n std::reverse(s.begin(), s.end()); \/\/ modifies s\n std::cout << s << '\\n';\n}\n\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":772} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nusing namespace std;\n\nclass playfair\n{\npublic:\n void doIt( string k, string t, bool ij, bool e )\n {\n\tcreateGrid( k, ij ); getTextReady( t, ij, e );\n\tif( e ) doIt( 1 ); else doIt( -1 );\n\tdisplay();\n }\n\nprivate:\n void doIt( int dir )\n {\n\tint a, b, c, d; string ntxt;\n\tfor( string::const_iterator ti = _txt.begin(); ti != _txt.end(); ti++ )\n\t{\n\t if( getCharPos( *ti++, a, b ) )\n\t\tif( getCharPos( *ti, c, d ) )\n\t\t{\n\t\t if( a == c ) { ntxt += getChar( a, b + dir ); ntxt += getChar( c, d + dir ); }\n\t\t else if( b == d ){ ntxt += getChar( a + dir, b ); ntxt += getChar( c + dir, d ); }\n\t\t else { ntxt += getChar( c, b ); ntxt += getChar( a, d ); }\n\t\t}\n\t}\n\t_txt = ntxt;\n }\n\n void display()\n {\n\tcout << \"\\n\\n OUTPUT:\\n=========\" << endl;\n\tstring::iterator si = _txt.begin(); int cnt = 0;\n\twhile( si != _txt.end() )\n\t{\n\t cout << *si; si++; cout << *si << \" \"; si++;\n\t if( ++cnt >= 26 ) cout << endl, cnt = 0;\n\t}\n\tcout << endl << endl;\n }\n\n char getChar( int a, int b )\n {\n\treturn _m[ (b + 5) % 5 ][ (a + 5) % 5 ];\n }\n\n bool getCharPos( char l, int &a, int &b )\n {\n\tfor( int y = 0; y < 5; y++ )\n\t for( int x = 0; x < 5; x++ )\n\t\tif( _m[y][x] == l )\n\t\t{ a = x; b = y; return true; }\n\n\treturn false;\n }\n\n void getTextReady( string t, bool ij, bool e )\n {\n\tfor( string::iterator si = t.begin(); si != t.end(); si++ )\n\t{\n\t *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t if( *si == 'J' && ij ) *si = 'I';\n\t else if( *si == 'Q' && !ij ) continue;\n\t _txt += *si;\n\t}\n\tif( e )\n\t{\n\t string ntxt = \"\"; size_t len = _txt.length();\n\t for( size_t x = 0; x < len; x += 2 )\n\t {\n\t\tntxt += _txt[x];\n\t\tif( x + 1 < len )\n\t\t{\n\t\t if( _txt[x] == _txt[x + 1] ) ntxt += 'X';\n\t\t ntxt += _txt[x + 1];\n\t\t}\n\t }\n\t _txt = ntxt;\n\t}\n\tif( _txt.length() & 1 ) _txt += 'X';\n }\n\n void createGrid( string k, bool ij )\n {\n\tif( k.length() < 1 ) k = \"KEYWORD\"; \n\tk += \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"; string nk = \"\";\n\tfor( string::iterator si = k.begin(); si != k.end(); si++ )\n\t{\n\t *si = toupper( *si ); if( *si < 65 || *si > 90 ) continue;\n\t if( ( *si == 'J' && ij ) || ( *si == 'Q' && !ij ) )continue;\n\t if( nk.find( *si ) == -1 ) nk += *si;\n\t}\n\tcopy( nk.begin(), nk.end(), &_m[0][0] );\n }\n\n string _txt; char _m[5][5];\n};\n\nint main( int argc, char* argv[] )\n{\n string key, i, txt; bool ij, e;\n cout << \"(E)ncode or (D)ecode? \"; getline( cin, i ); e = ( i[0] == 'e' || i[0] == 'E' );\n cout << \"Enter a en\/decryption key: \"; getline( cin, key ); \n cout << \"I <-> J (Y\/N): \"; getline( cin, i ); ij = ( i[0] == 'y' || i[0] == 'Y' );\n cout << \"Enter the text: \"; getline( cin, txt ); \n playfair pf; pf.doIt( key, txt, ij, e ); return system( \"pause\" );\n}\n\n\n","human_summarization":"Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.","id":773} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n#include \n\n#include \/\/ for numeric_limits\n\n#include \n#include \/\/ for pair\n#include \n#include \n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits::infinity();\n\nstruct neighbor {\n vertex_t target;\n weight_t weight;\n neighbor(vertex_t arg_target, weight_t arg_weight)\n : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector > adjacency_list_t;\n\n\nvoid DijkstraComputePaths(vertex_t source,\n const adjacency_list_t &adjacency_list,\n std::vector &min_distance,\n std::vector &previous)\n{\n int n = adjacency_list.size();\n min_distance.clear();\n min_distance.resize(n, max_weight);\n min_distance[source] = 0;\n previous.clear();\n previous.resize(n, -1);\n std::set > vertex_queue;\n vertex_queue.insert(std::make_pair(min_distance[source], source));\n\n while (!vertex_queue.empty()) \n {\n weight_t dist = vertex_queue.begin()->first;\n vertex_t u = vertex_queue.begin()->second;\n vertex_queue.erase(vertex_queue.begin());\n\n \/\/ Visit each edge exiting u\n\tconst std::vector &neighbors = adjacency_list[u];\n for (std::vector::const_iterator neighbor_iter = neighbors.begin();\n neighbor_iter != neighbors.end();\n neighbor_iter++)\n {\n vertex_t v = neighbor_iter->target;\n weight_t weight = neighbor_iter->weight;\n weight_t distance_through_u = dist + weight;\n\t if (distance_through_u < min_distance[v]) {\n\t vertex_queue.erase(std::make_pair(min_distance[v], v));\n\n\t min_distance[v] = distance_through_u;\n\t previous[v] = u;\n\t vertex_queue.insert(std::make_pair(min_distance[v], v));\n\n\t }\n\n }\n }\n}\n\n\nstd::list DijkstraGetShortestPathTo(\n vertex_t vertex, const std::vector &previous)\n{\n std::list path;\n for ( ; vertex != -1; vertex = previous[vertex])\n path.push_front(vertex);\n return path;\n}\n\n\nint main()\n{\n \/\/ remember to insert edges both ways for an undirected graph\n adjacency_list_t adjacency_list(6);\n \/\/ 0 = a\n adjacency_list[0].push_back(neighbor(1, 7));\n adjacency_list[0].push_back(neighbor(2, 9));\n adjacency_list[0].push_back(neighbor(5, 14));\n \/\/ 1 = b\n adjacency_list[1].push_back(neighbor(0, 7));\n adjacency_list[1].push_back(neighbor(2, 10));\n adjacency_list[1].push_back(neighbor(3, 15));\n \/\/ 2 = c\n adjacency_list[2].push_back(neighbor(0, 9));\n adjacency_list[2].push_back(neighbor(1, 10));\n adjacency_list[2].push_back(neighbor(3, 11));\n adjacency_list[2].push_back(neighbor(5, 2));\n \/\/ 3 = d\n adjacency_list[3].push_back(neighbor(1, 15));\n adjacency_list[3].push_back(neighbor(2, 11));\n adjacency_list[3].push_back(neighbor(4, 6));\n \/\/ 4 = e\n adjacency_list[4].push_back(neighbor(3, 6));\n adjacency_list[4].push_back(neighbor(5, 9));\n \/\/ 5 = f\n adjacency_list[5].push_back(neighbor(0, 14));\n adjacency_list[5].push_back(neighbor(2, 2));\n adjacency_list[5].push_back(neighbor(4, 9));\n\n std::vector min_distance;\n std::vector previous;\n DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n std::list path = DijkstraGetShortestPathTo(4, previous);\n std::cout << \"Path\u00a0: \";\n std::copy(path.begin(), path.end(), std::ostream_iterator(std::cout, \" \"));\n std::cout << std::endl;\n\n return 0;\n}\n\n\n\n#include \n#include \n#include \n#include \n\n#include \/\/ for numeric_limits\n\n#include \n#include \/\/ for pair\n#include \n#include \n\n\ntypedef int vertex_t;\ntypedef double weight_t;\n\nconst weight_t max_weight = std::numeric_limits::infinity();\n\nstruct neighbor {\n vertex_t target;\n weight_t weight;\n neighbor(vertex_t arg_target, weight_t arg_weight)\n : target(arg_target), weight(arg_weight) { }\n};\n\ntypedef std::vector > adjacency_list_t;\ntypedef std::pair weight_vertex_pair_t;\n\nvoid DijkstraComputePaths(vertex_t source,\n const adjacency_list_t &adjacency_list,\n std::vector &min_distance,\n std::vector &previous)\n{\n int n = adjacency_list.size();\n min_distance.clear();\n min_distance.resize(n, max_weight);\n min_distance[source] = 0;\n previous.clear();\n previous.resize(n, -1);\n \/\/ we use greater instead of less to turn max-heap into min-heap\n std::priority_queue,\n\t\t\tstd::greater > vertex_queue;\n vertex_queue.push(std::make_pair(min_distance[source], source));\n\n while (!vertex_queue.empty()) \n {\n weight_t dist = vertex_queue.top().first;\n vertex_t u = vertex_queue.top().second;\n vertex_queue.pop();\n\n\t\/\/ Because we leave old copies of the vertex in the priority queue\n\t\/\/ (with outdated higher distances), we need to ignore it when we come\n\t\/\/ across it again, by checking its distance against the minimum distance\n\tif (dist > min_distance[u])\n\t continue;\n\n \/\/ Visit each edge exiting u\n\tconst std::vector &neighbors = adjacency_list[u];\n for (std::vector::const_iterator neighbor_iter = neighbors.begin();\n neighbor_iter != neighbors.end();\n neighbor_iter++)\n {\n vertex_t v = neighbor_iter->target;\n weight_t weight = neighbor_iter->weight;\n weight_t distance_through_u = dist + weight;\n\t if (distance_through_u < min_distance[v]) {\n\t min_distance[v] = distance_through_u;\n\t previous[v] = u;\n\t vertex_queue.push(std::make_pair(min_distance[v], v));\n\n\t }\n\n }\n }\n}\n\n\nstd::list DijkstraGetShortestPathTo(\n vertex_t vertex, const std::vector &previous)\n{\n std::list path;\n for ( ; vertex != -1; vertex = previous[vertex])\n path.push_front(vertex);\n return path;\n}\n\n\nint main()\n{\n \/\/ remember to insert edges both ways for an undirected graph\n adjacency_list_t adjacency_list(6);\n \/\/ 0 = a\n adjacency_list[0].push_back(neighbor(1, 7));\n adjacency_list[0].push_back(neighbor(2, 9));\n adjacency_list[0].push_back(neighbor(5, 14));\n \/\/ 1 = b\n adjacency_list[1].push_back(neighbor(0, 7));\n adjacency_list[1].push_back(neighbor(2, 10));\n adjacency_list[1].push_back(neighbor(3, 15));\n \/\/ 2 = c\n adjacency_list[2].push_back(neighbor(0, 9));\n adjacency_list[2].push_back(neighbor(1, 10));\n adjacency_list[2].push_back(neighbor(3, 11));\n adjacency_list[2].push_back(neighbor(5, 2));\n \/\/ 3 = d\n adjacency_list[3].push_back(neighbor(1, 15));\n adjacency_list[3].push_back(neighbor(2, 11));\n adjacency_list[3].push_back(neighbor(4, 6));\n \/\/ 4 = e\n adjacency_list[4].push_back(neighbor(3, 6));\n adjacency_list[4].push_back(neighbor(5, 9));\n \/\/ 5 = f\n adjacency_list[5].push_back(neighbor(0, 14));\n adjacency_list[5].push_back(neighbor(2, 2));\n adjacency_list[5].push_back(neighbor(4, 9));\n\n std::vector min_distance;\n std::vector previous;\n DijkstraComputePaths(0, adjacency_list, min_distance, previous);\n std::cout << \"Distance from 0 to 4: \" << min_distance[4] << std::endl;\n std::list path = DijkstraGetShortestPathTo(4, previous);\n std::cout << \"Path\u00a0: \";\n std::copy(path.begin(), path.end(), std::ostream_iterator(std::cout, \" \"));\n std::cout << std::endl;\n\n return 0;\n}\n\n","human_summarization":"The code implements Dijkstra's algorithm to find the shortest path between a given source node and all other nodes in a graph. The graph is represented by an adjacency matrix or list and a start node. The algorithm is applied on a directed and weighted graph with non-negative edge path costs. The output is a set of edges depicting the shortest path to each destination node. The code also includes functionality to interpret the output and provide the shortest path from the source node to specific nodes. The algorithm is optimized using a self-balancing binary search tree for the priority queue of vertices, ensuring a time complexity of O(E log V).","id":774} {"lang_cluster":"C++","source_code":"#include \n#include \n\n\/* AVL node *\/\ntemplate \nclass AVLnode {\npublic:\n T key;\n int balance;\n AVLnode *left, *right, *parent;\n\n AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),\n left(NULL), right(NULL) {}\n\n ~AVLnode() {\n delete left;\n delete right;\n }\n};\n\n\/* AVL tree *\/\ntemplate \nclass AVLtree {\npublic:\n AVLtree(void);\n ~AVLtree(void);\n bool insert(T key);\n void deleteKey(const T key);\n void printBalance();\n\nprivate:\n AVLnode *root;\n\n AVLnode* rotateLeft ( AVLnode *a );\n AVLnode* rotateRight ( AVLnode *a );\n AVLnode* rotateLeftThenRight ( AVLnode *n );\n AVLnode* rotateRightThenLeft ( AVLnode *n );\n void rebalance ( AVLnode *n );\n int height ( AVLnode *n );\n void setBalance ( AVLnode *n );\n void printBalance ( AVLnode *n );\n};\n\n\/* AVL class definition *\/\ntemplate \nvoid AVLtree::rebalance(AVLnode *n) {\n setBalance(n);\n\n if (n->balance == -2) {\n if (height(n->left->left) >= height(n->left->right))\n n = rotateRight(n);\n else\n n = rotateLeftThenRight(n);\n }\n else if (n->balance == 2) {\n if (height(n->right->right) >= height(n->right->left))\n n = rotateLeft(n);\n else\n n = rotateRightThenLeft(n);\n }\n\n if (n->parent != NULL) {\n rebalance(n->parent);\n }\n else {\n root = n;\n }\n}\n\ntemplate \nAVLnode* AVLtree::rotateLeft(AVLnode *a) {\n AVLnode *b = a->right;\n b->parent = a->parent;\n a->right = b->left;\n\n if (a->right != NULL)\n a->right->parent = a;\n\n b->left = a;\n a->parent = b;\n\n if (b->parent != NULL) {\n if (b->parent->right == a) {\n b->parent->right = b;\n }\n else {\n b->parent->left = b;\n }\n }\n\n setBalance(a);\n setBalance(b);\n return b;\n}\n\ntemplate \nAVLnode* AVLtree::rotateRight(AVLnode *a) {\n AVLnode *b = a->left;\n b->parent = a->parent;\n a->left = b->right;\n\n if (a->left != NULL)\n a->left->parent = a;\n\n b->right = a;\n a->parent = b;\n\n if (b->parent != NULL) {\n if (b->parent->right == a) {\n b->parent->right = b;\n }\n else {\n b->parent->left = b;\n }\n }\n\n setBalance(a);\n setBalance(b);\n return b;\n}\n\ntemplate \nAVLnode* AVLtree::rotateLeftThenRight(AVLnode *n) {\n n->left = rotateLeft(n->left);\n return rotateRight(n);\n}\n\ntemplate \nAVLnode* AVLtree::rotateRightThenLeft(AVLnode *n) {\n n->right = rotateRight(n->right);\n return rotateLeft(n);\n}\n\ntemplate \nint AVLtree::height(AVLnode *n) {\n if (n == NULL)\n return -1;\n return 1 + std::max(height(n->left), height(n->right));\n}\n\ntemplate \nvoid AVLtree::setBalance(AVLnode *n) {\n n->balance = height(n->right) - height(n->left);\n}\n\ntemplate \nvoid AVLtree::printBalance(AVLnode *n) {\n if (n != NULL) {\n printBalance(n->left);\n std::cout << n->balance << \" \";\n printBalance(n->right);\n }\n}\n\ntemplate \nAVLtree::AVLtree(void) : root(NULL) {}\n\ntemplate \nAVLtree::~AVLtree(void) {\n delete root;\n}\n\ntemplate \nbool AVLtree::insert(T key) {\n if (root == NULL) {\n root = new AVLnode(key, NULL);\n }\n else {\n AVLnode\n *n = root,\n *parent;\n\n while (true) {\n if (n->key == key)\n return false;\n\n parent = n;\n\n bool goLeft = n->key > key;\n n = goLeft ? n->left : n->right;\n\n if (n == NULL) {\n if (goLeft) {\n parent->left = new AVLnode(key, parent);\n }\n else {\n parent->right = new AVLnode(key, parent);\n }\n\n rebalance(parent);\n break;\n }\n }\n }\n\n return true;\n}\n\ntemplate \nvoid AVLtree::deleteKey(const T delKey) {\n if (root == NULL)\n return;\n\n AVLnode\n *n = root,\n *parent = root,\n *delNode = NULL,\n *child = root;\n\n while (child != NULL) {\n parent = n;\n n = child;\n child = delKey >= n->key ? n->right : n->left;\n if (delKey == n->key)\n delNode = n;\n }\n\n if (delNode != NULL) {\n delNode->key = n->key;\n\n child = n->left != NULL ? n->left : n->right;\n\n if (root->key == delKey) {\n root = child;\n }\n else {\n if (parent->left == n) {\n parent->left = child;\n }\n else {\n parent->right = child;\n }\n\n rebalance(parent);\n }\n }\n}\n\ntemplate \nvoid AVLtree::printBalance() {\n printBalance(root);\n std::cout << std::endl;\n}\n\nint main(void)\n{\n AVLtree t;\n\n std::cout << \"Inserting integer values 1 to 10\" << std::endl;\n for (int i = 1; i <= 10; ++i)\n t.insert(i);\n\n std::cout << \"Printing balance: \";\n t.printBalance();\n}\n\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree, ensuring the heights of two child subtrees of any node differ by at most one. The codes provide basic operations including lookup, insertion, and deletion, all of which take O(log n) time. The tree is rebalanced as necessary through tree rotations. Duplicate node keys are not allowed. The implementation is compared with red-black trees for performance analysis.","id":775} {"lang_cluster":"C++","source_code":"\nWorks with: C++11\n#include \n#include \n#include \n\nstruct point { double x, y; };\n\nbool operator==(const point& lhs, const point& rhs)\n{ return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y); }\n\nenum result_category { NONE, ONE_COINCEDENT, ONE_DIAMETER, TWO, INFINITE };\n\nusing result_t = std::tuple;\n\ndouble distance(point l, point r)\n{ return std::hypot(l.x - r.x, l.y - r.y); }\n\nresult_t find_circles(point p1, point p2, double r)\n{\n point ans1 { 1\/0., 1\/0.}, ans2 { 1\/0., 1\/0.};\n if (p1 == p2) {\n if(r == 0.) return std::make_tuple(ONE_COINCEDENT, p1, p2 );\n else return std::make_tuple(INFINITE, ans1, ans2);\n }\n point center { p1.x\/2 + p2.x\/2, p1.y\/2 + p2.y\/2};\n double half_distance = distance(center, p1);\n if(half_distance > r) return std::make_tuple(NONE, ans1, ans2);\n if(half_distance - r == 0) return std::make_tuple(ONE_DIAMETER, center, ans2);\n double root = sqrt(pow(r, 2.l) - pow(half_distance, 2.l)) \/ distance(p1, p2);\n ans1.x = center.x + root * (p1.y - p2.y);\n ans1.y = center.y + root * (p2.x - p1.x);\n ans2.x = center.x - root * (p1.y - p2.y);\n ans2.y = center.y - root * (p2.x - p1.x);\n return std::make_tuple(TWO, ans1, ans2);\n}\n\nvoid print(result_t result, std::ostream& out = std::cout)\n{\n point r1, r2; result_category res;\n std::tie(res, r1, r2) = result;\n switch(res) {\n case NONE:\n out << \"There are no solutions, points are too far away\\n\"; break;\n case ONE_COINCEDENT: case ONE_DIAMETER:\n out << \"Only one solution: \" << r1.x << ' ' << r1.y << '\\n'; break;\n case INFINITE:\n out << \"Infinitely many circles can be drawn\\n\"; break;\n case TWO:\n out << \"Two solutions: \" << r1.x << ' ' << r1.y << \" and \" << r2.x << ' ' << r2.y << '\\n'; break;\n }\n}\n\nint main()\n{\n constexpr int size = 5;\n const point points[size*2] = {\n {0.1234, 0.9876}, {0.8765, 0.2345}, {0.0000, 2.0000}, {0.0000, 0.0000},\n {0.1234, 0.9876}, {0.1234, 0.9876}, {0.1234, 0.9876}, {0.8765, 0.2345},\n {0.1234, 0.9876}, {0.1234, 0.9876}\n };\n const double radius[size] = {2., 1., 2., .5, 0.};\n\n for(int i = 0; i < size; ++i)\n print(find_circles(points[i*2], points[i*2 + 1], radius[i]));\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":776} {"lang_cluster":"C++","source_code":"\nUINT_64 TGost::SWAP32(UINT_32 N1, UINT_32 N2)\n{\n UINT_64 N;\n\tN = N1;\n\tN = (N<<32)|N2;\n\treturn UINT_64(N);\n}\n\nUINT_32 TGost::ReplaceBlock(UINT_32 x)\n{ \n register i;\n UINT_32 res = 0UL;\n for(i=7;i>=0;i--)\n {\n ui4_0 = x>>(i*4);\n ui4_0 = BS[ui4_0][i];\n res = (res<<4)|ui4_0;\n }\n return res;\n}\n\nUINT_64 TGost::MainStep(UINT_64 N,UINT_32 X)\n{\n UINT_32 N1,N2,S=0UL;\n N1=UINT_32(N);\n N2=N>>32;\n S = N1 + X % 0x4000000000000;\n S = ReplaceBlock(S);\n S = (S<<11)|(S>>21);\n S ^= N2;\n N2 = N1;\n N1 = S;\n return SWAP32(N2,N1);\n}\n\n\n","human_summarization":"implement the main step of the GOST 28147-89 encryption algorithm, which takes a 64-bit block of text and one of the eight 32-bit encryption key elements, uses the replacement table (BS), and returns an encrypted block.","id":777} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n\nint main(){\n\tsrand(time(NULL)); \/\/ randomize seed\n\twhile(true){\n\t\tconst int a = rand() % 20; \/\/ biased towards lower numbers if RANDMAX\u00a0% 20 > 0\n\t\tstd::cout << a << std::endl;\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tconst int b = rand() % 20;\n\t\tstd::cout << b << std::endl;\n\t}\n\treturn 0;\n}\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":778} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\ntypedef uint64_t integer;\n\ninteger bit_count(integer n) {\n integer count = 0;\n for (; n > 0; count++)\n n >>= 1;\n return count;\n}\n\ninteger mod_pow(integer p, integer n) {\n integer square = 1;\n for (integer bits = bit_count(p); bits > 0; square %= n) {\n square *= square;\n if (p & (1 << --bits))\n square <<= 1;\n }\n return square;\n}\n\nbool is_prime(integer n) {\n if (n < 2)\n return false;\n if (n % 2 == 0)\n return n == 2;\n for (integer p = 3; p * p <= n; p += 2)\n if (n % p == 0)\n return false;\n return true;\n}\n\ninteger find_mersenne_factor(integer p) {\n for (integer k = 0, q = 1;;) {\n q = 2 * ++k * p + 1;\n if ((q % 8 == 1 || q % 8 == 7) && mod_pow(p, q) == 1 && is_prime(q))\n return q;\n }\n return 0;\n}\n\nint main() {\n std::cout << find_mersenne_factor(929) << std::endl;\n return 0;\n}\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":779} {"lang_cluster":"C++","source_code":"\n\nLibrary: LibXML\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef LIBXML_XPATH_ENABLED\n# error libxml was not configured with XPath support\n#endif\n\n\/\/ Because libxml2 is a C library, we need a couple things to make it work\n\/\/ well with modern C++:\n\/\/ 1) a ScopeGuard-like type to handle cleanup functions; and\n\/\/ 2) an exception type that transforms the library's errors.\n\n\/\/ ScopeGuard-like type to handle C library cleanup functions.\ntemplate \nclass [[nodiscard]] scope_exit\n{\npublic:\n \/\/ C++20: Constructor can (and should) be [[nodiscard]].\n \/*[[nodiscard]]*\/ constexpr explicit scope_exit(F&& f) :\n f_{std::move(f)}\n {}\n\n ~scope_exit()\n {\n f_();\n }\n\n \/\/ Non-copyable, non-movable.\n scope_exit(scope_exit const&) = delete;\n scope_exit(scope_exit&&) = delete;\n auto operator=(scope_exit const&) -> scope_exit& = delete;\n auto operator=(scope_exit&&) -> scope_exit& = delete;\n\nprivate:\n F f_;\n};\n\n\/\/ Exception that gets last libxml2 error.\nclass libxml_error : public std::runtime_error\n{\npublic:\n libxml_error() : libxml_error(std::string{}) {}\n\n explicit libxml_error(std::string message) :\n std::runtime_error{make_message_(std::move(message))}\n {}\n\nprivate:\n static auto make_message_(std::string message) -> std::string\n {\n if (auto const last_error = ::xmlGetLastError(); last_error)\n {\n if (not message.empty())\n message += \": \";\n message += last_error->message;\n }\n\n return message;\n }\n};\n\nauto main() -> int\n{\n try\n {\n \/\/ Initialize libxml.\n ::xmlInitParser();\n LIBXML_TEST_VERSION\n auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};\n\n \/\/ Load and parse XML document.\n auto const doc = ::xmlParseFile(\"test.xml\");\n if (not doc)\n throw libxml_error{\"failed to load document\"};\n auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};\n\n \/\/ Create XPath context for document.\n auto const xpath_context = ::xmlXPathNewContext(doc);\n if (not xpath_context)\n throw libxml_error{\"failed to create XPath context\"};\n auto const xpath_context_cleanup = scope_exit{[xpath_context]\n { ::xmlXPathFreeContext(xpath_context); }};\n\n \/\/ Task 1 ============================================================\n {\n std::cout << \"Task 1:\\n\";\n\n auto const xpath =\n reinterpret_cast<::xmlChar const*>(u8\"\/\/item[1]\");\n\n \/\/ Create XPath object (same for every task).\n auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context);\n if (not xpath_obj)\n throw libxml_error{\"failed to evaluate XPath\"};\n auto const xpath_obj_cleanup = scope_exit{[xpath_obj]\n { ::xmlXPathFreeObject(xpath_obj); }};\n\n \/\/ 'result' a xmlNode* to the desired node, or nullptr if it\n \/\/ doesn't exist. If not nullptr, the node is owned by 'doc'.\n auto const result = xmlXPathNodeSetItem(xpath_obj->nodesetval, 0);\n if (result)\n std::cout << '\\t' << \"node found\" << '\\n';\n else\n std::cout << '\\t' << \"node not found\" << '\\n';\n }\n\n \/\/ Task 2 ============================================================\n {\n std::cout << \"Task 2:\\n\";\n\n auto const xpath =\n reinterpret_cast<::xmlChar const*>(u8\"\/\/price\/text()\");\n\n \/\/ Create XPath object (same for every task).\n auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context);\n if (not xpath_obj)\n throw libxml_error{\"failed to evaluate XPath\"};\n auto const xpath_obj_cleanup = scope_exit{[xpath_obj]\n { ::xmlXPathFreeObject(xpath_obj); }};\n\n \/\/ Printing the results.\n auto const count =\n xmlXPathNodeSetGetLength(xpath_obj->nodesetval);\n for (auto i = decltype(count){0}; i < count; ++i)\n {\n auto const node =\n xmlXPathNodeSetItem(xpath_obj->nodesetval, i);\n assert(node);\n\n auto const content = XML_GET_CONTENT(node);\n assert(content);\n\n \/\/ Note that reinterpret_cast here is a Bad Idea, because\n \/\/ 'content' is UTF-8 encoded, which may or may not be the\n \/\/ encoding cout expects. A *PROPER* solution would translate\n \/\/ content to the correct encoding (or at least verify that\n \/\/ UTF-8 *is* the correct encoding).\n \/\/\n \/\/ But this \"works\" well enough for illustration.\n std::cout << \"\\n\\t\" << reinterpret_cast(content);\n }\n\n std::cout << '\\n';\n }\n\n \/\/ Task 3 ============================================================\n {\n std::cout << \"Task 3:\\n\";\n\n auto const xpath =\n reinterpret_cast<::xmlChar const*>(u8\"\/\/name\");\n\n \/\/ Create XPath object (same for every task).\n auto xpath_obj = ::xmlXPathEvalExpression(xpath, xpath_context);\n if (not xpath_obj)\n throw libxml_error{\"failed to evaluate XPath\"};\n auto const xpath_obj_cleanup = scope_exit{[xpath_obj]\n { ::xmlXPathFreeObject(xpath_obj); }};\n\n \/\/ 'results' is a vector of pointers to the result nodes. The\n \/\/ nodes pointed to are owned by 'doc'.\n auto const results = [ns=xpath_obj->nodesetval]()\n {\n auto v = std::vector<::xmlNode*>{};\n if (ns && ns->nodeTab)\n v.assign(ns->nodeTab, ns->nodeTab + ns->nodeNr);\n return v;\n }();\n std::cout << '\\t' << \"set of \" << results.size()\n << \" node(s) found\" << '\\n';\n }\n }\n catch (std::exception const& x)\n {\n std::cerr << \"ERROR: \" << x.what() << '\\n';\n return EXIT_FAILURE;\n }\n}\n\n","human_summarization":"1. Retrieves the first \"item\" element from an XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Generates an array of all the \"name\" elements in the XML document.","id":780} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n#include \n\nnamespace set_display {\ntemplate \nstd::ostream& operator<<(std::ostream& os, const std::set& set)\n{\n os << '[';\n if (!set.empty()) {\n std::copy(set.begin(), --set.end(), std::ostream_iterator(os, \", \"));\n os << *--set.end();\n }\n return os << ']';\n}\n}\n\ntemplate \nbool contains(const std::set& set, const T& key)\n{\n return set.count(key) != 0;\n}\n\ntemplate \nstd::set set_union(const std::set& a, const std::set& b)\n{\n std::set result;\n std::set_union(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.end()));\n return result;\n}\n\ntemplate \nstd::set set_intersection(const std::set& a, const std::set& b)\n{\n std::set result;\n std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.end()));\n return result;\n}\n\ntemplate \nstd::set set_difference(const std::set& a, const std::set& b)\n{\n std::set result;\n std::set_difference(a.begin(), a.end(), b.begin(), b.end(), std::inserter(result, result.end()));\n return result;\n}\n\ntemplate \nbool is_subset(const std::set& set, const std::set& subset)\n{\n return std::includes(set.begin(), set.end(), subset.begin(), subset.end());\n}\n\nint main()\n{\n using namespace set_display;\n std::set a{2, 5, 7, 5, 9, 2}; \/\/C++11 initialization syntax\n std::set b{1, 5, 9, 7, 4 };\n std::cout << \"a = \" << a << '\\n';\n std::cout << \"b = \" << b << '\\n';\n\n int value1 = 8, value2 = 5;\n std::cout << \"Set a \" << (contains(a, value1) ? \"contains \" : \"does not contain \") << value1 << '\\n';\n std::cout << \"Set a \" << (contains(a, value2) ? \"contains \" : \"does not contain \") << value2 << '\\n';\n\n std::cout << \"Union of a and b: \" << set_union(a, b) << '\\n';\n std::cout << \"Intersection of a and b: \" << set_intersection(a, b) << '\\n';\n std::cout << \"Difference of a and b: \" << set_difference(a, b) << '\\n';\n\n std::set sub{5, 9};\n std::cout << \"Set b \" << (is_subset(a, b) ? \"is\" : \"is not\") << \" a subset of a\\n\";\n std::cout << \"Set \" << sub << ' ' << (is_subset(a, sub) ? \"is\" : \"is not\") << \" a subset of a\\n\";\n\n std::set copy = a;\n std::cout << \"a \" << (a == copy ? \"equals \" : \"does not equal \") << copy << '\\n';\n\n return 0;\n}\n\n","human_summarization":"demonstrate various set operations including set creation, testing for an element in a set, performing union, intersection, and difference operations between two sets, checking for subset and equality between two sets. The code also optionally shows other set operations and methods to modify a mutable set. The set implementation could be done using an associative array, a binary search tree, a hash table, or an ordered array of binary bits. The code also makes use of the C++ standard library's set class and unordered_set.","id":781} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n\nint main() {\n std::cout << \"Yuletide holidays must be allowed in the following years:\\n\";\n for (int year : std::views::iota(2008, 2121)\n | std::views::filter([](auto year) {\n if (std::chrono::weekday{\n std::chrono::year{year}\/std::chrono::December\/25}\n == std::chrono::Sunday) {\n return true;\n }\n return false;\n })) {\n std::cout << year << '\\n';\n }\n}\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":782} {"lang_cluster":"C++","source_code":"\n\/*\n * g++ -O3 -Wall --std=c++11 qr_standalone.cpp -o qr_standalone\n *\/\n#include \n#include \n#include \/\/ for memset\n#include \n#include \n#include \n\n#include \n\nclass Vector;\n\nclass Matrix {\n\npublic:\n \/\/ default constructor (don't allocate)\n Matrix() : m(0), n(0), data(nullptr) {}\n \n \/\/ constructor with memory allocation, initialized to zero\n Matrix(int m_, int n_) : Matrix() {\n m = m_;\n n = n_;\n allocate(m_,n_);\n }\n\n \/\/ copy constructor\n Matrix(const Matrix& mat) : Matrix(mat.m,mat.n) {\n\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++)\n\t(*this)(i,j) = mat(i,j);\n }\n \n \/\/ constructor from array\n template\n Matrix(double (&a)[rows][cols]) : Matrix(rows,cols) {\n\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++)\n\t(*this)(i,j) = a[i][j];\n }\n\n \/\/ destructor\n ~Matrix() {\n deallocate();\n }\n\n\n \/\/ access data operators\n double& operator() (int i, int j) {\n return data[i+m*j]; }\n double operator() (int i, int j) const {\n return data[i+m*j]; }\n\n \/\/ operator assignment\n Matrix& operator=(const Matrix& source) {\n \n \/\/ self-assignment check\n if (this != &source) { \n if ( (m*n) != (source.m * source.n) ) { \/\/ storage cannot be reused\n\tallocate(source.m,source.n); \/\/ re-allocate storage\n }\n \/\/ storage can be used, copy data\n std::copy(source.data, source.data + source.m*source.n, data);\n }\n return *this;\n }\n \n \/\/ compute minor\n void compute_minor(const Matrix& mat, int d) {\n\n allocate(mat.m, mat.n);\n \n for (int i = 0; i < d; i++)\n (*this)(i,i) = 1.0;\n for (int i = d; i < mat.m; i++)\n for (int j = d; j < mat.n; j++)\n\t(*this)(i,j) = mat(i,j);\n \n }\n\n \/\/ Matrix multiplication\n \/\/ c = a * b\n \/\/ c will be re-allocated here\n void mult(const Matrix& a, const Matrix& b) {\n\n if (a.n != b.m) {\n std::cerr << \"Matrix multiplication not possible, sizes don't match\u00a0!\\n\";\n return;\n }\n\n \/\/ reallocate ourself if necessary i.e. current Matrix has not valid sizes\n if (a.m != m or b.n != n)\n allocate(a.m, b.n);\n\n memset(data,0,m*n*sizeof(double));\n \n for (int i = 0; i < a.m; i++)\n for (int j = 0; j < b.n; j++)\n\tfor (int k = 0; k < a.n; k++)\n\t (*this)(i,j) += a(i,k) * b(k,j);\n \n }\n\n void transpose() {\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < i; j++) {\n\tdouble t = (*this)(i,j);\n\t(*this)(i,j) = (*this)(j,i);\n\t(*this)(j,i) = t;\n }\n }\n }\n\n \/\/ take c-th column of m, put in v\n void extract_column(Vector& v, int c); \n\n \/\/ memory allocation\n void allocate(int m_, int n_) {\n\n \/\/ if already allocated, memory is freed\n deallocate();\n \n \/\/ new sizes\n m = m_;\n n = n_;\n \n data = new double[m_*n_];\n memset(data,0,m_*n_*sizeof(double));\n\n } \/\/ allocate\n\n \/\/ memory free\n void deallocate() {\n\n if (data)\n delete[] data;\n\n data = nullptr;\n\n } \n \n int m, n;\n \nprivate:\n double* data;\n \n}; \/\/ struct Matrix\n\n\/\/ column vector\nclass Vector {\n\npublic:\n \/\/ default constructor (don't allocate)\n Vector() : size(0), data(nullptr) {}\n \n \/\/ constructor with memory allocation, initialized to zero\n Vector(int size_) : Vector() {\n size = size_;\n allocate(size_);\n }\n\n \/\/ destructor\n ~Vector() {\n deallocate();\n }\n\n \/\/ access data operators\n double& operator() (int i) {\n return data[i]; }\n double operator() (int i) const {\n return data[i]; }\n\n \/\/ operator assignment\n Vector& operator=(const Vector& source) {\n \n \/\/ self-assignment check\n if (this != &source) { \n if ( size != (source.size) ) { \/\/ storage cannot be reused\n\tallocate(source.size); \/\/ re-allocate storage\n }\n \/\/ storage can be used, copy data\n std::copy(source.data, source.data + source.size, data);\n }\n return *this;\n }\n\n \/\/ memory allocation\n void allocate(int size_) {\n\n deallocate();\n \n \/\/ new sizes\n size = size_;\n \n data = new double[size_];\n memset(data,0,size_*sizeof(double));\n\n } \/\/ allocate\n\n \/\/ memory free\n void deallocate() {\n\n if (data)\n delete[] data;\n\n data = nullptr;\n\n } \n\n \/\/ ||x||\n double norm() {\n double sum = 0;\n for (int i = 0; i < size; i++) sum += (*this)(i) * (*this)(i);\n return sqrt(sum);\n }\n\n \/\/ divide data by factor\n void rescale(double factor) {\n for (int i = 0; i < size; i++) (*this)(i) \/= factor;\n }\n\n void rescale_unit() {\n double factor = norm();\n rescale(factor);\n }\n \n int size;\n \nprivate:\n double* data;\n\n}; \/\/ class Vector\n\n\/\/ c = a + b * s\nvoid vmadd(const Vector& a, const Vector& b, double s, Vector& c)\n{\n if (c.size != a.size or c.size != b.size) {\n std::cerr << \"[vmadd]: vector sizes don't match\\n\";\n return;\n }\n \n for (int i = 0; i < c.size; i++)\n c(i) = a(i) + s * b(i);\n}\n\n\/\/ mat = I - 2*v*v^T\n\/\/\u00a0!!! m is allocated here\u00a0!!!\nvoid compute_householder_factor(Matrix& mat, const Vector& v)\n{\n\n int n = v.size;\n mat.allocate(n,n);\n for (int i = 0; i < n; i++)\n for (int j = 0; j < n; j++)\n mat(i,j) = -2 * v(i) * v(j);\n for (int i = 0; i < n; i++)\n mat(i,i) += 1; \n}\n\n\/\/ take c-th column of a matrix, put results in Vector v\nvoid Matrix::extract_column(Vector& v, int c) {\n if (m != v.size) {\n std::cerr << \"[Matrix::extract_column]: Matrix and Vector sizes don't match\\n\";\n return;\n }\n \n for (int i = 0; i < m; i++)\n v(i) = (*this)(i,c);\n}\n\nvoid matrix_show(const Matrix& m, const std::string& str=\"\")\n{\n std::cout << str << \"\\n\";\n for(int i = 0; i < m.m; i++) {\n for (int j = 0; j < m.n; j++) {\n printf(\" %8.3f\", m(i,j));\n }\n printf(\"\\n\");\n }\n printf(\"\\n\");\n}\n\n\/\/ L2-norm ||A-B||^2\ndouble matrix_compare(const Matrix& A, const Matrix& B) {\n \/\/ matrices must have same size\n if (A.m != B.m or A.n != B.n)\n return std::numeric_limits::max();\n\n double res=0;\n for(int i = 0; i < A.m; i++) {\n for (int j = 0; j < A.n; j++) {\n res += (A(i,j)-B(i,j)) * (A(i,j)-B(i,j));\n }\n }\n\n res \/= A.m*A.n;\n return res;\n}\n\nvoid householder(Matrix& mat,\n\t\t Matrix& R,\n\t\t Matrix& Q)\n{\n\n int m = mat.m;\n int n = mat.n;\n\n \/\/ array of factor Q1, Q2, ... Qm\n std::vector qv(m);\n\n \/\/ temp array\n Matrix z(mat);\n Matrix z1;\n \n for (int k = 0; k < n && k < m - 1; k++) {\n\n Vector e(m), x(m);\n double a;\n \n \/\/ compute minor\n z1.compute_minor(z, k);\n \n \/\/ extract k-th column into x\n z1.extract_column(x, k);\n \n a = x.norm();\n if (mat(k,k) > 0) a = -a;\n \n for (int i = 0; i < e.size; i++)\n e(i) = (i == k) ? 1 : 0;\n\n \/\/ e = x + a*e\n vmadd(x, e, a, e);\n\n \/\/ e = e \/ ||e||\n e.rescale_unit();\n \n \/\/ qv[k] = I - 2 *e*e^T\n compute_householder_factor(qv[k], e);\n\n \/\/ z = qv[k] * z1\n z.mult(qv[k], z1);\n\n }\n \n Q = qv[0];\n\n \/\/ after this loop, we will obtain Q (up to a transpose operation)\n for (int i = 1; i < n && i < m - 1; i++) {\n\n z1.mult(qv[i], Q);\n Q = z1;\n \n }\n \n R.mult(Q, mat);\n Q.transpose();\n}\n \ndouble in[][3] = {\n { 12, -51, 4},\n { 6, 167, -68},\n { -4, 24, -41},\n { -1, 1, 0},\n { 2, 0, 3},\n};\n \nint main()\n{\n Matrix A(in); \n Matrix Q, R;\n\n matrix_show(A,\"A\"); \n\n \/\/ compute QR decompostion\n householder(A, R, Q);\n \n matrix_show(Q,\"Q\");\n matrix_show(R,\"R\");\n \n \/\/ compare Q*R to the original matrix A\n Matrix A_check;\n A_check.mult(Q, R);\n\n \/\/ compute L2 norm ||A-A_check||^2\n double l2 = matrix_compare(A,A_check);\n\n \/\/ display Q*R\n matrix_show(A_check, l2 < 1e-12 ? \"A == Q * R\u00a0? yes\" : \"A == Q * R\u00a0? no\");\n \n return EXIT_SUCCESS;\n}\n\n\n","human_summarization":"The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.","id":783} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \nusing namespace std;\n\nint main() {\n typedef set TySet;\n int data[] = {1, 2, 3, 2, 3, 4};\n\n TySet unique_set(data, data + 6);\n\n cout << \"Set items:\" << endl;\n for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n cout << *iter << \" \";\n cout << endl;\n}\n\n\nWorks with: GCC\n#include \n#include \nusing namespace std;\n\nint main() {\n typedef __gnu_cxx::hash_set TyHash;\n int data[] = {1, 2, 3, 2, 3, 4};\n\n TyHash unique_set(data, data + 6);\n\n cout << \"Set items:\" << endl;\n for (TyHash::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n cout << *iter << \" \";\n cout << endl;\n}\n\n\nWorks with: GCC\n#include \n#include \nusing namespace std;\n\nint main() {\n typedef tr1::unordered_set TyHash;\n int data[] = {1, 2, 3, 2, 3, 4};\n\n TyHash unique_set(data, data + 6);\n\n cout << \"Set items:\" << endl;\n for (TyHash::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)\n cout << *iter << \" \";\n cout << endl;\n}\n\n\n#include \n#include \n#include \n\n\/\/ helper template\ntemplate T* end(T (&array)[size]) { return array+size; }\n\nint main()\n{\n int data[] = { 1, 2, 3, 2, 3, 4 };\n std::sort(data, end(data));\n int* new_end = std::unique(data, end(data));\n std::copy(data, new_end, std::ostream_iterator(std::cout, \" \");\n std::cout << std::endl;\n}\n\n\nWorks with: C++11\n#include \n#include \n#include \n\nint main() {\n std::vector data = {1, 2, 3, 2, 3, 4};\n\n std::sort(data.begin(), data.end());\n data.erase(std::unique(data.begin(), data.end()), data.end());\n\n for(int& i: data) std::cout << i << \" \";\n std::cout << std::endl;\n return 0;\n}\n\n","human_summarization":"The code removes duplicate elements from an array using three different methods: using a hash table, sorting the elements and removing consecutive duplicates, and iterating through the list to check for duplicates. It also includes versions using std::set, hash_set, and unordered_set, as well as an alternative method that works directly on the array using sort, unique, and erase on a vector.","id":784} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \/\/ for std::partition\n#include \/\/ for std::less\n\n\/\/ helper function for median of three\ntemplate\n T median(T t1, T t2, T t3)\n{\n if (t1 < t2)\n {\n if (t2 < t3)\n return t2;\n else if (t1 < t3)\n return t3;\n else\n return t1;\n }\n else\n {\n if (t1 < t3)\n return t1;\n else if (t2 < t3)\n return t3;\n else\n return t2;\n }\n}\n\n\/\/ helper object to get <= from <\ntemplate struct non_strict_op:\n public std::binary_function\n{\n non_strict_op(Order o): order(o) {}\n bool operator()(typename Order::second_argument_type arg1,\n typename Order::first_argument_type arg2) const\n {\n return !order(arg2, arg1);\n }\nprivate:\n Order order;\n};\n\ntemplate non_strict_op non_strict(Order o)\n{\n return non_strict_op(o);\n}\n\ntemplate\n void quicksort(RandomAccessIterator first, RandomAccessIterator last, Order order)\n{\n if (first != last && first+1 != last)\n {\n typedef typename std::iterator_traits::value_type value_type;\n RandomAccessIterator mid = first + (last - first)\/2;\n value_type pivot = median(*first, *mid, *(last-1));\n RandomAccessIterator split1 = std::partition(first, last, std::bind2nd(order, pivot));\n RandomAccessIterator split2 = std::partition(split1, last, std::bind2nd(non_strict(order), pivot));\n quicksort(first, split1, order);\n quicksort(split2, last, order);\n }\n}\n\ntemplate\n void quicksort(RandomAccessIterator first, RandomAccessIterator last)\n{\n quicksort(first, last, std::less::value_type>());\n}\n\n\n#include \n#include \/\/ for std::partition\n#include \/\/ for std::less\n\ntemplate\n void quicksort(RandomAccessIterator first, RandomAccessIterator last, Order order)\n{\n if (last - first > 1)\n {\n RandomAccessIterator split = std::partition(first+1, last, std::bind2nd(order, *first));\n std::iter_swap(first, split-1);\n quicksort(first, split-1, order);\n quicksort(split, last, order);\n }\n}\n\ntemplate\n void quicksort(RandomAccessIterator first, RandomAccessIterator last)\n{\n quicksort(first, last, std::less::value_type>());\n}\n\n","human_summarization":"implement the quicksort algorithm. The algorithm sorts an array or list by choosing a pivot element and dividing the rest of the elements into two partitions: one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include two versions of quicksort: one that uses a median-of-three pivot and works in place to avoid memory allocation, and a simpler version that uses the first element as the pivot.","id":785} {"lang_cluster":"C++","source_code":"\n\/\/ Display the current date in the formats of \"2007-11-10\"\n\/\/ and \"Sunday, November 10, 2007\". \n\n#include \n#include \n#include \n#include \n\n\/** Return the current date in a string, formatted as either ISO-8601\n * or \"Weekday-name, Month-name Day, Year\".\n *\n * The date is initialized when the object is created and will return\n * the same date for the lifetime of the object. The date returned\n * is the date in the local timezone.\n *\/\nclass Date\n{\n struct tm ltime;\n\npublic:\n \/\/\/ Default constructor.\n Date()\n {\n time_t t = time(0);\n localtime_r(&t, <ime);\n }\n \n \/** Return the date based on a format string. The format string is\n * fed directly into strftime(). See the strftime() documentation\n * for information on the proper construction of format strings.\n *\n * @param[in] fmt is a valid strftime() format string.\n *\n * @return a string containing the formatted date, or a blank string\n * if the format string was invalid or resulted in a string that\n * exceeded the internal buffer length.\n *\/\n std::string getDate(const char* fmt)\n {\n char out[200];\n size_t result = strftime(out, sizeof out, fmt, <ime);\n return std::string(out, out + result);\n }\n \n \/** Return the date in ISO-8601 date format.\n *\n * @return a string containing the date in ISO-8601 date format.\n *\/\n std::string getISODate() {return getDate(\"%F\");}\n \n \/** Return the date formatted as \"Weekday-name, Month-name Day, Year\".\n *\n * @return a string containing the date in the specified format.\n *\/\n std::string getTextDate() {return getDate(\"%A, %B %d, %Y\");}\n};\n\nint main()\n{\n Date d;\n std::cout << d.getISODate() << std::endl;\n std::cout << d.getTextDate() << std::endl;\n return 0;\n}\n\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":786} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n#include \ntypedef std::set set_type;\ntypedef std::set powerset_type;\n\npowerset_type powerset(set_type const& set)\n{\n typedef set_type::const_iterator set_iter;\n typedef std::vector vec;\n typedef vec::iterator vec_iter;\n\n struct local\n {\n static int dereference(set_iter v) { return *v; }\n };\n\n powerset_type result;\n\n vec elements;\n do\n {\n set_type tmp;\n std::transform(elements.begin(), elements.end(),\n std::inserter(tmp, tmp.end()),\n local::dereference);\n result.insert(tmp);\n if (!elements.empty() && ++elements.back() == set.end())\n {\n elements.pop_back();\n }\n else\n {\n set_iter iter;\n if (elements.empty())\n {\n iter = set.begin();\n }\n else\n {\n iter = elements.back();\n ++iter;\n }\n for (; iter != set.end(); ++iter)\n {\n elements.push_back(iter);\n }\n }\n } while (!elements.empty());\n\n return result;\n}\n\nint main()\n{\n int values[4] = { 2, 3, 5, 7 };\n set_type test_set(values, values+4);\n\n powerset_type test_powerset = powerset(test_set);\n\n for (powerset_type::iterator iter = test_powerset.begin();\n iter != test_powerset.end();\n ++iter)\n {\n std::cout << \"{ \";\n char const* prefix = \"\";\n for (set_type::iterator iter2 = iter->begin();\n iter2 != iter->end();\n ++iter2)\n {\n std::cout << prefix << *iter2;\n prefix = \", \";\n }\n std::cout << \" }\\n\";\n }\n}\n\n\n","human_summarization":"The code takes a set S as input and generates its power set. The power set includes all subsets of S, including the empty set and the set itself. The code also demonstrates the ability to handle edge cases such as the power set of an empty set and the power set of a set containing only the empty set.","id":787} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nstd::string to_roman(int value)\n{\n struct romandata_t { int value; char const* numeral; };\n static romandata_t const romandata[] =\n { 1000, \"M\",\n 900, \"CM\",\n 500, \"D\",\n 400, \"CD\",\n 100, \"C\",\n 90, \"XC\",\n 50, \"L\",\n 40, \"XL\",\n 10, \"X\",\n 9, \"IX\",\n 5, \"V\",\n 4, \"IV\",\n 1, \"I\",\n 0, NULL }; \/\/ end marker\n\n std::string result;\n for (romandata_t const* current = romandata; current->value > 0; ++current)\n {\n while (value >= current->value)\n {\n result += current->numeral;\n value -= current->value;\n }\n }\n return result;\n}\n\nint main()\n{\n for (int i = 1; i <= 4000; ++i)\n {\n std::cout << to_roman(i) << std::endl;\n }\n}\n\n#include \n#include \n\nstd::string to_roman(int x) {\n if (x <= 0)\n return \"Negative or zero!\";\n auto roman_digit = [](char one, char five, char ten, int x) {\n if (x <= 3)\n return std::string().assign(x, one);\n if (x <= 5)\n return std::string().assign(5 - x, one) + five;\n if (x <= 8)\n return five + std::string().assign(x - 5, one);\n return std::string().assign(10 - x, one) + ten;\n };\n if (x >= 1000)\n return x - 1000 > 0 ? \"M\" + to_roman(x - 1000) : \"M\";\n if (x >= 100) {\n auto s = roman_digit('C', 'D', 'M', x \/ 100);\n return x % 100 > 0 ? s + to_roman(x % 100) : s;\n }\n if (x >= 10) {\n auto s = roman_digit('X', 'L', 'C', x \/ 10);\n return x % 10 > 0 ? s + to_roman(x % 10) : s;\n }\n return roman_digit('I', 'V', 'X', x);\n}\n\nint main() {\n for (int i = 0; i < 2018; i++)\n std::cout << i << \" --> \" << to_roman(i) << std::endl;\n}\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":788} {"lang_cluster":"C++","source_code":"\nWorks with: C++11\n\n#include \n#include \n\n\/\/ These headers are only needed for the demonstration\n#include \n#include \n#include \n#include \n\n\/\/ This is a template function that works for any array-like object\ntemplate \nvoid demonstrate(Array& array)\n{\n \/\/ Array element access\n array[2] = \"Three\"; \/\/ Fast, but unsafe - if the index is out of bounds you\n \/\/ get undefined behaviour\n array.at(1) = \"Two\"; \/\/ *Slightly* less fast, but safe - if the index is out\n \/\/ of bounds, an exception is thrown\n \n \/\/ Arrays can be used with standard algorithms\n std::reverse(begin(array), end(array));\n std::for_each(begin(array), end(array),\n [](typename Array::value_type const& element) \/\/ in C++14, you can just use auto\n {\n std::cout << element << ' ';\n });\n \n std::cout << '\\n';\n}\n\nint main()\n{\n \/\/ Compile-time sized fixed-size array\n auto fixed_size_array = std::array{ \"One\", \"Four\", \"Eight\" };\n \/\/ If you do not supply enough elements, the remainder are default-initialized\n \n \/\/ Dynamic array\n auto dynamic_array = std::vector{ \"One\", \"Four\" };\n dynamic_array.push_back(\"Eight\"); \/\/ Dynamically grows to accept new element\n \n \/\/ All types of arrays can be used more or less interchangeably\n demonstrate(fixed_size_array);\n demonstrate(dynamic_array);\n}\n\n","human_summarization":"demonstrate the basic syntax of arrays in C++. It includes creating both fixed-length and dynamic arrays, assigning values to them, and retrieving an element. The code also showcases the use of std::array and std::vector, discussing their size allocation, memory placement, and additional functionalities. The code also refers to obsolete tasks related to array creation, value assignment, and element retrieval.","id":789} {"lang_cluster":"C++","source_code":"\nWorks with: g++ version 3.4.2\n#include \n#include \n#include \n\nusing namespace std;\n\nint main() {\n string line;\n ifstream input ( \"input.txt\" );\n ofstream output (\"output.txt\");\n \n if (output.is_open()) {\n if (input.is_open()){\n while (getline (input,line)) {\n output << line << endl;\n }\n input.close(); \/\/ Not necessary - will be closed when variable goes out of scope.\n }\n else {\n cout << \"input.txt cannot be opened!\\n\";\n }\n output.close(); \/\/ Not necessary - will be closed when variable goes out of scope.\n }\n else {\n cout << \"output.txt cannot be written to!\\n\";\n }\n return 0;\n}\n\n\n#include \n#include \n#include \n\nint main()\n{\n std::ifstream input(\"input.txt\");\n if (!input.is_open())\n {\n std::cerr << \"could not open input.txt for reading.\\n\";\n return EXIT_FAILURE;\n }\n \n std::ofstream output(\"output.txt\");\n if (!output.is_open())\n {\n std::cerr << \"could not open output.txt for writing.\\n\";\n return EXIT_FAILURE;\n }\n \n output << input.rdbuf();\n if (!output)\n {\n std::cerr << \"error copying the data.\\n\";\n return EXIT_FAILURE;\n }\n \n return EXIT_SUCCESS;\n}\n\n\n# include \n# include \n\nint main() {\n std::ifstream ifile(\"input.txt\");\n std::ofstream ofile(\"output.txt\");\n std::copy(std::istreambuf_iterator(ifile),\n std::istreambuf_iterator(),\n std::ostreambuf_iterator(ofile));\n}\n\n\n#include \n\nint main()\n{\n std::ifstream input(\"input.txt\");\n std::ofstream output(\"output.txt\");\n output << input.rdbuf();\n}\n\n","human_summarization":"demonstrate how to read the contents of \"input.txt\" file into a variable and then write this variable's contents into a new file called \"output.txt\". The codes also show the usage of istream and ostream iterators. The use of oneliners that skip the intermediate variable is also explored, although it's of secondary interest.","id":790} {"lang_cluster":"C++","source_code":"\nWorks with: g++ version 3.4.4 (cygming special)\nLibrary: STL\n\n#include \n#include \n#include \n\n\/\/\/ \\brief in-place convert string to upper case\n\/\/\/ \\return ref to transformed string\nvoid str_toupper(std::string &str) {\n std::transform(str.begin(), \n str.end(), \n str.begin(),\n (int(*)(int)) std::toupper);\n}\n\n\/\/\/ \\brief in-place convert string to lower case\n\/\/\/ \\return ref to transformed string\nvoid str_tolower(std::string &str) {\n std::transform(str.begin(), \n str.end(), \n str.begin(),\n (int(*)(int)) std::tolower);\n}\n\n\n#include \n#include \n\nusing namespace std;\nint main() {\n string foo(\"_upperCas3Me!!\");\n str_toupper(foo);\n cout << foo << endl;\n str_tolower(foo);\n cout << foo << endl;\n return 0;\n}\n\n","human_summarization":"demonstrate how to convert the string \"alphaBETA\" to upper-case and lower-case using the default encoding of a string literal or plain ASCII. The codes also showcase additional case conversion functions such as swapping case, capitalizing the first letter, etc. The transformation is done in-place, but alternate methods may return a new copy or use a stream manipulator.","id":791} {"lang_cluster":"C++","source_code":"\n\/*\n\tAuthor: Kevin Bacon\n\tDate: 04\/03\/2014\n\tTask: Closest-pair problem\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef std::pair point_t;\ntypedef std::pair points_t;\n\ndouble distance_between(const point_t& a, const point_t& b) {\n\treturn std::sqrt(std::pow(b.first - a.first, 2)\n\t\t+ std::pow(b.second - a.second, 2));\n}\n\nstd::pair find_closest_brute(const std::vector& points) {\n\tif (points.size() < 2) {\n\t\treturn { -1, { { 0, 0 }, { 0, 0 } } };\n\t}\n\tauto minDistance = std::abs(distance_between(points.at(0), points.at(1)));\n\tpoints_t minPoints = { points.at(0), points.at(1) };\n\tfor (auto i = std::begin(points); i != (std::end(points) - 1); ++i) {\n\t\tfor (auto j = i + 1; j < std::end(points); ++j) {\n\t\t\tauto newDistance = std::abs(distance_between(*i, *j));\n\t\t\tif (newDistance < minDistance) {\n\t\t\t\tminDistance = newDistance;\n\t\t\t\tminPoints.first = *i;\n\t\t\t\tminPoints.second = *j;\n\t\t\t}\n\t\t}\n\t}\n\treturn { minDistance, minPoints };\n}\n\nstd::pair find_closest_optimized(const std::vector& xP,\n\tconst std::vector& yP) {\n\tif (xP.size() <= 3) {\n\t\treturn find_closest_brute(xP);\n\t}\n\tauto N = xP.size();\n\tauto xL = std::vector();\n\tauto xR = std::vector();\n\tstd::copy(std::begin(xP), std::begin(xP) + (N \/ 2), std::back_inserter(xL));\n\tstd::copy(std::begin(xP) + (N \/ 2), std::end(xP), std::back_inserter(xR));\n\tauto xM = xP.at((N-1) \/ 2).first;\n\tauto yL = std::vector();\n\tauto yR = std::vector();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) {\n\t\treturn p.first <= xM;\n\t});\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) {\n\t\treturn p.first > xM;\n\t});\n\tauto p1 = find_closest_optimized(xL, yL);\n\tauto p2 = find_closest_optimized(xR, yR);\n\tauto minPair = (p1.first <= p2.first) ? p1 : p2;\n\tauto yS = std::vector();\n\tstd::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) {\n\t\treturn std::abs(xM - p.first) < minPair.first;\n\t});\n\tauto result = minPair;\n\tfor (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) {\n\t\tfor (auto k = i + 1; k != std::end(yS) &&\n\t\t ((k->second - i->second) < minPair.first); ++k) {\n\t\t\tauto newDistance = std::abs(distance_between(*k, *i));\n\t\t\tif (newDistance < result.first) {\n\t\t\t\tresult = { newDistance, { *k, *i } };\n\t\t\t}\n\t\t}\n\t}\n\treturn result;\n}\n\nvoid print_point(const point_t& point) {\n\tstd::cout << \"(\" << point.first\n\t\t<< \", \" << point.second\n\t\t<< \")\";\n}\n\nint main(int argc, char * argv[]) {\n\tstd::default_random_engine re(std::chrono::system_clock::to_time_t(\n\t\tstd::chrono::system_clock::now()));\n\tstd::uniform_real_distribution urd(-500.0, 500.0);\n\tstd::vector points(100);\n\tstd::generate(std::begin(points), std::end(points), [&urd, &re]() {\n return point_t { 1000 + urd(re), 1000 + urd(re) };\n });\n\tauto answer = find_closest_brute(points);\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.first < b.first;\n\t});\n\tauto xP = points;\n\tstd::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) {\n\t\treturn a.second < b.second;\n\t});\n\tauto yP = points;\n\tstd::cout << \"Min distance (brute): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\tanswer = find_closest_optimized(xP, yP);\n\tstd::cout << \"\\nMin distance (optimized): \" << answer.first << \" \";\n\tprint_point(answer.second.first);\n\tstd::cout << \", \";\n\tprint_point(answer.second.second);\n\treturn 0;\n}\n\n\n","human_summarization":"provide two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute force algorithm with a complexity of O(n^2) to find the two closest points. The second function uses a recursive divide and conquer approach with a complexity of O(n log n) to find the two closest points. Both functions return the minimum distance and the pair of points.","id":792} {"lang_cluster":"C++","source_code":"\n\n\nint a[5]; \/\/ array of 5 ints (since int is POD, the members are not initialized)\na[0] = 1; \/\/ indexes start at 0\n\nint primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; \/\/ arrays can be initialized on creation\n\n#include \nstd::string strings[4]; \/\/ std::string is no POD, therefore all array members are default-initialized\n \/\/ (for std::string this means initialized with empty strings)\n\n\n#include \n\nstd::vector v; \/\/ empty vector\nv.push_back(5); \/\/ insert a 5 at the end\nv.insert(v.begin(), 7); \/\/ insert a 7 at the beginning\n\n\n#include \n\nstd::deque d; \/\/ empty deque\nd.push_back(5); \/\/ insert a 5 at the end\nd.push_front(7); \/\/ insert a 7 at the beginning\nd.insert(v.begin()+1, 6); \/\/ insert a 6 in the middle\n\n\n#include \n\nstd::list l; \/\/ empty list\nl.push_back(5); \/\/ insert a 5 at the end\nl.push_front(7); \/\/ insert a 7 at the beginning\nstd::list::iterator i = l.begin();\n++l;\nl.insert(i, 6); \/\/ insert a 6 in the middle\n\n\n#include \n\nstd::set s; \/\/ empty set\ns.insert(5); \/\/ insert a 5\ns.insert(7); \/\/ insert a 7 (automatically placed after the 5)\ns.insert(5); \/\/ try to insert another 5 (will not change the set)\n\nmulti\n#include \n\nstd::multiset m; \/\/ empty multiset\nm.insert(5); \/\/ insert a 5\nm.insert(7); \/\/ insert a 7 (automatically placed after the 5)\nm.insert(5); \/\/ insert a second 5 (now m contains two 5s, followed by one 7)\n\n","human_summarization":"demonstrate the creation and usage of various collections in C++. It includes the creation of a collection and adding values to it. The collections used include built-in arrays, vectors, deques, lists, sets, and multisets. The code also demonstrates the different optimizations and behaviors of these collections, such as resizable arrays, efficient access to elements, and sorted elements. It also covers the use of user-defined types in collections and the requirement for types to be copyable and assignable.","id":793} {"lang_cluster":"C++","source_code":"\n#include \n \nint main()\n{ \n int i;\n for (i = 1; i<=10 ; i++){\n std::cout << i;\n if (i < 10)\n std::cout << \", \";\n }\n return 0;\n}\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":794} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\ntemplate\nclass topological_sorter {\nprotected:\n struct relations {\n std::size_t dependencies;\n std::set dependents;\n };\n std::map map;\npublic:\n void add_goal(Goal const &goal) {\n map[goal];\n }\n void add_dependency(Goal const &goal, Goal const &dependency) {\n if (dependency == goal)\n return;\n auto &dependents = map[dependency].dependents;\n if (dependents.find(goal) == dependents.end()) {\n dependents.insert(goal);\n ++map[goal].dependencies;\n }\n }\n template\n void add_dependencies(Goal const &goal, Container const &dependencies) {\n for (auto const &dependency : dependencies)\n add_dependency(goal, dependency);\n }\n template\n void destructive_sort(ResultContainer &sorted, CyclicContainer &unsortable) {\n sorted.clear();\n unsortable.clear();\n for (auto const &lookup : map) {\n auto const &goal = lookup.first;\n auto const &relations = lookup.second;\n if (relations.dependencies == 0)\n sorted.push_back(goal);\n }\n for (std::size_t index = 0; index < sorted.size(); ++index)\n for (auto const &goal : map[sorted[index]].dependents)\n if (--map[goal].dependencies == 0)\n sorted.push_back(goal);\n for (auto const &lookup : map) {\n auto const &goal = lookup.first;\n auto const &relations = lookup.second;\n if (relations.dependencies != 0)\n unsortable.push_back(goal);\n }\n }\n template\n void sort(ResultContainer &sorted, CyclicContainer &unsortable) {\n topological_sorter temporary = *this;\n temporary.destructive_sort(sorted, unsortable);\n }\n void clear() {\n map.clear();\n }\n};\n\n\/*\n Example usage with text strings\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nvoid display_heading(string const &message) {\n cout << endl << \"~ \" << message << \" ~\" << endl;\n}\nvoid display_results(string const &input) {\n topological_sorter sorter;\n vector sorted, unsortable;\n stringstream lines(input);\n string line;\n while (getline(lines, line)) {\n stringstream buffer(line);\n string goal, dependency;\n buffer >> goal;\n sorter.add_goal(goal);\n while (buffer >> dependency)\n sorter.add_dependency(goal, dependency);\n }\n sorter.destructive_sort(sorted, unsortable);\n if (sorted.size() == 0)\n display_heading(\"Error: no independent variables found!\");\n else {\n display_heading(\"Result\");\n for (auto const &goal : sorted)\n cout << goal << endl;\n }\n if (unsortable.size() != 0) {\n display_heading(\"Error: cyclic dependencies detected!\");\n for (auto const &goal : unsortable)\n cout << goal << endl;\n }\n}\nint main(int argc, char **argv) {\n if (argc == 1) {\n string example = \"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\\n\"\n \"dw01 ieee dw01 dware gtech\\n\"\n \"dw02 ieee dw02 dware\\n\"\n \"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\\n\"\n \"dw04 dw04 ieee dw01 dware gtech\\n\"\n \"dw05 dw05 ieee dware\\n\"\n \"dw06 dw06 ieee dware\\n\"\n \"dw07 ieee dware\\n\"\n \"dware ieee dware\\n\"\n \"gtech ieee gtech\\n\"\n \"ramlib std ieee\\n\"\n \"std_cell_lib ieee std_cell_lib\\n\"\n \"synopsys\\n\"\n \"cycle_11 cycle_12\\n\"\n \"cycle_12 cycle_11\\n\"\n \"cycle_21 dw01 cycle_22 dw02 dw03\\n\"\n \"cycle_22 cycle_21 dw01 dw04\";\n display_heading(\"Example: each line starts with a goal followed by it's dependencies\");\n cout << example << endl;\n display_results(example);\n display_heading(\"Enter lines of data (press enter when finished)\");\n string line, data;\n while (getline(cin, line) && !line.empty())\n data += line + '\\n';\n if (!data.empty())\n display_results(data);\n } else\n while (*(++argv)) {\n ifstream file(*argv);\n typedef istreambuf_iterator iterator;\n display_results(string(iterator(file), iterator()));\n }\n}\n\n#include \n#include \n#include \n\ntemplate \nclass topological_sorter\n{\npublic:\n using value_type = ValueType;\n\nprotected:\n struct relations\n {\n std::size_t dependencies { 0 };\n std::unordered_set dependents {};\n };\n\n std::unordered_map _map {};\n\npublic:\n void add(const value_type &object)\n {\n _map.try_emplace(object, relations {});\n }\n\n void add(const value_type &object, const value_type &dependency)\n {\n if (dependency == object) return;\n\n auto &dependents = _map[dependency].dependents;\n\n if (dependents.find(object) == std::end(dependents))\n {\n dependents.insert(object);\n\n ++_map[object].dependencies;\n }\n }\n\n template \n void add(const value_type &object, const Container &dependencies)\n {\n for (auto const &dependency : dependencies) add(object, dependency);\n }\n\n void add(const value_type &object, const std::initializer_list &dependencies)\n {\n add>(object, dependencies);\n }\n\n template\n void add(const value_type &object, const Args&... dependencies)\n {\n (add(object, dependencies), ...);\n }\n\n auto sort()\n {\n std::vector sorted, cycled;\n auto map { _map };\n\n for (const auto &[object, relations] : map) if (!relations.dependencies) sorted.emplace_back(object);\n\n for (decltype(std::size(sorted)) idx = 0; idx < std::size(sorted); ++idx)\n for (auto const& object : map[sorted[idx]].dependents)\n if (!--map[object].dependencies) sorted.emplace_back(object);\n\n for (const auto &[object, relations] : map) if (relations.dependencies) cycled.emplace_back(std::move(object));\n\n return std::pair(std::move(sorted), std::move(cycled));\n }\n\n void clear()\n {\n _map.clear();\n }\n};\n\n\/*\n\tExample usage with shared_ptr to class\n*\/\n#include \n#include \n\nint main()\n{\n using namespace std::string_literals;\n\n struct task\n {\n std::string message;\n\n task(const std::string &v) : message { v } {}\n ~task() { std::cout << message[0] << \" - destroyed\" << std::endl; }\n };\n\n using task_ptr = std::shared_ptr;\n\n std::vector tasks\n {\n \/\/ defining simple tasks\n std::make_shared(\"A - depends on B and C\"s), \/\/0\n std::make_shared(\"B - depends on none\"s), \/\/1\n std::make_shared(\"C - depends on D and E\"s), \/\/2\n std::make_shared(\"D - depends on none\"s), \/\/3\n std::make_shared(\"E - depends on F, G and H\"s), \/\/4\n std::make_shared(\"F - depends on I\"s), \/\/5\n std::make_shared(\"G - depends on none\"s), \/\/6\n std::make_shared(\"H - depends on none\"s), \/\/7\n std::make_shared(\"I - depends on none\"s), \/\/8\n };\n\n topological_sorter resolver;\n\n \/\/ now setting relations between them as described above\n resolver.add(tasks[0], { tasks[1], tasks[2] });\n \/\/resolver.add(tasks[1]); \/\/ no need for this since the task was already mentioned as a dependency\n resolver.add(tasks[2], { tasks[3], tasks[4] });\n \/\/resolver.add(tasks[3]); \/\/ no need for this since the task was already mentioned as a dependency\n resolver.add(tasks[4], tasks[5], tasks[6], tasks[7]); \/\/ using templated add with fold expression\n resolver.add(tasks[5], tasks[8]);\n \/\/resolver.add(tasks[6]); \/\/ no need for this since the task was already mentioned as a dependency\n \/\/resolver.add(tasks[7]); \/\/ no need for this since the task was already mentioned as a dependency\n\n \/\/resolver.add(tasks[3], tasks[0]); \/\/ uncomment this line to test cycled dependency\n\n const auto &[sorted, cycled] = resolver.sort();\n\n if (std::empty(cycled))\n {\n for (auto const& d: sorted)\n std::cout << d->message << std::endl;\n }\n else\n {\n std::cout << \"Cycled dependencies detected: \";\n\n for (auto const& d: cycled)\n std::cout << d->message[0] << \" \";\n\n std::cout << std::endl;\n }\n\n \/\/tasks.clear(); \/\/ uncomment this line to destroy all tasks in sorted order.\n\n std::cout << \"exiting...\" << std::endl;\n\n return 0;\n}\n\n\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":795} {"lang_cluster":"C++","source_code":"\n#include \nusing namespace std;\n\nstring s1=\"abcd\";\nstring s2=\"abab\";\nstring s3=\"ab\";\n\/\/Beginning\ns1.compare(0,s3.size(),s3)==0;\n\/\/End\ns1.compare(s1.size()-s3.size(),s3.size(),s3)==0;\n\/\/Anywhere\ns1.find(s2)\/\/returns string::npos\nint loc=s2.find(s3)\/\/returns 0\nloc=s2.find(s3,loc+1)\/\/returns 2\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":796} {"lang_cluster":"C++","source_code":"\n\/\/C++14\/17\n#include \/\/std::for_each\n#include \/\/std::cout\n#include \/\/std::iota\n#include \/\/std::vector, save solutions\n#include \/\/std::list, for fast erase\n\nusing std::begin, std::end, std::for_each;\n\n\/\/Generates all the valid solutions for the problem in the specified range [from, to)\nstd::list> combinations(int from, int to)\n{\n if (from > to)\n return {}; \/\/Return nothing if limits are invalid\n\n auto pool = std::vector(to - from);\/\/Here we'll save our values\n std::iota(begin(pool), end(pool), from);\/\/Populates pool\n\n auto solutions = std::list>{}; \/\/List for the solutions\n\n \/\/Brute-force calculation of valid values...\n for (auto a : pool)\n for (auto b : pool)\n for (auto c : pool)\n for (auto d : pool)\n for (auto e : pool)\n for (auto f : pool)\n for (auto g : pool)\n if ( a == c + d\n && b + c == e + f\n && d + e == g )\n solutions.push_back({a, b, c, d, e, f, g});\n return solutions;\n}\n\n\/\/Filter the list generated from \"combinations\" and return only lists with no repetitions\nstd::list> filter_unique(int from, int to)\n{\n \/\/Helper lambda to check repetitions:\n \/\/If the count is > 1 for an element, there must be a repetition inside the range\n auto has_non_unique_values = [](const auto & range, auto target)\n {\n return std::count( begin(range), end(range), target) > 1;\n };\n\n \/\/Generates all the solutions...\n auto results = combinations(from, to);\n\n \/\/For each solution, find duplicates inside\n for (auto subrange = cbegin(results); subrange != cend(results); ++subrange)\n {\n bool repetition = false;\n\n \/\/If some element is repeated, repetition becomes true \n for (auto x : *subrange)\n repetition |= has_non_unique_values(*subrange, x);\n\n if (repetition) \/\/If repetition is true, remove the current subrange from the list\n {\n results.erase(subrange); \/\/Deletes subrange from solutions\n --subrange; \/\/Rewind to the last subrange analysed\n }\n }\n\n return results; \/\/Finally return remaining results\n}\n\ntemplate \/\/Template for the sake of simplicity\ninline void print_range(const Container & c)\n{\n for (const auto & subrange : c)\n {\n std::cout << \"[\";\n for (auto elem : subrange)\n std::cout << elem << ' ';\n std::cout << \"\\b]\\n\";\n }\n}\n\n\nint main()\n{\n std::cout << \"Unique-numbers combinations in range 1-7:\\n\";\n auto solution1 = filter_unique(1, 8);\n print_range(solution1);\n std::cout << \"\\nUnique-numbers combinations in range 3-9:\\n\";\n auto solution2 = filter_unique(3,10);\n print_range(solution2);\n std::cout << \"\\nNumber of combinations in range 0-9: \" \n << combinations(0, 10).size() << \".\" << std::endl;\n\n return 0;\n}\n\n\nUnique-numbers combinations in range 1-7:\n[3 7 2 1 5 4 6]\n[4 5 3 1 6 2 7]\n[4 7 1 3 2 6 5]\n[5 6 2 3 1 7 4]\n[6 4 1 5 2 3 7]\n[6 4 5 1 2 7 3]\n[7 2 6 1 3 5 4]\n[7 3 2 5 1 4 6]\n\nUnique-numbers combinations in range 3-9:\n[7 8 3 4 5 6 9]\n[8 7 3 5 4 6 9]\n[9 6 4 5 3 7 8]\n[9 6 5 4 3 8 7]\n\nNumber of combinations in range 0-9: 2860.\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It replaces letters a to g with unique decimal digits ranging from a specified low to high value. It provides solutions for ranges 1-7 and 3-9 where each letter is unique. Additionally, it calculates the number of solutions for the range 0-9 where letters can be non-unique.","id":797} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n\n\/\/--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n\/\/--------------------------------------------------------------------------------------------------\nconst int BMP_SIZE = 300, MY_TIMER = 987654, CENTER = BMP_SIZE >> 1, SEC_LEN = CENTER - 20,\n MIN_LEN = SEC_LEN - 20, HOUR_LEN = MIN_LEN - 20;\nconst float PI = 3.1415926536f;\n\n\/\/--------------------------------------------------------------------------------------------------\nclass vector2\n{\npublic:\n vector2() { x = y = 0; }\n vector2( int a, int b ) { x = a; y = b; }\n void set( int a, int b ) { x = a; y = b; }\n void rotate( float angle_r )\n {\n\tfloat _x = static_cast( x ),\n\t _y = static_cast( y ),\n\t s = sinf( angle_r ),\n\t c = cosf( angle_r ),\n\t a = _x * c - _y * s,\n\t b = _x * s + _y * c;\n\n\tx = static_cast( a );\n\ty = static_cast( b );\n }\n int x, y;\n};\n\/\/--------------------------------------------------------------------------------------------------\nclass myBitmap\n{\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap()\n {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n }\n\n bool create( int w, int h )\n {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes = 1;\n\tbi.bmiHeader.biWidth = w;\n\tbi.bmiHeader.biHeight = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n }\n\n void clear( BYTE clr = 0 )\n {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n\n void setBrushColor( DWORD bClr )\n {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n }\n\n void setPenColor( DWORD c )\n {\n\tclr = c;\n\tcreatePen();\n }\n\n void setPenWidth( int w )\n {\n\twid = w;\n\tcreatePen();\n }\n\n void saveBitmap( string path )\n {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO infoheader;\n\tBITMAP bitmap;\n\tDWORD wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\t\n ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n }\n\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\n\nprivate:\n void createPen()\n {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n }\n\n HBITMAP bmp;\n HDC hdc;\n HPEN pen;\n HBRUSH brush;\n void *pBits;\n int width, height, wid;\n DWORD clr;\n};\n\/\/--------------------------------------------------------------------------------------------------\nclass clock\n{\npublic:\n clock() \n {\n\t_bmp.create( BMP_SIZE, BMP_SIZE );\n\t_bmp.clear( 100 );\n\t_bmp.setPenWidth( 2 );\n\t_ang = DegToRadian( 6 );\n }\n\t\n void setNow()\n {\n\tGetLocalTime( &_sysTime );\n\tdraw();\n }\n\n float DegToRadian( float degree ) { return degree * ( PI \/ 180.0f ); }\n\n void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n void drawTicks( HDC dc )\n {\n\tvector2 line;\n\t_bmp.setPenWidth( 1 );\n\tfor( int x = 0; x < 60; x++ )\n\t{\n\t line.set( 0, 50 );\n\t line.rotate( static_cast( x + 30 ) * _ang );\n\t MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL );\n\t LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) );\n\t}\n\n\t_bmp.setPenWidth( 3 );\n\tfor( int x = 0; x < 60; x += 5 )\n\t{\n\t line.set( 0, 50 );\n\t line.rotate( static_cast( x + 30 ) * _ang );\n\t MoveToEx( dc, CENTER - static_cast( 2.5f * static_cast( line.x ) ), CENTER - static_cast( 2.5f * static_cast( line.y ) ), NULL );\n\t LineTo( dc, CENTER - static_cast( 2.81f * static_cast( line.x ) ), CENTER - static_cast( 2.81f * static_cast( line.y ) ) );\n\t}\n }\n\n void drawHands( HDC dc )\n {\n\tfloat hp = DegToRadian( ( 30.0f * static_cast( _sysTime.wMinute ) ) \/ 60.0f );\n\tint h = ( _sysTime.wHour > 12 ? _sysTime.wHour - 12 : _sysTime.wHour ) * 5;\n\t\t\n\t_bmp.setPenWidth( 3 );\n\t_bmp.setPenColor( RGB( 0, 0, 255 ) );\n\tdrawHand( dc, HOUR_LEN, ( _ang * static_cast( 30 + h ) ) + hp );\n\n\t_bmp.setPenColor( RGB( 0, 128, 0 ) );\n\tdrawHand( dc, MIN_LEN, _ang * static_cast( 30 + _sysTime.wMinute ) );\n\n\t_bmp.setPenWidth( 2 );\n\t_bmp.setPenColor( RGB( 255, 0, 0 ) );\n\tdrawHand( dc, SEC_LEN, _ang * static_cast( 30 + _sysTime.wSecond ) );\n }\n\n void drawHand( HDC dc, int len, float ang )\n {\n\tvector2 line;\n\tline.set( 0, len );\n\tline.rotate( ang );\n\tMoveToEx( dc, CENTER, CENTER, NULL );\n\tLineTo( dc, line.x + CENTER, line.y + CENTER );\n }\n\n void draw()\n {\n\tHDC dc = _bmp.getDC();\n\n\t_bmp.setBrushColor( RGB( 250, 250, 250 ) );\n\tEllipse( dc, 0, 0, BMP_SIZE, BMP_SIZE );\n\t_bmp.setBrushColor( RGB( 230, 230, 230 ) );\n\tEllipse( dc, 10, 10, BMP_SIZE - 10, BMP_SIZE - 10 );\n\n\tdrawTicks( dc );\n\tdrawHands( dc );\n\n\t_bmp.setPenColor( 0 ); _bmp.setBrushColor( 0 );\n\tEllipse( dc, CENTER - 5, CENTER - 5, CENTER + 5, CENTER + 5 );\n\n\t_wdc = GetDC( _hwnd );\n\tBitBlt( _wdc, 0, 0, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n\tReleaseDC( _hwnd, _wdc );\n }\n\n myBitmap _bmp;\n HWND _hwnd;\n HDC _wdc;\n SYSTEMTIME _sysTime;\n float _ang;\n};\n\/\/--------------------------------------------------------------------------------------------------\nclass wnd\n{\npublic:\n wnd() { _inst = this; }\n int wnd::Run( HINSTANCE hInst )\n {\n\t_hInst = hInst;\n\t_hwnd = InitAll();\n\tSetTimer( _hwnd, MY_TIMER, 1000, NULL );\n\t_clock.setHWND( _hwnd );\n\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t }\n\t}\n\treturn UnregisterClass( \"_MY_CLOCK_\", _hInst );\n }\nprivate:\n void wnd::doPaint( HDC dc ) { _clock.setNow(); }\n void wnd::doTimer() { _clock.setNow(); }\n static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n {\n\tswitch( msg )\n\t{\n\t case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t case WM_PAINT:\n\t {\n\t\tPAINTSTRUCT ps;\n\t\tHDC dc = BeginPaint( hWnd, &ps );\n\t\t_inst->doPaint( dc );\n\t\tEndPaint( hWnd, &ps );\n\t\treturn 0;\n\t }\n\t case WM_TIMER: _inst->doTimer(); break;\n\t default:\n\t\treturn DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n }\n\n HWND InitAll()\n {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize = sizeof( WNDCLASSEX );\n\twcex.style = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc = ( WNDPROC )WndProc;\n\twcex.hInstance = _hInst;\n\twcex.hCursor = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_MY_CLOCK_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left, h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_MY_CLOCK_\", \".: Clock -- PJorente\u00a0:.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n }\n\n static wnd* _inst;\n HINSTANCE _hInst;\n HWND _hwnd;\n clock _clock;\n};\nwnd* wnd::_inst = 0;\n\/\/--------------------------------------------------------------------------------------------------\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n wnd myWnd;\n return myWnd.Run( hInstance );\n}\n\/\/--------------------------------------------------------------------------------------------------\n\n","human_summarization":"The code creates a simple, non-resource-intensive clock that displays the passage of seconds. It uses system or language-specific timers or events instead of constant polling. The clock display updates every second and cycles after a set period. The code is written in a clear and concise manner.","id":798} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nauto CountTriplets(unsigned long long maxPerimeter)\n{\n unsigned long long totalCount = 0;\n unsigned long long primitveCount = 0;\n auto max_M = (unsigned long long)sqrt(maxPerimeter\/2) + 1;\n for(unsigned long long m = 2; m < max_M; ++m)\n {\n for(unsigned long long n = 1 + m % 2; n < m; n+=2)\n {\n if(gcd(m,n) != 1)\n {\n continue;\n }\n \n \/\/ The formulas below will generate primitive triples if:\n \/\/ 0 < n < m\n \/\/ m and n are relatively prime (gcd == 1)\n \/\/ m + n is odd\n \n auto a = m * m - n * n;\n auto b = 2 * m * n;\n auto c = m * m + n * n;\n auto perimeter = a + b + c;\n if(perimeter <= maxPerimeter)\n {\n primitveCount++;\n totalCount+= maxPerimeter \/ perimeter;\n }\n }\n }\n \n return tuple(totalCount, primitveCount);\n}\n\n\nint main()\n{\n vector inputs{100, 1000, 10'000, 100'000,\n 1000'000, 10'000'000, 100'000'000, 1000'000'000,\n 10'000'000'000}; \/\/ This last one takes almost a minute\n for(auto maxPerimeter : inputs)\n {\n auto [total, primitive] = CountTriplets(maxPerimeter);\n cout << \"\\nMax Perimeter: \" << maxPerimeter << \", Total: \" << total << \", Primitive: \" << primitive ;\n }\n}\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":799} {"lang_cluster":"C++","source_code":"\nLibrary: Qt\nUses: Qt (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses library\" (as page type) with input value \"library\/Qt\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\n\n#include \n#include \n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n QMainWindow window;\n window.show();\n return app.exec();\n}\n\nLibrary: GTK\n\n#include \n#include \n\nint\nmain( int argc, char* argv[] )\n{\n try\n {\n Gtk::Main m( argc, argv ) ;\n Gtk::Window win ;\n m.run( win ) ;\n }\n \n catch( std::exception const & exc )\n {\n std::cout << exc.what() << std::endl ;\n exit( -1 ) ;\n }\n \n exit( 0 ) ;\n}\n\n","human_summarization":"create a GUI window that can respond to close requests. It is compiled using qmake and g++ commands.","id":800} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main()\n{\n\tstd::ifstream input(\"filename.txt\", std::ios_base::binary);\n\tif (!input)\n\t{\n\t\tstd::cerr << \"error: can't open file\\n\";\n\t\treturn -1;\n\t}\n\n\tsize_t count[256];\n\tstd::fill_n(count, 256, 0);\n\n\tfor (char c; input.get(c); ++count[uint8_t(c)]) \/\/ process input file\n\t\t; \/\/ empty loop body\n\n\tfor (size_t i = 0; i < 256; ++i)\n\t{\n\t\tif (count[i] && isgraph(i)) \/\/ non-zero counts of printable characters\n\t\t{\n\t\t\tstd::cout << char(i) << \" = \" << count[i] << '\\n';\n\t\t}\n\t}\n}\n\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":801} {"lang_cluster":"C++","source_code":"\n\nstruct link\n{\n link* next;\n int data;\n};\n\n\nstruct link\n{\n link* next;\n int data;\n link(int a_data, link* a_next = 0): next(a_next), data(a_data) {}\n};\n\n\n link* small_primes = new link(2, new link(3, new link(5, new link(7))));\n\n\ntemplate struct link\n{\n link* next;\n T data;\n link(T a_data, link* a_next = 0): next(a_next), data(a_data) {}\n};\n\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for holding a numeric value and a mutable link to the next element. The code also includes a constructor to simplify the initialization of links on the heap, allowing for direct initialization at allocation. The code is generic, supporting any data type, not just integral types.","id":802} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n\n\/\/--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n\/\/--------------------------------------------------------------------------------------------------\nconst float PI = 3.1415926536f;\n\n\/\/--------------------------------------------------------------------------------------------------\nclass myBitmap\n{\npublic:\n myBitmap() : pen( NULL ) {}\n ~myBitmap()\n {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n }\n\n bool create( int w, int h )\n {\n\tBITMAPINFO\tbi;\n\tvoid\t\t*pBits;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t = 1;\n\tbi.bmiHeader.biWidth\t = w;\n\tbi.bmiHeader.biHeight\t = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\n\twidth = w; height = h;\n\n\treturn true;\n }\n\n void setPenColor( DWORD clr )\n {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n }\n\n void saveBitmap( string path )\n {\n\tBITMAPFILEHEADER\tfileheader;\n\tBITMAPINFO\t\t\tinfoheader;\n\tBITMAP\t\t\t\tbitmap;\n\tDWORD*\t\t\t\tdwpBits;\n\tDWORD\t\t\t\twb;\n\tHANDLE\t\t\t\tfile;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tdwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tfile = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n }\n\n HDC getDC() { return hdc; }\n int getWidth() { return width; }\n int getHeight() { return height; }\n\nprivate:\n HBITMAP bmp;\n HDC\t hdc;\n HPEN pen;\n int width, height;\n};\n\/\/--------------------------------------------------------------------------------------------------\nclass vector2\n{\npublic:\n vector2() { x = y = 0; }\n vector2( int a, int b ) { x = a; y = b; }\n void set( int a, int b ) { x = a; y = b; }\n void rotate( float angle_r )\n {\n\tfloat _x = static_cast( x ),\n\t _y = static_cast( y ),\n\t s = sinf( angle_r ), \n\t c = cosf( angle_r ),\n\t a = _x * c - _y * s, \n\t b = _x * s + _y * c;\n\n\tx = static_cast( a ); \n\ty = static_cast( b );\n }\n\n int x, y;\n};\n\/\/--------------------------------------------------------------------------------------------------\nclass fractalTree\n{\npublic:\n fractalTree()\t\t { _ang = DegToRadian( 24.0f ); }\n float DegToRadian( float degree ) { return degree * ( PI \/ 180.0f ); }\n\n void create( myBitmap* bmp )\n {\n\t_bmp = bmp;\n\tfloat line_len = 130.0f;\n\n\tvector2 sp( _bmp->getWidth() \/ 2, _bmp->getHeight() - 1 );\n\tMoveToEx( _bmp->getDC(), sp.x, sp.y, NULL );\n\tsp.y -= static_cast( line_len );\n\tLineTo( _bmp->getDC(), sp.x, sp.y);\n\n\tdrawRL( &sp, line_len, 0, true );\n\tdrawRL( &sp, line_len, 0, false );\n }\n\nprivate:\n void drawRL( vector2* sp, float line_len, float a, bool rg )\n {\n\tline_len *= .75f;\n\tif( line_len < 2.0f ) return;\n\n\tMoveToEx( _bmp->getDC(), sp->x, sp->y, NULL );\n\tvector2 r( 0, static_cast( line_len ) );\n\n if( rg ) a -= _ang;\n else a += _ang; \n\n\tr.rotate( a );\n\tr.x += sp->x; r.y = sp->y - r.y;\n\n\tLineTo( _bmp->getDC(), r.x, r.y );\n\n\tdrawRL( &r, line_len, a, true );\n\tdrawRL( &r, line_len, a, false );\n }\n\n myBitmap* _bmp;\n float _ang;\n};\n\/\/--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n\n myBitmap bmp;\n bmp.create( 640, 512 );\n bmp.setPenColor( RGB( 255, 255, 0 ) );\n\n fractalTree tree;\n tree.create( &bmp );\n\t\n BitBlt( GetDC( GetConsoleWindow() ), 0, 20, 648, 512, bmp.getDC(), 0, 0, SRCCOPY );\n\n bmp.saveBitmap( \"f:\/\/rc\/\/fracTree.bmp\" );\n\t\n system( \"pause\" );\n\t\n return 0;\n}\n\/\/--------------------------------------------------------------------------------------------------\n\n","human_summarization":"Generates and draws a fractal tree by drawing the trunk, splitting it at an angle to create branches, and repeating this process until a desired level of branching is achieved.","id":803} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n#include \n\nstd::vector GenerateFactors(int n) {\n std::vector factors = { 1, n };\n for (int i = 2; i * i <= n; ++i) {\n if (n % i == 0) {\n factors.push_back(i);\n if (i * i != n)\n factors.push_back(n \/ i);\n }\n }\n\n std::sort(factors.begin(), factors.end());\n return factors;\n}\n\nint main() {\n const int SampleNumbers[] = { 3135, 45, 60, 81 };\n\n for (size_t i = 0; i < sizeof(SampleNumbers) \/ sizeof(int); ++i) {\n std::vector factors = GenerateFactors(SampleNumbers[i]);\n std::cout << \"Factors of \";\n std::cout.width(4);\n std::cout << SampleNumbers[i] << \" are: \";\n std::copy(factors.begin(), factors.end(), std::ostream_iterator(std::cout, \" \"));\n std::cout << std::endl;\n }\n\n return EXIT_SUCCESS;\n}\n\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":804} {"lang_cluster":"C++","source_code":"\n#include \n#include \/\/ for getline etc.\n#include \n#include \/\/ for istringstream\n#include \/\/ for max\n#include \/\/ for setw\n#include \/\/ for ofstream\n\nusing namespace std;\n\ntemplate< typename C >\nvoid enumerateFields( const string& strInput, char chDelim, C callback )\n{\n istringstream issFile( strInput );\n string strLine;\n string strField;\n size_t nColIndex;\n\n while ( getline( issFile, strLine ) )\n {\n istringstream issLine( strLine );\n nColIndex = 0;\n\n while ( getline( issLine, strField, chDelim ) )\n {\n callback( nColIndex, strField );\n\n nColIndex++;\n }\n }\n}\ntypedef vector< size_t > ColWidths;\n\nstruct MaxColWidthsDeterminer\n{\n explicit MaxColWidthsDeterminer( ColWidths& colWidths )\n : m_colWidths( colWidths ) {}\n\n void operator()( size_t nColIndex, const string& strField );\n\n ColWidths& m_colWidths;\n};\n\nvoid MaxColWidthsDeterminer::operator()( size_t nColIndex,\n const string& strField )\n{\n size_t nWidth = strField.length();\n\n if ( nColIndex >= m_colWidths.size() )\n m_colWidths.push_back( nWidth );\n else\n m_colWidths[ nColIndex ] = max( m_colWidths[ nColIndex ], nWidth );\n}\nstruct FormattedLister\n{\n enum Alignment { eLeft, eRight, eCenter };\n\n FormattedLister( const ColWidths& colWidths, ostream& os,\n Alignment alignment = eLeft )\n : m_colWidths( colWidths ), m_os( os ), m_alignment( alignment ),\n m_nPrevColIndex( 0 )\n {\n m_savedStreamFlags = os.flags();\n m_os.setf( ( m_alignment == eRight ) ? ios::right : ios::left,\n ios::adjustfield );\n }\n\n ~FormattedLister()\n {\n m_os.flags( m_savedStreamFlags );\n }\n\n void operator()( size_t nColIndex, const string& strField );\n\n const ColWidths& m_colWidths;\n ostream& m_os;\n Alignment m_alignment;\n size_t m_nPrevColIndex;\n ios::fmtflags m_savedStreamFlags;\n};\n\nvoid FormattedLister::operator()( size_t nColIndex, const string& strField )\n{\n if ( nColIndex < m_nPrevColIndex )\n m_os << '\n';\n\n if ( m_alignment == eCenter )\n {\n size_t nSpacesBefore = ( m_colWidths[ nColIndex ] - strField.length() )\n \/ 2;\n size_t nSpacesAfter = m_colWidths[ nColIndex ] - strField.length()\n - nSpacesBefore + 1;\n\n m_os << string( nSpacesBefore, ' ' ) << strField\n << string( nSpacesAfter, ' ' );\n }\n else\n {\n m_os << setw( static_cast< streamsize >( m_colWidths[ nColIndex ] ) )\n << strField << ' ';\n }\n\n m_nPrevColIndex = nColIndex;\n}\nint main()\n{\n const string strInput( \n \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n\"\n \"are$delineated$by$a$single$'dollar'$character,$write$a$program\n\"\n \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n\"\n \"column$are$separated$by$at$least$one$space.\n\"\n \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n\"\n \"justified,$right$justified,$or$center$justified$within$its$column.\" );\n\n const char chDelim = '$';\n\n ColWidths colWidths;\n\n enumerateFields( strInput, chDelim, MaxColWidthsDeterminer( colWidths ) );\n\n ofstream outFile( \"ColumnAligner.txt\" );\n if ( outFile )\n {\n enumerateFields( strInput, chDelim,\n FormattedLister( colWidths, outFile ) );\n outFile << '\n';\n\n enumerateFields( strInput, chDelim,\n FormattedLister( colWidths, outFile,\n FormattedLister::eRight ) );\n outFile << '\n';\n\n enumerateFields( strInput, chDelim,\n FormattedLister( colWidths, outFile,\n FormattedLister::eCenter ) );\n outFile << endl;\n }\n}\n","human_summarization":"The code reads a text file where fields within a line are separated by a dollar symbol. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. The code does not require adding separating characters between or around columns. It handles trailing dollar characters and ignores consecutive spaces at the end of lines. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":805} {"lang_cluster":"C++","source_code":"\n\n#include\n#include\n\nint main()\n{\n int k;\n initwindow(1500,810,\"Rosetta Cuboid\");\n \n do{\n std::cout<<\"Enter ratio of sides ( 0 or -ve to exit)\u00a0: \";\n std::cin>>k;\n \n if(k>0){\n bar3d(100, 100, 100 + 2*k, 100 + 4*k, 3*k, 1);\n }\n }while(k>0);\n \n return 0;\n}\n\n\n","human_summarization":"draw a 2x3x4 cuboid, with three visible faces, using either graphical representation or ASCII art, and can be either static or rotational. The code requires BGI for Windows from Colorado State University.","id":806} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ the rot13 function\nstd::string rot13(std::string s)\n{\n static std::string const\n lcalph = \"abcdefghijklmnopqrstuvwxyz\",\n ucalph = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n std::string result;\n std::string::size_type pos;\n\n result.reserve(s.length());\n\n for (std::string::iterator it = s.begin(); it != s.end(); ++it)\n {\n if ( (pos = lcalph.find(*it)) != std::string::npos )\n result.push_back(lcalph[(pos+13) % 26]);\n else if ( (pos = ucalph.find(*it)) != std::string::npos )\n result.push_back(ucalph[(pos+13) % 26]);\n else\n result.push_back(*it);\n }\n\n return result;\n}\n\n\/\/ function to output the rot13 of a file on std::cout\n\/\/ returns false if an error occurred processing the file, true otherwise\n\/\/ on entry, the argument is must be open for reading\nint rot13_stream(std::istream& is)\n{\n std::string line;\n while (std::getline(is, line))\n {\n if (!(std::cout << rot13(line) << \"\\n\"))\n return false;\n }\n return is.eof();\n}\n\n\/\/ the main program\nint main(int argc, char* argv[])\n{\n if (argc == 1) \/\/ no arguments given\n return rot13_stream(std::cin)? EXIT_SUCCESS : EXIT_FAILURE;\n\n std::ifstream file;\n for (int i = 1; i < argc; ++i)\n {\n file.open(argv[i], std::ios::in);\n if (!file)\n {\n std::cerr << argv[0] << \": could not open for reading: \" << argv[i] << \"\\n\";\n return EXIT_FAILURE;\n }\n if (!rot13_stream(file))\n {\n if (file.eof())\n \/\/ no error occurred for file, so the error must have been in output\n std::cerr << argv[0] << \": error writing to stdout\\n\";\n else\n std::cerr << argv[0] << \": error reading from \" << argv[i] << \"\\n\";\n return EXIT_FAILURE;\n }\n file.clear();\n file.close();\n if (!file)\n std::cerr << argv[0] << \": warning: closing failed for \" << argv[i] << \"\\n\";\n }\n return EXIT_SUCCESS;\n}\n\n\nLibrary: Boost\n#include \n#include \n#include \/\/ output_filter\n#include \/\/ put\n#include \n#include \nnamespace io = boost::iostreams;\n\nclass rot_output_filter : public io::output_filter \n{\npublic:\n explicit rot_output_filter(int r=13):rotby(r),negrot(alphlen-r){};\n\n template\n bool put(Sink& dest, int c){\n char uc = toupper(c);\n\n if(('A' <= uc) && (uc <= ('Z'-rotby)))\n c = c + rotby;\n else if ((('Z'-rotby) <= uc) && (uc <= 'Z'))\n c = c - negrot;\n return boost::iostreams::put(dest, c);\n };\nprivate:\n static const int alphlen = 26;\n const int rotby;\n const int negrot;\n};\n\nint main(int argc, char *argv[])\n{\n io::filtering_ostream out;\n out.push(rot_output_filter(13));\n out.push(std::cout);\n\n if (argc == 1) out << std::cin.rdbuf();\n else for(int i = 1; i < argc; ++i){\n std::ifstream in(argv[i]);\n out << in.rdbuf();\n }\n}\n\n#include \n#include \n#include \n\nchar rot13(const char c){\n\tif (c >= 'a' && c <= 'z')\n\t\treturn (c - 'a' + 13) % 26 + 'a';\n\telse if (c >= 'A' && c <= 'Z')\n\t\treturn (c - 'A' + 13) % 26 + 'A';\n\treturn c;\n}\n\nstd::string &rot13(std::string &s){\n\tfor (auto &c : s) \/\/range based for is the only used C++11 feature\n\t\tc = rot13(c);\n\treturn s;\n}\n\nvoid rot13(std::istream &in, std::ostream &out){\n\tstd::string s;\n\twhile (std::getline(in, s))\n\t\tout << rot13(s) << '\\n';\n}\n\nint main(int argc, char *argv[]){\n\tif (argc == 1)\n\t\trot13(std::cin, std::cout);\n\tfor (int arg = 1; arg < argc; ++arg){\n\t\tstd::ifstream f(argv[arg]);\n\t\tif (!f)\n\t\t\treturn EXIT_FAILURE;\n\t\trot13(f, std::cout);\n\t}\n}\n\n","human_summarization":"The code implements a rot-13 function that replaces each letter of the ASCII alphabet with the letter 13 places ahead, wrapping from z to a as necessary. It maintains case and leaves non-alphabetic characters unaltered. The function can be optionally wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line, or acts as a filter on its standard input. The code also includes an alternative approach that allows rotation by any number.","id":807} {"lang_cluster":"C++","source_code":"\n\ng++ -std=c++11 sort.cpp\n\n#include \n#include \n#include \n\nstruct entry {\n std::string name;\n std::string value;\n};\n\nint main() {\n entry array[] = { { \"grass\", \"green\" }, { \"snow\", \"white\" },\n { \"sky\", \"blue\" }, { \"cherry\", \"red\" } };\n\n std::cout << \"Before sorting:\\n\";\n for (const auto &e : array) {\n std::cout << \"{\" << e.name << \", \" << e.value << \"}\\n\";\n }\n\n std::sort(std::begin(array), std::end(array), \n [](const entry & a, const entry & b) {\n return a.name < b.name;\n });\n\n std::cout << \"After sorting:\\n\";\n for (const auto &e : array) {\n std::cout << \"{\" << e.name << \", \" << e.value << \"}\\n\";\n }\n}\n\n\nBefore sorting:\n{grass, green}\n{snow, white}\n{sky, blue}\n{cherry, red}\nAfter sorting:\n{cherry, red}\n{grass, green}\n{sky, blue}\n{snow, white}\n\n","human_summarization":"sort an array of name-value pair structures by the key name using a custom comparator in C++11.","id":808} {"lang_cluster":"C++","source_code":"\nfor(int i = 0; i < 5; ++i) {\n for(int j = 0; j < i; ++j)\n std::cout.put('*');\n\n std::cout.put('\\n');\n}\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":809} {"lang_cluster":"C++","source_code":"\n\n#include \n\n\nstd::map exampleMap\n\n\nstd::map exampleMap\n\n\n\nexampleMap[7] = 3.14\n\n\nint myKey = 7;\ndouble myValue = 3.14;\nexampleMap[myKey] = myValue;\n\n\nexampleMap.insert(std::pair(7,3.14));\n\n\nexampleMap.insert(std::make_pair(7,3.14));\n\n\n\nmyValue = exampleMap[myKey]\n\n\n\ndouble myValue = 0.0;\nstd::map::iterator myIterator = exampleMap.find(myKey);\nif(exampleMap.end() != myIterator)\n{\n \/\/ Return the value for that key.\n myValue = myIterator->second;\n}\n\n\n\n#include \n#include \n\nint main()\n{\n \/\/ Create the map.\n std::map exampleMap;\n\n \/\/ Choose our key\n int myKey = 7;\n\n \/\/ Choose our value\n double myValue = 3.14;\n\n \/\/ Assign a value to the map with the specified key.\n exampleMap[myKey] = myValue;\n\n \/\/ Retrieve the value\n double myRetrievedValue = exampleMap[myKey];\n\n \/\/ Display our retrieved value.\n std::cout << myRetrievedValue << std::endl;\n\n \/\/ main() must return 0 on success.\n return 0;\n}\n\n","human_summarization":"The code creates an associative array or map using the C++ standard std::map. It defines a map with a key of type A and a value of type B. It also shows how to define a map with a key type of int and a value of double. The code demonstrates two ways to insert values into the map using an example key of 7 and a value of 3.14. It also explains how to retrieve values from the map using the correct key or using the find() function. If a value doesn't exist, it inserts a default-constructed object of the value's type using the specified key and returns that default value. The code also prints the value to STDOUT.","id":810} {"lang_cluster":"C++","source_code":"\n#include \n\n\/\/--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n\/\/--------------------------------------------------------------------------------------------------\nclass mRND\n{\npublic:\n void seed( unsigned int s ) { _seed = s; }\n\nprotected:\n mRND() : _seed( 0 ), _a( 0 ), _c( 0 ), _m( 2147483648 ) {}\n int rnd() { return( _seed = ( _a * _seed + _c ) % _m ); }\n\n int _a, _c;\n unsigned int _m, _seed;\n};\n\/\/--------------------------------------------------------------------------------------------------\nclass MS_RND : public mRND\n{\npublic:\n MS_RND() { _a = 214013; _c = 2531011; }\n int rnd() { return mRND::rnd() >> 16; }\n};\n\/\/--------------------------------------------------------------------------------------------------\nclass BSD_RND : public mRND\n{\npublic:\n BSD_RND() { _a = 1103515245; _c = 12345; }\n int rnd() { return mRND::rnd(); }\n};\n\/\/--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n BSD_RND bsd_rnd;\n MS_RND ms_rnd;\n\n cout << \"MS RAND:\" << endl << \"========\" << endl;\n for( int x = 0; x < 10; x++ )\n\tcout << ms_rnd.rnd() << endl;\n\n cout << endl << \"BSD RAND:\" << endl << \"=========\" << endl;\n for( int x = 0; x < 10; x++ )\n\tcout << bsd_rnd.rnd() << endl;\n\n cout << endl << endl;\n system( \"pause\" );\n return 0;\n}\n\/\/--------------------------------------------------------------------------------------------------\n\n\nMS RAND:\n========\n38\n7719\n21238\n2437\n8855\n11797\n8365\n32285\n10450\n30612\n\nBSD RAND:\n=========\n12345\n1406932606\n654583775\n1449466924\n229283573\n1109335178\n1051550459\n1293799192\n794471793\n551188310\n\nC++11\nWorks with: C++11\n#include \n#include \n\nint main() {\n\n std::linear_congruential_engine bsd_rand(0);\n std::linear_congruential_engine ms_rand(0);\n\n std::cout << \"BSD RAND:\" << std::endl << \"========\" << std::endl;\n for (int i = 0; i < 10; i++) {\n std::cout << bsd_rand() << std::endl;\n }\n std::cout << std::endl;\n std::cout << \"MS RAND:\" << std::endl << \"========\" << std::endl;\n for (int i = 0; i < 10; i++) {\n std::cout << (ms_rand() >> 16) << std::endl;\n }\n \n return 0;\n}\n\n\nBSD RAND:\n========\n12345\n1406932606\n654583775\n1449466924\n229283573\n1109335178\n1051550459\n1293799192\n794471793\n551188310\n\nMS RAND:\n========\n38\n7719\n21238\n2437\n8855\n11797\n8365\n32285\n10450\n30612\n\n","human_summarization":"The code replicates two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). It uses the Linear Congruential Generator formula to generate a sequence of random numbers, starting from a seed value. The generated sequence matches the original generator when starting from the same seed. The code also includes the specific formulas used by BSD and Microsoft, and the range of possible output values for each.","id":811} {"lang_cluster":"C++","source_code":"\n\ntemplate void insert_after(link* list_node, link* new_node)\n{\n new_node->next = list_node->next;\n list_node->next = new_node;\n};\n\n\nlink* a = new link('A', new link('B'));\nlink* c = new link('C');\n\n\n insert_after(a, c);\n\n\nwhile (a)\n{\n link* tmp = a;\n a = a->next;\n delete tmp;\n}\n\n","human_summarization":"define a method to insert an element into a singly-linked list after a given element. The method is then used to insert element C into a list comprised of elements A and B, specifically after element A. The list is then destroyed after the operation.","id":812} {"lang_cluster":"C++","source_code":"\n\ntemplate\nstruct Half \n{ \n enum { Result = N >> 1 };\n}; \n\ntemplate\nstruct Double \n{ \n enum { Result = N << 1 };\n}; \n\ntemplate\nstruct IsEven \n{ \n static const bool Result = (N & 1) == 0;\n};\n\ntemplate\nstruct EthiopianMultiplication\n{\n template\n struct AddIfNot\n {\n enum { Result = Plier + RunningTotal };\n };\n template\n struct AddIfNot \n {\n enum { Result = RunningTotal };\n };\n\n template\n struct Loop\n {\n enum { Result = Loop::Result, Double::Result,\n AddIfNot::Result, Plicand, RunningTotal >::Result >::Result };\n };\n template\n struct Loop <0, Plicand, RunningTotal>\n {\n enum { Result = RunningTotal };\n };\n\n enum { Result = Loop::Result };\n};\n\n#include \n\nint main(int, char **)\n{\n std::cout << EthiopianMultiplication<17, 54>::Result << std::endl;\n return 0;\n}\n\n","human_summarization":"The code defines three functions to halve an integer, double an integer, and check if an integer is even. These functions are used to implement the Ethiopian multiplication method, which multiplies two integers using only addition, doubling, and halving operations. The multiplication process involves repeatedly halving the first number and doubling the second number, discarding rows where the halved number is even, and summing the remaining values in the doubled column to get the multiplication result. The code is implemented as a C++ meta-program, running at compile time with the result saved into the compiled code.","id":813} {"lang_cluster":"C++","source_code":"\nWorks with: C++11\nWorks with: GCC version 4.8\n\n#include \n#include \n#include \n#include \n#include \n\ntypedef short int Digit; \/\/ Typedef for the digits data type.\n\nconstexpr Digit nDigits{4}; \/\/ Amount of digits that are taken into the game.\nconstexpr Digit maximumDigit{9}; \/\/ Maximum digit that may be taken into the game.\nconstexpr short int gameGoal{24}; \/\/ Desired result.\n\ntypedef std::array digitSet; \/\/ Typedef for the set of digits in the game.\ndigitSet d;\n\nvoid printTrivialOperation(std::string operation) { \/\/ Prints a commutative operation taking all the digits.\n\tbool printOperation(false);\n\tfor(const Digit& number : d) {\n\t\tif(printOperation)\n\t\t\tstd::cout << operation;\n\t\telse\n\t\t\tprintOperation = true;\n\t\tstd::cout << number;\n\t}\n\tstd::cout << std::endl;\n}\n\nvoid printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = \"\") {\n\tstd::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl;\n}\n\nint main() {\n\tstd::mt19937_64 randomGenerator;\n\tstd::uniform_int_distribution digitDistro{1, maximumDigit};\n\t\/\/ Let us set up a number of trials:\n\tfor(int trial{10}; trial; --trial) {\n\t\tfor(Digit& digit : d) {\n\t\t\tdigit = digitDistro(randomGenerator);\n\t\t\tstd::cout << digit << \" \";\n\t\t}\n\t\tstd::cout << std::endl;\n\t\tstd::sort(d.begin(), d.end());\n\t\t\/\/ We start with the most trivial, commutative operations:\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal)\n\t\t\tprintTrivialOperation(\" + \");\n\t\tif(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies{}) == gameGoal)\n\t\t\tprintTrivialOperation(\" * \");\n\t\t\/\/ Now let's start working on every permutation of the digits.\n\t\tdo {\n\t\t\t\/\/ Operations with 2 symbols + and one symbol -:\n\t\t\tif(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" + \", \" + \", \" - \"); \/\/ If gameGoal is ever changed to a smaller value, consider adding more operations in this category.\n\t\t\t\/\/ Operations with 2 symbols + and one symbol *:\n\t\t\tif(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" + \");\n\t\t\tif(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" + \", \" )\");\n\t\t\t\/\/ Operations with one symbol + and 2 symbols *:\n\t\t\tif((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) + \");\n\t\t\tif(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" + \", \" )\");\n\t\t\tif((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) + ( \", \" * \", \" )\");\n\t\t\t\/\/ Operations with one symbol - and 2 symbols *:\n\t\t\tif((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation(\"( \", \" * \", \" * \", \" ) - \");\n\t\t\tif(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation(\"( \", \" * \", \" * ( \", \" - \", \" )\");\n\t\t\tif((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation(\"( \", \" * \", \" ) - ( \", \" * \", \" )\");\n\t\t\t\/\/ Operations with one symbol +, one symbol *, and one symbol -:\n\t\t\tif(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation(\"\", \" * \", \" + \", \" - \");\n\t\t\tif(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" ) - \");\n\t\t\tif(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation(\"\", \" * ( \", \" - \", \" ) + \");\n\t\t\tif(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation(\"\", \" * ( \", \" + \", \" - \", \" )\");\n\t\t\tif(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation(\"\", \" * \", \" - ( \", \" + \", \" )\");\n\t\t\t\/\/ Operations with one symbol *, one symbol \/, one symbol +:\n\t\t\tif(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation(\"( \", \" * \", \" \/ \", \" ) + \");\n\t\t\tif(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) + \", \" ) \/ \");\n\t\t\tif((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" + \", \" ) * \", \" ) \/ \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation(\"( \", \" * \", \" ) \/ ( \", \" + \", \" )\");\n\t\t\t\/\/ Operations with one symbol *, one symbol \/, one symbol -:\n\t\t\tif(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation(\"( \", \" * \", \" \/ \", \" ) - \");\n\t\t\tif(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation(\"(( \", \" * \", \" ) - \", \" ) \/ \");\n\t\t\tif((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation(\"(( \", \" - \", \" ) * \", \" ) \/ \");\n\t\t\tif(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation(\"( \", \" * \", \" ) \/ ( \", \" - \", \" )\");\n\t\t\t\/\/ Operations with 2 symbols *, one symbol \/:\n\t\t\tif(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation(\"\", \" * \", \" * \", \" \/ \");\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"\", \" * \", \" \/ ( \", \" * \", \" )\");\n\t\t\t\/\/ Operations with 2 symbols \/, one symbol -:\n\t\t\tif(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation(\"\", \" \/ ( \", \" - \", \" \/ \", \" )\");\n\t\t\t\/\/ Operations with 2 symbols \/, one symbol *:\n\t\t\tif(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation(\"( \", \" * \", \" \/ \", \" ) \/ \", \"\");\n\t\t} while(std::next_permutation(d.begin(), d.end())); \/\/ All operations are repeated for all possible permutations of the numbers.\n\t}\n\treturn 0;\n}\n\n\n","human_summarization":"The code accepts four digits either from user input or random generation and computes arithmetic expressions based on the rules of the 24 game. It also provides examples of the generated solutions. The code can be extended to work with more numbers, different goals, or digit ranges.","id":814} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n\nint factorial(int n)\n{\n \/\/ last is one-past-end\n return std::accumulate(boost::counting_iterator(1), boost::counting_iterator(n+1), 1, std::multiplies());\n}\n\n\n\/\/iteration with while\nlong long int factorial(long long int n)\n{ \n long long int r = 1;\n while(1\nstruct Factorial \n{\n enum { value = N * Factorial::value };\n};\n \ntemplate <>\nstruct Factorial<0> \n{\n enum { value = 1 };\n};\n \n\/\/ Factorial<4>::value == 24\n\/\/ Factorial<0>::value == 1\nvoid foo()\n{\n int x = Factorial<4>::value; \/\/ == 24\n int y = Factorial<0>::value; \/\/ == 1\n}\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing ulli = unsigned long long int;\n\n\/\/ bad style do-while and wrong for Factorial1(0LL) -> 0\u00a0!!!\nulli Factorial1(ulli m_nValue) {\n ulli result = m_nValue;\n ulli result_next;\n ulli pc = m_nValue;\n do {\n result_next = result * (pc - 1);\n result = result_next;\n pc--;\n } while (pc > 2);\n return result;\n}\n\n\/\/ iteration with while\nulli Factorial2(ulli n) {\n ulli r = 1;\n while (1 < n)\n r *= n--;\n return r;\n}\n\n\/\/ recursive\nulli Factorial3(ulli n) {\n return n < 2 ? 1 : n * Factorial3(n - 1);\n}\n\n\/\/ tail recursive\ninline ulli _fac_aux(ulli n, ulli acc) {\n return n < 1 ? acc : _fac_aux(n - 1, acc * n);\n}\nulli Factorial4(ulli n) {\n return _fac_aux(n, 1);\n}\n\n\/\/ accumulate with functor\nulli Factorial5(ulli n) {\n \/\/ last is one-past-end\n return std::accumulate(boost::counting_iterator(1ULL),\n boost::counting_iterator(n + 1ULL), 1ULL,\n std::multiplies());\n}\n\n\/\/ accumulate with lambda\nulli Factorial6(ulli n) {\n \/\/ last is one-past-end\n return std::accumulate(boost::counting_iterator(1ULL),\n boost::counting_iterator(n + 1ULL), 1ULL,\n [](ulli a, ulli b) { return a * b; });\n}\n\nint main() {\n ulli v = 20; \/\/ max value with unsigned long long int\n ulli result;\n std::cout << std::fixed;\n using duration = std::chrono::duration;\n\n {\n auto t1 = std::chrono::high_resolution_clock::now();\n result = Factorial1(v);\n auto t2 = std::chrono::high_resolution_clock::now();\n std::cout << \"do-while(1) result \" << result << \" took \" << duration(t2 - t1).count() << \" \u00b5s\\n\";\n }\n\n {\n auto t1 = std::chrono::high_resolution_clock::now();\n result = Factorial2(v);\n auto t2 = std::chrono::high_resolution_clock::now();\n std::cout << \"while(2) result \" << result << \" took \" << duration(t2 - t1).count() << \" \u00b5s\\n\";\n }\n\n {\n auto t1 = std::chrono::high_resolution_clock::now();\n result = Factorial3(v);\n auto t2 = std::chrono::high_resolution_clock::now();\n std::cout << \"recursive(3) result \" << result << \" took \" << duration(t2 - t1).count() << \" \u00b5s\\n\";\n }\n\n {\n auto t1 = std::chrono::high_resolution_clock::now();\n result = Factorial3(v);\n auto t2 = std::chrono::high_resolution_clock::now();\n std::cout << \"tail recursive(4) result \" << result << \" took \" << duration(t2 - t1).count() << \" \u00b5s\\n\";\n }\n\n {\n auto t1 = std::chrono::high_resolution_clock::now();\n result = Factorial5(v);\n auto t2 = std::chrono::high_resolution_clock::now();\n std::cout << \"std::accumulate(5) result \" << result << \" took \" << duration(t2 - t1).count() << \" \u00b5s\\n\";\n }\n\n {\n auto t1 = std::chrono::high_resolution_clock::now();\n result = Factorial6(v);\n auto t2 = std::chrono::high_resolution_clock::now();\n std::cout << \"std::accumulate lambda(6) result \" << result << \" took \" << duration(t2 - t1).count() << \" \u00b5s\\n\";\n }\n}\n\ndo-while(1) result 2432902008176640000 took 0.110000 \u00b5s\nwhile(2) result 2432902008176640000 took 0.078000 \u00b5s\nrecursive(3) result 2432902008176640000 took 0.057000 \u00b5s\ntail recursive(4) result 2432902008176640000 took 0.056000 \u00b5s\nstd::accumulate(5) result 2432902008176640000 took 0.056000 \u00b5s\nstd::accumulate lambda(6) result 2432902008176640000 took 0.079000 \u00b5s\n\n","human_summarization":"The code defines a function that calculates the factorial of a positive integer number. The factorial is calculated either iteratively or recursively. The function may optionally handle negative input errors. The code can also be adapted for C++ using STL and boost, with an iterative version using a while loop.","id":815} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n\nbool contains_duplicates(std::string s)\n{\n std::sort(s.begin(), s.end());\n return std::adjacent_find(s.begin(), s.end()) != s.end();\n}\n\nvoid game()\n{\n typedef std::string::size_type index;\n\n std::string symbols = \"0123456789\";\n unsigned int const selection_length = 4;\n\n std::random_shuffle(symbols.begin(), symbols.end());\n std::string selection = symbols.substr(0, selection_length);\n std::string guess;\n while (std::cout << \"Your guess? \", std::getline(std::cin, guess))\n {\n if (guess.length() != selection_length\n || guess.find_first_not_of(symbols) != std::string::npos\n || contains_duplicates(guess))\n {\n std::cout << guess << \" is not a valid guess!\";\n continue;\n }\n\n unsigned int bulls = 0;\n unsigned int cows = 0;\n for (index i = 0; i != selection_length; ++i)\n {\n index pos = selection.find(guess[i]);\n if (pos == i)\n ++bulls;\n else if (pos != std::string::npos)\n ++cows;\n }\n std::cout << bulls << \" bulls, \" << cows << \" cows.\\n\";\n if (bulls == selection_length)\n {\n std::cout << \"Congratulations! You have won!\\n\";\n return;\n }\n }\n std::cerr << \"Oops! Something went wrong with input, or you've entered end-of-file!\\nExiting ...\\n\";\n std::exit(EXIT_FAILURE);\n}\n\nint main()\n{\n std::cout << \"Welcome to bulls and cows!\\nDo you want to play? \";\n std::string answer;\n while (true)\n {\n while (true)\n {\n if (!std::getline(std::cin, answer))\n {\n std::cout << \"I can't get an answer. Exiting.\\n\";\n return EXIT_FAILURE;\n }\n if (answer == \"yes\" || answer == \"Yes\" || answer == \"y\" || answer == \"Y\")\n break;\n if (answer == \"no\" || answer == \"No\" || answer == \"n\" || answer == \"N\")\n {\n std::cout << \"Ok. Goodbye.\\n\";\n return EXIT_SUCCESS;\n }\n std::cout << \"Please answer yes or no: \";\n }\n game(); \n std::cout << \"Another game? \";\n }\n}\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":816} {"lang_cluster":"C++","source_code":"\nWorks with: C++11\n\n#include \n#include \n#include \n#include \nusing namespace std;\n\nint main()\n{\n random_device seed;\n mt19937 engine(seed());\n normal_distribution dist(1.0, 0.5);\n auto rnd = bind(dist, engine);\n\n vector v(1000);\n generate(v.begin(), v.end(), rnd);\n return 0;\n}\n\nWorks with: C++03\n#include \/\/ for rand\n#include \/\/ for atan, sqrt, log, cos\n#include \/\/ for generate_n\n\ndouble const pi = 4*std::atan(1.0);\n\n\/\/ simple functor for normal distribution\nclass normal_distribution\n{\npublic:\n normal_distribution(double m, double s): mu(m), sigma(s) {}\n double operator() const \/\/ returns a single normally distributed number\n {\n double r1 = (std::rand() + 1.0)\/(RAND_MAX + 1.0); \/\/ gives equal distribution in (0, 1]\n double r2 = (std::rand() + 1.0)\/(RAND_MAX + 1.0);\n return mu + sigma * std::sqrt(-2*std::log(r1))*std::cos(2*pi*r2);\n }\nprivate:\n const double mu, sigma;\n};\n\nint main()\n{\n double array[1000];\n std::generate_n(array, 1000, normal_distribution(1.0, 0.5));\n return 0;\n}\n\nLibrary: Boost\n\n#include \n#include \"boost\/random.hpp\"\n#include \"boost\/generator_iterator.hpp\" \n#include \n#include \n\ntypedef boost::mt19937 RNGType; \/\/\/< mersenne twister generator\n\nint main() {\n RNGType rng;\n boost::normal_distribution<> rdist(1.0,0.5); \/**< normal distribution \n with mean of 1.0 and standard deviation of 0.5 *\/\n\n boost::variate_generator< RNGType, boost::normal_distribution<> >\n get_rand(rng, rdist); \n\n std::vector v(1000);\n generate(v.begin(),v.end(),get_rand);\n return 0;\n}\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5 using the Mersenne Twister generator. The code also includes the option to change the generator type.","id":817} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main()\n{\n int a[] = { 1, 3, -5 };\n int b[] = { 4, -2, -1 };\n\n std::cout << std::inner_product(a, a + sizeof(a) \/ sizeof(a[0]), b, 0) << std::endl;\n\n return 0;\n}\n\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":818} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ word by word\ntemplate\nvoid read_words(std::istream& is, OutIt dest)\n{\n std::string word;\n while (is >> word)\n {\n \/\/ send the word to the output iterator\n *dest = word;\n }\n}\n\n\/\/ line by line:\ntemplate\nvoid read_lines(std::istream& is, OutIt dest)\n{\n std::string line;\n while (std::getline(is, line))\n {\n \/\/ store the line to the output iterator\n *dest = line;\n }\n}\n\nint main()\n{\n \/\/ 1) sending words from std. in std. out (end with Return)\n read_words(std::cin, \n std::ostream_iterator(std::cout, \" \"));\n\n \/\/ 2) appending lines from std. to vector (end with Ctrl+Z)\n std::vector v;\n read_lines(std::cin, std::back_inserter(v));\n \n return 0;\n}\n\n\ntemplate\nvoid read_words(std::istream& is, OutIt dest)\n{\n typedef std::istream_iterator InIt;\n std::copy(InIt(is), InIt(),\n dest);\n}\n\nnamespace detail \n{\n struct ReadableLine : public std::string \n { \n friend std::istream & operator>>(std::istream & is, ReadableLine & line)\n { \n return std::getline(is, line);\n }\n };\n}\n\ntemplate\nvoid read_lines(std::istream& is, OutIt dest)\n{\n typedef std::istream_iterator InIt;\n std::copy(InIt(is), InIt(),\n dest);\n}\n\n","human_summarization":"The code reads data from a text stream either word-by-word or line-by-line until there is no more data. The amount of data in the stream is unknown. The read words or lines are then sent to a generic output iterator using specific functions. Alternatively, istream iterators can be used for reading words or lines.","id":819} {"lang_cluster":"C++","source_code":"\nLibrary: LibXML\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef LIBXML_TREE_ENABLED\n# error libxml was not configured with DOM tree support\n#endif\n\n#ifndef LIBXML_OUTPUT_ENABLED\n# error libxml was not configured with serialization support\n#endif\n\n\/\/ Because libxml2 is a C library, we need a couple things to make it work\n\/\/ well with modern C++:\n\/\/ 1) a ScopeGuard-like type to handle cleanup functions; and\n\/\/ 2) an exception type that transforms the library's errors.\n\n\/\/ ScopeGuard-like type to handle C library cleanup functions.\ntemplate \nclass [[nodiscard]] scope_exit\n{\npublic:\n \/\/ C++20: Constructor can (and should) be [[nodiscard]].\n \/*[[nodiscard]]*\/ constexpr explicit scope_exit(F&& f) :\n f_{std::move(f)}\n {}\n\n ~scope_exit()\n {\n f_();\n }\n\n \/\/ Non-copyable, non-movable.\n scope_exit(scope_exit const&) = delete;\n scope_exit(scope_exit&&) = delete;\n auto operator=(scope_exit const&) -> scope_exit& = delete;\n auto operator=(scope_exit&&) -> scope_exit& = delete;\n\nprivate:\n F f_;\n};\n\n\/\/ Exception that gets last libxml2 error.\nclass libxml_error : public std::runtime_error\n{\npublic:\n libxml_error() : libxml_error(std::string{}) {}\n\n explicit libxml_error(std::string message) :\n std::runtime_error{make_message_(std::move(message))}\n {}\n\nprivate:\n static auto make_message_(std::string message) -> std::string\n {\n if (auto const last_error = ::xmlGetLastError(); last_error)\n {\n if (not message.empty())\n message += \": \";\n message += last_error->message;\n }\n\n return message;\n }\n};\n\nauto add_text(::xmlNode* node, ::xmlChar const* content)\n{\n \/\/ Create a new text node with the desired content.\n auto const text_node = ::xmlNewText(content);\n if (not text_node)\n throw libxml_error{\"failed to create text node\"};\n\n \/\/ Try to add it to the node. If it succeeds, that node will take\n \/\/ ownership of the text node. If it fails, we have to clean up the text\n \/\/ node ourselves first, then we can throw.\n if (auto const res = ::xmlAddChild(node, text_node); not res)\n {\n ::xmlFreeNode(text_node);\n throw libxml_error{\"failed to add text node\"};\n }\n \n return text_node;\n}\n\nauto main() -> int\n{\n \/\/ Set this to true if you don't want the XML declaration.\n constexpr auto no_xml_declaration = false;\n\n try\n {\n \/\/ Initialize libxml.\n ::xmlInitParser();\n LIBXML_TEST_VERSION\n auto const libxml_cleanup = scope_exit{[] { ::xmlCleanupParser(); }};\n\n \/\/ Create a new document.\n auto doc = ::xmlNewDoc(reinterpret_cast<::xmlChar const*>(u8\"1.0\"));\n if (not doc)\n throw libxml_error{\"failed to create document\"};\n auto const doc_cleanup = scope_exit{[doc] { ::xmlFreeDoc(doc); }};\n\n \/\/ Create the root element.\n auto root = ::xmlNewNode(nullptr,\n reinterpret_cast<::xmlChar const*>(u8\"root\"));\n if (not root)\n throw libxml_error{\"failed to create root element\"};\n ::xmlDocSetRootElement(doc, root); \/\/ doc now owns root\n\n \/\/ Add whitespace. Unless you know the whitespace is not significant,\n \/\/ you should do this manually, rather than relying on automatic\n \/\/ indenting.\n add_text(root, reinterpret_cast<::xmlChar const*>(u8\"\\n \"));\n\n \/\/ Add the child element.\n if (auto const res = ::xmlNewTextChild(root, nullptr,\n reinterpret_cast<::xmlChar const*>(u8\"element\"),\n reinterpret_cast<::xmlChar const*>(\n u8\"\\n Some text here\\n \"));\n not res)\n throw libxml_error{\"failed to create child text element\"};\n\n \/\/ Add whitespace.\n add_text(root, reinterpret_cast<::xmlChar const*>(u8\"\\n\"));\n\n \/\/ Output tree. Note that the output is UTF-8 in all cases. If you\n \/\/ want something different, use xmlSaveFileEnc() or the second\n \/\/ argument of xmlSaveDoc().\n if constexpr (no_xml_declaration)\n {\n auto const save_context = ::xmlSaveToFilename(\"-\", nullptr,\n XML_SAVE_NO_DECL);\n auto const save_context_cleanup = scope_exit{[save_context] {\n ::xmlSaveClose(save_context); }};\n\n if (auto const res = ::xmlSaveDoc(save_context, doc); res == -1)\n throw libxml_error{\"failed to write tree to stdout\"};\n }\n else\n {\n if (auto const res = ::xmlSaveFile(\"-\", doc); res == -1)\n throw libxml_error{\"failed to write tree to stdout\"};\n }\n }\n catch (std::exception const& x)\n {\n std::cerr << \"ERROR: \" << x.what() << '\\n';\n return EXIT_FAILURE;\n }\n}\n\n","human_summarization":"Create a simple DOM and serialize it into the specified XML format.","id":820} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n\nint main( ) {\n boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ;\n std::cout << to_simple_string( t ) << std::endl ;\n return 0 ;\n}\n\n#include \n#include \/\/for conversion std::ctime()\n#include \n\nint main() {\n auto timenow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());\n std::cout << std::ctime(&timenow) << std::endl;\n}\n\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The code is related to the task of date formatting and is compiled under Linux using g++ with the boost_date_time library.","id":821} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n\n \ntemplate\nauto sedol_checksum(std::string const& sedol, result_sink_t result_sink)\n{\n if(sedol.size() != 6) \n return result_sink(0, \"length of sedol string\u00a0!= 6\");\n \n const char * valid_chars = \"BCDFGHJKLMNPQRSTVWXYZ0123456789\";\n if(sedol.find_first_not_of(valid_chars) != std::string::npos)\n return result_sink(0, \"sedol string contains disallowed characters\");\n \n const int weights[] = {1,3,1,7,3,9}; \n auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0\n , [](int acc, int prod){ return acc + prod; }\n , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; }\n );\n return result_sink((10 - (weighted_sum % 10)) % 10, nullptr);\n}\n\nint main()\n{\n using namespace std; \n string inputs[] = {\n \"710889\", \"B0YBKJ\", \"406566\", \"B0YBLH\", \"228276\", \"B0YBKL\", \n \"557910\", \"B0YBKR\", \"585284\", \"B0YBKT\", \"B00030\"\n }; \n for(auto const & sedol : inputs)\n {\n sedol_checksum(sedol, [&](auto sum, char const * errorMessage)\n {\n if(errorMessage)\n cout << \"error for sedol: \" << sedol << \" message: \" << errorMessage << \"\\n\";\n else\n cout << sedol << sum << \"\\n\"; \n });\n }\n return 0;\n}\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":822} {"lang_cluster":"C++","source_code":"\nLibrary: Qt\n\/\/ Based on https:\/\/www.cairographics.org\/samples\/gradient\/\n\n#include \n#include \n\nint main() {\n const QColor black(0, 0, 0);\n const QColor white(255, 255, 255);\n\n const int size = 300;\n const double diameter = 0.6 * size;\n\n QImage image(size, size, QImage::Format_RGB32);\n QPainter painter(&image);\n painter.setRenderHint(QPainter::Antialiasing);\n\n QLinearGradient linearGradient(0, 0, 0, size);\n linearGradient.setColorAt(0, white);\n linearGradient.setColorAt(1, black);\n\n QBrush brush(linearGradient);\n painter.fillRect(QRect(0, 0, size, size), brush);\n\n QPointF point1(0.4 * size, 0.4 * size);\n QPointF point2(0.45 * size, 0.4 * size);\n QRadialGradient radialGradient(point1, size * 0.5, point2, size * 0.1);\n radialGradient.setColorAt(0, white);\n radialGradient.setColorAt(1, black);\n\n QBrush brush2(radialGradient);\n painter.setPen(Qt::NoPen);\n painter.setBrush(brush2);\n painter.drawEllipse(QRectF((size - diameter)\/2, (size - diameter)\/2, diameter, diameter));\n\n image.save(\"sphere.png\");\n return 0;\n}\n\n\n","human_summarization":"represent the functionality to draw a sphere either graphically or in ASCII art, with the option for static or rotational projection, depending on the language capabilities.","id":823} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nusing namespace std;\n\nstring Suffix(int num)\n{\n switch (num % 10)\n {\n case 1 : if(num % 100 != 11) return \"st\";\n break;\n case 2 : if(num % 100 != 12) return \"nd\";\n break;\n case 3 : if(num % 100 != 13) return \"rd\";\n }\n\n return \"th\";\n}\n\nint main()\n{\n cout << \"Set [0,25]:\" << endl;\n for (int i = 0; i < 26; i++)\n cout << i << Suffix(i) << \" \";\n \n cout << endl;\n\n cout << \"Set [250,265]:\" << endl;\n for (int i = 250; i < 266; i++)\n cout << i << Suffix(i) << \" \";\n \n cout << endl;\n\n cout << \"Set [1000,1025]:\" << endl;\n for (int i = 1000; i < 1026; i++)\n cout << i << Suffix(i) << \" \";\n \n cout << endl;\n\n return 0;\n}\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":824} {"lang_cluster":"C++","source_code":"\nWorks with: C++11\n#include \n#include \n#include \n\nstd::string stripchars(std::string str, const std::string &chars)\n{\n str.erase(\n std::remove_if(str.begin(), str.end(), [&](char c){\n return chars.find(c) != std::string::npos;\n }),\n str.end()\n );\n return str;\n}\n\nint main()\n{\n std::cout << stripchars(\"She was a soul stripper. She took my heart!\", \"aei\") << '\\n';\n return 0;\n}\n\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":825} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n\nclass pair {\npublic:\n pair( int s, std::string z ) { p = std::make_pair( s, z ); }\n bool operator < ( const pair& o ) const { return i() < o.i(); }\n int i() const { return p.first; }\n std::string s() const { return p.second; }\nprivate:\n std::pair p;\n};\nvoid gFizzBuzz( int c, std::vector& v ) {\n bool output;\n for( int x = 1; x <= c; x++ ) {\n output = false;\n for( std::vector::iterator i = v.begin(); i != v.end(); i++ ) {\n if( !( x % ( *i ).i() ) ) {\n std::cout << ( *i ).s();\n output = true;\n }\n }\n if( !output ) std::cout << x;\n std::cout << \"\\n\";\n }\n}\nint main( int argc, char* argv[] ) {\n std::vector v;\n v.push_back( pair( 7, \"Baxx\" ) );\n v.push_back( pair( 3, \"Fizz\" ) );\n v.push_back( pair( 5, \"Buzz\" ) );\n std::sort( v.begin(), v.end() );\n gFizzBuzz( 20, v );\n return 0;\n}\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":826} {"lang_cluster":"C++","source_code":"\ninclude \n#include \n#include \n#include \n\nint main( ) {\n std::vector myStrings { \"prepended to\" , \"my string\" } ;\n std::string prepended = std::accumulate( myStrings.begin( ) , \n\t myStrings.end( ) , std::string( \"\" ) , []( std::string a , \n\t std::string b ) { return a + b ; } ) ;\n std::cout << prepended << std::endl ;\n return 0 ;\n}\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":827} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n\n\/\/-----------------------------------------------------------------------------------------\nusing namespace std;\n\n\/\/-----------------------------------------------------------------------------------------\nconst int BMP_SIZE = 800, NORTH = 1, EAST = 2, SOUTH = 4, WEST = 8, LEN = 1;\n\n\/\/-----------------------------------------------------------------------------------------\nclass myBitmap\n{\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap()\n {\n\tDeleteObject( pen ); DeleteObject( brush );\n\tDeleteDC( hdc ); DeleteObject( bmp );\n }\n\n bool create( int w, int h )\n {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes = 1;\n\tbi.bmiHeader.biWidth = w;\n\tbi.bmiHeader.biHeight = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n\n\twidth = w; height = h;\n\treturn true;\n }\n\n void clear( BYTE clr = 0 )\n {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n\n void setBrushColor( DWORD bClr )\n {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n }\n\n void setPenColor( DWORD c )\n {\n\tclr = c; createPen();\n }\n\n void setPenWidth( int w )\n {\n\twid = w; createPen();\n }\n\n void saveBitmap( string path )\n {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO infoheader;\n\tBITMAP bitmap;\n\tDWORD wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n }\n\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\n\nprivate:\n void createPen()\n {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n }\n\n HBITMAP bmp;\n HDC hdc;\n HPEN pen;\n HBRUSH brush;\n void *pBits;\n int width, height, wid;\n DWORD clr;\n};\n\/\/-----------------------------------------------------------------------------------------\nclass dragonC\n{\npublic:\n dragonC() { bmp.create( BMP_SIZE, BMP_SIZE ); dir = WEST; }\n void draw( int iterations ) { generate( iterations ); draw(); }\n\nprivate:\n void generate( int it )\n {\n\tgenerator.push_back( 1 );\n\tstring temp;\n\n\tfor( int y = 0; y < it - 1; y++ )\n\t{\n\t temp = generator; temp.push_back( 1 );\n\t for( string::reverse_iterator x = generator.rbegin(); x != generator.rend(); x++ )\n\t\ttemp.push_back( !( *x ) );\n\n\t generator = temp;\n\t}\n }\n\n void draw()\n {\n\tHDC dc = bmp.getDC();\n\tunsigned int clr[] = { 0xff, 0xff00, 0xff0000, 0x00ffff };\n\tint mov[] = { 0, 0, 1, -1, 1, -1, 1, 0 }; int i = 0;\n\n\tfor( int t = 0; t < 4; t++ )\n\t{\n\t int a = BMP_SIZE \/ 2, b = a; a += mov[i++]; b += mov[i++];\n\t MoveToEx( dc, a, b, NULL );\n\n\t bmp.setPenColor( clr[t] );\n\t for( string::iterator x = generator.begin(); x < generator.end(); x++ )\n\t {\n\t\tswitch( dir )\n\t\t{\n\t\t case NORTH:\n\t\t\tif( *x ) { a += LEN; dir = EAST; }\n\t\t\telse { a -= LEN; dir = WEST; }\t\t\t\t\n\t\t break;\n\t\t case EAST:\n\t\t\tif( *x ) { b += LEN; dir = SOUTH; }\n\t\t\telse { b -= LEN; dir = NORTH; }\n\t\t break;\n\t\t case SOUTH:\n\t\t\tif( *x ) { a -= LEN; dir = WEST; }\n\t\t\telse { a += LEN; dir = EAST; }\n\t\t break;\n\t\t case WEST:\n\t\t\tif( *x ) { b -= LEN; dir = NORTH; }\n\t\t\telse { b += LEN; dir = SOUTH; }\n\t\t}\n\t LineTo( dc, a, b );\n\t }\n\t}\n\t\/\/\u00a0!!! change this path\u00a0!!!\n\tbmp.saveBitmap( \"f:\/rc\/dragonCpp.bmp\" );\n }\n\t\n int dir;\n myBitmap bmp;\n string generator;\n};\n\/\/-----------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n dragonC d; d.draw( 17 );\n return system( \"pause\" );\n}\n\/\/-----------------------------------------------------------------------------------------\n\n","human_summarization":"The code generates a dragon curve fractal, either displaying it directly or writing it to an image file. It uses various algorithms including recursive, successive approximation, iterative, and absolute direction methods. The code also includes functionality for calculating absolute X,Y coordinates of a point, testing whether a given X,Y point or segment is on the curve, and generating the curve as a Lindenmayer system of expansions. The generated curve is then saved to the hard drive.","id":828} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n\nint main()\n{\n srand(time(0));\n int n = 1 + (rand() % 10);\n int g;\n std::cout << \"I'm thinking of a number between 1 and 10.\\nTry to guess it! \";\n while(true)\n {\n std::cin >> g;\n if (g == n)\n break;\n else\n std::cout << \"That's not my number.\\nTry another guess! \";\n }\n std::cout << \"You've guessed my number!\";\n return 0;\n}\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":829} {"lang_cluster":"C++","source_code":"\n\nWorks with: C++11\n#include \n#include \n\nint main() {\n std::string lower(26,' ');\n\n std::iota(lower.begin(), lower.end(), 'a');\n}\n\n","human_summarization":"generate an array, list, or string of all lower case ASCII characters from 'a' to 'z' using a reliable coding style and strong typing. The codes also demonstrate how to access a similar sequence from the standard library if it exists. The approach avoids manually enumerating all lowercase characters to prevent bugs. The functionality can be implemented identically in C and C++ or using a STL function in C++.","id":830} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n \nvoid print_bin(unsigned int n) {\n std::string str = \"0\";\n\n if (n > 0) {\n str = std::bitset::digits>(n).to_string();\n str = str.substr(str.find('1')); \/\/ remove leading zeros\n } \n \n std::cout << str << '\\n';\n}\n\nint main() {\n print_bin(0);\n print_bin(5);\n print_bin(50);\n print_bin(9000);\n}\n\n\n","human_summarization":"The code takes a non-negative integer as input and generates a sequence of binary digits corresponding to the input integer. It can use built-in radix functions or a user-defined function for this conversion. The output is a string of binary digits followed by a newline, without any leading zeros, whitespace, radix, or sign markers. The code also includes a shorter version using a bitset and the '>>' operator, and another version using bitwise operations with recursion.","id":831} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstruct Patient\n{\n string ID;\n string LastName;\n};\n\nstruct Visit\n{\n string PatientID;\n string Date;\n optional Score;\n};\n\nint main(void) \n{\n auto patients = vector {\n {\"1001\", \"Hopper\"},\n {\"4004\", \"Wirth\"},\n {\"3003\", \"Kemeny\"},\n {\"2002\", \"Gosling\"},\n {\"5005\", \"Kurtz\"}};\n\n auto visits = vector { \n {\"2002\", \"2020-09-10\", 6.8},\n {\"1001\", \"2020-09-17\", 5.5},\n {\"4004\", \"2020-09-24\", 8.4},\n {\"2002\", \"2020-10-08\", },\n {\"1001\", \"\" , 6.6},\n {\"3003\", \"2020-11-12\", },\n {\"4004\", \"2020-11-05\", 7.0},\n {\"1001\", \"2020-11-19\", 5.3}};\n\n \/\/ sort the patients by ID\n sort(patients.begin(), patients.end(), \n [](const auto& a, const auto&b){ return a.ID < b.ID;}); \n\n cout << \"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\\n\";\n for(const auto& patient : patients)\n {\n \/\/ loop over all of the patients and determine the fields\n string lastVisit;\n float sum = 0;\n int numScores = 0;\n \n \/\/ use C++20 ranges to filter the visits by patients\n auto patientFilter = [&patient](const Visit &v){return v.PatientID == patient.ID;};\n for(const auto& visit : visits | views::filter( patientFilter ))\n {\n if(visit.Score)\n {\n sum += *visit.Score;\n numScores++;\n }\n lastVisit = max(lastVisit, visit.Date);\n }\n \n \/\/ format the output\n cout << \"| \" << patient.ID << \" | \";\n cout.width(8); cout << patient.LastName << \" | \";\n cout.width(10); cout << lastVisit << \" | \";\n if(numScores > 0)\n {\n cout.width(9); cout << sum << \" | \";\n cout.width(9); cout << (sum \/ float(numScores));\n }\n else cout << \" | \";\n cout << \" |\\n\";\n }\n}\n\n\n","human_summarization":"\"Merge and aggregate two provided .csv datasets into a new dataset. The data is grouped by patient id and last name, with calculations for the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in-memory or written to a file. The code is particularly suitable for data science and data processing programming languages like F#, Python, R, SPSS, MATLAB etc. and utilizes C++20.\"","id":832} {"lang_cluster":"C++","source_code":"\nLibrary: Boost\nWorks with: Visual Studio version 2005\n\n#include \"stdafx.h\"\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace boost;\n\ntypedef boost::tokenizer > Tokenizer;\nstatic const char_separator sep(\" \",\"#;,\");\n\n\/\/Assume that the config file represent a struct containing all the parameters to load\nstruct configs{\n\tstring fullname;\n\tstring favoritefruit;\n\tbool needspelling;\n\tbool seedsremoved;\n\tvector otherfamily;\n} conf;\n\nvoid parseLine(const string &line, configs &conf)\n{\n\tif (line[0] == '#' || line.empty())\n\t\treturn;\n\tTokenizer tokenizer(line, sep);\n\tvector tokens;\n\tfor (Tokenizer::iterator iter = tokenizer.begin(); iter != tokenizer.end(); iter++)\n\t\ttokens.push_back(*iter);\n\tif (tokens[0] == \";\"){\n\t\talgorithm::to_lower(tokens[1]);\n\t\tif (tokens[1] == \"needspeeling\")\n\t\t\tconf.needspelling = false;\n\t\tif (tokens[1] == \"seedsremoved\")\n\t\t\tconf.seedsremoved = false;\n\t}\n\talgorithm::to_lower(tokens[0]);\n\tif (tokens[0] == \"needspeeling\")\n\t\tconf.needspelling = true;\n\tif (tokens[0] == \"seedsremoved\")\n\t\tconf.seedsremoved = true;\n\tif (tokens[0] == \"fullname\"){\n\t\tfor (unsigned int i=1; i\" << endl;\n\t\treturn -1;\n\t}\n\tifstream file (argv[1]);\n\t\n\tif (file.is_open())\n\t\twhile(file.good())\n\t\t{\n\t\t\tchar line[255];\n\t\t\tfile.getline(line, 255);\n\t\t\tstring linestring(line);\n\t\t\tparseLine(linestring, conf);\n\t\t}\n\telse\n\t{\n\t\tcout << \"Unable to open the file\" << endl;\n\t\treturn -2;\n\t}\n\n\tcout << \"Fullname= \" << conf.fullname << endl;\n\tcout << \"Favorite Fruit= \" << conf.favoritefruit << endl;\n\tcout << \"Need Spelling= \" << (conf.needspelling?\"True\":\"False\") << endl;\n\tcout << \"Seed Removed= \" << (conf.seedsremoved?\"True\":\"False\") << endl;\n\tstring otherFamily;\n\tfor (unsigned int i = 0; i < conf.otherfamily.size(); i++)\n\t\totherFamily += conf.otherfamily[i] + \", \";\n\totherFamily.erase(otherFamily.size()-2, 2);\n\tcout << \"Other Family= \" << otherFamily << endl;\n\n\treturn 0;\n}\n\n\n","human_summarization":"The code reads a standard configuration file, ignoring lines starting with a hash or semicolon and blank lines. It sets variables based on the configuration entries, treating configuration option names as case insensitive and configuration parameter data as case sensitive. It supports optional equal signs to separate configuration parameter data from the option name and allows multiple parameters separated by commas for a configuration option. The code sets four variables: fullname, favouritefruit, needspeeling, and seedsremoved, and stores multiple parameters in an array. The solution doesn't use Boost libraries and is not optimized.","id":833} {"lang_cluster":"C++","source_code":"\n#define _USE_MATH_DEFINES\n\n#include \n#include \n\nconst static double EarthRadiusKm = 6372.8;\n\ninline double DegreeToRadian(double angle)\n{\n\treturn M_PI * angle \/ 180.0;\n}\n\nclass Coordinate\n{\npublic:\n\tCoordinate(double latitude ,double longitude):myLatitude(latitude), myLongitude(longitude)\n\t{}\n\n\tdouble Latitude() const\n\t{\n\t\treturn myLatitude;\n\t}\n\n\tdouble Longitude() const\n\t{\n\t\treturn myLongitude;\n\t}\n\nprivate:\n\n\tdouble myLatitude;\n\tdouble myLongitude;\n};\n\ndouble HaversineDistance(const Coordinate& p1, const Coordinate& p2)\n{\n\tdouble latRad1 = DegreeToRadian(p1.Latitude());\n\tdouble latRad2 = DegreeToRadian(p2.Latitude());\n\tdouble lonRad1 = DegreeToRadian(p1.Longitude());\n\tdouble lonRad2 = DegreeToRadian(p2.Longitude());\n\n\tdouble diffLa = latRad2 - latRad1;\n\tdouble doffLo = lonRad2 - lonRad1;\n\n\tdouble computation = asin(sqrt(sin(diffLa \/ 2) * sin(diffLa \/ 2) + cos(latRad1) * cos(latRad2) * sin(doffLo \/ 2) * sin(doffLo \/ 2)));\n\treturn 2 * EarthRadiusKm * computation;\n}\n\nint main()\n{\n\tCoordinate c1(36.12, -86.67);\n\tCoordinate c2(33.94, -118.4);\n\n\tstd::cout << \"Distance = \" << HaversineDistance(c1, c2) << std::endl;\n\treturn 0;\n}\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":834} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n\nint main() {\n\tWSADATA wsaData;\n\tWSAStartup( MAKEWORD( 2, 2 ), &wsaData );\n\n\taddrinfo *result = NULL;\n\taddrinfo hints;\n\n\tZeroMemory( &hints, sizeof( hints ) );\n\thints.ai_family = AF_UNSPEC;\n\thints.ai_socktype = SOCK_STREAM;\n\thints.ai_protocol = IPPROTO_TCP;\n\n\tgetaddrinfo( \"74.125.45.100\", \"80\", &hints, &result ); \/\/ http:\/\/www.google.com\n\n\tSOCKET s = socket( result->ai_family, result->ai_socktype, result->ai_protocol );\n\n\tconnect( s, result->ai_addr, (int)result->ai_addrlen );\n\n\tfreeaddrinfo( result );\n\n\tsend( s, \"GET \/ HTTP\/1.0\\n\\n\", 16, 0 );\n\n\tchar buffer[512];\n\tint bytes;\n\n\tdo {\n\t\tbytes = recv( s, buffer, 512, 0 );\n\n\t\tif ( bytes > 0 )\n\t\t\tstd::cout.write(buffer, bytes);\n\t} while ( bytes > 0 );\n\n\treturn 0;\n}\n\nLibrary: U++\n#include \n\nusing namespace Upp;\n\nCONSOLE_APP_MAIN\n{\n\tCout() << HttpClient(\"www.rosettacode.org\").ExecuteRedirect();\n}\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":835} {"lang_cluster":"C++","source_code":"\n#include \nusing namespace std;\n\nint toInt(const char c)\n{\n return c-'0';\n}\n\nint confirm( const char *id)\n{\n bool is_odd_dgt = true;\n int s = 0;\n const char *cp;\n\n for(cp=id; *cp; cp++);\n while(cp > id) {\n --cp;\n int k = toInt(*cp);\n if (is_odd_dgt) {\n s += k;\n }\n else {\n s += (k!=9)? (2*k)%9 : 9;\n }\n\tis_odd_dgt = !is_odd_dgt;\n }\n return 0 == s%10;\n}\n\nint main( )\n{\n const char * t_cases[] = {\n \"49927398716\",\n \"49927398717\",\n \"1234567812345678\",\n \"1234567812345670\",\n NULL,\n };\n for ( const char **cp = t_cases; *cp; cp++) {\n cout << *cp << \": \" << confirm(*cp) << endl;\n }\n return 0;\n}\n\n#include \n#include \n#include \nusing namespace std;\n\nbool luhn( const string& id)\n{\n static const int m[10] = {0,2,4,6,8,1,3,5,7,9}; \/\/ mapping for rule 3\n bool is_odd_dgt = false;\n auto lambda = [&](int a, char c) {return a + ((is_odd_dgt = !is_odd_dgt) ? c-'0' : m[c-'0']);};\n int s = std::accumulate(id.rbegin(), id.rend(), 0, lambda);\n return 0 == s%10;\n}\n\nint main( )\n{\n auto t_cases = {\"49927398716\", \"49927398717\", \"1234567812345678\", \"1234567812345670\"};\n auto print = [](const string & s) {cout << s << \": \" << luhn(s) << endl;};\n for_each(t_cases.begin(), t_cases.end(), print);\n return 0;\n}\n\n\n#include \n#include \n\ntemplate\nstruct find_impl;\n\ntemplate\nstruct find_impl<0, A, Args...> {\n using type = std::integral_constant;\n};\n\ntemplate\nstruct find_impl<0, A, B, Args...> {\n using type = std::integral_constant;\n};\n\ntemplate\nstruct find_impl {\n using type = typename find_impl::type;\n};\n\nnamespace detail {\ntemplate\nstruct append_sequence\n{};\n\ntemplate\nstruct append_sequence> {\n using type = std::tuple;\n};\n\ntemplate\nstruct reverse_sequence {\n using type = std::tuple<>;\n};\n\ntemplate\nstruct reverse_sequence {\n using type = typename append_sequence<\n T,\n typename reverse_sequence::type\n >::type;\n};\n}\n\ntemplate\nusing rule3 = typename find_impl::type;\n\ntemplate\nstruct calc\n : std::integral_constant\n{};\n\ntemplate\nstruct calc\n : std::integral_constant::type::value>\n{};\n\ntemplate\nstruct luhn_impl;\n\ntemplate\nstruct luhn_impl {\n using type = typename calc::type;\n};\n\ntemplate\nstruct luhn_impl {\n using type =\n typename luhn_impl::type, !Dgt, B, Args...>::type;\n};\n\ntemplate\nstruct luhn;\n\ntemplate\nstruct luhn> {\n using type = typename luhn_impl, true, Args::value...>::type;\n constexpr static bool result = (type::value % 10) == 0;\n};\n\ntemplate\nbool operator \"\" _luhn() {\n return luhn...>::type>::result;\n}\n\nint main() {\n std::cout << std::boolalpha;\n std::cout << 49927398716_luhn << std::endl;\n std::cout << 49927398717_luhn << std::endl;\n std::cout << 1234567812345678_luhn << std::endl;\n std::cout << 1234567812345670_luhn << std::endl;\n return 0;\n}\n\ntrue\nfalse\nfalse\ntrue\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It first reverses the order of the digits in the number. Then, it forms a partial sum (s1) by summing the first, third, and every other odd digit in the reversed digits. For the even digits in the reversed number, it multiplies each digit by two and sums the digits if the result is greater than nine to form partial sums. It then sums these partial sums to form another sum (s2). If the total sum of s1 and s2 ends in zero, the original number is a valid credit card number. The code performs this validation for the numbers 49927398716, 49927398717, 1234567812345678, and 1234567812345670. It can also be implemented at compile-time using metaprogramming.","id":836} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\n\/\/--------------------------------------------------------------------------------------------------\nusing namespace std;\ntypedef unsigned long long bigint;\n\n\/\/--------------------------------------------------------------------------------------------------\nclass josephus\n{\npublic:\n bigint findSurvivors( bigint n, bigint k, bigint s = 0 )\n {\n\tbigint i = s + 1;\n\tfor( bigint x = i; x <= n; x++, i++ )\n\t s = ( s + k ) % i;\n\n\treturn s;\n }\n\n void getExecutionList( bigint n, bigint k, bigint s = 1 )\n {\n\tcout << endl << endl << \"Execution list: \" << endl;\n\n\tprisoners.clear();\n\tfor( bigint x = 0; x < n; x++ )\n\t prisoners.push_back( x );\n\n\tbigint index = 0;\n\twhile( prisoners.size() > s )\n\t{\n\t index += k - 1;\n\t if( index >= prisoners.size() ) index %= prisoners.size();\n\t cout << prisoners[static_cast( index )] << \", \";\n\n\t vector::iterator it = prisoners.begin() + static_cast( index );\n\t prisoners.erase( it );\n\t}\n }\n\nprivate:\n vector prisoners;\n};\n\/\/--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n josephus jo;\n bigint n, k, s;\n while( true )\n {\n\tsystem( \"cls\" );\n\tcout << \"Number of prisoners( 0 to QUIT ): \"; cin >> n;\n\tif( !n ) return 0;\n\tcout << \"Execution step: \"; cin >> k;\n\tcout << \"How many survivors: \"; cin >> s;\n\t\t\n\tcout << endl << \"Survivor\";\n\tif( s == 1 )\n\t{\n\t cout << \": \" << jo.findSurvivors( n, k );\n\t jo.getExecutionList( n, k );\n\t}\n\telse\n\t{\n\t cout << \"s: \";\n\t for( bigint x = 0; x < s; x++ )\n\t\tcout << jo.findSurvivors( n, k, x ) << \", \";\n\n\t jo.getExecutionList( n, k, s );\n\t}\n\n\tcout << endl << endl;\n\tsystem( \"pause\" );\n }\n return 0;\n}\n\/\/--------------------------------------------------------------------------------------------------\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":837} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nstd::string repeat( const std::string &word, int times ) {\n std::string result ;\n result.reserve(times*word.length()); \/\/ avoid repeated reallocation\n for ( int a = 0 ; a < times ; a++ ) \n result += word ;\n return result ;\n}\n\nint main( ) {\n std::cout << repeat( \"Ha\" , 5 ) << std::endl ;\n return 0 ;\n}\n\n\n#include \n#include \n\nint main( ) {\n std::cout << std::string( 5, '*' ) << std::endl ;\n return 0 ;\n}\n\n#include \n#include \n \nstd::string repeat( const std::string &word, uint times ) {\n return\n times == 0 ? \"\" :\n times == 1 ? word :\n times == 2 ? word + word :\n repeat(repeat(word, times \/ 2), 2) +\n repeat(word, times % 2);\n}\n\nint main( ) {\n std::cout << repeat( \"Ha\" , 5 ) << std::endl ;\n return 0 ;\n}\n\n","human_summarization":"\"Implements a function to repeat a given string or a single character a specified number of times.\"","id":838} {"lang_cluster":"C++","source_code":"\nWorks with: g++ version 4.0.2 (may need to be retested?)\n\n#include \n#include \n#include \n#include \n\nint main()\n{\n std::regex re(\".* string$\");\n std::string s = \"Hi, I am a string\";\n\n \/\/ match the complete string\n if (std::regex_match(s, re))\n std::cout << \"The string matches.\\n\";\n else\n std::cout << \"Oops - not found?\\n\";\n\n \/\/ match a substring\n std::regex re2(\" a.*a\");\n std::smatch match;\n if (std::regex_search(s, match, re2))\n {\n std::cout << \"Matched \" << match.length()\n << \" characters starting at \" << match.position() << \".\\n\";\n std::cout << \"Matched character sequence: \\\"\"\n << match.str() << \"\\\"\\n\";\n }\n else\n {\n std::cout << \"Oops - not found?\\n\";\n }\n\n \/\/ replace a substring\n std::string dest_string;\n std::regex_replace(std::back_inserter(dest_string),\n s.begin(), s.end(),\n re2,\n \"'m now a changed\");\n std::cout << dest_string << std::endl;\n}\n\n","human_summarization":"utilize Boost's Regex library to match a string against a regular expression and substitute part of the string using a regular expression in standards earlier than C++11.","id":839} {"lang_cluster":"C++","source_code":"\n#include \n\nint main()\n{\n int a, b;\n std::cin >> a >> b;\n std::cout << \"a+b = \" << a+b << \"\\n\";\n std::cout << \"a-b = \" << a-b << \"\\n\";\n std::cout << \"a*b = \" << a*b << \"\\n\";\n std::cout << \"a\/b = \" << a\/b << \", remainder \" << a%b << \"\\n\";\n return 0;\n}\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":840} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\n\/\/ returns count of non-overlapping occurrences of 'sub' in 'str'\nint countSubstring(const std::string& str, const std::string& sub)\n{\n if (sub.length() == 0) return 0;\n int count = 0;\n for (size_t offset = str.find(sub); offset != std::string::npos;\n\t offset = str.find(sub, offset + sub.length()))\n {\n ++count;\n }\n return count;\n}\n\nint main()\n{\n std::cout << countSubstring(\"the three truths\", \"th\") << '\\n';\n std::cout << countSubstring(\"ababababab\", \"abab\") << '\\n';\n std::cout << countSubstring(\"abaabba*bbaba*bbab\", \"a*b\") << '\\n';\n\n return 0;\n}\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":841} {"lang_cluster":"C++","source_code":"\nWorks with: g++\nvoid move(int n, int from, int to, int via) {\n if (n == 1) {\n std::cout << \"Move disk from pole \" << from << \" to pole \" << to << std::endl;\n } else {\n move(n - 1, from, via, to);\n move(1, from, to, via);\n move(n - 1, via, to, from);\n }\n}\n\nWorks with: Chipmunk Basic version 3.6.4100 cls\n110 print \"Three disks\" : print\n120 hanoi(3,1,2,3)\n130 print chr$(10)\"Four disks\" chr$(10)\n140 hanoi(4,1,2,3)\n150 print : print \"Towers of Hanoi puzzle completed!\"\n160 end\n170 sub hanoi(n,desde,hasta,via)\n180 if n > 0 then\n190 hanoi(n-1,desde,via,hasta)\n200 print \"Move disk \" n \"from pole \" desde \"to pole \" hasta\n210 hanoi(n-1,via,hasta,desde)\n220 endif\n230 end sub\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":842} {"lang_cluster":"C++","source_code":"\ndouble Factorial(double nValue)\n {\n double result = nValue;\n double result_next;\n double pc = nValue;\n do\n {\n result_next = result*(pc-1);\n result = result_next;\n pc--;\n }while(pc>2);\n nValue = result;\n return nValue;\n }\n\ndouble binomialCoefficient(double n, double k)\n {\n if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0;\n if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n;\n return Factorial(n) \/(Factorial(k)*Factorial((n - k)));\n }\n\n\nint main()\n{\n cout<<\"The Binomial Coefficient of 5, and 3, is equal to: \"<< binomialCoefficient(5,3);\n cin.get();\n}\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is capable of outputting the binomial coefficient of 5 choose 3, which equals 10. It also includes tasks related to combinations and permutations, both with and without replacement.","id":843} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\n\/\/--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n\/\/--------------------------------------------------------------------------------------------------\nconst int MAX = 126;\nclass shell\n{\npublic:\n shell() \n { _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }\n\n void sort( int* a, int count )\n {\n\t_cnt = count;\n\tfor( int x = 0; x < 9; x++ )\n\t if( count > _gap[x] )\n\t { _idx = x; break; }\n\n\tsortIt( a );\n }\n\nprivate:\t\n void sortIt( int* arr )\n {\n\tbool sorted = false;\n\twhile( true )\n\t{\n\t sorted = true;\n\t int st = 0;\n\t for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )\n\t {\n\t\tif( arr[st] > arr[x] )\n\t\t{ swap( arr[st], arr[x] ); sorted = false; }\n\t\tst = x;\n\t }\n\t if( ++_idx >= 8 ) _idx = 8;\n\t if( sorted && _idx == 8 ) break;\n\t}\n }\n\n void swap( int& a, int& b ) { int t = a; a = b; b = t; }\n\n int _gap[9], _idx, _cnt;\n};\n\/\/--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n srand( static_cast( time( NULL ) ) ); int arr[MAX];\n for( int x = 0; x < MAX; x++ )\n\tarr[x] = rand() % MAX - rand() % MAX;\n\n cout << \" Before: \\n=========\\n\";\n for( int x = 0; x < 7; x++ )\n {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n }\n cout << endl; shell s; s.sort( arr, MAX );\n\t\n cout << \" After: \\n========\\n\";\n for( int x = 0; x < 7; x++ )\n {\n\tfor( int a = 0; a < 18; a++ )\n\t{ cout << arr[x * 18 + a] << \" \"; }\n\tcout << endl;\n }\n cout << endl << endl; return system( \"pause\" );\n}\n\/\/--------------------------------------------------------------------------------------------------\n\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":844} {"lang_cluster":"C++","source_code":"\nLibrary: Qt\n\n#include \"animationwidget.h\"\n\n#include \n#include \n#include \n\n#include \n\nAnimationWidget::AnimationWidget(QWidget *parent) : QWidget(parent) {\n setWindowTitle(tr(\"Animation\"));\n QFont font(\"Courier\", 24);\n QLabel* label = new QLabel(\"Hello World! \");\n label->setFont(font);\n QVBoxLayout* layout = new QVBoxLayout(this);\n layout->addWidget(label);\n QTimer* timer = new QTimer(this);\n connect(timer, &QTimer::timeout, this, [label,this]() {\n QString text = label->text();\n std::rotate(text.begin(), text.begin() + (right_ ? text.length() - 1 : 1), text.end());\n label->setText(text);\n });\n timer->start(200);\n}\n\nvoid AnimationWidget::mousePressEvent(QMouseEvent*) {\n right_ = !right_;\n}\n\n\n#ifndef ANIMATIONWIDGET_H\n#define ANIMATIONWIDGET_H\n\n#include \n\nclass AnimationWidget : public QWidget {\n Q_OBJECT\npublic:\n AnimationWidget(QWidget *parent = nullptr);\nprotected:\n void mousePressEvent(QMouseEvent *event) override;\nprivate:\n bool right_ = true;\n};\n\n#endif \/\/ ANIMATIONWIDGET_H\n\n\n#include \"animationwidget.h\"\n\n#include \n\nint main(int argc, char *argv[]) {\n QApplication a(argc, argv);\n AnimationWidget w;\n w.show();\n return a.exec();\n}\n\n","human_summarization":"create an animated window displaying the string \"Hello World!\". The animation gives the illusion of the text rotating to the right by periodically moving the last letter to the beginning of the string. The direction of rotation reverses when the user clicks on the text in the window.","id":845} {"lang_cluster":"C++","source_code":"\nint val = 0;\ndo{\n val++;\n std::cout << val << std::endl;\n}while(val % 6 != 0);\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":846} {"lang_cluster":"C++","source_code":"\nWorks with: ISO C++\nWorks with: g++ version 4.0.2\n#include \/\/ (not !)\nusing std::string;\n\nint main()\n{\n string s = \"Hello, world!\";\n string::size_type length = s.length(); \/\/ option 1: In Characters\/Bytes\n string::size_type size = s.size(); \/\/ option 2: In Characters\/Bytes\n \/\/ In bytes same as above since sizeof(char) == 1\n string::size_type bytes = s.length() * sizeof(string::value_type); \n}\n\n\n#include \nusing std::wstring;\n \nint main()\n{\n wstring s = L\"\\u304A\\u306F\\u3088\\u3046\";\n wstring::size_type length = s.length() * sizeof(wstring::value_type); \/\/ in bytes\n}\n\nWorks with: C++98\nWorks with: g++ version 4.0.2\n\n#include \nusing std::wstring;\n\nint main()\n{\n wstring s = L\"\\u304A\\u306F\\u3088\\u3046\";\n wstring::size_type length = s.length();\n}\n\n\nWorks with: C++11\nWorks with: clang++ version 3.0\n#include \n#include \nint main()\n{\n std::string utf8 = \"\\x7a\\xc3\\x9f\\xe6\\xb0\\xb4\\xf0\\x9d\\x84\\x8b\"; \/\/ U+007a, U+00df, U+6c34, U+1d10b\n std::cout << \"Byte length: \" << utf8.size() << '\\n';\n std::wstring_convert, char32_t> conv;\n std::cout << \"Character length: \" << conv.from_bytes(utf8).size() << '\\n';\n}\n\nWorks with: C++98\nWorks with: g++ version 4.1.2 20061115 (prerelease) (SUSE Linux)\n#include \/\/ for mbstate_t\n#include \n\n\/\/ give the character length for a given named locale\nstd::size_t char_length(std::string const& text, char const* locale_name)\n{\n \/\/ locales work on pointers; get length and data from string and\n \/\/ then don't touch the original string any more, to avoid\n \/\/ invalidating the data pointer\n std::size_t len = text.length();\n char const* input = text.data();\n\n \/\/ get the named locale\n std::locale loc(locale_name);\n\n \/\/ get the conversion facet of the locale\n typedef std::codecvt cvt_type;\n cvt_type const& cvt = std::use_facet(loc);\n\n \/\/ allocate buffer for conversion destination\n std::size_t bufsize = cvt.max_length()*len;\n wchar_t* destbuf = new wchar_t[bufsize];\n wchar_t* dest_end;\n\n \/\/ do the conversion\n mbstate_t state = mbstate_t();\n cvt.in(state, input, input+len, input, destbuf, destbuf+bufsize, dest_end);\n\n \/\/ determine the length of the converted sequence\n std::size_t length = dest_end - destbuf;\n\n \/\/ get rid of the buffer\n delete[] destbuf;\n\n \/\/ return the result\n return length;\n}\n\n\n#include \n\nint main()\n{\n \/\/ T\u00fcr (German for door) in UTF8\n std::cout << char_length(\"\\x54\\xc3\\xbc\\x72\", \"de_DE.utf8\") << \"\\n\"; \/\/ outputs 3\n\n \/\/ T\u00fcr in ISO-8859-1\n std::cout << char_length(\"\\x54\\xfc\\x72\", \"de_DE\") << \"\\n\"; \/\/ outputs 3\n}\n\n\n","human_summarization":"The code calculates the character and byte length of a string, correctly handling encodings like UTF-8 and UTF-16. It counts individual Unicode code points as characters, not user-visible graphemes or code unit counts. It also correctly handles non-BMP code points. The code can provide the string length in graphemes if the language supports it. It works with both wide and narrow character strings and is not affected by the encoding used for the source code.","id":847} {"lang_cluster":"C++","source_code":"\n\nWorks with: C++11\n#include \n#include \n \nint main()\n{\n std::random_device rd;\n std::uniform_int_distribution dist; \/\/ long is guaranteed to be 32 bits\n \n std::cout << \"Random Number: \" << dist(rd) << std::endl;\n}\n\n","human_summarization":"demonstrate how to generate a non-deterministic, uniformly-distributed 32-bit random number using std::random_device, provided a hardware device is available for generating random numbers. If such a device is not available, a pseudo-random number engine is used instead.","id":848} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main( ) {\n std::string word( \"Premier League\" ) ;\n std::cout << \"Without first letter: \" << word.substr( 1 ) << \"\u00a0!\\n\" ;\n std::cout << \"Without last letter: \" << word.substr( 0 , word.length( ) - 1 ) << \"\u00a0!\\n\" ;\n std::cout << \"Without first and last letter: \" << word.substr( 1 , word.length( ) - 2 ) << \"\u00a0!\\n\" ;\n return 0 ;\n}\n\n\nWithout first letter: remier League\u00a0!\nWithout last letter: Premier Leagu\u00a0!\nWithout first and last letter: remier Leagu\u00a0!\n\n","human_summarization":"demonstrate how to remove the first, last, or both first and last characters from a string, ensuring compatibility with any valid Unicode code point in UTF-8 or UTF-16 encoding. The program does not support other encodings like 8-bit ASCII or EUC-JP.","id":849} {"lang_cluster":"C++","source_code":"\nWorks with: Windows version 2000 or later\n\n#include \n\n\nHANDLE mutex;\n\n\nmutex = CreateMutex( NULL, TRUE, \"MyApp\" );\nif ( GetLastError() == ERROR_ALREADY_EXISTS )\n{\n \/\/ There's another instance running. What do you do?\n}\n\n\nCloseHandle( mutex );\n\n","human_summarization":"The code checks if an instance of an application is already running. If so, it displays a message and exits. A HANDLE type variable is initialized at the start of the program to perform this check. Finally, the mutex is closed at the end of the program.","id":850} {"lang_cluster":"C++","source_code":"#include \nusing namespace std;\n\nclass SudokuSolver {\nprivate:\n int grid[81];\n\npublic:\n\n SudokuSolver(string s) {\n for (unsigned int i = 0; i < s.length(); i++) {\n grid[i] = (int) (s[i] - '0');\n }\n }\n\n void solve() {\n try {\n placeNumber(0);\n cout << \"Unsolvable!\" << endl;\n } catch (char* ex) {\n cout << ex << endl;\n cout << this->toString() << endl;\n }\n }\n\n void placeNumber(int pos) {\n if (pos == 81) {\n throw (char*) \"Finished!\";\n }\n if (grid[pos] > 0) {\n placeNumber(pos + 1);\n return;\n }\n for (int n = 1; n <= 9; n++) {\n if (checkValidity(n, pos % 9, pos \/ 9)) {\n grid[pos] = n;\n placeNumber(pos + 1);\n grid[pos] = 0;\n }\n }\n }\n\n bool checkValidity(int val, int x, int y) {\n for (int i = 0; i < 9; i++) {\n if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)\n return false;\n }\n int startX = (x \/ 3) * 3;\n int startY = (y \/ 3) * 3;\n for (int i = startY; i < startY + 3; i++) {\n for (int j = startX; j < startX + 3; j++) {\n if (grid[i * 9 + j] == val)\n return false;\n }\n }\n return true;\n }\n\n string toString() {\n string sb;\n for (int i = 0; i < 9; i++) {\n for (int j = 0; j < 9; j++) {\n char c[2];\n c[0] = grid[i * 9 + j] + '0';\n c[1] = '\\0';\n sb.append(c);\n sb.append(\" \");\n if (j == 2 || j == 5)\n sb.append(\"| \");\n }\n sb.append(\"\\n\");\n if (i == 2 || i == 5)\n sb.append(\"------+-------+------\\n\");\n }\n return sb;\n }\n\n};\n\nint main() {\n SudokuSolver ss(\"850002400\"\n \"720000009\"\n \"004000000\"\n \"000107002\"\n \"305000900\"\n \"040000000\"\n \"000080070\"\n \"017000000\"\n \"000036040\");\n ss.solve();\n return EXIT_SUCCESS;\n}\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":851} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n\ntemplate\nvoid knuthShuffle(RandomAccessIterator begin, RandomAccessIterator end) {\n for(unsigned int n = end - begin - 1; n >= 1; --n) {\n unsigned int k = rand() % (n + 1);\n if(k != n) {\n std::iter_swap(begin + k, begin + n);\n }\n }\n}\n\n\n#include \n#include \n\nint main()\n{\n int array[] = { 1,2,3,4,5,6,7,8,9 }; \/\/ C-style array of integers\n std::vector vec(array, array + 9); \/\/ build STL container from int array\n\n std::random_shuffle(array, array + 9); \/\/ shuffle C-style array\n std::random_shuffle(vec.begin(), vec.end()); \/\/ shuffle STL container\n}\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an input array in-place. The shuffling process involves iterating over the array from the last index down to 1, and for each iteration, swapping the current element with a randomly selected element from the range of 0 to the current index. If in-place modification is not possible, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":852} {"lang_cluster":"C++","source_code":"\nLibrary: Boost\n\n#include \n#include \n#include \n\nint main( int argc , char* argv[ ] ) {\n using namespace boost::gregorian ;\n\n greg_month months[ ] = { Jan , Feb , Mar , Apr , May , Jun , Jul ,\n Aug , Sep , Oct , Nov , Dec } ;\n greg_year gy = atoi( argv[ 1 ] ) ;\n for ( int i = 0 ; i < 12 ; i++ ) {\n last_day_of_the_week_in_month lwdm ( Friday , months[ i ] ) ;\n date d = lwdm.get_date( gy ) ;\n std::cout << d << std::endl ;\n }\n return 0 ;\n}\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year. The input is provided through a simple method such as command line or standard input. The code is written in C++20 and does not require external libraries.","id":853} {"lang_cluster":"C++","source_code":"\n#include \n\nint main() {\n std::cout << \"Goodbye, World!\";\n return 0;\n}\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":854} {"lang_cluster":"C++","source_code":"\n\ntask.h\n\n#ifndef TASK_H\n#define TASK_H\n\n#include \n\nclass QLabel ;\nclass QLineEdit ;\nclass QVBoxLayout ;\nclass QHBoxLayout ;\n\nclass EntryWidget : public QWidget {\n\n Q_OBJECT \npublic :\n EntryWidget( QWidget *parent = 0 ) ;\nprivate :\n QHBoxLayout *upperpart , *lowerpart ;\n QVBoxLayout *entryLayout ;\n QLineEdit *stringinput ;\n QLineEdit *numberinput ;\n QLabel *stringlabel ;\n QLabel *numberlabel ;\n} ;\n\n#endif\n\ntask.cpp\n\n#include \n#include \n#include \n#include \n#include \n#include \"task.h\"\n\nEntryWidget::EntryWidget ( QWidget *parent ) \n : QWidget( parent ) {\n entryLayout = new QVBoxLayout( this ) ;\n stringlabel = new QLabel( \"Enter a string!\" ) ;\n stringinput = new QLineEdit( \"\" ) ;\n stringinput->setMaxLength( 20 ) ;\n stringinput->setInputMask( QString( \"AAAAAAAAAAAAAAAAAAA\" ) ) ;\n upperpart = new QHBoxLayout ;\n upperpart->addWidget( stringlabel ) ;\n upperpart->addWidget( stringinput ) ;\n numberlabel = new QLabel( \"Enter a number!\" ) ;\n numberinput = new QLineEdit( \"0\" ) ;\n numberinput->setMaxLength( 5 ) ;\n numberinput->setInputMask( QString( \"99999\" ) ) ;\n lowerpart = new QHBoxLayout ;\n lowerpart->addWidget( numberlabel ) ;\n lowerpart->addWidget( numberinput ) ;\n entryLayout->addLayout( upperpart ) ;\n entryLayout->addLayout( lowerpart ) ;\n setLayout( entryLayout ) ;\n}\n\nmain.cpp\n\n#include \n#include \"task.h\"\n\nint main( int argc , char *argv[ ] ) {\n QApplication app( argc , argv ) ;\n EntryWidget theWidget ;\n theWidget.show( ) ;\n return app.exec( ) ;\n}\n\n","human_summarization":"\"Code uses Qt 4.4 library to create a graphical user interface that accepts a string and the integer 75000 as inputs from the user.\"","id":855} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n\nclass MyTransform {\nprivate : \n int shift ;\npublic :\n MyTransform( int s ) : shift( s ) { } \n\n char operator( )( char c ) {\n if ( isspace( c ) ) \n\t return ' ' ;\n else {\n\t static std::string letters( \"abcdefghijklmnopqrstuvwxyz\" ) ;\n\t std::string::size_type found = letters.find(tolower( c )) ;\n\t int shiftedpos = ( static_cast( found ) + shift ) % 26 ;\n\t if ( shiftedpos < 0 ) \/\/in case of decryption possibly\n\t shiftedpos = 26 + shiftedpos ;\n\t char shifted = letters[shiftedpos] ;\n\t return shifted ;\n }\n }\n} ;\n\nint main( ) {\n std::string input ;\n std::cout << \"Which text is to be encrypted\u00a0?\\n\" ;\n getline( std::cin , input ) ;\n std::cout << \"shift\u00a0?\\n\" ;\n int myshift = 0 ;\n std::cin >> myshift ;\n std::cout << \"Before encryption:\\n\" << input << std::endl ;\n std::transform ( input.begin( ) , input.end( ) , input.begin( ) ,\n\t MyTransform( myshift ) ) ;\n std::cout << \"encrypted:\\n\" ;\n std::cout << input << std::endl ;\n myshift *= -1 ; \/\/decrypting again\n std::transform ( input.begin( ) , input.end( ) , input.begin( ) ,\n\t MyTransform( myshift ) ) ;\n std::cout << \"Decrypted again:\\n\" ;\n std::cout << input << std::endl ;\n return 0 ;\n}\n\n\n","human_summarization":"implement a Caesar cipher for both encoding and decoding. It uses an integer key from 1 to 25 to rotate the letters of the alphabet. The encoding process replaces each letter with the 1st to 25th next letter in the alphabet, wrapping Z to A. The code also includes an alternative version using lambda functions, auto, and iterators. The Caesar cipher is identical to the Vigen\u00e8re cipher with a key of length 1 and to the Rot-13 cipher with a key of 13.","id":856} {"lang_cluster":"C++","source_code":"\nLibrary: Boost\n#include \n#include \n\nint main( ) {\n std::cout << \"The least common multiple of 12 and 18 is \" << \n boost::math::lcm( 12 , 18 ) << \" ,\\n\"\n << \"and the greatest common divisor \" << boost::math::gcd( 12 , 18 ) << \"\u00a0!\" << std::endl ;\n return 0 ;\n}\n\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":857} {"lang_cluster":"C++","source_code":"#include \n#include \n\nbool isCusip(const std::string& s) {\n if (s.size() != 9) return false;\n\n int sum = 0;\n for (int i = 0; i <= 7; ++i) {\n char c = s[i];\n\n int v;\n if ('0' <= c && c <= '9') {\n v = c - '0';\n } else if ('A' <= c && c <= 'Z') {\n v = c - '@';\n } else if (c = '*') {\n v = 36;\n } else if (c = '#') {\n v = 38;\n } else {\n return false;\n }\n if (i % 2 == 1) {\n v *= 2;\n }\n sum += v \/ 10 + v % 10;\n }\n return s[8] - '0' == (10 - (sum % 10)) % 10;\n}\n\nint main() {\n using namespace std;\n\n vector candidates{\n \"037833100\",\n \"17275R102\",\n \"38259P508\",\n \"594918104\",\n \"68389X106\",\n \"68389X105\"\n };\n\n for (auto str : candidates) {\n auto res = isCusip(str) ? \"correct\" : \"incorrect\";\n cout << str.c_str() << \" -> \" << res << \"\\n\";\n }\n\n return 0;\n}\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":858} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main()\n{\n std::cout << \"int is \" << sizeof(int) << \" bytes\\n\";\n std::cout << \"a pointer is \" << sizeof(int*) << \" bytes\\n\\n\";\n\n if (std::endian::native == std::endian::big)\n {\n std::cout << \"platform is big-endian\\n\";\n }\n else\n {\n std::cout << \"host is little-endian\\n\";\n }\n}\n\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":859} {"lang_cluster":"C++","source_code":"\nLibrary: Boost\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstruct Sort { \/\/sorting programming languages according to frequency\n bool operator( ) ( const std::pair & a , const std::pair & b ) \n const {\n\t return a.second > b.second ;\n }\n} ;\n\nint main( ) {\n try {\n \/\/setting up an io service , with templated subelements for resolver and query\n boost::asio::io_service io_service ; \n boost::asio::ip::tcp::resolver resolver ( io_service ) ;\n boost::asio::ip::tcp::resolver::query query ( \"rosettacode.org\" , \"http\" ) ;\n boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve( query ) ;\n boost::asio::ip::tcp::resolver::iterator end ;\n boost::asio::ip::tcp::socket socket( io_service ) ;\n boost::system::error_code error = boost::asio::error::host_not_found ;\n \/\/looking for an endpoint the socket will be able to connect to\n while ( error && endpoint_iterator != end ) {\n\t socket.close( ) ;\n\t socket.connect( *endpoint_iterator++ , error ) ;\n }\n if ( error ) \n\t throw boost::system::system_error ( error ) ;\n \/\/we send a request\n boost::asio::streambuf request ;\n std::ostream request_stream( &request ) ;\n request_stream << \"GET \" << \"\/mw\/index.php?title=Special:Categories&limit=5000\" << \" HTTP\/1.0\\r\\n\" ;\n request_stream << \"Host: \" << \"rosettacode.org\" << \"\\r\\n\" ;\n request_stream << \"Accept: *\/*\\r\\n\" ;\n request_stream << \"Connection: close\\r\\n\\r\\n\" ;\n \/\/send the request\n boost::asio::write( socket , request ) ;\n \/\/we receive the response analyzing every line and storing the programming language \n boost::asio::streambuf response ;\n std::istream response_stream ( &response ) ;\n boost::asio::read_until( socket , response , \"\\r\\n\\r\\n\" ) ;\n boost::regex e( \"

  • ]+?\\\">([a-zA-Z\\\\+#1-9]+?)<\/a>\\\\s?\\\\((\\\\d+) members\\\\)<\/li>\" ) ;\n \/\/using the wrong regex produces incorrect sorting!!\n std::ostringstream line ;\n std::vector > languages ; \/\/holds language and number of examples\n boost::smatch matches ;\n while ( boost::asio::read( socket , response , boost::asio::transfer_at_least( 1 ) , error ) ) {\n\t line << &response ;\n\t if ( boost::regex_search( line.str( ) , matches , e ) ) {\n\t std::string lang( matches[2].first , matches[2].second ) ;\n\t int zahl = atoi ( lang.c_str( ) ) ;\n\t languages.push_back( std::make_pair( matches[ 1 ] , zahl ) ) ;\n\t }\n\t line.str( \"\") ;\/\/we have to erase the string buffer for the next read\n }\n if ( error != boost::asio::error::eof ) \n\t throw boost::system::system_error( error ) ;\n \/\/we sort the vector entries , see the struct above\n std::sort( languages.begin( ) , languages.end( ) , Sort( ) ) ;\n int n = 1 ;\n for ( std::vector >::const_iterator spi = languages.begin( ) ;\n\t spi != languages.end( ) ; ++spi ) {\n\t std::cout << std::setw( 3 ) << std::right << n << '.' << std::setw( 4 ) << std::right << \n\t spi->second << \" - \" << spi->first << '\\n' ;\n\t n++ ;\n }\n } catch ( std::exception &ex ) {\n std::cout << \"Exception: \" << ex.what( ) << '\\n' ;\n }\n return 0 ;\n}\n\n\nSample output (just the \"top ten\"):\n 1. 367 - Tcl\n 2. 334 - Python\n 3. 319 - Ruby\n 4. 286 - C\n 5. 277 - Perl\n 6. 272 - OCaml\n 7. 264 - Ada\n 8. 241 - E\n 9. 239 - AutoHotkey\n10. 193 - Forth\n\n","human_summarization":"The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It can access data through web scraping or using the API method. The code also has the option to filter incorrect results. It generates a complete ranked list of all languages, which can be checked against a periodically updated list of all programming languages. The code is designed to run on Linux using g++.","id":860} {"lang_cluster":"C++","source_code":"\n\nfor (container_type::iterator i = container.begin(); i != container.end(); ++i)\n{\n std::cout << *i << \"\\n\";\n}\n\n\nstd::copy(container.begin(), container.end(),\n std::ostream_iterator(std::cout, \"\\n\"));\n\n\nvoid print_element(container_type::value_type const& v)\n{\n std::cout << v << \"\\n\";\n}\n\n...\n std::for_each(container.begin(), container.end(), print_element);\n\nWorks with: C++11\nfor (auto element: container)\n{\n std::cout << element << \"\\n\";\n}\n\n\nfor (auto const& element: container)\n{\n std::cout << element << \"\\n\";\n}\n\n\nfor (auto&& element: container) \/\/use a 'universal reference'\n{\n element += 42;\n}\n\n","human_summarization":"iterate through each element in a given collection in a sequential manner. The code uses a \"for each\" loop if available in the language, otherwise, it uses another type of loop. In the case of C++03, a generic loop is used as it doesn't support a \"for each\" loop. The code also allows for the modification of container elements using a non-const reference, unless the container is constant.","id":861} {"lang_cluster":"C++","source_code":"\nWorks with: C++98\n\n#include \n#include \n#include \n#include \n#include \n#include \nint main()\n{\n std::string s = \"Hello,How,Are,You,Today\";\n std::vector v;\n std::istringstream buf(s);\n for(std::string token; getline(buf, token, ','); )\n v.push_back(token);\n copy(v.begin(), v.end(), std::ostream_iterator(std::cout, \".\"));\n std::cout << '\\n';\n}\n\nWorks with: C++98\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \nstruct comma_ws : std::ctype {\n static const mask* make_table() {\n static std::vector v(classic_table(), classic_table() + table_size);\n v[','] |= space; \/\/ comma will be classified as whitespace\n return &v[0];\n }\n comma_ws(std::size_t refs = 0) : ctype(make_table(), false, refs) {}\n};\nint main()\n{\n std::string s = \"Hello,How,Are,You,Today\";\n std::istringstream buf(s);\n buf.imbue(std::locale(buf.getloc(), new comma_ws));\n std::istream_iterator beg(buf), end;\n std::vector v(beg, end);\n copy(v.begin(), v.end(), std::ostream_iterator(std::cout, \".\"));\n std::cout << '\\n';\n}\n\nWorks with: C++98\nLibrary: boost\n\n#include \n#include \n#include \n#include \n#include \n#include \nint main()\n{\n std::string s = \"Hello,How,Are,You,Today\";\n boost::tokenizer<> tok(s);\n std::vector v(tok.begin(), tok.end());\n copy(v.begin(), v.end(), std::ostream_iterator(std::cout, \".\"))\n std::cout << '\\n';\n}\n\nWorks with: C++23\n\n#include \n#include \n#include \nint main() {\n std::string s = \"Hello,How,Are,You,Today\";\n s = s \/\/ Assign the final string back to the string variable\n | std::views::split(',') \/\/ Produce a range of the comma separated words\n | std::views::join_with('.') \/\/ Concatenate the words into a single range of characters\n | std::ranges::to(); \/\/ Convert the range of characters into a regular string\n std::cout << s;\n}\n\n","human_summarization":"\"Tokenizes a given string by commas into an array, and displays the words separated by a period using std::getline() function in C++. It takes advantage of C++'s ability to redefine whitespace and the boost library's tokenization options. The code is optimized for C++20 and C++23 for better range manipulation.\"","id":862} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main() {\n std::cout << \"The greatest common divisor of 12 and 18 is \" << std::gcd(12, 18) << \"\u00a0!\\n\";\n}\n\nLibrary: Boost\n#include \n#include \n\nint main() {\n std::cout << \"The greatest common divisor of 12 and 18 is \" << boost::math::gcd(12, 18) << \"!\\n\";\n}\n\n\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":863} {"lang_cluster":"C++","source_code":"\n\n#include \/\/ for istringstream\n\nusing namespace std;\n\nbool isNumeric( const char* pszInput, int nNumberBase )\n{\n\tistringstream iss( pszInput );\n\n\tif ( nNumberBase == 10 )\n\t{\n\t\tdouble dTestSink;\n\t\tiss >> dTestSink;\n\t}\n\telse if ( nNumberBase == 8 || nNumberBase == 16 )\n\t{\n\t\tint nTestSink;\n\t\tiss >> ( ( nNumberBase == 8 ) ? oct : hex ) >> nTestSink;\n\t}\n\telse\n\t\treturn false;\n\n\t\/\/ was any input successfully consumed\/converted?\n\tif ( ! iss )\n\t\treturn false;\n\n\t\/\/ was all the input successfully consumed\/converted?\n\treturn ( iss.rdbuf()->in_avail() == 0 );\n}\n\n\nbool isNumeric( const char* pszInput, int nNumberBase )\n{\n\tstring base = \"0123456789ABCDEF\";\n\tstring input = pszInput;\n\n\treturn (input.find_first_not_of(base.substr(0, nNumberBase)) == string::npos);\n}\n\n\nbool isNumeric(const std::string& input) {\n return std::all_of(input.begin(), input.end(), ::isdigit);\n}\n\n","human_summarization":"\"Implement a boolean function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, using the syntax of numeric literals or numbers converted from strings. This is achieved using stringstream, find, and all_of (C++11 required).\"","id":864} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n\nstruct vec2 {\n float x = 0.0f, y = 0.0f;\n\n constexpr vec2 operator+(vec2 other) const {\n return vec2{x + other.x, y + other.y};\n }\n\n constexpr vec2 operator-(vec2 other) const {\n return vec2{x - other.x, y - other.y};\n }\n};\n\nconstexpr vec2 operator*(vec2 a, float b) { return vec2{a.x * b, a.y * b}; }\n\nconstexpr float dot(vec2 a, vec2 b) { return a.x * b.x + a.y * b.y; }\n\nconstexpr float cross(vec2 a, vec2 b) { return a.x * b.y - b.x * a.y; }\n\n\/\/ check if a point is on the LEFT side of an edge\nconstexpr bool is_inside(vec2 point, vec2 a, vec2 b) {\n return (cross(a - b, point) + cross(b, a)) < 0.0f;\n}\n\n\/\/ calculate intersection point\nconstexpr vec2 intersection(vec2 a1, vec2 a2, vec2 b1, vec2 b2) {\n return ((b1 - b2) * cross(a1, a2) - (a1 - a2) * cross(b1, b2)) *\n (1.0f \/ cross(a1 - a2, b1 - b2));\n}\n\n\/\/ Sutherland-Hodgman clipping\nstd::vector suther_land_hodgman(\n std::span subject_polygon, std::span clip_polygon) {\n if (clip_polygon.empty() || subject_polygon.empty()) {\n return {};\n }\n\n std::vector ring{subject_polygon.begin(), subject_polygon.end()};\n\n vec2 p1 = clip_polygon[clip_polygon.size() - 1];\n\n std::vector input;\n\n for (vec2 p2 : clip_polygon) {\n input.clear();\n input.insert(input.end(), ring.begin(), ring.end());\n vec2 s = input[input.size() - 1];\n\n ring.clear();\n\n for (vec2 e : input) {\n if (is_inside(e, p1, p2)) {\n if (!is_inside(s, p1, p2)) {\n ring.push_back(intersection(p1, p2, s, e));\n }\n\n ring.push_back(e);\n } else if (is_inside(s, p1, p2)) {\n ring.push_back(intersection(p1, p2, s, e));\n }\n\n s = e;\n }\n\n p1 = p2;\n }\n\n return ring;\n}\n\nint main(int argc, char **argv) {\n \/\/ subject polygon\n vec2 subject_polygon[] = {{50, 150}, {200, 50}, {350, 150},\n {350, 300}, {250, 300}, {200, 250},\n {150, 350}, {100, 250}, {100, 200}};\n\n \/\/ clipping polygon\n vec2 clip_polygon[] = {{100, 100}, {300, 100}, {300, 300}, {100, 300}};\n\n \/\/ apply clipping\n std::vector clipped_polygon =\n suther_land_hodgman(subject_polygon, clip_polygon);\n\n \/\/ print clipped polygon points\n std::cout << \"Clipped polygon points:\" << std::endl;\n for (vec2 p : clipped_polygon) {\n std::cout << \"(\" << p.x << \", \" << p.y << \")\" << std::endl;\n }\n\n return EXIT_SUCCESS;\n}\n\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":865} {"lang_cluster":"C++","source_code":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate\nstd::ostream& print(std::ostream& os, const T& src) {\n auto it = src.cbegin();\n auto end = src.cend();\n\n os << \"[\";\n if (it != end) {\n os << *it;\n it = std::next(it);\n }\n while (it != end) {\n os << \", \" << *it;\n it = std::next(it);\n }\n\n return os << \"]\";\n}\n\ntypedef std::map Map;\ntypedef Map::value_type MapEntry;\n\nvoid standardRank(const Map& scores) {\n std::cout << \"Standard Rank\" << std::endl;\n\n std::vector list;\n for (auto& elem : scores) {\n list.push_back(elem.second);\n }\n std::sort(list.begin(), list.end(), std::greater{});\n list.erase(std::unique(list.begin(), list.end()), list.end());\n\n int rank = 1;\n for (auto value : list) {\n int temp = rank;\n for (auto& e : scores) {\n if (e.second == value) {\n std::cout << temp << \" \" << value << \" \" << e.first.c_str() << std::endl;\n rank++;\n }\n }\n }\n\n std::cout << std::endl;\n}\n\nvoid modifiedRank(const Map& scores) {\n std::cout << \"Modified Rank\" << std::endl;\n\n std::vector list;\n for (auto& elem : scores) {\n list.push_back(elem.second);\n }\n std::sort(list.begin(), list.end(), std::greater{});\n list.erase(std::unique(list.begin(), list.end()), list.end());\n\n int rank = 0;\n for (auto value : list) {\n rank += std::count_if(scores.begin(), scores.end(), [value](const MapEntry& e) { return e.second == value; });\n for (auto& e : scores) {\n if (e.second == value) {\n std::cout << rank << \" \" << value << \" \" << e.first.c_str() << std::endl;\n }\n }\n }\n\n std::cout << std::endl;\n}\n\nvoid denseRank(const Map& scores) {\n std::cout << \"Dense Rank\" << std::endl;\n\n std::vector list;\n for (auto& elem : scores) {\n list.push_back(elem.second);\n }\n std::sort(list.begin(), list.end(), std::greater{});\n list.erase(std::unique(list.begin(), list.end()), list.end());\n\n int rank = 1;\n for (auto value : list) {\n for (auto& e : scores) {\n if (e.second == value) {\n std::cout << rank << \" \" << value << \" \" << e.first.c_str() << std::endl;\n }\n }\n rank++;\n }\n\n std::cout << std::endl;\n}\n\nvoid ordinalRank(const Map& scores) {\n std::cout << \"Ordinal Rank\" << std::endl;\n\n std::vector list;\n for (auto& elem : scores) {\n list.push_back(elem.second);\n }\n std::sort(list.begin(), list.end(), std::greater{});\n list.erase(std::unique(list.begin(), list.end()), list.end());\n\n int rank = 1;\n for (auto value : list) {\n for (auto& e : scores) {\n if (e.second == value) {\n std::cout << rank++ << \" \" << value << \" \" << e.first.c_str() << std::endl;\n }\n }\n }\n\n std::cout << std::endl;\n}\n\nvoid fractionalRank(const Map& scores) {\n std::cout << \"Ordinal Rank\" << std::endl;\n\n std::vector list;\n for (auto& elem : scores) {\n list.push_back(elem.second);\n }\n std::sort(list.begin(), list.end(), std::greater{});\n list.erase(std::unique(list.begin(), list.end()), list.end());\n\n int rank = 0;\n for (auto value : list) {\n double avg = 0.0;\n int cnt = 0;\n\n for (auto& e : scores) {\n if (e.second == value) {\n rank++;\n cnt++;\n avg += rank;\n }\n }\n avg \/= cnt;\n\n for (auto& e : scores) {\n if (e.second == value) {\n std::cout << std::setprecision(1) << std::fixed << avg << \" \" << value << \" \" << e.first.c_str() << std::endl;\n }\n }\n }\n\n std::cout << std::endl;\n}\n\nint main() {\n using namespace std;\n\n map scores{\n {\"Solomon\", 44},\n {\"Jason\", 42},\n {\"Errol\", 42},\n {\"Gary\", 41},\n {\"Bernard\", 41},\n {\"Barry\", 41},\n {\"Stephen\", 39}\n };\n\n standardRank(scores);\n modifiedRank(scores);\n denseRank(scores);\n ordinalRank(scores);\n fractionalRank(scores);\n\n return 0;\n}\n\n\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":866} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\n#ifdef M_PI \/\/ defined by all POSIX systems and some non-POSIX ones\ndouble const pi = M_PI;\n#else\ndouble const pi = 4*std::atan(1);\n#endif\n\ndouble const degree = pi\/180;\n\nint main()\n{\n std::cout << \"=== radians ===\\n\";\n std::cout << \"sin(pi\/3) = \" << std::sin(pi\/3) << \"\\n\";\n std::cout << \"cos(pi\/3) = \" << std::cos(pi\/3) << \"\\n\";\n std::cout << \"tan(pi\/3) = \" << std::tan(pi\/3) << \"\\n\";\n std::cout << \"arcsin(1\/2) = \" << std::asin(0.5) << \"\\n\";\n std::cout << \"arccos(1\/2) = \" << std::acos(0.5) << \"\\n\";\n std::cout << \"arctan(1\/2) = \" << std::atan(0.5) << \"\\n\";\n\n std::cout << \"\\n=== degrees ===\\n\";\n std::cout << \"sin(60\u00b0) = \" << std::sin(60*degree) << \"\\n\";\n std::cout << \"cos(60\u00b0) = \" << std::cos(60*degree) << \"\\n\";\n std::cout << \"tan(60\u00b0) = \" << std::tan(60*degree) << \"\\n\";\n std::cout << \"arcsin(1\/2) = \" << std::asin(0.5)\/degree << \"\u00b0\\n\";\n std::cout << \"arccos(1\/2) = \" << std::acos(0.5)\/degree << \"\u00b0\\n\";\n std::cout << \"arctan(1\/2) = \" << std::atan(0.5)\/degree << \"\u00b0\\n\";\n\n return 0;\n}\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":867} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\n\nclass StopTimer\n{\npublic:\n StopTimer(): begin_(getUsec()) {}\n unsigned long long getTime() const { return getUsec() - begin_; }\nprivate:\n static unsigned long long getUsec()\n {\/\/...you might want to use something else under Windows\n timeval tv;\n const int res = ::gettimeofday(&tv, 0);\n if(res)\n return 0;\n return tv.tv_usec + 1000000 * tv.tv_sec;\n }\n unsigned long long begin_;\n};\n\nstruct KnapsackTask\n{\n struct Item\n {\n std::string name;\n unsigned w, v, qty;\n Item(): w(), v(), qty() {}\n Item(const std::string& iname, unsigned iw, unsigned iv, unsigned iqty):\n name(iname), w(iw), v(iv), qty(iqty)\n {}\n };\n typedef std::vector Items;\n struct Solution\n {\n unsigned v, w;\n unsigned long long iterations, usec;\n std::vector n;\n Solution(): v(), w(), iterations(), usec() {}\n };\n \/\/...\n KnapsackTask(): maxWeight_(), totalWeight_() {}\n void add(const Item& item)\n {\n const unsigned totalItemWeight = item.w * item.qty;\n if(const bool invalidItem = !totalItemWeight)\n throw std::logic_error(\"Invalid item: \" + item.name);\n totalWeight_ += totalItemWeight;\n items_.push_back(item);\n }\n const Items& getItems() const { return items_; }\n void setMaxWeight(unsigned maxWeight) { maxWeight_ = maxWeight; }\n unsigned getMaxWeight() const { return std::min(totalWeight_, maxWeight_); }\n\nprivate:\n unsigned maxWeight_, totalWeight_;\n Items items_;\n};\n\nclass BoundedKnapsackRecursiveSolver\n{\npublic:\n typedef KnapsackTask Task;\n typedef Task::Item Item;\n typedef Task::Items Items;\n typedef Task::Solution Solution;\n\n void solve(const Task& task)\n {\n Impl(task, solution_).solve();\n }\n const Solution& getSolution() const { return solution_; }\nprivate:\n class Impl\n {\n struct Candidate\n {\n unsigned v, n;\n bool visited;\n Candidate(): v(), n(), visited(false) {}\n };\n typedef std::vector Cache;\n public:\n Impl(const Task& task, Solution& solution):\n items_(task.getItems()),\n maxWeight_(task.getMaxWeight()),\n maxColumnIndex_(task.getItems().size() - 1),\n solution_(solution),\n cache_(task.getMaxWeight() * task.getItems().size()),\n iterations_(0)\n {}\n void solve()\n {\n if(const bool nothingToSolve = !maxWeight_ || items_.empty())\n return;\n StopTimer timer;\n Candidate candidate;\n solve(candidate, maxWeight_, items_.size() - 1);\n convertToSolution(candidate);\n solution_.usec = timer.getTime();\n }\n private:\n void solve(Candidate& current, unsigned reminderWeight, const unsigned itemIndex)\n {\n ++iterations_;\n\n const Item& item(items_[itemIndex]);\n\n if(const bool firstColumn = !itemIndex)\n {\n const unsigned maxQty = std::min(item.qty, reminderWeight\/item.w);\n current.v = item.v * maxQty;\n current.n = maxQty;\n current.visited = true;\n }\n else\n {\n const unsigned nextItemIndex = itemIndex - 1;\n {\n Candidate& nextItem = cachedItem(reminderWeight, nextItemIndex);\n if(!nextItem.visited)\n solve(nextItem, reminderWeight, nextItemIndex);\n current.visited = true;\n current.v = nextItem.v;\n current.n = 0;\n }\n if(reminderWeight >= item.w)\n {\n for (unsigned numberOfItems = 1; numberOfItems <= item.qty; ++numberOfItems)\n {\n reminderWeight -= item.w;\n Candidate& nextItem = cachedItem(reminderWeight, nextItemIndex);\n if(!nextItem.visited)\n solve(nextItem, reminderWeight, nextItemIndex);\n\n const unsigned checkValue = nextItem.v + numberOfItems * item.v;\n if ( checkValue > current.v)\n {\n current.v = checkValue;\n current.n = numberOfItems;\n }\n if(!(reminderWeight >= item.w))\n break;\n }\n }\n }\n }\n void convertToSolution(const Candidate& candidate)\n {\n solution_.iterations = iterations_;\n solution_.v = candidate.v;\n solution_.n.resize(items_.size());\n\n const Candidate* iter = &candidate;\n unsigned weight = maxWeight_, itemIndex = items_.size() - 1;\n while(true)\n {\n const unsigned currentWeight = iter->n * items_[itemIndex].w;\n solution_.n[itemIndex] = iter->n;\n weight -= currentWeight;\n if(!itemIndex--)\n break;\n iter = &cachedItem(weight, itemIndex);\n }\n solution_.w = maxWeight_ - weight;\n }\n Candidate& cachedItem(unsigned weight, unsigned itemIndex)\n {\n return cache_[weight * maxColumnIndex_ + itemIndex];\n }\n const Items& items_;\n const unsigned maxWeight_;\n const unsigned maxColumnIndex_;\n Solution& solution_;\n Cache cache_;\n unsigned long long iterations_;\n };\n Solution solution_;\n};\n\nvoid populateDataset(KnapsackTask& task)\n{\n typedef KnapsackTask::Item Item;\n task.setMaxWeight( 400 );\n task.add(Item(\"map\",9,150,1));\n task.add(Item(\"compass\",13,35,1));\n task.add(Item(\"water\",153,200,2));\n task.add(Item(\"sandwich\",50,60,2));\n task.add(Item(\"glucose\",15,60,2));\n task.add(Item(\"tin\",68,45,3));\n task.add(Item(\"banana\",27,60,3));\n task.add(Item(\"apple\",39,40,3));\n task.add(Item(\"cheese\",23,30,1));\n task.add(Item(\"beer\",52,10,3));\n task.add(Item(\"suntancream\",11,70,1));\n task.add(Item(\"camera\",32,30,1));\n task.add(Item(\"T-shirt\",24,15,2));\n task.add(Item(\"trousers\",48,10,2));\n task.add(Item(\"umbrella\",73,40,1));\n task.add(Item(\"w-trousers\",42,70,1));\n task.add(Item(\"w-overclothes\",43,75,1));\n task.add(Item(\"note-case\",22,80,1));\n task.add(Item(\"sunglasses\",7,20,1));\n task.add(Item(\"towel\",18,12,2));\n task.add(Item(\"socks\",4,50,1));\n task.add(Item(\"book\",30,10,2));\n}\n\nint main()\n{\n KnapsackTask task;\n populateDataset(task);\n\n BoundedKnapsackRecursiveSolver solver;\n solver.solve(task);\n const KnapsackTask::Solution& solution = solver.getSolution();\n\n cout << \"Iterations to solve: \" << solution.iterations << endl;\n cout << \"Time to solve: \" << solution.usec << \" usec\" << endl;\n cout << \"Solution:\" << endl;\n for (unsigned i = 0; i < solution.n.size(); ++i)\n {\n if (const bool itemIsNotInKnapsack = !solution.n[i])\n continue;\n cout << \" \" << solution.n[i] << ' ' << task.getItems()[i].name << \" ( item weight = \" << task.getItems()[i].w << \" )\" << endl;\n }\n\n cout << \"Weight: \" << solution.w << \" Value: \" << solution.v << endl;\n return 0;\n}\n\n","human_summarization":"\"Implement a solution for the Bounded Knapsack problem, where a tourist needs to decide which items to carry on a trip to maximize the total value without exceeding a weight limit of 4 kg. The items, their weights, values, and available quantities are given in a list. The solution uses dynamic programming and is a refactored and bug-fixed version of an initial C++ implementation.\"","id":868} {"lang_cluster":"C++","source_code":"#include \n#include \n#include \n#include \n#include \n\nvolatile sig_atomic_t gotint = 0;\n\nvoid handler(int signum) {\n\t\/\/ Set a flag for handling the signal, as other methods like printf are not safe here\n\tgotint = 1;\n}\n\nint main() {\n\tusing namespace std;\n\n\tsignal(SIGINT, handler);\n\n\tint i = 0;\n\tclock_t startTime = clock();\n\twhile (true) {\n\t\tif (gotint) break;\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds(500));\n\t\tif (gotint) break;\n\t\tcout << ++i << endl;\n\t}\n\tclock_t endTime = clock();\n\n\tdouble dt = (endTime - startTime) \/ (double)CLOCKS_PER_SEC;\n\tcout << \"Program has run for \" << dt << \" seconds\" << endl;\n\n\treturn 0;\n}\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.","id":869} {"lang_cluster":"C++","source_code":"\n\/\/ standard C++ string stream operators\n#include \n#include \n#include \n\n\/\/ inside a function or method...\nstd::string s = \"12345\";\n\nint i;\nstd::istringstream(s) >> i;\ni++;\n\/\/or:\n\/\/int i = std::atoi(s.c_str()) + 1;\n\nstd::ostringstream oss;\nif (oss << i) s = oss.str();\n\nWorks with: C++11\n#include \n\nstd::string s = \"12345\";\ns = std::to_string(1+std::stoi(s));\n\nLibrary: Boost\n\/\/ Boost\n#include \n#include \n#include \n\n\/\/ inside a function or method...\nstd::string s = \"12345\";\nint i = boost::lexical_cast(s) + 1;\ns = boost::lexical_cast(i);\n\nLibrary: Qt\nUses: Qt (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses Library\" (as page type) with input value \"Library\/Qt\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\n\/\/ Qt\nQString num1 = \"12345\";\nQString num2 = QString(\"%1\").arg(v1.toInt()+1);\n\nLibrary: MFC\nUses: Microsoft Foundation Classes (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses Library\" (as page type) with input value \"Library\/Microsoft Foundation Classes\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\nUses: C Runtime (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses Library\" (as page type) with input value \"Library\/C Runtime\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\n\/\/ MFC\nCString s = \"12345\";\nint i = _ttoi(s) + 1;\nint i = _tcstoul(s, NULL, 10) + 1; \ns.Format(\"%d\", i);\n\n\nWorks with: g++ version 4.0.2\n#include \n#include \n#include \n\nvoid increment_numerical_string(std::string& s)\n{\n std::string::reverse_iterator iter = s.rbegin(), end = s.rend();\n int carry = 1;\n while (carry && iter != end)\n {\n int value = (*iter - '0') + carry;\n carry = (value \/ 10);\n *iter = '0' + (value % 10);\n ++iter;\n }\n if (carry)\n s.insert(0, \"1\");\n}\n\nint main()\n{\n std::string big_number = \"123456789012345678901234567899\";\n std::cout << \"before increment: \" << big_number << \"\\n\";\n increment_numerical_string(big_number);\n std::cout << \"after increment: \" << big_number << \"\\n\";\n}\n\n","human_summarization":"\"Increments an almost arbitrarily large numerical string, going beyond the INT_MAX limit.\"","id":870} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n\nstd::string longestPath( const std::vector & , char ) ;\n\nint main( ) {\n std::string dirs[ ] = {\n \"\/home\/user1\/tmp\/coverage\/test\" ,\n \"\/home\/user1\/tmp\/covert\/operator\" ,\n \"\/home\/user1\/tmp\/coven\/members\" } ;\n std::vector myDirs ( dirs , dirs + 3 ) ;\n std::cout << \"The longest common path of the given directories is \"\n << longestPath( myDirs , '\/' ) << \"!\\n\" ;\n return 0 ;\n}\n\nstd::string longestPath( const std::vector & dirs , char separator ) {\n std::vector::const_iterator vsi = dirs.begin( ) ;\n int maxCharactersCommon = vsi->length( ) ;\n std::string compareString = *vsi ;\n for ( vsi = dirs.begin( ) + 1 ; vsi != dirs.end( ) ; vsi++ ) {\n std::pair p = \n\t std::mismatch( compareString.begin( ) , compareString.end( ) , vsi->begin( ) ) ;\n if (( p.first - compareString.begin( ) ) < maxCharactersCommon ) \n\t maxCharactersCommon = p.first - compareString.begin( ) ;\n }\n std::string::size_type found = compareString.rfind( separator , maxCharactersCommon ) ;\n return compareString.substr( 0 , found ) ;\n}\n\n\nThe longest common path of the given directories is \/home\/user1\/tmp!\n\n","human_summarization":"\"Code identifies the common directory path from a given set of directory paths using a specified directory separator character.\"","id":871} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n\nclass cycle{\npublic:\n template \n void cy( T* a, int len ) {\n int i, j;\n show( \"original: \", a, len );\n std::srand( unsigned( time( 0 ) ) );\n\n for( int i = len - 1; i > 0; i-- ) {\n do {\n j = std::rand() % i;\n } while( j >= i );\n std::swap( a[i], a[j] );\n }\n\n show( \" cycled: \", a, len ); std::cout << \"\\n\";\n }\nprivate:\n template \n void show( std::string s, T* a, int len ) {\n std::cout << s;\n for( int i = 0; i < len; i++ ) {\n std::cout << a[i] << \" \";\n }\n std::cout << \"\\n\";\n }\n};\nint main( int argc, char* argv[] ) {\n std::string d0[] = { \"\" },\n d1[] = { \"10\" },\n d2[] = { \"10\", \"20\" };\n int d3[] = { 10, 20, 30 },\n d4[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 };\n cycle c;\n c.cy( d0, sizeof( d0 ) \/ sizeof( d0[0] ) );\n c.cy( d1, sizeof( d1 ) \/ sizeof( d1[0] ) );\n c.cy( d2, sizeof( d2 ) \/ sizeof( d2[0] ) );\n c.cy( d3, sizeof( d3 ) \/ sizeof( d3[0] ) );\n c.cy( d4, sizeof( d4 ) \/ sizeof( d4[0] ) );\n\n return 0;\n}\n\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":872} {"lang_cluster":"C++","source_code":"\n\n#include \n\n\/\/ inputs must be random-access iterators of doubles\n\/\/ Note: this function modifies the input range\ntemplate \ndouble median(Iterator begin, Iterator end) {\n \/\/ this is middle for odd-length, and \"upper-middle\" for even length\n Iterator middle = begin + (end - begin) \/ 2;\n\n \/\/ This function runs in O(n) on average, according to the standard\n std::nth_element(begin, middle, end);\n\n if ((end - begin) % 2 != 0) { \/\/ odd length\n return *middle;\n } else { \/\/ even length\n \/\/ the \"lower middle\" is the max of the lower half\n Iterator lower_middle = std::max_element(begin, middle);\n return (*middle + *lower_middle) \/ 2.0;\n }\n}\n\n#include \n\nint main() {\n double a[] = {4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2};\n double b[] = {4.1, 7.2, 1.7, 9.3, 4.4, 3.2};\n\n std::cout << median(a+0, a + sizeof(a)\/sizeof(a[0])) << std::endl; \/\/ 4.4\n std::cout << median(b+0, b + sizeof(b)\/sizeof(b[0])) << std::endl; \/\/ 4.25\n\n return 0;\n}\n\n\nLibrary: gnu_pbds\n#include \n#include \n#include \n\n\/\/ the std::less_equal<> comparator allows the tree to support duplicates\ntypedef __gnu_pbds::tree, __gnu_pbds::rb_tree_tag, __gnu_pbds::tree_order_statistics_node_update> ost_t;\n\n\/\/ The lookup method, find_by_order (aka Select), is O(log n) for this data structure, much faster than std::nth_element()\ndouble median(ost_t &OST)\n{\n int n = OST.size();\n int m = n\/2;\n if (n == 1)\n return *OST.find_by_order(0);\n if (n == 2)\n return (*OST.find_by_order(0) + *OST.find_by_order(1)) \/ 2;\n \n if (n & 1) \/\/ odd number of elements\n return *OST.find_by_order(m);\n else \/\/ even number of elements\n return (*OST.find_by_order(m) + *OST.find_by_order(m-1)) \/ 2;\n}\n\nint main(int argc, char* argv[])\n{\n ost_t ostree;\n \n \/\/ insertion is also O(log n) for OSTs\n ostree.insert(4.1);\n ostree.insert(7.2);\n ostree.insert(1.7);\n ostree.insert(9.3);\n ostree.insert(4.4);\n ostree.insert(3.2);\n\n printf(\"%.3f\\n\", median(ostree)); \/\/ 4.250\n\n return 0;\n}\n\n","human_summarization":"\"Calculates the median value of a vector of floating-point numbers using the selection algorithm. Handles even number of elements by returning the average of the two middle values. Runs in linear time on average and uses a GNU C++ policy-based data structure to compute median in O(log n) time. Also includes tasks for calculating various statistical measures like mean, mode, and standard deviation.\"","id":873} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main()\n{\n\n\tint fizz = 0, buzz = 0, fizzbuzz = 0;\n\n\tbool isFizz = false;\n\n\tauto startTime = std::chrono::high_resolution_clock::now();\n\n\tfor (unsigned int i = 1; i <= 4000000000; i++) {\n\t\tisFizz = false;\n\n\t\tif (i % 3 == 0) {\n\t\t\tisFizz = true;\n\t\t\tfizz++;\n\t\t}\n\n\t\tif (i % 5 == 0) {\n\t\t\tif (isFizz) {\n\t\t\t\tfizz--;\n\t\t\t\tfizzbuzz++;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tbuzz++;\n\t\t\t}\n\t\t}\n\n\t}\n\n\tauto endTime = std::chrono::high_resolution_clock::now();\n\tauto totalTime = endTime - startTime;\n\n\tprintf(\"\\t fizz\u00a0: %d, buzz: %d, fizzbuzz: %d, duration %lld milliseconds\\n\", fizz, buzz, fizzbuzz, (totalTime \/ std::chrono::milliseconds(1)));\n\n\treturn 0;\n}\n\n#include \n\nusing namespace std;\nint main ()\n{\n for (int i = 1; i <= 100; i++) \n {\n if ((i % 15) == 0)\n cout << \"FizzBuzz\\n\";\n else if ((i % 3) == 0)\n cout << \"Fizz\\n\";\n else if ((i % 5) == 0)\n cout << \"Buzz\\n\";\n else\n cout << i << \"\\n\";\n }\n return 0;\n}\n\n#include \nusing namespace std;\n\nint main()\n{\n for (int i = 0; i <= 100; ++i)\n {\n bool fizz = (i % 3) == 0;\n bool buzz = (i % 5) == 0;\n if (fizz)\n cout << \"Fizz\";\n if (buzz)\n cout << \"Buzz\";\n if (!fizz && !buzz)\n cout << i;\n cout << \"\\n\";\n }\n return 0;\n}\n\n\n#include \n\nint main()\n{\n int i, f = 2, b = 4; \n\n for ( i = 1 ; i <= 100 ; ++i, --f, --b )\n {\n if ( f && b ) { std::cout << i; }\n if ( !f ) { std::cout << \"Fizz\"; f = 3; }\n if ( !b ) { std::cout << \"Buzz\"; b = 5; }\n std::cout << std::endl;\n }\n\n return 0;\n}\n\nWorks with: C++11\n#include \n#include \n#include \n\nint main()\n{\n std::vector range(100);\n std::iota(range.begin(), range.end(), 1);\n\n std::vector values;\n values.resize(range.size());\n\n auto fizzbuzz = [](int i) -> std::string {\n if ((i%15) == 0) return \"FizzBuzz\";\n if ((i%5) == 0) return \"Buzz\";\n if ((i%3) == 0) return \"Fizz\";\n return std::to_string(i);\n };\n\n std::transform(range.begin(), range.end(), values.begin(), fizzbuzz);\n\n for (auto& str: values) std::cout << str << std::endl;\n\n return 0;\n}\n\n\n#include \n\ntemplate \nstruct fizzbuzz : fizzbuzz\n{\n fizzbuzz() \n { std::cout << n << std::endl; }\n};\n\ntemplate \nstruct fizzbuzz : fizzbuzz\n{\n fizzbuzz() \n { std::cout << \"FizzBuzz\" << std::endl; }\n};\n\ntemplate \nstruct fizzbuzz : fizzbuzz\n{\n fizzbuzz() \n { std::cout << \"Fizz\" << std::endl; }\n};\n\ntemplate \nstruct fizzbuzz : fizzbuzz\n{\n fizzbuzz() \n { std::cout << \"Buzz\" << std::endl; }\n};\n\ntemplate <>\nstruct fizzbuzz<0,0,0>\n{\n fizzbuzz() \n { std::cout << 0 << std::endl; }\n};\n\ntemplate \nstruct fb_run\n{\n fizzbuzz fb;\n};\n\nint main()\n{\n fb_run<100> fb;\n return 0;\n}\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ exponentiation calculations\ntemplate struct POWER_CORE : POWER_CORE{};\n\ntemplate \nstruct POWER_CORE\n{\n enum : int { val = accum };\n};\n\ntemplate struct POWER : POWER_CORE<1, base, exp>{};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ # of digit calculations\ntemplate struct NUM_DIGITS_CORE : NUM_DIGITS_CORE{};\n\ntemplate \nstruct NUM_DIGITS_CORE\n{\n enum : int { val = depth};\n};\n\ntemplate struct NUM_DIGITS : NUM_DIGITS_CORE<0, i>{};\n\ntemplate <>\nstruct NUM_DIGITS<0>\n{\n enum : int { val = 1 };\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Convert digit to character (1 -> '1')\ntemplate \nstruct DIGIT_TO_CHAR\n{\n enum : char{ val = i + 48 };\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Find the digit at a given offset into a number of the form 0000000017\ntemplate \/\/ place -> [0 .. 10]\nstruct DIGIT_AT\n{\n enum : char{ val = (i \/ POWER<10, place>::val) % 10 };\n};\n\nstruct NULL_CHAR\n{\n enum : char{ val = '\\0' };\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Convert the digit at a given offset into a number of the form '0000000017' to a character\ntemplate \/\/ place -> [0 .. 9]\n struct ALT_CHAR : DIGIT_TO_CHAR< DIGIT_AT::val >{};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Convert the digit at a given offset into a number of the form '17' to a character\n\n\/\/ Template description, with specialization to generate null characters for out of range offsets\ntemplate \n struct OFFSET_CHAR_CORE_CHECKED{};\ntemplate \n struct OFFSET_CHAR_CORE_CHECKED : NULL_CHAR{};\ntemplate \n struct OFFSET_CHAR_CORE_CHECKED : ALT_CHAR{};\n\n\/\/ Perform the range check and pass it on\ntemplate \n struct OFFSET_CHAR_CORE : OFFSET_CHAR_CORE_CHECKED{};\n\n\/\/ Calc the number of digits and pass it on\ntemplate \n struct OFFSET_CHAR : OFFSET_CHAR_CORE::val>{};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Integer to char* template. Works on unsigned ints.\ntemplate \nstruct IntToStr\n{\n const static char str[];\n typedef typename mpl::string<\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n \/*OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,*\/\n NULL_CHAR::val>::type type;\n};\n\ntemplate \nconst char IntToStr::str[] = \n{\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n OFFSET_CHAR::val,\n NULL_CHAR::val\n};\n\ntemplate \nstruct IF\n{\n typedef Then RET;\n};\n\ntemplate \nstruct IF\n{\n typedef Else RET;\n};\n\n\ntemplate < typename Str1, typename Str2 >\nstruct concat : mpl::insert_range::type, Str2> {};\ntemplate \nstruct concat3 : mpl::insert_range::type, typename concat::type > {};\n\ntypedef typename mpl::string<'f','i','z','z'>::type fizz;\ntypedef typename mpl::string<'b','u','z','z'>::type buzz;\ntypedef typename mpl::string<'\\r', '\\n'>::type mpendl;\ntypedef typename concat::type fizzbuzz;\n\n\/\/ discovered boost mpl limitation on some length\n\ntemplate \nstruct FizzBuzz\n{\n typedef typename concat3::type, typename IF::type >::RET >::RET >::RET, typename mpendl::type>::type type;\n};\n\ntemplate <>\nstruct FizzBuzz<1>\n{\n typedef mpl::string<'1','\\r','\\n'>::type type;\n};\n\nint main(int argc, char** argv)\n{\n const int n = 7;\n std::cout << mpl::c_str::type>::value << std::endl;\n\treturn 0;\n}\n\n\n","human_summarization":"The code prints integers from 1 to 100. For multiples of three, it prints 'Fizz', for multiples of five, it prints 'Buzz', and for multiples of both three and five, it prints 'FizzBuzz'. This FizzBuzz problem is used to illustrate basic programming comprehension. The code uses modulo operation which can be expensive on some architectures. A version of the code uses metaprogramming to compute FizzBuzz at compile time, which requires specific compilation settings and may consume significant memory and time.","id":874} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n\n\/\/ get dimensions for arrays\ntemplate\n std::size_t get_first_dimension(ElementType (&a)[dim1][dim2])\n{\n return dim1;\n}\n\ntemplate\n std::size_t get_second_dimension(ElementType (&a)[dim1][dim2])\n{\n return dim2;\n}\n\n\ntemplate\n void draw_Mandelbrot(ImageType& image, \/\/where to draw the image\n ColorType set_color, ColorType non_set_color, \/\/which colors to use for set\/non-set points\n double cxmin, double cxmax, double cymin, double cymax,\/\/the rect to draw in the complex plane\n unsigned int max_iterations) \/\/the maximum number of iterations\n{\n std::size_t const ixsize = get_first_dimension(image);\n std::size_t const iysize = get_first_dimension(image);\n for (std::size_t ix = 0; ix < ixsize; ++ix)\n for (std::size_t iy = 0; iy < iysize; ++iy)\n {\n std::complex c(cxmin + ix\/(ixsize-1.0)*(cxmax-cxmin), cymin + iy\/(iysize-1.0)*(cymax-cymin));\n std::complex z = 0;\n unsigned int iterations;\n\n for (iterations = 0; iterations < max_iterations && std::abs(z) < 2.0; ++iterations) \n z = z*z + c;\n\n image[ix][iy] = (iterations == max_iterations) ? set_color : non_set_color;\n\n }\n}\n\n\n\n\n#include \n\nint f(float X, float Y, float x, float y, int n){\nreturn (x*x+y*y<4 && n<100)?1+f(X, Y, x*x-y*y+X, 2*x*y+Y, n+1):0;\n}\n\nmain(){\nfor(float j=1; j>=-1; j-=.015)\nfor(float i=-2, x; i<=.5; i+=.015, x=f(i, j, 0, 0, 0))\nprintf(\"%c%s\", x<10?' ':x<20?'.':x<50?':':x<80?'*':'#', i>-2?\" \":\"\\n\");\n}\n\n","human_summarization":"generate and draw the Mandelbrot set using a specific algorithm. The image is treated as a two-dimensional array of colors. The function can either draw the Mandelbrot set into a given array or use a class that maps the subscript operator to a pixel drawing routine of a graphics library. In the latter case, the code requires functions to get the first and second dimensions of the type. The functionality also includes a simple version implemented in CPP.","id":875} {"lang_cluster":"C++","source_code":"\nLibrary: STL\n#include \n#include \n\nint arg[] = { 1, 2, 3, 4, 5 };\nint sum = std::accumulate(arg, arg+5, 0, std::plus());\n\/\/ or just\n\/\/ std::accumulate(arg, arg + 5, 0);\n\/\/ since plus() is the default functor for accumulate\nint prod = std::accumulate(arg, arg+5, 1, std::multiplies());\n\n\n\/\/ this would be more elegant using STL collections\ntemplate T sum (const T *array, const unsigned n)\n{\n T accum = 0;\n for (unsigned i=0; i T prod (const T *array, const unsigned n)\n{\n T accum = 1;\n for (unsigned i=0; i\nusing std::cout;\nusing std::endl;\n\nint main ()\n{\n int aint[] = {1, 2, 3};\n cout << sum(aint,3) << \" \" << prod(aint, 3) << endl;\n float aflo[] = {1.1, 2.02, 3.003, 4.0004};\n cout << sum(aflo,4) << \" \" << prod(aflo,4) << endl;\n return 0;\n}\n\n","human_summarization":"\"Calculates the sum and product of all integers in a given array.\"","id":876} {"lang_cluster":"C++","source_code":"\n\ng++ -std=c++11 leap_year.cpp\n\n#include \n\nbool is_leap_year(int year) {\n return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);\n}\n\nint main() {\n for (auto year : {1900, 1994, 1996, 1997, 2000}) {\n std::cout << year << (is_leap_year(year) ? \" is\" : \" is not\") << \" a leap year.\\n\";\n }\n}\n\n\n","human_summarization":"\"Code checks if a given year is a leap year in the Gregorian calendar using C++11.\"","id":877} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main( int argc, char* argv[] ) {\n int sol = 1;\n std::cout << \"\\t\\tFIRE\\t\\tPOLICE\\t\\tSANITATION\\n\";\n for( int f = 1; f < 8; f++ ) {\n for( int p = 1; p < 8; p++ ) {\n for( int s = 1; s < 8; s++ ) {\n if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {\n std::cout << \"SOLUTION #\" << std::setw( 2 ) << sol++ << std::setw( 2 ) \n << \":\\t\" << std::setw( 2 ) << f << \"\\t\\t \" << std::setw( 3 ) << p \n << \"\\t\\t\" << std::setw( 6 ) << s << \"\\n\";\n }\n }\n }\n }\n return 0;\n}\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":878} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main( ) {\n std::string original (\"This is the original\");\n std::string my_copy = original;\n std::cout << \"This is the copy: \" << my_copy << std::endl;\n original = \"Now we change the original! \";\n std::cout << \"my_copy still is \" << my_copy << std::endl;\n}\n\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":879} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n\nclass Hofstadter\n{\npublic:\n static int F(int n) {\n if ( n == 0 ) return 1;\n return n - M(F(n-1));\n }\n static int M(int n) {\n if ( n == 0 ) return 0;\n return n - F(M(n-1));\n }\n};\n\nusing namespace std;\n\nint main()\n{\n int i;\n vector ra, rb;\n\n for(i=0; i < 20; i++) {\n ra.push_back(Hofstadter::F(i));\n rb.push_back(Hofstadter::M(i));\n }\n copy(ra.begin(), ra.end(),\n ostream_iterator(cout, \" \"));\n cout << endl;\n copy(rb.begin(), rb.end(),\n ostream_iterator(cout, \" \"));\n cout << endl;\n return 0;\n}\n\n\nclass Hofstadter\n{\npublic:\n static int F(int n);\n static int M(int n);\n};\n\nint Hofstadter::F(int n)\n{\n if ( n == 0 ) return 1;\n return n - M(F(n-1));\n}\n\nint Hofstadter::M(int n)\n{\n if ( n == 0 ) return 0;\n return n - F(M(n-1));\n}\n\n","human_summarization":"implement two mutually recursive functions, F and M, that compute the Hofstadter Female and Male sequences. These functions are defined as static methods within a class, allowing them to call each other without needing prior declaration. This is possible due to the class declaration parsing all possible methods and fields upon its first read.","id":880} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n\nint main( ) {\n std::vector numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;\n std::random_device seed ;\n \/\/ generator \n std::mt19937 engine( seed( ) ) ;\n \/\/ number distribution\n std::uniform_int_distribution choose( 0 , numbers.size( ) - 1 ) ;\n std::cout << \"random element picked\u00a0: \" << numbers[ choose( engine ) ] \n << \"\u00a0!\\n\" ;\n return 0 ;\n}\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":881} {"lang_cluster":"C++","source_code":"\nLibrary: Poco\nWorks with: g++\n#include \n#include \"Poco\/URI.h\"\n#include \n\nint main( ) {\n std::string encoded( \"http%3A%2F%2Ffoo%20bar%2F\" ) ;\n std::string decoded ;\n Poco::URI::decode ( encoded , decoded ) ;\n std::cout << encoded << \" is decoded: \" << decoded << \"\u00a0!\" << std::endl ;\n return 0 ;\n}\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":882} {"lang_cluster":"C++","source_code":"\n\ntemplate int binsearch(const T array[], int low, int high, T value) {\n if (high < low) {\n return -1;\n }\n auto mid = (low + high) \/ 2;\n if (value < array[mid]) {\n return binsearch(array, low, mid - 1, value);\n } else if (value > array[mid]) {\n return binsearch(array, mid + 1, high, value);\n }\n return mid;\n}\n\n#include \nint main()\n{\n int array[] = {2, 3, 5, 6, 8};\n int result1 = binsearch(array, 0, sizeof(array)\/sizeof(int), 4),\n result2 = binsearch(array, 0, sizeof(array)\/sizeof(int), 8);\n if (result1 == -1) std::cout << \"4 not found!\" << std::endl;\n else std::cout << \"4 found at \" << result1 << std::endl;\n if (result2 == -1) std::cout << \"8 not found!\" << std::endl;\n else std::cout << \"8 found at \" << result2 << std::endl;\n\n return 0;\n}\n\n\ntemplate \nint binSearch(const T arr[], int len, T what) {\n int low = 0;\n int high = len - 1;\n while (low <= high) {\n int mid = (low + high) \/ 2;\n if (arr[mid] > what)\n high = mid - 1;\n else if (arr[mid] < what)\n low = mid + 1;\n else\n return mid;\n }\n return -1; \/\/ indicate not found \n}\n\n\nC++'s Standard Template Library has four functions for binary search, depending on what information you want to get. They all need#include \n\n\nint *ptr = std::lower_bound(array, array+len, what); \/\/ a custom comparator can be given as fourth arg\n\n\nint *ptr = std::upper_bound(array, array+len, what); \/\/ a custom comparator can be given as fourth arg\n\n\nstd::pair bounds = std::equal_range(array, array+len, what); \/\/ a custom comparator can be given as fourth arg\n\n\nbool found = std::binary_search(array, array+len, what); \/\/ a custom comparator can be given as fourth arg\n\n","human_summarization":"Implement a binary search algorithm that divides a range of values into halves to find an unknown value. The algorithm can be either recursive or iterative and should print whether the number was found in the array, and if so, its index. The code also includes different versions of binary search algorithms that handle multiple equal values and return the \"insertion point\" for the value. The code also ensures no overflow bugs occur when calculating the midpoint of two integers. Additionally, it includes functions that return iterators to the first and last positions where a value could be inserted without violating the order, and a function that checks if an element exists in the array.","id":883} {"lang_cluster":"C++","source_code":"\n\n#include \n\nint main(int argc, const char* argv[]) {\n std::cout << \"This program is named \" << argv[0] << '\\n'\n << \"There are \" << argc - 1 << \" arguments given.\\n\";\n for (int i = 1; i < argc; ++i)\n std::cout << \"The argument #\" << i << \" is \" << argv[i] << '\\n';\n}\n\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program. It uses a method similar to C for passing arguments. The example command line used is 'myprogram -c \"alpha beta\" -h \"gamma\"'. The code utilizes for input\/output operations, although C-style i\/o is also compatible. The program name and parsing command-line arguments are also considered.","id":884} {"lang_cluster":"C++","source_code":"\nLibrary: wxWidgets\n\n#ifndef __wxPendulumDlg_h__\n#define __wxPendulumDlg_h__\n\n\/\/ ---------------------\n\/\/\/ @author Martin Ettl\n\/\/\/ @date 2013-02-03\n\/\/ ---------------------\n\n#ifdef __BORLANDC__\n#pragma hdrstop\n#endif\n\n#ifndef WX_PRECOMP\n#include \n#include \n#else\n#include \n#endif\n#include \n#include \n#include \n\nclass wxPendulumDlgApp : public wxApp\n{\n public:\n bool OnInit();\n int OnExit();\n};\n\nclass wxPendulumDlg : public wxDialog\n{\n public:\n\n wxPendulumDlg(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT(\"wxPendulum\"), \n\t\t\t\t const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, \n\t\t\t\t long style = wxSUNKEN_BORDER | wxCAPTION | wxRESIZE_BORDER | wxSYSTEM_MENU | wxDIALOG_NO_PARENT | wxMINIMIZE_BOX | wxMAXIMIZE_BOX | wxCLOSE_BOX);\n\n virtual ~wxPendulumDlg();\n\t\n\t\t\/\/ Event handler\n void wxPendulumDlgPaint(wxPaintEvent& event);\n void wxPendulumDlgSize(wxSizeEvent& event);\n void OnTimer(wxTimerEvent& event);\n\n private:\n\n\t\t\/\/ a pointer to a timer object\n wxTimer *m_timer;\n\n\t\tunsigned int m_uiLength;\n\t\tdouble \t m_Angle;\n\t\tdouble m_AngleVelocity;\n\n enum wxIDs\n {\n ID_WXTIMER1 = 1001,\n ID_DUMMY_VALUE_ \n };\n\n void OnClose(wxCloseEvent& event);\n void CreateGUIControls();\n\n DECLARE_EVENT_TABLE()\n};\n\n#endif \/\/ __wxPendulumDlg_h__\n\n\n\/\/ ---------------------\n\/\/\/ @author Martin Ettl\n\/\/\/ @date 2013-02-03\n\/\/ ---------------------\n\n#include \"wxPendulumDlg.hpp\"\n#include \n\nIMPLEMENT_APP(wxPendulumDlgApp)\n\nbool wxPendulumDlgApp::OnInit()\n{\n wxPendulumDlg* dialog = new wxPendulumDlg(NULL);\n SetTopWindow(dialog);\n dialog->Show(true);\n return true;\n}\n\nint wxPendulumDlgApp::OnExit()\n{\n return 0;\n}\n\nBEGIN_EVENT_TABLE(wxPendulumDlg, wxDialog)\n EVT_CLOSE(wxPendulumDlg::OnClose)\n EVT_SIZE(wxPendulumDlg::wxPendulumDlgSize)\n EVT_PAINT(wxPendulumDlg::wxPendulumDlgPaint)\n EVT_TIMER(ID_WXTIMER1, wxPendulumDlg::OnTimer)\nEND_EVENT_TABLE()\n\nwxPendulumDlg::wxPendulumDlg(wxWindow *parent, wxWindowID id, const wxString &title, const wxPoint &position, const wxSize& size, long style)\n : wxDialog(parent, id, title, position, size, style)\n{\n CreateGUIControls();\n}\n\nwxPendulumDlg::~wxPendulumDlg()\n{\n}\n\nvoid wxPendulumDlg::CreateGUIControls()\n{\n SetIcon(wxNullIcon);\n SetSize(8, 8, 509, 412);\n Center();\n\n\tm_uiLength = 200;\n\tm_Angle = M_PI\/2.;\n\tm_AngleVelocity = 0;\n\n m_timer = new wxTimer();\n m_timer->SetOwner(this, ID_WXTIMER1);\n m_timer->Start(20);\n}\n\nvoid wxPendulumDlg::OnClose(wxCloseEvent& WXUNUSED(event))\n{\n Destroy();\n}\n\nvoid wxPendulumDlg::wxPendulumDlgPaint(wxPaintEvent& WXUNUSED(event))\n{\n SetBackgroundStyle(wxBG_STYLE_CUSTOM);\n wxBufferedPaintDC dc(this);\n\n \/\/ Get window dimensions\n wxSize sz = GetClientSize();\n\t\/\/ determine the center of the canvas\n const wxPoint center(wxPoint(sz.x \/ 2, sz.y \/ 2));\n\n \/\/ create background color\n wxColour powderblue = wxColour(176,224,230);\n\n \/\/ draw powderblue background\n dc.SetPen(powderblue);\n dc.SetBrush(powderblue);\n dc.DrawRectangle(0, 0, sz.x, sz.y);\n\n \/\/ draw lines\n\twxPen Pen(*wxBLACK_PEN);\n\tPen.SetWidth(1);\n dc.SetPen(Pen);\n dc.SetBrush(*wxBLACK_BRUSH);\n\n double angleAccel, dt = 0.15;\n\n angleAccel = (-9.81 \/ m_uiLength) * sin(m_Angle);\n m_AngleVelocity += angleAccel * dt;\n m_Angle += m_AngleVelocity * dt;\n\n int anchorX = sz.x \/ 2, anchorY = sz.y \/ 4;\n int ballX = anchorX + (int)(sin(m_Angle) * m_uiLength);\n int ballY = anchorY + (int)(cos(m_Angle) * m_uiLength);\n dc.DrawLine(anchorX, anchorY, ballX, ballY);\n\n dc.SetBrush(*wxGREY_BRUSH);\n dc.DrawEllipse(anchorX - 3, anchorY - 4, 7, 7);\n\n dc.SetBrush(wxColour(255,255,0)); \/\/ yellow\n dc.DrawEllipse(ballX - 7, ballY - 7, 20, 20);\n}\n\nvoid wxPendulumDlg::wxPendulumDlgSize(wxSizeEvent& WXUNUSED(event))\n{\n Refresh();\n}\n\nvoid wxPendulumDlg::OnTimer(wxTimerEvent& WXUNUSED(event))\n{\n\t\/\/ force refresh\n\tRefresh();\n}\n\n\n","human_summarization":"create and animate a simple physical model of a gravity pendulum. The animation is achieved by simulating the variables of the pendulum system in a dynamically changing graphical display. The program is compatible with wxWidgets version 2.8 and 2.9 and includes a makefile for Linux compilation. The entire project can be downloaded from GitHub.","id":885} {"lang_cluster":"C++","source_code":"\nLibrary: U++\n#include \"Core\/Core.h\"\n\nusing namespace Upp;\n\nCONSOLE_APP_MAIN\n{\n\tJsonArray a;\n\ta << Json(\"name\", \"John\")(\"phone\", \"1234567\") << Json(\"name\", \"Susan\")(\"phone\", \"654321\");\n\tString txt = ~a;\n\tCout() << txt << '\\n';\n\tValue v = ParseJSON(txt);\n\tfor(int i = 0; i < v.GetCount(); i++)\n\t\tCout() << v[i][\"name\"] << ' ' << v[i][\"phone\"] << '\\n';\n}\n\nC++11 Library: nlohmann::json\n#include \n#include \/\/ std::setw\n#include \n#include \n\n#include \"json.hpp\"\n\nusing json = nlohmann::json;\n\nint main( int argc, char* argv[] )\n{\n std::string const expected =\nR\"delim123({\n \"answer\": {\n \"everything\": 42\n },\n \"happy\": true,\n \"list\": [\n 1,\n 0,\n 2\n ],\n \"name\": \"Niels\",\n \"nothing\": null,\n \"object\": {\n \"currency\": \"USD\",\n \"value\": 42.99\n },\n \"pi\": 3.141\n})delim123\";\n\n json const jexpected = json::parse( expected );\n\n assert( jexpected[\"list\"][1].get() == 0 );\n assert( jexpected[\"object\"][\"currency\"] == \"USD\" );\n\n json jhandmade = {\n {\"pi\", 3.141},\n {\"happy\", true},\n {\"name\", \"Niels\"},\n {\"nothing\", nullptr},\n {\"answer\", {\n {\"everything\", 42}\n }\n },\n {\"list\", {1, 0, 2}},\n {\"object\", {\n {\"currency\", \"USD\"},\n {\"value\", 42.99}\n }\n }\n };\n\n assert( jexpected == jhandmade );\n\n std::stringstream jhandmade_stream;\n jhandmade_stream << std::setw(4) << jhandmade;\n\n std::string jhandmade_string = jhandmade.dump(4);\n\n assert( jhandmade_string == expected );\n assert( jhandmade_stream.str() == expected );\n \n return 0; \n}\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":886} {"lang_cluster":"C++","source_code":"\ndouble NthRoot(double m_nValue, double index, double guess, double pc)\n {\n double result = guess;\n double result_next;\n do\n {\n result_next = (1.0\/index)*((index-1.0)*result+(m_nValue)\/(pow(result,(index-1.0))));\n result = result_next;\n pc--;\n }while(pc>1);\n return result;\n };\n\ndouble NthRoot(double value, double degree)\n{\n return pow(value, (double)(1 \/ degree));\n};\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":887} {"lang_cluster":"C++","source_code":"\n#include \n\nvoid leoN( int cnt, int l0 = 1, int l1 = 1, int add = 1 ) {\n int t;\n for( int i = 0; i < cnt; i++ ) {\n std::cout << l0 << \" \";\n t = l0 + l1 + add; l0 = l1; l1 = t;\n }\n}\nint main( int argc, char* argv[] ) {\n std::cout << \"Leonardo Numbers: \"; leoN( 25 );\n std::cout << \"\\n\\nFibonacci Numbers: \"; leoN( 25, 0, 1, 0 );\n return 0;\n}\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":888} {"lang_cluster":"C++","source_code":"\nWorks with: C++11\n\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nclass RPNParse\n{\npublic:\n stack stk;\n multiset digits;\n\n void op(function f)\n {\n if(stk.size() < 2)\n throw \"Improperly written expression\";\n int b = stk.top(); stk.pop();\n int a = stk.top(); stk.pop();\n stk.push(f(a, b));\n }\n\n void parse(char c)\n {\n if(c >= '0' && c <= '9')\n {\n stk.push(c - '0');\n digits.insert(c - '0');\n }\n else if(c == '+')\n op([](double a, double b) {return a+b;});\n else if(c == '-')\n op([](double a, double b) {return a-b;});\n else if(c == '*')\n op([](double a, double b) {return a*b;});\n else if(c == '\/')\n op([](double a, double b) {return a\/b;});\n }\n\n void parse(string s)\n {\n for(int i = 0; i < s.size(); ++i)\n parse(s[i]);\n }\n\n double getResult()\n {\n if(stk.size() != 1)\n throw \"Improperly written expression\";\n return stk.top();\n }\n};\n\nint main()\n{\n random_device seed;\n mt19937 engine(seed());\n uniform_int_distribution<> distribution(1, 9);\n auto rnd = bind(distribution, engine);\n\n multiset digits;\n cout << \"Make 24 with the digits: \";\n for(int i = 0; i < 4; ++i)\n {\n int n = rnd();\n cout << \" \" << n;\n digits.insert(n);\n }\n cout << endl;\n\n RPNParse parser;\n\n try\n {\n string input;\n getline(cin, input);\n parser.parse(input);\n\n if(digits != parser.digits)\n cout << \"Error: Not using the given digits\" << endl;\n else\n {\n double r = parser.getResult();\n cout << \"Result: \" << r << endl;\n\n if(r > 23.999 && r < 24.001)\n cout << \"Good job!\" << endl;\n else\n cout << \"Try again.\" << endl;\n }\n }\n catch(char* e)\n {\n cout << \"Error: \" << e << endl;\n }\n return 0;\n}\n\n\n","human_summarization":"generate and display four random digits from 1 to 9. It then prompts the player to input an arithmetic expression using these digits exactly once. The program checks and evaluates the expression to see if it equals 24. The allowed operations are multiplication, division, addition, and subtraction. Division operation preserves remainders. The program also supports the use of brackets and does not require the digits to be in the same order as given. The program does not generate or test the validity of the expression. It uses the C++11 standard and accepts input in RPN format.","id":889} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n#include \n\nnamespace detail_ {\n\n\/\/ For constexpr digit<->number conversions.\nconstexpr auto digits = std::array{'0','1','2','3','4','5','6','7','8','9'};\n\n\/\/ Helper function to encode a run-length.\ntemplate \nconstexpr auto encode_run_length(std::size_t n, OutputIterator out)\n{\n constexpr auto base = digits.size();\n \n \/\/ Determine the number of digits needed.\n auto const num_digits = [base](auto n)\n {\n auto d = std::size_t{1};\n while ((n \/= digits.size()))\n ++d;\n return d;\n }(n);\n \n \/\/ Helper lambda to raise the base to an integer power.\n auto base_power = [base](auto n)\n {\n auto res = decltype(base){1};\n for (auto i = decltype(n){1}; i < n; ++i)\n res *= base;\n return res;\n };\n \n \/\/ From the most significant digit to the least, output the digit.\n for (auto i = decltype(num_digits){0}; i < num_digits; ++i)\n *out++ = digits[(n \/ base_power(num_digits - i)) % base];\n \n return out;\n}\n\n\/\/ Helper function to decode a run-length.\n\/\/ As of C++20, this can be constexpr, because std::find() is constexpr.\n\/\/ Before C++20, it can be constexpr by emulating std::find().\ntemplate \nauto decode_run_length(InputIterator first, InputIterator last)\n{\n auto count = std::size_t{0};\n \n while (first != last)\n {\n \/\/ If the next input character is not a digit, we're done.\n auto const p = std::find(digits.begin(), digits.end(), *first);\n if (p == digits.end())\n break;\n \n \/\/ Convert the digit to a number, and append it to the size.\n count *= digits.size();\n count += std::distance(digits.begin(), p);\n \n \/\/ Move on to the next input character.\n ++first;\n }\n \n return std::tuple{count, first};\n}\n\n} \/\/ namespace detail_\n\ntemplate \nconstexpr auto encode(InputIterator first, InputIterator last, OutputIterator out)\n{\n while (first != last)\n {\n \/\/ Read the next value.\n auto const value = *first++;\n \n \/\/ Increase the count as long as the next value is the same.\n auto count = std::size_t{1};\n while (first != last && *first == value)\n {\n ++count;\n ++first;\n }\n \n \/\/ Write the value and its run length.\n out = detail_::encode_run_length(count, out);\n *out++ = value;\n }\n \n return out;\n}\n\n\/\/ As of C++20, this can be constexpr, because std::find() and\n\/\/ std::fill_n() are constexpr (and decode_run_length() can be\n\/\/ constexpr, too).\n\/\/ Before C++20, it can be constexpr by emulating std::find() and\n\/\/ std::fill_n().\ntemplate \nauto decode(InputIterator first, InputIterator last, OutputIterator out)\n{\n while (first != last)\n {\n using detail_::digits;\n \n \/\/ Assume a run-length of 1, then try to decode the actual\n \/\/ run-length, if any.\n auto count = std::size_t{1};\n if (std::find(digits.begin(), digits.end(), *first) != digits.end())\n std::tie(count, first) = detail_::decode_run_length(first, last);\n \n \/\/ Write the run.\n out = std::fill_n(out, count, *first++);\n }\n \n return out;\n}\n\ntemplate \nconstexpr auto encode(Range&& range, OutputIterator out)\n{\n using std::begin;\n using std::end;\n \n return encode(begin(range), end(range), out);\n}\n\ntemplate \nauto decode(Range&& range, OutputIterator out)\n{\n using std::begin;\n using std::end;\n \n return decode(begin(range), end(range), out);\n}\n\n\/\/ Sample application and checking ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n#include \n#include \n\nint main()\n{\n using namespace std::literals;\n \n constexpr auto test_string = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"sv;\n \n std::cout << \"Input: \\\"\" << test_string << \"\\\"\\n\";\n std::cout << \"","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":890} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main() {\n std::string s = \"hello\";\n std::cout << s << \" literal\" << std::endl;\n std::string s2 = s + \" literal\";\n std::cout << s2 << std::endl;\n return 0;\n}\n\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":891} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n\nint main( ) {\n QByteArray text ( \"http:\/\/foo bar\/\" ) ;\n QByteArray encoded( text.toPercentEncoding( ) ) ;\n std::cout << encoded.data( ) << '\\n' ;\n return 0 ;\n}\n\n\n","human_summarization":"The code provides a function to convert a given string into its URL encoding representation. It converts special, control, and extended characters into a percent symbol followed by a two-digit hexadecimal code. For instance, a space character is encoded as %20. The function primarily converts characters outside the range of 0-9, A-Z, and a-z. It also supports variations such as lowercase escapes and different encoding standards like RFC 3986 and HTML 5. An optional feature allows the use of an exception string to preserve certain symbols from conversion. The code utilizes the Qt 4.6 library.","id":892} {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n\ntemplate\nstd::vector common_sorted_list(const std::vector>& ll) {\n std::set resultset;\n std::vector result;\n for (auto& list : ll)\n for (auto& item : list)\n resultset.insert(item);\n for (auto& item : resultset)\n result.push_back(item);\n \n std::sort(result.begin(), result.end());\n return result;\n}\n\nint main() {\n std::vector a = {5,1,3,8,9,4,8,7};\n std::vector b = {3,5,9,8,4};\n std::vector c = {1,3,7,9};\n std::vector> nums = {a, b, c};\n \n auto csl = common_sorted_list(nums);\n for (auto n : csl) std::cout << n << \" \";\n std::cout << std::endl;\n \n return 0;\n}\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":893} {"lang_cluster":"C++","source_code":"\n#include\n#include\n#include\n\nusing namespace std;\ndouble result;\ndouble capacity = 15;\nint NumberOfItems;\nint number;\n\nstruct items\n{\n char name[32];\n double weight;\n double price;\n double m;\n} item[256];\n\nbool cmp(items a,items b)\n{\n return a.price\/a.weight > b.price\/b.weight; \/\/ the compare function for the sorting algorithm\n}\n\nint main()\n{\nNumberOfItems=9;\nstrcpy(item[1].name,\"beef\");\nitem[1].weight=3.8;\nitem[1].price=36;\n\nstrcpy(item[2].name,\"pork\");\nitem[2].weight=5.4;\nitem[2].price=43;\n\nstrcpy(item[3].name,\"ham\");\nitem[3].weight=3.6;\nitem[3].price=90;\n\nstrcpy(item[4].name,\"greaves\");\nitem[4].weight=2.4;\nitem[4].price=45;\n\nstrcpy(item[5].name,\"flitch\");\nitem[5].weight=4.0;\nitem[5].price=30;\n\nstrcpy(item[6].name,\"brawn\");\nitem[6].weight=2.5;\nitem[6].price=56;\n\nstrcpy(item[7].name,\"welt\");\nitem[7].weight=3.7;\nitem[7].price=67;\n\nstrcpy(item[8].name,\"salami\");\nitem[8].weight=3.0;\nitem[8].price=95;\n\nstrcpy(item[9].name,\"sausage\");\nitem[9].weight=5.9;\nitem[9].price=98;\n\n\nsort(item+1,item+NumberOfItems+1,cmp); \/\/ We'll sort using Introsort from STL\n\n number = 1;\n while(capacity>0&&number<=NumberOfItems)\n {\n if(item[number].weight<=capacity)\n {\n result+=item[number].price;\n capacity-=item[number].weight;\n item[number].m=1;\n }\n else\n {\n result+=(item[number].price)*(capacity\/item[number].weight);\n item[number].m=(capacity\/item[number].weight);\n capacity=0;\n\n }\n ++number;\n }\n\ncout<<\"Total Value = \"<\n#include \n#include \n#include \n#include \n#include \n#include \n \nint main() {\n std::ifstream in(\"unixdict.txt\");\n typedef std::map > AnagramMap;\n AnagramMap anagrams;\n \n std::string word;\n size_t count = 0;\n while (std::getline(in, word)) {\n std::string key = word;\n std::sort(key.begin(), key.end());\n \/\/ note: the [] op. automatically inserts a new value if key does not exist\n AnagramMap::mapped_type & v = anagrams[key];\n v.push_back(word);\n count = std::max(count, v.size());\n }\n \n in.close();\n \n for (AnagramMap::const_iterator it = anagrams.begin(), e = anagrams.end();\n it != e; it++)\n if (it->second.size() >= count) {\n std::copy(it->second.begin(), it->second.end(),\n std::ostream_iterator(std::cout, \", \"));\n std::cout << std::endl;\n }\n return 0;\n}\n\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":895} {"lang_cluster":"C++","source_code":"\n\n\/\/ contributed to rosettacode.org by Peter Helcmanovsky\n\/\/ BCT = Binary-Coded Ternary: pairs of bits form one digit [0,1,2] (0b11 is invalid digit)\n\n#include \n#include \n#include \n\nstatic constexpr int32_t bct_low_bits = 0x55555555;\n\nstatic int32_t bct_decrement(int32_t v) {\n --v; \/\/ either valid BCT (v-1), or block of bottom 0b00 digits becomes invalid 0b11\n return v ^ (v & (v>>1) & bct_low_bits); \/\/ fix all 0b11 to 0b10 (digit \"2\")\n}\n\nint main (int argc, char *argv[])\n{\n \/\/ parse N from first argument, if no argument, use 3 as default value\n const int32_t n = (1 < argc) ? std::atoi(argv[1]) : 3;\n \/\/ check for valid N (0..9) - 16 requires 33 bits for BCT form 1<<(n*2) => hard limit\n if (n < 0 || 9 < n) { \/\/ but N=9 already produces 370MB output\n std::printf(\"N out of range (use 0..9): %ld\\n\", long(n));\n return 1;\n }\n\n const int32_t size_bct = 1<<(n*2); \/\/ 3**n in BCT form (initial value for loops)\n \/\/ draw the carpet, two nested loops counting down in BCT form of values\n int32_t y = size_bct;\n do { \/\/ all lines loop\n y = bct_decrement(y); \/\/ --Y (in BCT)\n int32_t x = size_bct;\n do { \/\/ line loop\n x = bct_decrement(x); \/\/ --X (in BCT)\n \/\/ check if x has ternary digit \"1\" at same position(s) as y -> output space (hole)\n std::putchar((x & y & bct_low_bits) ? ' ' : '#');\n } while (0 < x);\n std::putchar('\\n');\n } while (0 < y);\n\n return 0;\n}\n\n\n#include \n#include \n\n\/\/--------------------------------------------------------------------------------------------------\nconst int BMP_SIZE = 738;\n\n\/\/--------------------------------------------------------------------------------------------------\nclass Sierpinski\n{\npublic:\n void draw( HDC wdc, int wid, int hei, int ord )\n {\n\t_wdc = wdc;\n _ord = wid \/ static_cast( pow( 3.0, ord ) );\n\tdrawIt( 0, 0, wid, hei );\n }\n\n void setHWND( HWND hwnd ) { _hwnd = hwnd; }\n\nprivate:\n void drawIt( int x, int y, int wid, int hei )\n {\n\tif( wid < _ord || hei < _ord ) return;\n\tint w = wid \/ 3, h = hei \/ 3;\n\tRECT rc;\n\tSetRect( &rc, x + w, y + h, x + w + w, y + h + h );\n\tFillRect( _wdc, &rc, static_cast( GetStockObject( BLACK_BRUSH ) ) );\n\t\t\n\tfor( int a = 0; a < 3; a++ )\n\t for( int b = 0; b < 3; b++ )\n\t {\n\t\tif( a == 1 && b == 1 ) continue;\n\t\tdrawIt( x + b * w, y + a * h, w, h );\n\t }\n }\n\n HWND _hwnd;\n HDC _wdc;\n int _ord;\n};\n\/\/--------------------------------------------------------------------------------------------------\nclass wnd\n{\npublic:\n wnd() { _inst = this; }\n int wnd::Run( HINSTANCE hInst )\n {\n\t_hInst = hInst;\n\t_hwnd = InitAll();\n\n\t_carpet.setHWND( _hwnd );\n\n\tShowWindow( _hwnd, SW_SHOW );\n\tUpdateWindow( _hwnd );\n\n\tMSG msg;\n\tZeroMemory( &msg, sizeof( msg ) );\n\twhile( msg.message != WM_QUIT )\n\t{\n\t if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )\n\t {\n\t\tTranslateMessage( &msg );\n\t\tDispatchMessage( &msg );\n\t }\n\t}\n\treturn UnregisterClass( \"_SIERPINSKI_\", _hInst );\n }\nprivate:\n void wnd::doPaint( HDC dc ) { _carpet.draw( dc, BMP_SIZE, BMP_SIZE, 5 ); }\n\n static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )\n {\n\tswitch( msg )\n\t{\n\t case WM_DESTROY: PostQuitMessage( 0 ); break;\n\t case WM_PAINT:\n\t {\n\t\tPAINTSTRUCT ps;\n\t\tHDC dc = BeginPaint( hWnd, &ps );\n\t\t_inst->doPaint( dc ); \n\t\tEndPaint( hWnd, &ps );\n\t }\t\t\n\t default:\n\t return DefWindowProc( hWnd, msg, wParam, lParam );\n\t}\n\treturn 0;\n }\n\n HWND InitAll()\n {\n\tWNDCLASSEX wcex;\n\tZeroMemory( &wcex, sizeof( wcex ) );\n\twcex.cbSize\t = sizeof( WNDCLASSEX );\n\twcex.style\t = CS_HREDRAW | CS_VREDRAW;\n\twcex.lpfnWndProc = ( WNDPROC )WndProc;\n\twcex.hInstance = _hInst;\n\twcex.hCursor = LoadCursor( NULL, IDC_ARROW );\n\twcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );\n\twcex.lpszClassName = \"_SIERPINSKI_\";\n\n\tRegisterClassEx( &wcex );\n\n\tRECT rc = { 0, 0, BMP_SIZE, BMP_SIZE };\n\tAdjustWindowRect( &rc, WS_SYSMENU | WS_CAPTION, FALSE );\n\tint w = rc.right - rc.left,\n\t h = rc.bottom - rc.top;\n\treturn CreateWindow( \"_SIERPINSKI_\", \".: Sierpinski carpet -- PJorente\u00a0:.\", WS_SYSMENU, CW_USEDEFAULT, 0, w, h, NULL, NULL, _hInst, NULL );\n }\n\n static wnd* _inst;\n HINSTANCE _hInst;\n HWND _hwnd;\n Sierpinski _carpet;\n};\nwnd* wnd::_inst = 0;\n\/\/--------------------------------------------------------------------------------------------------\nint APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )\n{\n wnd myWnd;\n return myWnd.Run( hInstance );\n}\n\/\/--------------------------------------------------------------------------------------------------\n\n","human_summarization":"generate an ASCII-art or graphical representation of a Sierpinski carpet of a given order N. The representation uses specific placement of whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The code also includes a performance-focused variant that is approximately 7 times faster than div\/mod solutions on an AMD Ryzen 7 4800H.","id":896} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n#include \/\/ for CHAR_BIT\n#include \n#include \n\nconst int UniqueSymbols = 1 << CHAR_BIT;\nconst char* SampleString = \"this is an example for huffman encoding\";\n\ntypedef std::vector HuffCode;\ntypedef std::map HuffCodeMap;\n\nclass INode\n{\npublic:\n const int f;\n\n virtual ~INode() {}\n\nprotected:\n INode(int f) : f(f) {}\n};\n\nclass InternalNode : public INode\n{\npublic:\n INode *const left;\n INode *const right;\n\n InternalNode(INode* c0, INode* c1) : INode(c0->f + c1->f), left(c0), right(c1) {}\n ~InternalNode()\n {\n delete left;\n delete right;\n }\n};\n\nclass LeafNode : public INode\n{\npublic:\n const char c;\n\n LeafNode(int f, char c) : INode(f), c(c) {}\n};\n\nstruct NodeCmp\n{\n bool operator()(const INode* lhs, const INode* rhs) const { return lhs->f > rhs->f; }\n};\n\nINode* BuildTree(const int (&frequencies)[UniqueSymbols])\n{\n std::priority_queue, NodeCmp> trees;\n\n for (int i = 0; i < UniqueSymbols; ++i)\n {\n if(frequencies[i] != 0)\n trees.push(new LeafNode(frequencies[i], (char)i));\n }\n while (trees.size() > 1)\n {\n INode* childR = trees.top();\n trees.pop();\n\n INode* childL = trees.top();\n trees.pop();\n\n INode* parent = new InternalNode(childR, childL);\n trees.push(parent);\n }\n return trees.top();\n}\n\nvoid GenerateCodes(const INode* node, const HuffCode& prefix, HuffCodeMap& outCodes)\n{\n if (const LeafNode* lf = dynamic_cast(node))\n {\n outCodes[lf->c] = prefix;\n }\n else if (const InternalNode* in = dynamic_cast(node))\n {\n HuffCode leftPrefix = prefix;\n leftPrefix.push_back(false);\n GenerateCodes(in->left, leftPrefix, outCodes);\n\n HuffCode rightPrefix = prefix;\n rightPrefix.push_back(true);\n GenerateCodes(in->right, rightPrefix, outCodes);\n }\n}\n\nint main()\n{\n \/\/ Build frequency table\n int frequencies[UniqueSymbols] = {0};\n const char* ptr = SampleString;\n while (*ptr != '\\0')\n ++frequencies[*ptr++];\n\n INode* root = BuildTree(frequencies);\n \n HuffCodeMap codes;\n GenerateCodes(root, HuffCode(), codes);\n delete root;\n\n for (HuffCodeMap::const_iterator it = codes.begin(); it != codes.end(); ++it)\n {\n std::cout << it->first << \" \";\n std::copy(it->second.begin(), it->second.end(),\n std::ostream_iterator(std::cout));\n std::cout << std::endl;\n }\n return 0;\n}\n\n\n","human_summarization":"generate a Huffman encoding for each character in the given string. The program first builds a tree based on the frequency of each character, then traverses the tree to assign binary codes to each character. The resulting Huffman codes are then printed as a table.","id":897} {"lang_cluster":"C++","source_code":"\nUses: Qt (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses Library\" (as page type) with input value \"Library\/Qt\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\nLibrary: Qt 4.4 with source files as shown , built from a Makefile generated by the Qt tool qmake\n#ifndef CLICKCOUNTER_H\n#define CLICKCOUNTER_H\n\n#include \nclass QLabel ;\nclass QPushButton ;\nclass QVBoxLayout ;\n\nclass Counter : public QWidget {\n Q_OBJECT\npublic :\n Counter( QWidget * parent = 0 ) ;\nprivate :\n int number ;\n QLabel *countLabel ;\n QPushButton *clicker ;\n QVBoxLayout *myLayout ;\nprivate slots :\n void countClicks( ) ;\n} ;\n#endif\n\n#include \n#include \n#include \n#include \"clickcounter.h\" \n\nCounter::Counter( QWidget * parent ) : QWidget( parent ) {\n number = 0 ;\n countLabel = new QLabel( \"There have been no clicks yet!\" ) ;\n clicker = new QPushButton( \"click me\" ) ;\n connect ( clicker , SIGNAL( clicked( ) ) , this , SLOT( countClicks( ) ) ) ;\n myLayout = new QVBoxLayout ;\n myLayout->addWidget( countLabel ) ;\n myLayout->addWidget( clicker ) ;\n setLayout( myLayout ) ;\n}\n\nvoid Counter::countClicks( ) {\n number++ ;\n countLabel->setText( QString( \"The button has been clicked %1 times!\").arg( number ) ) ;\n}\n\n#include \n#include \"clickcounter.h\"\n\nint main( int argc , char *argv[ ] ) {\n QApplication app( argc , argv ) ;\n Counter counter ;\n counter.show( ) ;\n return app.exec( ) ;\n}\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":898} {"lang_cluster":"C++","source_code":"\nfor(int i = 10; i >= 0; --i)\n std::cout << i << \"\\n\";\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":899} {"lang_cluster":"C++","source_code":"\n#include \n#include \nusing namespace std;\n\nclass Vigenere\n{\npublic:\n string key;\n\n Vigenere(string key)\n {\n for(int i = 0; i < key.size(); ++i)\n {\n if(key[i] >= 'A' && key[i] <= 'Z')\n this->key += key[i];\n else if(key[i] >= 'a' && key[i] <= 'z')\n this->key += key[i] + 'A' - 'a';\n }\n }\n\n string encrypt(string text)\n {\n string out;\n\n for(int i = 0, j = 0; i < text.length(); ++i)\n {\n char c = text[i];\n \n if(c >= 'a' && c <= 'z')\n c += 'A' - 'a';\n else if(c < 'A' || c > 'Z')\n continue;\n\n out += (c + key[j] - 2*'A') % 26 + 'A'; \n j = (j + 1) % key.length();\n }\n\n return out;\n }\n\n string decrypt(string text)\n {\n string out;\n\n for(int i = 0, j = 0; i < text.length(); ++i)\n {\n char c = text[i];\n \n if(c >= 'a' && c <= 'z')\n c += 'A' - 'a';\n else if(c < 'A' || c > 'Z')\n continue;\n\n out += (c - key[j] + 26) % 26 + 'A'; \n j = (j + 1) % key.length();\n }\n\n return out;\n }\n};\n\nint main()\n{\n Vigenere cipher(\"VIGENERECIPHER\");\n\n string original = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n string encrypted = cipher.encrypt(original);\n string decrypted = cipher.decrypt(encrypted);\n\n cout << original << endl;\n cout << \"Encrypted: \" << encrypted << endl;\n cout << \"Decrypted: \" << decrypted << endl;\n}\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":900} {"lang_cluster":"C++","source_code":"\n\nfor (int i = 1; i < 10; i += 2)\n std::cout << i << std::endl;\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one, printing all odd digits.","id":901} {"lang_cluster":"C++","source_code":"\n#include \n\n#define SUM(i,lo,hi,term)\\\n[&](const int _lo,const int _hi){\\\n decltype(+(term)) sum{};\\\n for (i = _lo; i <= _hi; ++i) sum += (term);\\\n return sum;\\\n}((lo),(hi))\n\nint i;\ndouble sum(int &i, int lo, int hi, double (*term)()) {\n double temp = 0;\n for (i = lo; i <= hi; i++)\n temp += term();\n return temp;\n}\ndouble term_func() { return 1.0 \/ i; }\n\nint main () {\n std::cout << sum(i, 1, 100, term_func) << std::endl;\n std::cout << SUM(i,1,100,1.0\/i) << \"\\n\";\n return 0;\n}\n\n\n","human_summarization":"\"Implement Jensen's Device, a programming technique that exploits call by name to compute the 100th harmonic number. The technique assumes that an expression passed as an actual parameter to a procedure would be re-evaluated in the caller's context every time the corresponding formal parameter's value was required. The code also demonstrates the importance of passing the first parameter by name or reference for changes to be visible in the caller's context. The output of the code is 5.18738.\"","id":902} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n\n\/\/--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n\/\/--------------------------------------------------------------------------------------------------\nconst int BMP_SIZE = 512;\n\n\/\/--------------------------------------------------------------------------------------------------\nclass myBitmap\n{\npublic:\n myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {}\n ~myBitmap()\n {\n\tDeleteObject( pen );\n\tDeleteObject( brush );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n }\n \n bool create( int w, int h )\n {\n\tBITMAPINFO bi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes = 1;\n\tbi.bmiHeader.biWidth = w;\n\tbi.bmiHeader.biHeight = -h;\n \n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n \n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc );\n \n\twidth = w; height = h;\n\treturn true;\n }\n \n void clear( BYTE clr = 0 )\n {\n\tmemset( pBits, clr, width * height * sizeof( DWORD ) );\n }\n \n void setBrushColor( DWORD bClr )\n {\n\tif( brush ) DeleteObject( brush );\n\tbrush = CreateSolidBrush( bClr );\n\tSelectObject( hdc, brush );\n }\n \n void setPenColor( DWORD c ) { clr = c; createPen(); }\n \n void setPenWidth( int w ) { wid = w; createPen(); }\n \n void saveBitmap( string path )\n {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO infoheader;\n\tBITMAP bitmap;\n\tDWORD wb;\n \n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n \n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n \n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n \n\tfileheader.bfType = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n \n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n \n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n \n\tdelete [] dwpBits;\n }\n \n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\n \nprivate:\n void createPen()\n {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, wid, clr );\n\tSelectObject( hdc, pen );\n }\n \n HBITMAP bmp;\n HDC hdc;\n HPEN pen;\n HBRUSH brush;\n void *pBits;\n int width, height, wid;\n DWORD clr;\n};\n\/\/--------------------------------------------------------------------------------------------------\nclass mSquares\n{\npublic:\n mSquares()\n {\n bmp.create( BMP_SIZE, BMP_SIZE );\n createPallete();\n }\n\n void draw()\n {\n\tHDC dc = bmp.getDC();\n\tfor( int y = 0; y < BMP_SIZE; y++ )\n\t for( int x = 0; x < BMP_SIZE; x++ )\n\t {\n\t\tint c = ( x ^ y ) % 256;\n\t\tSetPixel( dc, x, y, clrs[c] );\n\t }\n\n\tBitBlt( GetDC( GetConsoleWindow() ), 30, 30, BMP_SIZE, BMP_SIZE, dc, 0, 0, SRCCOPY );\n\t\/\/bmp.saveBitmap( \"f:\\\\rc\\\\msquares_cpp.bmp\" );\n }\n\nprivate:\n void createPallete()\n {\n\tfor( int x = 0; x < 256; x++ )\n\tclrs[x] = RGB( x<<1, x, x<<2 );\/\/rand()\u00a0% 180 + 50, rand()\u00a0% 200 + 50, rand()\u00a0% 180 + 50 );\n }\n\n unsigned int clrs[256];\n myBitmap bmp;\n};\n\/\/--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n srand( GetTickCount() );\n mSquares s; s.draw();\n return system( \"pause\" );\n}\n\/\/--------------------------------------------------------------------------------------------------\n\n","human_summarization":"\"Generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.\"","id":903} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n#include \n\n\/\/--------------------------------------------------------------------------------------------------\nusing namespace std;\n\n\/\/--------------------------------------------------------------------------------------------------\nconst int BMP_SIZE = 512, CELL_SIZE = 8;\n\n\/\/--------------------------------------------------------------------------------------------------\nenum directions { NONE, NOR = 1, EAS = 2, SOU = 4, WES = 8 };\n\n\/\/--------------------------------------------------------------------------------------------------\nclass myBitmap\n{\npublic:\n myBitmap() : pen( NULL ) {}\n ~myBitmap()\n {\n\tDeleteObject( pen );\n\tDeleteDC( hdc );\n\tDeleteObject( bmp );\n }\n\n bool create( int w, int h )\n {\n\tBITMAPINFO\tbi;\n\tZeroMemory( &bi, sizeof( bi ) );\n\tbi.bmiHeader.biSize\t = sizeof( bi.bmiHeader );\n\tbi.bmiHeader.biBitCount\t = sizeof( DWORD ) * 8;\n\tbi.bmiHeader.biCompression = BI_RGB;\n\tbi.bmiHeader.biPlanes\t = 1;\n\tbi.bmiHeader.biWidth\t = w;\n\tbi.bmiHeader.biHeight\t = -h;\n\n\tHDC dc = GetDC( GetConsoleWindow() );\n\tbmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );\n\tif( !bmp ) return false;\n\n\thdc = CreateCompatibleDC( dc );\n\tSelectObject( hdc, bmp );\n\tReleaseDC( GetConsoleWindow(), dc ); \n\twidth = w; height = h;\n\n\treturn true;\n }\n\n void clear()\n {\n\tZeroMemory( pBits, width * height * sizeof( DWORD ) );\n }\n\n void setPenColor( DWORD clr )\n {\n\tif( pen ) DeleteObject( pen );\n\tpen = CreatePen( PS_SOLID, 1, clr );\n\tSelectObject( hdc, pen );\n }\n\n void saveBitmap( string path )\n {\n\tBITMAPFILEHEADER fileheader;\n\tBITMAPINFO\t infoheader;\n\tBITMAP\t\t bitmap;\n\tDWORD\t\t wb;\n\n\tGetObject( bmp, sizeof( bitmap ), &bitmap );\n\n\tDWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];\n\tZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );\n\tZeroMemory( &infoheader, sizeof( BITMAPINFO ) );\n\tZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );\n\n\tinfoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;\n\tinfoheader.bmiHeader.biCompression = BI_RGB;\n\tinfoheader.bmiHeader.biPlanes = 1;\n\tinfoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );\n\tinfoheader.bmiHeader.biHeight = bitmap.bmHeight;\n\tinfoheader.bmiHeader.biWidth = bitmap.bmWidth;\n\tinfoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );\n\n\tfileheader.bfType = 0x4D42;\n\tfileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );\n\tfileheader.bfSize = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;\n\n\tGetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );\n\n\tHANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );\n\tWriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );\n\tWriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );\n\tWriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );\n\tCloseHandle( file );\n\n\tdelete [] dwpBits;\n }\n\n HDC getDC() const { return hdc; }\n int getWidth() const { return width; }\n int getHeight() const { return height; }\n\nprivate:\n HBITMAP bmp;\n HDC\t hdc;\n HPEN pen;\n void *pBits;\n int\t width, height;\n};\n\/\/--------------------------------------------------------------------------------------------------\nclass mazeGenerator\n{\npublic:\n mazeGenerator()\n {\n\t_world = 0; \n\t_bmp.create( BMP_SIZE, BMP_SIZE ); \n\t_bmp.setPenColor( RGB( 0, 255, 0 ) ); \n }\n\n ~mazeGenerator() { killArray(); }\n\n void create( int side )\n {\n\t_s = side;\n\tgenerate();\n\tdisplay();\n }\n\nprivate:\n void generate()\n {\n\tkillArray();\n\t_world = new BYTE[_s * _s];\n\tZeroMemory( _world, _s * _s );\n\t_ptX = rand() % _s; _ptY = rand() % _s;\n\tcarve();\n }\n\n void carve()\n {\n\twhile( true )\n\t{\n\t int d = getDirection();\n\t if( d < NOR ) return;\n\n\t switch( d )\n\t {\n\t case NOR:\n\t _world[_ptX + _s * _ptY] |= NOR; _ptY--;\n\t\t _world[_ptX + _s * _ptY] = SOU | SOU << 4;\n\t\tbreak;\n\t case EAS:\n\t\t _world[_ptX + _s * _ptY] |= EAS; _ptX++;\n\t\t _world[_ptX + _s * _ptY] = WES | WES << 4;\n\t\tbreak;\n\t\tcase SOU:\n\t\t _world[_ptX + _s * _ptY] |= SOU; _ptY++;\n\t\t _world[_ptX + _s * _ptY] = NOR | NOR << 4;\n\t\tbreak;\n\t\tcase WES:\n\t\t _world[_ptX + _s * _ptY] |= WES; _ptX--;\n\t\t _world[_ptX + _s * _ptY] = EAS | EAS << 4;\n\t }\n\t}\n }\n\n void display()\n {\n\t_bmp.clear();\n\tHDC dc = _bmp.getDC();\n\tfor( int y = 0; y < _s; y++ )\n\t{\n\t int yy = y * _s;\n\t for( int x = 0; x < _s; x++ )\n\t {\n\t\tBYTE b = _world[x + yy];\n\t\tint nx = x * CELL_SIZE, \n\t\t ny = y * CELL_SIZE;\n\t\t\t\t\n\t\tif( !( b & NOR ) )\n\t\t{\n\t\t MoveToEx( dc, nx, ny, NULL );\n\t\t LineTo( dc, nx + CELL_SIZE + 1, ny );\n\t\t}\n\t\tif( !( b & EAS ) )\n\t\t{\n\t\t MoveToEx( dc, nx + CELL_SIZE, ny, NULL );\n\t\t LineTo( dc, nx + CELL_SIZE, ny + CELL_SIZE + 1 );\n\t\t}\n\t\tif( !( b & SOU ) )\n\t\t{\n\t\t MoveToEx( dc, nx, ny + CELL_SIZE, NULL );\n\t\t LineTo( dc, nx + CELL_SIZE + 1, ny + CELL_SIZE );\n\t\t}\n\t\tif( !( b & WES ) )\n\t\t{\n\t\t MoveToEx( dc, nx, ny, NULL );\n\t\t LineTo( dc, nx, ny + CELL_SIZE + 1 );\n\t\t}\n\t }\n\t}\n\n\t\/\/_bmp.saveBitmap( \"f:\\\\rc\\\\maze.bmp\" );\n\tBitBlt( GetDC( GetConsoleWindow() ), 10, 60, BMP_SIZE, BMP_SIZE, _bmp.getDC(), 0, 0, SRCCOPY );\n }\n\n int getDirection()\n {\n\tint d = 1 << rand() % 4;\n\twhile( true )\n\t{\n\t for( int x = 0; x < 4; x++ )\n\t {\n\t\tif( testDir( d ) ) return d;\n\t\td <<= 1;\n\t\tif( d > 8 ) d = 1;\n\t }\n\t d = ( _world[_ptX + _s * _ptY] & 0xf0 ) >> 4;\n\t if( !d ) return -1;\n\t switch( d )\n\t {\n\t\tcase NOR: _ptY--; break;\n\t\tcase EAS: _ptX++; break;\n\t\tcase SOU: _ptY++; break;\n\t\tcase WES: _ptX--; break;\n\t }\n d = 1 << rand() % 4;\n\t}\n }\n\n bool testDir( int d )\n {\n\tswitch( d )\n\t{\n\t case NOR: return ( _ptY - 1 > -1 && !_world[_ptX + _s * ( _ptY - 1 )] );\n\t case EAS: return ( _ptX + 1 < _s && !_world[_ptX + 1 + _s * _ptY] );\n\t case SOU: return ( _ptY + 1 < _s && !_world[_ptX + _s * ( _ptY + 1 )] );\n\t case WES: return ( _ptX - 1 > -1 && !_world[_ptX - 1 + _s * _ptY] );\n\t}\n\treturn false;\n }\n\n void killArray() { if( _world ) delete [] _world; }\n\n BYTE* _world;\n int _s, _ptX, _ptY;\n myBitmap _bmp;\n};\n\/\/--------------------------------------------------------------------------------------------------\nint main( int argc, char* argv[] )\n{\n ShowWindow( GetConsoleWindow(), SW_MAXIMIZE );\n srand( GetTickCount() );\n\n mazeGenerator mg;\n int s;\n while( true )\n {\n\tcout << \"Enter the maze size, an odd number bigger than 2 ( 0 to QUIT ): \"; cin >> s;\n\tif( !s ) return 0;\n\tif( !( s & 1 ) ) s++;\n\tif( s >= 3 ) mg.create( s );\n\tcout << endl;\n\tsystem( \"pause\" );\n\tsystem( \"cls\" );\n }\n return 0;\n}\n\/\/--------------------------------------------------------------------------------------------------\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It begins at a random cell, marks it as visited, and obtains a list of its neighboring cells. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, then recursively applies the same process with the neighbor as the current cell.","id":904} {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nusing namespace boost::multiprecision;\n\nclass Gospers\n{\n cpp_int q, r, t, i, n;\n\npublic: \n\n \/\/ use Gibbons spigot algorith based on the Gospers series\n Gospers() : q{1}, r{0}, t{1}, i{1}\n {\n ++*this; \/\/ move to the first digit\n }\n\n \/\/ the ++ prefix operator will move to the next digit\n Gospers& operator++()\n {\n n = (q*(27*i-12)+5*r) \/ (5*t);\n\n while(n != (q*(675*i-216)+125*r)\/(125*t))\n {\n r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);\n q = i*(2*i-1)*q;\n t = 3*(3*i+1)*(3*i+2)*t;\n i++;\n\n n = (q*(27*i-12)+5*r) \/ (5*t);\n }\n\n q = 10*q;\n r = 10*r-10*n*t;\n\n return *this;\n }\n\n \/\/ the dereference operator will give the current digit\n int operator*()\n {\n return (int)n;\n }\n};\n\nint main()\n{\n Gospers g;\n\n std::cout << *g << \".\"; \/\/ print the first digit and the decimal point\n\n for(;;) \/\/ run forever\n {\n std::cout << *++g; \/\/ increment to the next digit and print\n }\n}\n\n\n","human_summarization":"are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.","id":905} {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n\nint main() {\n std::vector a;\n a.push_back(1);\n a.push_back(2);\n a.push_back(1);\n a.push_back(3);\n a.push_back(2);\n std::vector b;\n b.push_back(1);\n b.push_back(2);\n b.push_back(0);\n b.push_back(4);\n b.push_back(4);\n b.push_back(0);\n b.push_back(0);\n b.push_back(0);\n\n std::cout << std::boolalpha << (a < b) << std::endl; \/\/ prints \"false\"\n return 0;\n}\n\n","human_summarization":"\"Function to compare and order two numerical lists based on lexicographic order, returning true if the first list should be ordered before the second, and false otherwise.\"","id":906} {"lang_cluster":"C++","source_code":"\n#include \n\nunsigned int ackermann(unsigned int m, unsigned int n) {\n if (m == 0) {\n return n + 1;\n }\n if (n == 0) {\n return ackermann(m - 1, 1);\n }\n return ackermann(m - 1, ackermann(m, n - 1));\n}\n\nint main() {\n for (unsigned int m = 0; m < 4; ++m) {\n for (unsigned int n = 0; n < 10; ++n) {\n std::cout << \"A(\" << m << \", \" << n << \") = \" << ackermann(m, n) << \"\\n\";\n }\n }\n}\n\ng++ -std=c++11 -I \/path\/to\/boost ackermann.cpp.\n\n#include \n#include \n#include \n#include \n\nusing big_int = boost::multiprecision::cpp_int;\n\nbig_int ipow(big_int base, big_int exp) {\n big_int result(1);\n while (exp) {\n if (exp & 1) {\n result *= base;\n }\n exp >>= 1;\n base *= base;\n }\n return result;\n}\n\nbig_int ackermann(unsigned m, unsigned n) {\n static big_int (*ack)(unsigned, big_int) =\n [](unsigned m, big_int n)->big_int {\n switch (m) {\n case 0:\n return n + 1;\n case 1:\n return n + 2;\n case 2:\n return 3 + 2 * n;\n case 3:\n return 5 + 8 * (ipow(big_int(2), n) - 1);\n default:\n return n == 0 ? ack(m - 1, big_int(1)) : ack(m - 1, ack(m, n - 1));\n }\n };\n return ack(m, big_int(n));\n}\n\nint main() {\n for (unsigned m = 0; m < 4; ++m) {\n for (unsigned n = 0; n < 10; ++n) {\n std::cout << \"A(\" << m << \", \" << n << \") = \" << ackermann(m, n) << \"\\n\";\n }\n }\n\n std::cout << \"A(4, 1) = \" << ackermann(4, 1) << \"\\n\";\n\n std::stringstream ss;\n ss << ackermann(4, 2);\n auto text = ss.str();\n std::cout << \"A(4, 2) = (\" << text.length() << \" digits)\\n\"\n << text.substr(0, 80) << \"\\n...\\n\"\n << text.substr(text.length() - 80) << \"\\n\";\n}\n\n
    \nA(0, 0) = 1\nA(0, 1) = 2\nA(0, 2) = 3\nA(0, 3) = 4\nA(0, 4) = 5\nA(0, 5) = 6\nA(0, 6) = 7\nA(0, 7) = 8\nA(0, 8) = 9\nA(0, 9) = 10\nA(1, 0) = 2\nA(1, 1) = 3\nA(1, 2) = 4\nA(1, 3) = 5\nA(1, 4) = 6\nA(1, 5) = 7\nA(1, 6) = 8\nA(1, 7) = 9\nA(1, 8) = 10\nA(1, 9) = 11\nA(2, 0) = 3\nA(2, 1) = 5\nA(2, 2) = 7\nA(2, 3) = 9\nA(2, 4) = 11\nA(2, 5) = 13\nA(2, 6) = 15\nA(2, 7) = 17\nA(2, 8) = 19\nA(2, 9) = 21\nA(3, 0) = 5\nA(3, 1) = 13\nA(3, 2) = 29\nA(3, 3) = 61\nA(3, 4) = 125\nA(3, 5) = 253\nA(3, 6) = 509\nA(3, 7) = 1021\nA(3, 8) = 2045\nA(3, 9) = 4093\nA(4, 1) = 65533\nA(4, 2) = (19729 digits)\n2003529930406846464979072351560255750447825475569751419265016973710894059556311\n...\n4717124577965048175856395072895337539755822087777506072339445587895905719156733\n\n","human_summarization":"The code implements the Ackermann function, a recursive function that grows rapidly in value. The function accepts two non-negative arguments and always terminates. It returns the value of A(m, n) with arbitrary precision preferred but not mandatory. The function is defined with three conditions: if m equals 0, it returns n+1; if m is greater than 0 and n equals 0, it calls itself with m-1, 1; if both m and n are greater than 0, it calls itself with m-1 and the result of a recursive call with m, n-1.","id":907}
    {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n\n\/\/ Calculate the coefficients used by Spouge's approximation (based on the C\n\/\/ implemetation)\nstd::vector CalculateCoefficients(int numCoeff)\n{\n    std::vector c(numCoeff);\n    double k1_factrl = 1.0;\n    c[0] = sqrt(2.0 * std::numbers::pi);\n    for(size_t k=1; k < numCoeff; k++)\n    {\n        c[k] = exp(numCoeff-k) * pow(numCoeff-k, k-0.5) \/ k1_factrl;\n        k1_factrl *= -(double)k;\n    }\n    return c;\n}\n\n\/\/ The Spouge approximation\ndouble Gamma(const std::vector& coeffs, double x)\n{\n        const size_t numCoeff = coeffs.size();\n        double accm = coeffs[0];\n        for(size_t k=1; k < numCoeff; k++)\n        {\n            accm += coeffs[k] \/ ( x + k );\n        }\n        accm *= exp(-(x+numCoeff)) * pow(x+numCoeff, x+0.5);\n        return accm\/x;\n}\n\nint main()\n{\n    \/\/ estimate the gamma function with 1, 4, and 10 coefficients\n    const auto coeff1 = CalculateCoefficients(1);\n    const auto coeff4 = CalculateCoefficients(4);\n    const auto coeff10 = CalculateCoefficients(10);\n\n    const auto inputs = std::vector{\n        0.001, 0.01, 0.1, 0.5, 1.0,\n        1.461632145, \/\/ minimum of the gamma function\n        2, 2.5, 3, 4, 5, 6, 7, 8, 9, 10, 50, 100, \n        150 \/\/ causes overflow for this implemetation\n        };\n    \n    printf(\"%16s%16s%16s%16s%16s\\n\", \"gamma( x ) =\", \"Spouge 1\", \"Spouge 4\", \"Spouge 10\", \"built-in\");\n    for(auto x : inputs) \n    {\n        printf(\"gamma(%7.3f) = %16.10g %16.10g %16.10g %16.10g\\n\", \n            x,\n            Gamma(coeff1, x),\n            Gamma(coeff4, x), \n            Gamma(coeff10, x), \n            std::tgamma(x)); \/\/ built-in gamma function\n    }\n}\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":908}
    {"lang_cluster":"C++","source_code":"\n\/\/ Much shorter than the version below;\n\/\/ uses C++11 threads to parallelize the computation; also uses backtracking\n\/\/ Outputs all solutions for any table size\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Print table. 'pos' is a vector of positions \u2013 the index in pos is the row,\n\/\/ and the number at that index is the column where the queen is placed.\nstatic void print(const std::vector &pos)\n{\n\t\/\/ print table header\n\tfor (int i = 0; i < pos.size(); i++) {\n\t\tstd::cout << std::setw(3) << char('a' + i);\n\t}\n\n\tstd::cout << '\\n';\n\n\tfor (int row = 0; row < pos.size(); row++) {\n\t\tint col = pos[row];\n\t\tstd::cout << row + 1 << std::setw(3 * col + 3) << \" # \";\n\t\tstd::cout << '\\n';\n\t}\n\n\tstd::cout << \"\\n\\n\";\n}\n\nstatic bool threatens(int row_a, int col_a, int row_b, int col_b)\n{\n\treturn row_a == row_b \/\/ same row\n\t\tor col_a == col_b \/\/ same column\n\t\tor std::abs(row_a - row_b) == std::abs(col_a - col_b); \/\/ diagonal\n}\n\n\/\/ the i-th queen is in the i-th row\n\/\/ we only check rows up to end_idx\n\/\/ so that the same function can be used for backtracking and checking the final solution\nstatic bool good(const std::vector &pos, int end_idx)\n{\n\tfor (int row_a = 0; row_a < end_idx; row_a++) {\n\t\tfor (int row_b = row_a + 1; row_b < end_idx; row_b++) {\n\t\t\tint col_a = pos[row_a];\n\t\t\tint col_b = pos[row_b];\n\t\t\tif (threatens(row_a, col_a, row_b, col_b)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true;\n}\n\nstatic std::mutex print_count_mutex; \/\/ mutex protecting 'n_sols'\nstatic int n_sols = 0; \/\/ number of solutions\n\n\/\/ recursive DFS backtracking solver\nstatic void n_queens(std::vector &pos, int index)\n{\n\t\/\/ if we have placed a queen in each row (i. e. we are at a leaf of the search tree), check solution and return\n\tif (index >= pos.size()) {\n\t\tif (good(pos, index)) {\n\t\t\tstd::lock_guard lock(print_count_mutex);\n\t\t\tprint(pos);\n\t\t\tn_sols++;\n\t\t}\n\n\t\treturn;\n\t}\n\n\t\/\/ backtracking step\n\tif (not good(pos, index)) {\n\t\treturn;\n\t}\n\n\t\/\/ optimization: the first level of the search tree is parallelized\n\tif (index == 0) {\n\t\tstd::vector> fts;\n\t\tfor (int col = 0; col < pos.size(); col++) {\n\t\t\tpos[index] = col;\n\t\t\tauto ft = std::async(std::launch::async, [=]{ auto cpos(pos); n_queens(cpos, index + 1); });\n\t\t\tfts.push_back(std::move(ft));\n\t\t}\n\n\t\tfor (const auto &ft : fts) {\n\t\t\tft.wait();\n\t\t}\n\t} else { \/\/ deeper levels are not\n\t\tfor (int col = 0; col < pos.size(); col++) {\n\t\t\tpos[index] = col;\n\t\t\tn_queens(pos, index + 1);\n\t\t}\n\t}\n}\n\nint main()\n{\n\tstd::vector start(12); \/\/ 12: table size\n\tn_queens(start, 0);\n\tstd::cout << n_sols << \" solutions found.\\n\";\n\treturn 0;\n}\n\n\n","human_summarization":"\"Code to solve the N-queens puzzle for a board of size NxN, specifically optimized for Windows. It uses heuristics for solution construction as explained in the provided reference. The code also provides the number of solutions for small values of N as per OEIS: A000170.\"","id":909}
    {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main()\n{\n  std::vector a(3), b(4);\n  a[0] = 11; a[1] = 12; a[2] = 13;\n  b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for (int i = 0; i < a.size(); ++i)\n    std::cout << \"a[\" << i << \"] = \" << a[i] << \"\\n\";\n}\n\nWorks with: C++11\n\n#include                                                                                                        \n#include \n\nint main() {\n  std::vector a {1, 2, 3, 4};\n  std::vector b {5, 6, 7, 8, 9};\n\n  a.insert(a.end(), b.begin(), b.end());\n\n  for(int& i: a) std::cout << i << \" \";\n  std::cout << std::endl;\n  return 0;\n}\n\n\n#include \n\nusing namespace std;\n\ntemplate \nint* concatArrays( T1& array_1, T2& array_2) {\n  int arrayCount_1 = sizeof(array_1) \/ sizeof(array_1[0]);\n  int arrayCount_2 = sizeof(array_2) \/ sizeof(array_2[0]);\n  int newArraySize = arrayCount_1 + arrayCount_2;\n\n  int *p = new int[newArraySize];\n\n  for (int i = 0; i < arrayCount_1; i++) {\n    p[i] = array_1[i];\n  }\n\n  for (int i = arrayCount_1; i < newArraySize; i++) {\n    int newIndex = i-arrayCount_2;\n\n    if (newArraySize % 2 == 1)\n\tnewIndex--;\n\n    p[i] = array_2[newIndex];\n    cout << \"i: \" << i << endl;\n    cout << \"array_2[i]: \" << array_2[newIndex] << endl;\n    cout << endl;\n  }\n\n  return p;\n}\n\nint main() {\n  \n  int ary[4] = {1, 2, 3, 123};\n  int anotherAry[3] = {4, 5, 6};\n  \n  int *r = concatArrays(ary, anotherAry);\n\n  cout << *(r + 0) << endl;\n  cout << *(r + 1) << endl;\n  cout << *(r + 2) << endl;\n  cout << *(r + 3) << endl;\n  cout << *(r + 4) << endl;\n  cout << *(r + 5) << endl;\n  cout << *(r + 6) << endl;\n\n  delete r;\n\n  return 0;\n}\n\n","human_summarization":"demonstrate how to concatenate two arrays using both simple addition and initialization schematics, as well as with function level templates and pointers.","id":910}
    {"lang_cluster":"C++","source_code":"\nLibrary: Boost\n#include \n#include \n#include \n#include \n#include \n\nint findBestPack( const std::vector > & , \n      std::set & , const int  ) ;\n\nint main( ) {\n   std::vector > items ;\n   \/\/===========fill the vector with data====================\n   items.push_back( boost::make_tuple( \"\" , 0  ,  0 ) ) ;\n   items.push_back( boost::make_tuple( \"map\" , 9 , 150 ) ) ;\n   items.push_back( boost::make_tuple( \"compass\" , 13 , 35 ) ) ;\n   items.push_back( boost::make_tuple( \"water\" , 153 , 200 ) ) ;\n   items.push_back( boost::make_tuple( \"sandwich\", 50 , 160 ) ) ;\n   items.push_back( boost::make_tuple( \"glucose\" , 15 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"tin\", 68 , 45 ) ) ;\n   items.push_back( boost::make_tuple( \"banana\", 27 , 60 ) ) ;\n   items.push_back( boost::make_tuple( \"apple\" , 39 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"cheese\" , 23 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"beer\" , 52 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"suntan creme\" , 11 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"camera\" , 32 , 30 ) ) ;\n   items.push_back( boost::make_tuple( \"T-shirt\" , 24 , 15 ) ) ;\n   items.push_back( boost::make_tuple( \"trousers\" , 48 , 10 ) ) ;\n   items.push_back( boost::make_tuple( \"umbrella\" , 73 , 40 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof trousers\" , 42 , 70 ) ) ;\n   items.push_back( boost::make_tuple( \"waterproof overclothes\" , 43 , 75 ) ) ;\n   items.push_back( boost::make_tuple( \"note-case\" , 22 , 80 ) ) ;\n   items.push_back( boost::make_tuple( \"sunglasses\" , 7 , 20 ) ) ;\n   items.push_back( boost::make_tuple( \"towel\" , 18 , 12 ) ) ;\n   items.push_back( boost::make_tuple( \"socks\" , 4 , 50 ) ) ;\n   items.push_back( boost::make_tuple( \"book\" , 30 , 10 ) ) ;\n   const int maximumWeight = 400 ;\n   std::set bestItems ; \/\/these items will make up the optimal value\n   int bestValue = findBestPack( items , bestItems , maximumWeight ) ;\n   std::cout << \"The best value that can be packed in the given knapsack is \" <<\n      bestValue << \"\u00a0!\\n\" ;\n   int totalweight = 0 ;\n   std::cout << \"The following items should be packed in the knapsack:\\n\" ;\n   for ( std::set::const_iterator si = bestItems.begin( ) ; \n\t si != bestItems.end( ) ; si++ ) { \n      std::cout << (items.begin( ) + *si)->get<0>( ) << \"\\n\" ;\n      totalweight += (items.begin( ) + *si)->get<1>( ) ;\n   }\n   std::cout << \"The total weight of all items is \" << totalweight << \"\u00a0!\\n\" ;\n   return 0 ;\n}\n   \nint findBestPack( const std::vector > & items ,std::set & bestItems , const int weightlimit ) {\n   \/\/dynamic programming approach sacrificing storage space for execution\n   \/\/time , creating a table of optimal values for every weight and a \n   \/\/second table of sets with the items collected so far in the knapsack\n   \/\/the best value is in the bottom right corner of the values table,\n   \/\/the set of items in the bottom right corner of the sets' table.\n   const int n = items.size( ) ;\n   int bestValues [ n ][ weightlimit ] ;\n   std::set solutionSets[ n ][ weightlimit ] ;\n   std::set emptyset ;\n   for ( int i = 0 ; i < n ; i++ ) {\n      for ( int j = 0 ; j < weightlimit  ; j++ ) {\n\t bestValues[ i ][ j ] = 0 ;\n\t solutionSets[ i ][ j ] = emptyset ;\n       }\n    }\n    for ( int i = 0 ; i < n ; i++ ) {\n       for ( int weight = 0 ; weight < weightlimit ; weight++ ) {\n\t  if ( i == 0 )\n\t     bestValues[ i ][ weight ] = 0 ;\n\t  else  {\n\t     int itemweight = (items.begin( ) + i)->get<1>( ) ; \n\t     if ( weight < itemweight ) {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     } else { \/\/ weight >= itemweight\n\t\tif ( bestValues[ i - 1 ][ weight - itemweight ] + \n\t\t   (items.begin( ) + i)->get<2>( ) >\n\t\t        bestValues[ i - 1 ][ weight ] ) {\n\t\t   bestValues[ i ][ weight ] = \n\t\t       bestValues[ i - 1 ][ weight - itemweight ] + \n\t        \t(items.begin( ) + i)->get<2>( ) ;\n\t\t  solutionSets[ i ][ weight ] = \n\t\t      solutionSets[ i - 1 ][ weight - itemweight ] ;\n\t\t  solutionSets[ i ][ weight ].insert( i ) ;\n\t     }\n\t     else {\n\t\tbestValues[ i ][ weight ] = bestValues[ i - 1 ][ weight ] ;\n\t\tsolutionSets[ i ][ weight ] = solutionSets[ i - 1 ][ weight ] ;\n\t     }\n\t  }\n       }\n      }\n    }\n    bestItems.swap( solutionSets[ n - 1][ weightlimit - 1 ] ) ;\n    return bestValues[ n - 1 ][ weightlimit - 1 ] ;\n}\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":911}
    {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\nconst char *men_data[][11] = {\n    { \"abe\",  \"abi\",\"eve\",\"cath\",\"ivy\",\"jan\",\"dee\",\"fay\",\"bea\",\"hope\",\"gay\" },\n    { \"bob\",  \"cath\",\"hope\",\"abi\",\"dee\",\"eve\",\"fay\",\"bea\",\"jan\",\"ivy\",\"gay\" },\n    { \"col\",  \"hope\",\"eve\",\"abi\",\"dee\",\"bea\",\"fay\",\"ivy\",\"gay\",\"cath\",\"jan\" },\n    { \"dan\",  \"ivy\",\"fay\",\"dee\",\"gay\",\"hope\",\"eve\",\"jan\",\"bea\",\"cath\",\"abi\" },\n    { \"ed\",   \"jan\",\"dee\",\"bea\",\"cath\",\"fay\",\"eve\",\"abi\",\"ivy\",\"hope\",\"gay\" },\n    { \"fred\", \"bea\",\"abi\",\"dee\",\"gay\",\"eve\",\"ivy\",\"cath\",\"jan\",\"hope\",\"fay\" },\n    { \"gav\",  \"gay\",\"eve\",\"ivy\",\"bea\",\"cath\",\"abi\",\"dee\",\"hope\",\"jan\",\"fay\" },\n    { \"hal\",  \"abi\",\"eve\",\"hope\",\"fay\",\"ivy\",\"cath\",\"jan\",\"bea\",\"gay\",\"dee\" },\n    { \"ian\",  \"hope\",\"cath\",\"dee\",\"gay\",\"bea\",\"abi\",\"fay\",\"ivy\",\"jan\",\"eve\" },\n    { \"jon\",  \"abi\",\"fay\",\"jan\",\"gay\",\"eve\",\"bea\",\"dee\",\"cath\",\"ivy\",\"hope\" }\n};\n \nconst char *women_data[][11] = {\n    { \"abi\",  \"bob\",\"fred\",\"jon\",\"gav\",\"ian\",\"abe\",\"dan\",\"ed\",\"col\",\"hal\" },\n    { \"bea\",  \"bob\",\"abe\",\"col\",\"fred\",\"gav\",\"dan\",\"ian\",\"ed\",\"jon\",\"hal\" },\n    { \"cath\", \"fred\",\"bob\",\"ed\",\"gav\",\"hal\",\"col\",\"ian\",\"abe\",\"dan\",\"jon\" },\n    { \"dee\",  \"fred\",\"jon\",\"col\",\"abe\",\"ian\",\"hal\",\"gav\",\"dan\",\"bob\",\"ed\" },\n    { \"eve\",  \"jon\",\"hal\",\"fred\",\"dan\",\"abe\",\"gav\",\"col\",\"ed\",\"ian\",\"bob\" },\n    { \"fay\",  \"bob\",\"abe\",\"ed\",\"ian\",\"jon\",\"dan\",\"fred\",\"gav\",\"col\",\"hal\" },\n    { \"gay\",  \"jon\",\"gav\",\"hal\",\"fred\",\"bob\",\"abe\",\"col\",\"ed\",\"dan\",\"ian\" },\n    { \"hope\", \"gav\",\"jon\",\"bob\",\"abe\",\"ian\",\"dan\",\"hal\",\"ed\",\"col\",\"fred\" },\n    { \"ivy\",  \"ian\",\"col\",\"hal\",\"gav\",\"fred\",\"bob\",\"abe\",\"ed\",\"jon\",\"dan\" },\n    { \"jan\",  \"ed\",\"hal\",\"gav\",\"abe\",\"bob\",\"jon\",\"col\",\"ian\",\"fred\",\"dan\" }\n};\n\ntypedef vector PrefList;\ntypedef map PrefMap;\ntypedef map Couples;\n\n\/\/ Does 'first' appear before 'second' in preference list?\nbool prefers(const PrefList &prefer, const string &first, const string &second)\n{\n    for (PrefList::const_iterator it = prefer.begin(); it != prefer.end(); ++it)\n    {\n        if (*it == first) return true;\n        if (*it == second) return false;\n    }\n    return false; \/\/ no preference\n}\n\nvoid check_stability(const Couples &engaged, const PrefMap &men_pref, const PrefMap &women_pref)\n{\n    cout << \"Stablility:\\n\";\n    bool stable = true;\n    for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)\n    {\n        const string &bride = it->first;\n        const string &groom = it->second;\n        const PrefList &preflist = men_pref.at(groom);\n\n        for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)\n        {\n            if (*it == bride) \/\/ he prefers his bride\n                break;\n            if (prefers(preflist, *it, bride) && \/\/ he prefers another woman\n                prefers(women_pref.at(*it), groom, engaged.at(*it))) \/\/ other woman prefers him\n            {\n                cout << \"\\t\" << *it <<\n                    \" prefers \" << groom <<\n                    \" over \" << engaged.at(*it) <<\n                    \" and \" << groom <<\n                    \" prefers \" << *it <<\n                    \" over \" << bride << \"\\n\";\n                stable = false;\n            }\n        }\n    }\n    if (stable) cout << \"\\t(all marriages stable)\\n\";\n}\n\nint main()\n{\n    PrefMap men_pref, women_pref;\n    queue bachelors;\n\n    \/\/ init data structures\n    for (int i = 0; i < 10; ++i) \/\/ person\n    {\n        for (int j = 1; j < 11; ++j) \/\/ preference\n        {\n              men_pref[  men_data[i][0]].push_back(  men_data[i][j]);\n            women_pref[women_data[i][0]].push_back(women_data[i][j]);\n        }\n        bachelors.push(men_data[i][0]);\n    }\n\n    Couples engaged; \/\/ \n\n    cout << \"Matchmaking:\\n\";\n    while (!bachelors.empty())\n    {\n        const string &suitor = bachelors.front();\n        const PrefList &preflist = men_pref[suitor];\n\n        for (PrefList::const_iterator it = preflist.begin(); it != preflist.end(); ++it)\n        {\n            const string &bride = *it;\n\n            if (engaged.find(bride) == engaged.end()) \/\/ she's available\n            {\n                cout << \"\\t\" << bride << \" and \" << suitor << \"\\n\";\n                engaged[bride] = suitor; \/\/ hook up\n                break;\n            }\n\n            const string &groom = engaged[bride];\n\n            if (prefers(women_pref[bride], suitor, groom))\n            {\n                cout << \"\\t\" << bride << \" dumped \" << groom << \" for \" << suitor << \"\\n\";\n                bachelors.push(groom); \/\/ dump that zero\n                engaged[bride] = suitor; \/\/ get a hero\n                break;\n            }\n        }\n        bachelors.pop(); \/\/ pop at the end to not invalidate suitor reference\n    }\n\n    cout << \"Engagements:\\n\";\n    for (Couples::const_iterator it = engaged.begin(); it != engaged.end(); ++it)\n    {\n        cout << \"\\t\" << it->first << \" and \" << it->second << \"\\n\";\n    }\n\n    check_stability(engaged, men_pref, women_pref);\n\n    cout << \"Perturb:\\n\";\n    std::swap(engaged[\"abi\"], engaged[\"bea\"]);\n    cout << \"\\tengage abi with \" << engaged[\"abi\"] << \" and bea with \" << engaged[\"bea\"] << \"\\n\";\n\n    check_stability(engaged, men_pref, women_pref);\n}\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":912}
    {"lang_cluster":"C++","source_code":"\n\n#include \n\nbool a(bool in)\n{\n    std::cout << \"a\" << std::endl;\n    return in;\n}\n\nbool b(bool in)\n{\n    std::cout << \"b\" << std::endl;\n    return in;\n}\n\nvoid test(bool i, bool j) {\n    std::cout << std::boolalpha << i << \" and \" << j << \" = \" << (a(i) && b(j)) << std::endl;\n    std::cout << std::boolalpha << i << \" or \" << j << \" = \" << (a(i) || b(j)) << std::endl;\n}\n\nint main()\n{\n    test(false, false);\n    test(false, true);\n    test(true, false);\n    test(true, true);\n    return 0;\n}\n\n\n","human_summarization":"The code defines two functions, 'a' and 'b', that take a boolean input, return the same value, and print their name when called. It then calculates the values of two equations, 'x' and 'y', using these functions. The code is optimized to only call function 'b' when necessary, utilizing short-circuit evaluation in conjunction and disjunction operations. If the programming language does not support short-circuit evaluation, nested 'if' statements are used instead.","id":913}
    {"lang_cluster":"C++","source_code":"\n\/*\nMichal Sikorski\n06\/07\/2016\n*\/\n#include \n#include \n#include \n#include \nusing namespace std;\nint main(int argc, char *argv[])\n{\n    string inpt;\n    char ascii[28] = \" ABCDEFGHIJKLMNOPQRSTUVWXYZ\", lwcAscii[28] = \" abcdefghijklmnopqrstuvwxyz\";\n    string morse[27] = {\"  \", \".- \", \"-... \", \"-.-. \", \"-.. \", \". \", \"..-. \", \"--. \", \".... \", \".. \", \".--- \", \"-.- \", \".-.. \", \"-- \", \"-. \", \"--- \", \".--.\", \"--.- \", \".-. \", \"... \", \"- \", \"..- \", \"...- \", \".-- \", \"-..- \", \"-.-- \", \"--.. \"};\n    string outpt;\n    getline(cin,inpt);\n    int xx=0;\n    int size = inpt.length();\n    cout<<\"Length:\"< convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":914}
    {"lang_cluster":"C++","source_code":"\nWorks with: C++11\n\ng++-4.7 -Wall -std=c++0x abc.cpp\n\n#include \n#include \n#include \n#include \n#include \n\ntypedef std::pair item_t;\ntypedef std::vector list_t;\n\nbool can_make_word(const std::string& w, const list_t& vals) {\n    std::set used;\n    while (used.size() < w.size()) {\n        const char c = toupper(w[used.size()]);\n        uint32_t x = used.size();\n        for (uint32_t i = 0, ii = vals.size(); i < ii; ++i) {\n            if (used.find(i) == used.end()) {\n                if (toupper(vals[i].first) == c || toupper(vals[i].second) == c) {\n                    used.insert(i);\n                    break;\n                }\n            }\n        }\n        if (x == used.size()) break;\n    }\n    return used.size() == w.size();\n}\n\nint main() {\n    list_t vals{ {'B','O'}, {'X','K'}, {'D','Q'}, {'C','P'}, {'N','A'}, {'G','T'}, {'R','E'}, {'T','G'}, {'Q','D'}, {'F','S'}, {'J','W'}, {'H','U'}, {'V','I'}, {'A','N'}, {'O','B'}, {'E','R'}, {'F','S'}, {'L','Y'}, {'P','C'}, {'Z','M'} };\n    std::vector words{\"A\",\"BARK\",\"BOOK\",\"TREAT\",\"COMMON\",\"SQUAD\",\"CONFUSE\"};\n    for (const std::string& w : words) {\n        std::cout << w << \": \" << std::boolalpha << can_make_word(w,vals) << \".\\n\";\n    }\n}\n\n\n","human_summarization":"The code takes a string input and checks if it can be spelled using a given collection of ABC blocks. Each block can only be used once and the check is case-insensitive. The code returns a boolean value indicating whether or not the word can be formed. It tests this functionality with seven example words.","id":915}
    {"lang_cluster":"C++","source_code":"\nLibrary: Poco Crypto\n#include \n#include \n#include \"Poco\/MD5Engine.h\"\n#include \"Poco\/DigestStream.h\"\n\nusing Poco::DigestEngine ;\nusing Poco::MD5Engine ;\nusing Poco::DigestOutputStream ;\n\nint main( ) {\n   std::string myphrase ( \"The quick brown fox jumped over the lazy dog's back\" ) ;\n   MD5Engine md5 ;\n   DigestOutputStream outstr( md5 ) ;\n   outstr << myphrase ;\n   outstr.flush( ) ; \/\/to pass everything to the digest engine\n   const DigestEngine::Digest& digest = md5.digest( ) ;\n   std::cout << myphrase << \" as a MD5 digest\u00a0:\\n\" << DigestEngine::digestToHex( digest ) \n      << \"\u00a0!\" << std::endl ;\n   return 0 ;\n}\n\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":916}
    {"lang_cluster":"C++","source_code":"\n#include \n#include \n#include \n#include \n#include \n\nstd::vector splitOnChar ( std::string & s , const char c ) {\n   typedef boost::tokenizer> tokenizer ;\n   std::vector parts ;\n   boost::char_separator sep( &c ) ;\n   tokenizer tokens( s , sep ) ;\n   for ( auto it = tokens.begin( ) ; it != tokens.end( ) ; it++ ) \n      parts.push_back( *it ) ;\n   return parts ;\n}\n\nbool myCompare ( const std::string & s1 , const std::string & s2 ) {\n   std::string firstcopy( s1 ) ;\n   std::string secondcopy ( s2 ) ;\n   std::vector firstparts( splitOnChar ( firstcopy, '.' ) ) ;\n   std::vector secondparts( splitOnChar ( secondcopy, '.' ) ) ;\n   std::vector numbers1( firstparts.size( ) ) ;\n   std::vector numbers2( secondparts.size( ) ) ;\n   std::transform( firstparts.begin( ) , firstparts.end( ) , numbers1.begin( ) ,\n\t []( std::string st ) { return std::stoi( st , nullptr ) ; } ) ;\n   std::transform( secondparts.begin( ) , secondparts.end( ) , numbers2.begin( ) ,\n\t []( std::string st ) { return std::stoi( st , nullptr ) ; } ) ;\n   auto it1 = numbers1.begin( ) ;\n   auto it2 = numbers2.begin( ) ;\n   while ( *it1 == *it2 ) {\n      it1++ ;\n      it2++ ;\n   }\n   if ( it1 == numbers1.end( )  || it2 == numbers2.end( )  )\n      return std::lexicographical_compare( s1.begin( ) , s1.end( ) , s2.begin( ) , s2.end( ) ) ;\n   return *it1 < *it2 ;\n}\n\nint main( ) {\n   std::vector arrayOID { \"1.3.6.1.4.1.11.2.17.19.3.4.0.10\" ,\n      \"1.3.6.1.4.1.11.2.17.5.2.0.79\" ,\n      \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\" ,\n      \"1.3.6.1.4.1.11150.3.4.0.1\" ,\n      \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\" ,\n      \"1.3.6.1.4.1.11150.3.4.0\" } ;\n   std::sort( arrayOID.begin( ) , arrayOID.end( ) , myCompare ) ;\n   for ( std::string s : arrayOID ) \n      std::cout << s << '\\n' ;\n   return 0 ;\n}\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. OIDs are strings of one or more non-negative integers in base 10, separated by dots. The sorting is done based on numeric comparison between the dot-separated fields.","id":917}
    {"lang_cluster":"C++","source_code":"\n\n\/\/compile with g++ main.cpp -lboost_system -pthread \n\n#include \n\nint main()\n{\n  boost::asio::io_context io_context;\n  boost::asio::ip::tcp::socket sock(io_context);\n  boost::asio::ip::tcp::resolver resolver(io_context);\n  boost::asio::ip::tcp::resolver::query query(\"localhost\", \"4321\");\n\n  boost::asio::connect(sock, resolver.resolve(query));\n  boost::asio::write(sock, boost::asio::buffer(\"Hello world socket\\r\\n\"));\n\n  return 0;\n}\n\n","human_summarization":"The code opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket. No exception handling is implemented. The functionality was tested using nc -vlp 4321.","id":918}
    {"lang_cluster":"C++","source_code":"\nLibrary: POCO\nWorks with: POCO version 1.3.6\n\/\/ on Ubuntu: sudo apt-get install libpoco-dev\n\/\/ or see http:\/\/pocoproject.org\/\n\/\/ compile with: g++ -Wall -O3 send-mail-cxx.C -lPocoNet -lPocoFoundation\n\n#include \n#include \n#include \n#include \n\nusing namespace Poco::Net;\n\nint main (int argc, char **argv)\n{\n  try\n    {\n      MailMessage msg;\n\n      msg.addRecipient (MailRecipient (MailRecipient::PRIMARY_RECIPIENT,\n                                       \"alice@example.com\",\n                                       \"Alice Moralis\"));\n      msg.addRecipient (MailRecipient (MailRecipient::CC_RECIPIENT,\n                                       \"pat@example.com\",\n                                       \"Patrick Kilpatrick\"));\n      msg.addRecipient (MailRecipient (MailRecipient::BCC_RECIPIENT,\n                                       \"mike@example.com\",\n                                       \"Michael Carmichael\"));\n\n      msg.setSender (\"Roy Kilroy \");\n\n      msg.setSubject (\"Rosetta Code\");\n      msg.setContent (\"Sending mail from C++ using POCO C++ Libraries\");\n\n      SMTPClientSession smtp (\"mail.example.com\"); \/\/ SMTP server name\n      smtp.login ();\n      smtp.sendMessage (msg);\n      smtp.close ();\n      std::cerr << \"Sent mail successfully!\" << std::endl;\n    }\n  catch (std::exception &e)\n    {\n      std::cerr << \"failed to send mail: \" << e.what() << std::endl;\n      return EXIT_FAILURE;\n    }\n\n  return EXIT_SUCCESS;\n}\n\n\nfailed to send mail: Host not found\n\n","human_summarization":"The code is a function for sending an email. It takes parameters for setting the sender, recipient, and Cc addresses, the subject, and the message text. It also optionally accepts server name and login details. The code uses built-in language libraries or functions, and is portable across different operating systems. It prints an error message if the SMTP server does not exist and requires manual input of a valid SMTP server and adjustment of sender and recipient addresses. The function does not perform authentication, but it can accept a username and password for this purpose. It also supports STARTTLS through SecureSMTPClientSession in newer versions of POCO.","id":919}
    {"lang_cluster":"C++","source_code":"\n\n#include \n\nint main()\n{\n  unsigned i = 0;\n  do\n  {\n    std::cout << std::oct << i << std::endl;\n    ++i;\n  } while(i != 0);\n  return 0;\n}\n\n","human_summarization":"generate a sequential count in octal format, starting from zero and incrementing by one. Each number is printed on a separate line. The counting continues until the program is terminated or the maximum value of the numeric type in use is reached, preventing an infinite loop.","id":920}
    {"lang_cluster":"C++","source_code":"\n\ntemplate void swap(T& left, T& right)\n{\n  T tmp(left);\n  left = right;\n  right = tmp;\n}\n\n\nstd::swap(x,y);\n\n\n\ntemplate\nvoid swap(T &lhs, T &rhs){\n  T tmp = std::move(lhs);\n  lhs = std::move(rhs);\n  rhs = std::move(tmp);\n}\n\n","human_summarization":"implement a generic swap function or operator that can exchange the values of two variables, regardless of their types. The function uses templates in C++ for generic programming, requiring the type T to have an accessible copy constructor and assignment operator. The standard utility 'swap' is used to swap two values, compatible with any types. The code also utilizes C++11's move constructors for efficiency.","id":921}
    {"lang_cluster":"C++","source_code":"\n\n#include \n#include \n\nbool is_palindrome(std::string const& s)\n{\n  return std::equal(s.begin(), s.end(), s.rbegin());\n}\n\n\n#include \n#include \n\nbool is_palindrome(std::string const& s)\n{\n  return std::equal(s.begin(), s.begin()+s.length()\/2, s.rbegin());\n}\n\n","human_summarization":"The code checks if a given sequence of characters is a palindrome. It supports Unicode characters and can detect inexact palindromes by ignoring white-space, punctuation, and case. It uses a function to reverse a string for palindrome detection and includes a test function. For odd-length strings, it checks half of the string, ignoring the middle element.","id":922}
    {"lang_cluster":"C++","source_code":"\n#include \n#include \n\nint main()\n{\n   puts(getenv(\"HOME\"));\n   return 0;\n}\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":923}
    {"lang_cluster":"C++","source_code":"\/\/Aamrun , 11th July, 2022\n\n#include \nusing namespace std;\n\nint F(int n,int x,int y) {\n  if (n == 0) {\n    return x + y;\n  }\n \n  else if (y == 0) {\n    return x;\n  }\n \n  return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y);\n}\n\nint main() {\n  cout << \"F(1,3,3) = \"< this%first\n    x = this%first%data\n    this%first => this%first%next\n    deallocate(tmp)\n    this%len = this%len -1\n  end function pop\n\n  subroutine push(this, x)\n    real*8 :: x\n    class(stack), target :: this\n    type(node), pointer :: new, tmp\n    allocate(new)\n    new%data = x\n    if (.not. associated(this%first)) then\n      this%first => new\n    else\n      tmp => this%first\n      this%first => new\n      this%first%next => tmp\n    end if\n    this%len = this%len + 1\n  end subroutine push\n\n  function peek(this) result(x)\n    class(stack) :: this\n    real*8 :: x\n    x = this%first%data\n  end function peek\n\n  function getSize(this) result(n)\n    class(stack) :: this\n    integer :: n\n    n = this%len\n  end function getSize\n\n  function isEmpty(this) result(empty)\n    class(stack) :: this\n    logical :: empty\n    if ( this%len > 0 ) then\n      empty = .FALSE.\n    else\n      empty = .TRUE.\n    end if\n  end function isEmpty\n\n  subroutine clearStack(this)\n    class(stack) :: this\n    type(node), pointer :: tmp\n    integer :: i\n    if ( this%len == 0 ) then\n      return\n    end if\n    do i = 1, this%len\n      tmp => this%first\n      if ( .not. associated(tmp)) exit\n      this%first => this%first%next\n      deallocate(tmp)\n    end do\n    this%len = 0\n  end subroutine clearStack\nend module mod_stack\n\nprogram main\n  use mod_stack\n  type(stack) :: my_stack\n  integer :: i\n  real*8 :: dat\n  do i = 1, 5, 1\n    dat = 1.0 * i\n    call my_stack%push(dat)\n  end do\n  do while ( .not. my_stack%isEmpty() )\n    print*, my_stack%pop()\n  end do\n  call my_stack%clearStack()\nend program main\n\n","human_summarization":"implement a stack data structure with basic operations such as push (adds an element to the top of the stack), pop (removes the topmost element from the stack and returns it), and empty (checks if the stack is empty). The stack follows a last in, first out (LIFO) access policy. The code can be adapted to various data types, not just floating point numbers.","id":925}
    {"lang_cluster":"Fortran","source_code":"\nC     FIBONACCI SEQUENCE - FORTRAN IV\n      NN=46\n      DO 1 I=0,NN\n    1 WRITE(*,300) I,IFIBO(I)\n  300 FORMAT(1X,I2,1X,I10)\n      END\nC\n      FUNCTION IFIBO(N)\n      IF(N) 9,1,2\n    1 IFN=0\n      GOTO 9\n    2 IF(N-1) 9,3,4\n    3 IFN=1\n      GOTO 9\n    4 IFNM1=0\n      IFN=1\n      DO 5 I=2,N\n      IFNM2=IFNM1\n      IFNM1=IFN\n    5 IFN=IFNM1+IFNM2\n    9 IFIBO=IFN\n      END\n\n","human_summarization":"The code is a function that generates the nth Fibonacci number, which can be either iterative or recursive. It follows the Fibonacci sequence rules, with optional support for negative n values. The function is written in ISO Fortran 90 or later.","id":926}
    {"lang_cluster":"Fortran","source_code":"\nmodule funcs\n  implicit none\ncontains\n  pure function iseven(x)\n    logical :: iseven\n    integer, intent(in) :: x\n    iseven = mod(x, 2) == 0\n  end function iseven\nend module funcs\n\nprogram Filter\n  use funcs\n  implicit none\n\n  integer, parameter                 :: N = 100\n  integer, dimension(N)              :: array\n  integer, dimension(:), pointer     :: filtered\n\n  integer :: i\n\n  forall(i=1:N) array(i) = i\n\n  filtered => filterwith(array, iseven)\n  print *, filtered\n\ncontains\n\n  function filterwith(ar, testfunc)\n    integer, dimension(:), pointer        :: filterwith\n    integer, dimension(:), intent(in)     :: ar\n    interface\n       elemental function testfunc(x)\n         logical :: testfunc\n         integer, intent(in) :: x\n       end function testfunc\n    end interface\n\n    integer :: i, j, n\n\n    n = count( testfunc(ar) )\n    allocate( filterwith(n) )\n\n    j = 1\n    do i = lbound(ar, dim=1), ubound(ar, dim=1)\n       if ( testfunc(ar(i)) ) then\n          filterwith(j) = ar(i)\n          j = j + 1\n       end if\n    end do\n\n  end function filterwith\n\nend program Filter\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":927}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram test_substring\n\n  character (*), parameter :: string = 'The quick brown fox jumps over the lazy dog.'\n  character (*), parameter :: substring = 'brown'\n  character    , parameter :: c = 'q'\n  integer      , parameter :: n = 5\n  integer      , parameter :: m = 15\n  integer                  :: i\n\n! Display the substring starting from n characters in and of length m.\n  write (*, '(a)') string (n : n + m - 1)\n! Display the substring starting from n characters in, up to the end of the string.\n  write (*, '(a)') string (n :)\n! Display the whole string minus the last character.\n  i = len (string) - 1\n  write (*, '(a)') string (: i)\n! Display the substring starting from a known character and of length m.\n  i = index (string, c)\n  write (*, '(a)') string (i : i + m - 1)\n! Display the substring starting from a known substring and of length m.\n  i = index (string, substring)\n  write (*, '(a)') string (i : i + m - 1)\n\nend program test_substring\n\n\n","human_summarization":"The code performs the following operations: \n\n1. It displays a substring starting from 'n' characters in and of 'm' length.\n2. It displays a substring starting from 'n' characters in, up to the end of the string.\n3. It displays the whole string minus the last character.\n4. It displays a substring starting from a known character within the string and of 'm' length.\n5. It displays a substring starting from a known substring within the string and of 'm' length.\n\nThe code is compatible with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. It is not required to handle all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP. In Fortran, the positions inside character strings are one-based.","id":928}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nPROGRAM Example\n\n  CHARACTER(80) :: str = \"This is a string\"\n  CHARACTER :: temp\n  INTEGER :: i, length\n\n  WRITE (*,*) str\n  length = LEN_TRIM(str) ! Ignores trailing blanks. Use LEN(str) to reverse those as well\n  DO i = 1, length\/2\n     temp = str(i:i)\n     str(i:i) = str(length+1-i:length+1-i)\n     str(length+1-i:length+1-i) = temp\n  END DO\n  WRITE(*,*) str\n\nEND PROGRAM Example\n\n\n","human_summarization":"\"Reverses a given string while preserving the order of Unicode combining characters.\"","id":929}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 2008\nWorks with: Fortran version 2018\n\nmodule avl_trees\n  !\n  ! References:\n  !\n  !   * Niklaus Wirth, 1976. Algorithms + Data Structures =\n  !     Programs. Prentice-Hall, Englewood Cliffs, New Jersey.\n  !\n  !   * Niklaus Wirth, 2004. Algorithms and Data Structures. Updated\n  !     by Fyodor Tkachov, 2014.\n  !\n\n  implicit none\n  private\n\n  ! The type for an AVL tree.\n  public :: avl_tree_t\n\n  ! The type for a pair of pointers to key and data within the tree.\n  ! (Be careful with these!)\n  public :: avl_pointer_pair_t\n\n  ! Insertion, replacement, modification, etc.\n  public :: avl_insert_or_modify\n\n  ! Insert or replace.\n  public :: avl_insert\n\n  ! Is the key in the tree?\n  public :: avl_contains\n\n  ! Retrieve data from a tree.\n  public :: avl_retrieve\n\n  ! Delete data from a tree. This is a generic function.\n  public :: avl_delete\n\n  ! Implementations of avl_delete.\n  public :: avl_delete_with_found\n  public :: avl_delete_without_found\n\n  ! How many nodes are there in the tree?\n  public :: avl_size\n\n  ! Return a list of avl_pointer_pair_t for the elements in the\n  ! tree. The list will be in order.\n  public :: avl_pointer_pairs\n\n  ! Print a representation of the tree to an output unit.\n  public :: avl_write\n\n  ! Check the AVL condition (that the heights of the two branches from\n  ! a node should differ by zero or one). ERROR STOP if the condition\n  ! is not met.\n  public :: avl_check\n\n  ! Procedure types.\n  public :: avl_less_than_t\n  public :: avl_insertion_t\n  public :: avl_key_data_writer_t\n\n  type :: avl_node_t\n     class(*), allocatable :: key, data\n     type(avl_node_t), pointer :: left\n     type(avl_node_t), pointer :: right\n     integer :: bal             ! bal == -1, 0, 1\n  end type avl_node_t\n\n  type :: avl_tree_t\n     type(avl_node_t), pointer :: p => null ()\n   contains\n     final :: avl_tree_t_final\n  end type avl_tree_t\n\n  type :: avl_pointer_pair_t\n     class(*), pointer :: p_key, p_data\n     class(avl_pointer_pair_t), pointer :: next => null ()\n   contains\n     final :: avl_pointer_pair_t_final\n  end type avl_pointer_pair_t\n\n  interface avl_delete\n     module procedure avl_delete_with_found\n     module procedure avl_delete_without_found\n  end interface avl_delete\n\n  interface\n     function avl_less_than_t (key1, key2) result (key1_lt_key2)\n       !\n       ! The ordering predicate (\u2018<\u2019).\n       !\n       ! Two keys a,b are considered equivalent if neither a tree%p\n    call free_the_nodes (p)\n\n  contains\n\n    recursive subroutine free_the_nodes (p)\n      type(avl_node_t), pointer, intent(inout) :: p\n\n      if (associated (p)) then\n         call free_the_nodes (p%left)\n         call free_the_nodes (p%right)\n         deallocate (p)\n      end if\n    end subroutine free_the_nodes\n\n  end subroutine avl_tree_t_final\n\n  recursive subroutine avl_pointer_pair_t_final (node)\n    type(avl_pointer_pair_t), intent(inout) :: node\n\n    if (associated (node%next)) deallocate (node%next)\n  end subroutine avl_pointer_pair_t_final\n\n  function avl_contains (less_than, key, tree) result (found)\n    procedure(avl_less_than_t) :: less_than\n    class(*), intent(in) :: key\n    class(avl_tree_t), intent(in) :: tree\n    logical :: found\n\n    found = avl_contains_recursion (less_than, key, tree%p)\n  end function avl_contains\n\n  recursive function avl_contains_recursion (less_than, key, p) result (found)\n    procedure(avl_less_than_t) :: less_than\n    class(*), intent(in) :: key\n    type(avl_node_t), pointer, intent(in) :: p\n    logical :: found\n\n    if (.not. associated (p)) then\n       found = .false.\n    else if (less_than (key, p%key)) then\n       found = avl_contains_recursion (less_than, key, p%left)\n    else if (less_than (p%key, key)) then\n       found = avl_contains_recursion (less_than, key, p%right)\n    else\n       found = .true.\n    end if\n  end function avl_contains_recursion\n\n  subroutine avl_retrieve (less_than, key, tree, found, data)\n    procedure(avl_less_than_t) :: less_than\n    class(*), intent(in) :: key\n    class(avl_tree_t), intent(in) :: tree\n    logical, intent(out) :: found\n    class(*), allocatable, intent(inout) :: data\n\n    call avl_retrieve_recursion (less_than, key, tree%p, found, data)\n  end subroutine avl_retrieve\n\n  recursive subroutine avl_retrieve_recursion (less_than, key, p, found, data)\n    procedure(avl_less_than_t) :: less_than\n    class(*), intent(in) :: key\n    type(avl_node_t), pointer, intent(in) :: p\n    logical, intent(out) :: found\n    class(*), allocatable, intent(inout) :: data\n\n    if (.not. associated (p)) then\n       found = .false.\n    else if (less_than (key, p%key)) then\n       call avl_retrieve_recursion (less_than, key, p%left, found, data)\n    else if (less_than (p%key, key)) then\n       call avl_retrieve_recursion (less_than, key, p%right, found, data)\n    else\n       found = .true.\n       data = p%data\n    end if\n  end subroutine avl_retrieve_recursion\n\n  subroutine avl_insert (less_than, key, data, tree)\n    procedure(avl_less_than_t) :: less_than\n    class(*), intent(in) :: key, data\n    class(avl_tree_t), intent(inout) :: tree\n\n    call avl_insert_or_modify (less_than, insert_or_replace, key, data, tree)\n  end subroutine avl_insert\n\n  subroutine insert_or_replace (key, data, p_is_new, p)\n    class(*), intent(in) :: key, data\n    logical, intent(in) :: p_is_new\n    type(avl_node_t), pointer, intent(inout) :: p\n\n    p%data = data\n  end subroutine insert_or_replace\n\n  subroutine avl_insert_or_modify (less_than, insertion, key, data, tree)\n    procedure(avl_less_than_t) :: less_than\n    procedure(avl_insertion_t) :: insertion ! Or modification in place.\n    class(*), intent(in) :: key, data\n    class(avl_tree_t), intent(inout) :: tree\n\n    logical :: fix_balance\n\n    fix_balance = .false.\n    call insertion_search (less_than, insertion, key, data, tree%p, fix_balance)\n  end subroutine avl_insert_or_modify\n\n  recursive subroutine insertion_search (less_than, insertion, key, data, p, fix_balance)\n    procedure(avl_less_than_t) :: less_than\n    procedure(avl_insertion_t) :: insertion\n    class(*), intent(in) :: key, data\n    type(avl_node_t), pointer, intent(inout) :: p\n    logical, intent(inout) :: fix_balance\n\n    type(avl_node_t), pointer :: p1, p2\n\n    if (.not. associated (p)) then\n       ! The key was not found. Make a new node.\n       allocate (p)\n       p%key = key\n       p%left => null ()\n       p%right => null ()\n       p%bal = 0\n       call insertion (key, data, .true., p)\n       fix_balance = .true.\n    else if (less_than (key, p%key)) then\n       ! Continue searching.\n       call insertion_search (less_than, insertion, key, data, p%left, fix_balance)\n       if (fix_balance) then\n          ! A new node has been inserted on the left side.\n          select case (p%bal)\n          case (1)\n             p%bal = 0\n             fix_balance = .false.\n          case (0)\n             p%bal = -1\n          case (-1)\n             ! Rebalance.\n             p1 => p%left\n             select case (p1%bal)\n             case (-1)\n                ! A single LL rotation.\n                p%left => p1%right\n                p1%right => p\n                p%bal = 0\n                p => p1\n                p%bal = 0\n                fix_balance = .false.\n             case (0, 1)\n                ! A double LR rotation.\n                p2 => p1%right\n                p1%right => p2%left\n                p2%left => p1\n                p%left => p2%right\n                p2%right => p\n                p%bal = -(min (p2%bal, 0))\n                p1%bal = -(max (p2%bal, 0))\n                p => p2\n                p%bal = 0\n                fix_balance = .false.\n             case default\n                error stop\n             end select\n          case default\n             error stop\n          end select\n       end if\n    else if (less_than (p%key, key)) then\n       call insertion_search (less_than, insertion, key, data, p%right, fix_balance)\n       if (fix_balance) then\n          ! A new node has been inserted on the right side.\n          select case (p%bal)\n          case (-1)\n             p%bal = 0\n             fix_balance = .false.\n          case (0)\n             p%bal = 1\n          case (1)\n             ! Rebalance.\n             p1 => p%right\n             select case (p1%bal)\n             case (1)\n                ! A single RR rotation.\n                p%right => p1%left\n                p1%left => p\n                p%bal = 0\n                p => p1\n                p%bal = 0\n                fix_balance = .false.\n             case (-1, 0)\n                ! A double RL rotation.\n                p2 => p1%left\n                p1%left => p2%right\n                p2%right => p1\n                p%right => p2%left\n                p2%left => p\n                p%bal = -(max (p2%bal, 0))\n                p1%bal = -(min (p2%bal, 0))\n                p => p2\n                p%bal = 0\n                fix_balance = .false.\n             case default\n                error stop\n             end select\n          case default\n             error stop\n          end select\n       end if\n    else\n       ! The key was found. The pointer p points to an existing node.\n       call insertion (key, data, .false., p)\n    end if\n  end subroutine insertion_search\n\n  subroutine avl_delete_with_found (less_than, key, tree, found)\n    procedure(avl_less_than_t) :: less_than\n    class(*), intent(in) :: key\n    class(avl_tree_t), intent(inout) :: tree\n    logical, intent(out) :: found\n\n    logical :: fix_balance\n\n    fix_balance = .false.\n    call deletion_search (less_than, key, tree%p, fix_balance, found)\n  end subroutine avl_delete_with_found\n\n  subroutine avl_delete_without_found (less_than, key, tree)\n    procedure(avl_less_than_t) :: less_than\n    class(*), intent(in) :: key\n    class(avl_tree_t), intent(inout) :: tree\n\n    logical :: found\n\n    call avl_delete_with_found (less_than, key, tree, found)\n  end subroutine avl_delete_without_found\n\n  recursive subroutine deletion_search (less_than, key, p, fix_balance, found)\n    procedure(avl_less_than_t) :: less_than\n    class(*), intent(in) :: key\n    type(avl_node_t), pointer, intent(inout) :: p\n    logical, intent(inout) :: fix_balance\n    logical, intent(out) :: found\n\n    type(avl_node_t), pointer :: q\n\n    if (.not. associated (p)) then\n       ! The key is not in the tree.\n       found = .false.\n    else if (less_than (key, p%key)) then\n       call deletion_search (less_than, key, p%left, fix_balance, found)\n       if (fix_balance) call balance_for_shrunken_left (p, fix_balance)\n    else if (less_than (p%key, key)) then\n       call deletion_search (less_than, key, p%right, fix_balance, found)\n       if (fix_balance) call balance_for_shrunken_right (p, fix_balance)\n    else\n       q => p\n       if (.not. associated (q%right)) then\n          p => q%left\n          fix_balance = .true.\n       else if (.not. associated (q%left)) then\n          p => q%right\n          fix_balance = .true.\n       else\n          call del (q%left, q, fix_balance)\n          if (fix_balance) call balance_for_shrunken_left (p, fix_balance)\n       end if\n       deallocate (q)\n       found = .true.\n    end if\n  end subroutine deletion_search\n\n  recursive subroutine del (r, q, fix_balance)\n    type(avl_node_t), pointer, intent(inout) :: r, q\n    logical, intent(inout) :: fix_balance\n\n    if (associated (r%right)) then\n       call del (r%right, q, fix_balance)\n       if (fix_balance) call balance_for_shrunken_right (r, fix_balance)\n    else\n       q%key = r%key\n       q%data = r%data\n       q => r\n       r => r%left\n       fix_balance = .true.\n    end if\n  end subroutine del\n\n  subroutine balance_for_shrunken_left (p, fix_balance)\n    type(avl_node_t), pointer, intent(inout) :: p\n    logical, intent(inout) :: fix_balance\n\n    ! The left side has lost a node.\n\n    type(avl_node_t), pointer :: p1, p2\n\n    if (.not. fix_balance) error stop\n\n    select case (p%bal)\n    case (-1)\n       p%bal = 0\n    case (0)\n       p%bal = 1\n       fix_balance = .false.\n    case (1)\n       ! Rebalance.\n       p1 => p%right\n       select case (p1%bal)\n       case (0)\n          ! A single RR rotation.\n          p%right => p1%left\n          p1%left => p\n          p%bal = 1\n          p1%bal = -1\n          p => p1\n          fix_balance = .false.\n       case (1)\n          ! A single RR rotation.\n          p%right => p1%left\n          p1%left => p\n          p%bal = 0\n          p1%bal = 0\n          p => p1\n          fix_balance = .true.\n       case (-1)\n          ! A double RL rotation.\n          p2 => p1%left\n          p1%left => p2%right\n          p2%right => p1\n          p%right => p2%left\n          p2%left => p\n          p%bal = -(max (p2%bal, 0))\n          p1%bal = -(min (p2%bal, 0))\n          p => p2\n          p2%bal = 0\n       case default\n          error stop\n       end select\n    case default\n       error stop\n    end select\n  end subroutine balance_for_shrunken_left\n\n  subroutine balance_for_shrunken_right (p, fix_balance)\n    type(avl_node_t), pointer, intent(inout) :: p\n    logical, intent(inout) :: fix_balance\n\n    ! The right side has lost a node.\n\n    type(avl_node_t), pointer :: p1, p2\n\n    if (.not. fix_balance) error stop\n\n    select case (p%bal)\n    case (1)\n       p%bal = 0\n    case (0)\n       p%bal = -1\n       fix_balance = .false.\n    case (-1)\n       ! Rebalance.\n       p1 => p%left\n       select case (p1%bal)\n       case (0)\n          ! A single LL rotation.\n          p%left => p1%right\n          p1%right => p\n          p1%bal = 1\n          p%bal = -1\n          p => p1\n          fix_balance = .false.\n       case (-1)\n          ! A single LL rotation.\n          p%left => p1%right\n          p1%right => p\n          p1%bal = 0\n          p%bal = 0\n          p => p1\n          fix_balance = .true.\n       case (1)\n          ! A double LR rotation.\n          p2 => p1%right\n          p1%right => p2%left\n          p2%left => p1\n          p%left => p2%right\n          p2%right => p\n          p%bal = -(min (p2%bal, 0))\n          p1%bal = -(max (p2%bal, 0))\n          p => p2\n          p2%bal = 0\n       case default\n          error stop\n       end select\n    case default\n       error stop\n    end select\n  end subroutine balance_for_shrunken_right\n\n  function avl_size (tree) result (size)\n    class(avl_tree_t), intent(in) :: tree\n    integer :: size\n\n    size = traverse (tree%p)\n\n  contains\n\n    recursive function traverse (p) result (size)\n      type(avl_node_t), pointer, intent(in) :: p\n      integer :: size\n\n      if (associated (p)) then\n         ! The order of traversal is arbitrary.\n         size = 1 + traverse (p%left) + traverse (p%right)\n      else\n         size = 0\n      end if\n    end function traverse\n\n  end function avl_size\n\n  function avl_pointer_pairs (tree) result (lst)\n    class(avl_tree_t), intent(in) :: tree\n    type(avl_pointer_pair_t), pointer :: lst\n\n    ! Reverse in-order traversal of the tree, to produce a CONS-list\n    ! of pointers to the contents.\n\n    lst => null ()\n    if (associated (tree%p)) lst => traverse (tree%p, lst)\n\n  contains\n\n    recursive function traverse (p, lst1) result (lst2)\n      type(avl_node_t), pointer, intent(in) :: p\n      type(avl_pointer_pair_t), pointer, intent(in) :: lst1\n      type(avl_pointer_pair_t), pointer :: lst2\n\n      type(avl_pointer_pair_t), pointer :: new_entry\n\n      lst2 => lst1\n      if (associated (p%right)) lst2 => traverse (p%right, lst2)\n      allocate (new_entry)\n      new_entry%p_key => p%key\n      new_entry%p_data => p%data\n      new_entry%next => lst2\n      lst2 => new_entry\n      if (associated (p%left)) lst2 => traverse (p%left, lst2)\n    end function traverse\n\n  end function avl_pointer_pairs\n\n  subroutine avl_write (write_key_data, unit, tree)\n    procedure(avl_key_data_writer_t) :: write_key_data\n    integer, intent(in) :: unit\n    class(avl_tree_t), intent(in) :: tree\n\n    character(len = *), parameter :: tab = achar (9)\n\n    type(avl_node_t), pointer :: p\n\n    p => tree%p\n    if (.not. associated (p)) then\n       continue\n    else\n       call traverse (p%left, 1, .true.)\n       call write_key_data (unit, p%key, p%data)\n       write (unit, '(2A, \"depth = \", I0, \"  bal = \", I0)') tab, tab, 0, p%bal\n       call traverse (p%right, 1, .false.)\n    end if\n\n  contains\n\n    recursive subroutine traverse (p, depth, left)\n      type(avl_node_t), pointer, intent(in) :: p\n      integer, value :: depth\n      logical, value :: left\n\n      if (.not. associated (p)) then\n         continue\n      else\n         call traverse (p%left, depth + 1, .true.)\n         call pad (depth, left)\n         call write_key_data (unit, p%key, p%data)\n         write (unit, '(2A, \"depth = \", I0, \"  bal = \", I0)') tab, tab, depth, p%bal\n         call traverse (p%right, depth + 1, .false.)\n      end if\n    end subroutine traverse\n\n    subroutine pad (depth, left)\n      integer, value :: depth\n      logical, value :: left\n\n      integer :: i\n\n      do i = 1, depth\n         write (unit, '(2X)', advance = 'no')\n      end do\n    end subroutine pad\n\n  end subroutine avl_write\n\n  subroutine avl_check (tree)\n    use, intrinsic :: iso_fortran_env, only: error_unit\n    class(avl_tree_t), intent(in) :: tree\n\n    type(avl_node_t), pointer :: p\n    integer :: height_L, height_R\n\n    p => tree%p\n    call get_heights (p, height_L, height_R)\n    call check_heights (height_L, height_R)\n\n  contains\n\n    recursive subroutine get_heights (p, height_L, height_R)\n      type(avl_node_t), pointer, intent(in) :: p\n      integer, intent(out) :: height_L, height_R\n\n      integer :: height_LL, height_LR\n      integer :: height_RL, height_RR\n\n      height_L = 0\n      height_R = 0\n      if (associated (p)) then\n         call get_heights (p%left, height_LL, height_LR)\n         call check_heights (height_LL, height_LR)\n         height_L = height_LL + height_LR\n         call get_heights (p%right, height_RL, height_RR)\n         call check_heights (height_RL, height_RR)\n         height_R = height_RL + height_RR\n      end if\n    end subroutine get_heights\n\n    subroutine check_heights (height_L, height_R)\n      integer, value :: height_L, height_R\n\n      if (2 <= abs (height_L - height_R)) then\n         write (error_unit, '(\"*** AVL condition violated ***\")')\n         error stop\n      end if\n    end subroutine check_heights\n\n  end subroutine avl_check\n\nend module avl_trees\n\nprogram avl_trees_demo\n  use, intrinsic :: iso_fortran_env, only: output_unit\n  use, non_intrinsic :: avl_trees\n\n  implicit none\n\n  integer, parameter :: keys_count = 20\n\n  type(avl_tree_t) :: tree\n  logical :: found\n  class(*), allocatable :: retval\n  integer :: the_keys(1:keys_count)\n  integer :: i, j\n\n  do i = 1, keys_count\n     the_keys(i) = i\n  end do\n  call fisher_yates_shuffle (the_keys, keys_count)\n\n  call avl_check (tree)\n  do i = 1, keys_count\n     call avl_insert (lt, the_keys(i), real (the_keys(i)), tree)\n     call avl_check (tree)\n     if (avl_size (tree) \/= i) error stop\n     do j = 1, keys_count\n        if (avl_contains (lt, the_keys(j), tree) .neqv. (j <= i)) error stop\n     end do\n     do j = 1, keys_count\n        call avl_retrieve (lt, the_keys(j), tree, found, retval)\n        if (found .neqv. (j <= i)) error stop\n        if (found) then\n           ! This crazy way to write \u2018\/=\u2019 is to quell those tiresome\n           ! warnings about using \u2018==\u2019 or \u2018\/=\u2019 with floating point\n           ! numbers. Floating point numbers can represent integers\n           ! *exactly*.\n           if (0 < abs (real_cast (retval) - real (the_keys(j)))) error stop\n        end if\n        if (found) then\n           block\n             character(len = 1), parameter :: ch = '*'\n             !\n             ! Try replacing the data with a character and then\n             ! restoring the number.\n             !\n             call avl_insert (lt, the_keys(j), ch, tree)\n             call avl_retrieve (lt, the_keys(j), tree, found, retval)\n             if (.not. found) error stop\n             if (char_cast (retval) \/= ch) error stop\n             call avl_insert (lt, the_keys(j), real (the_keys(j)), tree)\n             call avl_retrieve (lt, the_keys(j), tree, found, retval)\n             if (.not. found) error stop\n             if (0 < abs (real_cast (retval) - real (the_keys(j)))) error stop\n           end block\n        end if\n     end do\n  end do\n\n  write (output_unit, '(70(\"-\"))')\n  call avl_write (int_real_writer, output_unit, tree)\n  write (output_unit, '(70(\"-\"))')\n  call print_contents (output_unit, tree)\n  write (output_unit, '(70(\"-\"))')\n\n  call fisher_yates_shuffle (the_keys, keys_count)\n  do i = 1, keys_count\n     call avl_delete (lt, the_keys(i), tree)\n     call avl_check (tree)\n     if (avl_size (tree) \/= keys_count - i) error stop\n     ! Try deleting a second time.\n     call avl_delete (lt, the_keys(i), tree)\n     call avl_check (tree)\n     if (avl_size (tree) \/= keys_count - i) error stop\n     do j = 1, keys_count\n        if (avl_contains (lt, the_keys(j), tree) .neqv. (i < j)) error stop\n     end do\n     do j = 1, keys_count\n        call avl_retrieve (lt, the_keys(j), tree, found, retval)\n        if (found .neqv. (i < j)) error stop\n        if (found) then\n           if (0 < abs (real_cast (retval) - real (the_keys(j)))) error stop\n        end if\n     end do\n  end do\n\ncontains\n\n  subroutine fisher_yates_shuffle (keys, n)\n    integer, intent(inout) :: keys(*)\n    integer, intent(in) :: n\n\n    integer :: i, j\n    real :: randnum\n    integer :: tmp\n\n    do i = 1, n - 1\n       call random_number (randnum)\n       j = i + floor (randnum * (n - i + 1))\n       tmp = keys(i)\n       keys(i) = keys(j)\n       keys(j) = tmp\n    end do\n  end subroutine fisher_yates_shuffle\n\n  function int_cast (u) result (v)\n    class(*), intent(in) :: u\n    integer :: v\n\n    select type (u)\n    type is (integer)\n       v = u\n    class default\n       ! This case is not handled.\n       error stop\n    end select\n  end function int_cast\n\n  function real_cast (u) result (v)\n    class(*), intent(in) :: u\n    real :: v\n\n    select type (u)\n    type is (real)\n       v = u\n    class default\n       ! This case is not handled.\n       error stop\n    end select\n  end function real_cast\n\n  function char_cast (u) result (v)\n    class(*), intent(in) :: u\n    character(len = 1) :: v\n\n    select type (u)\n    type is (character(*))\n       v = u\n    class default\n       ! This case is not handled.\n       error stop\n    end select\n  end function char_cast\n\n  function lt (u, v) result (u_lt_v)\n    class(*), intent(in) :: u, v\n    logical :: u_lt_v\n\n    select type (u)\n    type is (integer)\n       select type (v)\n       type is (integer)\n          u_lt_v = (u < v)\n       class default\n          ! This case is not handled.\n          error stop\n       end select\n    class default\n       ! This case is not handled.\n       error stop\n    end select\n  end function lt\n\n  subroutine int_real_writer (unit, key, data)\n    integer, intent(in) :: unit\n    class(*), intent(in) :: key, data\n\n    write (unit, '(\"(\", I0, \", \", F0.1, \")\")', advance = 'no') &\n         & int_cast(key), real_cast(data)\n  end subroutine int_real_writer\n\n  subroutine print_contents (unit, tree)\n    integer, intent(in) :: unit\n    class(avl_tree_t), intent(in) :: tree\n\n    type(avl_pointer_pair_t), pointer :: ppairs, pp\n\n    write (unit, '(\"tree size = \", I0)') avl_size (tree)\n    ppairs => avl_pointer_pairs (tree)\n    pp => ppairs\n    do while (associated (pp))\n       write (unit, '(\"(\", I0, \", \", F0.1, \")\")') &\n            & int_cast (pp%p_key), real_cast (pp%p_data)\n       pp => pp%next\n    end do\n    if (associated (ppairs)) deallocate (ppairs)\n  end subroutine print_contents\n\nend program avl_trees_demo\n\n\n","human_summarization":"Implement an AVL tree with operations such as lookup, insertion, and deletion which all take O(log n) time. The tree ensures that the heights of two child subtrees of any node differ by at most one. The implementation also includes checking the AVL condition, printing the tree representation, outputting the full contents as an ordered linked list, and computing the tree size by traversal. The keys and data can be of any type. Duplicate node keys are not allowed. The operations are written using some more general mechanisms.","id":930}
    {"lang_cluster":"Fortran","source_code":"\n! Implemented by Anant Dixit (Nov. 2014)\n! Transpose elements in find_center to obtain correct results. R.N. McLean (Dec 2017)\nprogram circles\nimplicit none\ndouble precision :: P1(2), P2(2), R\n\nP1 = (\/0.1234d0, 0.9876d0\/)\nP2 = (\/0.8765d0,0.2345d0\/)\nR = 2.0d0\ncall print_centers(P1,P2,R)\n\nP1 = (\/0.0d0, 2.0d0\/)\nP2 = (\/0.0d0,0.0d0\/)\nR = 1.0d0\ncall print_centers(P1,P2,R)\n\nP1 = (\/0.1234d0, 0.9876d0\/)\nP2 = (\/0.1234d0, 0.9876d0\/)\nR = 2.0d0\ncall print_centers(P1,P2,R)\n\nP1 = (\/0.1234d0, 0.9876d0\/)\nP2 = (\/0.8765d0, 0.2345d0\/)\nR = 0.5d0\ncall print_centers(P1,P2,R)\n\nP1 = (\/0.1234d0, 0.9876d0\/)\nP2 = (\/0.1234d0, 0.9876d0\/)\nR = 0.0d0\ncall print_centers(P1,P2,R)\nend program circles\n\nsubroutine print_centers(P1,P2,R)\nimplicit none\ndouble precision :: P1(2), P2(2), R, Center(2,2)\ninteger :: Res\ncall test_inputs(P1,P2,R,Res)\nwrite(*,*)\nwrite(*,'(A10,F7.4,A1,F7.4)') 'Point1 \u00a0: ', P1(1), ' ', P1(2)\nwrite(*,'(A10,F7.4,A1,F7.4)') 'Point2 \u00a0: ', P2(1), ' ', P2(2)\nwrite(*,'(A10,F7.4)') 'Radius \u00a0: ', R\nif(Res.eq.1) then\n  write(*,*) 'Same point because P1=P2 and r=0.'\nelseif(Res.eq.2) then\n  write(*,*) 'No circles can be drawn because r=0.'\nelseif(Res.eq.3) then\n  write(*,*) 'Infinite circles because P1=P2 for non-zero radius.'\nelseif(Res.eq.4) then\n  write(*,*) 'No circles with given r can be drawn because points are far apart.'\nelseif(Res.eq.0) then\n  call find_center(P1,P2,R,Center)\n  if(Center(1,1).eq.Center(2,1) .and. Center(1,2).eq.Center(2,2)) then\n    write(*,*) 'Points lie on the diameter. A single circle can be drawn.'\n    write(*,'(A10,F7.4,A1,F7.4)') 'Center \u00a0: ', Center(1,1), ' ', Center(1,2)\n  else\n    write(*,*) 'Two distinct circles found.'\n    write(*,'(A10,F7.4,A1,F7.4)') 'Center1\u00a0: ', Center(1,1), ' ', Center(1,2)\n    write(*,'(A10,F7.4,A1,F7.4)') 'Center2\u00a0: ', Center(2,1), ' ', Center(2,2)\n  end if\nelseif(Res.lt.0) then\n  write(*,*) 'Incorrect value for r.'\nend if\nwrite(*,*)\nend subroutine print_centers\n\nsubroutine test_inputs(P1,P2,R,Res)\nimplicit none\ndouble precision :: P1(2), P2(2), R, dist\ninteger :: Res\nif(R.lt.0.0d0) then\n  Res = -1\n  return\nelseif(R.eq.0.0d0 .and. P1(1).eq.P2(1) .and. P1(2).eq.P2(2)) then\n  Res = 1\n  return\nelseif(R.eq.0.0d0) then\n  Res = 2\n  return\nelseif(P1(1).eq.P2(1) .and. P1(2).eq.P2(2)) then\n  Res = 3\n  return\nelse\n  dist = sqrt( (P1(1)-P2(1))**2 + (P1(2)-P2(2))**2 )\n  if(dist.gt.2.0d0*R) then\n    Res = 4\n    return\n  else\n    Res = 0\n    return\n  end if\nend if\nend subroutine test_inputs\n\nsubroutine find_center(P1,P2,R,Center)\nimplicit none\ndouble precision :: P1(2), P2(2), MP(2), Center(2,2), R, dm, dd\nMP = (P1 + P2)\/2.0d0\ndm = sqrt((P1(1) - P2(1))**2 + (P1(2) - P2(2))**2)\ndd = sqrt(R**2 - (dm\/2.0d0)**2)\nCenter(1,1) = MP(1) - dd*(P2(2) - P1(2))\/dm\nCenter(1,2) = MP(2) + dd*(P2(1) - P1(1))\/dm\n\nCenter(2,1) = MP(1) + dd*(P2(2) - P1(2))\/dm\nCenter(2,2) = MP(2) - dd*(P2(1) - P1(1))\/dm\nend subroutine find_center\n\n\n","human_summarization":"The code defines a function that takes two points and a radius as input and returns two circles that pass through these points. The function handles special cases such as when the radius is zero, the points are coincident, form a diameter, or are too far apart. It also provides output for specific input values. The code also includes a module for handling error messages and uses complex number arithmetic. The output format is free-format, displaying complex numbers in brackets.","id":931}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram Example\n  implicit none\n\n  real :: r\n  integer :: a, b\n\n  do\n     call random_number(r)\n     a = int(r * 20)\n     write(*,*) a\n     if (a == 10) exit\n     call random_number(r)\n     b = int(r * 20)\n     write(*,*) b\n  end do\n\nend program Example\n\nWorks with: Fortran version 77 and later\n      PROGRAM LOOPBREAK\n        INTEGER I, RNDINT\n\nC       It doesn't matter what number you put here.\n        CALL SDRAND(123)\n\nC       Because FORTRAN 77 semantically lacks many loop structures, we\nC       have to use GOTO statements to do the same thing.\n   10   CONTINUE\nC         Print a random number.\n          I = RNDINT(0, 19)\n          WRITE (*,*) I\n\nC         If the random number is ten, break (i.e. skip to after the end\nC         of the \"loop\").\n          IF (I .EQ. 10) GOTO 20\n\nC         Otherwise, print a second random number.\n          I = RNDINT(0, 19)\n          WRITE (*,*) I\n\nC         This is the end of our \"loop,\" meaning we jump back to the\nC         beginning again.\n          GOTO 10\n\n   20   CONTINUE\n\n        STOP\n      END\n\nC FORTRAN 77 does not come with a random number generator, but it\nC is easy enough to type \"fortran 77 random number generator\" into your\nC preferred search engine and to copy and paste what you find. The\nC following code is a slightly-modified version of:\nC\nC     http:\/\/www.tat.physik.uni-tuebingen.de\/\nC         ~kley\/lehre\/ftn77\/tutorial\/subprograms.html\n      SUBROUTINE SDRAND (IRSEED)\n        COMMON  \/SEED\/ UTSEED, IRFRST\n        UTSEED = IRSEED\n        IRFRST = 0\n        RETURN\n      END\n      INTEGER FUNCTION RNDINT (IFROM, ITO)\n        INTEGER IFROM, ITO\n        PARAMETER (MPLIER=16807, MODLUS=2147483647,                     &\n     &              MOBYMP=127773, MOMDMP=2836)\n        COMMON  \/SEED\/ UTSEED, IRFRST\n        INTEGER HVLUE, LVLUE, TESTV, NEXTN\n        SAVE    NEXTN\n        IF (IRFRST .EQ. 0) THEN\n          NEXTN = UTSEED\n          IRFRST = 1\n        ENDIF\n        HVLUE = NEXTN \/ MOBYMP\n        LVLUE = MOD(NEXTN, MOBYMP)\n        TESTV = MPLIER*LVLUE - MOMDMP*HVLUE\n        IF (TESTV .GT. 0) THEN\n          NEXTN = TESTV\n        ELSE\n          NEXTN = TESTV + MODLUS\n        ENDIF\n        IF (NEXTN .GE. 0) THEN\n          RNDINT = MOD(MOD(NEXTN, MODLUS), ITO - IFROM + 1) + IFROM\n        ELSE\n          RNDINT = MOD(MOD(NEXTN, MODLUS), ITO - IFROM + 1) + ITO + 1\n        ENDIF\n        RETURN\n      END\n\nWorks with: Fortran version 66 and earlier\n\n      SUBROUTINE RANDU(IX,IY,YFL)\nCopied from the IBM1130 Scientific Subroutines Package (1130-CM-02X): Programmer's Manual, page 60.\nCAUTION! This routine's 32-bit variant is reviled by Prof. Knuth and many others for good reason!\n        IY = IX*899\n        IF (IY) 5,6,6\n    5   IY = IY + 32767 + 1\n    6   YFL = IY\n        YFL = YFL\/32767.\n      END\n\n      FUNCTION IR19(IX)\n        CALL RANDU(IX,IY,YFL)\n        IX = IY\n        I = YFL*20\n        IF (I - 20) 12,11,11\n   11   I = 19\n   12   IR19 = I\n      END\n\n      IX = 1\nCommence the loop.\n   10 I = IR19(IX)\n      WRITE (6,11) I\n   11 FORMAT (I3)\n      IF (I - 10) 12,20,12\n   12 I = IR19(IX)\n      WRITE (6,11) I\n      GO TO 10\nCease.\n   20 CONTINUE\n      END\n\n\n 0 13  4 19  1  7  2 12  4  7 14 11  6  4  0  9  5 12 16 19 18  2  0 13  2  7 10\n\n\n","human_summarization":"The code generates and prints random numbers between 0 and 19 in a loop. If the first generated number in a loop is 10, the loop stops. If not, a second random number is generated and printed before the loop restarts. If 10 is never the first number generated, the loop continues indefinitely. The random number generation is done using the RANDU generator, in the style of Fortran 66. The code ensures that all numbers have an equal chance of being generated, with special handling for the edge case of 19.","id":932}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nPROGRAM EXAMPLE\n  IMPLICIT NONE\n  INTEGER :: exponent, factor\n\n  WRITE(*,*) \"Enter exponent of Mersenne number\"\n  READ(*,*) exponent\n  factor = Mfactor(exponent)\n  IF (factor == 0) THEN\n    WRITE(*,*) \"No Factor found\"\n  ELSE\n    WRITE(*,\"(A,I0,A,I0)\") \"M\", exponent, \" has a factor: \", factor\n  END IF\n\nCONTAINS\n\nFUNCTION isPrime(number)\n!   code omitted - see [[Primality by Trial Division]]\nEND FUNCTION\n\nFUNCTION  Mfactor(p)\n  INTEGER :: Mfactor\n  INTEGER, INTENT(IN) :: p\n  INTEGER :: i, k,  maxk, msb, n, q\n\n  DO i = 30, 0 , -1\n    IF(BTEST(p, i)) THEN\n      msb = i\n      EXIT\n    END IF\n  END DO\n \n  maxk = 16384  \/ p     ! limit for k to prevent overflow of 32 bit signed integer\n  DO k = 1, maxk\n    q = 2*p*k + 1\n    IF (.NOT. isPrime(q)) CYCLE\n    IF (MOD(q, 8) \/= 1 .AND. MOD(q, 8) \/= 7) CYCLE\n    n = 1\n    DO i = msb, 0, -1\n      IF (BTEST(p, i)) THEN\n        n = MOD(n*n*2, q)\n      ELSE\n        n = MOD(n*n, q)\n      ENDIF\n    END DO\n    IF (n == 1) THEN\n      Mfactor = q\n      RETURN\n    END IF\n  END DO\n  Mfactor = 0\nEND FUNCTION\nEND PROGRAM EXAMPLE\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":933}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n\nPROGRAM YULETIDE\n \nIMPLICIT NONE\n  \nINTEGER :: day, year\n \nWRITE(*, \"(A)\", ADVANCE=\"NO\") \"25th of December is a Sunday in\"\nDO year = 2008, 2121\n   day = Day_of_week(25, 12, year)\n   IF (day == 1) WRITE(*, \"(I5)\", ADVANCE=\"NO\") year\nEND DO\n  \nCONTAINS\n \nFUNCTION Day_of_week(d, m, y)\n   INTEGER :: Day_of_week, j, k, mm, yy\n   INTEGER, INTENT(IN) :: d, m, y\n  \n   mm=m\n   yy=y\n   IF(mm.le.2) THEN\n      mm=mm+12\n      yy=yy-1\n   END IF\n   j = yy \/ 100\n   k = MOD(yy, 100)\n   Day_of_week = MOD(d + ((mm+1)*26)\/10 + k + k\/4 + j\/4 + 5*j, 7)\nEND FUNCTION Day_of_week\n  \nEND PROGRAM YULETIDE\n\n\n","human_summarization":"\"Determines the years between 2008 and 2121 when Christmas falls on a Sunday using standard date handling libraries, and compares the results across different programming languages to identify any discrepancies due to issues like overflow in date\/time representation.\"","id":934}
    {"lang_cluster":"Fortran","source_code":"\nLibrary: LAPACK\n\nprogram qrtask\n    implicit none\n    integer, parameter :: n = 4\n    real(8) :: durer(n, n) = reshape(dble([ &\n        16,  5,  9,  4, &\n         3, 10,  6, 15, &\n         2, 11,  7, 14, &\n        13,  8, 12,  1  &\n    ]), [n, n])\n    real(8) :: q(n, n), r(n, n), qr(n, n), id(n, n), tau(n)\n    integer, parameter :: lwork = 1024\n    real(8) :: work(lwork)\n    integer :: info, i, j\n \n    q = durer\n    call dgeqrf(n, n, q, n, tau, work, lwork, info)\n \n    r = 0d0\n    forall (i = 1:n, j = 1:n, j >= i) r(i, j) = q(i, j)\n \n    call dorgqr(n, n, n, q, n, tau, work, lwork, info)\n \n    qr = matmul(q, r)\n    id = matmul(q, transpose(q))\n \n    call show(4, durer, \"A\")\n    call show(4, q, \"Q\")\n    call show(4, r, \"R\")\n    call show(4, qr, \"Q*R\")\n    call show(4, id, \"Q*Q'\")\ncontains\n    subroutine show(n, a, s)\n        character(*) :: s\n        integer :: n, i\n        real(8) :: a(n, n)\n \n        print *, s\n        do i = 1, n\n            print 1, a(i, :)\n          1 format (*(f12.6,:,' '))\n        end do\n    end subroutine\nend program\n\n\n","human_summarization":"\"Implement QR decomposition using Householder reflections on a given matrix. The code also includes the application of QR decomposition for solving linear least squares problems. The code handles cases where the matrix is not square by removing zero padded bottom rows. The solution is obtained by back substitution.\"","id":935}
    {"lang_cluster":"Fortran","source_code":"\n\nprogram remove_dups\n  implicit none\n  integer :: example(12)         ! The input\n  integer :: res(size(example))  ! The output\n  integer :: k                   ! The number of unique elements\n  integer :: i, j\n\n  example = [1, 2, 3, 2, 2, 4, 5, 5, 4, 6, 6, 5]\n  k = 1\n  res(1) = example(1)\n  outer: do i=2,size(example)\n     do j=1,k\n        if (res(j) == example(i)) then\n           ! Found a match so start looking again\n           cycle outer\n        end if\n     end do\n     ! No match found so add it to the output\n     k = k + 1\n     res(k) = example(i)\n  end do outer\n  write(*,advance='no',fmt='(a,i0,a)') 'Unique list has ',k,' elements: '\n  write(*,*) res(1:k)\nend program remove_dups\n\n\nprogram remove_dups\n    implicit none\n    integer :: example(12)         ! The input\n    integer :: res(size(example))  ! The output\n    integer :: k                   ! The number of unique elements\n    integer :: i\n\n    example = [1, 2, 3, 2, 2, 4, 5, 5, 4, 6, 6, 5]\n    k = 1\n    res(1) = example(1)\n    do i=2,size(example)\n        ! if the number already exist in res check next\n        if (any( res == example(i) )) cycle\n        ! No match found so add it to the output\n        k = k + 1\n        res(k) = example(i)\n    end do\n\n    write(*,advance='no',fmt='(a,i0,a)') 'Unique list has ',k,' elements: '\n    write(*,*) res(1:k)\nend program remove_dups\n\n\n","human_summarization":"implement a method to remove duplicate elements from an array in Fortran. This is achieved by comparing all elements in the array. If a duplicate is found, it is discarded. The code also uses the 'ANY' function to check if an input number already exists in the array of unique elements.","id":936}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n\nIf the largest element is in the last slot, the call to QSort(A(marker:),nA-marker+1) goes beyond the end of the array. This can cause exceptions and bad results.\nThe use of a random number causes non reproducible performance.\n\nMODULE qsort_mod\n\n  IMPLICIT NONE\n\n  TYPE group\n     INTEGER :: order    ! original order of unsorted data\n     REAL    :: VALUE    ! values to be sorted by\n  END TYPE group\n\nCONTAINS\n\n  RECURSIVE SUBROUTINE QSort(a,na)\n\n    ! DUMMY ARGUMENTS\n    INTEGER, INTENT(in) :: nA\n    TYPE (group), DIMENSION(nA), INTENT(in out) :: A\n\n    ! LOCAL VARIABLES\n    INTEGER :: left, right\n    REAL :: random\n    REAL :: pivot\n    TYPE (group) :: temp\n    INTEGER :: marker\n\n    IF (nA > 1) THEN\n\n       CALL random_NUMBER(random)\n       pivot = A(INT(random*REAL(nA-1))+1)%VALUE   ! Choice a random pivot (not best performance, but avoids worst-case)\n       left = 1\n       right = nA\n       ! Partition loop\n       DO\n          IF (left >= right) EXIT\n          DO\n             IF (A(right)%VALUE <= pivot) EXIT\n             right = right - 1\n          END DO\n          DO\n             IF (A(left)%VALUE >= pivot) EXIT\n             left = left + 1\n          END DO\n          IF (left < right) THEN\n             temp = A(left)\n             A(left) = A(right)\n             A(right) = temp\n          END IF\n       END DO\n\n       IF (left == right) THEN\n          marker = left + 1\n       ELSE\n          marker = left\n       END IF\n\n       CALL QSort(A(:marker-1),marker-1)\n       CALL QSort(A(marker:),nA-marker+1)  WARNING CAN GO BEYOND END OF ARRAY DO NOT USE THIS IMPLEMENTATION\n\n    END IF\n\n  END SUBROUTINE QSort\n\nEND MODULE qsort_mod\n     \n! Test Qsort Module\nPROGRAM qsort_test\n  USE qsort_mod\n  IMPLICIT NONE\n\n  INTEGER, PARAMETER :: nl = 10, nc = 5, l = nc*nl, ns=33\n  TYPE (group), DIMENSION(l) :: A\n  INTEGER, DIMENSION(ns) :: seed\n  INTEGER :: i\n  REAL :: random\n  CHARACTER(LEN=80) :: fmt1, fmt2\n  ! Using the Fibonacci sequence to initialize seed:\n  seed(1) = 1 ; seed(2) = 1\n  DO i = 3,ns\n     seed(i) = seed(i-1)+seed(i-2)\n  END DO\n  ! Formats of the outputs\n  WRITE(fmt1,'(A,I2,A)') '(', nc, '(I5,2X,F6.2))'\n  WRITE(fmt2,'(A,I2,A)') '(3x', nc, '(\"Ord.  Num.\",3x))' \n  PRINT *, \"Unsorted Values:\"\n  PRINT fmt2,\n  CALL random_SEED(put = seed)\n  DO i = 1, l\n     CALL random_NUMBER(random)\n     A(i)%VALUE = NINT(1000*random)\/10.0\n     A(i)%order = i\n     IF (MOD(i,nc) == 0) WRITE (*,fmt1) A(i-nc+1:i)\n  END DO\n  PRINT *\n  CALL QSort(A,l)\n  PRINT *, \"Sorted Values:\"\n  PRINT fmt2,\n  DO i = nc, l, nc\n     IF (MOD(i,nc) == 0) WRITE (*,fmt1) A(i-nc+1:i)\n  END DO\n  STOP\nEND PROGRAM qsort_test\n\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by selecting a pivot element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then recursively sorted. The algorithm also includes an optimized version that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified and can vary. The implementation also discusses the comparison of Quicksort with merge sort and its performance. Note: The Fortran implementation of Quicksort is flawed and an alternative is suggested.","id":937}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 95 and later\n\nPROGRAM DATE\n\n  IMPLICIT NONE\n  \n  INTEGER :: dateinfo(8), day\n  CHARACTER(9) :: month, dayname\n     \n  CALL DATE_AND_TIME(VALUES=dateinfo)\n  SELECT CASE(dateinfo(2))\n    CASE(1)\n      month = \"January\"\n    CASE(2)\n      month = \"February\"\n    CASE(3)\n      month = \"March\"\n    CASE(4)\n      month = \"April\"\n    CASE(5)\n      month = \"May\"\n    CASE(6)\n      month = \"June\"\n    CASE(7)\n      month = \"July\"\n    CASE(8)\n      month = \"August\"\n    CASE(9)\n      month = \"September\"\n    CASE(10)\n      month = \"October\"\n    CASE(11)\n      month = \"November\"\n    CASE(12)\n     month = \"December\"\n  END SELECT\n\n  day = Day_of_week(dateinfo(3), dateinfo(2), dateinfo(1))\n\n  SELECT CASE(day)\n    CASE(0)\n      dayname = \"Saturday\"\n    CASE(1)\n      dayname = \"Sunday\"\n    CASE(2)\n      dayname = \"Monday\"\n    CASE(3)\n      dayname = \"Tuesday\"\n    CASE(4)\n      dayname = \"Wednesday\"\n    CASE(5)\n      dayname = \"Thursday\"\n    CASE(6)\n      dayname = \"Friday\"\n  END SELECT\n  \n  WRITE(*,\"(I0,A,I0,A,I0)\") dateinfo(1),\"-\", dateinfo(2),\"-\", dateinfo(3)\n  WRITE(*,\"(4(A),I0,A,I0)\") trim(dayname), \", \", trim(month), \" \", dateinfo(3), \", \", dateinfo(1)\n\nCONTAINS\n\n  FUNCTION Day_of_week(d, m, y)\n    INTEGER :: Day_of_week, j, k\n    INTEGER, INTENT(IN) :: d, m, y\n    \n    j = y \/ 100\n    k = MOD(y, 100)\n    Day_of_week = MOD(d + (m+1)*26\/10 + k + k\/4 + j\/4 + 5*j, 7)\n  END FUNCTION Day_of_week\n\nEND PROGRAM DATE\n\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\". It includes a custom function to determine the day of the week as the DATE_AND_TIME subroutine does not provide this information.","id":938}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram roman_numerals\n\n  implicit none\n\n  write (*, '(a)') roman (2009)\n  write (*, '(a)') roman (1666)\n  write (*, '(a)') roman (3888)\n\ncontains\n\nfunction roman (n) result (r)\n\n  implicit none\n  integer, intent (in) :: n\n  integer, parameter   :: d_max = 13\n  integer              :: d\n  integer              :: m\n  integer              :: m_div\n  character (32)       :: r\n  integer,        dimension (d_max), parameter :: d_dec = &\n    & (\/1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1\/)\n  character (32), dimension (d_max), parameter :: d_rom = &\n    & (\/'M ', 'CM', 'D ', 'CD', 'C ', 'XC', 'L ', 'XL', 'X ', 'IX', 'V ', 'IV', 'I '\/)\n\n  r = ''\n  m = n\n  do d = 1, d_max\n    m_div = m \/ d_dec (d)\n    r = trim (r) \/\/ repeat (trim (d_rom (d)), m_div)\n    m = m - d_dec (d) * m_div\n  end do\n\nend function roman\n\nend program roman_numerals\n\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":939}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n\ninteger a (10)\ninteger\u00a0:: a (10)\ninteger, dimension (10)\u00a0:: a\n\ninteger, dimension (10)\u00a0:: a\ninteger, dimension (1\u00a0: 10)\u00a0:: a\n\ninteger, dimension (0\u00a0: 9)\u00a0:: a\n\nreal, dimension (10)\u00a0:: a\ntype (my_type), dimension (10)\u00a0:: a\n\ninteger, dimension (10, 10)\u00a0:: a\ninteger, dimension (10, 10, 10)\u00a0:: a\n\ninteger, dimension (:), allocatable\u00a0:: a\ninteger, dimension (:,\u00a0:), allocatable\u00a0:: a\n\nallocate (a (10))\nallocate (a (10, 10))\n\ndeallocate (a)\n\ninteger, dimension (10)\u00a0:: a = (\/1, 2, 3, 4, 5, 6, 7, 8, 9, 10\/)\ninteger\u00a0:: i\ninteger, dimension (10)\u00a0:: a = (\/(i * i, i = 1, 10)\/)\ninteger, dimension (10)\u00a0:: a = 0\ninteger\u00a0:: i\ninteger, dimension (10, 10)\u00a0:: a = reshape ((\/(i * i, i = 1, 100)\/), (\/10, 10\/))\n\ninteger\u00a0:: i\ninteger, dimension (10), parameter\u00a0:: a = (\/(i * i, i = 1, 10)\/)\n\na (1) = 1\na (1, 1) = 1\n\na = (\/1, 2, 3, 4, 5, 6, 7, 8, 9, 10\/)\na = (\/(i * i, i = 1, 10)\/)\na = reshape ((\/(i * i, i = 1, 100)\/), (\/10, 10\/))\na = 0\n\na (:) = (\/1, 2, 3, 4, 5, 6, 7, 8, 9, 10\/)\na (1\u00a0: 5) = (\/1, 2, 3, 4, 5\/)\na (: 5) = (\/1, 2, 3, 4, 5\/)\na (6\u00a0:) = (\/1, 2, 3, 4, 5\/)\na (1\u00a0: 5) = (\/(i * i, i = 1, 10)\/)\na (1\u00a0: 5)= 0\na (1,\u00a0:)= (\/(i * i, i = 1, 10)\/)\na (1\u00a0: 5, 1)= (\/(i * i, i = 1, 5)\/)\n\ni = a (1)\n\na = b (1\u00a0: 10)\n\ni = size (a)\n\ni = size (a, 1)\n\ni_min = lbound (a)\ni_max = ubound (a)\n\na = ubound (b)\n","human_summarization":"demonstrate the basic syntax of arrays in the given programming language. It includes the creation of both fixed-length and dynamic arrays, assigning values to them, and retrieving an element. The code also showcases pushing a value into the array. It covers the declaration of arrays with different bases and types, including multidimensional and allocatable arrays. The code also illustrates the process of array allocation, deallocation, initialization, and constant array declaration. It further demonstrates element assignment, array assignment, and array section assignment. The retrieval of an element, array section, size, and bounds of an array, including multidimensional arrays, are also included.","id":940}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 2003\n\nprogram FileIO\n\n  integer, parameter :: out = 123, in = 124\n  integer :: err\n  character :: c\n\n  open(out, file=\"output.txt\", status=\"new\", action=\"write\", access=\"stream\", iostat=err)\n  if (err == 0) then\n     open(in, file=\"input.txt\", status=\"old\", action=\"read\", access=\"stream\", iostat=err)\n     if (err == 0) then\n        err = 0\n        do while (err == 0)\n           read(unit=in, iostat=err) c\n           if (err == 0) write(out) c\n        end do\n        close(in)\n     end if\n     close(out)\n  end if\n\nend program FileIO\n\n","human_summarization":"demonstrate how to create a file named \"output.txt\", read the contents from \"input.txt\" into an intermediate variable, and then write these contents into \"output.txt\". It uses the \"stream\" access method as per the Fortran 2003 standard for easy binary data copying.","id":941}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n program example\n  \n   implicit none\n   \n   character(9) :: teststring = \"alphaBETA\"\n  \n   call To_upper(teststring)\n   write(*,*) teststring\n   call To_lower(teststring)\n   write(*,*) teststring\n  \n contains\n \n   subroutine To_upper(str)\n     character(*), intent(in out) :: str\n     integer :: i\n  \n     do i = 1, len(str)\n       select case(str(i:i))\n         case(\"a\":\"z\")\n           str(i:i) = achar(iachar(str(i:i))-32)\n       end select\n     end do \n   end subroutine To_upper\n \n   subroutine To_lower(str)\n     character(*), intent(in out) :: str\n     integer :: i\n  \n     do i = 1, len(str)\n       select case(str(i:i))\n         case(\"A\":\"Z\")\n           str(i:i) = achar(iachar(str(i:i))+32)\n       end select\n     end do  \n   end subroutine To_Lower\n\n end program example\n\n\nFor converting lower-case text to upper, the following will work both on an ASCII system and an EBCDIC system (or any other encodement), once it is compiled for that system:       SUBROUTINE UPCASE(TEXT)\n       CHARACTER*(*) TEXT\n       INTEGER I,C\n        DO I = 1,LEN(TEXT)\n          C = INDEX(\"abcdefghijklmnopqrstuvwxyz\",TEXT(I:I))\n          IF (C.GT.0) TEXT(I:I) = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"(C:C)\n        END DO\n      END\n\nThe INDEX function of course returning zero if the character is not found. Converting from upper to lower case is the obvious inverse and it might be worthwhile defining a MODULE with suitable named character constants to avoid repetition - one might hope the compiler will share duplicated constants rather than producing a fresh version every time, but it might not too. The repeated text scanning done by the INDEX function for each character of TEXT will of course be a lot slower. A still-more advanced compiler might be able to take advantage of special translation op-codes, on systems that offer them. If storage space is not at a premium a swifter method would be to create something like CHARACTER*1 XLATUC(0:255) with most entries being equal to their index, except for those corresponding to the lower case letters for which the value is the corresponding upper case letter. Then       DO I = 1,LEN(TEXT)\n        TEXT(I:I) = XLATUC(ICHAR(TEXT(I:I)))\n      END DO\n\n\nmodule uplow\n   implicit none\n   character(len=26), parameter, private :: low  = \"abcdefghijklmnopqrstuvwxyz\"\n   character(len=26), parameter, private :: high = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\ncontains\n\n   function to_upper(s) result(t)\n      ! returns upper case of s\n      implicit none\n      character(len=*), intent(in) :: s\n      character(len=len(s))        :: t\n\n      character(len=1), save       :: convtable(0:255)\n      logical, save                :: first = .true.\n      integer                      :: i\n\n      if(first) then\n         do i=0,255\n            convtable(i) = char(i)\n         enddo\n         do i=1,len(low)\n            convtable(iachar(low(i:i))) = char(iachar(high(i:i)))\n         enddo\n         first = .false.\n      endif\n\n      t = s\n\n      do i=1,len_trim(s)\n         t(i:i) = convtable(iachar(s(i:i)))\n      enddo\n\n   end function to_upper\n\n   function to_lower(s) result(t)\n      ! returns lower case of s\n      implicit none\n      character(len=*), intent(in) :: s\n      character(len=len(s))        :: t\n\n      character(len=1), save :: convtable(0:255)\n      logical, save          :: first = .true.\n      integer                :: i\n\n      if(first) then\n         do i=0,255\n            convtable(i) = char(i)\n         enddo\n         do i = 1,len(low)\n            convtable(iachar(high(i:i))) = char(iachar(low(i:i)))\n         enddo\n         first = .false.\n      endif\n\n      t = s\n\n      do i=1,len_trim(s)\n         t(i:i) = convtable(iachar(s(i:i)))\n      enddo\n\n   end function to_lower\n\n\nend module uplow\n\n\nprogram doit\n   use uplow\n   character(len=40) :: s\n\n   s = \"abcdxyz ZXYDCBA _!@\"\n   print *,\"original: \",'[',s,']'\n   print *,\"to_upper: \",'[',to_upper(s),']'\n   print *,\"to_lower: \",'[',to_lower(s),']'\n\nend program doit\n\n","human_summarization":"The code takes a string 'alphaBETA' and demonstrates conversion to upper-case and lower-case using default encoding or ASCII. It also showcases additional case conversion functions like swapping case, capitalizing the first letter, etc. The code uses functions or subroutines, and handles different character sets like ASCII and EBCDIC. It also manages different data formats in a file. The code is compatible with both ASCII and EBCDIC systems.","id":942}
    {"lang_cluster":"Fortran","source_code":"\nmodule Points_Module\n  implicit none\n\n  type point\n     real :: x, y\n  end type point\n\n  interface operator (-)\n     module procedure pt_sub\n  end interface\n\n  interface len\n     module procedure pt_len\n  end interface\n\n  public :: point\n  private :: pt_sub, pt_len\n\ncontains\n\n  function pt_sub(a, b) result(c)\n    type(point), intent(in) :: a, b\n    type(point) :: c\n    \n    c = point(a%x - b%x, a%y - b%y)\n  end function pt_sub\n\n  function pt_len(a) result(l)\n    type(point), intent(in) :: a\n    real :: l\n\n    l = sqrt((a%x)**2 + (a%y)**2)\n  end function pt_len\n\nend module Points_Module\n\nmodule qsort_module\n  use Points_Module\n  implicit none\n\ncontains\n\n  recursive subroutine qsort(a, comparator)\n    type(point), intent(inout) :: a(:)\n    interface\n       integer function comparator(aa, bb)\n         use Points_Module\n         type(point), intent(in) :: aa, bb\n       end function comparator\n    end interface\n\n    integer :: split\n\n    if(size(a) > 1) then\n       call partition(a, split, comparator)\n       call qsort(a(:split-1), comparator)\n       call qsort(a(split:), comparator)\n    end if\n\n  end subroutine qsort\n\n  subroutine partition(a, marker, comparator)\n    type(point), intent(inout) :: a(:)\n    integer, intent(out) :: marker\n\n    interface\n       integer function comparator(aa, bb)\n         use Points_Module\n         type(point), intent(in) :: aa, bb\n       end function comparator\n    end interface\n\n    type(point) :: pivot, temp\n    integer :: left, right\n\n    left = 0                       \n    right = size(a) + 1\n    pivot = a(size(a)\/2)\n\n    do while (left < right)\n       right = right - 1\n       do while (comparator(a(right), pivot) > 0)\n          right = right - 1\n       end do\n       left = left + 1\n       do while (comparator(a(left), pivot) < 0)\n          left = left + 1\n       end do\n       if ( left < right ) then\n          temp = a(left)\n          a(left) = a(right)\n          a(right) = temp\n       end if\n    end do\n\n    if (left == right) then\n       marker = left + 1\n    else\n       marker = left\n    end if\n  end subroutine partition\n\nend module qsort_module\n\nmodule Order_By_XY\n  use Points_Module\n  implicit none\ncontains\n  integer function order_by_x(aa, bb)\n    type(point), intent(in) :: aa, bb\n\n    if ( aa%x < bb%x ) then\n       order_by_x = -1\n    elseif (aa%x > bb%x) then\n       order_by_x = 1\n    else\n       order_by_x = 0\n    end if\n  end function order_by_x\n\n  integer function order_by_y(aa, bb)\n    type(point), intent(in) :: aa, bb\n\n    if ( aa%y < bb%y ) then\n       order_by_y = -1\n    elseif (aa%y > bb%y) then\n       order_by_y = 1\n    else\n       order_by_y = 0\n    end if    \n  end function order_by_y\nend module Order_By_XY\n\nmodule ClosestPair\n  use Points_Module\n  use Order_By_XY\n  use qsort_module\n  implicit none\n\n  private :: closest_pair_real\n\ncontains\n\n  function closest_pair_simple(p, pair) result(distance)\n    type(point), dimension(:), intent(in) :: p\n    type(point), dimension(:), intent(out), optional :: pair\n    real :: distance\n\n    type(point), dimension(2) :: cp\n    integer :: i, j\n    real :: d\n\n    if ( size(P) < 2 ) then\n       distance = huge(0.0)\n    else\n       distance = len(p(1) - p(2))\n       cp = (\/ p(1), p(2) \/)\n       do i = 1, size(p) - 1\n          do j = i+1, size(p)\n             d = len(p(i) - p(j))\n             if ( d < distance ) then\n                distance = d\n                cp = (\/ p(i), p(j) \/)\n             end if\n          end do\n       end do\n       if ( present(pair) ) pair = cp\n    end if\n  end function closest_pair_simple\n\n\n  function closest_pair(p, pair) result(distance)\n    type(point), dimension(:), intent(in) :: p\n    type(point), dimension(:), intent(out), optional :: pair\n    real :: distance\n\n    type(point), dimension(2) :: dp\n    type(point), dimension(size(p)) :: xp, yp\n    integer :: i\n\n    xp = p\n    yp = p\n\n    call qsort(xp, order_by_x)\n    call qsort(yp, order_by_y)\n\n    distance = closest_pair_real(xp, yp, dp)\n    if ( present(pair) ) pair = dp\n  end function closest_pair\n\n\n  recursive function closest_pair_real(xp, yp, pair) result(distance)\n    type(point), dimension(:), intent(in) :: xp, yp\n    type(point), dimension(:), intent(out) :: pair\n    real :: distance\n\n    type(point), dimension(2) :: pairl, pairr\n    type(point), dimension(:), allocatable :: ys\n    type(point), dimension(:), allocatable :: pl, yl\n    type(point), dimension(:), allocatable :: pr, yr\n    real :: dl, dr, dmin, xm, d\n    integer :: ns, i, k, j, midx\n\n    if ( size(xp) <= 3 ) then\n       distance = closest_pair_simple(xp, pair)\n    else\n       midx = ceiling(size(xp)\/2.0)\n\n       allocate(ys(size(xp)))\n       allocate(pl(midx), yl(midx))\n       allocate(pr(size(xp)-midx), yr(size(xp)-midx))\n\n       pl = xp(1:midx)\n       pr = xp((midx+1):size(xp))\n\n       xm = xp(midx)%x\n\n       k = 1; j = 1\n       do i = 1, size(yp)\n          if ( yp(i)%x > xm ) then\n             ! guard ring; this is an \"idiosyncrasy\" that should be fixed in a\n             ! smarter way\n             if ( k <= size(yr) ) yr(k) = yp(i)\n             k = k + 1\n          else\n             ! guard ring (see above)\n             if ( j <= size(yl) ) yl(j) = yp(i)\n             j = j + 1\n          end if\n       end do\n\n       dl = closest_pair_real(pl, yl, pairl)\n       dr = closest_pair_real(pr, yr, pairr)\n\n       pair = pairr\n       dmin = dr\n       if ( dl < dr ) then\n          pair = pairl\n          dmin = dl\n       end if\n\n       ns = 0\n       do i = 1, size(yp)\n          if ( abs(yp(i)%x - xm) < dmin ) then\n             ns = ns + 1\n             ys(ns) = yp(i)\n          end if\n       end do\n\n       distance = dmin\n       do i = 1, ns-1\n          k = i + 1\n          do while ( k <= ns .and. abs(ys(k)%y - ys(i)%y) < dmin )\n             d = len(ys(k) - ys(i))\n             if ( d < distance ) then\n                distance = d\n                pair = (\/ ys(k), ys(i) \/)\n             end if\n             k = k + 1\n          end do\n       end do\n       deallocate(ys)\n       deallocate(pl, yl)\n       deallocate(pr, yr)\n    end if\n  end function closest_pair_real\n\nend module ClosestPair\n","human_summarization":"The code provides two functions to solve the Closest Pair of Points problem in a two-dimensional plane. The first function uses a brute-force algorithm with a time complexity of O(n^2) to find the closest pair of points among a given set. The second function uses a recursive divide and conquer approach with a time complexity of O(n log n) to achieve the same task. It sorts the points by x and y coordinates and recursively finds the closest pairs in the divided sets. It also checks for closer pairs across the divided sets.","id":943}
    {"lang_cluster":"Fortran","source_code":"\nThe only facility for a collection more organised than a collection of separately-named variables (even if with a system for the names) is the array, which is a collection of items of identical type, indexed by an integer only, definitely not by a text as in say Snobol. Thus  REAL A(36)   !Declares a one-dimensional array A(1), A(2), ... A(36)\n  A(1) = 1           !Assigns a value to the first element.\n  A(2) = 3*A(1) + 5  !The second element gets 8.\n\nWith F90 came a large expansion in the facilities for manipulating arrays. They can now have any lower bound, as in REAL A(-6:+12) and their size can be defined at run time, not just compile time. Further, programmer-defined data aggregates can be defined via the TYPE statement, and arrays of such types can be manipulated. However, type-matching remains rigid: all elements of an array must be of the same type. So,  TYPE(MIXED)           !Name the \"type\".\n  INTEGER COUNTER        !Its content is listed.\n  REAL WEIGHT,DEPTH\n  CHARACTER*28 MARKNAME\n  COMPLEX PATH(6)        !The mixed collection includes an array.\n END TYPE MIXED\n TYPE(MIXED) TEMP,A(6) !Declare some items of that type.\n\n\n\n","human_summarization":"The code creates a collection of values, adds a few items to it, and allows for the manipulation of these values. It uses the concept of collections to represent sets of values, with specific focus on statically-typed languages where values are of a common data type. It also demonstrates the usage of complex formulae and the co-array concept for parallel execution. Additionally, it showcases the flexibility of the CHARACTER type to represent different types as texts.","id":944}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n\nPROGRAM KNAPSACK\n\n  IMPLICIT NONE\n \n  REAL :: totalWeight, totalVolume\n  INTEGER :: maxPanacea, maxIchor, maxGold, maxValue = 0\n  INTEGER :: i, j, k\n  INTEGER :: n(3)  \n\n  TYPE Bounty\n    INTEGER :: value\n    REAL :: weight\n    REAL :: volume\n  END TYPE Bounty\n\n  TYPE(Bounty) :: panacea, ichor, gold, sack, current\n\n  panacea = Bounty(3000, 0.3, 0.025)\n  ichor   = Bounty(1800, 0.2, 0.015)\n  gold    = Bounty(2500, 2.0, 0.002)\n  sack    = Bounty(0, 25.0, 0.25)\n\n  maxPanacea = MIN(sack%weight \/ panacea%weight, sack%volume \/ panacea%volume)\n  maxIchor = MIN(sack%weight \/ ichor%weight, sack%volume \/ ichor%volume)\n  maxGold = MIN(sack%weight \/ gold%weight, sack%volume \/ gold%volume)\n  \n  DO i = 0, maxPanacea\n     DO j = 0, maxIchor\n        Do k = 0, maxGold\n           current%value = k * gold%value + j * ichor%value + i * panacea%value\n           current%weight = k * gold%weight + j * ichor%weight + i * panacea%weight\n           current%volume = k * gold%volume + j * ichor%volume + i * panacea%volume       \n           IF (current%weight > sack%weight .OR. current%volume > sack%volume) CYCLE\n           IF (current%value > maxValue) THEN\n              maxValue = current%value\n              totalWeight = current%weight\n              totalVolume = current%volume\n              n(1) = i ; n(2) = j ; n(3) = k\n           END IF\n        END DO  \n     END DO\n  END DO\n\n  WRITE(*, \"(A,I0)\") \"Maximum value achievable is \", maxValue\n  WRITE(*, \"(3(A,I0),A)\") \"This is achieved by carrying \", n(1), \" panacea, \", n(2), \" ichor and \", n(3), \" gold items\"\n  WRITE(*, \"(A,F4.1,A,F5.3)\") \"The weight to carry is \", totalWeight, \" and the volume used is \", totalVolume\n \nEND PROGRAM KNAPSACK\n\n\nMaximum value achievable is 54500\nThis is achieved by carrying 0 panacea, 15 ichor and 11 gold items\nThe weight to carry is 25.0 and the volume used is 0.247\n\n","human_summarization":"\"Code calculates the maximum value a traveler can carry in his knapsack from available items in Shangri La, considering the weight and volume constraints. It determines the optimal quantity of each item to take, using a brute force approach. It provides one of the four possible solutions that maximize the value.\"","id":945}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: FORTRAN version IV and later\nC     Loops N plus one half - Fortran IV (1964)\n      INTEGER I\n      WRITE(6,301) (I,I=1,10)\n  301 FORMAT((I3,','))\n      END\n\nWorks with: Fortran version 77 and later\nC     WARNING: This program is not valid ANSI FORTRAN 77 code. It uses\nC     two nonstandard characters on the lines labelled 5001 and 5002.\nC     Many F77 compilers should be okay with it, but it is *not*\nC     standard.\n      PROGRAM LOOPPLUSONEHALF\n        INTEGER I, TEN\nC       I'm setting a parameter to distinguish from the label 10.\n        PARAMETER (TEN = 10)\n\n        DO 10 I = 1, TEN\nC         Write the number only.\n          WRITE (*,5001) I\n\nC         If we are on the last one, stop here. This will make this test\nC         every iteration, which can slow your program down a little. If\nC         you want to speed this up at the cost of your own convenience,\nC         you could loop only to nine, and handle ten on its own after\nC         the loop is finished. If you don't care, power to you.\n          IF (I .EQ. TEN) GOTO 10\n\nC         Append a comma to the number.\n          WRITE (*,5002) ','\n   10   CONTINUE\n\nC       Always finish with a newline. This programmer hates it when a\nC       program does not end its output with a newline.\n        WRITE (*,5000) ''\n        STOP\n\n 5000   FORMAT (A)\n\nC       Standard FORTRAN 77 is completely incapable of completing a\nC       WRITE statement without printing a newline. This program would\nC       be much more difficult (i.e. impossible) to write in the ANSI\nC       standard, without cheating and saying something like:\nC\nC           WRITE (*,*) '1, 2, 3, 4, 5, 6, 7, 8, 9, 10'\nC\nC       The dollar sign at the end of the format is a nonstandard\nC       character. It tells the compiler not to print a newline. If you\nC       are actually using FORTRAN 77, you should figure out what your\nC       particular compiler accepts. If you are actually using Fortran\nC       90 or later, you should replace this line with the commented\nC       line that follows it.\n 5001   FORMAT (I3, $)\n 5002   FORMAT (A, $)\nC5001   FORMAT (T3, ADVANCE='NO')\nC5001   FORMAT (A, ADVANCE='NO')\n      END\n\nWorks with: Fortran version 90 and later\ni = 1\ndo\n  write(*, '(I0)', advance='no') i\n  if ( i == 10 ) exit\n  write(*, '(A)', advance='no') ', '\n  i = i + 1\nend do\nwrite(*,*)\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":946}
    {"lang_cluster":"Fortran","source_code":"\n\n      SUBROUTINE TSORT(NL,ND,IDEP,IORD,IPOS,NO)\n      IMPLICIT NONE\n      INTEGER NL,ND,NO,IDEP(ND,2),IORD(NL),IPOS(NL),I,J,K,IL,IR,IPL,IPR\n      DO 10 I=1,NL\n      IORD(I)=I\n   10 IPOS(I)=I\n      K=1\n   20 J=K\n      K=NL+1\n      DO 30 I=1,ND\n      IL=IDEP(I,1)\n      IR=IDEP(I,2)\n      IPL=IPOS(IL)\n      IPR=IPOS(IR)\n      IF(IL.EQ.IR .OR. IPL.GE.K .OR. IPL.LT.J .OR. IPR.LT.J) GO TO 30\n      K=K-1\n      IPOS(IORD(K))=IPL\n      IPOS(IL)=K\n      IORD(IPL)=IORD(K)\n      IORD(K)=IL\n   30 CONTINUE\n      IF(K.GT.J) GO TO 20\n      NO=J-1\n      END\n\n\n      PROGRAM EX_TSORT\n      IMPLICIT NONE\n      INTEGER NL,ND,NC,NO,IDEP,IORD,IPOS,ICODE,I,J,IL,IR\n      PARAMETER(NL=15,ND=44,NC=69)\n      CHARACTER*(20) LABEL\n      DIMENSION IDEP(ND,2),LABEL(NL),IORD(NL),IPOS(NL),ICODE(NC)\n      DATA LABEL\/'DES_SYSTEM_LIB','DW01','DW02','DW03','DW04','DW05',\n     1 'DW06','DW07','DWARE','GTECH','RAMLIB','STD_CELL_LIB','SYNOPSYS',\n     2 'STD','IEEE'\/\n      DATA ICODE\/1,14,13,12,1,3,2,11,15,0,2,15,2,9,10,0,3,15,3,9,0,4,14,\n     213,9,4,3,2,15,10,0,5,5,15,2,9,10,0,6,6,15,9,0,7,7,15,9,0,8,15,9,0,\n     39,15,9,0,10,15,10,0,11,14,15,0,12,15,12,0,0\/\n\nC DECODE DEPENDENCIES AND BUILD IDEP ARRAY\n      I=0\n      J=0\n   10 I=I+1\n      IL=ICODE(I)\n      IF(IL.EQ.0) GO TO 30\n   20 I=I+1\n      IR=ICODE(I)\n      IF(IR.EQ.0) GO TO 10\n      J=J+1\n      IDEP(J,1)=IL\n      IDEP(J,2)=IR\n      GO TO 20\n   30 CONTINUE\n\nC SORT LIBRARIES ACCORDING TO DEPENDENCIES (TOPOLOGICAL SORT)\n      CALL TSORT(NL,ND,IDEP,IORD,IPOS,NO)\n\n      PRINT*,'COMPILE ORDER'\n      DO 40 I=1,NO\n   40 PRINT*,LABEL(IORD(I))\n      PRINT*,'UNORDERED LIBRARIES'\n      DO 50 I=NO+1,NL\n   50 PRINT*,LABEL(IORD(I))\n      END\n\n\n","human_summarization":"implement a function to perform a topological sort on VHDL libraries based on their dependencies. The function returns a valid compile order of the libraries, ignoring self-dependencies and flagging un-orderable dependencies. The function uses either Kahn's 1962 topological sort or depth-first search algorithm. It also includes a routine to handle the dependencies and compile order, with potential for optimization. The input data is assumed to be an array of dependencies with library names as single words.","id":947}
    {"lang_cluster":"Fortran","source_code":"\n\n      SUBROUTINE STARTS(A,B)\t!Text A starts with text B?\n       CHARACTER*(*) A,B\n        IF (INDEX(A,B).EQ.1) THEN\t!Searches A to find B.\n          WRITE (6,*) \">\",A,\"< starts with >\",B,\"<\"\n         ELSE\n          WRITE (6,*) \">\",A,\"< does not start with >\",B,\"<\"\n        END IF\n      END SUBROUTINE STARTS\n\n      SUBROUTINE HAS(A,B)\t!Text B appears somewhere in text A?\n       CHARACTER*(*) A,B\n       INTEGER L\n        L = INDEX(A,B)\t\t!The first position in A where B matches.\n        IF (L.LE.0) THEN\n          WRITE (6,*) \">\",A,\"< does not contain >\",B,\"<\"\n         ELSE\n          WRITE (6,*) \">\",A,\"< contains a >\",B,\"<, offset\",L\n        END IF\n      END SUBROUTINE HAS\n\n      SUBROUTINE ENDS(A,B)\t!Text A ends with text B.\n       CHARACTER*(*) A,B\n       INTEGER L\n        L = LEN(A) - LEN(B)\t!Find the tail end of A that B might match.\n        IF (L.LT.0) THEN\t!Dare not use an OR, because of full evaluation risks.\n          WRITE (6,*) \">\",A,\"< is too short to end with >\",B,\"<\"\t!Might as well have a special message.\n        ELSE IF (A(L + 1:L + LEN(B)).NE.B) THEN\t!Otherwise, it is safe to look.\n          WRITE (6,*) \">\",A,\"< does not end with >\",B,\"<\"\n        ELSE\n          WRITE (6,*) \">\",A,\"< ends with >\",B,\"<\"\n        END IF\n      END SUBROUTINE ENDS\n\n      CALL STARTS(\"This\",\"is\")\n      CALL STARTS(\"Theory\",\"The\")\n      CALL HAS(\"Bananas\",\"an\")\n      CALL ENDS(\"Banana\",\"an\")\n      CALL ENDS(\"Banana\",\"na\")\n      CALL ENDS(\"Brief\",\"Much longer\")\n      END\n\n\n >This< does not start with >is<\n >Theory< starts with >The<\n >Bananas< contains a >an<, offset           2\n >Banana< does not end with >an<\n >Banana< ends with >na<\n >Brief< is too short to end with >Much longer<\n\n\n!-----------------------------------------------------------------------\n!Main program string_matching\n!-----------------------------------------------------------------------\nprogram    string_matching\n   implicit none\n   character(len=*), parameter :: fmt= '(I0)'\n   write(*,fmt) starts(\"this\",\"is\")\n   write(*,fmt) starts(\"theory\",\"the\")\n   write(*,fmt) has(\"bananas\",\"an\")\n   write(*,fmt) ends(\"banana\",\"an\")\n   write(*,fmt) ends(\"banana\",\"na\")\n   write(*,fmt) ends(\"brief\",\"much longer\")\n\n contains\n   !     Determining if the first string starts with second string\n   function  starts(string1, string2) result(answer)\n      implicit none\n      character(len=*), intent(in) :: string1\n      character(len=*), intent(in) :: string2\n      integer :: answer\n      answer = 0\n      if(len(string2)>len(string1)) return\n      if(string1(1:len(string2))==string2) answer = 1\n   end function starts\n   !     Determining if the first string contains the second string at any location\n   function  has(string1, string2) result(answer)\n      implicit none\n      character(len=*), intent(in) :: string1\n      character(len=*), intent(in) :: string2\n      character(len=:),allocatable :: temp\n      integer :: answer, add\n      character(len=*), parameter :: fmt= '(A6,X,I0)'\n      answer = 0\n      add = 0\n      if(len(string2)>len(string1)) return\n      answer = index(string1, string2)\n      if(answer==0) return\n      !     Print the location of the match for part 2\n      write(*,fmt) \" at \", answer\n      !     Handle multiple occurrences of a string for part 2.\n      add = answer\n      temp = string1(answer+1:)\n      do while(answer>0)\n         answer = index(temp, string2)\n         add = add + answer\n         if(answer>0) write(*,fmt) \" at \", add\n         !          deallocate(temp)\n         temp = string1(add+1:) ! auto reallocation\n      enddo\n      answer = 1\n   end function has\n   !     Determining if the first string ends with the second string\n   function  ends(string1, string2) result(answer)\n      implicit none\n      character(len=*), intent(in) :: string1\n      character(len=*), intent(in) :: string2\n      integer :: answer\n      answer = 0\n      if(len(string2)>len(string1)) return\n      if(string1(len(string1)-len(string2)+1:)==string2) answer = 1\n   end function ends\nend program string_matching\n\n\n0\n1\n   at  2\n   at  4\n1\n0\n1\n0\n\n\n","human_summarization":"The code performs three types of string matching operations: checking if the first string starts with the second string, if the first string contains the second string at any location, and if the first string ends with the second string. It also optionally prints the location of the match and handles multiple occurrences of a string. The code uses the CHARACTER variable and LEN function in Fortran for string-like usage. The INDEX function is used to determine the first index where the target matches. The code also handles potential issues with logical expressions and indexing. The output indicates whether the match is true or false, and displays multiple occurrences if applicable. The code is written in modern Fortran style with intrinsic procedures for string manipulation.","id":948}
    {"lang_cluster":"Fortran","source_code":"\n\nAlso standardised in F90 is the $ format code, which specifies that the output line is not to end with the WRITE statement. The problem here is that Fortran does not offer an IF ...FI bracketing construction inside an expression, that would allow something like WRITE(...) FIRST,LAST,IF (UNIQUE) THEN \"Distinct values only\" ELSE \"Repeated values allowed\" FI \/\/ \".\"\n so that the correct alternative will be selected. Further, an array (that would hold those two texts) can't be indexed by a LOGICAL variable, and playing with EQUIVALENCE won't help, because the numerical values revealed thereby for .TRUE. and .FALSE. may not be 1 and 0. And anyway, parameters are not allowed to be accessed via EQUIVALENCE to another variable.\nSo, a two-part output, and to reduce the blather, two IF-statements.       SUBROUTINE FOURSHOW(FIRST,LAST,UNIQUE)\t!The \"Four Rings\" or \"Four Squares\" puzzle.\nChoose values such that A+B = B+C+D = D+E+F = F+G, all being integers in FIRST:LAST...\n       INTEGER FIRST,LAST\t!The range of allowed values.\n       LOGICAL UNIQUE\t\t!Solutions need not have unique values.\n       INTEGER A,B,C,D,E,F,G\t!Ah, Diophantus of Alexandria.\n       INTEGER V(7),S,N\t\t!Assistants.\n       EQUIVALENCE (V(1),A),(V(2),B),(V(3),C),\t\t!Yes,\n     1             (V(4),D),(V(5),E),(V(6),F),(V(7),G)\t!We're all individuals.\n        WRITE (6,1) FIRST,LAST\t!Announce: first part.\n    1   FORMAT (\/,\"The Four Rings puzzle, over \",I0,\" to \",I0,\".\",$)\t!$: An addendum follows.\n        IF (UNIQUE) WRITE (6,*) \"Distinct values only.\"\t!Save on the THEN ... ELSE ... END IF blather.\n        IF (.NOT.UNIQUE) WRITE (6,*) \"Repeated values allowed.\"\t!Perhaps the compiler will be smarter.\n\n        N = 0\t!No solutions have been found.\n      BB:DO B = FIRST,LAST\t!Start chugging through the possibilities.\n        CC:DO C = FIRST,LAST\t\t!Brute force and ignorance.\n             IF (UNIQUE .AND. B.EQ.C) CYCLE CC\t!The first constraint shows up.\n          DD:DO D = FIRST,LAST\t\t!Start by forming B, C, and D.\n               IF (UNIQUE .AND. ANY(V(2:3).EQ.D)) CYCLE DD\t!Ignoring A just for now.\n               S = B + C + D\t\t!This is the common sum.\n               A = S - B\t\t!The value of A is not free from BCD.\n               IF (A < FIRST .OR. A > LAST) CYCLE DD\t!And it may not be within bounds.\n               IF (UNIQUE .AND. ANY(V(2:4).EQ.A)) CYCLE DD\t!Or, if required so, unique.\n            EE:DO E = FIRST,LAST\t!Righto, A,B,C,D are valid. Try an E.\n                 IF (UNIQUE .AND. ANY(V(1:4).EQ.E)) CYCLE EE\t!Precluded already?\n                 F = S - (E + D)\t\t!No. So therefore, F is determined.\n                 IF (F < FIRST .OR. F > LAST) CYCLE EE\t!Acceptable?\n                 IF (UNIQUE .AND. ANY(V(1:5).EQ.F)) CYCLE EE\t!And, if required, unique?\n                 G = S - F\t\t\t!Yes! So finally, G is determined.\n                 IF (G < FIRST .OR. G > LAST) CYCLE EE\t!Acceptable?\n                 IF (UNIQUE .AND. ANY(V(1:6).EQ.G)) CYCLE EE\t!And, if required, unique?\n                 N = N + 1\t\t\t!Yes! Count a solution set!\n                 IF (UNIQUE) WRITE (6,\"(7I3)\") V\t!Show its values.\n               END DO EE\t\t\t!Consder another E.\n             END DO DD\t\t\t!Consider another D.\n           END DO CC\t\t!Consider another C.\n         END DO BB\t!Consider another B.\n        WRITE (6,2) N\t!Announce the count.\n    2   FORMAT (I9,\" found.\")\t!Numerous, if no need for distinct values.\n      END SUBROUTINE FOURSHOW\t!That was fun!\n\n      PROGRAM POKE\n\n      CALL FOURSHOW(1,7,.TRUE.)\n      CALL FOURSHOW(3,9,.TRUE.)\n      CALL FOURSHOW(0,9,.FALSE.)\n\n      END\n\n\nThe Four Rings puzzle, over 1 to 7. Distinct values only.\n  7  2  6  1  3  5  4\n  7  3  2  5  1  4  6\n  6  4  1  5  2  3  7\n  6  4  5  1  2  7  3\n  4  5  3  1  6  2  7\n  5  6  2  3  1  7  4\n  4  7  1  3  2  6  5\n  3  7  2  1  5  4  6\n        8 found.\n\nThe Four Rings puzzle, over 3 to 9. Distinct values only.\n  9  6  4  5  3  7  8\n  9  6  5  4  3  8  7\n  8  7  3  5  4  6  9\n  7  8  3  4  5  6  9\n        4 found.\n\nThe Four Rings puzzle, over 0 to 9. Repeated values allowed.\n     2860 found.\n\n\n31:                    IF (UNIQUE .AND. ANY(V(1:6).EQ.G)) CYCLE EE    !And, if required, unique?\n00401496   mov         edi,dword ptr [UNIQUE]\n00401499   mov         edi,dword ptr [edi]\n0040149B   mov         ebx,dword ptr [G (00470380)]\n004014A1   mov         eax,0\n004014A6   mov         ecx,1\n004014AB   mov         dword ptr [ebp-60h],1\n004014B2   cmp         dword ptr [ebp-60h],6\n004014B6   jg          FOURSHOW+4C4h (004014fc)\n004014B8   cmp         ecx,1\n004014BB   jl          FOURSHOW+48Ah (004014c2)\n004014BD   cmp         ecx,7\n004014C0   jle         FOURSHOW+493h (004014cb)\n004014C2   xor         esi,esi\n004014C4   mov         dword ptr [ebp-6Ch],esi\n004014C7   dec         esi\n004014C8   bound       esi,qword ptr [ebp-6Ch]\n004014CB   imul        esi,ecx,4\n004014CE   mov         esi,dword ptr S+4 (00470364)[esi]\n004014D4   xor         edx,edx\n004014D6   cmp         esi,ebx\n004014D8   sete        dl\n004014DB   mov         dword ptr [ebp-6Ch],edx\n004014DE   mov         edx,eax\n004014E0   or          edx,dword ptr [ebp-6Ch]\n004014E3   and         edx,1\n004014E6   mov         eax,edx\n004014E8   neg         eax\n004014EA   mov         esi,ecx\n004014EC   add         esi,1\n004014EF   mov         ecx,esi\n004014F1   mov         edx,dword ptr [ebp-60h]\n004014F4   add         edx,1\n004014F7   mov         dword ptr [ebp-60h],edx\n004014FA   jmp         FOURSHOW+47Ah (004014b2)\n004014FC   and         edi,eax\n004014FE   mov         edx,edi\n00401500   and         edx,1\n00401503   cmp         edx,0\n00401506   jne         FOURSHOW+531h (00401569)\n32:                    N = N + 1          !Yes! Count a solution set!\n00401508   mov         esi,dword ptr [N (0047035c)]\n0040150E   add         esi,1\n00401511   mov         dword ptr [N (0047035c)],esi\n33:                    IF (UNIQUE) WRITE (6,\"(7I3)\") V    !Show its values.\n\n\n","human_summarization":"The code replaces the variables a, b, c, d, e, f, and g with decimal digits ranging from LOW to HIGH, ensuring that the sum of the variables in each of the four large squares is equal. It displays all unique solutions for ranges 1-7 and 3-9, and the total number of solutions for non-unique variables in the range 0-9. The code uses the ANY function and DO-loops with text labels for multiple tests and array manipulation. The output is not in a specific order due to the variable determination sequence.","id":949}
    {"lang_cluster":"Fortran","source_code":"\n\n!Digital Text implemented as in C version - Anant Dixit (Oct, 2014)\nprogram clock\nimplicit none\ninteger :: t(8)\ndo\n  call date_and_time(values=t)\n  call sleep(1)\n  call system('clear')\n  call digital_display(t(5),t(6),t(7))\nend do\nend program\n\nsubroutine digital_display(H,M,S)\n!arguments\ninteger :: H, M, S\n!local\ncharacter(len=*), parameter :: nfmt='(A8)', cfmt='(A6)'\ncharacter(len=88), parameter :: d1 = ' 00000     1     22222   33333      4   5555555  66666  7777777  88888   99999        '\ncharacter(len=88), parameter :: d2 = '0     0   11    2     2 3     3    44   5       6     6 7     7 8     8 9     9 \u00a0::   '\ncharacter(len=88), parameter :: d3 = '0    00  1 1          2       3   4 4   5       6             7 8     8 9     9 \u00a0::   '\ncharacter(len=88), parameter :: d4 = '0   0 0    1         2        3  4  4   5       6            7  8     8 9     9 \u00a0::   '\ncharacter(len=88), parameter :: d5 = '0  0  0    1        2      333  4444444 555555  666666      7    88888   999999       '\ncharacter(len=88), parameter :: d6 = '0 0   0    1       2          3     4         5 6     6    7    8     8       9 \u00a0::   '\ncharacter(len=88), parameter :: d7 = '00    0    1      2           3     4         5 6     6   7     8     8       9 \u00a0::   '\ncharacter(len=88), parameter :: d8 = '0     0    1     2      3     3     4   5     5 6     6  7      8     8 9     9 \u00a0::   '\ncharacter(len=88), parameter :: d9 = ' 00000  1111111 2222222  33333      4    55555   66666  7        88888   99999        '\ninteger :: h1, h2, m1, m2, s1, s2\nh1 = 1+8*floor(dble(H)\/10.D0)\nh2 = 1+8*modulo(H,10)\nm1 = 1+8*floor(dble(M)\/10.D0)\nm2 = 1+8*modulo(M,10)\ns1 = 1+8*floor(dble(S)\/10.D0)\ns2 = 1+8*modulo(S,10)\n\nwrite(*,nfmt,advance='no') d1(h1:h1+8)\nwrite(*,nfmt,advance='no') d1(h2:h2+8)\nwrite(*,cfmt,advance='no') d1(81:88)\nwrite(*,nfmt,advance='no') d1(m1:m1+8)\nwrite(*,nfmt,advance='no') d1(m2:m2+8)\nwrite(*,cfmt,advance='no') d1(81:88)\nwrite(*,nfmt,advance='no') d1(s1:s1+8)\nwrite(*,nfmt) d1(s2:s2+8)\n\nwrite(*,nfmt,advance='no') d2(h1:h1+8)\nwrite(*,nfmt,advance='no') d2(h2:h2+8)\nwrite(*,cfmt,advance='no') d2(81:88)\nwrite(*,nfmt,advance='no') d2(m1:m1+8)\nwrite(*,nfmt,advance='no') d2(m2:m2+8)\nwrite(*,cfmt,advance='no') d2(81:88)\nwrite(*,nfmt,advance='no') d2(s1:s1+8)\nwrite(*,nfmt) d2(s2:s2+8)\n\nwrite(*,nfmt,advance='no') d3(h1:h1+8)\nwrite(*,nfmt,advance='no') d3(h2:h2+8)\nwrite(*,cfmt,advance='no') d3(81:88)\nwrite(*,nfmt,advance='no') d3(m1:m1+8)\nwrite(*,nfmt,advance='no') d3(m2:m2+8)\nwrite(*,cfmt,advance='no') d3(81:88)\nwrite(*,nfmt,advance='no') d3(s1:s1+8)\nwrite(*,nfmt) d3(s2:s2+8)\n\nwrite(*,nfmt,advance='no') d4(h1:h1+8)\nwrite(*,nfmt,advance='no') d4(h2:h2+8)\nwrite(*,cfmt,advance='no') d4(81:88)\nwrite(*,nfmt,advance='no') d4(m1:m1+8)\nwrite(*,nfmt,advance='no') d4(m2:m2+8)\nwrite(*,cfmt,advance='no') d4(81:88)\nwrite(*,nfmt,advance='no') d4(s1:s1+8)\nwrite(*,nfmt) d4(s2:s2+8)\n\nwrite(*,nfmt,advance='no') d5(h1:h1+8)\nwrite(*,nfmt,advance='no') d5(h2:h2+8)\nwrite(*,cfmt,advance='no') d5(81:88)\nwrite(*,nfmt,advance='no') d5(m1:m1+8)\nwrite(*,nfmt,advance='no') d5(m2:m2+8)\nwrite(*,cfmt,advance='no') d5(81:88)\nwrite(*,nfmt,advance='no') d5(s1:s1+8)\nwrite(*,nfmt) d5(s2:s2+8)\n\nwrite(*,nfmt,advance='no') d6(h1:h1+8)\nwrite(*,nfmt,advance='no') d6(h2:h2+8)\nwrite(*,cfmt,advance='no') d6(81:88)\nwrite(*,nfmt,advance='no') d6(m1:m1+8)\nwrite(*,nfmt,advance='no') d6(m2:m2+8)\nwrite(*,cfmt,advance='no') d6(81:88)\nwrite(*,nfmt,advance='no') d6(s1:s1+8)\nwrite(*,nfmt) d6(s2:s2+8)\n\nwrite(*,nfmt,advance='no') d7(h1:h1+8)\nwrite(*,nfmt,advance='no') d7(h2:h2+8)\nwrite(*,cfmt,advance='no') d7(81:88)\nwrite(*,nfmt,advance='no') d7(m1:m1+8)\nwrite(*,nfmt,advance='no') d7(m2:m2+8)\nwrite(*,cfmt,advance='no') d7(81:88)\nwrite(*,nfmt,advance='no') d7(s1:s1+8)\nwrite(*,nfmt) d7(s2:s2+8)\n\nwrite(*,nfmt,advance='no') d8(h1:h1+8)\nwrite(*,nfmt,advance='no') d8(h2:h2+8)\nwrite(*,cfmt,advance='no') d8(81:88)\nwrite(*,nfmt,advance='no') d8(m1:m1+8)\nwrite(*,nfmt,advance='no') d8(m2:m2+8)\nwrite(*,cfmt,advance='no') d8(81:88)\nwrite(*,nfmt,advance='no') d8(s1:s1+8)\nwrite(*,nfmt) d8(s2:s2+8)\n\nwrite(*,nfmt,advance='no') d9(h1:h1+8)\nwrite(*,nfmt,advance='no') d9(h2:h2+8)\nwrite(*,cfmt,advance='no') d9(81:88)\nwrite(*,nfmt,advance='no') d9(m1:m1+8)\nwrite(*,nfmt,advance='no') d9(m2:m2+8)\nwrite(*,cfmt,advance='no') d9(81:88)\nwrite(*,nfmt,advance='no') d9(s1:s1+8)\nwrite(*,nfmt) d9(s2:s2+8)\n\nend subroutine\n\n\n\n\n 22222   33333           1     88888           1       1    \n2     2 3     3 \u00a0::     11    8     8 \u00a0::     11      11    \n      2       3 \u00a0::    1 1    8     8 \u00a0::    1 1     1 1    \n     2        3 \u00a0::      1    8     8 \u00a0::      1       1    \n    2      333           1     88888           1       1    \n   2          3 \u00a0::      1    8     8 \u00a0::      1       1    \n  2           3 \u00a0::      1    8     8 \u00a0::      1       1    \n 2      3     3 \u00a0::      1    8     8 \u00a0::      1       1    \n2222222  33333        1111111  88888        1111111 1111111 \n\n\n","human_summarization":"create a graphical or text-based clock that displays time in seconds. The clock updates every second and cycles every minute or 30 seconds. The code ensures the clock is not CPU intensive and matches the system clock time. It uses system commands for screen clearing, sleeping, and time retrieval. The code is simple and concise.","id":950}
    {"lang_cluster":"Fortran","source_code":"\n\n       MODULE DATEGNASH\n\n       TYPE DATEBAG\n        INTEGER DAY,MONTH,YEAR\n       END TYPE DATEBAG\n\n       CHARACTER*9 MONTHNAME(12),DAYNAME(0:6)\n       PARAMETER (MONTHNAME = (\/\"JANUARY\",\"FEBRUARY\",\"MARCH\",\"APRIL\",\n     1  \"MAY\",\"JUNE\",\"JULY\",\"AUGUST\",\"SEPTEMBER\",\"OCTOBER\",\"NOVEMBER\",\n     2  \"DECEMBER\"\/))\n       PARAMETER (DAYNAME = (\/\"SUNDAY\",\"MONDAY\",\"TUESDAY\",\"WEDNESDAY\",\n     1  \"THURSDAY\",\"FRIDAY\",\"SATURDAY\"\/))\n\n       INTEGER*4 JDAYSHIFT\n       PARAMETER (JDAYSHIFT = 2415020)\n       CONTAINS\n       INTEGER FUNCTION LSTNB(TEXT)\n        CHARACTER*(*),INTENT(IN):: TEXT\n        INTEGER L\n         L = LEN(TEXT)\n    1    IF (L.LE.0) GO TO 2\n         IF (ICHAR(TEXT(L:L)).GT.ICHAR(\" \")) GO TO 2\n         L = L - 1\n         GO TO 1\n    2    LSTNB = L\n        RETURN\n       END FUNCTION LSTNB\n      CHARACTER*2 FUNCTION I2FMT(N)\n       INTEGER*4 N\n        IF (N.LT.0) THEN\n          IF (N.LT.-9) THEN\n            I2FMT = \"-!\"\n           ELSE\n            I2FMT = \"-\"\/\/CHAR(ICHAR(\"0\") - N)\n          END IF\n        ELSE IF (N.LT.10) THEN\n          I2FMT = \" \" \/\/CHAR(ICHAR(\"0\") + N)\n        ELSE IF (N.LT.100) THEN\n          I2FMT = CHAR(N\/10      + ICHAR(\"0\"))\n     1           \/\/CHAR(MOD(N,10) + ICHAR(\"0\"))\n        ELSE\n          I2FMT = \"+!\"\n        END IF\n      END FUNCTION I2FMT\n      CHARACTER*8 FUNCTION I8FMT(N)\n       INTEGER*4 N\n       CHARACTER*8 HIC\n        WRITE (HIC,1) N\n    1   FORMAT (I8)\n        I8FMT = HIC\n      END FUNCTION I8FMT\n\n      SUBROUTINE SAY(OUT,TEXT)\n       INTEGER OUT\n       CHARACTER*(*) TEXT\n        WRITE (6,1) TEXT(1:LSTNB(TEXT))\n    1   FORMAT (A)\n      END SUBROUTINE SAY\n\n       INTEGER*4 FUNCTION DAYNUM(YY,M,D)\n        INTEGER*4 JDAYN\n        INTEGER YY,Y,M,MM,D\n         Y = YY\n         IF (Y.LT.1) Y = Y + 1\n         MM = (M - 14)\/12\n         JDAYN = D - 32075\n     A    + 1461*(Y + 4800  + MM)\/4\n     B    +  367*(M - 2     - MM*12)\/12\n     C    -    3*((Y + 4900 + MM)\/100)\/4\n         DAYNUM = JDAYN - JDAYSHIFT\n       END FUNCTION DAYNUM\n\n       TYPE(DATEBAG) FUNCTION MUNYAD(DAYNUM)\n        INTEGER*4 DAYNUM,JDAYN\n        INTEGER Y,M,D,L,N\n         JDAYN = DAYNUM + JDAYSHIFT\n         L = JDAYN + 68569\n         N = 4*L\/146097\n         L = L - (146097*N + 3)\/4\n         Y = 4000*(L + 1)\/1461001\n         L = L - 1461*Y\/4 + 31\n         M = 80*L\/2447\n         D = L - 2447*M\/80\n         L = M\/11\n         M = M + 2 - 12*L\n         Y = 100*(N - 49) + Y + L\n         IF (Y.LT.1) Y = Y - 1\n         MUNYAD%YEAR  = Y\n         MUNYAD%MONTH = M\n         MUNYAD%DAY   = D\n       END FUNCTION MUNYAD\n\n       INTEGER FUNCTION PMOD(N,M)\n        INTEGER N,M\n         PMOD = MOD(MOD(N,M) + M,M)\n       END FUNCTION PMOD\n\n      SUBROUTINE CALENDAR(Y1,Y2,COLUMNS)\n\n       INTEGER Y1,Y2,YEAR\n       INTEGER M,M1,M2,MONTH\n       INTEGER*4 DN1,DN2,DN,D\n       INTEGER W,G\n       INTEGER L,LINE\n       INTEGER COL,COLUMNS,COLWIDTH\n       CHARACTER*200 STRIPE(6),SPECIAL(6),MLINE,DLINE\n        W = 3\n        G = 1\n        COLWIDTH = 7*W + G\n      Y:DO YEAR = Y1,Y2\n          CALL SAY(MSG,\"\")\n          IF (YEAR.EQ.0) THEN\n            CALL SAY(MSG,\"THERE IS NO YEAR ZERO.\")\n            CYCLE Y\n          END IF\n          MLINE = \"\"\n          L = (COLUMNS*COLWIDTH - G - 8)\/2\n          IF (YEAR.GT.0) THEN\n            MLINE(L:) = I8FMT(YEAR)\n           ELSE\n            MLINE(L - 1:) = I8FMT(-YEAR)\/\/\"BC\"\n          END IF\n          CALL SAY(MSG,MLINE)\n          DO MONTH = 1,12,COLUMNS\n            M1 = MONTH\n            M2 = MIN(12,M1 + COLUMNS - 1)\n            MLINE = \"\"\n            DLINE = \"\"\n            STRIPE = \"\"\n            SPECIAL = \"\"\n            L0 = 1\n            DO M = M1,M2\n              L = (COLWIDTH - G - LSTNB(MONTHNAME(M)))\/2 - 1\n              MLINE(L0 + L:) = MONTHNAME(M)\n              DO D = 0,6\n                L = L0 + (3 - W) + D*W\n                DLINE(L:L + 2) = DAYNAME(D)(1:W - 1)\n              END DO\n              DN1 = DAYNUM(YEAR,M,1)\n              DN2 = DAYNUM(YEAR,M + 1,0)\n              COL = MOD(PMOD(DN1,7) + 7,7)\n              LINE = 1\n              D = 1\n              DO DN = DN1,DN2\n                L = L0 + COL*W\n                STRIPE(LINE)(L:L + 1) = I2FMT(D)\n                D = D + 1\n                COL = COL + 1\n                IF (COL.GT.6) THEN\n                  LINE = LINE + 1\n                  COL = 0\n                END IF\n              END DO\n              L0 = L0 + 7*W + G\n            END DO\n            CALL SAY(MSG,MLINE)\n            CALL SAY(MSG,DLINE)\n            DO LINE = 1,6\n              IF (STRIPE(LINE).NE.\"\") THEN\n                CALL SAY(MSG,STRIPE(LINE))\n              END IF\n            END DO\n          END DO\n        END DO Y\n        CALL SAY(MSG,\"\")\n      END SUBROUTINE CALENDAR\n      END MODULE DATEGNASH\n\n      PROGRAM SHOW1968\n       USE DATEGNASH\n       INTEGER NCOL\n        DO NCOL = 1,6\n          CALL CALENDAR(1969,1969,NCOL)\n        END DO\n      END\n\n\n                                                                1969\n      JANUARY              FEBRUARY                MARCH                 APRIL                  MAY                  JUNE\nSU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA\n          1  2  3  4                     1                     1         1  2  3  4  5               1  2  3   1  2  3  4  5  6  7\n 5  6  7  8  9 10 11   2  3  4  5  6  7  8   2  3  4  5  6  7  8   6  7  8  9 10 11 12   4  5  6  7  8  9 10   8  9 10 11 12 13 14\n12 13 14 15 16 17 18   9 10 11 12 13 14 15   9 10 11 12 13 14 15  13 14 15 16 17 18 19  11 12 13 14 15 16 17  15 16 17 18 19 20 21\n19 20 21 22 23 24 25  16 17 18 19 20 21 22  16 17 18 19 20 21 22  20 21 22 23 24 25 26  18 19 20 21 22 23 24  22 23 24 25 26 27 28\n26 27 28 29 30 31     23 24 25 26 27 28     23 24 25 26 27 28 29  27 28 29 30           25 26 27 28 29 30 31  29 30\n                                            30 31\n       JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER\nSU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA\n       1  2  3  4  5                  1  2      1  2  3  4  5  6            1  2  3  4                     1      1  2  3  4  5  6\n 6  7  8  9 10 11 12   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8   7  8  9 10 11 12 13\n13 14 15 16 17 18 19  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15  14 15 16 17 18 19 20\n20 21 22 23 24 25 26  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22  21 22 23 24 25 26 27\n27 28 29 30 31        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29  28 29 30 31\n                      31                                                                30\n\n\n","human_summarization":"The code provides an algorithm for generating a calendar formatted to fit a page that is 132 characters wide, similar to the output of 1969 era line printers. The entire code is written in uppercase, inspired by the programming practices of the 1960s. It does not include Snoopy generation but instead outputs a placeholder. The code is designed for practicality and ease of reading, especially for those with presbyopia.","id":951}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and latermodule triples\n  implicit none\n  \n  integer :: max_peri, prim, total\n  integer :: u(9,3) = reshape((\/ 1, -2, 2,  2, -1, 2,  2, -2, 3, &\n                                 1,  2, 2,  2,  1, 2,  2,  2, 3, &\n                                -1,  2, 2, -2,  1, 2, -2,  2, 3 \/), &\n                                (\/ 9, 3 \/))\n                                \ncontains\n\nrecursive subroutine new_tri(in)\n  integer, intent(in) :: in(:)\n  integer :: i\n  integer :: t(3), p\n\n  p = sum(in)\n  if (p > max_peri) return\n\n  prim = prim + 1\n  total = total + max_peri \/ p\n  do i = 1, 3\n    t(1) = sum(u(1:3, i) * in)\n    t(2) = sum(u(4:6, i) * in)\n    t(3) = sum(u(7:9, i) * in)\n    call new_tri(t);\n  end do\nend subroutine new_tri\nend module triples\n\nprogram Pythagorean\n  use triples\n  implicit none\n\n  integer :: seed(3) = (\/ 3, 4, 5 \/)\n  \n  max_peri = 10\n  do\n    total = 0\n    prim = 0\n    call new_tri(seed)\n    write(*, \"(a, i10, 2(i10, a))\") \"Up to\", max_peri, total, \" triples\",  prim, \" primitives\"\n    if(max_peri == 100000000) exit\n    max_peri = max_peri * 10\n  end do\nend program Pythagorean\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":952}
    {"lang_cluster":"Fortran","source_code":"\n\n-*- mode: compilation; default-directory: \"\/tmp\/\" -*-\nCompilation started at Sat May 18 18:09:46\n\na=.\/F && make $a && $a < configuration.file\nf95 -Wall -ffree-form F.F -o F\n          92          21          17          24          82          19          19          22          67           0           2          27          27          57          55          31           1          61          43          60          20           6           2           0          10           0\n\nCompilation finished at Sat May 18 18:09:46\n\n\n! count letters from stdin\nprogram LetterFrequency\n  implicit none\n  character (len=1) :: s\n  integer, dimension(26) :: a\n  integer :: ios, i, t\n  data a\/26*0\/,i\/0\/\n  open(unit=7, file='\/dev\/stdin', access='direct', form='formatted', recl=1, status='old', iostat=ios)\n  if (ios .ne. 0) then\n    write(0,*)'Opening stdin failed'\n    stop\n  endif\n  do i=1, huge(i)\n    read(unit=7, rec = i, fmt = '(a)', iostat = ios ) s\n    if (ios .ne. 0) then\n      !write(0,*)'ios on failure is ',ios\n      close(unit=7)\n      exit\n    endif\n    t = ior(iachar(s(1:1)), 32) - iachar('a')\n    if ((0 .le. t) .and. (t .le. iachar('z'))) then\n      t = t+1\n      a(t) = a(t) + 1\n    endif\n  end do\n  write(6, *) a\nend program LetterFrequency\n\n","human_summarization":"The code opens a text file and counts the frequency of each letter occurrence. It can count all characters, including punctuation, or just the letters A to Z, based on the configuration file. The program is compiled and executed on a gnu\/linux system. The FORTRAN90 source code reads from stdin and writes the result to stdout, with a potential future enhancement to use block size records.","id":953}
    {"lang_cluster":"Fortran","source_code":"\n\ntype node\n   real :: data\n   type( node ), pointer :: next => null() \nend type node\n!\n!. . . .\n!\ntype( node ) :: head\n\n","human_summarization":"define a data structure for a singly-linked list element. This element includes a data member for storing a numeric value and a mutable link to the next element.","id":954}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram Factors\n  implicit none\n  integer :: i, number\n  \n  write(*,*) \"Enter a number between 1 and 2147483647\"\n  read*, number\n\n  do i = 1, int(sqrt(real(number))) - 1\n    if (mod(number, i) == 0) write (*,*) i, number\/i\n  end do\n  \n  ! Check to see if number is a square\n  i = int(sqrt(real(number))) \n  if (i*i == number) then\n     write (*,*) i\n  else if (mod(number, i) == 0) then\n     write (*,*) i, number\/i\n  end if\n    \nend program\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":955}
    {"lang_cluster":"Fortran","source_code":"\n\n      SUBROUTINE RAKE(IN,M,X,WAY)\t!Casts forth text in fixed-width columns.\nCollates column widths so that each column is wide enough for its widest member.\n       INTEGER IN\t\t!Fingers the input file.\n       INTEGER M\t\t!Maximum record length thereof.\n       CHARACTER*1 X\t\t!The delimiter, possibly a comma.\n       INTEGER WAY\t\t!Alignment style.\n       INTEGER W(M + 1)\t\t!If every character were X in the maximum-length record,\n       INTEGER C(0:M + 1)\t!Then M + 1 would be the maximum number of fields possible.\n       CHARACTER*(M) ACARD\t!A scratchpad big enough for the biggest.\n       CHARACTER*(28 + 4*M) FORMAT\t!Guess. Allow for \"Ann,\" per field.\n       INTEGER I\t\t!A stepper.\n       INTEGER L,LF\t\t!Text fingers.\n       INTEGER NF,MF\t\t!Field counts.\n       CHARACTER*6 WAYNESS(-1:+1)\t!Some annotation may be helpful.\n       PARAMETER (WAYNESS = (\/\"Left\",\"Centre\",\"Right\"\/))\t!Using normal language.\n       INTEGER LINPR\t!The mouthpiece.\n       COMMON LINPR\t!Used all over.\n        W = 0\t\t!Maximum field widths so far seen.\n        MF = 0\t\t!Maximum number of fields to a record.\n        C(0) = 0\t!Syncopation for the first field's predecessor.\n        WRITE (LINPR,*)\t!Some separation.\n        WRITE (LINPR,*) \"Align \",WAYNESS(MIN(MAX(WAY,-1),+1))\t!Explain, cautiously.\n\nChase through the file assessing the lengths of each field.\n   10   READ (IN,11,END = 20) L,ACARD(1:L)\t!Grab a record.\n   11   FORMAT (Q,A)\t\t\t\t!Working only up to its end.\n        CALL LIZZIEBORDEN\t!Find the chop points.\n        W(1:NF) = MAX(W(1:NF),C(1:NF) - C(0:NF - 1) - 1)\t!Thereby the lengths between.\n        MF = MAX(MF,NF)\t\t!Also want to know the most number of chops.\n        GO TO 10\t\t!Get the next record.\n\nConcoct a FORMAT based on the maximum size of each field. Plus one.\n   20   REWIND(IN)\t\t!Back to the beginning.\n        WRITE (FORMAT,21) W(1:MF) + 1\t!Add one to meet the specified at least one space between columns.\n   21   FORMAT (\"(\",(\"A\",I0,\",\"))\t!Generates a sequence of An, items.\n        LF = INDEX(FORMAT,\", \")\t\t!The last one has a trailing comma.\n        IF (LF.LE.0) STOP \"Format trouble!\"\t!Or, maybe not!\n        FORMAT(LF:LF) = \")\"\t\t\t!Convert it to the closing bracket.\n        WRITE (LINPR,*) \"Format\",FORMAT(1:LF)\t!Present it.\n\nChug afresh, this time knowing the maximum length of each field.\n   30   READ (IN,11,END = 40) L,ACARD(1:L)\t!Place just the record's content.\n        CALL LIZZIEBORDEN\t\t!Find the chop points.\n        SELECT CASE(WAY)\t!What is to be done?\n         CASE(-1)\t\t!Shove leftwards by appending spaces.\n          WRITE (LINPR,FORMAT) (ACARD(C(I - 1) + 1:C(I) - 1)\/\/\t!The chopped text.\n     1     REPEAT(\" \",W(I) - C(I) + C(I - 1) + 1),I = 1,NF)\t!Some spaces.\n         CASE( 0)\t\t!Centre by appending half as many spaces.\n          WRITE (LINPR,FORMAT) (ACARD(C(I - 1) + 1:C(I) - 1)\/\/\t!The chopped text.\n     1     REPEAT(\" \",(W(I) - C(I) + C(I - 1) + 1)\/2),I = 1,NF)\t!Some spaces.\n         CASE(+1)\t\t!Align rightwards is the default style.\n          WRITE (LINPR,FORMAT) (ACARD(C(I - 1) + 1:C(I) - 1),I = 1,NF)\t!So, just the texts.\n         CASE DEFAULT\t\t!This shouldn't happen.\n         WRITE (LINPR,*) \"Huh? WAY=\",WAY\t!But if it does,\n         STOP \"Unanticipated value for WAY!\"\t!Explain.\n        END SELECT\t\t!So much for that record.\n        GO TO 30\t\t!Go for another.\nClosedown\n   40   REWIND(IN)\t\t!Be polite.\n       CONTAINS\t!This also marks the end of source for RAKE...\n        SUBROUTINE LIZZIEBORDEN\t!Take an axe to ACARD, chopping at X.\n          NF = 0\t\t!No strokes so far.\n          DO I = 1,L\t\t!So, step away.\n            IF (ICHAR(ACARD(I:I)).EQ.ICHAR(X)) THEN\t!Here?\n              NF = NF + 1\t\t!Yes!\n              C(NF) = I\t\t!The place!\n            END IF\t\t!So much for that.\n          END DO\t\t!On to the next.\n          NF = NF + 1\t\t!And the end of ACARD is also a chop point.\n          C(NF) = L + 1\t\t!As if here.\n        END SUBROUTINE LIZZIEBORDEN\t!She was aquitted.\n      END SUBROUTINE RAKE\t!So much raking over.\n\n      INTEGER L,M,N\t!To be determined the hard way.\n      INTEGER LINPR,IN\t!I\/O unit numbers.\n      COMMON LINPR\t!Some of general note.\n      LINPR = 6\t\t!Standard output via this unit number.\n      IN = 10\t\t!Some unit number for the input file.\n      OPEN (IN,FILE=\"Rake.txt\",STATUS=\"OLD\",ACTION=\"READ\")\t!For formatted input.\n      N = 0\t\t!No records read.\n      M = 0\t\t!Longest record so far.\n\n    1 READ (IN,2,END = 10) L\t!How long is this record?\n    2 FORMAT (Q)\t!Obviously, Q specifies the length, not a content field.\n      N = N + 1\t\t!Anyway, another record has been read.\n      M = MAX(M,L)\t!And this is the longest so far.\n      GO TO 1\t\t!Go back for more.\n\n   10 REWIND (IN)\t!We're ready now.\n      WRITE (LINPR,*) N,\"Recs, longest rec. length is \",M\n      CALL RAKE(IN,M,\"$\",-1)\t!Align left.\n      CALL RAKE(IN,M,\"$\", 0)\t!Centre.\n      CALL RAKE(IN,M,\"$\",+1)\t!Align right.\n      END\t!That's all.\n\n\n          6 Recs, longest rec. length is           66\n\nAlign Left\nFormat(A11,A11,A11,A7,A7,A10,A11,A9,A8,A8,A7,A5,A1)\nGiven      a          text       file   of     many      lines,     where    fields  within  a      line\nare        delineated by         a      single 'dollar'  character, write    a       program\nthat       aligns     each       column of     fields    by         ensuring that    words   in     each\ncolumn     are        separated  by     at     least     one        space.\nFurther,   allow      for        each   word   in        a          column   to      be      either left\njustified, right      justified, or     center justified within     its      column.\n\nAlign Centre\nFormat(A11,A11,A11,A7,A7,A10,A11,A9,A8,A8,A7,A5,A1)\n   Given        a        text     file    of      many     lines,     where   fields  within    a   line\n    are    delineated     by        a   single  'dollar' character,   write     a    program\n   that      aligns      each    column   of     fields      by     ensuring   that   words    in   each\n  column       are     separated   by     at     least       one     space.\n Further,     allow       for     each   word      in         a      column     to      be   either left\njustified,    right   justified,   or   center justified   within      its   column.\n\nAlign Right\nFormat(A11,A11,A11,A7,A7,A10,A11,A9,A8,A8,A7,A5,A1)\n     Given          a       text   file     of      many     lines,    where  fields  within      a line\n       are delineated         by      a single  'dollar' character,    write       a program\n      that     aligns       each column     of    fields         by ensuring    that   words     in each\n    column        are  separated     by     at     least        one   space.\n  Further,      allow        for   each   word        in          a   column      to      be either left\njustified,      right justified,     or center justified     within      its column.\n\n","human_summarization":"The code reads a text file where fields within a line are delineated by a dollar character. It aligns each column of fields by ensuring that words in each column are separated by at least one space. It also allows for each word in a column to be either left justified, right justified, or center justified within its column. The code handles varying record lengths and field sizes, and computes the minimum space between columns from the text itself. It also determines the maximum record length and maximum widths for each column. Finally, it makes another pass through the file to produce the output with the aligned columns.","id":956}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram test_rot_13\n\n  implicit none\n  integer, parameter :: len_max = 256\n  integer, parameter :: unit = 10\n  character (len_max) :: file\n  character (len_max) :: fmt\n  character (len_max) :: line\n  integer :: arg\n  integer :: arg_max\n  integer :: iostat\n\n  write (fmt, '(a, i0, a)') '(a', len_max, ')'\n  arg_max = iargc ()\n  if (arg_max > 0) then\n! Encode all files listed on the command line.\n    do arg = 1, arg_max\n      call getarg (arg, file)\n      open (unit, file = file, iostat = iostat)\n      if (iostat \/= 0) cycle\n      do\n        read (unit, fmt = fmt, iostat = iostat) line\n        if (iostat \/= 0) exit\n        write (*, '(a)') trim (rot_13 (line))\n      end do\n      close (unit)\n    end do\n  else\n! Encode standard input.\n    do\n      read (*, fmt = fmt, iostat = iostat) line\n      if (iostat \/= 0) exit\n      write (*, '(a)') trim (rot_13 (line))\n    end do\n  end if\n\ncontains\n\n  function rot_13 (input) result (output)\n\n    implicit none\n    character (len_max), intent (in) :: input\n    character (len_max) :: output\n    integer :: i\n\n    output = input\n    do i = 1, len_trim (output)\n      select case (output (i : i))\n      case ('A' : 'M', 'a' : 'm')\n        output (i : i) = char (ichar (output (i : i)) + 13)\n      case ('N' : 'Z', 'n' : 'z')\n        output (i : i) = char (ichar (output (i : i)) - 13)\n      end select\n    end do\n\n  end function rot_13\n\nend program test_rot_13\n\n\n> cat foo.txt\nfoo\n> cat bar.txt\nbar\n> .\/rot_13 foo.txt bar.txt\nsbb\none\n> .\/rot_13 < foo.txt\nsbb\n> cat foo.txt bar.txt | .\/rot_13\nsbb\none\n\n","human_summarization":"The code implements a rot-13 function, which is a mono-alphabetic substitution cipher that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function works on both upper and lower case letters, preserves case, and passes all non-alphabetic characters in the input stream through without alteration. It can optionally be wrapped in a utility program, acting like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input contained in each file listed on its command line or acting as a filter on its standard input.","id":957}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n\nPROGRAM EXAMPLE\n  IMPLICIT NONE  \n\n  TYPE Pair\n    CHARACTER(6) :: name\n    CHARACTER(1) :: value\n  END TYPE Pair\n\n  TYPE(Pair) :: rcc(10), temp\n  INTEGER :: i, j\n\n  rcc(1) = Pair(\"Black\", \"0\")\n  rcc(2) = Pair(\"Brown\", \"1\")\n  rcc(3) = Pair(\"Red\", \"2\")\n  rcc(4) = Pair(\"Orange\", \"3\")\n  rcc(5) = Pair(\"Yellow\", \"4\") \n  rcc(6) = Pair(\"Green\", \"5\")\n  rcc(7) = Pair(\"Blue\", \"6\")\n  rcc(8) = Pair(\"Violet\", \"7\")\n  rcc(9) = Pair(\"Grey\", \"8\")\n  rcc(10) = Pair(\"White\", \"9\")\n\n  DO i = 2, SIZE(rcc)\n     j = i - 1\n     temp = rcc(i)\n        DO WHILE (j>=1 .AND. LGT(rcc(j)%name, temp%name))\n           rcc(j+1) = rcc(j)\n           j = j - 1\n        END DO\n     rcc(j+1) = temp\n  END DO\n\n  WRITE (*,\"(2A6)\") rcc\n\nEND PROGRAM EXAMPLE\n\n\nBlack      0\nBlue       6\nBrown      1\nGreen      5\nGrey       8\nOrange     3\nRed        2\nViolet     7\nWhite      9\nYellow     4\n\n","human_summarization":"\"Sorts an array of composite structures (name-value pairs) by the key 'name' using a custom comparator. In languages without a built-in sort function, an insertion sort method is implemented.\"","id":958}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 77 and later\nC     WARNING: This program is not valid ANSI FORTRAN 77 code. It uses\nC     one nonstandard character on the line labelled 5001. Many F77\nC     compilers should be okay with it, but it is *not* standard.\n      PROGRAM FORLOOP\n        INTEGER I, J\n\n        DO 20 I = 1, 5\n          DO 10 J = 1, I\nC           Print the asterisk.\n            WRITE (*,5001) '*'\n   10     CONTINUE\nC         Print a newline.\n          WRITE (*,5000) ''\n   20   CONTINUE\n\n        STOP\n\n 5000   FORMAT (A)\nC       Standard FORTRAN 77 is completely incapable of completing a\nC       WRITE statement without printing a newline. If you wanted to\nC       write this program in valid F77, you would have to come up with\nC       a creative way of printing varying numbers of asterisks in a\nC       single write statement.\nC\nC       The dollar sign at the end of the format is a nonstandard\nC       character. It tells the compiler not to print a newline. If you\nC       are actually using FORTRAN 77, you should figure out what your\nC       particular compiler accepts. If you are actually using Fortran\nC       90 or later, you should replace this line with the commented\nC       line that follows it.\n 5001   FORMAT (A, $)\nC5001   FORMAT (A, ADVANCE='NO')\n      END\n\nWorks with: Fortran version 90 and later\nDO i = 1, 5\n  DO j = 1, i\n    WRITE(*, \"(A)\", ADVANCE=\"NO\") \"*\"\n  END DO\n  WRITE(*,*)\nEND DO\n\n\nWorks with: Fortran version 95 and later\ninteger :: i\ninteger, dimension(10) :: v\n\nforall (i=1:size(v)) v(i) = i\n\n\n      DO 1 I = 1,5\n    1 WRITE (6,*) (\"*\", J = 1,I)\n      END\n\n\n      DO 1 I = 1,5\n    1 WRITE (6,2) (666, J = 1,I)\n    2 FORMAT(5I1)\n      END\n\n\n","human_summarization":"demonstrate the use of nested \"for\" loops to print a specific pattern. The number of iterations of the inner loop is controlled by the outer loop. The program also utilizes a loop structure in Fortran 95 that can be used when the result is independent of the real order of execution of the loop. It uses an old-style DO label style of DO-loop and an \"implied\" DO-loop to generate the output list. The output item is a text literal, and if a value cannot fit into its output field, the field is filled with asterisks.","id":959}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nmodule lcgs\n  implicit none\n\n  integer, parameter :: i64 = selected_int_kind(18)\n  integer, parameter :: a1 = 1103515245, a2 = 214013\n  integer, parameter :: c1 = 12345, c2 = 2531011\n  integer, parameter :: div = 65536\n  integer(i64), parameter :: m = 2147483648_i64  ! need to go to 64 bits because\n                                                 ! of the use of signed integers\ncontains \n\nfunction bsdrand(seed)\n  integer :: bsdrand\n  integer, optional, intent(in) :: seed\n  integer(i64) :: x = 0\n  \n  if(present(seed)) x = seed\n  x = mod(a1 * x + c1, m)\n  bsdrand = x\nend function\n\nfunction msrand(seed)\n  integer :: msrand\n  integer, optional, intent(in) :: seed\n  integer(i64) :: x = 0\n \n  if(present(seed)) x = seed \n  x = mod(a2 * x + c2, m)\n  msrand = x \/ div\nend function\nend module\n\nprogram lcgtest\n  use lcgs\n  implicit none\n  integer :: i\n  \n  write(*, \"(a)\") \"      BSD            MS\"\n  do i = 1, 10\n    write(*, \"(2i12)\") bsdrand(), msrand()\n  end do\nend program\n\n\n      BSD            MS\n       12345          38\n  1406932606        7719\n   654583775       21238\n  1449466924        2437\n   229283573        8855\n  1109335178       11797\n  1051550459        8365\n  1293799192       32285\n   794471793       10450\n   551188310       30612\n","human_summarization":"implement two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The sequence of random numbers generated should be the same as the original functions when starting from the same seed. The BSD formula generates numbers in the range 0 to 2147483647, while the Microsoft formula generates numbers in the range 0 to 32767.","id":960}
    {"lang_cluster":"Fortran","source_code":"\n\nelemental subroutine addAfter(nodeBefore,value)\n   type (node), intent(inout) :: nodeBefore\n   real, intent(in)           :: value\n   type (node), pointer       :: newNode\n   \n   allocate(newNode)\n   newNode%data = value\n   newNode%next => nodeBefore%next\n   nodeBefore%next => newNode\nend subroutine addAfter\n\n","human_summarization":"define a method to insert an element into a singly-linked list after a specified element. The method is then used to insert element C into a list comprised of elements A and B, after element A.","id":961}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and laterprogram EthiopicMult\n  implicit none\n\n  print *, ethiopic(17, 34, .true.)\n\ncontains\n\n  subroutine halve(v)\n    integer, intent(inout) :: v\n    v = int(v \/ 2)\n  end subroutine halve\n\n  subroutine doublit(v)\n    integer, intent(inout) :: v\n    v = v * 2\n  end subroutine doublit\n\n  function iseven(x)\n    logical :: iseven\n    integer, intent(in) :: x\n    iseven = mod(x, 2) == 0\n  end function iseven\n\n  function ethiopic(multiplier, multiplicand, tutorialized) result(r)\n    integer :: r\n    integer, intent(in) :: multiplier, multiplicand\n    logical, intent(in), optional :: tutorialized\n\n    integer :: plier, plicand\n    logical :: tutor\n\n    plier = multiplier\n    plicand = multiplicand\n\n    if ( .not. present(tutorialized) ) then\n       tutor = .false.\n    else\n       tutor = tutorialized\n    endif\n\n    r = 0\n\n    if ( tutor ) write(*, '(A, I0, A, I0)') \"ethiopian multiplication of \", plier, \" by \", plicand\n\n    do while(plier >= 1)\n       if ( iseven(plier) ) then\n          if (tutor) write(*, '(I4, \" \", I6, A)') plier, plicand, \" struck\"\n       else\n          if (tutor) write(*, '(I4, \" \", I6, A)') plier, plicand, \" kept\"\n          r = r + plicand\n       endif\n       call halve(plier)\n       call doublit(plicand)\n    end do\n\n  end function ethiopic\n\nend program EthiopicMult\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":962}
    {"lang_cluster":"Fortran","source_code":"\nprogram solve_24\n  use helpers\n  implicit none\n  real                 :: vector(4), reals(4), p, q, r, s\n  integer              :: numbers(4), n, i, j, k, a, b, c, d\n  character, parameter :: ops(4) = (\/ '+', '-', '*', '\/' \/)\n  logical              :: last\n  real,parameter       :: eps = epsilon(1.0)\n\n  do n=1,12\n    call random_number(vector)\n    reals   = 9 * vector + 1\n    numbers = int(reals)\n    call Insertion_Sort(numbers)\n    \n    permutations: do\n      a = numbers(1); b = numbers(2); c = numbers(3); d = numbers(4)\n      reals = real(numbers)\n      p = reals(1);   q = reals(2);   r = reals(3);   s = reals(4)\n      ! combinations of operators:\n      do i=1,4\n        do j=1,4\n          do k=1,4\n            if      ( abs(op(op(op(p,i,q),j,r),k,s)-24.0) < eps ) then\n              write (*,*) numbers, '\u00a0: ', '((',a,ops(i),b,')',ops(j),c,')',ops(k),d\n              exit permutations\n            else if ( abs(op(op(p,i,op(q,j,r)),k,s)-24.0) < eps ) then\n              write (*,*) numbers, '\u00a0: ', '(',a,ops(i),'(',b,ops(j),c,'))',ops(k),d\n              exit permutations\n            else if ( abs(op(p,i,op(op(q,j,r),k,s))-24.0) < eps ) then\n              write (*,*) numbers, '\u00a0: ', a,ops(i),'((',b,ops(j),c,')',ops(k),d,')'\n              exit permutations\n            else if ( abs(op(p,i,op(q,j,op(r,k,s)))-24.0) < eps ) then\n              write (*,*) numbers, '\u00a0: ', a,ops(i),'(',b,ops(j),'(',c,ops(k),d,'))'\n              exit permutations\n            else if ( abs(op(op(p,i,q),j,op(r,k,s))-24.0) < eps ) then\n              write (*,*) numbers, '\u00a0: ', '(',a,ops(i),b,')',ops(j),'(',c,ops(k),d,')'\n              exit permutations\n            end if\n          end do\n        end do\n      end do\n      call nextpermutation(numbers,last)  \n      if ( last ) then\n        write (*,*) numbers, '\u00a0: no solution.'\n        exit permutations\n      end if\n    end do permutations\n\n  end do\n\ncontains\n\n  pure real function op(x,c,y)\n    integer, intent(in) :: c\n    real, intent(in)    :: x,y\n    select case ( ops(c) )\n      case ('+')\n        op = x+y\n      case ('-')\n        op = x-y\n      case ('*')\n        op = x*y\n      case ('\/')\n        op = x\/y\n    end select\n  end function op\n\nend program solve_24\n\nmodule helpers\n\ncontains\n  \n  pure subroutine Insertion_Sort(a)\n    integer, intent(inout) :: a(:)\n    integer                :: temp, i, j\n    do i=2,size(a)\n      j = i-1\n      temp = a(i)\n      do while ( j>=1 .and. a(j)>temp )\n        a(j+1) = a(j)\n        j = j - 1\n      end do\n      a(j+1) = temp\n    end do\n  end subroutine Insertion_Sort\n\n  subroutine nextpermutation(perm,last)\n    integer, intent(inout) :: perm(:)\n    logical, intent(out)   :: last\n    integer :: k,l\n    k = largest1()\n    last = k == 0\n    if ( .not. last ) then    \n      l = largest2(k)\n      call swap(l,k)\n      call reverse(k)\n    end if\n  contains\n    pure integer function largest1()\n      integer :: k, max\n      max = 0\n      do k=1,size(perm)-1\n        if ( perm(k) < perm(k+1) ) then\n          max = k\n        end if\n      end do\n      largest1 = max\n    end function largest1\n\n    pure integer function largest2(k)\n      integer, intent(in) :: k\n      integer             :: l, max\n      max = k+1\n      do l=k+2,size(perm)\n        if ( perm(k) < perm(l) ) then\n          max = l\n        end if\n      end do\n      largest2 = max\n    end function largest2\n\n    subroutine swap(l,k)\n      integer, intent(in) :: k,l\n      integer             :: temp\n      temp    = perm(k)\n      perm(k) = perm(l)\n      perm(l) = temp\n    end subroutine swap\n    \n    subroutine reverse(k)\n      integer, intent(in) :: k\n      integer             :: i\n      do i=1,(size(perm)-k)\/2\n        call swap(k+i,size(perm)+1-i)\n      end do\n    end subroutine reverse\n    \n  end subroutine nextpermutation\n\nend module helpers\n\n\n","human_summarization":"The code accepts four digits, either from user input or randomly generated, and calculates arithmetic expressions following the 24 game rules. It also displays examples of the solutions it generates.","id":963}
    {"lang_cluster":"Fortran","source_code":"\n\nnfactorial = PRODUCT((\/(i, i=1,n)\/))\n\nINTEGER RECURSIVE FUNCTION RECURSIVE_FACTORIAL(X) RESULT(ANS)\n    INTEGER, INTENT(IN)\u00a0:: X\n\n    IF (X <= 1) THEN\n        ANS = 1\n    ELSE\n        ANS = X * RECURSIVE_FACTORIAL(X-1)\n    END IF\n\nEND FUNCTION RECURSIVE_FACTORIAL\n      INTEGER FUNCTION MFACT(N)\n      INTEGER N,I,FACT\n      FACT=1\n      IF (N.EQ.0) GOTO 20\n      DO 10 I=1,N\n        FACT=FACT*I\n10    CONTINUE\n20    CONTINUE\n      MFACT = FACT\n      RETURN\n      END\n","human_summarization":"implement a function that calculates the factorial of a given number, either iteratively or recursively. The function optionally handles negative input errors. The factorial of 0 is defined as 1, and the factorial of a positive integer n is the product of the sequence from n to 1.","id":964}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nmodule bac\n  implicit none\n\ncontains\n\n  subroutine Gennum(n)\n    integer, intent(out) :: n(4)\n    integer :: i, j\n    real :: r\n      \n    call random_number(r)\n    n(1) = int(r * 9.0) + 1\n    i = 2\n    \nouter: do while (i <= 4)\n         call random_number(r)\n         n(i) = int(r * 9.0) + 1\ninner:   do j = i-1 , 1, -1\n           if (n(j) == n(i)) cycle outer\n         end do inner\n         i = i + 1\n       end do outer\n \n  end subroutine Gennum\n\n  subroutine Score(n, guess, b, c) \n    character(*), intent(in) :: guess\n    integer, intent(in) :: n(0:3)\n    integer, intent(out) :: b, c\n    integer :: digit, i, j, ind\n   \n    b = 0; c = 0\n    do i = 1, 4\n      read(guess(i:i), \"(i1)\") digit\n      if (digit == n(i-1)) then\n        b = b + 1\n      else\n        do j = i, i+2\n          ind = mod(j, 4)\n          if (digit == n(ind)) then\n            c = c + 1\n            exit\n          end if\n        end do    \n      end if\n    end do  \n\n end subroutine Score  \n\nend module bac\n\nprogram Bulls_and_Cows\n   use bac\n   implicit none\n   \n   integer :: n(4)\n   integer :: bulls=0, cows=0, tries=0\n   character(4) :: guess\n\n   call random_seed\n   call Gennum(n)\n   \n   write(*,*) \"I have selected a number made up of 4 digits (1-9) without repetitions.\"\n   write(*,*) \"You attempt to guess this number.\"\n   write(*,*) \"Every digit in your guess that is in the correct position scores 1 Bull\"\n   write(*,*) \"Every digit in your guess that is in an incorrect position scores 1 Cow\"\n   write(*,*)\n\n   do while (bulls \/= 4)\n     write(*,*) \"Enter a 4 digit number\"\n     read*, guess\n     if (verify(guess, \"123456789\") \/= 0) then\n       write(*,*) \"That is an invalid entry. Please try again.\"\n       cycle\n     end if\n     tries = tries + 1\n     call Score (n, guess, bulls, cows)\n     write(*, \"(a, i1, a, i1, a)\") \"You scored \", bulls, \" bulls and \", cows, \" cows\"\n     write(*,*)\n   end do\n\n   write(*,\"(a,i0,a)\") \"Congratulations! You correctly guessed the correct number in \", tries, \" attempts\"\n\nend program Bulls_and_Cows\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":965}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nPROGRAM Random\n\n  INTEGER, PARAMETER :: n = 1000\n  INTEGER :: i\n  REAL :: array(n), pi, temp, mean = 1.0, sd = 0.5\n\n  pi = 4.0*ATAN(1.0)\n  CALL RANDOM_NUMBER(array) ! Uniform distribution\n \n! Now convert to normal distribution\n  DO i = 1, n-1, 2\n    temp = sd * SQRT(-2.0*LOG(array(i))) * COS(2*pi*array(i+1)) + mean\n    array(i+1) = sd * SQRT(-2.0*LOG(array(i))) * SIN(2*pi*array(i+1)) + mean\n    array(i) = temp\n  END DO\n\n! Check mean and standard deviation\n  mean = SUM(array)\/n\n  sd = SQRT(SUM((array - mean)**2)\/n)\n \n  WRITE(*, \"(A,F8.6)\") \"Mean = \", mean\n  WRITE(*, \"(A,F8.6)\") \"Standard Deviation = \", sd\n\nEND PROGRAM Random\n\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":966}
    {"lang_cluster":"Fortran","source_code":"\nprogram test_dot_product\n\n  write (*, '(i0)') dot_product ([1, 3, -5], [4, -2, -1])\n\nend program test_dot_product\n\n\n","human_summarization":"implement a function to compute the dot product of two vectors of any length. The vectors must be of the same length. The function multiplies corresponding terms from each vector and sums the products to produce the result. The function can handle various precisions of integer, floating-point and complex arrays, and even logical types.","id":967}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n\nprogram BasicInputLoop\n\n  implicit none\n\n  integer, parameter        :: in = 50, &\n                               linelen = 1000\n  integer                   :: ecode\n  character(len=linelen)    :: l\n\n  open(in, file=\"afile.txt\", action=\"read\", status=\"old\", iostat=ecode)\n  if ( ecode == 0 ) then\n     do\n        read(in, fmt=\"(A)\", iostat=ecode) l\n        if ( ecode \/= 0 ) exit\n        write(*,*) trim(l)\n     end do\n     close(in)\n  end if\n\nend program BasicInputLoop\n\n","human_summarization":"read from a text stream either word-by-word or line-by-line until there's no more data, with a parameter limiting the maximum line length.","id":968}
    {"lang_cluster":"Fortran","source_code":"\nIn ISO Fortran 90 or later, use the SYSTEM_CLOCK intrinsic subroutine:integer :: start, stop, rate\nreal :: result\n      \n! optional 1st integer argument (COUNT) is current raw system clock counter value (not UNIX epoch millis!!)\n! optional 2nd integer argument (COUNT_RATE) is clock cycles per second\n! optional 3rd integer argument (COUNT_MAX) is maximum clock counter value\ncall system_clock( start, rate )\n      \nresult = do_timed_work()\n      \ncall system_clock( stop )\n      \nprint *, \"elapsed time: \", real(stop - start) \/ real(rate)\nIn ISO Fortran 95 or later, use the CPU_TIME intrinsic subroutine:real :: start, stop\nreal :: result\n      \n! System clock value interpreted as floating point seconds\ncall cpu_time( start )\n      \nresult = do_timed_work()\n      \ncall cpu_time( stop )\n      \nprint *, \"elapsed time: \", stop - start\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":969}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nMODULE SEDOL_CHECK\n  IMPLICIT NONE\n  CONTAINS\n \n  FUNCTION Checkdigit(c)\n    CHARACTER :: Checkdigit\n    CHARACTER(6), INTENT(IN) :: c\n    CHARACTER(36) :: alpha = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    INTEGER, DIMENSION(6) :: weights = (\/ 1, 3, 1, 7, 3, 9 \/), temp\n    INTEGER :: i, n\n\n    DO i = 1, 6\n      temp(i) = INDEX(alpha, c(i:i)) - 1\n    END DO\n    temp = temp * weights\n    n = MOD(10 - (MOD(SUM(temp), 10)), 10)  \n    Checkdigit = ACHAR(n + 48)\n  END FUNCTION Checkdigit\n \nEND MODULE SEDOL_CHECK\n\nPROGRAM SEDOLTEST\n  USE SEDOL_CHECK\n  IMPLICIT NONE\n \n  CHARACTER(31) :: valid = \"0123456789BCDFGHJKLMNPQRSTVWXYZ\"\n  CHARACTER(6) :: codes(10) = (\/ \"710889\", \"B0YBKJ\", \"406566\", \"B0YBLH\", \"228276\" ,  &\n                                 \"B0YBKL\", \"557910\", \"B0YBKR\", \"585284\", \"B0YBKT\" \/)\n  CHARACTER(7) :: sedol\n  INTEGER :: i, invalid\n\n  DO i = 1, 10\n    invalid = VERIFY(codes(i), valid)\n    IF (invalid == 0) THEN\n      sedol = codes(i)\n      sedol(7:7) = Checkdigit(codes(i))\n    ELSE\n      sedol = \"INVALID\"\n    END IF\n    WRITE(*, \"(2A9)\") codes(i), sedol\n  END DO\n   \nEND PROGRAM SEDOLTEST\n\n\n  710889  7108899\n  B0YBKJ  B0YBKJ7\n  406566  4065663\n  B0YBLH  B0YBLH2\n  228276  2282765\n  B0YBKL  B0YBKL9\n  557910  5579107\n  B0YBKR  B0YBKR5\n  585284  5852842\n  B0YBKT  B0YBKT7\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end. It also validates the input to ensure it is correctly formed according to the SEDOL string rules.","id":970}
    {"lang_cluster":"Fortran","source_code":"\n\n!-*- mode: compilation; default-directory: \"\/tmp\/\" -*-\n!Compilation started at Fri Jun  6 15:40:18\n!\n!a=.\/f && make -k $a && echo 0 25 | $a && echo 250 265 | $a && echo 1000 1025 | $a\n!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none -g f.f08 -o f\n!                  0'th                  1'st                  2'nd\n!                  3'rd                  4'th                  5'th\n!                  6'th                  7'th                  8'th\n!                  9'th                 10'th                 11'th\n!                 12'th                 13'th                 14'th\n!                 15'th                 16'th                 17'th\n!                 18'th                 19'th                 20'th\n!                 21'st                 22'nd                 23'rd\n!                 24'th                 25'th\n!                                      250'th                251'st\n!                252'nd                253'rd                254'th\n!                255'th                256'th                257'th\n!                258'th                259'th                260'th\n!                261'st                262'nd                263'rd\n!                264'th                265'th\n!                                     1000th                1001st \n!               1002nd                1003rd                1004th \n!               1005th                1006th                1007th \n!               1008th                1009th                1010th \n!               1011th                1012th                1013th \n!               1014th                1015th                1016th \n!               1017th                1018th                1019th \n!               1020th                1021st                1022nd \n!               1023rd                1024th                1025th \n!\n!Compilation finished at Fri Jun  6 15:40:18\n\nprogram nth\n  implicit none\n  logical :: need\n  integer :: here, there, n, i, iostat\n  read(5,*,iostat=iostat) here, there\n  if (iostat .ne. 0) then\n     write(6,*)'such bad input never before seen.'\n     write(6,*)'I AYE EYE QUIT!'\n     call exit(1)\n  end if\n  need = .false.\n  n = abs(there - here) + 1\n  i = 0\n  do while (0 \/= mod(3+mod(here-i, 3), 3))\n     write(6,'(a22)',advance='no') ''\n     i = i+1\n  end do\n  do i = here, there, sign(1, there-here)\n     write(6,'(a22)',advance='no') ordinate(i)\n     if (2 \/= mod(i,3)) then\n        need = .true.\n     else\n        write(6,'(a)')''\n        need = .false.\n     end if\n  end do\n  if (need) write(6,'(a)')''\n\ncontains\n\n  character(len=22) function ordinate(n)\n    character(len=19) :: a\n    character(len=20), parameter :: &\n         &a09 =   \"thstndrdthththththth\",&\n         &ateen = \"thththththththththth\"\n    integer :: ones, tens, ones_index\n    integer, intent(in) :: n\n    write(a,'(i19)') n\n    ones = mod(n,10)\n    tens = mod(n,100)\n    ones_index = ones*2+1\n    if (n < 1000) then\n       if ((10 .le. tens) .and. (tens .lt. 20)) then\n          ordinate = a \/\/ \"'\" \/\/ ateen(ones_index:ones_index+1)\n          !            ^^^^^^  remove these characters to remove the important '\n       else\n          ordinate = a \/\/ \"'\" \/\/ a09(ones_index:ones_index+1)\n          !            ^^^^^^  remove these characters to remove the important '\n       end if\n    else\n       if ((10 .le. tens) .and. (tens .lt. 20)) then\n          ordinate = a \/\/ ateen(ones_index:ones_index+1)\n       else\n          ordinate = a \/\/ a09(ones_index:ones_index+1)\n       end if\n    end if\n  end function ordinate\n\nend program nth\n\n","human_summarization":"The code is a function that takes a non-negative integer as input and returns a string representation of the number with its ordinal suffix, such as 1'st, 2'nd, 3'rd, 11'th, 111'th, 1001'st, 1012'th. It demonstrates its functionality with the integer ranges of 0..25, 250..265, 1000..1025.","id":971}
    {"lang_cluster":"Fortran","source_code":"\nelemental subroutine strip(string,set)\n  character(len=*), intent(inout) :: string\n  character(len=*), intent(in)    :: set\n  integer                         :: old, new, stride\n  old = 1; new = 1\n  do\n    stride = scan( string( old : ), set )\n    if ( stride > 0 ) then\n      string( new : new+stride-2 ) = string( old : old+stride-2 )\n      old = old+stride\n      new = new+stride-1\n    else\n      string( new : ) = string( old : )\n      return\n    end if\n  end do\nend subroutine strip\nNote: Since strip is an elemental subroutine, it can be called with arrays of strings as well.\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":972}
    {"lang_cluster":"Fortran","source_code":"\n\nWith Fortran IV came the ability to use arrays of integers and the A1 format code in READ and WRITE statements for them. With sixteen-bit integers, one might use A2 and so forth, but the numerical values of the integers would not be convenient especially if the sign bit was involved. This would be even more difficult with floating-point variables. Still, the desire for good headings and annotations and flexible layout flogged one onwards. Following the Pascal \"Hello world!\" example, one might proceed somewhat as follows:      INTEGER*4 I,TEXT(66)\n      DATA TEXT(1),TEXT(2),TEXT(3)\/\"Wo\",\"rl\",\"d!\"\/\n\n      WRITE (6,1) (TEXT(I), I = 1,3)\n    1 FORMAT (\"Hello \",66A2)\n\n      DO 2 I = 1,3\n    2   TEXT(I + 3) = TEXT(I)\n      TEXT(1) = \"He\"\n      TEXT(2) = \"ll\"\n      TEXT(3) = \"o \"\n\n      WRITE (6,3) (TEXT(I), I = 1,6)\n    3 FORMAT (66A2)\n      END\n\n\nHaving made space, the next statements merely assign some bit patterns to elements of TEXT, and then the result is revealed, again using known constants instead of the associated variables of the more general approach. The result from the two WRITE statements is of course Hello world!\nHello world!\nWith F77 came the CHARACTER type...       CHARACTER*66 TEXT\n      TEXT = \"World!\"\n      TEXT = \"Hello \"\/\/TEXT\n      WRITE (6,*) TEXT\n      END\n\n\n\n","human_summarization":"The code creates a string variable and assigns it a text value. It then prepends this string variable with another string literal. The code also demonstrates idiomatic ways to prepend a string without referring to the variable twice in one expression. The content of the variable is then displayed. The code also includes handling of text manipulation in Fortran, including the use of arrays, integer constants, and format codes. It also discusses the issues of re-entrancy and the use of a temporary working area for character copying. The code also demonstrates how to shift the content of a string variable to make room for prepending text.","id":973}
    {"lang_cluster":"Fortran","source_code":"\nprogram guess_the_number\n implicit none\n\n integer                          :: guess\n real                             :: r\n integer                          :: i, clock, count, n\n integer,dimension(:),allocatable :: seed\n\n real,parameter :: rmax = 10\t\n\n!initialize random number generator:\n call random_seed(size=n)\n allocate(seed(n))\n call system_clock(count)\n seed = count\n call random_seed(put=seed)\n deallocate(seed)\n\n!pick a random number between 1 and rmax:\n call random_number(r)          !r between 0.0 and 1.0\n i = int((rmax-1.0)*r + 1.0)    !i between 1 and rmax\n\n!get user guess:\n write(*,'(A)') 'I''m thinking of a number between 1 and 10.'\n do   !loop until guess is correct\n\twrite(*,'(A)',advance='NO') 'Enter Guess: '\n\tread(*,'(I5)') guess\n\tif (guess==i) exit\n\twrite(*,*) 'Sorry, try again.'\n end do\n\n write(*,*) 'You''ve guessed my number!'\n\nend program guess_the_number\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":974}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n  character(26) :: alpha\n  integer :: i\n\n  do i = 1, 26\n    alpha(i:i) = achar(iachar('a') + i - 1)\n  end do\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":975}
    {"lang_cluster":"Fortran","source_code":"\n\n!-*- mode: compilation; default-directory: \"\/tmp\/\" -*-\n!Compilation started at Sun May 19 23:14:14\n!\n!a=.\/F && make $a && $a < unixdict.txt\n!f95 -Wall -ffree-form F.F -o F\n!101\n!110010\n!10001100101000\n!\n!Compilation finished at Sun May 19 23:14:14\n!\n!\n!   tobin=: -.&' '@\":@#:\n!   tobin 5\n!101\n!   tobin 50\n!110010\n!   tobin 9000\n!10001100101000\n\nprogram bits\n  implicit none\n  integer, dimension(3) :: a\n  integer :: i\n  data a\/5,50,9000\/\n  do i = 1, 3\n    call s(a(i))\n  enddo\n\ncontains\n\n  subroutine s(a)\n    integer, intent(in) :: a\n    integer :: i\n    if (a .eq. 0) then\n      write(6,'(a)')'0'\n      return\n    endif\n    do i = 31, 0, -1\n      if (btest(a, i)) exit\n    enddo\n    do while (0 .lt. i)\n      if (btest(a, i)) then\n        write(6,'(a)',advance='no')'1'\n      else\n        write(6,'(a)',advance='no')'0'\n      endif\n      i = i-1\n    enddo\n    if (btest(a, i)) then\n      write(6,'(a)')'1'\n    else\n      write(6,'(a)')'0'\n    endif\n  end subroutine s\n\nend program bits\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output is a string of binary digits with no leading zeros, whitespace, radix or sign markers. The function uses either built-in radix functions or a user-defined function to achieve this. After each binary representation, a newline is added. Example inputs and outputs include 5 to '101', 50 to '110010', and 9000 to '10001100101000'.","id":976}
    {"lang_cluster":"Fortran","source_code":"\nprogram readconfig\n  implicit none\n  integer, parameter    :: strlen = 100\n  logical               :: needspeeling = .false., seedsremoved =.false.\n  character(len=strlen) :: favouritefruit = \"\", fullname = \"\", fst, snd\n  character(len=strlen), allocatable :: otherfamily(:), tmp(:)\n  character(len=1000)   :: line\n  integer               :: lun, stat,  j, j0, j1, ii = 1, z\n  integer, parameter    :: state_begin=1, state_in_fst=2, state_in_sep=3\n\n  open(newunit=lun, file=\"config.ini\", status=\"old\")\n  \n  do \n    read(lun, \"(a)\", iostat=stat) line\n    if (stat<0) exit\n    if ((line(1:1) == \"#\") .or. &\n        (line(1:1) == \";\") .or. &\n        (len_trim(line)==0)) then\n      cycle\n    end if\n    z = state_begin\n    do j = 1, len_trim(line)\n      if (z == state_begin) then\n        if (line(j:j)\/=\" \") then\n          j0 = j\n          z = state_in_fst\n        end if\n      elseif (z == state_in_fst) then\n        if (index(\"= \",line(j:j))>0) then\n          fst = lower(line(j0:j-1))\n          z = state_in_sep\n        end if\n      elseif (z == state_in_sep) then\n        if (index(\" =\",line(j:j)) == 0) then\n          snd = line(j:)\n          exit\n        end if\n      else\n         stop \"not possible to be here\"\n      end if\n    end do\n    if (z == state_in_fst) then\n      fst = lower(line(j0:))\n    elseif (z == state_begin) then\n      cycle\n    end if\n\n    if (fst==\"fullname\") then\n      read(snd,\"(a)\") fullname\n    elseif (fst==\"favouritefruit\") then\n      read(snd,\"(a)\") favouritefruit\n    elseif (fst==\"seedsremoved\") then\n      seedsremoved = .true.\n    elseif (fst==\"needspeeling\") then\n      needspeeling = .true.\n    elseif (fst==\"otherfamily\") then\n      j = 1; ii = 1\n      do while (len_trim(snd(j:)) >0)\n        j1  = index(snd(j:),\",\")\n        if (j1==0) then\n          j1 = len_trim(snd)\n        else\n          j1 = j + j1 - 2\n        end if\n        do \n          if (j>len_trim(snd)) exit\n          if (snd(j:j) \/= \" \") exit\n          j = j +1\n        end do\n        allocate(tmp(ii)) \n        tmp(1:ii-1) = otherfamily\n        call move_alloc(tmp, otherfamily)\n        read(snd(j:j1),\"(a)\"), otherfamily(ii)\n        j = j1 + 2 \n        ii = ii + 1\n      end do\n    else \n      print *, \"unknown option '\"\/\/trim(fst)\/\/\"'\"; stop\n    end if\n  end do\n  close(lun)\n\n  print \"(a,a)\",\"fullname = \",       trim(fullname)\n  print \"(a,a)\",\"favouritefruit = \", trim(favouritefruit)\n  print \"(a,l)\",\"needspeeling = \",   needspeeling\n  print \"(a,l)\",\"seedsremoved = \",   seedsremoved\n  print \"(a,*(a,:,', '))\", \"otherfamily = \", &\n         (trim(otherfamily(j)), j=1,size(otherfamily))\n\ncontains\n\npure function lower (str) result (string)\n    implicit none\n    character(*), intent(In) :: str\n    character(len(str))      :: string\n    Integer :: ic, i\n\n    character(26), parameter :: cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n    character(26), parameter :: low = 'abcdefghijklmnopqrstuvwxyz'\n\n    string = str\n    do i = 1, len_trim(str)\n        ic = index(cap, str(i:i))\n        if (ic > 0) string(i:i) = low(ic:ic)\n    end do\nend function \n\nend program\n\n","human_summarization":"read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.","id":977}
    {"lang_cluster":"Fortran","source_code":"\nprogram example\nimplicit none\nreal :: d\n\nd = haversine(36.12,-86.67,33.94,-118.40) ! BNA to LAX\nprint '(A,F9.4,A)', 'distance: ',d,' km' ! distance: 2887.2600 km\n\ncontains\n\n      function to_radian(degree) result(rad)\n          ! degrees to radians\n          real,intent(in) :: degree\n          real, parameter :: deg_to_rad = atan(1.0)\/45 ! exploit intrinsic atan to generate pi\/180 runtime constant\n          real :: rad\n\n          rad = degree*deg_to_rad\n      end function to_radian\n \n      function haversine(deglat1,deglon1,deglat2,deglon2) result (dist)\n          ! great circle distance -- adapted from Matlab \n          real,intent(in) :: deglat1,deglon1,deglat2,deglon2\n          real :: a,c,dist,dlat,dlon,lat1,lat2\n          real,parameter :: radius = 6372.8 \n\n          dlat = to_radian(deglat2-deglat1)\n          dlon = to_radian(deglon2-deglon1)\n          lat1 = to_radian(deglat1)\n          lat2 = to_radian(deglat2)\n          a = (sin(dlat\/2))**2 + cos(lat1)*cos(lat2)*(sin(dlon\/2))**2\n          c = 2*asin(sqrt(a))\n          dist = radius*c\n      end function haversine\n\nend program example\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":978}
    {"lang_cluster":"Fortran","source_code":"\nprogram luhn\n  implicit none\n  integer              :: nargs\n  character(len=20)    :: arg\n  integer              :: alen, i, dr\n  integer, allocatable :: number(:)\n  integer, parameter   :: drmap(0:9) = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]\n\n  ! Get number\n  nargs = command_argument_count()\n  if (nargs \/= 1) then\n     stop\n  end if\n  call get_command_argument(1, arg, alen)\n  allocate(number(alen))\n  do i=1, alen\n     number(alen-i+1) = iachar(arg(i:i)) - iachar('0')\n  end do\n\n  ! Calculate number\n  dr = 0\n  do i=1, alen\n     dr = dr + merge(drmap(number(i)), number(i), mod(i,2) == 0)\n  end do\n\n  if (mod(dr,10) == 0) then\n     write(*,'(a,i0)') arg(1:alen)\/\/' is valid'\n  else\n     write(*,'(a,i0)') arg(1:alen)\/\/' is not valid'\n  end if\nend program luhn\n\n! Results:\n! 49927398716 is valid\n! 49927398717 is not valid\n! 1234567812345678 is not valid\n! 1234567812345670 is valid\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":979}
    {"lang_cluster":"Fortran","source_code":"\n\nprogram josephus\n   implicit none\n   integer :: n, i, k, p\n   integer, allocatable :: next(:)\n   read *, n, k\n   allocate(next(0:n - 1))\n   do i = 0, n - 2\n      next(i) = i + 1\n   end do\n   next(n - 1) = 0\n   p = 0\n   do while(next(p) \/= p)\n      do i = 1, k - 2\n         p = next(p)\n      end do\n      print *, \"Kill\", next(p)\n      next(p) = next(next(p))\n      p = next(p)\n   end do\n   print *, \"Alive\", p\n   deallocate(next)\nend program\n\n","human_summarization":"The code implements the Josephus problem, where given 'n' prisoners and 'k' as the step count, it determines the final survivor. It also provides a way to calculate the position of any prisoner in the killing sequence. The prisoners can be numbered either from 0 to n-1 or 1 to n. The code follows a naive approach where prisoners are put in a linked buffer and iteratively killed until only one remains. The complexity of the operation is O(kn) to find the complete killing sequence and O(m) to find the m-th prisoner to die.","id":980}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram test_repeat\n\n  write (*, '(a)') repeat ('ha', 5)\n\nend program test_repeat\n\n\nhahahahaha\n\n","human_summarization":"Code summarization: The code repeats a given string or character a specified number of times. For example, it can turn \"ha\" repeated 5 times into \"hahahahaha\" or \"*\" repeated 5 times into \"*****\".","id":981}
    {"lang_cluster":"Fortran","source_code":"\n\n INTEGER A, B\n PRINT *, 'Type in two integer numbers separated by white space',\n+         ' and press ENTER'\n READ *, A, B\n PRINT *, '   A + B = ', (A + B)\n PRINT *, '   A - B = ', (A - B)\n PRINT *, '   A * B = ', (A * B)\n PRINT *, '   A \/ B = ', (A \/ B)\n PRINT *, 'MOD(A,B) = ', MOD(A,B)\n PRINT *\n PRINT *, 'Even though you did not ask, ',\n+         'exponentiation is an intrinsic op in Fortran, so...'\n PRINT *, '  A ** B = ', (A ** B)\n END\n\n","human_summarization":"take two integers as input from the user and calculate their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding method for the quotient and the sign of the remainder. It does not include error handling. Additionally, it includes an example of the integer `divmod` operator. The code is written in ANSI FORTRAN 77 or later.","id":982}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram Example\n  implicit none\n  integer :: n\n  \n  n = countsubstring(\"the three truths\", \"th\")\n  write(*,*) n\n  n = countsubstring(\"ababababab\", \"abab\")\n  write(*,*) n\n  n = countsubstring(\"abaabba*bbaba*bbab\", \"a*b\")\n  write(*,*) n\n \ncontains\n\nfunction countsubstring(s1, s2) result(c)\n  character(*), intent(in) :: s1, s2\n  integer :: c, p, posn\n \n  c = 0\n  if(len(s2) == 0) return\n  p = 1\n  do \n    posn = index(s1(p:), s2)\n    if(posn == 0) return\n    c = c + 1\n    p = p + posn + len(s2) - 1\n  end do\nend function\nend program\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":983}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nPROGRAM TOWER\n                             \n  CALL Move(4, 1, 2, 3)\n                \nCONTAINS\n\n  RECURSIVE SUBROUTINE Move(ndisks, from, to, via)\n    INTEGER, INTENT (IN) :: ndisks, from, to, via\n   \n    IF (ndisks == 1) THEN\n       WRITE(*, \"(A,I1,A,I1)\") \"Move disk from pole \", from, \" to pole \", to\n    ELSE\n       CALL Move(ndisks-1, from, via, to)\n       CALL Move(1, from, to, via)\n       CALL Move(ndisks-1, via, to, from)\n    END IF\n  END SUBROUTINE Move\n\nEND PROGRAM TOWER\n\n\nPROGRAM TOWER2\n \n  CALL Move(4, 1, 2, 3)\n \nCONTAINS\n \n  RECURSIVE SUBROUTINE Move(ndisks, from, via, to)\n    INTEGER, INTENT (IN) :: ndisks, from, via, to\n \n    IF (ndisks > 1) THEN\n       CALL Move(ndisks-1, from, to, via)\n       WRITE(*, \"(A,I1,A,I1,A,I1)\") \"Move disk \", ndisks, \"  from pole \", from, \" to pole \", to\n       Call Move(ndisks-1,via,from,to)\n    ELSE\n       WRITE(*, \"(A,I1,A,I1,A,I1)\") \"Move disk \", ndisks, \"  from pole \", from, \" to pole \", to\n    END IF\n  END SUBROUTINE Move\n \nEND PROGRAM TOWER2\n\n","human_summarization":"Implement a recursive solution to solve the Towers of Hanoi problem.","id":984}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram test_choose\n\n  implicit none\n\n  write (*, '(i0)') choose (5, 3)\n\ncontains\n\n  function factorial (n) result (res)\n\n    implicit none\n    integer, intent (in) :: n\n    integer :: res\n    integer :: i\n\n    res = product ((\/(i, i = 1, n)\/))\n\n  end function factorial\n\n  function choose (n, k) result (res)\n\n    implicit none\n    integer, intent (in) :: n\n    integer, intent (in) :: k\n    integer :: res\n\n    res = factorial (n) \/ (factorial (k) * factorial (n - k))\n\n  end function choose\n\nend program test_choose\n\n\n","human_summarization":"The code calculates any binomial coefficient using the given formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which equals 10. The code also handles tasks related to combinations and permutations, both with and without replacement. It uses a method that delays overflow by potentially extending the primes array.","id":985}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nMODULE sort\n\nCONTAINS\n\nSUBROUTINE Shell_Sort(a)\n\n  IMPLICIT NONE\n  INTEGER :: i, j, increment\n  REAL :: temp\n  REAL, INTENT(in out) :: a(:)\n\t\n  increment = SIZE(a) \/ 2\n  DO WHILE (increment > 0)\n      DO i = increment+1, SIZE(a)\n         j = i\n         temp = a(i)\n         DO WHILE (j >= increment+1 .AND. a(j-increment) > temp)\n            a(j) = a(j-increment)\n            j = j - increment\n         END DO\n         a(j) = temp\n      END DO\n      IF (increment == 2) THEN\n   \t  increment = 1\n      ELSE\n         increment = increment * 5 \/ 11\n      END IF      \n  END DO\n \nEND SUBROUTINE Shell_Sort\n\nEND MODULE sort\n\nPROGRAM Shellsort\n\nUSE sort\n\n  IMPLICIT NONE\n  REAL :: array(1000)\n     \n  CALL RANDOM_SEED\n  CALL RANDOM_NUMBER(array)\n \n  WRITE (*,*) \"Unsorted array\"\n  WRITE (*,*) array\n  WRITE (*,*) \n  CALL Shell_Sort(array)\n  WRITE (*,*) \"Sorted array\"\n  WRITE (*,*) array\n  \nEND PROGRAM Shellsort\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":986}
    {"lang_cluster":"Fortran","source_code":"\n\ntype scimage\n   integer, dimension(:,:), pointer :: channel\n   integer :: width, height\nend type scimage\n\n\ninterface alloc_img\n   module procedure alloc_img_rgb, alloc_img_sc\nend interface\n\ninterface free_img\n   module procedure free_img_rgb, free_img_sc\nend interface\n\n\ninterface assignment(=)\n   module procedure rgbtosc, sctorgb\nend interface\n\nsubroutine alloc_img_sc(img, w, h)\n  type(scimage) :: img\n  integer, intent(in) :: w, h\n\n  allocate(img%channel(w, h))\n  img%width = w\n  img%height = h\nend subroutine alloc_img_sc\n\nsubroutine free_img_sc(img)\n  type(scimage) :: img\n\n  if ( associated(img%channel) ) deallocate(img%channel)\nend subroutine free_img_sc\n\nsubroutine rgbtosc(sc, colored)\n  type(rgbimage), intent(in) :: colored\n  type(scimage), intent(inout) :: sc\n\n  if ( ( .not. valid_image(sc) ) .and. valid_image(colored) ) then\n     call alloc_img(sc, colored%width, colored%height)\n  end if\n\n  if ( valid_image(sc) .and. valid_image(colored) ) then\n     sc%channel = floor(0.2126*colored%red + 0.7152*colored%green + &\n                        0.0722*colored%blue)\n  end if\n  \nend subroutine rgbtosc\n\nsubroutine sctorgb(colored, sc)\n  type(scimage), intent(in) :: sc\n  type(rgbimage), intent(inout) :: colored\n\n  if ( ( .not. valid_image(colored) ) .and. valid_image(sc) ) then\n     call alloc_img_rgb(colored, sc%width, sc%height)\n  end if\n\n  if ( valid_image(sc) .and. valid_image(colored) ) then\n     colored%red = sc%channel\n     colored%green = sc%channel\n     colored%blue = sc%channel\n  end if\n\nend subroutine sctorgb\n\n\ntype(scimage) :: gray\ntype(rgbimage) :: animage\n  ! ... here we \"load\" or create animage\n  ! while gray must be created or initialized to null\n  ! or errors can arise...\n  call init_img(gray)\n  gray = animage\n  animage = gray\n  call output_ppm(an_unit, animage)\n\n","human_summarization":"extend the data storage type to support grayscale images, convert a color image to a grayscale image and vice versa. It uses the CIE recommended formula for luminance calculation, ensuring no rounding errors cause run-time problems or distorted results. The codes also rename certain subroutines appending the _rgb suffix for proper overloading, and define new interfaces and subroutines related to the task. An example usage is provided for converting an rgb image to grayscale and back.","id":987}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nINTEGER :: i = 0\nDO \n  i = i + 1\n  WRITE(*, *) i\n  IF (MOD(i, 6) == 0) EXIT\nEND DO\n\nWorks with: Fortran version 77 and later\n      PROGRAM DOWHILE\nC Initialize modulus and value.\n        INTEGER MODLUS, IVALUE\n        PARAMETER (MODLUS = 6)\n        IVALUE = 0\n\nC FORTRAN 77 has no do-while structure -- not semantically. It is not\nC difficult to simulate it using GOTO, however:\n   10   CONTINUE\n          IVALUE = IVALUE + 1\n          WRITE (*,*) IVALUE\n        IF (.NOT. (MOD(IVALUE, MODLUS) .EQ. 0)) GOTO 10\n\n        STOP\n      END\n\nWorks with: Fortran version IV and later\n      IVALUE = 0\n   10 CONTINUE\n        IVALUE=IVALUE+1\n        WRITE(6,301) IVALUE\n  301   FORMAT(I5)          \n      IF(MOD(IVALUE,6).NE.0) GOTO 10\n      END\n\nWorks with: Fortran version I and later\n      IVALUE = 0\n   10 IVALUE=IVALUE+1\n      WRITE 301,IVALUE\n  301 FORMAT(I5)          \n      IF(IVALUE-IVALUE\/6*6) 10,20,10\n   20 STOP\n      END\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":988}
    {"lang_cluster":"Fortran","source_code":"\n\n\n\n","human_summarization":"The code determines the character and byte length of a string, accurately handling encodings like UTF-8. It correctly counts Unicode code points as individual characters, not user-visible graphemes. It also handles Non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. It can also provide string length in graphemes if the language supports it. In Fortran 77, it uses CHARACTER type variables and associated syntax to store character data and uses intrinsic functions like LEN(text) to report the number of characters in the variable. It does not support fancy Unicode schemes.","id":989}
    {"lang_cluster":"Fortran","source_code":"\n\n!-----------------------------------------------------------------------\n! Test Linux urandom in Fortran\n!-----------------------------------------------------------------------\nprogram    urandom_test\n  use iso_c_binding, only : c_long\n  implicit none\n\n  character(len=*), parameter :: RANDOM_PATH = \"\/dev\/urandom\"\n  integer :: funit, ios\n  integer(c_long) :: buf\n\n  open(newunit=funit, file=RANDOM_PATH, access=\"stream\", form=\"UNFORMATTED\", &\n       iostat=ios, status=\"old\", action=\"read\")\n  if ( ios \/= 0 ) stop \"Error opening file: \"\/\/RANDOM_PATH\n\n  read(funit) buf\n\n  close(funit)\n\n  write(*,'(A,I64)') \"Integer:     \", buf\n  write(*,'(A,B64)') \"Binary:      \", buf\n  write(*,'(A,Z64)') \"Hexadecimal: \", buf\n\nend program urandom_test\n\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using the \/dev\/urandom device in a Unix-based system.","id":990}
    {"lang_cluster":"Fortran","source_code":"\nprogram substring\n\n  character(len=5) :: string\n  string = \"Hello\"\n  \n  write (*,*) string\n  write (*,*) string(2:)\n  write (*,*) string( :len(string)-1)\n  write (*,*) string(2:len(string)-1)\n\nend program substring\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":991}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n\nprogram sudoku\n\n  implicit none\n  integer, dimension (9, 9) :: grid\n  integer, dimension (9, 9) :: grid_solved\n  grid = reshape ((\/               &\n    & 0, 0, 3, 0, 2, 0, 6, 0, 0,   &\n    & 9, 0, 0, 3, 0, 5, 0, 0, 1,   &\n    & 0, 0, 1, 8, 0, 6, 4, 0, 0,   &\n    & 0, 0, 8, 1, 0, 2, 9, 0, 0,   &\n    & 7, 0, 0, 0, 0, 0, 0, 0, 8,   &\n    & 0, 0, 6, 7, 0, 8, 2, 0, 0,   &\n    & 0, 0, 2, 6, 0, 9, 5, 0, 0,   &\n    & 8, 0, 0, 2, 0, 3, 0, 0, 9,   &\n    & 0, 0, 5, 0, 1, 0, 3, 0, 0\/), &\n    & shape = (\/9, 9\/),            &\n    & order = (\/2, 1\/))\n  call pretty_print (grid)\n  call solve (1, 1)\n  write (*, *)\n  call pretty_print (grid_solved)\n\ncontains\n\n  recursive subroutine solve (i, j)\n    implicit none\n    integer, intent (in) :: i\n    integer, intent (in) :: j\n    integer :: n\n    integer :: n_tmp\n    if (i > 9) then\n      grid_solved = grid\n    else\n      do n = 1, 9\n        if (is_safe (i, j, n)) then\n          n_tmp = grid (i, j)\n          grid (i, j) = n\n          if (j == 9) then\n            call solve (i + 1, 1)\n          else\n            call solve (i, j + 1)\n          end if\n          grid (i, j) = n_tmp\n        end if\n      end do\n    end if\n  end subroutine solve\n\n  function is_safe (i, j, n) result (res)\n    implicit none\n    integer, intent (in) :: i\n    integer, intent (in) :: j\n    integer, intent (in) :: n\n    logical :: res\n    integer :: i_min\n    integer :: j_min\n    if (grid (i, j) == n) then\n      res = .true.\n      return\n    end if\n    if (grid (i, j) \/= 0) then\n      res = .false.\n      return\n    end if\n    if (any (grid (i, :) == n)) then\n      res = .false.\n      return\n    end if\n    if (any (grid (:, j) == n)) then\n      res = .false.\n      return\n    end if\n    i_min = 1 + 3 * ((i - 1) \/ 3)\n    j_min = 1 + 3 * ((j - 1) \/ 3)\n    if (any (grid (i_min : i_min + 2, j_min : j_min + 2) == n)) then\n      res = .false.\n      return\n    end if\n    res = .true.\n  end function is_safe\n\n  subroutine pretty_print (grid)\n    implicit none\n    integer, dimension (9, 9), intent (in) :: grid\n    integer :: i\n    integer :: j\n    character (*), parameter :: bar = '+-----+-----+-----+'\n    character (*), parameter :: fmt = '(3 (\"|\", i0, 1x, i0, 1x, i0), \"|\")'\n    write (*, '(a)') bar\n    do j = 0, 6, 3\n      do i = j + 1, j + 3\n        write (*, fmt) grid (i, :)\n      end do\n      write (*, '(a)') bar\n    end do\n  end subroutine pretty_print\n\nend program sudoku\n\n\n","human_summarization":"implement a Sudoku solver that fills a given 9x9 grid using a brute force method. The function 'solve' recursively checks for valid entries based on the rules defined in the 'is_safe' function. If 'solve' is called beyond the end of the Sudoku, it means all entered values are valid and the result is displayed.","id":992}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram Knuth_Shuffle\n  implicit none\n\n  integer, parameter :: reps = 1000000\n  integer :: i, n\n  integer, dimension(10) :: a, bins = 0, initial = (\/ (n, n=1,10) \/) \n\n  do i = 1, reps\n    a = initial\n \tcall Shuffle(a)\n    where (a == initial) bins = bins + 1  ! skew tester\n  end do\n  write(*, \"(10(i8))\") bins\n! prints  100382  100007   99783  100231  100507   99921   99941  100270  100290  100442\n\ncontains\n\nsubroutine Shuffle(a)\n  integer, intent(inout) :: a(:)\n  integer :: i, randpos, temp\n  real :: r\n\n  do i = size(a), 2, -1\n    call random_number(r)\n    randpos = int(r * i) + 1\n    temp = a(randpos)\n    a(randpos) = a(i)\n    a(i) = temp\n  end do\n     \nend subroutine Shuffle\n   \nend program Knuth_Shuffle\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":993}
    {"lang_cluster":"Fortran","source_code":"\n\nprogram fridays\n   implicit none\n   integer :: days(1:12) = (\/31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31\/)\n   integer :: year, k, y, m\n   read *, year\n   if (mod(year, 400) == 0 .or. (mod(year, 4) == 0 .and. mod(year, 100) \/= 0)) days(2) = 29\n   y = year - 1\n   k = 44 + y + y\/4 + 6*(y\/100) + y\/400\n   do m = 1, 12\n      k = k + days(m)\n      print \"(I4,A1,I2.2,A1,I2)\", year, '-', m, '-', days(m) - mod(k, 7)\n   end do\nend program\n\n","human_summarization":"The code takes a year as input and calculates the dates of the last Fridays of each month for that year. It starts by determining the day of the week for the last day of January, then adjusts the date backwards to the preceding Friday. This process is repeated for each month. The dates are output in a YYYY-MM-DD format.","id":994}
    {"lang_cluster":"Fortran","source_code":"\nprogram bye\n  write (*,'(a)',advance='no') 'Goodbye, World!'\nend program bye\n\n\n      WRITE (6,1) \"Goodbye, World!\"\n    1 FORMAT (A,$)\n      END\n\n\n","human_summarization":"The code displays the string \"Goodbye, World!\" without a trailing newline. It uses the Fortran 'advance' facility and format instructions to prevent automatic newline insertion after outputting the string. This is useful for writing prompts to the screen where the response input appears on the same line. The code uses a carriage control character to manage line advancement, rather than the typical sequence of outputting text followed by a carriage control.","id":995}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortan 90 and later\nprogram Caesar_Cipher\n  implicit none\n\n  integer, parameter :: key = 3     \n  character(43) :: message = \"The five boxing wizards jump quickly\"\n\n  write(*, \"(2a)\") \"Original message  = \", message\n  call encrypt(message)\n  write(*, \"(2a)\") \"Encrypted message = \", message\n  call decrypt(message)\n  write(*, \"(2a)\") \"Decrypted message = \", message\n  \ncontains\n\nsubroutine encrypt(text)\n  character(*), intent(inout) :: text\n  integer :: i\n  \n  do i = 1, len(text)\n    select case(text(i:i))\n      case ('A':'Z')\n        text(i:i) = achar(modulo(iachar(text(i:i)) - 65 + key, 26) + 65)\n      case ('a':'z')\n        text(i:i) = achar(modulo(iachar(text(i:i)) - 97 + key, 26) + 97)\n    end select\n  end do\nend subroutine\n\nsubroutine decrypt(text)\n  character(*), intent(inout) :: text\n  integer :: i\n  \n  do i = 1, len(text)\n    select case(text(i:i))\n      case ('A':'Z')\n        text(i:i) = achar(modulo(iachar(text(i:i)) - 65 - key, 26) + 65)\n      case ('a':'z')\n        text(i:i) = achar(modulo(iachar(text(i:i)) - 97 - key, 26) + 97)\n    end select\n  end do\nend subroutine\n\nend program Caesar_Cipher\n\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":996}
    {"lang_cluster":"Fortran","source_code":"\n\n    integer function lcm(a,b)\n    integer:: a,b\n        lcm = a*b \/ gcd(a,b)\n    end function lcm\n\n    integer function gcd(a,b)\n    integer :: a,b,t\n        do while (b\/=0)\n            t = b\n            b = mod(a,b)\n            a = t\n        end do\n        gcd = abs(a)\n    end function gcd\n\n","human_summarization":"The code calculates the least common multiple (LCM) of two given integers m and n. The LCM is the smallest positive integer that is a multiple of both m and n. If either m or n is zero, the LCM is zero. The code uses the formula lcm(m, n) = |m x n| \/ gcd(m, n) to calculate the LCM, where gcd is the greatest common divisor. The code can also find the LCM by merging the prime decompositions of both m and n. The solution is implemented as two functions or as a subroutine.","id":997}
    {"lang_cluster":"Fortran","source_code":"\n\nThere is no checking that only valid characters are presented, nor that eight-character codes only are offered, though the compiler might complain if the function were to be invoked with a text literal of the wrong size. In the absence of such checks, there need be no added complications to support a scheme for reporting such errors.       CHARACTER*1 FUNCTION CUSIPCHECK(TEXT)\t!Determines the check sum character.\nCommittee on Uniform Security Identification Purposes, of the American (i.e. USA) Bankers' Association.\n       CHARACTER*8 TEXT\t\t!Specifically, an eight-symbol code.\n       CHARACTER*(*) VALID\t!These only are valid.\n       PARAMETER (VALID = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#\")\n       INTEGER I,V,S\t\t!Assistants.\n        S = 0\t\t!Start the checksum.\n        DO I = 1,LEN(TEXT)\t!Step through the text.\n          V = INDEX(VALID,TEXT(I:I)) - 1\t!Since counting starts with one.\n          IF (MOD(I,2).EQ.0) V = V*2\t\t!V = V*(2 - MOD(I,2))?\n          S = S + V\/10 + MOD(V,10)\t\t!Specified calculation.\n        END DO\t\t\t!On to the next character.\n        I = MOD(10 - MOD(S,10),10) + 1\t!Again, counting starts with one.\n        CUSIPCHECK = VALID(I:I)\t!Thanks to the MOD 10, surely a digit.\n      END FUNCTION CUSIPCHECK\t!No checking for invalid input...\n\n      PROGRAM POKE\t!Just to try it out.\n      INTEGER I,N\t!Assistants.\n      PARAMETER (N = 6)\t\t!A whole lot of blather\n      CHARACTER*9 CUSIP(N)\t!Just to have an array of test codes.\n      DATA CUSIP\/\t\t!Here they are, as specified.\n     1  \"037833100\",\n     2  \"17275R102\",\n     3  \"38259P508\",\n     4  \"594918104\",\n     5  \"68389X106\",\n     6  \"68389X105\"\/\n      CHARACTER*1 CUSIPCHECK\t!Needed as no use of the MODULE protocol.\n\n      DO I = 1,N\t!\"More than two? Use a DO...\"\n        WRITE (6,*) CUSIP(I),CUSIPCHECK(CUSIP(I)(1:8)).EQ.CUSIP(I)(9:9)\n      END DO\n\n      END\n\n\n037833100 T\n17275R102 T\n38259P508 T\n594918104 T\n68389X106 F\n68389X105 T\n\n\n","human_summarization":"The code validates the last digit (check digit) of a CUSIP code, a nine-character alphanumeric code identifying North American financial securities. It uses a sequence of valid characters and a function to find the position of each character in the code. The function returns a character code to be compared with the check character of the CUSIP code. The output is standard and free-format, starting with a space. The code also handles potential issues with ASCII and EBCDIC encodements.","id":998}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and < 2018\n   integer :: i\n   character(len=1) :: c(20)\n   equivalence (c, i)\n\n   WRITE(*,*) bit_size(1)  ! number of bits in the default integer type\n                           ! which may (or may not!) equal the word size\n   i = 1\n\n   IF (ichar(c(1)) == 0) THEN\n      WRITE(*,*) \"Big Endian\"\n   ELSE\n     WRITE(*,*) \"Little Endian\"\n   END IF\n\nWorks with: Fortran version  77 and later\n      PROGRAM endianness\n      IMPLICIT NONE\n      INTEGER(KIND=4)  :: i = 1\n\n      !ISHFT(INTEGER, SHIFT)\u00a0: Left shift if SHIFT > 0\n      !ISHFT(INTEGER, SHIFT)\u00a0: Right shift if SHIFT < 0\n      IF (ISHFT(i,1) .EQ. 0) THEN\n        WRITE(*,FMT='(A)') 'Architechture is Big Endian'\n      ELSE\n        WRITE(*,FMT='(A)') 'Architecture is Little Endian'\n      END IF\n\n      RETURN\n\n      STOP\n      END PROGRAM endianness\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":999}
    {"lang_cluster":"Fortran","source_code":"\nprogram main\n\n implicit none\n\n integer :: i\n character(len=5),dimension(5),parameter :: colors = ['Red  ','Green','Blue ','Black','White']\n\n !using a do loop:\n do i=1,size(colors)\n   write(*,'(A)') colors(i) \n end do\n\n !this will also print each element:\n write(*,'(A)') colors\n\nend program main\n\n","human_summarization":"Iterates through each element in a collection in order and prints it, using a \"for each\" loop or another loop if \"for each\" is not available in the language.","id":1000}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nPROGRAM Example\n\n  CHARACTER(23) :: str = \"Hello,How,Are,You,Today\"\n  CHARACTER(5) :: word(5)\n  INTEGER :: pos1 = 1, pos2, n = 0, i\n\n  DO\n    pos2 = INDEX(str(pos1:), \",\")\n    IF (pos2 == 0) THEN\n       n = n + 1\n       word(n) = str(pos1:)\n       EXIT\n    END IF\n    n = n + 1\n    word(n) = str(pos1:pos1+pos2-2)\n    pos1 = pos2+pos1\n END DO\n\n DO i = 1, n\n   WRITE(*,\"(2A)\", ADVANCE=\"NO\") TRIM(word(i)), \".\"\n END DO\n \nEND PROGRAM Example\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":1001}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 95 and later\nrecursive function gcd_rec(u, v) result(gcd)\n    integer             :: gcd\n    integer, intent(in) :: u, v\n    \n    if (mod(u, v) \/= 0) then\n        gcd = gcd_rec(v, mod(u, v))\n    else\n        gcd = v\n    end if\nend function gcd_rec\n\nsubroutine gcd_iter(value, u, v)\n  integer, intent(out) :: value\n  integer, intent(inout) :: u, v\n  integer :: t\n\n  do while( v \/= 0 )\n     t = u\n     u = v\n     v = mod(t, v)\n  enddo\n  value = abs(u)\nend subroutine gcd_iter\n\n\nfunction gcd(v, t)\n  integer :: gcd\n  integer, intent(in) :: v, t\n  integer :: c, b, a\n\n  b = t\n  a = v\n  do\n     c = mod(a, b)\n     if ( c == 0) exit\n     a = b\n     b = c\n  end do\n  gcd = b ! abs(b)\nend function gcd\n\nsubroutine gcd_bin(value, u, v)\n  integer, intent(out) :: value\n  integer, intent(inout) :: u, v\n  integer :: k, t\n\n  u = abs(u)\n  v = abs(v)\n  if( u < v ) then\n     t = u\n     u = v\n     v = t\n  endif\n  if( v == 0 ) then\n     value = u\n     return\n  endif\n  k = 1\n  do while( (mod(u, 2) == 0).and.(mod(v, 2) == 0) )\n     u = u \/ 2\n     v = v \/ 2\n     k = k * 2\n  enddo\n  if( (mod(u, 2) == 0) ) then\n     t = u\n  else\n     t = -v\n  endif\n  do while( t \/= 0 )\n     do while( (mod(t, 2) == 0) )\n        t = t \/ 2\n     enddo\n     if( t > 0 ) then\n        u = t\n     else\n        v = -t\n     endif\n     t = u - v\n  enddo\n  value = u * k\nend subroutine gcd_bin\n\n\nWorks with: Fortran version 2008\nWorks with: Fortran version 2018\n! Stein\u2019s algorithm implemented in Fortran 2008.\n! Translated from my implementation for ATS\/Postiats.\n\nelemental function gcd (u, v) result (d)\n  implicit none\n  integer, intent(in) :: u, v\n  integer :: d\n\n  integer :: x, y\n\n  ! gcd(x,y) = gcd(u,v), but x and y are non-negative and x <= y.\n  x = min (abs (u), abs (v))\n  y = max (abs (u), abs (v))\n\n  if (x == 0) then\n     d = y\n  else\n     d = gcd_pos_pos (x, y)\n  end if\n\ncontains\n\n  elemental function gcd_pos_pos (u, v) result (d)\n    integer, intent(in) :: u, v\n    integer :: d\n\n    integer :: n\n    integer :: x, y\n    integer :: p, q\n\n    ! n = the number of common factors of two in u and v.\n    n = trailz (ior (u, v))\n\n    ! Remove the common twos from u and v, giving x and y.\n    x = ishft (u, -n)\n    y = ishft (v, -n)\n\n    ! Make both numbers odd. One of the numbers already was odd.\n    ! There is no effect on the value of their gcd.\n    x = ishft (x, -trailz (x))\n    y = ishft (y, -trailz (y))\n\n    do while (x \/= y)\n       ! If x > y then swap x and y, renaming them p\n       ! and q. Thus p <= q, and gcd(p,q) = gcd(x,y).\n       p = min (x, y)\n       q = max (x, y)\n\n       x = p                    ! x remains odd.\n       q = q - p\n       y = ishft (q, -trailz (q)) ! Make y odd again.\n    end do\n\n    ! Put the common twos back in.\n    d = ishft (x, n)\n  end function gcd_pos_pos\n\nend function gcd\n\nprogram test_gcd\n  implicit none\n\n  interface\n     elemental function gcd (u, v) result (d)\n       integer, intent(in) :: u, v\n       integer :: d\n     end function gcd\n  end interface\n\n  write (*, '(\"gcd (0, 0) = \", I0)') gcd (0, 0)\n  write (*, '(\"gcd (0, 10) = \", I0)') gcd (0, 10)\n  write (*, '(\"gcd (-6, -9) = \", I0)') gcd (-6, -9)\n  write (*, '(\"gcd (64 * 5, -16 * 3) = \", I0)') gcd (64 * 5, -16 * 3)\n  write (*, '(\"gcd (40902, 24140) = \", I0)') gcd (40902, 24140)\n  write (*, '(\"gcd (-40902, 24140) = \", I0)') gcd (-40902, 24140)\n  write (*, '(\"gcd (40902, -24140) = \", I0)') gcd (40902, -24140)\n  write (*, '(\"gcd (-40902, -24140) = \", I0)') gcd (-40902, -24140)\n  write (*, '(\"gcd (24140, 40902) = \", I0)') gcd (24140, 40902)\n\nend program test_gcd\n\n\n","human_summarization":"implement functions to find the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. Two versions of the function are provided, one iterative (gcd_iter) and one binary (gcd_bin), with performance times provided for comparison. The code also includes new intrinsic functions for integer operations introduced in Fortran 2008.","id":1002}
    {"lang_cluster":"Fortran","source_code":"\nFUNCTION is_numeric(string)\n  IMPLICIT NONE\n  CHARACTER(len=*), INTENT(IN) :: string\n  LOGICAL :: is_numeric\n  REAL :: x\n  INTEGER :: e\n  READ(string,*,IOSTAT=e) x\n  is_numeric = e == 0\nEND FUNCTION is_numeric\n\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":1003}
    {"lang_cluster":"Fortran","source_code":"\n\nmodule SutherlandHodgmanUtil\n  ! functions and type needed for Sutherland-Hodgman algorithm\n\n  ! --------------------------------------------------------\u00a0!\n  type polygon\n    !type for polygons\n    ! when you define a polygon, the first and the last vertices have to be the same\n    integer :: n\n    double precision, dimension(:,:), allocatable :: vertex\n  end type polygon\n  \n  contains \n  \n  ! --------------------------------------------------------\u00a0!\n  subroutine sutherlandHodgman( ref, clip, outputPolygon )\n    ! Sutherland Hodgman algorithm for 2d polygons\n  \n    ! -- parameters of the subroutine --\n    type(polygon) :: ref, clip, outputPolygon\n  \n    ! -- variables used is the subroutine\n    type(polygon) :: workPolygon               ! polygon clipped step by step \n    double precision, dimension(2) :: y1,y2    ! vertices of edge to clip workPolygon\n    integer :: i  \n  \n    ! allocate workPolygon with the maximal possible size\n    !   the sum of the size of polygon ref and clip\n    allocate(workPolygon%vertex( ref%n+clip%n , 2 ))\n    \n    !  initialise the work polygon with clip\n    workPolygon%n = clip%n\n    workPolygon%vertex(1:workPolygon%n,:) = clip%vertex(1:workPolygon%n,:)\n\n    do i=1,ref%n-1 ! for each edge i of the polygon ref\n      y1(:) = ref%vertex(i,:)   !  vertex 1 of edge i\n      y2(:) = ref%vertex(i+1,:) !  vertex 2 of edge i\n  \n      ! clip the work polygon by edge i\n      call edgeClipping( workPolygon, y1, y2, outputPolygon)\n      ! workPolygon <= outputPolygon\n      workPolygon%n = outputPolygon%n\n      workPolygon%vertex(1:workPolygon%n,:) = outputPolygon%vertex(1:workPolygon%n,:)\n\n    end do \n    deallocate(workPolygon%vertex)\n  end subroutine sutherlandHodgman\n  \n  ! --------------------------------------------------------\u00a0!\n  subroutine edgeClipping( poly, y1, y2, outputPoly )\n    ! make the clipping  of the polygon by the line (x1x2)\n    \n    type(polygon) :: poly, outputPoly\n    double precision, dimension(2) :: y1, y2, x1, x2, intersecPoint\n    integer ::  i, c\n    \n    c = 0 ! counter for the output polygon\n    \n    do i=1,poly%n-1 ! for each edge i of poly\n      x1(:) = poly%vertex(i,:)   ! vertex 1 of edge i\n      x2(:) = poly%vertex(i+1,:) ! vertex 2 of edge i\n      \n      if ( inside(x1, y1, y2) ) then ! if vertex 1 in inside clipping region\n        if ( inside(x2, y1, y2) ) then ! if vertex 2 in inside clipping region\n          ! add the vertex 2 to the output polygon\n          c = c+1\n          outputPoly%vertex(c,:) = x2(:)\n\n        else ! vertex i+1 is outside\n          intersecPoint = intersection(x1, x2, y1,y2)\n          c = c+1\n          outputPoly%vertex(c,:) = intersecPoint(:)\n        end if\n      else ! vertex i is outside\n        if ( inside(x2, y1, y2) ) then\n          intersecPoint = intersection(x1, x2, y1,y2)\n          c = c+1\n          outputPoly%vertex(c,:) = intersecPoint(:)\n          \n          c = c+1\n          outputPoly%vertex(c,:) = x2(:)\n        end if\n      end if\n    end do\n    \n    if (c .gt. 0) then\n      ! if the last vertice is not equal to the first one\n      if ( (outputPoly%vertex(1,1) .ne. outputPoly%vertex(c,1)) .or. & \n           (outputPoly%vertex(1,2) .ne. outputPoly%vertex(c,2)))  then\n        c=c+1\n        outputPoly%vertex(c,:) = outputPoly%vertex(1,:)\n      end if\n    end if\n    ! set the size of the outputPolygon\n    outputPoly%n = c\n  end subroutine edgeClipping\n  \n  ! --------------------------------------------------------\u00a0!\n  function intersection( x1, x2, y1, y2)\n    ! computes the intersection between segment [x1x2] \n    ! and line the line (y1y2) \n\n    ! -- parameters of the function --\n    double precision, dimension(2) :: x1, x2, &  ! points of the segment\n                                      y1, y2     ! points of the line\n    \n    double precision, dimension(2) :: intersection, vx, vy, x1y1 \n    double precision :: a\n  \n    vx(:) = x2(:) - x1(:) \n    vy(:) = y2(:) - y1(:)\n\n    ! if the vectors are colinear\n    if ( crossProduct(vx,vy) .eq. 0.d0) then\n      x1y1(:) = y1(:) - x1(:)\n      ! if the the segment [x1x2] is included in the line (y1y2)\n      if ( crossProduct(x1y1,vx) .eq. 0.d0) then\n        ! the intersection is the last point of the segment\n        intersection(:) = x2(:)\n      end if\n    else ! the vectors are not colinear\n      ! we want to find the inersection between [x1x2]\n      ! and (y1,y2).\n      ! mathematically, we want to find a in [0;1] such\n      ! that\u00a0:\n      !     x1 + a vx = y1 + b vy        \n      ! <=> a vx = x1y1 + b vy\n      ! <=> a vx^vy = x1y1^vy      , ^ is cross product\n      ! <=> a = x1y1^vy \/ vx^vy\n     \n      x1y1(:) = y1(:) - x1(:) \n      ! we compute a\n      a = crossProduct(x1y1,vy)\/crossProduct(vx,vy)\n      ! if a is not in [0;1]\n      if ( (a .gt. 1.d0) .or. (a .lt. 0)) then\n        ! no intersection\n      else\n        intersection(:) = x1(:) + a*vx(:)\n      end if\n    end if\n\n  end function intersection\n  \n  \n  ! --------------------------------------------------------\u00a0!\n  function inside( p, y1, y2)\n    ! function that tells is the point p is at left of the line (y1y2)\n    \n    double precision, dimension(2) :: p, y1, y2, v1, v2\n    logical :: inside\n    v1(:) = y2(:) -  y1(:)\n    v2(:) = p(:)  -  y1(:)  \n    if ( crossProduct(v1,v2) .ge. 0.d0) then\n      inside = .true.\n    else \n      inside = .false.\n    end if\n   \n   contains \n  end function inside\n\n  ! --------------------------------------------------------\u00a0!\n  function dotProduct( v1, v2)\n    ! compute the dot product of vectors v1 and v2\n    double precision, dimension(2) :: v1\n    double precision, dimension(2) :: v2\n    double precision :: dotProduct\n    dotProduct = v1(1)*v2(1) + v1(2)*v2(2)\n  end function dotProduct\n\n  ! --------------------------------------------------------\u00a0!\n  function crossProduct( v1, v2)\n    ! compute the crossproduct of vectors v1 and v2\n    double precision, dimension(2) :: v1\n    double precision, dimension(2) :: v2\n    double precision :: crossProduct\n    crossProduct = v1(1)*v2(2) - v1(2)*v2(1)\n  end function crossProduct\n\nend module SutherlandHodgmanUtil\n\nprogram main\n  \n  ! load the module for S-H algorithm\n  use SutherlandHodgmanUtil, only : polygon, &\n                                    sutherlandHodgman, &\n                                    edgeClipping\n\n  type(polygon) :: p1, p2, res\n  integer :: c, n \n  double precision, dimension(2) :: y1, y2\n  \n  ! when you define a polygon, the first and the last vertices have to be the same\n\n  ! first polygon\n  p1%n = 10\n  allocate(p1%vertex(p1%n,2))\n  p1%vertex(1,1)=50.d0\n  p1%vertex(1,2)=150.d0\n  \n  p1%vertex(2,1)=200.d0\n  p1%vertex(2,2)=50.d0\n  \n  p1%vertex(3,1)= 350.d0\n  p1%vertex(3,2)= 150.d0\n  \n  p1%vertex(4,1)= 350.d0\n  p1%vertex(4,2)= 300.d0\n  \n  p1%vertex(5,1)= 250.d0\n  p1%vertex(5,2)= 300.d0\n  \n  p1%vertex(6,1)= 200.d0\n  p1%vertex(6,2)= 250.d0\n  \n  p1%vertex(7,1)= 150.d0\n  p1%vertex(7,2)= 350.d0\n  \n  p1%vertex(8,1)= 100.d0\n  p1%vertex(8,2)= 250.d0\n  \n  p1%vertex(9,1)= 100.d0\n  p1%vertex(9,2)= 200.d0\n  \n  p1%vertex(10,1)=  50.d0\n  p1%vertex(10,2)= 150.d0\n \n  y1 = (\/ 100.d0, 300.d0 \/)\n  y2 = (\/ 300.d0, 300.d0 \/)\n  \n  ! second polygon\n  p2%n = 5\n  allocate(p2%vertex(p2%n,2))\n\n  p2%vertex(1,1)= 100.d0\n  p2%vertex(1,2)= 100.d0\n  \n  p2%vertex(2,1)= 300.d0\n  p2%vertex(2,2)= 100.d0\n  \n  p2%vertex(3,1)= 300.d0\n  p2%vertex(3,2)= 300.d0\n  \n  p2%vertex(4,1)= 100.d0\n  p2%vertex(4,2)= 300.d0\n  \n  p2%vertex(5,1)= 100.d0\n  p2%vertex(5,2)= 100.d0\n \n  allocate(res%vertex(p1%n+p2%n,2))\n  call sutherlandHodgman( p2, p1, res)\n  write(*,*) \"Suterland-Hodgman\"\n  do c=1, res%n\n    write(*,*) res%vertex(c,1), res%vertex(c,2)\n  end do\n  deallocate(res%vertex)\n\nend program main\n\n\n  Suterland-Hodgman\n  300.00000000000000        300.00000000000000     \n  250.00000000000000        300.00000000000000     \n  200.00000000000000        250.00000000000000     \n  175.00000000000000        300.00000000000000     \n  125.00000000000000        300.00000000000000     \n  100.00000000000000        250.00000000000000     \n  100.00000000000000        200.00000000000000     \n  100.00000000000000        200.00000000000000     \n  100.00000000000000        116.66666666666667     \n  125.00000000000000        100.00000000000000     \n  275.00000000000000        100.00000000000000     \n  300.00000000000000        116.66666666666666     \n  300.00000000000000        300.00000000000000\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The algorithm takes a subject polygon and a clip polygon as inputs, and outputs the intersecting polygon. The subject polygon is defined by a sequence of points and the clip polygon is a rectangle defined by another sequence of points. The program also includes an extra feature to display all three polygons on a graphical surface, each in a different color, and fills the resulting polygon. The polygons are of fortran type with an allocatable array \"vertex\" containing the vertices and an integer n indicating the size of the polygon. The first and last vertices of any polygon are identical. The vertex array of the resulting polygon is allocated with its maximum size in the main function.","id":1004}
    {"lang_cluster":"Fortran","source_code":"\n\nPROGRAM Trig\n\n  REAL pi, dtor, rtod, radians, degrees\n \n  pi = 4.0 * ATAN(1.0)\n  dtor = pi \/ 180.0\n  rtod = 180.0 \/ pi\n  radians = pi \/ 4.0\n  degrees = 45.0 \n \n  WRITE(*,*) SIN(radians), SIN(degrees*dtor)\n  WRITE(*,*) COS(radians), COS(degrees*dtor)\n  WRITE(*,*) TAN(radians), TAN(degrees*dtor)\n  WRITE(*,*) ASIN(SIN(radians)), ASIN(SIN(degrees*dtor))*rtod\n  WRITE(*,*) ACOS(COS(radians)), ACOS(COS(degrees*dtor))*rtod\n  WRITE(*,*) ATAN(TAN(radians)), ATAN(TAN(degrees*dtor))*rtod\n\nEND PROGRAM Trig\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions such as sine, cosine, tangent, and their inverses in a given programming language. The functions are applied to the same angle in both radians and degrees. The code also includes a conversion process for degrees to radians as trigonometric functions expect arguments in radians. The code also handles scenarios where the language does not have built-in trigonometric functions, by implementing these functions based on known approximations or identities. The output also highlights the accuracy issues in calculations with radians due to the representation of pi and conversion factors.","id":1005}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: gfortran\n\nprogram signal_handling\n  use, intrinsic :: iso_fortran_env, only: atomic_logical_kind\n  implicit none\n\n  interface\n    integer(C_INT) function usleep(microseconds) bind(c)\n      use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T\n      integer(C_INT32_T), value :: microseconds\n    end function usleep\n  end interface\n\n  integer, parameter :: half_second = 500000\n  integer, parameter :: sigint = 2\n  integer, parameter :: sigquit = 3\n\n  logical(atomic_logical_kind) :: interrupt_received[*]\n  integer :: half_seconds\n  logical :: interrupt_received_ref\n\n  interrupt_received = .false.\n  half_seconds = 0\n\n  ! \"Install\" the same signal handler for both SIGINT and SIGQUIT.\n  call signal(sigint, signal_handler)\n  call signal(sigquit, signal_handler)\n\n  ! Indefinite loop (until one of the two signals are received).\n  do\n    if (usleep(half_second) == -1) &\n      print *, \"Call to usleep interrupted.\"\n\n    call atomic_ref(interrupt_received_ref, interrupt_received)\n    if (interrupt_received_ref) then\n      print \"(A,I0,A)\", \"Program ran for \", half_seconds \/ 2, \" second(s).\"\n      stop\n    end if\n\n    half_seconds = half_seconds + 1\n    print \"(I0)\", half_seconds\n  end do\n\ncontains\n\n  subroutine signal_handler(sig_num)\n    use, intrinsic :: iso_c_binding, only: C_INT\n    integer(C_INT), value, intent(in) :: sig_num\n    ! Must be declared with attribute `value` to force pass-by-value semantics\n    ! (what C uses by default).\n\n    select case (sig_num)\n      case (sigint)\n        print *, \"Received SIGINT.\"\n      case (sigquit)\n        print *, \"Received SIGQUIT.\"\n    end select\n\n    call atomic_define(interrupt_received, .true.)\n  end subroutine signal_handler\n\nend program signal_handling\n\n","human_summarization":"The code outputs an integer every half second. It handles the SIGINT or SIGQUIT signal, usually triggered by the user pressing ctrl-C or ctrl-\\, respectively. On receiving this signal, the code stops outputting integers, displays the total runtime in seconds, and then terminates. The code utilizes atomic operations enabled by the -fcoarray=single compilation flag.","id":1006}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n\nCHARACTER(10) :: intstr = \"12345\", realstr = \"1234.5\"\nINTEGER :: i\nREAL :: r\n \nREAD(intstr, \"(I10)\") i        ! Read numeric string into integer i\ni = i + 1                      ! increment i\nWRITE(intstr, \"(I10)\") i       ! Write i back to string\n\nREAD(realstr, \"(F10.1)\") r \t\nr = r + 1.0\t\t\t\t\nWRITE(realstr, \"(F10.1)\") r\n\n","human_summarization":"\"Code increments both integer and real numerical strings using 'internal' files.\"","id":1007}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram Median_Test\n\n  real            :: a(7) = (\/ 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 \/), &\n                     b(6) = (\/ 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 \/)\n\n  print *, median(a)\n  print *, median(b)\n\ncontains\n\n  function median(a, found)\n    real, dimension(:), intent(in) :: a\n      ! the optional found argument can be used to check\n      ! if the function returned a valid value; we need this\n      ! just if we suspect our \"vector\" can be \"empty\"\n    logical, optional, intent(out) :: found\n    real :: median\n\n    integer :: l\n    real, dimension(size(a,1)) :: ac\n\n    if ( size(a,1) < 1 ) then\n       if ( present(found) ) found = .false.\n    else\n       ac = a\n       ! this is not an intrinsic: peek a sort algo from\n       ! Category:Sorting, fixing it to work with real if\n       ! it uses integer instead.\n       call sort(ac)\n\n       l = size(a,1)\n       if ( mod(l, 2) == 0 ) then\n          median = (ac(l\/2+1) + ac(l\/2))\/2.0\n       else\n          median = ac(l\/2+1)\n       end if\n\n       if ( present(found) ) found = .true.\n    end if\n\n  end function median\n\nend program Median_Test\n\nIf one refers to Quickselect_algorithm#Fortran which offers function FINDELEMENT(K,A,N) that returns the value of A(K) when the array of N elements has been rearranged if necessary so that A(K) is the K'th in order, then, supposing that a version is devised using the appropriate type for array A,       K = N\/2\n      MEDIAN = FINDELEMENT(K + 1,A,N)\n      IF (MOD(N,2).EQ.0) MEDIAN = (FINDELEMENT(K,A,N) + MEDIAN)\/2\n\n\n","human_summarization":"\"Calculates the median value of a vector of floating-point numbers, handling even number of elements by returning the average of the two middle values. The median is found using the selection algorithm. The function may re-arrange the elements of the array but not fully sort them.\"","id":1008}
    {"lang_cluster":"Fortran","source_code":"\n\nprogram fizzbuzz_if\n   integer\u00a0:: i\n   \n   do i = 1, 100\n      if     (mod(i,15) == 0) then; print *, 'FizzBuzz'\n      else if (mod(i,3) == 0) then; print *, 'Fizz'\n      else if (mod(i,5) == 0) then; print *, 'Buzz'\n      else;                         print *, i\n      end if\n   end do\nend program fizzbuzz_if\n\nprogram FizzBuzz\nimplicit none\ninteger\u00a0:: i = 1\n\ndo i = 1, 100\n    if (Mod(i,3) == 0)write(*,\"(A)\",advance='no')  \"Fizz\"\n    if (Mod(i,5) == 0)write(*,\"(A)\",advance='no') \"Buzz\"\n    if (Mod(i,3) \/= 0 .and. Mod(i,5) \/=0 )write(*,\"(I3)\",advance='no') i\n    print *, \"\"\nend do\nend program FizzBuzz\n\nprogram fizzbuzz_select\n    integer\u00a0:: i\n    \n    do i = 1, 100\n       select case (mod(i,15))\n          case 0;        print *, 'FizzBuzz'\n          case 3,6,9,12; print *, 'Fizz'\n          case 5,10;     print *, 'Buzz'\n          case default;  print *, i\n       end select\n    end do\n end program fizzbuzz_select\n","human_summarization":"The code prints integers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'. It uses structured IF-THEN-ELSE statements in ANSI FORTRAN 77 or later, and SELECT-CASE statement in ISO Fortran 90 or later. The code prints \"Fizz\" and \"Buzz\" together if the number is divisible by both 3 and 5, delaying the line break until after the If statements.","id":1009}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram mandelbrot\n\n  implicit none\n  integer  , parameter :: rk       = selected_real_kind (9, 99)\n  integer  , parameter :: i_max    =  800\n  integer  , parameter :: j_max    =  600\n  integer  , parameter :: n_max    =  100\n  real (rk), parameter :: x_centre = -0.5_rk\n  real (rk), parameter :: y_centre =  0.0_rk\n  real (rk), parameter :: width    =  4.0_rk\n  real (rk), parameter :: height   =  3.0_rk\n  real (rk), parameter :: dx_di    =   width \/ i_max\n  real (rk), parameter :: dy_dj    = -height \/ j_max\n  real (rk), parameter :: x_offset = x_centre - 0.5_rk * (i_max + 1) * dx_di\n  real (rk), parameter :: y_offset = y_centre - 0.5_rk * (j_max + 1) * dy_dj\n  integer, dimension (i_max, j_max) :: image\n  integer   :: i\n  integer   :: j\n  integer   :: n\n  real (rk) :: x\n  real (rk) :: y\n  real (rk) :: x_0\n  real (rk) :: y_0\n  real (rk) :: x_sqr\n  real (rk) :: y_sqr\n\n  do j = 1, j_max\n    y_0 = y_offset + dy_dj * j\n    do i = 1, i_max\n      x_0 = x_offset + dx_di * i\n      x = 0.0_rk\n      y = 0.0_rk\n      n = 0\n      do\n        x_sqr = x ** 2\n        y_sqr = y ** 2\n        if (x_sqr + y_sqr > 4.0_rk) then\n          image (i, j) = 255\n          exit\n        end if\n        if (n == n_max) then\n          image (i, j) = 0\n          exit\n        end if\n        y = y_0 + 2.0_rk * x * y\n        x = x_0 + x_sqr - y_sqr\n        n = n + 1\n      end do\n    end do\n  end do\n  open  (10, file = 'out.pgm')\n  write (10, '(a\/ i0, 1x, i0\/ i0)') 'P2', i_max, j_max, 255\n  write (10, '(i0)') image\n  close (10)\n\nend program mandelbrot\nbs\n","human_summarization":"generate and draw the Mandelbrot set using various available algorithms and functions.","id":1010}
    {"lang_cluster":"Fortran","source_code":"\n\ninteger, dimension(10) :: a = (\/ (i, i=1, 10) \/)\ninteger :: sresult, presult\n\nsresult = sum(a)\npresult = product(a)\n\n","human_summarization":"Computes the sum and product of an array of integers using SUM and PRODUCT intrinsics in ISO Fortran 90 and later.","id":1011}
    {"lang_cluster":"Fortran","source_code":"\nprogram leap\n implicit none\n\n write(*,*) leap_year([1900, 1996, 1997, 2000])\n\n contains\n\n\tpure elemental function leap_year(y) result(is_leap)\n\timplicit none\n\tlogical :: is_leap\n\tinteger,intent(in) :: y\t\n\t\n\tis_leap = (mod(y,4)==0 .and. .not. mod(y,100)==0) .or. (mod(y,400)==0)\t\n\t\n\tend function leap_year\n\t\nend program leap\n\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":1012}
    {"lang_cluster":"Fortran","source_code":"\n\nNote that the syntax enables two classes of labels: the old-style numerical label in columns one to five, and the special label-like prefix of a DO-loop that is not in columns one to five. And yes, a line can have both.       INTEGER P,S,F\t!Department codes for Police, Sanitation, and Fire. Values 1 to 7 only.\n    1  PP:DO P = 2,7,2\t!The police demand an even number. They're special and use violence.\n    2   SS:DO S = 1,7\t\t!The sanitation department accepts any value.\n    3        IF (P.EQ.S) CYCLE SS\t!But it must differ from the others.\n    4        F = 12 - (P + S)\t\t!The fire department accepts any number, but the sum must be twelve.\n    5        IF (F.LE.0 .OR. F.GT.7) CYCLE SS\t!Ensure that the only option is within range.\n    6        IF ((F - S)*(F - P)) 7,8,7\t\t!And F is to differ from S and from P\n    7        WRITE (6,\"(3I2)\") P,S,F\t\t!If we get here, we have a possible set.\n    8      END DO SS\t\t!Next S\n    9    END DO PP\t!Next P.\n      END\t!Well, that was straightforward.\n\n\n 2 3 7\n 2 4 6\n 2 6 4\n 2 7 3\n 4 1 7\n 4 2 6\n 4 3 5\n 4 5 3\n 4 6 2\n 4 7 1\n 6 1 5\n 6 2 4\n 6 4 2\n 6 5 1\n\n","human_summarization":"generate all possible unique combinations of numbers between 1 and 7 for three city departments (police, sanitation, fire) that add up to 12. The police department number is always an even number. The combinations are generated without using a GO TO statement, instead using a DO-loop and CYCLE statement. The program also considers the evaluation of compound boolean expressions.","id":1013}
    {"lang_cluster":"Fortran","source_code":"\nstr2 = str1\n\n\n","human_summarization":"\"Implements a string copy operation, distinguishing between copying the string content and creating an additional reference to the existing string. Handles Fortran's fixed length character strings, padding or truncating as necessary.\"","id":1014}
    {"lang_cluster":"Fortran","source_code":"\n\nWorks with: Fortran version 95 and later\nmodule MutualRec\n  implicit none\ncontains\n  pure recursive function m(n) result(r)\n    integer :: r\n    integer, intent(in) :: n\n    if ( n == 0 ) then\n       r = 0\n       return\n    end if\n    r = n - f(m(n-1))\n  end function m\n  \n  pure recursive function f(n) result(r)\n    integer :: r\n    integer, intent(in) :: n\n    if ( n == 0 ) then\n       r = 1\n       return\n    end if\n    r = n - m(f(n-1))\n  end function f\n\nend module\n\n\nprogram testmutrec\n  use MutualRec\n  implicit none\n\n  integer :: i\n  integer, dimension(20) :: a = (\/ (i, i=0,19) \/), b = (\/ (i, i=0,19) \/)\n  integer, dimension(20) :: ra, rb\n  \n  forall(i=1:20) \n     ra(i) = m(a(i))\n     rb(i) = f(b(i))\n  end forall\n\n  write(*,'(20I3)') rb\n  write(*,'(20I3)') ra\n  \nend program testmutrec\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions are defined such that F(0) = 1, M(0) = 0, F(n) = n - M(F(n-1)) for n > 0, and M(n) = n - F(M(n-1)) for n > 0. The functions are designed to be used within the same module or program block. If they are in different modules, the interface of the other function needs to be loaded. The functions are marked as pure for use in a forall statement.","id":1015}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram pick_random\n  implicit none\n\n  integer :: i\n  integer :: a(10) = (\/ (i, i = 1, 10) \/)\n  real :: r\n\n  call random_seed\n  call random_number(r)\n  write(*,*) a(int(r*size(a)) + 1)\nend program\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":1016}
    {"lang_cluster":"Fortran","source_code":"\n\nrecursive function binarySearch_R (a, value) result (bsresult)\n    real, intent(in) :: a(:), value\n    integer          :: bsresult, mid\n    \n    mid = size(a)\/2 + 1\n    if (size(a) == 0) then\n        bsresult = 0        ! not found\n    else if (a(mid) > value) then\n        bsresult= binarySearch_R(a(:mid-1), value)\n    else if (a(mid) < value) then\n        bsresult = binarySearch_R(a(mid+1:), value)\n        if (bsresult \/= 0) then\n            bsresult = mid + bsresult\n        end if\n    else\n        bsresult = mid      ! SUCCESS!!\n    end if\nend function binarySearch_R\n\n\nfunction binarySearch_I (a, value)\n    integer                  :: binarySearch_I\n    real, intent(in), target :: a(:)\n    real, intent(in)         :: value\n    real, pointer            :: p(:)\n    integer                  :: mid, offset\n    \n    p => a\n    binarySearch_I = 0\n    offset = 0\n    do while (size(p) > 0)\n        mid = size(p)\/2 + 1\n        if (p(mid) > value) then\n            p => p(:mid-1)\n        else if (p(mid) < value) then\n            offset = offset + mid\n            p => p(mid+1:)\n        else\n            binarySearch_I = offset + mid    ! SUCCESS!!\n            return\n        end if\n    end do\nend function binarySearch_I\n\n\n      INTEGER FUNCTION FINDI(X,A,N)\t!Binary chopper. Find i such that X = A(i)\nCareful: it is surprisingly difficult to make this neat, due to vexations when N = 0 or 1.\n       REAL X,A(*)\t\t!Where is X in array A(1:N)?\n       INTEGER N\t\t!The count.\n       INTEGER L,R,P\t\t!Fingers.\n        L = 0\t\t\t!Establish outer bounds, to search A(L+1:R-1).\n        R = N + 1\t\t!L = first - 1; R = last + 1.\n    1   P = (R - L)\/2\t\t!Probe point. Beware INTEGER overflow with (L + R)\/2.\n        IF (P.LE.0) GO TO 5\t!Aha! Nowhere!! The span is empty.\n        P = P + L\t\t!Convert an offset from L to an array index.\n        IF (X - A(P)) 3,4,2\t!Compare to the probe point.\n    2   L = P\t\t\t!A(P) < X. Shift the left bound up: X follows A(P).\n        GO TO 1\t\t\t!Another chop.\n    3   R = P\t\t\t!X < A(P). Shift the right bound down: X precedes A(P).\n        GO TO 1\t\t\t!Try again.\n    4   FINDI = P\t\t!A(P) = X. So, X is found, here!\n       RETURN\t\t\t!Done.\nCurse it!\n    5   FINDI = -L\t\t!X is not found. Insert it at L + 1, i.e. at A(1 - FINDI).\n      END FUNCTION FINDI\t!A's values need not be all different, merely in order.\n\n\n\n      INTEGER FUNCTION FINDI(X,A,N)\t!Binary chopper. Find i such that X = A(i)\nCareful: it is surprisingly difficult to make this neat, due to vexations when N = 0 or 1.\n       REAL X,A(*)\t\t!Where is X in array A(1:N)?\n       INTEGER N\t\t!The count.\n       INTEGER L,R,P\t\t!Fingers.\n        L = 0\t\t\t!Establish outer bounds, to search A(L+1:R-1).\n        R = N + 1\t\t!L = first - 1; R = last + 1.\n        GO TO 1\t\t\t!Hop to it.\n    2   L = P\t\t\t!A(P) < X. Shift the left bound up: X follows A(P).\n    1   P = (R - L)\/2\t\t!Probe point. Beware INTEGER overflow with (L + R)\/2.\n        IF (P.LE.0) GO TO 5\t!Aha! Nowhere!! The span is empty.\n        P = P + L\t\t!Convert an offset from L to an array index.\n        IF (X - A(P)) 3,4,2\t!Compare to the probe point.\n    3   R = P\t\t\t!X < A(P). Shift the right bound down: X precedes A(P).\n        GO TO 1\t\t\t!Try again.\n    4   FINDI = P\t\t!A(P) = X. So, X is found, here!\n       RETURN\t\t\t!Done.\nCurse it!\n    5   FINDI = -L\t\t!X is not found. Insert it at L + 1, i.e. at A(1 - FINDI).\n      END FUNCTION FINDI\t!A's values need not be all different, merely in order.\n\n\n if expression > 0 then optionP\n  else if expression < 0 then optionN\n   else optionZ;\n\n\n if X > 0 then print \"Positive\"\n  else if X > 0 then print \"Still positive\";\n\n\n","human_summarization":"The code implements a binary search algorithm that divides a range of values into halves to find an unknown value. It includes both recursive and iterative versions of the algorithm. The code also handles multiple values equal to the given value and indicates whether the element was found or not. It provides pseudocode for traditional binary search, leftmost insertion point, and rightmost insertion point. The code also ensures no overflow bugs occur when calculating the mean of two integers. It is designed to work with a sorted integer array, returning the index of the found number or a \"not found\" message.","id":1017}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 2003 and later\nprogram command_line_arguments\n\n  implicit none\n  integer, parameter :: len_max = 256\n  integer :: i , nargs\n  character (len_max) :: arg\n  \n  nargs = command_argument_count()\n  !nargs = iargc()\n  do i = 0, nargs\n    call get_command_argument (i, arg)\n    !call getarg (i, arg)\n    write (*, '(a)') trim (arg)\n  end do\n\nend program command_line_arguments\n\n\n> .\/a.out -c \"alpha beta\" -h \"gamma\"\n.\/a.out\n-c\nalpha beta\n-h\ngamma\n\n","human_summarization":"\"Retrieves and prints the list of command-line arguments provided to the program. The program also includes intelligent parsing of these arguments. It utilizes Fortran 2003 intrinsic routines command_argument_count and get_command_argument for this purpose.\"","id":1018}
    {"lang_cluster":"Fortran","source_code":"\n\n!Implemented by Anant Dixit (October, 2014)\nprogram animated_pendulum\nimplicit none\ndouble precision, parameter :: pi = 4.0D0*atan(1.0D0), l = 1.0D-1, dt = 1.0D-2, g = 9.8D0\ninteger :: io\ndouble precision :: s_ang, c_ang, p_ang, n_ang\n\nwrite(*,*) 'Enter starting angle (in degrees):'\ndo\n  read(*,*,iostat=io) s_ang\n  if(io.ne.0 .or. s_ang.lt.-90.0D0 .or. s_ang.gt.90.0D0) then\n    write(*,*) 'Please enter an angle between 90 and -90 degrees:'\n  else\n    exit\n  end if\nend do\ncall execute_command_line('cls')\n\nc_ang = s_ang*pi\/180.0D0\np_ang = c_ang\n\ncall display(c_ang)\ndo\n  call next_time_step(c_ang,p_ang,g,l,dt,n_ang)\n  if(abs(c_ang-p_ang).ge.0.05D0) then\n    call execute_command_line('cls')\n    call display(c_ang)\n  end if\nend do\nend program\n\nsubroutine next_time_step(c_ang,p_ang,g,l,dt,n_ang)\ndouble precision :: c_ang, p_ang, g, l, dt, n_ang\nn_ang = (-g*sin(c_ang)\/l)*2.0D0*dt**2 + 2.0D0*c_ang - p_ang\np_ang = c_ang\nc_ang = n_ang\nend subroutine\n\nsubroutine display(c_ang)\ndouble precision :: c_ang\ncharacter (len=*), parameter :: cfmt = '(A1)'\ndouble precision :: rx, ry\ninteger :: x, y, i, j\nrx = 45.0D0*sin(c_ang)\nry = 22.5D0*cos(c_ang)\nx = int(rx)+51\ny = int(ry)+2\ndo i = 1,32\n  do j = 1,100\n    if(i.eq.y .and. j.eq.x) then\n      write(*,cfmt,advance='no') 'O'\n    else if(i.eq.y .and. (j.eq.(x-1).or.j.eq.(x+1))) then\n      write(*,cfmt,advance='no') 'G'\n    else if(j.eq.x .and. (i.eq.(y-1).or.i.eq.(y+1))) then\n      write(*,cfmt,advance='no') 'G'\n    else if(i.eq.y .and. (j.eq.(x-2).or.j.eq.(x+2))) then\n      write(*,cfmt,advance='no') '#'\n    else if(j.eq.x .and. (i.eq.(y-2).or.i.eq.(y+2))) then\n      write(*,cfmt,advance='no') 'G'\n    else if((i.eq.(y+1).and.j.eq.(x+1)) .or. (i.eq.(y-1).and.j.eq.(x-1))) then\n      write(*,cfmt,advance='no') '#'\n    else if((i.eq.(y+1).and.j.eq.(x-1)) .or. (i.eq.(y-1).and.j.eq.(x+1))) then\n      write(*,cfmt,advance='no') '#'\n    else if(j.eq.50) then\n      write(*,cfmt,advance='no') '|'\n    else if(i.eq.2) then\n      write(*,cfmt,advance='no') '-'\n    else\n      write(*,cfmt,advance='no') ' '\n    end if\n  end do\n  write(*,*)\nend do\nend subroutine\n\n\n                                                 |                                                  \n-------------------------------------------------|--------------------------------------------------\n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                G                                 \n                                                 |               #G#                                \n                                                 |              #GOG#                               \n                                                 |               #G#                                \n                                                 |                G                                 \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n\n\n\n                                                 |                                                  \n-------------------------------------------------|--------------------------------------------------\n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                       G                          \n                                                 |                      #G#                         \n                                                 |                     #GOG#                        \n                                                 |                      #G#                         \n                                                 |                       G                          \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n\n\n\n                                                 |                                                  \n-------------------------------------------------|--------------------------------------------------\n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                            G                     \n                                                 |                           #G#                    \n                                                 |                          #GOG#                   \n                                                 |                           #G#                    \n                                                 |                            G                     \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n\n\n\n                                                 |                                                  \n-------------------------------------------------|--------------------------------------------------\n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                 G                \n                                                 |                                #G#               \n                                                 |                               #GOG#              \n                                                 |                                #G#               \n                                                 |                                 G                \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n\n\n\n                                                 |                                                  \n-------------------------------------------------|--------------------------------------------------\n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                     G            \n                                                 |                                    #G#           \n                                                 |                                   #GOG#          \n                                                 |                                    #G#           \n                                                 |                                     G            \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n\n\n\n                                                 |                                                  \n-------------------------------------------------|--------------------------------------------------\n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                       G          \n                                                 |                                      #G#         \n                                                 |                                     #GOG#        \n                                                 |                                      #G#         \n                                                 |                                       G          \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n\n\n\n                                                 |                                                  \n-------------------------------------------------|--------------------------------------------------\n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                         G        \n                                                 |                                        #G#       \n                                                 |                                       #GOG#      \n                                                 |                                        #G#       \n                                                 |                                         G        \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n\n\n\n                                                 |                                                  \n-------------------------------------------------|--------------------------------------------------\n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                          G       \n                                                 |                                         #G#      \n                                                 |                                        #GOG#     \n                                                 |                                         #G#      \n                                                 |                                          G       \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n                                                 |                                                  \n\n\n","human_summarization":"The code simulates and animates a simple gravity pendulum. It uses system commands to clear the screen and allows an initial starting angle between -90 and 90 degrees, checking for incorrect inputs. It also provides a small preview of the pendulum's motion with an example of an initial angle of 80 degrees.","id":1019}
    {"lang_cluster":"Fortran","source_code":"\n\n{\n  \"PhoneBook\": [\n    {\n      \"name\": \"Adam\",\n      \"phone\": \"0000001\"\n    },\n    {\n      \"name\": \"Eve\",\n      \"phone\": \"0000002\"\n    },\n    {\n      \"name\": \"Julia\",\n      \"phone\": \"6666666\"\n    }\n  ]\n}\n\nprogram json_fortran\n   use json_module\n   implicit none\n\n   type phonebook_type\n      character(len=:),allocatable :: name\n      character(len=:),allocatable :: phone\n   end type phonebook_type\n\n   type(phonebook_type), dimension(3) :: PhoneBook\n   integer :: i\n   type(json_value),pointer :: json_phonebook,p,e\n   type(json_file) :: json\n\n   PhoneBook(1) % name = 'Adam'\n   PhoneBook(2) % name = 'Eve'\n   PhoneBook(3) % name = 'Julia'\n   PhoneBook(1) % phone = '0000001'\n   PhoneBook(2) % phone = '0000002'\n   PhoneBook(3) % phone = '6666666'\n\n   call json_initialize()\n\n   !create the root structure:\n   call json_create_object(json_phonebook,'')\n\n   !create and populate the phonebook array:\n   call json_create_array(p,'PhoneBook')\n   do i=1,3\n      call json_create_object(e,'')\n      call json_add(e,'name',PhoneBook(i)%name)\n      call json_add(e,'phone',PhoneBook(i)%phone)\n      call json_add(p,e) !add this element to array\n      nullify(e) !cleanup for next loop\n   end do\n   call json_add(json_phonebook,p) !add p to json_phonebook\n   nullify(p) !no longer need this\n\n   !write it to a file:\n   call json_print(json_phonebook,'phonebook.json')\n\n   ! read directly from a character string\n   call json%load_from_string('{ \"PhoneBook\": [ { \"name\": \"Adam\", \"phone\": \"0000001\" },&\n   { \"name\": \"Eve\", \"phone\": \"0000002\" }, { \"name\": \"Julia\", \"phone\": \"6666666\" } ]}')\n   ! print it to the console\n   call json%print_file()\n\nend program json_fortran\n\n","human_summarization":"\"Loads a JSON string into a data structure, creates a new data structure, serializes it into JSON using objects and arrays, and validates the JSON using json-fortran library and jsonformatter.org. It also includes functionality for creating a JSON example file and reading a JSON string.\"","id":1020}
    {"lang_cluster":"Fortran","source_code":"\nprogram NthRootTest\n  implicit none\n\n  print *, nthroot(10, 7131.5**10)\n  print *, nthroot(5, 34.0)\n\ncontains\n\n  function nthroot(n, A, p)\n    real :: nthroot\n    integer, intent(in)        :: n\n    real, intent(in)           :: A\n    real, intent(in), optional :: p\n\n    real :: rp, x(2)\n\n    if ( A < 0 ) then\n       stop \"A < 0\"       ! we handle only real positive numbers\n    elseif ( A == 0 ) then\n       nthroot = 0\n       return\n    end if\n\n    if ( present(p) ) then\n       rp = p\n    else\n       rp = 0.001\n    end if\n\n    x(1) = A\n    x(2) = A\/n   ! starting \"guessed\" value...\n\n    do while ( abs(x(2) - x(1)) > rp )\n       x(1) = x(2)\n       x(2) = ((n-1.0)*x(2) + A\/(x(2) ** (n-1.0)))\/real(n)\n    end do\n\n    nthroot = x(2)\n\n  end function nthroot\n\nend program NthRootTest\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":1021}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: gfortran\n\nprogram HostTest\n  character(len=128) :: name \n  call hostnm(name)\n  print *, name\nend program HostTest\n\n\nprogram test_hostname\n   use, intrinsic  :: iso_c_binding\n   implicit none\n   interface !to function: int gethostname(char *name, size_t namelen);\n      integer(c_int) function gethostname(name, namelen) bind(c)\n         use, intrinsic  :: iso_c_binding, only: c_char, c_int, c_size_t\n         integer(c_size_t), value, intent(in) :: namelen\n         character(len=1,kind=c_char), dimension(namelen),  intent(inout) ::  name\n      end function gethostname\n   end interface\n   integer(c_int) :: status\n   integer,parameter :: HOST_NAME_MAX=255\n   character(kind=c_char,len=1),dimension(HOST_NAME_MAX) :: cstr_hostname\n   integer(c_size_t) :: lenstr\n   character(len=:),allocatable :: hostname\n   lenstr = HOST_NAME_MAX\n   status = gethostname(cstr_hostname, lenstr)\n   hostname = c_to_f_string(cstr_hostname)\n   write(*,*) hostname, len(hostname)\n\n contains\n   ! convert c_string to f_string\n   pure function c_to_f_string(c_string) result(f_string)\n      use, intrinsic :: iso_c_binding, only: c_char, c_null_char\n      character(kind=c_char,len=1), intent(in) :: c_string(:)\n      character(len=:), allocatable :: f_string\n      integer i, n\n      i = 1\n      do\n         if (c_string(i) == c_null_char) exit\n         i = i + 1\n      end do\n      n = i - 1  ! exclude c_null_char\n      allocate(character(len=n) :: f_string)\n      f_string = transfer(c_string(1:n), f_string)\n   end function c_to_f_string\n\nend program test_hostname\n\n","human_summarization":"The code uses the HOSTNM subroutine, a GNU extension, to find the name of the host where the routine is running. It utilizes Fortran 2003 C-interoperability to directly call the posix C function gethostname, a unix system call.","id":1022}
    {"lang_cluster":"Fortran","source_code":"\n\nThe method relies on producing a sequence of values, rather than calculating L(n) from the start each time a value from the sequence is required.       SUBROUTINE LEONARDO(LAST,L0,L1,AF)\t!Show the first LAST values of the sequence.\n       INTEGER LAST\t!Limit to show.\n       INTEGER L0,L1\t!Starting values.\n       INTEGER AF\t!The \"Add factor\" to deviate from Fibonacci numbers.\n       OPTIONAL AF\t!Indicate that this parameter may be omitted.\n       INTEGER EMBOLISM\t!The bloat to employ.\n       INTEGER N,LN,LNL1,LNL2\t!Assistants to the calculation.\n        IF (PRESENT(AF)) THEN\t!Perhaps the last parameter has not been given.\n          EMBOLISM = AF\t\t\t!It has. Take its value.\n         ELSE\t\t\t!But if not,\n          EMBOLISM = 1\t\t\t!This is the specified default.\n        END IF\t\t\t!Perhaps there should be some report on this?\n        WRITE (6,1) LAST,L0,L1,EMBOLISM\t!Announce.\n    1   FORMAT (\"The first \",I0,\t!The I0 format code avoids excessive spacing.\n     1   \" numbers in the Leonardo sequence defined by L(0) = \",I0,\n     2   \" and L(1) = \",I0,\" with L(n) = L(n - 1) + L(n - 2) + \",I0)\n        IF (LAST .GE. 1) WRITE (6,2) L0\t!In principle, LAST may be small.\n        IF (LAST .GE. 2) WRITE (6,2) L1\t!!So, suspicion rules.\n    2   FORMAT (I0,\", \",$)\t!Obviously, the $ sez \"don't finish the line\".\n        LNL1 = L0\t!Syncopation for the sequence's initial values.\n        LN = L1\t\t!Since the parameters ought not be damaged.\n        DO N = 3,LAST\t!Step away.\n          LNL2 = LNL1\t\t!Advance the two state variables one step.\n          LNL1 = LN\t\t!Ready to make a step forward.\n          LN = LNL1 + LNL2 + EMBOLISM\t!Thus.\n          WRITE (6,2) LN\t!Reveal the value. Overflow is distant...\n        END DO\t\t!On to the next step.\n        WRITE (6,*)\t!Finish the line.\n      END SUBROUTINE LEONARDO\t!Only speedy for the sequential production of values.\n\n      PROGRAM POKE\n\n      CALL LEONARDO(25,1,1,1)\t!The first 25 Leonardo numbers.\n      CALL LEONARDO(25,0,1,0)\t!Deviates to give the Fibonacci sequence.\n      END\n\n\nThe first 25 numbers in the Leonardo sequence defined by L(0) = 1 and L(1) = 1 with L(n) = L(n - 1) + L(n - 2) + 1\n1, 1, 3, 5, 9, 15, 25, 41, 67, 109, 177, 287, 465, 753, 1219, 1973, 3193, 5167, 8361, 13529, 21891, 35421, 57313, 92735, 150049,\nThe first 25 numbers in the Leonardo sequence defined by L(0) = 0 and L(1) = 1 with L(n) = L(n - 1) + L(n - 2) + 0\n0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368,\n\n","human_summarization":"The code calculates and displays the first 25 Leonardo numbers, starting from L(0). It allows the first two Leonardo numbers (L(0) and L(1)) and the add number to be specified, with 1 as the default value for the add number. The code also shows the first 25 Leonardo numbers when 0 and 1 are specified for L(0) and L(1) respectively, and 0 for the add number, which results in the Fibonacci sequence. The code uses 32-bit integers and the F90 facilities for subroutine naming and integer formatting. The code also handles optional parameters.","id":1023}
    {"lang_cluster":"Fortran","source_code":"\n\nprogram game_24\n  implicit none\n  real               :: vector(4), reals(11), result, a, b, c, d\n  integer            :: numbers(4), ascii(11), i\n  character(len=11)  :: expression\n  character          :: syntax(11)\n  ! patterns:\n  character, parameter :: one(11)   = (\/ '(','(','1','x','1',')','x','1',')','x','1' \/)\n  character, parameter :: two(11)   = (\/ '(','1','x','(','1','x','1',')',')','x','1' \/)\n  character, parameter :: three(11) = (\/ '1','x','(','(','1','x','1',')','x','1',')' \/)\n  character, parameter :: four(11)  = (\/ '1','x','(','1','x','(','1','x','1',')',')' \/)\n  character, parameter :: five(11)  = (\/ '(','1','x','1',')','x','(','1','x','1',')' \/)\n  \n  do\n    call random_number(vector)\n    numbers = 9 * vector + 1\n    write (*,*) 'Digits: ',numbers\n    write (*,'(a)',advance='no') 'Your expression: '\n    read (*,'(a11)') expression\n\n    forall (i=1:11) syntax(i) = expression(i:i)\n    ascii = iachar(syntax)\n    where (syntax >= '0' .and. syntax <= '9')\n      syntax = '1'  ! number\n    elsewhere (syntax == '+' .or. syntax == '-' .or. syntax == '*' .or. syntax == '\/')\n      syntax = 'x'  ! op\n    elsewhere (syntax \/= '(' .and. syntax \/= ')')\n      syntax = '-'  ! error\n    end where\n\n    reals = real(ascii-48)\n    if ( all(syntax == one) ) then\n      a = reals(3); b = reals(5); c = reals(8); d = reals(11)\n      call check_numbers(a,b,c,d)\n      result = op(op(op(a,4,b),7,c),10,d)\n    else if ( all(syntax == two) ) then\n      a = reals(2); b = reals(5); c = reals(7); d = reals(11)\n      call check_numbers(a,b,c,d)\n      result = op(op(a,3,op(b,6,c)),10,d)\n    else if ( all(syntax == three) ) then\n      a = reals(1); b = reals(5); c = reals(7); d = reals(10)\n      call check_numbers(a,b,c,d)\n      result = op(a,2,op(op(b,6,c),9,d))\n    else if ( all(syntax == four) ) then\n      a = reals(1); b = reals(4); c = reals(7); d = reals(9)\n      call check_numbers(a,b,c,d)\n      result = op(a,2,op(b,5,op(c,8,d)))\n    else if ( all(syntax == five) ) then\n      a = reals(2); b = reals(4); c = reals(8); d = reals(10)\n      call check_numbers(a,b,c,d)\n      result = op(op(a,3,b),6,op(c,9,d))\n    else\n      stop 'Input string: incorrect syntax.'\n    end if\n\n    if ( abs(result-24.0) < epsilon(1.0) ) then\n      write (*,*) 'You won!'\n    else\n      write (*,*) 'Your result (',result,') is incorrect!'\n    end if\n  \n    write (*,'(a)',advance='no') 'Another one? [y\/n] '\n    read (*,'(a1)') expression\n    if ( expression(1:1) == 'n' .or. expression(1:1) == 'N' ) then\n      stop\n    end if  \n  end do\n  \ncontains\n\n  pure real function op(x,c,y)\n    integer, intent(in) :: c\n    real, intent(in) :: x,y\n    select case ( char(ascii(c)) )\n      case ('+')\n        op = x+y\n      case ('-')\n        op = x-y\n      case ('*')\n        op = x*y\n      case ('\/')\n        op = x\/y\n    end select\n  end function op\n  \n  subroutine check_numbers(a,b,c,d)\n    real, intent(in) :: a,b,c,d\n    integer          :: test(4)\n    test = (\/ nint(a),nint(b),nint(c),nint(d) \/)\n    call Insertion_Sort(numbers)\n    call Insertion_Sort(test)\n    if ( any(test \/= numbers) ) then\n      stop 'You cheat\u00a0;-) (Incorrect numbers)'\n    end if\n  end subroutine check_numbers\n  \n  pure subroutine Insertion_Sort(a)\n    integer, intent(inout) :: a(:)\n    integer                :: temp, i, j\n    do i=2,size(a)\n      j = i-1\n      temp = a(i)\n      do while ( j>=1 .and. a(j)>temp )\n        a(j+1) = a(j)\n        j = j - 1\n      end do\n      a(j+1) = temp\n    end do\n  end subroutine Insertion_Sort\n\nend program game_24\n\n\n! implement a recursive descent parser\nmodule evaluate_algebraic_expression\n\n  integer, parameter :: size = 124\n  character, parameter :: statement_end = achar(0)\n  character(len=size) :: text_to_parse\n  integer :: position\n  data position\/0\/,text_to_parse\/' '\/\n\ncontains\n\n  character function get_token()\n    ! return the current token\n    implicit none\n    if (position <= size) then\n       get_token = text_to_parse(position:position)\n       do while (get_token <= ' ')\n          call advance\n          if (size < position) exit\n          get_token = text_to_parse(position:position)\n       end do\n    end if\n    if (size < position) get_token = statement_end\n  end function get_token\n\n  subroutine advance ! consume a token.  Move to the next token.  consume_token would have been a better name.\n    position = position + 1    \n  end subroutine advance\n  \n  logical function unfinished()\n    unfinished = get_token() \/= statement_end\n  end function unfinished\n\n  subroutine parse_error()\n    write(6,*)'\"'\/\/get_token()\/\/'\" unexpected in expression at',position\n    stop 1\n  end subroutine parse_error\n\n  function precedence3() result(a)\n    implicit none\n    real :: a\n    character :: token\n    character(len=10), parameter :: digits = '0123456789'\n    token = get_token()\n    if (verify(token,digits) \/= 0) call parse_error()\n    a = index(digits, token) - 1\n    call advance()\n  end function precedence3\n\n  recursive function precedence2() result(a)\n    real :: a\n    character :: token\n    token = get_token()\n    if (token \/= '(') then\n       a = precedence3()\n    else\n       call advance\n       a = precedence0()\n       token = get_token()\n       if (token \/= ')') call parse_error()\n       call advance\n    end if\n  end function precedence2\n\n  recursive function precedence1() result(a)\n    implicit none\n    real :: a\n    real, dimension(2) :: argument\n    character(len=2), parameter :: tokens = '*\/'\n    character :: token\n    a = 0\n    token = get_token()\n    argument(1) = precedence2()\n    token = get_token()\n    do while (verify(token,tokens) == 0)\n       call advance()\n       argument(2) = precedence2()\n       if (token == '\/') argument(2) = 1 \/ argument(2)\n       argument(1) = product(argument)       \n       token = get_token()\n    end do\n    a = argument(1)\n  end function precedence1\n\n  recursive function precedence0() result(a)\n    implicit none\n    real :: a\n    real, dimension(2) :: argument\n    character(len=2), parameter :: tokens = '+-'\n    character :: token\n    a = 0\n    token = get_token()\n    argument(1) = precedence1()\n    token = get_token()\n    do while (verify(token,tokens) == 0)\n       call advance()\n       argument(2) = precedence1()\n       if (token == '-') argument = argument * (\/1, -1\/)\n       argument(1) = sum(argument)\n       token = get_token()\n    end do\n    a = argument(1)\n  end function precedence0\n\n  real function statement()\n    implicit none\n    if (unfinished()) then\n       statement = precedence0()\n    else                        !empty okay\n       statement = 0\n    end if\n    if (unfinished()) call parse_error()\n  end function statement\n\n  real function evaluate(expression)\n    implicit none\n    character(len=*), intent(in) :: expression\n    text_to_parse = expression\n    evaluate = statement()\n  end function evaluate\n  \nend module evaluate_algebraic_expression\n\n\nprogram g24\n  use evaluate_algebraic_expression\n  implicit none\n  integer, dimension(4) :: digits\n  character(len=78) :: expression\n  real :: result\n  ! integer\u00a0:: i\n  call random_seed!easily found internet examples exist to seed by \/dev\/urandom or time\n  call deal(digits)\n  ! do i=1, 9999\u00a0! produce the data to test digit distribution\n  !   call deal(digits)\n  !   write(6,*) digits\n  ! end do\n  write(6,'(a13,4i2,a26)')'Using digits',digits,', and the algebraic dyadic'\n  write(6,*)'operators +-*\/() enter an expression computing 24.'\n  expression = ' '\n  read(5,'(a78)') expression\n  if (invalid_digits(expression, digits)) then\n     write(6,*)'invalid digits'\n  else\n     result = evaluate(expression)\n     if (nint(result) == 24) then\n        write(6,*) result, ' close enough'\n     else\n        write(6,*) result, ' no good'\n     end if\n  end if\n\ncontains\n\n  logical function invalid_digits(e,d) !verify the digits\n    implicit none\n    character(len=*), intent(in) :: e\n    integer, dimension(4), intent(inout) :: d\n    integer :: i, j, k, count\n    logical :: unfound\n    count = 0\n    invalid_digits = .false. !validity assumed\n    !write(6,*)'expression:',e(1:len_trim(e))\n    do i=1, len_trim(e)\n       if (verify(e(i:i),'0123456789') == 0) then\n          j = index('0123456789',e(i:i))-1\n          unfound = .true.\n          do k=1, 4\n             if (j == d(k)) then\n                unfound = .false.\n                exit\n             end if\n          end do\n          if (unfound) then\n             invalid_digits = .true.\n             !return or exit is okay here\n          else\n             d(k) = -99\n             count = count + 1\n          end if\n       end if\n    end do\n    invalid_digits = invalid_digits .or. (count \/= 4)\n  end function invalid_digits\n\n  subroutine deal(digits)\n    implicit none\n    integer, dimension(4), intent(out) :: digits\n    integer :: i\n    real :: harvest\n    call random_number(harvest)\n    do i=1, 4\n       digits(i) = int(mod(harvest*9**i, 9.0))   + 1\n    end do\n    !    NB. computed with executable Iverson notation, www.jsoftware.oom\n    !    #B NB. B are the digits from 9999 deals\n    ! 39996\n    !    ({.,#)\/.~\/:~B  # show the distribution of digits\n    ! 0 4380\n    ! 1 4542\n    ! 2 4348\n    ! 3 4395\n    ! 4 4451\n    ! 5 4474\n    ! 6 4467\n    ! 7 4413\n    ! 8 4526\n    !    NB. this also shows that I forgot to add 1.  Inserting now...\n  end subroutine deal\nend program g24\n\n\n$ gfortran -g -O0 -std=f2008 -Wall f.f08 -o f.exe && echo '8*(9\/9+2)' | .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n   24.000000      close enough\n$ \n$ \n$ \n$ .\/f.exe \n$  Using digits 9 9 8 2, and the algebraic dyadic\n$  operators +-*\/() enter an expression computing 24.\n$     8 *   ( 9 \/ 9  +    2   )\n$    24.000000      close enough\n$ \n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n(((2+8+9+9)))\n   28.000000      no good\n$ \n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n(((8+9-2+9)))\n   24.000000      close enough\n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n8929\n \"9\" unexpected in expression at           2\nSTOP 1\n$ \n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n12348\n invalid digits\n$ \n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n892\n invalid digits\n$ \n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n8921\n invalid digits\n$ \n$ \n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n89291\n invalid digits\n$ \n$ \n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n9+x-2+8+9\n \"x\" unexpected in expression at           3\nSTOP 1\n$ \n$ \n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n(9-2)+8+(9\n \"^@\" unexpected in expression at         125\nSTOP 1\n$ \n$ \n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n(9-2)+8+(9)\n   24.000000      close enough\n$ \n$ \n$ \n$ .\/f.exe\n Using digits 9 9 8 2, and the algebraic dyadic\n operators +-*\/() enter an expression computing 24.\n(9-2)+8\/(9)\n   7.8888888      no good\n$ \n\n","human_summarization":"The code generates four random digits from 1 to 9 and prompts the player to form an arithmetic expression using these digits exactly once. The expression should evaluate to 24 using the operators: addition, subtraction, multiplication, and division. The code checks and evaluates the player's input expression, ensuring that the digit order is not necessarily preserved and multiple-digit numbers are not formed from the given digits. The code uses an expression evaluator, which could be an RPN evaluator, and Insertion_sort in Fortran. It also handles operator precedence, spaces, and arbitrary parentheses.","id":1024}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 95 and later\nprogram RLE\n  implicit none\n\n  integer, parameter :: bufsize = 100   ! Sets maximum size of coded and decoded strings, adjust as necessary\n  character(bufsize) :: teststr = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\n  character(bufsize) :: codedstr = \"\", decodedstr = \"\"\n    \n  call Encode(teststr, codedstr)\n  write(*,\"(a)\") trim(codedstr)\n  call Decode(codedstr, decodedstr)\n  write(*,\"(a)\") trim(decodedstr)\n\ncontains\n\nsubroutine Encode(instr, outstr)\n  character(*), intent(in)  :: instr\n  character(*), intent(out) :: outstr\n  character(8) :: tempstr = \"\"\n  character(26) :: validchars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n  integer :: a, b, c, i\n\n  if(verify(trim(instr), validchars) \/= 0) then\n    outstr = \"Invalid input\"\n    return\n  end if\n  outstr = \"\"\n  c = 1\n  a = iachar(instr(1:1))\n  do i = 2, len(trim(instr))\n    b = iachar(instr(i:i))\n    if(a == b) then\n      c = c + 1\n    else\n      write(tempstr, \"(i0)\") c\n      outstr = trim(outstr) \/\/ trim(tempstr) \/\/ achar(a)\n      a = b\n      c = 1\n    end if\n  end do\n  write(tempstr, \"(i0)\") c\n  outstr = trim(outstr) \/\/ trim(tempstr) \/\/ achar(b)\nend subroutine\n\nsubroutine Decode(instr, outstr)\n  character(*), intent(in)  :: instr\n  character(*), intent(out) :: outstr\n  character(26) :: validchars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n  integer :: startn, endn, n\n\n  outstr = \"\"\n  startn = 1\n  do while(startn < len(trim(instr)))\n    endn = scan(instr(startn:), validchars) + startn - 1\n    read(instr(startn:endn-1), \"(i8)\") n\n    outstr = trim(outstr) \/\/ repeat(instr(endn:endn), n)\n    startn = endn + 1\n  end do\nend subroutine\nend program\n\n\n12W1B12W3B24W1B14W\nWWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\n\n","human_summarization":"implement a run-length encoding algorithm that compresses a string of uppercase characters by storing the length of consecutive identical characters, and also provide a function to reverse this compression.","id":1025}
    {"lang_cluster":"Fortran","source_code":"\nprogram StringConcatenation\n\ninteger, parameter          :: maxstringlength = 64\ncharacter (maxstringlength) :: s1, s = \"hello\"\n\nprint *,s \/\/ \" literal\"\ns1 = trim(s) \/\/ \" literal\"\nprint *,s1\n\nend program\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":1026}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram KNAPSACK_CONTINUOUS\n  implicit none\n \n  real, parameter :: maxweight = 15.0\n  real :: total_weight = 0, total_value = 0, frac\n  integer :: i, j\n  \n  type Item\n    character(7) :: name\n    real :: weight\n    real :: value\n  end type Item\n\n  type(Item) :: items(9), temp\n  \n  items(1) = Item(\"beef\",    3.8, 36.0)\n  items(2) = Item(\"pork\",    5.4, 43.0)\n  items(3) = Item(\"ham\",     3.6, 90.0)\n  items(4) = Item(\"greaves\", 2.4, 45.0)\n  items(5) = Item(\"flitch\",  4.0, 30.0)\n  items(6) = Item(\"brawn\",   2.5, 56.0)\n  items(7) = Item(\"welt\",    3.7, 67.0)\n  items(8) = Item(\"salami\",  3.0, 95.0)\n  items(9) = Item(\"sausage\", 5.9, 98.0)\n\n  ! sort items in descending order of their value per unit weight\n  do i = 2, size(items)\n     j = i - 1\n     temp = items(i)\n     do while (j>=1 .and. items(j)%value \/ items(j)%weight < temp%value \/ temp%weight)\n       items(j+1) = items(j)\n       j = j - 1\n     end do\n    items(j+1) = temp\n  end do\n \n  i = 0\n  write(*, \"(a4, a13, a6)\") \"Item\", \"Weight\", \"Value\"\n  do while(i < size(items) .and. total_weight < maxweight)\n    i = i + 1\n    if(total_weight+items(i)%weight < maxweight) then\n      total_weight = total_weight + items(i)%weight\n      total_value = total_value + items(i)%value\n      write(*, \"(a7, 2f8.2)\") items(i)\n    else\n      frac = (maxweight-total_weight) \/ items(i)%weight\n      total_weight = total_weight + items(i)%weight * frac\n      total_value = total_value + items(i)%value * frac\n      write(*, \"(a7, 2f8.2)\") items(i)%name, items(i)%weight * frac, items(i)%value * frac\n    end if \n  end do\n\n  write(*, \"(f15.2, f8.2)\") total_weight, total_value\n \nend program KNAPSACK_CONTINUOUS\n\n","human_summarization":"determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.","id":1027}
    {"lang_cluster":"Fortran","source_code":"\n\n!***************************************************************************************\n\tmodule anagram_routines\n!***************************************************************************************\n\timplicit none\n\t\n\t!the dictionary file:\n\tinteger,parameter :: file_unit = 1000\n\tcharacter(len=*),parameter :: filename = 'unixdict.txt'\n\t\n\t!maximum number of characters in a word:\n\tinteger,parameter :: max_chars = 50\n\t\n\t!maximum number of characters in the string displaying the anagram lists:\n\tinteger,parameter :: str_len = 256\n\t\n\ttype word \n\t  character(len=max_chars) :: str = repeat(' ',max_chars)    !the word from the dictionary\n\t  integer                  :: n = 0                          !length of this word\n\t  integer                  :: n_anagrams = 0\t             !number of anagrams found\n\t  logical                  :: checked = .false.              !if this one has already been checked\n\t  character(len=str_len)   :: anagrams = repeat(' ',str_len) !the anagram list for this word\n\tend type word\n\t\n\t!the dictionary structure:\n\ttype(word),dimension(:),allocatable,target :: dict\n\t\n\tcontains\n!***************************************************************************************\n\n\t!******************************************************************************\n\t\tfunction count_lines_in_file(fid) result(n_lines)\n\t!******************************************************************************\n\t\timplicit none\n\t\n\t\tinteger             :: n_lines\n\t\tinteger,intent(in)  :: fid\t\t\n\t\tcharacter(len=1)    :: tmp\n\t\tinteger             :: i\n\t\tinteger             :: ios\n\t\t\n\t\t!the file is assumed to be open already.\n\t\t\n\t\trewind(fid)\t  !rewind to beginning of the file\n\t\t\n\t\tn_lines = 0\n\t\tdo !read each line until the end of the file.\n\t\t\tread(fid,'(A1)',iostat=ios) tmp\n\t\t\tif (ios < 0) exit      !End of file\n\t\t\tn_lines = n_lines + 1  !row counter\n\t\tend do\n\n\t\trewind(fid)   !rewind to beginning of the file\t\n\t\t\t\t\n\t!******************************************************************************\n\t\tend function count_lines_in_file\n\t!******************************************************************************\n\t\n\t!******************************************************************************\n\t\tpure elemental function is_anagram(x,y)\n\t!******************************************************************************\n\t\timplicit none\n\t\tcharacter(len=*),intent(in) :: x\n\t\tcharacter(len=*),intent(in) :: y\n\t\tlogical :: is_anagram\n\t\n\t\tcharacter(len=len(x)) :: x_tmp\t!a copy of x\n\t\tinteger :: i,j\n\t\t\n\t\t!a character not found in any word:\n\t\tcharacter(len=1),parameter :: null = achar(0)\n\t\t\t\n\t\t!x and y are assumed to be the same size.\n\t\t\n\t\tx_tmp = x\n\t\tdo i=1,len_trim(x)\n\t\t\tj = index(x_tmp, y(i:i)) !look for this character in x_tmp\n\t\t\tif (j\/=0) then\n\t\t\t\tx_tmp(j:j) = null  !clear it so it won't be checked again\n\t\t\telse\n\t\t\t\tis_anagram = .false. !character not found: x,y are not anagrams\n\t\t\t\treturn\n\t\t\tend if\n\t\tend do\n\t\n\t\t!if we got to this point, all the characters \n\t\t! were the same, so x,y are anagrams:\n\t\tis_anagram = .true.\n\t\t\t\t\t\n\t!******************************************************************************\n\t\tend function is_anagram\n\t!******************************************************************************\n\n!***************************************************************************************\n\tend module anagram_routines\n!***************************************************************************************\n\n!***************************************************************************************\n\tprogram main\n!***************************************************************************************\n\tuse anagram_routines\n\timplicit none\n\t\n\tinteger :: n,i,j,n_max\n\ttype(word),pointer :: x,y\n\tlogical :: first_word\n\treal :: start, finish\n\t\n\tcall cpu_time(start)\t!..start timer\n\t\n\t!open the dictionary and read in all the words:\n\topen(unit=file_unit,file=filename)      !open the file\n\tn = count_lines_in_file(file_unit)      !count lines in the file\n\tallocate(dict(n))                       !allocate dictionary structure\n\tdo i=1,n                                !\n\t\tread(file_unit,'(A)') dict(i)%str   !each line is a word in the dictionary\n\t\tdict(i)%n = len_trim(dict(i)%str)   !saving length here to avoid trim's below\n\tend do\t\t\n\tclose(file_unit)                        !close the file\n\t\n\t!search dictionary for anagrams:\n\tdo i=1,n\n\t\t\n\t\tx => dict(i)\t!pointer to simplify code\n\t\tfirst_word = .true.\t!initialize\n\t\t\n\t\tdo j=i,n\n\t\t\n\t\t\ty => dict(j)\t!pointer to simplify code\n\t\t\t\n\t\t\t!checks to avoid checking words unnecessarily:\n\t\t\tif (x%checked .or. y%checked) cycle     !both must not have been checked already\n\t\t\tif (x%n\/=y%n) cycle                     !must be the same size\n\t\t\tif (x%str(1:x%n)==y%str(1:y%n)) cycle   !can't be the same word\n\t\t\t\n\t\t\t! check to see if x,y are anagrams:\n\t\t\tif (is_anagram(x%str(1:x%n), y%str(1:y%n))) then\n\t\t\t\t!they are anagrams.\n\t\t\t\ty%checked = .true. \t!don't check this one again.\n\t\t\t\tx%n_anagrams = x%n_anagrams + 1\n\t\t\t\tif (first_word) then\n\t\t\t\t\t!this is the first anagram found for this word.\n\t\t\t\t\tfirst_word = .false.\n\t\t\t\t\tx%n_anagrams = x%n_anagrams + 1\n\t\t\t\t\tx%anagrams = trim(x%anagrams)\/\/x%str(1:x%n)  !add first word to list\n\t\t\t\tend if\n\t\t\t\tx%anagrams = trim(x%anagrams)\/\/','\/\/y%str(1:y%n) !add next word to list\n\t\t\tend if\n\t\n\t\tend do\n\t\tx%checked = .true.  !don't check this one again\n\t\t \n\tend do\n\t\n\t!anagram groups with the most words:\n\twrite(*,*) ''\n\tn_max = maxval(dict%n_anagrams)\n\tdo i=1,n\n\t\tif (dict(i)%n_anagrams==n_max) write(*,'(A)') trim(dict(i)%anagrams)\n\tend do\n\t\n\t!anagram group containing longest words:\n\twrite(*,*) ''\n\tn_max = maxval(dict%n, mask=dict%n_anagrams>0)\n\tdo i=1,n\n\t\tif (dict(i)%n_anagrams>0 .and. dict(i)%n==n_max) write(*,'(A)') trim(dict(i)%anagrams)\n\tend do\n\twrite(*,*) ''\n\n\tcall cpu_time(finish)\t!...stop timer\n\twrite(*,'(A,F6.3,A)') '[Runtime = ',finish-start,' sec]'\n\twrite(*,*) ''\n\n!***************************************************************************************\n\tend program main\n!***************************************************************************************\n\n\n","human_summarization":"\"Output: The code identifies sets of words from the provided URL that are anagrams of each other, specifically focusing on those sets with the most words.\"","id":1028}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and laterprogram Sierpinski_carpet\n  implicit none\n  \n  call carpet(4)\n\ncontains\n\nfunction In_carpet(a, b)\n  logical :: in_carpet\n  integer, intent(in) :: a, b\n  integer :: x, y\n\n  x = a ; y = b\n  do \n    if(x == 0 .or. y == 0) then\n      In_carpet = .true.\n      return\n    else if(mod(x, 3) == 1 .and. mod(y, 3) == 1) then\n      In_carpet = .false.\n      return\n    end if\n    x = x \/ 3\n    y = y \/ 3\n  end do\nend function\n\nsubroutine Carpet(n)\n  integer, intent(in) :: n\n  integer :: i, j\n \n  do i = 0, 3**n - 1 \n    do j = 0, 3**n - 1\n      if(In_carpet(i, j)) then\n        write(*, \"(a)\", advance=\"no\") \"#\"\n      else\n        write(*, \"(a)\", advance=\"no\") \" \"\n      end if\n    end do\n    write(*,*)\n  end do\nend subroutine Carpet\nend program Sierpinski_carpet\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":1029}
    {"lang_cluster":"Fortran","source_code":"\n! output:\n! d-> 00000, t-> 00001, h-> 0001, s-> 0010, \n! c-> 00110, x-> 00111, m-> 0100, o-> 0101, \n! n-> 011, u-> 10000, l-> 10001, a-> 1001, \n! r-> 10100, g-> 101010, p-> 101011, \n! e-> 1011, i-> 1100, f-> 1101,  -> 111\n!\n! 00001|0001|1100|0010|111|1100|0010|111|1001|011|\n! 111|1011|00111|1001|0100|101011|10001|1011|111|\n! 1101|0101|10100|111|0001|10000|1101|1101|0100|\n! 1001|011|111|1011|011|00110|0101|00000|1100|011|101010|\n!\nmodule huffman\nimplicit none\ntype node\n  character (len=1 ), allocatable :: sym(:)\n  character (len=10), allocatable :: code(:) \n  integer                         :: freq\ncontains\n  procedure                       :: show => show_node\nend type\n\ntype queue\n  type(node), allocatable :: buf(:)\n  integer                 :: n = 0\ncontains\n  procedure :: extractmin\n  procedure :: append\n  procedure :: siftdown\nend type\n\ncontains\n\nsubroutine siftdown(this, a)\n  class (queue)           :: this\n  integer                 :: a, parent, child\n  associate (x => this%buf)\n  parent = a\n  do while(parent*2 <= this%n)\n    child = parent*2\n    if (child + 1 <= this%n) then \n      if (x(child+1)%freq < x(child)%freq ) then\n        child = child +1 \n      end if\n    end if\n    if (x(parent)%freq > x(child)%freq) then\n      x([child, parent]) = x([parent, child])\n      parent = child\n    else\n      exit\n    end if  \n  end do      \n  end associate\nend subroutine\n\nfunction extractmin(this) result (res)\n  class(queue) :: this\n  type(node)   :: res\n  res = this%buf(1)\n  this%buf(1) = this%buf(this%n)\n  this%n = this%n - 1\n  call this%siftdown(1)\nend function\n\nsubroutine append(this, x)\n  class(queue), intent(inout) :: this\n  type(node)                  :: x\n  type(node), allocatable     :: tmp(:)\n  integer                     :: i\n  this%n = this%n +1  \n  if (.not.allocated(this%buf)) allocate(this%buf(1))\n  if (size(this%buf) ',g0,:,', '))\", advance=\"no\") &\n   (this%sym(i), trim(this%code(i)), i=1,size(this%sym))\n  print *\nend subroutine\n\nfunction create(letter, freq) result (this)\n  character :: letter\n  integer   :: freq\n  type(node) :: this\n  allocate(this%sym(1), this%code(1))\n  this%sym(1) = letter ; this%code(1) = \"\"\n  this%freq = freq\nend function\nend module \n\nprogram main\n  use huffman\n  character (len=*), parameter   :: txt = &\n   \"this is an example for huffman encoding\"\n  integer                        :: i, freq(0:255) = 0\n  type(queue)                    :: Q\n  type(node)                     :: x\n  do i = 1, len(txt)\n    freq(ichar(txt(i:i))) = freq(ichar(txt(i:i))) + 1 \n  end do\n  do i = 0, 255\n    if (freq(i)>0) then\n      call Q%append(create(char(i), freq(i)))\n    end if\n  end do\n  do i = 1, Q%n-1\n    call Q%append(join(Q%extractmin(),Q%extractmin()))\n  end do\n  x = Q%extractmin()\n  call x%show()\n  do i = 1, len(txt) \n    do k = 1, size(x%sym)\n      if (x%sym(k)==txt(i:i)) exit\n     end do\n     write (*, \"(a,'|')\", advance=\"no\")  trim(x%code(k))\n  end do\n  print *\nend program\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":1030}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nDO i = 10, 0, -1\n  WRITE(*, *) i\nEND DO\n\nWorks with: Fortran version 77 and later\n      PROGRAM DOWNWARDFOR\nC Initialize the loop parameters.\n        INTEGER I, START, FINISH, STEP\n        PARAMETER (START = 10, FINISH = 0, STEP = -1)\n\nC If you were to leave off STEP, it would default to positive one.\n        DO 10 I = START, FINISH, STEP\n          WRITE (*,*) I\n   10   CONTINUE\n\n        STOP\n      END\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":1031}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 95 and later\nprogram vigenere_cipher\n  implicit none\n  \n  character(80) :: plaintext = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\", &\n                   ciphertext = \"\"\n  character(14) :: key = \"VIGENERECIPHER\"\n\n\n  call encrypt(plaintext, ciphertext, key)\n  write(*,*) plaintext\n  write(*,*) ciphertext\n  call decrypt(ciphertext, plaintext, key)\n  write(*,*) plaintext\n\ncontains\n\nsubroutine encrypt(intxt, outtxt, k)\n  character(*), intent(in)  :: intxt, k\n  character(*), intent(out) :: outtxt\n  integer :: chrn\n  integer :: cp = 1, kp = 1\n  integer :: i\n  \n  outtxt = \"\"\n  do i = 1, len(trim(intxt))\n    select case(intxt(i:i))\n      case (\"A\":\"Z\", \"a\":\"z\")\n        select case(intxt(i:i))\n          case(\"a\":\"z\")\n            chrn = iachar(intxt(i:i)) - 32\n   \n          case default\n            chrn = iachar(intxt(i:i))\n                         \n        end select\n     \n        outtxt(cp:cp) = achar(modulo(chrn + iachar(k(kp:kp)), 26) + 65)\n        cp = cp + 1\n        kp = kp + 1\n        if(kp > len(k)) kp = kp - len(k)\n \n    end select\n  end do\nend subroutine\n\nsubroutine decrypt(intxt, outtxt, k)\n  character(*), intent(in)  :: intxt, k\n  character(*), intent(out) :: outtxt\n  integer :: chrn\n  integer :: cp = 1, kp = 1\n  integer :: i\n  \n  outtxt = \"\"\n  do i = 1, len(trim(intxt))\n    chrn = iachar(intxt(i:i))\n    outtxt(cp:cp) = achar(modulo(chrn - iachar(k(kp:kp)), 26) + 65)\n    cp = cp + 1\n    kp = kp + 1\n    if(kp > len(k)) kp = kp - len(k)\n   end do\nend subroutine\nend program\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters and discard non-alphabetic ones. If non-alphabetic characters are handled differently, it is noted.","id":1032}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\ndo i = 1,10,2\n   print *, i\nend do\n\nWorks with: Fortran version 77 and later\n      PROGRAM STEPFOR\n        INTEGER I\n\nC       This will print all even numbers from -10 to +10, inclusive.\n        DO 10 I = -10, 10, 2\n          WRITE (*,*) I\n   10   CONTINUE\n\n        STOP\n      END\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":1033}
    {"lang_cluster":"Fortran","source_code":"\nFortran does not offer call-by-name in the manner of the Algol language. It passes parameters by reference (i.e. by passing the storage address) and alternatively uses copy-in, copy-out to give the same effect, approximately, as by reference. If a parameter is an arithmetic expression, it will be evaluated and its value stored in a temporary storage area, whose address will be passed to the routine. This evaluation is done once only for each call, thus vitiating the repeated re-evaluation required by Jensen's device every time within the routine that the parameter is accessed. So, this will not work      FUNCTION SUM(I,LO,HI,TERM)\n        SUM = 0\n        DO I = LO,HI\n          SUM = SUM + TERM\n        END DO\n      END FUNCTION SUM\n      WRITE (6,*) SUM(I,1,100,1.0\/I)\n      END\n\n\nFortran does offer a facility to pass a function as a parameter using the EXTERNAL declaration, as follows - SUM is a F90 library function, so a name change to SUMJ:       FUNCTION SUMJ(I,LO,HI,TERM)\t!Attempt to follow Jensen's Device...\n       INTEGER I\t!Being by reference is workable.\n       INTEGER LO,HI\t!Just as any other parameters.\n       EXTERNAL TERM\t!Thus, not a variable, but a function.\n        SUMJ = 0\n        DO I = LO,HI\t!The specified span.\n          SUMJ = SUMJ + TERM(I)\t!Number and type of parameters now apparent.\n        END DO\t\t!TERM will be evaluated afresh, each time.\n      END FUNCTION SUMJ\t!So, almost there.\n\n      FUNCTION THIS(I)\t!A function of an integer.\n       INTEGER I\n        THIS = 1.0\/I\t!Convert to floating-point.\n      END\t\t!Since 1\/i will mostly give zero.\n\n      PROGRAM JENSEN\t!Aspiration.\n      EXTERNAL THIS\t!Thus, not a variable, but a function.\n      INTEGER I\t\t!But this is a variable, not a function.\n\n      WRITE (6,*) SUMJ(I,1,100,THIS)\t!No statement as to the parameters of THIS.\n      END\n\n\n","human_summarization":"The code demonstrates Jensen's Device, a programming technique that utilizes call by name. It calculates the 100th harmonic number using a sum procedure. The procedure takes four parameters, including a term passed by-name, and iterates from the lower to upper limit, accumulating the sum of the term. The code exploits call by name to ensure that the term and the bound variable of the summation are re-evaluated in the caller's context each time they are required. The result of the calculation is then printed.","id":1034}
    {"lang_cluster":"Fortran","source_code":"\n\nprogram pi\n  implicit none\n  integer,dimension(3350) :: vect\n  integer,dimension(201) :: buffer\n  integer :: more,karray,num,k,l,n\n  more = 0\n  vect = 2\n  do n = 1,201\n    karray = 0\n    do l = 3350,1,-1\n      num = 100000*vect(l) + karray*l\n      karray = num\/(2*l - 1)\n      vect(l) = num - karray*(2*l - 1)\n    end do\n    k = karray\/100000\n    buffer(n) = more + k\n    more = karray - k*100000\n  end do\n  write (*,'(i2,\".\"\/(1x,10i5.5))') buffer\nend program pi\n\n\n3.\n14159265358979323846264338327950288419716939937510\n58209749445923078164062862089986280348253421170679\n82148086513282306647093844609550582231725359408128\n48111745028410270193852110555964462294895493038196\n44288109756659334461284756482337867831652712019091\n45648566923460348610454326648213393607260249141273\n72458700660631558817488152092096282925409171536436\n78925903600113305305488204665213841469519415116094\n33057270365759591953092186117381932611793105118548\n07446237996274956735188575272489122793818301194912\n98336733624406566430860213949463952247371907021798\n60943702770539217176293176752384674818467669405132\n00056812714526356082778577134275778960917363717872\n14684409012249534301465495853710507922796892589235\n42019956112129021960864034418159813629774771309960\n51870721134999999837297804995105973173281609631859\n50244594553469083026425223082533446850352619311881\n71010003137838752886587533208381420617177669147303\n59825349042875546873115956286388235378759375195778\n18577805321712268066130019278766111959092164201989\n\n\n!================================================\n        program pi_spigot_unbounded\n!================================================\n          do \n            call print_next_pi_digit()\n          end do\n\n        contains\n\n!------------------------------------------------\n          subroutine print_next_pi_digit()\n!------------------------------------------------\n            use fmzm\n            type (im) :: q, r, t, k, n, l, nr\n            logical   :: dot=.false., init=.false.\n            save      :: q, r, t, k, n, l\n            if (.not.init) then\n              q=to_im(1)\n              r=to_im(0)\n              t=to_im(1)\n              k=to_im(1)\n              n=to_im(3)\n              l=to_im(3)\n              init=.true.\n            end if\n            if (4*q+r-t < n*t) then\n              write(6,fmt='(i1)',advance='no') to_int(n)\n              if (.not.dot) then\n                write(6,fmt='(a1)',advance='no') '.'\n                dot=.true.\n              end if\n              flush(6)\n              nr = 10 * (        r      - n*t )\n              n  = 10 * ( (3*q + r) \/ t - n   )\n              q  = 10 *      q\n              r  = nr\n            else\n              nr = (2*q + r) * l\n              n  = ( (q * (7*k + 2) + r*l) \/ (t*l) )\n              q  = q * k\n              t  = t * l\n              l  = l + 2\n              k  = k + 1\n              r  = nr\n            end if\n          end subroutine\n\n        end program\n\n","human_summarization":"The code continually calculates and outputs the next decimal digit of Pi, starting from 3.14159265 and continuing indefinitely until manually stopped by the user. It uses the Fortran Multiple Precision Library for higher precision and initializes all elements of a vector to 2. The output can be written as each digit is calculated, without the need for an array buffer.","id":1035}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nPROGRAM EXAMPLE  \n  IMPLICIT NONE\n \n  INTEGER :: i, j\n \n  DO i = 0, 3\n    DO j = 0, 6\n       WRITE(*, \"(I10)\", ADVANCE=\"NO\") Ackermann(i, j)\n    END DO\n    WRITE(*,*)\n  END DO\n \nCONTAINS\n \n  RECURSIVE FUNCTION Ackermann(m, n) RESULT(ack)\n    INTEGER :: ack, m, n\n\n    IF (m == 0) THEN\n      ack = n + 1\n    ELSE IF (n == 0) THEN\n      ack = Ackermann(m - 1, 1)\n    ELSE\n      ack = Ackermann(m - 1, Ackermann(m, n - 1))\n    END IF\n  END FUNCTION Ackermann\n\nEND PROGRAM EXAMPLE\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":1036}
    {"lang_cluster":"Fortran","source_code":"\n\nWorks with: Fortran version 2008\nWorks with: Fortran version 95 with extensions\nprogram ComputeGammaInt\n\n  implicit none\n\n  integer :: i\n\n  write(*, \"(3A15)\") \"Simpson\", \"Lanczos\", \"Builtin\"\n  do i=1, 10\n     write(*, \"(3F15.8)\") my_gamma(i\/3.0), lacz_gamma(i\/3.0), gamma(i\/3.0)\n  end do\n\ncontains\n\n  pure function intfuncgamma(x, y) result(z)\n    real :: z\n    real, intent(in) :: x, y\n    \n    z = x**(y-1.0) * exp(-x)\n  end function intfuncgamma\n\n\n  function my_gamma(a) result(g)\n    real :: g\n    real, intent(in) :: a\n\n    real, parameter :: small = 1.0e-4\n    integer, parameter :: points = 100000\n\n    real :: infty, dx, p, sp(2, points), x\n    integer :: i\n    logical :: correction\n\n    x = a\n\n    correction = .false.\n    ! value with x<1 gives \\infty, so we use\n    ! \\Gamma(x+1) = x\\Gamma(x)\n    ! to avoid the problem\n    if ( x < 1.0 ) then\n       correction = .true.\n       x = x + 1\n    end if\n\n    ! find a \"reasonable\" infinity...\n    ! we compute this integral indeed\n    ! \\int_0^M dt t^{x-1} e^{-t}\n    ! where M is such that M^{x-1} e^{-M} \u2264 \\epsilon\n    infty = 1.0e4\n    do while ( intfuncgamma(infty, x) > small )\n       infty = infty * 10.0\n    end do\n\n    ! using simpson\n    dx = infty\/real(points)\n    sp = 0.0\n    forall(i=1:points\/2-1) sp(1, 2*i) = intfuncgamma(2.0*(i)*dx, x)\n    forall(i=1:points\/2) sp(2, 2*i - 1) = intfuncgamma((2.0*(i)-1.0)*dx, x)\n    g = (intfuncgamma(0.0, x) + 2.0*sum(sp(1,:)) + 4.0*sum(sp(2,:)) + &\n         intfuncgamma(infty, x))*dx\/3.0\n\n    if ( correction ) g = g\/a\n\n  end function my_gamma\n\n  \n  recursive function lacz_gamma(a) result(g)\n    real, intent(in) :: a\n    real :: g\n\n    real, parameter :: pi = 3.14159265358979324\n    integer, parameter :: cg = 7\n\n    ! these precomputed values are taken by the sample code in Wikipedia,\n    ! and the sample itself takes them from the GNU Scientific Library\n    real, dimension(0:8), parameter :: p = &\n         (\/ 0.99999999999980993, 676.5203681218851, -1259.1392167224028, &\n         771.32342877765313, -176.61502916214059, 12.507343278686905, &\n         -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7 \/)\n\n    real :: t, w, x\n    integer :: i\n\n    x = a\n\n    if ( x < 0.5 ) then\n       g = pi \/ ( sin(pi*x) * lacz_gamma(1.0-x) )\n    else\n       x = x - 1.0\n       t = p(0)\n       do i=1, cg+2\n          t = t + p(i)\/(x+real(i))\n       end do\n       w = x + real(cg) + 0.5\n       g = sqrt(2.0*pi) * w**(x+0.5) * exp(-w) * t\n    end if\n  end function lacz_gamma\n\nend program ComputeGammaInt\n\n\n","human_summarization":"The code implements the Gamma function using two methods: Numerical Integration through the Simpson formula and the Lanczos approximation. It compares the results with the built-in Gamma function if available. The Gamma function is computed in the real field only.","id":1037}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 95 and later\n\nprogram Nqueens\n  implicit none\n\n  integer, parameter :: n = 8  ! size of board\n  integer :: file = 1, rank = 1, queens = 0\n  integer :: i\n  logical :: board(n,n) = .false.\n\n  do while (queens < n)\n    board(file, rank) = .true.\n    if(is_safe(board, file, rank)) then\n      queens = queens + 1\n      file = 1\n      rank = rank + 1\n    else\n      board(file, rank) = .false.\n      file = file + 1\n      do while(file > n)\n         rank = rank - 1\n         if (rank < 1) then\n           write(*, \"(a,i0)\") \"No solution for n = \", n\n           stop\n         end if  \n         do i = 1, n\n           if (board(i, rank)) then\n             file = i\n             board(file, rank) = .false.\n             queens = queens - 1\n             file = i + 1\n             exit\n           end if\n         end do\n       end do\n    end if\n  end do\n\n  call Printboard(board)\n  \ncontains\n\nfunction is_safe(board, file, rank)\n  logical :: is_safe\n  logical, intent(in) :: board(:,:)\n  integer, intent(in) :: file, rank\n  integer :: i, f, r\n  \n  is_safe = .true.\n  do i = rank-1, 1, -1\n    if(board(file, i)) then\n      is_safe = .false.\n      return\n    end if\n  end do\n  \n  f = file - 1\n  r = rank - 1\n  do while(f > 0 .and. r > 0)\n    if(board(f, r)) then\n      is_safe = .false.\n      return\n    end if\n    f = f - 1\n    r = r - 1\n  end do\n\n  f = file + 1\n  r = rank - 1\n  do while(f <= n .and. r > 0)\n    if(board(f, r)) then\n      is_safe = .false.\n      return\n    end if\n    f = f + 1\n    r = r - 1\n  end do\nend function    \n\nsubroutine Printboard(board)\n  logical, intent(in) :: board(:,:)\n  character(n*4+1) :: line\n  integer :: f, r\n  \n  write(*, \"(a, i0)\") \"n = \", n\n  line = repeat(\"+---\", n) \/\/ \"+\"\n  do r = 1, n\n    write(*, \"(a)\") line\n    do f = 1, n\n      write(*, \"(a)\", advance=\"no\") \"|\"\n      if(board(f, r)) then\n        write(*, \"(a)\", advance=\"no\") \" Q \"\n      else if(mod(f+r, 2) == 0) then\n        write(*, \"(a)\", advance=\"no\") \"   \"\n      else\n        write(*, \"(a)\", advance=\"no\") \"###\"\n      end if\n    end do\n    write(*, \"(a)\") \"|\"\n  end do\n  write(*, \"(a)\") line\nend subroutine\nend program\n\n\n","human_summarization":"solve the N-queens problem using a backtracking method, optimized for symmetry of the chess board and parallelized with OpenMP. The algorithm starts backtracking from the third column. The program counts solutions, stores, and prints all solutions for given board sizes. It also demonstrates the use of Fortran's type polymorphism and linked lists. The program can be compiled with GCC, Absoft Pro Fortran, or Intel Fortran.","id":1038}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram Concat_Arrays\n  implicit none\n\n  ! Note: in Fortran 90 you must use the old array delimiters (\/ , \/)\n  integer, dimension(3) :: a = [1, 2, 3] ! (\/1, 2, 3\/)\n  integer, dimension(3) :: b = [4, 5, 6] ! (\/4, 5, 6\/)\n  integer, dimension(:), allocatable :: c, d\n  \n  allocate(c(size(a)+size(b)))\n  c(1 : size(a)) = a\n  c(size(a)+1 : size(a)+size(b)) = b\n  print*, c\n\n  ! alternative\n  d = [a, b] ! (\/a, b\/)\n  print*, d\nend program Concat_Arrays\n\n","human_summarization":"demonstrate how to concatenate two arrays.","id":1039}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\n\nprogram Short_Circuit_Eval\n  implicit none\n\n  logical :: x, y\n  logical, dimension(2) :: l = (\/ .false., .true. \/)\n  integer :: i, j\n\n  do i = 1, 2\n    do j = 1, 2\n      write(*, \"(a,l1,a,l1,a)\") \"Calculating x = a(\", l(i), \") and b(\", l(j), \")\"   \n      ! a AND b\n      x = a(l(i))  \n      if(x) then\n        x = b(l(j))\n        write(*, \"(a,l1)\") \"x = \", x\n      else\n        write(*, \"(a,l1)\") \"x = \", x\n      end if\n  \n      write(*,*)\n      write(*, \"(a,l1,a,l1,a)\") \"Calculating y = a(\", l(i), \") or b(\", l(j), \")\"   \n      ! a OR b\n      y = a(l(i))\n      if(y) then\n        write(*, \"(a,l1)\") \"y = \", y\n      else\n        y = b(l(j))\n        write(*, \"(a,l1)\") \"y = \", y\n      end if\n      write(*,*)\n    end do\n  end do\n\ncontains\n\nfunction a(value)\n  logical :: a\n  logical, intent(in) :: value\n\n  a = value\n  write(*, \"(a,l1,a)\") \"Called function a(\", value, \")\"\nend function\n\nfunction b(value)\n  logical :: b\n  logical, intent(in) :: value\n  \n  b = value\n  write(*, \"(a,l1,a)\") \"Called function b(\", value, \")\"\nend function\nend program\n\n\n","human_summarization":"The code defines two functions, a and b, which return and print the same boolean value. It then calculates the values of two equations, using short-circuit evaluation to ensure that function b is only called when necessary. If the programming language doesn't support short-circuit evaluation, this is achieved using nested if statements.","id":1040}
    {"lang_cluster":"Fortran","source_code":"\n\n!-*- mode: compilation; default-directory: \"\/tmp\/\" -*-\n!Compilation started at Thu Jun  5 01:52:03\n!\n!make f && for a in '' a bark book treat common squad confuse\u00a0; do echo $a | .\/f\u00a0; done\n!gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none -g f.f08 -o f\n! T                      \n! T  A                    NA\n! T  BARK                 BO NA RE XK\n! F  BOOK                 OB BO -- --\n! T  TREAT                GT RE ER NA TG\n! F  COMMON               PC OB ZM -- -- --\n! T  SQUAD                FS DQ HU NA QD\n! T  CONFUSE              CP BO NA FS HU FS RE\n!\n!Compilation finished at Thu Jun  5 01:52:03\n\nprogram abc\n  implicit none\n  integer, parameter :: nblocks = 20\n  character(len=nblocks) :: goal\n  integer, dimension(nblocks) :: solution\n  character(len=2), dimension(0:nblocks) :: blocks_copy, blocks = &\n       &(\/'--','BO','XK','DQ','CP','NA','GT','RE','TG','QD','FS','JW','HU','VI','AN','OB','ER','FS','LY','PC','ZM'\/)\n  logical :: valid\n  integer :: i, iostat\n  read(5,*,iostat=iostat) goal\n  if (iostat .ne. 0) goal = ''\n  call ucase(goal)\n  solution = 0\n  blocks_copy = blocks\n  valid = assign_block(goal(1:len_trim(goal)), blocks, solution, 1)\n  write(6,*) valid, ' '\/\/goal, (' '\/\/blocks_copy(solution(i)), i=1,len_trim(goal))\n\ncontains\n\n  recursive function assign_block(goal, blocks, solution, n) result(valid)\n    implicit none\n    logical :: valid\n    character(len=*), intent(in) :: goal\n    character(len=2), dimension(0:), intent(inout) :: blocks\n    integer, dimension(:), intent(out) :: solution\n    integer, intent(in) :: n\n    integer :: i\n    character(len=2) :: backing_store\n    valid = .true.\n    if (len(goal)+1 .eq. n) return\n    do i=1, size(blocks)\n       if (index(blocks(i),goal(n:n)) .ne. 0) then\n          backing_store = blocks(i)\n          blocks(i) = ''\n          solution(n) = i\n          if (assign_block(goal, blocks, solution, n+1)) return\n          blocks(i) = backing_store\n       end if\n    end do\n    valid = .false.\n    return\n  end function assign_block\n\n  subroutine ucase(a)\n    implicit none\n    character(len=*), intent(inout) :: a\n    integer :: i, j\n    do i = 1, len_trim(a)\n       j = index('abcdefghijklmnopqrstuvwxyz',a(i:i))\n       if (j .ne. 0) a(i:i) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'(j:j)\n    end do\n  end subroutine ucase\n\nend program abc\n\n\n      MODULE PLAYPEN\t!Messes with a set of alphabet blocks.\n       INTEGER MSG\t\t!Output unit number.\n       PARAMETER (MSG = 6)\t!Standard output.\n       INTEGER MS\t\t!I dislike unidentified constants...\n       PARAMETER (MS = 2)\t!So this is the maximum number of lettered sides.\n       INTEGER LETTER(26),SUPPLY(26)\t!For counting the alphabet.\n       CONTAINS\n        SUBROUTINE SWAP(I,J)\t!This really should be known to the compiler.\n         INTEGER I,J,K\t\t!Which could generate in-place code,\n          K = I\t\t\t!Using registers, maybe.\n          I = J\t\t\t!Or maybe, there are special op-codes.\n          J = K\t\t\t!Rather than this clunkiness.\n        END SUBROUTINE SWAP\t!And it should be for any type of thingy.\n\n        INTEGER FUNCTION LSTNB(TEXT)  !Sigh. Last Not Blank.\nConcocted yet again by R.N.McLean (whom God preserve) December MM.\nCode checking reveals that the Compaq compiler generates a copy of the string and then finds the length of that when using the latter-day intrinsic LEN_TRIM. Madness!\nCan't   DO WHILE (L.GT.0 .AND. TEXT(L:L).LE.' ')\t!Control chars. regarded as spaces.\nCurse the morons who think it good that the compiler MIGHT evaluate logical expressions fully.\nCrude GO TO rather than a DO-loop, because compilers use a loop counter as well as updating the index variable.\nComparison runs of GNASH showed a saving of ~3% in its mass-data reading through the avoidance of DO in LSTNB alone.\nCrappy code for character comparison of varying lengths is avoided by using ICHAR which is for single characters only.\nChecking the indexing of CHARACTER variables for bounds evoked astounding stupidities, such as calculating the length of TEXT(L:L) by subtracting L from L!\nComparison runs of GNASH showed a saving of ~25-30% in its mass data scanning for this, involving all its two-dozen or so single-character comparisons, not just in LSTNB.\n         CHARACTER*(*),INTENT(IN):: TEXT\t!The bumf. If there must be copy-in, at least there need not be copy back.\n         INTEGER L\t\t!The length of the bumf.\n          L = LEN(TEXT)\t\t!So, what is it?\n    1     IF (L.LE.0) GO TO 2\t!Are we there yet?\n          IF (ICHAR(TEXT(L:L)).GT.ICHAR(\" \")) GO TO 2\t!Control chars are regarded as spaces also.\n          L = L - 1\t\t!Step back one.\n          GO TO 1\t\t!And try again.\n    2     LSTNB = L\t\t!The last non-blank, possibly zero.\n         RETURN\t\t\t!Unsafe to use LSTNB as a variable.\n        END FUNCTION LSTNB\t!Compilers can bungle it.\n\n        SUBROUTINE LETTERCOUNT(TEXT)\t!Count the occurrences of A-Z.\n         CHARACTER*(*) TEXT\t!The text to inspect.\n         INTEGER I,K\t\t!Assistants.\n          DO I = 1,LEN(TEXT)\t\t!Step through the text.\n            K = ICHAR(TEXT(I:I)) - ICHAR(\"A\") + 1\t!This presumes that A-Z have contiguous codes!\n            IF (K.GE.1 .AND. K.LE.26) LETTER(K) = LETTER(K) + 1\t!Not so with EBCDIC!!\n          END DO\t\t\t!On to the next letter.\n        END SUBROUTINE LETTERCOUNT\t!Be careful with LETTER.\n\n        SUBROUTINE UPCASE(TEXT)\t!In the absence of an intrinsic...\nConverts any lower case letters in TEXT to upper case...\nConcocted yet again by R.N.McLean (whom God preserve) December MM.\nConverting from a DO loop evades having both an iteration counter to decrement and an index variable to adjust.\n         CHARACTER*(*) TEXT\t!The stuff to be modified.\nc        CHARACTER*26 LOWER,UPPER\t!Tables. a-z may not be contiguous codes.\nc        PARAMETER (LOWER = \"abcdefghijklmnopqrstuvwxyz\")\nc        PARAMETER (UPPER = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\nCAREFUL!! The below relies on a-z and A-Z being contiguous, as is NOT the case with EBCDIC.\n         INTEGER I,L,IT\t\t!Fingers.\n          L = LEN(TEXT)\t\t!Get a local value, in case LEN engages in oddities.\n          I = L\t\t\t!Start at the end and work back..\n    1     IF (I.LE.0) RETURN \t!Are we there yet? Comparison against zero should not require a subtraction.\nc         IT = INDEX(LOWER,TEXT(I:I))\t!Well?\nc         IF (IT .GT. 0) TEXT(I:I) = UPPER(IT:IT)\t!One to convert?\n          IT = ICHAR(TEXT(I:I)) - ICHAR(\"a\")\t\t!More symbols precede \"a\" than \"A\".\n          IF (IT.GE.0 .AND. IT.LE.25) TEXT(I:I) = CHAR(IT + ICHAR(\"A\"))\t!In a-z? Convert!\n          I = I - 1\t\t\t!Back one.\n          GO TO 1\t\t\t!Inspect..\n        END SUBROUTINE UPCASE\t!Easy.\n\n        SUBROUTINE ORDERSIDE(LETTER)\t!Puts the letters into order.\n         CHARACTER*(*) LETTER\t!The letters.\n         INTEGER I,N,H\t\t!Assistants.\n         CHARACTER*1 T\t\t!A scratchpad.\n         LOGICAL CURSE\t\t!A bit.\n          N = LEN(LETTER)\t!So, how many letters?\n          H = N - 1\t\t!Last - First, and not +1.\n          IF (H.LE.0) RETURN\t!Ha ha.\n    1     H = MAX(1,H*10\/13)\t\t!The special feature.\n          IF (H.EQ.9 .OR. H.EQ.10) H = 11\t!A twiddle.\n          CURSE = .FALSE.\t\t!So far, so good.\n          DO I = N - H,1,-1\t\t!If H = 1, this is a BubbleSort.\n            IF (LETTER(I:I).LT.LETTER(I + H:I + H)) THEN\t!One compare.\n              T = LETTER(I:I)\t\t\t!One swap.\n              LETTER(I:I) = LETTER(I + H:I + H)\t!Alas, no SWAP(A,B)\n              LETTER(I + H:I + H) = T\t\t!Is recognised by the compiler.\n              CURSE = .TRUE.\t\t!If once a tiger is seen...\n            END IF\t\t\t!So much for that comparison.\n          END DO\t\t\t!On to the next.\n          IF (CURSE .OR. H.GT.1) GO TO 1!Another pass?\n        END SUBROUTINE ORDERSIDE\t!Simple enough.\n        SUBROUTINE ORDERBLOCKS(N,SOME)\t!Puts the collection of blocks into order.\n         INTEGER N\t\t!The number of blocks.\n         CHARACTER*(*) SOME(:)\t!Their lists of letters.\n         INTEGER I,H\t\t!Assistants.\n         CHARACTER*(LEN(SOME(1))) T\t!A scratchpad matching an element of SOME.\n         LOGICAL CURSE\t\t\t!Since there is still no SWAP(SOME(I),SOME(I + H)).\n          H = N - 1\t\t!So here comes another CombSort.\n          IF (H.LE.0) RETURN\t!With standard suspicion.\n    1     H = MAX(1,H*10\/13)\t\t!This is the outer loop.\n          IF (H.EQ.9 .OR. H.EQ.10) H = 11\t!This is a fiddle.\n          CURSE = .FALSE.\t\t!Start the next pass in hope.\n          DO I = N - H,1,-1\t\t!Going backwards, just for fun.\n            IF (SOME(I).LT.SOME(I + H)) THEN\t!So then?\n              T = SOME(I)\t\t!Disorder.\n              SOME(I) = SOME(I + H)\t!So once again,\n              SOME(I + H) = T\t\t!Swap the two miscreants.\n              CURSE = .TRUE.\t\t!And remember.\n            END IF\t\t\t!So much for that comparison.\n          END DO\t\t\t!On to the next.\n          IF (CURSE .OR. H.GT.1) GO TO 1!Are we there yet?\n        END SUBROUTINE ORDERBLOCKS\t!Not much code, but ringing the changes is still tedious.\n\n        SUBROUTINE PLAY(N,SOME)\t!Mess about with the collection of blocks.\n         INTEGER N\t\t!Their number.\n         CHARACTER*(*) SOME(:)\t!Their letters.\n         INTEGER NH,HIT(N)\t!A list of blocks.\n         INTEGER B,I,J,K,L,M\t!Assistants.\n         CHARACTER*1 C\t\t!A letter of the moment.\n          L = LEN(SOME(1))\t!The maximum number of letters to any block.\nCast the collection on to the floor.\n          WRITE (MSG,1) N,L,SOME\t!Announce the set as it is supplied.\n    1     FORMAT (I7,\" blocks, with at most\",I2,\" letters:\",66(1X,A))\nChange the \"orientation\" of some blocks.\n          DO B = 1,N\t\t!Step through each block.\n            CALL UPCASE(SOME(B))\t!Paranoia rules.\n            CALL ORDERSIDE(SOME(B))\t!Put its letter list into order.\n          END DO\t\t!On to the next block.\n          WRITE (MSG,2) SOME\t!Reveal the orderly array.\n    2     FORMAT (6X,\"... the letters in reverse order:\",66(1X,A))\nCollate the collection of blocks.\n          CALL ORDERBLOCKS(N,SOME)\t!Now order the blocks by their letters.\n          WRITE (MSG,3) SOME\t\t!Reveal them in neato order.\n    3     FORMAT (7X,\"... the blocks in reverse order:\",66(1X,A))\nCount the appearances of the letters of the alphabet.\n          LETTER = 0\t\t!Enough of shuffling blocks around.\n          DO B = 1,N\t\t!Now inspect their collective letters.\n            CALL LETTERCOUNT(SOME(B))\t!A block's worth at a go.\n          END DO\t\t!On to the next block.\n          SUPPLY = LETTER\t!Save the counts of supplied letters.\n          WRITE (MSG,4) (CHAR(ICHAR(\"A\") + I - 1),I = 1,26),SUPPLY\t!Results.\n    4     FORMAT (15X,\"Letters of the alphabet:\",26A,\/,\t!First, a line with A ... Z.\n     1     11X,\"... number thereof supplied:\",26I)\t!Then a line of the associated counts.\nCheck for blocks with duplicated letters.\n          WRITE (MSG,5)\t\t!Announce.\n    5     FORMAT (8X,\"Blocks with duplicated letters:\",$)\t!Further output impends.\n          M = 0\t\t\t!No duplication found.\n          DO B = 1,N\t\t!So step through each block.\n         JJ:DO J = 2,L\t\t\t!Inspecting successive letters of the block,\n              IF (SOME(B)(J:J).LE.\" \") EXIT JJ\t!Provided they've not run out.\n              DO K = 1,J - 1\t\t\t!To see if it has appeared earlier.\n                IF (SOME(B)(K:K).LE.\" \") EXIT JJ!Reverse order means that spaces will be at the end!\n                IF (SOME(B)(J:J).EQ.SOME(B)(K:K)) THEN\t!Well?\n                  M = M + 1\t\t!A match!\n                  WRITE (MSG,6) SOME(B)\t!Name the block.\n    6             FORMAT (1X,A,$)\t!With further output still impending,\n                  EXIT JJ\t\t!And give up on this block.\n                END IF\t\t\t!One duplicated letter is sufficient for its downfall.\n              END DO\t\t\t!Next letter up.\n            END DO JJ\t\t\t!On to the next letter of the block.\n          END DO\t\t!On to the next block.\n          CALL HIC(M)\t\t!Show the count and end the line.\nCheck for duplicate blocks, knowing that the array of blocks is ordered.\n          WRITE (MSG,7)\t\t!Announce.\n    7     FORMAT (21X,\"Duplicated blocks:\",$)\t!Again, leave the line dangling.\n          K = 0\t\t\t!No duplication found.\n          B = 1\t\t\t!Syncopation.\n   70     B = B + 1\t\t!Advance one.\n          IF (B.GT.N) GO TO 72\t!Are we there yet?\n          IF (SOME(B).NE.SOME(B - 1)) GO TO 70\t!No match? Search on.\n          K = K + 1\t\t!A match is counted.\n          WRITE (MSG,6) SOME(B)\t!Name it.\n   71     B = B + 1\t\t!And speed through continued matching.\n          IF (B.GT.N) GO TO 72\t!Unless we're of the end.\n          IF (SOME(B).EQ.SOME(B - 1)) GO TO 71\t!Continued matching?\n          GO TO 70\t\t!Mismatch: resume the normal scan.\n   72     CALL HIC(K)\t\t!So much for that.\nCheck for duplicated letters across different blocks.\n          IF (ALL(SUPPLY.LE.1)) RETURN\t!Unless there are no duplicated letters.\n          WRITE (MSG,8)\t\t!Announce.\n    8     FORMAT (\"Duplicated letters on different blocks:\",$)\t!More to come.\n          K = 0\t\t!Start another count.\n          DO I = 1,26\t\t!A well-known span.\n            IF (SUPPLY(I).LE.1) CYCLE\t!Any duplicated letters?\n            C = CHAR(ICHAR(\"A\") + I - 1)!Yes. This is the character.\n            NH = 0\t\t!So, how many blocks contribute?\n            DO B = 1,N\t\t!Find out.\n              IF (INDEX(SOME(B),C).GT.0) THEN\t!On this block?\n                NH = NH + 1\t\t!Yes.\n                HIT(NH) = B\t\t!Keep track of which.\n              END IF\t\t\t!So much for that block.\n            END DO\t\t!On to the next.\n            IF (ANY(SOME(HIT(2:NH)) .NE. SOME(HIT(1)))) THEN\t!All have the same collection of letters?\n              K = K + 1\t\t\t!No!\n              WRITE (MSG,9) C\t\t!Name the heterogenously supported letter.\n    9         FORMAT (A,$)\t!Use the same spacing even though one character only.\n            END IF\t\t!So much for that letter's search.\n          END DO\t\t!On to the next letter.\n          CALL HIC(K)\t!Finish the line with the count report.\n         CONTAINS\t!This is used often enough.\n          SUBROUTINE HIC(N)\t!But has very specific context.\n           INTEGER N\t\t\t!The count.\n            IF (N.LE.0) WRITE (MSG,*) \"None.\"\t!Yes, we have no bananas.\n            IF (N.GT.0) WRITE (MSG,*) N\t\t!Either way, end the line.\n          END SUBROUTINE HIC\t!This service routine is not needed elsewhere.\n        END SUBROUTINE PLAY\t!Look mummy! All the blockses are neatened!\n\n        LOGICAL FUNCTION CANBLOCK(WORD,N,SOME)\t!Can the blocks spell out the word?\nCreates a move tree based on the letters of WORD and for each, the blocks available.\n         CHARACTER*(*) WORD\t!The word to spell out.\n         INTEGER N\t\t!The number of blocks.\n         CHARACTER*(*) SOME(:)\t!The blocks and their letters.\n         INTEGER NA,AVAIL(N)\t!Say not the struggle naught availeth!\n         INTEGER NMOVE(LEN(WORD))\t!I need a list of acceptable blocks,\n         INTEGER MOVE(LEN(WORD),N)\t!One list for each letter of WORD.\n         INTEGER I,L,S\t\t!Assistants.\n         CHARACTER*1 C\t\t!The letter of the moment.\n          CANBLOCK = .FALSE.\t\t!Initial pessimism.\n          L = LSTNB(WORD)\t\t!Ignore trailing spaces.\n          IF (L.GT.N) RETURN\t\t!Enough blocks?\n          LETTER = 0\t\t\t\t!To make rabbit stew,\n          CALL LETTERCOUNT(WORD(1:L))\t\t!First catch your rabbit.\n          IF (ANY(SUPPLY .LT. LETTER)) RETURN\t!The larder is lacking.\n          NA = N\t\t\t!Prepare a list.\n          FORALL (I = 1:N) AVAIL(I) = I\t!That fingers every block.\n          I = 0\t\t!Step through the letters of the WORD.\nChug through the letters of the WORD.\n    1     I = I + 1\t!One letter after the other.\n          IF (I.GT.L) GO TO 100\t!Yay! We're through!\n          C = WORD(I:I)\t\t!The letter of the moment.\n          NMOVE(I) = 0\t\t!No moves known at this new level.\n          DO S = 1,NA\t\t!So, look for them amongst the available slots.\n            IF (INDEX(SOME(AVAIL(S)),C) .GT. 0) THEN\t!A hit?\n              NMOVE(I) = NMOVE(I) + 1\t!Yes! Count up another possible move.\n              MOVE(I,NMOVE(I)) = S\t!Remember its slot.\n            END IF\t\t\t!So much for that block.\n          END DO\t\t!On to the next.\n    2     IF (NMOVE(I).GT.0) THEN\t!Have we any moves?\n            S = MOVE(I,NMOVE(I))\t!Yes! Recover the last found.\n            NMOVE(I) = NMOVE(I) - 1\t!Uncount, as it is about to be used.\n            IF (S.NE.NA) CALL SWAP(AVAIL(S),AVAIL(NA))\t!This block is no longer available.\n            NA = NA - 1\t\t\t!Shift the boundary back.\n            GO TO 1\t\t\t!Try the next letter!\n          END IF\t\t!But if we can't find a move at that level...\n          I = I - 1\t\t!Retreat a level.\n          IF (I.LE.0) RETURN\t!Oh dear!\n          S = MOVE(I,NMOVE(I) + 1)\t!Undo the move that had been made at this level.\n          NA = NA + 1\t\t\t!And make its block is re-available.\n          IF (S.NE.NA) CALL SWAP(AVAIL(S),AVAIL(NA))\t!Move it back.\n          GO TO 2\t\t!See what moves remain at this level.\nCompleted!\n  100     CANBLOCK = .TRUE.\t!That's a relief.\n        END FUNCTION CANBLOCK\t!Some revisions might have been made.\n      END MODULE PLAYPEN\t!No sand here.\n\n      USE PLAYPEN\t!Just so.\n      INTEGER HAVE,TESTS\t\t!Parameters for the specified problem.\n      PARAMETER (HAVE = 20, TESTS = 7)\t!Number of blocks, number of tests.\n      CHARACTER*(MS) BLOCKS(HAVE)\t!Have blocks, will juggle.\n      DATA BLOCKS\/\"BO\",\"XK\",\"DQ\",\"CP\",\"NA\",\"GT\",\"RE\",\"TG\",\"QD\",\"FS\",\t!The specified set\n     1            \"JW\",\"HU\",\"VI\",\"AN\",\"OB\",\"ER\",\"FS\",\"LY\",\"PC\",\"ZM\"\/\t!Of letter blocks.\n      CHARACTER*8 WORD(TESTS)\t\t!Now for the specified test words.\n      LOGICAL ANS(TESTS),T,F\t\t!And the given results.\n      PARAMETER (T = .TRUE., F = .FALSE.)\t!Enable a more compact specification.\n      DATA WORD\/\"A\",\"BARK\",\"BOOK\",\"TREAT\",\"COMMON\",\"SQUAD\",\"CONFUSE\"\/\t!So that these\n      DATA  ANS\/ T ,    T ,    F ,     T ,      F ,     T ,       T \/\t!Can be aligned.\n      LOGICAL YAY\n      INTEGER I\n\n      WRITE (MSG,1)\n    1 FORMAT (\"Arranges alphabet blocks, attending only to the \",\n     1 \"letters on the blocks, and ignoring case and orientation.\",\/)\n\n      CALL PLAY(HAVE,BLOCKS)\t!Some fun first.\n\n      WRITE (MSG,'(\/\"Now to see if some words can be spelled out.\")')\n      DO I = 1,TESTS\n        CALL UPCASE(WORD(I))\n        YAY = CANBLOCK(WORD(I),HAVE,BLOCKS)\n        WRITE (MSG,*) YAY,ANS(I),YAY.EQ.ANS(I),WORD(I)\n      END DO\n      END\n\n\nArranges alphabet blocks, attending only to the letters on the blocks, and ignoring case and orientation.\n\n     20 blocks, with at most 2 letters: BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\n      ... the letters in reverse order: OB XK QD PC NA TG RE TG QD SF WJ UH VI NA OB RE SF YL PC ZM\n       ... the blocks in reverse order: ZM YL XK WJ VI UH TG TG SF SF RE RE QD QD PC PC OB OB NA NA\n               Letters of the alphabet:  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z\n           ... number thereof supplied:  2  2  2  2  2  2  2  1  1  1  1  1  1  2  2  2  2  2  2  2  1  1  1  1  1  1\n        Blocks with duplicated letters: None.\n                     Duplicated blocks: TG SF RE QD PC OB NA           7\nDuplicated letters on different blocks: None.\n\nNow to see if some words can be spelled out.\n T T T A\n T T T BARK\n F F T BOOK\n T T T TREAT\n F F T COMMON\n T T T SQUAD\n T T T CONFUSE\n\n","human_summarization":"The code defines a function that checks if a given word can be spelled using a collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive. It also includes a mechanism to backtrack if an initial selection of blocks prevents completion of the word due to the unavailability of required letters. The code also contains support routines to inspect the block collection and report whether a word can be spelled with the provided blocks. The output indicates whether the word can be spelled, the expected result, and if the two match.","id":1041}
    {"lang_cluster":"Fortran","source_code":"\n\nmodule md5_mod\n    use kernel32\n    use advapi32\n    implicit none\n    integer, parameter :: MD5LEN = 16\ncontains\n    subroutine md5hash(name, hash, dwStatus, filesize)\n        implicit none\n        character(*) :: name\n        integer, parameter :: BUFLEN = 32768\n        integer(HANDLE) :: hFile, hProv, hHash\n        integer(DWORD) :: dwStatus, nRead\n        integer(BOOL) :: status\n        integer(BYTE) :: buffer(BUFLEN)\n        integer(BYTE) :: hash(MD5LEN)\n        integer(UINT64) :: filesize\n \n        dwStatus = 0\n        filesize = 0\n        hFile = CreateFile(trim(name) \/\/ char(0), GENERIC_READ, FILE_SHARE_READ, NULL, &\n                           OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL)\n \n        if (hFile == INVALID_HANDLE_VALUE) then\n            dwStatus = GetLastError()\n            print *, \"CreateFile failed.\"\n            return\n        end if\n \n        if (CryptAcquireContext(hProv, NULL, NULL, PROV_RSA_FULL, &\n                                CRYPT_VERIFYCONTEXT) == FALSE) then\n            dwStatus = GetLastError()\n            print *, \"CryptAcquireContext failed.\"\n            goto 3\n        end if\n \n        if (CryptCreateHash(hProv, CALG_MD5, 0_ULONG_PTR, 0_DWORD, hHash) == FALSE) then\n            dwStatus = GetLastError()\n            print *, \"CryptCreateHash failed.\"\n            go to 2\n        end if\n \n        do\n            status = ReadFile(hFile, loc(buffer), BUFLEN, nRead, NULL)\n            if (status == FALSE .or. nRead == 0) exit\n            filesize = filesize + nRead\n            if (CryptHashData(hHash, buffer, nRead, 0) == FALSE) then\n                dwStatus = GetLastError()\n                print *, \"CryptHashData failed.\"\n                go to 1\n            end if\n        end do\n \n        if (status == FALSE) then\n            dwStatus = GetLastError()\n            print *, \"ReadFile failed.\"\n            go to 1\n        end if\n \n        nRead = MD5LEN\n        if (CryptGetHashParam(hHash, HP_HASHVAL, hash, nRead, 0) == FALSE) then\n            dwStatus = GetLastError()\n            print *, \"CryptGetHashParam failed.\", status, nRead, dwStatus\n        end if\n \n      1 status = CryptDestroyHash(hHash)\n      2 status = CryptReleaseContext(hProv, 0)\n      3 status = CloseHandle(hFile)\n    end subroutine\nend module\n \nprogram md5\n    use md5_mod\n    implicit none\n    integer :: n, m, i, j\n    character(:), allocatable :: name\n    integer(DWORD) :: dwStatus\n    integer(BYTE) :: hash(MD5LEN)\n    integer(UINT64) :: filesize\n \n    n = command_argument_count()\n    do i = 1, n\n        call get_command_argument(i, length=m)\n        allocate(character(m) :: name)\n        call get_command_argument(i, name)\n        call md5hash(name, hash, dwStatus, filesize)\n        if (dwStatus == 0) then\n            do j = 1, MD5LEN\n                write(*, \"(Z2.2)\", advance=\"NO\") hash(j)\n            end do\n            write(*, \"(' ',A,' (',G0,' bytes)')\") name, filesize\n        end if\n        deallocate(name)\n    end do\nend program\n\n","human_summarization":"The code implements the MD5 encoding algorithm to encode a given string. It optionally validates the implementation using test values from IETF RFC (1321) for MD5. It also includes a warning about the known weaknesses of MD5 and suggests stronger alternatives for production-grade cryptography. If the solution is a library solution, it refers to MD5\/Implementation for an implementation from scratch. The code uses Windows API functions like CryptAcquireContextA, CryptCreateHash, CryptHashData, and CryptGetHashParam.","id":1042}
    {"lang_cluster":"Fortran","source_code":"\n\nprogram sendmail\n    use ifcom\n    use msoutl\n    implicit none\n    integer(4) :: app, status, msg\n    \n    call cominitialize(status)\n    call comcreateobject(\"Outlook.Application\", app, status)\n    msg = $Application_CreateItem(app, olMailItem, status)\n    call $MailItem_SetTo(msg, \"somebody@somewhere\", status)\n    call $MailItem_SetSubject(msg, \"Title\", status)\n    call $MailItem_SetBody(msg, \"Hello\", status)\n    call $MailItem_Send(msg, status)\n    call $Application_Quit(app, status)\n    call comuninitialize()\nend program\n\n","human_summarization":"The code is a function that sends an email using the Outlook COM server. It accepts parameters for setting From, To, Cc addresses, Subject, and message text, with optional fields for server name and login details. It provides notifications for problems or success. The solution is portable across multiple operating systems. Sensitive data used in examples is obfuscated. The code requires linking with a Fortran module for the Microsoft Outlook Object Library, generated using the Intel Fortran Module Wizard.","id":1043}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 95 and later\nprogram Octal\n  implicit none\n  \n  integer, parameter :: i64 = selected_int_kind(18)\n  integer(i64) :: n = 0\n  \n! Will stop when n overflows from\n! 9223372036854775807 to -92233720368547758078 (1000000000000000000000 octal)\n  do while(n >= 0)\n    write(*, \"(o0)\") n\n    n = n + 1\n  end do\nend program\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":1044}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nMODULE Genericswap\n  IMPLICIT NONE\n\n  INTERFACE Swap\n    MODULE PROCEDURE Swapint, Swapreal, Swapstring\n  END INTERFACE\n\nCONTAINS\n\n  SUBROUTINE Swapint(a, b)\n    INTEGER, INTENT(IN OUT) :: a, b\n    INTEGER :: temp\n    temp = a ; a = b ; b = temp\n  END SUBROUTINE Swapint\n\n  SUBROUTINE Swapreal(a, b)\n    REAL, INTENT(IN OUT) :: a, b\n    REAL :: temp\n    temp = a ; a = b ; b = temp\n  END SUBROUTINE Swapreal\n\n  SUBROUTINE Swapstring(a, b)\n    CHARACTER(*), INTENT(IN OUT) :: a, b\n    CHARACTER(len(a)) :: temp\n    temp = a ; a = b ; b = temp\n  END SUBROUTINE Swapstring\nEND MODULE Genericswap\n\nPROGRAM EXAMPLE\n  USE Genericswap\n  IMPLICIT NONE\n  INTEGER :: i1 = 1, i2 = 2\n  REAL :: r1 = 1.0, r2 = 2.0\n  CHARACTER(3) :: s1=\"abc\", s2=\"xyz\"\n\n  CALL Swap(i1, i2)\n  CALL Swap(r1, r2)\n  CALL Swap(s1, s2)\n\n  WRITE(*,*) i1, i2   ! Prints 2 and 1\n  WRITE(*,*) r1, r2   ! Prints 2.0 and 1.0\n  WRITE(*,*) s1, s2   ! Prints xyz and abc\nEND PROGRAM EXAMPLE\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.","id":1045}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: Fortran version 90 and later\nprogram palindro\n\n  implicit none\n\n  character(len=*), parameter :: p = \"ingirumimusnocteetconsumimurigni\"\n  \n  print *, is_palindro_r(p)\n  print *, is_palindro_r(\"anothertest\")\n  print *, is_palindro2(p)\n  print *, is_palindro2(\"test\")\n  print *, is_palindro(p)\n  print *, is_palindro(\"last test\")\n\ncontains\n\n\n! non-recursive\nfunction is_palindro(t)\n  logical :: is_palindro\n  character(len=*), intent(in) :: t\n\n  integer :: i, l\n\n  l = len(t)\n  is_palindro = .false.\n  do i=1, l\/2\n     if ( t(i:i) \/= t(l-i+1:l-i+1) ) return\n  end do\n  is_palindro = .true.\nend function is_palindro\n\n! non-recursive 2\nfunction is_palindro2(t) result(isp)\n  logical :: isp\n  character(len=*), intent(in) :: t\n\n  character(len=len(t)) :: s\n  integer :: i\n\n  forall(i=1:len(t)) s(len(t)-i+1:len(t)-i+1) = t(i:i)\n  isp = ( s == t )\nend function is_palindro2\n\n\n  recursive function is_palindro_r (t) result (isp)\n\n    implicit none\n    character (*), intent (in) :: t\n    logical :: isp\n\n    isp = len (t) == 0 .or. t (: 1) == t (len (t) :) .and. is_palindro_r (t (2 : len (t) - 1))\n\n  end function is_palindro_r\n\nend program palindro\n\n","human_summarization":"The code includes a function that checks if a given sequence of characters is a palindrome. It supports Unicode characters and also includes a second function that detects inexact palindromes, ignoring white-space, punctuation, and case sensitivity. The functions are designed both recursively and non-recursively.","id":1046}
    {"lang_cluster":"Fortran","source_code":"\nWorks with: any Fortran compiler\nprogram show_home\nimplicit none\ncharacter(len=32) :: home_val  ! The string value of the variable HOME\ninteger           :: home_len  ! The actual length of the value\ninteger           :: stat      ! The status of the value:\n                               !  0 = ok\n                               !  1 = variable does not exist\n                               ! -1 = variable is not long enought to hold the result\ncall get_environment_variable('HOME', home_val, home_len, stat)\nif (stat == 0) then\n    write(*,'(a)') 'HOME = '\/\/trim(home_val)\nelse\n    write(*,'(a)') 'No HOME to go to!'\nend if\nend program show_home\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":1047}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: COBOL version 2002\nWorks with: OpenCOBOL version 1.1\n\n       01  stack.\n         05  head USAGE IS POINTER VALUE NULL.\n\n\n       01  node BASED.\n         COPY node-info REPLACING\n           01 BY 05\n           node-info BY info.\n         05  link USAGE IS POINTER VALUE NULL.\n\n\n       01  node-info PICTURE X(10) VALUE SPACES.\n\n\n       01  p PICTURE 9.\n         88 nil VALUE ZERO WHEN SET TO FALSE IS 1.\n         88 t   VALUE 1 WHEN SET TO FALSE IS ZERO.\n\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. push.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       COPY p.\n       COPY node.\n       LINKAGE SECTION.\n       COPY stack.\n       01  node-info-any PICTURE X ANY LENGTH.\n       PROCEDURE DIVISION USING stack node-info-any.\n         ALLOCATE node\n         CALL \"pointerp\" USING\n           BY REFERENCE ADDRESS OF node\n           BY REFERENCE p\n         END-CALL\n         IF nil\n           CALL \"stack-overflow-error\" END-CALL\n         ELSE\n           MOVE node-info-any TO info OF node\n           SET link OF node TO head OF stack\n           SET head OF stack TO ADDRESS OF node\n         END-IF\n         GOBACK.\n       END PROGRAM push.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. pop.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       COPY p.\n       COPY node.\n       LINKAGE SECTION.\n       COPY stack.\n       COPY node-info.\n       PROCEDURE DIVISION USING stack node-info.\n         CALL \"empty\" USING\n           BY REFERENCE stack\n           BY REFERENCE p\n         END-CALL\n         IF t\n           CALL \"stack-underflow-error\" END-CALL\n         ELSE\n           SET ADDRESS OF node TO head OF stack\n           SET head OF stack TO link OF node\n           MOVE info OF node TO node-info\n         END-IF\n         FREE ADDRESS OF node\n         GOBACK.\n       END PROGRAM pop.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. empty.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       LINKAGE SECTION.\n       COPY stack.\n       COPY p.\n       PROCEDURE DIVISION USING stack p.\n         CALL \"pointerp\" USING\n           BY CONTENT head OF stack\n           BY REFERENCE p\n         END-CALL\n         IF t\n           SET t TO FALSE\n         ELSE\n           SET t TO TRUE\n         END-IF\n         GOBACK.\n       END PROGRAM empty.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. head.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       COPY p.\n       COPY node.\n       LINKAGE SECTION.\n       COPY stack.\n       COPY node-info.\n       PROCEDURE DIVISION USING stack node-info.\n         CALL \"empty\" USING\n           BY REFERENCE stack\n           BY REFERENCE p\n         END-CALL\n         IF t\n           CALL \"stack-underflow-error\" END-CALL\n         ELSE\n           SET ADDRESS OF node TO head OF stack\n           MOVE info OF node TO node-info\n         END-IF\n         GOBACK.\n       END PROGRAM head.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. peek.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       LINKAGE SECTION.\n       COPY stack.\n       COPY node-info.\n       PROCEDURE DIVISION USING stack node-info.\n         CALL \"head\" USING\n           BY CONTENT stack\n           BY REFERENCE node-info\n         END-CALL\n         GOBACK.\n       END PROGRAM peek.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. pointerp.\n       DATA DIVISION.\n       LINKAGE SECTION.\n       01  test-pointer USAGE IS POINTER.\n       COPY p.\n       PROCEDURE DIVISION USING test-pointer p.\n         IF test-pointer EQUAL NULL\n           SET nil TO TRUE\n         ELSE\n           SET t TO TRUE\n         END-IF\n         GOBACK.\n       END PROGRAM pointerp.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. stack-overflow-error.\n       PROCEDURE DIVISION.\n         DISPLAY \"stack-overflow-error\" END-DISPLAY\n         STOP RUN.\n       END PROGRAM stack-overflow-error.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. stack-underflow-error.\n       PROCEDURE DIVISION.\n         DISPLAY \"stack-underflow-error\" END-DISPLAY\n         STOP RUN.\n       END PROGRAM stack-underflow-error.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. copy-stack.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       COPY p.\n       COPY node-info.\n       LINKAGE SECTION.\n       COPY stack.\n       COPY stack REPLACING stack BY new-stack.\n       PROCEDURE DIVISION USING stack new-stack.\n         CALL \"empty\" USING\n           BY REFERENCE stack\n           BY REFERENCE p\n         END-CALL\n         IF nil\n           CALL \"pop\" USING\n             BY REFERENCE stack\n             BY REFERENCE node-info\n           END-CALL\n           CALL \"copy-stack\" USING\n             BY REFERENCE stack\n             BY REFERENCE new-stack\n           END-CALL\n           CALL \"push\" USING\n             BY REFERENCE stack\n             BY REFERENCE node-info\n           END-CALL\n           CALL \"push\" USING\n             BY REFERENCE new-stack\n             BY REFERENCE node-info\n           END-CALL\n         END-IF\n         GOBACK.\n       END PROGRAM copy-stack.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. reverse-stack.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       COPY p.\n       COPY node-info.\n       LINKAGE SECTION.\n       COPY stack.\n       COPY stack REPLACING stack BY new-stack.\n       PROCEDURE DIVISION USING stack new-stack.\n         CALL \"empty\" USING\n           BY REFERENCE stack\n           BY REFERENCE p\n         END-CALL\n         IF nil\n           CALL \"pop\" USING\n             BY REFERENCE stack\n             BY REFERENCE node-info\n           END-CALL\n           CALL \"push\" USING\n             BY REFERENCE new-stack\n             BY REFERENCE node-info\n           END-CALL\n           CALL \"reverse-stack\" USING\n             BY REFERENCE stack\n             BY REFERENCE new-stack\n           END-CALL\n           CALL \"push\" USING\n             BY REFERENCE stack\n             BY REFERENCE node-info\n           END-CALL\n         END-IF\n         GOBACK.\n       END PROGRAM reverse-stack.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. traverse-stack.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       COPY p.\n       COPY node-info.\n       COPY stack REPLACING stack BY new-stack.\n       LINKAGE SECTION.\n       COPY stack.\n       PROCEDURE DIVISION USING stack.\n         CALL \"copy-stack\" USING\n           BY REFERENCE stack\n           BY REFERENCE new-stack\n         END-CALL\n         CALL \"empty\" USING\n           BY REFERENCE new-stack\n           BY REFERENCE p\n         END-CALL\n         IF nil\n           CALL \"head\" USING\n             BY CONTENT new-stack\n             BY REFERENCE node-info\n           END-CALL\n           DISPLAY node-info END-DISPLAY\n           CALL \"peek\" USING\n             BY CONTENT new-stack\n             BY REFERENCE node-info\n           END-CALL\n           DISPLAY node-info END-DISPLAY\n           CALL \"pop\" USING\n             BY REFERENCE new-stack\n             BY REFERENCE node-info\n           END-CALL\n           DISPLAY node-info END-DISPLAY\n           CALL \"traverse-stack\" USING\n             BY REFERENCE new-stack\n           END-CALL\n         END-IF\n         GOBACK.\n       END PROGRAM traverse-stack.\n\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. stack-test.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       COPY stack.\n       COPY stack REPLACING stack BY new-stack.\n       PROCEDURE DIVISION.\n         CALL \"push\" USING\n           BY REFERENCE stack\n           BY CONTENT \"daleth\"\n         END-CALL\n         CALL \"push\" USING\n           BY REFERENCE stack\n           BY CONTENT \"gimel\"\n         END-CALL\n         CALL \"push\" USING\n           BY REFERENCE stack\n           BY CONTENT \"beth\"\n         END-CALL\n         CALL \"push\" USING\n           BY REFERENCE stack\n           BY CONTENT \"aleph\"\n         END-CALL\n         CALL \"traverse-stack\" USING\n           BY REFERENCE stack\n         END-CALL\n         CALL \"reverse-stack\" USING\n           BY REFERENCE stack\n           BY REFERENCE new-stack\n         END-CALL\n         CALL \"traverse-stack\" USING\n           BY REFERENCE new-stack\n         END-CALL\n         STOP RUN.\n       END PROGRAM stack-test.\n\n       COPY stack-utilities.\n\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and is accessed through its top. The 'push' operation stores a new element onto the stack top, 'pop' operation returns and removes the last pushed stack element, and 'empty' checks if the stack contains no elements. The 'top' operation returns the topmost element without modifying the stack. The stack implementation is used for resource management, particularly memory, and is common in programming, processors, and various algorithms.","id":1048}
    {"lang_cluster":"COBOL","source_code":"\nProgram-ID. Fibonacci-Sequence.\nData Division.\nWorking-Storage Section.\n  01  FIBONACCI-PROCESSING.\n    05  FIBONACCI-NUMBER  PIC 9(36)   VALUE 0.\n    05  FIB-ONE           PIC 9(36)   VALUE 0.\n    05  FIB-TWO           PIC 9(36)   VALUE 1.\n  01  DESIRED-COUNT       PIC 9(4).\n  01  FORMATTING.\n    05  INTERM-RESULT     PIC Z(35)9.\n    05  FORMATTED-RESULT  PIC X(36).\n    05  FORMATTED-SPACE   PIC x(35).\nProcedure Division.\n  000-START-PROGRAM.\n    Display \"What place of the Fibonacci Sequence would you like (<173)? \" with no advancing.\n    Accept DESIRED-COUNT.\n    If DESIRED-COUNT is less than 1\n      Stop run.\n    If DESIRED-COUNT is less than 2\n      Move FIBONACCI-NUMBER to INTERM-RESULT\n      Move INTERM-RESULT to FORMATTED-RESULT\n      Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT\n      Display FORMATTED-RESULT\n      Stop run.\n    Subtract 1 from DESIRED-COUNT.\n    Move FIBONACCI-NUMBER to INTERM-RESULT.\n    Move INTERM-RESULT to FORMATTED-RESULT.\n    Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.\n    Display FORMATTED-RESULT.\n    Perform 100-COMPUTE-FIBONACCI until DESIRED-COUNT = zero.\n    Stop run.\n  100-COMPUTE-FIBONACCI.\n    Compute FIBONACCI-NUMBER = FIB-ONE + FIB-TWO.\n    Move FIB-TWO to FIB-ONE.\n    Move FIBONACCI-NUMBER to FIB-TWO.\n    Subtract 1 from DESIRED-COUNT.\n    Move FIBONACCI-NUMBER to INTERM-RESULT.\n    Move INTERM-RESULT to FORMATTED-RESULT.\n    Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.\n    Display FORMATTED-RESULT.\nWorks with: GNU Cobol version 2.0\n       >>SOURCE FREE\nIDENTIFICATION DIVISION.\nPROGRAM-ID. fibonacci-main.\n\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  num                                 PIC 9(6) COMP.\n01  fib-num                             PIC 9(6) COMP.\n\nPROCEDURE DIVISION.\n    ACCEPT num\n    CALL \"fibonacci\" USING CONTENT num RETURNING fib-num\n    DISPLAY fib-num\n    .\nEND PROGRAM fibonacci-main.\n\nIDENTIFICATION DIVISION.\nPROGRAM-ID. fibonacci RECURSIVE.\n\nDATA DIVISION.\nLOCAL-STORAGE SECTION.\n01  1-before                            PIC 9(6) COMP.\n01  2-before                            PIC 9(6) COMP.\n\nLINKAGE SECTION.\n01  num                                 PIC 9(6) COMP.\n\n01  fib-num                             PIC 9(6) COMP BASED.\n\nPROCEDURE DIVISION USING num RETURNING fib-num.\n    ALLOCATE fib-num\n    EVALUATE num\n        WHEN 0\n            MOVE 0 TO fib-num\n        WHEN 1\n            MOVE 1 TO fib-num\n        WHEN OTHER\n            SUBTRACT 1 FROM num\n            CALL \"fibonacci\" USING CONTENT num RETURNING 1-before\n            SUBTRACT 1 FROM num\n            CALL \"fibonacci\" USING CONTENT num RETURNING 2-before\n            ADD 1-before TO 2-before GIVING fib-num\n    END-EVALUATE\n    .\nEND PROGRAM fibonacci.\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":1049}
    {"lang_cluster":"COBOL","source_code":"\n       identification division.\n       program-id. substring.\n\n       environment division.\n       configuration section.\n       repository.\n           function all intrinsic.\n\n       data division.\n       working-storage section.\n       01 original.\n          05 value \"this is a string\".\n       01 starting  pic 99 value 3.\n       01 width     pic 99 value 8.\n       01 pos       pic 99.\n       01 ender     pic 99.\n       01 looking   pic 99.\n       01 indicator pic x.\n          88 found  value high-value when set to false is low-value.\n       01 look-for  pic x(8).\n\n       procedure division.\n       substring-main.\n\n       display \"Original |\" original \"|, n = \" starting \" m = \" width\n       display original(starting : width)\n       display original(starting :)\n       display original(1 : length(original) - 1)\n\n       move \"a\" to look-for\n       move 1 to looking\n       perform find-position\n       if found\n           display original(pos : width)\n       end-if\n\n       move \"is a st\" to look-for\n       move length(trim(look-for)) to looking\n       perform find-position\n       if found\n           display original(pos : width)\n       end-if\n       goback.\n\n       find-position.\n       set found to false\n       compute ender = length(original) - looking\n       perform varying pos from 1 by 1 until pos > ender\n           if original(pos : looking) equal look-for then\n               set found to true\n               exit perform\n           end-if\n       end-perform\n       .\n\n       end program substring.\n\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":1050}
    {"lang_cluster":"COBOL","source_code":"\nFUNCTION REVERSE('QWERTY')\n\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":1051}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: OpenCOBOL\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Random-Nums.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  Num  PIC Z9.\n\n       PROCEDURE DIVISION.\n       Main.\n           PERFORM FOREVER\n               PERFORM Generate-And-Display-Num\n\n               IF Num = 10\n                   EXIT PERFORM\n               ELSE\n                   PERFORM Generate-And-Display-Num\n               END-IF\n           END-PERFORM\n\n           GOBACK\n           .\n\n       Generate-And-Display-Num.\n           COMPUTE Num =  FUNCTION REM(FUNCTION RANDOM * 100, 20)\n           DISPLAY Num\n           .\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":1052}
    {"lang_cluster":"COBOL","source_code":"\n\n       program-id. dec25.\n       data division.\n       working-storage section.\n       1 work-date.\n        2 yr pic 9(4) value 2008.\n        2 mo-da pic 9(4) value 1225. *> Dec 25\n       1 wk-date redefines work-date pic 9(8).\n       1 binary.\n        2 int-date pic 9(8).\n        2 dow pic 9(4).\n       procedure division.\n           perform varying yr from 2008 by 1\n           until yr > 2121\n               compute int-date = function integer-of-date (wk-date)\n               compute dow = function mod ((int-date - 1) 7) + 1\n               if dow = 7  *> Sunday = 7 per ISO 8601 and ISO 1989\n                   display yr\n               end-if\n           end-perform\n           stop run\n           .\n       end program dec25.\n\n\n","human_summarization":"\"Determines the years between 2008 and 2121 where Christmas falls on a Sunday using standard date handling libraries. The code also compares the results with other languages to identify any discrepancies due to issues like overflow in date\/time representation.\"","id":1053}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: Visual COBOL\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. quicksort RECURSIVE.\n       \n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       01  temp                   PIC S9(8).\n       \n       01  pivot                  PIC S9(8).\n       \n       01  left-most-idx          PIC 9(5).\n       01  right-most-idx         PIC 9(5).\n       \n       01  left-idx               PIC 9(5).\n       01  right-idx              PIC 9(5).\n       \n       LINKAGE SECTION.\n       78  Arr-Length             VALUE 50.\n       \n       01  arr-area.\n           03  arr                PIC S9(8) OCCURS Arr-Length TIMES.\n           \n       01  left-val               PIC 9(5).\n       01  right-val              PIC 9(5).  \n       \n       PROCEDURE DIVISION USING REFERENCE arr-area, OPTIONAL left-val,\n               OPTIONAL right-val.\n           IF left-val IS OMITTED OR right-val IS OMITTED\n               MOVE 1 TO left-most-idx, left-idx\n               MOVE Arr-Length TO right-most-idx, right-idx\n           ELSE\n               MOVE left-val TO left-most-idx, left-idx\n               MOVE right-val TO right-most-idx, right-idx\n           END-IF\n           \n           IF right-most-idx - left-most-idx < 1\n               GOBACK\n           END-IF\n       \n           COMPUTE pivot = arr ((left-most-idx + right-most-idx) \/ 2)\n       \n           PERFORM UNTIL left-idx > right-idx\n               PERFORM VARYING left-idx FROM left-idx BY 1\n                   UNTIL arr (left-idx) >= pivot\n               END-PERFORM\n               \n               PERFORM VARYING right-idx FROM right-idx BY -1\n                   UNTIL arr (right-idx) <= pivot\n               END-PERFORM\n               \n               IF left-idx <= right-idx\n                   MOVE arr (left-idx) TO temp\n                   MOVE arr (right-idx) TO arr (left-idx)\n                   MOVE temp TO arr (right-idx)\n                   \n                   ADD 1 TO left-idx\n                   SUBTRACT 1 FROM right-idx\n               END-IF\n           END-PERFORM\n       \n           CALL \"quicksort\" USING REFERENCE arr-area,\n               CONTENT left-most-idx, right-idx\n           CALL \"quicksort\" USING REFERENCE arr-area, CONTENT left-idx,\n               right-most-idx\n               \n           GOBACK\n           .\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":1054}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: OpenCOBOL\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Date-Format.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n\n       01  Days-Area.\n           03  Days-Data.\n               05  FILLER PIC X(9) VALUE \"Monday\".\n               05  FILLER PIC X(9) VALUE \"Tuesday\".\n               05  FILLER PIC X(9) VALUE \"Wednesday\".\n               05  FILLER PIC X(9) VALUE \"Thursday\".\n               05  FILLER PIC X(9) VALUE \"Friday\".\n               05  FILLER PIC X(9) VALUE \"Saturday\".\n               05  FILLER PIC X(9) VALUE \"Sunday\".\n\n           03  Days-Values REDEFINES Days-Data.\n               05  Days-Table PIC X(9) OCCURS 7 TIMES.\n\n       01  Months-Area.\n           03  Months-Data.\n               05  FILLER PIC X(9) VALUE \"January\".\n               05  FILLER PIC X(9) VALUE \"February\".\n               05  FILLER PIC X(9) VALUE \"March\".\n               05  FILLER PIC X(9) VALUE \"April\".\n               05  FILLER PIC X(9) VALUE \"May\".\n               05  FILLER PIC X(9) VALUE \"June\".\n               05  FILLER PIC X(9) VALUE \"July\".\n               05  FILLER PIC X(9) VALUE \"August\".\n               05  FILLER PIC X(9) VALUE \"September\".\n               05  FILLER PIC X(9) VALUE \"October\".\n               05  FILLER PIC X(9) VALUE \"November\".\n               05  FILLER PIC X(9) VALUE \"December\".\n              \n           03  Months-Values REDEFINES Months-Data.\n               05  Months-Table PIC X(9) OCCURS 12 TIMES.\n\n       01  Current-Date-Str.\n           03  Current-Year     PIC X(4).\n           03  Current-Month    PIC X(2).\n           03  Current-Day      PIC X(2).\n\n       01  Current-Day-Of-Week  PIC 9.\n\n       PROCEDURE DIVISION.\n           MOVE FUNCTION CURRENT-DATE (1:8) TO Current-Date-Str\n           \n           DISPLAY Current-Year \"-\" Current-Month \"-\" Current-Day\n\n           ACCEPT Current-Day-Of-Week FROM DAY-OF-WEEK\n           DISPLAY\n               FUNCTION TRIM(\n                   Days-Table (FUNCTION NUMVAL(Current-Day-Of-Week)))\n               \", \"\n               FUNCTION TRIM(\n                   Months-Table (FUNCTION NUMVAL(Current-Month)))\n               \" \"\n               Current-Day\n               \", \"\n               Current-Year\n           END-DISPLAY\n\n           GOBACK\n           .\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":1055}
    {"lang_cluster":"COBOL","source_code":"\nIDENTIFICATION DIVISION.\nPROGRAM-ID. TOROMAN.\nDATA DIVISION.\nworking-storage section.\n  01 ws-number pic 9(4) value 0.\n  01 ws-save-number pic 9(4).\n  01 ws-tbl-def.\n    03 filler pic x(7) value '1000M  '.\n    03 filler pic x(7) value '0900CM '.\n    03 filler pic x(7) value '0500D  '.\n    03 filler pic x(7) value '0400CD '.\n    03 filler pic x(7) value '0100C  '.\n    03 filler pic x(7) value '0090XC '.\n    03 filler pic x(7) value '0050L  '.\n    03 filler pic x(7) value '0040XL '.\n    03 filler pic x(7) value '0010X  '.\n    03 filler pic x(7) value '0009IX '.\n    03 filler pic x(7) value '0005V  '.\n    03 filler pic x(7) value '0004IV '.\n    03 filler pic x(7) value '0001I  '.\n  01  filler redefines ws-tbl-def.\n    03 filler occurs 13 times indexed by rx.\n      05 ws-tbl-divisor    pic 9(4).\n      05 ws-tbl-roman-ch   pic x(1) occurs 3 times indexed by cx.\n  01 ocx pic 99.\n  01 ws-roman.\n    03 ws-roman-ch         pic x(1) occurs 16 times.\nPROCEDURE DIVISION.\n  accept ws-number\n  perform\n  until ws-number = 0\n    move ws-number to ws-save-number\n    if ws-number > 0 and ws-number < 4000\n      initialize ws-roman\n      move 0 to ocx\n      perform varying rx from 1 by +1\n      until ws-number = 0\n        perform until ws-number < ws-tbl-divisor (rx)\n          perform varying cx from 1 by +1 \n  \t\t  until ws-tbl-roman-ch (rx, cx) = spaces\n            compute ocx = ocx + 1\n            move ws-tbl-roman-ch (rx, cx) to ws-roman-ch (ocx)\n          end-perform\n          compute ws-number = ws-number - ws-tbl-divisor (rx)\n        end-perform\n      end-perform\n      display 'inp=' ws-save-number ' roman=' ws-roman\n    else\n      display 'inp=' ws-save-number ' invalid'\n    end-if\n    accept ws-number\n  end-perform\n  .\n\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":1056}
    {"lang_cluster":"COBOL","source_code":"\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. arrays.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  fixed-length-table.\n           03  fixed-table-elt      PIC X OCCURS 5 TIMES.\n\n       01  table-length             PIC 9(5) VALUE 1.\n       01  variable-length-table.\n           03  variable-table-elt   PIC X OCCURS 1 TO 5 TIMES\n               DEPENDING ON table-length.\n\n       01  initial-value-area.\n           03  initial-values.\n               05  FILLER           PIC X(10) VALUE \"One\".\n               05  FILLER           PIC X(10) VALUE \"Two\".\n               05  FILLER           PIC X(10) VALUE \"Three\".\n           03 initial-value-table REDEFINES initial-values.\n              05  initial-table-elt PIC X(10) OCCURS 3 TIMES.\n\n       01  indexed-table.\n           03  indexed-elt          PIC X OCCURS 5 TIMES\n               INDEXED BY table-index.\n\n       PROCEDURE DIVISION.\n           *> Assigning the contents of an entire table.\n           MOVE \"12345\" TO fixed-length-table\n           \n           *>  Indexing an array (using an index)\n           MOVE 1 TO table-index\n           MOVE \"1\" TO indexed-elt (table-index)\n\n           *> Pushing a value into a variable-length table.\n           ADD 1 TO table-length\n           MOVE \"1\" TO variable-table-elt (2)\n\n           GOBACK\n           .\n\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. It includes the creation of both fixed-length and dynamic arrays, assigning values to them, and retrieving an element from them. The codes also handle the concept of arrays in COBOL, where they are referred to as tables and their indexes start from 1.","id":1057}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: COBOL 85 standard\n\n     $set ans85 flag\"ans85\" flagas\"s\" sequential\"line\"\n\n       identification division.\n       program-id. copyfile.\n       environment division.\n       input-output section.\n       file-control.\n           select input-file assign to \"input.txt\"\n               organization sequential\n           .\n           select output-file assign to \"output.txt\"\n               organization sequential\n           .\n       data division.\n       file section.\n       fd input-file.\n       1 input-record pic x(80).\n       fd output-file.\n       1 output-record pic x(80).\n       working-storage section.\n       1 end-of-file-flag pic 9 value 0.\n         88 eof value 1.\n       1 text-line pic x(80).\n       procedure division.\n       begin.\n           open input input-file\n               output output-file\n           perform read-input\n           perform until eof\n               write output-record from text-line\n               perform read-input\n           end-perform\n           close input-file output-file\n           stop run\n           .\n       read-input.\n           read input-file into text-line\n           at end\n               set eof to true\n           end-read\n           .\n       end program copyfile.\n\nWorks with: OpenCOBOL\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. file-io.\n\n       ENVIRONMENT DIVISION.\n       INPUT-OUTPUT SECTION.\n       FILE-CONTROL.\n           SELECT in-file ASSIGN \"input.txt\"\n               ORGANIZATION LINE SEQUENTIAL.\n             \n           SELECT OPTIONAL out-file ASSIGN \"output.txt\"\n               ORGANIZATION LINE SEQUENTIAL.\n\n       DATA DIVISION.\n       FILE SECTION.\n       FD  in-file.\n       01  in-line                 PIC X(256).\n\n       FD  out-file.\n       01  out-line                PIC X(256).\n       \n       PROCEDURE DIVISION.\n       DECLARATIVES.\n       in-file-error SECTION.\n           USE AFTER ERROR ON in-file.\n           DISPLAY \"An error occurred while using input.txt.\"\n           GOBACK\n           .\n       out-file-error SECTION.\n           USE AFTER ERROR ON out-file.\n           DISPLAY \"An error occurred while using output.txt.\"\n           GOBACK\n           .\n       END DECLARATIVES.\n\n       mainline.\n           OPEN INPUT in-file\n           OPEN OUTPUT out-file\n\n           PERFORM FOREVER\n               READ in-file\n                   AT END\n                       EXIT PERFORM\n               END-READ\n               WRITE out-line FROM in-line\n           END-PERFORM\n\n           CLOSE in-file, out-file\n           .\n\nWorks with: OpenCOBOL\nWorks with: Visual COBOL\n*> Originally from ACUCOBOL-GT\nCALL \"C$COPY\" USING \"input.txt\", \"output.txt\", 0\n\n*> Originally from Micro Focus COBOL\nCALL \"CBL_COPY_FILE\" USING \"input.txt\", \"output.txt\"\n\n","human_summarization":"demonstrate reading the contents of \"input.txt\" into a variable, and then writing these contents into a newly created file \"output.txt\" using Micro Focus COBOL. The process does not utilize direct copy commands but involves an intermediate variable.","id":1058}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. string-case-85.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  example PIC X(9) VALUE \"alphaBETA\".\n\n       01  result  PIC X(9).\n\n       PROCEDURE DIVISION.\n           DISPLAY \"Example: \" example\n\n           *> Using the intrinsic functions.\n           DISPLAY \"Lower-case: \" FUNCTION LOWER-CASE(example)\n\n           DISPLAY \"Upper-case: \" FUNCTION UPPER-CASE(example)\n\n           *> Using INSPECT\n           MOVE example TO result\n           INSPECT result CONVERTING \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n               TO \"abcdefghijklmnopqrstuvwxyz\"\n           DISPLAY \"Lower-case: \" result\n\n           MOVE example TO result\n           INSPECT result CONVERTING \"abcdefghijklmnopqrstuvwxyz\"\n               TO  \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n           DISPLAY \"Upper-case: \" result\n\n           GOBACK\n           .\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. string-case-extensions.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       78  example VALUE \"alphaBETA\".\n\n       01  result  PIC X(9).\n\n       PROCEDURE DIVISION.\n           DISPLAY \"Example: \" example\n\n           *> ACUCOBOL-GT\n           MOVE example TO result\n           CALL \"C$TOLOWER\" USING result, BY VALUE 9\n           DISPLAY \"Lower-case: \" result\n\n           MOVE example TO result\n           CALL \"C$TOUPPER\" USING result, BY VALUE 9\n           DISPLAY \"Upper-case: \" result\n\n           *> Visual COBOL\n           MOVE example TO result\n           CALL \"CBL_TOLOWER\" USING result, BY VALUE 9\n           DISPLAY \"Lower-case: \" result\n\n           MOVE example TO result\n           CALL \"CBL_TOUPPER\" USING result BY VALUE 9\n           DISPLAY \"Upper-case: \" result\n\n           GOBACK\n           .\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":1059}
    {"lang_cluster":"COBOL","source_code":"\n\nWorks with: GnuCOBOL\n       identification division.\n       program-id. collections.\n\n       data division.\n       working-storage section.\n       01 sample-table.\n          05 sample-record occurs 1 to 3 times depending on the-index.\n             10 sample-alpha   pic x(4).\n             10 filler         pic x value \":\".\n             10 sample-number  pic 9(4).\n             10 filler         pic x value space.\n       77 the-index            usage index.\n\n       procedure division.\n       collections-main.\n\n       set the-index to 3\n       move 1234 to sample-number(1)\n       move \"abcd\" to sample-alpha(1)\n\n       move \"test\" to sample-alpha(2)\n\n       move 6789 to sample-number(3)\n       move \"wxyz\" to sample-alpha(3)\n\n       display \"sample-table   \u00a0: \" sample-table\n       display \"sample-number(1): \" sample-number(1)\n       display \"sample-record(2): \" sample-record(2)\n       display \"sample-number(3): \" sample-number(3)\n\n      *> abend: out of bounds subscript, -debug turns on bounds check\n       set the-index down by 1\n       display \"sample-table   \u00a0: \" sample-table\n       display \"sample-number(3): \" sample-number(3)\n\n       goback.\n       end program collections.\n\n\n","human_summarization":"The code creates a collection in a statically-typed language and adds a few values to it. It demonstrates the usage of collections, arrays, and various types of linked lists. It also includes an example of a small record layout within a table in COBOL, showing how to handle fixed length records and tables in this environment. The code also demonstrates a run-time bounds check.","id":1060}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: OpenCOBOL\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Loop-N-And-Half.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  I    PIC 99.\n       01  List PIC X(45).\n\n       PROCEDURE DIVISION.\n           PERFORM FOREVER\n               *> The list to display must be built up because using\n               *> DISPLAY adds an endline at the end automatically.\n               STRING FUNCTION TRIM(List) \" \"  I  INTO List\n\n               IF I = 10\n                   EXIT PERFORM\n               END-IF\n               \n               STRING FUNCTION TRIM(List) \",\" INTO List\n\n               ADD 1 TO I\n           END-PERFORM\n\n           DISPLAY List\n\n           GOBACK\n           .\n\n\nIDENTIFICATION DIVISION.\nPROGRAM-ID. LOOP-1p5-NOADV.\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  I    PIC 99 VALUE 1.\n01\tIDISP\tPIC Z9.\nPROCEDURE DIVISION.\n\tPERFORM FOREVER\n\t\tMOVE I TO IDISP\n\t\tDISPLAY FUNCTION TRIM(IDISP) WITH NO ADVANCING\n\t\tIF I = 10\n\t\t\tEXIT PERFORM\n\t\tEND-IF\n\t\tDISPLAY \", \" WITH NO ADVANCING\n\t\tADD 1 TO I\n\tEND-PERFORM.\n\tSTOP RUN.\n\tEND-PROGRAM.\n\n\nIDENTIFICATION DIVISION.\nPROGRAM-ID. LOOP-1p5-NOADV-GOTO.\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  I\tPIC 99\tVALUE 1.\n\t88\tEND-LIST\tVALUE 10.\n01\tI-OUT\tPIC Z9.\nPROCEDURE DIVISION.\n01-LOOP.\n\tMOVE I TO I-OUT.\n\tDISPLAY FUNCTION TRIM(I-OUT) WITH NO ADVANCING.\n\tIF END-LIST GO TO 02-DONE.\n\tDISPLAY \", \" WITH NO ADVANCING.\n\tADD 1 TO I.\n\tGO TO 01-LOOP.\n02-DONE.\n\tSTOP RUN.\n\tEND-PROGRAM.\n\n\nIDENTIFICATION DIVISION.\nPROGRAM-ID. LOOP-1p5-NOADV-VARY.\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  I    \tPIC 99  VALUE 1.\n\t88\tEND-LIST\tVALUE 10.\n01\tI-OUT\tPIC Z9.\nPROCEDURE DIVISION.\n\tPERFORM WITH TEST AFTER VARYING I FROM 1 BY 1 UNTIL END-LIST \n\t\tMOVE I TO I-OUT\n\t\tDISPLAY FUNCTION TRIM(I-OUT) WITH NO ADVANCING\n\t\tIF NOT END-LIST\n\t\t\tDISPLAY \", \" WITH NO ADVANCING\n\t\tEND-IF\n\tEND-PERFORM.\n\tSTOP RUN.\n\tEND-PROGRAM.\n\n","human_summarization":"demonstrate a loop that prints a comma-separated list of numbers from 1 to 10, using separate output statements for the number and the comma within the loop body. The loop implementation uses 'DISPLAY NO ADVANCING', 'GO TO', 88-level, and 'PERFORM VARYING' in the procedure division.","id":1061}
    {"lang_cluster":"COBOL","source_code":"\nIDENTIFICATION DIVISION.\n       PROGRAM-ID.  CALEND.\n       ENVIRONMENT DIVISION.\n       INPUT-OUTPUT SECTION.\n       DATA DIVISION.\n \n       WORKING-STORAGE SECTION.\n       01  WS-DAY-NAMES-DEF.\n         03 FILLER PIC X(09) VALUE 'SUNDAY   '.\n         03 FILLER PIC X(09) VALUE 'MONDAY   '.\n         03 FILLER PIC X(09) VALUE 'TUESDAY  '.\n         03 FILLER PIC X(09) VALUE 'WEDNESDAY'.\n         03 FILLER PIC X(09) VALUE 'THURSDAY '.\n         03 FILLER PIC X(09) VALUE 'FRIDAY   '.\n         03 FILLER PIC X(09) VALUE 'SATURDAY '.\n       01  FILLER REDEFINES WS-DAY-NAMES-DEF.\n         03  WS-DAY-NAME       PIC X(09) OCCURS 07 TIMES.\n \n       01  WS-MTH-INFO-DEF.\n         03 FILLER PIC X(11) VALUE 'JANUARY  31'.\n         03 FILLER PIC X(11) VALUE 'FEBRUARY 28'.\n         03 FILLER PIC X(11) VALUE 'MARCH    31'.\n         03 FILLER PIC X(11) VALUE 'APRIL    30'.\n         03 FILLER PIC X(11) VALUE 'MAY      31'.\n         03 FILLER PIC X(11) VALUE 'JUNE     30'.\n         03 FILLER PIC X(11) VALUE 'JULY     31'.\n         03 FILLER PIC X(11) VALUE 'AUGUST   31'.\n         03 FILLER PIC X(11) VALUE 'SEPTEMBER30'.\n         03 FILLER PIC X(11) VALUE 'OCTOBER  31'.\n         03 FILLER PIC X(11) VALUE 'NOVEMBER 30'.\n         03 FILLER PIC X(11) VALUE 'DECEMBER 31'.\n       01  FILLER REDEFINES WS-MTH-INFO-DEF.\n         03  WS-MTH-INFO-TABLE OCCURS 12 TIMES.\n           05  WS-MTH-INFO-NAME   PIC X(09).\n           05  WS-MTH-INFO-DAYS   PIC 9(02).\n\n       01  WS-MTH-AREA.\n         03  WS-MTH-DD         PIC S99.\n         03  WS-DAY1           PIC   9.\n         03  WS-DAYS           PIC  99.\n         03  WS-DD             PIC   9.\n         03  WS-WK             PIC   9.\n         03  WS-MM             PIC  99.\n         03  WS-QQ             PIC  99.\n \n         03  WS-MTH-MONTH  OCCURS 12 TIMES.\n           05  WS-MTH-WEEK OCCURS 6 TIMES.\n             07  WS-DAY-FLD      OCCURS 7 TIMES.\n               09  WS-DAY        PIC ZZ.\n       01  INPDATE-RECORD.\n           05  INPD-YEAR          PIC 9(04).\n           05  FILLER             PIC X(01).\n           05  INPD-MONTH         PIC 9(02).\n           05  FILLER             PIC X(01).\n           05  INPD-DAY           PIC 9(02).\n       01  WMS-DOW                PIC 9(01).\n       01  WS-PRT                 PIC X(132).\n       01  WS-COL                 PIC  9(03) VALUE 0.\n       01  WS-PP                  PIC  9(03) VALUE 0.\n       01  WS-CFGN.\n         03  FILLER               PIC  9(03) VALUE  80.\n         03  FILLER               PIC  9(02) VALUE  5.\n         03  FILLER               PIC  9(01) VALUE  1.\n         03  FILLER               PIC  9(02) VALUE  5.\n         03  FILLER               PIC  9(01) VALUE  2.\n       01  WS-CFGW.\n         03  FILLER               PIC  9(03) VALUE 120.\n         03  FILLER               PIC  9(02) VALUE 10.\n         03  FILLER               PIC  9(01) VALUE  2.\n         03  FILLER               PIC  9(02) VALUE 10.\n         03  FILLER               PIC  9(01) VALUE  3.\n       01  WS-CFG.\n         03  WS-LS                PIC  9(03) VALUE 120.\n         03  WS-LMAR              PIC  9(02) VALUE 10.\n         03  WS-SPBD              PIC  9(01) VALUE  2.\n         03  WS-SPBC              PIC  9(02) VALUE 10.\n         03  WS-DNMW              PIC  9(01) VALUE  3.\n       PROCEDURE DIVISION.\n           MOVE '1969-01-01' TO INPDATE-RECORD\n           MOVE WS-CFGN   TO WS-CFG\n           IF  (FUNCTION MOD ( INPD-YEAR , 400 ) = 0\n           OR  (FUNCTION MOD ( INPD-YEAR , 4   ) = 0\n               AND\n               FUNCTION MOD ( INPD-YEAR , 100 ) NOT = 0))\n             MOVE 29         TO WS-MTH-INFO-DAYS (02)\n           ELSE\n             MOVE 28         TO WS-MTH-INFO-DAYS (02)\n           END-IF\n \n           PERFORM VARYING WS-MM FROM 1 BY +1\n           UNTIL WS-MM > 12\n           MOVE WS-MM TO INPD-MONTH\n           CALL 'DATE2DOW' USING INPDATE-RECORD, WMS-DOW\n           COMPUTE WS-MTH-DD = 1 - WMS-DOW\n           COMPUTE WS-DAYS = WS-MTH-INFO-DAYS (INPD-MONTH)\n           PERFORM VARYING WS-WK FROM 1 BY +1\n           UNTIL WS-WK > 6\n             PERFORM VARYING WS-DD FROM 1 BY +1\n             UNTIL WS-DD > 7\n               COMPUTE WS-MTH-DD = WS-MTH-DD + 1\n               IF (WS-MTH-DD < 1)\n               OR (WS-MTH-DD > WS-DAYS)\n                 MOVE 0         TO WS-DAY (WS-MM, WS-WK, WS-DD)\n               ELSE\n                 MOVE WS-MTH-DD TO WS-DAY (WS-MM, WS-WK, WS-DD)\n               END-IF\n             END-PERFORM\n           END-PERFORM\n           END-PERFORM\n \n           COMPUTE WS-MM = 0\n           PERFORM VARYING WS-QQ FROM 1 BY +1\n           UNTIL WS-QQ > 4\n \n             INITIALIZE WS-PRT\n             COMPUTE WS-PP = 1\n             PERFORM VARYING WS-COL FROM 1 BY +1\n             UNTIL WS-COL > 3\n             COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL\n \n               IF WS-COL = 1\n                 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW\n               ELSE\n                 COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW\n               END-IF\n               MOVE WS-MTH-INFO-NAME (WS-MM)\n                             TO WS-PRT(WS-PP:9)\n               COMPUTE WS-PP\n               =       WS-PP + ( 2 * 7 + WS-SPBD * 6 + WS-SPBD - 1)\n               -       4\n               MOVE INPD-YEAR TO WS-PRT (WS-PP:4)\n               COMPUTE WS-PP = WS-PP + 4\n             END-PERFORM\n             DISPLAY WS-PRT (1:WS-LS)\n \n             INITIALIZE WS-PRT\n             COMPUTE WS-PP = 1\n             PERFORM VARYING WS-COL FROM 1 BY +1\n             UNTIL WS-COL > 3\n             COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL\n \n               IF WS-COL = 1\n                 COMPUTE WS-PP = WS-PP + WS-LMAR + 2 - WS-DNMW\n               ELSE\n                 COMPUTE WS-PP = WS-PP + WS-SPBC + 2 - WS-DNMW\n               END-IF\n               PERFORM VARYING WS-DD FROM 1 BY +1\n               UNTIL WS-DD > 7\n                 IF WS-DD > 1\n                   COMPUTE WS-PP = WS-PP + WS-SPBD + 2 - WS-DNMW\n                 END-IF\n                 MOVE WS-DAY-NAME (WS-DD) (1:WS-DNMW)\n                             TO WS-PRT (WS-PP:WS-DNMW)\n                 COMPUTE WS-PP = WS-PP + WS-DNMW\n               END-PERFORM\n             END-PERFORM\n             DISPLAY WS-PRT (1:WS-LS)\n \n             PERFORM VARYING WS-WK FROM 1 BY +1\n             UNTIL WS-WK > 6\n               INITIALIZE WS-PRT\n               COMPUTE WS-PP = 1\n               PERFORM VARYING WS-COL FROM 1 BY +1\n               UNTIL WS-COL > 3\n               COMPUTE WS-MM = 3 * (WS-QQ - 1) + WS-COL\n \n                 IF WS-COL = 1\n                   COMPUTE WS-PP = WS-PP + WS-LMAR\n                 ELSE\n                   COMPUTE WS-PP = WS-PP + WS-SPBC\n                 END-IF\n                 PERFORM VARYING WS-DD FROM 1 BY +1\n                 UNTIL WS-DD > 7\n                   IF WS-DD > 1\n                     COMPUTE WS-PP = WS-PP + WS-SPBD\n                   END-IF\n                   MOVE WS-DAY (WS-MM, WS-WK, WS-DD)\n                               TO WS-PRT (WS-PP:2)\n                   COMPUTE WS-PP = WS-PP + 2\n                 END-PERFORM\n               END-PERFORM\n               DISPLAY WS-PRT (1:WS-LS)\n             END-PERFORM\n             DISPLAY ' '\n           END-PERFORM\n           GOBACK\n           .\n       END PROGRAM CALEND.\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID.  DATE2DOW.\n       ENVIRONMENT DIVISION.\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  WMS-WORK-AREA.\n         03  WMS-YEAR       PIC 9(04).\n         03  WMS-MONTH      PIC 9(02).\n         03  WMS-CSYS       PIC 9(01) VALUE 1.\n         03  WMS-SUM        pic 9(04).\n       LINKAGE SECTION.\n       01  INPDATE-RECORD.\n           05  INPD-YEAR          PIC 9(04).\n           05  FILLER             PIC X(01).\n           05  INPD-MONTH         PIC 9(02).\n           05  FILLER             PIC X(01).\n           05  INPD-DAY           PIC 9(02).\n       01  WMS-DOW                PIC 9(01).\n       PROCEDURE DIVISION USING INPDATE-RECORD, WMS-DOW.\n       1010-CONVERT-DATE-TO-DOW.\n           IF INPD-MONTH < 3\n               COMPUTE WMS-MONTH = INPD-MONTH + 12\n               COMPUTE WMS-YEAR  = INPD-YEAR - 1\n           ELSE\n               COMPUTE WMS-MONTH = INPD-MONTH\n               COMPUTE WMS-YEAR  = INPD-YEAR\n           END-IF\n           COMPUTE WMS-SUM  = \n                            ( INPD-DAY + 2 * WMS-MONTH + WMS-YEAR\n                            + FUNCTION INTEGER (6 * (WMS-MONTH + 1) \/ 10)\n                            + FUNCTION INTEGER ( WMS-YEAR \/ 4   )\n                            - FUNCTION INTEGER ( WMS-YEAR \/ 100 )\n                            + FUNCTION INTEGER ( WMS-YEAR \/ 400 )\n                            + WMS-CSYS )\n           COMPUTE WMS-DOW = FUNCTION MOD (WMS-SUM, 7) + 1\n           GOBACK\n           .\n       END PROGRAM DATE2DOW.\n","human_summarization":"provide an algorithm to format a calendar that fills a page 132 characters wide, with all code written in uppercase. This is inspired by 1969 era line printers and the concept that \"real programmers think in UPPERCASE\". The code does not include Snoopy generation but instead outputs a placeholder. The code and output follow the example of a \"REAL programmer\" calendar.","id":1062}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Letter-Frequency.\n       AUTHOR.  Bill Gunshannon.\n       INSTALLATION.  Home.\n       DATE-WRITTEN.  12 December 2021.\n      ************************************************************\n      ** Program Abstract:\n      **   A rather simplistic program to do the kind of thing\n      **   that COBOL does really well.                \n      ************************************************************\n       \n       ENVIRONMENT DIVISION.\n       \n       INPUT-OUTPUT SECTION.\n       FILE-CONTROL.\n            SELECT Text-File ASSIGN TO \"File.txt\"\n                 ORGANIZATION IS LINE SEQUENTIAL.\n       \n       DATA DIVISION.\n       \n       FILE SECTION.\n       \n       FD  Text-File\n           DATA RECORD IS Record-Name.\n       01  Record-Name           PIC X(80).\n       \n       \n       WORKING-STORAGE SECTION.\n       \n       01 Eof                   PIC X     VALUE 'F'.\n\n       01  Letter-cnt.\n           05  A-cnt            PIC 9(5)    VALUE 0.\n           05  B-cnt            PIC 9(5)    VALUE 0.\n           05  C-cnt            PIC 9(5)    VALUE 0.\n           05  D-cnt            PIC 9(5)    VALUE 0.\n           05  E-cnt            PIC 9(5)    VALUE 0.\n           05  F-cnt            PIC 9(5)    VALUE 0.\n           05  G-cnt            PIC 9(5)    VALUE 0.\n           05  H-cnt            PIC 9(5)    VALUE 0.\n           05  I-cnt            PIC 9(5)    VALUE 0.\n           05  J-cnt            PIC 9(5)    VALUE 0.\n           05  K-cnt            PIC 9(5)    VALUE 0.\n           05  L-cnt            PIC 9(5)    VALUE 0.\n           05  M-cnt            PIC 9(5)    VALUE 0.\n           05  N-cnt            PIC 9(5)    VALUE 0.\n           05  O-cnt            PIC 9(5)    VALUE 0.\n           05  P-cnt            PIC 9(5)    VALUE 0.\n           05  Q-cnt            PIC 9(5)    VALUE 0.\n           05  R-cnt            PIC 9(5)    VALUE 0.\n           05  S-cnt            PIC 9(5)    VALUE 0.\n           05  T-cnt            PIC 9(5)    VALUE 0.\n           05  U-cnt            PIC 9(5)    VALUE 0.\n           05  V-cnt            PIC 9(5)    VALUE 0.\n           05  W-cnt            PIC 9(5)    VALUE 0.\n           05  X-cnt            PIC 9(5)    VALUE 0.\n           05  Y-cnt            PIC 9(5)    VALUE 0.\n           05  Z-cnt            PIC 9(5)    VALUE 0.\n       \n       01  Letter-disp.\n           05  A-cnt            PIC ZZZZ9.\n           05  B-cnt            PIC ZZZZ9.\n           05  C-cnt            PIC ZZZZ9.\n           05  D-cnt            PIC ZZZZ9.\n           05  E-cnt            PIC ZZZZ9.\n           05  F-cnt            PIC ZZZZ9.\n           05  G-cnt            PIC ZZZZ9.\n           05  H-cnt            PIC ZZZZ9.\n           05  I-cnt            PIC ZZZZ9.\n           05  J-cnt            PIC ZZZZ9.\n           05  K-cnt            PIC ZZZZ9.\n           05  L-cnt            PIC ZZZZ9.\n           05  M-cnt            PIC ZZZZ9.\n           05  N-cnt            PIC ZZZZ9.\n           05  O-cnt            PIC ZZZZ9.\n           05  P-cnt            PIC ZZZZ9.\n           05  Q-cnt            PIC ZZZZ9.\n           05  R-cnt            PIC ZZZZ9.\n           05  S-cnt            PIC ZZZZ9.\n           05  T-cnt            PIC ZZZZ9.\n           05  U-cnt            PIC ZZZZ9.\n           05  V-cnt            PIC ZZZZ9.\n           05  W-cnt            PIC ZZZZ9.\n           05  X-cnt            PIC ZZZZ9.\n           05  Y-cnt            PIC ZZZZ9.\n           05  Z-cnt            PIC ZZZZ9.\n       \n       PROCEDURE DIVISION.\n       \n       Main-Program.\n           OPEN INPUT  Text-File\n           PERFORM UNTIL Eof = 'T'\n              READ  Text-File\n                    AT END MOVE 'T' to Eof\n              END-READ\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING A-cnt OF Letter-cnt  FOR ALL 'A'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING B-cnt OF Letter-cnt  FOR ALL 'B'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING C-cnt OF Letter-cnt  FOR ALL 'C'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING D-cnt OF Letter-cnt  FOR ALL 'D'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING E-cnt OF Letter-cnt  FOR ALL 'E'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING F-cnt OF Letter-cnt  FOR ALL 'F'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING G-cnt OF Letter-cnt  FOR ALL 'G'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING H-cnt OF Letter-cnt  FOR ALL 'H'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING I-cnt OF Letter-cnt  FOR ALL 'I'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING J-cnt OF Letter-cnt  FOR ALL 'J'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING K-cnt OF Letter-cnt  FOR ALL 'K'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING L-cnt OF Letter-cnt  FOR ALL 'L'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING M-cnt OF Letter-cnt  FOR ALL 'M'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING N-cnt OF Letter-cnt  FOR ALL 'N'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING O-cnt OF Letter-cnt  FOR ALL 'O'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING P-cnt OF Letter-cnt  FOR ALL 'P'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING Q-cnt OF Letter-cnt  FOR ALL 'Q'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING R-cnt OF Letter-cnt  FOR ALL 'R'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING S-cnt OF Letter-cnt  FOR ALL 'S'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING T-cnt OF Letter-cnt  FOR ALL 'T'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING U-cnt OF Letter-cnt  FOR ALL 'U'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING V-cnt OF Letter-cnt  FOR ALL 'V'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING W-cnt OF Letter-cnt  FOR ALL 'W'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING X-cnt OF Letter-cnt  FOR ALL 'X'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING Y-cnt OF Letter-cnt  FOR ALL 'Y'\n           INSPECT FUNCTION UPPER-CASE(Record-Name)\n                   TALLYING Z-cnt OF Letter-cnt  FOR ALL 'Z'\n           END-PERFORM.\n           CLOSE Text-File.\n           MOVE CORRESPONDING Letter-cnt To Letter-disp.\n           DISPLAY 'Letter Frequency Distribution'.\n           DISPLAY '-----------------------------'.\n           DISPLAY 'A\u00a0: ' A-cnt OF Letter-disp '          '\n                   'N\u00a0: ' N-cnt OF Letter-disp.\n           DISPLAY 'B\u00a0: ' B-cnt OF Letter-disp '          '\n                   'O\u00a0: ' O-cnt OF Letter-disp.\n           DISPLAY 'C\u00a0: ' C-cnt OF Letter-disp '          '\n                   'P\u00a0: ' P-cnt OF Letter-disp.\n           DISPLAY 'D\u00a0: ' D-cnt OF Letter-disp '          '\n                   'Q\u00a0: ' Q-cnt OF Letter-disp.\n           DISPLAY 'E\u00a0: ' E-cnt OF Letter-disp '          '\n                   'R\u00a0: ' R-cnt OF Letter-disp.\n           DISPLAY 'F\u00a0: ' F-cnt OF Letter-disp '          '\n                   'S\u00a0: ' S-cnt OF Letter-disp.\n           DISPLAY 'G\u00a0: ' G-cnt OF Letter-disp '          '\n                   'T\u00a0: ' T-cnt OF Letter-disp.\n           DISPLAY 'H\u00a0: ' H-cnt OF Letter-disp '          '\n                   'U\u00a0: ' U-cnt OF Letter-disp.\n           DISPLAY 'I\u00a0: ' I-cnt OF Letter-disp '          '\n                   'V\u00a0: ' V-cnt OF Letter-disp.\n           DISPLAY 'J\u00a0: ' J-cnt OF Letter-disp '          '\n                   'W\u00a0: ' W-cnt OF Letter-disp.\n           DISPLAY 'K\u00a0: ' K-cnt OF Letter-disp '          '\n                   'X\u00a0: ' X-cnt OF Letter-disp.\n           DISPLAY 'L\u00a0: ' L-cnt OF Letter-disp '          '\n                   'Y\u00a0: ' Y-cnt OF Letter-disp.\n           DISPLAY 'M\u00a0: ' M-cnt OF Letter-disp '          '\n                   'Z\u00a0: ' Z-cnt OF Letter-disp.\n           STOP RUN.\n       \n       \n       END-PROGRAM.\n\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":1063}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. FACTORS.\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  CALCULATING.\n           03  NUM  USAGE BINARY-LONG VALUE ZERO.\n           03  LIM  USAGE BINARY-LONG VALUE ZERO.\n           03  CNT  USAGE BINARY-LONG VALUE ZERO.\n           03  DIV  USAGE BINARY-LONG VALUE ZERO.\n           03  REM  USAGE BINARY-LONG VALUE ZERO.\n           03  ZRS  USAGE BINARY-SHORT VALUE ZERO.\n\n       01  DISPLAYING.\n           03  DIS  PIC 9(10) USAGE DISPLAY.\n\n       PROCEDURE DIVISION.\n       MAIN-PROCEDURE.\n           DISPLAY \"Factors of? \" WITH NO ADVANCING\n           ACCEPT NUM\n           DIVIDE NUM BY 2 GIVING LIM.\n\n           PERFORM VARYING CNT FROM 1 BY 1 UNTIL CNT > LIM\n               DIVIDE NUM BY CNT GIVING DIV REMAINDER REM\n               IF REM = 0\n                   MOVE CNT TO DIS\n                   PERFORM SHODIS\n               END-IF\n           END-PERFORM.\n\n           MOVE NUM TO DIS.\n           PERFORM SHODIS.\n           STOP RUN.\n\n       SHODIS.\n           MOVE ZERO TO ZRS.\n           INSPECT DIS TALLYING ZRS FOR LEADING ZERO.\n           DISPLAY DIS(ZRS + 1:)\n           EXIT PARAGRAPH.\n\n       END PROGRAM FACTORS.\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":1064}
    {"lang_cluster":"COBOL","source_code":"\n       identification division.\n       program-id. AlignColumns.\n\n       data division.\n       working-storage section.\n      *>-> Constants\n       78 MAX-LINES value 6.\n       78 MAX-LINE-SIZE value 66.\n       78 MAX-COLUMNS value 12.\n       78 MAX-COLUMN-SIZE value 16.\n      *>-> Indexes\n       01 w-idx                   pic is 9(2).\n       01 w-idy                   pic is 9(2).\n       01 w-pos                   pic is 9(3).\n      *>-> Data structures\n       01 w-lines.\n          05 w-line               pic is x(MAX-LINE-SIZE) occurs MAX-LINES.\n       01 w-column-sizes.\n          05 w-column-size        pic is 99 occurs MAX-COLUMNS value zeros.\n       01 w-matrix.\n          05 filler               occurs MAX-LINES.\n             10 filler            occurs MAX-COLUMNS.\n                15 w-content      pic is x(MAX-COLUMN-SIZE).\n      *>-> Output\n       01 w-line-out              pic is x(120).\n      *>-> Data alignment\n       01 w-alignment             pic is x(1).\n          88 alignment-left       value is \"L\".\n          88 alignment-center     value is \"C\".\n          88 alignment-right      value is \"R\".\n\n       procedure division.\n       main.\n           move \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\" to w-line(1)\n           move \"are$delineated$by$a$single$'dollar'$character,$write$a$program\" to w-line(2)\n           move \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\" to w-line(3)\n           move \"column$are$separated$by$at$least$one$space.\" to w-line(4)\n           move \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\" to w-line(5)\n           move \"justified,$right$justified,$or$center$justified$within$its$column.\" to w-line(6)\n           perform calculate-size-columns\n           set alignment-left to true\n           perform show-content\n           set alignment-center to true\n           perform show-content\n           set alignment-right to true\n           perform show-content\n           goback\n           .\n       calculate-size-columns.\n           perform\n              varying             w-idx from 1 by 1\n                 until            w-idx > MAX-LINES\n              unstring w-line(w-idx) delimited by \"$\" into w-content(w-idx, 1), w-content(w-idx, 2), \n                  w-content(w-idx, 3), w-content(w-idx, 4), w-content(w-idx, 5), w-content(w-idx, 6), \n                  w-content(w-idx, 7), w-content(w-idx, 8), w-content(w-idx, 9), w-content(w-idx, 10), \n                  w-content(w-idx, 11), w-content(w-idx, 12),\n              perform\n                 varying          w-idy from 1 by 1\n                    until         w-idy > MAX-COLUMNS\n                 if function stored-char-length(w-content(w-idx, w-idy)) > w-column-size(w-idy)\n                    move function stored-char-length(w-content(w-idx, w-idy)) to w-column-size(w-idy)\n                 end-if\n              end-perform\n           end-perform\n           .\n       show-content.\n           move all \"-\" to w-line-out\n           display w-line-out\n           perform\n              varying             w-idx from 1 by 1\n                 until            w-idx > MAX-LINES\n              move spaces to w-line-out\n              move 1 to w-pos\n              perform\n                 varying          w-idy from 1 by 1\n                    until         w-idy > MAX-COLUMNS\n                 call \"C$JUSTIFY\" using w-content(w-idx, w-idy)(1:w-column-size(w-idy)), w-alignment\n                 move w-content(w-idx, w-idy) to w-line-out(w-pos:w-column-size(w-idy))\n                 compute w-pos = w-pos + w-column-size(w-idy) + 1\n              end-perform\n              display w-line-out\n           end-perform\n           .\n\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":1065}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: COBOL-85\n\nFORMAT IDENTIFICATION DIVISION.\n       PROGRAM-ID. rot-13.\n\n       DATA DIVISION.\n       LINKAGE SECTION.\n       77  in-str       PIC X(100).\n       77  out-str      PIC X(100).\n\n       PROCEDURE DIVISION USING BY REFERENCE in-str, out-str.\n           MOVE in-str TO out-str\n           INSPECT out-str\n               CONVERTING \"abcdefghijklmnopqrstuvwxyz\"\n               TO \"nopqrstuvwxyzabcdefghijklm\"\n           INSPECT out-str\n               CONVERTING \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n               TO \"NOPQRSTUVWXYZABCDEFGHIJKLM\"\n           EXIT PROGRAM.\n\n       END PROGRAM rot-13.\n\nWorks with: COBOL 2002\n\nIDENTIFICATION DIVISION.\nFUNCTION-ID. rot-13.\n\nDATA DIVISION.\nLOCAL-STORAGE SECTION.\n01  STR-LENGTH   CONSTANT AS 100.\n01  normal-lower CONSTANT AS \"abcdefghijklmnopqrstuvwxyz\".\n01  rot13-lower  CONSTANT AS \"nopqrstuvwxyzabcdefghijklm\".\n01  normal-upper CONSTANT AS \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".\n01  rot13-upper  CONSTANT AS \"NOPQRSTUVWXYZABCDEFGHIJKLM\".\nLINKAGE SECTION.\n77  in-str       PICTURE IS X(STR-LENGTH).\n77  out-str      PICTURE IS X(STR-LENGTH).\n\nPROCEDURE DIVISION USING in-str, RETURNING out-str.\n    MOVE in-str TO out-str\n    INSPECT out-str CONVERTING normal-lower TO rot13-lower\n    INSPECT out-str CONVERTING normal-upper TO rot13-upper\n    GOBACK.\n\nEND FUNCTION rot-13.\n\n","human_summarization":"The code implements a rot-13 function, which is a mono-alphabetic substitution cipher that replaces each letter in the ASCII alphabet with the letter 13 positions ahead, wrapping from 'z' to 'a' as needed. This function is optionally wrapped in a utility program similar to a common UNIX utility, processing files line by line or acting as a filter on its standard input. It preserves case and passes all non-alphabetic characters without alteration. The code also includes a modern version with a user-defined function and compile-time constants, following strict COBOL-85 implementation.","id":1066}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Display-Triangle.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  Outer-Counter PIC 9.\n       01  Inner-Counter PIC 9. \n\n       PROCEDURE DIVISION.\n       PERFORM VARYING Outer-Counter FROM 1 BY 1 UNTIL 5 < Outer-Counter\n\n           PERFORM VARYING Inner-Counter FROM 1 BY 1\n                   UNTIL Outer-Counter < Inner-Counter\n               DISPLAY \"*\" NO ADVANCING\n           END-PERFORM\n\n           DISPLAY \"\" *> Output a newline\n       END-PERFORM\n\n       GOBACK\n       .\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":1067}
    {"lang_cluster":"COBOL","source_code":"Works with: COBOL version 2002\nWorks with: OpenCOBOL version 1.1\n\n       *>* Ethiopian multiplication\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. ethiopian-multiplication.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       01  l                  PICTURE 9(10) VALUE 17.\n       01  r                  PICTURE 9(10) VALUE 34.\n       01  ethiopian-multiply PICTURE 9(20).\n       01  product            PICTURE 9(20).\n       PROCEDURE DIVISION.\n         CALL \"ethiopian-multiply\" USING\n           BY CONTENT l, BY CONTENT r,\n           BY REFERENCE ethiopian-multiply\n         END-CALL\n         DISPLAY ethiopian-multiply END-DISPLAY\n         MULTIPLY l BY r GIVING product END-MULTIPLY\n         DISPLAY product END-DISPLAY\n         STOP RUN.\n       END PROGRAM ethiopian-multiplication.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. ethiopian-multiply.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       01  evenp   PICTURE 9.\n         88 even   VALUE 1.\n         88 odd    VALUE 0.\n       LINKAGE SECTION.\n       01  l       PICTURE 9(10).\n       01  r       PICTURE 9(10).\n       01  product PICTURE 9(20) VALUE ZERO.\n       PROCEDURE DIVISION using l, r, product.\n         MOVE ZEROES TO product\n         PERFORM UNTIL l EQUAL ZERO\n           CALL \"evenp\" USING\n             BY CONTENT l,\n             BY REFERENCE evenp\n           END-CALL\n           IF odd\n             ADD r TO product GIVING product END-ADD\n           END-IF\n           CALL \"halve\" USING\n             BY CONTENT l,\n             BY REFERENCE l\n           END-CALL\n           CALL \"twice\" USING\n             BY CONTENT r,\n             BY REFERENCE r\n           END-CALL\n         END-PERFORM\n         GOBACK.\n       END PROGRAM ethiopian-multiply.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. halve.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       LINKAGE SECTION.\n       01  n   PICTURE 9(10).\n       01  m   PICTURE 9(10).\n       PROCEDURE DIVISION USING n, m.\n         DIVIDE n BY 2 GIVING m END-DIVIDE\n         GOBACK.\n       END PROGRAM halve.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. twice.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       LINKAGE SECTION.\n       01  n   PICTURE 9(10).\n       01  m   PICTURE 9(10).\n       PROCEDURE DIVISION USING n, m.\n         MULTIPLY n by 2 GIVING m END-MULTIPLY\n         GOBACK.\n       END PROGRAM twice.\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. evenp.\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       01  q   PICTURE 9(10).\n       LINKAGE SECTION.\n       01  n   PICTURE 9(10).\n       01  m   PICTURE 9(1).\n         88 even   VALUE 1.\n         88 odd    VALUE 0.\n       PROCEDURE DIVISION USING n, m.\n         DIVIDE n BY 2 GIVING q REMAINDER m END-DIVIDE\n         SUBTRACT m FROM 1 GIVING m END-SUBTRACT\n         GOBACK.\n       END PROGRAM evenp.\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. It then uses these functions to implement the Ethiopian multiplication method. This method involves repeatedly halving the first number and doubling the second number, discarding rows where the first number is even, and summing the remaining values in the second column to get the product of the original two numbers. In the case of COBOL, the doubling function is named 'twice' due to 'double' being a reserved word.","id":1068}
    {"lang_cluster":"COBOL","source_code":"\n        >>SOURCE FORMAT FREE\n*> This code is dedicated to the public domain\n*> This is GNUCobol 2.0\nidentification division.\nprogram-id. twentyfoursolve.\nenvironment division.\nconfiguration section.\nrepository. function all intrinsic.\ninput-output section.\nfile-control.\n    select count-file\n        assign to count-file-name\n        file status count-file-status\n        organization line sequential.\ndata division.\nfile section.\nfd  count-file.\n01  count-record pic x(7).\n\nworking-storage section.\n01  count-file-name pic x(64) value 'solutioncounts'.\n01  count-file-status pic xx.\n\n01  command-area.\n    03  nd pic 9.\n    03  number-definition.\n        05  n occurs 4 pic 9.\n    03  number-definition-9 redefines number-definition\n        pic 9(4).\n    03  command-input pic x(16).\n    03  command pic x(5).\n    03  number-count pic 9999.\n    03  l1 pic 99.\n    03  l2 pic 99.\n    03  expressions pic zzz,zzz,zz9.\n\n01  number-validation.\n    03  px pic 99.\n    03  permutations value\n          '1234'\n        & '1243'\n        & '1324'\n        & '1342'\n        & '1423'\n        & '1432'\n\n        & '2134'\n        & '2143'\n        & '2314'\n        & '2341'\n        & '2413'\n        & '2431'\n\n        & '3124'\n        & '3142'\n        & '3214'\n        & '3241'\n        & '3423'\n        & '3432'\n\n        & '4123'\n        & '4132'\n        & '4213'\n        & '4231'\n        & '4312'\n        & '4321'.\n        05  permutation occurs 24 pic x(4).\n    03  cpx pic 9.\n    03  current-permutation pic x(4).\n    03  od1 pic 9.\n    03  od2 pic 9.\n    03  od3 pic 9.\n    03  operator-definitions pic x(4) value '+-*\/'.\n    03  cox pic 9.\n    03  current-operators pic x(3).\n    03  rpn-forms value\n          'nnonono'\n        & 'nnonnoo'\n        & 'nnnonoo'\n        & 'nnnoono'\n        & 'nnnnooo'.\n        05  rpn-form occurs 5 pic x(7).\n    03  rpx pic 9.\n    03  current-rpn-form pic x(7).\n\n01  calculation-area.\n    03  oqx pic 99.\n    03  output-queue pic x(7).\n    03  work-number pic s9999.\n    03  top-numerator pic s9999 sign leading separate.\n    03  top-denominator pic s9999 sign leading separate.\n    03  rsx pic 9.\n    03  result-stack occurs 8.\n        05  numerator pic s9999.\n        05  denominator pic s9999.\n    03  divide-by-zero-error pic x.\n\n01  totals.\n    03  s pic 999.\n    03  s-lim pic 999 value 600.\n    03  s-max pic 999 value 0.\n    03  solution occurs 600 pic x(7).\n    03  sc pic 999.\n    03  sc1 pic 999.\n    03  sc2 pic 9.\n    03  sc-max pic 999 value 0.\n    03  sc-lim pic 999 value 600.\n    03  solution-counts value zeros.\n        05  solution-count occurs 600 pic 999.\n    03  ns pic 9999.\n    03  ns-max pic 9999 value 0.\n    03  ns-lim pic 9999 value 6561.\n    03  number-solutions occurs 6561.\n        05 ns-number pic x(4).\n        05 ns-count pic 999.\n    03  record-counts pic 9999.\n    03  total-solutions pic 9999.\n\n01  infix-area.\n    03  i pic 9.\n    03  i-s pic 9.\n    03  i-s1 pic 9.\n    03  i-work pic x(16).\n    03  i-stack occurs 7 pic x(13).\n\nprocedure division.\nstart-twentyfoursolve.\n    display 'start twentyfoursolve'\n    perform display-instructions\n    perform get-command\n    perform until command-input = spaces\n        display space\n        initialize command number-count\n        unstring command-input delimited by all space\n            into command number-count\n        move command-input to number-definition\n        move spaces to command-input\n        evaluate command\n        when 'h'\n        when 'help'\n            perform display-instructions\n        when 'list'\n            if ns-max = 0\n                perform load-solution-counts\n            end-if\n            perform list-counts\n        when 'show'\n            if ns-max = 0\n                perform load-solution-counts\n            end-if\n            perform show-numbers\n        when other\n            if number-definition-9 not numeric\n                display 'invalid number'\n            else\n                perform get-solutions\n                perform display-solutions\n            end-if\n        end-evaluate\n        if command-input = spaces\n            perform get-command\n        end-if\n    end-perform\n    display 'exit twentyfoursolve'\n    stop run\n    .\ndisplay-instructions.\n    display space\n    display 'enter a number  as four integers from 1-9 to see its solutions'\n    display 'enter list to see counts of solutions for all numbers'\n    display 'enter show  to see numbers having  solutions'\n    display ' ends the program'\n    .\nget-command.\n    display space\n    move spaces to command-input\n    display '(h for help)?' with no advancing\n    accept command-input\n    .\nask-for-more.\n    display space\n    move 0 to l1\n    add 1 to l2\n    if l2 = 10\n        display 'more ()?' with no advancing\n        accept command-input\n        move 0 to l2\n    end-if\n    .\nlist-counts. \n    add 1 to sc-max giving sc\n    display 'there are ' sc ' solution counts'\n    display space\n    display 'solutions\/numbers'\n    move 0 to l1\n    move 0 to l2\n    perform varying sc from 1 by 1 until sc > sc-max\n    or command-input <> spaces\n        if solution-count(sc) > 0\n            subtract 1 from sc giving sc1 *> offset to capture zero counts\n            display sc1 '\/' solution-count(sc) space with no advancing\n            add 1 to l1\n            if l1 = 8\n                perform ask-for-more\n            end-if\n        end-if\n    end-perform\n    if l1 > 0\n        display space\n    end-if\n    .\nshow-numbers. *> with number-count solutions\n    add 1 to number-count giving sc1 *> offset for zero count\n    evaluate true\n    when number-count >= sc-max\n        display 'no number has ' number-count ' solutions'\n        exit paragraph\n    when solution-count(sc1) = 1 and number-count = 1\n        display '1 number has 1 solution'\n    when solution-count(sc1) = 1\n        display '1 number has ' number-count ' solutions'\n    when number-count = 1\n        display solution-count(sc1) ' numbers have 1 solution'\n    when other\n        display solution-count(sc1) ' numbers have ' number-count ' solutions'\n    end-evaluate\n    display space\n    move 0 to l1\n    move 0 to l2\n    perform varying ns from 1 by 1 until ns > ns-max\n    or command-input <> spaces\n        if ns-count(ns) = number-count\n            display ns-number(ns) space with no advancing\n            add 1 to l1\n            if l1 = 14\n                perform ask-for-more\n            end-if\n        end-if\n    end-perform\n    if l1 > 0\n        display space\n    end-if\n    .\ndisplay-solutions.\n    evaluate s-max\n    when 0 display number-definition ' has no solutions'\n    when 1 display number-definition ' has 1 solution'\n    when other display number-definition ' has ' s-max ' solutions'\n    end-evaluate\n    display space\n    move 0 to l1\n    move 0 to l2\n    perform varying s from 1 by 1 until s > s-max\n    or command-input <> spaces\n        *> convert rpn solution(s) to infix\n        move 0 to i-s\n        perform varying i from 1 by 1 until i > 7\n            if solution(s)(i:1) >= '1' and <= '9'\n                add 1 to i-s\n                move solution(s)(i:1) to i-stack(i-s)\n            else\n                subtract 1 from i-s giving i-s1\n                move spaces to i-work\n                string '(' i-stack(i-s1) solution(s)(i:1) i-stack(i-s) ')'\n                    delimited by space into i-work\n                move i-work to i-stack(i-s1)\n                subtract 1 from i-s\n            end-if\n        end-perform\n        display solution(s) space i-stack(1) space space with no advancing\n        add 1 to l1\n        if l1 = 3\n            perform ask-for-more\n        end-if\n    end-perform\n    if l1 > 0\n        display space\n    end-if\n    .\nload-solution-counts.\n    move 0 to ns-max *> numbers and their solution count\n    move 0 to sc-max *> solution counts\n    move spaces to count-file-status\n    open input count-file\n    if count-file-status <> '00'\n        perform create-count-file\n        move 0 to ns-max *> numbers and their solution count\n        move 0 to sc-max *> solution counts\n        open input count-file\n    end-if\n    read count-file\n    move 0 to record-counts\n    move zeros to solution-counts\n    perform until count-file-status <> '00'\n        add 1 to record-counts\n        perform increment-ns-max\n        move count-record to number-solutions(ns-max)\n        add 1 to ns-count(ns-max) giving sc *> offset 1 for zero counts\n        if sc > sc-lim\n            display 'sc ' sc ' exceeds sc-lim ' sc-lim\n            stop run\n        end-if\n        if sc > sc-max\n            move sc to sc-max\n        end-if\n        add 1 to solution-count(sc)\n        read count-file\n    end-perform\n    close count-file\n    .\ncreate-count-file.\n    open output count-file\n    display 'Counting solutions for all numbers'\n    display 'We will examine 9*9*9*9 numbers'\n    display 'For each number we will examine 4! permutations of the digits'\n    display 'For each permutation we will examine 4*4*4 combinations of operators'\n    display 'For each permutation and combination we will examine 5 rpn forms'\n    display 'We will count the number of unique solutions for the given number'\n    display 'Each number and its counts will be written to file ' trim(count-file-name)\n    compute expressions = 9*9*9*9*factorial(4)*4*4*4*5\n    display 'So we will evaluate ' trim(expressions) ' statements'\n    display 'This will take a few minutes'\n    display 'In the future if ' trim(count-file-name) ' exists, this step will be bypassed'\n    move 0 to record-counts\n    move 0 to total-solutions\n    perform varying n(1) from 1 by 1 until n(1) = 0\n        perform varying n(2) from 1 by 1 until n(2) = 0\n            display n(1) n(2) '..' *> show progress\n            perform varying n(3) from 1 by 1 until n(3) = 0\n                perform varying n(4) from 1 by 1 until n(4) = 0\n                    perform get-solutions\n                    perform increment-ns-max\n                    move number-definition to ns-number(ns-max)\n                    move s-max to ns-count(ns-max)\n                    move number-solutions(ns-max) to count-record\n                    write count-record\n                    add s-max to total-solutions\n                    add 1 to record-counts\n                    add 1 to ns-count(ns-max) giving sc *> offset by 1 for zero counts\n                    if sc > sc-lim\n                        display 'error: ' sc ' solution count exceeds ' sc-lim\n                        stop run\n                    end-if\n                    add 1 to solution-count(sc)\n                end-perform\n            end-perform\n        end-perform\n    end-perform\n    close count-file\n    display record-counts ' numbers and counts written to ' trim(count-file-name)\n    display total-solutions ' total solutions'\n    display space\n    .\nincrement-ns-max.\n    if ns-max >= ns-lim\n        display 'error: numbers exceeds ' ns-lim\n        stop run\n    end-if\n    add 1 to ns-max\n    .\nget-solutions.\n    move 0 to s-max\n    perform varying px from 1 by 1 until px > 24\n        move permutation(px) to current-permutation\n        perform varying od1 from 1 by 1 until od1 > 4\n            move operator-definitions(od1:1) to current-operators(1:1)\n            perform varying od2 from 1 by 1 until od2 > 4\n                move operator-definitions(od2:1) to current-operators(2:1)\n                perform varying od3 from 1 by 1 until od3 > 4\n                    move operator-definitions(od3:1) to current-operators(3:1)\n                    perform varying rpx from 1 by 1 until rpx > 5\n                        move rpn-form(rpx) to current-rpn-form\n                        move 0 to cpx cox\n                        move spaces to output-queue\n                        perform varying oqx from 1 by 1 until oqx > 7\n                            if current-rpn-form(oqx:1) = 'n'\n                                add 1 to cpx\n                                move current-permutation(cpx:1) to nd\n                                move n(nd) to output-queue(oqx:1)\n                            else\n                                add 1 to cox\n                                move current-operators(cox:1) to output-queue(oqx:1)\n                            end-if\n                        end-perform\n                        perform evaluate-rpn\n                        if divide-by-zero-error = space\n                        and 24 * top-denominator = top-numerator\n                            perform varying s from 1 by 1 until s > s-max\n                            or solution(s) = output-queue\n                                continue\n                            end-perform\n                            if s > s-max\n                                if s >= s-lim\n                                    display 'error: solutions ' s ' for ' number-definition ' exceeds ' s-lim\n                                    stop run\n                                end-if\n                                move s to s-max\n                                move output-queue to solution(s-max)\n                            end-if\n                        end-if\n                    end-perform\n                end-perform\n            end-perform\n        end-perform\n    end-perform\n    .\nevaluate-rpn.\n    move space to divide-by-zero-error\n    move 0 to rsx *> stack depth\n    perform varying oqx from 1 by 1 until oqx > 7\n        if output-queue(oqx:1) >= '1' and <= '9'\n            *> push the digit onto the stack\n            add 1 to rsx\n            move top-numerator to numerator(rsx)\n            move top-denominator to denominator(rsx)\n            move output-queue(oqx:1) to top-numerator\n            move 1 to top-denominator\n        else\n            *> apply the operation\n            evaluate output-queue(oqx:1)\n            when '+'\n                compute top-numerator = top-numerator * denominator(rsx)\n                    + top-denominator * numerator(rsx)\n                compute top-denominator = top-denominator * denominator(rsx)\n            when '-'\n                compute top-numerator = top-denominator * numerator(rsx)\n                    - top-numerator * denominator(rsx)\n                compute top-denominator = top-denominator * denominator(rsx)\n            when '*'\n                compute top-numerator = top-numerator * numerator(rsx)\n                compute top-denominator = top-denominator * denominator(rsx)\n            when '\/'\n                compute work-number = numerator(rsx) * top-denominator\n                compute top-denominator = denominator(rsx) * top-numerator\n                if top-denominator = 0\n                    move 'y' to divide-by-zero-error\n                    exit paragraph\n                end-if\n                move work-number to top-numerator\n            end-evaluate\n            *> pop the stack\n            subtract 1 from rsx\n        end-if\n    end-perform\n    .\nend program twentyfoursolve.\n\n\n","human_summarization":"The code accepts four digits, either from user input or randomly generated, and calculates arithmetic expressions following the 24 game rules. It also displays examples of the solutions it generates.","id":1069}
    {"lang_cluster":"COBOL","source_code":"\n\n\nMOVE FUNCTION FACTORIAL(num) TO result\n\nWorks with: GnuCOBOL\n       IDENTIFICATION DIVISION.\n       FUNCTION-ID. factorial_iterative.\n\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       01  i      PIC 9(38).\n\n       LINKAGE SECTION.\n       01  n      PIC 9(38).\n       01  ret    PIC 9(38).\n\n       PROCEDURE DIVISION USING BY VALUE n RETURNING ret.\n           MOVE 1 TO ret\n \n           PERFORM VARYING i FROM 2 BY 1 UNTIL n < i\n               MULTIPLY i BY ret\n           END-PERFORM\n \n           GOBACK.\n\n       END FUNCTION factorial_iterative.\n\nWorks with: Visual COBOL\nWorks with: GnuCOBOL\n       IDENTIFICATION DIVISION.\n       FUNCTION-ID. factorial_recursive.\n\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       01  prev-n PIC 9(38).\n\n       LINKAGE SECTION.\n       01  n      PIC 9(38).\n       01  ret    PIC 9(38).\n\n       PROCEDURE DIVISION USING BY VALUE n RETURNING ret.\n           IF n = 0\n               MOVE 1 TO ret\n           ELSE\n               SUBTRACT 1 FROM n GIVING prev-n\n               MULTIPLY n BY factorial_recursive(prev-n) GIVING ret\n           END-IF\n \n           GOBACK.\n\n       END FUNCTION factorial_recursive.\nWorks with: GnuCOBOL\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. factorial_test.\n\n       ENVIRONMENT DIVISION.\n       CONFIGURATION SECTION.\n       REPOSITORY.\n           FUNCTION factorial_iterative\n           FUNCTION factorial_recursive.\n\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       01  i      PIC 9(38).\n\n       PROCEDURE DIVISION.\n           DISPLAY\n               \"i = \"\n               WITH NO ADVANCING\n           END-DISPLAY.\n           ACCEPT i END-ACCEPT.\n           DISPLAY SPACE END-DISPLAY.\n\n           DISPLAY\n               \"factorial_iterative(i) = \"\n               factorial_iterative(i)\n           END-DISPLAY.\n\n           DISPLAY\n               \"factorial_recursive(i) = \"\n               factorial_recursive(i)\n           END-DISPLAY.\n\n           GOBACK.\n\n       END PROGRAM factorial_test.\n\n","human_summarization":"The code is a function that calculates the factorial of a given number. It can be implemented either iteratively or recursively. The function does not necessarily handle negative input errors. It does not need to check for negative parameters as they are unsigned. The function is related to the task of generating Primorial numbers. In COBOL, it uses an intrinsic function to return the factorial of its argument.","id":1070}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. RANDOM.\n       AUTHOR.  Bill Gunshannon\n       INSTALLATION.  Home.\n       DATE-WRITTEN.  14 January 2022.\n      ************************************************************\n      ** Program Abstract:\n      **   Able to get the Mean to be really close to 1.0 but\n      **     couldn't get the Standard Deviation any closer than\n      **     .3 to .4.\n      ************************************************************\n       \n       DATA DIVISION.\n       \n       WORKING-STORAGE SECTION.\n       \n       01  Sample-Size          PIC 9(5)         VALUE 1000.\n       01  Total                PIC 9(10)V9(5)  VALUE 0.0.\n       01  Arith-Mean           PIC 999V999  VALUE 0.0.\n       01  Std-Dev              PIC 999V999  VALUE 0.0.\n       01  Seed                 PIC 999V999.\n       01  TI                   PIC 9(8).\n\n       01  Idx                  PIC 99999     VALUE 0.\n       01  Intermediate         PIC 9(10)V9(5)  VALUE 0.0.\n       01  Rnd-Work.\n           05  Rnd-Tbl \n                   OCCURS 1 TO 99999 TIMES DEPENDING ON Sample-Size.\n               10  Rnd              PIC 9V9999999  VALUE 0.0.\n       \n       PROCEDURE DIVISION.\n       \n       Main-Program.\n           ACCEPT TI FROM TIME.\n           MOVE FUNCTION RANDOM(TI) TO Seed.\n           PERFORM WITH TEST AFTER VARYING Idx \n                   FROM 1 BY 1 \n                   UNTIL Idx = Sample-Size\n              COMPUTE Intermediate = \n                           (FUNCTION RANDOM() * 2.01) \n              MOVE Intermediate TO Rnd(Idx)\n           END-PERFORM.\n           PERFORM WITH TEST AFTER VARYING Idx \n                   FROM 1 BY 1 \n                   UNTIL Idx = Sample-Size \n              COMPUTE Total = Total + Rnd(Idx)\n           END-PERFORM.\n\n\n           COMPUTE Arith-Mean = Total \/ Sample-Size.\n           DISPLAY \"Mean: \" Arith-Mean.\n\n\n           PERFORM WITH TEST AFTER VARYING Idx\n                   FROM 1 BY 1\n                   UNTIL Idx = Sample-Size\n              COMPUTE Intermediate = \n                      Intermediate + (Rnd(Idx) - Arith-Mean) ** 2\n           END-PERFORM.\n              COMPUTE Std-Dev = Intermediate \/ Sample-Size.\n\n\n           DISPLAY \"Std-Dev: \" Std-Dev.\n\n           STOP RUN.\n       \n       END PROGRAM RANDOM.\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":1071}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: GNU Cobol version 2.0\nWorks with: Visual COBOL\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. input-loop.\n       \n       ENVIRONMENT DIVISION.\n       INPUT-OUTPUT SECTION.\n       FILE-CONTROL.\n           SELECT in-stream ASSIGN TO KEYBOARD *> or any other file\/stream\n               ORGANIZATION LINE SEQUENTIAL\n               FILE STATUS in-stream-status.\n               \n       DATA DIVISION.\n       FILE SECTION.\n       FD  in-stream.\n       01  stream-line                 PIC X(80).\n       \n       WORKING-STORAGE SECTION.\n       01  in-stream-status            PIC 99.\n           88  end-of-stream           VALUE 10.\n       \n       PROCEDURE DIVISION.\n           OPEN INPUT in-stream\n           \n           PERFORM UNTIL EXIT\n               READ in-stream\n                   AT END\n                       EXIT PERFORM\n               END-READ\n               DISPLAY stream-line\n           END-PERFORM\n           \n           CLOSE in-stream\n           .\n       END PROGRAM input-loop.\n\n","human_summarization":"\"Continuously read words or lines from a text stream until there is no more data available.\"","id":1072}
    {"lang_cluster":"COBOL","source_code":"\n       WORKING-STORAGE SECTION.\n       01  WS-CURRENT-DATE-FIELDS.\n           05  WS-CURRENT-DATE.\n               10  WS-CURRENT-YEAR    PIC  9(4).\n               10  WS-CURRENT-MONTH   PIC  9(2).\n               10  WS-CURRENT-DAY     PIC  9(2).\n           05  WS-CURRENT-TIME.\n               10  WS-CURRENT-HOUR    PIC  9(2).\n               10  WS-CURRENT-MINUTE  PIC  9(2).\n               10  WS-CURRENT-SECOND  PIC  9(2).\n               10  WS-CURRENT-MS      PIC  9(2).\n           05  WS-DIFF-FROM-GMT       PIC S9(4).\n \n       PROCEDURE DIVISION.\n           MOVE FUNCTION CURRENT-DATE TO WS-CURRENT-DATE-FIELDS.\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":1073}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: GNU Cobol version 2.0\n       >>SOURCE FREE\nIDENTIFICATION DIVISION.\nPROGRAM-ID. sedol.\n\nENVIRONMENT DIVISION.\nINPUT-OUTPUT SECTION.\nFILE-CONTROL.\n    SELECT sedol-file ASSIGN \"sedol.txt\"\n        ORGANIZATION LINE SEQUENTIAL\n        FILE STATUS sedol-file-status.\n\nDATA DIVISION.\nFILE SECTION.\nFD  sedol-file.\n01  sedol                               PIC X(6).\n\nWORKING-STORAGE SECTION.\n01  sedol-file-status                   PIC XX.\n    88  sedol-file-ok                   VALUE \"00\".\n\n01  digit-num                           PIC 9 COMP.\n    \n01  digit-weights-area                  VALUE \"1317391\".\n    03  digit-weights                   PIC 9 OCCURS 7 TIMES.\n    \n01  weighted-sum-parts-area.\n    03  weighted-sum-parts              PIC 9(3) COMP OCCURS 6 TIMES.\n\n01  weighted-sum                        PIC 9(3) COMP.\n\n01  check-digit                         PIC 9.\n\nPROCEDURE DIVISION.\n    OPEN INPUT sedol-file\n    PERFORM UNTIL NOT sedol-file-ok\n        READ sedol-file\n            AT END\n                EXIT PERFORM\n        END-READ\n\n        MOVE FUNCTION UPPER-CASE(sedol) TO sedol\n        \n        PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6\n            EVALUATE TRUE\n                WHEN sedol (digit-num:1) IS ALPHABETIC-UPPER\n                    IF sedol (digit-num:1) = \"A\" OR \"E\" OR \"I\" OR \"O\" OR \"U\"\n                        DISPLAY \"Invalid SEDOL: \" sedol\n                        EXIT PERFORM CYCLE\n                    END-IF\n                \n                    COMPUTE weighted-sum-parts (digit-num) =\n                        (FUNCTION ORD(sedol (digit-num:1)) - FUNCTION ORD(\"A\")\n                        + 10) * digit-weights (digit-num)\n                        \n                WHEN sedol (digit-num:1) IS NUMERIC\n                    MULTIPLY FUNCTION NUMVAL(sedol (digit-num:1))\n                        BY digit-weights (digit-num)\n                        GIVING weighted-sum-parts (digit-num)\n                        \n                WHEN OTHER\n                    DISPLAY \"Invalid SEDOL: \" sedol\n                    EXIT PERFORM CYCLE\n            END-EVALUATE\n        END-PERFORM\n\n        INITIALIZE weighted-sum\n        PERFORM VARYING digit-num FROM 1 BY 1 UNTIL digit-num > 6\n            ADD weighted-sum-parts (digit-num) TO weighted-sum\n        END-PERFORM\n        \n        COMPUTE check-digit =\n            FUNCTION MOD(10 - FUNCTION MOD(weighted-sum, 10), 10)\n\n        DISPLAY sedol check-digit\n    END-PERFORM\n    \n    CLOSE sedol-file\n    .\nEND PROGRAM sedol.\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":1074}
    {"lang_cluster":"COBOL","source_code":"\n\nIDENTIFICATION DIVISION.\nPROGRAM-ID. NTH-PROGRAM.\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  WS-NUMBER.\n    05 N               PIC 9(8).\n    05 LAST-TWO-DIGITS PIC 99.\n    05 LAST-DIGIT      PIC 9.\n    05 N-TO-OUTPUT     PIC Z(7)9.\n    05 SUFFIX          PIC AA.\nPROCEDURE DIVISION.\nTEST-PARAGRAPH.\n    PERFORM NTH-PARAGRAPH VARYING N FROM 0 BY 1 UNTIL N IS GREATER THAN 25.\n    PERFORM NTH-PARAGRAPH VARYING N FROM 250 BY 1 UNTIL N IS GREATER THAN 265.\n    PERFORM NTH-PARAGRAPH VARYING N FROM 1000 BY 1 UNTIL N IS GREATER THAN 1025.\n    STOP RUN.\nNTH-PARAGRAPH.\n    MOVE 'TH' TO SUFFIX.\n    MOVE N (7:2) TO LAST-TWO-DIGITS.\n    IF LAST-TWO-DIGITS IS LESS THAN 4,\n    OR LAST-TWO-DIGITS IS GREATER THAN 20,\n    THEN PERFORM DECISION-PARAGRAPH.\n    MOVE N TO N-TO-OUTPUT.\n    DISPLAY N-TO-OUTPUT WITH NO ADVANCING.\n    DISPLAY SUFFIX WITH NO ADVANCING.\n    DISPLAY SPACE WITH NO ADVANCING.\nDECISION-PARAGRAPH.\n    MOVE N (8:1) TO LAST-DIGIT.\n    IF LAST-DIGIT IS EQUAL TO 1 THEN MOVE 'ST' TO SUFFIX.\n    IF LAST-DIGIT IS EQUAL TO 2 THEN MOVE 'ND' TO SUFFIX.\n    IF LAST-DIGIT IS EQUAL TO 3 THEN MOVE 'RD' TO SUFFIX.\n\n\n       0TH        1ST        2ND        3RD        4TH        5TH        6TH        7TH        8TH        9TH       10TH       11TH       12TH       13TH       14TH       15TH       16TH       17TH       18TH       19TH       20TH       21ST       22ND       23RD       24TH       25TH      250TH      251ST      252ND      253RD      254TH      255TH      256TH      257TH      258TH      259TH      260TH      261ST      262ND      263RD      264TH      265TH     1000TH     1001ST     1002ND     1003RD     1004TH     1005TH     1006TH     1007TH     1008TH     1009TH     1010TH     1011TH     1012TH     1013TH     1014TH     1015TH     1016TH     1017TH     1018TH     1019TH     1020TH     1021ST     1022ND     1023RD     1024TH     1025TH\n","human_summarization":"The code is a function that takes a non-negative integer as input and returns a string representation of the number with its ordinal suffix. The function handles specific cases for numbers ending in 1, 2, 3 and numbers in the teens. The function is demonstrated with the ranges 0..25, 250..265, 1000..1025. The code directly extracts the last digit or two, leveraging COBOL's decimal number storage.","id":1075}
    {"lang_cluster":"COBOL","source_code":"\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Strip-Chars.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  Str-Size  CONSTANT 128.\n\n       LOCAL-STORAGE SECTION.\n       01  I       PIC 999.\n       01  Str-Pos PIC 999.\n\n       01  Offset  PIC 999.\n       01  New-Pos PIC 999.\n\n       01  Str-End PIC 999.\n\n       LINKAGE SECTION.\n       01  Str     PIC X(Str-Size).\n       01  Chars-To-Replace PIC X(256).\n\n       PROCEDURE DIVISION USING Str BY VALUE Chars-To-Replace.\n       Main.\n           PERFORM VARYING I FROM 1 BY 1\n                   UNTIL Chars-To-Replace (I:1) = X\"00\"\n\n               MOVE ZERO TO Offset\n\n*              *> Overwrite the characters to remove by left-shifting\n*              *> following characters over them.\n               PERFORM VARYING Str-Pos FROM 1 BY 1\n                       UNTIL Str-Size < Str-Pos\n                   IF Str (Str-Pos:1) = Chars-To-Replace (I:1)\n                       ADD 1 TO Offset\n                   ELSE IF Offset NOT = ZERO\n                       COMPUTE New-Pos = Str-Pos - Offset\n                       MOVE Str (Str-Pos:1) TO Str (New-Pos:1)\n                   END-IF\n               END-PERFORM\n               \n*              *> Move spaces to characters at the end that have been\n*              *> shifted over.\n               COMPUTE Str-End = Str-Size - Offset\n               MOVE SPACES TO Str (Str-End:Offset)\n           END-PERFORM\n\n           GOBACK\n           .\n\n","human_summarization":"The code defines a function that removes a specified set of characters from a given string. The function takes two arguments: the original string and the string of characters to be removed. The function then returns the original string with all instances of the specified characters removed.","id":1076}
    {"lang_cluster":"COBOL","source_code":"\n       identification division.\n       program-id. prepend.\n       data division.\n       working-storage section.\n       1 str pic x(30) value \"World!\".\n       1 binary.\n        2 len pic 9(4) value 0.\n        2 scratch pic 9(4) value 0.\n       procedure division.\n       begin.\n           perform rev-sub-str\n           move function reverse (\"Hello \") to str (len + 1:)\n           perform rev-sub-str\n           display str\n           stop run\n           .\n\n       rev-sub-str.\n           move 0 to len scratch\n           inspect function reverse (str)\n           tallying scratch for leading spaces\n               len for characters after space\n           move function reverse (str (1:len)) to str\n           .\n       end program prepend.\n\nHello World!\nWorks with: GNU Cobol version 2.0\n       >>SOURCE FREE\nPROGRAM-ID. prepend.\n\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  str                                 PIC X(30) VALUE \"world!\".\n\nPROCEDURE DIVISION.\n    MOVE FUNCTION CONCATENATE(\"Hello, \", str) TO str\n    DISPLAY str\n    .\nEND PROGRAM prepend.\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":1077}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: GnuCOBOL\n         >>SOURCE FORMAT FREE\n*> This code is dedicated to the public domain\nidentification division.\nprogram-id. dragon.\nenvironment division.\nconfiguration section.\nrepository. function all intrinsic.\ndata division.\nworking-storage section.\n01  segment-length pic 9 value 2.\n01  mark pic x value '.'.\n01  segment-count pic 9999 value 513.\n\n01  segment pic 9999.\n01  point pic 9999 value 1.\n01  point-max pic 9999.\n01  point-lim pic 9999 value 8192.\n01  dragon-curve.\n    03  filler occurs 8192.\n        05  ydragon pic s9999.\n        05  xdragon pic s9999.\n\n01  x pic s9999 value 1.\n01  y pic S9999 value 1.\n\n01  xdelta pic s9 value 1. *> start pointing east\n01  ydelta pic s9 value 0.\n\n01  x-max pic s9999 value -9999.\n01  x-min pic s9999 value 9999.\n01  y-max pic s9999 value -9999.\n01  y-min pic s9999 value 9999.\n\n01  n pic 9999.\n01  r pic 9.\n\n01  xupper pic s9999.\n01  yupper pic s9999.\n\n01  window-line-number pic 99.\n01  window-width pic 99 value 64.\n01  window-height pic 99 value 22.\n01  window.\n    03  window-line occurs 22.\n        05  window-point occurs 64 pic x.\n\n01  direction pic x.\n\nprocedure division.\nstart-dragon.\n\n    if segment-count * segment-length > point-lim\n        *> too many segments for the point-table\n        compute segment-count = point-lim \/ segment-length\n    end-if\n\n    perform varying segment from 1 by 1\n    until segment > segment-count\n\n        *>===========================================\n        *> segment = n * 2 ** b\n        *> if mod(n,4) = 3, turn left else turn right\n        *>===========================================\n\n        *> calculate the turn\n        divide 2 into segment giving n remainder r\n        perform until r <> 0\n            divide 2 into n giving n remainder r\n        end-perform\n        divide 2 into n giving n remainder r\n\n        *> perform the turn\n        evaluate r also xdelta also ydelta\n        when 0 also 1 also 0  *> turn right from east\n        when 1 also -1 also 0 *> turn left from west\n            *> turn to south\n            move 0 to xdelta\n            move 1 to ydelta\n        when 1 also 1 also 0  *> turn left from east\n        when 0 also -1 also 0 *> turn right from west\n            *> turn to north\n            move 0 to xdelta\n            move -1 to ydelta\n        when 0 also 0 also 1  *> turn right from south\n        when 1 also 0 also -1 *> turn left from north\n            *> turn to west\n            move 0 to ydelta\n            move -1 to xdelta\n        when 1 also 0 also 1  *> turn left from south\n        when 0 also 0 also -1 *> turn right from north\n            *> turn to east\n            move 0 to ydelta\n            move 1 to xdelta\n        end-evaluate\n\n        *> plot the segment points\n        perform segment-length times\n            add xdelta to x\n            add ydelta to y\n\n            move x to xdragon(point)\n            move y to ydragon(point)\n\n            add 1 to point\n        end-perform\n\n        *> update the limits for the display\n        compute x-max = max(x, x-max)\n        compute x-min = min(x, x-min)\n        compute y-max = max(y, y-max)\n        compute y-min = min(y, y-min)\n        move point to point-max\n\n    end-perform\n\n    *>==========================================\n    *> display the curve\n    *> hjkl corresponds to left, up, down, right\n    *> anything else ends the program\n    *>==========================================\n\n    move 1 to yupper xupper\n\n    perform with test after\n    until direction <> 'h' and 'j' and 'k' and 'l'\n\n        *>==========================================\n        *> (yupper,xupper) maps to window-point(1,1)\n        *>==========================================\n\n        *> move the window\n        evaluate true\n        when direction = 'h' *> move window left\n        and xupper > x-min + window-width\n           subtract 1 from xupper\n        when direction = 'j' *> move window up\n        and yupper < y-max - window-height\n           add 1 to yupper\n        when direction = 'k' *> move window down\n        and yupper > y-min + window-height\n           subtract 1 from yupper\n        when direction = 'l' *> move window right\n        and xupper < x-max - window-width\n            add 1 to xupper\n        end-evaluate\n\n        *> plot the dragon points in the window\n        move spaces to window\n        perform varying point from 1 by 1\n        until point > point-max\n            if ydragon(point) >= yupper and < yupper + window-height\n            and xdragon(point) >= xupper and < xupper + window-width\n                *> we're in the window\n                compute y = ydragon(point) - yupper + 1\n                compute x =  xdragon(point) - xupper + 1\n                move mark to window-point(y, x)\n            end-if\n         end-perform\n\n         *> display the window\n         perform varying window-line-number from 1 by 1\n         until window-line-number > window-height\n             display window-line(window-line-number)\n         end-perform\n\n         *> get the next window move or terminate\n         display 'hjkl?' with no advancing\n         accept direction\n    end-perform\n\n    stop run\n    .\nend program dragon.\n\n\n","human_summarization":"generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.","id":1078}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Guess-The-Number.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  Random-Num PIC 99.\n       01  Guess      PIC 99.\n\n       PROCEDURE DIVISION.\n           COMPUTE Random-Num = 1 + (FUNCTION RANDOM * 10)\n           DISPLAY \"Guess a number between 1 and 10:\"\n\n           PERFORM FOREVER\n               ACCEPT Guess\n\n               IF Guess = Random-Num\n                   DISPLAY \"Well guessed!\"\n                   EXIT PERFORM\n               ELSE\n                   DISPLAY \"That isn't it. Try again.\"\n               END-IF\n           END-PERFORM\n           \n           GOBACK\n           .\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":1079}
    {"lang_cluster":"COBOL","source_code":"\n\nidentification division.\nprogram-id. lower-case-alphabet-program.\ndata division.\nworking-storage section.\n01  ascii-lower-case.\n    05 lower-case-alphabet pic a(26).\n    05 character-code      pic 999.\n    05 loop-counter        pic 99.\nprocedure division.\ncontrol-paragraph.\n    perform add-next-letter-paragraph varying loop-counter from 1 by 1\n    until loop-counter is greater than 26.\n    display lower-case-alphabet upon console.\n    stop run.\nadd-next-letter-paragraph.\n    add 97 to loop-counter giving character-code.\n    move function char(character-code) to lower-case-alphabet(loop-counter:1).\n\n\n","human_summarization":"generate an array, list, sequence, or string of all lower case ASCII characters from 'a' to 'z'. It demonstrates both accessing such a sequence from the standard library and manually generating a similar sequence. The code is written in a reliable style suitable for large programs and uses strong typing if available. It avoids manually enumerating all lowercase characters to prevent bugs. In the case of COBOL, the code uses mutable and subscripted strings to build the sequence in a loop.","id":1080}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. SAMPLE.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n\n         01 binary_number   pic X(21).\n         01 str             pic X(21).\n         01 binary_digit    pic X.\n         01 digit           pic 9.\n         01 n               pic 9(7).\n         01 nstr            pic X(7).\n\n       PROCEDURE DIVISION.\n         accept nstr\n         move nstr to n\n         perform until n equal 0\n           divide n by 2 giving n remainder digit\n           move digit to binary_digit\n           string binary_digit  DELIMITED BY SIZE\n                  binary_number DELIMITED BY SPACE\n                  into str\n           move str to binary_number\n         end-perform.\n         display binary_number\n         stop run.\n\n\nIDENTIFICATION DIVISION.\nPROGRAM-ID. binary-conversion.\n\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01 binary-number   pic X(21).\n01 digit           pic 9.\n01 n               pic 9(7).\n01 nstr            pic X(7).\n01 ptr\t\t\t   pic 99.\n\nPROCEDURE DIVISION.\n\tdisplay \"Number: \" with no advancing.\n\taccept nstr.\n\tmove nstr to n.\n\tmove zeroes to binary-number.\n\tmove length binary-number to ptr.\n\tperform until n equal 0\n\t\tdivide n by 2 giving n remainder digit\n\t\tmove digit to binary-number(ptr:1) \n\t\tsubtract 1 from ptr\n\t\tif ptr < 1\n\t\t\texit perform\n\t\tend-if\n\tend-perform.\n\tdisplay binary-number.\n\tstop run.\n\n","human_summarization":"The code takes a non-negative integer as input and outputs its binary representation. It uses either built-in radix functions or a user-defined function to generate the binary sequence. The output contains only the binary digits of the input number, followed by a newline, with no leading zeros, whitespace, radix, or sign markers.","id":1081}
    {"lang_cluster":"COBOL","source_code":"\n       identification division.\n       program-id. ReadConfiguration.\n\n       environment division.\n       configuration section.\n       repository.\n           function all intrinsic.\n\n       input-output section.\n       file-control.\n           select config-file     assign to \"Configuration.txt\"\n                                  organization line sequential.\n       data division.\n       file section.\n\n       fd  config-file.\n       01  config-record          pic is x(128).\n\n       working-storage section.\n       77  idx                    pic 9(3).\n       77  pos                    pic 9(3).\n       77  last-pos               pic 9(3).\n       77  config-key             pic x(32).\n       77  config-value           pic x(64).\n       77  multi-value            pic x(64).\n       77  full-name              pic x(64).\n       77  favourite-fruit        pic x(64).\n       77  other-family           pic x(64) occurs 10.\n       77  need-speeling          pic x(5) value \"false\".\n       77  seeds-removed          pic x(5) value \"false\".\n\n       procedure division.\n       main.\n           open input config-file\n           perform until exit\n              read config-file\n                 at end\n                    exit perform\n              end-read  \n              move trim(config-record) to config-record\n              if config-record(1:1) = \"#\" or \";\" or spaces\n                 exit perform cycle\n              end-if\n              unstring config-record delimited by spaces into config-key\n              move trim(config-record(length(trim(config-key)) + 1:)) to config-value\n              if config-value(1:1) = \"=\"\n                 move trim(config-value(2:)) to config-value\n              end-if\n              evaluate upper-case(config-key)\n                 when \"FULLNAME\"\n                    move config-value to full-name\n                 when \"FAVOURITEFRUIT\"\n                    move config-value to favourite-fruit\n                 when \"NEEDSPEELING\"\n                    if config-value = spaces\n                       move \"true\" to config-value\n                    end-if\n                    if config-value = \"true\" or \"false\"\n                       move config-value to need-speeling\n                    end-if\n                 when \"SEEDSREMOVED\"\n                    if config-value = spaces\n                       move \"true\" to config-value\n                    end-if,\n                    if config-value = \"true\" or \"false\"\n                       move config-value to seeds-removed\n                    end-if\n                 when \"OTHERFAMILY\"\n                    move 1 to idx, pos\n                    perform until exit\n                       unstring config-value delimited by \",\" into multi-value with pointer pos\n                          on overflow\n                             move trim(multi-value) to other-family(idx)\n                             move pos to last-pos\n                          not on overflow\n                             if config-value(last-pos:) <> spaces\n                                move trim(config-value(last-pos:)) to other-family(idx)\n                             end-if,\n                             exit perform\n                       end-unstring\n                       add 1 to idx\n                    end-perform\n              end-evaluate\n           end-perform\n           close config-file\n\n           display \"fullname = \" full-name\n           display \"favouritefruit = \" favourite-fruit\n           display \"needspeeling = \" need-speeling\n           display \"seedsremoved = \" seeds-removed\n           perform varying idx from 1 by 1 until idx > 10\n              if other-family(idx) <> low-values\n                 display \"otherfamily(\" idx \") = \" other-family(idx)\n              end-if\n           end-perform\n           .\n\n\n","human_summarization":"read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.","id":1082}
    {"lang_cluster":"COBOL","source_code":"\n\nCOBOL  >>SOURCE FORMAT IS FIXED\n       identification division.\n       program-id. curl-rosetta.\n\n       environment division.\n       configuration section.\n       repository.\n           function read-url\n           function all intrinsic.\n\n       data division.\n       working-storage section.\n\n       copy \"gccurlsym.cpy\".\n\n       01 web-page             pic x(16777216).\n       01 curl-status          usage binary-long.\n\n       01 cli                  pic x(7) external.\n          88 helping           values \"-h\", \"-help\", \"help\", spaces.\n          88 displaying        value \"display\".            \n          88 summarizing       value \"summary\". \n\n      *> ***************************************************************\n       procedure division.\n       accept cli from command-line\n       if helping then\n           display \".\/curl-rosetta [help|display|summary]\"\n           goback\n       end-if\n\n      *>\n      *> Read a web resource into fixed ram.\n      *>   Caller is in charge of sizing the buffer,\n      *>     (or getting trickier with the write callback)\n      *> Pass URL and working-storage variable,\n      *>   get back libcURL error code or 0 for success\n\n       move read-url(\"http:\/\/www.rosettacode.org\", web-page)\n         to curl-status\n\n       perform check\n       perform show\n\n       goback.\n      *> ***************************************************************\n\n      *> Now tesing the result, relying on the gccurlsym\n      *>   GnuCOBOL Curl Symbol copy book\n       check.\n       if curl-status not equal zero then\n           display\n               curl-status \" \"\n               CURLEMSG(curl-status) upon syserr\n       end-if\n       .\n\n      *> And display the page\n       show.\n       if summarizing then\n           display \"Length: \" stored-char-length(web-page)\n       end-if\n       if displaying then\n           display trim(web-page trailing) with no advancing\n       end-if\n       .\n\n       REPLACE ALSO ==:EXCEPTION-HANDLERS:== BY\n       ==\n      *> informational warnings and abends\n       soft-exception.\n         display space upon syserr\n         display \"--Exception Report-- \" upon syserr\n         display \"Time of exception:   \" current-date upon syserr\n         display \"Module:              \" module-id upon syserr\n         display \"Module-path:         \" module-path upon syserr\n         display \"Module-source:       \" module-source upon syserr\n         display \"Exception-file:      \" exception-file upon syserr\n         display \"Exception-status:    \" exception-status upon syserr\n         display \"Exception-location:  \" exception-location upon syserr\n         display \"Exception-statement: \" exception-statement upon syserr\n       .\n\n       hard-exception.\n           perform soft-exception\n           stop run returning 127 \n       .\n       ==.\n\n       end program curl-rosetta.\n      *> ***************************************************************\n\n      *> ***************************************************************\n      *>\n      *> The function hiding all the curl details\n      *>\n      *> Purpose:   Call libcURL and read into memory\n      *> ***************************************************************\n       identification division.\n       function-id. read-url.\n\n       environment division.\n       configuration section.\n       repository.\n           function all intrinsic.\n\n       data division.\n       working-storage section.\n\n       copy \"gccurlsym.cpy\".\n\n       replace also ==:CALL-EXCEPTION:== by\n       ==\n           on exception\n               perform hard-exception\n       ==.\n\n       01 curl-handle          usage pointer.\n       01 callback-handle      usage procedure-pointer.\n       01 memory-block.\n          05 memory-address    usage pointer sync.\n          05 memory-size       usage binary-long sync.\n          05 running-total     usage binary-long sync.\n       01 curl-result          usage binary-long.\n\n       01 cli                  pic x(7) external.\n          88 helping           values \"-h\", \"-help\", \"help\", spaces.\n          88 displaying        value \"display\".            \n          88 summarizing       value \"summary\". \n\n       linkage section.\n       01 url                  pic x any length.\n       01 buffer               pic x any length.\n       01 curl-status          usage binary-long.\n\n      *> ***************************************************************\n       procedure division using url buffer returning curl-status.\n       if displaying or summarizing then \n           display \"Read: \" url upon syserr\n       end-if\n\n      *> initialize libcurl, hint at missing library if need be\n       call \"curl_global_init\" using by value CURL_GLOBAL_ALL\n           on exception\n               display\n                   \"need libcurl, link with -lcurl\" upon syserr\n               stop run returning 1\n       end-call\n\n      *> initialize handle\n       call \"curl_easy_init\" returning curl-handle\n           :CALL-EXCEPTION:\n       end-call\n       if curl-handle equal NULL then\n           display \"no curl handle\" upon syserr\n           stop run returning 1\n       end-if\n\n      *> Set the URL\n       call \"curl_easy_setopt\" using\n           by value curl-handle\n           by value CURLOPT_URL\n           by reference concatenate(trim(url trailing), x\"00\")\n           :CALL-EXCEPTION:\n       end-call\n\n      *> follow all redirects\n       call \"curl_easy_setopt\" using\n           by value curl-handle\n           by value CURLOPT_FOLLOWLOCATION\n           by value 1\n           :CALL-EXCEPTION:\n       end-call\n\n      *> set the call back to write to memory\n       set callback-handle to address of entry \"curl-write-callback\"\n       call \"curl_easy_setopt\" using\n           by value curl-handle\n           by value CURLOPT_WRITEFUNCTION\n           by value callback-handle\n           :CALL-EXCEPTION:\n       end-call\n\n      *> set the curl handle data handling structure\n       set memory-address to address of buffer\n       move length(buffer) to memory-size\n       move 1 to running-total\n\n       call \"curl_easy_setopt\" using\n           by value curl-handle\n           by value CURLOPT_WRITEDATA\n           by value address of memory-block\n           :CALL-EXCEPTION:\n       end-call\n\n      *> some servers demand an agent\n       call \"curl_easy_setopt\" using\n           by value curl-handle\n           by value CURLOPT_USERAGENT\n           by reference concatenate(\"libcurl-agent\/1.0\", x\"00\")\n           :CALL-EXCEPTION:\n       end-call\n\n      *> let curl do all the hard work\n       call \"curl_easy_perform\" using\n           by value curl-handle\n           returning curl-result\n           :CALL-EXCEPTION:\n       end-call\n\n      *> the call back will handle filling ram, return the result code\n       move curl-result to curl-status\n\n      *> curl clean up, more important if testing cookies\n       call \"curl_easy_cleanup\" using\n           by value curl-handle\n           returning omitted\n           :CALL-EXCEPTION:\n       end-call\n\n       goback.\n\n       :EXCEPTION-HANDLERS:\n\n       end function read-url.\n      *> ***************************************************************\n\n      *> ***************************************************************\n      *> Supporting libcurl callback\n       identification division.\n       program-id. curl-write-callback.\n\n       environment division.\n       configuration section.\n       repository.\n           function all intrinsic.\n\n       data division.\n       working-storage section.\n       01 real-size            usage binary-long.\n\n      *> libcURL will pass a pointer to this structure in the callback\n       01 memory-block         based.\n          05 memory-address    usage pointer sync.\n          05 memory-size       usage binary-long sync.\n          05 running-total     usage binary-long sync.\n\n       01 content-buffer       pic x(65536) based.\n       01 web-space            pic x(16777216) based.\n       01 left-over            usage binary-long.\n\n       linkage section.\n       01 contents             usage pointer.\n       01 element-size         usage binary-long.\n       01 element-count        usage binary-long.\n       01 memory-structure     usage pointer.\n\n      *> ***************************************************************\n       procedure division\n           using\n              by value contents\n              by value element-size\n              by value element-count\n              by value memory-structure\n          returning real-size.\n\n       set address of memory-block to memory-structure\n       compute real-size = element-size * element-count end-compute\n\n      *> Fence off the end of buffer\n       compute\n           left-over = memory-size - running-total\n       end-compute\n       if left-over > 0 and < real-size then\n           move left-over to real-size\n       end-if\n\n      *> if there is more buffer, and data not zero length\n       if (left-over > 0) and (real-size > 1) then\n           set address of content-buffer to contents\n           set address of web-space to memory-address\n\n           move content-buffer(1:real-size)\n             to web-space(running-total:real-size)\n\n           add real-size to running-total\n       else\n           display \"curl buffer sizing problem\" upon syserr\n       end-if\n\n       goback.\n       end program curl-write-callback.\n\n\n      *> manifest constants for libcurl\n      *> Usage: COPY occurlsym  inside data division\n      *>  Taken from include\/curl\/curl.h 2013-12-19\n\n      *> Functional enums\n       01 CURL_MAX_HTTP_HEADER CONSTANT AS     102400.\n\n       78 CURL_GLOBAL_ALL                      VALUE 3.\n\n       78 CURLOPT_FOLLOWLOCATION               VALUE 52.\n       78 CURLOPT_WRITEDATA                    VALUE 10001.\n       78 CURLOPT_URL                          VALUE 10002.\n       78 CURLOPT_USERAGENT                    VALUE 10018.\n       78 CURLOPT_WRITEFUNCTION                VALUE 20011.\n       78 CURLOPT_COOKIEFILE                   VALUE 10031.\n       78 CURLOPT_COOKIEJAR                    VALUE 10082.\n       78 CURLOPT_COOKIELIST                   VALUE 10135.\n\n      *> Informationals\n       78 CURLINFO_COOKIELIST                  VALUE 4194332.\n\n      *> Result codes\n       78 CURLE_OK                             VALUE 0.\n      *> Error codes\n       78 CURLE_UNSUPPORTED_PROTOCOL           VALUE 1.\n       78 CURLE_FAILED_INIT                    VALUE 2.\n       78 CURLE_URL_MALFORMAT                  VALUE 3.\n       78 CURLE_OBSOLETE4                      VALUE 4.\n       78 CURLE_COULDNT_RESOLVE_PROXY          VALUE 5.\n       78 CURLE_COULDNT_RESOLVE_HOST           VALUE 6.\n       78 CURLE_COULDNT_CONNECT                VALUE 7.\n       78 CURLE_FTP_WEIRD_SERVER_REPLY         VALUE 8.\n       78 CURLE_REMOTE_ACCESS_DENIED           VALUE 9.\n       78 CURLE_OBSOLETE10                     VALUE 10.\n       78 CURLE_FTP_WEIRD_PASS_REPLY           VALUE 11.\n       78 CURLE_OBSOLETE12                     VALUE 12.\n       78 CURLE_FTP_WEIRD_PASV_REPLY           VALUE 13.\n       78 CURLE_FTP_WEIRD_227_FORMAT           VALUE 14.\n       78 CURLE_FTP_CANT_GET_HOST              VALUE 15.\n       78 CURLE_OBSOLETE16                     VALUE 16.\n       78 CURLE_FTP_COULDNT_SET_TYPE           VALUE 17.\n       78 CURLE_PARTIAL_FILE                   VALUE 18.\n       78 CURLE_FTP_COULDNT_RETR_FILE          VALUE 19.\n       78 CURLE_OBSOLETE20                     VALUE 20.\n       78 CURLE_QUOTE_ERROR                    VALUE 21.\n       78 CURLE_HTTP_RETURNED_ERROR            VALUE 22.\n       78 CURLE_WRITE_ERROR                    VALUE 23.\n       78 CURLE_OBSOLETE24                     VALUE 24.\n       78 CURLE_UPLOAD_FAILED                  VALUE 25.\n       78 CURLE_READ_ERROR                     VALUE 26.\n       78 CURLE_OUT_OF_MEMORY                  VALUE 27.\n       78 CURLE_OPERATION_TIMEDOUT             VALUE 28.\n       78 CURLE_OBSOLETE29                     VALUE 29.\n       78 CURLE_FTP_PORT_FAILED                VALUE 30.\n       78 CURLE_FTP_COULDNT_USE_REST           VALUE 31.\n       78 CURLE_OBSOLETE32                     VALUE 32.\n       78 CURLE_RANGE_ERROR                    VALUE 33.\n       78 CURLE_HTTP_POST_ERROR                VALUE 34.\n       78 CURLE_SSL_CONNECT_ERROR              VALUE 35.\n       78 CURLE_BAD_DOWNLOAD_RESUME            VALUE 36.\n       78 CURLE_FILE_COULDNT_READ_FILE         VALUE 37.\n       78 CURLE_LDAP_CANNOT_BIND               VALUE 38.\n       78 CURLE_LDAP_SEARCH_FAILED             VALUE 39.\n       78 CURLE_OBSOLETE40                     VALUE 40.\n       78 CURLE_FUNCTION_NOT_FOUND             VALUE 41.\n       78 CURLE_ABORTED_BY_CALLBACK            VALUE 42.\n       78 CURLE_BAD_FUNCTION_ARGUMENT          VALUE 43.\n       78 CURLE_OBSOLETE44                     VALUE 44.\n       78 CURLE_INTERFACE_FAILED               VALUE 45.\n       78 CURLE_OBSOLETE46                     VALUE 46.\n       78 CURLE_TOO_MANY_REDIRECTS             VALUE 47.\n       78 CURLE_UNKNOWN_TELNET_OPTION          VALUE 48.\n       78 CURLE_TELNET_OPTION_SYNTAX           VALUE 49.\n       78 CURLE_OBSOLETE50                     VALUE 50.\n       78 CURLE_PEER_FAILED_VERIFICATION       VALUE 51.\n       78 CURLE_GOT_NOTHING                    VALUE 52.\n       78 CURLE_SSL_ENGINE_NOTFOUND            VALUE 53.\n       78 CURLE_SSL_ENGINE_SETFAILED           VALUE 54.\n       78 CURLE_SEND_ERROR                     VALUE 55.\n       78 CURLE_RECV_ERROR                     VALUE 56.\n       78 CURLE_OBSOLETE57                     VALUE 57.\n       78 CURLE_SSL_CERTPROBLEM                VALUE 58.\n       78 CURLE_SSL_CIPHER                     VALUE 59.\n       78 CURLE_SSL_CACERT                     VALUE 60.\n       78 CURLE_BAD_CONTENT_ENCODING           VALUE 61.\n       78 CURLE_LDAP_INVALID_URL               VALUE 62.\n       78 CURLE_FILESIZE_EXCEEDED              VALUE 63.\n       78 CURLE_USE_SSL_FAILED                 VALUE 64.\n       78 CURLE_SEND_FAIL_REWIND               VALUE 65.\n       78 CURLE_SSL_ENGINE_INITFAILED          VALUE 66.\n       78 CURLE_LOGIN_DENIED                   VALUE 67.\n       78 CURLE_TFTP_NOTFOUND                  VALUE 68.\n       78 CURLE_TFTP_PERM                      VALUE 69.\n       78 CURLE_REMOTE_DISK_FULL               VALUE 70.\n       78 CURLE_TFTP_ILLEGAL                   VALUE 71.\n       78 CURLE_TFTP_UNKNOWNID                 VALUE 72.\n       78 CURLE_REMOTE_FILE_EXISTS             VALUE 73.\n       78 CURLE_TFTP_NOSUCHUSER                VALUE 74.\n       78 CURLE_CONV_FAILED                    VALUE 75.\n       78 CURLE_CONV_REQD                      VALUE 76.\n       78 CURLE_SSL_CACERT_BADFILE             VALUE 77.\n       78 CURLE_REMOTE_FILE_NOT_FOUND          VALUE 78.\n       78 CURLE_SSH                            VALUE 79.\n       78 CURLE_SSL_SHUTDOWN_FAILED            VALUE 80.\n       78 CURLE_AGAIN                          VALUE 81.\n\n      *> Error strings\n       01 LIBCURL_ERRORS.\n          02 CURLEVALUES.\n             03 FILLER PIC X(30) VALUE \"CURLE_UNSUPPORTED_PROTOCOL    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FAILED_INIT             \".\n             03 FILLER PIC X(30) VALUE \"CURLE_URL_MALFORMAT           \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE4               \".\n             03 FILLER PIC X(30) VALUE \"CURLE_COULDNT_RESOLVE_PROXY   \".\n             03 FILLER PIC X(30) VALUE \"CURLE_COULDNT_RESOLVE_HOST    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_COULDNT_CONNECT         \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FTP_WEIRD_SERVER_REPLY  \".\n             03 FILLER PIC X(30) VALUE \"CURLE_REMOTE_ACCESS_DENIED    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE10              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FTP_WEIRD_PASS_REPLY    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE12              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FTP_WEIRD_PASV_REPLY    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FTP_WEIRD_227_FORMAT    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FTP_CANT_GET_HOST       \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE16              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FTP_COULDNT_SET_TYPE    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_PARTIAL_FILE            \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FTP_COULDNT_RETR_FILE   \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE20              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_QUOTE_ERROR             \".\n             03 FILLER PIC X(30) VALUE \"CURLE_HTTP_RETURNED_ERROR     \".\n             03 FILLER PIC X(30) VALUE \"CURLE_WRITE_ERROR             \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE24              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_UPLOAD_FAILED           \".\n             03 FILLER PIC X(30) VALUE \"CURLE_READ_ERROR              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OUT_OF_MEMORY           \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OPERATION_TIMEDOUT      \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE29              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FTP_PORT_FAILED         \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FTP_COULDNT_USE_REST    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE32              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_RANGE_ERROR             \".\n             03 FILLER PIC X(30) VALUE \"CURLE_HTTP_POST_ERROR         \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SSL_CONNECT_ERROR       \".\n             03 FILLER PIC X(30) VALUE \"CURLE_BAD_DOWNLOAD_RESUME     \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FILE_COULDNT_READ_FILE  \".\n             03 FILLER PIC X(30) VALUE \"CURLE_LDAP_CANNOT_BIND        \".\n             03 FILLER PIC X(30) VALUE \"CURLE_LDAP_SEARCH_FAILED      \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE40              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FUNCTION_NOT_FOUND      \".\n             03 FILLER PIC X(30) VALUE \"CURLE_ABORTED_BY_CALLBACK     \".\n             03 FILLER PIC X(30) VALUE \"CURLE_BAD_FUNCTION_ARGUMENT   \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE44              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_INTERFACE_FAILED        \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE46              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_TOO_MANY_REDIRECTS      \".\n             03 FILLER PIC X(30) VALUE \"CURLE_UNKNOWN_TELNET_OPTION   \".\n             03 FILLER PIC X(30) VALUE \"CURLE_TELNET_OPTION_SYNTAX    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE50              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_PEER_FAILED_VERIFICATION\".\n             03 FILLER PIC X(30) VALUE \"CURLE_GOT_NOTHING             \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SSL_ENGINE_NOTFOUND     \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SSL_ENGINE_SETFAILED    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SEND_ERROR              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_RECV_ERROR              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_OBSOLETE57              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SSL_CERTPROBLEM         \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SSL_CIPHER              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SSL_CACERT              \".\n             03 FILLER PIC X(30) VALUE \"CURLE_BAD_CONTENT_ENCODING    \".\n             03 FILLER PIC X(30) VALUE \"CURLE_LDAP_INVALID_URL        \".\n             03 FILLER PIC X(30) VALUE \"CURLE_FILESIZE_EXCEEDED       \".\n             03 FILLER PIC X(30) VALUE \"CURLE_USE_SSL_FAILED          \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SEND_FAIL_REWIND        \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SSL_ENGINE_INITFAILED   \".\n             03 FILLER PIC X(30) VALUE \"CURLE_LOGIN_DENIED            \".\n             03 FILLER PIC X(30) VALUE \"CURLE_TFTP_NOTFOUND           \".\n             03 FILLER PIC X(30) VALUE \"CURLE_TFTP_PERM               \".\n             03 FILLER PIC X(30) VALUE \"CURLE_REMOTE_DISK_FULL        \".\n             03 FILLER PIC X(30) VALUE \"CURLE_TFTP_ILLEGAL            \".\n             03 FILLER PIC X(30) VALUE \"CURLE_TFTP_UNKNOWNID          \".\n             03 FILLER PIC X(30) VALUE \"CURLE_REMOTE_FILE_EXISTS      \".\n             03 FILLER PIC X(30) VALUE \"CURLE_TFTP_NOSUCHUSER         \".\n             03 FILLER PIC X(30) VALUE \"CURLE_CONV_FAILED             \".\n             03 FILLER PIC X(30) VALUE \"CURLE_CONV_REQD               \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SSL_CACERT_BADFILE      \".\n             03 FILLER PIC X(30) VALUE \"CURLE_REMOTE_FILE_NOT_FOUND   \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SSH                     \".\n             03 FILLER PIC X(30) VALUE \"CURLE_SSL_SHUTDOWN_FAILED     \".\n             03 FILLER PIC X(30) VALUE \"CURLE_AGAIN                   \".\n       01 FILLER REDEFINES LIBCURL_ERRORS.\n          02 CURLEMSG OCCURS 81 TIMES PIC X(30).\n\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP requests, tested with GnuCOBOL and a copybook.","id":1083}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: OpenCOBOL\nWorks with: IBM Enterprise COBOL for z\/OS\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID.  LUHNTEST.\n       ENVIRONMENT DIVISION.\n       INPUT-OUTPUT SECTION.\n       data division.\n       WORKING-STORAGE SECTION.\n       01  inp-card.\n         03  inp-card-ch      pic x(01) occurs 20 times.\n       01  ws-result          pic 9(01).\n         88  pass-luhn-test             value 0.\n\n       PROCEDURE DIVISION.\n           move \"49927398716\"       to inp-card\n           perform test-card\n           move \"49927398717\"       to inp-card\n           perform test-card\n           move \"1234567812345678\"  to inp-card\n           perform test-card\n           move \"1234567812345670\"  to inp-card\n           perform test-card\n           stop run\n           .\n       test-card.\n           call \"LUHN\" using inp-card, ws-result\n           if pass-luhn-test\n             display \"input=\" inp-card \"pass\"\n           else\n             display \"input=\" inp-card \"fail\"\n           .\n\n       END PROGRAM LUHNTEST.\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID.  LUHN.\n       ENVIRONMENT DIVISION.\n       INPUT-OUTPUT SECTION.\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  maxlen           pic 9(02) comp value 16.\n       01  inplen           pic 9(02) comp value 0.\n       01  i                pic 9(02) comp value 0.\n       01  j                pic 9(02) comp value 0.\n       01  l                pic 9(02) comp value 0.\n       01  dw               pic 9(02) comp value 0.\n       01  ws-total         pic 9(03) comp value 0.\n       01  ws-prod          pic 99.\n       01  filler redefines ws-prod.\n         03  ws-prod-tens   pic 9.\n         03  ws-prod-units  pic 9.\n       01  ws-card.\n         03  filler           occurs 16 times depending on maxlen.\n           05  ws-card-ch     pic x(01).\n           05  ws-card-digit redefines ws-card-ch  pic 9(01).\n       LINKAGE SECTION.\n       01  inp-card.\n         03  inp-card-ch      pic x(01) occurs 20 times.\n       01  ws-result          pic 9(01).\n         88  pass-luhn-test             value 0.\n\n       PROCEDURE DIVISION using inp-card, ws-result.\n           perform varying i from 1 by +1\n           until i > maxlen\n           or    inp-card-ch (i) = space\n           end-perform\n           compute l = i - 1\n           compute inplen = l\n           perform varying j from 1 by +1\n           until j > inplen\n             if l < 1\n               move \"0\"             to ws-card-ch (j)\n             else\n               move inp-card-ch (l) to ws-card-ch (j)\n               compute l = l - 1\n             end-if\n           end-perform\n           move 0 to ws-total\n           perform varying i from 1 by +1\n           until i > inplen\n             compute dw = 2 - (i - 2 * function integer (i \/ 2))\n             compute ws-prod = ws-card-digit (i) * dw\n             compute ws-total = ws-total\n                              + ws-prod-tens\n                              + ws-prod-units\n           end-perform\n           compute ws-result = ws-total - 10 * function integer (ws-total \/ 10)\n           goback\n           .\n       END PROGRAM LUHN.\n\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":1084}
    {"lang_cluster":"COBOL","source_code":"\n\nIDENTIFICATION DIVISION.\nPROGRAM-ID. REPEAT-PROGRAM.\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n77  HAHA         PIC A(10).\nPROCEDURE DIVISION.\n    MOVE ALL 'ha' TO HAHA.\n    DISPLAY HAHA.\n    STOP RUN.\n\n\n","human_summarization":"The code takes a string and a number as input and repeats the string that number of times. It also has the functionality to repeat a single character to create a new string.","id":1085}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Int-Arithmetic.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n\n       01 A      PIC S9(10).\n       01 B      PIC S9(10).\n       01 Result PIC S9(10).\n\n       PROCEDURE DIVISION.\n           DISPLAY \"First number: \" WITH NO ADVANCING\n           ACCEPT A\n           DISPLAY \"Second number: \" WITH NO ADVANCING\n           ACCEPT B\n           \n*          *> Note: The various ADD\/SUBTRACT\/etc. statements can be\n*          *> replaced with COMPUTE statements, which allow those\n*          *> operations to be defined similarly to other languages,\n*          *> e.g. COMPUTE Result = A + B\n\n           ADD A TO B GIVING Result\n           DISPLAY \"A + B = \" Result\n\n           SUBTRACT B FROM A GIVING Result\n           DISPLAY \"A - B = \" Result\n\n           MULTIPLY A BY B GIVING Result\n           DISPLAY \"A * B = \" Result\n\n*          *> Division here truncates towards zero. DIVIDE can take a\n*          *> ROUNDED clause, which will round the result to the nearest\n*          *> integer.\n           DIVIDE A BY B GIVING Result\n           DISPLAY \"A \/ B = \" Result\n\n           COMPUTE Result = A ^ B\n           DISPLAY \"A ^ B = \" Result\n       \n*          *> Matches sign of first argument.\n           DISPLAY \"A\u00a0% B = \" FUNCTION REM(A, B)\n\n           GOBACK\n           .\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":1086}
    {"lang_cluster":"COBOL","source_code":"\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. testing.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  occurrences             PIC 99.\n\n       PROCEDURE DIVISION.\n           INSPECT \"the three truths\" TALLYING occurrences FOR ALL \"th\"\n           DISPLAY occurrences\n\n           MOVE 0 TO occurrences\n           INSPECT \"ababababab\" TALLYING occurrences FOR ALL \"abab\"\n           DISPLAY occurrences\n           \n           MOVE 0 TO occurrences\n           INSPECT \"abaabba*bbaba*bbab\" TALLYING occurrences\n               FOR ALL \"a*b\"\n           DISPLAY occurrences\n\n           GOBACK\n           .\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function does not count overlapping substrings and matches from left-to-right or right-to-left for the highest number of non-overlapping matches.","id":1087}
    {"lang_cluster":"COBOL","source_code":"Works with: OpenCOBOL version 2.0\n       >>SOURCE FREE\nIDENTIFICATION DIVISION.\nPROGRAM-ID. towers-of-hanoi.\n\nPROCEDURE DIVISION.\n    CALL \"move-disk\" USING 4, 1, 2, 3\n    .\nEND PROGRAM towers-of-hanoi.\n\nIDENTIFICATION DIVISION.\nPROGRAM-ID. move-disk RECURSIVE.\n\nDATA DIVISION.\nLINKAGE SECTION.\n01  n                         PIC 9 USAGE COMP.\n01  from-pole                 PIC 9 USAGE COMP.\n01  to-pole                   PIC 9 USAGE COMP.\n01  via-pole                  PIC 9 USAGE COMP.\n\nPROCEDURE DIVISION USING n, from-pole, to-pole, via-pole.\n    IF n > 0\n       SUBTRACT 1 FROM n\n       CALL \"move-disk\" USING CONTENT n, from-pole, via-pole, to-pole\n       DISPLAY \"Move disk from pole \" from-pole \" to pole \" to-pole\n       CALL \"move-disk\" USING CONTENT n, via-pole, to-pole, from-pole\n    END-IF\n    .\nEND PROGRAM move-disk.\n\n\n \nIDENTIFICATION DIVISION.\nPROGRAM-ID. towers-of-hanoi.\n \nPROCEDURE DIVISION.\n    CALL \"move-disk\" USING 4, 1, 2, 3\n    .\nEND PROGRAM towers-of-hanoi.\n \nIDENTIFICATION DIVISION.\nPROGRAM-ID. move-disk RECURSIVE.\n \nDATA DIVISION.\nLINKAGE SECTION.\n01  n                         PIC 9 USAGE COMP.\n01  from-pole                 PIC 9 USAGE COMP.\n01  to-pole                   PIC 9 USAGE COMP.\n01  via-pole                  PIC 9 USAGE COMP.\n \nPROCEDURE DIVISION USING n, from-pole, to-pole, via-pole.\n    IF n > 0\n       SUBTRACT 1 FROM n\n       CALL \"move-disk\" USING CONTENT n, from-pole, via-pole, to-pole\n       ADD 1 TO n\n       DISPLAY \"Move disk number \"n \" from pole \" from-pole \" to pole \" to-pole\n       SUBTRACT 1 FROM n\n       CALL \"move-disk\" USING CONTENT n, via-pole, to-pole, from-pole\n    END-IF\n    .\nEND PROGRAM move-disk.\n\n\nWorks with: CIS COBOL version 4.2Works with: GnuCOBOL version 3.0-rc1.0\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. ITERATIVE-TOWERS-OF-HANOI.\n       AUTHOR. SOREN ROUG.\n       DATE-WRITTEN. 2019-06-28.\n       ENVIRONMENT DIVISION.\n       CONFIGURATION SECTION.\n       SOURCE-COMPUTER. LINUX.\n       OBJECT-COMPUTER. KAYPRO4.\n       INPUT-OUTPUT SECTION.\n       FILE-CONTROL.\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       77  NUM-DISKS                   PIC 9 VALUE 4.\n       77  N1                          PIC 9 COMP.\n       77  N2                          PIC 9 COMP.\n       77  FROM-POLE                   PIC 9 COMP.\n       77  TO-POLE                     PIC 9 COMP.\n       77  VIA-POLE                    PIC 9 COMP.\n       77  FP-TMP                      PIC 9 COMP.\n       77  TO-TMP                      PIC 9 COMP.\n       77  P-TMP                       PIC 9 COMP.\n       77  TMP-P                       PIC 9 COMP.\n       77  I                           PIC 9 COMP.\n       77  DIV                         PIC 9 COMP.\n       01  STACKNUMS.\n           05  NUMSET OCCURS 3 TIMES.\n               10  DNUM                PIC 9 COMP.\n       01  GAMESET.\n           05  POLES OCCURS 3 TIMES.\n               10  STACK OCCURS 10 TIMES.\n                   15  POLE            PIC 9 USAGE COMP.\n\n       PROCEDURE DIVISION.\n       HANOI.\n           DISPLAY \"TOWERS OF HANOI PUZZLE WITH \", NUM-DISKS, \" DISKS.\".\n           ADD NUM-DISKS, 1 GIVING N1.\n           ADD NUM-DISKS, 2 GIVING N2.\n           MOVE 1 TO DNUM (1).\n           MOVE N1 TO DNUM (2), DNUM (3).\n           MOVE N1 TO POLE (1, N1), POLE (2, N1), POLE (3, N1).\n           MOVE 1 TO POLE (1, N2).\n           MOVE 2 TO POLE (2, N2).\n           MOVE 3 TO POLE (3, N2).\n           MOVE 1 TO I.\n           PERFORM INIT-PUZZLE UNTIL I = N1.\n           MOVE 1 TO FROM-POLE.\n           DIVIDE 2 INTO NUM-DISKS GIVING DIV.\n           MULTIPLY 2 BY DIV.\n           IF DIV NOT = NUM-DISKS PERFORM INITODD ELSE PERFORM INITEVEN.\n           PERFORM MOVE-DISK UNTIL DNUM (3) NOT > 1.\n           DISPLAY \"TOWERS OF HANOI PUZZLE COMPLETED!\".\n           STOP RUN.\n       INIT-PUZZLE.\n           MOVE I TO POLE (1, I).\n           MOVE 0 TO POLE (2, I), POLE (3, I).\n           ADD 1 TO I.\n       INITEVEN.\n           MOVE 2 TO TO-POLE.\n           MOVE 3 TO VIA-POLE.\n       INITODD.\n           MOVE 3 TO TO-POLE.\n           MOVE 2 TO VIA-POLE.\n       MOVE-DISK.\n           MOVE DNUM (FROM-POLE) TO FP-TMP.\n           MOVE POLE (FROM-POLE, FP-TMP) TO I.\n           DISPLAY \"MOVE DISK FROM \", POLE (FROM-POLE, N2),\n               \" TO \", POLE (TO-POLE, N2).\n           ADD 1 TO DNUM (FROM-POLE).\n           MOVE VIA-POLE TO TMP-P.\n           SUBTRACT 1 FROM DNUM (TO-POLE).\n           MOVE DNUM (TO-POLE) TO TO-TMP.\n           MOVE I TO POLE (TO-POLE, TO-TMP).\n           DIVIDE 2 INTO I GIVING DIV.\n           MULTIPLY 2 BY DIV.\n           IF I NOT = DIV PERFORM MOVE-TO-VIA ELSE\n               PERFORM MOVE-FROM-VIA.\n       MOVE-TO-VIA.\n           MOVE TO-POLE TO VIA-POLE.\n           MOVE DNUM (FROM-POLE) TO FP-TMP.\n           MOVE DNUM (TMP-P) TO P-TMP.\n           IF POLE (FROM-POLE, FP-TMP) > POLE (TMP-P, P-TMP)\n               PERFORM MOVE-FROM-TO\n           ELSE MOVE TMP-P TO TO-POLE.\n       MOVE-FROM-TO.\n           MOVE FROM-POLE TO TO-POLE.\n           MOVE TMP-P TO FROM-POLE.\n           MOVE DNUM (FROM-POLE) TO FP-TMP.\n           MOVE DNUM (TMP-P) TO P-TMP.\n       MOVE-FROM-VIA.\n           MOVE FROM-POLE TO VIA-POLE.\n           MOVE TMP-P TO FROM-POLE.\n\n","human_summarization":"implement a recursive solution to solve the Towers of Hanoi problem, taking into account the number of disks. However, for early versions of COBOL that do not support recursion, an iterative algorithm adapted from Kolar's Hanoi Tower algorithm no. 1 is used instead.","id":1088}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: IBM Enterprise COBOL for z\/OS\n\n      *******************************************************           \n       IDENTIFICATION DIVISION.                                         \n      *******************************************************           \n       PROGRAM-ID.      SHELLSRT.                                       \n      ************************************************************      \n      *** SHELLSORT                                           ****      \n      ************************************************************      \n       ENVIRONMENT DIVISION.                                            \n       DATA DIVISION.                                                   \n       WORKING-STORAGE SECTION.                                         \n       01 II                        PIC S9(008) COMP-5.                 \n       01 IJ                        PIC S9(008) COMP-5.                 \n       01 IZ                        PIC S9(008) COMP-5.                 \n       01 IA                        PIC S9(008) COMP-5.                 \n       01 STRT1                     PIC S9(008) COMP-5.                 \n       01 STRT2                     PIC S9(008) COMP-5.                 \n       01 LGT                       PIC S9(008) COMP-5.                 \n       01 ORG                       PIC S9(008) COMP-5.                 \n       01 DST                       PIC S9(008) COMP-5.                 \n      *                                                                 \n       01 GAP                       PIC S9(008) COMP-5.                 \n       01 NEGAP                     PIC S9(008) COMP-5.                 \n       01 TEMP                      PIC X(32768).                       \n       77 KEY-RESULT                PIC X.                              \n      *                                                                 \n       LINKAGE SECTION.                                                 \n       01 SRT-ARRAY                 PIC  X(1000000).                    \n       01 NUM-ITEM                  PIC  9(008) COMP-5.                 \n       01 SRT-DATA.                                                     \n          03 LGT-ITEM               PIC  9(004) COMP-5.                 \n          03 SRT-KEYS.                                                  \n             05 SRT-KEY OCCURS 10.                                      \n                07 K-START         PIC S9(004) COMP-5.                  \n                07 K-LENGTH        PIC S9(004) COMP-5.                  \n                07 K-ASC           PIC X.                               \n      *                                                                 \n      *    P R O C E D U R E      D I V I S I O N                       \n      *                                                                 \n       PROCEDURE DIVISION USING SRT-ARRAY NUM-ITEM SRT-DATA.                \n                                                                        \n           COMPUTE GAP = NUM-ITEM \/ 2.                                  \n           PERFORM UNTIL GAP < 1                                        \n              COMPUTE NEGAP = GAP * -1                                  \n              PERFORM VARYING II FROM GAP BY 1                          \n                        UNTIL II GREATER  NUM-ITEM                      \n                 MOVE ' ' TO KEY-RESULT                                 \n                 COMPUTE ORG = (II - 1) * LGT-ITEM + 1                  \n                 MOVE SRT-ARRAY(ORG:LGT-ITEM) TO TEMP(1:LGT-ITEM)       \n                 PERFORM VARYING IJ FROM II BY NEGAP                    \n                           UNTIL IJ NOT GREATER  GAP                    \n                              OR (KEY-RESULT NOT EQUAL '<' AND ' ')     \n                    COMPUTE IA = IJ - GAP                               \n                    IF IA < 1                                           \n                       MOVE 1 TO IA                                     \n                    END-IF                                              \n                    PERFORM COMPARE-KEYS                                \n                    IF KEY-RESULT = '<'                                 \n                       COMPUTE ORG = (IA - 1) * LGT-ITEM + 1            \n                       COMPUTE DST = (IJ - 1) * LGT-ITEM + 1            \n                       MOVE SRT-ARRAY(ORG:LGT-ITEM)                     \n                         TO SRT-ARRAY(DST:LGT-ITEM)                     \n                       COMPUTE DST = (IA - 1) * LGT-ITEM + 1            \n                       MOVE TEMP(1:LGT-ITEM) TO SRT-ARRAY(DST:LGT-ITEM) \n                    END-IF                                              \n                 END-PERFORM                                            \n              END-PERFORM                                               \n              IF GAP = 2                                                \n                 MOVE 1 TO GAP                                          \n              ELSE                                                      \n                 COMPUTE GAP = GAP \/ 2.2                                \n              END-IF                                                    \n           END-PERFORM.                                                 \n           GOBACK.                                                      \n      *                                                                 \n       COMPARE-KEYS.                                                    \n           MOVE ' ' TO KEY-RESULT                                       \n           PERFORM VARYING IZ FROM 1 BY 1                               \n                     UNTIL IZ GREATER 10                                \n                        OR (KEY-RESULT NOT EQUAL '=' AND ' ')           \n              IF SRT-KEY(IZ) GREATER LOW-VALUES                         \n                 COMPUTE STRT1 = (IJ - 1) * LGT-ITEM + K-START(IZ)      \n                 COMPUTE STRT2 = (IA - 1) * LGT-ITEM + K-START(IZ)      \n                 MOVE K-LENGTH(IZ) TO LGT                               \n                 IF SRT-ARRAY(STRT1:LGT) > SRT-ARRAY(STRT2:LGT) AND     \n                    K-ASC(IZ) EQUAL 'A'                                 \n                 OR SRT-ARRAY(STRT1:LGT) < SRT-ARRAY(STRT2:LGT) AND     \n                    K-ASC(IZ) EQUAL 'D'                                 \n                    MOVE '>' TO KEY-RESULT                              \n                 END-IF                                                 \n                 IF SRT-ARRAY(STRT1:LGT) < SRT-ARRAY(STRT2:LGT) AND     \n                    K-ASC(IZ) EQUAL 'A'                                 \n                 OR SRT-ARRAY(STRT1:LGT) > SRT-ARRAY(STRT2:LGT) AND     \n                    K-ASC(IZ) EQUAL 'D'                                 \n                    MOVE '<' TO KEY-RESULT                              \n                 END-IF                                                 \n              END-IF                                                    \n           END-PERFORM.                                                 \n           IF KEY-RESULT = ' '                                          \n              MOVE '=' TO KEY-RESULT                                    \n           END-IF.\n\n\n       C-PROCESS SECTION.\n       C-000.\n           DISPLAY \"SORT STARTING\".\n\n           DIVIDE WC-SIZE BY 2 GIVING WC-GAP.\n\n           PERFORM E-PROCESS-GAP UNTIL WC-GAP = 0.\n\n           DISPLAY \"SORT FINISHED\".\n\n       C-999.\n           EXIT.\n\n\n       E-PROCESS-GAP SECTION.\n       E-000.\n           PERFORM F-SELECTION VARYING WB-IX-1 FROM WC-GAP BY 1\n                               UNTIL WB-IX-1 > WC-SIZE.\n\n           DIVIDE WC-GAP BY 2.2 GIVING WC-GAP.\n\n       E-999.\n           EXIT.\n\n       F-SELECTION SECTION.\n       F-000.\n           SET WB-IX-2            TO WB-IX-1.\n           MOVE WB-ENTRY(WB-IX-1) TO WC-TEMP.\n\n           SET WB-IX-3 TO WB-IX-2.\n           SET WB-IX-3 DOWN BY WC-GAP.\n           PERFORM G-PASS UNTIL WB-IX-2 NOT > WC-GAP\n      * The next line logically reads\u00a0:\n      *                   or wb-entry(wb-ix-2 - wc-gap) not > wc-temp.\n                          OR WB-ENTRY(WB-IX-3) NOT > WC-TEMP.\n\n           IF WB-IX-1 NOT = WB-IX-2\n              MOVE WC-TEMP TO WB-ENTRY(WB-IX-2).\n\n       F-999.\n           EXIT.\n\n       G-PASS SECTION.\n      * Note that WB-IX-3 is WC-GAP less than WB-IX-2.\n      * Logically this should be\u00a0:\n      *    move wb-entry(wb-ix-2 - wc-gap) to wb-entry(wb-ix-2).\n      *    set wb-ix-2 down by wc-gap.\n      * Unfortunately wb-entry(wb-ix-2 - wc-gap) is not legal in C2 cobol\n       G-000.\n           MOVE WB-ENTRY(WB-IX-3) TO WB-ENTRY(WB-IX-2).\n           SET WB-IX-2            DOWN BY WC-GAP.\n           SET WB-IX-3            DOWN BY WC-GAP.\n\n       G-999.\n           EXIT.\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. The algorithm uses a diminishing increment sort, with the increment size reducing after each pass until it reaches 1. The codes work with any sequence ending in 1 and use a geometric increment sequence with a ratio of about 2.2. The codes are compatible with Cobol\/2 and sort arrays using the standard EBCDIC sequence. The user needs to provide an array, array length, and an area detailing row-length and up to 10 sort keys. The codes do not perform boundary checks and do not work properly with signed packed variables.","id":1089}
    {"lang_cluster":"COBOL","source_code":"\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. loop-do-while.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  i PIC 99 VALUE 0.\n\n       PROCEDURE DIVISION.\n           PERFORM WITH TEST AFTER UNTIL FUNCTION MOD(i, 6) = 0\n               ADD 1 TO i\n               DISPLAY i\n           END-PERFORM\n\n           GOBACK\n           .\n\n","human_summarization":"Initialize a value at 0, then enter a loop which continues until the value modulo 6 is not 0. In each iteration, the value is incremented by 1 and then printed. The loop is executed at least once. This is implemented using the COBOL equivalent of a do-while loop, which is PERFORM WITH TEST AFTER UNTIL a certain condition is met.","id":1090}
    {"lang_cluster":"COBOL","source_code":"\nFUNCTION BYTE-LENGTH(str)\n\n\nWorks with: GNU Cobol\nLENGTH OF str\n\nWorks with: GNU Cobol\nWorks with: Visual COBOL\nFUNCTION LENGTH-AN(str)\n\nFUNCTION LENGTH(str)\n\n","human_summarization":"calculate the character and byte length of a string, considering UTF-8 encoding. It also handles non-BMP code points correctly, providing the actual character counts in code points, not in code unit counts. The code can also provide the string length in graphemes if the language is capable of it.","id":1091}
    {"lang_cluster":"COBOL","source_code":"\n       identification division.\n       program-id. toptail.\n\n       data division.\n       working-storage section.\n       01 data-field.\n          05 value \"[this is a test]\".\n\n       procedure division.\n       sample-main.\n       display data-field\n      *> Using reference modification, which is (start-position:length)\n       display data-field(2:)\n       display data-field(1:length of data-field - 1)\n       display data-field(2:length of data-field - 2)\n       goback.\n       end program toptail.\n\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":1092}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. knuth-shuffle.\n\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       01  i                       PIC 9(8).\n       01  j                       PIC 9(8).\n\n       01  temp                    PIC 9(8).\n\n       LINKAGE SECTION.\n       78  Table-Len               VALUE 10.\n       01  ttable-area.\n           03  ttable              PIC 9(8) OCCURS Table-Len TIMES.\n\n       PROCEDURE DIVISION USING ttable-area.\n           MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (11:6)) TO i\n\n           PERFORM VARYING i FROM Table-Len BY -1 UNTIL i = 0\n               COMPUTE j =\n                   FUNCTION MOD(FUNCTION RANDOM * 10000, Table-Len) + 1\n\n               MOVE ttable (i) TO temp\n               MOVE ttable (j) TO ttable (i)\n               MOVE temp TO ttable (j)\n           END-PERFORM\n\n           GOBACK\n           .\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":1093}
    {"lang_cluster":"COBOL","source_code":"\n       program-id. last-fri.\n       data division.\n       working-storage section.\n       1 wk-date.\n        2 yr pic 9999.\n        2 mo pic 99 value 1.\n        2 da pic 99 value 1.\n       1 rd-date redefines wk-date pic 9(8).\n       1 binary.\n        2 int-date pic 9(8).\n        2 dow pic 9(4).\n        2 friday pic 9(4) value 5.\n       procedure division.\n           display \"Enter a calendar year (1601 thru 9999): \"\n               with no advancing\n           accept yr\n           if yr >= 1601 and <= 9999\n               continue\n           else\n               display \"Invalid year\"\n               stop run\n           end-if\n           perform 12 times\n               move 1 to da\n               add 1 to mo\n               if mo > 12              *> to avoid y10k in 9999\n                   move 12 to mo\n                   move 31 to da\n               end-if\n               compute int-date = function\n                   integer-of-date (rd-date)\n               if mo =12 and da = 31   *> to avoid y10k in 9999\n                   continue\n               else\n                   subtract 1 from int-date\n               end-if\n               compute rd-date = function\n                   date-of-integer (int-date)\n               compute dow = function mod\n                   ((int-date - 1) 7) + 1\n               compute dow = function mod ((dow - friday) 7)\n               subtract dow from da\n               display yr \"-\" mo \"-\" da\n               add 1 to mo\n           end-perform\n           stop run\n           .\n       end program last-fri.\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":1094}
    {"lang_cluster":"COBOL","source_code":"\nIDENTIFICATION DIVISION.\nPROGRAM-ID. GOODBYE-WORLD.\n\nPROCEDURE DIVISION.\nDISPLAY 'Goodbye, World!'\n    WITH NO ADVANCING\nEND-DISPLAY\n.\nSTOP RUN.\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":1095}
    {"lang_cluster":"COBOL","source_code":"\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. CAESAR.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  MSG        PIC X(50)\n           VALUE \"The quick brown fox jumped over the lazy dog.\".\n       01  OFFSET     PIC 9(4) VALUE 7 USAGE BINARY.\n       01  FROM-CHARS PIC X(52).\n       01  TO-CHARS   PIC X(52).\n       01  TABL.\n           02         PIC X(26) VALUE \"abcdefghijklmnopqrstuvwxyz\".\n           02         PIC X(26) VALUE \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".\n           02         PIC X(26) VALUE \"abcdefghijklmnopqrstuvwxyz\".\n           02         PIC X(26) VALUE \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".\n\n       PROCEDURE DIVISION.\n       BEGIN.\n           DISPLAY MSG\n           PERFORM ENCRYPT\n           DISPLAY MSG\n           PERFORM DECRYPT\n           DISPLAY MSG\n           STOP RUN.\n\n       ENCRYPT.\n           MOVE TABL (1:52) TO FROM-CHARS\n           MOVE TABL (1 + OFFSET:52) TO TO-CHARS\n           INSPECT MSG CONVERTING FROM-CHARS TO TO-CHARS.\n\n       DECRYPT.\n           MOVE TABL (1 + OFFSET:52) TO FROM-CHARS\n           MOVE TABL (1:52) TO TO-CHARS\n           INSPECT MSG CONVERTING FROM-CHARS TO TO-CHARS.\n\n       END PROGRAM CAESAR.\n\n\n","human_summarization":"implement a Caesar cipher that can both encode and decode. The key for the cipher is an integer from 1 to 25 and rotates the letters of the alphabet either left or right. The cipher replaces each letter with the 1st to 25th next letter in the alphabet, wrapping Z to A. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key of length 1 and Rot-13 is identical to Caesar cipher with key 13. The codes are written in COBOL-85 ASCII or EBCIDIC.","id":1096}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. show-lcm.\n\n       ENVIRONMENT DIVISION.\n       CONFIGURATION SECTION.\n       REPOSITORY.\n           FUNCTION lcm\n           .\n       PROCEDURE DIVISION.\n           DISPLAY \"lcm(35, 21) = \" FUNCTION lcm(35, 21)\n           GOBACK\n           .\n       END PROGRAM show-lcm.\n\n       IDENTIFICATION DIVISION.\n       FUNCTION-ID. lcm.\n       \n       ENVIRONMENT DIVISION.\n       CONFIGURATION SECTION.\n       REPOSITORY.\n           FUNCTION gcd\n           .\n       DATA DIVISION.\n       LINKAGE SECTION.\n       01  m                       PIC S9(8).\n       01  n                       PIC S9(8).\n       01  ret                     PIC S9(8).\n\n       PROCEDURE DIVISION USING VALUE m, n RETURNING ret.\n           COMPUTE ret = FUNCTION ABS(m * n) \/ FUNCTION gcd(m, n)\n           GOBACK\n           .\n       END FUNCTION lcm.\n           \n       IDENTIFICATION DIVISION.\n       FUNCTION-ID. gcd.\n\n       DATA DIVISION.\n       LOCAL-STORAGE SECTION.\n       01  temp                    PIC S9(8).\n\n       01  x                       PIC S9(8).\n       01  y                       PIC S9(8).\n\n       LINKAGE SECTION.\n       01  m                       PIC S9(8).\n       01  n                       PIC S9(8).\n       01  ret                     PIC S9(8).\n\n       PROCEDURE DIVISION USING VALUE m, n RETURNING ret.\n           MOVE m to x\n           MOVE n to y\n\n           PERFORM UNTIL y = 0\n               MOVE x TO temp\n               MOVE y TO x\n               MOVE FUNCTION MOD(temp, y) TO Y\n           END-PERFORM\n\n           MOVE FUNCTION ABS(x) TO ret\n           GOBACK\n           .\n       END FUNCTION gcd.\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":1097}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: Visual COBOL\n01  things occurs 3.\n...\nset content of things to (\"Apple\", \"Banana\", \"Coconut\")\nperform varying thing as string through things\n    display thing\nend-perform\n\n","human_summarization":"iterate through each element in a collection in a sequential manner, printing each one. If the language supports it, a \"for each\" loop is used, otherwise, another type of loop is utilized. This is implemented in Managed COBOL dialect.","id":1098}
    {"lang_cluster":"COBOL","source_code":"\n\n      identification division.\n       program-id. tokenize.\n\n       environment division.\n       configuration section.\n       repository.\n           function all intrinsic.\n\n       data division.\n       working-storage section.\n       01 period constant as \".\".\n       01 cmma   constant as \",\".\n\n       01 start-with.\n          05 value \"Hello,How,Are,You,Today\".\n\n       01 items.\n          05 item pic x(6) occurs 5 times.\n\n       procedure division.\n       tokenize-main.\n       unstring start-with delimited by cmma\n           into item(1) item(2) item(3) item(4) item(5)\n\n       display trim(item(1)) period trim(item(2)) period\n               trim(item(3)) period trim(item(4)) period\n               trim(item(5))\n\n       goback.\n       end program tokenize.\n\n\n","human_summarization":"\"Tokenizes a string by separating it into an array based on commas, then displays the words to the user separated by a period. The code can handle complex cases with multiple delimiters, capture which delimiter was used for each field, and use a pointer for the starting position. It also includes match tallying.\"","id":1099}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. GCD.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01 A        PIC 9(10)   VALUE ZEROES.\n       01 B        PIC 9(10)   VALUE ZEROES.\n       01 TEMP     PIC 9(10)   VALUE ZEROES.\n\n       PROCEDURE DIVISION.\n       Begin.\n           DISPLAY \"Enter first number, max 10 digits.\"\n           ACCEPT A\n           DISPLAY \"Enter second number, max 10 digits.\"\n           ACCEPT B\n           IF A < B\n             MOVE B TO TEMP\n             MOVE A TO B\n             MOVE TEMP TO B\n           END-IF\n\n           PERFORM UNTIL B = 0\n             MOVE A TO TEMP\n             MOVE B TO A\n             DIVIDE TEMP BY B GIVING TEMP REMAINDER B\n           END-PERFORM\n           DISPLAY \"The gcd is \" A\n           STOP RUN.\n\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":1100}
    {"lang_cluster":"COBOL","source_code":"\n\n        program-id. is-numeric.\n        procedure division.\n        display function test-numval-f(\"abc\") end-display\n        display function test-numval-f(\"-123.01E+3\") end-display\n        if function test-numval-f(\"+123.123\") equal zero then\n            display \"is numeric\" end-display\n        else\n            display \"failed numval-f test\" end-display\n        end-if\n        goback.\n\nWorks with: OpenCOBOL\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Is-Numeric.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  Numeric-Chars      PIC X(10) VALUE \"0123456789\".\n       \n       01  Success            CONSTANT 0.\n       01  Failure            CONSTANT 128.\n\n       LOCAL-STORAGE SECTION.\n       01  I                  PIC 99.\n\n       01  Num-Decimal-Points PIC 99.\n       01  Num-Valid-Chars    PIC 99.\n\n       LINKAGE SECTION.\n       01  Str                PIC X(30). \n\n       PROCEDURE DIVISION USING Str.\n           IF Str = SPACES\n               MOVE Failure TO Return-Code\n               GOBACK\n           END-IF\n\n           MOVE FUNCTION TRIM(Str) TO Str\n\n           INSPECT Str TALLYING Num-Decimal-Points FOR ALL \".\"\n           IF Num-Decimal-Points > 1\n               MOVE Failure TO Return-Code\n               GOBACK\n           ELSE\n               ADD Num-Decimal-Points TO Num-Valid-Chars\n           END-IF\n\n           IF Str (1:1) = \"-\" OR \"+\"\n               ADD 1 TO Num-Valid-Chars\n           END-IF\n           \n           PERFORM VARYING I FROM 1 BY 1 UNTIL I > 10\n               INSPECT Str TALLYING Num-Valid-Chars\n                   FOR ALL Numeric-Chars (I:1) BEFORE SPACE\n           END-PERFORM\n\n           INSPECT Str TALLYING Num-Valid-Chars FOR TRAILING SPACES\n\n           IF Num-Valid-Chars = FUNCTION LENGTH(Str) \n               MOVE Success TO Return-Code\n           ELSE\n               MOVE Failure TO Return-Code\n           END-IF\n\n           GOBACK\n           .\n\n","human_summarization":"implement a boolean function to check if a given string is a numeric string, including floating point and negative numbers. The function utilizes COBOL's intrinsic functions TEST-NUMVAL, TEST-NUMVAL-C, and TEST-NUMVAL-F (for drafts supporting the 20XX standard) to validate the string. The function returns 0 if the string is valid, otherwise, it returns the position of the first incorrect character.","id":1101}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Trig.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  Pi-Third   USAGE COMP-2.\n       01  Degree     USAGE COMP-2.\n\n       01  60-Degrees USAGE COMP-2.\n\n       01  Result     USAGE COMP-2.\n\n       PROCEDURE DIVISION.\n           COMPUTE Pi-Third = FUNCTION PI \/ 3\n\n           DISPLAY \"Radians:\"\n           DISPLAY \"  Sin(\u03c0 \/ 3)  = \" FUNCTION SIN(Pi-Third)\n           DISPLAY \"  Cos(\u03c0 \/ 3)  = \" FUNCTION COS(Pi-Third)\n           DISPLAY \"  Tan(\u03c0 \/ 3)  = \" FUNCTION TAN(Pi-Third)\n           DISPLAY \"  Asin(0.5)   = \" FUNCTION ASIN(0.5)\n           DISPLAY \"  Acos(0.5)   = \" FUNCTION ACOS(0.5)\n           DISPLAY \"  Atan(0.5)   = \" FUNCTION ATAN(0.5)\n\n           COMPUTE Degree = FUNCTION PI \/ 180\n           COMPUTE 60-Degrees = Degree * 60\n\n           DISPLAY \"Degrees:\"\n           DISPLAY \"  Sin(60\u00b0)  = \" FUNCTION SIN(60-Degrees)\n           DISPLAY \"  Cos(60\u00b0)  = \" FUNCTION COS(60-Degrees)\n           DISPLAY \"  Tan(60\u00b0)  = \" FUNCTION TAN(60-Degrees)\n           COMPUTE Result = FUNCTION ASIN(0.5) \/ 60\n           DISPLAY \"  Asin(0.5) = \" Result\n           COMPUTE Result = FUNCTION ACOS(0.5) \/ 60\n           DISPLAY \"  Acos(0.5) = \" Result\n           COMPUTE Result = FUNCTION ATAN(0.5) \/ 60\n           DISPLAY \"  Atan(0.5) = \" Result\n\n           GOBACK\n           .\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":1102}
    {"lang_cluster":"COBOL","source_code":"\n\n       identification division.\n       program-id. signals.\n       data division.\n       working-storage section.\n       01 signal-flag  pic 9 external.\n          88 signalled value 1.\n       01 half-seconds usage binary-long.\n       01 start-time   usage binary-c-long.\n       01 end-time     usage binary-c-long.\n       01 handler      usage program-pointer.\n       01 SIGINT       constant as 2.\n\n       procedure division.\n       call \"gettimeofday\" using start-time null\n       set handler to entry \"handle-sigint\"\n       call \"signal\" using by value SIGINT by value handler\n\n       perform until exit\n           if signalled then exit perform end-if\n           call \"CBL_OC_NANOSLEEP\" using 500000000\n           if signalled then exit perform end-if\n           add 1 to half-seconds\n           display half-seconds\n       end-perform\n\n       call \"gettimeofday\" using end-time null\n       subtract start-time from end-time\n       display \"Program ran for \" end-time \" seconds\"\n       goback.\n       end program signals.\n\n       identification division.\n       program-id. handle-sigint.\n       data division.\n       working-storage section.\n       01 signal-flag  pic 9 external.\n\n       linkage section.\n       01 the-signal   usage binary-long.\n\n       procedure division using by value the-signal returning omitted.\n       move 1 to signal-flag\n       goback.\n       end program handle-sigint.\n\n\n","human_summarization":"The code outputs an integer every half second. It handles SIGINT or SIGQUIT signals, often generated by user's ctrl-C or ctrl-\\ commands. On receiving these signals, it stops outputting integers, displays the total runtime in seconds, and then terminates. The code is compatible with GnuCOBOL 2.0.","id":1103}
    {"lang_cluster":"COBOL","source_code":"\n       PROGRAM-ID. increment-num-str.\n       \n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  str                    PIC X(5) VALUE \"12345\".\n       01  num                    REDEFINES str PIC 9(5).\n       \n       PROCEDURE DIVISION.\n           DISPLAY str\n           ADD 1 TO num\n           DISPLAY str\n\n           GOBACK\n           .\n\n\n       PROGRAM-ID. increment-num-str.\n       \n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  num-str                PIC 9(5) VALUE 12345.\n       \n       PROCEDURE DIVISION.\n           DISPLAY num-str\n           ADD 1 TO num-str\n           DISPLAY num-str\n       \n           GOBACK\n           .\n\n","human_summarization":"Code summarization: The code increments a numerical string, storing the contents as characters due to the implicit definition of num-str as USAGE DISPLAY.","id":1104}
    {"lang_cluster":"COBOL","source_code":"\n\nFUNCTION MEDIAN(some-table (ALL))\n\n","human_summarization":"\"Code calculates the median value of a vector of floating-point numbers, handling even number of elements by returning the average of the two middle values. It uses the selection algorithm for efficient computation. It also includes tasks for calculating various statistical measures such as mean, mode, standard deviation, and others.\"","id":1105}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: OpenCOBOL\n      * FIZZBUZZ.COB\n      * cobc -x -g FIZZBUZZ.COB\n      *\n       IDENTIFICATION        DIVISION.\n       PROGRAM-ID.           fizzbuzz.\n       DATA                  DIVISION.\n       WORKING-STORAGE       SECTION.\n       01 CNT      PIC 9(03) VALUE 1.\n       01 REM      PIC 9(03) VALUE 0.\n       01 QUOTIENT PIC 9(03) VALUE 0.\n       PROCEDURE             DIVISION.\n      *\n       PERFORM UNTIL CNT > 100\n         DIVIDE 15 INTO CNT GIVING QUOTIENT REMAINDER REM\n         IF REM = 0\n           THEN\n             DISPLAY \"FizzBuzz \" WITH NO ADVANCING\n           ELSE\n             DIVIDE 3 INTO CNT GIVING QUOTIENT REMAINDER REM\n             IF REM = 0\n               THEN\n                 DISPLAY \"Fizz \" WITH NO ADVANCING\n               ELSE\n                 DIVIDE 5 INTO CNT GIVING QUOTIENT REMAINDER REM\n                 IF REM = 0\n                   THEN\n                     DISPLAY \"Buzz \" WITH NO ADVANCING\n                   ELSE\n                     DISPLAY CNT \" \" WITH NO ADVANCING\n                 END-IF\n             END-IF\n         END-IF\n         ADD 1 TO CNT\n       END-PERFORM\n       DISPLAY \"\"\n       STOP RUN.\n\n\nWorks with: OpenCOBOL\nIdentification division.\nProgram-id. fizz-buzz.\n\nData division.\nWorking-storage section.\n\n01 num pic 999.\n\nProcedure division.\n    Perform varying num from 1 by 1 until num > 100\n        if function mod (num, 15) = 0 then display \"fizzbuzz\"\n        else if function mod (num, 3) = 0 then display \"fizz\"\n        else if function mod (num, 5) = 0 then display \"buzz\"\n        else display num\n    end-perform.\n    Stop run.\n\n\nWorks with: OpenCOBOL\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID.  FIZZBUZZ.\n       ENVIRONMENT DIVISION.\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  X PIC 999.\n       01  Y PIC 999.\n       01  REM3 PIC 999.\n       01  REM5 PIC 999.\n       PROCEDURE DIVISION.\n           PERFORM VARYING X FROM 1 BY 1 UNTIL X > 100\n               DIVIDE X BY 3 GIVING Y REMAINDER REM3\n               DIVIDE X BY 5 GIVING Y REMAINDER REM5\n            EVALUATE REM3 ALSO REM5\n              WHEN ZERO ALSO ZERO\n                DISPLAY \"FizzBuzz\"\n              WHEN ZERO ALSO ANY\n                DISPLAY \"Fizz\"\n              WHEN ANY ALSO ZERO\n                DISPLAY \"Buzz\"\n              WHEN OTHER\n                DISPLAY X\n            END-EVALUATE\n           END-PERFORM\n           STOP RUN\n           .\n\nWorks with: OpenCOBOL\n\n         >>SOURCE FORMAT FREE\nidentification division.\nprogram-id. fizzbuzz.\ndata division.\nworking-storage section.\n01  i pic 999.\n01  fizz pic 999 value 3.\n01  buzz pic 999 value 5.\nprocedure division.\nstart-fizzbuzz.\n    perform varying i from 1 by 1 until i > 100 \n        evaluate i also i\n        when fizz also buzz\n            display 'fizzbuzz'\n            add 3 to fizz\n            add 5 to buzz\n        when fizz also any\n            display 'fizz'\n            add 3 to fizz\n        when buzz also any\n            display 'buzz'\n            add 5 to buzz\n        when other\n            display i\n        end-evaluate\n    end-perform\n    stop run\n    .\nend program fizzbuzz.\n\n","human_summarization":"print integers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":1106}
    {"lang_cluster":"COBOL","source_code":"\n\nIDENTIFICATION DIVISION.\nPROGRAM-ID. MANDELBROT-SET-PROGRAM.\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  COMPLEX-ARITHMETIC.\n    05 X               PIC S9V9(9).\n    05 Y               PIC S9V9(9).\n    05 X-A             PIC S9V9(6).\n    05 X-B             PIC S9V9(6).\n    05 Y-A             PIC S9V9(6).\n    05 X-A-SQUARED     PIC S9V9(6).\n    05 Y-A-SQUARED     PIC S9V9(6).\n    05 SUM-OF-SQUARES  PIC S9V9(6).\n    05 ROOT            PIC S9V9(6).\n01  LOOP-COUNTERS.\n    05 I               PIC 99.\n    05 J               PIC 99.\n    05 K               PIC 999.\n77  PLOT-CHARACTER     PIC X.\nPROCEDURE DIVISION.\nCONTROL-PARAGRAPH.\n    PERFORM OUTER-LOOP-PARAGRAPH\n    VARYING I FROM 1 BY 1 UNTIL I IS GREATER THAN 24.\n    STOP RUN.\nOUTER-LOOP-PARAGRAPH.\n    PERFORM INNER-LOOP-PARAGRAPH\n    VARYING J FROM 1 BY 1 UNTIL J IS GREATER THAN 64.\n    DISPLAY ''.\nINNER-LOOP-PARAGRAPH.\n    MOVE SPACE TO PLOT-CHARACTER.\n    MOVE ZERO  TO X-A.\n    MOVE ZERO  TO Y-A.\n    MULTIPLY J   BY   0.0390625   GIVING X.\n    SUBTRACT 1.5 FROM X.\n    MULTIPLY I   BY   0.083333333 GIVING Y.\n    SUBTRACT 1 FROM Y.\n    PERFORM ITERATION-PARAGRAPH VARYING K FROM 1 BY 1\n    UNTIL K IS GREATER THAN 100 OR PLOT-CHARACTER IS EQUAL TO '#'.\n    DISPLAY PLOT-CHARACTER WITH NO ADVANCING.\nITERATION-PARAGRAPH.\n    MULTIPLY X-A BY X-A GIVING X-A-SQUARED.\n    MULTIPLY Y-A BY Y-A GIVING Y-A-SQUARED.\n    SUBTRACT Y-A-SQUARED FROM X-A-SQUARED GIVING X-B.\n    ADD      X   TO X-B.\n    MULTIPLY X-A BY Y-A GIVING Y-A.\n    MULTIPLY Y-A BY 2   GIVING Y-A.\n    SUBTRACT Y   FROM Y-A.\n    MOVE     X-B TO   X-A.\n    ADD X-A-SQUARED TO Y-A-SQUARED GIVING SUM-OF-SQUARES.\n    MOVE FUNCTION SQRT (SUM-OF-SQUARES) TO ROOT.\n    IF ROOT IS GREATER THAN 2 THEN MOVE '#' TO PLOT-CHARACTER.\n\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions.","id":1107}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. array-sum-and-product.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       78  Array-Size              VALUE 10.\n       01  array-area              VALUE \"01020304050607080910\".\n           03  array               PIC 99 OCCURS Array-Size TIMES.\n\n       01  array-sum               PIC 9(8).\n       01  array-product           PIC 9(10) VALUE 1.\n\n       01  i                       PIC 99.\n\n       PROCEDURE DIVISION.\n           PERFORM VARYING i FROM 1 BY 1 UNTIL Array-Size < i\n               ADD array (i) TO array-sum\n               MULTIPLY array (i) BY array-product\n           END-PERFORM\n\n           DISPLAY \"Sum:     \" array-sum\n           DISPLAY \"Product: \" array-product\n\n           GOBACK\n           .\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":1108}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. leap-year.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  examples VALUE \"19001994199619972000\".\n           03  year PIC 9(4) OCCURS 5 TIMES\n               INDEXED BY year-index.\n\n       01  remainders.\n           03 400-rem   PIC 9(4).\n           03 100-rem   PIC 9(4).\n           03 4-rem     PIC 9(4).\n\n       PROCEDURE DIVISION.\n           PERFORM VARYING year-index FROM 1 BY 1 UNTIL 5 < year-index\n               MOVE FUNCTION MOD(year (year-index), 400) TO 400-rem\n               MOVE FUNCTION MOD(year (year-index), 100) TO 100-rem\n               MOVE FUNCTION MOD(year (year-index), 4) TO 4-rem\n\n               IF 400-rem = 0 OR ((100-rem NOT = 0) AND 4-rem = 0)\n                   DISPLAY year (year-index) \" is a leap year.\"\n               ELSE\n                   DISPLAY year (year-index) \" is not a leap year.\"\n               END-IF\n           END-PERFORM\n\n           GOBACK\n           .\n\n\n       program-id. leap-yr.\n           *> Given a year, where 1601 <= year <= 9999\n           *> Determine if the year is a leap year\n       data division.\n       working-storage section.\n       1 input-year pic 9999.\n       1 binary.\n        2 int-date pic 9(8).\n        2 cal-mo-day pic 9(4).\n       procedure division.\n           display \"Enter calendar year (1601 thru 9999): \"\n               with no advancing\n           accept input-year\n           if input-year >= 1601 and <= 9999\n           then\n                   *> if the 60th day of a year is Feb 29\n                   *> then the year is a leap year\n               compute int-date = function integer-of-day\n                   ( input-year * 1000 + 60 )\n               compute cal-mo-day = function mod (\n                   (function date-of-integer ( int-date )) 10000 )\n               display \"Year \" input-year space with no advancing\n               if cal-mo-day = 229\n                   display \"is a leap year\"\n               else\n                   display \"is NOT a leap year\"\n               end-if\n           else\n               display \"Input date is not within range\"\n           end-if\n           stop run\n           .\n       end program leap-yr.\n\n\n","human_summarization":"determine if a specified year is a leap year in the Gregorian calendar using Date Intrinsic Functions.","id":1109}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. DEPARTMENT-NUMBERS.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.       \n       01 BANNER        PIC X(24) VALUE \"POLICE  SANITATION  FIRE\".\n       01 COMBINATION.\n          03 FILLER     PIC X(5)  VALUE SPACES.\n          03 POLICE     PIC 9.\n          03 FILLER     PIC X(11) VALUE SPACES.\n          03 SANITATION PIC 9.\n          03 FILLER     PIC X(5)  VALUE SPACES.\n          03 FIRE       PIC 9.\n       01 TOTAL         PIC 99.\n\n       PROCEDURE DIVISION.\n       BEGIN. \n           DISPLAY BANNER.\n           PERFORM POLICE-LOOP VARYING POLICE FROM 2 BY 2\n           UNTIL POLICE IS GREATER THAN 6.\n           STOP RUN.\n \n       POLICE-LOOP. \n           PERFORM SANITATION-LOOP VARYING SANITATION FROM 1 BY 1\n           UNTIL SANITATION IS GREATER THAN 7.\n  \n       SANITATION-LOOP.\n           PERFORM FIRE-LOOP VARYING FIRE FROM 1 BY 1\n           UNTIL FIRE IS GREATER THAN 7.\n \n       FIRE-LOOP.\n           ADD POLICE, SANITATION, FIRE GIVING TOTAL.\n           IF POLICE IS NOT EQUAL TO SANITATION\n               AND POLICE IS NOT EQUAL TO FIRE\n               AND SANITATION IS NOT EQUAL TO FIRE\n               AND TOTAL IS EQUAL TO 12,\n               DISPLAY COMBINATION.\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":1110}
    {"lang_cluster":"COBOL","source_code":"MOVE \"Hello\" TO src\nMOVE src TO dst\n\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":1111}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: GNU Cobol\n       >>SOURCE FREE\nIDENTIFICATION DIVISION.\nPROGRAM-ID. random-element.\n\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  nums-area                           VALUE \"123456789\".\n    03  nums                            PIC 9 OCCURS 9 TIMES.\n    \n01  random-idx                          PIC 9 COMP.\n    \nPROCEDURE DIVISION.\n    COMPUTE random-idx = FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:7)) * 9 + 1\n    DISPLAY nums (random-idx)\n    .\nEND PROGRAM random-element.\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":1112}
    {"lang_cluster":"COBOL","source_code":"\n\n        >>SOURCE FREE\nIDENTIFICATION DIVISION.\nPROGRAM-ID. binary-search.\n\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  nums-area                           VALUE \"01040612184356\".\n    03  nums                            PIC 9(2)\n                                        OCCURS 7 TIMES\n                                        ASCENDING KEY nums\n                                        INDEXED BY nums-idx.\nPROCEDURE DIVISION.\n    SEARCH ALL nums\n        WHEN nums (nums-idx) = 4\n            DISPLAY \"Found 4 at index \" nums-idx\n    END-SEARCH\n    .\nEND PROGRAM binary-search.\n\n","human_summarization":"The code implements a binary search algorithm on a sorted integer array. It takes the starting point, ending point of a range, and a \"secret value\" as inputs. The search can be either recursive or iterative. It divides the range into halves and continues to narrow down the search field until the \"secret value\" is found. It also handles multiple values equal to the given value and indicates whether the element was found or not. The code also includes a fix for potential overflow bugs.","id":1113}
    {"lang_cluster":"COBOL","source_code":"\n\nWorks with: OpenCOBOL\nWorks with: Visual COBOL\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. accept-all-args.\n       \n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  args                   PIC X(50).\n       \n       PROCEDURE DIVISION.\n       main-line.\n           ACCEPT args FROM COMMAND-LINE\n           DISPLAY args\n           \n           GOBACK\n           .\n\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. accept-args-one-at-a-time.\n       \n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  arg                 PIC X(50) VALUE SPACES.\n       \n       PROCEDURE DIVISION.\n           ACCEPT arg FROM ARGUMENT-VALUE\n           PERFORM UNTIL arg = SPACES\n               DISPLAY arg\n               MOVE SPACES TO arg\n               ACCEPT arg FROM ARGUMENT-VALUE\n           END-PERFORM\n           \n           GOBACK\n           .\n\n\nWorks with: OpenCOBOL\nWorks with: gnuCOBOL\n       *>Created By Zwiegnet 8\/19\/2004\n\n        IDENTIFICATION DIVISION.\n        PROGRAM-ID. arguments.\n\n        ENVIRONMENT DIVISION.\n\n        DATA DIVISION.\n\n\n        WORKING-STORAGE SECTION.\n\n        01 command1 PIC X(50).\n        01 command2 PIC X(50).\n        01 command3 PIC X(50).\n\n\n        PROCEDURE DIVISION.\n       \n        PERFORM GET-ARGS.\n\n        *> Display Usage for Failed Checks\n        ARGUSAGE.\n        display \"Usage:   \"\n        STOP RUN.\n\n        *> Evaluate Arguments\n        GET-ARGS.\n        ACCEPT command1 FROM ARGUMENT-VALUE\n        IF command1 = SPACE OR LOW-VALUES THEN\n        PERFORM ARGUSAGE\n        ELSE\n        INSPECT command1 REPLACING ALL SPACES BY LOW-VALUES\n\n\n        ACCEPT command2 from ARGUMENT-VALUE\n        IF command2 = SPACE OR LOW-VALUES THEN\n        PERFORM ARGUSAGE\n        ELSE\n        INSPECT command2 REPLACING ALL SPACES BY LOW-VALUES\n\n\n        ACCEPT command3 from ARGUMENT-VALUE\n        IF command3 = SPACE OR LOW-VALUES THEN\n        PERFORM ARGUSAGE\n        ELSE\n                INSPECT command3 REPLACING ALL SPACES BY LOW-VALUES\n        \n\n\n        *> Display Final Output\n        display command1 \" \" command2 \" \" command3\n\n\n        STOP RUN.\n\n.\n\n","human_summarization":"retrieve and print the list of command-line arguments passed to the program. It provides methods for retrieving all arguments at once or one at a time, with arguments being split by whitespace if not enclosed in quotes. It also handles passing arguments from UNIX\/Linux Systems to COBOL, despite the COBOL standard not specifying methods for retrieving command-line arguments.","id":1114}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Nth-Root.\n       AUTHOR.  Bill Gunshannon.\n       INSTALLATION.  \n       DATE-WRITTEN.  4 Feb 2020.\n      ************************************************************\n      ** Program Abstract:\n      **   Compute the Nth Root of a positive real number.\n      **   \n      **   Takes values from console.  If Precision is left\n      **   blank defaults to 0.001.\n      **   \n      **   Enter 0 for first value to terminate program.\n      ************************************************************\n       \n       ENVIRONMENT DIVISION.\n       \n       INPUT-OUTPUT SECTION.\n       FILE-CONTROL.\n            SELECT Root-File ASSIGN TO \"Root-File\"\n                 ORGANIZATION IS LINE SEQUENTIAL.\n       \n       DATA DIVISION.\n       \n       FILE SECTION.\n       \n       FD  Root-File\n           DATA RECORD IS Parameters.\n       01  Parameters.\n           05 Root                       PIC 9(5).\n           05 Num                        PIC 9(5)V9(5).\n           05 Precision                  PIC 9V9(9).\n\n       \n       WORKING-STORAGE SECTION.\n       \n       01  TEMP0                         PIC 9(9)V9(9).\n       01  TEMP1                         PIC 9(9)V9(9).\n       01  RESULTS.\n           05  Field1                        PIC ZZZZZ.ZZZZZ.\n           05  FILLER                        PIC X(5).\n           05  Field2                        PIC ZZZZ9.\n           05  FILLER                        PIC X(14).\n           05  Field3                        PIC 9.999999999.\n\n       01  HEADER.\n           05  FILLER                        PIC X(72) \n               VALUE \"   Number           Root           Precision.\".\n       \n       01  Disp-Root                         PIC ZZZZZ.ZZZZZ.\n       \n       PROCEDURE DIVISION.\n       \n       Main-Program.\n           PERFORM FOREVER\n           \n              PERFORM Get-Input\n              IF Precision = 0.0 \n                  THEN MOVE 0.001 to Precision\n              END-IF\n\n              PERFORM Compute-Root\n\n              MOVE Root TO Field2\n              MOVE Num TO Field1\n              MOVE Precision TO Field3\n              DISPLAY HEADER\n              DISPLAY RESULTS\n              DISPLAY \" \"\n              MOVE TEMP1 TO Disp-Root\n              DISPLAY \"The Root is: \" Disp-Root\n           END-PERFORM.\n       \n       Get-Input.\n           DISPLAY \"Input Base Number: \" WITH NO ADVANCING\n           ACCEPT Num\n           IF Num EQUALS ZERO\n              THEN \n                   DISPLAY \"Good Bye.\"\n                   STOP RUN\n           END-IF\n           DISPLAY \"Input Root: \" WITH NO ADVANCING\n           ACCEPT Root\n           DISPLAY \"Input Desired Precision: \" WITH NO ADVANCING\n           ACCEPT Precision.\n\n       Compute-Root.\n          MOVE Root TO TEMP0\n          DIVIDE Num BY Root GIVING TEMP1\n\n          PERFORM UNTIL FUNCTION ABS(TEMP0 - TEMP1) \n                                    LESS THAN Precision \n               MOVE TEMP1 TO TEMP0\n               COMPUTE TEMP1 = (( Root - 1.0) * TEMP1 + Num \/ \n                                        TEMP1 ** (Root - 1.0)) \/ Root\n          END-PERFORM.\n       \n       END-PROGRAM.\n\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":1115}
    {"lang_cluster":"COBOL","source_code":"\n       identification division.\n       program-id. hostname.\n\n       data division.\n       working-storage section.\n       01 hostname pic x(256).\n       01 nullpos  pic 999 value 1.\n\n       procedure division.\n       call \"gethostname\" using hostname by value length of hostname\n       string hostname delimited by low-value into hostname\n           with pointer nullpos\n       display \"Host: \" hostname(1 : nullpos - 1)\n       goback.\n       end program hostname.\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":1116}
    {"lang_cluster":"COBOL","source_code":"\n        >>SOURCE FORMAT FREE\n*> This code is dedicated to the public domain\n*> This is GNUCobol 2.0\nidentification division.\nprogram-id. twentyfour.\nenvironment division.\nconfiguration section.\nrepository. function all intrinsic.\ndata division.\nworking-storage section.\n01  p pic 999.\n01  p1 pic 999.\n01  p-max pic 999 value 38.\n01  program-syntax pic x(494) value\n*>statement = expression;\n        '001 001 000 n'\n    &   '002 000 004 ='\n    &   '003 005 000 n'\n    &   '004 000 002\u00a0;'\n*>expression = term, {('+'|'-') term,};\n    &   '005 005 000 n'\n    &   '006 000 016 ='\n    &   '007 017 000 n'\n    &   '008 000 015 {'\n    &   '009 011 013 ('\n    &   '010 001 000 t'\n    &   '011 013 000 |'\n    &   '012 002 000 t'\n    &   '013 000 009 )'\n    &   '014 017 000 n'\n    &   '015 000 008 }'\n    &   '016 000 006\u00a0;'\n*>term = factor, {('*'|'\/') factor,};\n    &   '017 017 000 n'\n    &   '018 000 028 ='\n    &   '019 029 000 n'\n    &   '020 000 027 {'\n    &   '021 023 025 ('\n    &   '022 003 000 t'\n    &   '023 025 000 |'\n    &   '024 004 000 t'\n    &   '025 000 021 )'\n    &   '026 029 000 n'\n    &   '027 000 020 }'\n    &   '028 000 018\u00a0;'\n*>factor = ('(' expression, ')' | digit,);\n    &   '029 029 000 n'\n    &   '030 000 038 ='\n    &   '031 035 037 ('\n    &   '032 005 000 t'\n    &   '033 005 000 n'\n    &   '034 006 000 t'\n    &   '035 037 000 |'\n    &   '036 000 000 n'\n    &   '037 000 031 )'\n    &   '038 000 030\u00a0;'.\n01  filler redefines program-syntax.\n    03  p-entry occurs 038.\n        05  p-address pic 999.\n        05  filler pic x.\n        05  p-definition pic 999.\n        05  p-alternate redefines p-definition pic 999.\n        05  filler pic x.\n        05  p-matching pic 999.\n        05  filler pic x.\n        05  p-symbol pic x.\n\n01  t pic 999.\n01  t-len pic 99 value 6.\n01  terminal-symbols\n    pic x(210) value\n        '01 +                               '                                                               \n    &   '01 -                               '                                                               \n    &   '01 *                               '\n    &   '01 \/                               '\n    &   '01 (                               '\n    &   '01 )                               '.\n01  filler redefines terminal-symbols.\n    03  terminal-symbol-entry occurs 6.\n        05  terminal-symbol-len pic 99.\n        05  filler pic x.\n        05  terminal-symbol pic x(32).\n\n01  nt pic 999.\n01  nt-lim pic 99 value 5.\n01  nonterminal-statements pic x(294) value\n        \"000 ....,....,....,....,....,....,....,....,....,\"\n    &   \"001 statement = expression;                      \"                                                       \n    &   \"005 expression = term, {('+'|'-') term,};        \"                                                      \n    &   \"017 term = factor, {('*'|'\/') factor,};          \"                                                             \n    &   \"029 factor = ('(' expression, ')' | digit,);     \"                                                           \n    &   \"036 digit;                                       \".                                                            \n01  filler redefines nonterminal-statements.\n    03  nonterminal-statement-entry occurs 5.\n        05  nonterminal-statement-number pic 999.\n        05  filler pic x.\n        05  nonterminal-statement pic x(45).\n\n01  indent pic x(64) value all '|  '. \n01  interpreter-stack.\n    03  r pic 99. *> previous top of stack\n    03  s pic 99. *> current top of stack\n    03  s-max pic 99 value 32.\n    03  s-entry occurs 32.\n        05  filler pic x(2) value 'p='.\n        05  s-p pic 999. *> callers return address\n        05  filler pic x(4) value ' sc='.\n        05  s-start-control pic 999. *> sequence start address\n        05  filler pic x(4) value ' ec='.\n        05  s-end-control pic 999. *> sequence end address\n        05  filler pic x(4) value ' al='.\n        05  s-alternate pic 999. *> the next alternate \n        05  filler pic x(3) value ' r='.\n        05  s-result pic x. *> S success, F failure, N no result\n        05  filler pic x(3) value ' c='.\n        05  s-count pic 99. *> successes in a sequence\n        05  filler pic x(3) value ' x='.\n        05  s-repeat pic 99. *> repeats in a {} sequence\n        05  filler pic x(4) value ' nt='.\n        05  s-nt pic 99. *> current nonterminal\n\n01  language-area.\n    03  l pic 99.\n    03  l-lim pic 99.\n    03  l-len pic 99 value 1.\n    03  nd pic 9.\n    03  number-definitions.\n        05  n occurs 4 pic 9.\n    03  nu pic 9.\n    03  number-use.\n        05  u occurs 4 pic x.\n    03  statement.\n        05  c occurs 32.\n            07  c9 pic 9.\n\n01  number-validation.\n    03  p4 pic 99.\n    03  p4-lim pic 99 value 24.\n    03  permutations-4 pic x(96) value\n          '1234'\n        & '1243'\n        & '1324'\n        & '1342'\n        & '1423'\n        & '1432'\n        & '2134'\n        & '2143'\n        & '2314'\n        & '2341'\n        & '2413'\n        & '2431'\n        & '3124'\n        & '3142'\n        & '3214'\n        & '3241'\n        & '3423'\n        & '3432'\n        & '4123'\n        & '4132'\n        & '4213'\n        & '4231'\n        & '4312'\n        & '4321'.\n     03  filler redefines permutations-4.\n         05  permutation-4 occurs 24 pic x(4).\n     03  current-permutation-4 pic x(4).\n     03  cpx pic 9.\n     03  od1 pic 9.\n     03  od2 pic 9.\n     03  odx pic 9.\n     03  od-lim pic 9 value 4.\n     03  operator-definitions pic x(4) value '+-*\/'.\n     03  current-operators pic x(3).\n     03  co3 pic 9.\n     03  rpx pic 9.\n     03  rpx-lim pic 9 value 4.\n     03  valid-rpn-forms pic x(28) value\n          'nnonono'\n        & 'nnnonoo'\n        & 'nnnoono'\n        & 'nnnnooo'.\n    03  filler redefines valid-rpn-forms.\n        05  rpn-form occurs 4 pic x(7).\n    03  current-rpn-form pic x(7).\n\n01  calculation-area.\n    03  osx pic 99.\n    03  operator-stack pic x(32).\n    03  oqx pic 99.\n    03  oqx1 pic 99.\n    03  output-queue pic x(32).\n    03  work-number pic s9999.\n    03  top-numerator pic s9999 sign leading separate.\n    03  top-denominator pic s9999 sign leading separate.\n    03  rsx pic 9.\n    03  result-stack occurs 8.\n        05  numerator pic s9999.\n        05  denominator pic s9999.\n\n01  error-found pic x.\n01  divide-by-zero-error pic x.\n\n*>  diagnostics\n01  NL pic x value x'0A'.\n01  NL-flag pic x value space.\n01  display-level pic x value '0'.\n01  loop-lim pic 9999 value 1500.\n01  loop-count pic 9999 value 0.\n01  message-area value spaces.\n    03  message-level pic x.\n    03  message-value pic x(128).\n\n*>  input and examples\n01  instruction pic x(32) value spaces.\n01  tsx pic 99.\n01  tsx-lim pic 99 value 14.\n01  test-statements.\n    03  filler pic x(32) value '1234;1 + 2 + 3 + 4'.\n    03  filler pic x(32) value '1234;1 * 2 * 3 * 4'. \n    03  filler pic x(32) value '1234;((1)) * (((2 * 3))) * 4'. \n    03  filler pic x(32) value '1234;((1)) * ((2 * 3))) * 4'. \n    03  filler pic x(32) value '1234;(1 + 2 + 3 + 4'. \n    03  filler pic x(32) value '1234;)1 + 2 + 3 + 4'. \n    03  filler pic x(32) value '1234;1 * * 2 * 3 * 4'. \n    03  filler pic x(32) value '5679;6 - (5 - 7) * 9'. \n    03  filler pic x(32) value '1268;((1 * (8 * 6) \/ 2))'. \n    03  filler pic x(32) value '4583;-5-3+(8*4)'. \n    03  filler pic x(32) value '4583;8 * 4 - 5 - 3'. \n    03  filler pic x(32) value '4583;8 * 4 - (5 + 3)'. \n    03  filler pic x(32) value '1223;1 * 3 \/ (2 - 2)'. \n    03  filler pic x(32) value '2468;(6 * 8) \/ 4 \/ 2'. \n01  filler redefines test-statements.\n    03  filler occurs 14.\n        05  test-numbers pic x(4).\n        05  filler pic x.\n        05  test-statement pic x(27).\n\nprocedure division.\nstart-twentyfour.\n    display 'start twentyfour'\n    perform generate-numbers\n    display 'type h  to see instructions'\n    accept instruction\n    perform until instruction = spaces or 'q'\n        evaluate true\n        when instruction = 'h'\n            perform display-instructions\n        when instruction = 'n'\n            perform generate-numbers\n        when instruction(1:1) = 'm'\n            move instruction(2:4) to number-definitions\n            perform validate-number\n            if divide-by-zero-error = space\n            and 24 * top-denominator = top-numerator\n                display number-definitions ' is solved by ' output-queue(1:oqx)\n            else\n                display number-definitions ' is not solvable'\n            end-if\n        when instruction = 'd0' or 'd1' or 'd2' or 'd3'\n            move instruction(2:1) to display-level\n        when instruction = 'e'\n            display 'examples:'\n            perform varying tsx from 1 by 1\n            until tsx > tsx-lim\n                move spaces to statement\n                move test-numbers(tsx) to number-definitions\n                move test-statement(tsx) to statement\n                perform evaluate-statement\n                perform show-result\n            end-perform\n        when other\n            move instruction to statement\n            perform evaluate-statement\n            perform show-result\n        end-evaluate\n        move spaces to instruction\n        display 'instruction? ' with no advancing\n        accept instruction\n    end-perform\n\n    display 'exit twentyfour'\n    stop run\n    .\ngenerate-numbers.\n    perform with test after until divide-by-zero-error = space\n    and 24 * top-denominator = top-numerator\n        compute n(1) = random(seconds-past-midnight) * 10 *> seed\n        perform varying nd from 1 by 1 until nd > 4\n            compute n(nd) = random() * 10\n            perform until n(nd) <> 0\n                compute n(nd) = random() * 10\n            end-perform\n        end-perform\n        perform validate-number\n    end-perform\n    display NL 'numbers:' with no advancing\n    perform varying nd from 1 by 1 until nd > 4\n        display space n(nd) with no advancing\n    end-perform\n    display space\n    .\nvalidate-number.\n    perform varying p4 from 1 by 1 until p4 > p4-lim\n        move permutation-4(p4) to current-permutation-4 \n        perform varying od1 from 1 by 1 until od1 > od-lim\n            move operator-definitions(od1:1) to current-operators(1:1)\n            perform varying od2 from 1 by 1 until od2 > od-lim\n                move operator-definitions(od2:1) to current-operators(2:1)\n                perform varying odx from 1 by 1 until odx > od-lim\n                    move operator-definitions(odx:1) to current-operators(3:1)\n                    perform varying rpx from 1 by 1 until rpx > rpx-lim\n                        move rpn-form(rpx) to current-rpn-form\n                        move 0 to cpx co3\n                        move spaces to output-queue\n                        move 7 to oqx\n                        perform varying oqx1 from 1 by 1 until oqx1 > oqx\n                            if current-rpn-form(oqx1:1) = 'n'\n                                add 1 to cpx\n                                move current-permutation-4(cpx:1) to nd\n                                move n(nd) to output-queue(oqx1:1)\n                            else\n                                add 1 to co3\n                                move current-operators(co3:1) to output-queue(oqx1:1)\n                            end-if\n                        end-perform\n                    end-perform\n                    perform evaluate-rpn\n                    if divide-by-zero-error = space\n                    and 24 * top-denominator = top-numerator\n                        exit paragraph\n                    end-if\n                end-perform\n            end-perform\n        end-perform\n    end-perform\n    .  \ndisplay-instructions.\n    display '1)  Type h  to repeat these instructions.'\n    display '2)  The program will display four randomly-generated'\n    display '    single-digit numbers and will then prompt you to enter'\n    display '    an arithmetic expression followed by  to sum'\n    display '    the given numbers to 24.'\n    display '    The four numbers may contain duplicates and the entered'\n    display '    expression must reference all the generated numbers and duplicates.'\n    display '    Warning:  the program converts the entered infix expression'\n    display '    to a reverse polish notation (rpn) expression'\n    display '    which is then interpreted from RIGHT to LEFT.'\n    display '    So, for instance, 8*4 - 5 - 3 will not sum to 24.' \n    display '3)  Type n  to generate a new set of four numbers.'\n    display '    The program will ensure the generated numbers are solvable.'\n    display '4)  Type m####  (e.g. m1234) to create a fixed set of numbers'\n    display '    for testing purposes.'\n    display '    The program will test the solvability of the entered numbers.'\n    display '    For example, m1234 is solvable and m9999 is not solvable.'\n    display '5)  Type d0, d1, d2 or d3 followed by  to display none or'\n    display '    increasingly detailed diagnostic information as the program evaluates' \n    display '    the entered expression.'\n    display '6)  Type e  to see a list of example expressions and results'\n    display '7)  Type  or q  to exit the program' \n    .\nshow-result.\n    if error-found = 'y'\n    or divide-by-zero-error = 'y'\n        exit paragraph\n    end-if\n    display 'statement in RPN is' space output-queue\n    evaluate true\n    when top-numerator = 0\n    when top-denominator = 0\n    when 24 * top-denominator <> top-numerator\n        display 'result (' top-numerator '\/' top-denominator ') is not 24'\n    when other\n        display 'result is 24'\n    end-evaluate\n    .\nevaluate-statement.\n    compute l-lim = length(trim(statement))\n\n    display NL 'numbers:' space n(1) space n(2) space n(3) space n(4)\n    move number-definitions to number-use\n    display 'statement is' space statement  \n\n    move 1 to l\n    move 0 to loop-count\n    move space to error-found\n\n    move 0 to osx oqx\n    move spaces to output-queue\n\n    move 1 to p\n    move 1 to nt\n    move 0 to s\n    perform increment-s\n    perform display-start-nonterminal\n    perform increment-p\n\n    *>===================================\n    *> interpret ebnf\n    *>=================================== \n    perform until s = 0 \n    or error-found = 'y'\n\n        evaluate true\n\n        when p-symbol(p) = 'n'\n        and p-definition(p) = 000 *> a variable\n           perform test-variable\n       if s-result(s) = 'S'\n               perform increment-l\n           end-if\n           perform increment-p\n\n       when p-symbol(p) = 'n'\n       and p-address(p) <> p-definition(p) *> nonterminal reference\n           move p to s-p(s)\n           move p-definition(p) to p\n\n       when p-symbol(p) = 'n'\n       and p-address(p) = p-definition(p) *> nonterminal definition\n           perform increment-s\n           perform display-start-nonterminal\n           perform increment-p\n\n        when p-symbol(p) = '=' *> nonterminal control\n            move p to s-start-control(s)\n            move p-matching(p) to s-end-control(s)\n            perform increment-p\n\n        when p-symbol(p) = ';' *> end nonterminal\n            perform display-end-control\n            perform display-end-nonterminal\n            perform decrement-s\n            if s > 0\n                evaluate true\n                when s-result(r) = 'S'\n                    perform set-success\n                when s-result(r) = 'F'\n                    perform set-failure\n                end-evaluate\n                move s-p(s) to p\n                perform increment-p\n                perform display-continue-nonterminal\n            end-if\n\n    when p-symbol(p) = '{' *> start repeat sequence\n            perform increment-s\n            perform display-start-control\n            move p to s-start-control(s)\n            move p-alternate(p) to s-alternate(s)\n            move p-matching(p) to s-end-control(s)\n            move 0 to s-count(s)\n            perform increment-p\n\n        when p-symbol(p) = '}' *> end repeat sequence\n            perform display-end-control\n            evaluate true\n            when s-result(s) = 'S' *> repeat the sequence\n                perform display-repeat-control\n                perform set-nothing\n                add 1 to s-repeat(s)\n                move s-start-control(s) to p\n                perform increment-p\n           when other\n               perform decrement-s\n               evaluate true\n               when s-result(r) = 'N'\n               and s-repeat(r) = 0 *> no result\n                   perform increment-p\n               when s-result(r) = 'N'\n               and s-repeat(r) > 0 *> no result after success\n                   perform set-success\n                   perform increment-p\n               when other *> fail the sequence\n                   perform increment-p\n               end-evaluate\n           end-evaluate\n\n        when p-symbol(p) = '(' *> start sequence\n            perform increment-s\n            perform display-start-control\n            move p to s-start-control(s)\n            move p-alternate(p) to s-alternate(s)\n            move p-matching(p) to s-end-control(s)\n            move 0 to s-count(s)\n            perform increment-p\n\n       when p-symbol(p) = ')' *> end sequence\n           perform display-end-control\n           perform decrement-s\n           evaluate true\n           when s-result(r) = 'S' *> success\n               perform set-success\n               perform increment-p\n           when s-result(r) = 'N' *> no result\n               perform set-failure\n               perform increment-p\n            when other *> fail the sequence\n               perform set-failure\n               perform increment-p\n           end-evaluate\n\n        when p-symbol(p) = '|' *> alternate\n            evaluate true\n            when s-result(s) = 'S' *> exit the sequence\n                perform display-skip-alternate\n                move s-end-control(s) to p\n            when other\n                perform display-take-alternate\n                move p-alternate(p) to s-alternate(s) *> the next alternate\n                perform increment-p\n                perform set-nothing\n            end-evaluate\n\n        when p-symbol(p) = 't' *> terminal\n            move p-definition(p) to t\n            move terminal-symbol-len(t) to t-len\n            perform display-terminal\n            evaluate true\n            when statement(l:t-len) = terminal-symbol(t)(1:t-len) *> successful match\n               perform set-success\n               perform display-recognize-terminal\n               perform process-token\n               move t-len to l-len\n               perform increment-l\n               perform increment-p\n            when s-alternate(s) <> 000 *> we are in an alternate sequence\n               move s-alternate(s) to p\n            when other *> fail the sequence\n               perform set-failure\n               move s-end-control(s) to p\n            end-evaluate\n\n        when other *> end control\n            perform display-control-failure *> shouldnt happen\n\n        end-evaluate\n\n     end-perform\n\n     evaluate true *> at end of evaluation\n     when error-found = 'y'\n         continue\n     when l <= l-lim *> not all tokens parsed\n         display 'error: invalid statement'\n         perform statement-error\n     when number-use <> spaces\n         display 'error:  not all numbers were used: ' number-use\n         move 'y' to error-found\n     end-evaluate\n    .\nincrement-l.\n    evaluate true\n    when l > l-lim *> end of statement\n        continue\n    when other\n        add l-len to l\n        perform varying l from l by 1 \n        until c(l) <> space\n        or l > l-lim\n            continue\n        end-perform\n        move 1 to l-len\n        if l > l-lim\n            perform end-tokens\n        end-if\n    end-evaluate\n    .\nincrement-p.\n    evaluate true\n    when p >= p-max\n        display 'at' space p ' parse overflow'\n            space 's=<' s space s-entry(s) '>'\n        move 'y' to error-found\n    when other\n        add 1 to p\n        perform display-statement\n    end-evaluate\n    .\nincrement-s.\n    evaluate true\n    when s >= s-max\n        display 'at' space p ' stack overflow '\n            space 's=<' s space s-entry(s) '>'\n        move 'y' to error-found\n    when other\n        move s to r\n        add 1 to s\n        initialize s-entry(s)\n        move 'N' to s-result(s)\n        move p to s-p(s)\n        move nt to s-nt(s)\n    end-evaluate\n    .\ndecrement-s.\n    if s > 0\n        move s to r\n        subtract 1 from s\n        if s > 0\n            move s-nt(s) to nt\n        end-if\n    end-if\n    .\nset-failure.\n    move 'F' to s-result(s)\n    if s-count(s) > 0\n        display 'sequential parse failure'\n        perform statement-error\n    end-if\n    .\nset-success.\n    move 'S' to s-result(s)\n    add 1 to s-count(s)\n    .\nset-nothing.\n    move 'N' to s-result(s)\n    move 0 to s-count(s)\n    .\nstatement-error.\n    display statement\n    move spaces to statement\n    move '^ syntax error' to statement(l:)\n    display statement\n    move 'y' to error-found\n    .\n*>=====================\n*> twentyfour semantics\n*>=====================\ntest-variable.\n    *> check validity\n    perform varying nd from 1 by 1 until nd > 4\n    or c(l) = n(nd)\n        continue\n    end-perform\n    *> check usage\n    perform varying nu from 1 by 1 until nu > 4\n    or c(l) = u(nu)\n        continue\n    end-perform\n    evaluate true\n    when l > l-lim\n        perform set-failure\n    when c9(l) not numeric\n        perform set-failure\n    when nd > 4\n        display 'invalid number'\n        perform statement-error\n    when nu > 4\n        display 'number already used'\n        perform statement-error\n    when other\n        move space to u(nu)\n        perform set-success\n        add 1 to oqx\n        move c(l) to output-queue(oqx:1)\n    end-evaluate\n    .\n*> ==================================\n*> Dijkstra Shunting-Yard Algorithm\n*> to convert infix to rpn\n*> ==================================\nprocess-token.\n    evaluate true\n    when c(l) = '('\n        add 1 to osx\n        move c(l) to operator-stack(osx:1)\n    when c(l) = ')'\n        perform varying osx from osx by -1 until osx < 1\n        or operator-stack(osx:1) = '('\n            add 1 to oqx\n            move operator-stack(osx:1) to output-queue(oqx:1)\n        end-perform\n        if osx < 1\n            display 'parenthesis error'\n            perform statement-error\n            exit paragraph\n        end-if\n        subtract 1 from osx\n    when (c(l) = '+' or '-') and (operator-stack(osx:1) = '*' or '\/')\n        *> lesser operator precedence\n        add 1 to oqx\n        move operator-stack(osx:1) to output-queue(oqx:1) \n        move c(l) to operator-stack(osx:1)\n    when other\n        *> greater operator precedence\n        add 1 to osx\n        move c(l) to operator-stack(osx:1)\n    end-evaluate\n    . \nend-tokens.\n    *> 1) copy stacked operators to the output-queue\n    perform varying osx from osx by -1 until osx < 1\n    or operator-stack(osx:1) = '('\n        add 1 to oqx\n        move operator-stack(osx:1) to output-queue(oqx:1)\n    end-perform\n    if osx > 0\n        display 'parenthesis error'\n        perform statement-error\n        exit paragraph\n    end-if\n    *> 2) evaluate the rpn statement\n    perform evaluate-rpn\n    if divide-by-zero-error = 'y'\n        display 'divide by zero error'\n    end-if\n    .\nevaluate-rpn.\n    move space to divide-by-zero-error\n    move 0 to rsx *> stack depth\n    perform varying oqx1 from 1 by 1 until oqx1 > oqx\n        if output-queue(oqx1:1) >= '1' and <= '9'\n            *> push current data onto the stack\n            add 1 to rsx\n            move top-numerator to numerator(rsx)\n            move top-denominator to denominator(rsx)\n            move output-queue(oqx1:1) to top-numerator\n            move 1 to top-denominator\n        else\n            *> apply the operation\n            evaluate true\n            when output-queue(oqx1:1) = '+'\n                compute top-numerator = top-numerator * denominator(rsx)\n                    + top-denominator * numerator(rsx)\n                compute top-denominator = top-denominator * denominator(rsx)  \n            when output-queue(oqx1:1) = '-' \n                compute top-numerator = top-denominator * numerator(rsx)\n                    - top-numerator * denominator(rsx)\n                compute top-denominator = top-denominator * denominator(rsx)  \n            when output-queue(oqx1:1) = '*' \n                compute top-numerator = top-numerator * numerator(rsx)\n                compute top-denominator = top-denominator * denominator(rsx)  \n            when output-queue(oqx1:1) = '\/'\n                compute work-number = numerator(rsx) * top-denominator\n                compute top-denominator = denominator(rsx) * top-numerator\n                if top-denominator = 0\n                    move 'y' to divide-by-zero-error\n                    exit paragraph\n                end-if\n                move work-number to top-numerator\n            end-evaluate\n            *> pop the stack\n            subtract 1 from rsx\n        end-if\n    end-perform \n    .\n*>====================\n*> diagnostic displays\n*>====================\ndisplay-start-nonterminal.\n    perform varying nt from nt-lim by -1 until nt < 1\n    or p-definition(p) = nonterminal-statement-number(nt)\n        continue\n    end-perform\n    if nt > 0\n        move '1' to NL-flag\n        string '1' indent(1:s + s) 'at ' s space p ' start ' trim(nonterminal-statement(nt))\n            into message-area perform display-message\n        move nt to s-nt(s)\n    end-if\n    .\ndisplay-continue-nonterminal.\n    move s-nt(s) to nt\n    string '1' indent(1:s + s) 'at ' s space p space p-symbol(p) ' continue ' trim(nonterminal-statement(nt)) ' with result ' s-result(s)\n            into message-area perform display-message\n    .\ndisplay-end-nonterminal.\n    move s-nt(s) to nt\n    move '2' to NL-flag\n    string '1' indent(1:s + s) 'at ' s space p ' end ' trim(nonterminal-statement(nt)) ' with result ' s-result(s)\n            into message-area perform display-message\n    .\ndisplay-start-control.\n    string '2' indent(1:s + s) 'at ' s space p ' start ' p-symbol(p) ' in ' trim(nonterminal-statement(nt))\n        into message-area perform display-message\n    .\ndisplay-repeat-control.\n    string '2' indent(1:s + s) 'at ' s space p ' repeat ' p-symbol(p) ' in ' trim(nonterminal-statement(nt))  ' with result ' s-result(s)\n        into message-area perform display-message\n    .\ndisplay-end-control.\n    string '2' indent(1:s + s) 'at ' s space p ' end ' p-symbol(p)  ' in ' trim(nonterminal-statement(nt)) ' with result ' s-result(s)\n        into message-area perform display-message\n    .\ndisplay-take-alternate.\n    string '2' indent(1:s + s) 'at ' s space p ' take alternate' ' in ' trim(nonterminal-statement(nt))\n        into message-area perform display-message\n    .\ndisplay-skip-alternate.\n    string '2' indent(1:s + s) 'at ' s space p ' skip alternate' ' in ' trim(nonterminal-statement(nt))\n        into message-area perform display-message\n    .\ndisplay-terminal.\n    string '1' indent(1:s + s) 'at ' s space p\n        ' compare ' statement(l:t-len) ' to ' terminal-symbol(t)(1:t-len)\n        ' in ' trim(nonterminal-statement(nt))\n        into message-area perform display-message\n    .\ndisplay-recognize-terminal.\n    string '1' indent(1:s + s) 'at ' s space p ' recognize terminal: ' c(l) ' in ' trim(nonterminal-statement(nt))\n        into message-area perform display-message\n    .\ndisplay-recognize-variable.\n    string '1' indent(1:s + s) 'at ' s space p ' recognize digit: ' c(l) ' in ' trim(nonterminal-statement(nt))\n        into message-area perform display-message\n    .\ndisplay-statement.\n    compute p1 = p - s-start-control(s)\n    string '3' indent(1:s + s) 'at ' s space p\n        ' statement: ' s-start-control(s) '\/' p1\n        space p-symbol(p) space s-result(s)\n        ' in ' trim(nonterminal-statement(nt))\n        into message-area perform display-message\n    .\ndisplay-control-failure.\n    display loop-count space indent(1:s + s) 'at' space p ' control failure' ' in ' trim(nonterminal-statement(nt))\n    display loop-count space indent(1:s + s) '   ' 'p=<' p p-entry(p) '>'\n    display loop-count space indent(1:s + s) '   ' 's=<' s space s-entry(s) '>'\n    display loop-count space indent(1:s + s) '   ' 'l=<' l space c(l)'>'\n    perform statement-error\n    .\ndisplay-message.\n    if display-level = 1\n        move space to NL-flag\n    end-if\n    evaluate true\n    when loop-count > loop-lim *> loop control\n        display 'display count exceeds ' loop-lim\n        stop run\n    when message-level <= display-level\n        evaluate true\n        when NL-flag = '1'\n             display NL loop-count space trim(message-value)\n        when NL-flag = '2'\n             display loop-count space trim(message-value) NL\n        when other\n             display loop-count space trim(message-value)\n        end-evaluate\n    end-evaluate\n    add 1 to loop-count\n    move spaces to message-area\n    move space to NL-flag\n    .\nend program twentyfour.\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":1117}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: GNU Cobol version 2.0\n       >>SOURCE FREE\nIDENTIFICATION DIVISION.\nPROGRAM-ID. run-length-encoding.\n\nENVIRONMENT DIVISION.\nCONFIGURATION SECTION.\nREPOSITORY.\n    FUNCTION encode\n    FUNCTION decode\n    .\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  input-str                           PIC A(100).\n01  encoded                             PIC X(200).\n01  decoded                             PIC X(200).\n\nPROCEDURE DIVISION.\n    ACCEPT input-str\n    MOVE encode(FUNCTION TRIM(input-str)) TO encoded\n    DISPLAY \"Encoded: \" FUNCTION TRIM(encoded)\n    DISPLAY \"Decoded: \" FUNCTION TRIM(decode(encoded))\n    .\nEND PROGRAM run-length-encoding.\n\n\nIDENTIFICATION DIVISION.\nFUNCTION-ID. encode.\n\nDATA DIVISION.\nLOCAL-STORAGE SECTION.\n01  str-len                             PIC 9(3) COMP.\n\n01  i                                   PIC 9(3) COMP.\n\n01  current-char                        PIC A.\n\n01  num-chars                           PIC 9(3) COMP.\n01  num-chars-disp                      PIC Z(3).\n\n01  encoded-pos                         PIC 9(3) COMP VALUE 1.\n\nLINKAGE SECTION.\n01  str                                 PIC X ANY LENGTH.\n\n01  encoded                             PIC X(200).\n\nPROCEDURE DIVISION USING str RETURNING encoded.\n    MOVE FUNCTION LENGTH(str) TO str-len\n    MOVE str (1:1) TO current-char\n    MOVE 1 TO num-chars\n    PERFORM VARYING i FROM 2 BY 1 UNTIL i > str-len\n        IF str (i:1) <> current-char\n            CALL \"add-num-chars\" USING encoded, encoded-pos,\n                CONTENT current-char, num-chars\n                \n            MOVE str (i:1) TO current-char\n            MOVE 1 TO num-chars\n        ELSE\n            ADD 1 TO num-chars\n        END-IF\n    END-PERFORM\n\n    CALL \"add-num-chars\" USING encoded, encoded-pos, CONTENT current-char,\n        num-chars\n    .\nEND FUNCTION encode.\n\nIDENTIFICATION DIVISION.\nPROGRAM-ID. add-num-chars.\n\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  num-chars-disp                      PIC Z(3).\n\nLINKAGE SECTION.\n01  str                                 PIC X(200).\n\n01  current-pos                         PIC 9(3) COMP.\n\n01  char-to-encode                      PIC X.\n\n01  num-chars                           PIC 9(3) COMP.\n\nPROCEDURE DIVISION USING str, current-pos, char-to-encode, num-chars.\n    MOVE num-chars TO num-chars-disp\n    MOVE FUNCTION TRIM(num-chars-disp) TO str (current-pos:3)\n    ADD FUNCTION LENGTH(FUNCTION TRIM(num-chars-disp)) TO current-pos\n    MOVE char-to-encode TO str (current-pos:1)\n    ADD 1 TO current-pos\n    .\nEND PROGRAM add-num-chars.\n\n\nIDENTIFICATION DIVISION.\nFUNCTION-ID. decode.\n\nDATA DIVISION.\nLOCAL-STORAGE SECTION.\n01  encoded-pos                         PIC 9(3) COMP VALUE 1.\n01  decoded-pos                         PIC 9(3) COMP VALUE 1.\n\n01  num-of-char                         PIC 9(3) COMP VALUE 0.\n\nLINKAGE SECTION.\n01  encoded                             PIC X(200).\n\n01  decoded                             PIC X(100).\n\nPROCEDURE DIVISION USING encoded RETURNING decoded.\n    PERFORM VARYING encoded-pos FROM 1 BY 1\n            UNTIL encoded (encoded-pos:2) = SPACES OR encoded-pos > 200\n        IF encoded (encoded-pos:1) IS NUMERIC\n            COMPUTE num-of-char = num-of-char * 10\n                + FUNCTION NUMVAL(encoded (encoded-pos:1))\n        ELSE\n            PERFORM UNTIL num-of-char = 0\n                MOVE encoded (encoded-pos:1) TO decoded (decoded-pos:1)\n                ADD 1 TO decoded-pos\n                SUBTRACT 1 FROM num-of-char\n            END-PERFORM\n        END-IF\n    END-PERFORM\n    .\nEND FUNCTION decode.\n\n\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":1118}
    {"lang_cluster":"COBOL","source_code":"\n\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Concat.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  Str  PIC X(7) VALUE \"Hello, \".\n       01  Str2 PIC X(15).\n\n       PROCEDURE DIVISION.\n           DISPLAY \"Str \u00a0: \" Str\n           STRING Str \" World!\" DELIMITED BY SIZE INTO Str2\n           DISPLAY \"Str2\u00a0: \" Str2\n\n           GOBACK\n           .\n\n\n       ...\n       PROCEDURE DIVISION.\n           DISPLAY \"Str \u00a0: \" Str\n           MOVE FUNCTION CONCATENATE(Str, \" World!\") TO Str2\n           DISPLAY \"Str2\u00a0: \" Str2\n\n           GOBACK\n           .\n\n\n*      *> Using a '&'.\n       01  Long-Str-Val     PIC X(200) VALUE \"Lorem ipsum dolor sit \"\n           & \"amet, consectetuer adipiscing elit, sed diam nonummy \"\n           & \"nibh euismod tincidunt ut laoreet dolore magna aliquam \"\n           & \"erat volutpat.\".\n\n*      *> Using a '-' in column 7. Note the first two literals have no\n*      *> closing quotes.\n       01  Another-Long-Str PIC X(200) VALUE \" Ut wisi enim ad minim \n      -    \"veniam, quis nostrud exerci tation ullamcorper suscipit\n      -    \"lobortis nisl ut aliquip ex ea commodo consequat\".\n\n","human_summarization":"- Initializes a string variable with a text value.\n- Creates a second string variable that combines the original string variable with another string literal.\n- Displays the content of the variables.\n- Demonstrates string concatenation using the STRING verb and the CONCATENATE intrinsic function.\n- Shows additional methods for concatenating string literals.","id":1119}
    {"lang_cluster":"COBOL","source_code":"\n\n      *> TECTONICS\n      *>   wget http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt\n      *>   or visit https:\/\/sourceforge.net\/projects\/souptonuts\/files\n      *>   or snag ftp:\/\/ftp.openwall.com\/pub\/wordlists\/all.gz\n      *>      for a 5 million all language word file (a few phrases)\n      *>   cobc -xj anagrams.cob [-DMOSTWORDS -DMOREWORDS -DALLWORDS]\n      *> ***************************************************************\n       identification division.\n       program-id. anagrams.\n\n       environment division.\n       configuration section.\n       repository.\n           function all intrinsic.\n\n       input-output section.\n       file-control.\n           select words-in\n           assign to wordfile\n           organization is line sequential\n           status is words-status\n           .\n\n       REPLACE ==:LETTERS:== BY ==42==.\n\n       data division.\n       file section.\n       fd words-in record is varying from 1 to :LETTERS: characters\n                             depending on word-length.\n       01 word-record.\n          05 word-data         pic x occurs 0 to :LETTERS: times\n                                     depending on word-length.\n\n       working-storage section.\n       >>IF ALLWORDS DEFINED\n       01 wordfile     constant as \"\/usr\/local\/share\/dict\/all.words\".\n       01 max-words    constant as 4802100.\n\n       >>ELSE-IF MOSTWORDS DEFINED\n       01 wordfile     constant as \"\/usr\/local\/share\/dict\/linux.words\".\n       01 max-words    constant as 628000.\n\n       >>ELSE-IF MOREWORDS DEFINED\n       01 wordfile     constant as \"\/usr\/share\/dict\/words\".\n       01 max-words    constant as 100000.\n\n       >>ELSE\n       01 wordfile     constant as \"unixdict.txt\".\n       01 max-words    constant as 26000.\n       >>END-IF\n\n      *> The 5 million word file needs to restrict the word length\n       >>IF ALLWORDS DEFINED\n       01 max-letters          constant as 26.\n       >>ELSE\n       01 max-letters          constant as :LETTERS:.\n       >>END-IF\n\n       01 word-length          pic 99 comp-5.\n       01 words-status         pic xx.\n          88 ok-status         values '00' thru '09'.\n          88 eof-status        value '10'.\n\n      *> sortable word by letter table\n       01 letter-index         usage index.\n       01 letter-table.\n          05 letters           occurs 1 to max-letters times\n                               depending on word-length\n                               ascending key letter\n                               indexed by letter-index.\n             10 letter         pic x.\n\n      *> table of words\n       01 sorted-index         usage index.\n       01 word-table.\n          05 word-list         occurs 0 to max-words times\n                               depending on word-tally\n                               ascending key sorted-word\n                               indexed by sorted-index.\n             10 match-count    pic 999 comp-5.\n             10 this-word      pic x(max-letters).\n             10 sorted-word    pic x(max-letters).\n       01 sorted-display       pic x(10).\n\n       01 interest-table.\n          05 interest-list     pic 9(8) comp-5\n                               occurs 0 to max-words times\n                               depending on interest-tally.\n\n       01 outer                pic 9(8) comp-5.\n       01 inner                pic 9(8) comp-5.\n       01 starter              pic 9(8) comp-5.\n       01 ender                pic 9(8) comp-5.\n       01 word-tally           pic 9(8) comp-5.\n       01 interest-tally       pic 9(8) comp-5.\n       01 tally-display        pic zz,zzz,zz9.\n\n       01 most-matches         pic 99 comp-5.\n       01 matches              pic 99 comp-5.\n       01 match-display        pic z9.\n\n      *> timing display\n       01 time-stamp.\n          05 filler            pic x(11).\n          05 timer-hours       pic 99.\n          05 filler            pic x.\n          05 timer-minutes     pic 99.\n          05 filler            pic x.\n          05 timer-seconds     pic 99.\n          05 filler            pic x.\n          05 timer-subsec      pic v9(6).\n       01 timer-elapsed        pic 9(6)v9(6).\n       01 timer-value          pic 9(6)v9(6).\n       01 timer-display        pic zzz,zz9.9(6).\n\n      *> ***************************************************************\n       procedure division.\n       main-routine.\n\n       >>IF ALLWORDS DEFINED\n           display \"** Words limited to \" max-letters \" letters **\"\n       >>END-IF\n\n       perform show-time\n\n       perform load-words\n       perform find-most\n       perform display-result\n\n       perform show-time\n       goback\n       .\n\n      *> ***************************************************************\n       load-words.\n       open input words-in\n       if not ok-status then\n           display \"error opening \" wordfile upon syserr\n           move 1 to return-code\n           goback\n       end-if\n\n       perform until exit\n           read words-in\n           if eof-status then exit perform end-if\n           if not ok-status then\n               display wordfile \" read error: \" words-status upon syserr\n           end-if\n\n           if word-length equal zero then exit perform cycle end-if\n\n       >>IF ALLWORDS DEFINED\n           move min(word-length, max-letters) to word-length\n       >>END-IF\n\n           add 1 to word-tally\n           move word-record to this-word(word-tally) letter-table\n           sort letters ascending key letter\n           move letter-table to sorted-word(word-tally)\n       end-perform\n\n       move word-tally to tally-display\n       display trim(tally-display) \" words\" with no advancing\n\n       close words-in\n       if not ok-status then\n           display \"error closing \" wordfile upon syserr\n           move 1 to return-code\n       end-if\n\n      *> sort word list by anagram check field\n       sort word-list ascending key sorted-word\n       .\n\n      *> first entry in a list will end up with highest match count\n       find-most.\n       perform varying outer from 1 by 1 until outer > word-tally\n           move 1 to matches\n           add 1 to outer giving starter\n           perform varying inner from starter by 1\n                   until sorted-word(inner) not equal sorted-word(outer)\n               add 1 to matches\n           end-perform\n           if matches > most-matches then\n               move matches to most-matches\n               initialize interest-table all to value\n               move 0 to interest-tally\n           end-if\n           move matches to match-count(outer)\n           if matches = most-matches then\n               add 1 to interest-tally\n               move outer to interest-list(interest-tally)\n           end-if\n       end-perform\n       .\n\n      *> only display the words with the most anagrams\n       display-result.\n       move interest-tally to tally-display\n       move most-matches to match-display\n       display \", most anagrams: \" trim(match-display)\n               \", with \" trim(tally-display) \" set\" with no advancing\n       if interest-tally not equal 1 then\n           display \"s\" with no advancing\n       end-if\n       display \" of interest\"\n\n       perform varying outer from 1 by 1 until outer > interest-tally\n           move sorted-word(interest-list(outer)) to sorted-display\n           display sorted-display\n                   \" [\" trim(this-word(interest-list(outer)))\n              with no advancing\n           add 1 to interest-list(outer) giving starter\n           add most-matches to interest-list(outer) giving ender\n           perform varying inner from starter by 1\n               until inner = ender\n                   display \", \" trim(this-word(inner))\n                      with no advancing\n           end-perform\n           display \"]\"\n       end-perform\n       .\n\n      *> elapsed time\n       show-time.\n       move formatted-current-date(\"YYYY-MM-DDThh:mm:ss.ssssss\")\n         to time-stamp\n       compute timer-value = timer-hours * 3600 + timer-minutes * 60\n                             + timer-seconds + timer-subsec\n       if timer-elapsed = 0 then\n           display time-stamp\n           move timer-value to timer-elapsed\n       else\n           if timer-value < timer-elapsed then\n               add 86400 to timer-value\n           end-if\n           subtract timer-elapsed from timer-value\n           move timer-value to timer-display\n           display time-stamp \", \" trim(timer-display) \" seconds\"\n       end-if\n       .\n\n       end program anagrams.\n\n\n","human_summarization":"find the largest sets of anagrams from the word list provided at http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt using GnuCOBOL 2.0. The output display of all words is trimmed for width.","id":1120}
    {"lang_cluster":"COBOL","source_code":"\n\nidentification division.\nprogram-id. countdown.\nenvironment division.\ndata division.\nworking-storage section.\n01\tcounter \t\tpic 99.\n\t88\tcounter-done\tvalue 0.\n01\tcounter-disp\tpic Z9.\nprocedure division.\n\tperform with test after varying counter from 10 by -1 until counter-done\n\t\tmove counter to counter-disp\n\t\tdisplay counter-disp\n\tend-perform\n\tstop run.\n\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":1121}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Display-Odd-Nums.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  I PIC 99.\n\n       PROCEDURE DIVISION.\n           PERFORM VARYING I FROM 1 BY 2 UNTIL 10 < I\n               DISPLAY I\n           END-PERFORM\n\n           GOBACK\n           .\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":1122}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Ackermann.\n\n       DATA DIVISION.\n       LINKAGE SECTION.\n       01  M          USAGE UNSIGNED-LONG.\n       01  N          USAGE UNSIGNED-LONG.\n\n       01  Return-Val USAGE UNSIGNED-LONG.\n\n       PROCEDURE DIVISION USING M N Return-Val.\n           EVALUATE M ALSO N\n               WHEN 0 ALSO ANY\n                   ADD 1 TO N GIVING Return-Val\n\n               WHEN NOT 0 ALSO 0\n                   SUBTRACT 1 FROM M\n                   CALL \"Ackermann\" USING BY CONTENT M BY CONTENT 1\n                       BY REFERENCE Return-Val\n\n               WHEN NOT 0 ALSO NOT 0\n                   SUBTRACT 1 FROM N\n                   CALL \"Ackermann\" USING BY CONTENT M BY CONTENT N\n                       BY REFERENCE Return-Val\n                       \n                   SUBTRACT 1 FROM M\n                   CALL \"Ackermann\" USING BY CONTENT M\n                       BY CONTENT Return-Val BY REFERENCE Return-Val\n           END-EVALUATE\n\n           GOBACK\n           .\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":1123}
    {"lang_cluster":"COBOL","source_code":"\n       identification division.\n       program-id. array-concat.\n\n       environment division.\n       configuration section.\n       repository.\n           function all intrinsic.\n\n       data division.\n       working-storage section.\n       01 table-one.\n          05 int-field pic 999 occurs 0 to 5 depending on t1.\n       01 table-two.\n          05 int-field pic 9(4) occurs 0 to 10 depending on t2.\n\n       77 t1           pic 99.\n       77 t2           pic 99.\n\n       77 show         pic z(4).\n\n       procedure division.\n       array-concat-main.\n       perform initialize-tables\n       perform concatenate-tables\n       perform display-result\n       goback.\n\n       initialize-tables.\n           move 4 to t1\n           perform varying tally from 1 by 1 until tally > t1\n               compute int-field of table-one(tally) = tally * 3\n           end-perform\n\n           move 3 to t2\n           perform varying tally from 1 by 1 until tally > t2\n               compute int-field of table-two(tally) = tally * 6\n           end-perform\n       .\n\n       concatenate-tables.\n           perform varying tally from 1 by 1 until tally > t1\n               add 1 to t2\n               move int-field of table-one(tally)\n                 to int-field of table-two(t2)\n           end-perform\n       .\n\n       display-result.\n           perform varying tally from 1 by 1 until tally = t2\n               move int-field of table-two(tally) to show\n               display trim(show) \", \" with no advancing\n           end-perform\n           move int-field of table-two(tally) to show\n           display trim(show)\n       .\n\n       end program array-concat.\n\n\n","human_summarization":"demonstrate how to concatenate two arrays.","id":1124}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. MD5.\n       AUTHOR.  Bill Gunshannon\n       INSTALLATION.  Home.\n       DATE-WRITTEN.  16 December 2021.\n      ************************************************************\n      ** Program Abstract:\n      **   Use the md5sum utility and pass the HASH back using\n      **     a temp file.  Not elegant, but it works.\n      ************************************************************\n       \n       \n       ENVIRONMENT DIVISION.\n       \n       INPUT-OUTPUT SECTION.\n       FILE-CONTROL.\n            SELECT Tmp-MD5 ASSIGN TO \"\/tmp\/MD5\"\n                 ORGANIZATION IS LINE SEQUENTIAL.\n\n\n       DATA DIVISION.\n\n       FILE SECTION.\n       \n       FD  Tmp-MD5\n           DATA RECORD IS MD5-Rec.\n       01  MD5-Rec       PIC X(32).\n\n       \n       WORKING-STORAGE SECTION.\n       \n       01 Eof                   PIC X     VALUE 'F'.\n       01 Str1.\n          05  Pre-cmd   PIC X(8)\n              VALUE 'echo -n '.\n          05  Str1-complete.\n              10  Str1-Part1  PIC X(26)\n                  VALUE  'The quick brown fox jumps'.\n              10  Str1-Part2  PIC X(19)\n                  VALUE  ' over the lazy dog'.\n          05  Post-cmd    PIC X(20)\n              VALUE  ' | md5sum > \/tmp\/MD5'.\n       01  Str1-MD5          PIC X(32).\n       \n       \n       PROCEDURE DIVISION.\n       \n       Main-Program.\n\n           DISPLAY Str1-complete.\n           PERFORM Get-MD5.\n           DISPLAY Str1-MD5.\n\n           STOP RUN.\n\n       Get-MD5.\n       \n           CALL \"SYSTEM\" USING Str1.\n           OPEN INPUT Tmp-MD5.\n           READ Tmp-MD5 INTO Str1-MD5.\n           CLOSE Tmp-MD5.\n           CALL \"CBL_DELETE_FILE\" USING '\/tmp\/MD5'.\n\n \n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. MD5-DEMO.\n       AUTHOR.  Bill Gunshannon\n       INSTALLATION.  Home.\n       DATE-WRITTEN.  16 December 2021.\n      ************************************************************\n      ** Program Abstract:\n      **   Use the md5sum utility and pass the HASH back using\n      **     a temp file.  Not elegant, but it works.\n      **   Same program but made MD5 a User Defined Function\n      **     instead of a procedure.\n      ************************************************************\n \n \n       ENVIRONMENT DIVISION.\n \n       CONFIGURATION SECTION.\n\n       REPOSITORY.\n          FUNCTION MD5.\n\n       DATA DIVISION.\n \n       WORKING-STORAGE SECTION.\n \n       01 Eof                   PIC X     VALUE 'F'.\n       01 Str1.\n          05  Pre-cmd   PIC X(8)\n              VALUE 'echo -n '.\n          05  Str1-complete.\n              10  Str1-Part1  PIC X(26)\n                  VALUE  'The quick brown fox jumps'.\n              10  Str1-Part2  PIC X(19)\n                  VALUE  ' over the lazy dog'.\n          05  Post-cmd    PIC X(20)\n              VALUE  ' | md5sum > \/tmp\/MD5'.\n       01  Str1-MD5          PIC X(32).\n \n \n       PROCEDURE DIVISION.\n \n       Main-Program.\n \n           DISPLAY Str1-complete.\n      *    PERFORM Get-MD5.\n           MOVE FUNCTION MD5(Str1) TO Str1-MD5.\n           DISPLAY Str1-MD5.\n \n           STOP RUN.\n\n        END PROGRAM MD5-DEMO.\n \n       IDENTIFICATION DIVISION.\n       FUNCTION-ID. MD5.\n\n       ENVIRONMENT DIVISION.\n\n       INPUT-OUTPUT SECTION.\n       FILE-CONTROL.\n            SELECT Tmp-MD5 ASSIGN TO \"\/tmp\/MD5\"\n                 ORGANIZATION IS LINE SEQUENTIAL.\n\n\n       DATA DIVISION.\n\n       FILE SECTION.\n\n       FD  Tmp-MD5\n           DATA RECORD IS MD5-Rec.\n       01  MD5-Rec       PIC X(32).\n\n\n\n       LINKAGE SECTION.\n       01  Str1        PIC X(128).\n       01  Str1-MD5    PIC X(32).\n\n       PROCEDURE DIVISION USING Str1 RETURNING Str1-MD5.\n \n           CALL \"SYSTEM\" USING FUNCTION TRIM(Str1).\n           OPEN INPUT Tmp-MD5.\n           READ Tmp-MD5 INTO Str1-MD5.\n           CLOSE Tmp-MD5.\n           CALL \"CBL_DELETE_FILE\" USING '\/tmp\/MD5'.\n           GO-BACK. \n\n        END FUNCTION MD5.\n\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":1125}
    {"lang_cluster":"COBOL","source_code":"Works with: GNU Cobol version 2.0\n       >>SOURCE FREE\nIDENTIFICATION DIVISION.\nPROGRAM-ID. count-in-octal.\n\nENVIRONMENT DIVISION.\nCONFIGURATION SECTION.\nREPOSITORY.\n    FUNCTION dec-to-oct\n    .\nDATA DIVISION.\nWORKING-STORAGE SECTION.\n01  i                                   PIC 9(18).\n\nPROCEDURE DIVISION.\n    PERFORM VARYING i FROM 1 BY 1 UNTIL i = 0\n        DISPLAY FUNCTION dec-to-oct(i)\n    END-PERFORM\n    .\nEND PROGRAM count-in-octal.\n\n\nIDENTIFICATION DIVISION.\nFUNCTION-ID. dec-to-oct.\n\nDATA DIVISION.\nLOCAL-STORAGE SECTION.\n01  rem                                 PIC 9.\n\n01  dec                                 PIC 9(18).\n\nLINKAGE SECTION.\n01  dec-arg                             PIC 9(18).\n\n01  oct                                 PIC 9(18).\n\nPROCEDURE DIVISION USING dec-arg RETURNING oct.\n    MOVE dec-arg TO dec *> Copy is made to avoid modifying reference arg.\n    PERFORM WITH TEST AFTER UNTIL dec = 0\n        MOVE FUNCTION REM(dec, 8) TO rem\n        STRING rem, oct DELIMITED BY SPACES INTO oct\n        DIVIDE 8 INTO dec\n    END-PERFORM\n    .\nEND FUNCTION dec-to-oct.\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":1126}
    {"lang_cluster":"COBOL","source_code":"\n       PROGRAM-ID. SWAP-DEMO.\n       AUTHOR.  Bill Gunshannon.\n       INSTALLATION.  Home.\n       DATE-WRITTEN.  16 December 2021.\n      ************************************************************\n      ** Program Abstract:\n      **   A simple program to demonstrate the SWAP subprogram.\n      **     \n      ************************************************************\n       \n       DATA DIVISION.\n       \n       WORKING-STORAGE SECTION.\n       \n       01  Val1                 PIC X(72).\n       01  Val2                 PIC X(72).\n       \n       PROCEDURE DIVISION.\n       \n       Main-Program.\n\n          DISPLAY 'Enter a Value: ' WITH NO ADVANCING.\n          ACCEPT Val1.\n          DISPLAY 'Enter another Value: ' WITH NO ADVANCING.\n          ACCEPT Val2.\n          DISPLAY ' ' .\n          DISPLAY 'First value: ' FUNCTION TRIM(Val1) .\n          DISPLAY 'Second value: ' FUNCTION TRIM(Val2) .\n\n           CALL \"SWAP\" USING BY REFERENCE Val1,  BY REFERENCE Val2.\n\n          DISPLAY ' '.\n          DISPLAY 'After SWAP '.\n          DISPLAY ' '.\n          DISPLAY 'First value: ' FUNCTION TRIM(Val1).\n          DISPLAY 'Second value: ' FUNCTION TRIM(Val2).\n\n           STOP RUN.\n       \n       END PROGRAM SWAP-DEMO.\n       \n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. SWAP.\n       AUTHOR.  Bill Gunshannon.\n       INSTALLATION.  Home.\n       DATE-WRITTEN.  16 December 2021.\n      ************************************************************\n      ** Program Abstract:\n      **   SWAP any Alphanumeric value.  Only limit is 72\n      **     character size.  But that can be adjusted for\n      **     whatever use one needs.\n      ************************************************************\n\n       DATA DIVISION.\n\n       WORKING-STORAGE SECTION.\n\n       01  TEMP                  PIC X(72).\n\n       LINKAGE SECTION.\n\n       01  Field1                PIC X(72).\n       01  Field2                PIC X(72).\n\n       PROCEDURE DIVISION \n               USING BY REFERENCE Field1, BY REFERENCE Field2.\n\n       MOVE Field1 to TEMP.\n       MOVE Field2 to Field1.\n       MOVE TEMP to Field2.\n\n       GOBACK.\n\n       END PROGRAM SWAP.\n\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.","id":1127}
    {"lang_cluster":"COBOL","source_code":"\nWorks with: GnuCOBOL\n       identification division.\n       function-id. palindromic-test.\n\n       data division.\n       linkage section.\n       01 test-text            pic x any length.\n       01 result               pic x.\n          88 palindromic       value high-value\n                               when set to false low-value.\n\n       procedure division using test-text returning result.\n\n       set palindromic to false\n       if test-text equal function reverse(test-text) then\n           set palindromic to true\n       end-if\n\n       goback.\n       end function palindromic-test.\n\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":1128}
    {"lang_cluster":"COBOL","source_code":"\n       IDENTIFICATION DIVISION.\n       PROGRAM-ID. Environment-Vars.\n\n       DATA DIVISION.\n       WORKING-STORAGE SECTION.\n       01  home PIC X(75).\n\n       PROCEDURE DIVISION.\n*          *> Method 1.      \n           ACCEPT home FROM ENVIRONMENT \"HOME\"\n           DISPLAY home\n\n*          *> Method 2.\n           DISPLAY \"HOME\" UPON ENVIRONMENT-NAME\n           ACCEPT home FROM ENVIRONMENT-VALUE\n\n           GOBACK\n           .\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":1129}
    {"lang_cluster":"VBScript","source_code":"\nclass stack\n\tdim tos\n\tdim stack()\n\tdim stacksize\n\t\n\tprivate sub class_initialize\n\t\tstacksize = 100\n\t\tredim stack( stacksize )\n\t\ttos = 0\n\tend sub\n\n\tpublic sub push( x )\n\t\tstack(tos) = x\n\t\ttos = tos + 1\n\tend sub\n\t\n\tpublic property get stackempty\n\t\tstackempty = ( tos = 0 )\n\tend property\n\t\n\tpublic property get stackfull\n\t\tstackfull = ( tos > stacksize )\n\tend property\n\t\n\tpublic property get stackroom\n\t\tstackroom = stacksize - tos\n\tend property\n\t\n\tpublic function pop()\n\t\tpop = stack( tos - 1 )\n\t\ttos = tos - 1\n\tend function\n\n\tpublic sub resizestack( n )\n\t\tredim preserve stack( n )\n\t\tstacksize = n\n\t\tif tos > stacksize then\n\t\t\ttos = stacksize\n\t\tend if\n\tend sub\nend class\n\ndim s\nset s = new stack\ns.resizestack 10\nwscript.echo s.stackempty\ndim i\nfor i = 1 to 10\n\ts.push rnd\n\twscript.echo s.stackroom\n\tif s.stackroom = 0 then exit for\nnext\nfor i = 1 to 10\n\twscript.echo s.pop\n\tif s.stackempty then exit for\nnext\n\n","human_summarization":"implement a stack data structure with basic operations such as push (to add elements), pop (to remove and return the last added element), and empty (to check if the stack is empty). This stack follows a Last-In-First-Out (LIFO) access policy.","id":1130}
    {"lang_cluster":"VBScript","source_code":"\ntest_arr_1 = Array(1,2,3,4,5,6,7,8,9,10)\ntest_arr_2 = Array(1,2,3,4,5,6,7,8,9,10)\n\nWScript.StdOut.Write \"Scenario 1: Create a new array\"\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Input: \" & Join(test_arr_1,\",\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":1131}
    {"lang_cluster":"VBScript","source_code":"\nWorks with: Windows Script Host version *\nWScript.Echo StrReverse(\"asdf\")\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":1132}
    {"lang_cluster":"VBScript","source_code":"\n\nDim a, b, i\n\nDo\n    a = Int(Rnd * 20)\n    WScript.StdOut.Write a \n    If a = 10 Then Exit Do\n    b = Int(Rnd * 20)\n    WScript.Echo vbNullString, b\nLoop\n\nFor i = 1 To 100000\n    a = Int(Rnd * 20)\n    WScript.StdOut.Write a \n    If a = 10 Then Exit For\n    b = Int(Rnd * 20)\n    WScript.Echo vbNullString, b\nNext\n","human_summarization":"The code generates and prints random numbers from 0 to 19. If the generated number is 10, the loop stops. If not, a second random number is generated and printed before the loop restarts. The loop continues indefinitely if 10 is never generated as the first number. Demonstrates breaking out of loops in BASIC.","id":1133}
    {"lang_cluster":"VBScript","source_code":"' Factors of a Mersenne number\n    for i=1 to 59\n        z=i\n        if z=59 then z=929  ':) 61 turns into 929.\n        if isPrime(z) then \n            r=testM(z)\n            zz=left(\"M\" & z & space(4),4)\n            if r=0 then \n                Wscript.echo zz & \" prime.\"\n            else \n                Wscript.echo zz & \" not prime, a factor: \" & r\n            end if\n        end if\n    next\n\nfunction modPow(base,n,div)\n    dim i,y,z\n    i = n : y = 1 : z = base\n    do while i\n        if i and 1 then y = (y * z) mod div\n        z = (z * z) mod div\n        i = i \\ 2\n    loop\n    modPow= y\nend function\n\nfunction isPrime(x)\n    dim i\n    if x=2 or x=3 or _\n       x=5 or x=7 _\n                  then isPrime=1: exit function\n    if x<11       then isPrime=0: exit function\n    if x mod 2=0  then isPrime=0: exit function\n    if x mod 3=0  then isPrime=0: exit function\n    i=5\n    do\n        if (x mod i)     =0 or _\n           (x mod (i+2)) =0 _\n                  then isPrime=0: exit function\n        if i*i>x  then isPrime=1: exit function\n        i=i+6\n    loop\nend function\n\nfunction testM(x)\n    dim sqroot,k,q\n    sqroot=Sqr(2^x)\n    k=1\n    do\n        q=2*k*x+1\n        if q>sqroot then exit do\n        if (q and 7)=1 or (q and 7)=7 then\n            if isPrime(q) then\n                if modPow(2,x,q)=1 then \n                    testM=q\n                    exit function\n                end if\n            end if\n        end if\n        k=k+1\n    loop\n    testM=0 \nend function\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":1134}
    {"lang_cluster":"VBScript","source_code":"\nSet objXMLDoc = CreateObject(\"msxml2.domdocument\")\n\nobjXMLDoc.load(\"In.xml\")\n\nSet item_nodes = objXMLDoc.selectNodes(\"\/\/item\")\ni = 1\nFor Each item In item_nodes\n\tIf i = 1 Then\n\t\tWScript.StdOut.Write item.xml\n\t\tWScript.StdOut.WriteBlankLines(2)\n\t\tExit For\n\tEnd If\nNext\n\nSet price_nodes = objXMLDoc.selectNodes(\"\/\/price\")\nlist_price = \"\"\nFor Each price In price_nodes\n\tlist_price = list_price & price.text & \", \"\nNext\nWScript.StdOut.Write list_price\nWScript.StdOut.WriteBlankLines(2)\n\nSet name_nodes = objXMLDoc.selectNodes(\"\/\/name\")\nlist_name = \"\"\nFor Each name In name_nodes\n\tlist_name = list_name & name.text & \", \"\nNext\nWScript.StdOut.Write list_name\nWScript.StdOut.WriteBlankLines(2)\n\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":1135}
    {"lang_cluster":"VBScript","source_code":"Function quicksort(arr,s,n)\n\tIf n < 2 Then\n\t\tExit Function\n\tEnd If\n\tt = s + n - 1\n\tl = s\n\tr = t\n\tp = arr(Int((l + r)\/2))\n\tDo Until l > r\n\t\tDo While arr(l) < p\n\t\t\tl = l + 1\n\t\tLoop\n\t\tDo While arr(r) > p\n\t\t\tr = r -1\n\t\tLoop\n\t\tIf l <= r Then\n\t\t\ttmp = arr(l)\n\t\t\tarr(l) = arr(r)\n\t\t\tarr(r) = tmp\n\t\t\tl = l + 1\n\t\t\tr = r - 1\n\t\tEnd If\n\tLoop\n\tIf s < r Then\n\t\tCall quicksort(arr,s,r-s+1)\n\tEnd If\n\tIf l < t Then\n\t\tCall quicksort(arr,l,t-l+1)\n\tEnd If\n\tquicksort = arr\nEnd Function\n\nmyarray=Array(9,8,7,6,5,5,4,3,2,1,0,-1)\nm = quicksort(myarray,0,12)\nWScript.Echo Join(m,\",\")\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":1136}
    {"lang_cluster":"VBScript","source_code":"\n'YYYY-MM-DD format\nWScript.StdOut.WriteLine Year(Date) & \"-\" & Right(\"0\" & Month(Date),2) & \"-\" & Right(\"0\" & Day(Date),2)\n\n'Weekday_Name, Month_Name DD, YYYY format\nWScript.StdOut.WriteLine FormatDateTime(Now,1)\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":1137}
    {"lang_cluster":"VBScript","source_code":"\nFunction Dec2Bin(n)\n\tq = n\n\tDec2Bin = \"\"\n\tDo Until q = 0\n\t\tDec2Bin = CStr(q Mod 2) & Dec2Bin\n\t\tq = Int(q \/ 2)\n\tLoop\n\tDec2Bin = Right(\"00000\" & Dec2Bin,6)\nEnd Function\n\nFunction PowerSet(s)\n\tarrS = Split(s,\",\")\n\tPowerSet = \"{\"\n\tFor i = 0 To 2^(UBound(arrS)+1)-1\n\t\tIf i = 0 Then\n\t\t\tPowerSet = PowerSet & \"{},\"\n\t\tElse\n\t\t\tbinS = Dec2Bin(i)\n\t\t\tPowerSet = PowerSet & \"{\"\n\t\t\tc = 0\n\t\t\tFor j = Len(binS) To 1 Step -1\n\t\t\t\tIf CInt(Mid(binS,j,1)) = 1 Then\n\t\t\t\t\tPowerSet = PowerSet & arrS(c) & \",\"\t\n\t\t\t\tEnd If\n\t\t\t\tc = c + 1\n\t\t\tNext\n\t\t\tPowerSet = Mid(PowerSet,1,Len(PowerSet)-1) & \"},\"\n\t\tEnd If\n\tNext\n\tPowerSet = Mid(PowerSet,1,Len(PowerSet)-1) & \"}\"\nEnd Function\n\nWScript.StdOut.Write PowerSet(\"1,2,3,4\")\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":1138}
    {"lang_cluster":"VBScript","source_code":"\n'Arrays - VBScript - 08\/02\/2021\n\n    'create a static array\n    Dim a(3)   ' 4 items\u00a0: a(0), a(1), a(2), a(3)\n    'assign a value to elements\n    For i = 1 To 3\n        a(i) = i * i\n    Next\n    'and retrieve elements\n\tbuf=\"\"\n    For i = 1 To 3\n        buf = buf & a(i) & \" \"\n    Next\n    WScript.Echo buf\n\t\n    'create a dynamic array \n    Dim d()\n    ReDim d(3)   ' 4 items\u00a0: d(0), d(1), d(2), d(3)\n    For i = 1 To 3\n        d(i) = i * i\n    Next\n\tbuf=\"\"\n    For i = 1 To 3\n        buf = buf & d(i) & \" \"\n    Next\n\tWScript.Echo buf\n\t\n\td(0) = 0\n    'expand the array and preserve existing values\n    ReDim Preserve d(4)   ' 5 items\u00a0: d(0), d(1), d(2), d(3), d(4)\n    d(4) = 16\n\tbuf=\"\"\n    For i = LBound(d) To UBound(d)\n        buf = buf & d(i) & \" \"\n    Next\n\tWScript.Echo buf\n\n\t'create and initialize an array dynamicaly\n    b = Array(1, 4, 9)\n\t'and retrieve all elements\n\tWScript.Echo Join(b,\",\")\n\n\t'Multi-Dimensional arrays\n\t'The following creates a 5x4 matrix \n\tDim mat(4,3)\n\n","human_summarization":"demonstrate the basic syntax of arrays in the specific language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and the process of pushing a value into the array.","id":1139}
    {"lang_cluster":"VBScript","source_code":"\nDim MyWord\nMyWord = UCase(\"alphaBETA\")   ' Returns \"ALPHABETA\"\nMyWord = LCase(\"alphaBETA\")   ' Returns \"alphabeta\"\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":1140}
    {"lang_cluster":"VBScript","source_code":"\nclass topological\n\tdim dictDependencies\n\tdim dictReported\n\tdim depth\n\t\n\tsub class_initialize\n\t\tset dictDependencies = createobject(\"Scripting.Dictionary\")\n\t\tset dictReported = createobject(\"Scripting.Dictionary\")\n\t\tdepth = 0\n\tend sub\n\t\n\tsub reset\n\t\tdictReported.removeall\n\tend sub\n\t\n\tproperty let dependencies( s )\n\t\t'assuming token tab token-list newline\n\t\tdim i, j ,k\n\t\tdim aList\n\t\tdim dep\n\t\tdim a1\n\t\taList = Split( s, vbNewLine )\n\t\t'~ remove empty lines at end\n\t\tdo while aList( UBound( aList ) ) = vbnullstring\n\t\t\tredim preserve aList( UBound( aList ) - 1 )\n\t\tloop\n\n\t\tfor i = lbound( aList ) to ubound( aList )\n\t\t\taList( i ) = Split( aList( i ), vbTab, 2 )\n\t\t\ta1 = Split( aList( i )( 1 ), \" \" )\n\t\t\tk = 0\n\t\t\tfor j = lbound( a1) to ubound(a1)\n\t\t\t\tif a1(j) <> aList(i)(0) then\n\t\t\t\t\ta1(k) = a1(j)\n\t\t\t\t\tk = k + 1\n\t\t\t\tend if\n\t\t\tnext\n\t\t\tredim preserve a1(k-1)\n\t\t\taList(i)(1) = a1\n\t\tnext\n\t\tfor i = lbound( aList ) to ubound( aList )\n\t\t\tdep = aList(i)(0)\n\t\t\tif not dictDependencies.Exists( dep ) then\n\t\t\t\tdictDependencies.add dep, aList(i)(1)\n\t\t\tend if\n\t\tnext\n\t\t\n\tend property\n\t\n\tsub resolve( s )\n\t\tdim i \n\t\tdim deps\n\t\t'~ wscript.echo string(depth,\"!\"),s\n\t\tdepth = depth + 1\n\t\tif dictDependencies.Exists(s) then\n\t\t\tdeps = dictDependencies(s)\n\t\t\tfor i = lbound(deps) to ubound(deps)\n\t\t\t\tresolve deps(i)\n\t\t\tnext\n\t\tend if\n\t\tif not seen(s) then\n\t\t\twscript.echo s\n\t\t\tsee s\n\t\tend if\n\t\tdepth = depth - 1\n\tend sub\n\n\tfunction seen( key )\n\t\tseen = dictReported.Exists( key )\n\tend function\n\t\n\tsub see( key )\n\t\tdictReported.add key, \"\"\n\tend sub\n\t\n\tproperty get keys\n\t\tkeys = dictDependencies.keys\n\tend property\nend class\n\ndim toposort\nset toposort = new topological\ntoposort.dependencies = \"des_system_lib\tstd synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\" & vbNewLine & _\n\t\"dw01\tieee dw01 dware gtech\" & vbNewLine & _\n\t\"dw02\tieee dw02 dware\" & vbNewLine & _\n\t\"dw03\tstd synopsys dware dw03 dw02 dw01 ieee gtech\" & vbNewLine & _\n\t\"dw04\tdw04 ieee dw01 dware gtech\" & vbNewLine & _\n\t\"dw05\tdw05 ieee dware\" & vbNewLine & _\n\t\"dw06\tdw06 ieee dware\" & vbNewLine & _\n\t\"dw07\tieee dware\" & vbNewLine & _\n\t\"dware\tieee dware\" & vbNewLine & _\n\t\"gtech\tieee gtech\" & vbNewLine & _\n\t\"ramlib\tstd ieee\" & vbNewLine & _\n\t\"std_cell_lib\tieee std_cell_lib\" & vbNewLine & _\n\t\"synopsys\t\"\n\ndim k\nfor each k in toposort.keys\n\twscript.echo \"----- \" & k\n\ttoposort.resolve k\n\twscript.echo \"-----\"\n\ttoposort.reset\nnext\n\n----- des_system_lib\nstd\nsynopsys\nieee\nstd_cell_lib\ndware\ndw02\ngtech\ndw01\nramlib\ndes_system_lib\n-----\n----- dw01\nieee\ndware\ngtech\ndw01\n-----\n----- dw02\nieee\ndware\ndw02\n-----\n----- dw03\nstd\nsynopsys\nieee\ndware\ndw02\ngtech\ndw01\ndw03\n-----\n----- dw04\nieee\ndware\ngtech\ndw01\ndw04\n-----\n----- dw05\nieee\ndware\ndw05\n-----\n----- dw06\nieee\ndware\ndw06\n-----\n----- dw07\nieee\ndware\ndw07\n-----\n----- dware\nieee\ndware\n-----\n----- gtech\nieee\ngtech\n-----\n----- ramlib\nstd\nieee\nramlib\n-----\n----- std_cell_lib\nieee\nstd_cell_lib\n-----\n----- synopsys\nsynopsys\n-----\n\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":1141}
    {"lang_cluster":"VBScript","source_code":"\nFunction StartsWith(s1,s2)\n\tStartsWith = False\n\tIf Left(s1,Len(s2)) = s2 Then\n\t\tStartsWith = True\n\tEnd If\nEnd Function\n\nFunction Contains(s1,s2)\n\tContains = False\n\tIf InStr(1,s1,s2) Then\n\t\tContains = True & \" at positions \"\n\t\tj = 1\n\t\tDo Until InStr(j,s1,s2) = False\n\t\t\tContains = Contains & InStr(j,s1,s2) & \", \"\n\t\t\tIf j = 1 Then\n\t\t\t\tIf Len(s2) = 1 Then\n\t\t\t\t\tj = j + InStr(j,s1,s2)\n\t\t\t\tElse\n\t\t\t\t\tj = j + (InStr(j,s1,s2) + (Len(s2) - 1))\n\t\t\t\tEnd If\n\t\t\tElse\n\t\t\t\tIf Len(s2) = 1 Then\n\t\t\t\t\tj = j + ((InStr(j,s1,s2) - j) + 1)\n\t\t\t\tElse\n\t\t\t\t\tj = j + ((InStr(j,s1,s2) - j) + (Len(s2) - 1))\n\t\t\t\tEnd If\n\t\t\tEnd If\n\t\tLoop\n\tEnd If\nEnd Function\n\nFunction EndsWith(s1,s2)\n\tEndsWith = False\n\tIf Right(s1,Len(s2)) = s2 Then\n\t\tEndsWith = True\n\tEnd If\nEnd Function\n\nWScript.StdOut.Write \"Starts with test, 'foo' in 'foobar': \" & StartsWith(\"foobar\",\"foo\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Contains test, 'o' in 'fooooobar': \" & Contains(\"fooooobar\",\"o\")\nWScript.StdOut.WriteLine\nWScript.StdOut.Write \"Ends with test, 'bar' in 'foobar': \" & EndsWith(\"foobar\",\"bar\")\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":1142}
    {"lang_cluster":"VBScript","source_code":"\n\n'ANSI Clock\n\n'ansi escape functions\nans0=chr(27)&\"[\"\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub torc(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\n'bresenham\nSub draw_line(r1,c1, r2,c2,c)\n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub \n\nconst pi180=0.017453292519943\n'center of the clock\nconst r0=13\nconst c0=26\n\n'angles\nnangi=-30*pi180\naangi=-6*pi180\nang0=90*pi180\n\n'lengths of hands\nlh=7\nlm=9\nls=9\nln=12\n\n\nwhile 1\n     cls\n\n    'dial\n    angn=ang0+nangi\n    for i=1 to 12\n      torc r0-cint(ln*sin(angn)),cint(c0+2*ln*cos(angn)),i\n      angn=angn+nangi \n    next \n\n    'get time and display it in numbers\n    t=now()\n    torc 1,1, hour(t) &\":\"& minute(t) &\":\"& second(t) \n    \n    'angle for each hand\n    angh=ang0+hour(t) *nangi\n    angm=ang0+minute(t) *aangi\n    angS=ang0+second(t) *aangi\n\n    'draw them\n    draw_line r0,c0,cint(r0-ls*sin(angs)),cint(c0+2*ls*cos(angs)),\".\"\n    draw_line r0,c0,cint(r0-lm*sin(angm)),cint(c0+2*lm*cos(angm)),\"*\"\n    draw_line r0,c0,cint(r0-lh*sin(angh)),cint(c0+2*lh*cos(angh)),\"W\"\n    torc r0,c0,\"O\"\n    \n    'wait one second     \n    wscript.sleep(1000)\nwend\n\n\n","human_summarization":"The code is designed to create a simple, animated clock or timekeeping device. It displays the passage of seconds, with changes occurring every second and cycling periodically. The clock syncs with the system clock for accuracy but does not consume excessive CPU resources. The code is clear, concise, and avoids unnecessary complexity. It uses system or language-specific timers, signals, or events rather than constant polling. The animation is achieved using ANSI codes in VBScript and is compatible with Windows 10 and above.","id":1143}
    {"lang_cluster":"VBScript","source_code":"For i=1 To 8\n\tWScript.StdOut.WriteLine triples(10^i)\nNext\n\nFunction triples(pmax)\n\tprim=0 : count=0 : nmax=Sqr(pmax)\/2 : n=1\n\tDo While n <= nmax\n\t\tm=n+1 : p=2*m*(m+n)\n\t\tDo While p <= pmax\n\t\t\tIf gcd(m,n)=1 Then\n\t\t\t\tprim=prim+1\n\t\t\t\tcount=count+Int(pmax\/p)\n\t\t\tEnd If\n\t\t\tm=m+2\n\t\t\tp=2*m*(m+n)\n\t\tLoop\n\t\tn=n+1\n\tLoop \n\ttriples = \"Max Perimeter: \" & pmax &_\n\t\t\t\t\", Total: \" & count &_\n\t\t\t\t\", Primitive: \" & prim\nEnd Function\n\nFunction gcd(a,b)\n\tc = a : d = b\n\tDo\n\t\tIf c Mod d > 0 Then\n\t\t\te = c Mod d\n\t\t\tc = d\n\t\t\td = e\n\t\tElse\n\t\t\tgcd = d\n\t\t\tExit Do\n\t\tEnd If\n\tLoop\nEnd Function\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":1144}
    {"lang_cluster":"VBScript","source_code":"\nfilepath = \"SPECIFY FILE PATH HERE\"\n\nSet objfso = CreateObject(\"Scripting.FileSystemObject\")\nSet objdict = CreateObject(\"Scripting.Dictionary\")\nSet objfile = objfso.OpenTextFile(filepath,1)\n\ntxt = objfile.ReadAll\n\nFor i = 1 To Len(txt)\n\tchar = Mid(txt,i,1)\n\tIf objdict.Exists(char) Then\n\t\tobjdict.Item(char) = objdict.Item(char) + 1\n\tElse\n\t\tobjdict.Add char,1\n\tEnd If\nNext\n\nFor Each key In objdict.Keys\n\tWScript.StdOut.WriteLine key & \" = \" & objdict.Item(key)\nNext\t\n\nobjfile.Close\nSet objfso = Nothing\nSet objdict = Nothing\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":1145}
    {"lang_cluster":"VBScript","source_code":"' Align columns - RC - VBScript\n\tConst nr=16, nc=16\n\tReDim d(nc),t(nr), wor(nr,nc)\n\ti=i+1: t(i) = \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\"\n\ti=i+1: t(i) = \"are$delineated$by$a$single$'dollar'$character,$write$a$program\"\n\ti=i+1: t(i) = \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\"\n\ti=i+1: t(i) = \"column$are$separated$by$at$least$one$space.\"\n\ti=i+1: t(i) = \"Further,$allow$for$each$word$in$a$column$To$be$either$left$\"\n\ti=i+1: t(i) = \"justified,$right$justified,$or$center$justified$within$its$column.\"\n\tFor r=1 to nr\n\t\tIf t(r)=\"\" Then Exit For\n\t\tw=xRTrim(t(r),\"$\")\n\t\tm=Split(w,\"$\")\n\t\tFor c=1 To UBound(m)+1\n\t\t\twor(r,c)=m(c-1)\n\t\t\tIf Len(wor(r,c))>d(c) Then d(c)=Len(wor(r,c))\n\t\tNext 'c\n\t\tIf c>cols Then cols=c\n\tNext 'r\n\trows=r-1\n\ttt=Array(\"Left\",\"Right\",\"Center\")\n\tFor n=1 To 3\n\t\tWscript.Echo \n\t\tWscript.Echo \"*****\" & tt(n-1) & \"*****\" \n\t\tFor r=1 To rows\n\t\t\tw=\"\"\n\t\t\tFor c=1 To cols\n\t\t\t\tx=wor(r,c): s=Space(d(c))\n\t\t\t\tSelect Case n\n\t\t\t\t\tCase 1: w=w &\" \"& Left   (x & s,d(c)) \n\t\t\t\t\tCase 2: w=w &\" \"& Right  (s & x,d(c))\n\t\t\t\t\tCase 3: w=w &\" \"& xCentre(x,d(c),\" \")\n\t\t\t\tEnd Select 'n\n\t\t\tNext 'c\n\t\t\tWscript.Echo Mid(w,2)\n\t\tNext 'r\n\tNext 'n\n\t\nFunction xCentre(c, n, Pad) \n    Dim j\n    If n > Len(c) Then\n\t\tj = (n - Len(c)) \\  2\n\t\tIf (n - Len(c)) Mod 2 <> 0 Then j = j + 1\n\t\txCentre = Mid(String(j, Pad) & c & String(j, Pad), 1, n)\n    Else\n\t\txCentre = c\n    End If\nEnd Function 'xCentre\n\nFunction xRTrim(c, Pad) \n\tDim i2, l, cc \n\tcc = \"\": l = Len(c)\n\tIf l > 0 Then\n\t\ti2 = l\n\t\tDo While (Mid(c, i2, 1) = Pad And i2 > 1)\n\t\t\ti2 = i2 - 1\n\t\tLoop\n\t\tIf i2 = 1 And Mid(c, i2, 1) = Pad Then i2 = 0\n\t\tIf i2 > 0 Then cc = Mid(c, 1, i2)\n\tEnd If\n\txRTrim = cc\nEnd Function 'xRTrim\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":1146}
    {"lang_cluster":"VBScript","source_code":"x = 6 : y = 2 : z = 3\n\nSub cuboid(nx, ny, nz)\n   WScript.StdOut.WriteLine \"Cuboid \" & nx & \" \" & ny & \" \" & nz & \":\"\n   lx = X * nx : ly = y * ny : lz = z * nz\n\n   'define the array\n   Dim area(): ReDim area(ly+lz, lx+ly)\n   For i = 0 to ly+lz\n      For j = 0 to lx+ly : area(i,j) = \" \" : Next\n   Next\n\n   'drawing lines\n   For i = 0 to nz-1 : drawLine area, lx,      0,    Z*i, \"-\" : Next\n   For i = 0 to ny   : drawLine area, lx,    y*i, lz+y*i, \"-\" : Next\n   For i = 0 to nx-1 : drawLine area, lz,    x*i,      0, \"|\" : Next\n   For i = 0 to ny   : drawLine area, lz, lx+y*i,    y*i, \"|\" : Next\n   For i = 0 to nz-1 : drawLine area, ly,     lx,    z*i, \"\/\" : Next\n   For i = 0 to nx   : drawLine area, ly,    x*i,     lz, \"\/\" : Next\n\n   'output the cuboid (in reverse)\n   For i = UBound(area,1) to 0 Step -1\n      linOut = \"\"\n      For j = 0 to UBound(area,2) : linOut = linOut & area(i,j) : Next\n      WScript.StdOut.WriteLine linOut\n   Next\nEnd Sub\n\nSub drawLine(arr, n, sx, sy, c)\n   Select Case c\n      Case \"-\"\n         dx = 1 : dy = 0\n      Case \"|\"\n         dx = 0 : dy = 1\n      Case \"\/\"\n         dx = 1 : dy = 1\n   End Select\n   For i = 0 to n\n      xi = sx + (i * dx) : yi = sy + (i * dy)\n      If arr(yi, xi) = \" \" Then\n         arr(yi, xi) = c\n      Else\n         arr(yi, xi) = \"+\"\n      End If\n   Next\nEnd Sub\n\ncuboid 2,3,4\n\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":1147}
    {"lang_cluster":"VBScript","source_code":"\n\nSet objConn = CreateObject(\"ADODB.Connection\")\nSet objCmd = CreateObject(\"ADODB.Command\")\nobjConn.Provider = \"ADsDSOObject\"\nobjConn.Open\n\n","human_summarization":"Establish a connection to either an Active Directory or Lightweight Directory Access Protocol server.","id":1148}
    {"lang_cluster":"VBScript","source_code":"\noption explicit \n\nfunction rot13(a)\n  dim b,n1,n,i\n  b=\"\"\n  for i=1 to len(a)\n    n=asc(mid(a,i,1))\n    if n>=65 and n<= 91 then\n       n1=(((n-65)+13)mod 26)+65\n    elseif n>=97 and n<= 123 then\n       n1=(((n-97)+13)mod 26)+97\n    else\n        n1=n\n    end if\n    b=b & chr(n1)\n  next  \n  rot13=b\nend function\n\nconst a=\"The quick brown fox jumps over the lazy dog.\"\ndim b,c\nwscript.echo a \nb=rot13(a)\nwscript.echo b    \nc=rot13(b)\nwscript.echo c\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":1149}
    {"lang_cluster":"VBScript","source_code":"\nOption Explicit\nDim i, j, s\nFor i = 1 To 5\n    s = \"\"\n    For j = 1 To i\n        s = s + \"*\"\n    Next\n    WScript.Echo s\nNext\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":1150}
    {"lang_cluster":"VBScript","source_code":"\n\nImplementationoption explicit\n\nclass List\n\tprivate theList\n\tprivate nOccupiable\n\tprivate nTop\n\t\n\tsub class_initialize\n\t\tnTop = 0\n\t\tnOccupiable = 100\n\t\tredim theList( nOccupiable )\n\tend sub\n\t\n\tpublic sub store( x )\n\t\tif nTop >= nOccupiable then\n\t\t\tnOccupiable = nOccupiable + 100\n\t\t\tredim preserve theList( nOccupiable )\n\t\tend if\n\t\ttheList( nTop ) = x\n\t\tnTop = nTop + 1\n\tend sub\n\t\n\tpublic function recall( n )\n\t\tif n >= 0 and n <= nOccupiable then\n\t\t\trecall = theList( n )\n\t\telse\n\t\t\terr.raise vbObjectError + 1000,,\"Recall bounds error\"\n\t\tend if\n\tend function\n\t\n\tpublic sub replace( n, x )\n\t\tif n >= 0 and n <= nOccupiable then\n\t\t\ttheList( n )  = x\n\t\telse\n\t\t\terr.raise vbObjectError + 1001,,\"Replace bounds error\"\n\t\tend if\n\tend sub\n\t\n\tpublic property get listCount\n\t\tlistCount = nTop\n\tend property\n\t\t\nend class\n\nfunction halve( n )\n\thalve = int( n \/ 2 )\nend function\n\nfunction twice( n )\n\ttwice = int( n * 2 )\nend function\n\nfunction iseven( n )\n\tiseven = ( ( n mod 2 ) = 0 )\nend function\n\n\nfunction multiply( n1, n2 )\n\tdim LL\n\tset LL = new List\n\n\tdim RR\n\tset RR = new List\n\n\tLL.store n1\n\tRR.store n2\n\t\n\tdo while n1 <> 1\n\t\tn1 = halve( n1 )\n\t\tLL.store n1\n\t\tn2 = twice( n2 )\n\t\tRR.store n2\n\tloop\n\t\n\tdim i\n\tfor i = 0 to LL.listCount\n\t\tif iseven( LL.recall( i ) ) then\n\t\t\tRR.replace i, 0\n\t\tend if\n\tnext\n\n\tdim total\n\ttotal = 0\n\tfor i = 0 to RR.listCount\n\t\ttotal = total + RR.recall( i )\n\tnext\n\t\n\tmultiply = total\nend functionInvocationwscript.echo multiply(17,34)\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement the Ethiopian multiplication method, which multiplies two integers using only addition, doubling, and halving operations. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":1151}
    {"lang_cluster":"VBScript","source_code":"\n\nrandomize timer\nfail=array(\"Wrong number of chars\",\"Only figures 0 to 9 allowed\",\"Two or more figures are the same\") \np=dopuzzle()\nwscript.echo \"Bulls and Cows. Guess my 4 figure number!\"\ndo\n do\n  wscript.stdout.write vbcrlf & \"your move \": s=trim(wscript.stdin.readline)\n  c=checkinput(s)\n  if not isarray (c) then wscript.stdout.write fail(c) :exit do\n  bu=c(0)\n  wscript.stdout.write \"bulls: \" & c(0) & \" | cows: \" & c(1)\n loop while 0\nloop until bu=4  \nwscript.stdout.write vbcrlf & \"You won! \"\n\n\nfunction dopuzzle()\n  dim b(10)\n  for i=1 to 4\n    do\n      r=fix(rnd*10)\n    loop until b(r)=0\n    b(r)=1:dopuzzle=dopuzzle+chr(r+48)\n  next  \nend function\n\nfunction checkinput(s)\n  dim c(10)\n  bu=0:co=0\n  if len(s)<>4 then checkinput=0:exit function\n  for i=1 to 4\n    b=mid(s,i,1)\n    if instr(\"0123456789\",b)=0 then checkinput=1 :exit function\n\t\tif c(asc(b)-48)<>0 then checkinput=2 :exit function\n    c(asc(b)-48)=1\n    for j=1 to 4\n      if asc(b)=asc(mid(p,j,1)) then\n        if i=j then bu=bu+1 else co=co+1\n      end if\n    next\n  next\n  checkinput=array(bu,co)\nend function\n\n","human_summarization":"The code generates a random four-digit number from 1 to 9 without duplication. It prompts the user for guesses, rejects malformed guesses, and calculates a score based on the guess. The score is determined by the number of bulls and cows, where a bull is a correct digit in the correct place and a cow is a correct digit in the wrong place. The game ends when the user's guess matches the randomly generated number.","id":1152}
    {"lang_cluster":"VBScript","source_code":"\nWScript.Echo DotProduct(\"1,3,-5\",\"4,-2,-1\")\n\nFunction DotProduct(vector1,vector2)\n\tarrv1 = Split(vector1,\",\")\n\tarrv2 = Split(vector2,\",\")\n\tIf UBound(arrv1) <> UBound(arrv2) Then\n\t\tWScript.Echo \"The vectors are not of the same length.\"\n\t\tExit Function\n\tEnd If\n\tDotProduct = 0\n\tFor i = 0 To UBound(arrv1)\n\t\tDotProduct = DotProduct + (arrv1(i) * arrv2(i))\n\tNext\nEnd Function\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":1153}
    {"lang_cluster":"VBScript","source_code":"\nfilepath = \"SPECIFY PATH TO TEXT FILE HERE\"\n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objInFile = objFSO.OpenTextFile(filepath,1,False,0)\n\nDo Until objInFile.AtEndOfStream\n\tline = objInFile.ReadLine\n\tWScript.StdOut.WriteLine line\nLoop\n\nobjInFile.Close\nSet objFSO = Nothing\n","human_summarization":"\"Continuously read words or lines from a text stream until there is no more data available.\"","id":1154}
    {"lang_cluster":"VBScript","source_code":"\nWScript.Echo Now\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":1155}
    {"lang_cluster":"VBScript","source_code":"\n\narr = Array(\"710889\",_\n            \"B0YBKJ\",_\n\t    \"406566\",_\n\t    \"B0YBLH\",_\n\t    \"228276\",_\n\t    \"B0YBKL\",_\n\t    \"557910\",_\n            \"B0YBKR\",_\n\t    \"585284\",_\n\t    \"B0YBKT\",_\n\t    \"12345\",_\n\t    \"A12345\",_\n\t    \"B00030\")\n\nFor j = 0 To UBound(arr)\n\tWScript.StdOut.Write arr(j) & getSEDOLCheckDigit(arr(j))\n\tWScript.StdOut.WriteLine\nNext \n\nFunction getSEDOLCheckDigit(str)\n\tIf Len(str) <> 6 Then\n\t\tgetSEDOLCheckDigit = \" is invalid. Only 6 character strings are allowed.\"\n\t\tExit Function\n\tEnd If\n\tSet mult = CreateObject(\"Scripting.Dictionary\")\n\tWith mult\n\t\t.Add \"1\",\"1\" : .Add \"2\", \"3\" : .Add \"3\", \"1\"\n\t\t.Add \"4\",\"7\" : .Add \"5\", \"3\" : .Add \"6\", \"9\"\n\tEnd With\n\ttotal = 0\n\tFor i = 1 To 6\n\t\ts  = Mid(str,i,1)\n\t\tIf s = \"A\" Or s = \"E\" Or s = \"I\" Or s = \"O\" Or s = \"U\" Then\n\t\t\tgetSEDOLCheckDigit = \" is invalid. Vowels are not allowed.\"\n\t\t\tExit Function\n\t\tEnd If\n\t\tIf Asc(s) >= 48 And Asc(s) <=57 Then\n\t\t\ttotal = total + CInt(s) * CInt(mult.Item(CStr(i)))\n\t\tElse\n\t\t\ttotal = total + (Asc(s) - 55) * CInt(mult.Item(CStr(i)))\n\t\tEnd If\n\tNext\n\tgetSEDOLCheckDigit = (10 - total Mod 10) Mod 10\nEnd Function\n\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end. It also validates each input to ensure it is correctly formed according to SEDOL string rules.","id":1156}
    {"lang_cluster":"VBScript","source_code":"shades = Array(\".\", \":\", \"!\", \"*\", \"o\", \"e\", \"&\", \"#\", \"%\", \"@\")\nlight = Array(30, 30, -50)\n\nSub Normalize(v)\n   length = Sqr(v(0)*v(0) + v(1)*v(1) + v(2)*v(2))\n   v(0) = v(0)\/length : v(1) = v(1)\/length : v(2) = v(2)\/length\nEnd Sub\n\nFunction Dot(x, y)\n   d = x(0)*y(0) + x(1)*y(1) + x(2)*y(2)\n   If d < 0 Then Dot = -d Else Dot = 0 End If\nEnd Function\n\n'floor function is the Int function\n'ceil function implementation\nFunction Ceil(x)\n    Ceil = Int(x)\n    If Ceil <> x Then Ceil = Ceil + 1 End if\nEnd Function\n\nSub DrawSphere(R, k, ambient)\n   Dim i, j, intensity, inten, b, x, y\n   Dim vec(3)\n   For i = Int(-R) to Ceil(R)\n      x = i + 0.5\n      line = \"\"\n      For j = Int(-2*R) to Ceil(2*R)\n         y = j \/ 2 + 0.5\n         If x * x + y * y <= R*R Then\n            vec(0) = x\n            vec(1) = y\n            vec(2) = Sqr(R * R - x * x - y * y)\n            Normalize vec\n            b = dot(light, vec)^k + ambient\n            intensity = Int((1 - b) * UBound(shades))\n            If intensity < 0 Then intensity = 0 End If\n            If intensity >= UBound(shades) Then\n               intensity = UBound(shades)\n            End If\n            line = line & shades(intensity)\n         Else\n            line = line & \" \"\n         End If\n      Next\n      WScript.StdOut.WriteLine line\n   Next\nEnd Sub\n\nNormalize light\nDrawSphere 20, 4, 0.1\nDrawSphere 10,2,0.4\n\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":1157}
    {"lang_cluster":"VBScript","source_code":"\nFunction stripchars(s1,s2)\n\tFor i = 1 To Len(s1)\n\t\tIf InStr(s2,Mid(s1,i,1)) Then\n\t\t\ts1 = Replace(s1,Mid(s1,i,1),\"\")\n\t\tEnd If\n\tNext\n\tstripchars = s1\nEnd Function\n\nWScript.StdOut.Write stripchars(\"She was a soul stripper. She took my heart!\",\"aei\")\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":1158}
    {"lang_cluster":"VBScript","source_code":"\n'The Function\nFunction FizzBuzz(range, mapping)\n    data = Array()\n\n    'Parse the mapping and put to \"data\" array\n    temp = Split(mapping, \",\")\n    ReDim data(UBound(temp),1)\n    For i = 0 To UBound(temp)\n        map = Split(temp(i), \" \")\n        data(i, 0) = map(0)\n        data(i, 1) = map(1)\n    Next    \n\n    'Do the loop\n    For i = 1 to range\n        noMatch = True\n        For j = 0 to UBound(data, 1)\n            If (i Mod data(j, 0)) = 0 Then\n                WScript.StdOut.Write data(j, 1)\n                noMatch = False\n            End If\n        Next\n        If noMatch Then WScript.StdOut.Write i\n        WScript.StdOut.Write vbCrLf\n    Next\nEnd Function\n\n'The Main Thing\nWScript.StdOut.Write \"Range? \"\nx = WScript.StdIn.ReadLine\nWScript.StdOut.Write \"Mapping? \"\ny = WScript.StdIn.ReadLine\nWScript.StdOut.WriteLine \"\"\nFizzBuzz x, y\n\n\nSample Run:\n\\Desktop>cscript \/nologo fizzbuzz.vbs\nRange? 20\nMapping? 3 Fizz,5 Buzz,7 Baxx\n\n1\n2\nFizz\n4\nBuzz\nFizz\nBaxx\n8\nFizz\nBuzz\n11\nFizz\n13\nBaxx\nFizzBuzz\n16\n17\nFizz\n19\nBuzz\n\n\\Desktop>\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":1159}
    {"lang_cluster":"VBScript","source_code":"\ns = \"bar\"\ns = \"foo\" & s\nWScript.Echo s\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":1160}
    {"lang_cluster":"VBScript","source_code":"\nrandomize\nMyNum=Int(rnd*10)+1\nDo\n\tx=x+1\n\tYourGuess=InputBox(\"Enter A number from 1 to 10\")\n\tIf not Isnumeric(YourGuess) then\n\t\tmsgbox YourGuess &\" is not numeric. Try again.\"\n\tElseIf CInt(YourGuess)>10 or CInt(YourGuess)<1 then\n\t\tmsgbox YourGuess &\" is not between 1 and 10. Try Again.\"\n\tElseIf CInt(YourGuess)=CInt(MyNum) then\n\t\tMsgBox \"Well Guessed!\"\n\t\twscript.quit\n\tElseIf Cint(YourGuess)<>CInt(Mynum) then\n\t\tMsgBox \"Nope. Try again.\"\n\tend If\n\n\tif x > 20 then\n\t\tmsgbox \"I take pity on you\"\n\t\twscript.quit\n\tend if\nloop\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":1161}
    {"lang_cluster":"VBScript","source_code":"\nFunction ASCII_Sequence(range)\n\tarr = Split(range,\"..\")\n\tFor i = Asc(arr(0)) To Asc(arr(1))\n\t\tASCII_Sequence = ASCII_Sequence & Chr(i) & \" \"\n\tNext\nEnd Function\n\nWScript.StdOut.Write ASCII_Sequence(WScript.Arguments(0))\nWScript.StdOut.WriteLine\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":1162}
    {"lang_cluster":"VBScript","source_code":"\n\nOption Explicit\nDim bin\nbin=Array(\"    \",\"   I\",\"  I \",\"  II\",\" I  \",\" I I\",\" II \",\" III\",\"I   \",\"I  I\",\"I I \",\"I II\",\" I  \",\"II I\",\"III \",\"IIII\") \n\nFunction num2bin(n)\n Dim s,i,n1,n2\n s=Hex(n)\n For i=1 To Len(s)\n   n1=Asc(Mid(s,i,1))\n   If n1>64 Then n2=n1-55 Else n2=n1-48\n   num2bin=num2bin & bin(n2)\n Next\n num2bin=Replace(Replace(LTrim(num2bin),\" \",\"0\"),\"I\",1)\n End Function\n \n Sub print(s): \n     On Error Resume Next\n     WScript.stdout.WriteLine (s)  \n     If  err= &h80070006& Then WScript.Echo \" Please run this script with CScript\": WScript.quit\n End Sub\n print num2bin(5)     \n print num2bin(50)   \n print num2bin(9000)\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer, without leading zeros or any other whitespace, radix, or sign markers. The output is displayed line by line. The function can use built-in radix functions or a user-defined function.","id":1163}
    {"lang_cluster":"VBScript","source_code":"\nSet ofso = CreateObject(\"Scripting.FileSystemObject\")\nSet config = ofso.OpenTextFile(ofso.GetParentFolderName(WScript.ScriptFullName)&\"\\config.txt\",1)\n\nconfig_out = \"\"\n\nDo Until config.AtEndOfStream\n\tline = config.ReadLine\n\tIf Left(line,1) <> \"#\" And Len(line) <> 0 Then\n\t\tconfig_out = config_out & parse_var(line) & vbCrLf\n\tEnd If\nLoop\n\nWScript.Echo config_out\n\nFunction parse_var(s)\n\t'boolean false\n\tIf InStr(s,\";\") Then\n\t\tparse_var = Mid(s,InStr(1,s,\";\")+2,Len(s)-InStr(1,s,\";\")+2) & \" = FALSE\"\n\t'boolean true\n\tElseIf UBound(Split(s,\" \")) = 0 Then\n\t\tparse_var = s & \" = TRUE\"\n\t'multiple parameters\n\tElseIf InStr(s,\",\") Then\n\t\tvar = Left(s,InStr(1,s,\" \")-1)\n\t\tparams = Split(Mid(s,InStr(1,s,\" \")+1,Len(s)-InStr(1,s,\" \")+1),\",\")\n\t\tn = 1 : tmp = \"\"\n\t\tFor i = 0 To UBound(params)\n\t\t\tparse_var = parse_var & var & \"(\" & n & \") = \" & LTrim(params(i)) & vbCrLf\n\t\t\tn = n + 1\n\t\tNext\n\t'single var and paramater\n\tElse\n\t\tparse_var = Left(s,InStr(1,s,\" \")-1) & \" = \" & Mid(s,InStr(1,s,\" \")+1,Len(s)-InStr(1,s,\" \")+1)\n\tEnd If\nEnd Function\n\nconfig.Close\nSet ofso = Nothing\n\n\n","human_summarization":"read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.","id":1164}
    {"lang_cluster":"VBScript","source_code":"\nLibrary: Microsoft.XmlHTTP\n\nOption Explicit\n\nConst sURL=\"http:\/\/rosettacode.org\/\"\n\nDim oHTTP\nSet oHTTP = CreateObject(\"Microsoft.XmlHTTP\")\n\nOn Error Resume Next\noHTTP.Open \"GET\", sURL, False\noHTTP.Send \"\"\nIf Err.Number = 0 Then\n     WScript.Echo oHTTP.responseText\nElse\n     Wscript.Echo \"error \" & Err.Number & \": \" & Err.Description\nEnd If\n\nSet oHTTP = Nothing\n","human_summarization":"Accesses and prints the content of a specified URL using HTTP protocol. The code is based on the Microsoft.XmlHttp object method for retrieving HTML web pages with VBScript. Note that handling HTTPS requests is not included in this code.","id":1165}
    {"lang_cluster":"VBScript","source_code":"\nFunction Luhn_Test(cc)\n\tcc = RevString(cc)\n\ts1 = 0\n\ts2 = 0\n\tFor i = 1 To Len(cc)\n\t\tIf i Mod 2 > 0 Then\n\t\t\ts1 = s1 + CInt(Mid(cc,i,1))\n\t\tElse\n\t\t\ttmp = CInt(Mid(cc,i,1))*2\n\t\t\tIf  tmp < 10 Then\n\t\t\t\ts2 = s2 + tmp\n\t\t\tElse\n\t\t\t\ts2 = s2 + CInt(Right(CStr(tmp),1)) + 1\n\t\t\tEnd If\n\t\tEnd If \n\tNext\n\tIf Right(CStr(s1 + s2),1) = \"0\" Then\n\t\tLuhn_Test = \"Valid\"\n\tElse\n\t\tLuhn_Test = \"Invalid\"\n\tEnd If\nEnd Function\n\nFunction RevString(s)\n\tFor i = Len(s) To 1 Step -1\n\t\tRevString = RevString & Mid(s,i,1)\n\tNext\nEnd Function\n\nWScript.Echo \"49927398716 is \" & Luhn_Test(\"49927398716\")\nWScript.Echo \"49927398717 is \" & Luhn_Test(\"49927398717\")\t\t\t \nWScript.Echo \"1234567812345678 is \" & Luhn_Test(\"1234567812345678\")\nWScript.Echo \"1234567812345670 is \" & Luhn_Test(\"1234567812345670\")\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":1166}
    {"lang_cluster":"VBScript","source_code":"\nWorks with: Windows Script Host version *\n' VBScript has a String() function that can repeat a character a given number of times\n' but this only works with single characters (or the 1st char of a string):\nWScript.Echo String(10, \"123\")\t' Displays \"1111111111\"\n\n' To repeat a string of chars, you can use either of the following \"hacks\"...\nWScript.Echo Replace(Space(10), \" \", \"Ha\")\nWScript.Echo Replace(String(10, \"X\"), \"X\", \"Ha\")\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":1167}
    {"lang_cluster":"VBScript","source_code":"\n\ntext = \"I need more coffee!!!\"\nSet regex = New RegExp\nregex.Global = True\nregex.Pattern = \"\\s\"\nIf regex.Test(text) Then\n\tWScript.StdOut.Write regex.Replace(text,vbCrLf)\nElse\n\tWScript.StdOut.Write \"No matching pattern\"\nEnd If\n\nInput:\nI need more coffee!!!\n\n","human_summarization":"\"Matches a string with a regular expression and substitutes a part of the string using another regular expression, also replaces white spaces with line breaks.\"","id":1168}
    {"lang_cluster":"VBScript","source_code":"\n\noption explicit\ndim a, b\nwscript.stdout.write \"A? \"\na = wscript.stdin.readline\nwscript.stdout.write \"B? \"\nb = wscript.stdin.readline\n\na = int( a )\nb = int( b )\n\nwscript.echo \"a + b=\", a + b\nwscript.echo \"a - b=\", a - b\nwscript.echo \"a * b=\", a * b\nwscript.echo \"a \/ b=\", a \/ b\nwscript.echo \"a \\ b=\", a \\ b\nwscript.echo \"a mod b=\", a mod b\nwscript.echo \"a ^ b=\", a ^ b\nAnother \noption explicit\ndim a, b\nwscript.stdout.write \"A? \"\na = wscript.stdin.readline\nwscript.stdout.write \"B? \"\nb = wscript.stdin.readline\n\na = int( a )\nb = int( b )\n\ndim op\nfor each op in split(\"+ - * \/ \\ mod ^\", \" \")\n\twscript.echo \"a\",op,\"b=\",eval( \"a \" & op & \" b\")\nnext\nC:\\foo>arithmetic.vbs\nA? 45\nB? 11\na + b= 4511\na - b= 34\na * b= 495\na \/ b= 4.09090909090909\na \\ b= 4\na mod b= 1\na ^ b= 1.5322783012207E+18\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates how the quotient is rounded and the sign of the remainder. It does not include error handling. A bonus feature is an example of the integer `divmod` operator. The code is inspired by Python and is designed to give the same output for the same input. Variables in the code may be converted from integer to other types if necessary.","id":1169}
    {"lang_cluster":"VBScript","source_code":"\n\nFunction CountSubstring(str,substr)\n\tCountSubstring = 0\n\tFor i = 1 To Len(str)\n\t\tIf Len(str) >= Len(substr) Then\n\t\t\tIf InStr(i,str,substr) Then\n\t\t\t\tCountSubstring = CountSubstring + 1\n\t\t\t\ti = InStr(i,str,substr) + Len(substr) - 1\n\t\t\tEnd If\n\t\tElse\n\t\t\tExit For\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.StdOut.Write CountSubstring(\"the three truths\",\"th\") & vbCrLf\nWScript.StdOut.Write CountSubstring(\"ababababab\",\"abab\") & vbCrLf\n\nfunction CountSubstring(str,substr)\n  with new regexp\n     .pattern=substr\n     .global=true\n     set m=.execute(str)\n  end with\n  CountSubstring =m.count\nend function  \nWScript.StdOut.Writeline CountSubstring(\"the three truths\",\"th\") \nWScript.StdOut.Writeline CountSubstring(\"ababababab\",\"abab\")\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the main string and the substring to search for, and returns an integer count. The function does not count overlapping substrings and matches from left-to-right or right-to-left to yield the highest number of non-overlapping matches.","id":1170}
    {"lang_cluster":"VBScript","source_code":"\n\nSub Move(n,fromPeg,toPeg,viaPeg)\n\tIf n > 0 Then\n\t\tMove n-1, fromPeg, viaPeg, toPeg\n\t\tWScript.StdOut.Write \"Move disk from \" & fromPeg & \" to \" & toPeg\n\t\tWScript.StdOut.WriteBlankLines(1)\n\t\tMove n-1, viaPeg, toPeg, fromPeg\n\tEnd If\nEnd Sub\n\nMove 4,1,2,3\nWScript.StdOut.Write(\"Towers of Hanoi puzzle completed!\")\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem, based on the BASIC256 version.\"","id":1171}
    {"lang_cluster":"VBScript","source_code":"\nFunction binomial(n,k)\n\tbinomial = factorial(n)\/(factorial(n-k)*factorial(k))\nEnd Function\n\nFunction factorial(n)\n\tIf n = 0 Then\n\t\tfactorial = 1\n\tElse\n\t\tFor i = n To 1 Step -1\n\t\t\tIf i = n Then\n\t\t\t\tfactorial = n\n\t\t\tElse\n\t\t\t\tfactorial = factorial * i\n\t\t\tEnd If\n\t\tNext\n\tEnd If\nEnd Function\n\n'calling the function\nWScript.StdOut.Write \"the binomial coefficient of 5 and 3 = \" & binomial(5,3)\nWScript.StdOut.WriteLine\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":1172}
    {"lang_cluster":"VBScript","source_code":"\nLenB(string|varname)\n\nLen(string|varname)\n\n","human_summarization":"The code calculates the character and byte length of a string, correctly handling encodings like UTF-8 and UTF-16. It accurately counts Unicode code points as individual characters, not user-visible graphemes or code unit counts. It also provides the string length in graphemes if possible. It returns the number of bytes required to store a string in memory and the length of the string, returning null if the string is null.","id":1173}
    {"lang_cluster":"VBScript","source_code":"\nFunction TopNTail(s,mode)\n    Select Case mode\n        Case \"top\"\n            TopNTail = Mid(s,2,Len(s)-1)\n        Case \"tail\"\n            TopNTail = Mid(s,1,Len(s)-1)\n        Case \"both\"\n            TopNTail = Mid(s,2,Len(s)-2)\n    End Select\nEnd Function\n\nWScript.Echo \"Top: UPRAISERS = \" & TopNTail(\"UPRAISERS\",\"top\")\nWScript.Echo \"Tail: UPRAISERS = \" & TopNTail(\"UPRAISERS\",\"tail\")\nWScript.Echo \"Both: UPRAISERS = \" & TopNTail(\"UPRAISERS\",\"both\")\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":1174}
    {"lang_cluster":"VBScript","source_code":"\nDim grid(9, 9)\nDim gridSolved(9, 9)\n \nPublic Sub Solve(i, j)\n    If i > 9 Then\n        'exit with gridSolved = Grid\n        For r = 1 To 9\n\t    For c = 1 To 9\n\t        gridSolved(r, c) = grid(r, c)\n\t    Next 'c \n        Next 'r\n        Exit Sub\n    End If\n    For n = 1 To 9\n        If isSafe(i, j, n) Then\n          nTmp = grid(i, j)\n          grid(i, j) = n\n          If j = 9 Then\n                Solve i + 1, 1\n          Else\n                Solve i, j + 1\n          End If\n          grid(i, j) = nTmp\n        End If\n    Next 'n\nEnd Sub 'Solve\n \nPublic Function isSafe(i, j, n) \n    If grid(i, j) <> 0 Then\n        isSafe = (grid(i, j) = n)\n        Exit Function\n    End If\n    'grid(i,j) is an empty cell. Check if n is OK\n    'first check the row i\n    For c = 1 To 9\n        If grid(i, c) = n Then\n            isSafe = False\n            Exit Function\n        End If\n    Next 'c\n    'now check the column j\n    For r = 1 To 9\n        If grid(r, j) = n Then\n            isSafe = False\n            Exit Function\n        End If\n    Next 'r\n    'finally, check the 3x3 subsquare containing grid(i,j)\n    iMin = 1 + 3 * Int((i - 1) \/ 3)\n    jMin = 1 + 3 * Int((j - 1) \/ 3)\n    For r = iMin To iMin + 2\n        For c = jMin To jMin + 2\n            If grid(r, c) = n Then\n                isSafe = False\n                Exit Function\n            End If\n        Next 'c\n    Next 'r\n    'all tests were OK\n    isSafe = True\nEnd Function 'isSafe\n \nPublic Sub Sudoku()\n    'main routine\n   Dim s(9) \n    s(1) = \"001005070\"\n    s(2) = \"920600000\"\n    s(3) = \"008000600\"\n    s(4) = \"090020401\"\n    s(5) = \"000000000\"\n    s(6) = \"304080090\"\n    s(7) = \"007000300\"\n    s(8) = \"000007069\"\n    s(9) = \"010800700\"\n    For i = 1 To 9\n        For j = 1 To 9\n            grid(i, j) = Int(Mid(s(i), j, 1))\n        Next 'j\n    Next 'j\n    'print problem\n    Wscript.echo \"Problem:\"\n    For i = 1 To 9\n\t    c=\"\"\n        For j = 1 To 9\n            c=c & grid(i, j) & \" \"\n        Next 'j\n\t    Wscript.echo c\n    Next 'i\n    'solve it!\n    Solve 1, 1\n    'print solution\n    Wscript.echo \"Solution:\"\n    For i = 1 To 9\n\t    c=\"\"\n        For j = 1 To 9\n            c=c & gridSolved(i, j) & \" \"\n        Next 'j\n\t    Wscript.echo c\n    Next 'i\nEnd Sub 'Sudoku\n\nCall sudoku\n\n\n","human_summarization":"\"Solves a partially filled 9x9 Sudoku grid and displays the result in a human-readable format. The solution is optimized for console mode with cscript and is adapted from a faster C solution. The implementation is guided by the Algorithmics of Sudoku and a Python Sudoku Solver Computerphile video.\"","id":1175}
    {"lang_cluster":"VBScript","source_code":"\nImplementation\nfunction shuffle( a )\n\tdim i\n\tdim r\n\trandomize timer\n\tfor i = lbound( a ) to ubound( a )\n\t\tr = int( rnd * ( ubound( a ) + 1 )  )\n\t\tif r <> i then\n\t\t\tswap a(i), a(r)\n\t\tend if\n\tnext\n\tshuffle = a\nend function\n\nsub swap( byref a, byref b )\n\tdim tmp\n\ttmp = a\n\ta = b \n\tb = tmp\nend sub\nInvocation\ndim a\na = array( 1,2,3,4,5,6,7,8,9)\nwscript.echo \"before: \", join( a, \", \" )\nshuffle a\nwscript.echo \"after: \", join( a, \", \" )\nshuffle a\nwscript.echo \"after: \", join( a, \", \" )\nwscript.echo \"--\"\na = array( now(), \"cow\", 123, true, sin(1), 16.4 )\nwscript.echo \"before: \", join( a, \", \" )\nshuffle a\nwscript.echo \"after: \", join( a, \", \" )\nshuffle a\nwscript.echo \"after: \", join( a, \", \" )\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":1176}
    {"lang_cluster":"VBScript","source_code":"\nWorks with: Windows Script Host\nstrUserIn = InputBox(\"Enter Data\")\nWscript.Echo strUserIn\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":1177}
    {"lang_cluster":"VBScript","source_code":"\n\n \n\tstr = \"IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES.\"\n\n\tWscript.Echo str\n\tWscript.Echo Rotate(str,5)\n\tWscript.Echo Rotate(Rotate(str,5),-5)\n\n\t'Rotate (Caesar encrypt\/decrypt) test  positions.\n\t'  numpos < 0 - rotate left\n\t'  numpos > 0 - rotate right\n\t'Left rotation is converted to equivalent right rotation\n\n\tFunction Rotate (text, numpos)\n\n\t\tdim dic: set dic = CreateObject(\"Scripting.Dictionary\")\n\t\tdim ltr: ltr = Split(\"A B C D E F G H I J K L M N O P Q R S T U V W X Y Z\")\n\t\tdim rot: rot = (26 + numpos Mod 26) Mod 26 'convert all to right rotation\n\t\tdim ch\n\t\tdim i\n\n\t\tfor i = 0 to ubound(ltr)\n\t\t\tdic(ltr(i)) = ltr((rot+i) Mod 26)\n\t\tnext\n\n\t\tRotate = \"\"\n\n\t\tfor i = 1 to Len(text)\n\t\t\tch = Mid(text,i,1)\n\t\t\tif dic.Exists(ch) Then\n\t\t\t\tRotate = Rotate & dic(ch)\n\t\t\telse\n\t\t\t\tRotate = Rotate & ch\n\t\t\tend if\n\t\tnext\n\n\tEnd Function\n\n","human_summarization":"implement both encoding and decoding functionalities of a Caesar cipher. The key for the cipher is an integer between 1 and 25, which determines the rotation of the alphabet letters. The encoding process replaces each letter with the next 1st to 25th letter in the alphabet, with a wrap from Z to A. The cipher is identical to Vigen\u00e8re cipher with a key of length 1 and Rot-13 with key 13. All left rotations are converted to equivalent right rotations before translation.","id":1178}
    {"lang_cluster":"VBScript","source_code":"\nFunction LCM(a,b)\n\tLCM = POS((a * b)\/GCD(a,b))\nEnd Function\n\nFunction GCD(a,b)\n\tDo\n\t\tIf a Mod b > 0 Then\n\t\t\tc = a Mod b\n\t\t\ta = b\n\t\t\tb = c\n\t\tElse\n\t\t\tGCD = b\n\t\t\tExit Do\n\t\tEnd If\n\tLoop\nEnd Function\n\nFunction POS(n)\n\tIf n < 0 Then\n\t\tPOS = n * -1\n\tElse\n\t\tPOS = n\n\tEnd If\nEnd Function\n\ni = WScript.Arguments(0)\nj = WScript.Arguments(1)\n\nWScript.StdOut.Write \"The LCM of \" & i & \" and \" & j & \" is \" & LCM(i,j) & \".\"\nWScript.StdOut.WriteLine\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":1179}
    {"lang_cluster":"VBScript","source_code":"\n\n    '''''''''''''''''''''''''''''''''''''''''''''\n    ' Rosetta Code\/Rank Languages by Popularity '\n    '          VBScript Implementation          '\n    '...........................................'\n\n'API Links (From C Code)\nURL1 = \"http:\/\/www.rosettacode.org\/mw\/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&rawcontinue\"\nURL2 = \"http:\/\/www.rosettacode.org\/mw\/api.php?format=json&action=query&generator=categorymembers&gcmtitle=Category:Programming%20Languages&gcmlimit=500&prop=categoryinfo&gcmcontinue=\"\n\n'Get Contents of the API from the Web...\nFunction ScrapeGoat(link)\n    On Error Resume Next\n    ScrapeGoat = \"\"\n    Err.Clear\n    Set objHttp = CreateObject(\"Msxml2.ServerXMLHTTP\")\n    objHttp.Open \"GET\", link, False\n    objHttp.Send\n    If objHttp.Status = 200 And Err = 0 Then ScrapeGoat = objHttp.ResponseText\n    Set objHttp = Nothing\nEnd Function\n\n'HACK: Setup HTML for help of my partner\/competitor that is better than me, JavaScript...\nSet HTML = CreateObject(\"HtmlFile\")\nSet HTMLWindow = HTML.ParentWindow\n\n\n    ''''''''''''''''''''\n    ' Main code begins '\n    '..................'\n\nOn Error Resume Next\n\nisComplete = 0    ' 1 -> Complete Already\ncntLoop = 0       ' Counts Number of Loops Done\nSet outputData = CreateObject(\"Scripting.Dictionary\")\n\nDo\n    'Scrape Data From API\n    If cntLoop = 0 Then strData = ScrapeGoat(URL1) Else strData = ScrapeGoat(URL2 & gcmCont)\n    If Len(strData) = 0 Then\n        Set HTML = Nothing\n        WScript.StdErr.WriteLine \"Processing of data stopped because API query failed.\"\n        WScript.Quit(1)\n    End If\n\n    'Parse JSON HACK\n    HTMLWindow.ExecScript \"var json = \" & strData, \"JavaScript\"\n    Set ObjJS = HTMLWindow.json\n\n    Err.Clear    'Test if Query is Complete Already\n    batchCompl = ObjJS.BatchComplete\n    If Err.Number = 438 Then\n        'Query not yet complete. Get gcmContinue instead.\n        gcmCont = ObjJS.[Query-Continue].CategoryMembers.gcmContinue\n    Else\n        isComplete = 1    'Yes!\n    End If\n\n    'HACK #2: Put all language page ids into a JS array to be accessed by VBScript\n    HTMLWindow.ExecScript \"var langs=new Array(); for(var lang in json.query.pages){langs.push(lang);}\" & _\n                          \"var nums=langs.length;\", \"JavaScript\"\n    Set arrLangs = HTMLWindow.langs\n    arrLength = HTMLWindow.nums\n\n    For i = 0 to arrLength - 1\n        BuffStr = \"ObjJS.Query.Pages.[\" & Eval(\"arrLangs.[\" & i & \"]\") & \"]\"\n        EachStr = Eval(BuffStr & \".title\")\n\n        Err.Clear\n        CntLang =  Eval(BuffStr & \".CategoryInfo.Pages\")\n        If InStr(EachStr, \"Category:\") = 1 And Err.Number = 0 Then\n            outputData.Add Replace(EachStr, \"Category:\", \"\", 1, 1), CntLang\n        End If\n    Next\n\n    cntLoop = cntLoop + 1\nLoop While isComplete = 0\n'The outputData now contains the data we need. We should now sort and print it!\n\n'Make a 2D array with copy of outputData\narrRelease = Array()\nReDim arrRelease(UBound(outputData.Keys), 1)\n\noutKeys = outputData.Keys\noutItem = outputData.Items\nFor i = 0 To UBound(outKeys)\n    arrRelease(i, 0) = outKeys(i)\n    arrRelease(i, 1) = outItem(i)\nNext\n\n'Bubble Sort (Greatest to Least Number of Examples)\nFor i = 0 to UBound(arrRelease, 1)\n    For j = 0 to UBound(arrRelease, 1) - 1\n        If arrRelease(j, 1) < arrRelease(j + 1, 1) Then\n            temp1 = arrRelease(j + 1, 0)\n            temp2 = arrRelease(j + 1, 1)\n            arrRelease(j + 1, 0) = arrRelease(j, 0)\n            arrRelease(j + 1, 1) = arrRelease(j, 1)\n            arrRelease(j, 0) = temp1\n            arrRelease(j, 1) = temp2\n        End If\n    Next\nNext\n\n'Save contents to file instead to support Unicode Names\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet txtOut = objFSO.CreateTextFile(\".\\OutVBRC.txt\", True, True)\n\ntxtOut.WriteLine \"As of \" & Now & \", RC has \" & UBound(arrRelease) + 1 & \" languages.\"\ntxtOut.WriteLine \"\"\nFor i = 0 to UBound(arrRelease)\n    txtOut.WriteLine arrRelease(i, 1) & \" Examples - \" & arrRelease(i, 0)\nNext\n\n'Successfully Done\u00a0:)\nSet HTML = Nothing\nSet objFSO = Nothing\nWScript.Quit(0)\n\n\nSome Parts of Output as of December 31, 2016:\nAs of 12\/31\/2016 11:52:05 PM, RC has 624 languages.\n\n917 Examples - Racket\n906 Examples - Python\n894 Examples - Tcl\n859 Examples - J\n853 Examples - Perl 6\n819 Examples - Zkl\n813 Examples - Ruby\n796 Examples - C\n776 Examples - Java\n774 Examples - Go\n766 Examples - Haskell\n760 Examples - REXX\n755 Examples - Perl\n750 Examples - D\n\n.\n.\n.\n\n0 Examples - SheerPower 4GL\n0 Examples - Script Basic\n0 Examples - VRML\n0 Examples - Thistle\n0 Examples - UserRPL\n0 Examples - WML\n0 Examples - VAX Assembly\n","human_summarization":"The code sorts and ranks popular computer programming languages based on the number of members in their respective Rosetta Code categories. It retrieves data either through web scraping or using the API method. The code also includes optional functionality for filtering incorrect results. The sorted and ranked results are saved in a Unicode encoded text file named \"OutVBRC.txt\".","id":1180}
    {"lang_cluster":"VBScript","source_code":"\nWScript.Echo Join(Split(\"Hello,How,Are,You,Today\", \",\"), \".\")\n\n\nSub Main()\n    Dim parseMe As String, parsed As Variant\n    parseMe = \"Hello,How,Are,You,Today\"\n\n    parsed = Split(parseMe, \",\")\n\n    Dim L0 As Long, outP As String\n    outP = parsed(0)\n    For L0 = 1 To UBound(parsed)\n        outP = outP & \".\" & parsed(L0)\n    Next\n\n    MsgBox outP\nEnd Sub\n\n","human_summarization":"\"Tokenizes a string by commas into an array, then displays the words separated by a period. No need to know the number of tokens in advance as the array is automatically built.\"","id":1181}
    {"lang_cluster":"VBScript","source_code":"\nIsNumeric(Expr)\n\n","human_summarization":"The function checks if a given string can be interpreted as a numeric value (including floating point and negative numbers) in the syntax of the language, returning true if it is and false if not.","id":1182}
    {"lang_cluster":"VBScript","source_code":"\nLibrary: Microsoft.XmlHTTP\n\nOption Explicit\n\nConst sURL=\"https:\/\/sourceforge.net\/\"\n\nDim oHTTP\nSet oHTTP = CreateObject(\"Microsoft.XmlHTTP\")\n\nOn Error Resume Next\noHTTP.Open \"GET\", sURL, False\noHTTP.Send \"\"\nIf Err.Number = 0 Then\n     WScript.Echo oHTTP.responseText\nElse\n     Wscript.Echo \"error \" & Err.Number & \": \" & Err.Description\nEnd If\n\nSet oHTTP = Nothing\n\n","human_summarization":"send a GET request to the URL \"https:\/\/www.w3.org\/\" without authentication, check the host certificate for validity, and print the retrieved resource to the console. It's a contrast to the tasks of HTTP Request and HTTPS request with authentication. The codes are based on the method of retrieving HTML web pages with VBScript via the Microsoft.XmlHttp object.","id":1183}
    {"lang_cluster":"VBScript","source_code":"\nWorks with: Windows Script Host version *\n' Read the list of paths (newline-separated) into an array...\nstrPaths = Split(WScript.StdIn.ReadAll, vbCrLf)\n \n' Split each path by the delimiter (\/)...\nFor i = 0 To UBound(strPaths)\n\tstrPaths(i) = Split(strPaths(i), \"\/\")\nNext\n\nWith CreateObject(\"Scripting.FileSystemObject\")\n\n\t' Test each path segment...\n\tFor j = 0 To UBound(strPaths(0))\n\t\t\n\t\t' Test each successive path against the first...\n\t\tFor i = 1 To UBound(strPaths)\n\t\t\tIf strPaths(0)(j) <> strPaths(i)(j) Then Exit For\n\t\tNext\n\n\t\t' If we didn't make it all the way through, exit the block...\n\t\tIf i <= UBound(strPaths) Then Exit For\n\t\t\n\t\t' Make sure this path exists...\n\t\tIf Not .FolderExists(strPath & strPaths(0)(j) & \"\/\") Then Exit For\n\t\tstrPath = strPath & strPaths(0)(j) & \"\/\"\n\t\t\n\tNext\n\nEnd With\n\n' Remove the final \"\/\"...\nWScript.Echo Left(strPath, Len(strPath) - 1)\n\n","human_summarization":"The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '\/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.","id":1184}
    {"lang_cluster":"VBScript","source_code":"\nDim client\nDim result\nSet client = CreateObject(\"MSSOAP.SoapClient\")\nclient.MSSoapInit \"http:\/\/example.com\/soap\/wsdl\"\nresult = client.soapFunc(\"hello\")\nresult = client.anotherSoapFunc(34234)\n\n","human_summarization":"The code establishes a SOAP client to access and call the functions soapFunc() and anotherSoapFunc() from the WSDL located at http:\/\/example.com\/soap\/wsdl. Note, the task and corresponding code may require further clarification.","id":1185}
    {"lang_cluster":"VBScript","source_code":"\nWorks with: Windows Script Host version *\nFor i = 1 To 100\n\tIf i Mod 15 = 0 Then\n\t\tWScript.Echo \"FizzBuzz\"\n\tElseIf i Mod 5 = 0 Then\n\t\tWScript.Echo \"Buzz\"\n\tElseIf i Mod 3 = 0 Then\n\t\tWScript.Echo \"Fizz\"\n\tElse\n\t\tWScript.Echo i\n\tEnd If\nNext\nWorks with: Windows Script Host version *\nWith WScript.StdOut\n\tFor i = 1 To 100\n\t\tIf i Mod 3 = 0 Then .Write \"Fizz\"\n\t\tIf i Mod 5 = 0 Then .Write \"Buzz\"\n\t\tIf .Column = 1 Then .WriteLine i Else .WriteLine \"\"\n\tNext\nEnd With\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":1186}
    {"lang_cluster":"VBScript","source_code":"\noption explicit\n\n' Raster graphics class in VBSCRIPT by Antoni Gual\n'--------------------------------------------\n' An array keeps the image allowing to set pixels, draw lines and boxes in it. \n' at class destroy a bmp file is saved to disk and the default viewer is called\n' The class can work with 8 and 24 bit bmp. With 8 bit uses a built-in palette or can import a custom one\n\n\n'Declaration\u00a0: \n' Set MyObj = (New ImgClass)(name,width,height, orient,bits_per_pixel,palette_array)\n' name:path and name of the file created\n' width, height of the canvas\n' orient is the way the coord increases, 1 to 4 think of the 4 cuadrants of the caterian plane\n'    1 X:l>r Y:b>t   2 X:r>l Y:b>t  3 X:r>l Y:t>b   4 X:l>r  Y:t>b \n' bits_per_pixel can bs only 8 and 24\n' palette array only to substitute the default palette for 8 bits, else put a 0\n' it sets the origin at the corner of the image (bottom left if orient=1) \n\nClass ImgClass\n  Private ImgL,ImgH,ImgDepth,bkclr,loc,tt\n  private xmini,xmaxi,ymini,ymaxi,dirx,diry\n  public ImgArray()  'rgb in 24 bit mode, indexes to palette in 8 bits\n  private filename   \n  private Palette,szpal \n  \n  Public Property Let depth (x) \n  if depth=8 or depth =24 then \n    Imgdepth=depth\n  else \n    Imgdepth=8\n  end if\n  bytepix=imgdepth\/8\n  end property        \n  \n  Public Property Let Pixel (x,y,color)\n  If (x>=ImgL) or x<0 then exit property\n  if y>=ImgH or y<0 then exit property\n  ImgArray(x,y)=Color   \n  End Property\n  \n  Public Property Get Pixel (x,y)\n  If (x=0) And (y=0) Then\n    Pixel=ImgArray(x,y)\n  End If\n  End Property\n  \n  Public Property Get ImgWidth ()\n  ImgWidth=ImgL-1\n  End Property\n  \n  Public Property Get ImgHeight ()\n  ImgHeight=ImgH-1\n  End Property     \n  \n  'constructor (fn,w*2,h*2,32,0,0)\n  Public Default Function Init(name,w,h,orient,dep,bkg,mipal)\n  'offx, offy posicion de 0,0. si ofx+ , x se incrementa de izq a der, si offy+ y se incrementa de abajo arriba\n  dim i,j\n  ImgL=w\n  ImgH=h\n  tt=timer\n  set0 0,0   'origin blc positive up and right\n  redim imgArray(ImgL-1,ImgH-1)\n  bkclr=bkg\n  if bkg<>0 then \n    for i=0 to ImgL-1 \n      for j=0 to ImgH-1 \n        imgarray(i,j)=bkg\n      next\n    next  \n  end if \n  Select Case orient\n    Case 1: dirx=1\u00a0: diry=1   \n    Case 2: dirx=-1\u00a0: diry=1\n    Case 3: dirx=-1\u00a0: diry=-1\n    Case 4: dirx=1\u00a0: diry=-1\n  End select    \n  filename=name\n  ImgDepth =dep\n  'load user palette if provided  \n  if imgdepth=8 then  \n    loadpal(mipal)\n  end if       \n  set init=me\n  end function\n\n  private sub loadpal(mipale)\n    if isarray(mipale) Then\n      palette=mipale\n      szpal=UBound(mipale)+1\n    Else\n      szpal=256  \n    'Default palette recycled from ATARI\n  \n   End if  \n  End Sub\n  public sub set0 (x0,y0) 'origin can be changed during drawing\n    if x0<0 or x0>=imgl or y0<0 or y0>imgh then err.raise 9 \n    xmini=-x0\n    ymini=-y0\n    xmaxi=xmini+imgl-1\n    ymaxi=ymini+imgh-1 \n    \n  end sub\n\n    \n  Private Sub Class_Terminate\n  if err <>0 then wscript.echo \"Error \" & err.number\n  wscript.echo \"writing bmp to file\"\n    savebmp\n    wscript.echo \"opening \" & filename\n    CreateObject(\"Shell.Application\").ShellExecute filename\n  wscript.echo timer-tt & \" seconds\"\n  End Sub\n\n\n 'writes a 32bit integr value as binary to an utf16 string\n function long2wstr( x)  'falta muy poco!!!\n      dim k1,k2,x1\n      k1=  (x and &hffff&)' or (&H8000& And ((X And &h8000&)<>0)))\n      k2=((X And &h7fffffff&) \\ &h10000&) Or (&H8000& And (x<0))\n      long2wstr=chrw(k1) & chrw(k2)\n    end function \n    \n    function int2wstr(x)\n        int2wstr=ChrW((x and &h7fff) or (&H8000 And (X<0)))\n    End Function\n\n\n  Public Sub SaveBMP\n    'Save the picture to a bmp file\n    Dim s,ostream, x,y,loc\n   \n    const hdrs=54 '14+40 \n    dim bms:bms=ImgH* 4*(((ImgL*imgdepth\\8)+3)\\4)  'bitmap size including padding\n    dim palsize:if (imgdepth=8) then palsize=szpal*4 else palsize=0\n\n    with  CreateObject(\"ADODB.Stream\") 'auxiliary ostream, it creates an UNICODE with bom stream in memory\n      .Charset = \"UTF-16LE\"    'o \"UTF16-BE\" \n      .Type =  2' adTypeText  \n      .open \n      \n      'build a header\n      'bmp header: VBSCript does'nt have records nor writes binary values to files, so we use strings of unicode chars!! \n      'BMP header  \n      .writetext ChrW(&h4d42)                           ' 0 \"BM\" 4d42 \n      .writetext long2wstr(hdrs+palsize+bms)            ' 2 fiesize  \n      .writetext long2wstr(0)                           ' 6  reserved \n      .writetext long2wstr (hdrs+palsize)               '10 image offset \n       'InfoHeader \n      .writetext long2wstr(40)                          '14 infoheader size\n      .writetext long2wstr(Imgl)                        '18 image length  \n      .writetext long2wstr(imgh)                        '22 image width\n      .writetext int2wstr(1)                            '26 planes\n      .writetext int2wstr(imgdepth)                     '28 clr depth (bpp)\n      .writetext long2wstr(&H0)                         '30 compression used 0= NOCOMPR\n       \n      .writetext long2wstr(bms)                         '34 imgsize\n      .writetext long2wstr(&Hc4e)                       '38 bpp hor\n      .writetext long2wstr(&hc43)                       '42 bpp vert\n      .writetext long2wstr(szpal)                       '46  colors in palette\n      .writetext long2wstr(&H0)                         '50 important clrs 0=all\n     \n      'write bitmap\n      'precalc data for orientation\n       Dim x1,x2,y1,y2\n       If dirx=-1 Then x1=ImgL-1 :x2=0 Else x1=0:x2=ImgL-1\n       If diry=-1 Then y1=ImgH-1 :y2=0 Else y1=0:y2=ImgH-1 \n       \n      Select Case imgdepth\n      \n      Case 32\n        For y=y1 To y2  step diry   \n          For x=x1 To x2 Step dirx\n           'writelong fic, Pixel(x,y) \n           .writetext long2wstr(Imgarray(x,y))\n          Next\n        Next\n        \n      Case 8\n        'palette\n        For x=0 to szpal-1\n          .writetext long2wstr(palette(x))  '52\n        Next\n        'image\n        dim pad:pad=ImgL mod 4\n        For y=y1 to y2 step diry\n          For x=x1 To x2 step dirx*2\n             .writetext chrw((ImgArray(x,y) and 255)+ &h100& *(ImgArray(x+dirx,y) and 255))\n          Next\n          'line padding\n          if pad and 1 then .writetext  chrw(ImgArray(x2,y))\n          if pad >1 then .writetext  chrw(0)\n         Next\n         \n      Case Else\n        WScript.Echo \"ColorDepth not supported\u00a0: \" & ImgDepth & \" bits\"\n      End Select\n\n      'use a second stream to save to file starting past the BOM  the first ADODB.Stream has added\n      Dim outf:Set outf= CreateObject(\"ADODB.Stream\") \n      outf.Type    = 1 ' adTypeBinary  \n      outf.Open\n      .position=2              'remove bom (1 wchar) \n      .CopyTo outf\n      .close\n      outf.savetofile filename,2   'adSaveCreateOverWrite\n      outf.close\n    end with\n  End Sub\nEnd Class\n\nfunction mandelpx(x0,y0,maxit)\n   dim x,y,xt,i,x2,y2\n   i=0:x2=0:y2=0\n   Do While i< maxit\n     i=i+1\n     xt=x2-y2+x0\n     y=2*x*y+y0\n     x=xt \n     x2=x*x:y2=y*y \n     If (x2+y2)>=4 Then Exit do\n   loop \n   if i=maxit then\n      mandelpx=0\n   else   \n     mandelpx = i\n   end if  \nend function   \n\nSub domandel(x1,x2,y1,y2) \n Dim i,ii,j,jj,pix,xi,yi,ym\n ym=X.ImgHeight\\2\n 'get increments in the mandel plane\n xi=Abs((x1-x2)\/X.ImgWidth)\n yi=Abs((y2-0)\/(X.ImgHeight\\2))\n j=0\n For jj=0.  To y2 Step yi\n   i=0\n   For ii=x1 To x2 Step xi\n      pix=mandelpx(ii,jj,256)\n      'use simmetry\n      X.imgarray(i,ym-j)=pix\n      X.imgarray(i,ym+j)=pix\n      i=i+1   \n   Next\n   j=j+1   \n next\nEnd Sub\n\n'main------------------------------------\nDim i,x\n'custom palette\ndim pp(255)\nfor i=1 to 255\n   pp(i)=rgb(0,0,255*(i\/255)^.25)  'VBS' RGB function is for the web, it's bgr for Windows BMP\u00a0!!\nnext  \n \ndim fn:fn=CreateObject(\"Scripting.FileSystemObject\").GetSpecialFolder(2)& \"\\mandel.bmp\"\nSet X = (New ImgClass)(fn,580,480,1,8,0,pp)\ndomandel -2.,1.,-1.2,1.2\nSet X = Nothing\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions.","id":1187}
    {"lang_cluster":"VBScript","source_code":"\nFunction sum_and_product(arr)\n\tsum = 0\n\tproduct = 1\n\tFor i = 0 To UBound(arr)\n\t\tsum = sum + arr(i)\n\t\tproduct = product * arr(i)\n\tNext\n\tWScript.StdOut.Write \"Sum: \" & sum\n\tWScript.StdOut.WriteLine\n\tWScript.StdOut.Write \"Product: \" & product\n\tWScript.StdOut.WriteLine\nEnd Function\n\nmyarray = Array(1,2,3,4,5,6)\nsum_and_product(myarray)\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":1188}
    {"lang_cluster":"VBScript","source_code":"\nFunction pick_random(arr)\n\tSet objRandom = CreateObject(\"System.Random\")\n\tpick_random = arr(objRandom.Next_2(0,UBound(arr)+1))\nEnd Function\n\nWScript.Echo pick_random(Array(\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"))\n\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":1189}
    {"lang_cluster":"VBScript","source_code":"\nFunction RegExTest(str,patrn)\n    Dim regEx\n    Set regEx = New RegExp\n    regEx.IgnoreCase = True\n    regEx.Pattern = patrn\n    RegExTest = regEx.Test(str)\nEnd Function\n\nFunction URLDecode(sStr)\n    Dim str,code,a0\n    str=\"\"\n    code=sStr\n    code=Replace(code,\"+\",\" \")\n    While len(code)>0\n        If InStr(code,\"%\")>0 Then\n            str = str & Mid(code,1,InStr(code,\"%\")-1)\n            code = Mid(code,InStr(code,\"%\"))\n            a0 = UCase(Mid(code,2,1))\n            If a0=\"U\" And RegExTest(code,\"^%u[0-9A-F]{4}\") Then\n                str = str & ChrW((Int(\"&H\" & Mid(code,3,4))))\n                code = Mid(code,7)\n            ElseIf a0=\"E\" And RegExTest(code,\"^(%[0-9A-F]{2}){3}\") Then\n                str = str & ChrW((Int(\"&H\" & Mid(code,2,2)) And 15) * 4096 + (Int(\"&H\" & Mid(code,5,2)) And 63) * 64 + (Int(\"&H\" & Mid(code,8,2)) And 63))\n                code = Mid(code,10)\n            ElseIf a0>=\"C\" And a0<=\"D\" And RegExTest(code,\"^(%[0-9A-F]{2}){2}\") Then\n                str = str & ChrW((Int(\"&H\" & Mid(code,2,2)) And 3) * 64 + (Int(\"&H\" & Mid(code,5,2)) And 63))\n                code = Mid(code,7)\n            ElseIf (a0<=\"B\" Or a0=\"F\") And RegExTest(code,\"^%[0-9A-F]{2}\") Then\n                str = str & Chr(Int(\"&H\" & Mid(code,2,2)))\n                code = Mid(code,4)\n            Else\n                str = str & \"%\"\n                code = Mid(code,2)\n            End If\n        Else\n            str = str & code\n            code = \"\"\n        End If\n    Wend\n    URLDecode = str\nEnd Function\n\nurl = \"http%3A%2F%2Ffoo%20bar%C3%A8%2F\"\nWScript.Echo \"Encoded URL: \" & url & vbCrLf &_\n\t\"Decoded URL: \" & UrlDecode(url)\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":1190}
    {"lang_cluster":"VBScript","source_code":"\n\noption explicit\n\n const dt = 0.15\n const length=23\n dim ans0:ans0=chr(27)&\"[\"\n dim Veloc,Accel,angle,olr,olc,r,c \nconst r0=1\nconst c0=40\n cls\n angle=0.7\n while 1\n    wscript.sleep(50)\n    Accel = -.9 * sin(Angle)\n    Veloc = Veloc + Accel * dt\n    Angle = Angle + Veloc * dt\n   \n    r = r0 + int(cos(Angle) * Length)\n    c = c0+ int(2*sin(Angle) * Length)\n    cls\n    draw_line r,c,r0,c0\n    toxy r,c,\"O\"\n\n    olr=r :olc=c\nwend\n\nsub cls()  wscript.StdOut.Write ans0 &\"2J\"&ans0 &\"?25l\":end sub\nsub toxy(r,c,s)  wscript.StdOut.Write ans0 & r & \";\" & c & \"f\"  & s :end sub\n\nSub draw_line(r1,c1, r2,c2)  'Bresenham's line drawing\n  Dim x,y,xf,yf,dx,dy,sx,sy,err,err2\n  x =r1    : y =c1\n  xf=r2    : yf=c2\n  dx=Abs(xf-x) : dy=Abs(yf-y)\n  If x-dy Then err=err-dy: x=x+sx\n    If err2< dx Then err=err+dx: y=y+sy\n  Loop\nEnd Sub 'draw_line\n\n","human_summarization":"simulate and animate a simple gravity pendulum using a dynamic graphical display. The animation is created in a text mode as VbScript doesn't support graphics mode and should be called from cscript.","id":1191}
    {"lang_cluster":"VBScript","source_code":"\nSet objNetwork = CreateObject(\"WScript.Network\")\nWScript.Echo objNetwork.ComputerName\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":1192}
    {"lang_cluster":"VBScript","source_code":"\n\ts1=\"Hello\"\n\ts2=s1 & \" World!\"\n\tWScript.Echo s2\n\n","human_summarization":"initialize a string variable, concatenate it with another string literal, and display the content of the variables.","id":1193}
    {"lang_cluster":"VBScript","source_code":"\nFunction UrlEncode(url)\n\tFor i = 1 To Len(url)\n\t\tn = Asc(Mid(url,i,1))\n\t\tIf (n >= 48 And n <= 57) Or (n >= 65 And n <= 90) _\n\t\t\tOr (n >= 97 And n <= 122) Then\n\t\t\tUrlEncode = UrlEncode & Mid(url,i,1)\n\t\tElse\n\t\t\tChrHex = Hex(Asc(Mid(url,i,1)))\n                        For j = 0 to (Len(ChrHex) \/ 2) - 1\n\t\t\t    UrlEncode = UrlEncode & \"%\" & Mid(ChrHex,(2*j) + 1,2)\n                        Next\n\t\tEnd If\n\tNext\nEnd Function\n\nWScript.Echo UrlEncode(\"http:\/\/foo bar\u00e9\/\")\n\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":1194}
    {"lang_cluster":"VBScript","source_code":"\n\nConst adInteger = 3 \nConst adVarChar = 200 \n\nfunction charcnt(s,ch)\ncharcnt=0\nfor i=1 to len(s)\n  if mid(s,i,1)=ch then charcnt=charcnt+1\nnext\nend function  \n\nset fso=createobject(\"Scripting.Filesystemobject\")\ndim a(122)\n\nsfn=WScript.ScriptFullName\nsfn= Left(sfn, InStrRev(sfn, \"\\\"))\nset f=fso.opentextfile(sfn & \"unixdict.txt\",1)\n\n'words to dictionnary using acronym as key\nset d=createobject(\"Scripting.Dictionary\")\n\nwhile not f.AtEndOfStream\n  erase a :cnt=0\n  s=trim(f.readline)\n\t\n\t'tally chars\n  for i=1 to len(s)\n   n=asc(mid(s,i,1))\n   a(n)=a(n)+1\n  next\n\t\n  'build the anagram\n  k=\"\"\n  for i= 48 to 122\n    if a(i) then k=k & string(a(i),chr(i))\n  next\n\t\n\t'add to dict\n  if d.exists(k) then\n    b=d(k)\n    d(k)=b & \" \" & s\n  else\n    d(k)=s\n  end if\nwend\n\n'copy dictionnary to recorset to be able to sort it .Add nr of items as a new field\nSet rs = CreateObject(\"ADODB.Recordset\")\nrs.Fields.Append \"anag\", adVarChar, 30\nrs.Fields.Append \"items\", adInteger\nrs.Fields.Append \"words\", adVarChar, 200\nrs.open\nfor each k in d.keys\n rs.addnew\n rs(\"anag\")=k\n s=d(k)\n rs(\"words\")=s\n rs(\"items\")=charcnt(s,\" \")+1\n rs.update\nnext\nd.removeall\n\n'do the query\nrs.sort=\"items DESC, anag ASC\"\nrs.movefirst\nit=rs(\"items\")\nwhile rs(\"items\")=it\n  wscript.echo  rs(\"items\") & \" (\" &rs(\"anag\") & \") \" & rs(\"words\")\n  rs.movenext\nwend\nrs.close\n\n5 (abel) abel able bale bela elba\n5 (acert) caret carte cater crate trace\n5 (aegln) angel angle galen glean lange\n5 (aeglr) alger glare lager large regal\n5 (aeln) elan lane lean lena neal\n5 (eilv) evil levi live veil vile\n\n","human_summarization":"\"Find the largest sets of anagrams from a given word list (http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt) using a dictionary and a recordset.\"","id":1195}
    {"lang_cluster":"VBScript","source_code":"\nOption Explicit\n\nDim objFSO, DBSource \n\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\n\nDBSource = objFSO.GetParentFolderName(WScript.ScriptFullName) & \"\\postal_address.accdb\"\n\nWith CreateObject(\"ADODB.Connection\")\n\t.Open \"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\" & DBSource\n\t.Execute \"CREATE TABLE ADDRESS (STREET VARCHAR(30) NOT NULL,\" &_\n\t\t\t\"CITY VARCHAR(30) NOT NULL, STATE CHAR(2) NOT NULL,ZIP CHAR(5) NOT NULL)\"\n\t.Close\nEnd With\n\n","human_summarization":"create a table in a database to store US postal addresses, including fields for a unique identifier, street address, city, state code, and zipcode. The codes also demonstrate how to establish a database connection in non-database languages.","id":1196}
    {"lang_cluster":"VBScript","source_code":"Function Encrypt(text,key)\n\ttext = OnlyCaps(text) \n\tkey = OnlyCaps(key)\n\tj = 1\n\tFor i = 1 To Len(text)\n\t\tms = Mid(text,i,1)\n\t\tm = Asc(ms) - Asc(\"A\")\n\t\tks = Mid(key,j,1)\n\t\tk = Asc(ks) - Asc(\"A\")\n\t\tj = (j Mod Len(key)) + 1\n\t\tc = (m + k) Mod 26\n\t\tc = Chr(Asc(\"A\")+c)\n\t\tEncrypt = Encrypt & c\n\tNext\nEnd Function\n\nFunction Decrypt(text,key)\n\tkey = OnlyCaps(key)\n\tj = 1\n\tFor i = 1 To Len(text)\n\t\tms = Mid(text,i,1)\n\t\tm = Asc(ms) - Asc(\"A\")\n\t\tks = Mid(key,j,1)\n\t\tk = Asc(ks) - Asc(\"A\")\n\t\tj = (j Mod Len(key)) + 1\n\t\tc = (m - k + 26) Mod 26\n\t\tc = Chr(Asc(\"A\")+c)\n\t\tDecrypt = Decrypt & c\n\tNext\nEnd Function\n\nFunction OnlyCaps(s)\n\tFor i = 1 To Len(s)\n\t\tchar = UCase(Mid(s,i,1))\n\t\tIf Asc(char) >= 65 And Asc(char) <= 90 Then\n\t\t\tOnlyCaps = OnlyCaps & char\n\t\tEnd If\n\tNext\nEnd Function\n\n'testing the functions\norig_text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\norig_key = \"vigenerecipher\"\nWScript.StdOut.WriteLine \"Original: \" & orig_text\nWScript.StdOut.WriteLine \"Key: \" & orig_key\nWScript.StdOut.WriteLine \"Encrypted: \" & Encrypt(orig_text,orig_key)\nWScript.StdOut.WriteLine \"Decrypted: \" & Decrypt(Encrypt(orig_text,orig_key),orig_key)\n\n\n","human_summarization":"\"Implement Vigen\u00e8re cipher for both encryption and decryption, accommodating keys and text of unequal length. The code also capitalizes all characters and discards non-alphabetic ones. An alternate version uses RegExp for input filtering.\"","id":1197}
    {"lang_cluster":"VBScript","source_code":"\nbuffer = \"\"\nFor i = 2 To 8 Step 2\n    buffer = buffer & i & \" \"\nNext\nWScript.Echo buffer\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":1198}
    {"lang_cluster":"VBScript","source_code":"\nFunction order_list(arr1,arr2)\n\torder_list = \"FAIL\"\n\tn1 = UBound(arr1): n2 = UBound(arr2)\n\tn = 0 : p = 0\n\tIf n1 > n2 Then\n\t\tmax = n2\n\tElse\n\t\tmax = n1\n\tEnd If\n\tFor i = 0 To max\n\t\tIf arr1(i) > arr2(i) Then\n\t\t\tn = n + 1\n\t\tElseIf arr1(i) = arr2(i) Then\n\t\t\tp = p + 1\n\t\tEnd If\t\n\tNext\n\tIf (n1 < n2 And n = 0) Or _\n\t\t (n1 = n2 And n = 0 And p - 1 <> n1) Or _\n\t\t (n1 > n2 And n = 0 And p = n2) Then\n\t\t\torder_list = \"PASS\"\n\tEnd If\nEnd Function\n\nWScript.StdOut.WriteLine order_list(Array(-1),Array(0))\nWScript.StdOut.WriteLine order_list(Array(0),Array(0))\nWScript.StdOut.WriteLine order_list(Array(0),Array(-1))\nWScript.StdOut.WriteLine order_list(Array(0),Array(0,-1))\nWScript.StdOut.WriteLine order_list(Array(0),Array(0,0))\nWScript.StdOut.WriteLine order_list(Array(0),Array(0,1))\nWScript.StdOut.WriteLine order_list(Array(0,-1),Array(0))\nWScript.StdOut.WriteLine order_list(Array(0,0),Array(0))\nWScript.StdOut.WriteLine order_list(Array(0,0),Array(1))\nWScript.StdOut.WriteLine order_list(Array(1,2,1,3,2),Array(1,2,0,4,4,0,0,0))\n\n\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise.\"","id":1199}
    {"lang_cluster":"VBScript","source_code":"\n\nImplementation\noption explicit\n'~ dim depth\nfunction ack(m, n)\n\t'~ wscript.stdout.write depth & \" \"\n\tif m = 0 then \n\t\t'~ depth = depth + 1\n\t\tack = n + 1\n\t\t'~ depth = depth - 1\n\telseif m > 0 and n = 0 then\n\t\t'~ depth = depth + 1\n\t\tack = ack(m - 1, 1)\n\t\t'~ depth = depth - 1\n\t'~ elseif m > 0 and n > 0 then\n\telse\n\t\t'~ depth = depth + 1\n\t\tack = ack(m - 1, ack(m, n - 1))\n\t\t'~ depth = depth - 1\n\tend if\n\t\nend function\nInvocation\nwscript.echo ack( 1, 10 )\n'~ depth = 0\nwscript.echo ack( 2, 1 )\n'~ depth = 0\nwscript.echo ack( 4, 4 )\n\n","human_summarization":"Implement the Ackermann function, a non-primitive recursive function that takes two non-negative arguments and returns a rapidly growing value. The function should ideally support arbitrary precision due to the rapid growth of the function's output.","id":1200}
    {"lang_cluster":"VBScript","source_code":"\n'N-queens problem - non recursive & structured - vbs - 24\/02\/2017\nconst l=15\ndim a(),s(),u(): redim a(l),s(l),u(4*l-2)\nfor i=1 to l: a(i)=i: next\nfor n=1 to l\n    m=0\n    i=1\n    j=0\n    r=2*n-1\n    Do\n        i=i-1\n        j=j+1\n        p=0\n        q=-r\n        Do\n            i=i+1\n            u(p)=1\n            u(q+r)=1\n            z=a(j): a(j)=a(i): a(i)=z  'swap a(i),a(j)\n            p=i-a(i)+n\n            q=i+a(i)-1\n            s(i)=j\n            j=i+1\n        Loop Until j>n Or u(p)<>0 Or u(q+r)<>0\n        If u(p)=0 Then\n            If u(q+r)=0 Then\n                m=m+1  'm: number of solutions\n                'x=\"\": for k=1 to n: x=x&\" \"&a(k): next: msgbox x,,m\n             End If\n        End If\n        j=s(i)\n        Do While j>=n And i<>0\n            Do\n                z=a(j): a(j)=a(i): a(i)=z  'swap a(i),a(j)\n                j=j-1\n            Loop Until jxv and iw<=ww then xw=iw:xv=iv:l=m\n end if 'i1\n if iw<=ww then\n  w(2)=iw: v(2)=iv\n  for i2=0 to 1:m(2)=i2:j=1\n   if i2=1 then\n    iw=w(2)+data(j*3+1):iv=v(2)+data(j*3+2)\n    if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n   end if 'i2\n   if iw<=ww then\n    w(3)=iw: v(3)=iv\n    for i3=0 to 1:m(3)=i3:j=2\n     if i3=1 then\n      iw=w(3)+data(j*3+1):iv=v(3)+data(j*3+2)\n      if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n     end if 'i3\n     if iw<=ww then\n      w(4)=iw: v(4)=iv\n      for i4=0 to 1:m(4)=i4:j=3\n       if i4=1 then\n        iw=w(4)+data(j*3+1):iv=v(4)+data(j*3+2)\n        if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n       end if 'i4\n       if iw<=ww then\n        w(5)=iw: v(5)=iv\n        for i5=0 to 1:m(5)=i5:j=4\n         if i5=1 then\n          iw=w(5)+data(j*3+1):iv=v(5)+data(j*3+2)\n          if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n         end if 'i5\n         if iw<=ww then\n          w(6)=iw: v(6)=iv\n          for i6=0 to 1:m(6)=i6:j=5\n           if i6=1 then\n            iw=w(6)+data(j*3+1):iv=v(6)+data(j*3+2)\n            if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n           end if 'i6\n           if iw<=ww then\n            w(7)=iw: v(7)=iv\n            for i7=0 to 1:m(7)=i7:j=6\n             if i7=1 then\n              iw=w(7)+data(j*3+1):iv=v(7)+data(j*3+2)\n              if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n             end if 'i7\n             if iw<=ww then\n              w(8)=iw: v(8)=iv\n              for i8=0 to 1:m(8)=i8:j=7\n               if i8=1 then\n                iw=w(8)+data(j*3+1):iv=v(8)+data(j*3+2)\n                if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n               end if 'i8\n               if iw<=ww then\n                w(9)=iw: v(9)=iv\n                for i9=0 to 1:m(9)=i9:j=8\n                 if i9=1 then\n                  iw=w(9)+data(j*3+1):iv=v(9)+data(j*3+2)\n                  if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                 end if 'i9\n                 if iw<=ww then\n                  w(10)=iw: v(10)=iv\n                  for i10=0 to 1:m(10)=i10:j=9\n                   if i10=1 then\n                    iw=w(10)+data(j*3+1):iv=v(10)+data(j*3+2)\n                    if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                   end if 'i10\n                   if iw<=ww then\n                    w(11)=iw: v(11)=iv\n                    for i11=0 to 1:m(11)=i11:j=10\n                     if i11=1 then\n                      iw=w(11)+data(j*3+1):iv=v(11)+data(j*3+2)\n                      if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                     end if 'i11\n                     if iw<=ww then\n                      w(12)=iw: v(12)=iv\n                      for i12=0 to 1:m(12)=i12:j=11\n                       if i12=1 then\n                        iw=w(12)+data(j*3+1):iv=v(12)+data(j*3+2)\n                        if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                       end if 'i12\n                       if iw<=ww then\n                        w(13)=iw: v(13)=iv\n                        for i13=0 to 1:m(13)=i13:j=12\n                         if i13=1 then\n                          iw=w(13)+data(j*3+1):iv=v(13)+data(j*3+2)\n                          if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                         end if 'i13\n                         if iw<=ww then\n                          w(14)=iw: v(14)=iv\n                          for i14=0 to 1:m(14)=i14:j=13\n                           if i14=1 then\n                            iw=w(14)+data(j*3+1):iv=v(14)+data(j*3+2)\n                            if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                           end if 'i14\n                           if iw<=ww then\n                            w(15)=iw: v(15)=iv\n                            for i15=0 to 1:m(15)=i15:j=14\n                             if i15=1 then\n                              iw=w(15)+data(j*3+1):iv=v(15)+data(j*3+2)\n                              if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                             end if 'i15\n                             if iw<=ww then\n                              w(16)=iw: v(16)=iv\n                              for i16=0 to 1:m(16)=i16:j=15\n                               if i16=1 then\n                                iw=w(16)+data(j*3+1):iv=v(16)+data(j*3+2)\n                                if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                               end if 'i16\n                               if iw<=ww then\n                                w(17)=iw: v(17)=iv\n                                for i17=0 to 1:m(17)=i17:j=16\n                                 if i17=1 then\n                                  iw=w(17)+data(j*3+1):iv=v(17)+data(j*3+2)\n                                  if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                                 end if 'i17\n                                 if iw<=ww then\n                                  w(18)=iw: v(18)=iv\n                                  for i18=0 to 1:m(18)=i18:j=17\n                                   if i18=1 then\n                                    iw=w(18)+data(j*3+1):iv=v(18)+data(j*3+2)\n                                    if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                                   end if 'i18\n                                   if iw<=ww then\n                                    w(19)=iw: v(19)=iv\n                                    for i19=0 to 1:m(19)=i19:j=18\n                                     if i19=1 then\n                                      iw=w(19)+data(j*3+1):iv=v(19)+data(j*3+2)\n                                      if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                                     end if 'i19\n                                     if iw<=ww then\n                                      w(20)=iw: v(20)=iv\n                                      for i20=0 to 1:m(20)=i20:j=19\n                                       if i20=1 then\n                                        iw=w(20)+data(j*3+1):iv=v(20)+data(j*3+2)\n                                        if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                                       end if 'i20\n                                       if iw<=ww then\n                                        w(21)=iw: v(21)=iv\n                                        for i21=0 to 1:m(21)=i21:j=20\n                                         if i21=1 then\n                                          iw=w(21)+data(j*3+1):iv=v(21)+data(j*3+2)\n                                          if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                                         end if 'i21\n                                         if iw<=ww then\n                                          w(22)=iw: v(22)=iv\n                                          for i22=0 to 1:m(22)=i22:j=21\n                                           nn=nn+1\n                                           if i22=1 then\n                                            iw=w(22)+data(j*3+1):iv=v(22)+data(j*3+2)\n                                            if iv>xv and iw<=ww then xw=iw:xv=iv:l=m\n                                           end if 'i22\n                                           if iw<=ww then\n                                           end if 'i22\n                                          next:m(22)=0\n                                         end if 'i21\n                                        next:m(21)=0\n                                       end if 'i20\n                                      next:m(20)=0\n                                     end if 'i19\n                                    next:m(19)=0\n                                   end if 'i18\n                                  next:m(18)=0\n                                 end if 'i17\n                                next:m(17)=0\n                               end if 'i16\n                              next:m(16)=0\n                             end if 'i15\n                            next:m(15)=0\n                           end if 'i14\n                          next:m(14)=0\n                         end if 'i13\n                        next:m(13)=0\n                       end if 'i12\n                      next:m(12)=0\n                     end if 'i11\n                    next:m(11)=0\n                   end if 'i10\n                  next:m(10)=0\n                 end if 'i9\n                next:m(9)=0\n               end if 'i8\n              next:m(8)=0\n             end if 'i7\n            next:m(7)=0\n           end if 'i6\n          next:m(6)=0\n         end if 'i5\n        next:m(5)=0\n       end if 'i4\n      next:m(4)=0\n     end if 'i3\n    next:m(3)=0\n   end if 'i2\n  next:m(2)=0\n end if 'i1\nnext:m(1)=0\nfor i=1 to 22\n if l(i)=1 then wlist=wlist&vbCrlf&data((i-1)*3)\nnext\nMsgbox mid(wlist,3)&vbCrlf&vbCrlf&\"weight=\"&xw&vbCrlf&\"value=\"&xv,,\"Knapsack - nn=\"&nn\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg. It considers the weight and value of each item, ensuring the total weight does not exceed the limit while maximizing the total value. The solution is non-recursive and runs 13 times faster than its recursive counterpart. Only whole units of any item can be taken.","id":1203}
    {"lang_cluster":"VBScript","source_code":"\n' Sort a list of object identifiers - VBScript\nfunction myCompare(x,y)\n\tdim i,b\n\tsx=split(x,\".\")\n\tsy=split(y,\".\")\n\tb=false\n\tfor i=0 to ubound(sx)\n\t\tif i > ubound(sy) then b=true: exit for\n\t\tselect case sgn(int(sx(i))-int(sy(i)))\n\t\t\tcase  1: b=true:  exit for\n\t\t\tcase -1: b=false: exit for\n\t\tend select\n\tnext\n\tmyCompare=b\nend function\n\nfunction bubbleSort(t)\n\tdim i,n\n\tn=ubound(t) \n\tdo\n\t\tchanged=false\n\t\tn= n-1\n\t\tfor i=0 to n\n\t\t\tif myCompare(t(i),t(i+1)) then\n\t\t\t\ttmp=t(i): t(i)=t(i+1): t(i+1)=tmp\n\t\t\t\tchanged=true\n\t\t\tend if\n\t\tnext\n\tloop until not changed\n\tbubbleSort=t\nend function\n \na=array( _\n\t\"1.3.6.1.4.1.11.2.17.19.3.4.0.10\", _\n\t\"1.3.6.1.4.1.11.2.17.5.2.0.79\", _\n\t\"1.3.6.1.4.1.11.2.17.19.3.4.0.4\", _\n\t\"1.3.6.1.4.1.11150.3.4.0.1\", _\n\t\"1.3.6.1.4.1.11.2.17.19.3.4.0.1\", _\n\t\"1.3.6.1.4.1.11150.3.4.0\")\nbubbleSort a\nwscript.echo join(a,vbCrlf)\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":1204}
    {"lang_cluster":"VBScript","source_code":"\nFunction send_mail(from,recipient,cc,subject,message)\n\tWith CreateObject(\"CDO.Message\")\n\t\t.From = from\n\t\t.To = recipient\n\t\t.CC = cc\n\t\t.Subject = subject\n\t\t.Textbody = message\n\t\t.Configuration.Fields.Item _\n\t\t\t(\"http:\/\/schemas.microsoft.com\/cdo\/configuration\/sendusing\") = 2\n\t\t.Configuration.Fields.Item _\n\t\t\t(\"http:\/\/schemas.microsoft.com\/cdo\/configuration\/smtpserver\") = _\n\t\t        \"mystmpserver\"\n\t\t.Configuration.Fields.Item _\n\t\t    (\"http:\/\/schemas.microsoft.com\/cdo\/configuration\/smtpserverport\") = 25\n\t\t.Configuration.Fields.Update\n\t\t.Send\n\tEnd With\nEnd Function\n\nCall send_mail(\"Alerts@alerts.org\",\"jkspeed@jkspeed.org\",\"\",\"Test Email\",\"this is a test message\")\n\n","human_summarization":"Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.","id":1205}
    {"lang_cluster":"VBScript","source_code":"\nFor i = 0 To 20\n\tWScript.StdOut.WriteLine Oct(i)\nNext\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":1206}
    {"lang_cluster":"VBScript","source_code":"\nfunction Squish( s1 )\n\tdim sRes\n\tsRes = vbNullString\n\tdim i, c\n\tfor i = 1 to len( s1 )\n\t\tc = lcase( mid( s1, i, 1 ))\n\t\tif instr( \"abcdefghijklmnopqrstuvwxyz0123456789\", c ) then\n\t\t\tsRes = sRes & c\n\t\tend if\n\tnext\n\tSquish = sRes\nend function\n\t\t\nfunction isPalindrome( s1 )\n\tdim squished\n\tsquished = Squish( s1 )\n\tisPalindrome = ( squished = StrReverse( squished ) )\nend function\nwscript.echo isPalindrome( \"My dog has fleas\")\nwscript.echo isPalindrome( \"Madam, I'm Adam.\")\nwscript.echo isPalindrome( \"1 on 1\")\nwscript.echo isPalindrome( \"In girum imus nocte et consumimur igni\")\n\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":1207}
    {"lang_cluster":"Zig","source_code":"\n\nvar s = \"socat\".*;\nstd.mem.reverse(u8, &s);\n\nvar s = \"socat\".*;\nstd.mem.reverse(u8, s[0..]);\n\n\n\u2191 https:\/\/bugs.openjdk.org\/browse\/JDK-8291660\n\n\n\n\n\n","human_summarization":"take a string input, reverse it, and handle Unicode combining characters properly. The string is dereferenced to an array using `.*` and reversed in-place using `std.mem.reverse`. The final reversed string is stored in `s`. Tested on version 0.9.0.","id":1208}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\npub fn main() !void {\n    const RndGen = std.rand.DefaultPrng;\n    var rnd = RndGen.init(42);\n    \/\/ possible improvement: make rng fair\n    var rand_num1: u5 = undefined;\n    var rand_num2: u5 = undefined;\n    while (true) {\n        rand_num1 = rnd.random().int(u5)\u00a0% 20;\n        try std.io.getStdOut().writer().print(\"{d}\\n\", .{rand_num1});\n        if (rand_num1 == 10)\n            break;\n        rand_num2 = rnd.random().int(u5)\u00a0% 20;\n        try std.io.getStdOut().writer().print(\"{d}\\n\", .{rand_num2});\n    }\n}\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":1209}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\npub fn main() !void {\n    var in = try std.fs.cwd().openFile(\"input.txt\", .{});\n    defer in.close();\n    var out = try std.fs.cwd().openFile(\"output.txt\", .{ .mode = .write_only });\n    defer out.close();\n    var file_reader = in.reader();\n    var file_writer = out.writer();\n    var buf: [100]u8 = undefined;\n    var read: usize = 1;\n    while (read > 0) {\n        read = try file_reader.readAll(&buf);\n        try file_writer.writeAll(buf[0..read]);\n    }\n}\n\n\n\n","human_summarization":"demonstrate reading the contents of \"input.txt\" file into a variable and then writing this variable's contents into a new file called \"output.txt\".","id":1210}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\npub fn main() !void {\n    const stdout_wr = std.io.getStdOut().writer();\n    const string = \"alphaBETA\";\n    var lower: [string.len]u8 = undefined;\n    var upper: [string.len]u8 = undefined;\n    for (string) |char, i| {\n        lower[i] = std.ascii.toLower(char);\n        upper[i] = std.ascii.toUpper(char);\n    }\n    try stdout_wr.print(\"lower: {s}\\n\", .{lower});\n    try stdout_wr.print(\"upper: {s}\\n\", .{upper});\n\n    \/\/ TODO use https:\/\/github.com\/jecolon\/zigstr\n}\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":1211}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\npub fn main() !void {\n    const stdout_wr = std.io.getStdOut().writer();\n    var i: u8 = 1;\n    while (i <= 10)\u00a0: (i += 1) {\n        try stdout_wr.print(\"{d}\", .{i});\n        if (i == 10) {\n            try stdout_wr.writeAll(\"\\n\");\n        } else {\n            try stdout_wr.writeAll(\", \");\n        }\n    }\n}\n\n\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":1212}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\nconst Allocator = std.mem.Allocator;\npub fn main() !void {\n    const stdout = std.io.getStdOut().writer();\n\n    var gpa = std.heap.GeneralPurposeAllocator(.{}){};\n    defer {\n        const ok = gpa.deinit();\n        std.debug.assert(ok == .ok);\n    }\n    const allocator = gpa.allocator();\n\n    {\n        const nc = try getCombs(allocator, 1, 7, true);\n        defer allocator.free(nc.combinations);\n        try stdout.print(\"{d} unique solutions in 1 to 7\\n\", .{nc.num});\n        try stdout.print(\"{any}\\n\", .{nc.combinations});\n    }\n    {\n        const nc = try getCombs(allocator, 3, 9, true);\n        defer allocator.free(nc.combinations);\n        try stdout.print(\"{d} unique solutions in 3 to 9\\n\", .{nc.num});\n        try stdout.print(\"{any}\\n\", .{nc.combinations});\n    }\n    {\n        const nc = try getCombs(allocator, 0, 9, false);\n        defer allocator.free(nc.combinations);\n        try stdout.print(\"{d} non-unique solutions in 0 to 9\\n\", .{nc.num});\n    }\n}\n\/\/\/ Caller owns combinations slice memory.\nfn getCombs(allocator: Allocator, low: u16, high: u16, unique: bool) !struct { num: usize, combinations: [][7]usize } {\n    var num: usize = 0;\n    var valid_combinations = std.ArrayList([7]usize).init(allocator);\n    for (low..high + 1) |a|\n        for (low..high + 1) |b|\n            for (low..high + 1) |c|\n                for (low..high + 1) |d|\n                    for (low..high + 1) |e|\n                        for (low..high + 1) |f|\n                            for (low..high + 1) |g|\n                                if (validComb(a, b, c, d, e, f, g))\n                                    if (!unique or try isUnique(allocator, a, b, c, d, e, f, g)) {\n                                        num += 1;\n                                        try valid_combinations.append([7]usize{ a, b, c, d, e, f, g });\n                                    };\n    return .{ .num = num, .combinations = try valid_combinations.toOwnedSlice() };\n}\nfn isUnique(allocator: Allocator, a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize) !bool {\n    var data = std.AutoArrayHashMap(usize, void).init(allocator);\n    defer data.deinit();\n    try data.put(a, {});\n    try data.put(b, {});\n    try data.put(c, {});\n    try data.put(d, {});\n    try data.put(e, {});\n    try data.put(f, {});\n    try data.put(g, {});\n    return data.count() == 7;\n}\nfn validComb(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize) bool {\n    const square1 = a + b;\n    const square2 = b + c + d;\n    const square3 = d + e + f;\n    const square4 = f + g;\n    return square1 == square2 and square2 == square3 and square3 == square4;\n}\n\n\n","human_summarization":"The code finds all possible solutions for a puzzle where seven variables, represented by letters a through g, are replaced with decimal digits within a given range. The sum of the variables in each of the four squares should be equal. The code generates all unique solutions for ranges 1-7 and 3-9, and counts the number of solutions, including non-unique ones, for the range 0-9. The code is a translation of a Go solution into Zig, with manual memory management and error handling.","id":1213}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n \nvar arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);\n \nconst allocator = arena.allocator();\n \npub fn LinkedList(comptime Value: type) type {\n    return struct {\n        const This = @This();\n \n        const Node = struct {\n            value: Value,\n            next: ?*Node,\n        };\n \n        head: ?*Node,\n        tail: ?*Node,\n \n        pub fn init() This {\n            return LinkedList(Value) {\n                .head = null,\n                .tail = null,\n            };\n        }\n \n        pub fn add(this: *This, value: Value) !void {\n            var newNode = try allocator.create(Node);\n \n            newNode.* = .{ .value = value, .next = null };\n \n            if (this.tail) |tail| {\n                tail.next = newNode;\n                this.tail = newNode;\n            } else if (this.head) |head| {\n                head.next = newNode;\n                this.tail = newNode;\n            } else {\n                this.head = newNode;\n            }\n        }\n    };\n}\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":1214}
    {"lang_cluster":"Zig","source_code":"Library: raylib\nconst std = @import(\"std\");\nconst c = @cImport({\n    @cInclude(\"raylib.h\");\n});\n\npub fn main() !void {\n    c.SetConfigFlags(c.FLAG_WINDOW_RESIZABLE | c.FLAG_VSYNC_HINT);\n    c.InitWindow(600, 480, \"cuboid\");\n    defer c.CloseWindow();\n\n    const camera = c.Camera3D{\n        .position = .{ .x = 4.5, .y = 4.5, .z = 4.5 },\n        .target = .{ .x = 0, .y = 0, .z = 0 },\n        .up = .{ .x = 0, .y = 1, .z = 0 },\n        .fovy = 45.0,\n        .projection = c.CAMERA_PERSPECTIVE,\n    };\n\n    c.SetTargetFPS(60);\n\n    while (!c.WindowShouldClose()) {\n        c.BeginDrawing();\n        defer c.EndDrawing();\n\n        c.ClearBackground(c.BLACK);\n\n        {\n            c.BeginMode3D(camera);\n            defer c.EndMode3D();\n\n            c.DrawCubeWires(.{ .x = 0, .y = 0, .z = 0 }, 2, 3, 4, c.LIME);\n        }\n    }\n}\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":1215}
    {"lang_cluster":"Zig","source_code":"\n\/\/ Warning: modifies the buffer in-place (returns pointer to in)\nfn rot13(in: [] u8) []u8 {\n    for (in) |*c| {\n        var d\u00a0: u8 = c.*;\n        var x\u00a0: u8 = d;\n        x = if (@subWithOverflow(u8, d | 32, 97, &x) ) x else x;\n        if (x < 26) {\n            x = (x + 13)\u00a0% 26 + 65 + (d & 32);\n            c.* = x;\n        }        \n    }\n    return in;\n}\n\nconst msg: [:0] const u8 = \n    \\\\Lbh xabj vg vf tbvat gb or n onq qnl\n    \\\\ jura gur yrggref va lbhe nycunorg fbhc\n    \\\\ fcryy Q-V-F-N-F-G-R-E.\n;\n\n\/\/ need to copy the const string to a buffer\n\/\/ before we can modify it in-place\n\/\/https:\/\/zig.news\/kristoff\/what-s-a-string-literal-in-zig-31e9\n\nvar buf: [500]u8 = undefined;\nfn assignStr(out: []u8, str: [:0]const u8) void {\n    for (str) |c, i| {\n        out[i] = c;\n    }\n    out[str.len] = 0;\n}\n\nconst print = @import(\"std\").debug.print;\n\npub fn main() void {\n    assignStr(&buf, msg);\n    print(\"rot13={s}\\n\",.{rot13(&buf)});\n}\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":1216}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\npub fn main() !void {\n    const stdout_wr = std.io.getStdOut().writer();\n    var i: u8 = 1;\n    while (i < 5)\u00a0: (i += 1) {\n        var j: u8 = 1;\n        while (j <= i)\u00a0: (j += 1)\n            try stdout_wr.writeAll(\"*\");\n        try stdout_wr.writeAll(\"\\n\");\n    }\n}\n\n\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":1217}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\nvar arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);\n\nconst allocator = arena.allocator();\n\npub fn LinkedList(comptime Value: type) type {\n    return struct {\n        const This = @This();\n\n        const Node = struct {\n            value: Value,\n            next: ?*Node,\n        };\n\n        head: ?*Node,\n        tail: ?*Node,\n\n        pub fn init() This {\n            return LinkedList(Value) {\n                .head = null,\n                .tail = null,\n            };\n        }\n\n        pub fn add(this: *This, value: Value) !void {\n            var newNode = try allocator.create(Node);\n\n            newNode.* = .{ .value = value, .next = null };\n\n            if (this.tail) |tail| {\n                tail.next = newNode;\n                this.tail = newNode;\n            } else if (this.head) |head| {\n                head.next = newNode;\n                this.tail = newNode;\n            } else {\n                this.head = newNode;\n            }\n        }\n    };\n}\n\n\nvar l1 = LinkedList(i32).init();\n\n\ntry list.add(1);\n\n\n\n\n","human_summarization":"Defines a method to insert an element into a singly-linked list after a given element. The method is then used to insert an element 'C' into a list comprised of elements 'A' and 'B', specifically after element 'A'.","id":1218}
    {"lang_cluster":"Zig","source_code":"\n\nconst stdout = @import(\"std\").io.getStdOut().outStream();\n\npub fn factorial(comptime Num: type, n: i8) ?Num {\n    return if (@typeInfo(Num)\u00a0!= .Int)\n        @compileError(\"factorial called with num-integral type: \" ++ @typeName(Num))\n    else if (n < 0)\n        null\n    else calc: {\n        var i: i8 = 1;\n        var fac: Num = 1;\n        while (i <= n)\u00a0: (i += 1) {\n            if (@mulWithOverflow(Num, fac, i, &fac))\n                break :calc null;\n        } else break :calc fac;\n    };\n}\n\npub fn main() !void {\n    try stdout.print(\"-1! = {}\\n\", .{factorial(i32, -1)});\n    try stdout.print(\"0! = {}\\n\", .{factorial(i32, 0)});\n    try stdout.print(\"5! = {}\\n\", .{factorial(i32, 5)});\n    try stdout.print(\"33!(64 bit) = {}\\n\", .{factorial(i64, 33)}); \/\/ not vailid i64 factorial\n    try stdout.print(\"33! = {}\\n\", .{factorial(i128, 33)}); \/\/ biggest facorial possible\n    try stdout.print(\"34! = {}\\n\", .{factorial(i128, 34)}); \/\/ will overflow\n}\n\n","human_summarization":"The code implements a function to calculate the factorial of a given positive integer number. The factorial is calculated either iteratively or recursively. The function supports all integer data types, checks for overflow and negative numbers, and returns null in case of a domain error. It also relates to the task of generating Primorial numbers.","id":1219}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\nconst Vector = std.meta.Vector;\n\npub fn main() !void {\n    const a: Vector(3, i32) = [_]i32{1, 3, -5};\n    const b: Vector(3, i32) = [_]i32{4, -2, -1};\n    var dot: i32 = @reduce(.Add, a*b);\n\n    try std.io.getStdOut().writer().print(\"{d}\\n\", .{dot});\n}\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":1220}
    {"lang_cluster":"Zig","source_code":"Library: raylib\nconst std = @import(\"std\");\nconst c = @cImport({\n    @cInclude(\"raylib.h\");\n});\n\npub fn main() !void {\n    c.SetConfigFlags(c.FLAG_WINDOW_RESIZABLE | c.FLAG_VSYNC_HINT);\n    c.InitWindow(600, 480, \"Draw a Sphere\");\n    defer c.CloseWindow();\n\n    const camera = c.Camera3D{\n        .position = .{ .x = 4.5, .y = 4.5, .z = 4.5 },\n        .target = .{ .x = 0, .y = 0, .z = 0 },\n        .up = .{ .x = 0, .y = 1, .z = 0 },\n        .fovy = 45.0,\n        .projection = c.CAMERA_PERSPECTIVE,\n    };\n\n    c.SetTargetFPS(60);\n\n    while (!c.WindowShouldClose()) {\n        c.BeginDrawing();\n        defer c.EndDrawing();\n\n        c.ClearBackground(c.BLACK);\n\n        {\n            c.BeginMode3D(camera);\n            defer c.EndMode3D();\n\n            c.DrawSphereWires(.{ .x = 0, .y = 0, .z = 0 }, 2, 20, 20, c.LIME);\n        }\n    }\n}\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":1221}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\npub fn main() !void {\n    const cnt_lower = 26;\n    var lower: [cnt_lower]u8 = undefined;\n    comptime var i = 0;\n    inline while (i < cnt_lower)\u00a0: (i += 1)\n        lower[i] = i + 'a';\n\n    const stdout_wr = std.io.getStdOut().writer();\n    for (lower) |l|\n        try stdout_wr.print(\"{c} \", .{l});\n    try stdout_wr.writeByte('\\n');\n}\n\n\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":1222}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\nconst math = std.math; \/\/ Save some typing, reduce clutter. Otherwise math.sin() would be std.math.sin() etc.\n\npub fn main() !void {\n    \/\/ Coordinates are found here:\n    \/\/     http:\/\/www.airport-data.com\/airport\/BNA\/\n    \/\/     http:\/\/www.airport-data.com\/airport\/LAX\/\n\n    const bna = LatLong{\n        .lat = .{ .d = 36, .m = 7, .s = 28.10 },\n        .long = .{ .d = 86, .m = 40, .s = 41.50 },\n    };\n\n    const lax = LatLong{\n        .lat = .{ .d = 33, .m = 56, .s = 32.98 },\n        .long = .{ .d = 118, .m = 24, .s = 29.05 },\n    };\n\n    const distance = calcGreatCircleDistance(bna, lax);\n\n    std.debug.print(\"","human_summarization":"implement the Haversine formula to calculate the great-circle distance between Nashville International Airport (BNA) and Los Angeles International Airport (LAX) using their respective longitudes and latitudes. The earth's radius is approximated as either 6371.0 km or 6372.8 km, resulting in slightly different distances. The code also includes the use of Zig struct type for initialization and method calling.","id":1223}
    {"lang_cluster":"Zig","source_code":"const std = @import(\"std\");\n\npub fn print(from: u32, to: u32) void {\n    std.log.info(\"Moving disk from rod {} to rod {}\", .{ from, to });\n}\n\npub fn move(n: u32, from: u32, via: u32, to: u32) void {\n    if (n > 1) {\n        move(n - 1, from, to, via);\n        print(from, to);\n        move(n - 1, via, from, to);\n    } else {\n        print(from, to);\n    }\n}\n\npub fn main() !void {\n    move(4, 1, 2, 3);\n}\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":1224}
    {"lang_cluster":"Zig","source_code":"\n\nconst std = @import(\"std\");\n\npub fn binomial(n: u32)\u00a0?[]const u64 {\n    if (n >= rmax)\n        return null\n    else {\n        const k = n * (n + 1) \/ 2;\n        return pascal[k .. k + n + 1];\n    }\n}\n\npub fn nCk(n: u32, k: u32) ?u64 {\n    if (n >= rmax)\n        return null\n    else if (k > n)\n        return 0\n    else {\n        const j = n * (n + 1) \/ 2;\n        return pascal[j + k];\n    }\n}        \n\nconst rmax = 68;\n\nconst pascal = build: {\n    @setEvalBranchQuota(100_000);\n    var coefficients: [(rmax * (rmax + 1)) \/ 2]u64 = undefined;\n    coefficients[0] = 1;\n    var j: u32 = 0;\n    var k: u32 = 1;\n    var n: u32 = 1;\n    while (n < rmax)\u00a0: (n += 1) {\n        var prev = coefficients[j .. j + n];\n        var next = coefficients[k .. k + n + 1];\n        next[0] = 1;\n        var i: u32 = 1;\n        while (i < n)\u00a0: (i += 1)\n            next[i] = prev[i] + prev[i - 1];\n        next[i] = 1;\n        j = k;\n        k += n + 1;\n    }\n    break :build coefficients;\n};\n\ntest \"n choose k\" {\n    const expect = std.testing.expect;\n    try expect(nCk(10, 5).? == 252);\n    try expect(nCk(10, 11).? == 0);\n    try expect(nCk(10, 10).? == 1);\n    try expect(nCk(67, 33).? == 14226520737620288370); \n    try expect(nCk(68, 34) == null);\n}\n\n\n","human_summarization":"The code calculates any binomial coefficient, with a specific focus on outputting the binomial coefficient of 5 choose 3, which is 10. It uses a specific formula for the calculation and is capable of handling tasks related to combinations, permutations, and their variations with and without replacement. The code has been optimized for a 64-bit machine by precomputing all possible values of nCk, allowing for table lookup at runtime. It also handles out-of-range values by returning null. The maximum representable value it can compute is 67 choose 33. The functionality can be tested through a unit test module.","id":1225}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\npub fn main() !void {\n    var a: u8 = 0;\n    \/\/ no do-while in syntax, trust the optimizer to do\n    \/\/ correct Loop inversion https:\/\/en.wikipedia.org\/wiki\/Loop_inversion\n    \/\/ If the variable `alive` is independent to other variables and not in\n    \/\/ diverging control flow, then the optimization is possible in general.\n    var alive = true;\n    while (alive == true or a\u00a0% 6\u00a0!= 0) {\n        alive = false;\n        a += 1;\n        try std.io.getStdOut().writer().print(\"{d}\\n\", .{a});\n    }\n}\n\n\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":1226}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\nfn printResults(alloc: std.mem.Allocator, string: []const u8) !void {\n    const cnt_codepts_utf8 = try std.unicode.utf8CountCodepoints(string);\n    \/\/ There is no sane and portable extended ascii, so the best\n    \/\/ we get is counting the bytes and assume regular ascii.\n    const cnt_bytes_utf8 = string.len;\n    const stdout_wr = std.io.getStdOut().writer();\n    try stdout_wr.print(\"utf8  codepoints = {d}, bytes = {d}\\n\", .{ cnt_codepts_utf8, cnt_bytes_utf8 });\n\n    const utf16str = try std.unicode.utf8ToUtf16LeWithNull(alloc, string);\n    const cnt_codepts_utf16 = try std.unicode.utf16CountCodepoints(utf16str);\n    const cnt_2bytes_utf16 = try std.unicode.calcUtf16LeLen(string);\n    try stdout_wr.print(\"utf16 codepoints = {d}, bytes = {d}\\n\", .{ cnt_codepts_utf16, 2 * cnt_2bytes_utf16 });\n}\n\npub fn main() !void {\n    var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator);\n    defer arena_instance.deinit();\n    const arena = arena_instance.allocator();\n    const string1: []const u8 = \"Hello, world!\";\n    try printResults(arena, string1);\n    const string2: []const u8 = \"m\u00f8\u00f8se\";\n    try printResults(arena, string2);\n    const string3: []const u8 = \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\";\n    try printResults(arena, string3);\n    \/\/ \\u{332} is underscore of previous character, which the browser may not\n    \/\/ copy correctly\n    const string4: []const u8 = \"J\\u{332}o\\u{332}s\\u{332}e\\u{301}\\u{332}\";\n    try printResults(arena, string4);\n}\n\n","human_summarization":"calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.","id":1227}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\npub fn main() !void {\n    try std.io.getStdOut().writer().writeAll(\"Hello world!\");\n}\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":1228}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\nconst print = std.debug.print;\n\npub fn CusipCheckDigit(cusip: *const [9:0]u8) bool {\n    var i: usize = 0;\n    var sum: i32 = 0;\n    while (i < 8) {\n        const c = cusip[i];\n        var v: i32 = undefined;\n        if (c <= '9' and c >= '0') {\n            v = c - 48;\n        }\n        else if (c <= 'Z' and c >= 'A') {\n            v = c - 55;\n        }\n        else if (c == '*') {\n            v = 36;\n        }\n        else if (c == '@') {\n            v = 37;\n        }\n        else if (c == '#') {\n            v = 38;\n        }\n        else {\n            return false;\n        }\n        if (i % 2 == 1) {\n            v *= 2;\n        }\n        sum = sum + @divFloor(v, 10) + @mod(v, 10);\n        i += 1;\n    }\n    return (cusip[8] - 48 == @mod((10 - @mod(sum, 10)), 10));\n}\n\npub fn main() void {\n    const cusips = [_]*const [9:0]u8 {\n        \"037833100\",\n        \"17275R102\",\n        \"38259P508\",\n        \"594918104\",\n        \"68389X106\",\n        \"68389X105\"\n    };\n    for (cusips) |cusip| {\n        print(\"{s} -> {}\\n\", .{cusip, CusipCheckDigit(cusip)});\n    }\n}\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":1229}
    {"lang_cluster":"Zig","source_code":"const warn = @import(\"std\").debug.warn;\n\npub fn main() void {\n    const items = [_]i16{ 0, 1, 1, 2, 3, 5, 8 };\n\n     for (items) |i| {\n        warn(\"{}\\n\", .{i});\n    }\n}","human_summarization":"Iterates through each element in a collection in order and prints it, using a \"for each\" loop or another loop if \"for each\" is not available in the language.","id":1230}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\npub fn main() void {\n  const string = \"Hello,How,Are,You,Today\";\n  var tokens = std.mem.split(u8, string, \",\");\n  std.debug.print(\"{s}\", .{tokens.next().?});\n  while (tokens.next()) |token| {\n    std.debug.print(\".{s}\", .{token});\n  }\n}\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":1231}
    {"lang_cluster":"Zig","source_code":"\npub fn gcd(u: anytype, v: anytype) @TypeOf(u) {\n  if (@typeInfo(@TypeOf(u))\u00a0!= .Int) {\n    @compileError(\"non-integer type used on gcd: \" ++ @typeName(@TypeOf(u)));\n  }\n  if (@typeInfo(@TypeOf(v))\u00a0!= .Int) {\n    @compileError(\"non-integer type used on gcd: \" ++ @typeName(@TypeOf(v)));\n  }\n  return if (v\u00a0!= 0) gcd(v, @mod(u,v)) else u;\n}\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":1232}
    {"lang_cluster":"Zig","source_code":"\nconst print = @import(\"std\").debug.print;\npub fn main() void {\n    var i: usize = 1;\n    while (i <= 100)\u00a0: (i += 1) {\n        if (i\u00a0% 3 == 0 and i\u00a0% 5 == 0) {\n            print(\"FizzBuzz\\n\", .{});\n        } else if (i\u00a0% 3 == 0) {\n            print(\"Fizz\\n\", .{});\n        } else if (i\u00a0% 5 == 0) {\n            print(\"Buzz\\n\", .{});\n        } else {\n            print(\"{}\\n\", .{i});\n        }\n    }\n}\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":1233}
    {"lang_cluster":"Zig","source_code":"\nconst print = @import(\"std\").debug.print;\npub fn main() void {\n  const numbers = [_]u8{ 1, 2, 3, 4, 5 };\n  var sum: u8 = 0;\n  var product: u8 = 1;\n  for (numbers) |number| {\n    product *= number;\n    sum += number;\n  }\n  print(\"{} {}\\n\", .{ product, sum });\n}\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":1234}
    {"lang_cluster":"Zig","source_code":"\npub fn isLeapYear(year: anytype) bool {\n  const inttype = @TypeOf(year);\n  if (@typeInfo(inttype)\u00a0!= .Int) {\n    @compileError(\"non-integer type used on leap year: \" ++ @typeName(inttype));\n  }\n  return (if (@mod(year, @as(inttype, 100)) == 0)\n    @mod(year, @as(inttype, 400)) == 0\n  else\n    @mod(year, @as(inttype, 4)) == 0);\n}\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":1235}
    {"lang_cluster":"Zig","source_code":"\nWorks with: Zig version 0.11.0dev\nconst std = @import(\"std\");\n\npub fn main() !void {\n    const stdout = std.io.getStdOut().writer();\n\n    try stdout.writeAll(\"Police  Sanitation  Fire\\n\");\n    try stdout.writeAll(\"------  ----------  ----\\n\");\n\n    var p: usize = 2;\n    while (p <= 7) : (p += 2)\n        for (1..7 + 1) |s|\n            for (1..7 + 1) |f|\n                if (p != s and s != f and f != p and p + f + s == 12) {\n                    try stdout.print(\"  {d}         {d}         {d}\\n\", .{ p, s, f });\n                };\n}\n\n\n","human_summarization":"generates all unique combinations of numbers between 1 and 7 (inclusive) for the police, sanitation, and fire departments in a city, such that the sum of the numbers is 12 and the police department number is even. The combinations are generated using a Zig struct iterator.","id":1236}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\nconst debug = std.debug;\nconst mem = std.mem;\n\ntest \"copy a string\" {\n    const source = \"A string.\";\n\n    \/\/ Variable `dest1` will have the same type as `source`, which is\n    \/\/ `*const [9:0]u8`.\n    const dest1 = source;\n\n    \/\/ Variable `dest2`'s type is [9]u8.\n    \/\/\n    \/\/ The difference between the two is that `dest1` string is null-terminated,\n    \/\/ while `dest2` is not.\n    var dest2: [source.len]u8 = undefined;\n    mem.copy(u8, dest2[0..], source[0..]);\n\n    debug.assert(mem.eql(u8, dest1[0..], \"A string.\"));\n    debug.assert(mem.eql(u8, dest2[0..], \"A string.\"));\n}\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":1237}
    {"lang_cluster":"Zig","source_code":"\n\nconst std = @import(\"std\");\n\nconst debug = std.debug;\nconst rand = std.rand;\nconst time = std.time;\n\ntest \"pick random element\" {\n    var pcg = rand.Pcg.init(time.milliTimestamp());\n\n    const chars = [_]u8{\n        'A', 'B', 'C', 'D',\n        'E', 'F', 'G', 'H',\n        'I', 'J', 'K', 'L',\n        'M', 'N', 'O', 'P',\n        'Q', 'R', 'S', 'T',\n        'U', 'V', 'W', 'X',\n        'Y', 'Z', '?', '!',\n        '<', '>', '(', ')',\n    };\n\n    var i: usize = 0;\n    while (i < 32)\u00a0: (i += 1) {\n        if (i\u00a0% 4 == 0) {\n            debug.warn(\"\\n  \", .{});\n        }\n        debug.warn(\"'{c}', \", .{chars[pcg.random.int(usize)\u00a0% chars.len]});\n    }\n\n    debug.warn(\"\\n\", .{});\n}\n\n","human_summarization":"demonstrate how to select a random element from a list using the PCG algorithm.","id":1238}
    {"lang_cluster":"Zig","source_code":"\nLibrary: Raylib\nWorks with: Zig version 0.11.0dev Works with: Raylib version 4.6devconst math = @import(\"std\").math;\nconst c = @cImport({\n    @cInclude(\"raylib.h\");\n});\n\npub fn main() void {\n    c.SetConfigFlags(c.FLAG_VSYNC_HINT);\n    c.InitWindow(640, 320, \"Pendulum\");\n    defer c.CloseWindow();\n\n    \/\/ Simulation constants.\n    const g = 9.81; \/\/ Gravity (should be positive).\n    const length = 5.0; \/\/ Pendulum length.\n    const theta0 = math.pi \/ 3.0; \/\/ Initial angle for which omega = 0.\n\n    const e = g * length * (1 - @cos(theta0)); \/\/ Total energy = potential energy when starting.\n\n    \/\/ Simulation variables.\n    var theta: f32 = theta0; \/\/ Current angle.\n    var omega: f32 = 0; \/\/ Angular velocity = derivative of theta.\n    var accel: f32 = -g \/ length * @sin(theta0); \/\/ Angular acceleration = derivative of omega.\n\n    c.SetTargetFPS(60);\n\n    while (!c.WindowShouldClose()) \/\/ Detect window close button or ESC key\n    {\n        const half_width = @as(f32, @floatFromInt(c.GetScreenWidth())) \/ 2;\n        const pivot = c.Vector2{ .x = half_width, .y = 0 };\n\n        \/\/ Compute the position of the mass.\n        const mass = c.Vector2{\n            .x = 300 * @sin(theta) + pivot.x,\n            .y = 300 * @cos(theta),\n        };\n\n        {\n            c.BeginDrawing();\n            defer c.EndDrawing();\n\n            c.ClearBackground(c.RAYWHITE);\n\n            c.DrawLineV(pivot, mass, c.GRAY);\n            c.DrawCircleV(mass, 20, c.GRAY);\n        }\n\n        \/\/ Update theta and omega.\n        const dt = c.GetFrameTime();\n        theta += (omega + dt * accel \/ 2) * dt;\n        omega += accel * dt;\n\n        \/\/ If, due to computation errors, potential energy is greater than total energy,\n        \/\/ reset theta to \u00b1theta0 and omega to 0.\n        if (length * g * (1 - @cos(theta)) >= e) {\n            theta = math.sign(theta) * theta0;\n            omega = 0;\n        }\n        accel = -g \/ length * @sin(theta);\n    }\n}\n\n","human_summarization":"create and animate a simple physical model of a gravity pendulum.","id":1239}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\nfn Run(comptime T: type) type {\n    return struct {\n        value: T,\n        length: usize,\n    };\n}\n\nfn encode(\n    comptime T: type,\n    input: []const T,\n    allocator: std.mem.Allocator,\n)\u00a0![]Run(T) {\n    var runs = std.ArrayList(Run(T)).init(allocator);\n    defer runs.deinit();\n\n    var previous: ?T = null;\n    var length: usize = 0;\n\n    for (input) |current| {\n        if (previous == current) {\n            length += 1;\n        } else if (previous) |value| {\n            try runs.append(.{\n                .value = value,\n                .length = length,\n            });\n            previous = current;\n            length = 1;\n        } else {\n            previous = current;\n            length += 1;\n        }\n    }\n\n    if (previous) |value| {\n        try runs.append(.{\n            .value = value,\n            .length = length,\n        });\n    }\n\n    return runs.toOwnedSlice();\n}\n\ntest encode {\n    const input =\n        \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\";\n\n    const expected = [_]Run(u8){\n        .{ .length = 12, .value = 'W' },\n        .{ .length = 1, .value = 'B' },\n        .{ .length = 12, .value = 'W' },\n        .{ .length = 3, .value = 'B' },\n        .{ .length = 24, .value = 'W' },\n        .{ .length = 1, .value = 'B' },\n        .{ .length = 14, .value = 'W' },\n    };\n\n    const allocator = std.testing.allocator;\n    const actual = try encode(u8, input, allocator);\n    defer allocator.free(actual);\n\n    try std.testing.expectEqual(expected.len, actual.len);\n    for (expected, actual) |e, a| {\n        try std.testing.expectEqual(e.length, a.length);\n        try std.testing.expectEqual(e.value, a.value);\n    }\n}\n\nfn decode(\n    comptime T: type,\n    runs: []const Run(T),\n    allocator: std.mem.Allocator,\n)\u00a0![]T {\n    var values = std.ArrayList(T).init(allocator);\n    defer values.deinit();\n    for (runs) |r|\n        try values.appendNTimes(r.value, r.length);\n    return values.toOwnedSlice();\n}\n\ntest decode {\n    const runs = [_]Run(u8){\n        .{ .length = 12, .value = 'W' },\n        .{ .length = 1, .value = 'B' },\n        .{ .length = 12, .value = 'W' },\n        .{ .length = 3, .value = 'B' },\n        .{ .length = 24, .value = 'W' },\n        .{ .length = 1, .value = 'B' },\n        .{ .length = 14, .value = 'W' },\n    };\n\n    const allocator = std.testing.allocator;\n    const decoded = try decode(u8, &runs, allocator);\n    defer allocator.free(decoded);\n\n    try std.testing.expectEqualStrings(\n        \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\",\n        decoded,\n    );\n}\n\npub fn main() !void {\n    var gpa = std.heap.GeneralPurposeAllocator(.{}){};\n    defer std.debug.assert(gpa.deinit() == .ok);\n\n    const allocator = gpa.allocator();\n    var input = std.ArrayList(u8).init(allocator);\n    defer input.deinit();\n\n    const stdout = std.io.getStdOut().writer();\n    const stdin = std.io.getStdIn().reader();\n    try stdout.print(\"Input: \", .{});\n    try stdin.streamUntilDelimiter(input.writer(), '\\n', null);\n\n    const runs = try encode(u8, input.items, allocator);\n    defer allocator.free(runs);\n\n    try stdout.print(\"Encoded:\\n\", .{});\n    for (runs) |r|\n        try stdout.print(\"  {}\\n\", .{r});\n\n    const decoded = try decode(u8, runs, allocator);\n    defer allocator.free(decoded);\n\n    try stdout.print(\"Decoded: {s}\\n\", .{decoded});\n}\n\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":1240}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\nconst debug = std.debug;\nconst heap = std.heap;\nconst mem = std.mem;\n\ntest \"string concatenation\" {\n    const hello = \"Hello,\";\n\n    debug.warn(\"\\n{}{}\\n\", .{ hello, \" world!\" });\n\n    \/\/ Method 1: Array concatenation\n    \/\/\n    \/\/ This only works if the values are known at compile-time.\n    const hello_world_at_comptime = hello ++ \" world!\";\n\n    debug.warn(\"{}\\n\", .{hello_world_at_comptime});\n\n    \/\/ Method 2: std.mem.concat\n    var buf: [128]u8 = undefined;\n    const allocator = &heap.FixedBufferAllocator.init(&buf).allocator;\n\n    const hello_world_concatenated = try mem.concat(allocator, u8, &[_][]const u8{ hello, \" world!\" });\n\n    debug.warn(\"{}\\n\", .{hello_world_concatenated});\n\n    \/\/ Method 3: std.mem.join\n    const hello_world_joined = try mem.join(allocator, \" \", &[_][]const u8{ hello, \"world!\" });\n\n    debug.warn(\"{}\\n\", .{hello_world_joined});\n}\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":1241}
    {"lang_cluster":"Zig","source_code":"const std = @import(\"std\");\n\nconst Node = struct {\n    frequency: usize,\n    kind: union(enum) {\n        internal: struct {\n            left: *Node,\n            right: *Node,\n        },\n        leaf: u8,\n    },\n\n    fn initLeaf(frequency: usize, ch: u8) Node {\n        return .{\n            .frequency = frequency,\n            .kind = .{ .leaf = ch },\n        };\n    }\n\n    fn initInternal(\n        allocator: std.mem.Allocator,\n        left_child: Node,\n        right_child: Node,\n    ) !Node {\n        const left = try allocator.create(Node);\n        const right = try allocator.create(Node);\n        left.* = left_child;\n        right.* = right_child;\n        return .{\n            .frequency = left_child.frequency + right_child.frequency,\n            .kind = .{ .internal = .{ .left = left, .right = right } },\n        };\n    }\n\n    fn deinit(self: Node, allocator: std.mem.Allocator) void {\n        switch (self.kind) {\n            .internal => |inner| {\n                inner.left.deinit(allocator);\n                inner.right.deinit(allocator);\n                allocator.destroy(inner.left);\n                allocator.destroy(inner.right);\n            },\n            .leaf => {},\n        }\n    }\n\n    fn compare(context: void, a: Node, b: Node) std.math.Order {\n        _ = context;\n        return std.math.order(a.frequency, b.frequency);\n    }\n};\n\npub fn main() !void {\n    const text = \"this is an example for huffman encoding\";\n\n    var gpa = std.heap.GeneralPurposeAllocator(.{}){};\n    defer std.debug.assert(gpa.deinit() == .ok);\n\n    const allocator = gpa.allocator();\n    var frequencies = std.AutoHashMap(u8, usize).init(allocator);\n    defer frequencies.deinit();\n\n    for (text) |ch| {\n        const gop = try frequencies.getOrPut(ch);\n        if (gop.found_existing) {\n            gop.value_ptr.* += 1;\n        } else {\n            gop.value_ptr.* = 1;\n        }\n    }\n\n    var prioritized_frequencies =\n        std.PriorityQueue(Node, void, Node.compare).init(allocator, {});\n    defer prioritized_frequencies.deinit();\n\n    var freq_it = frequencies.iterator();\n    while (freq_it.next()) |counted_char| {\n        try prioritized_frequencies.add(Node.initLeaf(\n            counted_char.value_ptr.*,\n            counted_char.key_ptr.*,\n        ));\n    }\n\n    while (prioritized_frequencies.len > 1) {\n        try prioritized_frequencies.add(try Node.initInternal(\n            allocator,\n            prioritized_frequencies.remove(),\n            prioritized_frequencies.remove(),\n        ));\n    }\n\n    const root = prioritized_frequencies.items[0];\n    defer root.deinit(allocator);\n\n    var codes = std.AutoArrayHashMap(u8, []const u8).init(allocator);\n    defer codes.deinit();\n\n    var arena = std.heap.ArenaAllocator.init(allocator);\n    defer arena.deinit();\n\n    try generateCodes(arena.allocator(), &root, &.{}, &codes);\n\n    const stdout = std.io.getStdOut().writer();\n    var code_it = codes.iterator();\n    while (code_it.next()) |item| {\n        try stdout.print(\"{c}: {s}\\n\", .{\n            item.key_ptr.*,\n            item.value_ptr.*,\n        });\n    }\n}\n\nfn generateCodes(\n    arena: std.mem.Allocator,\n    node: *const Node,\n    prefix: []const u8,\n    out_codes: *std.AutoArrayHashMap(u8, []const u8),\n) !void {\n    switch (node.kind) {\n        .internal => |inner| {\n            const left_prefix = try arena.alloc(u8, prefix.len + 1);\n            std.mem.copy(u8, left_prefix, prefix);\n            left_prefix[prefix.len] = '0';\n            try generateCodes(arena, inner.left, left_prefix, out_codes);\n\n            const right_prefix = try arena.alloc(u8, prefix.len + 1);\n            std.mem.copy(u8, right_prefix, prefix);\n            right_prefix[prefix.len] = '1';\n            try generateCodes(arena, inner.right, right_prefix, out_codes);\n        },\n        .leaf => |ch| {\n            try out_codes.put(ch, prefix);\n        },\n    }\n}\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":1242}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\npub fn main() !void {\n    var i: u8 = 11;\n    while (i > 0) {\n        i -= 1;\n        try std.io.getStdOut().writer().print(\"{d}\\n\", .{i});\n    }\n}\n\n\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":1243}
    {"lang_cluster":"Zig","source_code":"\nWorks with: Zig version 0.11.0dev\nconst std = @import(\"std\");\nconst Allocator = std.mem.Allocator;\n\n\/\/\/ Caller owns the returned slice memory.\nfn vigenere(allocator: Allocator, text: []const u8, key: []const u8, encrypt: bool) Allocator.Error![]u8 {\n    var dynamic_string = std.ArrayList(u8).init(allocator);\n    var key_index: usize = 0;\n    for (text) |letter| {\n        const c = if (std.ascii.isLower(letter)) std.ascii.toUpper(letter) else letter;\n        if (std.ascii.isUpper(c)) {\n            const k = key[key_index];\n            const n = if (encrypt) ((c - 'A') + (k - 'A')) else 26 + c - k;\n            try dynamic_string.append(n % 26 + 'A'); \/\/ A-Z\n            key_index += 1;\n            key_index %= key.len;\n        }\n    }\n    return dynamic_string.toOwnedSlice();\n}\n\npub fn main() anyerror!void {\n    \/\/ allocator\n    var gpa = std.heap.GeneralPurposeAllocator(.{}){};\n    defer {\n        const ok = gpa.deinit();\n        std.debug.assert(ok == .ok);\n    }\n    const allocator = gpa.allocator();\n    \/\/\n    const stdout = std.io.getStdOut().writer();\n    \/\/\n    const key = \"VIGENERECIPHER\";\n    const text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n\n    const encoded = try vigenere(allocator, text, key, true);\n    defer allocator.free(encoded);\n    try stdout.print(\"{s}\\n\", .{encoded});\n\n    const decoded = try vigenere(allocator, encoded, key, false);\n    defer allocator.free(decoded);\n    try stdout.print(\"{s}\\n\", .{decoded});\n}\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":1244}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\n\npub fn main() !void {\n    const stdout_wr = std.io.getStdOut().writer();\n    var i: u8 = 1;\n    while (i < 10)\u00a0: (i += 2)\n        try stdout_wr.print(\"{d}\\n\", .{i});\n}\n\n\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":1245}
    {"lang_cluster":"Zig","source_code":"\npub fn ack(m: u64, n: u64) u64 {\n    if (m == 0) return n + 1;\n    if (n == 0) return ack(m - 1, 1);\n    return ack(m - 1, ack(m, n - 1));\n}\n\npub fn main() !void {\n    const stdout = @import(\"std\").io.getStdOut().writer();\n\n    var m: u8 = 0;\n    while (m <= 3)\u00a0: (m += 1) {\n        var n: u8 = 0;\n        while (n <= 8)\u00a0: (n += 1)\n            try stdout.print(\"{d:>8}\", .{ack(m, n)});\n        try stdout.print(\"\\n\", .{});\n    }\n}\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":1246}
    {"lang_cluster":"Zig","source_code":"\n\nconst std = @import(\"std\");\nconst stdout = std.io.getStdOut().outStream();\n\nvar board = [_]i8{-1} ** 8;\n\ninline fn abs(x: var) @TypeOf(x) {\n    return if (x < 0) -x else x;\n}\n\nfn safe(c: i32, r: i32) bool {\n    var i: i32 = 0;\n    return while (i < c)\u00a0: (i += 1) {\n        const q = board[@intCast(u3, i)];\n        if (r == q or c == i + abs(q - r))\n            break false;\n    } else true;\n}\n\npub fn main() !void {\n    var i: i32 = 0;\n    while (i >= 0) {\n        var j = board[@intCast(u3, i)] + 1;\n        while (j < 8)\u00a0: (j += 1) {\n            if (safe(i, j)) {\n                board[@intCast(u3, i)] = j;\n                i += 1;\n                break;\n            }\n        } else {\n            board[@intCast(u3, i)] = -1;\n            i -= 1;\n        }\n        if (i == 8) { \/\/ found a solution\n            for (board) |q|\n                try stdout.print(\"{} \", .{q + 1});\n            try stdout.print(\"\\n\", .{});\n            i -= 1; \/\/ create a failure to try new solutions.\n        }\n    }\n}\n\n","human_summarization":"all 92 solutions to the eight queens puzzle for a board of size NxN, as per the problem defined in OEIS: A000170.","id":1247}
    {"lang_cluster":"Zig","source_code":"\nconst std = @import(\"std\");\nfn concat(allocator: std.mem.Allocator, a: []const u32, b: []const u32)\u00a0![]u32 {\n  const result = try allocator.alloc(u32, a.len + b.len);\n  std.mem.copy(u32, result, a);\n  std.mem.copy(u32, result[a.len..], b);\n  return result;\n}\n\npub fn main() void {\n  var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};\n  const gpa = general_purpose_allocator.allocator();\n  var array1 = [_]u32{ 1, 2, 3, 4, 5 };\n  var array2 = [_]u32{ 6, 7, 8, 9, 10, 11, 12 };\n  const array3 = concat(gpa, &array1, &array2);\n  std.debug.print(\"Array 1: {any}\\nArray 2: {any}\\nArray 3: {any}\", .{ array1, array2, array3 });\n}\n","human_summarization":"demonstrate how to concatenate two arrays.","id":1248}
    {"lang_cluster":"Go","source_code":"\n\nvar intStack []int\n\n\nintStack = append(intStack, 7)\n\n\npopped, intStack = intStack[len(intStack)-1], intStack[:len(intStack)-1]\n\n\nlen(intStack) == 0\n\n\nintStack[len(intStack)-1]\n\n\npackage main\n\nimport \"fmt\"\n\ntype stack []interface{}\n\nfunc (k *stack) push(s interface{}) {\n    *k = append(*k, s)\n}\n\nfunc (k *stack) pop() (s interface{}, ok bool) {\n    if k.empty() {\n        return\n    }\n    last := len(*k) - 1\n    s = (*k)[last]\n    *k = (*k)[:last]\n    return s, true\n}\n\nfunc (k *stack) peek() (s interface{}, ok bool) {\n    if k.empty() {\n        return\n    }\n    last := len(*k) - 1\n    s = (*k)[last]\n    return s, true\n}\n\nfunc (k *stack) empty() bool {\n    return len(*k) == 0\n}\n\nfunc main() {\n    var s stack\n    fmt.Println(\"new stack:\", s)\n    fmt.Println(\"empty?\", s.empty())\n    s.push(3)\n    fmt.Println(\"push 3. stack:\", s)\n    fmt.Println(\"empty?\", s.empty())\n    s.push(\"four\")\n    fmt.Println(`push \"four\" stack:`, s)\n    if top, ok := s.peek(); ok {\n        fmt.Println(\"top value:\", top)\n    } else {\n        fmt.Println(\"nothing on stack\")\n    }\n    if popped, ok := s.pop(); ok {\n        fmt.Println(popped, \"popped.  stack:\", s)\n    } else {\n        fmt.Println(\"nothing to pop\")\n    }\n}\n\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and allows access to the topmost element without modifying the stack. It also includes a feature to test if the stack is empty.","id":1249}
    {"lang_cluster":"Go","source_code":"\nfunc fib(a int) int {\n  if a < 2 {\n    return a\n  }\n  return fib(a - 1) + fib(a - 2)\n}\nimport (\n\t\"math\/big\"\n)\n\nfunc fib(n uint64) *big.Int {\n\tif n < 2 {\n\t\treturn big.NewInt(int64(n))\n\t}\n\ta, b\u00a0:= big.NewInt(0), big.NewInt(1)\n\tfor n--; n > 0; n-- {\n\t\ta.Add(a, b)\n\t\ta, b = b, a\n\t}\n\treturn b\n}\nfunc fibNumber() func() int {\n\tfib1, fib2\u00a0:= 0, 1\n\treturn func() int {\n\t\tfib1, fib2 = fib2, fib1 + fib2\n\t\treturn fib1\n\t}\n}\n\nfunc fibSequence(n int) int {\n\tf\u00a0:= fibNumber()\n\tfib\u00a0:= 0\n\tfor i\u00a0:= 0; i < n; i++ {\n\t\tfib = f()\n\t}\n\treturn fib\n}\nfunc fib(c chan int) {\n\ta, b\u00a0:= 0, 1\n\tfor {\n\t\tc <- a\n\t\ta, b = b, a+b\n\t}\n}\n\nfunc main() {\n\tc\u00a0:= make(chan int)\n\tgo fib(c)\n\tfor i\u00a0:= 0; i < 10; i++ {\n\t\tfmt.Println(<-c)\n\t}\n}\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":1250}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/rand\"\n)\n\nfunc main() {\n    a := rand.Perm(20)\n    fmt.Println(a)       \/\/ show array to filter\n    fmt.Println(even(a)) \/\/ show result of non-destructive filter\n    fmt.Println(a)       \/\/ show that original array is unchanged\n    reduceToEven(&a)     \/\/ destructive filter\n    fmt.Println(a)       \/\/ show that a is now changed\n    \/\/ a is not only changed, it is changed in place.  length and capacity\n    \/\/ show that it still has its original allocated capacity but has now\n    \/\/ been reduced in length.\n    fmt.Println(\"a len:\", len(a), \"cap:\", cap(a))\n}\n\nfunc even(a []int) (r []int) {\n    for _, e := range a {\n        if e%2 == 0 {\n            r = append(r, e)\n        }\n    }\n    return\n}\n\nfunc reduceToEven(pa *[]int) {\n    a := *pa\n    var last int\n    for _, e := range a {\n        if e%2 == 0 {\n            a[last] = e\n            last++\n        }\n    }\n    *pa = a[:last]\n}\n\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":1251}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"ABCDEFGH\"\n    n, m := 2, 3\n    \/\/ for reference\n    fmt.Println(\"Index: \", \"01234567\")\n    fmt.Println(\"String:\", s)\n    \/\/ starting from n characters in and of m length\n    fmt.Printf(\"Start %d, length %d:    %s\\n\", n, m, s[n : n+m])\n    \/\/ starting from n characters in, up to the end of the string\n    fmt.Printf(\"Start %d, to end:      %s\\n\", n, s[n:])\n    \/\/ whole string minus last character\n    fmt.Printf(\"All but last:         %s\\n\", s[:len(s)-1])\n    \/\/ starting from a known character within the string and of m length\n    dx := strings.IndexByte(s, 'D')\n    fmt.Printf(\"Start 'D', length %d:  %s\\n\", m, s[dx : dx+m])\n    \/\/ starting from a known substring within the string and of m length\n    sx := strings.Index(s, \"DE\")\n    fmt.Printf(`Start \"DE\", length %d: %s`+\"\\n\", m, s[sx : sx+m])\n}\n\n\n","human_summarization":"The code performs the following operations on a string: \n1. Extracts a substring starting from the nth character with a length of m. \n2. Extracts a substring starting from the nth character up to the end of the string. \n3. Returns the whole string except the last character. \n4. Extracts a substring starting from a known character within the string with a length of m. \n5. Extracts a substring starting from a known substring within the string with a length of m. \n\nThe code supports any valid Unicode code point, referencing logical characters, not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. It is not required to handle all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP. The code is designed to work with ASCII data and handles strings as UTF-8 in Go.","id":1252}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"unicode\"\n    \"unicode\/utf8\"\n)\n\n\/\/ no encoding\nfunc reverseBytes(s string) string {\n    r := make([]byte, len(s))\n    for i := 0; i < len(s); i++ {\n        r[i] = s[len(s)-1-i]\n    }\n    return string(r)\n}\n\n\/\/ reverseCodePoints interprets its argument as UTF-8 and ignores bytes\n\/\/ that do not form valid UTF-8.  return value is UTF-8.\nfunc reverseCodePoints(s string) string {\n    r := make([]rune, len(s))\n    start := len(s)\n    for _, c := range s {\n        \/\/ quietly skip invalid UTF-8\n        if c != utf8.RuneError {\n            start--\n            r[start] = c\n        }\n    }\n    return string(r[start:])\n}\n\n\/\/ reversePreservingCombiningCharacters interprets its argument as UTF-8\n\/\/ and ignores bytes that do not form valid UTF-8.  return value is UTF-8.\nfunc reversePreservingCombiningCharacters(s string) string {\n    if s == \"\" {\n        return \"\"\n    }\n    p := []rune(s)\n    r := make([]rune, len(p))\n    start := len(r)\n    for i := 0; i < len(p); {\n        \/\/ quietly skip invalid UTF-8\n        if p[i] == utf8.RuneError {\n            i++\n            continue\n        }\n        j := i + 1\n        for j < len(p) && (unicode.Is(unicode.Mn, p[j]) ||\n            unicode.Is(unicode.Me, p[j]) || unicode.Is(unicode.Mc, p[j])) {\n            j++\n        }\n        for k := j - 1; k >= i; k-- {\n            start--\n            r[start] = p[k]\n        }\n        i = j\n    }\n    return (string(r[start:]))\n}\n\nfunc main() {\n    test(\"asdf\")\n    test(\"as\u20dddf\u0305\")\n}\n\nfunc test(s string) {\n    fmt.Println(\"\\noriginal:      \", []byte(s), s)\n    r := reverseBytes(s)\n    fmt.Println(\"reversed bytes:\", []byte(r), r)\n    fmt.Println(\"original code points:\", []rune(s), s)\n    r = reverseCodePoints(s)\n    fmt.Println(\"reversed code points:\", []rune(r), r)\n    r = reversePreservingCombiningCharacters(s)\n    fmt.Println(\"combining characters:\", []rune(r), r)\n}\n\n\n","human_summarization":"The code takes a string input, reverses it while preserving the order of Unicode combining characters. It assumes UTF-8 encoding and leverages Go's support for UTF-8 and its Unicode package for recognizing combining characters. For instance, \"asdf\" is reversed to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":1253}
    {"lang_cluster":"Go","source_code":"package main\n\nimport (\n    \"bufio\"\n    \"fmt\"\n    \"os\"\n    \"strings\"\n)\n\ntype playfairOption int\n\nconst (\n    noQ playfairOption = iota\n    iEqualsJ\n)\n\ntype playfair struct {\n    keyword string\n    pfo     playfairOption\n    table   [5][5]byte\n}\n\nfunc (p *playfair) init() {\n    \/\/ Build table.\n    var used [26]bool \/\/ all elements false\n    if p.pfo == noQ {\n        used[16] = true \/\/ Q used\n    } else {\n        used[9] = true \/\/ J used\n    }\n    alphabet := strings.ToUpper(p.keyword) + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    for i, j, k := 0, 0, 0; k < len(alphabet); k++ {\n        c := alphabet[k]\n        if c < 'A' || c > 'Z' {\n            continue\n        }\n        d := int(c - 65)\n        if !used[d] {\n            p.table[i][j] = c\n            used[d] = true\n            j++\n            if j == 5 {\n                i++\n                if i == 5 {\n                    break \/\/ table has been filled\n                }\n                j = 0\n            }\n        }\n    }\n}\n\nfunc (p *playfair) getCleanText(plainText string) string {\n    \/\/ Ensure everything is upper case.\n    plainText = strings.ToUpper(plainText)\n    \/\/ Get rid of any non-letters and insert X between duplicate letters.\n    var cleanText strings.Builder\n    \/\/ Safe to assume null byte won't be present in plainText.\n    prevByte := byte('\\000')\n    for i := 0; i < len(plainText); i++ {\n        nextByte := plainText[i]\n        \/\/ It appears that Q should be omitted altogether if NO_Q option is specified;\n        \/\/ we assume so anyway.\n        if nextByte < 'A' || nextByte > 'Z' || (nextByte == 'Q' && p.pfo == noQ) {\n            continue\n        }\n        \/\/ If iEqualsJ option specified, replace J with I.\n        if nextByte == 'J' && p.pfo == iEqualsJ {\n            nextByte = 'I'\n        }\n        if nextByte != prevByte {\n            cleanText.WriteByte(nextByte)\n        } else {\n            cleanText.WriteByte('X')\n            cleanText.WriteByte(nextByte)\n        }\n        prevByte = nextByte\n    }\n    l := cleanText.Len()\n    if l%2 == 1 {\n        \/\/ Dangling letter at end so add another letter to complete digram.\n        if cleanText.String()[l-1] != 'X' {\n            cleanText.WriteByte('X')\n        } else {\n            cleanText.WriteByte('Z')\n        }\n    }\n    return cleanText.String()\n}\n\nfunc (p *playfair) findByte(c byte) (int, int) {\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            if p.table[i][j] == c {\n                return i, j\n            }\n        }\n    }\n    return -1, -1\n}\n\nfunc (p *playfair) encode(plainText string) string {\n    cleanText := p.getCleanText(plainText)\n    var cipherText strings.Builder\n    l := len(cleanText)\n    for i := 0; i < l; i += 2 {\n        row1, col1 := p.findByte(cleanText[i])\n        row2, col2 := p.findByte(cleanText[i+1])\n        switch {\n        case row1 == row2:\n            cipherText.WriteByte(p.table[row1][(col1+1)%5])\n            cipherText.WriteByte(p.table[row2][(col2+1)%5])\n        case col1 == col2:\n            cipherText.WriteByte(p.table[(row1+1)%5][col1])\n            cipherText.WriteByte(p.table[(row2+1)%5][col2])\n        default:\n            cipherText.WriteByte(p.table[row1][col2])\n            cipherText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            cipherText.WriteByte(' ')\n        }\n    }\n    return cipherText.String()\n}\n\nfunc (p *playfair) decode(cipherText string) string {\n    var decodedText strings.Builder\n    l := len(cipherText)\n    \/\/ cipherText will include spaces so we need to skip them.\n    for i := 0; i < l; i += 3 {\n        row1, col1 := p.findByte(cipherText[i])\n        row2, col2 := p.findByte(cipherText[i+1])\n        switch {\n        case row1 == row2:\n            temp := 4\n            if col1 > 0 {\n                temp = col1 - 1\n            }\n            decodedText.WriteByte(p.table[row1][temp])\n            temp = 4\n            if col2 > 0 {\n                temp = col2 - 1\n            }\n            decodedText.WriteByte(p.table[row2][temp])\n        case col1 == col2:\n            temp := 4\n            if row1 > 0 {\n                temp = row1 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col1])\n            temp = 4\n            if row2 > 0 {\n                temp = row2 - 1\n            }\n            decodedText.WriteByte(p.table[temp][col2])\n        default:\n            decodedText.WriteByte(p.table[row1][col2])\n            decodedText.WriteByte(p.table[row2][col1])\n        }\n        if i < l-1 {\n            decodedText.WriteByte(' ')\n        }\n    }\n    return decodedText.String()\n}\n\nfunc (p *playfair) printTable() {\n    fmt.Println(\"The table to be used is\u00a0:\\n\")\n    for i := 0; i < 5; i++ {\n        for j := 0; j < 5; j++ {\n            fmt.Printf(\"%c \", p.table[i][j])\n        }\n        fmt.Println()\n    }\n}\n\nfunc main() {\n    scanner := bufio.NewScanner(os.Stdin)\n    fmt.Print(\"Enter Playfair keyword\u00a0: \")\n    scanner.Scan()\n    keyword := scanner.Text()\n    var ignoreQ string\n    for ignoreQ != \"y\" && ignoreQ != \"n\" {\n        fmt.Print(\"Ignore Q when building table  y\/n\u00a0: \")\n        scanner.Scan()\n        ignoreQ = strings.ToLower(scanner.Text())\n    }\n    pfo := noQ\n    if ignoreQ == \"n\" {\n        pfo = iEqualsJ\n    }\n    var table [5][5]byte\n    pf := &playfair{keyword, pfo, table}\n    pf.init()\n    pf.printTable()\n    fmt.Print(\"\\nEnter plain text\u00a0: \")\n    scanner.Scan()\n    plainText := scanner.Text()\n    if err := scanner.Err(); err != nil {\n        fmt.Fprintln(os.Stderr, \"reading standard input:\", err)\n        return\n    }\n    encodedText := pf.encode(plainText)\n    fmt.Println(\"\\nEncoded text is\u00a0:\", encodedText)\n    decodedText := pf.decode(encodedText)\n    fmt.Println(\"Deccoded text is\u00a0:\", decodedText)\n}\n\n\n","human_summarization":"Implement the Playfair cipher for both encryption and decryption. It allows the user to replace 'J' with 'I' or exclude 'Q' from the alphabet. The encrypted and decrypted messages are outputted in capitalized digraphs, separated by spaces.","id":1254}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"container\/heap\"\n\t\"fmt\"\n)\n\n\/\/ A PriorityQueue implements heap.Interface and holds Items.\ntype PriorityQueue struct {\n\titems []Vertex\n\tm     map[Vertex]int \/\/ value to index\n\tpr    map[Vertex]int \/\/ value to priority\n}\n\nfunc (pq *PriorityQueue) Len() int           { return len(pq.items) }\nfunc (pq *PriorityQueue) Less(i, j int) bool { return pq.pr[pq.items[i]] < pq.pr[pq.items[j]] }\nfunc (pq *PriorityQueue) Swap(i, j int) {\n\tpq.items[i], pq.items[j] = pq.items[j], pq.items[i]\n\tpq.m[pq.items[i]] = i\n\tpq.m[pq.items[j]] = j\n}\nfunc (pq *PriorityQueue) Push(x interface{}) {\n\tn := len(pq.items)\n\titem := x.(Vertex)\n\tpq.m[item] = n\n\tpq.items = append(pq.items, item)\n}\nfunc (pq *PriorityQueue) Pop() interface{} {\n\told := pq.items\n\tn := len(old)\n\titem := old[n-1]\n\tpq.m[item] = -1\n\tpq.items = old[0 : n-1]\n\treturn item\n}\n\n\/\/ update modifies the priority of an item in the queue.\nfunc (pq *PriorityQueue) update(item Vertex, priority int) {\n\tpq.pr[item] = priority\n\theap.Fix(pq, pq.m[item])\n}\nfunc (pq *PriorityQueue) addWithPriority(item Vertex, priority int) {\n\theap.Push(pq, item)\n\tpq.update(item, priority)\n}\n\nconst (\n\tInfinity      = int(^uint(0) >> 1)\n\tUninitialized = -1\n)\n\nfunc Dijkstra(g Graph, source Vertex) (dist map[Vertex]int, prev map[Vertex]Vertex) {\n\tvs := g.Vertices()\n\tdist = make(map[Vertex]int, len(vs))\n\tprev = make(map[Vertex]Vertex, len(vs))\n\tsid := source\n\tdist[sid] = 0\n\tq := &PriorityQueue{\n\t\titems: make([]Vertex, 0, len(vs)),\n\t\tm:     make(map[Vertex]int, len(vs)),\n\t\tpr:    make(map[Vertex]int, len(vs)),\n\t}\n\tfor _, v := range vs {\n\t\tif v != sid {\n\t\t\tdist[v] = Infinity\n\t\t}\n\t\tprev[v] = Uninitialized\n\t\tq.addWithPriority(v, dist[v])\n\t}\n\tfor len(q.items) != 0 {\n\t\tu := heap.Pop(q).(Vertex)\n\t\tfor _, v := range g.Neighbors(u) {\n\t\t\talt := dist[u] + g.Weight(u, v)\n\t\t\tif alt < dist[v] {\n\t\t\t\tdist[v] = alt\n\t\t\t\tprev[v] = u\n\t\t\t\tq.update(v, alt)\n\t\t\t}\n\t\t}\n\t}\n\treturn dist, prev\n}\n\n\/\/ A Graph is the interface implemented by graphs that\n\/\/ this algorithm can run on.\ntype Graph interface {\n\tVertices() []Vertex\n\tNeighbors(v Vertex) []Vertex\n\tWeight(u, v Vertex) int\n}\n\n\/\/ Nonnegative integer ID of vertex\ntype Vertex int\n\n\/\/ sg is a graph of strings that satisfies the Graph interface.\ntype sg struct {\n\tids   map[string]Vertex\n\tnames map[Vertex]string\n\tedges map[Vertex]map[Vertex]int\n}\n\nfunc newsg(ids map[string]Vertex) sg {\n\tg := sg{ids: ids}\n\tg.names = make(map[Vertex]string, len(ids))\n\tfor k, v := range ids {\n\t\tg.names[v] = k\n\t}\n\tg.edges = make(map[Vertex]map[Vertex]int)\n\treturn g\n}\nfunc (g sg) edge(u, v string, w int) {\n\tif _, ok := g.edges[g.ids[u]]; !ok {\n\t\tg.edges[g.ids[u]] = make(map[Vertex]int)\n\t}\n\tg.edges[g.ids[u]][g.ids[v]] = w\n}\nfunc (g sg) path(v Vertex, prev map[Vertex]Vertex) (s string) {\n\ts = g.names[v]\n\tfor prev[v] >= 0 {\n\t\tv = prev[v]\n\t\ts = g.names[v] + s\n\t}\n\treturn s\n}\nfunc (g sg) Vertices() []Vertex {\n\tvs := make([]Vertex, 0, len(g.ids))\n\tfor _, v := range g.ids {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Neighbors(u Vertex) []Vertex {\n\tvs := make([]Vertex, 0, len(g.edges[u]))\n\tfor v := range g.edges[u] {\n\t\tvs = append(vs, v)\n\t}\n\treturn vs\n}\nfunc (g sg) Weight(u, v Vertex) int { return g.edges[u][v] }\n\nfunc main() {\n\tg := newsg(map[string]Vertex{\n\t\t\"a\": 1,\n\t\t\"b\": 2,\n\t\t\"c\": 3,\n\t\t\"d\": 4,\n\t\t\"e\": 5,\n\t\t\"f\": 6,\n\t})\n\tg.edge(\"a\", \"b\", 7)\n\tg.edge(\"a\", \"c\", 9)\n\tg.edge(\"a\", \"f\", 14)\n\tg.edge(\"b\", \"c\", 10)\n\tg.edge(\"b\", \"d\", 15)\n\tg.edge(\"c\", \"d\", 11)\n\tg.edge(\"c\", \"f\", 2)\n\tg.edge(\"d\", \"e\", 6)\n\tg.edge(\"e\", \"f\", 9)\n\n\tdist, prev := Dijkstra(g, g.ids[\"a\"])\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"e\", dist[g.ids[\"e\"]], g.path(g.ids[\"e\"], prev))\n\tfmt.Printf(\"Distance to %s: %d, Path: %s\\n\", \"f\", dist[g.ids[\"f\"]], g.path(g.ids[\"f\"], prev))\n}\n\n\n\n","human_summarization":"The code implements Dijkstra's algorithm to find the shortest path from a given source node to all other nodes in a directed, weighted graph. The graph is represented by an adjacency matrix or list and a start node. The code takes this graph as input and outputs a set of edges that depict the shortest path to each reachable node from the source. It also includes functionality to interpret the output and display the shortest path from the source node to specific nodes. The vertices and edges of the graph can be identified using either numbers or names.","id":1255}
    {"lang_cluster":"Go","source_code":"\n\npackage avl\n\n\/\/ AVL tree adapted from Julienne Walker's presentation at\n\/\/ http:\/\/eternallyconfuzzled.com\/tuts\/datastructures\/jsw_tut_avl.aspx.\n\/\/ This port uses similar indentifier names.\n\n\/\/ The Key interface must be supported by data stored in the AVL tree.\ntype Key interface {\n    Less(Key) bool\n    Eq(Key) bool\n}\n\n\/\/ Node is a node in an AVL tree.\ntype Node struct {\n    Data    Key      \/\/ anything comparable with Less and Eq.\n    Balance int      \/\/ balance factor\n    Link    [2]*Node \/\/ children, indexed by \"direction\", 0 or 1.\n}\n\n\/\/ A little readability function for returning the opposite of a direction,\n\/\/ where a direction is 0 or 1.  Go inlines this.\n\/\/ Where JW writes !dir, this code has opp(dir).\nfunc opp(dir int) int {\n    return 1 - dir\n}\n\n\/\/ single rotation\nfunc single(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\/\/ double rotation\nfunc double(root *Node, dir int) *Node {\n    save := root.Link[opp(dir)].Link[dir]\n\n    root.Link[opp(dir)].Link[dir] = save.Link[opp(dir)]\n    save.Link[opp(dir)] = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save\n\n    save = root.Link[opp(dir)]\n    root.Link[opp(dir)] = save.Link[dir]\n    save.Link[dir] = root\n    return save\n}\n\n\/\/ adjust valance factors after double rotation\nfunc adjustBalance(root *Node, dir, bal int) {\n    n := root.Link[dir]\n    nn := n.Link[opp(dir)]\n    switch nn.Balance {\n    case 0:\n        root.Balance = 0\n        n.Balance = 0\n    case bal:\n        root.Balance = -bal\n        n.Balance = 0\n    default:\n        root.Balance = 0\n        n.Balance = bal\n    }\n    nn.Balance = 0\n}\n\nfunc insertBalance(root *Node, dir int) *Node {\n    n := root.Link[dir]\n    bal := 2*dir - 1\n    if n.Balance == bal {\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, opp(dir))\n    }\n    adjustBalance(root, dir, bal)\n    return double(root, opp(dir))\n}\n\nfunc insertR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return &Node{Data: data}, false\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = insertR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 2*dir - 1\n    switch root.Balance {\n    case 0:\n        return root, true\n    case 1, -1:\n        return root, false\n    }\n    return insertBalance(root, dir), true\n}\n\n\/\/ Insert a node into the AVL tree.\n\/\/ Data is inserted even if other data with the same key already exists.\nfunc Insert(tree **Node, data Key) {\n    *tree, _ = insertR(*tree, data)\n}\n\nfunc removeBalance(root *Node, dir int) (*Node, bool) {\n    n := root.Link[opp(dir)]\n    bal := 2*dir - 1\n    switch n.Balance {\n    case -bal:\n        root.Balance = 0\n        n.Balance = 0\n        return single(root, dir), false\n    case bal:\n        adjustBalance(root, opp(dir), -bal)\n        return double(root, dir), false\n    }\n    root.Balance = -bal\n    n.Balance = bal\n    return single(root, dir), true\n}\n\nfunc removeR(root *Node, data Key) (*Node, bool) {\n    if root == nil {\n        return nil, false\n    }\n    if root.Data.Eq(data) {\n        switch {\n        case root.Link[0] == nil:\n            return root.Link[1], false\n        case root.Link[1] == nil:\n            return root.Link[0], false\n        }\n        heir := root.Link[0]\n        for heir.Link[1] != nil {\n            heir = heir.Link[1]\n        }\n        root.Data = heir.Data\n        data = heir.Data\n    }\n    dir := 0\n    if root.Data.Less(data) {\n        dir = 1\n    }\n    var done bool\n    root.Link[dir], done = removeR(root.Link[dir], data)\n    if done {\n        return root, true\n    }\n    root.Balance += 1 - 2*dir\n    switch root.Balance {\n    case 1, -1:\n        return root, true\n    case 0:\n        return root, false\n    }\n    return removeBalance(root, dir)\n}\n\n\/\/ Remove a single item from an AVL tree.\n\/\/ If key does not exist, function has no effect.\nfunc Remove(tree **Node, data Key) {\n    *tree, _ = removeR(*tree, data)\n}\n\n\npackage main\n\nimport (\n    \"encoding\/json\"\n    \"fmt\"\n    \"log\"\n\n    \"avl\"\n)\n\ntype intKey int\n\n\/\/ satisfy avl.Key\nfunc (k intKey) Less(k2 avl.Key) bool { return k < k2.(intKey) }\nfunc (k intKey) Eq(k2 avl.Key) bool   { return k == k2.(intKey) }\n\n\/\/ use json for cheap tree visualization\nfunc dump(tree *avl.Node) {\n    b, err := json.MarshalIndent(tree, \"\", \"   \")\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(string(b))\n}\n\nfunc main() {\n    var tree *avl.Node\n    fmt.Println(\"Empty tree:\")\n    dump(tree)\n\n    fmt.Println(\"\\nInsert test:\")\n    avl.Insert(&tree, intKey(3))\n    avl.Insert(&tree, intKey(1))\n    avl.Insert(&tree, intKey(4))\n    avl.Insert(&tree, intKey(1))\n    avl.Insert(&tree, intKey(5))\n    dump(tree)\n\n    fmt.Println(\"\\nRemove test:\")\n    avl.Remove(&tree, intKey(3))\n    avl.Remove(&tree, intKey(1))\n    dump(tree)\n}\n\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree where the heights of two child subtrees of any node differ by at most one. The code ensures rebalancing of the tree during insertions and deletions. It provides basic operations with O(log n) time complexity for lookup, insertion, and deletion. The code doesn't allow duplicate node keys. The AVL tree implemented is more efficient for lookup-intensive applications compared to red-black trees.","id":1256}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nvar (\n    Two  = \"Two circles.\"\n    R0   = \"R==0.0 does not describe circles.\"\n    Co   = \"Coincident points describe an infinite number of circles.\"\n    CoR0 = \"Coincident points with r==0.0 describe a degenerate circle.\"\n    Diam = \"Points form a diameter and describe only a single circle.\"\n    Far  = \"Points too far apart to form circles.\"\n)\n\ntype point struct{ x, y float64 }\n\nfunc circles(p1, p2 point, r float64) (c1, c2 point, Case string) {\n    if p1 == p2 {\n        if r == 0 {\n            return p1, p1, CoR0\n        }\n        Case = Co\n        return\n    }\n    if r == 0 {\n        return p1, p2, R0\n    }\n    dx := p2.x - p1.x\n    dy := p2.y - p1.y\n    q := math.Hypot(dx, dy)\n    if q > 2*r {\n        Case = Far\n        return\n    }\n    m := point{(p1.x + p2.x) \/ 2, (p1.y + p2.y) \/ 2}\n    if q == 2*r {\n        return m, m, Diam\n    }\n    d := math.Sqrt(r*r - q*q\/4)\n    ox := d * dx \/ q\n    oy := d * dy \/ q\n    return point{m.x - oy, m.y + ox}, point{m.x + oy, m.y - ox}, Two\n}\n\nvar td = []struct {\n    p1, p2 point\n    r      float64\n}{\n    {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 2.0},\n    {point{0.0000, 2.0000}, point{0.0000, 0.0000}, 1.0},\n    {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 2.0},\n    {point{0.1234, 0.9876}, point{0.8765, 0.2345}, 0.5},\n    {point{0.1234, 0.9876}, point{0.1234, 0.9876}, 0.0},\n}\n\nfunc main() {\n    for _, tc := range td {\n        fmt.Println(\"p1: \", tc.p1)\n        fmt.Println(\"p2: \", tc.p2)\n        fmt.Println(\"r: \", tc.r)\n        c1, c2, Case := circles(tc.p1, tc.p2, tc.r)\n        fmt.Println(\"  \", Case)\n        switch Case {\n        case CoR0, Diam:\n            fmt.Println(\"   Center: \", c1)\n        case Two:\n            fmt.Println(\"   Center 1: \", c1)\n            fmt.Println(\"   Center 2: \", c2)\n        }\n        fmt.Println()\n    }\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":1257}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\ntype sBox [8][16]byte\n\ntype gost struct {\n    k87, k65, k43, k21 [256]byte\n    enc                []byte\n}\n\nfunc newGost(s *sBox) *gost {\n    var g gost\n    for i := range g.k87 {\n        g.k87[i] = s[7][i>>4]<<4 | s[6][i&15]\n        g.k65[i] = s[5][i>>4]<<4 | s[4][i&15]\n        g.k43[i] = s[3][i>>4]<<4 | s[2][i&15]\n        g.k21[i] = s[1][i>>4]<<4 | s[0][i&15]\n    }\n    g.enc = make([]byte, 8)\n    return &g\n}\n\nfunc (g *gost) f(x uint32) uint32 {\n    x = uint32(g.k87[x>>24&255])<<24 | uint32(g.k65[x>>16&255])<<16 |\n        uint32(g.k43[x>>8&255])<<8 | uint32(g.k21[x&255])\n    return x<<11 | x>>(32-11)\n}\n\n\/\/ code above adapted from posted C code\n\n\/\/ validation code below follows example on talk page\n\n\/\/ cbrf from WP\nvar cbrf = sBox{\n    {4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3},\n    {14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9},\n    {5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11},\n    {7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3},\n    {6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2},\n    {4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14},\n    {13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12},\n    {1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12},\n}\n\nfunc u32(b []byte) uint32 {\n    return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24\n}\n\nfunc b4(u uint32, b []byte) {\n    b[0] = byte(u)\n    b[1] = byte(u >> 8)\n    b[2] = byte(u >> 16)\n    b[3] = byte(u >> 24)\n}\n\nfunc (g *gost) mainStep(input []byte, key []byte) {\n    key32 := u32(key)\n    input1 := u32(input[:4])\n    input2 := u32(input[4:])\n    b4(g.f(key32+input1)^input2, g.enc[:4])\n    copy(g.enc[4:], input[:4])\n}\n\nfunc main() {\n    input := []byte{0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04}\n    key := []byte{0xF9, 0x04, 0xC1, 0xE2}\n\n    g := newGost(&cbrf)\n    g.mainStep(input, key)\n    for _, b := range g.enc {\n        fmt.Printf(\"[%02x]\", b)\n    }\n    fmt.Println()\n}\n\n\n","human_summarization":"Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.","id":1258}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\nimport \"math\/rand\"\nimport \"time\"\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    for {\n        a := rand.Intn(20)\n        fmt.Println(a)\n        if a == 10 {\n            break\n        }\n        b := rand.Intn(20)\n        fmt.Println(b)\n    }\n}\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":1259}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\n\/\/ limit search to small primes.  really this is higher than\n\/\/ you'd want it, but it's fun to factor M67.\nconst qlimit = 2e8\n\nfunc main() {\n    mtest(31)\n    mtest(67)\n    mtest(929)\n}\n\nfunc mtest(m int32) {\n    \/\/ the function finds odd prime factors by\n    \/\/ searching no farther than sqrt(N), where N = 2^m-1.\n    \/\/ the first odd prime is 3, 3^2 = 9, so M3 = 7 is still too small.\n    \/\/ M4 = 15 is first number for which test is meaningful.\n    if m < 4 {\n        fmt.Printf(\"%d < 4.  M%d not tested.\\n\", m, m)\n        return\n    }\n    flimit := math.Sqrt(math.Pow(2, float64(m)) - 1)\n    var qlast int32\n    if flimit < qlimit {\n        qlast = int32(flimit)\n    } else {\n        qlast = qlimit\n    }\n    composite := make([]bool, qlast+1)\n    sq := int32(math.Sqrt(float64(qlast)))\nloop:\n    for q := int32(3); ; {\n        if q <= sq {\n            for i := q * q; i <= qlast; i += q {\n                composite[i] = true\n            }\n        }\n        if q8 := q % 8; (q8 == 1 || q8 == 7) && modPow(2, m, q) == 1 {\n            fmt.Printf(\"M%d has factor %d\\n\", m, q)\n            return\n        }\n        for {\n            q += 2\n            if q > qlast {\n                break loop\n            }\n            if !composite[q] {\n                break\n            }\n        }\n    }\n    fmt.Printf(\"No factors of M%d found.\\n\", m)\n}\n\n\/\/ base b to power p, mod m\nfunc modPow(b, p, m int32) int32 {\n    pow := int64(1)\n    b64 := int64(b)\n    m64 := int64(m)\n    bit := uint(30)\n    for 1< sqrt(N). It only works on Mersenne numbers where P is prime.","id":1260}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"log\"\n\t\"os\"\n)\n\ntype Inventory struct {\n\tXMLName  xml.Name `xml:\"inventory\"`\n\tTitle    string   `xml:\"title,attr\"`\n\tSections []struct {\n\t\tXMLName xml.Name `xml:\"section\"`\n\t\tName    string   `xml:\"name,attr\"`\n\t\tItems   []struct {\n\t\t\tXMLName     xml.Name `xml:\"item\"`\n\t\t\tName        string   `xml:\"name\"`\n\t\t\tUPC         string   `xml:\"upc,attr\"`\n\t\t\tStock       int      `xml:\"stock,attr\"`\n\t\t\tPrice       float64  `xml:\"price\"`\n\t\t\tDescription string   `xml:\"description\"`\n\t\t} `xml:\"item\"`\n\t} `xml:\"section\"`\n}\n\n\/\/ To simplify main's error handling\nfunc printXML(s string, v interface{}) {\n\tfmt.Println(s)\n\tb, err := xml.MarshalIndent(v, \"\", \"\\t\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(string(b))\n\tfmt.Println()\n}\n\nfunc main() {\n\tfmt.Println(\"Reading XML from standard input...\")\n\n\tvar inv Inventory\n\tdec := xml.NewDecoder(os.Stdin)\n\tif err := dec.Decode(&inv); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t\/\/ At this point, inv is Go struct with all the fields filled\n\t\/\/ in from the XML data. Well-formed XML input that doesn't\n\t\/\/ match the specification of the fields in the Go struct are\n\t\/\/ discarded without error.\n\n\t\/\/ We can reformat the parts we parsed:\n\t\/\/printXML(\"Got:\", inv)\n\n\t\/\/ 1. Retrieve first item:\n\titem := inv.Sections[0].Items[0]\n\tfmt.Println(\"item variable:\", item)\n\tprintXML(\"As XML:\", item)\n\n\t\/\/ 2. Action on each price:\n\tfmt.Println(\"Prices:\")\n\tvar totalValue float64\n\tfor _, s := range inv.Sections {\n\t\tfor _, i := range s.Items {\n\t\t\tfmt.Println(i.Price)\n\t\t\ttotalValue += i.Price * float64(i.Stock)\n\t\t}\n\t}\n\tfmt.Println(\"Total inventory value:\", totalValue)\n\tfmt.Println()\n\n\t\/\/ 3. Slice of all the names:\n\tvar names []string\n\tfor _, s := range inv.Sections {\n\t\tfor _, i := range s.Items {\n\t\t\tnames = append(names, i.Name)\n\t\t}\n\t}\n\tfmt.Printf(\"names: %q\\n\", names)\n}\n\n\n","human_summarization":"The code executes three XPath queries on a given XML document. It retrieves the first \"item\" element, prints out each \"price\" element, and generates an array of all the \"name\" elements. The XML document represents an inventory of an OmniCorp Store.","id":1261}
    {"lang_cluster":"Go","source_code":"\n\n\npackage main\n\nimport \"fmt\"\n\n\/\/ Define set as a type to hold a set of complex numbers.  A type\n\/\/ could be defined similarly to hold other types of elements.  A common\n\/\/ variation is to make a map of interface{} to represent a set of\n\/\/ mixed types.  Also here the map value is a bool.  By always storing\n\/\/ true, the code is nicely readable.  A variation to use less memory\n\/\/ is to make the map value an empty struct.  The relative advantages\n\/\/ can be debated.\ntype set map[complex128]bool\n\nfunc main() {\n    \/\/ task: set creation\n    s0 := make(set)             \/\/ create empty set\n    s1 := set{3: true}          \/\/ create set with one element\n    s2 := set{3: true, 1: true} \/\/ create set with two elements\n\n    \/\/ option: another way to create a set\n    s3 := newSet(3, 1, 4, 1, 5, 9)\n\n    \/\/ option: output!\n    fmt.Println(\"s0:\", s0)\n    fmt.Println(\"s1:\", s1)\n    fmt.Println(\"s2:\", s2)\n    fmt.Println(\"s3:\", s3)\n\n    \/\/ task: element predicate\n    fmt.Printf(\"%v \u2208 s0: %t\\n\", 3, s0.hasElement(3))\n    fmt.Printf(\"%v \u2208 s3: %t\\n\", 3, s3.hasElement(3))\n    fmt.Printf(\"%v \u2208 s3: %t\\n\", 2, s3.hasElement(2))\n\n    \/\/ task: union\n    b := set{4: true, 2: true}\n    fmt.Printf(\"s3 \u222a %v: %v\\n\", b, union(s3, b))\n\n    \/\/ task: intersection\n    fmt.Printf(\"s3 \u2229 %v: %v\\n\", b, intersection(s3, b))\n\n    \/\/ task: difference\n    fmt.Printf(\"s3 \\\\ %v: %v\\n\", b, difference(s3, b))\n\n    \/\/ task: subset predicate\n    fmt.Printf(\"%v \u2286 s3: %t\\n\", b, subset(b, s3))\n    fmt.Printf(\"%v \u2286 s3: %t\\n\", s2, subset(s2, s3))\n    fmt.Printf(\"%v \u2286 s3: %t\\n\", s0, subset(s0, s3))\n\n    \/\/ task: equality\n    s2Same := set{1: true, 3: true}\n    fmt.Printf(\"%v = s2: %t\\n\", s2Same, equal(s2Same, s2))\n\n    \/\/ option: proper subset\n    fmt.Printf(\"%v \u2282 s2: %t\\n\", s2Same, properSubset(s2Same, s2))\n    fmt.Printf(\"%v \u2282 s3: %t\\n\", s2Same, properSubset(s2Same, s3))\n\n    \/\/ option: delete.  it's built in.\n    delete(s3, 3)\n    fmt.Println(\"s3, 3 deleted:\", s3)\n}\n\nfunc newSet(ms ...complex128) set {\n    s := make(set)\n    for _, m := range ms {\n        s[m] = true\n    }\n    return s\n}\n\nfunc (s set) String() string {\n    if len(s) == 0 {\n        return \"\u2205\"\n    }\n    r := \"{\"\n    for e := range s {\n        r = fmt.Sprintf(\"%s%v, \", r, e)\n    }\n    return r[:len(r)-2] + \"}\"\n}\n\nfunc (s set) hasElement(m complex128) bool {\n    return s[m]\n}\n\nfunc union(a, b set) set {\n    s := make(set)\n    for e := range a {\n        s[e] = true\n    }\n    for e := range b {\n        s[e] = true\n    }\n    return s\n}\n\nfunc intersection(a, b set) set {\n    s := make(set)\n    for e := range a {\n        if b[e] {\n            s[e] = true\n        }\n    }\n    return s\n}\n\nfunc difference(a, b set) set {\n    s := make(set)\n    for e := range a {\n        if !b[e] {\n            s[e] = true\n        }\n    }\n    return s\n}\n\nfunc subset(a, b set) bool {\n    for e := range a {\n        if !b[e] {\n            return false\n        }\n    }\n    return true\n}\n\nfunc equal(a, b set) bool {\n    return len(a) == len(b) && subset(a, b)\n}\n\nfunc properSubset(a, b set) bool {\n    return len(a) < len(b) && subset(a, b)\n}\n\n\n","human_summarization":"The code demonstrates various set operations including set creation, checking if an element is in a set, union, intersection, difference, subset, and equality of two sets. It also optionally shows additional set operations and methods to modify a mutable set. The implementation could be done using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the efficiency of different implementations. It mentions the use of Go maps and big.Int type for specific use cases.","id":1262}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\nimport \"time\"\n\nfunc main() {\n    for year := 2008; year <= 2121; year++ {\n        if time.Date(year, 12, 25, 0, 0, 0, 0, time.UTC).Weekday() ==\n            time.Sunday {\n            fmt.Printf(\"25 December %d is Sunday\\n\", year)\n        }\n    }\n}\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":1263}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n\n    \"github.com\/skelterjohn\/go.matrix\"\n)\n\nfunc sign(s float64) float64 {\n    if s > 0 {\n        return 1\n    } else if s < 0 {\n        return -1\n    }\n    return 0\n}\n\nfunc unitVector(n int) *matrix.DenseMatrix {\n    vec := matrix.Zeros(n, 1)\n    vec.Set(0, 0, 1)\n    return vec\n}\n\nfunc householder(a *matrix.DenseMatrix) *matrix.DenseMatrix {\n    m := a.Rows()\n    s := sign(a.Get(0, 0))\n    e := unitVector(m)\n    u := matrix.Sum(a, matrix.Scaled(e, a.TwoNorm()*s))\n    v := matrix.Scaled(u, 1\/u.Get(0, 0))\n    \/\/ (error checking skipped in this solution)\n    prod, _ := v.Transpose().TimesDense(v)\n    \u03b2 := 2 \/ prod.Get(0, 0)\n\n    prod, _ = v.TimesDense(v.Transpose())\n    return matrix.Difference(matrix.Eye(m), matrix.Scaled(prod, \u03b2))\n}\n\nfunc qr(a *matrix.DenseMatrix) (q, r *matrix.DenseMatrix) {\n    m := a.Rows()\n    n := a.Cols()\n    q = matrix.Eye(m)\n\n    last := n - 1\n    if m == n {\n        last--\n    }\n    for i := 0; i <= last; i++ {\n        \/\/ (copy is only for compatibility with an older version of gomatrix)\n        b := a.GetMatrix(i, i, m-i, n-i).Copy()\n        x := b.GetColVector(0)\n        h := matrix.Eye(m)\n        h.SetMatrix(i, i, householder(x))\n        q, _ = q.TimesDense(h)\n        a, _ = h.TimesDense(a)\n    }\n    return q, a\n}\n\nfunc main() {\n    \/\/ task 1: show qr decomp of wp example\n    a := matrix.MakeDenseMatrixStacked([][]float64{\n        {12, -51, 4},\n        {6, 167, -68},\n        {-4, 24, -41}})\n    q, r := qr(a)\n    fmt.Println(\"q:\\n\", q)\n    fmt.Println(\"r:\\n\", r)\n\n    \/\/ task 2: use qr decomp for polynomial regression example\n    x := matrix.MakeDenseMatrixStacked([][]float64{\n        {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}})\n    y := matrix.MakeDenseMatrixStacked([][]float64{\n        {1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}})\n    fmt.Println(\"\\npolyfit:\\n\", polyfit(x, y, 2))\n}\n\nfunc polyfit(x, y *matrix.DenseMatrix, n int) *matrix.DenseMatrix {\n    m := x.Cols()\n    a := matrix.Zeros(m, n+1)\n    for i := 0; i < m; i++ {\n        for j := 0; j <= n; j++ {\n            a.Set(i, j, math.Pow(x.Get(0, i), float64(j)))\n        }\n    }\n    return lsqr(a, y.Transpose())\n}\n\nfunc lsqr(a, b *matrix.DenseMatrix) *matrix.DenseMatrix {\n    q, r := qr(a)\n    n := r.Cols()\n    prod, _ := q.Transpose().TimesDense(b)\n    return solveUT(r.GetMatrix(0, 0, n, n), prod.GetMatrix(0, 0, n, 1))\n}\n\nfunc solveUT(r, b *matrix.DenseMatrix) *matrix.DenseMatrix {\n    n := r.Cols()\n    x := matrix.Zeros(n, 1)\n    for k := n - 1; k >= 0; k-- {\n        sum := 0.\n        for j := k + 1; j < n; j++ {\n            sum += r.Get(k, j) * x.Get(j, 0)\n        }\n        x.Set(k, 0, (b.Get(k, 0)-sum)\/r.Get(k, k))\n    }\n    return x\n}\n\n\nq:\n {-0.857143,  0.394286,  0.331429,\n -0.428571, -0.902857, -0.034286,\n  0.285714, -0.171429,  0.942857}\nr:\n { -14,  -21,   14,\n    0, -175,   70,\n    0,    0,  -35}\n\npolyfit:\n {1,\n 2,\n 3}\n\npackage main\n\nimport (\n    \"fmt\"\n\n    \"github.com\/gonum\/matrix\/mat64\"\n)\n\nfunc main() {\n    \/\/ task 1: show qr decomp of wp example\n    a := mat64.NewDense(3, 3, []float64{\n        12, -51, 4,\n        6, 167, -68,\n        -4, 24, -41,\n    })\n    var qr mat64.QR\n    qr.Factorize(a)\n    var q, r mat64.Dense\n    q.QFromQR(&qr)\n    r.RFromQR(&qr)\n    fmt.Printf(\"q:\u00a0%.3f\\n\\n\", mat64.Formatted(&q, mat64.Prefix(\"   \")))\n    fmt.Printf(\"r:\u00a0%.3f\\n\\n\", mat64.Formatted(&r, mat64.Prefix(\"   \")))\n\n    \/\/ task 2: use qr decomp for polynomial regression example\n    x := []float64{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n    y := []float64{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}\n    a = Vandermonde(x, 2)\n    b := mat64.NewDense(11, 1, y)\n    qr.Factorize(a)\n    var f mat64.Dense\n    f.SolveQR(&qr, false, b)\n    fmt.Printf(\"polyfit:\u00a0%.3f\\n\",\n        mat64.Formatted(&f, mat64.Prefix(\"         \")))\n}\n\nfunc Vandermonde(a []float64, degree int) *mat64.Dense {\n    x := mat64.NewDense(len(a), degree+1, nil)\n    for i := range a {\n        for j, p := 0, 1.; j <= degree; j, p = j+1, p*a[i] {\n            x.Set(i, j, p)\n        }\n    }\n    return x\n}\n\n\n","human_summarization":"The code demonstrates the QR decomposition of a given matrix using the method of Householder reflections. It first decomposes a given matrix into an orthogonal and an upper triangular matrix. Then, it applies Householder matrices on the matrix to zero all subdiagonal elements of the first column and transform it into an upper triangular matrix. The product of all the Householder matrices will yield the orthogonal matrix. The code also handles the case when the upper triangular matrix is not square by cutting off the zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.","id":1264}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc uniq(list []int) []int {\n\tunique_set := make(map[int]bool, len(list))\n\tfor _, x := range list {\n\t\tunique_set[x] = true\n\t}\n\tresult := make([]int, 0, len(unique_set))\n\tfor x := range unique_set {\n\t\tresult = append(result, x)\n\t}\n\treturn result\n}\n\nfunc main() {\n\tfmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) \/\/ prints: [3 4 1 2] (but in a semi-random order)\n}\n\n\npackage main\n\nimport \"fmt\"\n\nfunc uniq(list []int) []int {\n\tunique_set := make(map[int]int, len(list))\n\ti := 0\n\tfor _, x := range list {\n\t\tif _, there := unique_set[x]; !there {\n\t\t\tunique_set[x] = i\n\t\t\ti++\n\t\t}\n\t}\n\tresult := make([]int, len(unique_set))\n\tfor x, i := range unique_set {\n\t\tresult[i] = x\n\t}\n\treturn result\n}\n\nfunc main() {\n\tfmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) \/\/ prints: [1 2 3 4]\n}\n\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc uniq(list []float64) []float64 {\n\tunique_set := map[float64]int{}\n\ti := 0\n\tnan := false\n\tfor _, x := range list {\n\t\tif _, exists := unique_set[x]; exists {\n\t\t\tcontinue\n\t\t}\n\t\tif math.IsNaN(x) {\n\t\t\tif nan {\n\t\t\t\tcontinue\n\t\t\t} else {\n\t\t\t\tnan = true\n\t\t\t}\n\t\t}\n\t\tunique_set[x] = i\n\t\ti++\n\t}\n\tresult := make([]float64, len(unique_set))\n\tfor x, i := range unique_set {\n\t\tresult[i] = x\n\t}\n\treturn result\n}\n\nfunc main() {\n\tfmt.Println(uniq([]float64{1, 2, math.NaN(), 2, math.NaN(), 4})) \/\/ Prints [1 2 NaN 4]\n}\n\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"reflect\"\n)\n\nfunc uniq(x interface{}) (interface{}, bool) {\n\tv := reflect.ValueOf(x)\n\tif !v.IsValid() {\n\t\tpanic(\"uniq: invalid argument\")\n\t}\n\tif k := v.Kind(); k != reflect.Array && k != reflect.Slice {\n\t\tpanic(\"uniq: argument must be an array or a slice\")\n\t}\n\telemType := v.Type().Elem()\n\tintType := reflect.TypeOf(int(0))\n\tmapType := reflect.MapOf(elemType, intType)\n\tm := reflect.MakeMap(mapType)\n\ti := 0\n\tfor j := 0; j < v.Len(); j++ {\n\t\tx := v.Index(j)\n\t\tif m.MapIndex(x).IsValid() {\n\t\t\tcontinue\n\t\t}\n\t\tm.SetMapIndex(x, reflect.ValueOf(i))\n\t\tif m.MapIndex(x).IsValid() {\n\t\t\ti++\n\t\t}\n\t}\n\tsliceType := reflect.SliceOf(elemType)\n\tresult := reflect.MakeSlice(sliceType, i, i)\n\thadNaN := false\n\tfor _, key := range m.MapKeys() {\n\t\tival := m.MapIndex(key)\n\t\tif !ival.IsValid() {\n\t\t\thadNaN = true\n\t\t} else {\n\t\t\tresult.Index(int(ival.Int())).Set(key)\n\t\t}\n\t}\n\n\treturn result.Interface(), hadNaN\n}\n\ntype MyType struct {\n\tname  string\n\tvalue float32\n}\n\nfunc main() {\n\tintArray := [...]int{5, 1, 2, 3, 2, 3, 4}\n\tintSlice := []int{5, 1, 2, 3, 2, 3, 4}\n\tstringSlice := []string{\"five\", \"one\", \"two\", \"three\", \"two\", \"three\", \"four\"}\n\tfloats := []float64{1, 2, 2, 4,\n\t\tmath.NaN(), 2, math.NaN(),\n\t\tmath.Inf(1), math.Inf(1), math.Inf(-1), math.Inf(-1)}\n\tcomplexes := []complex128{1, 1i, 1 + 1i, 1 + 1i,\n\t\tcomplex(math.NaN(), 1), complex(1, math.NaN()),\n\t\tcomplex(math.Inf(+1), 1), complex(1, math.Inf(1)),\n\t\tcomplex(math.Inf(-1), 1), complex(1, math.Inf(1)),\n\t}\n\tstructs := []MyType{\n\t\t{\"foo\", 42},\n\t\t{\"foo\", 2},\n\t\t{\"foo\", 42},\n\t\t{\"bar\", 42},\n\t\t{\"bar\", 2},\n\t\t{\"fail\", float32(math.NaN())},\n\t}\n\n\tfmt.Print(\"intArray: \", intArray, \" \u2192 \")\n\tfmt.Println(uniq(intArray))\n\tfmt.Print(\"intSlice: \", intSlice, \" \u2192 \")\n\tfmt.Println(uniq(intSlice))\n\tfmt.Print(\"stringSlice: \", stringSlice, \" \u2192 \")\n\tfmt.Println(uniq(stringSlice))\n\tfmt.Print(\"floats: \", floats, \" \u2192 \")\n\tfmt.Println(uniq(floats))\n\tfmt.Print(\"complexes: \", complexes, \"\\n \u2192 \")\n\tfmt.Println(uniq(complexes))\n\tfmt.Print(\"structs: \", structs, \" \u2192 \")\n\tfmt.Println(uniq(structs))\n\t\/\/ Passing a non slice or array will compile put\n\t\/\/ then produce a run time panic:\n\t\/\/a\u00a0:= 42\n\t\/\/uniq(a)\n\t\/\/uniq(nil)\n}\n\n\n","human_summarization":"implement three methods to remove duplicate elements from an array. The first method uses a hash table, the second method sorts the array and removes consecutive duplicates, and the third method iterates through the list and discards any element if it appears again. The code also includes a functionality to preserve the order of elements and handle special cases like NaNs. It uses Go's reflect package to work on almost any array or slice type, and handles map keys that contain a NaN.","id":1265}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}\n    fmt.Println(\"unsorted:\", list)\n\n    quicksort(list)\n    fmt.Println(\"sorted!  \", list)\n}\n\nfunc quicksort(a []int) {\n    var pex func(int, int)\n    pex = func(lower, upper int) {\n        for {\n            switch upper - lower {\n            case -1, 0: \/\/ 0 or 1 item in segment.  nothing to do here!\n                return\n            case 1: \/\/ 2 items in segment\n                \/\/ < operator respects strict weak order\n                if a[upper] < a[lower] {\n                    \/\/ a quick exchange and we're done.\n                    a[upper], a[lower] = a[lower], a[upper]\n                }\n                return\n            \/\/ Hoare suggests optimized sort-3 or sort-4 algorithms here,\n            \/\/ but does not provide an algorithm.\n            }\n\n            \/\/ Hoare stresses picking a bound in a way to avoid worst case\n            \/\/ behavior, but offers no suggestions other than picking a\n            \/\/ random element.  A function call to get a random number is\n            \/\/ relatively expensive, so the method used here is to simply\n            \/\/ choose the middle element.  This at least avoids worst case\n            \/\/ behavior for the obvious common case of an already sorted list.\n            bx := (upper + lower) \/ 2\n            b := a[bx]  \/\/ b = Hoare's \"bound\" (aka \"pivot\")\n            lp := lower \/\/ lp = Hoare's \"lower pointer\"\n            up := upper \/\/ up = Hoare's \"upper pointer\"\n        outer:\n            for {\n                \/\/ use < operator to respect strict weak order\n                for lp < upper && !(b < a[lp]) {\n                    lp++\n                }\n                for {\n                    if lp > up {\n                        \/\/ \"pointers crossed!\"\n                        break outer\n                    }\n                    \/\/ < operator for strict weak order\n                    if a[up] < b {\n                        break \/\/ inner\n                    }\n                    up--\n                }\n                \/\/ exchange\n                a[lp], a[up] = a[up], a[lp]\n                lp++\n                up--\n            }\n            \/\/ segment boundary is between up and lp, but lp-up might be\n            \/\/ 1 or 2, so just call segment boundary between lp-1 and lp.\n            if bx < lp {\n                \/\/ bound was in lower segment\n                if bx < lp-1 {\n                    \/\/ exchange bx with lp-1\n                    a[bx], a[lp-1] = a[lp-1], b\n                }\n                up = lp - 2\n            } else {\n                \/\/ bound was in upper segment\n                if bx > lp {\n                    \/\/ exchange\n                    a[bx], a[lp] = a[lp], b\n                }\n                up = lp - 1\n                lp++\n            }\n            \/\/ \"postpone the larger of the two segments\" = recurse on\n            \/\/ the smaller segment, then iterate on the remaining one.\n            if up-lower < upper-lp {\n                pex(lower, up)\n                lower = lp\n            } else {\n                pex(lp, upper)\n                upper = up\n            }\n        }\n    }\n    pex(0, len(a)-1)\n}\n\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list. The elements in the array must have a strict weak order. The algorithm works by choosing a pivot and dividing the rest of the elements into two partitions based on their relation to the pivot. It then recursively sorts the partitions and joins them together. The code also includes an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The choice of pivot and whether to allocate new arrays or sort in place is not specified. The code also compares Quicksort with other sorting algorithms like merge sort and heap sort.","id":1266}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"time\"\nimport \"fmt\"\n\nfunc main() {\n    fmt.Println(time.Now().Format(\"2006-01-02\"))\n    fmt.Println(time.Now().Format(\"Monday, January 2, 2006\"))\n}\n\n\n","human_summarization":"display the current date in the formats \"2007-11-23\" and \"Friday, November 23, 2007\", based on a specified date and time format. The task description and examples have been reviewed for clarity and accuracy.","id":1267}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n    \"strings\"\n)\n\n\/\/ types needed to implement general purpose sets are element and set\n\n\/\/ element is an interface, allowing different kinds of elements to be\n\/\/ implemented and stored in sets.\ntype elem interface {\n    \/\/ an element must be distinguishable from other elements to satisfy\n    \/\/ the mathematical definition of a set.  a.eq(b) must give the same\n    \/\/ result as b.eq(a).\n    Eq(elem) bool\n    \/\/ String result is used only for printable output.  Given a, b where\n    \/\/ a.eq(b), it is not required that a.String() == b.String().\n    fmt.Stringer\n}\n\n\/\/ integer type satisfying element interface\ntype Int int\n\nfunc (i Int) Eq(e elem) bool {\n    j, ok := e.(Int)\n    return ok && i == j\n}\n\nfunc (i Int) String() string {\n    return strconv.Itoa(int(i))\n}\n\n\/\/ a set is a slice of elem's.  methods are added to implement\n\/\/ the element interface, to allow nesting.\ntype set []elem\n\n\/\/ uniqueness of elements can be ensured by using add method\nfunc (s *set) add(e elem) {\n    if !s.has(e) {\n        *s = append(*s, e)\n    }\n}\n\nfunc (s *set) has(e elem) bool {\n    for _, ex := range *s {\n        if e.Eq(ex) {\n            return true\n        }\n    }\n    return false\n}\n\nfunc (s set) ok() bool {\n    for i, e0 := range s {\n        for _, e1 := range s[i+1:] {\n            if e0.Eq(e1) {\n                return false\n            }\n        }\n    }\n    return true\n}\n\n\/\/ elem.Eq\nfunc (s set) Eq(e elem) bool {\n    t, ok := e.(set)\n    if !ok {\n        return false\n    }\n    if len(s) != len(t) {\n        return false\n    }\n    for _, se := range s {\n        if !t.has(se) {\n            return false\n        }\n    }\n    return true\n}\n\n\/\/ elem.String\nfunc (s set) String() string {\n    if len(s) == 0 {\n        return \"\u2205\"\n    }\n    var buf strings.Builder\n    buf.WriteRune('{')\n    for i, e := range s {\n        if i > 0 {\n            buf.WriteRune(',')\n        }\n        buf.WriteString(e.String())\n    }\n    buf.WriteRune('}')\n    return buf.String()\n}\n\n\/\/ method required for task\nfunc (s set) powerSet() set {\n    r := set{set{}}\n    for _, es := range s {\n        var u set\n        for _, er := range r {\n            er := er.(set)\n            u = append(u, append(er[:len(er):len(er)], es))\n        }\n        r = append(r, u...)\n    }\n    return r\n}\n\nfunc main() {\n    var s set\n    for _, i := range []Int{1, 2, 2, 3, 4, 4, 4} {\n        s.add(i)\n    }\n    fmt.Println(\"      s:\", s, \"length:\", len(s))\n    ps := s.powerSet()\n    fmt.Println(\"   \ud835\udc77(s):\", ps, \"length:\", len(ps))\n\n    fmt.Println(\"\\n(extra credit)\")\n    var empty set\n    fmt.Println(\"  empty:\", empty, \"len:\", len(empty))\n    ps = empty.powerSet()\n    fmt.Println(\"   \ud835\udc77(\u2205):\", ps, \"len:\", len(ps))\n    ps = ps.powerSet()\n    fmt.Println(\"\ud835\udc77(\ud835\udc77(\u2205)):\", ps, \"len:\", len(ps))\n\n    fmt.Println(\"\\n(regression test for earlier bug)\")\n    s = set{Int(1), Int(2), Int(3), Int(4), Int(5)}\n    fmt.Println(\"      s:\", s, \"length:\", len(s), \"ok:\", s.ok())\n    ps = s.powerSet()\n    fmt.Println(\"   \ud835\udc77(s):\", \"length:\", len(ps), \"ok:\", ps.ok())\n    for _, e := range ps {\n        if !e.(set).ok() {\n            panic(\"invalid set in ps\")\n        }\n    }\n}\n\n\n","human_summarization":"The code defines a function that takes a set S as input and returns the power set of S. It uses either a built-in set type or a defined set type with necessary operations. The function ensures the uniqueness of elements in the set. It also handles edge cases such as the power set of an empty set and a set containing only the empty set. The code does not use native set type in Go, but uses a slice as a set representation and an equality method to ensure uniqueness. The power set method computes the result directly without using the add method.","id":1268}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\nvar (\n    m0 = []string{\"\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\"}\n    m1 = []string{\"\", \"X\", \"XX\", \"XXX\", \"XL\", \"L\", \"LX\", \"LXX\", \"LXXX\", \"XC\"}\n    m2 = []string{\"\", \"C\", \"CC\", \"CCC\", \"CD\", \"D\", \"DC\", \"DCC\", \"DCCC\", \"CM\"}\n    m3 = []string{\"\", \"M\", \"MM\", \"MMM\", \"I\u0305V\u0305\",\n        \"V\u0305\", \"V\u0305I\u0305\", \"V\u0305I\u0305I\u0305\", \"V\u0305I\u0305I\u0305I\u0305\", \"I\u0305X\u0305\"}\n    m4 = []string{\"\", \"X\u0305\", \"X\u0305X\u0305\", \"X\u0305X\u0305X\u0305\", \"X\u0305L\u0305\",\n        \"L\u0305\", \"L\u0305X\u0305\", \"L\u0305X\u0305X\u0305\", \"L\u0305X\u0305X\u0305X\u0305\", \"X\u0305C\u0305\"}\n    m5 = []string{\"\", \"C\u0305\", \"C\u0305C\u0305\", \"C\u0305C\u0305C\u0305\", \"C\u0305D\u0305\",\n        \"D\u0305\", \"D\u0305C\u0305\", \"D\u0305C\u0305C\u0305\", \"D\u0305C\u0305C\u0305C\u0305\", \"C\u0305M\u0305\"}\n    m6 = []string{\"\", \"M\u0305\", \"M\u0305M\u0305\", \"M\u0305M\u0305M\u0305\"}\n)\n\nfunc formatRoman(n int) (string, bool) {\n    if n < 1 || n >= 4e6 {\n        return \"\", false\n    }\n    \/\/ this is efficient in Go.  the seven operands are evaluated,\n    \/\/ then a single allocation is made of the exact size needed for the result.\n    return m6[n\/1e6] + m5[n%1e6\/1e5] + m4[n%1e5\/1e4] + m3[n%1e4\/1e3] +\n        m2[n%1e3\/1e2] + m1[n%100\/10] + m0[n%10],\n        true\n}\n\nfunc main() {\n    \/\/ show three numbers mentioned in task descriptions\n    for _, n := range []int{1990, 2008, 1666} {\n        r, ok := formatRoman(n)\n        if ok {\n            fmt.Println(n, \"==\", r)\n        } else {\n            fmt.Println(n, \"not representable\")\n        }\n    }\n}\n\n\n","human_summarization":" define a function that converts a positive integer into its equivalent Roman numeral representation. The function handles integers greater than 3999 by using the Unicode overbar as a factor of 1000.","id":1269}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n)\n\nfunc main() {\n    \/\/ creates an array of five ints.\n    \/\/ specified length must be a compile-time constant expression.\n    \/\/ this allows compiler to do efficient bounds checking.\n    var a [5]int\n\n    \/\/ since length is compile-time constant, len() is a compile time constant\n    \/\/ and does not have the overhead of a function call.\n    fmt.Println(\"len(a) =\", len(a))\n\n    \/\/ elements are always initialized to 0\n    fmt.Println(\"a =\", a)\n\n    \/\/ assign a value to an element.  indexing is 0 based.\n    a[0] = 3\n    fmt.Println(\"a =\", a)\n\n    \/\/ retrieve element value with same syntax\n    fmt.Println(\"a[0] =\", a[0])\n\n    \/\/ a slice references an underlying array\n    s\u00a0:= a[:4] \/\/ this does not allocate new array space.\n    fmt.Println(\"s =\", s)\n\n    \/\/ slices have runtime established length and capacity, but len() and\n    \/\/ cap() are built in to the compiler and have overhead more like\n    \/\/ variable access than function call.\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \/\/ slices can be resliced, as long as there is space\n    \/\/ in the underlying array.\n    s = s[:5]\n    fmt.Println(\"s =\", s)\n\n    \/\/ s still based on a\n    a[0] = 22\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \/\/ append will automatically allocate a larger underlying array as needed.\n    s = append(s, 4, 5, 6)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \/\/ s no longer based on a\n    a[4] = -1\n    fmt.Println(\"a =\", a)\n    fmt.Println(\"s =\", s)\n\n    \/\/ make creates a slice and allocates a new underlying array\n    s = make([]int, 8)\n    fmt.Println(\"s =\", s)\n    fmt.Println(\"len(s) =\", len(s), \" cap(s) =\", cap(s))\n\n    \/\/ the cap()=10 array is no longer referenced\n    \/\/ and would be garbage collected eventually.\n}\n\n","human_summarization":"demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and includes the functionality of pushing a value into the array.","id":1270}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"io\/ioutil\"\n)\n\nfunc main() {\n    b, err := ioutil.ReadFile(\"input.txt\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = ioutil.WriteFile(\"output.txt\", b, 0666); err != nil {\n        fmt.Println(err)\n    }\n}\n\n\npackage main\n\nimport (\n    \"io\"\n    \"log\"\n    \"os\"\n)\n\nfunc CopyFile(out, in string) (err error) {\n    var inf, outf *os.File\n    inf, err = os.Open(in)\n    if err != nil {\n        return\n    }\n    defer func() {\n        cErr := inf.Close()\n        if err == nil {\n            err = cErr\n        }\n    }()\n    outf, err = os.Create(out)\n    if err != nil {\n        return\n    }\n    _, err = io.Copy(outf, inf)\n    cErr := outf.Close()\n    if err == nil {\n        err = cErr\n    }\n    return\n}\n\nfunc main() {\n    if err := CopyFile(\"output.txt\", \"input.txt\"); err != nil {\n        log.Fatal(err)\n    }\n}\n\n","human_summarization":"demonstrate how to read data from \"input.txt\" file into an intermediate variable and then write this data into a new file called \"output.txt\". An alternative solution of copying data directly from one file to another without using an intermediate variable is also provided.","id":1271}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode\"\n    \"unicode\/utf8\"\n)\n\nfunc main() {\n    show(\"alphaBETA\")\n    show(\"alpha BETA\")\n    \/\/ Three digraphs that should render similar to DZ, Lj, and nj.\n    show(\"\u01c4\u01c8\u01cc\")\n    \/\/ Unicode apostrophe in third word.\n    show(\"o'hare O'HARE o\u2019hare don't\")\n}\n\nfunc show(s string) {\n    fmt.Println(\"\\nstring:         \",\n        s, \" len:\", utf8.RuneCountInString(s), \"runes\") \/\/ DZLjnj\n    fmt.Println(\"All upper case: \", strings.ToUpper(s)) \/\/ DZLJNJ\n    fmt.Println(\"All lower case: \", strings.ToLower(s)) \/\/ dzljnj\n    fmt.Println(\"All title case: \", strings.ToTitle(s)) \/\/ DzLjNj\n    fmt.Println(\"Title words:    \", strings.Title(s))   \/\/ Dzljnj\n    fmt.Println(\"Swapping case:  \",                     \/\/ DzLjNJ\n        strings.Map(unicode.SimpleFold, s))\n}\n\n\n","human_summarization":"demonstrate the conversion of a string \"alphaBETA\" to upper-case and lower-case using default encoding or ASCII. The code also showcases additional case conversion functions such as swapping case, capitalizing the first letter, etc. It also explains the difference between \"Title case\" and \"ToTitle()\" in Go's Unicode package, mentioning the non-compliance of the word breaking algorithm with Unicode in Go 1.2 and the failure to convert certain Unicode characters like \u00df into SS.","id":1272}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math\/rand\"\n    \"time\"\n)\n\ntype xy struct {\n    x, y float64\n}\n\nconst n = 1000\nconst scale = 100.\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(points []xy) (p1, p2 xy) {\n    if len(points) < 2 {\n        panic(\"at least two points expected\")\n    }\n    min := 2 * scale\n    for i, q1 := range points[:len(points)-1] {\n        for _, q2 := range points[i+1:] {\n            if dq := d(q1, q2); dq < min {\n                p1, p2 = q1, q2\n                min = dq\n            }\n        }\n    }\n    return\n}\n\n\n\/\/ implementation following algorithm described in\n\/\/ http:\/\/www.cs.umd.edu\/~samir\/grant\/cp.pdf\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math\/rand\"\n    \"time\"\n)\n\n\/\/ number of points to search for closest pair\nconst n = 1e6\n\n\/\/ size of bounding box for points.\n\/\/ x and y will be random with uniform distribution in the range [0,scale).\nconst scale = 100.\n\n\/\/ point struct\ntype xy struct {\n    x, y float64 \/\/ coordinates\n    key  int64   \/\/ an annotation used in the algorithm\n}\n\nfunc d(p1, p2 xy) float64 {\n    return math.Hypot(p2.x-p1.x, p2.y-p1.y)\n}\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    points := make([]xy, n)\n    for i := range points {\n        points[i] = xy{rand.Float64() * scale, rand.Float64() * scale, 0}\n    }\n    p1, p2 := closestPair(points)\n    fmt.Println(p1, p2)\n    fmt.Println(\"distance:\", d(p1, p2))\n}\n\nfunc closestPair(s []xy) (p1, p2 xy) {\n    if len(s) < 2 {\n        panic(\"2 points required\")\n    }\n    var dxi float64\n    \/\/ step 0\n    for s1, i := s, 1; ; i++ {\n        \/\/ step 1: compute min distance to a random point\n        \/\/ (for the case of random data, it's enough to just try\n        \/\/ to pick a different point)\n        rp := i % len(s1)\n        xi := s1[rp]\n        dxi = 2 * scale\n        for p, xn := range s1 {\n            if p != rp {\n                if dq := d(xi, xn); dq < dxi {\n                    dxi = dq\n                }\n            }\n        }\n\n        \/\/ step 2: filter\n        invB := 3 \/ dxi             \/\/ b is size of a mesh cell\n        mx := int64(scale*invB) + 1 \/\/ mx is number of cells along a side\n        \/\/ construct map as a histogram:\n        \/\/ key is index into mesh.  value is count of points in cell\n        hm := map[int64]int{}\n        for ip, p := range s1 {\n            key := int64(p.x*invB)*mx + int64(p.y*invB)\n            s1[ip].key = key\n            hm[key]++\n        }\n        \/\/ construct s2 = s1 less the points without neighbors\n        s2 := make([]xy, 0, len(s1))\n        nx := []int64{-mx - 1, -mx, -mx + 1, -1, 0, 1, mx - 1, mx, mx + 1}\n        for i, p := range s1 {\n            nn := 0\n            for _, ofs := range nx {\n                nn += hm[p.key+ofs]\n                if nn > 1 {\n                    s2 = append(s2, s1[i])\n                    break\n                }\n            }\n        }\n\n        \/\/ step 3: done?\n        if len(s2) == 0 {\n            break\n        }\n        s1 = s2\n    }\n    \/\/ step 4: compute answer from approximation\n    invB := 1 \/ dxi\n    mx := int64(scale*invB) + 1\n    hm := map[int64][]int{}\n    for i, p := range s {\n        key := int64(p.x*invB)*mx + int64(p.y*invB)\n        s[i].key = key\n        hm[key] = append(hm[key], i)\n    }\n    nx := []int64{-mx - 1, -mx, -mx + 1, -1, 0, 1, mx - 1, mx, mx + 1}\n    var min = scale * 2\n    for ip, p := range s {\n        for _, ofs := range nx {\n            for _, iq := range hm[p.key+ofs] {\n                if ip != iq {\n                    if d1 := d(p, s[iq]); d1 < min {\n                        min = d1\n                        p1, p2 = p, s[iq]\n                    }\n                }\n            }\n        }\n    }\n    return p1, p2\n}\n\n","human_summarization":"The code provides two solutions to the Closest Pair of Points problem in a two-dimensional plane. The first solution is a brute-force algorithm with a time complexity of O(n^2), which iterates over all pairs of points to find the closest pair. The second solution is a more efficient divide-and-conquer algorithm with a time complexity of O(n log n), which sorts the points by x and y coordinates, divides them into two halves, and recursively finds the closest pairs in each half and the strip between them.","id":1273}
    {"lang_cluster":"Go","source_code":"\nSlices\nMaps\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    var a []interface{}\n    a = append(a, 3)\n    a = append(a, \"apples\", \"oranges\")\n    fmt.Println(a)\n}\n\n\n","human_summarization":"create a collection and add values to it. The collection can be any Go type, including an interface. The code also includes a variable 'a' which is a slice of interface{} objects. The collection is resizable and can be a slice or map. The code also references various types of lists and arrays.","id":1274}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\ntype Item struct {\n\tName           string\n\tValue          int\n\tWeight, Volume float64\n}\n\ntype Result struct {\n\tCounts []int\n\tSum    int\n}\n\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n\nfunc Knapsack(items []Item, weight, volume float64) (best Result) {\n\tif len(items) == 0 {\n\t\treturn\n\t}\n\tn := len(items) - 1\n\tmaxCount := min(int(weight\/items[n].Weight), int(volume\/items[n].Volume))\n\tfor count := 0; count <= maxCount; count++ {\n\t\tsol := Knapsack(items[:n],\n\t\t\tweight-float64(count)*items[n].Weight,\n\t\t\tvolume-float64(count)*items[n].Volume)\n\t\tsol.Sum += items[n].Value * count\n\t\tif sol.Sum > best.Sum {\n\t\t\tsol.Counts = append(sol.Counts, count)\n\t\t\tbest = sol\n\t\t}\n\t}\n\treturn\n}\n\nfunc main() {\n\titems := []Item{\n\t\t{\"Panacea\", 3000, 0.3, 0.025},\n\t\t{\"Ichor\", 1800, 0.2, 0.015},\n\t\t{\"Gold\", 2500, 2.0, 0.002},\n\t}\n\tvar sumCount, sumValue int\n\tvar sumWeight, sumVolume float64\n\n\tresult := Knapsack(items, 25, 0.25)\n\n\tfor i := range result.Counts {\n\t\tfmt.Printf(\"%-8s x%3d  -> Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\t\titems[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]),\n\t\t\titems[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i])\n\n\t\tsumCount += result.Counts[i]\n\t\tsumValue += items[i].Value * result.Counts[i]\n\t\tsumWeight += items[i].Weight * float64(result.Counts[i])\n\t\tsumVolume += items[i].Volume * float64(result.Counts[i])\n\t}\n\n\tfmt.Printf(\"TOTAL (%3d items) Weight: %4.1f  Volume: %5.3f  Value: %6d\\n\",\n\t\tsumCount, sumWeight, sumVolume, sumValue)\n}\n\n\nPanacea  x  9  -> Weight:  2.7  Volume: 0.225  Value:  27000\nIchor    x  0  -> Weight:  0.0  Volume: 0.000  Value:      0\nGold     x 11  -> Weight: 22.0  Volume: 0.022  Value:  27500\nTOTAL ( 20 items) Weight: 24.7  Volume: 0.247  Value:  54500\n\n","human_summarization":"\"Determine the optimal quantity of each item a traveler should take in order to maximize the total value, given the weight and volume constraints of his knapsack. The solution involves a recursive brute-force approach and only one of the four possible maximum value solutions needs to be provided.\"","id":1275}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; ; i++ {\n        fmt.Print(i)\n        if i == 10 {\n            fmt.Println()\n            break\n        }\n        fmt.Print(\", \")\n    }\n}\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":1276}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nvar data = `\nLIBRARY          LIBRARY DEPENDENCIES\n=======          ====================\ndes_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\ndw01             ieee dw01 dware gtech\ndw02             ieee dw02 dware\ndw03             std synopsys dware dw03 dw02 dw01 ieee gtech\ndw04             dw04 ieee dw01 dware gtech\ndw05             dw05 ieee dware\ndw06             dw06 ieee dware\ndw07             ieee dware\ndware            ieee dware\ngtech            ieee gtech\nramlib           std ieee\nstd_cell_lib     ieee std_cell_lib\nsynopsys         `\n\nfunc main() {\n    g, in, err := parseLibComp(data)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    order, cyclic := topSortKahn(g, in)\n    if cyclic != nil {\n        fmt.Println(\"Cyclic:\", cyclic)\n        return\n    }\n    fmt.Println(\"Order:\", order)\n}\n\ntype graph map[string][]string\ntype inDegree map[string]int\n\n\/\/ parseLibComp parses the text format of the task and returns a graph\n\/\/ representation and a list of the in-degrees of each node.  The returned graph\n\/\/ represents compile order rather than dependency order.  That is, for each map\n\/\/ map key n, the map elements are libraries that depend on n being compiled\n\/\/ first.\nfunc parseLibComp(data string) (g graph, in inDegree, err error) {\n    \/\/ small sanity check on input\n    lines := strings.Split(data, \"\\n\")\n    if len(lines) < 3 || !strings.HasPrefix(lines[2], \"=\") {\n        return nil, nil, fmt.Errorf(\"data format\")\n    }\n    \/\/ toss header lines\n    lines = lines[3:]\n    \/\/ scan and interpret input, build graph\n    g = graph{}\n    in = inDegree{}\n    for _, line := range lines {\n        libs := strings.Fields(line)\n        if len(libs) == 0 {\n            continue \/\/ allow blank lines\n        }\n        lib := libs[0]\n        g[lib] = g[lib]\n        for _, dep := range libs[1:] {\n            in[dep] = in[dep]\n            if dep == lib {\n                continue \/\/ ignore self dependencies\n            }\n            successors := g[dep]\n            for i := 0; ; i++ {\n                if i == len(successors) {\n                    g[dep] = append(successors, lib)\n                    in[lib]++\n                    break\n                }\n                if dep == successors[i] {\n                    break \/\/ ignore duplicate dependencies\n                }\n            }\n        }\n    }\n    return g, in, nil\n}\n\n\/\/ General purpose topological sort, not specific to the application of\n\/\/ library dependencies.  Adapted from Wikipedia pseudo code, one main\n\/\/ difference here is that this function does not consume the input graph.\n\/\/ WP refers to incoming edges, but does not really need them fully represented.\n\/\/ A count of incoming edges, or the in-degree of each node is enough.  Also,\n\/\/ WP stops at cycle detection and doesn't output information about the cycle.\n\/\/ A little extra code at the end of this function recovers the cyclic nodes.\nfunc topSortKahn(g graph, in inDegree) (order, cyclic []string) {\n    var L, S []string\n    \/\/ rem for \"remaining edges,\" this function makes a local copy of the\n    \/\/ in-degrees and consumes that instead of consuming an input.\n    rem := inDegree{}\n    for n, d := range in {\n        if d == 0 {\n            \/\/ accumulate \"set of all nodes with no incoming edges\"\n            S = append(S, n)\n        } else {\n            \/\/ initialize rem from in-degree\n            rem[n] = d\n        }\n    }\n    for len(S) > 0 {\n        last := len(S) - 1 \/\/ \"remove a node n from S\"\n        n := S[last]\n        S = S[:last]\n        L = append(L, n) \/\/ \"add n to tail of L\"\n        for _, m := range g[n] {\n            \/\/ WP pseudo code reads \"for each node m...\" but it means for each\n            \/\/ node m *remaining in the graph.*  We consume rem rather than\n            \/\/ the graph, so \"remaining in the graph\" for us means rem[m] > 0.\n            if rem[m] > 0 {\n                rem[m]--         \/\/ \"remove edge from the graph\"\n                if rem[m] == 0 { \/\/ if \"m has no other incoming edges\"\n                    S = append(S, m) \/\/ \"insert m into S\"\n                }\n            }\n        }\n    }\n    \/\/ \"If graph has edges,\" for us means a value in rem is > 0.\n    for c, in := range rem {\n        if in > 0 {\n            \/\/ recover cyclic nodes\n            for _, nb := range g[c] {\n                if rem[nb] > 0 {\n                    cyclic = append(cyclic, c)\n                    break\n                }\n            }\n        }\n    }\n    if len(cyclic) > 0 {\n        return nil, cyclic\n    }\n    return L, nil\n}\n\n\n","human_summarization":"The code performs a topological sort on a given set of VHDL libraries and their dependencies. It returns a valid compile order such that no library is compiled before its dependencies. It handles cases of self-dependencies and flags any un-orderable dependencies. The code uses either Kahn's 1962 topological sort algorithm or a depth-first search for the sorting process. It also includes a function for cycle detection.","id":1277}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc match(first, second string) {\n    fmt.Printf(\"1. %s starts with %s: %t\\n\",\n        first, second, strings.HasPrefix(first, second))\n    i := strings.Index(first, second)\n    fmt.Printf(\"2. %s contains %s: %t,\\n\", first, second, i >= 0)\n    if i >= 0 {\n        fmt.Printf(\"2.1. at location %d,\\n\", i)\n        for start := i+1;; {\n            if i = strings.Index(first[start:], second); i < 0 {\n                break\n            }\n            fmt.Printf(\"2.2. at location %d,\\n\", start+i)\n            start += i+1\n        }\n        fmt.Println(\"2.2. and that's all\")\n    }\n    fmt.Printf(\"3. %s ends with %s: %t\\n\",\n        first, second, strings.HasSuffix(first, second))\n}\n\nfunc main() {\n    match(\"abracadabra\", \"abr\")\n}\n\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":1278}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc main(){\n\tn, c := getCombs(1,7,true)\n\tfmt.Printf(\"%d unique solutions in 1 to 7\\n\",n)\n\tfmt.Println(c)\n\tn, c = getCombs(3,9,true)\n\tfmt.Printf(\"%d unique solutions in 3 to 9\\n\",n)\n\tfmt.Println(c)\n\tn, _ = getCombs(0,9,false)\n\tfmt.Printf(\"%d non-unique solutions in 0 to 9\\n\",n)\n}\n\nfunc getCombs(low,high int,unique bool) (num int,validCombs [][]int){\n\tfor a := low; a <= high; a++ {\n\t\tfor b := low; b <= high; b++ {\n\t\t\tfor c := low; c <= high; c++ {\n\t\t\t\tfor d := low; d <= high; d++ {\n\t\t\t\t\tfor e := low; e <= high; e++ {\n\t\t\t\t\t\tfor f := low; f <= high; f++ {\n\t\t\t\t\t\t\tfor g := low; g <= high; g++ {\n\t\t\t\t\t\t\t\tif validComb(a,b,c,d,e,f,g) {\n\t\t\t\t\t\t\t\t\tif !unique || isUnique(a,b,c,d,e,f,g) {\n\t\t\t\t\t\t\t\t\t\tnum++\n\t\t\t\t\t\t\t\t\t\tvalidCombs = append(validCombs,[]int{a,b,c,d,e,f,g})\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn\n}\nfunc isUnique(a,b,c,d,e,f,g int) (res bool) {\n\tdata := make(map[int]int)\n\tdata[a]++\n\tdata[b]++\n\tdata[c]++\n\tdata[d]++\n\tdata[e]++\n\tdata[f]++\n\tdata[g]++\n\treturn len(data) == 7\n}\nfunc validComb(a,b,c,d,e,f,g int) bool{\n\tsquare1 := a + b\n\tsquare2 := b + c + d\n\tsquare3 := d + e + f\n\tsquare4 := f + g\n\treturn square1 == square2 && square2 == square3 && square3 == square4\n}\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":1279}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"golang.org\/x\/net\/websocket\"\n\t\"flag\"\n\t\"fmt\"\n\t\"html\/template\"\n\t\"io\"\n\t\"math\"\n\t\"net\/http\"\n\t\"time\"\n)\n\nvar (\n\tPortnum  string\n\tHostsite string\n)\n\ntype PageSettings struct {\n\tHost string\n\tPort string\n}\n\nconst (\n\tCanvaswidth  = 512\n\tCanvasheight = 512\n\t\/\/color constants\n\tHourColor   = \"#ff7373\" \/\/ pinkish\n\tMinuteColor = \"#00b7e4\" \/\/light blue\n\tSecondColor = \"#b58900\" \/\/gold\n)\n\nfunc main() {\n\tflag.StringVar(&Portnum, \"Port\", \"1234\", \"Port to host server.\")\n\tflag.StringVar(&Hostsite, \"Site\", \"localhost\", \"Site hosting server\")\n\tflag.Parse()\n\thttp.HandleFunc(\"\/\", webhandler)\n\thttp.Handle(\"\/ws\", websocket.Handler(wshandle))\n\terr := http.ListenAndServe(Hostsite+\":\"+Portnum, nil)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\tfmt.Println(\"server running\")\n}\n\nfunc webhandler(w http.ResponseWriter, r *http.Request) {\n\twsurl := PageSettings{Host: Hostsite, Port: Portnum}\n\ttemplate, _ := template.ParseFiles(\"clock.html\")\n\ttemplate.Execute(w, wsurl)\n}\n\n\/\/Given a websocket connection,\n\/\/serves updating time function\nfunc wshandle(ws *websocket.Conn) {\n\tfor {\n\t\thour, min, sec := time.Now().Clock()\n\t\thourx, houry := HourCords(hour, Canvasheight\/2)\n\t\tminx, miny := MinSecCords(min, Canvasheight\/2)\n\t\tsecx, secy := MinSecCords(sec, Canvasheight\/2)\n\t\tmsg := \"CLEAR\\n\"\n\t\tmsg += fmt.Sprintf(\"HOUR %d %d %s\\n\", hourx, houry, HourColor)\n\t\tmsg += fmt.Sprintf(\"MIN %d %d %s\\n\", minx, miny, MinuteColor)\n\t\tmsg += fmt.Sprintf(\"SEC %d %d %s\", secx, secy, SecondColor)\n\t\tio.WriteString(ws, msg)\n\t\ttime.Sleep(time.Second \/ 60.0)\n\t}\n}\n\n\/\/Given current minute or second time(i.e 30 min, 60 minutes)\n\/\/and the radius, returns pair of cords to draw line to\nfunc MinSecCords(ctime int, radius int) (int, int) {\n\t\/\/converts min\/sec to angle and then to radians\n\n\ttheta := ((float64(ctime)*6 - 90) * (math.Pi \/ 180))\n\tx := float64(radius) * math.Cos(theta)\n\ty := float64(radius) * math.Sin(theta)\n\treturn int(x) + 256, int(y) + 256\n}\n\n\/\/Given current hour time(i.e. 12, 8) and the radius,\n\/\/returns pair of cords to draw line to\nfunc HourCords(ctime int, radius int) (int, int) {\n\t\/\/converts hours to angle and then to radians\n\ttheta := ((float64(ctime)*30 - 90) * (math.Pi \/ 180))\n\tx := float64(radius) * math.Cos(theta)\n\ty := float64(radius) * math.Sin(theta)\n\treturn int(x) + 256, int(y) + 256\n}\n\n\n\n\nClock<\/title>\n<script language=\"javascript\" type=\"text\/javascript\">\n\n  var connurl = \"ws:\/\/{{.Host}}:{{.Port}}\/ws\";\n  \/\/var ctx;\n  var secondhand;\n  var minutehand;\n  var hourhand;\n  function wsConnect()\n  {\n\t\/\/get contexts for drawing\n    \/\/var canvas = document.getElementById( \"canvas\" );\n    \/\/ctx = canvas.getContext( '2d' );\n\tvar canvas = document.getElementById(\"rim\");\n    \/\/draw circle for rim\n    rim =  canvas.getContext('2d');\n    rim.beginPath();\n    rim.arc(256,256,256,0,2*Math.PI);\n    rim.stroke();\n    \/\/minute hand\n    canvas = document.getElementById(\"minutehand\");\n    minutehand = canvas.getContext('2d');\n    \/\/hour hand\n    canvas = document.getElementById(\"hourhand\");\n    hourhand = canvas.getContext('2d');\n    \/\/second hand\n    canvas = document.getElementById(\"secondhand\");\n    secondhand = canvas.getContext('2d');\n\n    ws = new WebSocket( connurl );\n    ws.onopen = function( e ) {\n      console.log( \"CONNECTED\" );\n      ws.send( \"READY\" );\n    };\n    \/*ws.onclose = function( e ) { \n      console.log( \"DISCONNECTED\" );\n    };*\/\n    ws.onmessage = function( e ) {\n      var data = e.data.split(\"\\n\");\n      for ( var line in data ) {\n        var msg = data[line].split(\" \");\n        var cmd = msg[0];\n        if (cmd ==\"CLEAR\"){\n          minutehand.clearRect(0,0,512,512);\n          secondhand.clearRect(0,0,512,512);\n          hourhand.clearRect(0,0,512,512);\n        }else if (cmd === \"HOUR\"){\n          renderline(hourhand, msg);\n        }else if (cmd === \"MIN\"){\n          renderline(minutehand, msg);\n        }else if (cmd === \"SEC\"){\n          renderline(secondhand, msg);\n        }else if (cmd ===\"\"){\n          cmd = \"\";\n        }else{\n          console.log(\"BAD COMMAND: \"+cmd + \"; \"+msg);\n        }\n      }\n    };\n    ws.onerror = function( e ) {\n      console.log( 'WS Error: ' + e.data );\n    };\n  }\n  \/\/render line given paramets\n  function renderline(ctx, msg){\n    ctx.clearRect(0,0,512,512);\n    ctx.width = ctx.width;\n    var x = parseInt(msg[1],10);\n    var y = parseInt(msg[2],10);\n    var color = msg[3];\n    ctx.strokeStyle = color;\n    ctx.beginPath();\n    ctx.moveTo(256,256);\n    ctx.lineTo(x,y);\n    ctx.stroke();\n  }\n\n  window.addEventListener( \"load\", wsConnect, false );\n\n<\/script>\n\n<body>\n    <h2>Clock<\/h2>\n\t\n  <canvas id=\"rim\" width=\"512\" height=\"512\" style=\"position: absolute; left: 0; top: 0; z-index: 0;\">\n        Sorry, your browser does not support Canvas\n  <\/canvas>\n\t<canvas id=\"hourhand\" width=\"512\" height=\"512\"style=\"position: absolute; left: 0; top: 0; z-index: 1;\">\n        Sorry, your browser does not support Canvas\n  <\/canvas>\n\t<canvas id=\"minutehand\" width=\"512\" height=\"512\"style=\"position: absolute; left: 0; top: 0; z-index: 2;\">\n        Sorry, your browser does not support Canvas\n  <\/canvas>\n\t<canvas id=\"secondhand\" width=\"512\" height=\"512\"style=\"position: absolute; left: 0; top: 0; z-index: 3;\">\n        Sorry, your browser does not support Canvas\n  <\/canvas>\n\t\n<\/body>\n<\/html>\n\n","human_summarization":"The code creates a simple, animated clock that displays the passing of seconds. It utilizes a system timer or event to update the time, ensuring it doesn't unnecessarily consume system resources. The clock aligns with the system time for accuracy but doesn't require precision suitable for space flights. The code is designed to be clear, concise, and not overly complex. The clock can be any time-keeping device and is displayed either textually or graphically. The associated 'clock.html' file should be in the same directory as the binary.","id":1280}
    {"lang_cluster":"Go","source_code":"\n\nPACKAGE MAIN\n \nIMPORT (\n    \"FMT\"\n    \"TIME\"\n)\n \nCONST PAGEWIDTH = 80\n \nFUNC MAIN() {\n    PRINTCAL(1969)\n}\n \nFUNC PRINTCAL(YEAR INT) {\n    THISDATE := TIME.DATE(YEAR, 1, 1, 1, 1, 1, 1, TIME.UTC)\n    VAR (\n        DAYARR                  [12][7][6]INT \/\/ MONTH, WEEKDAY, WEEK\n        MONTH, LASTMONTH        TIME.MONTH\n        WEEKINMONTH, DAYINMONTH INT\n    )\n    FOR THISDATE.YEAR() == YEAR {\n        IF MONTH = THISDATE.MONTH(); MONTH != LASTMONTH {\n            WEEKINMONTH = 0\n            DAYINMONTH = 1\n        }\n        WEEKDAY := THISDATE.WEEKDAY()\n        IF WEEKDAY == 0 && DAYINMONTH > 1 {\n            WEEKINMONTH++\n        }\n        DAYARR[INT(MONTH)-1][WEEKDAY][WEEKINMONTH] = THISDATE.DAY()\n        LASTMONTH = MONTH\n        DAYINMONTH++\n        THISDATE = THISDATE.ADD(TIME.HOUR * 24)\n    }\n    CENTRE := FMT.SPRINTF(\"%D\", PAGEWIDTH\/2)\n    FMT.PRINTF(\"%\"+CENTRE+\"S\\N\\N\", \"[SNOOPY]\")\n    CENTRE = FMT.SPRINTF(\"%D\", PAGEWIDTH\/2-2)\n    FMT.PRINTF(\"%\"+CENTRE+\"D\\N\\N\", YEAR)\n    MONTHS := [12]STRING{\n        \" JANUARY \", \" FEBRUARY\", \"  MARCH  \", \"  APRIL  \",\n        \"   MAY   \", \"   JUNE  \", \"   JULY  \", \"  AUGUST \",\n        \"SEPTEMBER\", \" OCTOBER \", \" NOVEMBER\", \" DECEMBER\"}\n    DAYS := [7]STRING{\"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\"}\n    FOR QTR := 0; QTR < 4; QTR++ {\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \/\/ MONTH NAMES\n            FMT.PRINTF(\"      %S           \", MONTHS[QTR*3+MONTHINQTR])\n        }\n        FMT.PRINTLN()\n        FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ { \/\/ DAY NAMES\n            FOR DAY := 0; DAY < 7; DAY++ {\n                FMT.PRINTF(\" %S\", DAYS[DAY])\n            }\n            FMT.PRINTF(\"     \")\n        }\n        FMT.PRINTLN()\n        FOR WEEKINMONTH = 0; WEEKINMONTH < 6; WEEKINMONTH++ {\n            FOR MONTHINQTR := 0; MONTHINQTR < 3; MONTHINQTR++ {\n                FOR DAY := 0; DAY < 7; DAY++ {\n                    IF DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH] == 0 {\n                        FMT.PRINTF(\"   \")\n                    } ELSE {\n                        FMT.PRINTF(\"%3D\", DAYARR[QTR*3+MONTHINQTR][DAY][WEEKINMONTH])\n                    }\n                }\n                FMT.PRINTF(\"     \")\n            }\n            FMT.PRINTLN()\n        }\n        FMT.PRINTLN()\n    }\n}\n\n\npackage main\n\nimport (\n    \"io\/ioutil\"\n    \"log\"\n    \"os\"\n    \"os\/exec\"\n    \"strings\"\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    lower := []string{\n        \"const \", \"else \", \"for \", \"func \", \"if \", \"import \", \"int \", \"package \", \"string \", \"var \",\n        \" int\", \"int(\", \"string{\", \" main\", \"main(\", \"fmt\", \"time\", \"%d\", \"%s\", \"%3d\", `d\\n\\n`, `s\\n\\n`,\n    }\n    title := []string{\n        \".add\", \".date\", \".day\", \".hour\", \".month\", \".printf\", \".println\", \".sprintf\", \".weekday\", \".year\",\n    }\n    code, err := ioutil.ReadFile(\"realcal_UC.txt\")\n    check(err)\n    text := string(code)\n    for _, lwr := range lower {\n        text = strings.Replace(text, strings.ToUpper(lwr), lwr, -1)\n    }\n    for _, ttl := range title {\n        text = strings.Replace(text, strings.ToUpper(ttl), \".\"+strings.Title(ttl[1:]), -1)\n    }\n    err = ioutil.WriteFile(\"realcal_NC.go\", []byte(text), 0666)\n    check(err)\n    cmd := exec.Command(\"go\", \"run\", \"realcal_NC.go\")\n    cmd.Stdout = os.Stdout\n    cmd.Stderr = os.Stderr\n    check(cmd.Run())\n}\n\n\n                                [SNOOPY]\n\n                                  1969\n\n       JANUARY                   FEBRUARY                   MARCH             \n SU MO TU WE TH FR SA      SU MO TU WE TH FR SA      SU MO TU WE TH FR SA     \n           1  2  3  4                         1                         1     \n  5  6  7  8  9 10 11       2  3  4  5  6  7  8       2  3  4  5  6  7  8     \n 12 13 14 15 16 17 18       9 10 11 12 13 14 15       9 10 11 12 13 14 15     \n 19 20 21 22 23 24 25      16 17 18 19 20 21 22      16 17 18 19 20 21 22     \n 26 27 28 29 30 31         23 24 25 26 27 28         23 24 25 26 27 28 29     \n                                                     30 31                    \n\n        APRIL                      MAY                       JUNE             \n SU MO TU WE TH FR SA      SU MO TU WE TH FR SA      SU MO TU WE TH FR SA     \n        1  2  3  4  5                   1  2  3       1  2  3  4  5  6  7     \n  6  7  8  9 10 11 12       4  5  6  7  8  9 10       8  9 10 11 12 13 14     \n 13 14 15 16 17 18 19      11 12 13 14 15 16 17      15 16 17 18 19 20 21     \n 20 21 22 23 24 25 26      18 19 20 21 22 23 24      22 23 24 25 26 27 28     \n 27 28 29 30               25 26 27 28 29 30 31      29 30                    \n                                                                              \n\n         JULY                     AUGUST                  SEPTEMBER           \n SU MO TU WE TH FR SA      SU MO TU WE TH FR SA      SU MO TU WE TH FR SA     \n        1  2  3  4  5                      1  2          1  2  3  4  5  6     \n  6  7  8  9 10 11 12       3  4  5  6  7  8  9       7  8  9 10 11 12 13     \n 13 14 15 16 17 18 19      10 11 12 13 14 15 16      14 15 16 17 18 19 20     \n 20 21 22 23 24 25 26      17 18 19 20 21 22 23      21 22 23 24 25 26 27     \n 27 28 29 30 31            24 25 26 27 28 29 30      28 29 30                 \n                           31                                                 \n\n       OCTOBER                   NOVEMBER                  DECEMBER           \n SU MO TU WE TH FR SA      SU MO TU WE TH FR SA      SU MO TU WE TH FR SA     \n           1  2  3  4                         1          1  2  3  4  5  6     \n  5  6  7  8  9 10 11       2  3  4  5  6  7  8       7  8  9 10 11 12 13     \n 12 13 14 15 16 17 18       9 10 11 12 13 14 15      14 15 16 17 18 19 20     \n 19 20 21 22 23 24 25      16 17 18 19 20 21 22      21 22 23 24 25 26 27     \n 26 27 28 29 30 31         23 24 25 26 27 28 29      28 29 30 31              \n                           30                                                 \n\n","human_summarization":"The code provides an algorithm for a calendar task, formatted to fit a page that is 132 characters wide, with all the code written in uppercase. It takes an uppercase version of the Calendar program as input, makes minimal changes to make it runnable, and outputs a runnable program. The output is then printed to the terminal.","id":1281}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nvar total, prim, maxPeri int64\n\nfunc newTri(s0, s1, s2 int64) {\n    if p := s0 + s1 + s2; p <= maxPeri {\n        prim++\n        total += maxPeri \/ p\n        newTri(+1*s0-2*s1+2*s2, +2*s0-1*s1+2*s2, +2*s0-2*s1+3*s2)\n        newTri(+1*s0+2*s1+2*s2, +2*s0+1*s1+2*s2, +2*s0+2*s1+3*s2)\n        newTri(-1*s0+2*s1+2*s2, -2*s0+1*s1+2*s2, -2*s0+2*s1+3*s2)\n    }\n}\n\nfunc main() {\n    for maxPeri = 100; maxPeri <= 1e11; maxPeri *= 10 {\n        prim = 0\n        total = 0\n        newTri(3, 4, 5)\n        fmt.Printf(\"Up to %d:  %d triples, %d primitives\\n\",\n            maxPeri, total, prim)\n    }\n}\n\n\nUp to 100:  17 triples, 7 primitives\nUp to 1000:  325 triples, 70 primitives\nUp to 10000:  4858 triples, 703 primitives\nUp to 100000:  64741 triples, 7026 primitives\nUp to 1000000:  808950 triples, 70229 primitives\nUp to 10000000:  9706567 triples, 702309 primitives\nUp to 100000000:  113236940 triples, 7023027 primitives\nUp to 1000000000:  1294080089 triples, 70230484 primitives\nUp to 10000000000:  14557915466 triples, 702304875 primitives\nUp to 100000000000:  161750315680 triples, 7023049293 primitives\n\n","human_summarization":"\"Calculate the number of Pythagorean triples with a perimeter no larger than 100 and the number of these that are primitive. The program should also be able to handle large values up to 100,000,000 for extra credit.\"","id":1282}
    {"lang_cluster":"Go","source_code":"\nLibrary: go-gtk\npackage main\n\nimport (\n    \"github.com\/mattn\/go-gtk\/glib\"\n    \"github.com\/mattn\/go-gtk\/gtk\"\n)\n\nfunc main() {\n    gtk.Init(nil)\n    window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)\n    window.Connect(\"destroy\",\n        func(*glib.CallbackContext) { gtk.MainQuit() }, \"\")\n    window.Show()\n    gtk.Main()\n}\n\nLibrary: Go-SDL\npackage main\n\nimport (\n    \"log\"\n\n    \"github.com\/veandco\/go-sdl2\/sdl\"\n)\n\nfunc main() {\n    window, err := sdl.CreateWindow(\"RC Window Creation\",\n        sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,\n        320, 200, 0)\n    if err != nil {\n        log.Fatal(err)\n    }\n    for {\n        if _, ok := sdl.WaitEvent().(*sdl.QuitEvent); ok {\n            break\n        }\n    }\n    window.Destroy()\n}\n\npackage main\n\nimport (\n    \"code.google.com\/p\/x-go-binding\/ui\"\n    \"code.google.com\/p\/x-go-binding\/ui\/x11\"\n    \"log\"\n)\n\nfunc main() {\n    win, err := x11.NewWindow()\n    if err != nil {\n        log.Fatalf(\"Error: %v\\n\", err)\n    }\n    defer win.Close()\n\n    for ev := range win.EventChan() {\n        switch e := ev.(type) {\n        case ui.ErrEvent:\n            log.Fatalf(\"Error: %v\\n\", e.Err)\n        }\n    }\n}\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":1283}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"io\/ioutil\"\n    \"sort\"\n    \"unicode\"\n)\n\nconst file = \"unixdict.txt\"\n\nfunc main() {\n    bs, err := ioutil.ReadFile(file)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    m := make(map[rune]int)\n    for _, r := range string(bs) {\n        m[r]++\n    }\n    \/\/ answer is now in m.  sort and format output:\n    lfs := make(lfList, 0, len(m))\n    for l, f := range m {\n        lfs = append(lfs, &letterFreq{l, f})\n    }\n    sort.Sort(lfs)\n    fmt.Println(\"file:\", file)\n    fmt.Println(\"letter  frequency\")\n    for _, lf := range lfs {\n        if unicode.IsGraphic(lf.rune) {\n            fmt.Printf(\"   %c    %7d\\n\", lf.rune, lf.freq)\n        } else {\n            fmt.Printf(\"%U  %7d\\n\", lf.rune, lf.freq)\n        }\n    }\n}\n\ntype letterFreq struct {\n    rune\n    freq int\n}\ntype lfList []*letterFreq\n\nfunc (lfs lfList) Len() int { return len(lfs) }\nfunc (lfs lfList) Less(i, j int) bool {\n    switch fd := lfs[i].freq - lfs[j].freq; {\n    case fd < 0:\n        return false\n    case fd > 0:\n        return true\n    }\n    return lfs[i].rune < lfs[j].rune\n}\nfunc (lfs lfList) Swap(i, j int) {\n    lfs[i], lfs[j] = lfs[j], lfs[i]\n}\n\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":1284}
    {"lang_cluster":"Go","source_code":"\ntype Ele struct {\n    Data interface{}\n    Next *Ele\n}\n\nfunc (e *Ele) Append(data interface{}) *Ele {\n    if e.Next == nil {\n        e.Next = &Ele{data, nil}\n    } else {\n        tmp := &Ele{data, e.Next}\n        e.Next = tmp\n    }\n    return e.Next\n}\n\nfunc (e *Ele) String() string {\n    return fmt.Sprintf(\"Ele: %v\", e.Data)\n}\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":1285}
    {"lang_cluster":"Go","source_code":"\npng converted from output ppm\npackage main\n\n\/\/ Files required to build supporting package raster are found in:\n\/\/ * Bitmap\n\/\/ * Grayscale image\n\/\/ * Xiaolin Wu's line algorithm\n\/\/ * Write a PPM file\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\nconst (\n    width  = 400\n    height = 300\n    depth  = 8\n    angle  = 12\n    length = 50\n    frac   = .8\n)\n\nfunc main() {\n    g := raster.NewGrmap(width, height)\n    ftree(g, width\/2, height*9\/10, length, 0, depth)\n    g.Bitmap().WritePpmFile(\"ftree.ppm\")\n}\n\nfunc ftree(g *raster.Grmap, x, y, distance, direction float64, depth int) {\n    x2 := x + distance*math.Sin(direction*math.Pi\/180)\n    y2 := y - distance*math.Cos(direction*math.Pi\/180)\n    g.AaLine(x, y, x2, y2)\n    if depth > 0 {\n        ftree(g, x2, y2, distance*frac, direction-angle, depth-1)\n        ftree(g, x2, y2, distance*frac, direction+angle, depth-1)\n    }\n}\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":1286}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    printFactors(-1)\n    printFactors(0)\n    printFactors(1)\n    printFactors(2)\n    printFactors(3)\n    printFactors(53)\n    printFactors(45)\n    printFactors(64)\n    printFactors(600851475143)\n    printFactors(999999999999999989)\n}\n\nfunc printFactors(nr int64) {\n    if nr < 1 {\n        fmt.Println(\"\\nFactors of\", nr, \"not computed\")\n        return\n    }\n    fmt.Printf(\"\\nFactors of %d: \", nr)\n    fs := make([]int64, 1)\n    fs[0] = 1\n    apf := func(p int64, e int) {\n        n := len(fs)\n        for i, pp := 0, p; i < e; i, pp = i+1, pp*p {\n            for j := 0; j < n; j++ {\n                fs = append(fs, fs[j]*pp)\n            }\n        }\n    }\n    e := 0\n    for ; nr & 1 == 0; e++ {\n        nr >>= 1\n    }\n    apf(2, e)\n    for d := int64(3); nr > 1; d += 2 {\n        if d*d > nr {\n            d = nr\n        }\n        for e = 0; nr%d == 0; e++ {\n            nr \/= d\n        }\n        if e > 0 {\n            apf(d, e)\n        }\n    }\n    fmt.Println(fs)\n    fmt.Println(\"Number of factors =\", len(fs))\n}\n\n\n","human_summarization":"compute the factors of a positive integer, excluding zero and negative integers. It uses trial division without a prime number generator, optimized for factoring any 64-bit integer, with large primes taking several seconds. It also notes that every prime number has two factors: 1 and itself.","id":1287}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst text = `Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.`\n\ntype formatter struct {\n    text  [][]string\n    width []int\n}\n\nfunc newFormatter(text string) *formatter {\n    var f formatter\n    for _, line := range strings.Split(text, \"\\n\") {\n        words := strings.Split(line, \"$\")\n        for words[len(words)-1] == \"\" {\n            words = words[:len(words)-1]\n        }\n        f.text = append(f.text, words)\n        for i, word := range words {\n            if i == len(f.width) {\n                f.width = append(f.width, len(word))\n            } else if len(word) > f.width[i] {\n                f.width[i] = len(word)\n            }\n        }\n    }\n    return &f\n}\n\nconst (\n    left = iota\n    middle\n    right\n)\n\nfunc (f formatter) print(j int) {\n    for _, line := range f.text {\n        for i, word := range line {\n            fmt.Printf(\"%-*s \", f.width[i], fmt.Sprintf(\"%*s\",\n                len(word)+(f.width[i]-len(word))*j\/2, word))\n        }\n        fmt.Println(\"\")\n    }\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    f := newFormatter(text)\n    f.print(left)\n    f.print(middle)\n    f.print(right)\n}\n\nGiven      a          text       file   of     many      lines,     where    fields  within  a      line\nare        delineated by         a      single 'dollar'  character, write    a       program\nthat       aligns     each       column of     fields    by         ensuring that    words   in     each\ncolumn     are        separated  by     at     least     one        space.\nFurther,   allow      for        each   word   in        a          column   to      be      either left\njustified, right      justified, or     center justified within     its      column.\n\n  Given        a         text     file    of     many      lines,    where   fields  within    a    line\n   are     delineated     by       a    single 'dollar'  character,  write      a    program\n   that      aligns      each    column   of    fields       by     ensuring  that    words    in   each\n  column      are     separated    by     at     least      one      space.\n Further,    allow       for      each   word     in         a       column    to      be    either left\njustified,   right    justified,   or   center justified   within     its    column.\n\n     Given          a       text   file     of      many     lines,    where  fields  within      a line\n       are delineated         by      a single  'dollar' character,    write       a program\n      that     aligns       each column     of    fields         by ensuring    that   words     in each\n    column        are  separated     by     at     least        one   space.\n  Further,      allow        for   each   word        in          a   column      to      be either left\njustified,      right justified,     or center justified     within      its column.\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":1288}
    {"lang_cluster":"Go","source_code":"package main\n\nimport \"fmt\"\n\nfunc cuboid(dx, dy, dz int) {\n    fmt.Printf(\"cuboid %d %d %d:\\n\", dx, dy, dz)\n    cubLine(dy+1, dx, 0, \"+-\")\n    for i := 1; i <= dy; i++ {\n        cubLine(dy-i+1, dx, i-1, \"\/ |\")\n    }\n    cubLine(0, dx, dy, \"+-|\")\n    for i := 4*dz - dy - 2; i > 0; i-- {\n        cubLine(0, dx, dy, \"| |\")\n    }\n    cubLine(0, dx, dy, \"| +\")\n    for i := 1; i <= dy; i++ {\n        cubLine(0, dx, dy-i, \"| \/\")\n    }\n    cubLine(0, dx, 0, \"+-\\n\")\n}\n\nfunc cubLine(n, dx, dy int, cde string) {\n    fmt.Printf(\"%*s\", n+1, cde[:1])\n    for d := 9*dx - 1; d > 0; d-- {\n        fmt.Print(cde[1:2])\n    }\n    fmt.Print(cde[:1])\n    fmt.Printf(\"%*s\\n\", dy+1, cde[2:])\n}\n\nfunc main() {\n    cuboid(2, 3, 4)\n    cuboid(1, 1, 1)\n    cuboid(6, 2, 1)\n}\n\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":1289}
    {"lang_cluster":"Go","source_code":"\nLibrary: go-ldap-client\n\npackage main\n\nimport (\n    \"log\"\n    \"github.com\/jtblin\/go-ldap-client\"\n)\n\nfunc main() {\n    client := &ldap.LDAPClient{\n        Base:         \"dc=example,dc=com\",\n        Host:         \"ldap.example.com\",\n        Port:         389,\n        UseSSL:       false,\n        BindDN:       \"uid=readonlyuser,ou=People,dc=example,dc=com\",\n        BindPassword: \"readonlypassword\",\n        UserFilter:   \"(uid=%s)\",\n        GroupFilter:  \"(memberUid=%s)\",\n        Attributes:   []string{\"givenName\", \"sn\", \"mail\", \"uid\"},\n    }\n    defer client.Close()\n    err := client.Connect()\n    if err != nil { \n        log.Fatalf(\"Failed to connect\u00a0:\u00a0%+v\", err)\n    }\n    \/\/ Do something\n}\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server using a simple third-party LDAP library in Go. The implementation is largely based on the example provided in the library's main page.","id":1290}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc rot13char(c rune) rune {\n    if c >= 'a' && c <= 'm' || c >= 'A' && c <= 'M' {\n        return c + 13\n    } else if c >= 'n' && c <= 'z' || c >= 'N' && c <= 'Z' {\n        return c - 13\n    }\n    return c\n}\n\nfunc rot13(s string) string {\n    return strings.Map(rot13char, s)\n}\n\nfunc main() {\n    fmt.Println(rot13(\"nowhere ABJURER\"))\n}\n\n\nabjurer NOWHERE\n\n","human_summarization":"implement a rot-13 encoding function that can be optionally wrapped in a utility program. The function replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet, preserving case and passing all non-alphabetic characters without alteration. This encoding is used for obfuscating text to prevent casual reading of spoiler or offensive material.","id":1291}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype pair struct {\n    name, value string\n}\ntype csArray []pair\n\n\/\/ three methods satisfy sort.Interface\nfunc (a csArray) Less(i, j int) bool { return a[i].name < a[j].name }\nfunc (a csArray) Len() int           { return len(a) }\nfunc (a csArray) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }\n\nvar x = csArray{\n    pair{\"joe\", \"120\"},\n    pair{\"foo\", \"31\"},\n    pair{\"bar\", \"251\"},\n}\n\nfunc main() {\n    sort.Sort(x)\n    for _, p := range x {\n        fmt.Printf(\"%5s: %s\\n\", p.name, p.value)\n    }\n}\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":1292}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 1; i <= 5; i++ {\n        for j := 1; j <= i; j++ {\n            fmt.Printf(\"*\")\n        }\n        fmt.Printf(\"\\n\")\n    }\n}\n\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":1293}
    {"lang_cluster":"Go","source_code":"\n\n\/\/ declare a nil map variable, for maps from string to int\nvar x map[string]int\n\n\/\/ make an empty map\nx = make(map[string]int)\n\n\/\/ make an empty map with an initial capacity\nx = make(map[string]int, 42)\n\n\/\/ set a value\nx[\"foo\"] = 3\n\n\/\/ getting values\ny1 := x[\"bar\"]     \/\/ zero value returned if no map entry exists for the key\ny2, ok := x[\"bar\"] \/\/ ok is a boolean, true if key exists in the map\n\n\/\/ removing keys\ndelete(x, \"foo\")\n\n\/\/ make a map with a literal\nx = map[string]int{\n\t\"foo\": 2, \"bar\": 42, \"baz\": -1,\n}\n\n","human_summarization":"Code summarization: The code creates an associative array or dictionary, which supports keys of boolean, numeric, string, pointer, channel, interface types, structs and arrays containing these types. It does not support slice, function, and map types as keys.","id":1294}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\n\/\/ basic linear congruential generator\nfunc lcg(a, c, m, seed uint32) func() uint32 {\n    r := seed\n    return func() uint32 {\n        r = (a*r + c) % m\n        return r\n    }\n}\n\n\/\/ microsoft generator has extra division step\nfunc msg(seed uint32) func() uint32 {\n    g := lcg(214013, 2531011, 1<<31, seed)\n    return func() uint32 {\n        return g() \/ (1 << 16)\n    }\n}\n\nfunc example(seed uint32) {\n    fmt.Printf(\"\\nWith seed = %d\\n\", seed)\n    bsd := lcg(1103515245, 12345, 1<<31, seed)\n    msf := msg(seed)\n    fmt.Println(\"       BSD  Microsoft\")\n    for i := 0; i < 5; i++ {\n        fmt.Printf(\"%10d    %5d\\n\", bsd(), msf())\n    }\n}\n\nfunc main() {\n    example(0)\n    example(1)\n}\n\n\nWith seed = 0\n       BSD  Microsoft\n     12345       38\n1406932606     7719\n 654583775    21238\n1449466924     2437\n 229283573     8855\n\nWith seed = 1\n       BSD  Microsoft\n1103527590       41\n 377401575    18467\n 662824084     6334\n1147902781    26500\n2035015474    19169\n\n","human_summarization":"\"Implement two historic random number generators: the rand() function from BSD libc and the rand() function from Microsoft C Runtime (MSCVRT.DLL). The generators use a linear congruential generator formula and must yield the same sequence of integers as the original generator when given the same seed. The BSD generator produces a random number in the range 0 to 2147483647, while the Microsoft generator produces a random number in the range 0 to 32767.\"","id":1295}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\ntype Ele struct {\n    Data interface{}\n    Next *Ele\n}\n\nfunc (e *Ele) insert(data interface{}) {\n    if e == nil {\n        panic(\"attept to modify nil\")\n    }\n    e.Next = &Ele{data, e.Next}\n}\n\nfunc (e *Ele) printList() {\n    if e == nil {\n        fmt.Println(nil)\n        return\n    }\n    fmt.Printf(\"(%v\", e.Data)\n    for {\n        e = e.Next\n        if e == nil {\n            fmt.Println(\")\")\n            return\n        }\n        fmt.Print(\" \", e.Data)\n    }\n}\n\nfunc main() {\n    h := &Ele{\"A\", &Ele{\"B\", nil}}\n    h.printList()\n    h.insert(\"C\")\n    h.printList()\n}\n\n\n(A B)\n(A C B)\n\n","human_summarization":"\"Code implements a method to insert an element into a singly-linked list after a specified element, specifically inserting element 'C' after element 'A' in a list of elements 'A->B'.\"","id":1296}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc halve(i int) int { return i\/2 }\n\nfunc double(i int) int { return i*2 }\n\nfunc isEven(i int) bool { return i%2 == 0 }\n\nfunc ethMulti(i, j int) (r int) {\n    for ; i > 0; i, j = halve(i), double(j) {\n        if !isEven(i) {\n            r += j\n        }\n    }\n    return\n}\n\nfunc main() {\n    fmt.Printf(\"17 ethiopian 34 = %d\\n\", ethMulti(17, 34))\n}\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":1297}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"fmt\"\n\t\"math\/rand\"\n\t\"time\"\n)\n\nconst (\n\top_num = iota\n\top_add\n\top_sub\n\top_mul\n\top_div\n)\n\ntype frac struct {\n\tnum, denom int\n}\n\n\/\/ Expression: can either be a single number, or a result of binary\n\/\/ operation from left and right node\ntype Expr struct {\n\top          int\n\tleft, right *Expr\n\tvalue       frac\n}\n\nvar n_cards = 4\nvar goal = 24\nvar digit_range = 9\n\nfunc (x *Expr) String() string {\n\tif x.op == op_num {\n\t\treturn fmt.Sprintf(\"%d\", x.value.num)\n\t}\n\n\tvar bl1, br1, bl2, br2, opstr string\n\tswitch {\n\tcase x.left.op == op_num:\n\tcase x.left.op >= x.op:\n\tcase x.left.op == op_add && x.op == op_sub:\n\t\tbl1, br1 = \"\", \"\"\n\tdefault:\n\t\tbl1, br1 = \"(\", \")\"\n\t}\n\n\tif x.right.op == op_num || x.op < x.right.op {\n\t\tbl2, br2 = \"\", \"\"\n\t} else {\n\t\tbl2, br2 = \"(\", \")\"\n\t}\n\n\tswitch {\n\tcase x.op == op_add:\n\t\topstr = \" + \"\n\tcase x.op == op_sub:\n\t\topstr = \" - \"\n\tcase x.op == op_mul:\n\t\topstr = \" * \"\n\tcase x.op == op_div:\n\t\topstr = \" \/ \"\n\t}\n\n\treturn bl1 + x.left.String() + br1 + opstr +\n\t\tbl2 + x.right.String() + br2\n}\n\nfunc expr_eval(x *Expr) (f frac) {\n\tif x.op == op_num {\n\t\treturn x.value\n\t}\n\n\tl, r := expr_eval(x.left), expr_eval(x.right)\n\n\tswitch x.op {\n\tcase op_add:\n\t\tf.num = l.num*r.denom + l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_sub:\n\t\tf.num = l.num*r.denom - l.denom*r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_mul:\n\t\tf.num = l.num * r.num\n\t\tf.denom = l.denom * r.denom\n\t\treturn\n\n\tcase op_div:\n\t\tf.num = l.num * r.denom\n\t\tf.denom = l.denom * r.num\n\t\treturn\n\t}\n\treturn\n}\n\nfunc solve(ex_in []*Expr) bool {\n\t\/\/ only one expression left, meaning all numbers are arranged into\n\t\/\/ a binary tree, so evaluate and see if we get 24\n\tif len(ex_in) == 1 {\n\t\tf := expr_eval(ex_in[0])\n\t\tif f.denom != 0 && f.num == f.denom*goal {\n\t\t\tfmt.Println(ex_in[0].String())\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\tvar node Expr\n\tex := make([]*Expr, len(ex_in)-1)\n\n\t\/\/ try to combine a pair of expressions into one, thus reduce\n\t\/\/ the list length by 1, and recurse down\n\tfor i := range ex {\n\t\tcopy(ex[i:len(ex)], ex_in[i+1:len(ex_in)])\n\n\t\tex[i] = &node\n\t\tfor j := i + 1; j < len(ex_in); j++ {\n\t\t\tnode.left = ex_in[i]\n\t\t\tnode.right = ex_in[j]\n\n\t\t\t\/\/ try all 4 operators\n\t\t\tfor o := op_add; o <= op_div; o++ {\n\t\t\t\tnode.op = o\n\t\t\t\tif solve(ex) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/ also - and \/ are not commutative, so swap arguments\n\t\t\tnode.left = ex_in[j]\n\t\t\tnode.right = ex_in[i]\n\n\t\t\tnode.op = op_sub\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tnode.op = op_div\n\t\t\tif solve(ex) {\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tif j < len(ex) {\n\t\t\t\tex[j] = ex_in[j]\n\t\t\t}\n\t\t}\n\t\tex[i] = ex_in[i]\n\t}\n\treturn false\n}\n\nfunc main() {\n\tcards := make([]*Expr, n_cards)\n\trand.Seed(time.Now().Unix())\n\n\tfor k := 0; k < 10; k++ {\n\t\tfor i := 0; i < n_cards; i++ {\n\t\t\tcards[i] = &Expr{op_num, nil, nil,\n\t\t\t\tfrac{rand.Intn(digit_range-1) + 1, 1}}\n\t\t\tfmt.Printf(\" %d\", cards[i].value.num)\n\t\t}\n\t\tfmt.Print(\":  \")\n\t\tif !solve(cards) {\n\t\t\tfmt.Println(\"No solution\")\n\t\t}\n\t}\n}\n\n\n","human_summarization":"The code accepts four digits, either from user input or randomly generated, and calculates arithmetic expressions following the 24 game rules. It also displays examples of the solutions it generates.","id":1298}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/big\"\n)\n\nfunc main() {\n    fmt.Println(factorial(800))\n}\n\nfunc factorial(n int64) *big.Int {\n    if n < 0 {\n        return nil\n    }\n    r\u00a0:= big.NewInt(1)\n    var f big.Int\n    for i\u00a0:= int64(2); i <= n; i++ {\n        r.Mul(r, f.SetInt64(i))\n    }\n    return r\n}\n\npackage main\n\nimport (\n    \"math\/big\"\n    \"fmt\"\n)\n\nfunc factorial(n int64) *big.Int {\n    var z big.Int\n    return z.MulRange(1, n)\n}\n\nfunc main() {\n    fmt.Println(factorial(800))\n}\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc factorial(n float64) float64 {\n    return math.Gamma(n + 1)\n}\n\nfunc main() {\n    for i\u00a0:= 0.; i <= 10; i++ {\n        fmt.Println(i, factorial(i))\n    }\n    fmt.Println(100, factorial(100))\n}\n\n","human_summarization":"The code implements a function to calculate the factorial of a given number, either iteratively or recursively. It may optionally include error handling for negative input values. The function utilizes a divide and conquer technique for efficient computation, capable of handling large numbers up to a million.","id":1299}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"bufio\"\n    \"bytes\"\n    \"fmt\"\n    \"math\/rand\"\n    \"os\"\n    \"strings\"\n    \"time\"\n)\n\nfunc main() {\n    fmt.Println(`Cows and Bulls\nGuess four digit number of unique digits in the range 1 to 9.\nA correct digit but not in the correct place is a cow.\nA correct digit in the correct place is a bull.`)\n    \/\/ generate pattern\n    pat := make([]byte, 4)\n    rand.Seed(time.Now().Unix())\n    r := rand.Perm(9)\n    for i := range pat {\n        pat[i] = '1' + byte(r[i])\n    }\n\n    \/\/ accept and score guesses\n    valid := []byte(\"123456789\")\nguess:\n    for in := bufio.NewReader(os.Stdin); ; {\n        fmt.Print(\"Guess: \")\n        guess, err := in.ReadString('\\n')\n        if err != nil {\n            fmt.Println(\"\\nSo, bye.\")\n            return\n        }\n        guess = strings.TrimSpace(guess)\n        if len(guess) != 4 {\n            \/\/ malformed:  not four characters\n            fmt.Println(\"Please guess a four digit number.\")\n            continue\n        }\n        var cows, bulls int\n        for ig, cg := range guess {\n            if strings.IndexRune(guess[:ig], cg) >= 0 {\n                \/\/ malformed:  repeated digit\n                fmt.Printf(\"Repeated digit: %c\\n\", cg)\n                continue guess\n            }\n            switch bytes.IndexByte(pat, byte(cg)) {\n            case -1:\n                if bytes.IndexByte(valid, byte(cg)) == -1 {\n                    \/\/ malformed:  not a digit\n                    fmt.Printf(\"Invalid digit: %c\\n\", cg)\n                    continue guess\n                }\n            default: \/\/ I just think cows should go first\n                cows++\n            case ig:\n                bulls++\n            }\n        }\n        fmt.Printf(\"Cows: %d, bulls: %d\\n\", cows, bulls)\n        if bulls == 4 {\n            fmt.Println(\"You got it.\")\n            return\n        }\n    }\n}\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":1300}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math\/rand\"\n    \"strings\"\n    \"time\"\n)\n\nconst mean = 1.0\nconst stdv = .5\nconst n = 1000\n\nfunc main() {\n    var list [n]float64\n    rand.Seed(time.Now().UnixNano())\n    for i := range list {\n        list[i] = mean + stdv*rand.NormFloat64()\n    }\n    \/\/ show computed mean and stdv of list\n    var s, sq float64\n    for _, v := range list {\n        s += v\n    }\n    cm := s \/ n\n    for _, v := range list {\n        d := v - cm\n        sq += d * d\n    }\n    fmt.Printf(\"mean\u00a0%.3f, stdv\u00a0%.3f\\n\", cm, math.Sqrt(sq\/(n-1)))\n    \/\/ show histogram by hdiv divisions per stdv over +\/-hrange stdv\n    const hdiv = 3\n    const hrange = 2\n    var h [1 + 2*hrange*hdiv]int\n    for _, v := range list {\n        bin := hrange*hdiv + int(math.Floor((v-mean)\/stdv*hdiv+.5))\n        if bin >= 0 && bin < len(h) {\n            h[bin]++\n        }\n    }\n    const hscale = 10\n    for _, c := range h {\n        fmt.Println(strings.Repeat(\"*\", (c+hscale\/2)\/hscale))\n    }\n}\n\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using the math\/rand package in the standard library. The code also references the subrepository rand package at https:\/\/godoc.org\/golang.org\/x\/exp\/rand for additional functionality.","id":1301}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"errors\"\n    \"fmt\"\n    \"log\"\n)\n\nvar (\n    v1 = []int{1, 3, -5}\n    v2 = []int{4, -2, -1}\n)\n\nfunc dot(x, y []int) (r int, err error) {\n    if len(x) != len(y) {\n        return 0, errors.New(\"incompatible lengths\")\n    }\n    for i, xi := range x {\n        r += xi * y[i]\n    }\n    return\n}\n\nfunc main() {\n    d, err := dot([]int{1, 3, -5}, []int{4, -2, -1})\n    if err != nil {\n        log.Fatal(err)\n    }\n    fmt.Println(d)\n}\n\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":1302}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc main() {\n\tin := bufio.NewReader(os.Stdin)\n\tfor {\n\t\ts, err := in.ReadString('\\n')\n\t\tif err != nil {\n\t\t\t\/\/ io.EOF is expected, anything else\n\t\t\t\/\/ should be handled\/reported\n\t\t\tif err != io.EOF {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\t\t\/\/ Do something with the line of text\n\t\t\/\/ in string variable s.\n\t\t_ = s\n\t}\n}\n\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"log\"\n\t\"os\"\n)\n\nfunc main() {\n\ts := bufio.NewScanner(os.Stdin)\n\t\/\/ Select the split function, other ones are available\n\t\/\/ in bufio or you can provide your own.\n\ts.Split(bufio.ScanWords)\n\tfor s.Scan() {\n\t\t\/\/ Get and use the next 'token'\n\t\tasBytes := s.Bytes() \/\/ Bytes does no alloaction\n\t\tasString := s.Text() \/\/ Text returns a newly allocated string\n\t\t_, _ = asBytes, asString\n\t}\n\tif err := s.Err(); err != nil {\n\t\t\/\/ Handle\/report any error (EOF will not be reported)\n\t\tlog.Fatal(err)\n\t}\n}\n\n","human_summarization":"read either word-by-word or line-by-line from a text stream until there's no more data. It uses bufio.Scanner to read a line, word, byte, Unicode code point, or any custom split function at a time.","id":1303}
    {"lang_cluster":"Go","source_code":"\nLibrary: gitlab.com\/stone.code\/xmldom-go.git\n\npackage main\n\nimport (\n    \"fmt\"\n    dom \"gitlab.com\/stone.code\/xmldom-go.git\"\n)\n\nfunc main() {\n    d, err := dom.ParseStringXml(`\n<?xml version=\"1.0\"\u00a0?>\n<root>\n    <element>\n        Some text here\n    <\/element>\n<\/root>`)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    fmt.Println(string(d.ToXml()))\n}\n\n\n","human_summarization":"This code creates a simple Document Object Model (DOM) and serializes it into an XML format. It is a small subset of the W3C DOM Core implemented in Go language, extending the functionality of an existing XML parser. The code is a fork of the unsupported godom project. The serialized XML includes a root element containing a single element with some text.","id":1304}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"time\"\nimport \"fmt\"\n\nfunc main() {\n    t := time.Now()\n    fmt.Println(t)                                    \/\/ default format\n    fmt.Println(t.Format(\"Mon Jan  2 15:04:05 2006\")) \/\/ some custom format\n}\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":1305}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"strconv\"\n)\n\nconst input = `710889\nB0YBKJ\n406566\nB0YBLH\n228276\nB0YBKL\n557910\nB0YBKR\n585284\nB0YBKT\nB00030\n\nB\nB0003\nB000300\nA00030\nE00030\nI00030\nO00030\nU00030\n\u03b200030\n\u03b20003`\n\nvar weight = [...]int{1,3,1,7,3,9}\n\nfunc csd(code string) string {\n    switch len(code) {\n    case 6:\n    case 0:\n        return \"No data\"\n    default:\n        return \"Invalid length\"\n    }\n    sum := 0\n    for i, c := range code {\n        n, err := strconv.ParseInt(string(c), 36, 0)\n        if err != nil || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' {\n            return \"Invalid character\"\n        }\n        sum += int(n)*weight[i]\n    }\n    return strconv.Itoa(9-(sum-1)%10)\n}   \n    \nfunc main() {\n    for _, s := range strings.Split(input, \"\\n\") {\n        d := csd(s)\n        if len(d) > 1 {\n            fmt.Printf(\":%s: %s\\n\", s, d)\n        } else {\n            fmt.Println(s + d)\n        }\n    }\n}\n\n\n7108899\nB0YBKJ7\n4065663\nB0YBLH2\n2282765\nB0YBKL9\n5579107\nB0YBKR5\n5852842\nB0YBKT7\nB000300\n:: No data\n:B: Invalid length\n:B0003: Invalid length\n:B000300: Invalid length\n:A00030: Invalid character\n:E00030: Invalid character\n:I00030: Invalid character\n:O00030: Invalid character\n:U00030: Invalid character\n:\u03b200030: Invalid length\n:\u03b20003: Invalid character\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end. It also validates the input to ensure it is correctly formed according to SEDOL string rules.","id":1306}
    {"lang_cluster":"Go","source_code":"\nOutput png\npackage main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image\/color\"\n    \"image\/png\"\n    \"math\"\n    \"os\"\n)\n\ntype vector [3]float64\n\nfunc normalize(v *vector) {\n    invLen := 1 \/ math.Sqrt(dot(v, v))\n    v[0] *= invLen\n    v[1] *= invLen\n    v[2] *= invLen\n}\n\nfunc dot(x, y *vector) float64 {\n    return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n}\n\nfunc drawSphere(r int, k, amb float64, dir *vector) *image.Gray {\n    w, h := r*4, r*3\n    img := image.NewGray(image.Rect(-w\/2, -h\/2, w\/2, h\/2))\n    vec := new(vector)\n    for x := -r; x < r; x++ {\n        for y := -r; y < r; y++ {\n            if z := r*r - x*x - y*y; z >= 0 {\n                vec[0] = float64(x)\n                vec[1] = float64(y)\n                vec[2] = math.Sqrt(float64(z))\n                normalize(vec)\n                s := dot(dir, vec)\n                if s < 0 {\n                    s = 0\n                }\n                lum := 255 * (math.Pow(s, k) + amb) \/ (1 + amb)\n                if lum < 0 {\n                    lum = 0\n                } else if lum > 255 {\n                    lum = 255\n                }\n                img.SetGray(x, y, color.Gray{uint8(lum)})\n            }\n        }\n    }\n    return img\n}\n\nfunc main() {\n    dir := &vector{-30, -30, 50}\n    normalize(dir)\n    img := drawSphere(200, 1.5, .2, dir)\n    f, err := os.Create(\"sphere.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, img); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\n","human_summarization":"draw a graphical or ASCII art representation of a sphere, with the option for static or rotational projection, using an image library.","id":1307}
    {"lang_cluster":"Go","source_code":"package main\n\nimport \"fmt\"\n\nfunc ord(n int) string {\n    s := \"th\"\n    switch c := n % 10; c {\n    case 1, 2, 3:\n        if n%100\/10 == 1 {\n            break\n        }\n        switch c {\n        case 1:\n            s = \"st\"\n        case 2:\n            s = \"nd\"\n        case 3:\n            s = \"rd\"\n        }\n    }\n    return fmt.Sprintf(\"%d%s\", n, s)\n}\n\nfunc main() {\n    for n := 0; n <= 25; n++ {\n        fmt.Printf(\"%s \", ord(n))\n    }\n    fmt.Println()\n    for n := 250; n <= 265; n++ {\n        fmt.Printf(\"%s \", ord(n))\n    }\n    fmt.Println()\n    for n := 1000; n <= 1025; n++ {\n        fmt.Printf(\"%s \", ord(n))\n    }\n    fmt.Println()\n}\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":1308}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc stripchars(str, chr string) string {\n    return strings.Map(func(r rune) rune {\n        if strings.IndexRune(chr, r) < 0 {\n            return r\n        }\n        return -1\n    }, str)\n}\n\nfunc main() {\n    fmt.Println(stripchars(\"She was a soul stripper. She took my heart!\",\n        \"aei\"))\n}\n\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":1309}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"fmt\"\n)\n\nconst numbers = 3\n\nfunc main() {\n\n\t\/\/using the provided data\n\tmax := 20\n\twords := map[int]string{\n\t\t3: \"Fizz\",\n\t\t5: \"Buzz\",\n\t\t7: \"Baxx\",\n\t}\n\tkeys := []int{3, 5, 7}\n\tdivisible := false\n\tfor i := 1; i <= max; i++ {\n\t\tfor _, n := range keys {\n\t\t\tif i % n == 0 {\n\t\t\t\tfmt.Print(words[n])\n\t\t\t\tdivisible = true\n\t\t\t}\n\t\t}\n\t\tif !divisible {\n\t\t\tfmt.Print(i)\n\t\t}\n\t\tfmt.Println()\n\t\tdivisible = false\n\t}\n\n}\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":1310}
    {"lang_cluster":"Go","source_code":"\ns := \"world!\"\ns = \"Hello, \" + s\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":1311}
    {"lang_cluster":"Go","source_code":"\nOutput png\n\npackage main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image\/color\"\n    \"image\/draw\"\n    \"image\/png\"\n    \"math\"\n    \"os\"\n)\n\n\/\/ separation of the the two endpoints\n\/\/ make this a power of 2 for prettiest output\nconst sep = 512\n\/\/ depth of recursion.  adjust as desired for different visual effects.\nconst depth = 14\n\nvar s = math.Sqrt2 \/ 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = color.NRGBA{64, 192, 96, 255}\nvar b *image.NRGBA\n\nfunc main() {\n    width := sep * 11 \/ 6\n    height := sep * 4 \/ 3\n    bounds := image.Rect(0, 0, width, height)\n    b = image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.White), image.ZP, draw.Src)\n    dragon(14, 0, 1, sep, sep\/2, sep*5\/6)\n    f, err := os.Create(\"dragon.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        \/\/ Go packages used here do not have line drawing functions\n        \/\/ so we implement a very simple line drawing algorithm here.\n        \/\/ We take advantage of knowledge that we are always drawing\n        \/\/ 45 degree diagonal lines.\n        x1 := int(x + .5)\n        y1 := int(y + .5)\n        x2 := int(x + d*cos[a] + .5)\n        y2 := int(y + d*sin[a] + .5)\n        xInc := 1\n        if x1 > x2 {\n            xInc = -1\n        }\n        yInc := 1\n        if y1 > y2 {\n            yInc = -1\n        }\n        for x, y := x1, y1; ; x, y = x+xInc, y+yInc {\n            b.Set(x, y, p)\n            if x == x2 {\n                break\n            }\n        }\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n\n\npackage main\n\n\/\/ Files required to build supporting package raster are found in:\n\/\/ * Bitmap\n\/\/ * Write a PPM file\n\nimport (\n    \"math\"\n    \"raster\"\n)\n\n\/\/ separation of the the two endpoints\n\/\/ make this a power of 2 for prettiest output\nconst sep = 512\n\/\/ depth of recursion.  adjust as desired for different visual effects.\nconst depth = 14\n\nvar s = math.Sqrt2 \/ 2\nvar sin = []float64{0, s, 1, s, 0, -s, -1, -s}\nvar cos = []float64{1, s, 0, -s, -1, -s, 0, s}\nvar p = raster.Pixel{64, 192, 96}\nvar b *raster.Bitmap\n\nfunc main() {\n    width := sep * 11 \/ 6\n    height := sep * 4 \/ 3\n    b = raster.NewBitmap(width, height)\n    b.Fill(raster.Pixel{255, 255, 255})\n    dragon(14, 0, 1, sep, sep\/2, sep*5\/6)\n    b.WritePpmFile(\"dragon.ppm\")\n}\n\nfunc dragon(n, a, t int, d, x, y float64) {\n    if n <= 1 {\n        b.Line(int(x+.5), int(y+.5), int(x+d*cos[a]+.5), int(y+d*sin[a]+.5), p)\n        return\n    }\n    d *= s\n    a1 := (a - t) & 7\n    a2 := (a + t) & 7\n    dragon(n-1, a1, 1, d, x, y)\n    dragon(n-1, a2, -1, d, x+d*cos[a1], y+d*sin[a1])\n}\n\n","human_summarization":"The code generates a Dragon Curve fractal either by displaying it directly or writing it to an image file. It uses various algorithms to create the fractal, including recursive, successive approximation, iterative, and Lindenmayer system methods. The recursive method involves creating a right curling dragon followed by a left dragon at a 90-degree angle and vice versa. The successive approximation method rewrites each straight line as two new segments at a right angle. The iterative method uses bit manipulation to determine the turn direction at each point. The Lindenmayer system method uses two symbols for straight lines and applies rules for their transformation. The code also includes functionality to test whether a given point or segment is on the curve. The code can be adapted to use a standard image library, requiring additional line drawing code.","id":1312}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/rand\"\n    \"time\"\n)\n\nfunc main() {\n    fmt.Print(\"Guess number from 1 to 10: \")\n    rand.Seed(time.Now().Unix())\n    n := rand.Intn(10) + 1\n    for guess := n; ; fmt.Print(\"No. Try again: \") {\n        switch _, err := fmt.Scan(&guess); {\n        case err != nil:\n            fmt.Println(\"\\n\", err, \"\\nSo, bye.\")\n            return\n        case guess == n:\n            fmt.Println(\"Well guessed!\")\n            return\n        }\n    }\n}\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":1313}
    {"lang_cluster":"Go","source_code":"\nfunc loweralpha() string {\n\tp := make([]byte, 26)\n\tfor i := range p {\n\t\tp[i] = 'a' + byte(i)\n\t}\n\treturn string(p)\n}\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":1314}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"fmt\"\n)\n\nfunc main() {\n\tfor i := 0; i < 16; i++ {\n\t\tfmt.Printf(\"%b\\n\", i)\n\t}\n}\n\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":1315}
    {"lang_cluster":"Go","source_code":"package main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"sort\"\n)\n\ntype Patient struct {\n    id       int\n    lastName string\n}\n\n\/\/ maps an id to a lastname\nvar patientDir = make(map[int]string)\n\n\/\/ maintains a sorted list of ids\nvar patientIds []int\n\nfunc patientNew(id int, lastName string) Patient {\n    patientDir[id] = lastName\n    patientIds = append(patientIds, id)\n    sort.Ints(patientIds)\n    return Patient{id, lastName}\n}\n\ntype DS struct {\n    dates  []string\n    scores []float64\n}\n\ntype Visit struct {\n    id    int\n    date  string\n    score float64\n}\n\n\/\/ maps an id to lists of dates and scores\nvar visitDir = make(map[int]DS)\n\nfunc visitNew(id int, date string, score float64) Visit {\n    if date == \"\" {\n        date = \"0000-00-00\"\n    }\n    v, ok := visitDir[id]\n    if ok {\n        v.dates = append(v.dates, date)\n        v.scores = append(v.scores, score)\n        visitDir[id] = DS{v.dates, v.scores}\n    } else {\n        visitDir[id] = DS{[]string{date}, []float64{score}}\n    }\n    return Visit{id, date, score}\n}\n\ntype Merge struct{ id int }\n\nfunc (m Merge) lastName() string  { return patientDir[m.id] }\nfunc (m Merge) dates() []string   { return visitDir[m.id].dates }\nfunc (m Merge) scores() []float64 { return visitDir[m.id].scores }\n\nfunc (m Merge) lastVisit() string {\n    dates := m.dates()\n    dates2 := make([]string, len(dates))\n    copy(dates2, dates)\n    sort.Strings(dates2)\n    return dates2[len(dates2)-1]\n}\n\nfunc (m Merge) scoreSum() float64 {\n    sum := 0.0\n    for _, score := range m.scores() {\n        if score != -1 {\n            sum += score\n        }\n    }\n    return sum\n}\n\nfunc (m Merge) scoreAvg() float64 {\n    count := 0\n    for _, score := range m.scores() {\n        if score != -1 {\n            count++\n        }\n    }\n    return m.scoreSum() \/ float64(count)\n}\n\nfunc mergePrint(merges []Merge) {\n    fmt.Println(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\")\n    f := \"| %d       |\u00a0%-7s  | %s | %4s      | %4s      |\\n\"\n    for _, m := range merges {\n        _, ok := visitDir[m.id]\n        if ok {\n            lv := m.lastVisit()\n            if lv == \"0000-00-00\" {\n                lv = \"          \"\n            }\n            scoreSum := m.scoreSum()\n            ss := fmt.Sprintf(\"%4.1f\", scoreSum)\n            if scoreSum == 0 {\n                ss = \"    \"\n            }\n            scoreAvg := m.scoreAvg()\n            sa := \"    \"\n            if !math.IsNaN(scoreAvg) {\n                sa = fmt.Sprintf(\"%4.2f\", scoreAvg)\n            }\n            fmt.Printf(f, m.id, m.lastName(), lv, ss, sa)\n        } else {\n            fmt.Printf(f, m.id, m.lastName(), \"          \", \"    \", \"    \")\n        }\n    }\n}\n\nfunc main() {\n    patientNew(1001, \"Hopper\")\n    patientNew(4004, \"Wirth\")\n    patientNew(3003, \"Kemeny\")\n    patientNew(2002, \"Gosling\")\n    patientNew(5005, \"Kurtz\")\n\n    visitNew(2002, \"2020-09-10\", 6.8)\n    visitNew(1001, \"2020-09-17\", 5.5)\n    visitNew(4004, \"2020-09-24\", 8.4)\n    visitNew(2002, \"2020-10-08\", -1) \/\/ -1 signifies no score\n    visitNew(1001, \"\", 6.6)          \/\/ \"\" signifies no date\n    visitNew(3003, \"2020-11-12\", -1)\n    visitNew(4004, \"2020-11-05\", 7.0)\n    visitNew(1001, \"2020-11-19\", 5.3)\n\n    merges := make([]Merge, len(patientIds))\n    for i, id := range patientIds {\n        merges[i] = Merge{id}\n    }\n    mergePrint(merges)\n}\n\n\n","human_summarization":"\"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file.\"","id":1316}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image\/color\"\n    \"image\/draw\"\n)\n\nfunc main() {\n    rect := image.Rect(0, 0, 320, 240)\n    img := image.NewRGBA(rect)\n\n    \/\/ Use green background, say.\n    green := color.RGBA{0, 255, 0, 255}\n    draw.Draw(img, rect, &image.Uniform{green}, image.ZP, draw.Src)\n\n    \/\/ Set color of pixel at (100, 100) to red\n    red := color.RGBA{255, 0, 0, 255}\n    img.Set(100, 100, red)\n\n    \/\/ Check it worked.\n    cmap := map[color.Color]string{green: \"green\", red: \"red\"}\n    c1 := img.At(0, 0)\n    c2 := img.At(100, 100)\n    fmt.Println(\"The color of the pixel at (  0,   0) is\", cmap[c1], \"\\b.\")\n    fmt.Println(\"The color of the pixel at (100, 100) is\", cmap[c2], \"\\b.\")\n}\n\n\n","human_summarization":"Creates a 320x240 window and draws a red pixel at position (100,100).","id":1317}
    {"lang_cluster":"Go","source_code":"\n\npackage config\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"fmt\"\n\t\"bytes\"\n\t\"strings\"\n\t\"io\/ioutil\"\n)\n\nvar (\n\tENONE    = errors.New(\"Requested value does not exist\")\n\tEBADTYPE = errors.New(\"Requested type and actual type do not match\")\n\tEBADVAL  = errors.New(\"Value and type do not match\")\n)\n\ntype varError struct {\n\terr error\n\tn   string\n\tt   VarType\n}\n\nfunc (err *varError) Error() string {\n\treturn fmt.Sprintf(\"%v: (%q, %v)\", err.err, err.n, err.t)\n}\n\ntype VarType int\n\nconst (\n\tBool VarType = 1 + iota\n\tArray\n\tString\n)\n\nfunc (t VarType) String() string {\n\tswitch t {\n\tcase Bool:\n\t\treturn \"Bool\"\n\tcase Array:\n\t\treturn \"Array\"\n\tcase String:\n\t\treturn \"String\"\n\t}\n\n\tpanic(\"Unknown VarType\")\n}\n\ntype confvar struct {\n\tType VarType\n\tVal  interface{}\n}\n\ntype Config struct {\n\tm map[string]confvar\n}\n\nfunc Parse(r io.Reader) (c *Config, err error) {\n\tc = new(Config)\n\tc.m = make(map[string]confvar)\n\n\tbuf, err := ioutil.ReadAll(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tlines := bytes.Split(buf, []byte{'\\n'})\n\n\tfor _, line := range lines {\n\t\tline = bytes.TrimSpace(line)\n\t\tif len(line) == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tswitch line[0] {\n\t\tcase '#', ';':\n\t\t\tcontinue\n\t\t}\n\n\t\tparts := bytes.SplitN(line, []byte{' '}, 2)\n\t\tnam := string(bytes.ToLower(parts[0]))\n\n\t\tif len(parts) == 1 {\n\t\t\tc.m[nam] = confvar{Bool, true}\n\t\t\tcontinue\n\t\t}\n\n\t\tif strings.Contains(string(parts[1]), \",\") {\n\t\t\ttmpB := bytes.Split(parts[1], []byte{','})\n\t\t\tfor i := range tmpB {\n\t\t\t\ttmpB[i] = bytes.TrimSpace(tmpB[i])\n\t\t\t}\n\t\t\ttmpS := make([]string, 0, len(tmpB))\n\t\t\tfor i := range tmpB {\n\t\t\t\ttmpS = append(tmpS, string(tmpB[i]))\n\t\t\t}\n\n\t\t\tc.m[nam] = confvar{Array, tmpS}\n\t\t\tcontinue\n\t\t}\n\n\t\tc.m[nam] = confvar{String, string(bytes.TrimSpace(parts[1]))}\n\t}\n\n\treturn\n}\n\nfunc (c *Config) Bool(name string) (bool, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn false, nil\n\t}\n\n\tif c.m[name].Type != Bool {\n\t\treturn false, &varError{EBADTYPE, name, Bool}\n\t}\n\n\tv, ok := c.m[name].Val.(bool)\n\tif !ok {\n\t\treturn false, &varError{EBADVAL, name, Bool}\n\t}\n\treturn v, nil\n}\n\nfunc (c *Config) Array(name string) ([]string, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn nil, &varError{ENONE, name, Array}\n\t}\n\n\tif c.m[name].Type != Array {\n\t\treturn nil, &varError{EBADTYPE, name, Array}\n\t}\n\n\tv, ok := c.m[name].Val.([]string)\n\tif !ok {\n\t\treturn nil, &varError{EBADVAL, name, Array}\n\t}\n\treturn v, nil\n}\n\nfunc (c *Config) String(name string) (string, error) {\n\tname = strings.ToLower(name)\n\n\tif _, ok := c.m[name]; !ok {\n\t\treturn \"\", &varError{ENONE, name, String}\n\t}\n\n\tif c.m[name].Type != String {\n\t\treturn \"\", &varError{EBADTYPE, name, String}\n\t}\n\n\tv, ok := c.m[name].Val.(string)\n\tif !ok {\n\t\treturn \"\", &varError{EBADVAL, name, String}\n\t}\n\n\treturn v, nil\n}\n\n\npackage main\n\nimport (\n\t\"os\"\n\t\"fmt\"\n\t\"config\"\n)\n\nfunc main() {\n\tif len(os.Args) != 2 {\n\t\tfmt.Printf(\"Usage: %v <configfile>\\n\", os.Args[0])\n\t\tos.Exit(1)\n\t}\n\n\tfile, err := os.Open(os.Args[1])\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tdefer file.Close()\n\n\tconf, err := config.Parse(file)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tfullname, err := conf.String(\"fullname\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tfavouritefruit, err := conf.String(\"favouritefruit\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tneedspeeling, err := conf.Bool(\"needspeeling\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tseedsremoved, err := conf.Bool(\"seedsremoved\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\totherfamily, err := conf.Array(\"otherfamily\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Printf(\"FULLNAME: %q\\n\", fullname)\n\tfmt.Printf(\"FAVOURITEFRUIT: %q\\n\", favouritefruit)\n\tfmt.Printf(\"NEEDSPEELING: %q\\n\", needspeeling)\n\tfmt.Printf(\"SEEDSREMOVED: %q\\n\", seedsremoved)\n\tfmt.Printf(\"OTHERFAMILY: %q\\n\", otherfamily)\n}\n\n","human_summarization":"The code reads a standard configuration file, ignores lines starting with a hash or semicolon, and sets variables based on the configuration entries. It sets four variables: fullname, favouritefruit, needspeeling, and seedsremoved. It also handles an option with multiple parameters, storing them in an array. The configuration option names are not case sensitive, but the data is. An optional equals sign can be used to separate data from the option name.","id":1318}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc haversine(\u03b8 float64) float64 {\n    return .5 * (1 - math.Cos(\u03b8))\n}\n\ntype pos struct {\n    \u03c6 float64 \/\/ latitude, radians\n    \u03c8 float64 \/\/ longitude, radians\n}\n\nfunc degPos(lat, lon float64) pos {\n    return pos{lat * math.Pi \/ 180, lon * math.Pi \/ 180}\n}\n\nconst rEarth = 6372.8 \/\/ km\n\nfunc hsDist(p1, p2 pos) float64 {\n    return 2 * rEarth * math.Asin(math.Sqrt(haversine(p2.\u03c6-p1.\u03c6)+\n        math.Cos(p1.\u03c6)*math.Cos(p2.\u03c6)*haversine(p2.\u03c8-p1.\u03c8)))\n}\n\nfunc main() {\n    fmt.Println(hsDist(degPos(36.12, -86.67), degPos(33.94, -118.40)))\n}\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":1319}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"io\"\n    \"log\"\n    \"net\/http\"\n    \"os\"\n)\n\nfunc main() {\n    r, err := http.Get(\"http:\/\/rosettacode.org\/robots.txt\")\n    if err != nil {\n        log.Fatalln(err)\n    }\n    io.Copy(os.Stdout, r.Body)\n}\n\n\nUser-agent: *\nAllow: \/mw\/images\/\nAllow: \/mw\/skins\/\nAllow: \/mw\/title.png\nDisallow: \/w\/\nDisallow: \/mw\/\nDisallow: \/wiki\/Special:\n\n","human_summarization":"\"Prints the content of a specified URL to the console using HTTP request.\"","id":1320}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nconst input = `49927398716\n49927398717\n1234567812345678\n1234567812345670`\n\nvar t = [...]int{0, 2, 4, 6, 8, 1, 3, 5, 7, 9}\n\nfunc luhn(s string) bool {\n    odd := len(s) & 1\n    var sum int\n    for i, c := range s {\n        if c < '0' || c > '9' {\n            return false\n        }\n        if i&1 == odd {\n            sum += t[c-'0']\n        } else {\n            sum += int(c - '0')\n        }\n    }\n    return sum%10 == 0\n}\n\nfunc main() {\n    for _, s := range strings.Split(input, \"\\n\") {\n        fmt.Println(s, luhn(s))\n    }\n}\n\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":1321}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\n\/\/ basic task function\nfunc finalSurvivor(n, k int) int {\n    \/\/ argument validation omitted\n    circle := make([]int, n)\n    for i := range circle {\n        circle[i] = i\n    }\n    k--\n    exPos := 0\n    for len(circle) > 1 {\n        exPos = (exPos + k) % len(circle)\n        circle = append(circle[:exPos], circle[exPos+1:]...)\n    }\n    return circle[0]\n}\n\n\/\/ extra\nfunc position(n, k, pos int) int {\n    \/\/ argument validation omitted\n    circle := make([]int, n)\n    for i := range circle {\n        circle[i] = i\n    }\n    k--\n    exPos := 0\n    for len(circle) > 1 {\n        exPos = (exPos + k) % len(circle)\n        if pos == 0 {\n            return circle[exPos]\n        }\n        pos--\n        circle = append(circle[:exPos], circle[exPos+1:]...)\n    }\n    return circle[0]\n}\n\nfunc main() {\n    \/\/ show basic task function on given test case\n    fmt.Println(finalSurvivor(41, 3))\n    \/\/ show extra function on all positions of given test case\n    fmt.Println(\"Position  Prisoner\")\n    for i := 0; i < 41; i++ {\n        fmt.Printf(\"%5d%10d\\n\", i, position(41, 3, i))\n    }\n}\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":1322}
    {"lang_cluster":"Go","source_code":"\nfmt.Println(strings.Repeat(\"ha\", 5))        \/\/ ==> \"hahahahaha\"\n\n\nfmt.Println(strings.Repeat(string('h'), 5)) \/\/ prints hhhhh\n\n","human_summarization":"Code summarization: The code repeats a given string or character a specified number of times. For example, the function repeat(\"ha\", 5) returns \"hahahahaha\". The function also works with single characters, converting them to strings before repeating them.","id":1323}
    {"lang_cluster":"Go","source_code":"\npackage main\nimport \"fmt\"\nimport \"regexp\"\n\nfunc main() {\n  str := \"I am the original string\"\n\n  \/\/ Test\n  matched, _ := regexp.MatchString(\".*string$\", str)\n  if matched { fmt.Println(\"ends with 'string'\") }\n\n  \/\/ Substitute\n  pattern := regexp.MustCompile(\"original\")\n  result := pattern.ReplaceAllString(str, \"modified\")\n  fmt.Println(result)\n}\n\n","human_summarization":"\"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression.\"","id":1324}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    var a, b int\n    fmt.Print(\"enter two integers: \")\n    fmt.Scanln(&a, &b)\n    fmt.Printf(\"%d + %d = %d\\n\", a, b, a+b)\n    fmt.Printf(\"%d - %d = %d\\n\", a, b, a-b)\n    fmt.Printf(\"%d * %d = %d\\n\", a, b, a*b)\n    fmt.Printf(\"%d \/ %d = %d\\n\", a, b, a\/b)  \/\/ truncates towards 0\n    fmt.Printf(\"%d\u00a0%% %d = %d\\n\", a, b, a%b) \/\/ same sign as first operand\n    \/\/ no exponentiation operator\n}\n\n\nExample run:\nenter two integers: -5 3\n-5 + 3 = -2\n-5 - 3 = -8\n-5 * 3 = -15\n-5 \/ 3 = -1\n-5\u00a0% 3 = -2\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/big\"\n)\n\nfunc main() {\n    var a, b, c big.Int\n    fmt.Print(\"enter two integers: \")\n    fmt.Scan(&a, &b)\n    fmt.Printf(\"%d + %d = %d\\n\", &a, &b, c.Add(&a, &b))\n    fmt.Printf(\"%d - %d = %d\\n\", &a, &b, c.Sub(&a, &b))\n    fmt.Printf(\"%d * %d = %d\\n\", &a, &b, c.Mul(&a, &b))\n\n    \/\/ Quo, Rem functions work like Go operators on int:\n    \/\/ quo truncates toward 0,\n    \/\/ and a non-zero rem has the same sign as the first operand.\n    fmt.Printf(\"%d quo %d = %d\\n\", &a, &b, c.Quo(&a, &b))\n    fmt.Printf(\"%d rem %d = %d\\n\", &a, &b, c.Rem(&a, &b))\n\n    \/\/ Div, Mod functions do Euclidean division:\n    \/\/ the result m = a mod b is always non-negative,\n    \/\/ and for d = a div b, the results d and m give d*y + m = x.\n    fmt.Printf(\"%d div %d = %d\\n\", &a, &b, c.Div(&a, &b))\n    fmt.Printf(\"%d mod %d = %d\\n\", &a, &b, c.Mod(&a, &b))\n\n    \/\/ as with int, no exponentiation operator\n}\n\n\nExample run:\nenter two integers: -5 3\n-5 + 3 = -2\n-5 - 3 = -8\n-5 * 3 = -15\n-5 quo 3 = -1\n-5 rem 3 = -2\n-5 div 3 = -2\n-5 mod 3 = 1\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":1325}
    {"lang_cluster":"Go","source_code":"\n\npackage main\nimport (\n        \"fmt\"\n        \"strings\"\n)\n\nfunc main() {\n        fmt.Println(strings.Count(\"the three truths\", \"th\")) \/\/ says: 3\n        fmt.Println(strings.Count(\"ababababab\", \"abab\"))     \/\/ says: 2\n}\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two parameters: the main string and the substring to search for. It returns an integer representing the count of the non-overlapping occurrences. The function does not count overlapping substrings and matches from left to right or right to left for maximum non-overlapping matches. It uses the strings.Count() method for this task.","id":1326}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\n\/\/ a towers of hanoi solver just has one method, play\ntype solver interface {\n    play(int)\n}\n\nfunc main() {\n    var t solver    \/\/ declare variable of solver type\n    t = new(towers) \/\/ type towers must satisfy solver interface\n    t.play(4)\n}\n\n\/\/ towers is example of type satisfying solver interface\ntype towers struct {\n    \/\/ an empty struct.  some other solver might fill this with some\n    \/\/ data representation, maybe for algorithm validation, or maybe for\n    \/\/ visualization.\n}\n\n\/\/ play is sole method required to implement solver type\nfunc (t *towers) play(n int) {\n    \/\/ drive recursive solution, per task description\n    t.moveN(n, 1, 2, 3)\n}\n\n\/\/ recursive algorithm\nfunc (t *towers) moveN(n, from, to, via int) {\n    if n > 0 {\n        t.moveN(n-1, from, via, to)\n        t.move1(from, to)\n        t.moveN(n-1, via, to, from)\n    }\n}\n\n\/\/ example function prints actions to screen.\n\/\/ enhance with validation or visualization as needed.\nfunc (t *towers) move1(from, to int) {\n    fmt.Println(\"move disk from rod\", from, \"to rod\", to)\n}\n\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tmove(3, \"A\", \"B\", \"C\")\n}\n\nfunc move(n uint64, a, b, c string) {\n\tif n > 0 {\n\t\tmove(n-1, a, c, b)\n\t\tfmt.Println(\"Move disk from \" + a + \" to \" + c)\n\t\tmove(n-1, b, a, c)\n\t}\n}\n\n","human_summarization":"\"Implement a recursive solution for the Towers of Hanoi problem.\"","id":1327}
    {"lang_cluster":"Go","source_code":"\npackage main\nimport \"fmt\"\nimport \"math\/big\"\n\nfunc main() {\n  fmt.Println(new(big.Int).Binomial(5, 3))\n  fmt.Println(new(big.Int).Binomial(60, 30))\n}\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":1328}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\nvar a = []int{170, 45, 75, -90, -802, 24, 2, 66}\n\nfunc main() {\n    fmt.Println(\"before:\", a)\n    for inc := len(a) \/ 2; inc > 0; inc = (inc + 1) * 5 \/ 11 {\n        for i := inc; i < len(a); i++ {\n            j, temp := i, a[i]\n            for ; j >= inc && a[j-inc] > temp; j -= inc {\n                a[j] = a[j-inc]\n            }\n            a[j] = temp\n        }\n    }\n    fmt.Println(\"after: \", a)\n}\n\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. The algorithm, invented by Donald Shell, uses a diminishing increment sequence for sorting. It performs a series of interleaved insertion sorts based on an increment sequence, which reduces after each pass until it reaches 1. At this point, the sort becomes a basic insertion sort with the data almost sorted, which is the best case for insertion sort. The algorithm works with any sequence that ends in 1, but some sequences are more efficient than others, such as a geometric increment sequence with a ratio of about 2.2.","id":1329}
    {"lang_cluster":"Go","source_code":"\npackage raster\n\nimport (\n    \"math\"\n    \"math\/rand\"\n)\n\n\/\/ Grmap parallels Bitmap, but with an element type of uint16\n\/\/ in place of Pixel.\ntype Grmap struct {\n    Comments   []string\n    rows, cols int\n    px         []uint16\n    pxRow      [][]uint16\n}\n\n\/\/ NewGrmap constructor.\nfunc NewGrmap(x, y int) (b *Grmap) {\n    g := &Grmap{\n        Comments: []string{creator}, \/\/ creator a const in bitmap source file\n        rows:     y,\n        cols:     x,\n        px:       make([]uint16, x*y),\n        pxRow:    make([][]uint16, y),\n    }\n    x0, x1 := 0, x\n    for i := range g.pxRow {\n        g.pxRow[i] = g.px[x0:x1]\n        x0, x1 = x1, x1+x\n    }\n    return g\n}\n\nfunc (b *Grmap) Extent() (cols, rows int) {\n    return b.cols, b.rows\n}\n\nfunc (g *Grmap) Fill(c uint16) {\n    for i := range g.px {\n        g.px[i] = c\n    }\n}\n\nfunc (g *Grmap) SetPx(x, y int, c uint16) bool {\n    defer func() { recover() }()\n    g.pxRow[y][x] = c\n    return true\n}\n\nfunc (g *Grmap) GetPx(x, y int) (uint16, bool) {\n    defer func() { recover() }()\n    return g.pxRow[y][x], true\n}\n\n\/\/ Grmap method of Bitmap, converts (color) Bitmap to (grayscale) Grmap\nfunc (b *Bitmap) Grmap() *Grmap {\n    g := NewGrmap(b.cols, b.rows)\n    g.Comments = append([]string{}, b.Comments...)\n    for i, p := range b.px {\n        g.px[i] = uint16((int64(p.R)*2126 + int64(p.G)*7152 + int64(p.B)*722) *\n            math.MaxUint16 \/ (math.MaxUint8 * 10000))\n    }\n    return g\n}\n\n\/\/ Bitmap method Grmap, converts Grmap to Bitmap.  All pixels in the resulting\n\/\/ color Bitmap will be (very nearly) shades of gray.\nfunc (g *Grmap) Bitmap() *Bitmap {\n    b := NewBitmap(g.cols, g.rows)\n    b.Comments = append([]string{}, g.Comments...)\n    for i, p := range g.px {\n        roundedSum := int(p) * 3 * math.MaxUint8 \/ math.MaxUint16\n        rounded := uint8(roundedSum \/ 3)\n        remainder := roundedSum % 3\n        b.px[i].R = rounded\n        b.px[i].G = rounded\n        b.px[i].B = rounded\n        if remainder > 0 {\n            odd := rand.Intn(3)\n            switch odd + (remainder * 3) {\n            case 3:\n                b.px[i].R++\n            case 4:\n                b.px[i].G++\n            case 5:\n                b.px[i].B++\n            case 6:\n                b.px[i].G++\n                b.px[i].B++\n            case 7:\n                b.px[i].R++\n                b.px[i].B++\n            case 8:\n                b.px[i].R++\n                b.px[i].G++\n            }\n        }\n    }\n    return b\n}\n\n\n","human_summarization":"The code extends the data storage type to support grayscale images, includes operations to convert a color image to grayscale and vice versa using the CIE recommended formula for luminance calculation. It ensures that rounding errors in floating-point arithmetic do not cause run-time issues or distort results when the calculated luminance is stored as an unsigned integer. It also includes a demonstration program to read a PPM file.","id":1330}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"log\"\n    \"time\"\n\n    \"github.com\/gdamore\/tcell\"\n)\n\nconst (\n    msg             = \"Hello World! \"\n    x0, y0          = 8, 3\n    shiftsPerSecond = 4\n    clicksToExit    = 5\n)\n\nfunc main() {\n    s, err := tcell.NewScreen()\n    if err != nil {\n        log.Fatal(err)\n    }\n    if err = s.Init(); err != nil {\n        log.Fatal(err)\n    }\n    s.Clear()\n    s.EnableMouse()\n    tick := time.Tick(time.Second \/ shiftsPerSecond)\n    click := make(chan bool)\n    go func() {\n        for {\n            em, ok := s.PollEvent().(*tcell.EventMouse)\n            if !ok || em.Buttons()&0xFF == tcell.ButtonNone {\n                continue\n            }\n            mx, my := em.Position()\n            if my == y0 && mx >= x0 && mx < x0+len(msg) {\n                click <- true\n            }\n        }\n    }()\n    for inc, shift, clicks := 1, 0, 0; ; {\n        select {\n        case <-tick:\n            shift = (shift + inc) % len(msg)\n            for i, r := range msg {\n                s.SetContent(x0+((shift+i)%len(msg)), y0, r, nil, 0)\n            }\n            s.Show()\n        case <-click:\n            clicks++\n            if clicks == clicksToExit {\n                s.Fini()\n                return\n            }\n            inc = len(msg) - inc\n        }\n    }\n}\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":1331}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\tvar value int\n\tfor {\n\t\tvalue++\n\t\tfmt.Println(value)\n                if value%6 != 0 {\n                        break\n                }\n\t}\n}\n\n\n","human_summarization":"simulate a do-while loop in Go, which starts with a value at 0 and continues to add 1 to the value and print it until the value mod 6 equals 0. The loop executes at least once. The do-while loop is simulated using either a range-based for loop with a break statement or without using a break statement.","id":1332}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    m := \"m\u00f8\u00f8se\"\n    u := \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\"\n    j := \"J\u0332o\u0332s\u0332\u00e9\u0332\"\n    fmt.Printf(\"%d %s\u00a0% x\\n\", len(m), m, m)\n    fmt.Printf(\"%d %s\u00a0% x\\n\", len(u), u, u)\n    fmt.Printf(\"%d %s\u00a0% x\\n\", len(j), j, j)\n}\n\n\n7 m\u00f8\u00f8se\u00a06d c3 b8 c3 b8 73 65\n28 \ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22 f0 9d 94 98 f0 9d 94 ab f0 9d 94 a6 f0 9d 94 a0 f0 9d 94 ac f0 9d 94 a1 f0 9d 94 a2\n13 J\u0332o\u0332s\u0332\u00e9\u0332\u00a04a cc b2 6f cc b2 73 cc b2 c3 a9 cc b2\n\npackage main\n\nimport (\n    \"fmt\"\n    \"unicode\/utf8\"\n)\n\nfunc main() {\n    m := \"m\u00f8\u00f8se\"\n    u := \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\"\n    j := \"J\u0332o\u0332s\u0332\u00e9\u0332\"\n    fmt.Printf(\"%d %s %x\\n\", utf8.RuneCountInString(m), m, []rune(m))\n    fmt.Printf(\"%d %s %x\\n\", utf8.RuneCountInString(u), u, []rune(u))\n    fmt.Printf(\"%d %s %x\\n\", utf8.RuneCountInString(j), j, []rune(j))\n}\n\n\n5 m\u00f8\u00f8se [6d f8 f8 73 65]\n7 \ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22 [1d518 1d52b 1d526 1d520 1d52c 1d521 1d522]\n9 J\u0332o\u0332s\u0332\u00e9\u0332 [4a 332 6f 332 73 332 65 301 332]\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"unicode\"\n    \"unicode\/utf8\"\n)\n\nfunc main() {\n    m := \"m\u00f8\u00f8se\"\n    u := \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\"\n    j := \"J\u0332o\u0332s\u0332\u00e9\u0332\"\n    fmt.Printf(\"%d %s %x\\n\", grLen(m), m, []rune(m))\n    fmt.Printf(\"%d %s %x\\n\", grLen(u), u, []rune(u))\n    fmt.Printf(\"%d %s %x\\n\", grLen(j), j, []rune(j))\n}\n\nfunc grLen(s string) int {\n    if len(s) == 0 {\n        return 0\n    }\n    gr := 1\n    _, s1 := utf8.DecodeRuneInString(s)\n    for _, r := range s[s1:] {\n        if !unicode.Is(unicode.Mn, r) {\n            gr++\n        }\n    }\n    return gr\n}\n\n\n5 m\u00f8\u00f8se [6d f8 f8 73 65]\n7 \ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22 [1d518 1d52b 1d526 1d520 1d52c 1d521 1d522]\n4 J\u0332o\u0332s\u0332\u00e9\u0332 [4a 332 6f 332 73 332 65 301 332]\n\n","human_summarization":"determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. It handles individual Unicode code points, non-BMP code points, and provides the string length in graphemes if the language supports it. The code does not support recognizing graphemes directly in Go language.","id":1333}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"crypto\/rand\"\n    \"encoding\/binary\"\n    \"fmt\"\n    \"io\"\n    \"os\"\n)\n\nfunc main() {\n    testRandom(\"crypto\/rand\", rand.Reader)\n    testRandom(\"dev\/random\", newDevRandom())\n}\n\nfunc newDevRandom() (f *os.File) {\n    var err error\n    if f, err = os.Open(\"\/dev\/random\"); err != nil {\n        panic(err)\n    }\n    return\n}\n\nfunc testRandom(label string, src io.Reader) {\n    fmt.Printf(\"%s:\\n\", label)\n    var r int32\n    for i := 0; i < 10; i++ {\n        if err := binary.Read(src, binary.LittleEndian, &r); err != nil {\n            panic(err)\n        }\n        fmt.Print(r, \" \")\n    }\n    fmt.Println()\n}\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using the crypto\/rand library in Go, which utilizes \/dev\/urandom on Unix-like systems and CryptGenRandom API on Windows. The code also includes an option to use \/dev\/random.","id":1334}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"unicode\/utf8\"\n)\n\nfunc main() {\n    \/\/ ASCII contents:  Interpreting \"characters\" as bytes.\n    s := \"ASCII\"\n    fmt.Println(\"String:                \", s)\n    fmt.Println(\"First byte removed:    \", s[1:])\n    fmt.Println(\"Last byte removed:     \", s[:len(s)-1])\n    fmt.Println(\"First and last removed:\", s[1:len(s)-1])\n    \/\/ UTF-8 contents:  \"Characters\" as runes (unicode code points)\n    u := \"\u0394\u03b7\u03bc\u03bf\u03c4\u03b9\u03ba\u03ae\"\n    fmt.Println(\"String:                \", u)\n    _, sizeFirst := utf8.DecodeRuneInString(u)\n    fmt.Println(\"First rune removed:    \", u[sizeFirst:])\n    _, sizeLast := utf8.DecodeLastRuneInString(u)\n    fmt.Println(\"Last rune removed:     \", u[:len(u)-sizeLast])\n    fmt.Println(\"First and last removed:\", u[sizeFirst:len(u)-sizeLast])\n}\n\n\nString:                 ASCII\nFirst byte removed:     SCII\nLast byte removed:      ASCI\nFirst and last removed: SCI\nString:                 \u0394\u03b7\u03bc\u03bf\u03c4\u03b9\u03ba\u03ae\nFirst rune removed:     \u03b7\u03bc\u03bf\u03c4\u03b9\u03ba\u03ae\nLast rune removed:      \u0394\u03b7\u03bc\u03bf\u03c4\u03b9\u03ba\nFirst and last removed: \u03b7\u03bc\u03bf\u03c4\u03b9\u03ba\n\n","human_summarization":"demonstrate how to remove the first and last characters from a string, ensuring compatibility with any valid Unicode code point in UTF-8 or UTF-16 encoding. The codes also efficiently extract first and last runes from a string using utf8 package functions without decoding the entire string.","id":1335}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"net\"\n    \"time\"\n)\n\nconst lNet = \"tcp\"\nconst lAddr = \":12345\"\n\nfunc main() {\n    if _, err := net.Listen(lNet, lAddr); err != nil {\n        fmt.Println(\"an instance was already running\")\n        return\n    }\n    fmt.Println(\"single instance started\")\n    time.Sleep(10 * time.Second)\n}\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"time\"\n)\n\n\/\/ The path to the lock file should be an absolute path starting from the root.\n\/\/ (If you wish to prevent the same program running in different directories,\n\/\/ that is.)\nconst lfn = \"\/tmp\/rclock\"\n\nfunc main() {\n    lf, err := os.OpenFile(lfn, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)\n    if err != nil {\n        fmt.Println(\"an instance is already running\")\n        return\n    }\n    lf.Close()\n    fmt.Println(\"single instance started\")\n    time.Sleep(10 * time.Second)\n    os.Remove(lfn)\n}\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"time\"\n)\n\n\/\/ The path to the lock file should be an absolute path starting from the root.\n\/\/ (If you wish to prevent the same program running in different directories, that is.)\nconst lfn = \"\/tmp\/rclock\"\n\nfunc main() {\n    lf, err := os.OpenFile(lfn, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)\n    if err == nil {\n        \/\/ good\n        \/\/ 10 digit pid seems to be a standard for lock files\n        fmt.Fprintf(lf, \"%10d\", os.Getpid())\n        lf.Close()\n        defer os.Remove(lfn)\n    } else {\n        \/\/ problem\n        fmt.Println(err)\n        \/\/ dig deeper\n        lf, err = os.Open(lfn)\n        if err != nil {\n            return\n        }\n        defer lf.Close()\n        fmt.Println(\"inspecting lock file...\")\n        b10 := make([]byte, 10)\n        _, err = lf.Read(b10)\n        if err != nil {\n            fmt.Println(err)\n            return\n        }\n        pid, err := strconv.Atoi(strings.TrimSpace(string(b10)))\n        if err != nil {\n            fmt.Println(err)\n            return\n        }\n        fmt.Println(\"lock file created by pid\", pid)\n        return\n    }\n    fmt.Println(os.Getpid(), \"running...\")\n    time.Sleep(1e10)\n}\n\n","human_summarization":"\"Code checks if an application instance is already running. If so, it displays a message and exits. It uses O_CREATE|O_EXCL to handle this, storing the PID in a lock file for better messaging. However, if the program terminates early, the lock file remains. This solution is recommended over file-based solutions as the port is always released when the process ends.\"","id":1336}
    {"lang_cluster":"Go","source_code":"\nLibrary: RobotGo\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com\/go-vgo\/robotgo\"\n)\n\nfunc main() {\n    w, h := robotgo.GetScreenSize()\n    fmt.Printf(\"Screen size: %d x %d\\n\", w, h)\n    fpid, err := robotgo.FindIds(\"firefox\")\n    if err == nil && len(fpid) > 0 {\n        pid := fpid[0]\n        robotgo.ActivePID(pid)\n        robotgo.MaxWindow(pid)\n        _, _, w, h = robotgo.GetBounds(pid)\n        fmt.Printf(\"Max usable\u00a0: %d x %d\\n\", w, h)\n    }\n}\n\n\nScreen size: 1366 x 768\nMax usable\u00a0: 1301 x 744\n\n","human_summarization":"\"Determines the maximum height and width of a window that can fit on the screen without scrolling, considering window decorations, menubars, multiple monitors, and tiling window managers.\"","id":1337}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\n\/\/ sudoku puzzle representation is an 81 character string \nvar puzzle = \"\" +\n    \"394  267 \" +\n    \"   3  4  \" +\n    \"5  69  2 \" +\n    \" 45   9  \" +\n    \"6       7\" +\n    \"  7   58 \" +\n    \" 1  67  8\" +\n    \"  9  8   \" +\n    \" 264  735\"\n\nfunc main() {\n    printGrid(\"puzzle:\", puzzle)\n    if s := solve(puzzle); s == \"\" {\n        fmt.Println(\"no solution\")\n    } else {\n        printGrid(\"solved:\", s)\n    }\n}\n\n\/\/ print grid (with title) from 81 character string\nfunc printGrid(title, s string) {\n    fmt.Println(title)\n    for r, i := 0, 0; r < 9; r, i = r+1, i+9 {\n        fmt.Printf(\"%c %c %c | %c %c %c | %c %c %c\\n\", s[i], s[i+1], s[i+2],\n            s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])\n        if r == 2 || r == 5 {\n            fmt.Println(\"------+-------+------\")\n        }\n    }\n}   \n    \n\/\/ solve puzzle in 81 character string format.\n\/\/ if solved, result is 81 character string.\n\/\/ if not solved, result is the empty string.\nfunc solve(u string) string {\n    \/\/ construct an dlx object with 324 constraint columns.\n    \/\/ other than the number 324, this is not specific to sudoku.\n    d := newDlxObject(324)\n    \/\/ now add constraints that define sudoku rules.\n    for r, i := 0, 0; r < 9; r++ {\n        for c := 0; c < 9; c, i = c+1, i+1 {\n            b := r\/3*3 + c\/3\n            n := int(u[i] - '1')\n            if n >= 0 && n < 9 {\n                d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,\n                    243 + b*9 + n})\n            } else {\n                for n = 0; n < 9; n++ {\n                    d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,\n                        243 + b*9 + n})\n                }\n            }\n        }\n    }\n    \/\/ run dlx.  not sudoku specific.\n    d.search()\n    \/\/ extract the sudoku-specific 81 character result from the dlx solution.\n    return d.text()\n}\n\n\/\/ Knuth's data object\ntype x struct {\n    c          *y\n    u, d, l, r *x\n    \/\/ except x0 is not Knuth's.  it's pointer to first constraint in row,\n    \/\/ so that the sudoku string can be constructed from the dlx solution.\n    x0 *x\n}\n\n\/\/ Knuth's column object\ntype y struct {\n    x\n    s int \/\/ size\n    n int \/\/ name\n}\n\n\/\/ an object to hold the matrix and solution\ntype dlx struct {\n    ch []y  \/\/ all column headers\n    h  *y   \/\/ ch[0], the root node\n    o  []*x \/\/ solution\n}\n\n\/\/ constructor creates the column headers but no rows.\nfunc newDlxObject(nCols int) *dlx {\n    ch := make([]y, nCols+1)\n    h := &ch[0]\n    d := &dlx{ch, h, nil}\n    h.c = h\n    h.l = &ch[nCols].x\n    ch[nCols].r = &h.x\n    nh := ch[1:]\n    for i := range ch[1:] {\n        hi := &nh[i]\n        ix := &hi.x\n        hi.n = i\n        hi.c = hi\n        hi.u = ix\n        hi.d = ix\n        hi.l = &h.x\n        h.r = ix\n        h = hi\n    }\n    return d\n}   \n    \n\/\/ rows define constraints\nfunc (d *dlx) addRow(nr []int) {\n    if len(nr) == 0 {\n        return\n    }\n    r := make([]x, len(nr))\n    x0 := &r[0]\n    for x, j := range nr {\n        ch := &d.ch[j+1]\n        ch.s++\n        np := &r[x]\n        np.c = ch\n        np.u = ch.u\n        np.d = &ch.x\n        np.l = &r[(x+len(r)-1)%len(r)]\n        np.r = &r[(x+1)%len(r)]\n        np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np\n        np.x0 = x0\n    }\n}\n\n\/\/ extracts 81 character sudoku string\nfunc (d *dlx) text() string {\n    b := make([]byte, len(d.o))\n    for _, r := range d.o {\n        x0 := r.x0\n        b[x0.c.n] = byte(x0.r.c.n%9) + '1'\n    }\n    return string(b)\n}   \n    \n\/\/ the dlx algorithm \nfunc (d *dlx) search() bool {\n    h := d.h\n    j := h.r.c\n    if j == h {\n        return true\n    }\n    c := j \n    for minS := j.s; ; {\n        j = j.r.c\n        if j == h {\n            break\n        }\n        if j.s < minS {\n            c, minS = j, j.s\n        }\n    }\n\n    cover(c)\n    k := len(d.o)\n    d.o = append(d.o, nil)\n    for r := c.d; r != &c.x; r = r.d {\n        d.o[k] = r\n        for j := r.r; j != r; j = j.r {\n            cover(j.c)\n        }\n        if d.search() {\n            return true\n        }\n        r = d.o[k]\n        c = r.c\n        for j := r.l; j != r; j = j.l {\n            uncover(j.c)\n        }\n    }\n    d.o = d.o[:len(d.o)-1]\n    uncover(c)\n    return false\n}\n\nfunc cover(c *y) {\n    c.r.l, c.l.r = c.l, c.r\n    for i := c.d; i != &c.x; i = i.d {\n        for j := i.r; j != i; j = j.r {\n            j.d.u, j.u.d = j.u, j.d\n            j.c.s--\n        }\n    }\n}\n\nfunc uncover(c *y) {\n    for i := c.u; i != &c.x; i = i.u {\n        for j := i.l; j != i; j = j.l {\n            j.c.s++\n            j.d.u, j.u.d = j, j\n        }\n    }\n    c.r.l, c.l.r = &c.x, &c.x\n}\n\n\n","human_summarization":"implement a Sudoku solver that takes an 81 character string representing a partially filled 9x9 Sudoku grid as input, solves it using Knuth's DLX algorithm, and displays the solved Sudoku grid in a human-readable format.","id":1338}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/rand\"\n    \"time\"\n)\n\nfunc main() {\n    var a [20]int\n    for i := range a {\n        a[i] = i\n    }\n    fmt.Println(a)\n\n    rand.Seed(time.Now().UnixNano())\n    for i := len(a) - 1; i >= 1; i-- {\n        j := rand.Intn(i + 1)\n        a[i], a[j] = a[j], a[i]\n    }\n    fmt.Println(a)\n}\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/rand\"\n    \"time\"\n)\n\n\/\/ Generic Knuth Shuffle algorithm.  In Go, this is done with interface\n\/\/ types.  The parameter s of function shuffle is an interface type.\n\/\/ Any type satisfying the interface \"shuffler\" can be shuffled with\n\/\/ this function.  Since the shuffle function uses the random number\n\/\/ generator, it's nice to seed the generator at program load time.\nfunc init() {\n    rand.Seed(time.Now().UnixNano())\n}\nfunc shuffle(s shuffler) {\n    for i := s.Len() - 1; i >= 1; i-- {\n        j := rand.Intn(i + 1)\n        s.Swap(i, j)\n    }\n}\n\n\/\/ Conceptually, a shuffler is an indexed collection of things.\n\/\/ It requires just two simple methods.\ntype shuffler interface {\n    Len() int      \/\/ number of things in the collection\n    Swap(i, j int) \/\/ swap the two things indexed by i and j\n}\n\n\/\/ ints is an example of a concrete type implementing the shuffler\n\/\/ interface.\ntype ints []int\n\nfunc (s ints) Len() int      { return len(s) }\nfunc (s ints) Swap(i, j int) { s[i], s[j] = s[j], s[i] }\n\n\/\/ Example program.  Make an ints collection, fill with sequential numbers,\n\/\/ print, shuffle, print.\nfunc main() {\n    a := make(ints, 20)\n    for i := range a {\n        a[i] = i\n    }\n    fmt.Println(a)\n    shuffle(a)\n    fmt.Println(a)\n}\n\n\nExample output: (of either program)\n[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]\n[11 10 12 19 4 13 15 17 14 2 5 18 8 0 6 9 7 3 1 16]\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an integer array or an array of any type. The shuffle is performed in-place on the input array, but can be modified to return a new array if necessary. It can also be adjusted to iterate from left to right. The function also includes test cases for validation.","id":1339}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n)\n\nfunc main() {\n\ty := time.Now().Year()\n\tif len(os.Args) == 2 {\n\t\tif i, err := strconv.Atoi(os.Args[1]); err == nil {\n\t\t\ty = i\n\t\t}\n\t}\n\tfor m := time.January; m <= time.December; m++ {\n\t\td := time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC).Add(-24 * time.Hour)\n\t\td = d.Add(-time.Duration((d.Weekday()+7-time.Friday)%7) * 24 * time.Hour)\n\t\tfmt.Println(d.Format(\"2006-01-02\"))\n\t}\n}\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":1340}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc main() { fmt.Print(\"Goodbye, World!\") }\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":1341}
    {"lang_cluster":"Go","source_code":"\nLibrary: gotk3\npackage main\n\nimport (\n    \"github.com\/gotk3\/gotk3\/gtk\"\n    \"log\"\n    \"math\/rand\"\n    \"strconv\"\n    \"time\"\n)\n\nfunc validateInput(window *gtk.Window, str1, str2 string) bool {\n    n, err := strconv.ParseFloat(str2, 64)\n    if len(str1) == 0 || err != nil || n != 75000 {\n        dialog := gtk.MessageDialogNew(\n            window,\n            gtk.DIALOG_MODAL,\n            gtk.MESSAGE_ERROR,\n            gtk.BUTTONS_OK,\n            \"Invalid input\",\n        )\n        dialog.Run()\n        dialog.Destroy()\n        return false\n    }\n    return true\n}\n\nfunc check(err error, msg string) {\n    if err != nil {\n        log.Fatal(msg, err)\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    gtk.Init(nil)\n\n    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)\n    check(err, \"Unable to create window:\")\n    window.SetTitle(\"Rosetta Code\")\n    window.SetPosition(gtk.WIN_POS_CENTER)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n\n    vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1)\n    check(err, \"Unable to create vertical box:\")\n    vbox.SetBorderWidth(1)\n\n    hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create first horizontal box:\")\n\n    hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)\n    check(err, \"Unable to create second horizontal box:\")\n\n    label, err := gtk.LabelNew(\"Enter a string and the number 75000   \\n\")\n    check(err, \"Unable to create label:\")\n\n    sel, err := gtk.LabelNew(\"String:      \")\n    check(err, \"Unable to create string entry label:\")\n\n    nel, err := gtk.LabelNew(\"Number: \")\n    check(err, \"Unable to create number entry label:\")\n\n    se, err := gtk.EntryNew()\n    check(err, \"Unable to create string entry:\")\n\n    ne, err := gtk.EntryNew()\n    check(err, \"Unable to create number entry:\")\n\n    hbox1.PackStart(sel, false, false, 2)\n    hbox1.PackStart(se, false, false, 2)\n\n    hbox2.PackStart(nel, false, false, 2)\n    hbox2.PackStart(ne, false, false, 2)\n\n    \/\/ button to accept\n    ab, err := gtk.ButtonNewWithLabel(\"Accept\")\n    check(err, \"Unable to create accept button:\")\n    ab.Connect(\"clicked\", func() {\n        \/\/ read and validate the entered values\n        str1, _ := se.GetText()\n        str2, _ := ne.GetText()\n        if validateInput(window, str1, str2) {\n            window.Destroy() \/\/ close window if input is OK\n        }\n    })\n\n    vbox.Add(label)\n    vbox.Add(hbox1)\n    vbox.Add(hbox2)\n    vbox.Add(ab)\n    window.Add(vbox)\n\n    window.ShowAll()\n    gtk.Main()\n}\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":1342}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\ntype ckey struct {\n    enc, dec func(rune) rune\n}\n\nfunc newCaesar(k int) (*ckey, bool) {\n    if k < 1 || k > 25 {\n        return nil, false\n    }\n    rk := rune(k)\n    return &ckey{\n        enc: func(c rune) rune {\n            if c >= 'a' && c <= 'z'-rk || c >= 'A' && c <= 'Z'-rk {\n                return c + rk\n            } else if c > 'z'-rk && c <= 'z' || c > 'Z'-rk && c <= 'Z' {\n                return c + rk - 26\n            }\n            return c\n        },\n        dec: func(c rune) rune {\n            if c >= 'a'+rk && c <= 'z' || c >= 'A'+rk && c <= 'Z' {\n                return c - rk\n            } else if c >= 'a' && c < 'a'+rk || c >= 'A' && c < 'A'+rk {\n                return c - rk + 26\n            }\n            return c\n        },\n    }, true\n}\n\nfunc (ck ckey) encipher(pt string) string {\n    return strings.Map(ck.enc, pt)\n}\n\nfunc (ck ckey) decipher(ct string) string {\n    return strings.Map(ck.dec, ct)\n}\n\nfunc main() {\n    pt := \"The five boxing wizards jump quickly\"\n    fmt.Println(\"Plaintext:\", pt)\n    for _, key := range []int{0, 1, 7, 25, 26} {\n        ck, ok := newCaesar(key)\n        if !ok {\n            fmt.Println(\"Key\", key, \"invalid\")\n            continue\n        }\n        ct := ck.encipher(pt)\n        fmt.Println(\"Key\", key)\n        fmt.Println(\"  Enciphered:\", ct)\n        fmt.Println(\"  Deciphered:\", ck.decipher(ct))\n    }\n}\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode\"\n)\n\ntype ckey struct {\n    enc, dec unicode.SpecialCase\n}\n\nfunc newCaesar(k int) (*ckey, bool) {\n    if k < 1 || k > 25 {\n        return nil, false\n    }\n    i := uint32(k)\n    r := rune(k)\n    return &ckey{\n        unicode.SpecialCase{\n            {'A', 'Z' - i, [3]rune{r}},\n            {'Z' - i + 1, 'Z', [3]rune{r - 26}},\n            {'a', 'z' - i, [3]rune{r}},\n            {'z' - i + 1, 'z', [3]rune{r - 26}},\n        },\n        unicode.SpecialCase{\n            {'A', 'A' + i - 1, [3]rune{26 - r}},\n            {'A' + i, 'Z', [3]rune{-r}},\n            {'a', 'a' + i - 1, [3]rune{26 - r}},\n            {'a' + i, 'z', [3]rune{-r}},\n        },\n    }, true\n}\n\nfunc (ck ckey) encipher(pt string) string {\n    return strings.ToUpperSpecial(ck.enc, pt)\n}\n\nfunc (ck ckey) decipher(ct string) string {\n    return strings.ToUpperSpecial(ck.dec, ct)\n}\n\nfunc main() {\n    pt := \"The five boxing wizards jump quickly\"\n    fmt.Println(\"Plaintext:\", pt)\n    for _, key := range []int{0, 1, 7, 25, 26} {\n        ck, ok := newCaesar(key)\n        if !ok {\n            fmt.Println(\"Key\", key, \"invalid\")\n            continue\n        }\n        ct := ck.encipher(pt)\n        fmt.Println(\"Key\", key)\n        fmt.Println(\"  Enciphered:\", ct)\n        fmt.Println(\"  Deciphered:\", ck.decipher(ct))\n    }\n}\n\n\n","human_summarization":"implement both encoding and decoding functionalities of a Caesar cipher. The cipher uses a key ranging from 1 to 25 to rotate the letters of the alphabet. The encoding process replaces each letter with the 1st to 25th next letter in the alphabet, wrapping Z to A. The codes also consider the vulnerabilities of the cipher, such as frequency analysis and key guessing. It also highlights the similarities between Caesar cipher and Vigen\u00e8re cipher with a key of length 1, and Rot-13 with key 13.","id":1343}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/big\"\n)\n\nvar m, n, z big.Int\n\nfunc init() {\n    m.SetString(\"2562047788015215500854906332309589561\", 10)\n    n.SetString(\"6795454494268282920431565661684282819\", 10)\n}\n\nfunc main() {\n    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))\n}\n\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":1344}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc isCusip(s string) bool {\n    if len(s) != 9 { return false }\n    sum := 0\n    for i := 0; i < 8; i++ {\n        c := s[i]\n        var v int\n        switch {\n            case c >= '0' && c <= '9':\n                v = int(c) - 48\n            case c >= 'A' && c <= 'Z':\n                v = int(c) - 55\n            case c == '*':\n                v = 36\n            case c == '@':\n                v = 37\n            case c == '#':\n                v = 38\n            default:\n                return false\n        }\n        if i % 2 == 1 { v *= 2 }  \/\/ check if odd as using 0-based indexing\n        sum += v\/10 + v%10\n    }\n    return int(s[8]) - 48 == (10 - (sum%10)) % 10\n}\n\nfunc main() {\n    candidates := []string {\n        \"037833100\",\n        \"17275R102\",\n        \"38259P508\",\n        \"594918104\",\n        \"68389X106\",\n        \"68389X105\",\n    }\n\n    for _, candidate := range candidates {\n        var b string\n        if isCusip(candidate) {\n            b = \"correct\"\n        } else {\n            b = \"incorrect\"\n        }\n        fmt.Printf(\"%s -> %s\\n\", candidate, b)\n    }\n}\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":1345}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unsafe\"\n)\n\nfunc main() {\n\tfmt.Println(runtime.Version(), runtime.GOOS, runtime.GOARCH)\n\n\t\/\/ Inspect a uint32 variable to determine endianness.\n\tx := uint32(0x01020304)\n\tswitch *(*byte)(unsafe.Pointer(&x)) {\n\tcase 0x01:\n\t\tfmt.Println(\"big endian\")\n\tcase 0x04:\n\t\tfmt.Println(\"little endian\")\n\tdefault:\n\t\tfmt.Println(\"mixed endian?\")\n\t}\n\n\t\/\/ Usually one cares about the size the executible was compiled for\n\t\/\/ rather than the actual underlying host's size.\n\n\t\/\/ There are several ways of determining the size of an int\/uint.\n\tfmt.Println(\"         strconv.IntSize =\", strconv.IntSize)\n\t\/\/ That uses the following definition we can also be done by hand\n\tintSize := 32 << uint(^uint(0)>>63)\n\tfmt.Println(\"32 << uint(^uint(0)>>63) =\", intSize)\n\n\t\/\/ With Go\u00a01.0, 64-bit architectures had 32-bit int and 64-bit\n\t\/\/ uintptr. This was changed in Go\u00a01.1. In general it would\n\t\/\/ still be possible that int and uintptr (the type large enough\n\t\/\/ to hold the bit pattern of any pointer) are of different sizes.\n\tconst bitsPerByte = 8\n\tfmt.Println(\"  sizeof(int)     in bits:\", unsafe.Sizeof(int(0))*bitsPerByte)\n\tfmt.Println(\"  sizeof(uintptr) in bits:\", unsafe.Sizeof(uintptr(0))*bitsPerByte)\n\t\/\/ If we really want to know the architecture size the executable was\n\t\/\/ compiled for and not the size of int it safest to take the max of those.\n\tarchSize := unsafe.Sizeof(int(0))\n\tif psize := unsafe.Sizeof(uintptr(0)); psize > archSize {\n\t\tarchSize = psize\n\t}\n\tfmt.Println(\"  compiled with word size:\", archSize*bitsPerByte)\n\n\t\/\/ There are some *very* unportable ways to attempt to get the actual\n\t\/\/ underlying hosts' word size.\n\t\/\/ Inspect cpuinfo to determine word size (some unix-like OS' only).\n\tc, err := ioutil.ReadFile(\"\/proc\/cpuinfo\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tls := strings.Split(string(c), \"\\n\")\n\tfor _, l := range ls {\n\t\tif strings.HasPrefix(l, \"flags\") {\n\t\t\tfor _, f := range strings.Fields(l) {\n\t\t\t\tif f == \"lm\" { \/\/ \"long mode\"\n\t\t\t\t\tfmt.Println(\"64 bit word size\")\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt.Println(\"32 bit word size\")\n\t\t\treturn\n\t\t}\n\t}\n}\n\n\n","human_summarization":"\"Code prints the word size and endianness of the host machine using an alternative technique.\"","id":1346}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"encoding\/xml\"\n\t\"fmt\"\n\t\"io\"\n\t\"io\/ioutil\"\n\t\"log\"\n\t\"net\/http\"\n\t\"net\/url\"\n\t\"regexp\"\n\t\"sort\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nvar baseQuery = \"http:\/\/rosettacode.org\/mw\/api.php?action=query\" +\n\t\"&format=xml&list=categorymembers&cmlimit=500\"\n\nfunc req(u string, foundCm func(string)) string {\n\tresp, err := http.Get(u)\n\tif err != nil {\n\t\tlog.Fatal(err) \/\/ connection or request fail\n\t}\n\tdefer resp.Body.Close()\n\tfor p := xml.NewDecoder(resp.Body); ; {\n\t\tt, err := p.RawToken()\n\t\tswitch s, ok := t.(xml.StartElement); {\n\t\tcase err == io.EOF:\n\t\t\treturn \"\"\n\t\tcase err != nil:\n\t\t\tlog.Fatal(err)\n\t\tcase !ok:\n\t\t\tcontinue\n\t\tcase s.Name.Local == \"cm\":\n\t\t\tfor _, a := range s.Attr {\n\t\t\t\tif a.Name.Local == \"title\" {\n\t\t\t\t\tfoundCm(a.Value)\n\t\t\t\t}\n\t\t\t}\n\t\tcase s.Name.Local == \"categorymembers\" && len(s.Attr) > 0 &&\n\t\t\ts.Attr[0].Name.Local == \"cmcontinue\":\n\t\t\treturn url.QueryEscape(s.Attr[0].Value)\n\t\t}\n\t}\n\treturn \"\"\n}\n\n\/\/ satisfy sort interface (reverse sorting)\ntype pop struct {\n\tstring\n\tint\n}\ntype popList []pop\n\nfunc (pl popList) Len() int      { return len(pl) }\nfunc (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] }\nfunc (pl popList) Less(i, j int) bool {\n\tswitch d := pl[i].int - pl[j].int; {\n\tcase d > 0:\n\t\treturn true\n\tcase d < 0:\n\t\treturn false\n\t}\n\treturn pl[i].string < pl[j].string\n}\n\nfunc main() {\n\t\/\/ get languages, store in a map\n\tlangMap := make(map[string]bool)\n\tstoreLang := func(cm string) {\n\t\tif strings.HasPrefix(cm, \"Category:\") {\n\t\t\tcm = cm[9:]\n\t\t}\n\t\tlangMap[cm] = true\n\t}\n\tlanguageQuery := baseQuery + \"&cmtitle=Category:Programming_Languages\"\n\tcontinueAt := req(languageQuery, storeLang)\n\tfor continueAt != \"\" {\n\t\tcontinueAt = req(languageQuery+\"&cmcontinue=\"+continueAt, storeLang)\n\t}\n\t\/\/ allocate slice for sorting\n\ts := make(popList, 0, len(langMap))\n\n\t\/\/ get big list of categories\n\tresp, err := http.Get(\"http:\/\/rosettacode.org\/mw\/index.php\" +\n\t\t\"?title=Special:Categories&limit=5000\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tpage, err := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\n\t\/\/ split out fields of interest and populate sortable slice\n\trx := regexp.MustCompile(\"<li><a.*>(.*)<\/a>.*[(]([0-9]+) member\")\n\tfor _, sm := range rx.FindAllSubmatch(page, -1) {\n\t\tls := string(sm[1])\n\t\tif langMap[ls] {\n\t\t\tif n, err := strconv.Atoi(string(sm[2])); err == nil {\n\t\t\t\ts = append(s, pop{ls, n})\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ output\n\tsort.Sort(s)\n\tlastCnt, lastIdx := -1, 1\n\tfor i, lang := range s {\n\t\tif lang.int != lastCnt {\n\t\t\tlastCnt = lang.int\n\t\t\tlastIdx = i + 1\n\t\t}\n\t\tfmt.Printf(\"%3d. %3d - %s\\n\", lastIdx, lang.int, lang.string)\n\t}\n}\n\n\nOutput on 11 Aug 2014:\n  1. 832 - Tcl\n  2. 783 - Racket\n  3. 774 - Python\n  4. 733 - Perl 6\n  5. 729 - J\n\u2026\n506.   1 - Supernova\n506.   1 - TestML\n506.   1 - Vox\n506.   1 - XPath 2.0\n506.   1 - Xanadu\n\n\n","human_summarization":"sort and rank the most popular computer programming languages based on the number of members in Rosetta Code categories. It uses either web scraping or API methods to access the data, optionally filters incorrect results, and compares the results with a complete, periodically updated list of all programming languages. The final output is a ranked list of all languages.","id":1347}
    {"lang_cluster":"Go","source_code":"\n\nfunc printAll(values []int) {\n   for i, x := range values {\n      fmt.Printf(\"Item %d = %d\\n\", i, x)\n   }\n}\n\n","human_summarization":"Iterates through each element in a collection in sequence using a \"for each\" loop or an alternative loop if \"for each\" is not available. The range function is utilized with either one or two variables to retrieve the index and\/or value of each item in the collection. For channels, only the single-variable variant is used.","id":1348}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n)\n\nfunc main() {\n    s := \"Hello,How,Are,You,Today\"\n    fmt.Println(strings.Join(strings.Split(s, \",\"), \".\"))\n}\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":1349}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc gcd(a, b int) int {\n    var bgcd func(a, b, res int) int\n\n    bgcd = func(a, b, res int) int {\n\tswitch {\n\tcase a == b:\n\t    return res * a\n\tcase a % 2 == 0 && b % 2 == 0:\n\t    return bgcd(a\/2, b\/2, 2*res)\n\tcase a % 2 == 0:\n\t    return bgcd(a\/2, b, res)\n\tcase b % 2 == 0:\n\t    return bgcd(a, b\/2, res)\n\tcase a > b:\n\t    return bgcd(a-b, b, res)\n\tdefault:\n\t    return bgcd(a, b-a, res)\n\t}\n    }\n\n    return bgcd(a, b, 1)\n}\n\nfunc main() {\n    type pair struct {\n\ta int\n\tb int\n    }\n\n    var testdata []pair = []pair{\n\tpair{33, 77},\n\tpair{49865, 69811},\n    }\n\n    for _, v := range testdata {\n\tfmt.Printf(\"gcd(%d, %d) = %d\\n\", v.a, v.b, gcd(v.a, v.b))\n    }\n}\n\n\nOutput for Binary Euclidian algorithm:\ngcd(33, 77) = 11\ngcd(49865, 69811) = 9973\n\npackage main\n\nimport \"fmt\"\n\nfunc gcd(x, y int) int {\n    for y != 0 {\n        x, y = y, x%y\n    }\n    return x\n}\n\nfunc main() {\n    fmt.Println(gcd(33, 77))\n    fmt.Println(gcd(49865, 69811))\n}\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/big\"\n)\n\nfunc gcd(x, y int64) int64 {\n    return new(big.Int).GCD(nil, nil, big.NewInt(x), big.NewInt(y)).Int64()\n}\n\nfunc main() {\n    fmt.Println(gcd(33, 77))\n    fmt.Println(gcd(49865, 69811))\n}\n\n\nOutput in either case:\n11\n9973\n\n","human_summarization":"find the greatest common divisor (GCD), also known as the greatest common factor (gcf) or greatest common measure, of two integers. This function is a wrapper for big.GCD.","id":1350}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"fmt\"\n\t\"net\"\n\t\"bufio\"\n)\n\nfunc echo(s net.Conn, i int) {\n\tdefer s.Close();\n\n\tfmt.Printf(\"%d: %v <-> %v\\n\", i, s.LocalAddr(), s.RemoteAddr())\n\tb := bufio.NewReader(s)\n\tfor {\n\t\tline, e := b.ReadBytes('\\n')\n\t\tif e != nil {\n\t\t\tbreak\n\t\t}\n\t\ts.Write(line)\n\t}\n\tfmt.Printf(\"%d: closed\\n\", i)\n}\n\nfunc main() {\n\tl, e := net.Listen(\"tcp\", \":12321\")\n\tfor i := 0; e == nil; i++ {\n\t\tvar s net.Conn\n\t\ts, e = l.Accept()\n\t\tgo echo(s, i)\n\t}\n}\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":1351}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc isNumeric(s string) bool {\n    _, err := strconv.ParseFloat(s, 64)\n    return err == nil\n}\n\nfunc main() {\n    fmt.Println(\"Are these strings numeric?\")\n    strings := []string{\"1\", \"3.14\", \"-100\", \"1e2\", \"NaN\", \"rose\"}\n    for _, s := range strings {\n        fmt.Printf(\"  %4s -> %t\\n\", s, isNumeric(s))\n    }\n}\n\n\n","human_summarization":"check if a given string is a numeric value, including floating point and negative numbers, using a boolean function. The function utilizes both a library function and a custom one, but only verifies if the string can be converted into an integer.","id":1352}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"io\"\n    \"log\"\n    \"net\/http\"\n    \"os\"\n)\n\nfunc main() {\n    r, err := http.Get(\"https:\/\/sourceforge.net\/\")\n    if err != nil {\n        log.Fatalln(err)\n    }\n    io.Copy(os.Stdout, r.Body)\n}\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":1353}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\ntype point struct {\n    x, y float32\n}\n\nvar subjectPolygon = []point{{50, 150}, {200, 50}, {350, 150}, {350, 300},\n    {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}}\n\nvar clipPolygon = []point{{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunc main() {\n    var cp1, cp2, s, e point\n    inside := func(p point) bool {\n        return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n    }\n    intersection := func() (p point) {\n        dcx, dcy := cp1.x-cp2.x, cp1.y-cp2.y\n        dpx, dpy := s.x-e.x, s.y-e.y\n        n1 := cp1.x*cp2.y - cp1.y*cp2.x\n        n2 := s.x*e.y - s.y*e.x\n        n3 := 1 \/ (dcx*dpy - dcy*dpx)\n        p.x = (n1*dpx - n2*dcx) * n3\n        p.y = (n1*dpy - n2*dcy) * n3\n        return\n    }\n    outputList := subjectPolygon\n    cp1 = clipPolygon[len(clipPolygon)-1]\n    for _, cp2 = range clipPolygon { \/\/ WP clipEdge is cp1,cp2 here\n        inputList := outputList\n        outputList = nil\n        s = inputList[len(inputList)-1]\n        for _, e = range inputList {\n            if inside(e) {\n                if !inside(s) {\n                    outputList = append(outputList, intersection())\n                }\n                outputList = append(outputList, e)\n            } else if inside(s) {\n                outputList = append(outputList, intersection())\n            }\n            s = e\n        }\n        cp1 = cp2\n    }\n    fmt.Println(outputList)\n}\n\n\n","human_summarization":"Implement the Sutherland-Hodgman clipping algorithm to find the intersection of a given polygon and a rectangle. The code takes a polygon defined by a sequence of points and clips it by a rectangle, also defined by a sequence of points. The resulting clipped polygon is then printed. For extra credit, the code also displays all three polygons on a graphical surface, each in a different color, with the resulting polygon filled in.","id":1354}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n)\n\ntype rankable interface {\n\tLen() int\n\tRankEqual(int, int) bool\n}\n\nfunc StandardRank(d rankable) []float64 {\n\tr := make([]float64, d.Len())\n\tvar k int\n\tfor i := range r {\n\t\tif i == 0 || !d.RankEqual(i, i-1) {\n\t\t\tk = i + 1\n\t\t}\n\t\tr[i] = float64(k)\n\t}\n\treturn r\n}\n\nfunc ModifiedRank(d rankable) []float64 {\n\tr := make([]float64, d.Len())\n\tfor i := range r {\n\t\tk := i + 1\n\t\tfor j := i + 1; j < len(r) && d.RankEqual(i, j); j++ {\n\t\t\tk = j + 1\n\t\t}\n\t\tr[i] = float64(k)\n\t}\n\treturn r\n}\n\nfunc DenseRank(d rankable) []float64 {\n\tr := make([]float64, d.Len())\n\tvar k int\n\tfor i := range r {\n\t\tif i == 0 || !d.RankEqual(i, i-1) {\n\t\t\tk++\n\t\t}\n\t\tr[i] = float64(k)\n\t}\n\treturn r\n}\n\nfunc OrdinalRank(d rankable) []float64 {\n\tr := make([]float64, d.Len())\n\tfor i := range r {\n\t\tr[i] = float64(i + 1)\n\t}\n\treturn r\n}\n\nfunc FractionalRank(d rankable) []float64 {\n\tr := make([]float64, d.Len())\n\tfor i := 0; i < len(r); {\n\t\tvar j int\n\t\tf := float64(i + 1)\n\t\tfor j = i + 1; j < len(r) && d.RankEqual(i, j); j++ {\n\t\t\tf += float64(j + 1)\n\t\t}\n\t\tf \/= float64(j - i)\n\t\tfor ; i < j; i++ {\n\t\t\tr[i] = f\n\t\t}\n\t}\n\treturn r\n}\n\ntype scores []struct {\n\tscore int\n\tname  string\n}\n\nfunc (s scores) Len() int                { return len(s) }\nfunc (s scores) RankEqual(i, j int) bool { return s[i].score == s[j].score }\nfunc (s scores) Swap(i, j int)           { s[i], s[j] = s[j], s[i] }\nfunc (s scores) Less(i, j int) bool {\n\tif s[i].score != s[j].score {\n\t\treturn s[i].score > s[j].score\n\t}\n\treturn s[i].name < s[j].name\n}\n\nvar data = scores{\n\t{44, \"Solomon\"},\n\t{42, \"Jason\"},\n\t{42, \"Errol\"},\n\t{41, \"Garry\"},\n\t{41, \"Bernard\"},\n\t{41, \"Barry\"},\n\t{39, \"Stephen\"},\n}\n\nfunc main() {\n\tshow := func(name string, fn func(rankable) []float64) {\n\t\tfmt.Println(name, \"Ranking:\")\n\t\tr := fn(data)\n\t\tfor i, d := range data {\n\t\t\tfmt.Printf(\"%4v - %2d %s\\n\", r[i], d.score, d.name)\n\t\t}\n\t}\n\n\tsort.Sort(data)\n\tshow(\"Standard\", StandardRank)\n\tshow(\"\\nModified\", ModifiedRank)\n\tshow(\"\\nDense\", DenseRank)\n\tshow(\"\\nOrdinal\", OrdinalRank)\n\tshow(\"\\nFractional\", FractionalRank)\n}\n\n\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":1355}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nconst d = 30.\nconst r = d * math.Pi \/ 180\n\nvar s = .5\nvar c = math.Sqrt(3) \/ 2\nvar t = 1 \/ math.Sqrt(3)\n\nfunc main() {\n    fmt.Printf(\"sin(%9.6f deg) = %f\\n\", d, math.Sin(d*math.Pi\/180))\n    fmt.Printf(\"sin(%9.6f rad) = %f\\n\", r, math.Sin(r))\n    fmt.Printf(\"cos(%9.6f deg) = %f\\n\", d, math.Cos(d*math.Pi\/180))\n    fmt.Printf(\"cos(%9.6f rad) = %f\\n\", r, math.Cos(r))\n    fmt.Printf(\"tan(%9.6f deg) = %f\\n\", d, math.Tan(d*math.Pi\/180))\n    fmt.Printf(\"tan(%9.6f rad) = %f\\n\", r, math.Tan(r))\n    fmt.Printf(\"asin(%f) = %9.6f deg\\n\", s, math.Asin(s)*180\/math.Pi)\n    fmt.Printf(\"asin(%f) = %9.6f rad\\n\", s, math.Asin(s))\n    fmt.Printf(\"acos(%f) = %9.6f deg\\n\", c, math.Acos(c)*180\/math.Pi)\n    fmt.Printf(\"acos(%f) = %9.6f rad\\n\", c, math.Acos(c))\n    fmt.Printf(\"atan(%f) = %9.6f deg\\n\", t, math.Atan(t)*180\/math.Pi)\n    fmt.Printf(\"atan(%f) = %9.6f rad\\n\", t, math.Atan(t))\n}\n\n\n","human_summarization":"demonstrate the use of trigonometric functions such as sine, cosine, tangent, and their inverses in a given programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the same angle is used for each radian\/degree pair. For inverse functions, the same number is converted to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities. The Go math package's constant pi and six trigonometric functions are also utilized.","id":1356}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\ntype Item struct {\n\tname               string\n\tweight, value, qty int\n}\n\nvar items = []Item{\n\t{\"map\",\t\t\t9,\t150,\t1},\n\t{\"compass\",\t\t13,\t35,\t1},\n\t{\"water\",\t\t153,\t200,\t2},\n\t{\"sandwich\",\t\t50,\t60,\t2},\n\t{\"glucose\",\t\t15,\t60,\t2},\n\t{\"tin\",\t\t\t68,\t45,\t3},\n\t{\"banana\",\t\t27,\t60,\t3},\n\t{\"apple\",\t\t39,\t40,\t3},\n\t{\"cheese\",\t\t23,\t30,\t1},\n\t{\"beer\",\t\t52,\t10,\t3},\n\t{\"suntancream\",\t\t11,\t70,\t1},\n\t{\"camera\",\t\t32,\t30,\t1},\n\t{\"T-shirt\",\t\t24,\t15,\t2},\n\t{\"trousers\",\t\t48,\t10,\t2},\n\t{\"umbrella\",\t\t73,\t40,\t1},\n\t{\"w-trousers\",\t\t42,\t70,\t1},\n\t{\"w-overclothes\",\t43,\t75,\t1},\n\t{\"note-case\",\t\t22,\t80,\t1},\n\t{\"sunglasses\",\t\t7,      20,\t1},\n\t{\"towel\",\t\t18,\t12,\t2},\n\t{\"socks\",\t\t4,      50,\t1},\n\t{\"book\",\t\t30,\t10,\t2},\n}\n\ntype Chooser struct {\n\tItems []Item\n\tcache map[key]solution\n}\n\ntype key struct {\n\tw, p int\n}\n\ntype solution struct {\n\tv, w int\n\tqty  []int\n}\n\nfunc (c Chooser) Choose(limit int) (w, v int, qty []int) {\n\tc.cache = make(map[key]solution)\n\ts := c.rchoose(limit, len(c.Items)-1)\n\tc.cache = nil \/\/ allow cache to be garbage collected\n\treturn s.v, s.w, s.qty\n}\n\nfunc (c Chooser) rchoose(limit, pos int) solution {\n\tif pos < 0 || limit <= 0 {\n\t\treturn solution{0, 0, nil}\n\t}\n\n\tkey := key{limit, pos}\n\tif s, ok := c.cache[key]; ok {\n\t\treturn s\n\t}\n\n\tbest_i, best := 0, solution{0, 0, nil}\n\tfor i := 0; i*items[pos].weight <= limit && i <= items[pos].qty; i++ {\n\t\tsol := c.rchoose(limit-i*items[pos].weight, pos-1)\n\t\tsol.v += i * items[pos].value\n\t\tif sol.v > best.v {\n\t\t\tbest_i, best = i, sol\n\t\t}\n\t}\n\n\tif best_i > 0 {\n\t\t\/\/ best.qty is used in another cache entry,\n\t\t\/\/ we need to duplicate it before modifying it to\n\t\t\/\/ store as our cache entry.\n\t\told := best.qty\n\t\tbest.qty = make([]int, len(items))\n\t\tcopy(best.qty, old)\n\t\tbest.qty[pos] = best_i\n\t\tbest.w += best_i * items[pos].weight\n\t}\n\tc.cache[key] = best\n\treturn best\n}\n\nfunc main() {\n\tv, w, s := Chooser{Items: items}.Choose(400)\n\n\tfmt.Println(\"Taking:\")\n\tfor i, t := range s {\n\t\tif t > 0 {\n\t\t\tfmt.Printf(\"  %d of %d %s\\n\", t, items[i].qty, items[i].name)\n\t\t}\n\t}\n\tfmt.Printf(\"Value: %d; weight: %d\\n\", v, w)\n}\n\n\n\n","human_summarization":"The code implements a solution to the Bounded Knapsack Problem. It helps a tourist to determine the optimal combination of items to carry in his knapsack, ensuring the total weight does not exceed 4 kg and the total value is maximized. The code uses caching to improve performance. It considers the weight, value, and quantity of each item, and assumes that only whole units of any item can be taken.","id":1357}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n    \"os\/signal\"\n    \"time\"\n)\n\nfunc main() {\n    start := time.Now()\n    k := time.Tick(time.Second \/ 2)\n    sc := make(chan os.Signal, 1)\n    signal.Notify(sc, os.Interrupt)\n    for n := 1; ; {\n        \/\/ not busy waiting, this blocks until one of the two\n        \/\/ channel operations is possible\n        select {\n        case <-k:\n            fmt.Println(n)\n            n++\n        case <-sc:\n            fmt.Printf(\"Ran for %f seconds.\\n\",\n                time.Now().Sub(start).Seconds())\n            return\n        }\n    }\n}\n\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.","id":1358}
    {"lang_cluster":"Go","source_code":"\n\npackage main\nimport \"fmt\"\nimport \"strconv\"\nfunc main() {\n  i, _ := strconv.Atoi(\"1234\")\n  fmt.Println(strconv.Itoa(i + 1))\n}\n\n\npackage main\n\nimport (\n    \"math\/big\"\n    \"fmt\"\n    \"strconv\"\n)\n\nfunc main() {\n    \/\/ integer\n    is := \"1234\"\n    fmt.Println(\"original:   \", is)\n    i, err := strconv.Atoi(is)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \/\/ assignment back to original variable shows result is the same type.\n    is = strconv.Itoa(i + 1)\n    fmt.Println(\"incremented:\", is)\n\n    \/\/ error checking worthwhile\n    fmt.Println()\n    _, err = strconv.Atoi(\" 1234\") \/\/ whitespace not allowed\n    fmt.Println(err)\n    _, err = strconv.Atoi(\"12345678901\")\n    fmt.Println(err)\n    _, err = strconv.Atoi(\"_1234\")\n    fmt.Println(err)\n    _, err = strconv.ParseFloat(\"12.D34\", 64)\n    fmt.Println(err)\n\n    \/\/ float\n    fmt.Println()\n    fs := \"12.34\"\n    fmt.Println(\"original:   \", fs)\n    f, err := strconv.ParseFloat(fs, 64)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    \/\/ various options on FormatFloat produce different formats.  All are valid\n    \/\/ input to ParseFloat, so result format does not have to match original\n    \/\/ format.  (Matching original format would take more code.)\n    fs = strconv.FormatFloat(f+1, 'g', -1, 64)\n    fmt.Println(\"incremented:\", fs)\n    fs = strconv.FormatFloat(f+1, 'e', 4, 64)\n    fmt.Println(\"what format?\", fs)\n\n    \/\/ complex\n    \/\/ strconv package doesn't handle complex types, but fmt does.\n    \/\/ (fmt can be used on ints and floats too, but strconv is more efficient.)\n    fmt.Println()\n    cs := \"(12+34i)\"\n    fmt.Println(\"original:   \", cs)\n    var c complex128\n    _, err = fmt.Sscan(cs, &c)\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    cs = fmt.Sprint(c + 1)\n    fmt.Println(\"incremented:\", cs)\n\n    \/\/ big integers have their own functions\n    fmt.Println()\n    bs := \"170141183460469231731687303715884105728\"\n    fmt.Println(\"original:   \", bs)\n    var b, one big.Int\n    _, ok := b.SetString(bs, 10)\n    if !ok {\n        fmt.Println(\"big.SetString fail\")\n        return\n    }\n    one.SetInt64(1)\n    bs = b.Add(&b, &one).String()\n    fmt.Println(\"incremented:\", bs)\n}\n\n\n","human_summarization":"\"Increments a given numerical string.\"","id":1359}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path\"\n)\n\nfunc CommonPrefix(sep byte, paths ...string) string {\n\t\/\/ Handle special cases.\n\tswitch len(paths) {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn path.Clean(paths[0])\n\t}\n\n\t\/\/ Note, we treat string as []byte, not []rune as is often\n\t\/\/ done in Go. (And sep as byte, not rune). This is because\n\t\/\/ most\/all supported OS' treat paths as string of non-zero\n\t\/\/ bytes. A filename may be displayed as a sequence of Unicode\n\t\/\/ runes (typically encoded as UTF-8) but paths are\n\t\/\/ not required to be valid UTF-8 or in any normalized form\n\t\/\/ (e.g.\u00a0\"\u00e9\" (U+00C9) and \"\u00e9\" (U+0065,U+0301) are different\n\t\/\/ file names.\n\tc := []byte(path.Clean(paths[0]))\n\n\t\/\/ We add a trailing sep to handle the case where the\n\t\/\/ common prefix directory is included in the path list\n\t\/\/ (e.g.\u00a0\/home\/user1, \/home\/user1\/foo, \/home\/user1\/bar).\n\t\/\/ path.Clean will have cleaned off trailing \/ separators with\n\t\/\/ the exception of the root directory, \"\/\" (in which case we\n\t\/\/ make it \"\/\/\", but this will get fixed up to \"\/\" bellow).\n\tc = append(c, sep)\n\n\t\/\/ Ignore the first path since it's already in c\n\tfor _, v := range paths[1:] {\n\t\t\/\/ Clean up each path before testing it\n\t\tv = path.Clean(v) + string(sep)\n\n\t\t\/\/ Find the first non-common byte and truncate c\n\t\tif len(v) < len(c) {\n\t\t\tc = c[:len(v)]\n\t\t}\n\t\tfor i := 0; i < len(c); i++ {\n\t\t\tif v[i] != c[i] {\n\t\t\t\tc = c[:i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Remove trailing non-separator characters and the final separator\n\tfor i := len(c) - 1; i >= 0; i-- {\n\t\tif c[i] == sep {\n\t\t\tc = c[:i]\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn string(c)\n}\n\nfunc main() {\n\tc := CommonPrefix(os.PathSeparator,\n\t\t\/\/\"\/home\/user1\/tmp\",\n\t\t\"\/home\/user1\/tmp\/coverage\/test\",\n\t\t\"\/home\/user1\/tmp\/covert\/operator\",\n\t\t\"\/home\/user1\/tmp\/coven\/members\",\n\t\t\"\/home\/\/user1\/tmp\/coventry\",\n\t\t\"\/home\/user1\/.\/.\/tmp\/covertly\/foo\",\n\t\t\"\/home\/bob\/..\/user1\/tmp\/coved\/bar\",\n\t)\n\tif c == \"\" {\n\t\tfmt.Println(\"No common path\")\n\t} else {\n\t\tfmt.Println(\"Common path:\", c)\n\t}\n}\n\n","human_summarization":"The code identifies the common directory path from a set of given directory paths. It uses a specified directory separator to determine commonality. The code ensures that if the common path is also a directory in the list, it is not truncated. It has been tested with the forward slash '\/' as the directory separator and three specific strings as input paths. The function returns the valid directory and not the longest common string.","id":1360}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"math\/rand\"\n\t\"fmt\"\n)\n\nfunc main() {\n\tlist := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\n\tfor i := 1; i <= 10; i++ {\n\t\tsattoloCycle(list)\n\t\tfmt.Println(list)\n\t}\n}\n\nfunc sattoloCycle(list []int) {\n\tfor x := len(list) -1; x > 0; x-- {\n\t\tj := rand.Intn(x)\n\t\tlist[x], list[j] = list[j], list[x]\n\t}\n}\n\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":1361}
    {"lang_cluster":"Go","source_code":"\nLibrary: Go Soap\n\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com\/tiaguinho\/gosoap\"\n    \"log\"\n)\n\ntype CheckVatResponse struct {\n    CountryCode string `xml:\"countryCode\"`\n    VatNumber   string `xml:\"vatNumber\"`\n    RequestDate string `xml:\"requestDate\"`\n    Valid       string `xml:\"valid\"`\n    Name        string `xml:\"name\"`\n    Address     string `xml:\"address\"`\n}\n\nvar (\n    rv CheckVatResponse\n)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc main() {\n    \/\/ create SOAP client\n    soap, err := gosoap.SoapClient(\"http:\/\/ec.europa.eu\/taxation_customs\/vies\/checkVatService.wsdl\")\n\n    \/\/ map parameter names to values\n    params := gosoap.Params{\n        \"vatNumber\":   \"6388047V\",\n        \"countryCode\": \"IE\",\n    }\n\n    \/\/ call 'checkVat' function\n    err = soap.Call(\"checkVat\", params)\n    check(err)\n\n    \/\/ unmarshal response to 'rv'\n    err = soap.Unmarshal(&rv)\n    check(err)\n\n    \/\/ print response\n    fmt.Println(\"Country Code \u00a0: \", rv.CountryCode)\n    fmt.Println(\"Vat Number   \u00a0: \", rv.VatNumber)\n    fmt.Println(\"Request Date \u00a0: \", rv.RequestDate)\n    fmt.Println(\"Valid        \u00a0: \", rv.Valid)\n    fmt.Println(\"Name         \u00a0: \", rv.Name)\n    fmt.Println(\"Address      \u00a0: \", rv.Address)\n}\n\n\n","human_summarization":"create a SOAP client that accesses and calls the functions soapFunc() and anotherSoapFunc() from the SOAP server at http:\/\/example.com\/soap\/wsdl. The functionality is tested against a publicly available SOAP server.","id":1362}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc main() {\n    fmt.Println(median([]float64{3, 1, 4, 1}))    \/\/ prints 2\n    fmt.Println(median([]float64{3, 1, 4, 1, 5})) \/\/ prints 3\n}\n\nfunc median(a []float64) float64 {\n    sort.Float64s(a)\n    half := len(a) \/ 2\n    m := a[half]\n    if len(a)%2 == 0 {\n        m = (m + a[half-1]) \/ 2\n    }\n    return m\n}\n\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    fmt.Println(median([]float64{3, 1, 4, 1}))    \/\/ prints 2\n    fmt.Println(median([]float64{3, 1, 4, 1, 5})) \/\/ prints 3\n}\n\nfunc median(a []float64) float64 {\n    half := len(a) \/ 2\n    med := sel(a, half)\n    if len(a)%2 == 0 {\n        return (med + a[half-1]) \/ 2\n    }\n    return med\n}\n\nfunc sel(list []float64, k int) float64 {\n    for i, minValue := range list[:k+1] {\n        minIndex := i\n        for j := i + 1; j < len(list); j++ {\n            if list[j] < minValue {\n                minIndex = j\n                minValue = list[j]\n                list[i], list[minIndex] = minValue, list[i]\n            }\n        }\n    }\n    return list[k]\n}\n\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/rand\"\n)\n\nfunc main() {\n    fmt.Println(median([]float64{3, 1, 4, 1}))    \/\/ prints 2\n    fmt.Println(median([]float64{3, 1, 4, 1, 5})) \/\/ prints 3\n}\n\nfunc median(list []float64) float64 {\n    half := len(list) \/ 2\n    med := qsel(list, half)\n    if len(list)%2 == 0 {\n        return (med + qsel(list, half-1)) \/ 2\n    }\n    return med\n}\n\nfunc qsel(a []float64, k int) float64 {\n    for len(a) > 1 {\n        px := rand.Intn(len(a))\n        pv := a[px]\n        last := len(a) - 1\n        a[px], a[last] = a[last], pv\n        px = 0\n        for i, v := range a[:last] {\n            if v < pv {\n                a[px], a[i] = v, a[px]\n                px++\n            }\n        }\n        if px == k {\n            return pv\n        }\n        if k < px {\n            a = a[:px]\n        } else {\n            \/\/ swap elements.  simply assigning a[last] would be enough to\n            \/\/ allow qsel to return the correct result but it would leave slice\n            \/\/ \"a\" unusable for subsequent use.  we want this full swap so that\n            \/\/ we can make two successive qsel calls in the case of median\n            \/\/ of an even number of elements.\n            a[px], a[last] = pv, a[px]\n            a = a[px+1:]\n            k -= px + 1\n        }\n    }\n    return a[0]\n}\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles cases with an even number of elements by returning the average of the two middle values. The code implements the selection algorithm for finding the median in O(n) time. It also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation. The code references a selection algorithm and implements a quickselect with random pivoting for efficient computation.","id":1363}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    for i\u00a0:= 1; i <= 100; i++ {\n        switch {\n        case i%15==0:\n            fmt.Println(\"FizzBuzz\")\n        case i%3==0:\n            fmt.Println(\"Fizz\")\n        case i%5==0:\n            fmt.Println(\"Buzz\")\n        default: \n            fmt.Println(i)\n        }\n    }\n}\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    for i\u00a0:= 1; i <= 100; i++ {\n        fmt.Println(map[bool]map[bool]interface{}{\n            false: {false: i, true: \"Fizz\"}, true: {false: \"Buzz\", true: \"FizzBuzz\"},\n        }[i%5 == 0][i%3 == 0])\n    }\n}\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":1364}
    {"lang_cluster":"Go","source_code":"\nText\n\npackage main\n\nimport \"fmt\"\nimport \"math\/cmplx\"\n\nfunc mandelbrot(a complex128) (z complex128) {\n    for i := 0; i < 50; i++ {\n        z = z*z + a\n    }\n    return\n}\n\nfunc main() {\n    for y := 1.0; y >= -1.0; y -= 0.05 {\n        for x := -2.0; x <= 0.5; x += 0.0315 {\n            if cmplx.Abs(mandelbrot(complex(x, y))) < 2 {\n                fmt.Print(\"*\")\n            } else {\n                fmt.Print(\" \")\n            }\n        }\n        fmt.Println(\"\")\n    }\n}\n\nGraphical\n.png image\npackage main\n\nimport (\n    \"fmt\"\n    \"image\"\n    \"image\/color\"\n    \"image\/draw\"\n    \"image\/png\"\n    \"math\/cmplx\"\n    \"os\"\n)\n\nconst (\n    maxEsc = 100\n    rMin   = -2.\n    rMax   = .5\n    iMin   = -1.\n    iMax   = 1.\n    width  = 750\n    red    = 230\n    green  = 235\n    blue   = 255\n)\n\nfunc mandelbrot(a complex128) float64 {\n    i := 0\n    for z := a; cmplx.Abs(z) < 2 && i < maxEsc; i++ {\n        z = z*z + a\n    }\n    return float64(maxEsc-i) \/ maxEsc\n}\n\nfunc main() {\n    scale := width \/ (rMax - rMin)\n    height := int(scale * (iMax - iMin))\n    bounds := image.Rect(0, 0, width, height)\n    b := image.NewNRGBA(bounds)\n    draw.Draw(b, bounds, image.NewUniform(color.Black), image.ZP, draw.Src)\n    for x := 0; x < width; x++ {\n        for y := 0; y < height; y++ {\n            fEsc := mandelbrot(complex(\n                float64(x)\/scale+rMin,\n                float64(y)\/scale+iMin))\n            b.Set(x, y, color.NRGBA{uint8(red * fEsc),\n                uint8(green * fEsc), uint8(blue * fEsc), 255})\n\n        }\n    }\n    f, err := os.Create(\"mandelbrot.png\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    if err = png.Encode(f, b); err != nil {\n        fmt.Println(err)\n    }\n    if err = f.Close(); err != nil {\n        fmt.Println(err)\n    }\n}\n\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions, and print an 80-character by 41-line depiction of it.","id":1365}
    {"lang_cluster":"Go","source_code":"\nImplementation\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    sum, prod := 0, 1\n    for _, x := range []int{1,2,5} {\n        sum += x\n        prod *= x\n    }\n    fmt.Println(sum, prod)\n}\n\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":1366}
    {"lang_cluster":"Go","source_code":"\nfunc isLeap(year int) bool {\n    return year%400 == 0 || year%4 == 0 && year%100 != 0\n}\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":1367}
    {"lang_cluster":"Go","source_code":"package main\n\nimport (\n    \"bufio\"\n    \"crypto\/rand\"\n    \"fmt\"\n    \"io\/ioutil\"\n    \"log\"\n    \"math\/big\"\n    \"os\"\n    \"strconv\"\n    \"strings\"\n    \"unicode\"\n)\n\nconst (\n    charsPerLine = 48\n    chunkSize    = 6\n    cols         = 8\n    demo         = true \/\/ would normally be set to false\n)\n\ntype fileType int\n\nconst (\n    otp fileType = iota\n    enc\n    dec\n)\n\nvar scnr = bufio.NewScanner(os.Stdin)\n\nfunc check(err error) {\n    if err != nil {\n        log.Fatal(err)\n    }\n}\n\nfunc toAlpha(s string) string {\n    var filtered []rune\n    for _, r := range s {\n        if unicode.IsUpper(r) {\n            filtered = append(filtered, r)\n        }\n    }\n    return string(filtered)\n}\n\nfunc isOtpRelated(s string) bool {\n    return strings.HasSuffix(s, \".1tp\") || strings.HasSuffix(s, \"1tp_cpy\") ||\n        strings.HasSuffix(s, \".1tp_enc\") || strings.HasSuffix(s, \"1tp_dec\")\n}\n\nfunc makePad(nLines int) string {\n    nChars := nLines * charsPerLine\n    bytes := make([]byte, nChars)\n    \/* generate random upper case letters *\/\n    max := big.NewInt(26)\n    for i := 0; i < nChars; i++ {\n        n, err := rand.Int(rand.Reader, max)\n        check(err)\n        bytes[i] = byte(65 + n.Uint64())\n    }\n    return inChunks(string(bytes), nLines, otp)\n}\n\nfunc vigenere(text, key string, encrypt bool) string {\n    bytes := make([]byte, len(text))\n    var ci byte\n    for i, c := range text {\n        if encrypt {\n            ci = (byte(c) + key[i] - 130) % 26\n        } else {\n            ci = (byte(c) + 26 - key[i]) % 26\n        }\n        bytes[i] = ci + 65\n    }\n    temp := len(bytes) % charsPerLine\n    if temp > 0 { \/\/ pad with random characters so each line is a full one\n        max := big.NewInt(26)\n        for i := temp; i < charsPerLine; i++ {\n            n, err := rand.Int(rand.Reader, max)\n            check(err)\n            bytes = append(bytes, byte(65+n.Uint64()))\n        }\n    }\n    ft := enc\n    if !encrypt {\n        ft = dec\n    }\n    return inChunks(string(bytes), len(bytes)\/charsPerLine, ft)\n}\n\nfunc inChunks(s string, nLines int, ft fileType) string {\n    nChunks := len(s) \/ chunkSize\n    remainder := len(s) % chunkSize\n    chunks := make([]string, nChunks)\n    for i := 0; i < nChunks; i++ {\n        chunks[i] = s[i*chunkSize : (i+1)*chunkSize]\n    }\n    if remainder > 0 {\n        chunks = append(chunks, s[nChunks*chunkSize:])\n    }\n    var sb strings.Builder\n    for i := 0; i < nLines; i++ {\n        j := i * cols\n        sb.WriteString(\" \" + strings.Join(chunks[j:j+cols], \" \") + \"\\n\")\n    }\n    ss := \" file\\n\" + sb.String()\n    switch ft {\n    case otp:\n        return \"# OTP\" + ss\n    case enc:\n        return \"# Encrypted\" + ss\n    default: \/\/ case dec:\n        return \"# Decrypted\" + ss\n    }\n}\n\nfunc menu() int {\n    fmt.Println(`\n1. Create one time pad file.\n\n2. Delete one time pad file.\n\n3. List one time pad files.\n\n4. Encrypt plain text.\n\n5. Decrypt cipher text.\n\n6. Quit program.\n`)\n    choice := 0\n    for choice < 1 || choice > 6 {\n        fmt.Print(\"Your choice (1 to 6)\u00a0: \")\n        scnr.Scan()\n        choice, _ = strconv.Atoi(scnr.Text())\n        check(scnr.Err())\n    }\n    return choice\n}\n\nfunc main() {\n    for {\n        choice := menu()\n        fmt.Println()\n        switch choice {\n        case 1: \/\/ Create OTP\n            fmt.Println(\"Note that encrypted lines always contain 48 characters.\\n\")\n            fmt.Print(\"OTP file name to create (without extension)\u00a0: \")\n            scnr.Scan()\n            fileName := scnr.Text() + \".1tp\"\n            nLines := 0\n            for nLines < 1 || nLines > 1000 {\n                fmt.Print(\"Number of lines in OTP (max 1000)\u00a0: \")\n                scnr.Scan()\n                nLines, _ = strconv.Atoi(scnr.Text())\n            }\n            check(scnr.Err())\n            key := makePad(nLines)\n            file, err := os.Create(fileName)\n            check(err)\n            _, err = file.WriteString(key)\n            check(err)\n            file.Close()\n            fmt.Printf(\"\\n'%s' has been created in the current directory.\\n\", fileName)\n            if demo {\n                \/\/ a copy of the OTP file would normally be on a different machine\n                fileName2 := fileName + \"_cpy\" \/\/ copy for decryption\n                file, err := os.Create(fileName2)\n                check(err)\n                _, err = file.WriteString(key)\n                check(err)\n                file.Close()\n                fmt.Printf(\"'%s' has been created in the current directory.\\n\", fileName2)\n                fmt.Println(\"\\nThe contents of these files are\u00a0:\\n\")\n                fmt.Println(key)\n            }\n        case 2: \/\/ Delete OTP\n            fmt.Println(\"Note that this will also delete ALL associated files.\\n\")\n            fmt.Print(\"OTP file name to delete (without extension)\u00a0: \")\n            scnr.Scan()\n            toDelete1 := scnr.Text() + \".1tp\"\n            check(scnr.Err())\n            toDelete2 := toDelete1 + \"_cpy\"\n            toDelete3 := toDelete1 + \"_enc\"\n            toDelete4 := toDelete1 + \"_dec\"\n            allToDelete := []string{toDelete1, toDelete2, toDelete3, toDelete4}\n            deleted := 0\n            fmt.Println()\n            for _, name := range allToDelete {\n                if _, err := os.Stat(name); !os.IsNotExist(err) {\n                    err = os.Remove(name)\n                    check(err)\n                    deleted++\n                    fmt.Printf(\"'%s' has been deleted from the current directory.\\n\", name)\n                }\n            }\n            if deleted == 0 {\n                fmt.Println(\"There are no files to delete.\")\n            }\n        case 3: \/\/ List OTPs\n            fmt.Println(\"The OTP (and related) files in the current directory are:\\n\")\n            files, err := ioutil.ReadDir(\".\") \/\/ already sorted by file name\n            check(err)\n            for _, fi := range files {\n                name := fi.Name()\n                if !fi.IsDir() && isOtpRelated(name) {\n                    fmt.Println(name)\n                }\n            }\n        case 4: \/\/ Encrypt\n            fmt.Print(\"OTP file name to use (without extension)\u00a0: \")\n            scnr.Scan()\n            keyFile := scnr.Text() + \".1tp\"\n            if _, err := os.Stat(keyFile); !os.IsNotExist(err) {\n                file, err := os.Open(keyFile)\n                check(err)\n                bytes, err := ioutil.ReadAll(file)\n                check(err)\n                file.Close()\n                lines := strings.Split(string(bytes), \"\\n\")\n                le := len(lines)\n                first := le\n                for i := 0; i < le; i++ {\n                    if strings.HasPrefix(lines[i], \" \") {\n                        first = i\n                        break\n                    }\n                }\n                if first == le {\n                    fmt.Println(\"\\nThat file has no unused lines.\")\n                    continue\n                }\n                lines2 := lines[first:] \/\/ get rid of comments and used lines\n\n                fmt.Println(\"Text to encrypt\u00a0:-\\n\")\n                scnr.Scan()\n                text := toAlpha(strings.ToUpper(scnr.Text()))\n                check(scnr.Err())\n                tl := len(text)\n                nLines := tl \/ charsPerLine\n                if tl%charsPerLine > 0 {\n                    nLines++\n                }\n                if len(lines2) >= nLines {\n                    key := toAlpha(strings.Join(lines2[0:nLines], \"\"))\n                    encrypted := vigenere(text, key, true)\n                    encFile := keyFile + \"_enc\"\n                    file2, err := os.Create(encFile)\n                    check(err)\n                    _, err = file2.WriteString(encrypted)\n                    check(err)\n                    file2.Close()\n                    fmt.Printf(\"\\n'%s' has been created in the current directory.\\n\", encFile)\n                    for i := first; i < first+nLines; i++ {\n                        lines[i] = \"-\" + lines[i][1:]\n                    }\n                    file3, err := os.Create(keyFile)\n                    check(err)\n                    _, err = file3.WriteString(strings.Join(lines, \"\\n\"))\n                    check(err)\n                    file3.Close()\n                    if demo {\n                        fmt.Println(\"\\nThe contents of the encrypted file are\u00a0:\\n\")\n                        fmt.Println(encrypted)\n                    }\n                } else {\n                    fmt.Println(\"Not enough lines left in that file to do encryption.\")\n                }\n            } else {\n                fmt.Println(\"\\nThat file does not exist.\")\n            }\n        case 5: \/\/ Decrypt\n            fmt.Print(\"OTP file name to use (without extension)\u00a0: \")\n            scnr.Scan()\n            keyFile := scnr.Text() + \".1tp_cpy\"\n            check(scnr.Err())\n            if _, err := os.Stat(keyFile); !os.IsNotExist(err) {\n                file, err := os.Open(keyFile)\n                check(err)\n                bytes, err := ioutil.ReadAll(file)\n                check(err)\n                file.Close()\n                keyLines := strings.Split(string(bytes), \"\\n\")\n                le := len(keyLines)\n                first := le\n                for i := 0; i < le; i++ {\n                    if strings.HasPrefix(keyLines[i], \" \") {\n                        first = i\n                        break\n                    }\n                }\n                if first == le {\n                    fmt.Println(\"\\nThat file has no unused lines.\")\n                    continue\n                }\n                keyLines2 := keyLines[first:] \/\/ get rid of comments and used lines\n\n                encFile := keyFile[0:len(keyFile)-3] + \"enc\"\n                if _, err := os.Stat(encFile); !os.IsNotExist(err) {\n                    file2, err := os.Open(encFile)\n                    check(err)\n                    bytes, err := ioutil.ReadAll(file2)\n                    check(err)\n                    file2.Close()\n                    encLines := strings.Split(string(bytes), \"\\n\")[1:] \/\/ exclude comment line\n                    nLines := len(encLines)\n                    if len(keyLines2) >= nLines {\n                        encrypted := toAlpha(strings.Join(encLines, \"\"))\n                        key := toAlpha(strings.Join(keyLines2[0:nLines], \"\"))\n                        decrypted := vigenere(encrypted, key, false)\n                        decFile := keyFile[0:len(keyFile)-3] + \"dec\"\n                        file3, err := os.Create(decFile)\n                        check(err)\n                        _, err = file3.WriteString(decrypted)\n                        check(err)\n                        file3.Close()\n                        fmt.Printf(\"\\n'%s' has been created in the current directory.\\n\", decFile)\n                        for i := first; i < first+nLines; i++ {\n                            keyLines[i] = \"-\" + keyLines[i][1:]\n                        }\n                        file4, err := os.Create(keyFile)\n                        check(err)\n                        _, err = file4.WriteString(strings.Join(keyLines, \"\\n\"))\n                        check(err)\n                        file4.Close()\n                        if demo {\n                            fmt.Println(\"\\nThe contents of the decrypted file are\u00a0:\\n\")\n                            fmt.Println(decrypted)\n                        }\n                    }\n                } else {\n                    fmt.Println(\"Not enough lines left in that file to do decryption.\")\n                }\n            } else {\n                fmt.Println(\"\\nThat file does not exist.\")\n            }\n        case 6: \/\/ Quit program\n            return\n        }\n    }\n}\n\n\n","human_summarization":"The code implements a One-time pad for encrypting and decrypting messages using only letters. It generates data for a One-time pad based on user-specified filename and length, ensuring the use of \"true random\" numbers. The encryption and decryption process is similar to Rot-13, and much of Vigen\u00e8re cipher is reused with the key read from the One-time pad file. The code also optionally manages One-time pads, allowing users to list, mark as used, delete, and track which pad to use for which partner. It supports the management of pad-files with a \".1tp\" extension, and handles lines starting with \"#\" as comments, lines starting with \"-\" as \"used\", and ignores whitespace within the otp-data.","id":1368}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"bytes\"\n    \"encoding\/binary\"\n)\n\ntype testCase struct {\n    hashCode string\n    string\n}\n\nvar testCases = []testCase{\n    {\"d41d8cd98f00b204e9800998ecf8427e\", \"\"},\n    {\"0cc175b9c0f1b6a831c399e269772661\", \"a\"},\n    {\"900150983cd24fb0d6963f7d28e17f72\", \"abc\"},\n    {\"f96b697d7cb7938d525a2f31aaf161d0\", \"message digest\"},\n    {\"c3fcd3d76192e4007dfb496cca67e13b\", \"abcdefghijklmnopqrstuvwxyz\"},\n    {\"d174ab98d277d9f5a5611c2c9f419d9f\",\n        \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"},\n    {\"57edf4a22be3c955ac49da2e2107b67a\", \"12345678901234567890\" +\n        \"123456789012345678901234567890123456789012345678901234567890\"},\n}\n\nfunc main() {\n    for _, tc := range testCases {\n        fmt.Printf(\"%s\\n%x\\n\\n\", tc.hashCode, md5(tc.string))\n    }\n}\n\nvar shift = [...]uint{7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21}\nvar table [64]uint32\n\nfunc init() {\n    for i := range table {\n        table[i] = uint32((1 << 32) * math.Abs(math.Sin(float64(i + 1))))\n    }\n}\n\nfunc md5(s string) (r [16]byte) {\n    padded := bytes.NewBuffer([]byte(s))\n    padded.WriteByte(0x80)\n    for padded.Len() % 64 != 56 {\n        padded.WriteByte(0)\n    }\n    messageLenBits := uint64(len(s)) * 8\n    binary.Write(padded, binary.LittleEndian, messageLenBits)\n\n    var a, b, c, d uint32 = 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476\n    var buffer [16]uint32\n    for binary.Read(padded, binary.LittleEndian, buffer[:]) == nil { \/\/ read every 64 bytes\n        a1, b1, c1, d1 := a, b, c, d\n        for j := 0; j < 64; j++ {\n            var f uint32\n            bufferIndex := j\n            round := j >> 4\n            switch round {\n            case 0:\n                f = (b1 & c1) | (^b1 & d1)\n            case 1:\n                f = (b1 & d1) | (c1 & ^d1)\n                bufferIndex = (bufferIndex*5 + 1) & 0x0F\n            case 2:\n                f = b1 ^ c1 ^ d1\n                bufferIndex = (bufferIndex*3 + 5) & 0x0F\n            case 3:\n                f = c1 ^ (b1 | ^d1)\n                bufferIndex = (bufferIndex * 7) & 0x0F\n            }\n            sa := shift[(round<<2)|(j&3)]\n            a1 += f + buffer[bufferIndex] + table[j]\n            a1, d1, c1, b1 = d1, c1, b1, a1<<sa|a1>>(32-sa)+b1\n        }\n        a, b, c, d = a+a1, b+b1, c+c1, d+d1\n    }\n\n    binary.Write(bytes.NewBuffer(r[:0]), binary.LittleEndian, []uint32{a, b, c, d})\n    return\n}\n\n\nd41d8cd98f00b204e9800998ecf8427e\nd41d8cd98f00b204e9800998ecf8427e\n\n0cc175b9c0f1b6a831c399e269772661\n0cc175b9c0f1b6a831c399e269772661\n\n900150983cd24fb0d6963f7d28e17f72\n900150983cd24fb0d6963f7d28e17f72\n\nf96b697d7cb7938d525a2f31aaf161d0\nf96b697d7cb7938d525a2f31aaf161d0\n\nc3fcd3d76192e4007dfb496cca67e13b\nc3fcd3d76192e4007dfb496cca67e13b\n\nd174ab98d277d9f5a5611c2c9f419d9f\nd174ab98d277d9f5a5611c2c9f419d9f\n\n57edf4a22be3c955ac49da2e2107b67a\n57edf4a22be3c955ac49da2e2107b67a\n\n","human_summarization":"The code is an implementation of the MD5 Message Digest Algorithm, developed without using built-in or external hashing libraries. It generates a correct message digest for an input string, demonstrating bit manipulation, working with unsigned integers, and handling little-endian data. The code also handles boundary conditions and ensures accuracy in padding, endianness, and data layout. However, it does not support messages of arbitrary bit length, only those that are a number of whole bytes. It's important to note that the MD5 algorithm is not secure and should not be used in applications requiring high security.","id":1369}
    {"lang_cluster":"Go","source_code":"package main\n\nimport \"fmt\"\n\nfunc main() {\n    fmt.Println(\"Police  Sanitation  Fire\")\n    fmt.Println(\"------  ----------  ----\")\n    count := 0\n    for i := 2; i < 7; i += 2 {\n        for j := 1; j < 8; j++ {\n            if j == i { continue }\n            for k := 1; k < 8; k++ {\n                if k == i || k == j { continue }\n                if i + j + k != 12 { continue }\n                fmt.Printf(\"  %d         %d         %d\\n\", i, j, k)\n                count++\n            }\n        }\n    }\n    fmt.Printf(\"\\n%d valid combinations\\n\", count)\n}\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":1370}
    {"lang_cluster":"Go","source_code":"\n\nsrc := \"Hello\"\ndst := src\n\n\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n\t\/\/ creature string\n\tvar creature string = \"shark\"\n\t\/\/ point to creature\n\tvar pointer *string = &creature\n\t\/\/ creature string\n\tfmt.Println(\"creature =\", creature) \/\/ creature = shark\n\t\/\/ creature location in memory\n\tfmt.Println(\"pointer =\", pointer) \/\/ pointer = 0xc000010210\n\t\/\/ creature through the pointer\n\tfmt.Println(\"*pointer =\", *pointer) \/\/ *pointer = shark\n\t\/\/ set creature through the pointer\n\t*pointer = \"jellyfish\"\n\t\/\/ creature through the pointer\n\tfmt.Println(\"*pointer =\", *pointer) \/\/ *pointer = jellyfish\n\t\/\/ creature string\n\tfmt.Println(\"creature =\", creature) \/\/ creature = jellyfish\n}\n\n","human_summarization":"The code copies a string in Go language, where there's no need to differentiate between copying the contents and making an additional reference due to the immutability of strings. A new slice object is created during the assignment, possibly pointing to the same underlying array as the source string. However, this behavior is not guaranteed by the language.","id":1371}
    {"lang_cluster":"Go","source_code":"\n\npackage main\nimport \"fmt\"\n\nfunc F(n int) int {\n  if n == 0 { return 1 }\n  return n - M(F(n-1))\n}\n\nfunc M(n int) int {\n  if n == 0 { return 0 }\n  return n - F(M(n-1))\n}\n\nfunc main() {\n  for i := 0; i < 20; i++ {\n    fmt.Printf(\"%2d \", F(i))\n  }\n  fmt.Println()\n  for i := 0; i < 20; i++ {\n    fmt.Printf(\"%2d \", M(i))\n  }\n  fmt.Println()\n}\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions call each other in their definitions. If mutual recursion is not supported, the code will indicate this instead of providing an alternative solution. No special pre-declaration is required for these functions.","id":1372}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/rand\"\n    \"time\"\n)\n\nvar list = []string{\"bleen\", \"fuligin\", \"garrow\", \"grue\", \"hooloovoo\"}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    fmt.Println(list[rand.Intn(len(list))])\n}\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":1373}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net\/url\"\n)\n\nfunc main() {\n\tfor _, escaped := range []string{\n\t\t\"http%3A%2F%2Ffoo%20bar%2F\",\n\t\t\"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\",\n\t} {\n\t\tu, err := url.QueryUnescape(escaped)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Println(u)\n\t}\n}\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":1374}
    {"lang_cluster":"Go","source_code":"\n\nfunc binarySearch(a []float64, value float64, low int, high int) int {\n    if high < low {\n        return -1\n    }\n    mid := (low + high) \/ 2\n    if a[mid] > value {\n        return binarySearch(a, value, low, mid-1)\n    } else if a[mid] < value {\n        return binarySearch(a, value, mid+1, high)\n    }\n    return mid\n}\n\n\nfunc binarySearch(a []float64, value float64) int {\n    low := 0\n    high := len(a) - 1\n    for low <= high {\n        mid := (low + high) \/ 2\n        if a[mid] > value {\n            high = mid - 1\n        } else if a[mid] < value {\n            low = mid + 1\n        } else {\n            return mid\n        }\n    }\n    return -1\n}\n\n\nimport \"sort\"\n\n\/\/...\n\nsort.SearchInts([]int{0,1,4,5,6,7,8,9}, 6) \/\/ evaluates to 4\n\n\n","human_summarization":"The code implements a binary search algorithm that divides a range of values into halves to find a specific \"secret value\". It can handle both recursive and iterative methods. The code also includes different versions of binary search algorithms: traditional, leftmost insertion point, and rightmost insertion point. It ensures no overflow bugs occur by using specific techniques to calculate the midpoint. The code also provides the functionality to search within a sorted integer array and returns the index of the secret value if found.","id":1375}
    {"lang_cluster":"Go","source_code":"\npackage main\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfor i, x := range os.Args[1:] {\n\t\tfmt.Printf(\"the argument #%d is %s\\n\", i, x)\n\t}\n}\n\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c \"alpha beta\" -h \"gamma\"'. It also includes functionalities for intelligent parsing of these arguments.","id":1376}
    {"lang_cluster":"Go","source_code":"\nUsing Library: GXUI from Github\npackage main\n\nimport (\n\t\"github.com\/google\/gxui\"\n\t\"github.com\/google\/gxui\/drivers\/gl\"\n\t\"github.com\/google\/gxui\/math\"\n\t\"github.com\/google\/gxui\/themes\/dark\"\n\tomath \"math\"\n\t\"time\"\n)\n\n\/\/Two pendulums animated\n\/\/Top: Mathematical pendulum with small-angle approxmiation (not appropiate with PHI_ZERO=pi\/2)\n\/\/Bottom: Simulated with differential equation phi'' = g\/l * sin(phi)\n\nconst (\n\tANIMATION_WIDTH  int     = 480\n\tANIMATION_HEIGHT int     = 320\n\tBALL_RADIUS      float32 = 25.0\n\tMETER_PER_PIXEL  float64 = 1.0 \/ 20.0\n\tPHI_ZERO         float64 = omath.Pi * 0.5\n)\n\nvar (\n\tl    float64 = float64(ANIMATION_HEIGHT) * 0.5\n\tfreq float64 = omath.Sqrt(9.81 \/ (l * METER_PER_PIXEL))\n)\n\ntype Pendulum interface {\n\tGetPhi() float64\n}\n\ntype mathematicalPendulum struct {\n\tstart time.Time\n}\n\nfunc (p *mathematicalPendulum) GetPhi() float64 {\n\tif (p.start == time.Time{}) {\n\t\tp.start = time.Now()\n\t}\n\tt := float64(time.Since(p.start).Nanoseconds()) \/ omath.Pow10(9)\n\treturn PHI_ZERO * omath.Cos(t*freq)\n}\n\ntype numericalPendulum struct {\n\tcurrentPhi float64\n\tangAcc     float64\n\tangVel     float64\n\tlastTime   time.Time\n}\n\nfunc (p *numericalPendulum) GetPhi() float64 {\n\tdt := 0.0\n\tif (p.lastTime != time.Time{}) {\n\t\tdt = float64(time.Since(p.lastTime).Nanoseconds()) \/ omath.Pow10(9)\n\t}\n\tp.lastTime = time.Now()\n\n\tp.angAcc = -9.81 \/ (float64(l) * METER_PER_PIXEL) * omath.Sin(p.currentPhi)\n\tp.angVel += p.angAcc * dt\n\tp.currentPhi += p.angVel * dt\n\n\treturn p.currentPhi\n}\n\nfunc draw(p Pendulum, canvas gxui.Canvas, x, y int) {\n\tattachment := math.Point{X: ANIMATION_WIDTH\/2 + x, Y: y}\n\n\tphi := p.GetPhi()\n\tball := math.Point{X: x + ANIMATION_WIDTH\/2 + math.Round(float32(l*omath.Sin(phi))), Y: y + math.Round(float32(l*omath.Cos(phi)))}\n\n\tline := gxui.Polygon{gxui.PolygonVertex{attachment, 0}, gxui.PolygonVertex{ball, 0}}\n\n\tcanvas.DrawLines(line, gxui.DefaultPen)\n\n\tm := math.Point{int(BALL_RADIUS), int(BALL_RADIUS)}\n\trect := math.Rect{ball.Sub(m), ball.Add(m)}\n\tcanvas.DrawRoundedRect(rect, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, BALL_RADIUS, gxui.TransparentPen, gxui.CreateBrush(gxui.Yellow))\n}\n\nfunc appMain(driver gxui.Driver) {\n\ttheme := dark.CreateTheme(driver)\n\n\twindow := theme.CreateWindow(ANIMATION_WIDTH, 2*ANIMATION_HEIGHT, \"Pendulum\")\n\twindow.SetBackgroundBrush(gxui.CreateBrush(gxui.Gray50))\n\n\timage := theme.CreateImage()\n\n\tticker := time.NewTicker(time.Millisecond * 15)\n\tpendulum := &mathematicalPendulum{}\n\tpendulum2 := &numericalPendulum{PHI_ZERO, 0.0, 0.0, time.Time{}}\n\n\tgo func() {\n\t\tfor _ = range ticker.C {\n\t\t\tcanvas := driver.CreateCanvas(math.Size{ANIMATION_WIDTH, 2 * ANIMATION_HEIGHT})\n\t\t\tcanvas.Clear(gxui.White)\n\n\t\t\tdraw(pendulum, canvas, 0, 0)\n\t\t\tdraw(pendulum2, canvas, 0, ANIMATION_HEIGHT)\n\n\t\t\tcanvas.Complete()\n\t\t\tdriver.Call(func() {\n\t\t\t\timage.SetCanvas(canvas)\n\t\t\t})\n\t\t}\n\t}()\n\n\twindow.AddChild(image)\n\n\twindow.OnClose(ticker.Stop)\n\twindow.OnClose(driver.Terminate)\n}\n\nfunc main() {\n\tgl.StartDriver(appMain)\n}\n\n","human_summarization":"create and animate a simple physical model of a gravity pendulum.","id":1377}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"encoding\/json\"\nimport \"fmt\"\n\nfunc main() {\n    var data interface{}\n    err := json.Unmarshal([]byte(`{\"foo\":1, \"bar\":[10, \"apples\"]}`), &data)\n    if err == nil {\n        fmt.Println(data)\n    } else {\n        fmt.Println(err)\n    }\n\n    sample := map[string]interface{}{\n        \"blue\":  []interface{}{1, 2},\n        \"ocean\": \"water\",\n    }\n    json_string, err := json.Marshal(sample)\n    if err == nil {\n        fmt.Println(string(json_string))\n    } else {\n        fmt.Println(err)\n    }\n}\n\n\n","human_summarization":"load a JSON string into a data structure, create a new data structure and serialize it into JSON, ensuring the JSON is valid. The codes also demonstrate the correspondence between JSON objects and Go maps, and how to handle expected correspondence between JSON data and composite data types in the program.","id":1378}
    {"lang_cluster":"Go","source_code":"\nfunc root(a float64, n int) float64 {\n    n1 := n - 1\n    n1f, rn := float64(n1), 1\/float64(n)\n    x, x0 := 1., 0.\n    for {\n        potx, t2 := 1\/x, a\n        for b := n1; b > 0; b >>= 1 {\n            if b&1 == 1 {\n                t2 *= potx\n            }\n            potx *= potx\n        }\n        x0, x = x, rn*(n1f*x+t2)\n        if math.Abs(x-x0)*1e15 < x {\n            break\n        }\n    }\n    return x\n}\n\n\nimport \"math\/big\"\n\nfunc Root(a *big.Float, n uint64) *big.Float {\n\tlimit := Exp(New(2), 256) \n\tn1 := n-1\n\tn1f, rn := New(float64(n1)), Div(New(1.0), New(float64(n)))\n\tx, x0 := New(1.0), Zero()\n\t_ = x0\n\tfor {\n\t\tpotx, t2 := Div(New(1.0), x), a\n\t\tfor b:=n1; b>0; b>>=1 {\n\t\t\tif b&1 == 1 {\n\t\t\t\tt2 = Mul(t2, potx)\n\t\t\t}\n\t\t\tpotx = Mul(potx, potx)\n\t\t}\n\t\tx0, x = x, Mul(rn, Add(Mul(n1f, x), t2) )\n\t\tif Lesser(Mul(Abs(Sub(x, x0)), limit), x) { break } \n\t}\n\treturn x\n}\n\nfunc Abs(a *big.Float) *big.Float {\n\treturn Zero().Abs(a)\n}\n\nfunc Exp(a *big.Float, e uint64) *big.Float {\n\tresult := Zero().Copy(a)\n\tfor i:=uint64(0); i<e-1; i++ {\n\t\tresult = Mul(result, a)\n\t}\n\treturn result\n}\n\nfunc New(f float64) *big.Float {\n\tr := big.NewFloat(f)\n\tr.SetPrec(256)\n\treturn r\n}\n\nfunc Div(a, b *big.Float) *big.Float {\n\treturn Zero().Quo(a, b)\n}\n\nfunc Zero() *big.Float {\n\tr := big.NewFloat(0.0)\n\tr.SetPrec(256)\n\treturn r\n}\n\nfunc Mul(a, b *big.Float) *big.Float {\n\treturn Zero().Mul(a, b)\n}\n\nfunc Add(a, b *big.Float) *big.Float {\n\treturn Zero().Add(a, b)\n}\n\nfunc Sub(a, b *big.Float) *big.Float {\n\treturn Zero().Sub(a, b)\n}\n\nfunc Lesser(x, y *big.Float) bool {\n\treturn x.Cmp(y) == -1\n}\n\n","human_summarization":"implement an algorithm to compute the principal nth root of a positive real number using the method explained on Wikipedia. The implementation is for 64-bit wide floating point numbers and uses the `math\/big` Float for 256 bits of precision. Wrapper functions are used for readability and a power function (Exp) is created due to its absence in the library. The function avoids an infinite loop by ensuring the exponent in the limit is at least one less than the precision of the input value.","id":1379}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n)\n\nfunc main() {\n\tfmt.Println(os.Hostname())\n}\n\n","human_summarization":"Retrieves the hostname of the system where the program is running using os.Hostname.","id":1380}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc leonardo(n, l0, l1, add int) []int {\n    leo := make([]int, n)\n    leo[0] = l0\n    leo[1] = l1\n    for i := 2; i < n; i++ {\n        leo[i] = leo[i - 1] + leo[i - 2] + add\n    }\n    return leo\n}\n\nfunc main() {\n    fmt.Println(\"The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:\")\n    fmt.Println(leonardo(25, 1, 1, 1))\n    fmt.Println(\"\\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:\")\n    fmt.Println(leonardo(25, 0, 1, 0))\n}\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":1381}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n    \"math\/rand\"\n    \"time\"\n)\n\nfunc main() {\n    rand.Seed(time.Now().Unix())\n    n := make([]rune, 4)\n    for i := range n {\n        n[i] = rune(rand.Intn(9) + '1')\n    }\n    fmt.Printf(\"Your numbers: %c\\n\", n)\n    fmt.Print(\"Enter RPN: \")\n    var expr string\n    fmt.Scan(&expr)\n    if len(expr) != 7 {\n        fmt.Println(\"invalid. expression length must be 7.\" +\n            \" (4 numbers, 3 operators, no spaces)\")\n        return\n    }\n    stack := make([]float64, 0, 4)\n    for _, r := range expr {\n        if r >= '0' && r <= '9' {\n            if len(n) == 0 {\n                fmt.Println(\"too many numbers.\")\n                return\n            }\n            i := 0\n            for n[i] != r {\n                i++\n                if i == len(n) {\n                    fmt.Println(\"wrong numbers.\")\n                    return\n                }\n            }\n            n = append(n[:i], n[i+1:]...)\n            stack = append(stack, float64(r-'0'))\n            continue\n        }\n        if len(stack) < 2 {\n            fmt.Println(\"invalid expression syntax.\")\n            return\n        }\n        switch r {\n        case '+':\n            stack[len(stack)-2] += stack[len(stack)-1]\n        case '-':\n            stack[len(stack)-2] -= stack[len(stack)-1]\n        case '*':\n            stack[len(stack)-2] *= stack[len(stack)-1]\n        case '\/':\n            stack[len(stack)-2] \/= stack[len(stack)-1]\n        default:\n            fmt.Printf(\"%c invalid.\\n\", r)\n            return\n        }\n        stack = stack[:len(stack)-1]\n    }\n    if math.Abs(stack[0]-24) > 1e-6 {\n        fmt.Println(\"incorrect.\", stack[0], \"!= 24\")\n    } else {\n        fmt.Println(\"correct.\")\n    }\n}\n\n\nYour numbers: [5 8 1 3]\nEnter RPN: 83-5*1-\ncorrect.\n\n","human_summarization":"The code generates four random digits from 1 to 9 and prompts the player to form an arithmetic expression using these digits exactly once each. The expression should evaluate to 24 using the allowed operators (addition, subtraction, multiplication, division). The code also checks and evaluates the player's input expression. The division operator preserves remainders, and the order of the digits in the expression does not need to match the original order.","id":1382}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\n\/\/ encoding scheme:\n\/\/ encode to byte array\n\/\/ byte value < 26 means single character: byte value + 'A'\n\/\/ byte value 26..255 means (byte value - 24) copies of next byte\nfunc rllEncode(s string) (r []byte) {\n    if s == \"\" {\n        return\n    }\n    c := s[0]\n    if c < 'A' || c > 'Z' {\n        panic(\"invalid\")\n    }\n    nc := byte(1)\n    for i := 1; i < len(s); i++ {\n        d := s[i]\n        switch {\n        case d != c:\n        case nc < (255 - 24):\n            nc++\n            continue\n        }\n        if nc > 1 {\n            r = append(r, nc+24)\n        }\n        r = append(r, c-'A')\n        if d < 'A' || d > 'Z' {\n            panic(\"invalid\")\n        }\n        c = d\n        nc = 1\n    }\n    if nc > 1 {\n        r = append(r, nc+24)\n    }\n    r = append(r, c-'A')\n    return\n}\n\nfunc main() {\n    s := \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\n    fmt.Println(\"source: \", len(s), \"bytes:\", s)\n    e := rllEncode(s)\n    fmt.Println(\"encoded:\", len(e), \"bytes:\", e)\n    d := rllDecode(e)\n    fmt.Println(\"decoded:\", len(d), \"bytes:\", d)\n    fmt.Println(\"decoded = source:\", d == s)\n}\n\nfunc rllDecode(e []byte) string {\n    var c byte\n    var d []byte\n    for i := 0; i < len(e); i++ {\n        b := e[i]\n        if b < 26 {\n            c = 1\n        } else {\n            c = b - 24\n            i++\n            b = e[i]\n        }\n        for c > 0 {\n            d = append(d, b+'A')\n            c--\n        }\n    }\n    return string(d)\n}\n\n\nsource:  67 bytes: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nencoded: 12 bytes: [36 22 1 36 22 27 1 48 22 1 38 22]\ndecoded: 67 bytes: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\ndecoded = source: true\n\n","human_summarization":"implement a run-length encoding and decoding system. The code compresses consecutive repeated characters in a given string by storing the length of the run. It also provides a function to reverse the compression, effectively decoding the encoded string. The input string consists of uppercase characters (A-Z) only. The output can be any format that can be used to recreate the original input string.","id":1383}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ text assigned to a string variable\n    s := \"hello\"\n\n    \/\/ output string variable\n    fmt.Println(s)\n\n    \/\/ this output requested by original task descrption, although\n    \/\/ not really required by current wording of task description.\n    fmt.Println(s + \" literal\")\n\n    \/\/ concatenate variable and literal, assign result to another string variable\n    s2 := s + \" literal\"\n\n    \/\/ output second string variable\n    fmt.Println(s2)\n}\n\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":1384}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"net\/url\"\n)\n\nfunc main() {\n    fmt.Println(url.QueryEscape(\"http:\/\/foo bar\/\"))\n}\n\n\n","human_summarization":"The code provides a function to convert a given string into its URL encoding representation. It converts all characters, except 0-9, A-Z, and a-z, into their corresponding percent-encoded hexadecimal code. The code also allows for variations such as lowercase escapes and different encodings for special characters based on different standards like RFC 3986, HTML 5, and the encodeURI function in Javascript. An optional feature is the use of an exception string that contains symbols that don't need to be converted.","id":1385}
    {"lang_cluster":"Go","source_code":"package main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\nfunc distinctSortedUnion(ll [][]int) []int {\n    var res []int\n    for _, l := range ll {\n        res = append(res, l...)\n    }\n    set := make(map[int]bool)\n    for _, e := range res {\n        set[e] = true\n    }\n    res = res[:0]\n    for key := range set {\n        res = append(res, key)\n    }\n    sort.Ints(res)\n    return res\n}\n\nfunc main() {\n    ll := [][]int{{5, 1, 3, 8, 9, 4, 8, 7}, {3, 5, 9, 8, 4}, {1, 3, 7, 9}}\n    fmt.Println(\"Distinct sorted union of\", ll, \"is:\")\n    fmt.Println(distinctSortedUnion(ll))\n}\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":1386}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"sort\"\n)\n\ntype item struct {\n    item   string\n    weight float64\n    price  float64\n}\n\ntype items []item\n\nvar all = items{\n    {\"beef\", 3.8, 36},\n    {\"pork\", 5.4, 43},\n    {\"ham\", 3.6, 90},\n    {\"greaves\", 2.4, 45},\n    {\"flitch\", 4.0, 30},\n    {\"brawn\", 2.5, 56},\n    {\"welt\", 3.7, 67},\n    {\"salami\", 3.0, 95},\n    {\"sausage\", 5.9, 98},\n}\n\n\/\/ satisfy sort interface\nfunc (z items) Len() int      { return len(z) }\nfunc (z items) Swap(i, j int) { z[i], z[j] = z[j], z[i] }\nfunc (z items) Less(i, j int) bool {\n    return z[i].price\/z[i].weight > z[j].price\/z[j].weight\n}\n\nfunc main() {\n    left := 15.\n    sort.Sort(all)\n    for _, i := range all {\n        if i.weight <= left {\n            fmt.Println(\"take all the\", i.item)\n            if i.weight == left {\n                return\n            }\n            left -= i.weight\n        } else {\n            fmt.Printf(\"take\u00a0%.1fkg %s\\n\", left, i.item)\n            return\n        }\n    }\n}\n\n\ntake all the salami\ntake all the ham\ntake all the brawn\ntake all the greaves\ntake 3.5kg welt\n\n","human_summarization":"\"Implement a solution for the continuous knapsack problem where a thief maximizes his profit by selecting and possibly cutting items from a butcher's shop, given their weights and prices, without exceeding the knapsack's maximum capacity of 15 kg.\"","id":1387}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"io\/ioutil\"\n    \"net\/http\"\n    \"sort\"\n)\n\nfunc main() {\n    r, err := http.Get(\"http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    b, err := ioutil.ReadAll(r.Body)\n    r.Body.Close()\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    var ma int\n    var bs byteSlice\n    m := make(map[string][][]byte)\n    for _, word := range bytes.Fields(b) {\n        bs = append(bs[:0], byteSlice(word)...)\n        sort.Sort(bs)\n        k := string(bs)\n        a := append(m[k], word)\n        if len(a) > ma {\n            ma = len(a)\n        }\n        m[k] = a\n    }\n    for _, a := range m {\n        if len(a) == ma {\n            fmt.Printf(\"%s\\n\", a)\n        }\n    }\n}\n\ntype byteSlice []byte\n\nfunc (b byteSlice) Len() int           { return len(b) }\nfunc (b byteSlice) Swap(i, j int)      { b[i], b[j] = b[j], b[i] }\nfunc (b byteSlice) Less(i, j int) bool { return b[i] < b[j] }\n\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":1388}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"strings\"\n    \"unicode\/utf8\"\n)\n\nvar order = 3\nvar grain = \"#\"\n\nfunc main() {\n    carpet := []string{grain}\n    for ; order > 0; order-- {\n        \/\/ repeat expression allows for multiple character\n        \/\/ grain and for multi-byte UTF-8 characters.\n        hole := strings.Repeat(\" \", utf8.RuneCountInString(carpet[0]))\n        middle := make([]string, len(carpet))\n        for i, s := range carpet {\n            middle[i] = s + hole + s\n            carpet[i] = strings.Repeat(s, 3)\n        }\n        carpet = append(append(carpet, middle...), carpet...)\n    }\n    for _, r := range carpet {\n        fmt.Println(r)\n    }\n}\n\n","human_summarization":"generate an ASCII-art or graphical representation of a Sierpinski carpet of a given order N, where the placement of whitespace and non-whitespace characters is crucial. The non-whitespace character can be customized.","id":1389}
    {"lang_cluster":"Go","source_code":"package main\n\nimport (\n    \"container\/heap\"\n    \"fmt\"\n)\n\ntype HuffmanTree interface {\n    Freq() int\n}\n\ntype HuffmanLeaf struct {\n    freq  int\n    value rune\n}\n\ntype HuffmanNode struct {\n    freq        int\n    left, right HuffmanTree\n}\n\nfunc (self HuffmanLeaf) Freq() int {\n    return self.freq\n}\n\nfunc (self HuffmanNode) Freq() int {\n    return self.freq\n}\n\ntype treeHeap []HuffmanTree\n\nfunc (th treeHeap) Len() int { return len(th) }\nfunc (th treeHeap) Less(i, j int) bool {\n    return th[i].Freq() < th[j].Freq()\n}\nfunc (th *treeHeap) Push(ele interface{}) {\n    *th = append(*th, ele.(HuffmanTree))\n}\nfunc (th *treeHeap) Pop() (popped interface{}) {\n    popped = (*th)[len(*th)-1]\n    *th = (*th)[:len(*th)-1]\n    return\n}\nfunc (th treeHeap) Swap(i, j int) { th[i], th[j] = th[j], th[i] }\n\nfunc buildTree(symFreqs map[rune]int) HuffmanTree {\n    var trees treeHeap\n    for c, f := range symFreqs {\n        trees = append(trees, HuffmanLeaf{f, c})\n    }\n    heap.Init(&trees)\n    for trees.Len() > 1 {\n        \/\/ two trees with least frequency\n        a := heap.Pop(&trees).(HuffmanTree)\n        b := heap.Pop(&trees).(HuffmanTree)\n\n        \/\/ put into new node and re-insert into queue\n        heap.Push(&trees, HuffmanNode{a.Freq() + b.Freq(), a, b})\n    }\n    return heap.Pop(&trees).(HuffmanTree)\n}\n\nfunc printCodes(tree HuffmanTree, prefix []byte) {\n    switch i := tree.(type) {\n    case HuffmanLeaf:\n        \/\/ print out symbol, frequency, and code for this\n        \/\/ leaf (which is just the prefix)\n        fmt.Printf(\"%c\\t%d\\t%s\\n\", i.value, i.freq, string(prefix))\n    case HuffmanNode:\n        \/\/ traverse left\n        prefix = append(prefix, '0')\n        printCodes(i.left, prefix)\n        prefix = prefix[:len(prefix)-1]\n\n        \/\/ traverse right\n        prefix = append(prefix, '1')\n        printCodes(i.right, prefix)\n        prefix = prefix[:len(prefix)-1]\n    }\n}\n\nfunc main() {\n    test := \"this is an example for huffman encoding\"\n\n    symFreqs := make(map[rune]int)\n    \/\/ read each symbol and record the frequencies\n    for _, c := range test {\n        symFreqs[c]++\n    }\n\n    \/\/ build tree\n    tree := buildTree(symFreqs)\n\n    \/\/ print out results\n    fmt.Println(\"SYMBOL\\tWEIGHT\\tHUFFMAN CODE\")\n    printCodes(tree, []byte{})\n}\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":1390}
    {"lang_cluster":"Go","source_code":"\nLibrary: go-gtk\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com\/mattn\/go-gtk\/gtk\"\n)\n\nfunc main() {\n    gtk.Init(nil)\n    window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)\n    window.SetTitle(\"Click me\")\n    label := gtk.NewLabel(\"There have been no clicks yet\")\n    var clicks int\n    button := gtk.NewButtonWithLabel(\"click me\")\n    button.Clicked(func() {\n        clicks++\n        if clicks == 1 {\n            label.SetLabel(\"Button clicked 1 time\")\n        } else {\n            label.SetLabel(fmt.Sprintf(\"Button clicked %d times\",\n                clicks))\n        }\n    })\n    vbox := gtk.NewVBox(false, 1)\n    vbox.Add(label)\n    vbox.Add(button)\n    window.Add(vbox)\n    window.Connect(\"destroy\", func() {\n        gtk.MainQuit()\n    })\n    window.ShowAll()\n    gtk.Main()\n}\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":1391}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"database\/sql\"\n    \"fmt\"\n    \"log\"\n\n    _ \"github.com\/mattn\/go-sqlite3\"\n)\n\nfunc main() {\n    \/\/ task req: show database connection\n    db, err := sql.Open(\"sqlite3\", \"rc.db\")\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    defer db.Close()\n    \/\/ task req: create table with typed fields, including a unique id\n    _, err = db.Exec(`create table addr (\n        id     int unique,\n        street text,\n        city   text,\n        state  text,\n        zip    text\n    )`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    \/\/ show output:  query the created field names and types\n    rows, err := db.Query(`pragma table_info(addr)`)\n    if err != nil {\n        log.Print(err)\n        return\n    }\n    var field, storage string\n    var ignore sql.RawBytes\n    for rows.Next() {\n        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)\n        if err != nil {\n            log.Print(err)\n            return\n        }\n        fmt.Println(field, storage)\n    }\n}\n\n\n","human_summarization":"create a table in a database to store US postal addresses, including fields for a unique identifier, street address, city, state code, and zipcode. The codes also demonstrate how to establish a database connection in non-database languages.","id":1392}
    {"lang_cluster":"Go","source_code":"\nfor i := 10; i >= 0; i-- {\n  fmt.Println(i)\n}\n\npackage main\n\nimport \"fmt\"\nimport \"time\"\n\nfunc main() {\n\ti := 10\n\tfor i > 0 {\n\t\tfmt.Println(i)\n\t\ttime.Sleep(time.Second)\n\t\ti = i - 1\n\t}\n\tfmt.Println(\"blast off\")\n}\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":1393}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\ntype vkey string\n\nfunc newVigen\u00e8re(key string) (vkey, bool) {\n    v := vkey(upperOnly(key))\n    return v, len(v) > 0 \/\/ key length 0 invalid\n}\n\nfunc (k vkey) encipher(pt string) string {\n    ct := upperOnly(pt)\n    for i, c := range ct {\n        ct[i] = 'A' + (c-'A'+k[i%len(k)]-'A')%26\n    }\n    return string(ct)\n}\n\nfunc (k vkey) decipher(ct string) (string, bool) {\n    pt := make([]byte, len(ct))\n    for i := range pt {\n        c := ct[i]\n        if c < 'A' || c > 'Z' {\n            return \"\", false \/\/ invalid ciphertext\n        }\n        pt[i] = 'A' + (c-k[i%len(k)]+26)%26\n    }\n    return string(pt), true\n}\n\n\/\/ upperOnly extracts letters A-Z, a-z from a string and\n\/\/ returns them all upper case in a byte slice.\n\/\/ Useful for vkey constructor and encipher function.\nfunc upperOnly(s string) []byte {\n    u := make([]byte, 0, len(s))\n    for i := 0; i < len(s); i++ {\n        c := s[i]\n        if c >= 'A' && c <= 'Z' {\n            u = append(u, c)\n        } else if c >= 'a' && c <= 'z' {\n            u = append(u, c-32)\n        }\n    }\n    return u\n}\n\nconst testKey = \"Vigen\u00e8re Cipher\"\nconst testPT = `Beware the Jabberwock, my son!\n    The jaws that bite, the claws that catch!`\n\nfunc main() {\n    fmt.Println(\"Supplied key: \", testKey)\n    v, ok := newVigen\u00e8re(testKey)\n    if !ok {\n        fmt.Println(\"Invalid key\")\n        return\n    }\n    fmt.Println(\"Effective key:\", v)\n    fmt.Println(\"Plain text:\", testPT)\n    ct := v.encipher(testPT)\n    fmt.Println(\"Enciphered:\", ct)\n    dt, ok := v.decipher(ct)\n    if !ok {\n        fmt.Println(\"Invalid ciphertext\")\n        return\n    }\n    fmt.Println(\"Deciphered:\", dt)\n}\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":1394}
    {"lang_cluster":"Go","source_code":"\n\nfor i := 1; i < 10; i += 2 {\n  fmt.Printf(\"%d\\n\", i)\n}\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one to print all odd digits.","id":1395}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nvar i int\n\nfunc sum(i *int, lo, hi int, term func() float64) float64 {\n    temp := 0.0\n    for *i = lo; *i <= hi; (*i)++ {\n        temp += term()\n    }\n    return temp\n}\n\nfunc main() {\n    fmt.Printf(\"%f\\n\", sum(&i, 1, 100, func() float64 { return 1.0 \/ float64(i) }))\n}\n\n\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":1396}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"image\"\n    \"image\/png\"\n    \"os\"\n)\n\nfunc main() {\n    g := image.NewGray(image.Rect(0, 0, 256, 256))\n    for i := range g.Pix {\n        g.Pix[i] = uint8(i>>8 ^ i)\n    }\n    f, _ := os.Create(\"xor.png\")\n    png.Encode(f, g)\n    f.Close()\n}\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":1397}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"bytes\"\n    \"fmt\"\n    \"math\/rand\"\n    \"time\"\n)   \n    \ntype maze struct { \n    c  []byte   \/\/ cell contents\n    h  []byte   \/\/ horizontal walls above cells\n    v  []byte   \/\/ vertical walls to the left of cells\n    c2 [][]byte \/\/ cells by row\n    h2 [][]byte \/\/ horizontal walls by row (ignore first row)\n    v2 [][]byte \/\/ vertical walls by row (ignore first of each column)\n}\n\nfunc newMaze(rows, cols int) *maze {\n    c := make([]byte, rows*cols)              \/\/ all cells\n    h := bytes.Repeat([]byte{'-'}, rows*cols) \/\/ all horizontal walls\n    v := bytes.Repeat([]byte{'|'}, rows*cols) \/\/ all vertical walls\n    c2 := make([][]byte, rows)                \/\/ cells by row\n    h2 := make([][]byte, rows)                \/\/ horizontal walls by row\n    v2 := make([][]byte, rows)                \/\/ vertical walls by row\n    for i := range h2 {\n        c2[i] = c[i*cols : (i+1)*cols]\n        h2[i] = h[i*cols : (i+1)*cols]\n        v2[i] = v[i*cols : (i+1)*cols]\n    }\n    return &maze{c, h, v, c2, h2, v2}\n}\n\nfunc (m *maze) String() string {\n    hWall := []byte(\"+---\")\n    hOpen := []byte(\"+   \")\n    vWall := []byte(\"|   \")\n    vOpen := []byte(\"    \")\n    rightCorner := []byte(\"+\\n\") \n    rightWall := []byte(\"|\\n\")\n    var b []byte\n    \/\/ for all rows \n    for r, hw := range m.h2 {\n        \/\/ draw h walls\n        for _, h := range hw { \n            if h == '-' || r == 0 {\n                b = append(b, hWall...)\n            } else {\n                b = append(b, hOpen...)\n            }\n        }\n        b = append(b, rightCorner...)\n        \/\/ draw v walls\n        for c, vw := range m.v2[r] {\n            if vw == '|' || c == 0 {\n                b = append(b, vWall...)\n            } else {\n                b = append(b, vOpen...)\n            }\n            \/\/ draw cell contents\n            if m.c2[r][c] != 0 {\n                b[len(b)-2] = m.c2[r][c]\n            }\n        }\n        b = append(b, rightWall...)\n    }\n    \/\/ draw bottom edge of maze\n    for _ = range m.h2[0] {\n        b = append(b, hWall...)\n    }\n    b = append(b, rightCorner...)\n    return string(b)\n}\n\nfunc (m *maze) gen() {\n    m.g2(rand.Intn(len(m.c2)), rand.Intn(len(m.c2[0])))\n}\n\nconst (\n    up = iota\n    dn\n    rt\n    lf\n)\n\nfunc (m *maze) g2(r, c int) {\n    m.c2[r][c] = ' '\n    for _, dir := range rand.Perm(4) {\n        switch dir {\n        case up:\n            if r > 0 && m.c2[r-1][c] == 0 {\n                m.h2[r][c] = 0\n                m.g2(r-1, c)\n            }\n        case lf:\n            if c > 0 && m.c2[r][c-1] == 0 {\n                m.v2[r][c] = 0\n                m.g2(r, c-1)\n            }\n        case dn:\n            if r < len(m.c2)-1 && m.c2[r+1][c] == 0 {\n                m.h2[r+1][c] = 0\n                m.g2(r+1, c)\n            }\n        case rt:\n            if c < len(m.c2[0])-1 && m.c2[r][c+1] == 0 {\n                m.v2[r][c+1] = 0\n                m.g2(r, c+1)\n            }\n        }\n    }\n}\n\nfunc main() {\n    rand.Seed(time.Now().UnixNano())\n    m := newMaze(4, 6)\n    m.gen()\n    fmt.Print(m)\n}\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":1398}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n    \"fmt\"\n    \"math\/big\"\n)\n\ntype lft struct {\n    q,r,s,t big.Int\n}\n\nfunc (t *lft) extr(x *big.Int) *big.Rat {\n    var n, d big.Int\n    var r big.Rat\n    return r.SetFrac(\n        n.Add(n.Mul(&t.q, x), &t.r),\n        d.Add(d.Mul(&t.s, x), &t.t))\n}\n\nvar three = big.NewInt(3)\nvar four = big.NewInt(4)\n\nfunc (t *lft) next() *big.Int {\n    r := t.extr(three)\n    var f big.Int\n    return f.Div(r.Num(), r.Denom())\n}\n\nfunc (t *lft) safe(n *big.Int) bool {\n    r := t.extr(four)\n    var f big.Int\n    if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {\n        return true\n    }\n    return false\n}\n\nfunc (t *lft) comp(u *lft) *lft {\n    var r lft\n    var a, b big.Int\n    r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))\n    r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))\n    r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))\n    r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))\n    return &r\n}\n\nfunc (t *lft) prod(n *big.Int) *lft {\n    var r lft\n    r.q.SetInt64(10)\n    r.r.Mul(r.r.SetInt64(-10), n)\n    r.t.SetInt64(1)\n    return r.comp(t)\n}\n\nfunc main() {\n    \/\/ init z to unit\n    z := new(lft)\n    z.q.SetInt64(1)\n    z.t.SetInt64(1)\n\n    \/\/ lfts generator\n    var k int64\n    lfts := func() *lft {\n        k++\n        r := new(lft)\n        r.q.SetInt64(k)\n        r.r.SetInt64(4*k+2)\n        r.t.SetInt64(2*k+1)\n        return r\n    }\n\n    \/\/ stream\n    for {\n        y := z.next()\n        if z.safe(y) {\n            fmt.Print(y)\n            z = z.prod(y)\n        } else {\n            z = z.comp(lfts())\n        }\n    }\n}\n\n","human_summarization":"The code continually calculates and outputs the next decimal digit of Pi. The program runs indefinitely, producing each decimal digit in succession starting from 3.14159265, until it is manually stopped by the user. It is based on the algorithm from the Unbounded Spigot Algorithms for the Digits of Pi and is used for the pidigits benchmark of the Computer Language Benchmarks Game. The code is a simple translation from Haskell and runs slower than the standard Go distribution.","id":1399}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\n\/\/ If your numbers happen to be in the range of Unicode code points (0 to 0x10ffff), this function\n\/\/ satisfies the task:\nfunc lessRune(a, b []rune) bool {\n    return string(a) < string(b) \/\/ see also bytes.Compare\n}\n\n\/\/ Otherwise, the following function satisfies the task for all integer\n\/\/ and floating point types, by changing the type definition appropriately.\ntype numericType int\n\nfunc lessNT(a, b []numericType) bool {\n    l := len(a)\n    if len(b) < l {\n        l = len(b)\n    }\n    for i := 0; i < l; i++ {\n        if a[i] != b[i] {\n            return a[i] < b[i]\n        }\n    }\n    return l < len(b)\n}\n\nvar testCases = [][][]numericType{\n    {{0}, {}},\n    {{}, {}},\n    {{}, {0}},\n\n    {{-1}, {0}},\n    {{0}, {0}},\n    {{0}, {-1}},\n\n    {{0}, {0, -1}},\n    {{0}, {0, 0}},\n    {{0}, {0, 1}},\n    {{0, -1}, {0}},\n    {{0, 0}, {0}},\n    {{0, 0}, {1}},\n}\n\nfunc main() {\n    \/\/ demonstrate the general function\n    for _, tc := range testCases {\n        fmt.Printf(\"order %6s before %6s\u00a0: %t\\n\",\n            fmt.Sprintf(\"%v\", tc[0]),\n            fmt.Sprintf(\"%v\", tc[1]),\n            lessNT(tc[0], tc[1]))\n    }\n    fmt.Println()\n\n    \/\/ demonstrate that the byte specific function gives identical results\n    \/\/ by offsetting test data to a printable range of characters.\n    for _, tc := range testCases {\n        a := toByte(tc[0])\n        b := toByte(tc[1])\n        fmt.Printf(\"order %6q before %6q\u00a0: %t\\n\",\n            string(a),\n            string(b),\n            lessByte(a, b))\n    }\n}\n\nfunc toByte(a []numericType) []byte {\n    b := make([]byte, len(a))\n    for i, n := range a {\n        b[i] = 'b' + byte(n)\n    }\n    return b\n}\n\n\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise.\"","id":1400}
    {"lang_cluster":"Go","source_code":"\nfunc Ackermann(m, n uint) uint {\n\tswitch 0 {\n\tcase m:\n\t\treturn n + 1\n\tcase n:\n\t\treturn Ackermann(m - 1, 1)\n\t}\n\treturn Ackermann(m - 1, Ackermann(m, n - 1))\n}\n\nfunc Ackermann2(m, n uint) uint {\n  switch {\n    case m == 0:\n      return n + 1\n    case m == 1:\n      return n + 2\n    case m == 2:\n      return 2*n + 3\n    case m == 3:\n      return 8 << n - 3\n    case n == 0:\n      return Ackermann2(m - 1, 1)\n  }\n  return Ackermann2(m - 1, Ackermann2(m, n - 1))\n}\n\npackage main\n\nimport (\n\t\"fmt\"\n\t\"math\/big\"\n\t\"math\/bits\" \/\/ Added in Go 1.9\n)\n\nvar one = big.NewInt(1)\nvar two = big.NewInt(2)\nvar three = big.NewInt(3)\nvar eight = big.NewInt(8)\n\nfunc Ackermann2(m, n *big.Int) *big.Int {\n\tif m.Cmp(three) <= 0 {\n\t\tswitch m.Int64() {\n\t\tcase 0:\n\t\t\treturn new(big.Int).Add(n, one)\n\t\tcase 1:\n\t\t\treturn new(big.Int).Add(n, two)\n\t\tcase 2:\n\t\t\tr := new(big.Int).Lsh(n, 1)\n\t\t\treturn r.Add(r, three)\n\t\tcase 3:\n\t\t\tif nb := n.BitLen(); nb > bits.UintSize {\n\t\t\t\t\/\/ n is too large to represent as a\n\t\t\t\t\/\/ uint for use in the Lsh method.\n\t\t\t\tpanic(TooBigError(nb))\n\n\t\t\t\t\/\/ If we tried to continue anyway, doing\n\t\t\t\t\/\/ 8*2^n-3 as bellow, we'd use hundreds\n\t\t\t\t\/\/ of megabytes and lots of CPU time\n\t\t\t\t\/\/ without the Exp call even returning.\n\t\t\t\tr := new(big.Int).Exp(two, n, nil)\n\t\t\t\tr.Mul(eight, r)\n\t\t\t\treturn r.Sub(r, three)\n\t\t\t}\n\t\t\tr := new(big.Int).Lsh(eight, uint(n.Int64()))\n\t\t\treturn r.Sub(r, three)\n\t\t}\n\t}\n\tif n.BitLen() == 0 {\n\t\treturn Ackermann2(new(big.Int).Sub(m, one), one)\n\t}\n\treturn Ackermann2(new(big.Int).Sub(m, one),\n\t\tAckermann2(m, new(big.Int).Sub(n, one)))\n}\n\ntype TooBigError int\n\nfunc (e TooBigError) Error() string {\n\treturn fmt.Sprintf(\"A(m,n) had n of %d bits; too large\", int(e))\n}\n\nfunc main() {\n\tshow(0, 0)\n\tshow(1, 2)\n\tshow(2, 4)\n\tshow(3, 100)\n\tshow(3, 1e6)\n\tshow(4, 1)\n\tshow(4, 2)\n\tshow(4, 3)\n}\n\nfunc show(m, n int64) {\n\tdefer func() {\n\t\t\/\/ Ackermann2 could\/should have returned an error\n\t\t\/\/ instead of a panic. But here's how to recover\n\t\t\/\/ from the panic, and report \"expected\" errors.\n\t\tif e := recover(); e != nil {\n\t\t\tif err, ok := e.(TooBigError); ok {\n\t\t\t\tfmt.Println(\"Error:\", err)\n\t\t\t} else {\n\t\t\t\tpanic(e)\n\t\t\t}\n\t\t}\n\t}()\n\n\tfmt.Printf(\"A(%d, %d) = \", m, n)\n\ta := Ackermann2(big.NewInt(m), big.NewInt(n))\n\tif a.BitLen() <= 256 {\n\t\tfmt.Println(a)\n\t} else {\n\t\ts := a.String()\n\t\tfmt.Printf(\"%d digits starting\/ending with: %s...%s\\n\",\n\t\t\tlen(s), s[:20], s[len(s)-20:],\n\t\t)\n\t}\n}\n\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":1401}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    fmt.Println(\"    x               math.Gamma                 Lanczos7\")\n    for _, x := range []float64{-.5, .1, .5, 1, 1.5, 2, 3, 10, 140, 170} {\n        fmt.Printf(\"%5.1f %24.16g %24.16g\\n\", x, math.Gamma(x), lanczos7(x))\n    }\n}\n\nfunc lanczos7(z float64) float64 {\n    t := z + 6.5\n    x := .99999999999980993 +\n        676.5203681218851\/z -\n        1259.1392167224028\/(z+1) +\n        771.32342877765313\/(z+2) -\n        176.61502916214059\/(z+3) +\n        12.507343278686905\/(z+4) -\n        .13857109526572012\/(z+5) +\n        9.9843695780195716e-6\/(z+6) +\n        1.5056327351493116e-7\/(z+7)\n    return math.Sqrt2 * math.SqrtPi * math.Pow(t, z-.5) * math.Exp(-t) * x\n}\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":1402}
    {"lang_cluster":"Go","source_code":"\n\/\/ A fairly literal translation of the example program on the referenced\n\/\/ WP page.  Well, it happened to be the example program the day I completed\n\/\/ the task.  It seems from the WP history that there has been some churn\n\/\/ in the posted example program.  The example program of the day was in\n\/\/ Pascal and was credited to Niklaus Wirth, from his \"Algorithms +\n\/\/ Data Structures = Programs.\"\npackage main\n \nimport \"fmt\"\n \nvar (\n    i int\n    q bool\n    a [9]bool\n    b [17]bool\n    c [15]bool \/\/ offset by 7 relative to the Pascal version\n    x [9]int\n)\n \nfunc try(i int) {\n    for j := 1; ; j++ {\n        q = false\n        if a[j] && b[i+j] && c[i-j+7] {\n            x[i] = j\n            a[j] = false\n            b[i+j] = false\n            c[i-j+7] = false\n            if i < 8 {\n                try(i + 1)\n                if !q {\n                    a[j] = true\n                    b[i+j] = true\n                    c[i-j+7] = true\n                }\n            } else {\n                q = true\n            }\n        }\n        if q || j == 8 {\n            break\n        }\n    }\n}\n \nfunc main() {\n    for i := 1; i <= 8; i++ {\n        a[i] = true\n    }\n    for i := 2; i <= 16; i++ {\n        b[i] = true\n    }\n    for i := 0; i <= 14; i++ {\n        c[i] = true\n    }\n    try(1)\n    if q {\n        for i := 1; i <= 8; i++ {\n            fmt.Println(i, x[i])\n        }\n    }\n}\n\n\n","human_summarization":"Implement the solution for the N-queens puzzle, including the eight queens puzzle, using Knuth's Algorithm X and dancing links technique as provided in the dlx package. The code also calculates the number of solutions for small values of N as referenced in OEIS: A000170.","id":1403}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\nfunc main() {\n    \/\/ Example 1:  Idiomatic in Go is use of the append function.\n    \/\/ Elements must be of identical type.\n    a := []int{1, 2, 3}\n    b := []int{7, 12, 60} \/\/ these are technically slices, not arrays\n    c := append(a, b...)\n    fmt.Println(c)\n\n    \/\/ Example 2:  Polymorphism.\n    \/\/ interface{} is a type too, one that can reference values of any type.\n    \/\/ This allows a sort of polymorphic list.\n    i := []interface{}{1, 2, 3}\n    j := []interface{}{\"Crosby\", \"Stills\", \"Nash\", \"Young\"}\n    k := append(i, j...) \/\/ append will allocate as needed\n    fmt.Println(k)\n\n    \/\/ Example 3:  Arrays, not slices.\n    \/\/ A word like \"array\" on RC often means \"whatever array means in your\n    \/\/ language.\"  In Go, the common role of \"array\" is usually filled by\n    \/\/ Go slices, as in examples 1 and 2.  If by \"array\" you really mean\n    \/\/ \"Go array,\" then you have to do a little extra work.  The best\n    \/\/ technique is almost always to create slices on the arrays and then\n    \/\/ use the copy function.\n    l := [...]int{1, 2, 3}\n    m := [...]int{7, 12, 60} \/\/ arrays have constant size set at compile time\n    var n [len(l) + len(m)]int\n    copy(n[:], l[:]) \/\/ [:] creates a slice that references the entire array\n    copy(n[len(l):], m[:])\n    fmt.Println(n)\n\n}\n\n\n","human_summarization":"demonstrate how to concatenate two arrays using the specific syntax of the programming language.","id":1404}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\ntype item struct {\n    string\n    w, v int\n}\n\nvar wants = []item{\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39, 40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"T-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nconst maxWt = 400\n\nfunc main() {\n    items, w, v := m(len(wants)-1, maxWt)\n    fmt.Println(items)\n    fmt.Println(\"weight:\", w)\n    fmt.Println(\"value:\", v)\n}\n\nfunc m(i, w int) ([]string, int, int) {\n    if i < 0 || w == 0 {\n        return nil, 0, 0\n    } else if wants[i].w > w {\n        return m(i-1, w)\n    }\n    i0, w0, v0 := m(i-1, w)\n    i1, w1, v1 := m(i-1, w-wants[i].w)\n    v1 += wants[i].v\n    if v1 > v0 {\n        return append(i1, wants[i].string), w1 + wants[i].w, v1\n    }\n    return i0, w0, v0\n}\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg. It uses the 0-1 knapsack problem solution to maximize the total value of items in the knapsack without exceeding the weight limit. The code does not allow for fractional items or multiple instances of the same item.","id":1405}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport \"fmt\"\n\n\/\/ Asymetry in the algorithm suggests different data structures for the\n\/\/ map value types of the proposers and the recipients.  Proposers go down\n\/\/ their list of preferences in order, and do not need random access.\n\/\/ Recipients on the other hand must compare their preferences to arbitrary\n\/\/ proposers.  A slice is adequate for proposers, but a map allows direct\n\/\/ lookups for recipients and avoids looping code.\ntype proposers map[string][]string\n    \nvar mPref = proposers{\n    \"abe\": []string{\n        \"abi\", \"eve\", \"cath\", \"ivy\", \"jan\",\n        \"dee\", \"fay\", \"bea\", \"hope\", \"gay\"},\n    \"bob\": []string{\n        \"cath\", \"hope\", \"abi\", \"dee\", \"eve\",\n        \"fay\", \"bea\", \"jan\", \"ivy\", \"gay\"},\n    \"col\": []string{\n        \"hope\", \"eve\", \"abi\", \"dee\", \"bea\",\n        \"fay\", \"ivy\", \"gay\", \"cath\", \"jan\"},\n    \"dan\": []string{\n        \"ivy\", \"fay\", \"dee\", \"gay\", \"hope\",\n        \"eve\", \"jan\", \"bea\", \"cath\", \"abi\"},\n    \"ed\": []string{\n        \"jan\", \"dee\", \"bea\", \"cath\", \"fay\",\n        \"eve\", \"abi\", \"ivy\", \"hope\", \"gay\"},\n    \"fred\": []string{\n        \"bea\", \"abi\", \"dee\", \"gay\", \"eve\",\n        \"ivy\", \"cath\", \"jan\", \"hope\", \"fay\"},\n    \"gav\": []string{\n        \"gay\", \"eve\", \"ivy\", \"bea\", \"cath\",\n        \"abi\", \"dee\", \"hope\", \"jan\", \"fay\"},\n    \"hal\": []string{\n        \"abi\", \"eve\", \"hope\", \"fay\", \"ivy\",\n        \"cath\", \"jan\", \"bea\", \"gay\", \"dee\"},\n    \"ian\": []string{\n        \"hope\", \"cath\", \"dee\", \"gay\", \"bea\",\n        \"abi\", \"fay\", \"ivy\", \"jan\", \"eve\"},\n    \"jon\": []string{\n        \"abi\", \"fay\", \"jan\", \"gay\", \"eve\",\n        \"bea\", \"dee\", \"cath\", \"ivy\", \"hope\"},\n}\n\ntype recipients map[string]map[string]int\n\nvar wPref = recipients{\n    \"abi\": map[string]int{\n        \"bob\": 1, \"fred\": 2, \"jon\": 3, \"gav\": 4, \"ian\": 5,\n        \"abe\": 6, \"dan\": 7, \"ed\": 8, \"col\": 9, \"hal\": 10},\n    \"bea\": map[string]int{\n        \"bob\": 1, \"abe\": 2, \"col\": 3, \"fred\": 4, \"gav\": 5,\n        \"dan\": 6, \"ian\": 7, \"ed\": 8, \"jon\": 9, \"hal\": 10},\n    \"cath\": map[string]int{\n        \"fred\": 1, \"bob\": 2, \"ed\": 3, \"gav\": 4, \"hal\": 5,\n        \"col\": 6, \"ian\": 7, \"abe\": 8, \"dan\": 9, \"jon\": 10},\n    \"dee\": map[string]int{\n        \"fred\": 1, \"jon\": 2, \"col\": 3, \"abe\": 4, \"ian\": 5,\n        \"hal\": 6, \"gav\": 7, \"dan\": 8, \"bob\": 9, \"ed\": 10},\n    \"eve\": map[string]int{\n        \"jon\": 1, \"hal\": 2, \"fred\": 3, \"dan\": 4, \"abe\": 5,\n        \"gav\": 6, \"col\": 7, \"ed\": 8, \"ian\": 9, \"bob\": 10},\n    \"fay\": map[string]int{\n        \"bob\": 1, \"abe\": 2, \"ed\": 3, \"ian\": 4, \"jon\": 5,\n        \"dan\": 6, \"fred\": 7, \"gav\": 8, \"col\": 9, \"hal\": 10},\n    \"gay\": map[string]int{\n        \"jon\": 1, \"gav\": 2, \"hal\": 3, \"fred\": 4, \"bob\": 5,\n        \"abe\": 6, \"col\": 7, \"ed\": 8, \"dan\": 9, \"ian\": 10},\n    \"hope\": map[string]int{\n        \"gav\": 1, \"jon\": 2, \"bob\": 3, \"abe\": 4, \"ian\": 5,\n        \"dan\": 6, \"hal\": 7, \"ed\": 8, \"col\": 9, \"fred\": 10},\n    \"ivy\": map[string]int{\n        \"ian\": 1, \"col\": 2, \"hal\": 3, \"gav\": 4, \"fred\": 5,\n        \"bob\": 6, \"abe\": 7, \"ed\": 8, \"jon\": 9, \"dan\": 10},\n    \"jan\": map[string]int{\n        \"ed\": 1, \"hal\": 2, \"gav\": 3, \"abe\": 4, \"bob\": 5,\n        \"jon\": 6, \"col\": 7, \"ian\": 8, \"fred\": 9, \"dan\": 10},\n}\n\nfunc main() {\n    \/\/ get parings by Gale\/Shapley algorithm\n    ps := pair(mPref, wPref)\n    \/\/ show results\n    fmt.Println(\"\\nresult:\")\n    if !validateStable(ps, mPref, wPref) {\n        return \n    }\n    \/\/ perturb\n    for {\n        i := 0 \n        var w2, m2 [2]string\n        for w, m := range ps {\n            w2[i] = w\n            m2[i] = m\n            if i == 1 {\n                break\n            }\n            i++\n        }\n        fmt.Println(\"\\nexchanging partners of\", m2[0], \"and\", m2[1])\n        ps[w2[0]] = m2[1]\n        ps[w2[1]] = m2[0] \n        \/\/ validate perturbed parings\n        if !validateStable(ps, mPref, wPref) {\n            return\n        }\n        \/\/ if those happened to be stable as well, perturb more\n    }\n}   \n\ntype parings map[string]string \/\/ map[recipient]proposer (or map[w]m)\n    \n\/\/ Pair implements the Gale\/Shapley algorithm.\nfunc pair(pPref proposers, rPref recipients) parings {\n    \/\/ code is destructive on the maps, so work with copies\n    pFree := proposers{}\n    for k, v := range pPref {\n        pFree[k] = append([]string{}, v...)\n    }\n    rFree := recipients{}\n    for k, v := range rPref {\n        rFree[k] = v\n    }\n    \/\/ struct only used in this function.\n    \/\/ preferences must be saved in case engagement is broken.\n    type save struct {\n        proposer string\n        pPref    []string\n        rPref    map[string]int\n    }\n    proposals := map[string]save{} \/\/ key is recipient (w)\n\n    \/\/ WP pseudocode comments prefaced with WP: m is proposer, w is recipient.\n    \/\/ WP: while \u2203 free man m who still has a woman w to propose to\n    for len(pFree) > 0 { \/\/ while there is a free proposer,\n        var proposer string\n        var ppref []string\n        for proposer, ppref = range pFree {\n            break \/\/ pick a proposer at random, whatever range delivers first.\n        }\n        if len(ppref) == 0 {\n            continue \/\/ if proposer has no possible recipients, skip\n        }\n        \/\/ WP: w = m's highest ranked such woman to whom he has not yet proposed\n        recipient := ppref[0] \/\/ highest ranged is first in list.\n        ppref = ppref[1:]     \/\/ pop from list\n        var rpref map[string]int\n        var ok bool\n        \/\/ WP: if w is free\n        if rpref, ok = rFree[recipient]; ok {\n            \/\/ WP: (m, w) become engaged\n            \/\/ (common code follows if statement)\n        } else {\n            \/\/ WP: else some pair (m', w) already exists\n            s := proposals[recipient] \/\/ get proposal saved preferences\n            \/\/ WP: if w prefers m to m'\n            if s.rPref[proposer] < s.rPref[s.proposer] {\n                fmt.Println(\"engagement broken:\", recipient, s.proposer)\n                \/\/ WP: m' becomes free\n                pFree[s.proposer] = s.pPref \/\/ return proposer to the map\n                \/\/ WP: (m, w) become engaged\n                rpref = s.rPref\n                \/\/ (common code follows if statement)\n            } else {\n                \/\/ WP: else (m', w) remain engaged\n                pFree[proposer] = ppref \/\/ update preferences in map\n                continue\n            } \n        }\n        fmt.Println(\"engagement:\", recipient, proposer)\n        proposals[recipient] = save{proposer, ppref, rpref}\n        delete(pFree, proposer)\n        delete(rFree, recipient)\n    }\n    \/\/ construct return value \n    ps := parings{}\n    for recipient, s := range proposals {\n        ps[recipient] = s.proposer\n    }\n    return ps\n}\n\nfunc validateStable(ps parings, pPref proposers, rPref recipients) bool {\n    for r, p := range ps {\n        fmt.Println(r, p)\n    }\n    for r, p := range ps {\n        for _, rp := range pPref[p] {\n            if rp == r {\n                break\n            }\n            rprefs := rPref[rp]\n            if rprefs[p] < rprefs[ps[rp]] {\n                fmt.Println(\"unstable.\")\n                fmt.Printf(\"%s and %s would prefer each other over\"+\n                    \" their current pairings.\\n\", p, rp)\n                return false\n            }\n        }\n    }\n    fmt.Println(\"stable.\")\n    return true\n}\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":1406}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport \"fmt\"\n\nfunc a(v bool) bool {\n    fmt.Print(\"a\")\n    return v\n}\n\nfunc b(v bool) bool {\n    fmt.Print(\"b\")\n    return v\n}\n\nfunc test(i, j bool) {\n    fmt.Printf(\"Testing a(%t) && b(%t)\\n\", i, j)\n    fmt.Print(\"Trace:  \")\n    fmt.Println(\"\\nResult:\", a(i) && b(j))\n\n    fmt.Printf(\"Testing a(%t) || b(%t)\\n\", i, j)\n    fmt.Print(\"Trace:  \")\n    fmt.Println(\"\\nResult:\", a(i) || b(j))\n\n    fmt.Println(\"\")\n}\n\nfunc main() {\n    test(false, false)\n    test(false, true)\n    test(true, false)\n    test(true, true)\n}\n\n\n","human_summarization":"The code defines two functions, 'a' and 'b', which accept and return the same boolean value and print their name when called. It then calculates and assigns the values of two equations to variables 'x' and 'y', ensuring that function 'b' is only called when necessary, utilizing the short-circuit evaluation feature of boolean expressions. If the language does not support short-circuit evaluation, this is achieved using nested 'if' statements. The short-circuit operators used are '&&' and '||'.","id":1407}
    {"lang_cluster":"Go","source_code":"\n\/\/ Command morse translates an input string into morse code,\n\/\/ showing the output on the console, and playing it as sound.\n\/\/ Only works on ubuntu.\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log\"\n\t\"regexp\"\n\t\"strings\"\n\t\"syscall\"\n\t\"time\"\n\t\"unicode\"\n)\n\n\/\/ A key represents an action on the morse key.\n\/\/ It's either on or off, for the given duration.\ntype key struct {\n\tduration int\n\ton       bool\n\tsym      string \/\/ for debug output\n}\n\nvar (\n\truneToKeys   = map[rune][]key{}\n\tinterCharGap = []key{{1, false, \"\"}}\n\tpunctGap     = []key{{7, false, \" \/ \"}}\n\tcharGap      = []key{{3, false, \" \"}}\n\twordGap      = []key{{7, false, \" \/ \"}}\n)\n\nconst rawMorse = `\nA:.-    J:.---  S:...    1:.----  .:.-.-.- \u00a0::---...\nB:-...  K:-.-   T:-      2:..---  ,:--..-- \u00a0;:-.-.-.\nC:-.-.  L:.-..  U:..-    3:...-- \u00a0?:..--..  =:-...-\nD:-..   M:--    V:...-   4:....-  ':.----.  +:.-.-.\nE:.     N:-.    W:.--    5:..... \u00a0!:-.-.--  -:-....-\nF:..-.  O:---   X:-..-   6:-....  \/:-..-.   _:..--.-\nG:--.   P:.--.  Y:-.--   7:--...  (:-.--.   \":.-..-.\nH:....  Q:--.-  Z:--..   8:---..  ):-.--.-  $:...-..-\nI:..    R:.-.   0:-----  9:----.  &:.-...   @:.--.-.\n`\n\nfunc init() {\n\t\/\/ Convert the rawMorse table into a map of morse key actions.\n\tr := regexp.MustCompile(\"([^ ]):([.-]+)\")\n\tfor _, m := range r.FindAllStringSubmatch(rawMorse, -1) {\n\t\tc := m[1][0]\n\t\tkeys := []key{}\n\t\tfor i, dd := range m[2] {\n\t\t\tif i > 0 {\n\t\t\t\tkeys = append(keys, interCharGap...)\n\t\t\t}\n\t\t\tif dd == '.' {\n\t\t\t\tkeys = append(keys, key{1, true, \".\"})\n\t\t\t} else if dd == '-' {\n\t\t\t\tkeys = append(keys, key{3, true, \"-\"})\n\t\t\t} else {\n\t\t\t\tlog.Fatalf(\"found %c in morse for %c\", dd, c)\n\t\t\t}\n\t\t\truneToKeys[rune(c)] = keys\n\t\t\truneToKeys[unicode.ToLower(rune(c))] = keys\n\t\t}\n\t}\n}\n\n\/\/ MorseKeys translates an input string into a series of keys.\nfunc MorseKeys(in string) ([]key, error) {\n\tafterWord := false\n\tafterChar := false\n\tresult := []key{}\n\tfor _, c := range in {\n\t\tif unicode.IsSpace(c) {\n\t\t\tafterWord = true\n\t\t\tcontinue\n\t\t}\n\t\tmorse, ok := runeToKeys[c]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"can't translate %c to morse\", c)\n\t\t}\n\t\tif unicode.IsPunct(c) && afterChar {\n\t\t\tresult = append(result, punctGap...)\n\t\t} else if afterWord {\n\t\t\tresult = append(result, wordGap...)\n\t\t} else if afterChar {\n\t\t\tresult = append(result, charGap...)\n\t\t}\n\t\tresult = append(result, morse...)\n\t\tafterChar = true\n\t\tafterWord = false\n\t}\n\treturn result, nil\n}\n\nfunc main() {\n\tvar ditDuration time.Duration\n\tflag.DurationVar(&ditDuration, \"d\", 40*time.Millisecond, \"length of dit\")\n\tflag.Parse()\n\tin := \"hello world.\"\n\tif len(flag.Args()) > 1 {\n\t\tin = strings.Join(flag.Args(), \" \")\n\t}\n\tkeys, err := MorseKeys(in)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to translate: %s\", err)\n\t}\n\tfor _, k := range keys {\n\t\tif k.on {\n\t\t\tif err := note(true); err != nil {\n\t\t\t\tlog.Fatalf(\"failed to play note: %s\", err)\n\t\t\t}\n\t\t}\n\t\tfmt.Print(k.sym)\n\t\ttime.Sleep(ditDuration * time.Duration(k.duration))\n\t\tif k.on {\n\t\t\tif err := note(false); err != nil {\n\t\t\t\tlog.Fatalf(\"failed to stop note: %s\", err)\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println()\n}\n\n\/\/ Implement sound on ubuntu. Needs permission to access \/dev\/console.\n\nvar consoleFD uintptr\n\nfunc init() {\n\tfd, err := syscall.Open(\"\/dev\/console\", syscall.O_WRONLY, 0)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to get console device: %s\", err)\n\t}\n\tconsoleFD = uintptr(fd)\n}\n\nconst KIOCSOUND = 0x4B2F\nconst clockTickRate = 1193180\nconst freqHz = 600\n\n\/\/ note either starts or stops a note.\nfunc note(on bool) error {\n\targ := uintptr(0)\n\tif on {\n\t\targ = clockTickRate \/ freqHz\n\t}\n\t_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, consoleFD, KIOCSOUND, arg)\n\tif errno != 0 {\n\t\treturn errno\n\t}\n\treturn nil\n\n}\n\n","human_summarization":"<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":1408}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc newSpeller(blocks string) func(string) bool {\n\tbl := strings.Fields(blocks)\n\treturn func(word string) bool {\n\t\treturn r(word, bl)\n\t}\n}\n\nfunc r(word string, bl []string) bool {\n\tif word == \"\" {\n\t\treturn true\n\t}\n\tc := word[0] | 32\n\tfor i, b := range bl {\n\t\tif c == b[0]|32 || c == b[1]|32 {\n\t\t\tbl[i], bl[0] = bl[0], b\n\t\t\tif r(word[1:], bl[1:]) == true {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tbl[i], bl[0] = bl[0], bl[i]\n\t\t}\n\t}\n\treturn false\n}\n\nfunc main() {\n\tsp := newSpeller(\n\t\t\"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\")\n\tfor _, word := range []string{\n\t\t\"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"CONFUSE\"} {\n\t\tfmt.Println(word, sp(word))\n\t}\n}\n\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":1409}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"crypto\/md5\"\n    \"fmt\"\n)\n\nfunc main() {\n    for _, p := range [][2]string{\n        \/\/ RFC 1321 test cases\n        {\"d41d8cd98f00b204e9800998ecf8427e\", \"\"},\n        {\"0cc175b9c0f1b6a831c399e269772661\", \"a\"},\n        {\"900150983cd24fb0d6963f7d28e17f72\", \"abc\"},\n        {\"f96b697d7cb7938d525a2f31aaf161d0\", \"message digest\"},\n        {\"c3fcd3d76192e4007dfb496cca67e13b\", \"abcdefghijklmnopqrstuvwxyz\"},\n        {\"d174ab98d277d9f5a5611c2c9f419d9f\",\n            \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"},\n        {\"57edf4a22be3c955ac49da2e2107b67a\", \"12345678901234567890\" +\n            \"123456789012345678901234567890123456789012345678901234567890\"},\n        \/\/ test case popular with other RC solutions\n        {\"e38ca1d920c4b8b8d3946b2c72f01680\",\n            \"The quick brown fox jumped over the lazy dog's back\"},\n    } {\n        validate(p[0], p[1])\n    }\n}\n\nvar h = md5.New()\n\nfunc validate(check, s string) {\n    h.Reset()\n    h.Write([]byte(s))\n    sum := fmt.Sprintf(\"%x\", h.Sum(nil))\n    if sum != check {\n        fmt.Println(\"MD5 fail\")\n        fmt.Println(\"  for string,\", s)\n        fmt.Println(\"  expected:  \", check)\n        fmt.Println(\"  got:       \", sum)\n    }\n}\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":1410}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"log\"\n    \"math\/big\"\n    \"sort\"\n    \"strings\"\n)\n\nvar testCases = []string{\n    \"1.3.6.1.4.1.11.2.17.19.3.4.0.10\",\n    \"1.3.6.1.4.1.11.2.17.5.2.0.79\",\n    \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\",\n    \"1.3.6.1.4.1.11150.3.4.0.1\",\n    \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\",\n    \"1.3.6.1.4.1.11150.3.4.0\",\n}\n\n\/\/ a parsed representation\ntype oid []big.Int\n\n\/\/ \"constructor\" parses string representation\nfunc newOid(s string) oid {\n    ns := strings.Split(s, \".\")\n    os := make(oid, len(ns))\n    for i, n := range ns {\n        if _, ok := os[i].SetString(n, 10); !ok || os[i].Sign() < 0 {\n            return nil\n        }\n    }\n    return os\n}\n\n\/\/ \"stringer\" formats into string representation\nfunc (o oid) String() string {\n    s := make([]string, len(o))\n    for i, n := range o {\n        s[i] = n.String()\n    }\n    return strings.Join(s, \".\")\n}\n\nfunc main() {\n    \/\/ parse test cases\n    os := make([]oid, len(testCases))\n    for i, s := range testCases {\n        os[i] = newOid(s)\n        if os[i] == nil {\n            log.Fatal(\"invalid OID\")\n        }\n    }\n    \/\/ sort\n    sort.Slice(os, func(i, j int) bool {\n        \/\/ \"less\" function must return true if os[i] < os[j]\n        oi := os[i]\n        for x, v := range os[j] {\n            \/\/ lexicographic defintion: less if prefix or if element is <\n            if x == len(oi) || oi[x].Cmp(&v) < 0 {\n                return true\n            }\n            if oi[x].Cmp(&v) > 0 {\n                break\n            }\n        }\n        return false\n    })\n    \/\/ output sorted list\n    for _, o := range os {\n        fmt.Println(o)\n    }\n}\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":1411}
    {"lang_cluster":"Go","source_code":"\npackage main\n \nimport (\n    \"fmt\"\n    \"net\"\n)\n \nfunc main() {\n    conn, err := net.Dial(\"tcp\", \"localhost:256\")\n    if err != nil {\n        fmt.Println(err)\n        return\n    }\n    defer conn.Close()\n    _, err = conn.Write([]byte(\"hello socket world\"))\n    if err != nil {\n        fmt.Println(err)\n    }\n}\n\n\nTest with nc:\n$ sudo nc -l 256 & go run sock.go\n[2] 19754\nhello socket world[2]+  Done                    sudo nc -l 256\n$ \n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":1412}
    {"lang_cluster":"Go","source_code":"\n\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\/ioutil\"\n\t\"net\/smtp\"\n\t\"os\"\n\t\"strings\"\n)\n\ntype Message struct {\n\tFrom    string\n\tTo      []string\n\tCc      []string\n\tSubject string\n\tContent string\n}\n\nfunc (m Message) Bytes() (r []byte) {\n\tto := strings.Join(m.To, \",\")\n\tcc := strings.Join(m.Cc, \",\")\n\n\tr = append(r, []byte(\"From: \"+m.From+\"\\n\")...)\n\tr = append(r, []byte(\"To: \"+to+\"\\n\")...)\n\tr = append(r, []byte(\"Cc: \"+cc+\"\\n\")...)\n\tr = append(r, []byte(\"Subject: \"+m.Subject+\"\\n\\n\")...)\n\tr = append(r, []byte(m.Content)...)\n\n\treturn\n}\n\nfunc (m Message) Send(host string, port int, user, pass string) (err error) {\n\terr = check(host, user, pass)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = smtp.SendMail(fmt.Sprintf(\"%v:%v\", host, port),\n\t\tsmtp.PlainAuth(\"\", user, pass, host),\n\t\tm.From,\n\t\tm.To,\n\t\tm.Bytes(),\n\t)\n\n\treturn\n}\n\nfunc check(host, user, pass string) error {\n\tif host == \"\" {\n\t\treturn errors.New(\"Bad host\")\n\t}\n\tif user == \"\" {\n\t\treturn errors.New(\"Bad username\")\n\t}\n\tif pass == \"\" {\n\t\treturn errors.New(\"Bad password\")\n\t}\n\n\treturn nil\n}\n\nfunc main() {\n\tvar flags struct {\n\t\thost string\n\t\tport int\n\t\tuser string\n\t\tpass string\n\t}\n\tflag.StringVar(&flags.host, \"host\", \"\", \"SMTP server to connect to\")\n\tflag.IntVar(&flags.port, \"port\", 587, \"Port to connect to SMTP server on\")\n\tflag.StringVar(&flags.user, \"user\", \"\", \"Username to authenticate with\")\n\tflag.StringVar(&flags.pass, \"pass\", \"\", \"Password to authenticate with\")\n\tflag.Parse()\n\n\terr := check(flags.host, flags.user, flags.pass)\n\tif err != nil {\n\t\tflag.Usage()\n\t\tos.Exit(1)\n\t}\n\n\tbufin := bufio.NewReader(os.Stdin)\n\n\tfmt.Printf(\"From: \")\n\tfrom, err := bufin.ReadString('\\n')\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tfrom = strings.Trim(from, \" \\t\\n\\r\")\n\n\tvar to []string\n\tfor {\n\t\tfmt.Printf(\"To (Blank to finish): \")\n\t\ttmp, err := bufin.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\ttmp = strings.Trim(tmp, \" \\t\\n\\r\")\n\n\t\tif tmp == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tto = append(to, tmp)\n\t}\n\n\tvar cc []string\n\tfor {\n\t\tfmt.Printf(\"Cc (Blank to finish): \")\n\t\ttmp, err := bufin.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\ttmp = strings.Trim(tmp, \" \\t\\n\\r\")\n\n\t\tif tmp == \"\" {\n\t\t\tbreak\n\t\t}\n\n\t\tcc = append(cc, tmp)\n\t}\n\n\tfmt.Printf(\"Subject: \")\n\tsubject, err := bufin.ReadString('\\n')\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tsubject = strings.Trim(subject, \" \\t\\n\\r\")\n\n\tfmt.Printf(\"Content (Until EOF):\\n\")\n\tcontent, err := ioutil.ReadAll(os.Stdin)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tcontent = bytes.Trim(content, \" \\t\\n\\r\")\n\n\tm := Message{\n\t\tFrom:    from,\n\t\tTo:      to,\n\t\tCc:      cc,\n\t\tSubject: subject,\n\t\tContent: string(content),\n\t}\n\n\tfmt.Printf(\"\\nSending message...\\n\")\n\terr = m.Send(flags.host, flags.port, flags.user, flags.pass)\n\tif err != nil {\n\t\tfmt.Printf(\"Error: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tfmt.Printf(\"Message sent.\\n\")\n}\n\n","human_summarization":"\"Implement a function to send an email using SMTP package with TLS connections. The function accepts parameters for From, To, Cc addresses, Subject, message text, server name and login details. The code also handles notifications for success or failure. It is designed to be portable across multiple operating systems.\"","id":1413}
    {"lang_cluster":"Go","source_code":"\npackage main\n\nimport (\n    \"fmt\"\n    \"math\"\n)\n\nfunc main() {\n    for i := int8(0); ; i++ {\n        fmt.Printf(\"%o\\n\", i)\n        if i == math.MaxInt8 {\n            break\n        }\n    }\n}\n\n\n0\n1\n2\n3\n4\n5\n6\n7\n10\n11\n12\n...\n175\n176\n177\n\n\nfunc main() {\n    for i := uint16(0); ; i++ {  \/\/ type specified here\n        fmt.Printf(\"%o\\n\", i)\n        if i == math.MaxUint16 { \/\/ maximum value for type specified here\n            break\n        }\n    }\n}\n\n\n...\n177775\n177776\n177777\n\n\nimport \"fmt\"\n\nfunc main() {\n    for i := 0.; ; {\n        fmt.Printf(\"%o\\n\", int64(i))\n        \/* uncomment to produce example output\n        if i == 3 {\n            i = float64(1<<53 - 4) \/\/ skip to near the end\n            fmt.Println(\"...\")\n        } *\/\n        next := i + 1\n        if next == i {\n            break\n        }\n        i = next\n    }\n}\n\n\n0\n1\n2\n3\n...\n377777777777777775\n377777777777777776\n377777777777777777\n400000000000000000\n\n\nimport (\n    \"big\"\n    \"fmt\"\n)\n\nfunc main() {\n    defer func() {\n        recover()\n    }()\n    one := big.NewInt(1)\n    for i := big.NewInt(0); ; i.Add(i, one) {\n        fmt.Printf(\"%o\\n\", i)\n    }\n}\n\n\n0\n1\n2\n3\n4\n5\n6\n7\n10\n11\n12\n13\n14\n...\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one for each consecutive number. The count continues until the program is terminated or the maximum value of the numeric type in use is reached. The program also handles scenarios where different integer types are used, where floating point types might cause loss of precision, and where memory allocation might fail for big integers.","id":1414}
    {"lang_cluster":"Go","source_code":"\n\na, b = b, a\n\n\npackage main\n\nimport \"fmt\"\n\nfunc swap(a, b *interface{}) {\n    *a, *b = *b, *a\n}\n\nfunc main() {\n    var a, b interface{} = 3, \"four\"\n    fmt.Println(a, b)\n    swap(&a, &b)\n    fmt.Println(a, b)\n}\n\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. This function is applicable in both statically and dynamically typed languages, with certain constraints in case of typed variables. The function does not necessarily support swapping between incompatible types like string and integer. The code also mentions Go's built-in assignment operator that performs a generic swap for variables of identical types. The code also provides a version that allows pointers of any type to be passed, as long as they are of the same type.","id":1415}
    {"lang_cluster":"Go","source_code":"\npackage pal\n\nfunc IsPal(s string) bool {\n    mid := len(s) \/ 2\n    last := len(s) - 1\n    for i := 0; i < mid; i++ {\n        if s[i] != s[last-i] {\n            return false\n        }\n    }\n    return true\n}\n\n\nfunc isPalindrome(s string) bool {\n\trunes := []rune(s)\n\tnumRunes := len(runes) - 1\n\tfor i := 0; i < len(runes)\/2; i++ {\n\t\tif runes[i] != runes[numRunes-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n\nfunc isPalindrome(s string) bool {\n\trunes := []rune(s)\n\tfor len(runes) > 1 {\n\t\tif runes[0] != runes[len(runes)-1] {\n\t\t\treturn false\n\t\t}\n\t\trunes = runes[1 : len(runes)-1]\n\t}\n\treturn true\n}\n\n","human_summarization":"The code is a function that checks if a given sequence of characters or bytes is a palindrome. It supports Unicode characters and also detects inexact palindromes by ignoring white-space, punctuation, and case. It uses string reversal and might be useful for testing a function.","id":1416}
    {"lang_cluster":"Go","source_code":"\nSimply\n\npackage main\n\nimport (\n    \"fmt\"\n    \"os\"\n)\n\nfunc main() {\n    fmt.Println(os.Getenv(\"SHELL\"))\n}\n\n\n","human_summarization":"demonstrate how to retrieve a specific environment variable from the process's environment using the os.Environ library function in a Unix system. The variables that can be accessed include PATH, HOME, and USER.","id":1417}
    {"lang_cluster":"Go","source_code":"package main\n\nimport \"fmt\"\n\nfunc F(n, x, y int) int {\n    if n == 0 {\n        return x + y\n    }\n    if y == 0 {\n        return x\n    }\n    return F(n-1, F(n, x, y-1), F(n, x, y-1)+y)\n}\n\nfunc main() {\n    for n := 0; n < 2; n++ {\n        fmt.Printf(\"Values of F(%d, x, y):\\n\", n)\n        fmt.Println(\"y\/x    0   1   2   3   4   5\")\n        fmt.Println(\"----------------------------\")\n        for y := 0; y < 7; y++ {\n            fmt.Printf(\"%d  |\", y)\n            for x := 0; x < 6; x++ {\n                fmt.Printf(\"%4d\", F(n, x, y))\n            }\n            fmt.Println()\n        }\n        fmt.Println()\n    }\n    fmt.Printf(\"F(2, 1, 1) = %d\\n\", F(2, 1, 1))\n    fmt.Printf(\"F(3, 1, 1) = %d\\n\", F(3, 1, 1))\n    fmt.Printf(\"F(2, 2, 1) = %d\\n\", F(2, 2, 1))\n}\n\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.","id":1418}
    {"lang_cluster":"SAS","source_code":"\n\ndata fib;\n    a=0;\n    b=1;\n    do n=0 to 20;\n       f=a;\n       output;\n       a=b;\n       b=f+a;\n    end;\n    keep n f;\nrun;\n\noptions cmplib=work.f;\n\nproc fcmp outlib=work.f.p;\n    function fib(n);\n    if n = 0 or n = 1\n        then return(1);\n        else return(fib(n - 2) + fib(n - 1));\n    endsub;\nrun;\n\ndata _null_;\n    x = fib(5);\n    put 'fib(5) = ' x;\nrun;\n","human_summarization":"The code defines a function to generate the nth Fibonacci number, either iteratively or recursively. It optionally supports negative n values by inversely applying the Fibonacci sequence's definition. The function also builds a table holding the initial values of the Fibonacci sequence and logs one of the sequence members.","id":1419}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\n   a=\"abracadabra\";\n   b=substr(a,2,3); \/* first number is position, starting at 1,\n                       second number is length *\/\n   put _all_;\nrun;\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":1420}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\nlength a b $11;\na=\"I am Legend\";\nb=reverse(a);\nput a;\nput b;\nrun;\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":1421}
    {"lang_cluster":"SAS","source_code":"\n\n\/* create SAS data set *\/\ndata Edges;\n   input Start $ End $ Cost; \n   datalines;\na  b  7  \na  c  9  \na  f  14  \nb  c  10  \nb  d  15  \nc  d  11  \nc  f  2  \nd  e  6  \ne  f  9  \n;\n\n\/* call OPTMODEL procedure in SAS\/OR *\/\nproc optmodel;\n   \/* declare sets and parameters, and read input data *\/\n   set <str,str> LINKS;\n   num cost {LINKS};\n   read data Edges into LINKS=[start end] cost;\n   set NODES = union {<i,j> in LINKS} {i,j};\n   set SOURCES = {'a'};\n   set SINKS = {'e'};\n   \/* <source,sink,order,from,to> *\/\n   set <str,str,num,str,str> PATHS;\n\n   \/* call network solver *\/\n   solve with network \/\n      shortpath=(source=SOURCES sink=SINKS) links=(weight=cost) out=(sppaths=PATHS);\n\n   \/* write shortest path to SAS data set *\/\n   create data path from [source sink order from to]=PATHS cost[from,to];\nquit;\n\n\/* print shortest path *\/\nproc print data=path;\nrun;\n\n\nObs source sink order from to cost \n1 a e 1 a c 9 \n2 a e 2 c f 2 \n3 a e 3 e f 9 \n\n","human_summarization":"implement Dijkstra's algorithm to find the shortest path from a given source node to all other nodes in a graph. The algorithm takes a directed and weighted graph, represented by an adjacency matrix or list, and a start node as inputs. It outputs a set of edges depicting the shortest path to each reachable node. The code also includes functionality to interpret the output and display the shortest path from the source node to specific nodes.","id":1422}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\ndo while(1);\n   n=floor(uniform(0)*20);\n   put n;\n   if n=10 then leave;    \/* 'leave' to break a loop *\/\nend;\nrun;\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":1423}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\ndo y=2008 to 2121;\n    a=mdy(12,25,y);\n    if weekday(a)=1 then put y;\nend;\nrun;\n\n\/* 2011 2016 2022 2033 2039 2044 2050 2061 2067\n   2072 2078 2089 2095 2101 2107 2112 2118 *\/\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":1424}
    {"lang_cluster":"SAS","source_code":"\n\/* See http:\/\/support.sas.com\/documentation\/cdl\/en\/imlug\/63541\/HTML\/default\/viewer.htm#imlug_langref_sect229.htm *\/\n\nproc iml;\na={12 -51 4,6 167 -68,-4 24 -41};\nprint(a);\ncall qr(q,r,p,d,a);\nprint(q);\nprint(r);\nquit;\n\n\/*\n                  a\n\n           12       -51         4\n            6       167       -68\n           -4        24       -41\n\n\n                  q\n\n    -0.857143 0.3942857 -0.331429\n    -0.428571 -0.902857 0.0342857\n    0.2857143 -0.171429 -0.942857\n\n\n                  r\n\n          -14       -21        14\n            0      -175        70\n            0         0        35\n*\/\n\n","human_summarization":"The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.","id":1425}
    {"lang_cluster":"SAS","source_code":"\noptions mprint mlogic symbolgen source source2;\n\n%macro SubSets (FieldCount = );\ndata _NULL_;\n\tFields = &FieldCount;\n\tSubSets = 2**Fields;\n\tcall symput (\"NumSubSets\", SubSets);\nrun;\n\n%put &NumSubSets;\n\ndata inital;\n\t%do j = 1 %to &FieldCount;\n\t\tF&j. = 1;\n\t%end;\nrun;\n\ndata SubSets;\n\tset inital;\n\tRowCount =_n_;\n\tcall symput(\"SetCount\",RowCount);\nrun;\n\n%put SetCount\u00a0;\n\n%do %while (&SetCount < &NumSubSets);\n\ndata loop;\n\t%do j=1 %to &FieldCount;\n\t\tif rand('GAUSSIAN') > rand('GAUSSIAN') then F&j. = 1;\n\t%end;\n\ndata SubSets_ \u00a0;\nset SubSets loop;\nrun;\n\nproc sort data=SubSets_  nodupkey;\n\tby F1 - F&FieldCount.;\nrun;\n\ndata Subsets;\n\tset SubSets_;\n\tRowCount =_n_;\nrun;\n\nproc sql noprint;\n\tselect max(RowCount) into :SetCount\n\tfrom SubSets;\nquit;\nrun; \n\n%end;\n%Mend SubSets;\n\n%SubSets(FieldCount = 5);\n\n\n","human_summarization":"The code takes a set S as input and generates its power set. The power set includes all possible subsets of S, including the empty set and the set itself. For a set with n elements, the power set will have 2^n elements. The code also demonstrates the ability to handle edge cases such as the power set of an empty set and a set containing only the empty set. The output is a dataset named SUBSETS with 5 columns (F1, F2, F3, F4, F5) and 32 rows, each representing a different combination of 1 and missing values.","id":1426}
    {"lang_cluster":"SAS","source_code":"\n\ndata one;\n   wtpanacea=0.3;    wtichor=0.2;    wtgold=2.0;\n   volpanacea=0.025; volichor=0.015; volgold=0.002;\n   valpanacea=3000;  valichor=1800;  valgold=2500;\n   maxwt=25; maxvol=0.25;\n\n   \/* we can prune the possible selections *\/\n   maxpanacea = floor(min(maxwt\/wtpanacea, maxvol\/volpanacea));\n   maxichor = floor(min(maxwt\/wtichor, maxvol\/volichor));\n   maxgold = floor(min(maxwt\/wtgold, maxvol\/volgold));\n   do i1 = 0 to maxpanacea; \n      do i2 = 0 to maxichor;\n         do i3 = 0 to maxgold;\n            panacea = i1; ichor=i2; gold=i3; output;\n         end;\n      end;\n   end;\nrun;\ndata one; set one;\n   vals = valpanacea*panacea + valichor*ichor + valgold*gold;\n   totalweight = wtpanacea*panacea + wtichor*ichor + wtgold*gold;\n   totalvolume = volpanacea*panacea + volichor*ichor + volgold*gold;\n   if (totalweight le maxwt) and (totalvolume le maxvol);\nrun;\nproc sort data=one;\n   by descending vals;\nrun;\nproc print data=one (obs=4);\n   var panacea ichor gold vals;\nrun;\n\n\n Obs    panacea    ichor    gold     vals\n\n   1       0         15      11     54500\n   2       3         10      11     54500\n   3       6          5      11     54500\n   4       9          0      11     54500\n\n\n\/* create SAS data set *\/\ndata mydata;\n   input Item $1-19 Value weight Volume;\n   datalines;\npanacea (vials of) 3000 0.3 0.025\nichor (ampules of) 1800 0.2 0.015\ngold (bars)        2500 2.0 0.002\n;\n\n\/* call OPTMODEL procedure in SAS\/OR *\/\nproc optmodel;\n   \/* declare sets and parameters, and read input data *\/\n   set <str> ITEMS;\n   num value {ITEMS};\n   num weight {ITEMS};\n   num volume {ITEMS};\n   read data mydata into ITEMS=[item] value weight volume;\n\n   \/* declare variables, objective, and constraints *\/\n   var NumSelected {ITEMS} >= 0 integer;\n   max TotalValue = sum {i in ITEMS} value[i] * NumSelected[i];\n   con WeightCon:\n      sum {i in ITEMS} weight[i] * NumSelected[i] <= 25;\n   con VolumeCon:\n      sum {i in ITEMS} volume[i] * NumSelected[i] <= 0.25;\n\n   \/* call mixed integer linear programming (MILP) solver *\/\n   solve;\n\n   \/* print optimal solution *\/\n   print TotalValue;\n   print NumSelected;\n\n   \/* to get all optimal solutions, call CLP solver instead *\/\n   solve with CLP \/ findallsolns;\n\n   \/* print all optimal solutions *\/\n   print TotalValue;\n   for {s in 1.._NSOL_} print {i in ITEMS} NumSelected[i].sol[s];\nquit;\n\n\nTotalValue \n54500 \n\n[1] NumSelected \ngold (bars) 11 \nichor (ampules of) 0 \npanacea (vials of) 9 \n\n\nTotalValue \n54500 \n\n[1]   \ngold (bars) 11 \nichor (ampules of) 15 \npanacea (vials of) 0 \n\n[1]   \ngold (bars) 11 \nichor (ampules of) 10 \npanacea (vials of) 3 \n\n[1]   \ngold (bars) 11 \nichor (ampules of) 5 \npanacea (vials of) 6 \n\n[1]   \ngold (bars) 11 \nichor (ampules of) 0 \npanacea (vials of) 9 \n","human_summarization":"determine the maximum value of items a traveler can carry away from Shangri La, given the weight and volume constraints of his knapsack and the value, weight, and volume of each item. The code provides one of the four possible solutions to maximize the value taken. It uses a brute force approach and employs SAS\/OR, MILP and CLP solvers.","id":1427}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\nlength a $5;\ndo n=1 to 5;\n  a=\"*\";\n  do i=2 to n;\n    a=trim(a)\u00a0!! \"*\";\n  end;\n  put a;\nend;\nrun;\n\n\/* Possible without the inner loop. Notice TRIM is replaced with STRIP,\notherwise there is a blank space on the left *\/\n\ndata _null_;\nlength a $5;\ndo n=1 to 5;\n  a=strip(a)\u00a0!! \"*\";\n  put a;\nend;\nrun;\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":1428}
    {"lang_cluster":"SAS","source_code":"\n\/* Generate 1000 random numbers with mean 1 and standard deviation 0.5. \n  SAS version 9.2 was used to create this code.*\/\n\ndata norm1000;\n  call streaminit(123456); \n\/* Set the starting point, so we can replicate results. \n   If you want different results each time, comment the above line. *\/\n  do i=1 to 1000;\n    r=rand('normal',1,0.5);\n    output;\n  end;\nrun;\n\n\n The MEANS Procedure\n\n                     Analysis Variable\u00a0: r\n\n                          Mean         Std Dev\n                  ----------------------------\n                     0.9907408       0.4844051\n                  ----------------------------\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using libraries that generate uniformly distributed random numbers. It also includes a related task for calculating the standard deviation.","id":1429}
    {"lang_cluster":"SAS","source_code":"\n\n%let string=She was a soul stripper. She took my heart!;\n%let chars=aei;\n%let stripped=%sysfunc(compress(\"&string\",\"&chars\"));\n%put &stripped;\n\n\nSh ws  soul strppr. Sh took my hrt!\n\n","human_summarization":"\"Function to strip a given set of characters from a specified string.\"","id":1430}
    {"lang_cluster":"SAS","source_code":"\n  %let datefmt=E8601DA10.;\n  data patient;\n      infile \"patient.csv\" dsd dlm=',';\n      attrib\n          id length=4\n          lastname length=$10; \n      input id lastname;\n  data visit;\n      infile \"visit.csv\" dsd dlm=',';\n      attrib\n          id length=4\n          date informat=&datefmt format=&datefmt\n          score length=8; \n      input id date score;\n  proc sql;\n      select * from \n          (select id, max(date) format=&datefmt as max_date, sum(score) as sum_score,\n          \tavg(score) as avg_score from visit group by id)\n          natural right join patient\n          order by id;\n\n\n","human_summarization":"\"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file.\"","id":1431}
    {"lang_cluster":"SAS","source_code":"\noptions minoperator;\n\n%macro haver(lat1, long1, lat2, long2, type=D, dist=K);\n\n\t%if %upcase(&type) in (D DEG DEGREE DEGREES) %then %do;\n\t\t%let convert = constant('PI')\/180;\n\t\t%end;\n\t%else %if %upcase(&type) in (R RAD RADIAN RADIANS) %then %do;\n\t\t%let convert = 1;\n\t\t%end;\n\t%else %do;\n\t\t%put ERROR - Enter RADIANS or DEGREES for type.;\n\t\t%goto exit;\n\t\t%end;\n\n\t%if %upcase(&dist) in (M MILE MILES) %then %do;\n\t\t%let distrat = 1.609344;\n\t\t%end;\n\t%else %if %upcase(&dist) in (K KM KILOMETER KILOMETERS) %then %do;\n\t\t%let distrat = 1;\n\t\t%end;\n\t%else %do;\n\t\t%put ERROR - Enter M on KM for dist;\n\t\t%goto exit;\n\t\t%end;\n\t\t\n\t\tdata _null_;\n\t\t\tconvert = &convert;\n\t\t\tlat1 = &lat1 * convert;\n\t\t\tlat2 = &lat2 * convert;\n\t\t\tlong1 = &long1 * convert;\n\t\t\tlong2 = &long2 * convert;\n\n\t\t\tdiff1 = lat2 - lat1;\n\t\t\tdiff2 = long2 - long1;\n\n\t\t\tpart1 = sin(diff1\/2)**2;\n\t\t\tpart2 = cos(lat1)*cos(lat2);\n\t\t\tpart3 = sin(diff2\/2)**2;\n\n\t\t\troot = sqrt(part1 + part2*part3);\n\n\t\t\tdist = 2 * 6372.8 \/ &distrat * arsin(root);\n\n\t\t\tput \"Distance is \" dist \"%upcase(&dist)\";\n\t\trun;\n\n\t%exit:\n%mend;\n\n%haver(36.12, -86.67, 33.94, -118.40);\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":1432}
    {"lang_cluster":"SAS","source_code":"\n\/* using DO UNTIL so that the loop executes at least once *\/\ndata _null_;\nn=0;\ndo until(mod(n,6)=0);\n    n+1;\n    put n;\nend;\nrun;\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":1433}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\n   a=\"Hello, World!\";\n   b=length(c);\n   put _all_;\nrun;\n","human_summarization":"calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.","id":1434}
    {"lang_cluster":"SAS","source_code":"\n\n\/* define SAS data set *\/\ndata Indata;\n   input C1-C9;\n   datalines;\n. . 5 . . 7 . . 1\n. 7 . . 9 . . 3 .\n. . . 6 . . . . .\n. . 3 . . 1 . . 5\n. 9 . . 8 . . 2 .\n1 . . 2 . . 4 . .\n. . 2 . . 6 . . 9\n. . . . 4 . . 8 .\n8 . . 1 . . 5 . .\n;\n\n\/* call OPTMODEL procedure in SAS\/OR *\/\nproc optmodel;\n   \/* declare variables *\/\n   set ROWS = 1..9;\n   set COLS = ROWS;\n   var X {ROWS, COLS} >= 1 <= 9 integer;\n\n   \/* declare nine row constraints *\/\n   con RowCon {i in ROWS}:\n      alldiff({j in COLS} X[i,j]);\n\n   \/* declare nine column constraints *\/\n   con ColCon {j in COLS}:\n      alldiff({i in ROWS} X[i,j]);\n\n   \/* declare nine 3x3 block constraints *\/\n   con BlockCon {s in 0..2, t in 0..2}:\n      alldiff({i in 3*s+1..3*s+3, j in 3*t+1..3*t+3} X[i,j]);\n\n   \/* fix variables to cell values *\/\n   \/* X[i,j] = c[i,j] if c[i,j] is not missing *\/\n   num c {ROWS, COLS};\n   read data indata into [_N_] {j in COLS} <c[_N_,j]=col('C'||j)>;\n   for {i in ROWS, j in COLS: c[i,j] ne .}\n      fix X[i,j] = c[i,j];\n\n   \/* call CLP solver *\/\n   solve;\n\n   \/* print solution *\/\n   print X;\nquit;\n\n\nX \n  1 2 3 4 5 6 7 8 9 \n1 9 8 5 3 2 7 6 4 1 \n2 6 7 1 5 9 4 2 3 8 \n3 3 2 4 6 1 8 9 5 7 \n4 2 4 3 7 6 1 8 9 5 \n5 5 9 7 4 8 3 1 2 6 \n6 1 6 8 2 5 9 4 7 3 \n7 4 5 2 8 3 6 7 1 9 \n8 7 1 6 9 4 5 3 8 2 \n9 8 3 9 1 7 2 5 6 4 \n\n","human_summarization":"\"Code implements a Sudoku solver for a partially filled 9x9 grid, displaying the results in a human-readable format using a CLP solver in SAS\/OR. It references the Algorithmics of Sudoku and a Python Sudoku Solver Computerphile video.\"","id":1435}
    {"lang_cluster":"SAS","source_code":"\n\/* Initialize an array with integers 1 to 10, and print their sum *\/\ndata _null_;\narray a a1-a10;\nn=1;\ndo over a;\n  a=n;\n  n=n+1;\nend;\ns=sum(of a{*});\nput s;\nrun;\n","human_summarization":"Iterates through each element in a collection in order and prints it, using a \"for each\" loop or another loop if \"for each\" is not available in the language.","id":1436}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\npi = 4*atan(1);\ndeg = 30;\nrad = pi\/6;\nk = pi\/180;\nx = 0.2;\n\na = sin(rad);\nb = sin(deg*k);\nput a b;\n\na = cos(rad);\nb = cos(deg*k);\nput a b;\n\na = tan(rad);\nb = tan(deg*k);\nput a b;\n\na=arsin(x);\nb=arsin(x)\/k;\nput a b;\n\na=arcos(x);\nb=arcos(x)\/k;\nput a b;\n\na=atan(x);\nb=atan(x)\/k;\nput a b;\nrun;\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":1437}
    {"lang_cluster":"SAS","source_code":"\n\n\/* create SAS data set *\/\ndata mydata;\n   input item $1-23 weight value pieces;\n   datalines;\nmap                      9  150  1  \ncompass                 13   35  1  \nwater                  153  200  2  \nsandwich                50   60  2  \nglucose                 15   60  2  \ntin                     68   45  3  \nbanana                  27   60  3  \napple                   39   40  3  \ncheese                  23   30  1  \nbeer                    52   10  3  \nsuntan cream            11   70  1  \ncamera                  32   30  1  \nT-shirt                 24   15  2  \ntrousers                48   10  2  \numbrella                73   40  1  \nwaterproof trousers     42   70  1  \nwaterproof overclothes  43   75  1  \nnote-case               22   80  1  \nsunglasses               7   20  1  \ntowel                   18   12  2  \nsocks                    4   50  1  \nbook                    30   10  2  \n;\n\n\/* call OPTMODEL procedure in SAS\/OR *\/\nproc optmodel;\n   \/* declare sets and parameters, and read input data *\/\n   set <str> ITEMS;\n   num weight {ITEMS};\n   num value {ITEMS};\n   num pieces {ITEMS};\n   read data mydata into ITEMS=[item] weight value pieces;\n\n   \/* declare variables, objective, and constraints *\/\n   var NumSelected {i in ITEMS} >= 0 <= pieces[i] integer;\n   max TotalValue = sum {i in ITEMS} value[i] * NumSelected[i];\n   con WeightCon:\n      sum {i in ITEMS} weight[i] * NumSelected[i] <= 400;\n\n   \/* call mixed integer linear programming (MILP) solver *\/\n   solve;\n\n   \/* print optimal solution *\/\n   print TotalValue;\n   print {i in ITEMS: NumSelected[i].sol > 0.5} NumSelected;\nquit;\n\n\nTotalValue \n1010 \n\n[1] NumSelected \nbanana 3 \ncheese 1 \ncompass 1 \nglucose 2 \nmap 1 \nnote-case 1 \nsocks 1 \nsunglasses 1 \nsuntan cream 1 \nwater 1 \nwaterproof overclothes 1 \n\n","human_summarization":"determine the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. The items, their weights, values, and quantities are listed in a table. The goal is to maximize the total value of the items in the knapsack without exceeding the weight limit. The solution is obtained using the MILP solver in SAS\/OR.","id":1438}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\n  do i=1 to 100;\n    if mod(i,15)=0 then put \"FizzBuzz\";\n    else if mod(i,5)=0 then put \"Buzz\";\n    else if mod(i,3)=0 then put \"Fizz\";\n    else put i;\n  end;\nrun;\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":1439}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\n   array a{*} a1-a100;\n   do i=1 to 100;\n      a{i}=i*i;\n   end;\n   b=sum(of a{*});\n   put b c;\nrun;\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":1440}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\n   a=\"Hello,\";\n   b=\"World!\";\n   c=a\u00a0!! \" \"\u00a0!! b;\n   put c;\n   *Alternative using the catx function;\n   c=catx (\" \", a, b);\n   put c;\nrun;\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":1441}
    {"lang_cluster":"SAS","source_code":"\n\n\/* create SAS data set *\/\ndata mydata;\n   input item $ weight value;\n   datalines;\nbeef    3.8  36  \npork    5.4  43  \nham     3.6  90  \ngreaves 2.4  45  \nflitch  4.0  30  \nbrawn   2.5  56  \nwelt    3.7  67  \nsalami  3.0  95  \nsausage 5.9  98  \n;\n\n\/* call OPTMODEL procedure in SAS\/OR *\/\nproc optmodel;\n   \/* declare sets and parameters, and read input data *\/\n   set <str> ITEMS;\n   num weight {ITEMS};\n   num value {ITEMS};\n   read data mydata into ITEMS=[item] weight value;\n\n   \/* declare variables, objective, and constraints *\/\n   var WeightSelected {i in ITEMS} >= 0 <= weight[i];\n   max TotalValue = sum {i in ITEMS} (value[i]\/weight[i]) * WeightSelected[i];\n   con WeightCon:\n      sum {i in ITEMS} WeightSelected[i] <= 15;\n\n   \/* call linear programming (LP) solver *\/\n   solve;\n\n   \/* print optimal solution *\/\n   print TotalValue;\n   print {i in ITEMS: WeightSelected[i].sol > 1e-3} WeightSelected;\nquit;\n\n\nTotalValue \n349.38 \n\n[1] WeightSelected \nbrawn 2.5 \ngreaves 2.4 \nham 3.6 \nsalami 3.0 \nwelt 3.5 \n","human_summarization":"determine the optimal combination of items a thief can carry in his knapsack, given a maximum weight capacity of 15 kg. The items can be cut, with their price reducing proportionally to their weight. The goal is to maximize the total value of the items in the knapsack. The solution uses a Linear Programming solver in SAS\/OR.","id":1442}
    {"lang_cluster":"SAS","source_code":"\nPROC SQL;\nCREATE TABLE ADDRESS \n(\nADDRID CHAR(8)\n,STREET CHAR(50) \n,CITY CHAR(25)\n,STATE CHAR(2)\n,ZIP  CHAR(20)\n) \n;QUIT;\n\n","human_summarization":"create a table in a database to store US postal addresses, including fields for a unique identifier, street address, city, state code, and zipcode. The codes also demonstrate how to establish a database connection in non-database languages.","id":1443}
    {"lang_cluster":"SAS","source_code":"\ndata _null_;\ndo i=1 to 10 by 2;\nput i;\nend;\nrun;\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":1444}
    {"lang_cluster":"SAS","source_code":"\n\/* Store all 92 permutations in a SAS dataset. Translation of Fortran 77 *\/\ndata queens;\narray a{8} p1-p8;\narray s{8};\narray u{30};\nn=8;\ndo i=1 to n;\na(i)=i;\nend;\ndo i=1 to 4*n-2;\nu(i)=0;\nend;\nm=0;\ni=1;\nr=2*n-1;\ngoto L40;\nL30:\ns(i)=j;\nu(p)=1;\nu(q+r)=1;\ni=i+1;\nL40:\nif i>n then goto L80;\nj=i;\nL50:\nz=a(i);\ny=a(j);\np=i-y+n;\nq=i+y-1;\na(i)=y;\na(j)=z;\nif u(p)=0 and u(q+r)=0 then goto L30;\nL60:\nj=j+1;\nif j<=n then goto L50;\nL70:\nj=j-1;\nif j=i then goto L90;\nz=a(i);\na(i)=a(j);\na(j)=z;\ngoto L70;\nL80:\nm=m+1;\noutput;\nL90:\ni=i-1;\nif i=0 then goto L100;\np=i-a(i)+n;\nq=i+a(i)-1;\nj=s(i);\nu(p)=0;\nu(q+r)=0;\ngoto L60;\nL100:\nput n m;\nkeep p1-p8;\nrun;\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":1445}
    {"lang_cluster":"SAS","source_code":"\n\n\/* create SAS data set *\/\ndata mydata;\n   input item $1-23 weight value;\n   datalines;\nmap                      9  150\ncompass                 13   35\nwater                  153  200\nsandwich                50  160\nglucose                 15   60\ntin                     68   45\nbanana                  27   60\napple                   39   40\ncheese                  23   30\nbeer                    52   10\nsuntan cream            11   70\ncamera                  32   30\nT-shirt                 24   15\ntrousers                48   10\numbrella                73   40\nwaterproof trousers     42   70\nwaterproof overclothes  43   75\nnote-case               22   80\nsunglasses               7   20\ntowel                   18   12\nsocks                    4   50\nbook                    30   10\n;\n\n\/* call OPTMODEL procedure in SAS\/OR *\/\nproc optmodel;\n   \/* declare sets and parameters, and read input data *\/\n   set <str> ITEMS;\n   num weight {ITEMS};\n   num value {ITEMS};\n   read data mydata into ITEMS=[item] weight value;\n\n   \/* declare variables, objective, and constraints *\/\n   var NumSelected {ITEMS} binary;\n   max TotalValue = sum {i in ITEMS} value[i] * NumSelected[i];\n   con WeightCon:\n      sum {i in ITEMS} weight[i] * NumSelected[i] <= 400;\n\n   \/* call mixed integer linear programming (MILP) solver *\/\n   solve;\n\n   \/* print optimal solution *\/\n   print TotalValue;\n   print {i in ITEMS: NumSelected[i].sol > 0.5} NumSelected;\nquit;\n\n\nTotalValue \n1030 \n\n[1] NumSelected \nbanana 1 \ncompass 1 \nglucose 1 \nmap 1 \nnote-case 1 \nsandwich 1 \nsocks 1 \nsunglasses 1 \nsuntan cream 1 \nwater 1 \nwaterproof overclothes 1 \nwaterproof trousers 1 \n\n","human_summarization":"determine the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg, to maximize the total value of the items. The solution uses a MILP solver in SAS\/OR.","id":1446}
    {"lang_cluster":"SAS","source_code":"\nfilename msg email\n   to=\"afriend@someserver.com\"\n   cc=\"anotherfriend@somecompany.com\"\n   subject=\"Important message\"\n;\n\ndata _null_;\n   file msg;\n   put \"Hello, Connected World!\";\nrun;\n\n","human_summarization":"Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.","id":1447}
    {"lang_cluster":"SAS","source_code":"\n\nThe macro \"palindro\" has two parameters: string and ignorewhitespace.\n  string is the expression to be checked.\n  ignorewhitespace, (Y\/N), determines whether or not to ignore blanks and punctuation.\nThis macro was written in SAS 9.2.  If you use a version before SAS 9.1.3, \nthe compress function options will not work.\n\n \n%MACRO palindro(string, ignorewhitespace);\n  DATA _NULL_;\n    %IF %UPCASE(&ignorewhitespace)=Y %THEN %DO;\n\/* The arguments of COMPRESS (sp) ignore blanks and puncutation *\/\n\/* We take the string and record it in reverse order using the REVERSE function. *\/\n      %LET rev=%SYSFUNC(REVERSE(%SYSFUNC(COMPRESS(&string,,sp)))); \n      %LET string=%SYSFUNC(COMPRESS(&string.,,sp));\n    %END;\n\n    %ELSE %DO;\n      %LET rev=%SYSFUNC(REVERSE(&string));\n    %END;\n    \/*%PUT rev=&rev.;*\/\n    \/*%PUT string=&string.;*\/\n\n\/* Here we determine if the string and its reverse are the same. *\/\n    %IF %UPCASE(&string)=%UPCASE(&rev.) %THEN %DO;\n      %PUT TRUE;\n    %END;\n    %ELSE %DO;\n      %PUT FALSE; \n    %END;\n  RUN;\n%MEND;\n\n%palindro(\"a man, a plan, a canal: panama\",y);\n\nTRUE\n\nNOTE: DATA statement used (Total process time):\n      real time           0.00 seconds\n      cpu time            0.00 seconds\n\n%palindro(\"a man, a plan, a canal: panama\",n);\n\nFALSE\n\nNOTE: DATA statement used (Total process time):\n      real time           0.00 seconds\n      cpu time            0.00 seconds\n","human_summarization":"The code is a program or function that checks if a given sequence of characters or bytes is a palindrome. It supports Unicode characters and also has a feature to detect inexact palindromes by ignoring white-space, punctuation, and case-insensitive comparison. The code may also include a function to reverse a string.","id":1448}
    {"lang_cluster":"R","source_code":"\nLibrary: proto\n\nlibrary(proto)\n\nstack <- proto(expr = {\n   l <- list()\n   empty <- function(.) length(.$l) == 0\n   push <- function(., x) \n   {\n      .$l <- c(list(x), .$l)\n      print(.$l)\n      invisible()\n   }\n   pop <- function(.) \n   {\n      if(.$empty()) stop(\"can't pop from an empty list\")\n      .$l[[1]] <- NULL\n      print(.$l)\n      invisible()\n   }\n})\n\nstack$empty()\n# [1] TRUE\nstack$push(3)\n# [[1]]\n# [1] 3\nstack$push(\"abc\")\n# [[1]]\n# [1] \"abc\"\n# [[2]]\n# [1] 3\nstack$push(matrix(1:6, nrow=2))\n# [[1]]\n#      [,1] [,2] [,3]\n# [1,]    1    3    5\n# [2,]    2    4    6\n# [[2]]\n# [1] \"abc\"\n# [[3]]\n# [1] 3\nstack$empty()\n# [1] FALSE\nstack$pop()\n# [[1]]\n[1] \"abc\"\n# [[2]]\n# [1] 3\nstack$pop()\n# [[1]]\n# [1] 3\nstack$pop()\n# list()\nstack$pop()\n# Error in get(\"pop\", env = stack, inherits = TRUE)(stack, ...)\u00a0: \n#   can't pop from an empty list\n","human_summarization":"implement a stack data structure with last in, first out (LIFO) access policy. The stack supports basic operations such as push (adding a new element to the top of the stack), pop (removing and returning the last pushed element from the stack), and empty (checking if the stack contains no elements). The topmost element can be accessed without modifying the stack.","id":1449}
    {"lang_cluster":"R","source_code":"\nfib=function(n,x=c(0,1)) {\n   if (abs(n)>1) for (i in seq(abs(n)-1)) x=c(x[2],sum(x))\n   if (n<0) return(x[2]*(-1)^(abs(n)-1)) else if (n) return(x[2]) else return(0)\n}  \n\nsapply(seq(-31,31),fib)\n\n [1] 1346269 -832040  514229 -317811  196418 -121393   75025  -46368   28657\n[10]  -17711   10946   -6765    4181   -2584    1597    -987     610    -377\n[19]     233    -144      89     -55      34     -21      13      -8       5\n[28]      -3       2      -1       1       0       1       1       2       3\n[37]       5       8      13      21      34      55      89     144     233\n[46]     377     610     987    1597    2584    4181    6765   10946   17711\n[55]   28657   46368   75025  121393  196418  317811  514229  832040 1346269\n\n# recursive\nrecfibo <- function(n) {\n  if ( n < 2 ) n\n  else Recall(n-1) + Recall(n-2)\n}\n\n# print the first 21 elements\nprint.table(lapply(0:20, recfibo))\n\n# iterative\niterfibo <- function(n) {\n  if ( n < 2 )\n    n\n  else {\n    f <- c(0, 1)\n    for (i in 2:n) {\n      t <- f[2]\n      f[2] <- sum(f)\n      f[1] <- t\n    }\n    f[2]\n  }\n}\n\nprint.table(lapply(0:20, iterfibo))\n\n# iterative but looping replaced by map-reduce'ing\nfuncfibo <- function(n) {\n  if (n < 2) \n    n\n  else {\n    generator <- function(f, ...) {\n      c(f[2], sum(f))\n    }\n    Reduce(generator, 2:n, c(0,1))[2]\n  }\n}\n\nprint.table(lapply(0:20, funcfibo))\n\n\n","human_summarization":"\"Function to generate the nth Fibonacci number, supporting both positive and negative values of n. The function can be implemented either iteratively or recursively. The function also includes an option to call compiled C code for basic arithmetic operations in R.\"","id":1450}
    {"lang_cluster":"R","source_code":"\na <- 1:100\nevennums <- a[ a%%2 == 0 ]\nprint(evennums)\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":1451}
    {"lang_cluster":"R","source_code":"\ns <- \"abcdefgh\"\nn <- 2; m <- 2; char <- 'd'; chars <- 'cd'\nsubstring(s, n, n + m)\nsubstring(s, n)\nsubstring(s, 1, nchar(s)-1)\nindx <- which(strsplit(s, '')[[1]] %in% strsplit(char, '')[[1]])\nsubstring(s, indx, indx + m)\nindx <- which(strsplit(s, '')[[1]] %in% strsplit(chars, '')[[1]])[1]\nsubstring(s, indx, indx + m)\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":1452}
    {"lang_cluster":"R","source_code":"\nWorks with: R version 2.8.1\n\nrevstring <- function(stringtorev) {\n   return(\n      paste(\n           strsplit(stringtorev,\"\")[[1]][nchar(stringtorev):1]\n           ,collapse=\"\")\n           )\n}\n\n revstring <- function(s) paste(rev(strsplit(s,\"\")[[1]]),collapse=\"\")\nrevstring(\"asdf\")\nrevstring(\"m\\u00f8\\u00f8se\")\nEncoding(\"m\\u00f8\\u00f8se\")   # just to check if on your system it's something\n                              # different!\n\n","human_summarization":"\"Reverses a given string, preserving Unicode combining characters and working with UTF-8 encoded strings. The code can also handle strings encoded in Latin1 and UTF-8, with the ability to force encoding or translate between encodings when possible.\"","id":1453}
    {"lang_cluster":"R","source_code":"\nWorks with: R version 2.8.1\nsample0to19 <- function() sample(0L:19L, 1,replace=TRUE)\nrepeat\n{\n  result1 <- sample0to19()\n  if (result1 == 10L)\n  {\n    print(result1)\n    break\n  }\n  result2 <- sample0to19()\n  cat(result1, result2, \"\\n\")\n}\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":1454}
    {"lang_cluster":"R","source_code":"\nLibrary: XML (R)\nlibrary(\"XML\")\ndoc <- xmlInternalTreeParse(\"test3.xml\")\n\n# Retrieve the first \"item\" element\ngetNodeSet(doc, \"\/\/item\")[[1]]\n\n# Perform an action on each \"price\" element\nsapply(getNodeSet(doc, \"\/\/price\"), xmlValue)\n\n# Get an array of all the \"name\" elements\nsapply(getNodeSet(doc, \"\/\/name\"), xmlValue)\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":1455}
    {"lang_cluster":"R","source_code":"\nyears <- 2008:2121\nxmas <- as.POSIXlt(paste0(years, '\/12\/25'))\nyears[xmas$wday==0]\n# 2011 2016 2022 2033 2039 2044 2050 2061 2067 2072 2078 2089 2095 2101 2107 2112 2118\n\n# Also:\nxmas=seq(as.Date(\"2008\/12\/25\"), as.Date(\"2121\/12\/25\"), by=\"year\")\nas.numeric(format(xmas[weekdays(xmas)== 'Sunday'], \"%Y\"))\n\n# Still another solution, using ISOdate and weekdays\nwith(list(years=2008:2121), years[weekdays(ISOdate(years, 12, 25)) == \"Sunday\"])\n\n# Or with \"subset\"\nsubset(data.frame(years=2008:2121), weekdays(ISOdate(years, 12, 25)) == \"Sunday\")$years\n\n# Simply replace \"Sunday\" with whatever it's named in your country,\n# or set locale first, with\nSys.setlocale(cat=\"LC_ALL\", \"en\")\n\n# Under MS Windows, write instead\nSys.setlocale(\"LC_ALL\", \"English\")\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":1456}
    {"lang_cluster":"R","source_code":"\n# R has QR decomposition built-in (using LAPACK or LINPACK)\n\na <- matrix(c(12, -51, 4, 6, 167, -68, -4, 24, -41), nrow=3, ncol=3, byrow=T)\nd <- qr(a)\nqr.Q(d)\nqr.R(d)\n\n# now fitting a polynomial\nx <- 0:10\ny <- 3*x^2 + 2*x + 1\n\n# using QR decomposition directly\na <- cbind(1, x, x^2)\nqr.coef(qr(a), y)\n\n# using least squares\na <- cbind(x, x^2)\nlsfit(a, y)$coefficients\n\n# using a linear model\nxx <- x*x\nm <- lm(y ~ x + xx)\ncoef(m)\n\n","human_summarization":"The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.","id":1457}
    {"lang_cluster":"R","source_code":"\nitems <- c(1,2,3,2,4,3,2)\nunique (items)\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":1458}
    {"lang_cluster":"R","source_code":"qsort <- function(v) {\n  if ( length(v) > 1 ) \n  {\n    pivot <- (min(v) + max(v))\/2.0                            # Could also use pivot <- median(v)\n    c(qsort(v[v < pivot]), v[v == pivot], qsort(v[v > pivot])) \n  } else v\n}\n\nN <- 100\nvs <- runif(N)\nsystem.time(u <- qsort(vs))\nprint(u)\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":1459}
    {"lang_cluster":"R","source_code":"\n\nnow <- Sys.time()\nstrftime(now, \"%Y-%m-%d\")\nstrftime(now, \"%A, %B %d, %Y\")\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\" using strftime function.","id":1460}
    {"lang_cluster":"R","source_code":"\n\nfor each element in the set:\n\tfor each subset constructed so far:\n\t\tnew subset = (subset + element)\n\npowerset <- function(set){\n\tps <- list()\n\tps[[1]] <- numeric()\t\t\t\t\t\t#Start with the empty set.\n\tfor(element in set){\t\t\t\t\t\t#For each element in the set, take all subsets\n\t\ttemp <- vector(mode=\"list\",length=length(ps))\t\t#currently in \"ps\" and create new subsets (in \"temp\")\n\t\tfor(subset in 1:length(ps)){\t\t\t\t#by adding \"element\" to each of them.\n\t\t\ttemp[[subset]] = c(ps[[subset]],element)\n\t\t}\n\t\tps <- c(ps,temp)\t\t\t\t\t\t#Add the additional subsets (\"temp\") to \"ps\".\n\t}\n\tps\n}\n\npowerset(1:4)\n\nLibrary: sets\n\nlibrary(sets)\n\nv <- (1:3)^2\nsv <- as.set(v)\n2^sv\n{{}, {1}, {4}, {9}, {1, 4}, {1, 9}, {4, 9}, {1, 4, 9}}\n\n\nl <- list(a=1, b=\"qwerty\", c=list(d=TRUE, e=1:3))\nsl <- as.set(l)\n2^sl\n{{}, {1}, {\"qwerty\"}, {<<list(2)>>}, {1, <<list(2)>>}, {\"qwerty\",\n 1}, {\"qwerty\", <<list(2)>>}, {\"qwerty\", 1, <<list(2)>>}}\n\n","human_summarization":"The code defines a function that takes a set as input and returns the power set of the input set. The power set is the set of all subsets of the input set, including the empty set and the set itself. The function uses an associative array for set implementation and employs a non-recursive method for speed optimization. The function also handles edge cases like power set of an empty set and a set containing only the empty set.","id":1461}
    {"lang_cluster":"R","source_code":"\n\nas.roman(1666)   # MDCLXVI\n\nas.roman(1666) + 334   # MM\n","human_summarization":"The function takes a positive integer as input and returns its Roman numeral representation as a string. It breaks down the integer into its constituent digits and converts each digit into its corresponding Roman numeral, starting from the leftmost digit and skipping any zeros. The function also allows for arithmetic operations with Roman numerals.","id":1462}
    {"lang_cluster":"R","source_code":"\n\narr <- array(1)\n\narr <- append(arr,3)\n\narr[1] <- 2\n\nprint(arr[1])\n","human_summarization":"demonstrate the basic syntax of arrays in the given language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, as well as the process of pushing a value into the array.","id":1463}
    {"lang_cluster":"R","source_code":"\n\nsrc <- file(\"input.txt\", \"r\")\ndest <- file(\"output.txt\", \"w\")\n\nfc <- readLines(src, -1)\nwriteLines(fc, dest)\nclose(src); close(dest)\n\nsrc <- file(\"input.txt\", \"rb\")\ndest <- file(\"output.txt\", \"wb\")\n\nwhile( length(v <- readBin(src, \"raw\")) > 0 ) {\n  writeBin(v, dest) \n}\nclose(src); close(dest)\n\nfile.copy(\"input.txt\", \"output.txt\", overwrite = FALSE)\n","human_summarization":"demonstrate how to read the contents of an \"input.txt\" file into an intermediate variable and then write this variable's contents into a new file called \"output.txt\". It also shows alternative methods for copying file contents, such as using readLines for textual files or file.copy for non-textual files.","id":1464}
    {"lang_cluster":"R","source_code":"\n str <- \"alphaBETA\"\n toupper(str)\n tolower(str)\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":1465}
    {"lang_cluster":"R","source_code":"\nWorks with: R version 2.8.1+\n\nclosest_pair_brute <-function(x,y,plotxy=F) { \n    xy = cbind(x,y)\n    cp = bruteforce(xy)\n    cat(\"\\n\\nShortest path found = \\n From:\\t\\t(\",cp[1],',',cp[2],\")\\n To:\\t\\t(\",cp[3],',',cp[4],\")\\n Distance:\\t\",cp[5],\"\\n\\n\",sep=\"\")\n    if(plotxy) {\n        plot(x,y,pch=19,col='black',main=\"Closest Pair\", asp=1)\n        points(cp[1],cp[2],pch=19,col='red')\n        points(cp[3],cp[4],pch=19,col='red')\n    }\n    distance <- function(p1,p2) {\n        x1 = (p1[1])\n        y1 = (p1[2]) \n        x2 = (p2[1])\n        y2 = (p2[2]) \n        sqrt((x2-x1)^2 + (y2-y1)^2)\n    }\n    bf_iter <- function(m,p,idx=NA,d=NA,n=1) {\n        dd = distance(p,m[n,])\n        if((is.na(d) || dd<=d) && p!=m[n,]){d = dd; idx=n;}\n        if(n == length(m[,1])) { c(m[idx,],d) }\n        else bf_iter(m,p,idx,d,n+1)\n    }\n    bruteforce <- function(pmatrix,n=1,pd=c(NA,NA,NA,NA,NA)) {\n        p = pmatrix[n,]\n        ppd = c(p,bf_iter(pmatrix,p))\n        if(ppd[5]<pd[5] || is.na(pd[5])) pd = ppd\n        if(n==length(pmatrix[,1]))  pd \n        else bruteforce(pmatrix,n+1,pd)\n    }\n}\n\n\nclosestPair<-function(x,y)\n  {\n  distancev <- function(pointsv)\n    {\n    x1 <- pointsv[1]\n    y1 <- pointsv[2]\n    x2 <- pointsv[3]\n    y2 <- pointsv[4]\n    sqrt((x1 - x2)^2 + (y1 - y2)^2)\n    }\n  pairstocompare <- t(combn(length(x),2))\n  pointsv <- cbind(x[pairstocompare[,1]],y[pairstocompare[,1]],x[pairstocompare[,2]],y[pairstocompare[,2]])\n  pairstocompare <- cbind(pairstocompare,apply(pointsv,1,distancev))\n  minrow <- pairstocompare[pairstocompare[,3] == min(pairstocompare[,3])]\n  if (!is.null(nrow(minrow))) {print(\"More than one point at this distance!\"); minrow <- minrow[1,]}\n  cat(\"The closest pair is:\\n\\tPoint 1: \",x[minrow[1]],\", \",y[minrow[1]],\n                          \"\\n\\tPoint 2: \",x[minrow[2]],\", \",y[minrow[2]],\n                          \"\\n\\tDistance: \",minrow[3],\"\\n\",sep=\"\")\n  c(distance=minrow[3],x1.x=x[minrow[1]],y1.y=y[minrow[1]],x2.x=x[minrow[2]],y2.y=y[minrow[2]])\n  }\n\n\nclosest.pairs <- function(x, y=NULL, ...){\n      # takes two-column object(x,y-values), or creates such an object from x and y values\n       if(!is.null(y))  x <- cbind(x, y)\n       \n       distances <- dist(x)\n        min.dist <- min(distances)\n          point.pair <- combn(1:nrow(x), 2)[, which.min(distances)]\n       \n     cat(\"The closest pair is:\\n\\t\", \n      sprintf(\"Point 1:\u00a0%.3f,\u00a0%.3f \\n\\tPoint 2:\u00a0%.3f,\u00a0%.3f \\n\\tDistance:\u00a0%.3f.\\n\", \n        x[point.pair[1],1], x[point.pair[1],2], \n          x[point.pair[2],1], x[point.pair[2],2],  \n            min.dist), \n            sep=\"\"   )\n     c( x1=x[point.pair[1],1],y1=x[point.pair[1],2],\n        x2=x[point.pair[2],1],y2=x[point.pair[2],2],\n        distance=min.dist)\n     }\n\nExamplex = (sample(-1000.00:1000.00,100))\ny = (sample(-1000.00:1000.00,length(x)))\ncp = closest.pairs(x,y)\n#cp = closestPair(x,y)\nplot(x,y,pch=19,col='black',main=\"Closest Pair\", asp=1)\npoints(cp[\"x1.x\"],cp[\"y1.y\"],pch=19,col='red')\npoints(cp[\"x2.x\"],cp[\"y2.y\"],pch=19,col='red')\n#closest_pair_brute(x,y,T)\n\nPerformance\nsystem.time(closest_pair_brute(x,y), gcFirst = TRUE)\nShortest path found =\n From:          (32,-987)\n To:            (25,-993)\n Distance:      9.219544\n\n   user  system elapsed\n   0.35    0.02    0.37\n\nsystem.time(closest.pairs(x,y), gcFirst = TRUE)\nThe closest pair is:\n        Point 1: 32.000, -987.000\n        Point 2: 25.000, -993.000\n        Distance: 9.220.\n\n   user  system elapsed\n   0.08    0.00    0.10\n\nsystem.time(closestPair(x,y), gcFirst = TRUE)\nThe closest pair is:\n        Point 1: 32, -987\n        Point 2: 25, -993\n        Distance: 9.219544\n\n   user  system elapsed\n   0.17    0.00    0.19\n\n\nclosest.pairs.bruteforce <- function(x, y=NULL)\n{\n\tif (!is.null(y))\n\t{\n\t\tx <- cbind(x,y)\n\t}\n\td <- dist(x)\n\tcp <- x[combn(1:nrow(x), 2)[, which.min(d)],]\n\tlist(p1=cp[1,], p2=cp[2,], d=min(d))\n}\n\nclosest.pairs.dandc <- function(x, y=NULL)\n{\n\tif (!is.null(y))\n\t{\n\t\tx <- cbind(x,y)\n\t}\n\tif (sd(x[,\"x\"]) < sd(x[,\"y\"]))\n\t{\n\t\tx <- cbind(x=x[,\"y\"],y=x[,\"x\"])\n\t\tswap <- TRUE\n\t}\n\telse\n\t{\n\t\tswap <- FALSE\n\t}\n\txp <- x[order(x[,\"x\"]),]\n\t.cpdandc.rec <- function(xp,yp)\n\t{\n\t\tn <- dim(xp)[1]\n\t\tif (n <= 4)\n\t\t{\n\t\t\tclosest.pairs.bruteforce(xp)\n\t\t}\n\t\telse\n\t\t{\n\t\t\txl <- xp[1:floor(n\/2),]\n\t\t\txr <- xp[(floor(n\/2)+1):n,]\n\t\t\tcpl <- .cpdandc.rec(xl)\n\t\t\tcpr <- .cpdandc.rec(xr)\n\t\t\tif (cpl$d<cpr$d) cp <- cpl else cp <- cpr\n\t\t\tcp\n\t\t}\n\t}\n\tcp <- .cpdandc.rec(xp)\n\t\n\typ <- x[order(x[,\"y\"]),]\n\txm <- xp[floor(dim(xp)[1]\/2),\"x\"]\n\tys <- yp[which(abs(xm - yp[,\"x\"]) <= cp$d),]\n\tnys <- dim(ys)[1]\n\tif (!is.null(nys) && nys > 1)\n\t{\n\t\tfor (i in 1:(nys-1))\n\t\t{\n\t\t\tk <- i + 1\n\t\t\twhile (k <= nys && ys[i,\"y\"] - ys[k,\"y\"] < cp$d)\n\t\t\t{\n\t\t\t\td <- sqrt((ys[k,\"x\"]-ys[i,\"x\"])^2 + (ys[k,\"y\"]-ys[i,\"y\"])^2)\n\t\t\t\tif (d < cp$d) cp <- list(p1=ys[i,],p2=ys[k,],d=d)\n\t\t\t\tk <- k + 1\n\t\t\t}\n\t\t}\n\t}\n\tif (swap)\n\t{\n\t\tlist(p1=cbind(x=cp$p1[\"y\"],y=cp$p1[\"x\"]),p2=cbind(x=cp$p2[\"y\"],y=cp$p2[\"x\"]),d=cp$d)\n\t}\n\telse\n\t{\n\t\tcp\n\t}\n}\n\n# Test functions\ncat(\"How many points?\\n\")\nn <- scan(what=integer(),n=1)\nx <- rnorm(n)\ny <- rnorm(n)\ntstart <- proc.time()[3]\ncat(\"Closest pairs divide and conquer:\\n\")\nprint(cp <- closest.pairs.dandc(x,y))\ncat(sprintf(\"That took\u00a0%.2f seconds.\\n\",proc.time()[3] - tstart))\nplot(x,y)\npoints(c(cp$p1[\"x\"],cp$p2[\"x\"]),c(cp$p1[\"y\"],cp$p2[\"y\"]),col=\"red\")\ntstart <- proc.time()[3]\ncat(\"\\nClosest pairs brute force:\\n\")\nprint(closest.pairs.bruteforce(x,y))\ncat(sprintf(\"That took\u00a0%.2f seconds.\\n\",proc.time()[3] - tstart))\n\n\n","human_summarization":"The code provides a function to solve the Closest Pair of Points problem in a planar case. It includes two algorithms: a brute-force O(n^2) algorithm that finds the closest two points in a given set by comparing all pairs, and a more efficient O(n log n) divide-and-conquer algorithm that sorts the points by x and y coordinates, divides them into two halves, and recursively finds the closest pairs in each half. The function returns the minimum distance and the pair of points with the minimum distance.","id":1466}
    {"lang_cluster":"R","source_code":"\n\n\nnumeric(5)\n1:10\nc(1, 3, 6, 10, 7 + 8, sqrt(441))\n[1] 0 0 0 0 0\n[1]  1  2  3  4  5  6  7  8  9 10\n[1]  1  3  6 10 15 21\n\n\ninteger(5)\nc(1L, -2L, 99L);\n[1] 0 0 0 0 0\n[1]  1 -2 99\n\n\nlogical(5)\nc(TRUE, FALSE)\n[1] FALSE FALSE FALSE FALSE FALSE\n[1]  TRUE FALSE\n\n\ncharacter(5)\nc(\"abc\", \"defg\", \"\")\n[1] \"\" \"\" \"\" \"\" \"\"\n[1] \"abc\"  \"defg\" \"\"\n\n\nmatrix(1:12, nrow=3)\n\narray(1:24, dim=c(2,3,4)) #output not shown\n     [,1] [,2] [,3] [,4]\n[1,]    1    4    7   10\n[2,]    2    5    8   11\n[3,]    3    6    9   12\n\n\nlist(a=123, b=\"abc\", TRUE, 1:5, c=list(d=runif(5), e=5+6))\n$a\n[1] 123\n$b\n[1] \"abc\"\n[[3]]\n[1] TRUE\n[[4]]\n[1] 1 2 3 4 5 \n$c\n$c$d\n[1] 0.6013157 0.5011909 0.7106448 0.3882265 0.1274939\n$c$e\n[1] 11\n\ndata.frame(name=c(\"Alice\", \"Bob\", \"Carol\"), age=c(23, 35, 17))\n   name age\n1 Alice  23\n2   Bob  35\n3 Carol  17\n\n","human_summarization":"The code creates a collection and adds several values to it. It utilizes various types of collections available in R, such as numeric, integer, logical, and character types. These collections can be seen as vectors with a dimension attribute, with matrices being a special case of arrays with two dimensions. The code also uses lists, which are collections of other variables, and data frames, which are similar to a combination of a list and a matrix, where each row represents a collection of variables or a \"record\".","id":1467}
    {"lang_cluster":"R","source_code":"\n\n# Define consts\nweights <- c(panacea=0.3, ichor=0.2, gold=2.0)\nvolumes <- c(panacea=0.025, ichor=0.015, gold=0.002)\nvalues <- c(panacea=3000, ichor=1800, gold=2500)\nsack.weight <- 25\nsack.volume <- 0.25\nmax.items <- floor(pmin(sack.weight\/weights, sack.volume\/volumes))\n\n# Some utility functions\ngetTotalValue <- function(n) sum(n*values)\ngetTotalWeight <- function(n) sum(n*weights)\ngetTotalVolume <- function(n) sum(n*volumes)\nwillFitInSack <- function(n) getTotalWeight(n) <= sack.weight && getTotalVolume(n) <= sack.volume\n\n# Find all possible combination, then eliminate those that won't fit in the sack\nknapsack <- expand.grid(lapply(max.items, function(n) seq.int(0, n)))\nok <- apply(knapsack, 1, willFitInSack)\nknapok <- knapsack[ok,]\n\n# Find the solutions with the highest value\nvals <- apply(knapok, 1, getTotalValue)\nknapok[vals == max(vals),]\n\n     panacea ichor gold\n2067       9     0   11\n2119       6     5   11\n2171       3    10   11\n2223       0    15   11\n\n\nData_<-structure(list(item = c(\"Panacea\", \"Ichor\", \"Gold\"), value = c(3000, \n1800, 2500), weight = c(3, 2, 20), volume = c(25, 15, 2)), .Names = c(\"item\", \n\"value\", \"weight\", \"volume\"), row.names = c(NA, 3L), class = \"data.frame\")\n\nknapsack_volume<-function(Data, W, Volume, full_K) \n{\n\n\t# Data must have the colums with names: item, value, weight and volume.\n\tK<-list() # hightest values\n\tK_item<-list() # itens that reach the hightest value\n\tK<-rep(0,W+1) # The position '0'\n\tK_item<-rep('',W+1) # The position '0'\n\tfor(w in 1:W)\n\t{\n\t\ttemp_w<-0\n\t\ttemp_item<-''\n\t\ttemp_value<-0\n\t\tfor(i in 1:dim(Data)[1]) # each row\n\t\t{\n\t\t\twi<-Data$weight[i] # item i\n\t\t\tvi<- Data$value[i]\n\t\t\titem<-Data$item[i]\n\t\t\tvolume_i<-Data$volume[i]\n\t\t\tif(wi<=w & volume_i <= Volume)\n\t\t\t{\n\t\t\t\tback<- full_K[[Volume-volume_i+1]][w-wi+1]\n\t\t\t\ttemp_wi<-vi + back\n\n\t\t\t\tif(temp_w < temp_wi)\n\t\t\t\t{\n\t\t\t\t\ttemp_value<-temp_wi\n\t\t\t\t\ttemp_w<-temp_wi\n\t\t\t\t\ttemp_item <- item\n\t\t\t\t}\t\n\t\t\t}\n\t\t}\n\tK[[w+1]]<-temp_value\n\tK_item[[w+1]]<-temp_item\n\t}\nreturn(list(K=K,Item=K_item))\n}\n\n\nUn_knapsack<-function(Data,W,V)\n{\n\tK<-list();K_item<-list()\n\tK[[1]]<-rep(0,W+1) #the line 0\n\tK_item[[1]]<-rep('', W+1) #the line 0\n\tfor(v in 1:V)\n\t{\n\t\tbest_volum_v<-knapsack_volume(Data, W, v, K)\n\t\tK[[v+1]]<-best_volum_v$K\n\t\tK_item[[v+1]]<-best_volum_v$Item\n\t}\n\nreturn(list(K=data.frame(K),Item=data.frame(K_item,stringsAsFactors=F)))\n}\n\nretrieve_info<-function(knapsack, Data)\n{\n\tW<-dim(knapsack$K)[1]\n\titens<-c()\n\tcol<-dim(knapsack$K)[2]\n\tselected_item<-knapsack$Item[W,col]\n\twhile(selected_item!='')\n\t{\n\t\tselected_item<-knapsack$Item[W,col]\n\t\tif(selected_item!='')\n\t\t{\n\t\t\tselected_item_value<-Data[Data$item == selected_item,]\t\t\t\n\t\t\tW <- W - selected_item_value$weight\n\t\t\titens<-c(itens,selected_item)\t\t\t\n\t\t\tcol <- col - selected_item_value$volume\n\t\t}\n\t}\nreturn(itens)\n}\n\nmain_knapsack<-function(Data, W, Volume)\n{\n\tknapsack_result<-Un_knapsack(Data,W,Volume)\n\titems<-table(retrieve_info(knapsack_result, Data))\n\tK<-knapsack_result$K[W+1, Volume+1]\n\tcat(paste('The Total profit is: ', K, '\\n'))\n\tcat(paste('You must carry:', names(items), '(x',items, ') \\n'))\n}\n\nmain_knapsack(Data_, 250, 250)\n\n","human_summarization":"\"Determine the maximum value of items a traveler can carry in his knapsack given the weight and volume constraints, using dynamic programming. The solution shows the quantity of each item to be taken to achieve this maximum value. Only one of the four possible solutions needs to be provided.\"","id":1468}
    {"lang_cluster":"R","source_code":"\n\npaste(1:10, collapse=\", \")\n\nfor(i in 1:10)\n{\n   cat(i)\n   if(i==10) \n   {\n      cat(\"\\n\")\n      break\n   }\n   cat(\", \")\n}\n","human_summarization":"generate a comma-separated list of numbers from 1 to 10, using a loop with separate output statements for the number and the comma. The last iteration only outputs the number, not the comma.","id":1469}
    {"lang_cluster":"R","source_code":"\n\ndeps <- list(\n\"des_system_lib\" = c(\"std\", \"synopsys\", \"std_cell_lib\", \"des_system_lib\", \"dw02\", \"dw01\", \"ramlib\", \"ieee\"),\n\"dw01\" = c(\"ieee\", \"dw01\", \"dware\", \"gtech\", \"dw04\"),\n\"dw02\" = c(\"ieee\", \"dw02\", \"dware\"),\n\"dw03\" = c(\"std\", \"synopsys\", \"dware\", \"dw03\", \"dw02\", \"dw01\", \"ieee\", \"gtech\"),\n\"dw04\" = c(\"dw04\", \"ieee\", \"dw01\", \"dware\", \"gtech\"),\n\"dw05\" = c(\"dw05\", \"ieee\", \"dware\"),\n\"dw06\" = c(\"dw06\", \"ieee\", \"dware\"),\n\"dw07\" = c(\"ieee\", \"dware\"),\n\"dware\" = c(\"ieee\", \"dware\"),\n\"gtech\" = c(\"ieee\", \"gtech\"),\n\"ramlib\" = c(\"std\", \"ieee\"),\n\"std_cell_lib\" = c(\"ieee\", \"std_cell_lib\"),\n\"synopsys\" = c())\n\n\ntsort <- function(deps) {\n\tnm <- names(deps)\n\tlibs <- union(as.vector(unlist(deps)), nm)\n\t\n\ts <- c()\n\t# first libs that depend on nothing\n\tfor(x in libs) {\n\t\tif(!(x %in% nm)) {\n\t\t\ts <- c(s, x)\n\t\t}\n\t}\n\t\n\tk <- 1\n\twhile(k > 0) {\n\t\tk <- 0\n\t\tfor(x in setdiff(nm, s)) {\n\t\t\tr <- c(s, x)\n\t\t\tif(length(setdiff(deps[[x]], r)) == 0) {\n\t\t\t\ts <- r\n\t\t\t\tk <- 1\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif(length(s) < length(libs)) {\n\t\tv <- setdiff(libs, s)\n\t\tstop(sprintf(\"Unorderable items\u00a0:\\n%s\", paste(\"\", v, sep=\"\", collapse=\"\\n\")))\n\t}\n\t\n\ts\n}\n\n\ntsort(deps)\n# [1] \"std\"            \"ieee\"           \"dware\"          \"gtech\"          \"ramlib\"        \n# [6] \"std_cell_lib\"   \"synopsys\"       \"dw01\"           \"dw02\"           \"dw03\"          \n#[11] \"dw04\"           \"dw05\"           \"dw06\"           \"dw07\"           \"des_system_lib\"\n\n\nUnorderable items :\ndes_system_lib\ndw01\ndw04\ndw03\n\n","human_summarization":"The code implements a function for topological sorting of VHDL libraries based on their dependencies. It takes into account self-dependencies and un-orderable dependencies. The function returns a valid compile order of the libraries or throws an error if the order cannot be determined. The function uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":1470}
    {"lang_cluster":"R","source_code":"\n\n# 4 rings or 4 squares puzzle\n\nperms <- function (n, r, v = 1:n, repeats.allowed = FALSE) {\n  if (repeats.allowed) \n    sub <- function(n, r, v) {\n      if (r == 1) \n        matrix(v, n, 1)\n      else if (n == 1) \n        matrix(v, 1, r)\n      else {\n        inner <- Recall(n, r - 1, v)\n        cbind(rep(v, rep(nrow(inner), n)), matrix(t(inner), \n                                                  ncol = ncol(inner), nrow = nrow(inner) * n, \n                                                  byrow = TRUE))\n      }\n    }\n  else sub <- function(n, r, v) {\n    if (r == 1) \n      matrix(v, n, 1)\n    else if (n == 1) \n      matrix(v, 1, r)\n    else {\n      X <- NULL\n      for (i in 1:n) X <- rbind(X, cbind(v[i], Recall(n - 1, r - 1, v[-i])))\n      X\n    }\n  }\n  X <- sub(n, r, v[1:n])\n  \n  result <- vector(mode = \"numeric\")\n\n  for(i in 1:nrow(X)){\n    y <- X[i, ]\n    x1 <- y[1] + y[2]\n    x2 <- y[2] + y[3] + y[4]\n    x3 <- y[4] + y[5] + y[6]\n    x4 <- y[6] + y[7]\n    if(x1 == x2 & x2 == x3 & x3 == x4) result <- rbind(result, y)\n  }\n  return(result)\n}\n\nprint_perms <- function(n, r, v = 1:n, repeats.allowed = FALSE, table.out = FALSE) {\n  a <- perms(n, r, v, repeats.allowed)\n  colnames(a) <- rep(\"\", ncol(a))\n  rownames(a) <- rep(\"\", nrow(a)) \n  if(!repeats.allowed){\n    print(a)\n    cat(paste('\\n', nrow(a), 'unique solutions from', min(v), 'to', max(v)))\n  } else {\n    cat(paste('\\n', nrow(a), 'non-unique solutions from', min(v), 'to', max(v)))\n  }\n}\n\nregisterS3method(\"print_perms\", \"data.frame\", print_perms)\n\nprint_perms(7, 7, repeats.allowed = FALSE, table.out = TRUE)\nprint_perms(7, 7, v = 3:9, repeats.allowed = FALSE, table.out = TRUE)\nprint_perms(10, 7, v = 0:9, repeats.allowed = TRUE, table.out = FALSE)\n\n\n","human_summarization":"The code replaces the variables a, b, c, d, e, f, and g with decimal digits ranging from a low to a high value. It then calculates the sum of the variables in each of the four squares, ensuring they all add up to the same total. The code provides all unique solutions for the ranges 1-7 and 3-9, and the total number of solutions for the range 0-9, allowing for non-unique values. Additionally, it includes a function \"perms\" which is a modified version of the \"permutations\" function from the \"gtools\" R package.","id":1471}
    {"lang_cluster":"R","source_code":"\n\nwin <- tktoplevel()\n\nLibrary: gWidgets\n\nlibrary(gWidgetstcltk) #or e.g. gWidgetsRGtk2\nwin <- gwindow()\n\n","human_summarization":"create a GUI window using R's wrappers for GUI toolkits, specifically tcl\/tk and gWidgets packages. The window does not contain any elements but can be closed upon request.","id":1472}
    {"lang_cluster":"R","source_code":"\nletter.frequency <- function(filename)\n{\n    file <- paste(readLines(filename), collapse = '')\n    chars <- strsplit(file, NULL)[[1]]\n    summary(factor(chars))\n}\n\n\n> source('letter.frequency.r')\n> letter.frequency('letter.frequency.r')\n    -  ,  .  '  (  )  [  ]  {  }  <  =  1  a  c  d  e  f  h  i  l  L  m  n  N  o  p  q  r  s  t  u  U  y \n22  3  2  1  2  6  6  2  2  1  1  3  1  1  9  6  1 14  7  2  7  8  3  4  6  1  3  3  1  8  8  7  3  1  2\n\n\nletterFreq <- function(filename, lettersOnly)\n{\n  txt <- read.delim(filename, header = FALSE, stringsAsFactors = FALSE, allowEscapes = FALSE, quote = \"\")\n  count <- table(strsplit(paste0(txt[,], collapse = \"\"), \"\"))\n  if(lettersOnly) count[names(count) %in% c(LETTERS, letters)] else count\n}\n\n\n","human_summarization":"The code opens a text file and counts the frequency of each letter, ignoring punctuation and empty lines. It uses R's read.delim function for reading the file and table function for counting letters. The input is an HTML page, though this may result in inaccurate output due to parsing issues.","id":1473}
    {"lang_cluster":"R","source_code":"Works with: R version 3.3.3 and above\nFile:FRTR9.pngOutput FRTR9.png\nFile:FRTR12.pngOutput FRTR12.png\nFile:FRTR15.pngOutput FRTR15.png\n## Recursive FT plotting\nplotftree <- function(x, y, a, d, c) {\nx2=y2=0; d2r=pi\/180.0; a1 <- a*d2r; d1=0;\nif(d<=0) {return()}\nif(d>0)\n  { d1=d*10.0;\n    x2=x+cos(a1)*d1;\n    y2=y+sin(a1)*d1;\n    segments(x*c, y*c, x2*c, y2*c, col='darkgreen');\n    plotftree(x2,y2,a-20,d-1,c);\n    plotftree(x2,y2,a+20,d-1,c);\n    #return(2);\n  }\n}\n## Plotting Fractal Tree. aev 3\/27\/17\n## ord - order\/depth, c - scale, xsh - x-shift, fn - file name,\n##  ttl - plot title.\npFractalTree <- function(ord, c=1, xsh=0, fn=\"\", ttl=\"\") {\n  cat(\" *** START FRT:\", date(), \"\\n\");\n  m=640;\n  if(fn==\"\") {pf=paste0(\"FRTR\", ord, \".png\")} else {pf=paste0(fn, \".png\")};\n  if(ttl==\"\") {ttl=paste0(\"Fractal tree, order - \", ord)};\n  cat(\" *** Plot file -\", pf, \"title:\", ttl, \"\\n\");\n  ##plot(NA, xlim=c(0,m), ylim=c(-m,0), xlab=\"\", ylab=\"\", main=ttl);\n  plot(NA, xlim=c(0,m), ylim=c(0,m), xlab=\"\", ylab=\"\", main=ttl);\n  plotftree(m\/2+xsh,100,90,ord,c);\n  dev.copy(png, filename=pf, width=m, height=m);\n  dev.off(); graphics.off();\n  cat(\" *** END FRT:\",date(),\"\\n\");\n}\n## Executing:\npFractalTree(9);\npFractalTree(12,0.6,210);\npFractalTree(15,0.35,600);\n\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":1474}
    {"lang_cluster":"R","source_code":"\nfactors <- function(n)\n{\n   if(length(n) > 1) \n   {\n      lapply(as.list(n), factors)\n   } else\n   {\n      one.to.n <- seq_len(n)\n      one.to.n[(n\u00a0%% one.to.n) == 0]\n   }\n}\n\n","human_summarization":"calculate the factors of a given positive integer, excluding zero and negative integers. It also notes that every prime number has two factors: 1 and itself. An idiomatic way to achieve this is by using R's Filter function.","id":1475}
    {"lang_cluster":"R","source_code":"\n# Read in text\nlines <- readLines(tc <- textConnection(\"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\")); close(tc)\n\n#Split words by the dollar\nwords <- strsplit(lines, \"\\\\$\")\n\n#Reformat\nmaxlen <- max(sapply(words, length))\nwords <- lapply(words, function(x) {length(x) <- maxlen; x})\nblock <- matrix(unlist(words), byrow=TRUE, ncol=maxlen)\nblock[is.na(block)] <- \"\"\nleftjust <- format(block)\nrightjust <- format(block, justify=\"right\")\ncentrejust <- format(block, justify=\"centre\")\n\n# Print\nprint0 <- function(x) invisible(apply(x, 1, function(x) cat(x, \"\\n\")))\nprint0(leftjust)\nprint0(rightjust)\nprint0(centrejust)\n\n\n     Given          a       text       file         of       many     lines,      where     fields     within          a       line \n       are delineated         by          a     single   'dollar' character,      write          a    program                       \n      that     aligns       each     column         of     fields         by   ensuring       that      words         in       each \n    column        are  separated         by         at      least        one     space.                                             \n  Further,      allow        for       each       word         in          a     column         to         be     either       left \njustified,      right justified,         or     center  justified     within        its    column.                                  \n\n","human_summarization":"The code reads a text file where fields within a line are separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It allows for each word in a column to be either left justified, right justified, or center justified. The minimum space between columns is computed from the text. It handles trailing dollar characters and consecutive space characters at the end of lines. The output is displayed in a mono-spaced font on a plain text editor or basic terminal.","id":1476}
    {"lang_cluster":"R","source_code":"\nrot13 <- function(x)\n{\n  old <- paste(letters, LETTERS, collapse=\"\", sep=\"\")\n  new <- paste(substr(old, 27, 52), substr(old, 1, 26), sep=\"\")\n  chartr(old, new, x)\n}\nx <- \"The Quick Brown Fox Jumps Over The Lazy Dog!.,:;'#~[]{}\"\nrot13(x)   # \"Gur Dhvpx Oebja Sbk Whzcf Bire Gur Ynml Qbt!.,:;'#~[]{}\"\nx2 <- paste(letters, LETTERS, collapse=\"\", sep=\"\")\nrot13(x2)  # \"nNoOpPqQrRsStTuUvVwWxXyYzZaAbBcCdDeEfFgGhHiIjJkKlLmM\"\n\n","human_summarization":"The code implements a rot-13 function that replaces every letter of the ASCII alphabet with the letter rotated 13 characters around the 26 letter alphabet. It works on both upper and lower case letters, preserves case, and passes all non-alphabetic characters without alteration. The function can be optionally wrapped in a utility program acting like a common UNIX utility, performing a line-by-line rot-13 encoding of every line of input from each file listed on its command line or acting as a filter on its standard input.","id":1477}
    {"lang_cluster":"R","source_code":"\n\nsortbyname <- function(x, ...) x[order(names(x), ...)]\nx <- c(texas=68.9, ohio=87.8, california=76.2, \"new york\"=88.2)\nsortbyname(x)\n\ncalifornia   new york       ohio      texas \n      76.2       88.2       87.8       68.9 \n\nsortbyname(x, decreasing=TRUE)\n\n     texas       ohio   new york california \n      68.9       87.8       88.2       76.2\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key 'name' using a custom comparator.","id":1478}
    {"lang_cluster":"R","source_code":"\nfor(i in 0:4) {\n  s <- \"\"\n  for(j in 0:i) {\n    s <- paste(s, \"*\", sep=\"\")\n  }\n  print(s)\n}\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":1479}
    {"lang_cluster":"R","source_code":"\n\n> env <- new.env()\n> env[[\"x\"]] <- 123\n> env[[\"x\"]]\n[1] 123\n> index <- \"1\"\n> env[[index]] <- \"rainfed hay\"\n> env[[index]]\n[1] \"rainfed hay\"\n> env[[\"1\"]]\n[1] \"rainfed hay\"\n> env\n<environment: 0xb7cd560>\n> print(env)\n<environment: 0xb7cd560>\n> x <- c(hello=1, world=2, \"!\"=3)\n> print(x)\nhello world    \u00a0! \n    1     2     3\n> print(names(x))\n[1] \"hello\" \"world\" \"!\"\nprint(unname(x))\n[1] 1 2 3\n> a <- list(a=1, b=2, c=3.14, d=\"xyz\")\n> print(a)\n$a\n[1] 1\n\n$b\n[1] 2\n\n$c\n[1] 3.14\n\n$d\n[1] \"xyz\"\n> print(names(a))\n[1] \"a\" \"b\" \"c\" \"d\"\n> print(unname(a))\n[[1]]\n[1] 1\n\n[[2]]\n[1] 2\n\n[[3]]\n[1] 3.14\n\n[[4]]\n[1] \"xyz\"\n","human_summarization":"create an associative array (dictionary, map, or hash) in R using structures that allow named elements.","id":1480}
    {"lang_cluster":"R","source_code":"\nlibrary(gmp) # for big integers\n\nrand_BSD <- function(n = 1) {\n  a <- as.bigz(1103515245)\n  c <- as.bigz(12345)\n  m <- as.bigz(2^31)\n  x <- rep(as.bigz(0), n)\n  x[1] <- (a * as.bigz(seed) + c) %% m\n  i <- 1\n  while (i < n) {\n    x[i+1] <- (a * x[i] + c) %% m\n    i <- i + 1\n  }\n  as.integer(x)\n}\n\nseed <- 0\nrand_BSD(10)\n##  [1]      12345 1406932606  654583775 1449466924  229283573 1109335178\n##  [7] 1051550459 1293799192  794471793  551188310\n\nrand_MS <- function(n = 1) {\n  a <- as.bigz(214013)\n  c <- as.bigz(2531011)\n  m <- as.bigz(2^31)\n  x <- rep(as.bigz(0), n)\n  x[1] <- (a * as.bigz(seed) + c) %% m\n  i <- 1\n  while (i < n) {\n    x[i+1] <- (a * x[i] + c) %% m\n    i <- i + 1\n  }\n  as.integer(x \/ 2^16)\n}\n\nseed <- 0\nrand_MS(10)\n##  [1]    38  7719 21238  2437  8855 11797  8365 32285 10450 30612\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":1481}
    {"lang_cluster":"R","source_code":"\nhalve <- function(a) floor(a\/2)\ndouble <- function(a) a*2\niseven <- function(a) (a%%2)==0\n\nethiopicmult <- function(plier, plicand, tutor=FALSE) {\n  if (tutor) { cat(\"ethiopic multiplication of\", plier, \"and\", plicand, \"\\n\") }\n  result <- 0\n  while(plier >= 1) {\n    if (!iseven(plier)) { result <- result + plicand }\n    if (tutor) {\n      cat(plier, \", \", plicand, \" \", ifelse(iseven(plier), \"struck\", \"kept\"), \"\\n\", sep=\"\")\n    }\n    plier <- halve(plier)\n    plicand <- double(plicand)\n  }\n  result\n}\n\nprint(ethiopicmult(17, 34, TRUE))\n\nhalve <- function(a) floor(a\/2)\ndouble <- function(a) a*2\niseven <- function(a) (a%%2)==0\n\nethiopicmult<-function(x,y){\n\tres<-ifelse(iseven(y),0,x)\n\twhile(!y==1){\n\t\tx<-double(x)\n\t\ty<-halve(y)\n\t\tif(!iseven(y)) res<-res+x\n\t}\n\treturn(res)\n}\n\nprint(ethiopicmult(17,34))\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method that multiplies two integers using only addition, doubling, and halving operations.","id":1482}
    {"lang_cluster":"R","source_code":"\n\nlibrary(gtools)\n\nsolve24 <- function(vals=c(8, 4, 2, 1),\n                    goal=24,\n                    ops=c(\"+\", \"-\", \"*\", \"\/\")) {\n  \n  val.perms <- as.data.frame(t(\n                  permutations(length(vals), length(vals))))\n\n  nop <- length(vals)-1\n  op.perms <- as.data.frame(t(\n                  do.call(expand.grid,\n                          replicate(nop, list(ops)))))\n  \n  ord.perms <- as.data.frame(t(\n                   do.call(expand.grid,\n                           replicate(n <- nop, 1:((n <<- n-1)+1)))))\n\n  for (val.perm in val.perms)\n    for (op.perm in op.perms)\n      for (ord.perm in ord.perms)\n        {\n          expr <- as.list(vals[val.perm])\n          for (i in 1:nop) {\n            expr[[ ord.perm[i] ]] <- call(as.character(op.perm[i]),\n                                          expr[[ ord.perm[i]   ]],\n                                          expr[[ ord.perm[i]+1 ]])\n            expr <- expr[ -(ord.perm[i]+1) ]\n          }\n          if (identical(eval(expr[[1]]), goal)) return(expr[[1]])\n        }\n\n  return(NA)\n}\n\n\n","human_summarization":"The code accepts four digits as input or generates them randomly, then computes arithmetic expressions according to the rules of the 24 game. It also displays examples of the solutions it generates. The code uses exhaustive search and leverages R's ability to handle expressions as data, making it generally applicable for any set of operands and binary operators.","id":1483}
    {"lang_cluster":"R","source_code":"\nfact <- function(n) {\n  if (n <= 1) 1\n  else n * Recall(n - 1)\n}\nfactIter <- function(n) {\n  f = 1\n  if (n > 1) {\n    for (i in 2:n) f <- f * i\n  }\n  f\n}\n\nprint(factorial(50)) # 3.041409e+64\n","human_summarization":"The code is a function that calculates and returns the factorial of a given number. The factorial is computed either iteratively or recursively. The function may optionally handle errors for negative input values. It also includes a reference to the native gamma function in R for producing factorials.","id":1484}
    {"lang_cluster":"R","source_code":"\nWorks with: R version 2.8.1\ntarget <- sample(1:9,4)\nbulls <- 0\ncows <- 0\nattempts <- 0\nwhile (bulls != 4)\n  {\n  input <- readline(\"Guess a 4-digit number with no duplicate digits or 0s: \")\n  if (nchar(input) == 4)\n    {\n    input <- as.integer(strsplit(input,\"\")[[1]])\n    if ((sum(is.na(input)+sum(input==0))>=1) | (length(table(input)) != 4)) {print(\"Malformed input!\")} else {\n      bulls <- sum(input == target)\n      cows <- sum(input %in% target)-bulls\n      cat(\"\\n\",bulls,\" Bull(s) and \",cows, \" Cow(s)\\n\")\n      attempts <- attempts + 1\n      }\n    } else {print(\"Malformed input!\")}\n  }\nprint(paste(\"You won in\",attempts,\"attempt(s)!\"))\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":1485}
    {"lang_cluster":"R","source_code":"\n# For reproducibility, set the seed:\nset.seed(12345L)\n\nresult <- rnorm(1000, mean = 1, sd = 0.5)\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":1486}
    {"lang_cluster":"R","source_code":"\n\nx <- c(1, 3, -5)\ny <- c(4, -2, -1)\n\nsum(x*y)  # compute products, then do the sum\nx %*% y   # inner product\n\n# loop implementation\ndotp <- function(x, y) {\n\tn <- length(x)\n\tif(length(y) != n) stop(\"invalid argument\")\n\ts <- 0\n\tfor(i in 1:n) s <- s + x[i]*y[i]\n\ts\n}\n\ndotp(x, y)\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The vectors should be of the same length, and the function works by multiplying corresponding terms from each vector and summing the products.","id":1487}
    {"lang_cluster":"R","source_code":"\n\nlines <- readLines(\"file.txt\")\n\n","human_summarization":"\"Reads data from a text stream either word-by-word or line-by-line until the data is exhausted. It handles streams with an unknown amount of data. For 'dataset' style contents, read.csv and read.table can be used as alternatives.\"","id":1488}
    {"lang_cluster":"R","source_code":"\nWorks with: R version 2.8.1\nNote that this is output as a standard style string.Sys.time()\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":1489}
    {"lang_cluster":"R","source_code":"\n# Read in data from text connection\ndatalines <- readLines(tc <- textConnection(\"710889\nB0YBKJ\n406566\nB0YBLH\n228276\nB0YBKL\n557910\nB0YBKR\n585284\nB0YBKT\")); close(tc)\n\n# Check data valid\ncheckSedol <- function(datalines)\n{\n   ok <- grep(\"^[[:digit:][:upper:]]{6}$\", datalines)\n   if(length(ok) < length(datalines))\n   {\n      stop(\"there are invalid lines\") \n   }\n}\ncheckSedol(datalines)\n\n# Append check digit\nappendCheckDigit <- function(x) \n{   \n   if(length(x) > 1) return(sapply(x, appendCheckDigit)) \n   ascii <- as.integer(charToRaw(x))\n   scores <- ifelse(ascii < 65, ascii - 48, ascii - 55)\n   weights <- c(1, 3, 1, 7, 3, 9)\n   chkdig <- (10 - sum(scores * weights) %% 10) %% 10\n   paste(x, as.character(chkdig), sep=\"\")\n}\nwithchkdig <- appendCheckDigit(datalines)\n\n#Print in format requested\nwriteLines(withchkdig)\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":1490}
    {"lang_cluster":"R","source_code":"\nnth <- function(n)\n{\n  if (length(n) > 1) return(sapply(n, nth))\n  \n  mod <- function(m, n) ifelse(!(m%%n), n, m%%n)\n  suffices <- c(\"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\")\n  \n  if (n %% 100 <= 10 || n %% 100 > 20) \n    suffix <- suffices[mod(n+1, 10)]\n  else \n    suffix <- 'th'\n  \n  paste(n, \"'\", suffix, sep=\"\")\n}\n\nrange <- list(0:25, 250:275, 500:525, 750:775, 1000:1025)\n\nsapply(range, nth)\n\n\n","human_summarization":"The code implements a function that takes a non-negative integer as input and returns a string of the number followed by an apostrophe and its corresponding ordinal suffix. The function handles the special cases for the ordinal suffixes of numbers ending in 1, 2, and 3, except for those ending in 11, 12, and 13. The function is tested with the ranges 0..25, 250..265, and 1000..1025.","id":1491}
    {"lang_cluster":"R","source_code":"\n\ngenFizzBuzz <- function(n, ...)\n{\n  args <- list(...)\n  #R doesn't like vectors of mixed types, so c(3, \"Fizz\") is coerced to c(\"3\", \"Fizz\"). We must undo this.\n  #Treating \"[[\" as if it is a function is a bit of R's magic. You can treat it like a function because it actually is one.\n  factors <- as.integer(sapply(args, \"[[\", 1)) \n  words <- sapply(args, \"[[\", 2)\n  sortedPermutation <- sort.list(factors)#Required by the task: We must go from least factor to greatest.\n  factors <- factors[sortedPermutation]\n  words <- words[sortedPermutation]\n  for(i in 1:n)\n  {\n    isFactor <- i %% factors == 0\n    print(if(any(isFactor)) paste0(words[isFactor], collapse = \"\") else i)\n  }\n}\ngenFizzBuzz(105, c(3, \"Fizz\"), c(5, \"Buzz\"), c(7, \"Baxx\"))\ngenFizzBuzz(105, c(5, \"Buzz\"), c(9, \"Prax\"), c(3, \"Fizz\"), c(7, \"Baxx\"))\n\n\nnamedGenFizzBuzz <- function(n, namedNums)\n{\n  factors <- sort(namedNums)#Required by the task: We must go from least factor to greatest.\n  for(i in 1:n)\n  {\n    isFactor <- i %% factors == 0\n    print(if(any(isFactor)) paste0(names(factors)[isFactor], collapse = \"\") else i)\n  }\n}\nnamedNums <- c(Fizz=3, Buzz=5, Baxx=7)#Notice that we can name our inputs without a function call.\nnamedGenFizzBuzz(105, namedNums)\nshuffledNamedNums <- c(Buzz=5, Prax=9, Fizz=3, Baxx=7)\nnamedGenFizzBuzz(105, shuffledNamedNums)\n\n","human_summarization":"The code takes a maximum number and a list of factors with corresponding words as input from the user. It then prints numbers from 1 to the maximum number, replacing multiples of the given factors with the corresponding words. If a number is a multiple of more than one factor, it prints all corresponding words in the order of the factors. The code assumes 3 factors for simplicity but can handle more. It does not check for malformed user input.","id":1492}
    {"lang_cluster":"R","source_code":"\nDragon<-function(Iters){\n  Rotation<-matrix(c(0,-1,1,0),ncol=2,byrow=T) ########Rotation multiplication matrix\n  Iteration<-list() ###################################Set up list for segment matrices for 1st\n  Iteration[[1]] <- matrix(rep(0,16), ncol = 4)\n  Iteration[[1]][1,]<-c(0,0,1,0)\n  Iteration[[1]][2,]<-c(1,0,1,-1)\n  Moveposition<-rep(0,Iters) ##########################Which point should be shifted to origin\n  Moveposition[1]<-4\n  if(Iters > 1){#########################################where to move to get to origin\n    for(l in 2:Iters){#####################################only if >1, because 1 set before for loop\n      Moveposition[l]<-(Moveposition[l-1]*2)-2#############sets vector of all positions in matrix where last point is\n    }}\n  Move<-list() ########################################vector to add to all points to shift start at origin\nfor (i in 1:Iters){\nhalf<-dim(Iteration[[i]])[1]\/2\nhalf<-1:half\nfor(j in half){########################################Rotate all points 90 degrees clockwise\n  Iteration[[i]][j+length(half),]<-c(Iteration[[i]][j,1:2]%*%Rotation,Iteration[[i]][j,3:4]%*%Rotation)\n}\nMove[[i]]<-matrix(rep(0,4),ncol=4)\nMove[[i]][1,1:2]<-Move[[i]][1,3:4]<-(Iteration[[i]][Moveposition[i],c(3,4)]*-1)\nIteration[[i+1]]<-matrix(rep(0,2*dim(Iteration[[i]])[1]*4),ncol=4)##########move the dragon, set next Iteration's matrix\nfor(k in 1:dim(Iteration[[i]])[1]){#########################################move dragon by shifting all previous iterations point \n  Iteration[[i+1]][k,]<-Iteration[[i]][k,]+Move[[i]]###so the start is at the origin\n}\nxlimits<-c(min(Iteration[[i]][,3])-2,max(Iteration[[i]][,3]+2))#Plot\nylimits<-c(min(Iteration[[i]][,4])-2,max(Iteration[[i]][,4]+2))\nplot(0,0,type='n',axes=FALSE,xlab=\"\",ylab=\"\",xlim=xlimits,ylim=ylimits)\ns<-dim(Iteration[[i]])[1]\ns<-1:s\nsegments(Iteration[[i]][s,1], Iteration[[i]][s,2], Iteration[[i]][s,3], Iteration[[i]][s,4], col= 'red')\n}}#########################################################################\n\n\nWorks with: R version 3.3.1 and above\nFile:DCR7.pngOutput DCR7.png\nFile:DCR13.pngOutput DCR13.png\nFile:DCR16.pngOutput DCR16.png\n# Generate and plot Dragon curve.\n# translation of JavaScript v.#2: http:\/\/rosettacode.org\/wiki\/Dragon_curve#JavaScript\n# 2\/27\/16 aev \n# gpDragonCurve(ord, clr, fn, d, as, xsh, ysh)\n# Where: ord - order (defines the number of line segments); \n#   clr - color, fn - file name (.ext will be added), d - segment length,\n#   as - axis scale, xsh - x-shift, ysh - y-shift\ngpDragonCurve <- function(ord, clr, fn, d, as, xsh, ysh) {\n  cat(\" *** START:\", date(), \"order=\",ord, \"color=\",clr, \"\\n\");\n  d=10; m=640; ms=as*m; n=bitwShiftL(1, ord);\n  c=c1=c2=c2x=c2y=i1=0; x=y=x1=y1=0;\n  if(fn==\"\") {fn=\"DCR\"}\n  pf=paste0(fn, ord, \".png\");\n  ttl=paste0(\"Dragon curve, ord=\",ord);\n  cat(\" *** Plot file -\", pf, \"title:\", ttl, \"n=\",n, \"\\n\");\n  plot(NA, xlim=c(-ms,ms), ylim=c(-ms,ms), xlab=\"\", ylab=\"\", main=ttl);\n  for (i in 0:n) {\n    segments(x1+xsh, y1+ysh, x+xsh, y+ysh, col=clr); x1=x; y1=y;\n    c1=bitwAnd(c, 1); c2=bitwAnd(c, 2);\n    c2x=d; if(c2>0) {c2x=(-1)*d}; c2y=(-1)*c2x;\n    if(c1>0) {y=y+c2y} else {x=x+c2x}\n    i1=i+1; ii=bitwAnd(i1, -i1); c=c+i1\/ii;\n  }\n  dev.copy(png, filename=pf, width=m, height=m); # plot to png-file\n  dev.off(); graphics.off();  # Cleaning\n  cat(\" *** END:\",date(),\"\\n\");\n}\n## Testing samples:\ngpDragonCurve(7, \"red\", \"\", 20, 0.2, -30, -30)\n##gpDragonCurve(11, \"red\", \"\", 10, 0.6, 100, 200)\ngpDragonCurve(13, \"navy\", \"\", 10, 1, 300, -200)\n##gpDragonCurve(15, \"darkgreen\", \"\", 10, 2, -450, -500)\ngpDragonCurve(16, \"darkgreen\", \"\", 10, 3, -1050, -500)\n\n\n","human_summarization":"The code generates a dragon curve fractal, either displaying it directly or writing it to an image file. It uses various algorithms, including recursive, successive approximation, iterative, and Lindenmayer system methods. The recursive method uses right and left curling dragons, while the successive approximation method re-writes each straight line as two new segments at a right angle. The iterative method uses bit-twiddling to determine the direction of the turn at each point. The Lindenmayer system uses two symbols for straight lines and applies expansions. The code also includes a predicate test for determining if a given point or segment is on the curve. Note that the algorithm in R only works for orders <= 16 due to limitations with 32-bit integers.","id":1493}
    {"lang_cluster":"R","source_code":"\nf <- function() {\n    print(\"Guess a number between 1 and 10 until you get it right.\")\n    n <- sample(10, 1)\n    while (as.numeric(readline()) != n) {\n        print(\"Try again.\")\n    }\n    print(\"You got it!\")\n}\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":1494}
    {"lang_cluster":"R","source_code":"\n# From constants built into R:\nletters\n\n# Or generate the same with:\nsapply(97:122, intToUtf8)\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":1495}
    {"lang_cluster":"R","source_code":"\ndec2bin <- function(num) {\n  ifelse(num == 0,\n         0,\n         sub(\"^0+\",\"\",paste(rev(as.integer(intToBits(num))), collapse = \"\"))\n  )\n}\n\nfor (anumber in c(0, 5, 50, 9000)) {\n         cat(dec2bin(anumber),\"\\n\")\n}\n\n0\n101\n110010\n10001100101000\n\n","human_summarization":"generate the binary representation of a given non-negative integer, without leading zeros, whitespace, radix or sign markers. The binary digits are displayed as output, each followed by a newline. The function can utilize built-in radix functions or a user-defined function.","id":1496}
    {"lang_cluster":"R","source_code":"\n# load data from csv files\n# setwd(\"C:\\Temp\\csv\\\")\n# df_patient <- read.csv(file=\"patients.csv\", header = TRUE, sep = \",\")\n# df_visits <- read.csv(file=\"visits.csv\", header = TRUE, sep = \",\", dec = \".\", colClasses=c(\"character\",\"character\",\"numeric\"))\n\n# load data hard coded, create data frames\ndf_patient <- read.table(text = \"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\n\", header = TRUE, sep = \",\") #  character fields so no need for extra parameters colClasses etc.\n\ndf_visits <- read.table(text = \"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\n\", header = TRUE, dec = \".\", sep = \",\", colClasses=c(\"character\",\"character\",\"numeric\"))\n\n# aggregate visit date and scores\ndf_agg <- data.frame(\n  cbind(\n    PATIENT_ID = names(tapply(df_visits$VISIT_DATE, list(df_visits$PATIENT_ID), max, na.rm=TRUE)),\n    last_visit = tapply(df_visits$VISIT_DATE, list(df_visits$PATIENT_ID), max, na.rm=TRUE),\n    score_sum = tapply(df_visits$SCORE, list(df_visits$PATIENT_ID), sum, na.rm=TRUE),\n    score_avg = tapply(df_visits$SCORE, list(df_visits$PATIENT_ID), mean, na.rm=TRUE)\n  )\n) \n\n# merge patients and aggregate dataset\n# all.x = all the non matching cases of df_patient are appended to the result as well (i.e. 'left join')\ndf_result <- merge(df_patient, df_agg, by = 'PATIENT_ID', all.x = TRUE)\n\nprint(df_result)\n\n\n","human_summarization":"\"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file.\"","id":1497}
    {"lang_cluster":"R","source_code":"\ndms_to_rad <- function(d, m, s) (d + m \/ 60 + s \/ 3600) * pi \/ 180\n\n# Volumetric mean radius is 6371 km, see http:\/\/nssdc.gsfc.nasa.gov\/planetary\/factsheet\/earthfact.html\n# The diameter is thus 12742 km\n\ngreat_circle_distance <- function(lat1, long1, lat2, long2) {\n   a <- sin(0.5 * (lat2 - lat1))\n   b <- sin(0.5 * (long2 - long1))\n   12742 * asin(sqrt(a * a + cos(lat1) * cos(lat2) * b * b))\n}\n\n# Coordinates are found here:\n#     http:\/\/www.airport-data.com\/airport\/BNA\/\n#     http:\/\/www.airport-data.com\/airport\/LAX\/\n\ngreat_circle_distance(\n   dms_to_rad(36,  7, 28.10), dms_to_rad( 86, 40, 41.50),   # Nashville International Airport (BNA)\n   dms_to_rad(33, 56, 32.98), dms_to_rad(118, 24, 29.05))  # Los Angeles International Airport (LAX)\n\n# ","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":1498}
    {"lang_cluster":"R","source_code":"\nLibrary: RCurl\nLibrary: XML\n\nlibrary(RCurl)\nwebpage <- getURL(\"http:\/\/rosettacode.org\")\n\n#If you are linking to a page that no longer exists and need to follow the redirect, use followlocation=TRUE\nwebpage <- getURL(\"http:\/\/www.rosettacode.org\", .opts=list(followlocation=TRUE))\n\n#If you are behind a proxy server, you will need to use something like:\nwebpage <- getURL(\"http:\/\/rosettacode.org\", \n   .opts=list(proxy=\"123.123.123.123\", proxyusername=\"domain\\\\username\", proxypassword=\"mypassword\", proxyport=8080))\n#Don't forget that backslashes in your username or password need to be escaped!\n\n\nlibrary(XML)\npagetree <- htmlTreeParse(webpage )\npagetree$children$html\n\n","human_summarization":"Accesses a URL's content and prints it to the console, including parsing the HTML code into a tree structure. Note: This does not cover HTTPS requests.","id":1499}
    {"lang_cluster":"R","source_code":"\n \nis.luhn <- function(cc){\n  numbers <- as.numeric(rev(unlist(strsplit(cc,\"\"))))\n  (sum(numbers[seq(1,length(numbers),by=2)]) + sum({numbers[seq(2,length(numbers),by=2)]*2 ->.;  .%%10 +.%\/%10}))\u00a0%% 10 == 0\n}\n  \nsapply(c(\"49927398716\",\"49927398717\",\"1234567812345678\",\"1234567812345670\"),is.luhn)\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":1500}
    {"lang_cluster":"R","source_code":"\njose <-function(s, r,n){\ny <- 0:(r-1)\n for (i in (r+1):n)\n  y <- (y + s) %% i \n return(y)\n}\n> jose(3,1,41) # r is the number of remained prisoner.\n[1] 30\n\n\nIt is 1-indexed, meaning that we will have a tough time using most solutions that exploit modular arithmetic.\nIt lacks any concept of a linked list, meaning that we can't take a circular list approach.\nThe idiomatic way to roll an array in R (e.g. as the Ruby solution has) is to exploit the head and tail functions, but those break if we are rolling by more than the length of the array (see https:\/\/stackoverflow.com\/q\/18791212 for a few tricks for this).\n\njosephusProblem <- function(n, k, m)\n{\n  prisoners <- 0:(n - 1)\n  exPos <- countToK <- 1\n  dead <- integer(0)\n  while(length(prisoners) > m)\n  {\n    if(countToK == k)\n    {\n      dead <- c(dead, prisoners[exPos])\n      prisoners <- prisoners[-exPos]\n      exPos <- exPos - 1\n    }\n    exPos <- exPos + 1\n    countToK <- countToK + 1\n  if(exPos > length(prisoners)) exPos <- 1\n  if(countToK > k) countToK <- 1\n  }\n  print(paste0(\"Execution order: \", paste0(dead, collapse = \", \"), \".\"))\n  paste0(\"Survivors: \", paste0(prisoners, collapse = \", \"), \".\")\n}\n\n\n","human_summarization":"The code determines the final survivor in the Josephus problem, given a number of prisoners (n) and a step count (k). It also calculates the position of any prisoner in the killing sequence, considering a scenario where multiple survivors (m) can be freed. The code follows the execution process as described, providing the complete killing sequence and the complexity of the operation. It also offers flexibility in numbering the prisoners, either from 0 to n-1 or 1 to n.","id":1501}
    {"lang_cluster":"R","source_code":"\nstrrep(\"ha\", 5)\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":1502}
    {"lang_cluster":"R","source_code":"\n\npattern <- \"string\"\ntext1 <- \"this is a matching string\"\ntext2 <- \"this does not match\"\n\n\ngrep(pattern, c(text1, text2))  # 1\n\n\nregexpr(pattern, c(text1, text2))\n\n[1] 20 -1\nattr(,\"match.length\")\n[1]  6 -1\n\n\ngsub(pattern, \"pair of socks\", c(text1, text2))\n\n[1] \"this is a matching pair of socks\" \"this does not match\"\n\n","human_summarization":"define certain strings, match them against a regular expression using grep and regexpr, returning the indices of matched texts and the positions and lengths of the matches respectively, and substitute part of a string using a regular expression.","id":1503}
    {"lang_cluster":"R","source_code":"\ncat(\"insert number \")\na <- scan(nmax=1, quiet=TRUE)\ncat(\"insert number \")\nb <- scan(nmax=1, quiet=TRUE)\nprint(paste('a+b=', a+b))\nprint(paste('a-b=', a-b))\nprint(paste('a*b=', a*b))\nprint(paste('a%\/%b=', a%\/%b))\nprint(paste('a%%b=', a%%b))\nprint(paste('a^b=', a^b))\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":1504}
    {"lang_cluster":"R","source_code":"\n\ncount = function(haystack, needle)\n   {v = attr(gregexpr(needle, haystack, fixed = T)[[1]], \"match.length\")\n    if (identical(v, -1L)) 0 else length(v)}\n\nprint(count(\"hello\", \"l\"))\n\nLibrary: stringr\nlibrary(stringr)\nprint(str_count(\"hello\", fixed(\"l\")))\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string to be searched and the substring to search for. The function returns an integer count of the occurrences. It does not count overlapping substrings and matches from left-to-right or right-to-left for the highest number of non-overlapping matches. It also supports searching for a fixed string or using a POSIX regular expression or PCRE by specifying the corresponding parameters.","id":1505}
    {"lang_cluster":"R","source_code":"hanoimove <- function(ndisks, from, to, via) {\n  if (ndisks == 1) {\n    cat(\"move disk from\", from, \"to\", to, \"\\n\")\n  } else {\n    hanoimove(ndisks - 1, from, via, to)\n    hanoimove(1, from, to, via)\n    hanoimove(ndisks - 1, via, to, from)\n  }\n}\n\nhanoimove(4, 1, 2, 3)\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":1506}
    {"lang_cluster":"R","source_code":"\n\nchoose(5,3)\n\n\n","human_summarization":"calculate any binomial coefficient, specifically able to output the binomial coefficient of 5 choose 3 which equals 10. The calculation is based on the provided formula. It also includes tasks related to combinations and permutations, both with and without replacement. The code uses R's built-in choose() function to evaluate binomial coefficients.","id":1507}
    {"lang_cluster":"R","source_code":"\nLibrary: pixmap\n# Conversion from Grey to RGB uses the following code\nsetAs(\"pixmapGrey\", \"pixmapRGB\",\nfunction(from, to){\n    z = new(to, as(from, \"pixmap\"))\n    z@red = from@grey\n    z@green = from@grey\n    z@blue = from@grey\n    z@channels = c(\"red\", \"green\", \"blue\")\n    z\n})\n\n# Conversion from RGB to grey uses built-in coefficients of 0.3, 0.59, 0.11.  To see this, type\ngetMethods(addChannels)\n\n# We can override this behaviour with\nsetMethod(\"addChannels\", \"pixmapRGB\",\nfunction(object, coef=NULL){\n    if(is.null(coef)) coef = c(0.2126, 0.7152, 0.0722)\n    z = new(\"pixmapGrey\", object)\n    z@grey = coef[1] * object@red + coef[2] * object@green +\n        coef[3] * object@blue\n    z@channels = \"grey\"\n    z\n})\n\n# Colour image\nplot(p1 <- pixmapRGB(c(c(1,0,0,0,0,1), c(0,1,0,0,1,0), c(0,0,1,1,0,0)), nrow=6, ncol=6))\n\n#Convert to grey\nplot(p2 <- as(p1, \"pixmapGrey\"))\n\n# Convert back to \"colour\"\nplot(p3 <- as(p2, \"pixmapRGB\"))\n\n","human_summarization":"extend the data storage type to support grayscale images, define operations to convert a color image to grayscale and vice versa using the CIE recommended formula for luminance, and ensure no rounding errors or distorted results occur when storing calculated luminance as an unsigned integer.","id":1508}
    {"lang_cluster":"R","source_code":"\nLibrary: gWidgets\n\nrotate_string <- function(x, forwards) \n{ \n\u00a0 \u00a0nchx <- nchar(x) \n\u00a0 \u00a0if(forwards) \n\u00a0 \u00a0{ \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \n\u00a0 \u00a0 \u00a0 paste(substr(x, nchx, nchx), substr(x, 1, nchx - 1), sep = \"\") \n\u00a0 \u00a0} else \n\u00a0 \u00a0{ \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \n\u00a0 \u00a0 \u00a0 paste(substr(x, 2, nchx), substr(x, 1, 1), sep = \"\") \n\u00a0 \u00a0} \n}\n\nhandle_rotate_label <- function(obj, interval = 100)\n{\n\u00a0 addHandlerIdle(obj,\n\u00a0\u00a0\u00a0 handler = function(h, ...)\n\u00a0\u00a0\u00a0 {\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 svalue(obj) <- rotate_string(svalue(obj), tag(obj, \"forwards\"))\n\u00a0\u00a0\u00a0 },\n\u00a0\u00a0\u00a0 interval = interval\n\u00a0 )\n}\n\nhandle_change_direction_on_click <- function(obj)\n{\n\u00a0 addHandlerClicked(obj,\n\u00a0\u00a0\u00a0 handler = function(h, ...)\n\u00a0\u00a0\u00a0 {\n\u00a0\u00a0\u00a0\u00a0\u00a0 tag(h$obj, \"forwards\") <- !tag(h$obj, \"forwards\")\n\u00a0\u00a0\u00a0 }\n\u00a0 )\n}\n\nlibrary(gWidgets)\nlibrary(gWidgetstcltk) #or library(gWidgetsRGtk2)\u00a0or library(gWidgetsrJava)\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \nlab <- glabel(\"Hello World! \", container = gwindow()) \u00a0\ntag(lab, \"forwards\") <- TRUE \nhandle_rotate_label(lab) \nhandle_change_direction_on_click(lab)\n\n","human_summarization":"Create a GUI window displaying a rotating \"Hello World!\" text. The rotation direction of the text changes when the user clicks on it. The rotation and direction change are handled by two separate handlers. The text flow direction is stored as an attribute of the label using the tag function.","id":1509}
    {"lang_cluster":"R","source_code":"\ni <- 0\nrepeat\n{\n   i <- i + 1\n   print(i)\n   if(i\u00a0%% 6 == 0) break\n}\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":1510}
    {"lang_cluster":"R","source_code":"\na <- \"m\\u00f8\\u00f8se\"\nprint(nchar(a, type=\"bytes\"))  # print 7\nprint(nchar(a, type=\"chars\"))  # print 5\n","human_summarization":"calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.","id":1511}
    {"lang_cluster":"R","source_code":"\n\nfisheryatesshuffle <- function(n)\n{\n  pool <- seq_len(n)\n  a <- c()\n  while(length(pool) > 0)\n  {\n     k <- sample.int(length(pool), 1)\n     a <- c(a, pool[k])\n     pool <- pool[-k]\n  }\n  a\n}\nfisheryatesknuthshuffle <- function(n)\n{\n   a <- seq_len(n)\n   while(n >=2)\n   {     \n      k <- sample.int(n, 1)\n      if(k\u00a0!= n)\n      {\n         temp <- a[k]\n         a[k] <- a[n]\n         a[n] <- temp\n      }\n      n <- n - 1\n   }\n   a\n}\n\n#Example usage: \nfisheryatesshuffle(6)                # e.g. 1 3 6 2 4 5\nx <- c(\"foo\", \"bar\", \"baz\", \"quux\")\nx[fisheryatesknuthshuffle(4)]        # e.g. \"bar\"  \"baz\"  \"quux\" \"foo\"\n\nknuth <- function(vec)\n{\n  last <- length(vec)\n  if(last >= 2)\n  {\n    for(i in last:2)\n    {\n      j <- sample(seq_len(i), size = 1)\n      vec[c(i, j)] <- vec[c(j, i)]\n    }\n  }\n  vec\n}\n#Demonstration:\nknuth(integer(0))\nknuth(c(10))\nreplicate(10, knuth(c(10, 20)))\nreplicate(10, knuth(c(10, 20, 30)))\nknuth(c(\"Also\", \"works\", \"for\", \"strings\"))\n\n","human_summarization":"implement the Knuth shuffle algorithm, also known as the Fisher-Yates shuffle. This algorithm randomly shuffles the elements of an array. It operates by iterating from the last index to the first, selecting a random integer within the current range, and swapping the current element with the element at the random index. The algorithm modifies the input array in-place, but can be adjusted to return a new array or to iterate from left to right if necessary.","id":1512}
    {"lang_cluster":"R","source_code":"\nyear = commandArgs(T)\nd = as.Date(paste0(year, \"-01-01\"))\nfridays = d + seq(by = 7,\n    (5 - as.POSIXlt(d)$wday) %% 7,\n    364 + (months(d + 30 + 29) == \"February\"))\nmessage(paste(collapse = \"\\n\", fridays[tapply(\n    seq_along(fridays), as.POSIXlt(fridays)$mon, max)]))\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":1513}
    {"lang_cluster":"R","source_code":"\ncat(\"Goodbye, world!\")\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":1514}
    {"lang_cluster":"R","source_code":"\nlibrary(gWidgets)\noptions(guiToolkit=\"RGtk2\") ## using gWidgtsRGtk2\n\nw <- gwindow(\"Enter a string and a number\")\nlyt <- glayout(cont=w)\nlyt[1,1] <- \"Enter a string\"\nlyt[1,2] <- gedit(\"\", cont=lyt)\nlyt[2,1] <- \"Enter 75000\"\nlyt[2,2] <- gedit(\"\", cont=lyt)\nlyt[3,2] <- gbutton(\"validate\", cont=lyt, handler=function(h,...) {\n  txt <- svalue(lyt[1,2])\n  x <- svalue(lyt[2,2])\n  x <- gsub(\",\", \"\", x)\n  x <- as.integer(x)\n\n  if(nchar(txt) > 0 && x == 75000)\n    gmessage(\"Congratulations, you followed directions\", parent=w)\n  else\n    gmessage(\"You failed this simple task\", parent=w)\n})\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":1515}
    {"lang_cluster":"R","source_code":"\n\n# based on Rot-13 solution: http:\/\/rosettacode.org\/wiki\/Rot-13#R\nceasar <- function(x, key)\n{\n  # if key is negative, wrap to be positive\n  if (key < 0) {\n    key <- 26 + key \n  }\n  \n  old <- paste(letters, LETTERS, collapse=\"\", sep=\"\")\n  new <- paste(substr(old, key * 2 + 1, 52), substr(old, 1, key * 2), sep=\"\")\n  chartr(old, new, x)\n}\n\n# simple examples from description\nprint(ceasar(\"hi\",2))\nprint(ceasar(\"hi\",20))\n\n# more advanced example\nkey <- 3\nplaintext <- \"The five boxing wizards jump quickly.\"\ncyphertext <- ceasar(plaintext, key)\ndecrypted <- ceasar(cyphertext, -key)\n\nprint(paste(\"    Plain Text: \", plaintext, sep=\"\"))\nprint(paste(\"   Cypher Text: \", cyphertext, sep=\"\"))\nprint(paste(\"Decrypted Text: \", decrypted, sep=\"\"))\n\n","human_summarization":"implement a Caesar cipher for both encoding and decoding. The key for the cipher is an integer between 1 and 25 and it rotates the letters of the alphabet either left or right. The cipher replaces each letter with the next 1st to 25th letter in the alphabet, wrapping Z to A. The cipher is vulnerable to frequency analysis or brute force attacks. It is identical to Vigen\u00e8re cipher with a key length of 1 and Rot-13 with a key of 13.","id":1516}
    {"lang_cluster":"R","source_code":"\n\"%gcd%\" <- function(u, v) {ifelse(u %% v != 0, v %gcd% (u%%v), v)}\n\n\"%lcm%\" <- function(u, v) { abs(u*v)\/(u %gcd% v)}\n\nprint (50 %lcm% 75)\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":1517}
    {"lang_cluster":"R","source_code":"\n\n8 * .Machine$sizeof.long # e.g. 32\n\n\n.Platform$endian         # e.g. \"little\"\n\n","human_summarization":"The code prints the word size and endianness of the host machine.","id":1518}
    {"lang_cluster":"R","source_code":"\nlibrary(rvest)\nlibrary(dplyr)\noptions(stringsAsFactors=FALSE)\n\n# getting the required table from the rosetta website\nlangUrl <- \"https:\/\/rosettacode.org\/wiki\/Rosetta_Code\/Rank_languages_by_popularity\/Full_list\"\nlangs <- read_html(langUrl) %>%\n  html_nodes(xpath='\/html\/body\/div\/div\/div[1]\/div[3]\/main\/div[2]\/div[3]\/div[1]\/table') %>%\n  html_table() %>% \n  data.frame() %>%\n  select(c(\"Rank\",\"TaskEntries\",\"Language\"))\n\n\n # changing the columns to required format\nlangs$Rank = paste(\"Rank: \",langs$Rank)\nlangs$TaskEntries = paste0(\"(\", format(langs$TaskEntries, big.mark = \",\")\n                           ,\" entries\", \")\")\n\nnames(langs) <- NULL\n\nlangs[1:10,]\n\n\nOutput (as of October, 24, 2022):\n1   Rank:  1 (1,589 entries)   Phix\n2   Rank:  1 (1,589 entries)   Wren\n3   Rank:  3 (1,552 entries)  Julia\n4   Rank:  4 (1,535 entries)   Raku\n5   Rank:  5 (1,500 entries)     Go\n6   Rank:  6 (1,485 entries)   Perl\n7   Rank:  7 (1,422 entries) Python\n8   Rank:  8 (1,402 entries)    Nim\n9   Rank:  9 (1,293 entries)      J\n10 Rank:  10 (1,213 entries)      C\n\n","human_summarization":"sort the most popular computer programming languages based on the number of members in Rosetta Code categories. It fetches data either through web scraping or using the API method. The code also has the functionality to filter incorrect results. The final output is a ranked list of all programming languages.","id":1519}
    {"lang_cluster":"R","source_code":"\na <- list(\"First\", \"Second\", \"Third\", 5, 6)\nfor(i in a) print(i)\n","human_summarization":"Iterates through each element in a collection in order and prints it, using a \"for each\" loop or another loop if \"for each\" is not available in the language.","id":1520}
    {"lang_cluster":"R","source_code":"\ntext <- \"Hello,How,Are,You,Today\"\njunk <- strsplit(text, split=\",\")\nprint(paste(unlist(junk), collapse=\".\"))\n\npaste(unlist(strsplit(text, split=\",\")), collapse=\".\")\n","human_summarization":"\"Tokenizes a string by separating it into an array based on commas, then displays the words to the user separated by a period, with a trailing period for simplicity.\"","id":1521}
    {"lang_cluster":"R","source_code":"\n\n\"%gcd%\" <- function(u, v) {\n  ifelse(u\u00a0%% v\u00a0!= 0, v %gcd% (u%%v), v)\n}\n\n\"%gcd%\" <- function(v, t) {\n  while ( (c <- v%%t)\u00a0!= 0 ) {\n    v <- t\n    t <- c\n  }\n  t\n}\n\n","human_summarization":"find the greatest common divisor (GCD), also known as the greatest common factor (gcf) and greatest common measure, of two integers. This can be achieved through either recursive or iterative methods. The code also relates to the task of finding the least common multiple.","id":1522}
    {"lang_cluster":"R","source_code":"\n> strings <- c(\"152\", \"-3.1415926\", \"Foo123\")\n> suppressWarnings(!is.na(as.numeric(strings)))\n[1]  TRUE  TRUE FALSE\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":1523}
    {"lang_cluster":"R","source_code":"\nLibrary: RCurl\nLibrary: XML\n\nlibrary(RCurl)\nwebpage <- getURL(\"https:\/\/sourceforge.net\/\", .opts=list(followlocation=TRUE, ssl.verifyhost=FALSE, ssl.verifypeer=FALSE))\n\n\nwp <- readLines(tc <- textConnection(webpage))\nclose(tc)\n\n\npagetree <- htmlTreeParse(wp)\npagetree$children$html\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, print the obtained resource to the console, and process the unprocessed characters in the webpage output. No authentication is performed in this task.","id":1524}
    {"lang_cluster":"R","source_code":"\ndeg <- function(radians) 180*radians\/pi\nrad <- function(degrees) degrees*pi\/180\nsind <- function(ang) sin(rad(ang))\ncosd <- function(ang) cos(rad(ang))\ntand <- function(ang) tan(rad(ang))\nasind <- function(v) deg(asin(v))\nacosd <- function(v) deg(acos(v))\natand <- function(v) deg(atan(v))\n\nr <- pi\/3\nrd <- deg(r)\n\nprint( c( sin(r), sind(rd)) )\nprint( c( cos(r), cosd(rd)) )\nprint( c( tan(r), tand(rd)) )\n\nS <- sin(pi\/4)\nC <- cos(pi\/3)\nT <- tan(pi\/4)\n\nprint( c( asin(S), asind(S) ) )\nprint( c( acos(C), acosd(C) ) )\nprint( c( atan(T), atand(T) ) )\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":1525}
    {"lang_cluster":"R","source_code":"\n\nlibrary(tidyverse)\nlibrary(rvest)\n\ntask_html= read_html(\"http:\/\/rosettacode.org\/wiki\/Knapsack_problem\/Bounded\")\ntask_table= html_nodes(html, \"table\")[[1]] %>%\n  html_table(table, header= T, trim= T) %>%\n  set_names(c(\"items\", \"weight\", \"value\", \"pieces\")) %>%\n  filter(items != \"knapsack\") %>%\n  mutate(weight= as.numeric(weight),\n         value= as.numeric(value),\n         pieces= as.numeric(pieces))\n\n\nlibrary(rgenoud)\n\nfitness= function(x= rep(1, nrow(task_table))){\n  total_value= sum(task_table$value * x)\n  total_weight= sum(task_table$weight * x)\n  ifelse(total_weight <= 400, total_value, 400-total_weight)\n}\n\nallowed= matrix(c(rep(0, nrow(task_table)), task_table$pieces), ncol = 2)\nset.seed(42)\nevolution= genoud(fn= fitness, \n                  nvars= nrow(allowed), \n                  max= TRUE,\n                  pop.size= 10000,\n                  data.type.int= TRUE, \n                  Domains= allowed)\n\ncat(\"Value: \", evolution$value, \"\\n\")\ncat(\"Weight:\", sum(task_table$weight * evolution$par), \"dag\", \"\\n\")\ndata.frame(item= task_table$items, pieces= as.integer(solution)) %>%\n  filter(solution> 0)\n\n\n","human_summarization":"\"Implement a solution for the Knapsack problem using a genetic algorithm. The code reads in a list of potential items for a tourist's trip, each with a specific weight, value, and quantity available. It then determines the optimal combination of items to maximize the total value without exceeding a total weight of 4 kg. The items cannot be divided, only whole units can be taken.\"","id":1526}
    {"lang_cluster":"R","source_code":"\ns = \"12345\"\ns <- as.character(as.numeric(s) + 1)\n","human_summarization":"\"Increments a given numerical string.\"","id":1527}
    {"lang_cluster":"R","source_code":"\nget_common_dir <- function(paths, delim = \"\/\")\n{\n  path_chunks <- strsplit(paths, delim)\n  \n  i <- 1\n  repeat({\n    current_chunk <- sapply(path_chunks, function(x) x[i])\n    if(any(current_chunk != current_chunk[1])) break\n    i <- i + 1\n  })\n  paste(path_chunks[[1]][seq_len(i - 1)], collapse = delim)\n\n}\n\n# Example Usage:\npaths <- c(\n  '\/home\/user1\/tmp\/coverage\/test',\n  '\/home\/user1\/tmp\/covert\/operator',\n  '\/home\/user1\/tmp\/coven\/members')\n\nget_common_dir(paths)           # \"\/home\/user1\/tmp\"\n\n","human_summarization":"The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '\/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.","id":1528}
    {"lang_cluster":"R","source_code":"\n\nsattolo <- function(vec)\n{\n  last <- length(vec)\n  if(last >= 2)\n  {\n    for(i in last:2)\n    {\n      j <- sample(seq_len(i - 1), size = 1)\n      vec[c(i, j)] <- vec[c(j, i)]\n    } \n  }\n  vec\n}\n#Demonstration:\nsattolo(integer(0))\nsattolo(c(10))\nreplicate(10, sattolo(c(10, 20)))\nreplicate(10, sattolo(c(10, 20, 30)))\nsattolo(c(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22))\nsattolo(c(\"Also\", \"works\", \"for\", \"strings\"))\n\n\n","human_summarization":"Implement the Sattolo cycle algorithm, which randomly shuffles an array ensuring each element ends up in a new position. The algorithm modifies the input array in-place or returns a new shuffled array. It differs from the Knuth shuffle by choosing 'j' from the range 0 \u2264 j < i, ensuring no element remains in its original position.","id":1529}
    {"lang_cluster":"R","source_code":"\nomedian <- function(v) {\n  if ( length(v) < 1 )\n    NA\n  else {\n    sv <- sort(v)\n    l <- length(sv)\n    if ( l %% 2 == 0 )\n      (sv[floor(l\/2)+1] + sv[floor(l\/2)])\/2\n    else\n      sv[floor(l\/2)+1]\n  }\n}\n\na <- c(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)\nb <- c(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)\n\nprint(median(a))   # 4.4\nprint(omedian(a))\nprint(median(b))   # 4.25\nprint(omedian(b))\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles cases with an even number of elements by returning the average of the two middle values. It uses the selection algorithm for efficient computation. It also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. The code uses R's built-in median function.","id":1530}
    {"lang_cluster":"R","source_code":"\nxx <- x <- 1:100\nxx[x\u00a0%% 3 == 0] <- \"Fizz\"\nxx[x\u00a0%% 5 == 0] <- \"Buzz\"\nxx[x\u00a0%% 15 == 0] <- \"FizzBuzz\"\nxx\n\nxx <- rep(\"\", 100)\nx <- 1:100\nxx[x\u00a0%% 3 == 0] <- paste0(xx[x\u00a0%% 3 == 0], \"Fizz\")\nxx[x\u00a0%% 5 == 0] <- paste0(xx[x\u00a0%% 5 == 0], \"Buzz\")\nxx[xx == \"\"] <- x[xx == \"\"]\nxx\n\nx <- paste0(rep(\"\", 100), c(\"\", \"\", \"Fizz\"), c(\"\", \"\", \"\", \"\", \"Buzz\"))\ncat(ifelse(x == \"\", 1:100, x), sep = \"\\n\")\n\nx <- paste0(rep(\"\", 100), rep(c(\"\", \"Fizz\"), times = c(2, 1)), rep(c(\"\", \"Buzz\"), times = c(4, 1)))\ncat(ifelse(x == \"\", 1:100, x), sep = \"\\n\")\n\nx <- 1:100\nifelse(x\u00a0%% 15 == 0, 'FizzBuzz',\n       ifelse(x\u00a0%% 5 == 0, 'Buzz',\n              ifelse(x\u00a0%% 3 == 0, 'Fizz', x)))\n\nnamedNums <- c(Fizz = 3, Buzz = 5)\nfor(i in 1:100)\n{\n  isFactor <- i\u00a0%% namedNums == 0\n  print(if(any(isFactor)) paste0(names(namedNums)[isFactor], collapse = \"\") else i)\n}\n","human_summarization":"\"Output integers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.\"","id":1531}
    {"lang_cluster":"R","source_code":"\niterate.until.escape <- function(z, c, trans, cond, max=50, response=dwell) {\n  #we iterate all active points in the same array operation,\n  #and keeping track of which points are still iterating.\n  active <- seq_along(z)\n  dwell <- z\n  dwell[] <- 0\n  for (i in 1:max) {\n    z[active] <- trans(z[active], c[active]);\n    survived <- cond(z[active])\n    dwell[active[!survived]] <- i\n    active <- active[survived]\n    if (length(active) == 0) break\n  }\n  eval(substitute(response))\n}\n\nre = seq(-2, 1, len=500)\nim = seq(-1.5, 1.5, len=500)\nc <- outer(re, im, function(x,y) complex(real=x, imaginary=y))\nx <- iterate.until.escape(array(0, dim(c)), c,\n                          function(z,c)z^2+c, function(z)abs(z) <= 2,\n                          max=100)\nimage(x)\n\n#install.packages(\"caTools\") # install external package (if missing)\nlibrary(caTools)             # external package providing write.gif function\njet.colors <- colorRampPalette(c(\"red\", \"blue\", \"#007FFF\", \"cyan\", \"#7FFF7F\",\n                                 \"yellow\", \"#FF7F00\", \"red\", \"#7F0000\"))\ndx <- 800                    # define width\ndy <- 600                    # define height\nC  <- complex(real = rep(seq(-2.5, 1.5, length.out = dx), each = dy),\n              imag = rep(seq(-1.5, 1.5, length.out = dy), dx))\nC <- matrix(C, dy, dx)       # reshape as square matrix of complex numbers\nZ <- 0                       # initialize Z to zero\nX <- array(0, c(dy, dx, 20)) # initialize output 3D array\nfor (k in 1:20) {            # loop with 20 iterations\n  Z <- Z^2 + C               # the central difference equation\n  X[, , k] <- exp(-abs(Z))   # capture results\n}\nwrite.gif(X, \"Mandelbrot.gif\", col = jet.colors, delay = 100)\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. The code also includes a modified Mandelbrot set animation by Jarek Tuszynski, PhD.","id":1532}
    {"lang_cluster":"R","source_code":"\ntotal <- sum(1:5)\nproduct <- prod(1:5)\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":1533}
    {"lang_cluster":"R","source_code":"\nisLeapYear <- function(year) {\n    ifelse(year%%100==0, year%%400==0, year%%4==0)\n}\n\nfor (y in c(1900, 1994, 1996, 1997, 2000)) {\n  cat(y, ifelse(isLeapYear(y), \"is\", \"isn't\"), \"a leap year.\\n\")\n}\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":1534}
    {"lang_cluster":"R","source_code":"\n\nallPermutations <- setNames(expand.grid(seq(2, 7, by = 2), 1:7, 1:7), c(\"Police\", \"Sanitation\", \"Fire\"))\nsolution <- allPermutations[which(rowSums(allPermutations)==12 & apply(allPermutations, 1, function(x) !any(duplicated(x)))),]\nsolution <- solution[order(solution$Police, solution$Sanitation),]\nrow.names(solution) <- paste0(\"Solution #\", seq_len(nrow(solution)), \":\")\nprint(solution)\n\n\n","human_summarization":"generate all unique combinations of numbers between 1 and 7 for three city departments (police, sanitation, fire) such that the sum of the numbers is 12 and the police department number is even.","id":1535}
    {"lang_cluster":"R","source_code":"\n\nstr1 <- \"abc\"\nstr2 <- str1\n","human_summarization":"distinguish between copying a string by value versus creating an additional reference to an existing string.","id":1536}
    {"lang_cluster":"R","source_code":"\nF <- function(n) ifelse(n == 0, 1, n - M(F(n-1)))\nM <- function(n) ifelse(n == 0, 0, n - F(M(n-1)))\n\nprint.table(lapply(0:19, M))\nprint.table(lapply(0:19, F))\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":1537}
    {"lang_cluster":"R","source_code":"\n# a vector (letters are builtin)\nletters\n#  [1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\" \"k\" \"l\" \"m\" \"n\" \"o\" \"p\" \"q\" \"r\" \"s\"\n# [20] \"t\" \"u\" \"v\" \"w\" \"x\" \"y\" \"z\"\n\n# picking one element\nsample(letters, 1)\n# [1] \"n\"\n\n# picking some elements with repetition, and concatenating to get a word\npaste(sample(letters, 10, rep=T), collapse=\"\")\n# [1] \"episxgcgmt\"\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":1538}
    {"lang_cluster":"R","source_code":"\nURLdecode(\"http%3A%2F%2Ffoo%20bar%2F\")\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":1539}
    {"lang_cluster":"R","source_code":"\n\nBinSearch <- function(A, value, low, high) {\n  if ( high < low ) {\n    return(NULL)\n  } else {\n    mid <- floor((low + high) \/ 2)\n    if ( A[mid] > value )\n      BinSearch(A, value, low, mid-1)\n    else if ( A[mid] < value )\n      BinSearch(A, value, mid+1, high)\n    else\n      mid\n  }\n}\n\nIterBinSearch <- function(A, value) {\n  low = 1\n  high = length(A)\n  i = 0\n  while ( low <= high ) {\n    mid <- floor((low + high)\/2)\n    if ( A[mid] > value )\n      high <- mid - 1\n    else if ( A[mid] < value )\n      low <- mid + 1\n    else\n      return(mid)\n  }\n  NULL\n}\n\na <- 1:100\nIterBinSearch(a, 50)\nBinSearch(a, 50, 1, length(a)) # output 50\nIterBinSearch(a, 101) # outputs NULL\n","human_summarization":"The code implements a binary search algorithm that can be either recursive or iterative. It searches for a specific number in a sorted integer array, given a starting and ending point of a range, and a \"secret value\". It prints out whether the number was found in the array and its index if found. The code also handles multiple values equal to the given value and indicates whether the element was found or not. It includes traditional, leftmost insertion point, and rightmost insertion point binary search algorithms. It also ensures no overflow bugs occur during the calculation of the mid-point.","id":1540}
    {"lang_cluster":"R","source_code":"\n\nR CMD BATCH --vanilla --slave '--args a=1 b=c(2,5,6)' test.r test.out\n\n\n# Read the commandline arguments\nargs <- (commandArgs(TRUE))\n\n# args is now a list of character vectors\n# First check to see if any arguments were passed,\n# then evaluate each argument.\nif (length(args)==0) {\n    print(\"No arguments supplied.\")\n    # Supply default values\n    a <- 1\n    b <- c(1,1,1)\n} else {\n    for (i in 1:length(args)) {\n         eval(parse(text=args[[i]]))\n    }\n}\nprint(a*2)\nprint(b*3)\n\n\n[1] 2\n[1]  6 15 18\n> proc.time()\n   user  system elapsed \n  0.168   0.026   0.178 \n\n\nsent to stdout (i.e., as is normal with shell scripts)\ndone without the profiling\n\n","human_summarization":"Code summarization: The code retrieves and prints the list of command-line arguments given to the program. It also intelligently parses these arguments. An example command line is provided. The code also includes a script test.r that accepts arguments and redirects output to test.out.","id":1541}
    {"lang_cluster":"R","source_code":"\nlibrary(DescTools)\n\npendulum<-function(length=5,radius=1,circle.color=\"white\",bg.color=\"white\"){\n  tseq = c(seq(0,pi,by=.1),seq(pi,0,by=-.1))\n  slow=.27;fast=.07\n  sseq = c(seq(slow,fast,length.out = length(tseq)\/4),seq(fast,slow,length.out = length(tseq)\/4),seq(slow,fast,length.out = length(tseq)\/4),seq(fast,slow,length.out = length(tseq)\/4))\n  plot(0,0,xlim=c((-length-radius)*1.2,(length+radius)*1.2),ylim=c((-length-radius)*1.2,0),xaxt=\"n\",yaxt=\"n\",xlab=\"\",ylab=\"\")\n  cat(\"Press Esc to end animation\")\n\n  while(T){\n    for(i in 1:length(tseq)){\n      rect(par(\"usr\")[1],par(\"usr\")[3],par(\"usr\")[2],par(\"usr\")[4],col = bg.color)\n      abline(h=0,col=\"grey\")\n      points(0,0)\n      DrawCircle((radius+length)*cos(tseq[i]),(radius+length)*-sin(tseq[i]),r.out=radius,col=circle.color)\n      lines(c(0,length*cos(tseq[i])),c(0,length*-sin(tseq[i])))\n      Sys.sleep(sseq[i])\n    }\n  }\n  \n}\n\npendulum(5,1,\"gold\",\"lightblue\")\n\n","human_summarization":"create and animate a simple physical model of a gravity pendulum.","id":1542}
    {"lang_cluster":"R","source_code":"\nlibrary(rjson)\ndata <- fromJSON('{ \"foo\": 1, \"bar\": [10, \"apples\"] }')\ndata\n\ndata\n$foo\n[1] 1\n\n$bar\n$bar[[1]]\n[1] 10\n\n$bar[[2]]\n[1] \"apples\"\n\ncat(toJSON(data))\n\n{\"foo\":1,\"bar\":[10,\"apples\"]}\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":1543}
    {"lang_cluster":"R","source_code":"\nnthroot <- function(A, n, tol=sqrt(.Machine$double.eps))\n{\n   ifelse(A < 1, x0 <- A * n, x0 <- A \/ n)\n   repeat\n   {\n      x1 <- ((n-1)*x0 + A \/ x0^(n-1))\/n\n      if(abs(x1 - x0) > tol) x0 <- x1 else break\n   }\n   x1\n}\nnthroot(7131.5^10, 10)   # 7131.5\nnthroot(7, 0.5)          # 49\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":1544}
    {"lang_cluster":"R","source_code":"\n\nSys.info()[[\"nodename\"]]\n\n\nsystem(\"hostname\", intern = TRUE)\n\n\nenv_var <- ifelse(.Platform$OS.type == \"windows\", \"COMPUTERNAME\", \"HOSTNAME\") \nSys.getenv(env_var)\n\n","human_summarization":"retrieve the hostname of the system where the R routine is running using the Sys.info function. It also provides alternative methods to get the hostname by calling an OS command or retrieving an environment variable, considering Sys.info might not be available on all platforms.","id":1545}
    {"lang_cluster":"R","source_code":"\nleonardo_numbers <- function(add = 1, l0 = 1, l1 = 1, how_many = 25) {\n\tresult <- c(l0, l1)\n\tfor (i in 3:how_many) \n\t\tresult <- append(result, result[[i - 1]] + result[[i - 2]] + add)\n\tresult\n}\ncat(\"First 25 Leonardo numbers\\n\")\ncat(leonardo_numbers(), \"\\n\")\n\ncat(\"First 25 Leonardo numbers from 0, 1 with add number = 0\\n\")\ncat(leonardo_numbers(0, 0, 1), \"\\n\")\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":1546}
    {"lang_cluster":"R","source_code":"\n\ntwenty.four <- function(operators=c(\"+\", \"-\", \"*\", \"\/\", \"(\"),\n                        selector=function() sample(1:9, 4, replace=TRUE),\n                        arguments=selector(),\n                        goal=24) {\n  newdigits <- function() {\n    arguments <<- selector()\n    cat(\"New digits:\", paste(arguments, collapse=\", \"), \"\\n\")\n  } \n  help <- function() cat(\"Make\", goal,\n      \"out of the numbers\",paste(arguments, collapse=\", \"),\n      \"and the operators\",paste(operators, collapse=\", \"), \".\",\n      \"\\nEnter 'q' to quit, '!' to select new digits,\",\n      \"or '?' to repeat this message.\\n\")\n  help()\n  repeat {\n    switch(input <- readline(prompt=\"> \"),\n           q={ cat(\"Goodbye!\\n\"); break },\n           `?`=help(),\n           `!`=newdigits(),\n           tryCatch({\n             expr <- parse(text=input, n=1)[[1]]\n             check.call(expr, operators, arguments)\n             result <- eval(expr)\n             if (isTRUE(all.equal(result, goal))) {\n               cat(\"Correct!\\n\")\n               newdigits()\n             } else {\n               cat(\"Evaluated to\", result, \"( goal\", goal, \")\\n\")\n             }\n           },error=function(e) cat(e$message, \"\\n\")))\n  }\n}\n\ncheck.call <- function(expr, operators, arguments) {\n  unexpr <- function(x) {\n    if (is.call(x))\n      unexpr(as.list(x))\n    else if (is.list(x))\n      lapply(x,unexpr)\n    else x\n  }\n  leaves <- unlist(unexpr(expr))\n  if (any(disallowed <-\n          !leaves %in% c(lapply(operators, as.name),\n                         as.list(arguments)))) {\n    stop(\"'\", paste(sapply(leaves[disallowed], as.character),\n                    collapse=\", \"),\n         \"' not allowed. \")\n  }\n  numbers.used <- unlist(leaves[sapply(leaves, mode) == 'numeric'])\n  \n  if (! isTRUE(all.equal(sort(numbers.used), sort(arguments))))\n   stop(\"Must use each number once.\")\n}\n\n\n> twenty.four()\n\nMake 24 out of the numbers 1, 6, 7, 5 and the operators +, -, *, \/, ( . \nEnter 'q' to quit, '!' to select new digits, or '?' to repeat this message.\n> 6*(5-1)\nMust use each number once. \n> 1 + 6*5 - 7\nCorrect!\nNew digits: 7, 2, 9, 3 \n> (7+9)\/2*3\nCorrect!\nNew digits: 1, 4, 1, 7 \n> 4*(7-1)\nMust use each number once. \n> (7-1)*4*1\nCorrect!\nNew digits: 1, 5, 2, 8 \n> (5-1)^2+8\n'^' not allowed.\n> !\nNew digits: 2, 8, 5, 2 \n> 52-28\n'52, 28' not allowed.\n> (8-2)*(5-2\/2)\nMust use each number once. \n> (8+2)*2+5\nEvaluated to 25 ( goal 24 )\n> q\nGoodbye!\n\n","human_summarization":"The code generates four random digits from 1 to 9 and prompts the player to form an arithmetic expression using all four digits exactly once. The code then evaluates the expression to check if it equals 24. The allowed operations are multiplication, division, addition, and subtraction with division preserving remainders. The formation of multiple digit numbers from the given digits is not allowed. The code also supports the use of brackets if an infix expression evaluator is used. The type of expression evaluator used is not specified and the code does not generate or test the possibility of the expression.","id":1547}
    {"lang_cluster":"R","source_code":"\n\nrunlengthencoding <- function(x)\n{\n   splitx <- unlist(strsplit(input, \"\"))\n   rlex <- rle(splitx)\n   paste(with(rlex, as.vector(rbind(lengths, values))), collapse=\"\")\n}\n\ninput <- \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\nrunlengthencoding(input)\n\ninverserunlengthencoding <- function(x)\n{\n    lengths <- as.numeric(unlist(strsplit(output, \"[[:alpha:]]\")))\n    values <- unlist(strsplit(output, \"[[:digit:]]\"))\n    values <- values[values\u00a0!= \"\"]\n    uncompressed <- inverse.rle(list(lengths=lengths, values=values))\n    paste(uncompressed, collapse=\"\")\n}\n\noutput <- \"12W1B12W3B24W1B14W\"\ninverserunlengthencoding(output)\n","human_summarization":"implement a run-length encoding algorithm that compresses repeated runs of the same uppercase character in a string by storing the length of the run. It also includes a function to reverse the compression. The output can be used to recreate the original input string. The encoding step is similar to the Look-and-say sequence. The code also includes built-in functions for run length encoding and decompression in R programming language.","id":1548}
    {"lang_cluster":"R","source_code":"\nhello <- \"hello\"\npaste(hello, \"literal\") # \"hello literal\"\nhl <- paste(hello, \"literal\") #saves concatenates string to a new variable\npaste(\"no\", \"spaces\", \"between\", \"words\", sep=\"\") # \"nospacesbetweenwords\"\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":1549}
    {"lang_cluster":"R","source_code":"\n\nURLencode(\"http:\/\/foo bar\/\")\n\n\nlibrary(RCurl)\ncurlEscape(\"http:\/\/foo bar\/\")\n\n","human_summarization":"The code provides a function to convert a given string into its URL encoding representation. It converts special, control, and extended characters into a percent symbol followed by a two-digit hexadecimal code. It allows for exceptions, preserving certain characters as per different standards like RFC 3986, HTML 5, and encodeURI function in Javascript. The function also supports lowercase escapes and encoding space to \"+\".","id":1550}
    {"lang_cluster":"R","source_code":"\n\nknapsack<- function(Value, Weight, Objects, Capacity){\n  Fraction = rep(0, length(Value))\n  Cost = Value\/Weight\n  #print(Cost)\n  W = Weight[order(Cost, decreasing = TRUE)]\n  Obs = Objects[order(Cost, decreasing = TRUE)]\n  Val = Value[order(Cost, decreasing = TRUE)]\n  #print(W)\n  RemainCap = Capacity\n  i = 1\n  n = length(Cost)\n  if (W[1] <= Capacity){\n    Fits <- TRUE\n  }\n  else{\n    Fits <- FALSE \n  }\n  while (Fits && i <= n ){\n    Fraction[i] <- 1\n    RemainCap <- RemainCap - W[i]\n    i <- i+1\n    #print(RemainCap)\n    if (W[i] <= RemainCap){\n      Fits <- TRUE\n    }\n    else{\n      Fits <- FALSE\n    }\n  }\n  #print(RemainCap)\n  if (i <= n){\n    Fraction[i] <- RemainCap\/W[i]\n  }\n  names(Fraction) = Obs\n  Quantity_to_take = W*Fraction\n  Total_Value = sum(Val*Fraction)\n  print(\"Fraction of available quantity to take:\")\n  print(round(Fraction, 3))\n  print(\"KG of each to take:\")\n  print(Quantity_to_take)\n  print(\"Total value of tasty meats:\")\n  print(Total_Value)\n}\n\n\no = c(\"beef\", \"pork\", \"ham\", \"greaves\", \"flitch\", \"brawn\", \"welt\", \"salami\", \"sausage\")\nw = c(3.8,5.4,3.6,2.4,4.0,2.5,3.7,3.0,5.9)\nv = c(36,43,90,45,30,56,67,95,98)\nknapsack(v, w, o, 15)\n\n[1] \"Fraction of available quantity to take:\"\n salami     ham   brawn greaves    welt sausage    beef    pork  flitch \n  1.000   1.000   1.000   1.000   0.946   0.000   0.000   0.000   0.000 \n[1] \"KG of each to take:\"\n salami     ham   brawn greaves    welt sausage    beef    pork  flitch \n    3.0     3.6     2.5     2.4     3.5     0.0     0.0     0.0     0.0 \n[1] \"Total value of tasty meats:\"\n[1] 349.3784\n","human_summarization":"implement a solution for the continuous knapsack problem. The codes take as input the weights and prices of various items in a butcher's shop, and determine which items a thief should take (and in what quantities) to maximize his profit without exceeding a total weight of 15 kg. The thief can cut the items, and the price of the cut item is proportional to its mass. The output is the selection of items that maximize the total value without exceeding the knapsack's weight limit.","id":1551}
    {"lang_cluster":"R","source_code":"\nwords <- readLines(\"http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt\")\nword_group <- sapply(\n    strsplit(words, split=\"\"), # this will split all words to single letters...\n    function(x) paste(sort(x), collapse=\"\") # ...which we sort and paste again\n)\n\ncounts <- tapply(words, word_group, length) # group words by class to get number of anagrams\nanagrams <- tapply(words, word_group, paste, collapse=\", \") # group to get string with all anagrams\n\n# Results\ntable(counts)\ncounts\n    1     2     3     4     5 \n22263  1111   155    31     6 \n\nanagrams[counts == max(counts)]\n                               abel                               acert \n     \"abel, able, bale, bela, elba\" \"caret, carte, cater, crate, trace\" \n                              aegln                               aeglr \n\"angel, angle, galen, glean, lange\" \"alger, glare, lager, large, regal\" \n                               aeln                                eilv \n     \"elan, lane, lean, lena, neal\"      \"evil, levi, live, veil, vile\"\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":1552}
    {"lang_cluster":"R","source_code":"\nWorks with: R version 3.3.3 and above\nFile:SierpCRo5.pngOutput SierpCRo5.png\n## Are x,y inside Sierpinski carpet (and where)? (1-yes, 0-no)\ninSC <- function(x, y) {\n  while(TRUE) {\n    if(!x||!y) {return(1)}\n    if(x%%3==1&&y%%3==1) {return(0)}\n    x=x%\/%3; y=y%\/%3;\n  } return(0);\n}\n## Plotting Sierpinski carpet fractal. aev 4\/1\/17\n## ord - order, fn - file name, ttl - plot title, clr - color\npSierpinskiC <- function(ord, fn=\"\", ttl=\"\", clr=\"navy\") {\n  m=640; abbr=\"SCR\"; dftt=\"Sierpinski carpet fractal\";\n  n=3^ord-1; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);\n  cat(\" *** START\", abbr, date(), \"\\n\");\n  if(fn==\"\") {pf=paste0(abbr,\"o\", ord)} else {pf=paste0(fn, \".png\")};\n  if(ttl!=\"\") {dftt=ttl}; ttl=paste0(dftt,\", order \", ord);\n  cat(\" *** Plot file:\", pf,\".png\", \"title:\", ttl, \"\\n\");\n  for(i in 0:n) {\n    for(j in 0:n) {if(inSC(i,j)) {M[i,j]=1}\n  }}\n  plotmat(M, pf, clr, ttl);\n  cat(\" *** END\", abbr, date(), \"\\n\");\n}  \n## Executing:\npSierpinskiC(5);\n\n\n","human_summarization":"The code generates a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The ASCII art uses a combination of whitespace and non-whitespace characters, with the '#' character as an example. It also includes a reference to the related Sierpinski triangle task and uses the plotmat() function from the R Helper Functions page.","id":1553}
    {"lang_cluster":"R","source_code":"\nLibrary: gWidgets\nLibrary: gWidgetstcltk\n\nlibrary(gWidgets)\nlibrary(gWidgetstcltk)\nwin <- gwindow()\nlab <- glabel(\"There have been no clicks yet\", container=win)\nbtn <- gbutton(\"click me\", container=win, handle=function(h, ...) \n   {\n      val <- as.numeric(svalue(lab))\n      svalue(lab) <- ifelse(is.na(val) ,\"1\", as.character(val + 1))\n   }\n)\n\n","human_summarization":"create a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". When the button labeled \"click me\" is clicked, the label updates to show the number of times the button has been clicked. The application can be implemented using gWidgetsRGtk2, gWidgetsrJava, or gWidgetstcltk.","id":1554}
    {"lang_cluster":"R","source_code":"\nfor(i in 10:0) {print(i)}\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":1555}
    {"lang_cluster":"R","source_code":"\nmod1 = function(v, n)\n# mod1(1:20, 6)   =>   1 2 3 4 5 6 1 2 3 4 5 6 1 2 3 4 5 6 1 2\n    ((v - 1) %% n) + 1\n\nstr2ints = function(s)\n    as.integer(Filter(Negate(is.na),\n        factor(levels = LETTERS, strsplit(toupper(s), \"\")[[1]])))\n\nvigen = function(input, key, decrypt = F)\n   {input = str2ints(input)\n    key = rep(str2ints(key), len = length(input)) - 1\n    paste(collapse = \"\", LETTERS[\n        mod1(input + (if (decrypt) -1 else 1)*key, length(LETTERS))])}\n\nmessage(vigen(\"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\", \"vigenerecipher\"))\n  # WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\nmessage(vigen(\"WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\", \"vigenerecipher\", decrypt = T))\n  # BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":1556}
    {"lang_cluster":"R","source_code":"\nfor(a in seq(2,8,2)) {\n  cat(a, \", \")\n}\ncat(\"who do we appreciate?\\n\")\n\ncat(paste(c(seq(2, 8, by=2), \"who do we appreciate?\\n\"), collapse=\", \"))\n","human_summarization":"demonstrate a for-loop with a step-value greater than one, where the loop is done implicitly by first concatenating a string and then printing it.","id":1557}
    {"lang_cluster":"R","source_code":"\n\nsum <- function(var, lo, hi, term)\n  eval(substitute({\n    .temp <- 0;\n    for (var in lo:hi) {\n      .temp <- .temp + term\n    }\n    .temp\n  }, as.list(match.call()[-1])),\n  enclos=parent.frame())\n\nsum(i, 1, 100, 1\/i) #prints 5.187378\n\n##and because of enclos=parent.frame(), the term can involve variables in the caller's scope:\nx <- -1\nsum(i, 1, 100, i^x) #5.187378\n\n","human_summarization":"implement Jensen's Device, a programming technique that exploits call by name to compute the 100th harmonic number. The technique assumes that an expression passed as an actual parameter to a procedure would be re-evaluated in the caller's context every time the corresponding formal parameter's value was required. The global variable does not have to use the same identifier as the formal parameter. The code also demonstrates R's call by need evaluation strategy where function inputs are evaluated on demand and then cached.","id":1558}
    {"lang_cluster":"R","source_code":"\nsuppressMessages(library(gmp))\nONE <- as.bigz(\"1\")\nTWO <- as.bigz(\"2\")\nTHREE <- as.bigz(\"3\")\nFOUR <- as.bigz(\"4\")\nSEVEN <- as.bigz(\"7\")\nTEN <- as.bigz(\"10\")\n\nq <- as.bigz(\"1\")\nr <- as.bigz(\"0\")\nt <- as.bigz(\"1\")\nk <- as.bigz(\"1\")\nn <- as.bigz(\"3\")\nl <- as.bigz(\"3\")\n\nchar_printed <- 0\n\nhow_many <- 1000\n\nfirst <- TRUE\nwhile (how_many > 0) {\n  if ((FOUR * q + r - t) < (n * t)) {\n    if (char_printed == 80) {\n      cat(\"\\n\")\n      char_printed <- 0\n    }\n    how_many <- how_many - 1\n    char_printed <- char_printed + 1\n    cat(as.integer(n))\n    if (first) {\n      cat(\".\")\n      first <- FALSE\n      char_printed <- char_printed + 1\n    }\n    nr <- as.bigz(TEN * (r - n * t))\n    n <- as.bigz(((TEN * (THREE * q + r)) %\/% t) - (TEN * n))\n    q <- as.bigz(q * TEN)\n    r <- as.bigz(nr)\n  } else {\n    nr <- as.bigz((TWO * q + r) * l)\n    nn <- as.bigz((q * (SEVEN * k + TWO) + r * l) %\/% (t * l))\n    q <- as.bigz(q * k)\n    t <- as.bigz(t * l)\n    l <- as.bigz(l + TWO)\n    k <- as.bigz(k + ONE)\n    n <- as.bigz(nn)\n    r <- as.bigz(nr)\n  }\n}\ncat(\"\\n\")\n\n\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208\n99862803482534211706798214808651328230664709384460955058223172535940812848111745\n02841027019385211055596446229489549303819644288109756659334461284756482337867831\n65271201909145648566923460348610454326648213393607260249141273724587006606315588\n17488152092096282925409171536436789259036001133053054882046652138414695194151160\n94330572703657595919530921861173819326117931051185480744623799627495673518857527\n24891227938183011949129833673362440656643086021394946395224737190702179860943702\n77053921717629317675238467481846766940513200056812714526356082778577134275778960\n91736371787214684409012249534301465495853710507922796892589235420199561121290219\n60864034418159813629774771309960518707211349999998372978049951059731732816096318\n59502445945534690830264252230825334468503526193118817101000313783875288658753320\n83814206171776691473035982534904287554687311595628638823537875937519577818577805\n32171226806613001927876611195909216420198\n\n","human_summarization":"continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the program is manually terminated by the user.","id":1559}
    {"lang_cluster":"R","source_code":"\nackermann <- function(m, n) {\n  if ( m == 0 ) {\n    n+1\n  } else if ( n == 0 ) {\n    ackermann(m-1, 1)\n  } else {\n    ackermann(m-1, ackermann(m, n-1))\n  }\n}\nfor ( i in 0:3 ) {\n  print(ackermann(i, 4))\n}\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":1560}
    {"lang_cluster":"R","source_code":"\nstirling <- function(z) sqrt(2*pi\/z) * (exp(-1)*z)^z\n     \nnemes <- function(z) sqrt(2*pi\/z) * (exp(-1)*(z + (12*z - (10*z)^-1)^-1))^z\n\nlanczos <- function(z)\n{\n   if(length(z) > 1)\n   {\n      sapply(z, lanczos)\n   } else\n   {\n     g <- 7\n      p <- c(0.99999999999980993, 676.5203681218851, -1259.1392167224028,\n        771.32342877765313, -176.61502916214059, 12.507343278686905,\n        -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7)\n      z <- as.complex(z) \n      if(Re(z) < 0.5) \n      {\n         pi \/ (sin(pi*z) * lanczos(1-z)) \n      } else\n      {\n         z <- z - 1\n         x <- p[1]\n         for (i in 1:8) {\n           x <- x+p[i+1]\/(z+i)\n         }\n         tt <- z + g + 0.5\n         sqrt(2*pi) * tt^(z+0.5) * exp(-tt) * x\n      }\n   }   \n}\n\nspouge <- function(z, a=49)\n{\n   if(length(z) > 1)\n   {\n      sapply(z, spouge)\n   } else\n   {\n      z <- z-1\n      k <- seq.int(1, a-1)\n      ck <- rep(c(1, -1), len=a-1) \/ factorial(k-1) * (a-k)^(k-0.5) * exp(a-k)\n      (z + a)^(z+0.5) * exp(-z - a) * (sqrt(2*pi) + sum(ck\/(z+k)))\n   }\n}\n\n# Checks\nz <- (1:10)\/3\nall.equal(gamma(z), stirling(z))             # Mean relative difference: 0.07181942\nall.equal(gamma(z), nemes(z))                # Mean relative difference: 0.003460549\nall.equal(as.complex(gamma(z)), lanczos(z))  # TRUE\nall.equal(gamma(z), spouge(z))               # TRUE\ndata.frame(z=z, stirling=stirling(z), nemes=nemes(z), lanczos=lanczos(z), spouge=spouge(z), builtin=gamma(z))\n\n\n","human_summarization":"Implement and compare the Gamma function using built-in\/library function and self-implemented algorithms, specifically numerical integration, Lanczos approximation, and Stirling's approximation.","id":1561}
    {"lang_cluster":"R","source_code":"\nqueens <- function(n) {\n  a <- seq(n)\n  u <- rep(T, 2 * n - 1)\n  v <- rep(T, 2 * n - 1)\n  m <- NULL\n  aux <- function(i) {\n    if (i > n) {\n      m <<- cbind(m, a)\n    } else {\n      for (j in seq(i, n)) {\n        k <- a[[j]]\n        p <- i - k + n\n        q <- i + k - 1\n        if (u[[p]] && v[[q]]) {\n          u[[p]] <<- v[[q]] <<- F\n          a[[j]] <<- a[[i]]\n          a[[i]] <<- k\n          aux(i + 1)\n          u[[p]] <<- v[[q]] <<- T\n          a[[i]] <<- a[[j]]\n          a[[j]] <<- k\n        }\n      }\n    }\n  }\n  aux(1)\n  m\n}\n\nlibrary(Matrix)\na <- queens(8)\nas(a[, 1], \"pMatrix\")\n\n","human_summarization":"solve the N-queens problem using recursive backtracking, display the first solution for an 8x8 board as a permutation matrix, and count the number of solutions for board sizes ranging from 4x4 to 12x12.","id":1562}
    {"lang_cluster":"R","source_code":"\na1 <- c(1, 2, 3)\na2 <- c(3, 4, 5)\na3 <- c(a1, a2)\n","human_summarization":"demonstrate how to concatenate two arrays.","id":1563}
    {"lang_cluster":"R","source_code":"\nFull_Data<-structure(list(item = c(\"map\", \"compass\", \"water\", \"sandwich\", \n\"glucose\", \"tin\", \"banana\", \"apple\", \"cheese\", \"beer\", \"suntan_cream\", \n\"camera\", \"T-shirt\", \"trousers\", \"umbrella\", \"waterproof_trousers\", \n\"waterproof_overclothes\", \"note-case\", \"sunglasses\", \"towel\", \n\"socks\", \"book\"), weigth = c(9, 13, 153, 50, 15, 68, 27, 39, \n23, 52, 11, 32, 24, 48, 73, 42, 43, 22, 7, 18, 4, 30), value = c(150, \n35, 200, 160, 60, 45, 60, 40, 30, 10, 70, 30, 15, 10, 40, 70, \n75, 80, 20, 12, 50, 10)), .Names = c(\"item\", \"weigth\", \"value\"\n), row.names = c(NA, 22L), class = \"data.frame\")\n\n\nBounded_knapsack<-function(Data,W)\n{\n\tK<-matrix(NA,nrow=W+1,ncol=dim(Data)[1]+1)\n\t0->K[1,]->K[,1]\n\tmatrix_item<-matrix('',nrow=W+1,ncol=dim(Data)[1]+1)\n\tfor(j in 1:dim(Data)[1])\n\t{\n\t\tfor(w in 1:W)\n\t\t{\n\t\t\twj<-Data$weigth[j]\n\t\t\titem<-Data$item[j]\n\t\t\tvalue<-Data$value[j]\n\t\t\tif( wj > w )\n\t\t\t{\n\t\t\t\tK[w+1,j+1]<-K[w+1,j]\n\t\t\t\tmatrix_item[w+1,j+1]<-matrix_item[w+1,j]\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif( K[w+1,j] >= K[w+1-wj,j]+value )\n\t\t\t\t{\n\t\t\t\t\tK[w+1,j+1]<-K[w+1,j]\n\t\t\t\t\tmatrix_item[w+1,j+1]<-matrix_item[w+1,j]\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tK[w+1,j+1]<-K[w+1-wj,j]+value\n\t\t\t\t\tmatrix_item[w+1,j+1]<-item\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\nreturn(list(K=K,Item=matrix_item))\n}\n\nbacktracking<-function(knapsack, Data)\n{\n\tW<-dim(knapsack$K)[1]\n\titens<-c()\n\tcol<-dim(knapsack$K)[2]\n\tselected_item<-knapsack$Item[W,col]\n\twhile(selected_item!='')\n\t{\n\t\tselected_item<-knapsack$Item[W,col]\n\t\tif(selected_item!='')\n\t\t{\n\t\t\tselected_item_value<-Data[Data$item == selected_item,]\n\t\t\tif(-knapsack$K[W - selected_item_value$weigth,col-1]+knapsack$K[W,col]==selected_item_value$value)\n\t\t\t{\n\t\t\t\tW <- W - selected_item_value$weigth\n\t\t\t\titens<-c(itens,selected_item)\n\t\t\t}\n\t\t\tcol <- col - 1\n\t\t}\n\t}\nreturn(itens)\n}\n\nprint_output<-function(Data,W)\n{\n\tBounded_knapsack(Data,W)->Knap\n\tbacktracking(Knap, Data)->Items\n\toutput<-paste('You must carry:', paste(Items, sep = ', '), sep=' ' )\n\treturn(output)\n}\n\nprint_output(Full_Data, 400)\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":1564}
    {"lang_cluster":"R","source_code":"\na <- function(x) {cat(\"a called\\n\"); x}\nb <- function(x) {cat(\"b called\\n\"); x}\n\ntests <- expand.grid(op=list(quote(`||`), quote(`&&`)), x=c(1,0), y=c(1,0))\n\ninvisible(apply(tests, 1, function(row) {\n  call <- substitute(op(a(x),b(y)), row)\n  cat(deparse(call), \"->\", eval(call), \"\\n\\n\")\n}))\n\n\n","human_summarization":"The code creates two functions, 'a' and 'b', which accept and return the same boolean value, while also printing their name when called. The code then calculates and assigns the values of two boolean expressions to variables 'x' and 'y'. The expressions are structured to utilize short-circuit evaluation, ensuring function 'b' is only called when necessary. If the language does not support short-circuit evaluation, this is achieved with nested 'if' statements. The code also demonstrates that the built-in operators '&&' and '||' can short circuit in R language.","id":1565}
    {"lang_cluster":"R","source_code":"\n\nblocks <- rbind(c(\"B\",\"O\"),\n c(\"X\",\"K\"), \n c(\"D\",\"Q\"), \n c(\"C\",\"P\"), \n c(\"N\",\"A\"), \n c(\"G\",\"T\"), \n c(\"R\",\"E\"), \n c(\"T\",\"G\"), \n c(\"Q\",\"D\"), \n c(\"F\",\"S\"), \n c(\"J\",\"W\"), \n c(\"H\",\"U\"), \n c(\"V\",\"I\"), \n c(\"A\",\"N\"), \n c(\"O\",\"B\"), \n c(\"E\",\"R\"), \n c(\"F\",\"S\"), \n c(\"L\",\"Y\"), \n c(\"P\",\"C\"), \n c(\"Z\",\"M\"))\n\ncanMake <- function(x) {\n  x <- toupper(x)\n  used <- rep(FALSE, dim(blocks)[1L])\n  charList <- strsplit(x, character(0))\n  tryChars <- function(chars, pos, used, inUse=NA) {\n    if (pos > length(chars)) {\n      TRUE\n    } else {\n      used[inUse] <- TRUE\n      possible <- which(blocks == chars[pos] & !used, arr.ind=TRUE)[, 1L]\n      any(vapply(possible, function(possBlock) tryChars(chars, pos + 1, used, possBlock), logical(1)))\n    }\n  }\n  setNames(vapply(charList, tryChars, logical(1), 1L, used), x)\n}\ncanMake(c(\"A\",\n           \"BARK\",\n           \"BOOK\",\n           \"TREAT\",\n           \"COMMON\",\n           \"SQUAD\",\n           \"CONFUSE\"))\n\n\n","human_summarization":"The code is a function that checks if a given word can be spelled using a specified collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value indicating whether or not the word can be spelled with the blocks. The function also includes a vectorized version for R that takes a character vector and returns a logical vector of equal length, indicating which words can or cannot be spelled with the blocks. A second version of the function provides all unique combinations of blocks for each word.","id":1566}
    {"lang_cluster":"R","source_code":"\nlibrary(digest)\nhexdigest <- digest(\"The quick brown fox jumped over the lazy dog's back\", \n                    algo=\"md5\", serialize=FALSE)\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":1567}
    {"lang_cluster":"R","source_code":"\ns <- make.socket(port = 256)\nwrite.socket(s, \"hello socket world\")\nclose.socket(s)\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":1568}
    {"lang_cluster":"R","source_code":"\n\n\nlibrary(RDCOMClient)\n\nsend.mail <- function(to, title, body) {\n  olMailItem <- 0\n  ol <- COMCreate(\"Outlook.Application\")\n  msg <- ol$CreateItem(olMailItem)\n  msg[[\"To\"]] <- to\n  msg[[\"Subject\"]] <- title\n  msg[[\"Body\"]] <- body\n  msg$Send()\n  ol$Quit()\n}\n\nsend.mail(\"somebody@somewhere\", \"Title\", \"Hello\")\n\n","human_summarization":"The code is a function for sending an email using R programming language. It accepts parameters for From, To, Cc addresses, Subject, message text, and optional parameters for server name and login details. It uses the mail package from CRAN and the RDCOMClient package for Outlook COM server. It also handles notifications for any issues or success. The code's portability across different operating systems is noted. Sensitive data used in examples are obfuscated.","id":1569}
    {"lang_cluster":"R","source_code":"\n\nswap <- function(name1, name2, envir = parent.env(environment()))\n{\n    temp <- get(name1, pos = envir)\n    assign(name1, get(name2, pos = envir), pos = envir)\n    assign(name2, temp, pos = envir)\n}\n\n> x <- 1\n> y <- 2\n> swap('x', 'y')\n> cat(x, y)\n2 1\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain constraints for type compatibility. The function may not support swapping of incompatible types like string and integer, and may not work with functional languages that disallow destructive operations. The function also considers the challenges of parametric polymorphism in some static languages. In R, the function uses variable names and environment to overcome the limitation of pass-by-value argument passing.","id":1570}
    {"lang_cluster":"R","source_code":"\n\npalindro <- function(p) {\n  if ( nchar(p) == 1 ) {\n    return(TRUE)\n  } else if ( nchar(p) == 2 ) {\n    return(substr(p,1,1) == substr(p,2,2))\n  } else {\n    if ( substr(p,1,1) == substr(p, nchar(p), nchar(p)) ) {\n      return(palindro(substr(p, 2, nchar(p)-1)))\n    } else {\n      return(FALSE)\n    }\n  }\n}\n\npalindroi <- function(p) {\n  for(i in 1:floor(nchar(p)\/2) ) {\n    r <- nchar(p) - i + 1\n    if ( substr(p, i, i)\u00a0!= substr(p, r, r) ) return(FALSE) \n  }\n  TRUE\n}\n\nrevstring <- function(stringtorev) {\n   return(\n      paste(\n           strsplit(stringtorev,\"\")[[1]][nchar(stringtorev):1]\n           ,collapse=\"\")\n           )\n}\npalindroc <- function(p) {return(revstring(p)==p)}\n\nis.Palindrome <- function(string)\n{\n  characters <- unlist(strsplit(string, \"\"))\n  all(characters == rev(characters))\n}\n\n","human_summarization":"The code includes a function that checks if a given sequence of characters is a palindrome. It supports Unicode characters and has an additional function that detects inexact palindromes, ignoring white-space, punctuation, and case differences. The code uses both recursive and iterative methods, with the iterative method being faster. It also includes a method that incorrectly regards an empty string as not a palindrome. The code uses R's built-in function for reversing vectors and supports Unicode characters, but it doesn't support the detection of inexact palindromes.","id":1571}
    {"lang_cluster":"R","source_code":"\nSys.getenv(\"PATH\")\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":1572}
    {"lang_cluster":"R","source_code":"#Aamrun, 11th July 2022\n\nF <- function(n, x, y) {\n  if(n==0){\n  \tF <- x+y\n    return (F)\n  }\n  \n  else if(y == 0) {\n    F <- x\n    return (F)\n  }\n \n  F <- F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y)\n  return (F)\n}\n\nprint(paste(\"F(1,3,3) = \" , F(1,3,3)))\n\n\n[1] \"F(1,3,3) =  35\"\n\n","human_summarization":"implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns the value of F(x, y) based on the defined rules.","id":1573}
    {"lang_cluster":"Ruby","source_code":"\n\nstack = []\nstack.push(value) # pushing\nvalue = stack.pop # popping\nstack.empty? # is empty?\n\nrequire 'forwardable'\n\n# A stack contains elements in last-in, first-out order.\n# Stack#push adds new elements to the top of the stack;\n# Stack#pop removes elements from the top.\nclass Stack\n  extend Forwardable\n  \n  # Creates a Stack containing _objects_.\n  def self.[](*objects)\n    new.push(*objects)\n  end\n  \n  # Creates an empty Stack.\n  def initialize\n    @ary = []\n  end\n  \n  # Duplicates a Stack.\n  def initialize_copy(obj)\n    super\n    @ary = @ary.dup\n  end\n  \n  # Adds each object to the top of this Stack. Returns self.\n  def push(*objects)\n    @ary.push(*objects)\n    self\n  end\n  alias << push\n  \n  ##\n  # :method: pop\n  # :call-seq:\n  #   pop -> obj or nil\n  #   pop(n) -> ary\n  #\n  # Removes an element from the top of this Stack, and returns it.\n  # Returns nil if the Stack is empty.\n  #\n  # If passing a number _n_, removes the top _n_ elements, and returns\n  # an Array of them. If this Stack contains fewer than _n_ elements,\n  # returns them all. If this Stack is empty, returns an empty Array.\n  def_delegator\u00a0:@ary, :pop\n  \n  ##\n  # :method: top\n  # :call-seq:\n  #   top -> obj or nil\n  #   top(n) -> ary\n  # Returns the topmost element without modifying the stack.\n  def_delegator\u00a0:@ary, :last, :top\n  \n  ##\n  # :method: empty?\n  # Returns true if this Stack contains no elements.\n  def_delegator\u00a0:@ary, :empty?\n  \n  ##\n  # :method: size\n  # Returns the number of elements in this Stack.\n  def_delegator\u00a0:@ary, :size\n  alias length size\n  \n  # Converts this Stack to a String.\n  def to_s\n    \"#{self.class}#{@ary.inspect}\"\n  end\n  alias inspect to_s\nend\np s = Stack.new                 # => Stack[]\np s.empty?                      # => true\np s.size                        # => 0\np s.top                         # => nil\np s.pop                         # => nil\np s.pop(1)                      # => []\np s.push(1)                     # => Stack[1]\np s.push(2, 3)                  # => Stack[1, 2, 3]\np s.top                         # => 3\np s.top(2)                      # => [2, 3]\np s                             # => Stack[1, 2, 3]\np s.size                        # => 3\np s.pop                         # => 3\np s.pop(1)                      # => [2]\np s.empty?                      # => false\n\np s = Stack[:a, :b, :c]         # => Stack[:a, :b, :c]\np s << :d                       # => Stack[:a, :b, :c, :d]\np s.pop                         # => :d\n\nrequire 'forwardable'\n\nclass Stack\n  extend Forwardable\n\n  def initialize\n    @stack = []\n  end\n\n  def_delegators\u00a0:@stack, :push, :pop, :empty?\nend\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and empty. The push operation stores a new element onto the top of the stack, the pop operation returns and removes the last pushed element from the stack, and the empty operation checks if the stack contains no elements. The stack follows a last in, first out (LIFO) access policy.","id":1574}
    {"lang_cluster":"Ruby","source_code":"\ndef fib(n)\n  if n < 2\n    n\n  else\n    prev, fib = 0, 1\n    (n-1).times do\n      prev, fib = fib, fib + prev\n    end\n    fib\n  end\nend\n\np (0..10).map { |i| fib(i) }\n\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n\ndef fib(n, sequence=[1])\n  return sequence.last if n == 0\n\n  current_number, last_number = sequence.last(2)\n  sequence << current_number + (last_number or 0)\n\n  fib(n-1, sequence)\nend\n# Use the Hash#default_proc feature to\n# lazily calculate the Fibonacci numbers.\n\nfib = Hash.new do |f, n|\n  f[n] = if n <= -2\n           (-1)**(n + 1) * f[n.abs]\n         elsif n <= 1\n           n.abs\n         else\n           f[n - 1] + f[n - 2]\n         end\nend\n# examples: fib[10] => 55, fib[-10] => (-55\/1)\nrequire 'matrix'\n\n# To understand why this matrix is useful for Fibonacci numbers, remember\n# that the definition of Matrix.**2 for any Matrix[[a, b], [c, d]] is\n# is [[a*a + b*c, a*b + b*d], [c*a + d*b, c*b + d*d]].  In other words, the\n# lower right element is computing F(k - 2) + F(k - 1) every time M is multiplied\n# by itself (it is perhaps easier to understand this by computing M**2, 3, etc, and\n# watching the result march up the sequence of Fibonacci numbers).\n\nM = Matrix[[0, 1], [1,1]]\n\n# Matrix exponentiation algorithm to compute Fibonacci numbers.\n# Let M be Matrix [[0, 1], [1, 1]].  Then, the lower right element of M**k is\n# F(k + 1).  In other words, the lower right element of M is F(2) which is 1, and the\n# lower right element of M**2 is F(3) which is 2, and the lower right element\n# of M**3 is F(4) which is 3, etc.\n#\n# This is a good way to compute F(n) because the Ruby implementation of Matrix.**(n)\n# uses O(log n) rather than O(n) matrix multiplications.  It works by squaring squares\n# ((m**2)**2)... as far as possible\n# and then multiplying that by by M**(the remaining number of times).  E.g., to compute\n# M**19, compute partial = ((M**2)**2) = M**16, and then compute partial*(M**3) = M**19.\n# That's only 5 matrix multiplications of M to compute M*19. \ndef self.fib_matrix(n)\n  return 0 if n <= 0 # F(0)\n  return 1 if n == 1 # F(1)\n  # To get F(n >= 2), compute M**(n - 1) and extract the lower right element.\n  return CS::lower_right(M**(n - 1))\nend\n\n# Matrix utility to return\n# the lower, right-hand element of a given matrix.\ndef self.lower_right matrix\n  return nil if matrix.row_size == 0\n  return matrix[matrix.row_size - 1, matrix.column_size - 1]\nend\nfib = Enumerator.new do |y|\n  f0, f1 = 0, 1\n  loop do\n    y <<  f0\n    f0, f1 = f1, f0 + f1\n  end\nend\n\np fib.lazy.drop(8).next # => 21\nWorks with: Ruby version 1.9\n\nfib = Fiber.new do\n  a,b = 0,1\n  loop do\n    Fiber.yield a\n    a,b = b,a+b\n  end\nend\n9.times {puts fib.resume}\n\ndef fib_gen\n    a, b = 1, 1\n    lambda {ret, a, b = a, b, a+b; ret}\nend\nirb(main):034:0> fg = fib_gen\n=> #<Proc:0xb7cdf750@(irb):22>\nirb(main):035:0> 9.times { puts fg.call}\n1\n1\n2\n3\n5\n8\n13\n21\n34\n=> 9\n\ndef fib\n    phi = (1 + Math.sqrt(5)) \/ 2\n    ((phi**self - (-1 \/ phi)**self) \/ Math.sqrt(5)).to_i\nend\n1.9.3p125 :001 > def fib\n1.9.3p125 :002?>   phi = (1 + Math.sqrt(5)) \/ 2\n1.9.3p125 :003?>   ((phi**self - (-1 \/ phi)**self) \/ Math.sqrt(5)).to_i\n1.9.3p125 :004?>   end\n => nil \n1.9.3p125 :005 > (0..10).map(&:fib)\n => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]\n\n","human_summarization":"The code is a function that generates the nth Fibonacci number. It can be implemented either iteratively or recursively. The function also has the optional feature to support negative n values by using a straightforward inverse of the positive definition. The function uses fibers, a primitive for implementing lightweight cooperative concurrency in Ruby, which allows the creation of code blocks that can be paused and resumed.","id":1575}
    {"lang_cluster":"Ruby","source_code":"\n\n# Enumerable#select returns a new array.\nary = [1, 2, 3, 4, 5, 6]\neven_ary = ary.select {|elem| elem.even?}\np even_ary # => [2, 4, 6]\n\n# Enumerable#select also works with Range.\nrange = 1..6\neven_ary = range.select {|elem| elem.even?}\np even_ary # => [2, 4, 6]\n\nary = [1, 2, 3, 4, 5, 6]\nary.select! {|elem| elem.even?}\np ary # => [2, 4, 6]\n\nary = [1, 2, 3, 4, 5, 6]\nary.select!(&:even?)\np ary # => [2, 4, 6]\n","human_summarization":"select certain elements from an array into a new array. It specifically selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array. The methods used are Enumerable#select for creating a new array and Array#select! for modifying the original array.","id":1576}
    {"lang_cluster":"Ruby","source_code":"\nstr = 'abcdefgh'\nn = 2\nm = 3\nputs str[n, m]                  #=> cde\nputs str[n..m]                  #=> cd\nputs str[n..-1]                 #=> cdefgh\nputs str[0..-2]                 #=> abcdefg\nputs str[str.index('d'), m]     #=> def\nputs str[str.index('de'), m]    #=> def\nputs str[\/a.*d\/]                #=> abcd\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":1577}
    {"lang_cluster":"Ruby","source_code":"\nstr = \"asdf\"\nreversed = str.reverse\n\"r\u00e9sum\u00e9 ni\u00f1o\".reverse #=> \"o\u00f1in \u00e9mus\u00e9r\"\n\ngraphemes = 'as\u20dddf\u0305'.scan(\/\\X\/)\nreversed = graphemes.reverse\ngraphemes.join #=> \"f\u0305ds\u20dda\"\n","human_summarization":"take a string input, reverse it, and ensure Unicode combining characters are preserved in their original order.","id":1578}
    {"lang_cluster":"Ruby","source_code":"\n\nclass Playfair\n  Size = 5\n  def initialize(key, missing)\n    @missing = missing.upcase\n    alphabet = ('A'..'Z').to_a.join.upcase.delete(@missing).split''\n    extended = key.upcase.gsub(\/[^A-Z]\/,'').split('') + alphabet\n    grid = extended.uniq[0...Size*Size].each_slice(Size).to_a\n    coords = {}\n    grid.each_with_index do |row, i|\n      row.each_with_index do |letter, j|\n       coords[letter] = [i,j]\n      end\n    end\n    @encode = {}\n    alphabet.product(alphabet).reject { |a,b| a==b }.each do |a, b|\n      i1, j1 = coords[a]\n      i2, j2 = coords[b]\n      if i1 == i2 then\n         j1 = (j1 + 1) % Size\n         j2 = (j2 + 1) % Size\n      elsif j1 == j2 then\n         i1 = (i1 + 1) % Size\n         i2 = (i2 + 1) % Size\n      else\n         j1, j2 = j2, j1\n      end\n      @encode[\"#{a}#{b}\"] = \"#{grid[i1][j1]}#{grid[i2][j2]}\"\n      @decode = @encode.invert\n    end\n  end\n\n  def encode(plaintext) \n    plain = plaintext.upcase.gsub(\/[^A-Z]\/,'')\n    if @missing == 'J' then\n      plain = plain.gsub(\/J\/, 'I')\n    else\n      plain = plain.gsub(@missing, 'X')\n    end\n    plain = plain.gsub(\/(.)\\1\/, '\\1X\\1')\n    if plain.length % 2 == 1 then\n      plain += 'X'\n    end\n    return plain.upcase.split('').each_slice(2).map do |pair|\n      @encode[pair.join]\n    end.join.split('').each_slice(5).map{|s|s.join}.join(' ')\n  end\n\n  def decode(ciphertext) \n    cipher = ciphertext.upcase.gsub(\/[^A-Z]\/,'')\n    return cipher.upcase.split('').each_slice(2).map do |pair|\n      @decode[pair.join]\n    end.join.split('').each_slice(5).map{|s|s.join}.join(' ')\n  end\nend\n\n\n","human_summarization":"implement a Playfair cipher for both encryption and decryption. The user can choose whether to replace 'J' with 'I' or exclude 'Q' from the alphabet. The output message is displayed in capitalized digraphs, separated by spaces.","id":1579}
    {"lang_cluster":"Ruby","source_code":"\n\nWorks with: Ruby version 1.9.2+ (for INFINITY)\n\nAt every iteration, the next minimum distance node found by linear traversal of all nodes, which is inefficient.\nclass Graph\n  Vertex = Struct.new(:name, :neighbours, :dist, :prev)\n \n  def initialize(graph)\n    @vertices = Hash.new{|h,k| h[k]=Vertex.new(k,[],Float::INFINITY)}\n    @edges = {}\n    graph.each do |(v1, v2, dist)|\n      @vertices[v1].neighbours << v2\n      @vertices[v2].neighbours << v1\n      @edges[[v1, v2]] = @edges[[v2, v1]] = dist\n    end\n    @dijkstra_source = nil\n  end\n \n  def dijkstra(source)\n    return  if @dijkstra_source == source\n    q = @vertices.values\n    q.each do |v|\n      v.dist = Float::INFINITY\n      v.prev = nil\n    end\n    @vertices[source].dist = 0\n    until q.empty?\n      u = q.min_by {|vertex| vertex.dist}\n      break if u.dist == Float::INFINITY\n      q.delete(u)\n      u.neighbours.each do |v|\n        vv = @vertices[v]\n        if q.include?(vv)\n          alt = u.dist + @edges[[u.name, v]]\n          if alt < vv.dist\n            vv.dist = alt\n            vv.prev = u.name\n          end\n        end\n      end\n    end\n    @dijkstra_source = source\n  end\n \n  def shortest_path(source, target)\n    dijkstra(source)\n    path = []\n    u = target\n    while u\n      path.unshift(u)\n      u = @vertices[u].prev\n    end\n    return path, @vertices[target].dist\n  end\n \n  def to_s\n    \"#<%s vertices=%p edges=%p>\" % [self.class.name, @vertices.values, @edges] \n  end\nend\n\ng = Graph.new([ [:a, :b, 7],\n                [:a, :c, 9],\n                [:a, :f, 14],\n                [:b, :c, 10],\n                [:b, :d, 15],\n                [:c, :d, 11],\n                [:c, :f, 2],\n                [:d, :e, 6],\n                [:e, :f, 9],\n              ])\n\nstart, stop = :a, :e\npath, dist = g.shortest_path(start, stop)\nputs \"shortest path from #{start} to #{stop} has cost #{dist}:\"\nputs path.join(\" -> \")\n\n\n","human_summarization":"The code implements Dijkstra's algorithm to find the shortest path from a given source node to all other nodes in a directed, weighted graph. The graph is represented by an adjacency matrix or list, and the algorithm outputs a set of edges depicting the shortest paths. The code also includes a functionality to interpret the output and display the shortest path from the source node to specific nodes.","id":1580}
    {"lang_cluster":"Ruby","source_code":"Pt     = Struct.new(:x, :y)\nCircle = Struct.new(:x, :y, :r)\n\ndef circles_from(pt1, pt2, r)\n  raise ArgumentError, \"Infinite number of circles, points coincide.\" if pt1 == pt2 && r > 0\n  # handle single point and r == 0\n  return [Circle.new(pt1.x, pt1.y, r)] if pt1 == pt2 && r == 0\n  dx, dy = pt2.x - pt1.x, pt2.y - pt1.y\n  # distance between points\n  q = Math.hypot(dx, dy)\n  # Also catches pt1\u00a0!= pt2 && r == 0\n  raise ArgumentError, \"Distance of points > diameter.\" if q > 2.0*r\n  # halfway point\n  x3, y3 = (pt1.x + pt2.x)\/2.0, (pt1.y + pt2.y)\/2.0\n  d = (r**2 - (q\/2)**2)**0.5\n  [Circle.new(x3 - d*dy\/q, y3 + d*dx\/q, r),\n   Circle.new(x3 + d*dy\/q, y3 - d*dx\/q, r)].uniq\nend\n\n# Demo:\nar = [[Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 2.0],\n      [Pt.new(0.0000, 2.0000), Pt.new(0.0000, 0.0000), 1.0],\n      [Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 2.0],\n      [Pt.new(0.1234, 0.9876), Pt.new(0.8765, 0.2345), 0.5],\n      [Pt.new(0.1234, 0.9876), Pt.new(0.1234, 0.9876), 0.0]]\n\nar.each do |p1, p2, r|\n  print \"Given points:\\n  #{p1.values},\\n  #{p2.values}\\n  and radius #{r}\\n\"\n  begin\n    circles = circles_from(p1, p2, r)\n    puts \"You can construct the following circles:\"\n    circles.each{|c| puts \"  #{c}\"}\n  rescue ArgumentError => e\n    puts e\n  end\n  puts\nend\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":1581}
    {"lang_cluster":"Ruby","source_code":"\nloop do\n  a = rand(20)\n  print a\n  if a == 10\n    puts\n    break\n  end\n  b = rand(20)\n  puts \"\\t#{b}\"\nend\n\n\nloop do\n  print a = rand(20)\n  puts or break if a == 10\n  puts \"\\t#{rand(20)}\"\nend\n\n","human_summarization":"generates and prints random numbers from 0 to 19. If the generated number is 10, the loop stops. If not, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":1582}
    {"lang_cluster":"Ruby","source_code":"\nWorks with: Ruby version 1.9.3+\nrequire 'prime'\n\ndef mersenne_factor(p)\n  limit = Math.sqrt(2**p - 1)\n  k = 1\n  while (2*k*p - 1) < limit\n    q = 2*k*p + 1\n    if q.prime? and (q % 8 == 1 or q % 8 == 7) and trial_factor(2,p,q)\n      # q is a factor of 2**p-1\n      return q\n    end\n    k += 1\n  end\n  nil\nend\n\ndef trial_factor(base, exp, mod)\n  square = 1\n  (\"%b\" % exp).each_char {|bit| square = square**2 * (bit == \"1\" ? base : 1) % mod}\n  (square == 1)\nend\n\ndef check_mersenne(p)\n  print \"M#{p} = 2**#{p}-1 is \"\n  f = mersenne_factor(p)\n  if f.nil?\n    puts \"prime\"\n  else\n    puts \"composite with factor #{f}\"\n  end\nend\n\nPrime.each(53) { |p| check_mersenne p }\ncheck_mersenne 929\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":1583}
    {"lang_cluster":"Ruby","source_code":"\nLibrary: REXML\n#Example taken from the REXML tutorial (http:\/\/www.germane-software.com\/software\/rexml\/docs\/tutorial.html)\nrequire \"rexml\/document\"\ninclude REXML\n#create the REXML Document from the string (%q is Ruby's multiline string, everything between the two @-characters is the string)\ndoc = Document.new(\n        %q@<inventory title=\"OmniCorp Store #45x10^3\">\n             ...\n           <\/inventory>\n          @\n                          )\n# The invisibility cream is the first <item>\ninvisibility = XPath.first( doc, \"\/\/item\" ) \n# Prints out all of the prices\nXPath.each( doc, \"\/\/price\") { |element| puts element.text }\n# Gets an array of all of the \"name\" elements in the document.\nnames = XPath.match( doc, \"\/\/name\" )\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":1584}
    {"lang_cluster":"Ruby","source_code":"\n\n>> require 'set'\n=> true\n>> s1, s2 = Set[1, 2, 3, 4], [3, 4, 5, 6].to_set # different ways of creating a set\n=> [#<Set: {1, 2, 3, 4}>, #<Set: {5, 6, 3, 4}>]\n>> s1 | s2 # Union\n=> #<Set: {5, 6, 1, 2, 3, 4}>\n>> s1 & s2 # Intersection\n=> #<Set: {3, 4}>\n>> s1 - s2 # Difference\n=> #<Set: {1, 2}>\n>> s1.proper_subset?(s1) # Proper subset\n=> false\n>> Set[3, 1].proper_subset?(s1) # Proper subset\n=> true\n>> s1.subset?(s1) # Subset\n=> true\n>> Set[3, 1].subset?(s1) # Subset\n=> true\n>> Set[3, 2, 4, 1] == s1 # Equality\n=> true\n>> s1 == s2 # Equality\n=> false\n>> s1.include?(2) # Membership\n=> true\n>> Set[1, 2, 3, 4, 5].proper_superset?(s1) # Proper superset\n=> true\n>> Set[1, 2, 3, 4].proper_superset?(s1) # Proper superset\n=> false\n>> Set[1, 2, 3, 4].superset?(s1) # Superset\n=> true\n>> s1 ^ s2 # Symmetric difference\n=> #<Set: {5, 6, 1, 2}>\n>> s1.size # Cardinality\n=> 4\n>> s1 << 99 # Mutability (or s1.add(99) )\n=> #<Set: {99, 1, 2, 3, 4}>\n>> s1.delete(99) # Mutability\n=> #<Set: {1, 2, 3, 4}>\n>> s1.merge(s2) # Mutability\n=> #<Set: {5, 6, 1, 2, 3, 4}>\n>> s1.subtract(s2) # Mutability\n=> #<Set: {1, 2}>\n>>\n\n","human_summarization":"The code implements various set operations including creation of a set, checking if an element is part of a set, performing union, intersection, and difference operations between two sets, checking if one set is a subset or equal to another set. It also optionally demonstrates additional set operations and modifications on a mutable set. The set implementation can be done using an associative array, binary search tree, hash table, or binary bits. The code also includes performance details for the basic test operation. The Ruby standard library's \"set\" package is used for implementing Set and SortedSet classes.","id":1585}
    {"lang_cluster":"Ruby","source_code":"\nrequire 'date'\n\n(2008..2121).each {|year| puts \"25 Dec #{year}\" if Date.new(year, 12, 25).sunday? }\n\n","human_summarization":"\"Determines the years between 2008 and 2121 when Christmas falls on a Sunday using standard date handling libraries. Compares the results with other languages to identify any discrepancies due to issues like overflow in date\/time representation.\"","id":1586}
    {"lang_cluster":"Ruby","source_code":"\n\nary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant']\np ary.uniq              # => [1, 2, \"redundant\", [1, 2, 3]]\n\nclass Array\n  # used Hash\n  def uniq1\n    each_with_object({}) {|elem, h| h[elem] = true}.keys\n  end\n  # sort (requires comparable)\n  def uniq2\n    sorted = sort\n    pre = sorted.first\n    sorted.each_with_object([pre]){|elem, uniq| uniq << (pre = elem) if elem\u00a0!= pre}\n  end\n  # go through the list\n  def uniq3\n    each_with_object([]) {|elem, uniq| uniq << elem unless uniq.include?(elem)}\n  end\nend\n\nary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant']\np ary.uniq1             #=> [1, 2, \"redundant\", [1, 2, 3]]\np ary.uniq2 rescue nil  #   Error (not comparable)\np ary.uniq3             #=> [1, 2, \"redundant\", [1, 2, 3]]\n\nary = [1,2,3,7,6,5,2,3,4,5,6,1,1,1]\np ary.uniq1             #=> [1, 2, 3, 7, 6, 5, 4]\np ary.uniq2             #=> [1, 2, 3, 4, 5, 6, 7]\np ary.uniq3             #=> [1, 2, 3, 7, 6, 5, 4]\n\ndef unique(array)\n    pure = Array.new\n    for i in array\n        flag = false\n        for j in pure\n            flag = true if j==i\n        end\n        pure << i unless flag\n    end\n    return pure\nend\n\nunique [\"hi\",\"hey\",\"hello\",\"hi\",\"hey\",\"heyo\"]   # => [\"hi\", \"hey\", \"hello\", \"heyo\"]\nunique [1,2,3,4,1,2,3,5,1,2,3,4,5]              # => [1,2,3,4,5]\n","human_summarization":"\"Removes duplicate elements from an array using three possible methods: 1) Hash table implementation, 2) Sorting and removing consecutive duplicates, 3) Checking each element against the rest of the list. Also includes a built-in Ruby method and a custom method for removing duplicates.\"","id":1587}
    {"lang_cluster":"Ruby","source_code":"\nclass Array\n  def quick_sort\n    return self if length <= 1\n    pivot = self[0]\n    less, greatereq = self[1..-1].partition { |x| x < pivot }\n    less.quick_sort + [pivot] + greatereq.quick_sort\n  end\nend\n\nclass Array\n  def quick_sort\n    return self if length <= 1\n    pivot = sample\n    group = group_by{ |x| x <=> pivot }\n    group.default = []\n    group[-1].quick_sort + group[0] + group[1].quick_sort\n  end\nend\n\nclass Array\n  def quick_sort\n    h, *t = self\n    h\u00a0? t.partition { |e| e < h }.inject { |l, r| l.quick_sort + [h] + r.quick_sort }\u00a0: []\n  end\nend\n","human_summarization":"implement the Quicksort algorithm to sort an array or list. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions, one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts both partitions and joins them with the pivot. The algorithm also includes an optimized version that works in place by swapping elements within the array to avoid additional memory allocation. The pivot element selection method is not specified and can vary.","id":1588}
    {"lang_cluster":"Ruby","source_code":"\n\nputs Time.now\nputs Time.now.strftime('%Y-%m-%d')\nputs Time.now.strftime('%F')            # same as %Y-%m-%d (ISO 8601 date formats)\nputs Time.now.strftime('%A, %B %d, %Y')\n\n\n","human_summarization":"display the current date in the formats \"2007-11-23\" and \"Friday, November 23, 2007\" using Time#strftime formatting rules.","id":1589}
    {"lang_cluster":"Ruby","source_code":"\n# Based on http:\/\/johncarrino.net\/blog\/2006\/08\/11\/powerset-in-ruby\/ \n# See the link if you want a shorter version. \n# This was intended to show the reader how the method works. \nclass Array\n  # Adds a power_set method to every array, i.e.: [1, 2].power_set\n  def power_set\n    \n    # Injects into a blank array of arrays.\n    # acc is what we're injecting into\n    # you is each element of the array\n    inject([[]]) do |acc, you|\n      ret = []             # Set up a new array to add into\n      acc.each do |i|      # For each array in the injected array,\n        ret << i           # Add itself into the new array\n        ret << i + [you]   # Merge the array with a new array of the current element\n      end\n      ret       # Return the array we're looking at to inject more.\n    end\n    \n  end\n  \n  # A more functional and even clearer variant.\n  def func_power_set\n    inject([[]]) { |ps,item|    # for each item in the Array\n      ps +                      # take the powerset up to now and add\n      ps.map { |e| e + [item] } # it again, with the item appended to each element\n    }\n  end\nend\n\n#A direct translation of the \"power array\" version above\nrequire 'set'\nclass Set\n  def powerset \n    inject(Set[Set[]]) do |ps, item| \n      ps.union ps.map {|e| e.union (Set.new [item])}\n    end\n  end\nend\n\np [1,2,3,4].power_set\np %w(one two three).func_power_set\n\np Set[1,2,3].powerset\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":1590}
    {"lang_cluster":"Ruby","source_code":"\n\nSymbols = { 1=>'I', 5=>'V', 10=>'X', 50=>'L', 100=>'C', 500=>'D', 1000=>'M' }\nSubtractors = [ [1000, 100], [500, 100], [100, 10], [50, 10], [10, 1], [5, 1], [1, 0] ]\n\ndef roman(num)\n  return Symbols[num]  if Symbols.has_key?(num)\n  Subtractors.each do |cutPoint, subtractor| \n    return roman(cutPoint) + roman(num - cutPoint)      if num >  cutPoint\n    return roman(subtractor) + roman(num + subtractor)  if num >= cutPoint - subtractor and num < cutPoint\n  end\nend\n\n[1990, 2008, 1666].each do |i|\n  puts \"%4d => %s\"\u00a0% [i, roman(i)]\nend\n\n","human_summarization":"generate a Roman numeral representation of a given positive integer. The function starts from the leftmost digit and skips any digit with a value of zero. For instance, 1990 is represented as MCMXC, 2008 as MMVIII, and 1666 as MDCLXVI.","id":1591}
    {"lang_cluster":"Ruby","source_code":"\n\n# create an array with one object in it\na = ['foo']\n\n# the Array#new method allows several additional ways to create arrays\n\n# push objects into the array\na << 1         # [\"foo\", 1]\na.push(3,4,5)  # [\"foo\", 1, 3, 4, 5]\n\n# set the value at a specific index in the array\na[0] = 2       # [2, 1, 3, 4, 5]\n\n# a couple of ways to set a slice of the array\na[0,3] = 'bar'    # [\"bar\", 4, 5]\na[1..-1] = 'baz'  # [\"bar\", \"baz\"]\na[0] = nil        # [nil, \"baz\"]\na[0,1] = nil      # [\"baz\"]\n\n# retrieve an element\nputs a[0]\n","human_summarization":"demonstrate basic array syntax in a specific language, including creating an array, assigning a value to it, and retrieving an element. It also showcases both fixed-length and dynamic arrays, with a functionality to push a value into the array.","id":1592}
    {"lang_cluster":"Ruby","source_code":"\n\nstr = File.open('input.txt', 'rb') {|f| f.read}\nFile.open('output.txt', 'wb') {|f| f.write str}\n\n# Only if 'input.txt' is a text file!\n# Only if pipe '|' is not first character of path!\nstr = IO.read('input.txt')\nopen('output.txt', 'w') {|f| f.write str}\n\nrequire 'fileutils'\nFileUtils.copy_file 'input.txt', 'output.txt'\nWorks with: Just BASIC\nopen \"input.txt\" for input as #in\nfileLen   = LOF(#in)\t\t    'Length Of File\nfileData$ = input$(#in, fileLen)    'read entire file\nclose #in\n\nopen \"output.txt\" for output as #out\nprint #out, fileData$               'write entire fie\nclose #out \nend\n\nWorks with: Just BASIC\nopen \"input.txt\"  for input  as #in\nopen \"output.txt\" for output as #out\nfileLen   = LOF(#in)\t\t    'Length Of File\nprint #out, input$(#in, fileLen)    'entire file\nclose #in\nclose #out\n","human_summarization":"The code reads data from 'input.txt' file into an intermediate variable, then writes this data into a new file called 'output.txt'. It demonstrates file reading and writing operations in binary mode. It also includes a provision for copying file block by block using FileUtils from the standard library. The code avoids oneliners and operating system copy commands.","id":1593}
    {"lang_cluster":"Ruby","source_code":"\n\"alphaBETA\".downcase # => \"alphabeta\"\n\"alphaBETA\".upcase # => \"ALPHABETA\"\n\n\"alphaBETA\".swapcase # => \"ALPHAbeta\"\n\"alphaBETA\".capitalize # => \"Alphabeta\"\n\nWorks with: Ruby version  2.4\n'\u0125\u00e5\u00e7\u00fd\u0434\u0436\u043a'.upcase  # => \"\u0124\u00c5\u00c7\u00dd\u0414\u0416\u041a\"\n","human_summarization":"The code takes the string \"alphaBETA\" and converts it to both upper-case and lower-case using the default string literal or ASCII encoding. It also demonstrates additional case conversion functions, such as swapping case or capitalizing the first letter. The code supports full Unicode case mapping for most languages, with options for Turkic, Lithuanian and ASCII.","id":1594}
    {"lang_cluster":"Ruby","source_code":"\nPoint = Struct.new(:x, :y)\n\ndef distance(p1, p2)\n  Math.hypot(p1.x - p2.x, p1.y - p2.y)\nend\n\ndef closest_bruteforce(points)\n  mindist, minpts = Float::MAX, []\n  points.combination(2) do |pi,pj|\n    dist = distance(pi, pj)\n    if dist < mindist\n      mindist = dist\n      minpts = [pi, pj]\n    end\n  end\n  [mindist, minpts]\nend\n\ndef closest_recursive(points)\n  return closest_bruteforce(points) if points.length <= 3\n  xP = points.sort_by(&:x)\n  mid = points.length \/ 2\n  xm = xP[mid].x\n  dL, pairL = closest_recursive(xP[0,mid])\n  dR, pairR = closest_recursive(xP[mid..-1])\n  dmin, dpair = dL<dR ? [dL, pairL] : [dR, pairR]\n  yP = xP.find_all {|p| (xm - p.x).abs < dmin}.sort_by(&:y)\n  closest, closestPair = dmin, dpair\n  0.upto(yP.length - 2) do |i|\n    (i+1).upto(yP.length - 1) do |k|\n      break if (yP[k].y - yP[i].y) >= dmin\n      dist = distance(yP[i], yP[k])\n      if dist < closest\n        closest = dist\n        closestPair = [yP[i], yP[k]]\n      end\n    end\n  end\n  [closest, closestPair]\nend\n\npoints = Array.new(100) {Point.new(rand, rand)}\np ans1 = closest_bruteforce(points)\np ans2 = closest_recursive(points)\nfail \"bogus!\" if ans1[0] != ans2[0]\n\nrequire 'benchmark'\n\npoints = Array.new(10000) {Point.new(rand, rand)}\nBenchmark.bm(12) do |x|\n  x.report(\"bruteforce\") {ans1 = closest_bruteforce(points)}\n  x.report(\"recursive\")  {ans2 = closest_recursive(points)}\nend\n\n\n[0.005299616045889868, [#<struct Point x=0.24805908871087445, y=0.8413503128160198>, #<struct Point x=0.24355227214243136, y=0.8385620275629906>]]\n[0.005299616045889868, [#<struct Point x=0.24355227214243136, y=0.8385620275629906>, #<struct Point x=0.24805908871087445, y=0.8413503128160198>]]\n                   user     system      total        real\nbruteforce    43.446000   0.000000  43.446000 ( 43.530062)\nrecursive      0.187000   0.000000   0.187000 (  0.190000)\n\n","human_summarization":"The code provides two functions to solve the Closest Pair of Points problem in a two-dimensional space. The first function uses a brute-force algorithm with a time complexity of O(n^2), iterating over all pairs of points to find the closest pair. The second function uses a divide and conquer approach with a time complexity of O(n log n), sorting the points by coordinates and recursively finding the closest pair. The code returns the minimum distance and the pair of points with the minimum distance.","id":1595}
    {"lang_cluster":"Ruby","source_code":"\n\n# creating an empty array and adding values\na = []              #=> []\na[0] = 1            #=> [1]\na[3] = \"abc\"        #=> [1, nil, nil, \"abc\"]\na << 3.14           #=> [1, nil, nil, \"abc\", 3.14]\n\n# creating an array with the constructor\na = Array.new               #=> []\na = Array.new(3)            #=> [nil, nil, nil]\na = Array.new(3, 0)         #=> [0, 0, 0]\na = Array.new(3){|i| i*2}   #=> [0, 2, 4]\n\n# creating an empty hash\nh = {}              #=> {}\nh[\"a\"] = 1          #=> {\"a\"=>1}\nh[\"test\"] = 2.4     #=> {\"a\"=>1, \"test\"=>2.4}\nh[3] = \"Hello\"      #=> {\"a\"=>1, \"test\"=>2.4, 3=>\"Hello\"}\nh = {a:1, test:2.4, World!:\"Hello\"}\n                    #=> {:a=>1, :test=>2.4, :World!=>\"Hello\"}\n\n# creating a hash with the constructor\nh = Hash.new        #=> {}   (default value\u00a0: nil)\np h[1]              #=> nil\nh = Hash.new(0)     #=> {}   (default value\u00a0: 0)\np h[1]              #=> 0\np h                 #=> {}\nh = Hash.new{|hash, key| key.to_s}\n                    #=> {}\np h[123]            #=> \"123\"\np h                 #=> {}\nh = Hash.new{|hash, key| hash[key] = \"foo#{key}\"}\n                    #=> {}\np h[1]              #=> \"foo1\"\np h                 #=> {1=>\"foo1\"}\n\n# creating a struct\n\nPerson = Struct.new(:name, :age, :sex)\n\na = Person.new(\"Peter\", 15, :Man)\np a[0]              #=> \"Peter\"\np a[:age]           #=> 15\np a.sex             #=> :Man\np a.to_a            #=> [\"Peter\", 15, :Man]\np a.to_h            #=> {:name=>\"Peter\", :age=>15, :sex=>:Man}\n\nb = Person.new\np b                 #=> #<struct Person name=nil, age=nil, sex=nil>\nb.name = \"Margaret\"\nb[\"age\"] = 18\nb[-1] = :Woman\np b.values          #=> [\"Margaret\", 18, :Woman]\np b.members         #=> [:name, :age, :sex]\np b.size            #=> 3\n\nc = Person[\"Daniel\", 22, :Man]\np c.to_h            #=> {:name=>\"Daniel\", :age=>22, :sex=>:Man}\n\nrequire 'set'\n\n# different ways of creating a set\np s1 = Set[1, 2, 3, 4]          #=> #<Set: {1, 2, 3, 4}>\np s2 = [8, 6, 4, 2].to_set      #=> #<Set: {8, 6, 4, 2}>\np s3 = Set.new(1..4) {|x| x*2}  #=> #<Set: {2, 4, 6, 8}>\n\n# Union\np s1 | s2                       #=> #<Set: {1, 2, 3, 4, 8, 6}>\n# Intersection\np s1 & s2                       #=> #<Set: {4, 2}>\n# Difference\np s1 - s2                       #=> #<Set: {1, 3}>\n\np s1 ^ s2                       #=> #<Set: {8, 6, 1, 3}>\n\np s2 == s3                      #=> true\n\np s1.add(5)                     #=> #<Set: {1, 2, 3, 4, 5}>\np s1 << 0                       #=> #<Set: {1, 2, 3, 4, 5, 0}>\np s1.delete(3)                  #=> #<Set: {1, 2, 4, 5, 0}>\n\nrequire 'matrix'\n\n# creating a matrix\np m0 = Matrix.zero(3)       #=> Matrix[[0, 0, 0], [0, 0, 0], [0, 0, 0]]\np m1 = Matrix.identity(3)   #=> Matrix[[1, 0, 0], [0, 1, 0], [0, 0, 1]]\np m2 = Matrix[[11, 12], [21, 22]]\n                            #=> Matrix[[11, 12], [21, 22]]\np m3 = Matrix.build(3) {|row, col| row - col}\n                            #=> Matrix[[0, -1, -2], [1, 0, -1], [2, 1, 0]]\n\np m2[0,0]               #=> 11\np m1 * 5                #=> Matrix[[5, 0, 0], [0, 5, 0], [0, 0, 5]]\np m1 + m3               #=> Matrix[[1, -1, -2], [1, 1, -1], [2, 1, 1]]\np m1 * m3               #=> Matrix[[0, -1, -2], [1, 0, -1], [2, 1, 0]]\n\n# creating a Vector\np v1 = Vector[1,3,5]    #=> Vector[1, 3, 5]\np v2 = Vector[0,1,2]    #=> Vector[0, 1, 2]\np v1[1]                 #=> 3\np v1 * 2                #=> Vector[2, 6, 10]\np v1 + v2               #=> Vector[1, 4, 7]\n\np m1 * v1               #=> Vector[1, 3, 5]\np m3 * v1               #=> Vector[-13, -4, 5]\nOpen\nrequire 'ostruct'\n\n# creating a OpenStruct\nab = OpenStruct.new\np ab                #=> #<OpenStruct>\nab.foo = 25\np ab.foo            #=> 25\nab[:bar] = 2\np ab[\"bar\"]         #=> 2\np ab                #=> #<OpenStruct foo=25, bar=2>\nab.delete_field(\"foo\")\np ab.foo            #=> nil\np ab                #=> #<OpenStruct bar=2>\n\np son = OpenStruct.new({ :name => \"Thomas\", :age => 3 })\n                    #=> #<OpenStruct name=\"Thomas\", age=3>\np son.name          #=> \"Thomas\"\np son[:age]         #=> 3\nson.age += 1\np son.age           #=> 4\nson.items = [\"candy\",\"toy\"]\np son.items         #=> [\"candy\",\"toy\"]\np son               #=> #<OpenStruct name=\"Thomas\", age=4, items=[\"candy\", \"toy\"]\n","human_summarization":"The code creates a collection and adds a few values to it. It demonstrates the use of different collection types such as Arrays, Hashes, Structs, Sets, Matrix, Vector, and OpenStruct. The collections are used to represent sets of values, with Arrays being ordered and integer-indexed, Hashes allowing unique keys and values, Structs bundling attributes together, Sets implementing unordered values with no duplicates, and OpenStruct allowing the definition of arbitrary attributes with their values. The Matrix and Vector classes are used to represent mathematical matrices and vectors.","id":1596}
    {"lang_cluster":"Ruby","source_code":"\nBrute force method\nKnapsackItem = Struct.new(:volume, :weight, :value)\npanacea = KnapsackItem.new(0.025, 0.3, 3000)\nichor   = KnapsackItem.new(0.015, 0.2, 1800)\ngold    = KnapsackItem.new(0.002, 2.0, 2500)\nmaximum = KnapsackItem.new(0.25,  25,  0)\n\nmax_items = {}\nfor item in [panacea, ichor, gold]\n  max_items[item] = [(maximum.volume\/item.volume).to_i, (maximum.weight\/item.weight).to_i].min\nend\n\nmaxval = 0\nsolutions = []\n\n0.upto(max_items[ichor]) do |i|\n  0.upto(max_items[panacea]) do |p|\n    0.upto(max_items[gold]) do |g|\n      break if i*ichor.weight + p*panacea.weight + g*gold.weight > maximum.weight\n      break if i*ichor.volume + p*panacea.volume + g*gold.volume > maximum.volume\n      val = i*ichor.value + p*panacea.value + g*gold.value\n      if val > maxval\n        maxval = val\n        solutions = [[i, p, g]]\n      elsif val == maxval\n        solutions << [i, p, g]\n      end\n    end\n  end\nend\n\nputs \"The maximal solution has value #{maxval}\"\nsolutions.each do |i, p, g|\n  printf \"  ichor=%2d, panacea=%2d, gold=%2d -- weight:%.1f, volume=%.3f\\n\",\n    i, p, g,\n    i*ichor.weight + p*panacea.weight + g*gold.weight,\n    i*ichor.volume + p*panacea.volume + g*gold.volume \nend\n\n\n","human_summarization":"determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.","id":1597}
    {"lang_cluster":"Ruby","source_code":"\n(1..10).each do |i|\n  print i\n  break if i == 10\n  print \", \"\nend\nputs\n\nputs (1..10).join(\", \")\n","human_summarization":"generates a comma-separated list from 1 to 10 using separate output statements for the number and the comma within a loop. In the final iteration, only part of the loop body is executed. This is achieved using idiomatic Ruby.","id":1598}
    {"lang_cluster":"Ruby","source_code":"\n\nrequire 'tsort'\nclass Hash\n  include TSort\n  alias tsort_each_node each_key\n  def tsort_each_child(node, &block)\n    fetch(node).each(&block)\n  end\nend\n\ndepends = {}\nDATA.each do |line|\n  key, *libs = line.split\n  depends[key] = libs\n  libs.each {|lib| depends[lib] ||= []}\nend\n\nbegin\n  p depends.tsort\n  depends[\"dw01\"] << \"dw04\"\n  p depends.tsort\nrescue TSort::Cyclic => e\n  puts \"\\ncycle detected: #{e}\"\nend\n\n__END__\ndes_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\ndw01             ieee dw01 dware gtech\ndw02             ieee dw02 dware\ndw03             std synopsys dware dw03 dw02 dw01 ieee gtech\ndw04             dw04 ieee dw01 dware gtech\ndw05             dw05 ieee dware\ndw06             dw06 ieee dware\ndw07             ieee dware\ndware            ieee dware\ngtech            ieee gtech\nramlib           std ieee\nstd_cell_lib     ieee std_cell_lib\nsynopsys\n\n\n","human_summarization":"The code implements a function to determine a valid compile order of VHDL libraries based on their dependencies. It handles self-dependencies and flags any un-orderable dependencies. The function uses topological sorting, specifically Kahn's 1962 algorithm or depth-first search, to order the libraries. It assumes library names are single words and that items mentioned only as dependents have no dependents of their own. The function uses the TSort module from the Ruby standard library.","id":1599}
    {"lang_cluster":"Ruby","source_code":"\np 'abcd'.start_with?('ab')  #returns true\np 'abcd'.end_with?('ab')    #returns false\np 'abab'.include?('bb')     #returns false\np 'abab'.include?('ab')     #returns true\np 'abab'['bb']              #returns nil\np 'abab'['ab']              #returns \"ab\"\np 'abab'.index('bb')        #returns nil\np 'abab'.index('ab')        #returns 0\np 'abab'.index('ab', 1)     #returns 2\np 'abab'.rindex('ab')       #returns 2\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":1600}
    {"lang_cluster":"Ruby","source_code":"\ndef four_squares(low, high, unique=true, show=unique)\n  f = -> (a,b,c,d,e,f,g) {[a+b, b+c+d, d+e+f, f+g].uniq.size == 1}\n  if unique\n    uniq = \"unique\"\n    solutions = [*low..high].permutation(7).select{|ary| f.call(*ary)}\n  else\n    uniq = \"non-unique\"\n    solutions = [*low..high].repeated_permutation(7).select{|ary| f.call(*ary)}\n  end\n  if show\n    puts \" \" + [*\"a\"..\"g\"].join(\"  \")\n    solutions.each{|ary| p ary}\n  end\n  puts \"#{solutions.size} #{uniq} solutions in #{low} to #{high}\"\n  puts\nend\n\n[[1,7], [3,9]].each do |low, high|\n  four_squares(low, high)\nend\nfour_squares(0, 9, false)\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":1601}
    {"lang_cluster":"Ruby","source_code":"\nLibrary: Shoes\nSample display of Ruby solution\nShoes.app(:width=>205, :height => 228, :title => \"A Clock\") do\n  def draw_ray(width, start, stop, ratio)\n    angle = Math::PI * 2 * ratio - Math::PI\/2\n    strokewidth width\n    cos = Math::cos(angle)\n    sin = Math::sin(angle)\n    line 101+cos*start, 101+sin*start, 101+cos*stop, 101+sin*stop\n  end\n\n  def update\n    t = Time.now\n    @time.text = t.strftime(\"%H:%M:%S\")\n    h, m, s = (t.hour % 12).to_f, t.min.to_f, t.sec.to_f\n    s += t.to_f - t.to_i  # add the fractional seconds\n\n    @hands.clear do\n      draw_ray(3, 0, 70, (h + m\/60)\/12)\n      draw_ray(2, 0, 90, (m + s\/60)\/60)\n      draw_ray(1, 0, 95, s\/60)\n    end\n  end\n\n  # a place for the text display\n  @time = para(:align=>\"center\", :family => \"monospace\")\n\n  # draw the clock face\n  stack(:width=>203, :height=>203) do\n    strokewidth 1\n    fill gradient(deepskyblue, aqua)\n    oval 1, 1, 200\n    fill black\n    oval 98, 98, 6\n    # draw the minute indicators\n    0.upto(59) {|m| draw_ray(1, (m % 5 == 0 ? 96 : 98), 100, m.to_f\/60)}\n  end.move(0,23)\n\n  # the drawing area for the hands\n  @hands = stack(:width=>203, :height=>203) {}.move(0,23)\n\n  animate(5) {update}\nend\n\n\nBerlin-Uhr clock\nShoes.app(:title => \"Berlin-Uhr Clock\", :width => 209, :height => 300) do\n  background lightgrey\n\n  Red = rgb(255, 20, 20)\n  Yellow = rgb(173, 255, 47)\n  Green = rgb(154, 205, 50)\n  Gray = rgb(128, 128, 128)\n\n  @time = para(:align => \"center\")\n  stack do\n    fill Gray\n    stroke black\n    strokewidth 2\n    @seconds = oval 75, 3, 50\n    @hrs_a  =  4.times.collect {|i| rect   51*i,  56, 48, 30, 4}\n    @hrs_b  =  4.times.collect {|i| rect   51*i,  89, 48, 30, 4}\n    @mins_a = 11.times.collect {|i| rect 2+18*i, 122, 15, 30, 4}\n    @mins_b =  4.times.collect {|i| rect   51*i, 155, 48, 30, 4}\n    # some decoration\n    fill white\n    stroke darkslategray\n    rect -10, -30, 75, 70, 10\n    rect 140, -30, 75, 70, 10\n    rect -13, 192, 105, 100, 10\n    rect 110, 192, 105, 100, 10\n  end.move(3,20)\n    \n  animate(1) do\n    now = Time.now\n    @time.text = now.strftime(\"%H:%M:%S\")\n    @seconds.style(:fill => now.sec.even? ? Green : Gray)\n    a, b = now.hour.divmod(5)\n    4.times {|i| @hrs_a[i].style(:fill => i < a ? Red : Gray)}\n    4.times {|i| @hrs_b[i].style(:fill => i < b ? Red : Gray)}\n    a, b = now.min.divmod(5)\n    11.times {|i| @mins_a[i].style(:fill => i < a ? (i%3==2 ? Red : Yellow) : Gray)}\n    4.times  {|i| @mins_b[i].style(:fill => i < b ? Yellow : Gray)}\n  end\n  \n  keypress do |key|\n    case key\n    when :control_q, \"\\x11\" then exit\n    end\n  end\nend\n\nLibrary: RubyGems\nLibrary: JRubyArt\n\ndef setup\n  sketch_title 'Clock'\n  stroke 255\n  font = create_font 'NimbusRoman-Regular', 20\n  text_font font\nend\n\ndef draw\n  background 0\n  fill 80\n  no_stroke\n  clock_x = lambda do |val, adj, length|\n    DegLut.cos((val * adj).to_i - 90) * length + width \/ 2\n  end\n  clock_y = lambda do |val, adj, length|\n    DegLut.sin((val * adj).to_i - 90) * length + height \/ 2\n  end\n  ellipse 100, 100, 160, 160\n  stroke 220\n  stroke_weight 6\n  t = Time.now\n  line(100, 100, clock_x.call(t.hour % 12 + (t.min \/ 60.0), 30, 50),\n    clock_y.call(t.hour % 12 + (t.min \/ 60.0), 30, 50))\n  stroke_weight 3\n  line(100, 100, clock_x.call(t.min + (t.sec \/ 60.0), 6, 60),\n    clock_y.call(t.min + (t.sec \/ 60.0), 6, 60))\n  stroke 255, 0, 0\n  stroke_weight 1\n  line(100, 100, clock_x.call(t.sec, 6, 72), clock_y.call(t.sec, 6, 72))\n  # Draw the minute ticks\n  stroke_weight 2\n  stroke 255\n  (0..360).step(6) do |a|\n    x = 100 + DegLut.cos(a) * 72\n    y = 100 + DegLut.sin(a) * 72\n    point x, y\n  end\n  fill 200\n  text t.strftime('%H:%M:%S'), 50, 200\nend\n\ndef settings\n  size 200, 220\n  smooth 8\nend\n\n","human_summarization":"implement a visual time-keeping device, which can be of any type but must show the passage of seconds. The display must update every second and cycle periodically. The time displayed should be in sync with the system clock. The code avoids unnecessary system resource usage and maintains simplicity and clarity. An example of a Berlin-Uhr clock implemented in JRubyArt is provided.","id":1602}
    {"lang_cluster":"Ruby","source_code":"\n\nloadup.rb is the program loader.\n# loadup.rb - run UPPERCASE RUBY program\n\nclass Object\n  alias lowercase_method_missing method_missing\n\n  # Allow UPPERCASE method calls.\n  def method_missing(sym, *args, &block)\n    str = sym.to_s\n    if str == (down = str.downcase)\n      lowercase_method_missing sym, *args, &block\n    else\n      send down, *args, &block\n    end\n  end\n\n  # RESCUE an exception without the 'rescue' keyword.\n  def RESCUE(_BEGIN, _CLASS, _RESCUE)\n    begin _BEGIN.CALL\n    rescue _CLASS\n      _RESCUE.CALL; end\n  end\nend\n\n_PROGRAM = ARGV.SHIFT\n_PROGRAM || ABORT(\"USAGE: #{$0} PROGRAM.RB ARGS...\")\nLOAD($0 = _PROGRAM)\n\nCAL.RB is an UPPERCASE RUBY translation of Calendar#Ruby.\nWorks with: Ruby version 1.8.7\n# CAL.RB - CALENDAR\nREQUIRE 'DATE'.DOWNCASE\n\n# FIND CLASSES.\nOBJECT = [].CLASS.SUPERCLASS\nDATE = OBJECT.CONST_GET('DATE'.DOWNCASE.CAPITALIZE)\n\n# CREATES A CALENDAR OF _YEAR_. RETURNS THIS CALENDAR AS A MULTI-LINE\n# STRING FIT TO _COLUMNS_.\nOBJECT.SEND(:DEFINE_METHOD, :CAL) {|_YEAR, _COLUMNS|\n\n  # START AT JANUARY 1.\n  #\n  # DATE::ENGLAND MARKS THE SWITCH FROM JULIAN CALENDAR TO GREGORIAN\n  # CALENDAR AT 1752 SEPTEMBER 14. THIS REMOVES SEPTEMBER 3 TO 13 FROM\n  # YEAR 1752. (BY FORTUNE, IT KEEPS JANUARY 1.)\n  #\n  _DATE = DATE.NEW(_YEAR, 1, 1, DATE::ENGLAND)\n\n  # COLLECT CALENDARS OF ALL 12 MONTHS.\n  _MONTHS = (1..12).COLLECT {|_MONTH|\n    _ROWS = [DATE::MONTHNAMES[_MONTH].UPCASE.CENTER(20),\n             \"SU MO TU WE TH FR SA\"]\n\n    # MAKE ARRAY OF 42 DAYS, STARTING WITH SUNDAY.\n    _DAYS = []\n    _DATE.WDAY.TIMES { _DAYS.PUSH \"  \" }\n    CATCH(:BREAK) {\n      LOOP {\n        (_DATE.MONTH == _MONTH) || THROW(:BREAK)\n        _DAYS.PUSH(\"%2D\".DOWNCASE % _DATE.MDAY)\n        _DATE += 1 }}\n    (42 - _DAYS.LENGTH).TIMES { _DAYS.PUSH \"  \" }\n\n    _DAYS.EACH_SLICE(7) {|_WEEK| _ROWS.PUSH(_WEEK.JOIN \" \") }\n    _ROWS }\n\n  # CALCULATE MONTHS PER ROW (MPR).\n  #  1. DIVIDE COLUMNS BY 22 COLUMNS PER MONTH, ROUNDED DOWN. (PRETEND\n  #     TO HAVE 2 EXTRA COLUMNS; LAST MONTH USES ONLY 20 COLUMNS.)\n  #  2. DECREASE MPR IF 12 MONTHS WOULD FIT IN THE SAME MONTHS PER\n  #     COLUMN (MPC). FOR EXAMPLE, IF WE CAN FIT 5 MPR AND 3 MPC, THEN\n  #     WE USE 4 MPR AND 3 MPC.\n  _MPR = (_COLUMNS + 2).DIV 22\n  _MPR = 12.DIV((12 + _MPR - 1).DIV _MPR)\n\n  # USE 20 COLUMNS PER MONTH + 2 SPACES BETWEEN MONTHS.\n  _WIDTH = _MPR * 22 - 2\n\n  # JOIN MONTHS INTO CALENDAR.\n  _ROWS = [\"[SNOOPY]\".CENTER(_WIDTH), \"#{_YEAR}\".CENTER(_WIDTH)]\n  _MONTHS.EACH_SLICE(_MPR) {|_SLICE|\n    _SLICE[0].EACH_INDEX {|_I|\n      _ROWS.PUSH(_SLICE.MAP {|_A| _A[_I]}.JOIN \"  \") }}\n  _ROWS.JOIN(\"\\012\") }\n\n\n(ARGV.LENGTH == 1) || ABORT(\"USAGE: #{$0} YEAR\")\n\n# GUESS WIDTH OF TERMINAL.\n#  1. OBEY ENVIRONMENT VARIABLE COLUMNS.\n#  2. TRY TO REQUIRE 'IO\/CONSOLE' FROM RUBY 1.9.3.\n#  3. TRY TO RUN `TPUT CO`.\n#  4. ASSUME 80 COLUMNS.\nLOADERROR = OBJECT.CONST_GET('LOAD'.DOWNCASE.CAPITALIZE +\n                             'ERROR'.DOWNCASE.CAPITALIZE)\nSTANDARDERROR = OBJECT.CONST_GET('STANDARD'.DOWNCASE.CAPITALIZE +\n                                 'ERROR'.DOWNCASE.CAPITALIZE)\n_INTEGER = 'INTEGER'.DOWNCASE.CAPITALIZE\n_TPUT_CO = 'TPUT CO'.DOWNCASE\n_COLUMNS = RESCUE(PROC {SEND(_INTEGER, ENV[\"COLUMNS\"] || \"\")},\n                  STANDARDERROR,\n                  PROC {\n                    RESCUE(PROC {\n                             REQUIRE 'IO\/CONSOLE'.DOWNCASE\n                             IO.CONSOLE.WINSIZE[1]\n                           }, LOADERROR,\n                           PROC {\n                             RESCUE(PROC {\n                                      SEND(_INTEGER, `#{_TPUT_CO}`)\n                                    }, STANDARDERROR,\n                                    PROC {80}) }) })\n\nPUTS CAL(ARGV[0].TO_I, _COLUMNS)\n\nA local variable must start with a lowercase letter or an underscore, so we have many leading underscores (_YEAR, _COLUMN, _DATE and so on).\nWe form blocks with curly braces { ... }, never with lowercase keywords do ... end.\nOBJECT = [].CLASS.SUPERCLASS finds the superclass of the class of the empty array; this is the Object class! Class#CONST_GET finds some other classes.\nClass#DEFINE_METHOD defines a new method, Object#CAL, without a def keyword.\nKernel#LOOP, Kernel#THROW, Kernel#CATCH and operator || act like a while loop without a while keyword.\n$ ruby loadup.rb CAL.RB 1969   \n                                                             [SNOOPY]                                                             \n                                                               1969                                                               \n      JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE        \nSU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA\n          1  2  3  4                     1                     1         1  2  3  4  5               1  2  3   1  2  3  4  5  6  7\n 5  6  7  8  9 10 11   2  3  4  5  6  7  8   2  3  4  5  6  7  8   6  7  8  9 10 11 12   4  5  6  7  8  9 10   8  9 10 11 12 13 14\n12 13 14 15 16 17 18   9 10 11 12 13 14 15   9 10 11 12 13 14 15  13 14 15 16 17 18 19  11 12 13 14 15 16 17  15 16 17 18 19 20 21\n19 20 21 22 23 24 25  16 17 18 19 20 21 22  16 17 18 19 20 21 22  20 21 22 23 24 25 26  18 19 20 21 22 23 24  22 23 24 25 26 27 28\n26 27 28 29 30 31     23 24 25 26 27 28     23 24 25 26 27 28 29  27 28 29 30           25 26 27 28 29 30 31  29 30               \n                                            30 31                                                                                 \n        JULY                 AUGUST              SEPTEMBER              OCTOBER               NOVEMBER              DECEMBER      \nSU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA  SU MO TU WE TH FR SA\n       1  2  3  4  5                  1  2      1  2  3  4  5  6            1  2  3  4                     1      1  2  3  4  5  6\n 6  7  8  9 10 11 12   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8   7  8  9 10 11 12 13\n13 14 15 16 17 18 19  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15  14 15 16 17 18 19 20\n20 21 22 23 24 25 26  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22  21 22 23 24 25 26 27\n27 28 29 30 31        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29  28 29 30 31         \n                      31                                                                30                                        \n","human_summarization":"The code provides an algorithm for a calendar task, written entirely in uppercase, as per the requirements of \"real\" programmers from the 1960s era. It formats the calendar to fit a page that is 132 characters wide. The code is inspired by the articles \"Real Programmers Don't Use PASCAL\" and \"Real programmers think in UPPERCASE\". It also takes into account the practicality of programming in uppercase for those with hearing and sight difficulties. The code does not include Snoopy generation but instead outputs a placeholder. It is written in uppercase Ruby, using a custom program loader that responds to unknown method calls by calling their lowercase equivalents and defines Object#RESCUE to replace the 'rescue' keyword.","id":1603}
    {"lang_cluster":"Ruby","source_code":"class PythagoranTriplesCounter\n  def initialize(limit)\n    @limit = limit\n    @total = 0\n    @primitives = 0\n    generate_triples(3, 4, 5)\n  end\n  attr_reader :total, :primitives\n  \n  private\n  def generate_triples(a, b, c)\n    perim = a + b + c\n    return if perim > @limit\n\n    @primitives += 1\n    @total += @limit \/ perim\n\n    generate_triples( a-2*b+2*c, 2*a-b+2*c, 2*a-2*b+3*c)\n    generate_triples( a+2*b+2*c, 2*a+b+2*c, 2*a+2*b+3*c)\n    generate_triples(-a+2*b+2*c,-2*a+b+2*c,-2*a+2*b+3*c)\n  end\nend\n\nperim = 10\nwhile perim <= 100_000_000 \n  c = PythagoranTriplesCounter.new perim\n  p [perim, c.total, c.primitives]\n  perim *= 10\nend\n\n\n[10, 0, 0]\n[100, 17, 7]\n[1000, 325, 70]\n[10000, 4858, 703]\n[100000, 64741, 7026]\n[1000000, 808950, 70229]\n[10000000, 9706567, 702309]\n[100000000, 113236940, 7023027]\n","human_summarization":"determine the number of Pythagorean and primitive Pythagorean triples with a perimeter no larger than a given limit, and handle large perimeter values up to 100,000,000.","id":1604}
    {"lang_cluster":"Ruby","source_code":"\nWorks with: Ruby version 1.8.5\nLibrary: Ruby\/Tk\n require 'tk'\n \n window = TkRoot::new()\n window::mainloop()\n\nLibrary: GTK\n require 'gtk2'\n \n window = Gtk::Window.new.show\n Gtk.main\n\nLibrary: Shoes\nShoes.app {}\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":1605}
    {"lang_cluster":"Ruby","source_code":"\ndef letter_frequency(file)\n  letters = 'a' .. 'z'\n  File.read(file) .\n       split(\/\/) .\n       group_by {|letter| letter.downcase} .\n       select   {|key, val| letters.include? key} .\n       collect  {|key, val| [key, val.length]} \nend\n\nletter_frequency(ARGV[0]).sort_by {|key, val| -val}.each {|pair| p pair}\n\n\n$ ruby letterFrequency.rb letterFrequency.rb\n[\"e\", 34]\n[\"l\", 20]\n[\"t\", 17]\n[\"r\", 14]\n[\"a\", 12]\n[\"y\", 9]\n[\"c\", 8]\n[\"i\", 7]\n[\"v\", 6]\n[\"n\", 6]\n[\"f\", 6]\n[\"s\", 6]\n[\"d\", 5]\n[\"p\", 5]\n[\"k\", 5]\n[\"u\", 4]\n[\"o\", 4]\n[\"g\", 3]\n[\"b\", 2]\n[\"h\", 2]\n[\"q\", 2]\n[\"z\", 1]\n[\"w\", 1]\ndef letter_frequency(file)\n  freq = Hash.new(0)\n  file.each_char.lazy.grep(\/[[:alpha:]]\/).map(&:upcase).each_with_object(freq) do |char, freq_map|\n    freq_map[char] += 1\n  end\nend\n\nletter_frequency(ARGF).sort.each do |letter, frequency|\n  puts \"#{letter}: #{frequency}\"\nend\n\n\n$ ruby letter_frequency.rb \/usr\/share\/dict\/words\nA: 64439\nB: 15526\nC: 31872\nD: 28531\nE: 88833\nF: 10675\nG: 22712\nH: 19320\nI: 66986\nJ: 1948\nK: 8409\nL: 41107\nM: 22508\nN: 57144\nO: 48944\nP: 22274\nQ: 1524\nR: 57347\nS: 90113\nT: 53006\nU: 26118\nV: 7989\nW: 7530\nX: 2124\nY: 12652\nZ: 3281\n\u00c5: 1\n\u00e1: 10\n\u00e2: 6\n\u00e4: 7\n\u00e5: 3\n\u00e7: 5\n\u00e8: 28\n\u00e9: 144\n\u00ea: 6\n\u00ed: 2\n\u00f1: 8\n\u00f3: 8\n\u00f4: 2\n\u00f6: 16\n\u00fb: 3\n\u00fc: 12\n\n\np File.open(\"\/usr\/share\/dict\/words\",\"r\").each_char.tally\n\n","human_summarization":"open a text file and count the frequency of each letter. It can count all characters including punctuation or only letters from A to Z. The code is optimized for large files using lazy enumerables introduced in Ruby 2.0. It also works with unicode text and utilizes the \"tally\" feature introduced in Ruby 2.7 for enumerables.","id":1606}
    {"lang_cluster":"Ruby","source_code":"\nclass ListNode\n  attr_accessor :value, :succ\n\n  def initialize(value, succ=nil)\n    self.value = value\n    self.succ = succ\n  end\n\n  def each(&b)\n    yield self\n    succ.each(&b) if succ\n  end\n\n  include Enumerable\n\n  def self.from_array(ary)\n    head = self.new(ary[0], nil)\n    prev = head\n    ary[1..-1].each do |val|\n      node = self.new(val, nil)\n      prev.succ = node\n      prev = node\n    end\n    head\n  end\nend\n\nlist = ListNode.from_array([1,2,3,4])\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":1607}
    {"lang_cluster":"Ruby","source_code":"\nLibrary: Shoes\nShoes.app(:title => \"Fractal Tree\", :width => 600, :height => 600) do\n  background \"#fff\"\n  stroke \"#000\"\n  @deg_to_rad = Math::PI \/ 180.0\n  \n  def drawTree(x1, y1, angle, depth)\n    if depth != 0\n      x2 = x1 + (Math.cos(angle * @deg_to_rad) * depth * 10.0).to_i\n      y2 = y1 + (Math.sin(angle * @deg_to_rad) * depth * 10.0).to_i\n      \n      line x1, y1, x2, y2\n      \n      drawTree(x2, y2, angle - 20, depth - 1)\n      drawTree(x2, y2, angle + 20, depth - 1)      \n    end\n  end\n  \n  drawTree(300,550,-90,9)\nend\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":1608}
    {"lang_cluster":"Ruby","source_code":"\nclass Integer\n  def factors() (1..self).select { |n| (self\u00a0% n).zero? } end\nend\np 45.factors\n[1, 3, 5, 9, 15, 45]\n\n\nclass Integer\n  def factors\n    1.upto(Integer.sqrt(self)).select {|i| (self\u00a0% i).zero?}.inject([]) do |f, i| \n      f << self\/i unless i == self\/i\n      f << i\n    end.sort\n  end\nend\n[45, 53, 64].each {|n| puts \"#{n}\u00a0: #{n.factors}\"}\n\n","human_summarization":"calculate the factors of a given positive integer. The factors are the positive integers that can divide the input number without leaving a remainder. The code does not handle the cases of zero or negative integers. It also notes that every prime number has two factors: 1 and itself. The code optimizes the process by only looping up to the square root of the input number.","id":1609}
    {"lang_cluster":"Ruby","source_code":"\nWorks with: Ruby version 1.9.3+\nJ2justifier = {Left: :ljust, Right: :rjust, Center: :center}\n\n=begin\nJustify columns of textual tabular input where the record separator is the newline\nand the field separator is a 'dollar' character.\njustification can be Symbol; (:Left, :Right, or :Center).\n\nReturn the justified output as a string\n=end\ndef aligner(infile, justification = :Left)\n  fieldsbyrow = infile.map {|line| line.strip.split('$')}\n  # pad to same number of fields per record\n  maxfields = fieldsbyrow.map(&:length).max\n  fieldsbyrow.map! {|row| row + ['']*(maxfields - row.length)}\n  # calculate max fieldwidth per column\n  colwidths = fieldsbyrow.transpose.map {|column|\n    column.map(&:length).max\n  }\n  # pad fields in columns to colwidth with spaces\n  justifier = J2justifier[justification]\n  fieldsbyrow.map {|row|\n    row.zip(colwidths).map {|field, width|\n      field.send(justifier, width)\n    }.join(\" \")\n  }.join(\"\\n\")\nend\n\nrequire 'stringio'\n\ntextinfile = <<END\nGiven$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\nEND\n\nfor align in [:Left, :Right, :Center]\n  infile = StringIO.new(textinfile)\n  puts \"\\n# %s Column-aligned output:\" % align\n  puts aligner(infile, align)\nend\n\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":1610}
    {"lang_cluster":"Ruby","source_code":"\nX, Y, Z = 6, 2, 3\nDIR = {\"-\" => [1,0], \"|\" => [0,1], \"\/\" => [1,1]}\n\ndef cuboid(nx, ny, nz)\n  puts \"cuboid %d %d %d:\" % [nx, ny, nz]\n  x, y, z = X*nx, Y*ny, Z*nz\n  area = Array.new(y+z+1){\" \" * (x+y+1)}\n  draw_line = lambda do |n, sx, sy, c|\n    dx, dy = DIR[c]\n    (n+1).times do |i|\n      xi, yi = sx+i*dx, sy+i*dy\n      area[yi][xi] = (area[yi][xi]==\" \" ? c : \"+\")\n    end\n  end\n  nz    .times {|i| draw_line[x,     0,   Z*i, \"-\"]}\n  (ny+1).times {|i| draw_line[x,   Y*i, z+Y*i, \"-\"]}\n  nx    .times {|i| draw_line[z,   X*i,     0, \"|\"]}\n  (ny+1).times {|i| draw_line[z, x+Y*i,   Y*i, \"|\"]}\n  nz    .times {|i| draw_line[y,     x,   Z*i, \"\/\"]}\n  (nx+1).times {|i| draw_line[y,   X*i,     z, \"\/\"]}\n  puts area.reverse\nend\n\ncuboid(2, 3, 4)\ncuboid(1, 1, 1)\ncuboid(6, 2, 1)\ncuboid(2, 4, 1)\n\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":1611}
    {"lang_cluster":"Ruby","source_code":"\n\nLibrary: RubyGems\nrequire 'rubygems'\nrequire 'net\/ldap'\nldap = Net::LDAP.new(:host => 'ldap.example.com', :base => 'o=companyname')\nldap.authenticate('bind_dn', 'bind_pass')\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server using the Ruby LDAP package Net::LDAP.","id":1612}
    {"lang_cluster":"Ruby","source_code":"\n# Returns a copy of _s_ with rot13 encoding.\ndef rot13(s)\n  s.tr('A-Za-z', 'N-ZA-Mn-za-m')\nend\n\n# Perform rot13 on files from command line, or standard input.\nwhile line = ARGF.gets\n  print rot13(line)\nend\n\nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\n\n\nNOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm\n\n","human_summarization":"The code implements a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is 13 characters away in the 26 letter alphabet. It works on both upper and lower case letters, preserves case, and passes all non-alphabetic characters without alteration. The function can be wrapped in a utility program to perform a line-by-line rot-13 encoding of every line of input from each file listed on its command line or act as a filter on its standard input. It can be used to obfuscate text to prevent casual reading of spoiler or potentially offensive material.","id":1613}
    {"lang_cluster":"Ruby","source_code":"\nPerson = Struct.new(:name,:value) do\n  def to_s; \"name:#{name}, value:#{value}\" end\nend\n\nlist = [Person.new(\"Joe\",3),\n        Person.new(\"Bill\",4),\n        Person.new(\"Alice\",20),\n        Person.new(\"Harry\",3)]\nputs list.sort_by{|x|x.name}\nputs\nputs list.sort_by(&:value)\n\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":1614}
    {"lang_cluster":"Ruby","source_code":"\n\n\n\nfor\n\nRange#each\n\n\n\nfor i in 1..5\n  for j in 1..i\n    print \"*\"\n  end\n  puts\nend\n\n\n(1..5).each do |i|\n  (1..i).each do |j|\n    print \"*\"\n  end\n  puts\nend\n\n\n\n\nInteger#upto\n\nInteger#times\n\nKernel#loop\n\n\n\n1.upto(5) do |i|\n  1.upto(i) do |j|\n    print \"*\"\n  end\n  puts\nend\n\n\n5.times do |i|\n  # i goes from 0 to 4\n  (i+1).times do\n    print \"*\"\n  end\n  puts\nend\n\n\ni = 1\nloop do\n  j = 1\n  loop do\n    print \"*\"\n    break if (j += 1) > i\n  end\n  puts\n  break if (i += 1) > 5\nend\n\n\nputs (1..5).map { |i| \"*\" * i }\n","human_summarization":"The code demonstrates the use of nested 'for' loops in Ruby, where the number of iterations of the inner loop is controlled by the outer loop. It prints a pattern of asterisks, where each line has one more asterisk than the previous line. The code can be written in three different ways using Range#each, and can also be simplified to one line using Integer#upto, String#*, and Enumerable#map.","id":1615}
    {"lang_cluster":"Ruby","source_code":"\n\n{:name => 'Zeus', :planet => 'Jupiter'}\n\n{name: 'Zeus', planet: 'Jupiter'}\n\n{1 => 'two', three: 4}\n\n{}\n\nhash = {}\nhash[666] = 'devil'\nhash[777]  # => nil\nhash[666]  # => 'devil'\n\nhash = Hash.new('unknown key')\nhash[666] = 'devil'\nhash[777]  # => 'unknown key'\nhash[666]  # => 'devil'\n\nhash = Hash.new { |h, k| \"unknown key #{k}\" }\nhash[666] = 'devil'\nhash[777]  # => 'unknown key 777'\nhash[666]  # => 'devil'\n\nhash = Hash.new { |h, k| h[k] = \"key #{k} was added at #{Time.now}\" }\nhash[777]  # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'\nhash[555]  # => 'key 555 was added at Sun Apr 03 13:50:01 -0700 2011'\nhash[777]  # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'\n","human_summarization":"- Creates an associative array or hash\n- Demonstrates literal syntax for Hash objects in Ruby\n- Shows how to create a Hash with symbols as keys\n- Provides shorthand for symbol keys\n- Illustrates creation of a Hash with keys and values of different types\n- Creates an empty Hash\n- Constructs a Hash object that returns nil for unknown keys\n- Builds a Hash object that returns 'unknown key' for unknown keys\n- Creates a Hash object that returns a custom message with the key for unknown keys\n- Adds a timestamped entry to the hash when an unknown key is first encountered.","id":1616}
    {"lang_cluster":"Ruby","source_code":"\n\nmodule LCG\n  module Common\n    # The original seed of this generator.\n    attr_reader :seed\n\n    # Creates a linear congruential generator with the given _seed_.\n    def initialize(seed)\n      @seed = @r = seed\n    end\n  end\n\n  # LCG::Berkeley generates 31-bit integers using the same formula\n  # as BSD rand().\n  class Berkeley\n    include Common\n    def rand\n      @r = (1103515245 * @r + 12345) & 0x7fff_ffff\n    end\n  end\n\n  # LCG::Microsoft generates 15-bit integers using the same formula\n  # as rand() from the Microsoft C Runtime.\n  class Microsoft\n    include Common\n    def rand\n      @r = (214013 * @r + 2531011) & 0x7fff_ffff\n      @r >> 16\n    end\n  end\nend\n\n\nlcg = LCG::Berkeley.new(1)\np (1..5).map {lcg.rand}\n# prints [1103527590, 377401575, 662824084, 1147902781, 2035015474]\n\nlcg = LCG::Microsoft.new(1)\np (1..5).map {lcg.rand}\n# prints [41, 18467, 6334, 26500, 19169]\n\n","human_summarization":"The code replicates two historic random number generators, the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). It uses the linear congruential generator formula to generate a sequence of random numbers. The code also allows for the creation of multiple instances of LCG::Berkeley or LCG::Microsoft, each keeping the original seed and the current state. The .new method initializes a seed, the #rand method returns the next random number, and the #seed method returns the original seed.","id":1617}
    {"lang_cluster":"Ruby","source_code":"\nclass ListNode\n  def insert_after(search_value, new_value)\n    if search_value == value\n      self.succ = self.class.new(new_value, succ)\n    elsif self.succ.nil?\n      raise StandardError, \"value #{search_value} not found in list\"\n    else\n      self.succ.insert_after(search_value, new_value)\n    end\n  end\nend\n\nlist = ListNode.new(:a, ListNode.new(:b))\nlist.insert_after(:a, :c)\n\n","human_summarization":"\"Defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element C into a list of elements A->B, after element A.\"","id":1618}
    {"lang_cluster":"Ruby","source_code":"\n\ndef halve(x) = x\/2\ndef double(x) = x*2\n\n# iterative\ndef ethiopian_multiply(a, b)\n  product = 0\n  while a >= 1 \n    p [a, b, a.even?\u00a0? \"STRIKE\"\u00a0: \"KEEP\"] if $DEBUG\n    product += b unless a.even?\n    a = halve(a)\n    b = double(b)\n  end\n  product\nend\n\n# recursive\ndef rec_ethiopian_multiply(a, b)\n  return 0 if a < 1\n  p [a, b, a.even?\u00a0? \"STRIKE\"\u00a0: \"KEEP\"] if $DEBUG\n  (a.even?\u00a0? 0\u00a0: b) + rec_ethiopian_multiply(halve(a), double(b))\nend\n\n$DEBUG = true   # $DEBUG also set to true if \"-d\" option given\na, b = 20, 5\nputs \"#{a} * #{b} = #{ethiopian_multiply(a,b)}\"; puts\n\n","human_summarization":"The code defines three functions to perform Ethiopian multiplication. The first function halves an integer, the second function doubles an integer, and the third function checks if an integer is even. These functions are used to create a fourth function that performs Ethiopian multiplication, which involves repeatedly halving and doubling two numbers, discarding rows where the halved number is even, and summing the remaining doubled numbers.","id":1619}
    {"lang_cluster":"Ruby","source_code":"Works with: Ruby version 2.1\nclass TwentyFourGame\n  EXPRESSIONS = [\n    '((%dr %s %dr) %s %dr) %s %dr',\n    '(%dr %s (%dr %s %dr)) %s %dr',\n    '(%dr %s %dr) %s (%dr %s %dr)',\n    '%dr %s ((%dr %s %dr) %s %dr)',\n    '%dr %s (%dr %s (%dr %s %dr))',\n  ]\n  \n  OPERATORS = [:+, :-, :*, :\/].repeated_permutation(3).to_a\n  \n  def self.solve(digits)\n    solutions = []\n    perms = digits.permutation.to_a.uniq\n    perms.product(OPERATORS, EXPRESSIONS) do |(a,b,c,d), (op1,op2,op3), expr|\n      # evaluate using rational arithmetic\n      text = expr % [a, op1, b, op2, c, op3, d]\n      value = eval(text)  rescue next                 # catch division by zero\n      solutions << text.delete(\"r\")  if value == 24\n    end\n    solutions\n  end\nend\n\n# validate user input\ndigits = ARGV.map do |arg| \n  begin\n    Integer(arg)\n  rescue ArgumentError\n    raise \"error: not an integer: '#{arg}'\"\n  end\nend\ndigits.size == 4 or raise \"error: need 4 digits, only have #{digits.size}\"\n\nsolutions = TwentyFourGame.solve(digits)\nif solutions.empty?\n  puts \"no solutions\"\nelse\n  puts \"found #{solutions.size} solutions, including #{solutions.first}\"\n  puts solutions.sort\nend\n\n\n","human_summarization":"The code accepts four digits, either from user input or randomly generated, and calculates arithmetic expressions following the 24 game rules. It also displays examples of the solutions it generates.","id":1620}
    {"lang_cluster":"Ruby","source_code":"\n\nWith large n, the recursion can overflow the call stack and raise a SystemStackError. So factorial_recursive(10000) might fail.\nMRI does not optimize tail recursion. So factorial_tail_recursive(10000) might also fail.\n# Recursive\ndef factorial_recursive(n)\n  n.zero?\u00a0? 1\u00a0: n * factorial_recursive(n - 1)\nend\n\n# Tail-recursive\ndef factorial_tail_recursive(n, prod = 1)\n  n.zero?\u00a0? prod\u00a0: factorial_tail_recursive(n - 1, prod * n)\nend\n\n# Iterative with Range#each\ndef factorial_iterative(n)\n  (2...n).each { |i| n *= i }\n  n.zero?\u00a0? 1\u00a0: n\nend\n\n# Iterative with Range#inject\ndef factorial_inject(n)\n  (1..n).inject(1){ |prod, i| prod * i }\nend\n\n# Iterative with Range#reduce, requires Ruby 1.8.7\ndef factorial_reduce(n)\n  (2..n).reduce(1,\u00a0:*)\nend\n\n\nrequire 'benchmark'\n\nn = 400\nm = 10000\n\nBenchmark.bm(16) do |b|\n  b.report('recursive:')       {m.times {factorial_recursive(n)}}\n  b.report('tail recursive:')  {m.times {factorial_tail_recursive(n)}}\n  b.report('iterative:')       {m.times {factorial_iterative(n)}}\n  b.report('inject:')          {m.times {factorial_inject(n)}}\n  b.report('reduce:')          {m.times {factorial_reduce(n)}}\nend\n\n\n","human_summarization":"The code implements a function that calculates the factorial of a given number, either iteratively or recursively. The function may optionally handle errors for negative input numbers. Performance may vary depending on the Ruby implementation used.","id":1621}
    {"lang_cluster":"Ruby","source_code":"\n\nWorks with: Ruby version 1.8.7+\ndef generate_word(len)\n  [*\"1\"..\"9\"].shuffle.first(len)        # [*\"1\"..\"9\"].sample(len)  ver 1.9+\nend\n\ndef get_guess(len)\n  loop do\n    print \"Enter a guess: \"\n    guess = gets.strip\n    err = case\n          when guess.match(\/[^1-9]\/)             ; \"digits only\"\n          when guess.length != len               ; \"exactly #{len} digits\"\n          when guess.split(\"\").uniq.length != len; \"digits must be unique\"\n          else return guess.split(\"\")\n          end\n    puts \"the word must be #{len} unique digits between 1 and 9 (#{err}). Try again.\"\n  end\nend\n\ndef score(word, guess)\n  bulls = cows = 0\n  guess.each_with_index do |num, idx|\n    if word[idx] == num\n      bulls += 1\n    elsif word.include? num\n      cows += 1\n    end\n  end \n  [bulls, cows]\nend\n\nword_length = 4\nputs \"I have chosen a number with #{word_length} unique digits from 1 to 9.\"\nword = generate_word(word_length)\ncount = 0\nloop do\n  guess = get_guess(word_length)\n  count += 1\n  break if word == guess\n  puts \"that guess has %d bulls and %d cows\" % score(word, guess)\nend\nputs \"you guessed correctly in #{count} tries.\"\n\n\nWorks with: Ruby version 2.0+\nsize = 4\nsecret = [*'1' .. '9'].sample(size)\nguess = nil\n\ni=0\nloop do\n  i+=1\n  loop do\n    print \"Guess #{i}: \"\n    guess = gets.chomp.chars\n    exit if guess.empty?\n    \n    break if guess.size == size and \n             guess.all? { |x| ('1'..'9').include? x } and\n             guess.uniq.size == size\n    \n    puts \"Problem, try again. You need to enter #{size} unique digits from 1 to 9\"\n  end\n  \n  if guess == secret\n    puts \"Congratulations you guessed correctly in #{i} attempts\"\n    break\n  end\n  \n  bulls = cows = 0\n  size.times do |j|\n    if guess[j] == secret[j]\n      bulls += 1\n    elsif secret.include? guess[j]\n      cows += 1\n    end\n  end\n  \n  puts \"Bulls: #{bulls}; Cows: #{cows}\"\nend\n\n","human_summarization":"The code generates a unique four-digit random number from 1 to 9, prompts the user for guesses, rejects malformed guesses, and calculates a score based on the match between the guess and the random number. The game ends when the guess matches the random number. The score is calculated by assigning one bull for each digit that matches the random number in the correct position and one cow for each digit that is present in the random number but in the wrong position. Inspired by Python and Tcl.","id":1622}
    {"lang_cluster":"Ruby","source_code":"\nArray.new(1000) { 1 + Math.sqrt(-2 * Math.log(rand)) * Math.cos(2 * Math::PI * rand) }\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":1623}
    {"lang_cluster":"Ruby","source_code":"\n\nirb(main):001:0> require 'matrix'\n=> true\nirb(main):002:0> Vector[1, 3, -5].inner_product Vector[4, -2, -1]\n=> 3\n\nclass Array\n  def dot_product(other)\n    raise \"not the same size!\" if self.length\u00a0!= other.length\n    zip(other).sum {|a, b| a*b}\n  end\nend\n\np [1, 3, -5].dot_product [4, -2, -1]   # => 3\n","human_summarization":"The code computes the dot product of two vectors of the same length by multiplying corresponding elements and summing the results. It can handle vectors of arbitrary length. The vectors for the example provided are [1, 3, -5] and [4, -2, -1]. The code may also use the 'matrix' library and call Vector#inner_product to compute the dot product.","id":1624}
    {"lang_cluster":"Ruby","source_code":"\n\nstream = $stdin\nstream.each do |line|\n  # process line\nend\n\n\n# Create an array of lengths of every line.\nary = stream.map {|line| line.chomp.length}\n\n\n","human_summarization":"The code reads data from a text stream either word-by-word or line-by-line until there is no more data. It uses Ruby's IO objects and their methods like IO#each or IO#each_line for iteration, and Enumerable#map for looping through lines. The amount of data in the stream is unknown.","id":1625}
    {"lang_cluster":"Ruby","source_code":"\nLibrary: REXML\nrequire(\"rexml\/document\")\ninclude REXML\n(doc = Document.new) << XMLDecl.new\nroot = doc.add_element('root')\nelement = root.add_element('element')\nelement.add_text('Some text here')\n\n# save to a string \n# (the first argument to write() needs an object that understands \"<<\")\nserialized = String.new\ndoc.write(serialized, 4)\nputs serialized\n\n\n<?xml version='1.0'?>\n<root>\n    <element>\n        Some text here\n    <\/element>\n<\/root>\n","human_summarization":"Create a simple DOM and serialize it into a specific XML format.","id":1626}
    {"lang_cluster":"Ruby","source_code":"\nversion 1.9+t = Time.now\n\n# textual\nputs t        # => 2013-12-27 18:00:23 +0900\n\n# epoch time\nputs t.to_i   # => 1388134823\n\n# epoch time with fractional seconds\nputs t.to_f   # => 1388134823.9801579\n\n# epoch time as a rational (more precision):\nputs Time.now.to_r  # 1424900671883862959\/1000000000\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":1627}
    {"lang_cluster":"Ruby","source_code":"\nSedol_char = \"0123456789BCDFGHJKLMNPQRSTVWXYZ\"\nSedolweight = [1,3,1,7,3,9]\n\ndef char2value(c)\n  raise ArgumentError, \"Invalid char #{c}\" unless Sedol_char.include?(c)\n  c.to_i(36)\nend\n \ndef checksum(sedol)\n  raise ArgumentError, \"Invalid length\" unless sedol.size == Sedolweight.size\n  sum = sedol.chars.zip(Sedolweight).sum{|ch, weight| char2value(ch) * weight }\n  ((10 - (sum % 10)) % 10).to_s\nend\n \ndata = %w(710889\n          B0YBKJ\n          406566\n          B0YBLH\n          228276\n          B0YBKL\n          557910\n          B0YBKR\n          585284\n          B0YBKT\n          B00030\n          C0000\n          1234567\n          00000A)\n \ndata.each do |sedol|\n  print \"%-8s \" % sedol\n  begin\n    puts sedol + checksum(sedol)\n  rescue => e\n    p e\n  end\nend\n\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":1628}
    {"lang_cluster":"Ruby","source_code":"\nLibrary: Shoes\n\n\nShoes.app :width => 500, :height => 500, :resizable => false do\n  image 400, 470, :top => 30, :left => 50 do\n    nostroke\n    fill \"#127\"\n    image :top => 230, :left => 0 do\n      oval 70, 130, 260, 40\n      blur 30\n    end\n    oval 10, 10, 380, 380\n    image :top => 0, :left => 0 do\n      fill \"#46D\"\n      oval 30, 30, 338, 338\n      blur 10\n    end\n    fill gradient(rgb(1.0, 1.0, 1.0, 0.7), rgb(1.0, 1.0, 1.0, 0.0))\n    oval 80, 14, 240, 176\n    image :top => 0, :left => 0 do\n      fill \"#79F\"\n      oval 134, 134, 130, 130\n      blur 40\n    end\n    image :top => 150, :left => 40, :width => 320, :height => 260 do\n      fill gradient(rgb(0.7, 0.9, 1.0, 0.0), rgb(0.7, 0.9, 1.0, 0.6))\n      oval 60, 60, 200, 136\n      blur 20\n    end\n  end\nend\n\n","human_summarization":"\"Code to draw a sphere, either graphically or in ASCII art, with static or rotational projection capabilities.\"","id":1629}
    {"lang_cluster":"Ruby","source_code":"\n\nclass Integer\n  def ordinalize\n    num = self.abs\n    ordinal = if (11..13).include?(num % 100)\n      \"th\"\n    else\n      case num % 10\n        when 1; \"st\"\n        when 2; \"nd\"\n        when 3; \"rd\"\n        else    \"th\"\n      end\n    end\n    \"#{self}#{ordinal}\"\n  end\nend\n\n[(0..25),(250..265),(1000..1025)].each{|r| puts r.map(&:ordinalize).join(\", \"); puts}\n\n\n","human_summarization":"The code is a function that accepts an integer (0 or greater) as an input and returns a string representation of the number with an ordinal suffix. The function also demonstrates its output for specific ranges: 0-25, 250-265, and 1000-1025. The use of apostrophes in the output is optional.","id":1630}
    {"lang_cluster":"Ruby","source_code":"\n\"She was a soul stripper. She took my heart!\".delete(\"aei\")  # => \"Sh ws  soul strppr. Sh took my hrt!\"\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":1631}
    {"lang_cluster":"Ruby","source_code":"\ndef general_fizzbuzz(text)\n  num, *nword = text.split\n  num = num.to_i\n  dict = nword.each_slice(2).map{|n,word| [n.to_i,word]}\n  (1..num).each do |i|\n    str = dict.map{|n,word| word if i%n==0}.join\n    puts str.empty? ? i : str\n  end\nend\n\ntext = <<EOS\n20\n3 Fizz\n5 Buzz\n7 Baxx\nEOS\n\ngeneral_fizzbuzz(text)\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":1632}
    {"lang_cluster":"Ruby","source_code":"\n\nstr = \"llo world\"\nstr.prepend(\"He\")\np str #=> \"Hello world\"\n\n","human_summarization":"create a string variable, prepend it with another string literal, and display the content of the variable. If possible, the task should be accomplished without referring to the variable twice in one expression.","id":1633}
    {"lang_cluster":"Ruby","source_code":"\nLibrary: Shoes\nPoint = Struct.new(:x, :y)\nLine = Struct.new(:start, :stop)\n\nShoes.app(:width => 800, :height => 600, :resizable => false) do\n\n  def split_segments(n)\n    dir = 1\n    @segments = @segments.inject([]) do |new, l|\n      a, b, c, d = l.start.x, l.start.y, l.stop.x, l.stop.y\n\n      mid_x = a + (c-a)\/2.0 - (d-b)\/2.0*dir\n      mid_y = b + (d-b)\/2.0 + (c-a)\/2.0*dir\n      mid_p = Point.new(mid_x, mid_y)\n\n      dir *= -1\n      new << Line.new(l.start, mid_p)\n      new << Line.new(mid_p, l.stop)\n    end\n  end\n\n  @segments = [Line.new(Point.new(200,200), Point.new(600,200))]\n  15.times do |n|\n    info \"calculating frame #{n}\"\n    split_segments(n)\n  end\n\n  stack do\n    @segments.each do |l|\n      line l.start.x, l.start.y, l.stop.x, l.stop.y\n    end\n  end\nend\n\nLibrary: RubyGems\nLibrary: JRubyArt\nLEN = 3\nGEN = 14\nattr_reader :angle\n\ndef setup\n  sketch_title 'Heighway Dragon'\n  background(0, 0, 255)\n  translate(170, 170)\n  stroke(255)\n  @angle = 90.radians\n  turn_left(GEN)\nend\n\ndef draw_line\n  line(0, 0, 0, -LEN)\n  translate(0, -LEN)\nend\n\ndef turn_right(gen)\n  return draw_line if gen.zero?\n\n  turn_left(gen - 1)\n  rotate(angle)\n  turn_right(gen - 1)\nend\n\ndef turn_left(gen)\n  return draw_line if gen.zero?\n\n  turn_left(gen - 1)\n  rotate(-angle)\n  turn_right(gen - 1)\nend\n\ndef settings\n  size(700, 600)\nend\n\nLibrary: RubyGems\nLibrary: JRubyArt\nLibrary: cf3ruby\n\nrequire 'cf3'\n\nINV_SQRT = 1 \/ Math.sqrt(2)\n\ndef setup_the_dragon\n  @dragon = ContextFree.define do\n    shape :start do\n      dragon alpha: 1\n    end\n\n    shape :dragon do\n      square hue: 0, brightness: 0, saturation: 1, alpha: 0.02\n      split do\n        dragon size: INV_SQRT, rotation: -45, x: 0.25, y: 0.25\n        rewind\n        dragon size: INV_SQRT, rotation: 135, x: 0.25, y: 0.25\n        rewind\n      end\n    end\n  end\nend\n\ndef settings\n  size 800, 500\nend\n\ndef setup\n  sketch_title 'Heighway Dragon'\n  setup_the_dragon\n  draw_it\nend\n\ndef draw_it\n  background 255\n  @dragon.render :start, size: width * 0.8, stop_size: 2,\n                         start_x: width \/ 3, start_y: height \/ 3.5\nend\n\n","human_summarization":"The code generates a dragon curve fractal, which can be displayed directly or written to an image file. It uses various algorithms to achieve this, including recursive methods, successive approximation, iterative methods, and absolute direction calculation. The code also includes functionality to calculate absolute X,Y coordinates of a point and to test whether a given X,Y point or segment is on the curve. The dragon curve can be generated as a Lindenmayer system of expansions, and the code can limit the curve drawn to a certain number of points. The code is also capable of drawing other curves defined by L-systems.","id":1634}
    {"lang_cluster":"Ruby","source_code":"\nn = rand(1..10)\nputs 'Guess the number: '\nputs 'Wrong! Guess again: ' until gets.to_i == n\nputs 'Well guessed!'\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":1635}
    {"lang_cluster":"Ruby","source_code":"\np ('a' .. 'z').to_a\np [*'a' .. 'z']\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":1636}
    {"lang_cluster":"Ruby","source_code":"\n[5,50,9000].each do |n|\n  puts \"%b\"\u00a0% n\nend\n\nfor n in [5,50,9000]\n  puts n.to_s(2)\nend\n\n","human_summarization":"\"Output: The code takes a non-negative integer as input and converts it into its binary representation. It uses built-in radix functions or a user-defined function to achieve this. The binary output is displayed with no leading zeros, whitespace, radix, or sign markers. Each binary number is followed by a newline.\"","id":1637}
    {"lang_cluster":"Ruby","source_code":"\nWorks with: Ruby version 2.6.6\nLibrary: gtk3\nrequire 'gtk3'\n\nWidth, Height = 320, 240\nPosX, PosY = 100, 100\n\nwindow = Gtk::Window.new\nwindow.set_default_size(Width, Height)\nwindow.title = 'Draw a pixel'\n\nwindow.signal_connect(:draw) do |widget, context|\n  context.set_antialias(Cairo::Antialias::NONE)\n  # paint out bg with white\n  # context.set_source_rgb(1.0, 1.0, 1.0)\n  # context.paint(1.0)\n  # draw a rectangle\n  context.set_source_rgb(1.0, 0.0, 0.0)\n  context.fill do\n    context.rectangle(PosX, PosY, 1, 1)\n  end\nend\n\nwindow.signal_connect(:destroy) { Gtk.main_quit }\n\nwindow.show\nGtk.main\n\n","human_summarization":"\"Creates a 320x240 window and draws a single red pixel at position (100, 100).\"","id":1638}
    {"lang_cluster":"Ruby","source_code":"\nfullname = favouritefruit = \"\"\nneedspeeling = seedsremoved = false\notherfamily = []\n\nIO.foreach(\"config.file\") do |line|\n  line.chomp!\n  key, value = line.split(nil, 2)\n  case key\n  when \/^([#;]|$)\/; # ignore line\n  when \"FULLNAME\"; fullname = value\n  when \"FAVOURITEFRUIT\"; favouritefruit = value\n  when \"NEEDSPEELING\"; needspeeling = true\n  when \"SEEDSREMOVED\"; seedsremoved = true\n  when \"OTHERFAMILY\"; otherfamily = value.split(\",\").map(&:strip)\n  when \/^.\/; puts \"#{key}: unknown key\"\n  end\nend\n\nputs \"fullname       = #{fullname}\"\nputs \"favouritefruit = #{favouritefruit}\"\nputs \"needspeeling   = #{needspeeling}\"\nputs \"seedsremoved   = #{seedsremoved}\"\notherfamily.each_with_index do |name, i|\n  puts \"otherfamily(#{i+1}) = #{name}\"\nend\n\n\n","human_summarization":"read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.","id":1639}
    {"lang_cluster":"Ruby","source_code":"\ninclude Math\n\nRadius = 6372.8  # rough radius of the Earth, in kilometers\n\ndef spherical_distance(start_coords, end_coords)\n  lat1, long1 = deg2rad *start_coords\n  lat2, long2 = deg2rad *end_coords\n  2 * Radius * asin(sqrt(sin((lat2-lat1)\/2)**2 + cos(lat1) * cos(lat2) * sin((long2 - long1)\/2)**2))\nend\n\ndef deg2rad(lat, long)\n  [lat * PI \/ 180, long * PI \/ 180]\nend\n\nbna = [36.12, -86.67]\nlax = [33.94, -118.4]\n\nputs \"%.1f\" % spherical_distance(bna, lax)\n\n\n","human_summarization":"implement the Haversine formula to calculate the great-circle distance between Nashville International Airport and Los Angeles International Airport. The codes use either the authalic radius (6371.0 km) or the average great-circle radius (6372.8 km) for the earth, with the latter being recommended for more accurate results.","id":1640}
    {"lang_cluster":"Ruby","source_code":"\n\nrequire 'open-uri'\n\nprint open(\"http:\/\/rosettacode.org\") {|f| f.read}\n\nrequire 'fileutils'\nrequire 'open-uri'\n\nopen(\"http:\/\/rosettacode.org\/\") {|f| FileUtils.copy_stream(f, $stdout)}\n","human_summarization":"\"Code accesses a URL's content and prints it to the console using FileUtils.copy_stream for large content.\"","id":1641}
    {"lang_cluster":"Ruby","source_code":"\n def luhn_valid?(str)\n   str.scan(\/\\d\/).reverse            #using str.to_i.digits fails for cases with leading zeros\n      .each_slice(2)\n      .sum { |i, k = 0| i.to_i + ((k.to_i)*2).digits.sum }\n      .modulo(10).zero?\n end\n\n[\"49927398716\", \"49927398717\", \"1234567812345678\", \"1234567812345670\"].map{ |i| luhn_valid?(i) }\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It first reverses the order of the digits in the number. Then, it calculates the sum of every other odd digit (s1) and the sum of the doubled even digits (s2). If the sum of s1 and s2 ends in zero, the number is a valid credit card number. The code tests this functionality on four different numbers.","id":1642}
    {"lang_cluster":"Ruby","source_code":"\nn = (ARGV[0] || 41).to_i\nk = (ARGV[1] || 3).to_i\n\nprisoners = (0...n).to_a\nprisoners.rotate!(k-1).shift  while prisoners.length > 1\nputs prisoners.first\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":1643}
    {"lang_cluster":"Ruby","source_code":"\n\"ha\" * 5  # ==> \"hahahahaha\"\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":1644}
    {"lang_cluster":"Ruby","source_code":"\n\nstr = \"I am a string\"\np \"Ends with 'string'\" if str =~ \/string$\/\np \"Does not start with 'You'\" unless str =~ \/^You\/\n\nstr.sub(\/ a \/, ' another ') #=> \"I am another string\"\n# Or:\nstr[\/ a \/] = ' another '    #=> \"another\"\nstr                         #=> \"I am another string\"\n\nstr.gsub(\/\\bam\\b\/) { |match| match.upcase } #=> \"I AM a string\"\n","human_summarization":"- Matches a string with a regular expression\n- Replaces a part of the string using a regular expression\n- Tests the substitution\n- Performs substitution using a block","id":1645}
    {"lang_cluster":"Ruby","source_code":"\nputs 'Enter x and y'\nx = gets.to_i  # to check errors, use x=Integer(gets)\ny = gets.to_i\n\nputs \"Sum: #{x+y}\",\n     \"Difference: #{x-y}\",\n     \"Product: #{x*y}\",\n     \"Quotient: #{x\/y}\",       # truncates towards negative infinity\n     \"Quotient: #{x.fdiv(y)}\", # float\n     \"Remainder: #{x%y}\",      # same sign as second operand\n     \"Exponentiation: #{x**y}\",\n     \"Quotient: %d with Remainder: %d\"\u00a0% x.divmod(y)\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":1646}
    {"lang_cluster":"Ruby","source_code":"\ndef countSubstrings str, subStr\n  str.scan(subStr).length\nend\n\np countSubstrings \"the three truths\", \"th\"      #=> 3\np countSubstrings \"ababababab\", \"abab\"          #=> 2\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the main string and the substring to search for. It returns an integer representing the count of the non-overlapping occurrences. The function does not count overlapping substrings and matches from left-to-right or right-to-left for the highest number of non-overlapping matches.","id":1647}
    {"lang_cluster":"Ruby","source_code":"\ndef move(num_disks, start=0, target=1, using=2)\n  if num_disks == 1\n   @towers[target] << @towers[start].pop\n    puts \"Move disk from #{start} to #{target}\u00a0: #{@towers}\"\n  else\n    move(num_disks-1, start, using, target)\n    move(1,           start, target, using)\n    move(num_disks-1, using, target, start)\n  end \nend\n\nn = 5\n@towers = [[*1..n].reverse, [], []]\nmove(n)\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":1648}
    {"lang_cluster":"Ruby","source_code":"Works with: Ruby version 1.8.7+\nclass Integer\n  # binomial coefficient: n C k\n  def choose(k)\n    # n!\/(n-k)!\n    pTop = (self-k+1 .. self).inject(1, &:*) \n    # k!\n    pBottom = (2 .. k).inject(1, &:*)\n    pTop \/ pBottom\n  end\nend\n\np 5.choose(3)\np 60.choose(30)\n\n\n10\n118264581564861424\n\ndef c n, r\n  (0...r).inject(1) do |m,i| (m * (n - i)) \/ (i + 1) end\nend\nRuby's Arrays have a combination method which result in a (lazy) enumerator. This Enumerator has a \"size\" method, which returns the size of the enumerator, or nil if it can\u2019t be calculated lazily. (Since Ruby 2.0)\n(1..60).to_a.combination(30).size  #=> 118264581564861424\n\n","human_summarization":"The code calculates any binomial coefficient using the given formula. It is able to output the binomial coefficient of 5 choose 3, which equals to 10. It also handles tasks related to combinations and permutations, both with and without replacement.","id":1649}
    {"lang_cluster":"Ruby","source_code":"\nclass Array\n  def shellsort!\n    inc = length \/ 2\n    while inc != 0\n      inc.step(length-1) do |i|\n        el = self[i]\n        while i >= inc and self[i - inc] > el\n          self[i] = self[i - inc]\n          i -= inc\n        end\n        self[i] = el\n      end\n      inc = (inc == 2 ? 1 : (inc * 5.0 \/ 11).to_i)\n    end\n    self\n  end\nend\n\ndata = [22, 7, 2, -5, 8, 4]\ndata.shellsort!\np data # [-5, 2, 4, 7, 8, 22]\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This method, invented by Donald Shell, uses a diminishing increment sequence for interleaved insertion sorts. The increment size is reduced after each pass until it reaches 1, at which point the data is almost sorted. The sequence can be any as long as it ends in 1, with a geometric increment sequence of ratio 2.2 shown to work well. The method sorts in place, so a copy should be made if the original list needs to be preserved.","id":1650}
    {"lang_cluster":"Ruby","source_code":"\n\nclass RGBColour\n  def to_grayscale\n    luminosity = Integer(0.2126*@red + 0.7152*@green + 0.0722*@blue)\n    self.class.new(luminosity, luminosity, luminosity)\n  end\nend\n\nclass Pixmap\n  def to_grayscale\n    gray = self.class.new(@width, @height)\n    @width.times do |x|\n      @height.times do |y|\n        gray[x,y] = self[x,y].to_grayscale\n      end\n    end\n    gray\n  end\nend\n\n","human_summarization":"The code extends the basic bitmap storage to support grayscale images. It defines two operations for converting a color image to a grayscale image and vice versa. The conversion uses the CIE recommended formula for luminance calculation. It also ensures that rounding errors in floating-point arithmetic do not cause run-time issues or distort results when the calculated luminance is stored as an unsigned integer.","id":1651}
    {"lang_cluster":"Ruby","source_code":"Library: Ruby\/Tk\nrequire 'tk'\n$str = TkVariable.new(\"Hello World! \")\n$dir = :right\n \ndef animate\n  $str.value = shift_char($str.value, $dir)\n  $root.after(125) {animate}\nend\n\ndef shift_char(str, dir)\n  case dir\n  when :right then str[-1,1] + str[0..-2]\n  when :left  then str[1..-1] + str[0,1]\n  end\nend\n \n$root = TkRoot.new(\"title\" => \"Basic Animation\")\n \nTkLabel.new($root) do\n  textvariable $str\n  font \"Courier 14\"\n  pack {side 'top'}\n  bind(\"ButtonPress-1\") {$dir = {:right=>:left,:left=>:right}[$dir]}\nend\n \nanimate\nTk.mainloop\n\nLibrary: Shoes\nShoes.app do\n  @direction = 1\n  @label = para \"Hello World! \", :family => 'monospace'\n\n  click {|button, left, top| @direction *= -1 if button == 1}\n\n  animate(8) do |f| \n    t = @label.text\n    @label.text = @direction > 0 ? t[-1] + t[0..-2] : t[1..-1] + t[0]\n  end\nend\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":1652}
    {"lang_cluster":"Ruby","source_code":"\n\n\n\nwhile\n\nuntil\n\n\nval = 0\nbegin\n   val += 1\n   puts val\nend while val\u00a0% 6\u00a0!= 0\n\nval = 0\nbegin\n   val += 1\n   puts val\nend until val\u00a0% 6 == 0\n\n\n\n\nbreak unless\n\nbreak if\n\n\nval = 0\nloop do\n   val += 1\n   puts val\n   break unless val %6\u00a0!= 0\nend\n\nval = 0\nloop do\n   val += 1\n   puts val\n   break if val %6 == 0\nend\n\n\n","human_summarization":"The code initializes a value at 0 and enters a loop which continues until the value modulo 6 is not 0. In each iteration, the value is incremented by 1 and printed. The loop is guaranteed to execute at least once. This behavior is attributed to the while statement modifier on a begin...end statement. The code prints the numbers 1 through 6.","id":1653}
    {"lang_cluster":"Ruby","source_code":"\n\n\"J\u0332o\u0332s\u0332\u00e9\u0332\".bytesize\n\"J\u0332o\u0332s\u0332\u00e9\u0332\".chars.length\n\"J\u0332o\u0332s\u0332\u00e9\u0332\".grapheme_clusters.length\n\n\nTo run these programs, you must convert them to different encodings.\n\nIf you use Emacs: Paste each program into Emacs. The magic comment, like -*- coding: iso-8859-1 -*-, will tell Emacs to save with that encoding.\nIf your text editor saves UTF-8: Convert the file before running it. For example:$ ruby -pe '$_.encode!(\"iso-8859-1\", \"utf-8\")' scratch.rb | ruby\n\nWorks with: Ruby version 1.9\n\n\nProgram\n\nOutput\n\n\n# -*- coding: iso-8859-1 -*-\ns = \"m\u00f8\u00f8se\"\nputs \"Byte length: %d\"\u00a0% s.bytesize\nputs \"Character length: %d\"\u00a0% s.length\n\nByte length: 5\nCharacter length: 5\n\n\n# -*- coding: utf-8 -*-\ns = \"m\u00f8\u00f8se\"\nputs \"Byte length: %d\"\u00a0% s.bytesize\nputs \"Character length: %d\"\u00a0% s.length\n\nByte length: 7\nCharacter length: 5\n\n\n# -*- coding: gb18030 -*-\ns = \"m\u00f8\u00f8se\"\nputs \"Byte length: %d\"\u00a0% s.bytesize\nputs \"Character length: %d\"\u00a0% s.length\n\nByte length: 11\nCharacter length: 5\n\n\n\/.\/n uses no multibyte encoding.\n\/.\/e uses EUC-JP.\n\/.\/s uses Shift-JIS or Windows-31J.\n\/.\/u uses UTF-8.\n\n# -*- coding: utf-8 -*-\n\nclass String\n  # Define String#bytesize for Ruby 1.8.6.\n  unless method_defined?(:bytesize)\n    alias bytesize length\n  end\nend\n\ns = \"\u6587\u5b57\u5316\u3051\"\nputs \"Byte length: %d\"\u00a0% s.bytesize\nputs \"Character length: %d\"\u00a0% s.gsub(\/.\/u, ' ').size\n","human_summarization":"determine the character and byte length of a string, considering different encodings such as UTF-8 and UTF-16. It handles Unicode code points correctly, distinguishing between actual character counts and code unit counts. It also provides the string length in graphemes if the language supports it. The code is compatible with different versions of Ruby and can count UTF-8 characters in a string.","id":1654}
    {"lang_cluster":"Ruby","source_code":"\n\nrequire 'securerandom'\nSecureRandom.random_number(1 << 32)\n\n#or specifying SecureRandom as the desired RNG:\np (1..10).to_a.sample(3, random: SecureRandom) # =>[1, 4, 5]\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using the system's built-in mechanism, such as \/dev\/urandom in Unix. If available, the 'securerandom' library introduced in Ruby 1.8.7 is used, which attempts to generate random numbers by loading OpenSSL, opening \/dev\/urandom, or calling CryptGenRandom.","id":1655}
    {"lang_cluster":"Ruby","source_code":"\nputs \"knight\"[1..-1]   # strip first character\nputs \"socks\"[0..-2]    # strip last character\nputs \"socks\".chop      # alternate way to strip last character\nputs \"brooms\"[1..-2]   # strip both first and last characters\nputs \"\u4e0e\u4eca\u4ee4\"[1..-2]    # => \u4eca\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":1656}
    {"lang_cluster":"Ruby","source_code":"\n\ndef main\n  puts \"first instance\"\n  sleep 20\n  puts :done\nend\n\nif $0 == __FILE__\n  if File.new(__FILE__).flock(File::LOCK_EX | File::LOCK_NB)\n    main\n  else\n    raise \"another instance of this program is running\"\n  end\nend\n\n__END__\n\n","human_summarization":"check if a single instance of an application is running, display a message and exit if another instance is found, using file locking on the program file.","id":1657}
    {"lang_cluster":"Ruby","source_code":"\n\nWorks with: Ruby version 2.0+\ndef read_matrix(data)\n  lines = data.lines\n  9.times.collect { |i| 9.times.collect { |j| lines[i][j].to_i } }\nend\n\ndef permissible(matrix, i, j)\n  ok = [nil, *1..9]\n  check = ->(x,y) { ok[matrix[x][y]] = nil  if matrix[x][y].nonzero? }\n  # Same as another in the column isn't permissible...\n  9.times { |x| check[x, j] }\n  # Same as another in the row isn't permissible...\n  9.times { |y| check[i, y] }\n  # Same as another in the 3x3 block isn't permissible...\n  xary = [ *(x = (i \/ 3) * 3) .. x + 2 ]        #=> [0,1,2], [3,4,5] or [6,7,8]\n  yary = [ *(y = (j \/ 3) * 3) .. y + 2 ]\n  xary.product(yary).each { |x, y| check[x, y] }\n  # Gathering only permitted one\n  ok.compact\nend\n\ndef deep_copy_sudoku(matrix)\n  matrix.collect { |row| row.dup }\nend\n\ndef solve_sudoku(matrix)\n  loop do\n    options = []\n    9.times do |i|\n      9.times do |j|\n        next if matrix[i][j].nonzero?\n        p = permissible(matrix, i, j)\n        # If nothing is permissible, there is no solution at this level.\n        return if p.empty?              # return nil\n        options << [i, j, p]\n      end\n    end\n    # If the matrix is complete, we have a solution...\n    return matrix if options.empty?\n    \n    i, j, permissible = options.min_by { |x| x.last.length }\n    \n    # If there is an option with only one solution, set it and re-check permissibility\n    if permissible.length == 1\n      matrix[i][j] = permissible[0]\n      next\n    end\n    \n    # We have two or more choices. We need to search both...\n    permissible.each do |v|\n      mtmp = deep_copy_sudoku(matrix)\n      mtmp[i][j] = v\n      ret = solve_sudoku(mtmp)\n      return ret if ret\n    end\n    \n    # We did an exhaustive search on this branch and nothing worked out.\n    return\n  end\nend\n\ndef print_matrix(matrix)\n  puts \"Impossible\" or return  unless matrix\n  \n  border = \"+-----+-----+-----+\"\n  9.times do |i|\n    puts border if i%3 == 0\n    9.times do |j|\n      print j%3 == 0 ? \"|\" : \" \"\n      print matrix[i][j] == 0 ? \".\" : matrix[i][j]\n    end\n    puts \"|\"\n  end\n  puts border\nend\n\ndata = <<EOS\n394__267_\n___3__4__\n5__69__2_\n_45___9__\n6_______7\n__7___58_\n_1__67__8\n__9__8___\n_264__735\nEOS\n\nmatrix = read_matrix(data)\nprint_matrix(matrix)\nputs\nprint_matrix(solve_sudoku(matrix))\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid and outputs the completed grid in a human-readable format, using backtracking algorithm.\"","id":1658}
    {"lang_cluster":"Ruby","source_code":"class Array\n  def knuth_shuffle!\n    j = length\n    i = 0\n    while j > 1\n      r = i + rand(j)\n      self[i], self[r] = self[r], self[i]\n      i += 1\n      j -= 1\n    end\n    self\n  end\nend\n\nr = Hash.new(0)\n100_000.times do |i|\n  a = [1,2,3].knuth_shuffle!\n  r[a] += 1\nend\n\nr.keys.sort.each {|a| puts \"#{a.inspect} => #{r[a]}\"}\n\n[1, 2, 3] => 16572\n[1, 3, 2] => 16610\n[2, 1, 3] => 16633\n[2, 3, 1] => 16714\n[3, 1, 2] => 16838\n[3, 2, 1] => 16633\n\nclass Array\n  def knuth_shuffle!\n    (length - 1).downto(1) do |i|\n      j = rand(i + 1)\n      self[i], self[j] = self[j], self[i]\n    end\n    self\n  end\nend\n","human_summarization":"implement the Knuth shuffle algorithm, which randomly shuffles the elements of an array. The algorithm modifies the input array in-place or returns the shuffled items as a new array, depending on the programming language. The algorithm can also be modified to iterate from left to right if needed.","id":1659}
    {"lang_cluster":"Ruby","source_code":"\nrequire 'date'\n\ndef last_friday(year, month)\n  # Last day of month: Date.new interprets a negative number as a relative month\/day from the end of year\/month.\n  d = Date.new(year, month, -1)\n  d -= (d.wday - 5) % 7  # Subtract days after Friday.\nend\n\nyear = Integer(ARGV.shift)\n(1..12).each {|month| puts last_friday(year, month)}\n\n\n\n","human_summarization":"The code takes a year as input and returns the dates of the last Fridays of each month for that year. It calculates this by either using the expression (d.wday - 5) % 7 to count days after Friday, or by getting the last day of the month and going back day by day until it reaches a Friday.","id":1660}
    {"lang_cluster":"Ruby","source_code":"\nprint \"Goodbye, World!\"\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":1661}
    {"lang_cluster":"Ruby","source_code":"\n\nLibrary: Ruby\/Tk\nrequire 'tk'\n\ndef main\n  root = TkRoot.new\n  l1 = TkLabel.new(root, \"text\" => \"input a string\")\n  e1 = TkEntry.new(root)\n  l2 = TkLabel.new(root, \"text\" => \"input the number 75000\")\n  e2 = TkEntry.new(root) do\n    validate \"focusout\"\n    validatecommand lambda {e2.value.to_i == 75_000}\n    invalidcommand  lambda {focus_number_entry(e2)}\n  end\n  ok = TkButton.new(root) do\n    text \"OK\"\n    command lambda {validate_input(e1, e2)}\n  end\n  Tk.grid(l1, e1)\n  Tk.grid(l2, e2)\n  Tk.grid(\"x\",ok, \"sticky\" => \"w\")  \n  Tk.mainloop\nend\n\ndef validate_input(text_entry, number_entry)\n  if number_entry.value.to_i != 75_000\n    focus_number_entry(number_entry)\n  else\n    puts %Q{You entered: \"#{text_entry.value}\" and \"#{number_entry.value}\"}\n    root.destroy\n  end\nend\n\ndef focus_number_entry(widget)\n  widget \\\n    .configure(\"background\" => \"red\", \"foreground\" => \"white\") \\\n    .selection_range(0, \"end\") \\\n    .focus\nend\n\nmain\n\nLibrary: Shoes\nShoes.app do\n  string = ask('Enter a string:')\n  begin\n    number = ask('Enter the number 75000:')\n  end while number.to_i != 75000\n  para %Q{you entered the string \"#{string}\" and the number #{number}}\nend\n\n","human_summarization":"\"Implement a graphical user interface to accept a string and the integer 75000 as input, and validate the input number to ensure it is exactly 75000.\"","id":1662}
    {"lang_cluster":"Ruby","source_code":"\nclass String\n  ALFABET = (\"A\"..\"Z\").to_a\n\n  def caesar_cipher(num)\n    self.tr(ALFABET.join, ALFABET.rotate(num).join)\n  end\n\nend\n\n#demo:\nencypted  = \"THEYBROKEOURCIPHEREVERYONECANREADTHIS\".caesar_cipher(3)\ndecrypted = encypted.caesar_cipher(-3)\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":1663}
    {"lang_cluster":"Ruby","source_code":"\n\nirb(main):001:0> 12.lcm 18\n=> 36\n\n\ndef gcd(m, n)\n  m, n = n, m % n until n.zero?\n  m.abs\nend\n\ndef lcm(*args)\n  args.inject(1) do |m, n|\n    return 0 if n.zero?\n    (m * n).abs \/ gcd(m, n)\n  end\nend\n\np lcm 12, 18, 22\np lcm 15, 14, -6, 10, 21\n\n\n","human_summarization":"The code calculates the least common multiple (LCM) of two integers, m and n. The LCM is the smallest positive integer that is a multiple of both m and n. If either m or n is zero, the LCM is zero. The code can calculate the LCM by iterating all multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m x n| \/ gcd(m, n), where gcd is the greatest common divisor. The code can also find the LCM by merging the prime decompositions of m and n.","id":1664}
    {"lang_cluster":"Ruby","source_code":"\n#!\/usr\/bin\/env ruby\n\ndef check_cusip(cusip)\n  abort('CUSIP must be 9 characters') if cusip.size != 9\n\n  sum = 0\n  cusip.split('').each_with_index do |char, i|\n    next if i == cusip.size - 1\n    case\n    when char.scan(\/\\D\/).empty?\n      v = char.to_i\n    when char.scan(\/\\D\/).any?\n      pos = char.upcase.ord - 'A'.ord + 1\n      v = pos + 9\n    when char == '*'\n      v = 36\n    when char == '@'\n      v = 37\n    when char == '#'\n      v = 38\n    end\n\n    v *= 2 unless (i % 2).zero?\n    sum += (v\/10).to_i + (v % 10)\n  end\n\n  check = (10 - (sum % 10)) % 10\n  return 'VALID' if check.to_s == cusip.split('').last\n  'INVALID'\nend\n\nCUSIPs = %w[\n  037833100 17275R102 38259P508 594918104 68389X106 68389X105\n]\n\nCUSIPs.each do |cusip|\n  puts \"#{cusip}: #{check_cusip(cusip)}\"\nend\n\n\n037833100: VALID\n17275R102: VALID\n38259P508: VALID\n594918104: VALID\n68389X106: INVALID\n68389X105: VALID\n\n\nTABLE = (\"0\"..\"9\").chain(\"A\"..\"Z\", %w(* @ #)).zip(0..).to_h\n\ndef valid_CUSIP?(str)\n  sum = str[0..-2].chars.each_slice(2).sum do |c1,c2|\n    TABLE[c1].divmod(10).sum + (TABLE[c2]*2).divmod(10).sum\n  end\n  str[-1].to_i == (10 - (sum % 10)) % 10\nend\n\nCUSIPs = %w(037833100 17275R102 38259P508 594918104 68389X106 68389X105)\nCUSIPs.each{|cusip| puts \"#{cusip}: #{valid_CUSIP? cusip}\"}\n\n","human_summarization":"The code validates the last digit (check digit) of a CUSIP code, which is a nine-character alphanumeric code identifying North American financial securities. It uses a specific algorithm to calculate the check digit from the first 8 characters of the CUSIP code and compares it with the actual last digit. The algorithm handles digits, letters, and special characters differently. The code is written in Ruby and requires a version > 2.5 due to the usage of methods like chain, to_h, sum, and infinite Range syntax (0..).","id":1665}
    {"lang_cluster":"Ruby","source_code":"\n# We assume that a Fixnum occupies one machine word.\n# Fixnum#size returns bytes (1 byte = 8 bits).\nword_size = 42.size * 8\nputs \"Word size: #{word_size} bits\"\n\n# Array#pack knows the native byte order. We pack 1 as a 16-bit integer,\n# then unpack bytes: [0, 1] is big endian, [1, 0] is little endian.\nbytes = [1].pack('S').unpack('C*')\nbyte_order = (bytes[0] == 0 ? 'big' : 'little') + ' endian'\nputs \"Byte order: #{byte_order}\"\n\n\n","human_summarization":"determine and print the word size and endianness of the host machine. It takes into account the differences in Fixnum size between MRI and JRuby implementations of Ruby. In MRI, Fixnum size is equivalent to a native machine word, while in JRuby, it is always 64 bits. The code also ensures correct native byte order in JRuby by using java.nio.ByteOrder.nativeOrder().","id":1666}
    {"lang_cluster":"Ruby","source_code":"\nWorks with: Ruby version 1.8.7\n\nrequire 'rosettacode'\n\nlangs = []\nRosettaCode.category_members(\"Programming Languages\") {|lang| langs << lang}\n\n# API has trouble with long titles= values.\n# To prevent skipping languages, use short slices of 20 titles.\nlangcount = {}\nlangs.each_slice(20) do |sublist|\n  url = RosettaCode.get_api_url({\n    \"action\" => \"query\",\n    \"prop\" => \"categoryinfo\",\n    \"format\" => \"xml\",\n    \"titles\" => sublist.join(\"|\"),\n  })\n\n  doc = REXML::Document.new open(url)\n  REXML::XPath.each(doc, \"\/\/page\") do |page|\n    lang = page.attribute(\"title\").value\n    info = REXML::XPath.first(page, \"categoryinfo\")\n    langcount[lang] = info.nil? ? 0 : info.attribute(\"pages\").value.to_i\n  end\nend\n\nputs Time.now\nputs \"There are #{langcount.length} languages\"\nputs \"the top 25:\"\nlangcount.sort_by {|key,val| val}.reverse[0,25].each_with_index do |(lang, count), i|\n  puts \"#{i+1}. #{count} - #{lang.sub(\/Category:\/, '')}\"\nend\n\n\nResults:\n2010-07-08 14:52:46 -0500\nThere are 306 languages\nthe top 25:\n1. 399 - Tcl\n2. 370 - Python\n3. 352 - Ruby\n4. 338 - J\n5. 337 - C\n6. 333 - PicoLisp\n7. 322 - OCaml\n8. 322 - Haskell\n9. 299 - Perl\n10. 299 - AutoHotkey\n11. 288 - Common Lisp\n12. 280 - Java\n13. 275 - Ada\n14. 270 - D\n15. 267 - Oz\n16. 253 - R\n17. 252 - PureBasic\n18. 245 - E\n19. 243 - C++\n20. 241 - C sharp\n21. 239 - ALGOL 68\n22. 236 - JavaScript\n23. 221 - Forth\n24. 207 - Clojure\n25. 201 - Fortran\n","human_summarization":"The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It uses either web scraping or API methods to access the data. The code also has the option to filter incorrect results. It handles more than 500 categories by using the RC API to retrieve the categories and count the members of each. The code utilizes the RosettaCode module from Count programming examples#Ruby.","id":1667}
    {"lang_cluster":"Ruby","source_code":"\nfor i in collection do\n  puts i\nend\n\ncollection.each do |i|\n  puts i\nend\n\n","human_summarization":"utilize a \"for each\" loop or another type of loop to iterate through and print each element of a collection in order. It also demonstrates the use of different versions of \"each\" that are dependent on the class, such as String#each_char, Array#each_index, Hash#each_key, etc.","id":1668}
    {"lang_cluster":"Ruby","source_code":"\nputs \"Hello,How,Are,You,Today\".split(',').join('.')\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":1669}
    {"lang_cluster":"Ruby","source_code":"\n\n40902.gcd(24140)  # => 34\n\ndef gcd(u, v)\n  u, v = u.abs, v.abs\n  while v > 0\n    u, v = v, u\u00a0% v\n  end\n  u\nend\n","human_summarization":"implement the gcd method to find the greatest common divisor (GCD), also known as greatest common factor (gcf) and greatest common measure, of two integers. This method is related to the task of finding the least common multiple. More information can be found in the MathWorld and Wikipedia entries for greatest common divisor.","id":1670}
    {"lang_cluster":"Ruby","source_code":"\nrequire 'socket'\nserver = TCPServer.new(12321)\n\nwhile (connection = server.accept)\n  Thread.new(connection) do |conn|\n    port, host = conn.peeraddr[1,2]\n    client = \"#{host}:#{port}\"\n    puts \"#{client} is connected\"\n    begin\n      loop do\n        line = conn.readline\n        puts \"#{client} says: #{line}\"\n        conn.puts(line)\n      end\n    rescue EOFError\n      conn.close\n      puts \"#{client} has disconnected\"\n    end\n  end\nend\n\n\nWorks with: Ruby version 1.9.2\nrequire 'socket'\n\nSocket.tcp_server_loop(12321) do |conn, addr|\n  Thread.new do\n    client = \"#{addr.ip_address}:#{addr.ip_port}\"\n    puts \"#{client} is connected\"\n    begin\n      loop do\n        line = conn.readline\n        puts \"#{client} says: #{line}\"\n        conn.puts(line)\n      end\n    rescue EOFError\n      conn.close\n      puts \"#{client} has disconnected\"\n    end\n  end\nend\n\n","human_summarization":"The code implements an echo server that runs on TCP port 12321, accepting and echoing back complete lines from multiple simultaneous connections, primarily from localhost. It handles multiple clients using multi-threading or multi-processing and continues to respond to other clients even if one client sends a partial line or stops reading responses. Connection information is logged to standard output. The server is created using the Socket.tcp_server_loop method introduced in Ruby 1.9.2.","id":1671}
    {"lang_cluster":"Ruby","source_code":"\ndef is_numeric?(s)\n  begin\n    Float(s)\n  rescue\n    false # not numeric\n  else\n    true # numeric\n  end\nend\n\ndef is_numeric?(s)\n   \u00a0!!Float(s) rescue false\nend\n\ndef is_numeric?(s)\n   \u00a0!!Float(s, exception: false)\nend\n\nstrings = %w(0 0.0 -123 abc 0x10 0xABC 123a -123e3 0.1E-5 50e)\nstrings.each do |str|\n  puts \"%9p => %s\"\u00a0% [str, is_numeric?(str)]\nend\n\n","human_summarization":"\"Create a function that checks if a given string can be considered as a numeric value, including floating point and negative numbers, in the syntax used by the language for numeric literals or numbers converted from strings. Note that since Ruby 2.6, `rescue` is not needed by adding `exception: false` to return `nil` instead.\"","id":1672}
    {"lang_cluster":"Ruby","source_code":"\n\nrequire 'net\/https'\nrequire 'uri'\nrequire 'pp'\n\nuri = URI.parse('https:\/\/sourceforge.net')\nhttp = Net::HTTP.new(uri.host,uri.port)\nhttp.use_ssl = true\nhttp.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\nhttp.start do\n  content = http.get(uri)\n  p [content.code, content.message]\n  pp content.to_hash\n  puts content.body\nend\n\n\n[\"302\", \"Found\"]\n{\"location\"=>[\"http:\/\/sourceforge.net\/\"],\n \"content-type\"=>[\"text\/html; charset=UTF-8\"],\n \"connection\"=>[\"close\"],\n \"server\"=>[\"nginx\/0.7.60\"],\n \"date\"=>[\"Sun, 30 Aug 2009 20:20:07 GMT\"],\n \"content-length\"=>[\"229\"],\n \"set-cookie\"=>\n  [\"sf.consume=89f65c6fadd222338b2f3de6f8e8a17b2c8f67c2gAJ9cQEoVQhfZXhwaXJlc3ECY2RhdGV0aW1lCmRhdGV0aW1lCnEDVQoH9gETAw4HAAAAhVJxBFUDX2lkcQVVIDEyOWI2MmVkOWMwMWYxYWZiYzE5Y2JhYzcwZDMxYTE4cQZVDl9hY2Nlc3NlZF90aW1lcQdHQdKmt73UN21VDl9jcmVhdGlvbl90aW1lcQhHQdKmt73UN2V1Lg==; expires=Tue, 19-Jan-2038 03:14:07 GMT; Path=\/\"]}\n<html>\n <head>\n  <title>302 Found<\/title>\n <\/head>\n <body>\n  <h1>302 Found<\/h1>\n  The resource was found at <a href=\"http:\/\/sourceforge.net\/\">http:\/\/sourceforge.net\/<\/a>;\nyou should be redirected automatically.\n\n\n <\/body>\n<\/html>\n\n","human_summarization":"send a GET request to the URL \"https:\/\/www.w3.org\/\" and print the result to the console. The code checks the host certificate for validity and does not include authentication. It uses the Net::HTTP object for the request, which is set to use SSL before the session starts.","id":1673}
    {"lang_cluster":"Ruby","source_code":"Point = Struct.new(:x,:y) do\n  def to_s; \"(#{x}, #{y})\" end\nend\n\ndef sutherland_hodgman(subjectPolygon, clipPolygon)\n  # These inner functions reduce the argument passing to\n  # \"inside\" and \"intersection\".\n  cp1, cp2, s, e = nil\n  inside = proc do |p|\n    (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\n  end\n  intersection = proc do\n    dcx, dcy = cp1.x-cp2.x, cp1.y-cp2.y\n    dpx, dpy = s.x-e.x, s.y-e.y\n    n1 = cp1.x*cp2.y - cp1.y*cp2.x\n    n2 = s.x*e.y - s.y*e.x\n    n3 = 1.0 \/ (dcx*dpy - dcy*dpx)\n    Point[(n1*dpx - n2*dcx) * n3, (n1*dpy - n2*dcy) * n3]\n  end\n  \n  outputList = subjectPolygon\n  cp1 = clipPolygon.last\n  for cp2 in clipPolygon\n    inputList = outputList\n    outputList = []\n    s = inputList.last\n    for e in inputList\n      if inside[e]\n        outputList << intersection[] unless inside[s]\n        outputList << e\n      elsif inside[s]\n        outputList << intersection[]\n      end\n      s = e\n    end\n    cp1 = cp2\n  end\n  outputList\nend\n\nsubjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300],\n                  [250, 300], [200, 250], [150, 350], [100, 250],\n                  [100, 200]].collect{|pnt| Point[*pnt]}\n \nclipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]].collect{|pnt| Point[*pnt]}\n \nputs sutherland_hodgman(subjectPolygon, clipPolygon)\n\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":1674}
    {"lang_cluster":"Ruby","source_code":"\nar = \"44 Solomon\n42 Jason\n42 Errol\n41 Garry\n41 Bernard\n41 Barry\n39 Stephen\".lines.map{|line| line.split}\ngrouped = ar.group_by{|pair| pair.shift.to_i}\ns_rnk = 1\nm_rnk = o_rnk = 0\nputs \"stand.\\tmod.\\tdense\\tord.\\tfract.\"\n\ngrouped.each.with_index(1) do |(score, names), d_rnk|\n  m_rnk += names.flatten!.size\n  f_rnk = (s_rnk + m_rnk)\/2.0\n  names.each do |name|\n    o_rnk += 1\n    puts \"#{s_rnk}\\t#{m_rnk}\\t#{d_rnk}\\t#{o_rnk}\\t#{f_rnk.to_s.sub(\".0\",\"\")}\\t#{score} #{name}\"\n  end\n  s_rnk += names.size\nend\n\n\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":1675}
    {"lang_cluster":"Ruby","source_code":"\n\nradians = Math::PI \/ 4\ndegrees = 45.0\n\ndef deg2rad(d)\n  d * Math::PI \/ 180\nend\n\ndef rad2deg(r)\n  r * 180 \/ Math::PI\nend\n\n#sine\nputs \"#{Math.sin(radians)} #{Math.sin(deg2rad(degrees))}\"\n#cosine\nputs \"#{Math.cos(radians)} #{Math.cos(deg2rad(degrees))}\"\n#tangent\nputs \"#{Math.tan(radians)} #{Math.tan(deg2rad(degrees))}\"\n#arcsine\narcsin = Math.asin(Math.sin(radians))\nputs \"#{arcsin} #{rad2deg(arcsin)}\"\n#arccosine\narccos = Math.acos(Math.cos(radians))\nputs \"#{arccos} #{rad2deg(arccos)}\"\n#arctangent\narctan = Math.atan(Math.tan(radians))\nputs \"#{arctan} #{rad2deg(arctan)}\"\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions including sine, cosine, tangent and their inverses in a specific programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the same angle is used for each radian\/degree pair. For inverse functions, the same number is converted to radians and degrees. If the language lacks certain trigonometric functions, they are manually calculated using known approximations or identities. The codes also handle conversion between radians and degrees and provide the option to increase precision of the results using BigDecimal class.","id":1676}
    {"lang_cluster":"Ruby","source_code":"# Item struct to represent each item in the problem\nStruct.new('Item', :name, :weight, :value, :count)\n\n$items = [\n  Struct::Item.new('map', 9, 150, 1),\n  Struct::Item.new('compass', 13, 35, 1),\n  Struct::Item.new('water', 153, 200, 3),\n  Struct::Item.new('sandwich', 50, 60, 2),\n  Struct::Item.new('glucose', 15, 60, 2),\n  Struct::Item.new('tin', 68, 45, 3),\n  Struct::Item.new('banana', 27, 60, 3),\n  Struct::Item.new('apple', 39, 40, 3),\n  Struct::Item.new('cheese', 23, 30, 1),\n  Struct::Item.new('beer', 52, 10, 3),\n  Struct::Item.new('suntan cream', 11, 70, 1),\n  Struct::Item.new('camera', 32, 30, 1),\n  Struct::Item.new('t-shirt', 24, 15, 2),\n  Struct::Item.new('trousers', 48, 10, 2),\n  Struct::Item.new('umbrella', 73, 40, 1),\n  Struct::Item.new('w-trousers', 42, 70, 1),\n  Struct::Item.new('w-overcoat', 43, 75, 1),\n  Struct::Item.new('note-case', 22, 80, 1),\n  Struct::Item.new('sunglasses', 7, 20, 1),\n  Struct::Item.new('towel', 18, 12, 2),\n  Struct::Item.new('socks', 4, 50, 1),\n  Struct::Item.new('book', 30, 10, 2)\n]\n\ndef choose_item(weight, id, cache)\n  return 0, [] if id < 0\n\n  k = [weight, id]\n  return cache[k] unless cache[k].nil?\n  value = $items[id].value\n  best_v = 0\n  best_list = []\n  ($items[id].count+1).times do |i|\n    wlim = weight - i * $items[id].weight\n    break if wlim < 0\n    val, taken = choose_item(wlim, id - 1, cache)\n    if val + i * value > best_v\n      best_v = val + i * value\n      best_list = taken + [i]\n    end\n  end\n  cache[k] = [best_v, best_list]\n  return [best_v, best_list]\nend\n\nval, list = choose_item(400, $items.length - 1, {})\nw = 0\nlist.each_with_index do |cnt, i|\n  if cnt > 0\n    print \"#{cnt} #{$items[i].name}\\n\"\n    w += $items[i][1] * cnt\n  end\nend\n\np \"Total weight: #{w}, Value: #{val}\"\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. It selects items based on their importance value and weight, ensuring the total weight does not exceed the limit and the total value is maximized. The code considers the quantity available of each item and only allows whole units to be selected.","id":1677}
    {"lang_cluster":"Ruby","source_code":"\nt1 = Time.now\n\ncatch :done do\n  Signal.trap('INT') do\n    Signal.trap('INT', 'DEFAULT') # reset to default\n    throw :done\n  end\n  n = 0\n  loop do\n    sleep(0.5)\n    n += 1\n    puts n\n  end\nend\n\ntdelt = Time.now - t1\nputs 'Program has run for %5.3f seconds.' % tdelt\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.","id":1678}
    {"lang_cluster":"Ruby","source_code":"\n\n'1234'.succ #=> '1235'\n'99'.succ #=> '100'\n","human_summarization":"\"Code to increment a numerical string using the succ method\"","id":1679}
    {"lang_cluster":"Ruby","source_code":"\n\nrequire 'abbrev'\n\ndirs = %w( \/home\/user1\/tmp\/coverage\/test \/home\/user1\/tmp\/covert\/operator \/home\/user1\/tmp\/coven\/members )\n\ncommon_prefix = dirs.abbrev.keys.min_by {|key| key.length}.chop  # => \"\/home\/user1\/tmp\/cove\"\ncommon_directory = common_prefix.sub(%r{\/[^\/]*$}, '')            # => \"\/home\/user1\/tmp\"\n\n\nseparator = '\/'\npath0, *paths = dirs.collect {|dir| dir.split(separator)}\nuncommon_idx = path0.zip(*paths).index {|dirnames| dirnames.uniq.length > 1}\nuncommon_idx = path0.length  unless uncommon_idx                # if uncommon_idx==nil\ncommon_directory = path0[0...uncommon_idx].join(separator)      # => \"\/home\/user1\/tmp\"\n\n\ndef common_directory_path(dirs, separator='\/')\n  dir1, dir2 = dirs.minmax.map{|dir| dir.split(separator)}\n  dir1.zip(dir2).take_while{|dn1,dn2| dn1==dn2}.map(&:first).join(separator)\nend\n\np common_directory_path(dirs)           #=> \"\/home\/user1\/tmp\"\n\n","human_summarization":"\"Create a function to find and return the common directory path from a set of given directory paths using a specified directory separator character. The function also includes a test case using '\/' as the directory separator and three specific directory paths. The function does not return the longest common string, but the valid directory path. If a pre-existing function in the language can perform this task, it should be mentioned. The function also uses the abbrev module to calculate and return a hash of unambiguous abbreviations for the given strings.\"","id":1680}
    {"lang_cluster":"Ruby","source_code":"\n> class Array\n>   def sattolo_cycle!\n>     (length - 1).downto(1) do |i|\n*       j = rand(i)\n>       self[i], self[j] = self[j], self[i]\n>     end\n>     self\n>   end\n> end\n=> :sattolo_cycle!\n\n> # Tests\n> 10.times do\n*   p [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].sattolo_cycle!\n> end\n[10, 6, 9, 7, 8, 1, 3, 2, 5, 4]\n[3, 7, 5, 10, 4, 8, 1, 2, 6, 9]\n[10, 3, 4, 8, 9, 7, 1, 5, 6, 2]\n[8, 7, 4, 2, 6, 9, 1, 5, 10, 3]\n[2, 7, 5, 10, 8, 3, 6, 9, 4, 1]\n[2, 10, 8, 6, 1, 3, 5, 9, 7, 4]\n[8, 5, 6, 1, 4, 9, 2, 10, 7, 3]\n[5, 4, 10, 7, 2, 1, 8, 9, 3, 6]\n[9, 8, 4, 2, 6, 1, 5, 10, 3, 7]\n[9, 4, 2, 7, 6, 1, 10, 3, 8, 5]\n=> 10\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":1681}
    {"lang_cluster":"Ruby","source_code":"\nWorks with: Ruby version 1.8\nrequire 'soap\/wsdlDriver'\n\nwsdl = SOAP::WSDLDriverFactory.new(\"http:\/\/example.com\/soap\/wsdl\")\nsoap = wsdl.create_rpc_driver\n\nresponse1 = soap.soapFunc(:elementName => \"value\")\nputs response1.soapFuncReturn\n\nresponse2 = soap.anotherSoapFunc(:aNumber => 42)\nputs response2.anotherSoapFuncReturn\n\n","human_summarization":"The code establishes a SOAP client to access and call the functions soapFunc() and anotherSoapFunc() from the WSDL located at http:\/\/example.com\/soap\/wsdl. Note, the task and corresponding code may require further clarification.","id":1682}
    {"lang_cluster":"Ruby","source_code":"\ndef median(ary)\n  return nil if ary.empty?\n  mid, rem = ary.length.divmod(2)\n  if rem == 0\n    ary.sort[mid-1,2].inject(:+) \/ 2.0\n  else\n    ary.sort[mid]\n  end\nend\n\np median([])                        # => nil\np median([5,3,4])                   # => 4\np median([5,4,2,3])                 # => 3.5\np median([3,4,1,-8.4,7.2,4,1,1.2])  # => 2.1\n\n\ndef median(aray)\n    srtd = aray.sort\n    alen = srtd.length\n    (srtd[(alen-1)\/2] + srtd[alen\/2]) \/ 2.0\nend\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers, handling the case of even number of elements by returning the average of the two middle values. It uses the selection algorithm for efficiency. It also includes tasks for calculating various statistical measures including mean, median, mode, and standard deviation, both in a moving and cumulative manner.","id":1683}
    {"lang_cluster":"Ruby","source_code":"\n1.upto(100) do |n|\n  print \"Fizz\" if a = (n\u00a0% 3).zero?\n  print \"Buzz\" if b = (n\u00a0% 5).zero?\n  print n unless (a || b)\n  puts\nend\n\n(1..100).each do |n|\n  puts if (n\u00a0% 15).zero?\n    \"FizzBuzz\"\n  elsif (n\u00a0% 5).zero?\n    \"Buzz\"\n  elsif (n\u00a0% 3).zero?\n    \"Fizz\"\n  else\n    n\n  end\nend\n\nclass Enumerator::Lazy\n  def filter_map\n    Lazy.new(self) do |holder, *values|\n      result = yield *values\n      holder << result if result\n    end\n  end\nend\n \nclass Fizz\n  def initialize(head, tail)\n    @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i\u00a0% 3 == 0}.first(tail)\n  end\n \n  def fizz?(num)\n    search = @list\n    search.include?(num)\n  end\n \n  def drop(num)\n    list = @list\n    list.delete(num)\n  end\n \n  def to_a\n    @list.to_a\n  end\nend\n \nclass Buzz\n  def initialize(head, tail)\n    @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i\u00a0% 5 == 0}.first(tail)\n  end\n \n  def buzz?(num)\n    search = @list\n    search.include?(num)\n  end\n \n  def drop(num)\n    list = @list\n    list.delete(num)\n  end\n \n  def to_a\n    @list.to_a\n  end\nend\n \nclass FizzBuzz\n  def initialize(head, tail)\n    @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i\u00a0% 15 == 0}.first(tail)\n  end\n \n  def fizzbuzz?(num)\n    search = @list\n    search.include?(num)\n  end\n \n  def to_a\n    @list.to_a\n  end\n \n  def drop(num)\n    list = @list\n    list.delete(num)\n  end\nend\nstopper = 100\n@fizz = Fizz.new(1,100)\n@buzz = Buzz.new(1,100)\n@fizzbuzz = FizzBuzz.new(1,100)\ndef min(v, n)\n  if v == 1\n    puts \"Fizz: #{n}\"\n    @fizz::drop(n)\n  elsif v == 2\n    puts \"Buzz: #{n}\"\n    @buzz::drop(n)\n  else\n    puts \"FizzBuzz: #{n}\"\n    @fizzbuzz::drop(n)\n  end\nend\n(@fizz.to_a & @fizzbuzz.to_a).map{|d| @fizz::drop(d)}\n(@buzz.to_a & @fizzbuzz.to_a).map{|d| @buzz::drop(d)}\nwhile @fizz.to_a.min < stopper or @buzz.to_a.min < stopper or @fizzbuzz.to_a.min < stopper\n  f, b, fb = @fizz.to_a.min, @buzz.to_a.min, @fizzbuzz.to_a.min\n  min(1,f)  if f < fb and f < b\n  min(2,b)  if b < f and b < fb\n  min(0,fb) if fb < b and fb < f\nend\n\n(1..100).each do |n|\n  v = \"#{\"Fizz\" if n\u00a0% 3 == 0}#{\"Buzz\" if n\u00a0% 5 == 0}\"\n  puts v.empty?\u00a0? n\u00a0: v\nend\n\n1.upto(100) { |n| puts \"#{'Fizz' if n\u00a0% 3 == 0}#{'Buzz' if n\u00a0% 5 == 0}#{n if n\u00a0% 3\u00a0!= 0 && n\u00a0% 5\u00a0!= 0}\" }\n\n1.upto 100 do |n|\n  r = ''\n  r << 'Fizz' if n\u00a0% 3 == 0\n  r << 'Buzz' if n\u00a0% 5 == 0\n  r << n.to_s if r.empty?\n  puts r\nend\n\n1.upto(100) { |i| puts \"#{[:Fizz][i%3]}#{[:Buzz][i%5]}\"[\/.+\/] || i }\n\n1.upto(100){|i|puts'FizzBuzz '[n=i**4%-15,n+13]||i}\n\nf = [nil, nil, :Fizz].cycle\nb = [nil, nil, nil, nil, :Buzz].cycle\n(1..100).each do |i|\n  puts \"#{f.next}#{b.next}\"[\/.+\/] || i\nend\n\nseq = *0..100\n{Fizz:3, Buzz:5, FizzBuzz:15}.each{|k,n| n.step(100,n){|i|seq[i]=k}}\nputs seq.drop(1)\n\nclass Integer\n  def fizzbuzz\n    v = \"#{\"Fizz\" if self\u00a0% 3 == 0}#{\"Buzz\" if self\u00a0% 5 == 0}\"\n    v.empty?\u00a0? self\u00a0: v\n  end\nend\n\nputs *(1..100).map(&:fizzbuzz)\n\nfizzbuzz = ->(i) do\n  (i%15).zero? and next \"FizzBuzz\"\n  (i%3).zero?  and next \"Fizz\"\n  (i%5).zero?  and next \"Buzz\"\n  i\nend\n\nputs (1..100).map(&fizzbuzz).join(\"\\n\")\n\n1.upto(100) do |n|\n  puts case [(n\u00a0% 3).zero?, (n\u00a0% 5).zero?]\n       in true, false\n         \"Fizz\"\n       in false, true\n         \"Buzz\"\n       in true, true\n         \"FizzBuzz\"\n       else\n         n\n       end\nend\n","human_summarization":"print integers from 1 to 100. For multiples of three, it prints 'Fizz', for multiples of five, it prints 'Buzz', and for multiples of both three and five, it prints 'FizzBuzz'. It also includes functionality to grab the first n fizz\/buzz\/fizzbuzz numbers in a list with a user defined function, starting at a specified number. Various solutions are presented including the use of string interpolation, append, Enumerable#cycle, and Ruby 3's Pattern Matching.","id":1684}
    {"lang_cluster":"Ruby","source_code":"\n\nrequire 'complex'\n\ndef mandelbrot(a)\n  Array.new(50).inject(0) { |z,c| z*z + a }\nend\n\n(1.0).step(-1,-0.05) do |y|\n  (-2.0).step(0.5,0.0315) do |x|\n    print mandelbrot(Complex(x,y)).abs < 2\u00a0? '*'\u00a0: ' '\n  end\n  puts\nend\n# frozen_string_literal: true\n\nrequire_relative 'raster_graphics'\n\nclass RGBColour\n  def self.mandel_colour(i)\n    self.new( 16*(i\u00a0% 15), 32*(i\u00a0% 7), 8*(i\u00a0% 31) )\n  end\nend\n\nclass Pixmap\n  def self.mandelbrot(width, height)\n    mandel = Pixmap.new(width,height)\n    pb = ProgressBar.new(width) if $DEBUG\n    width.times do |x|\n      height.times do |y|\n        x_ish = Float(x - width*11\/15) \/ (width\/3)\n        y_ish = Float(y - height\/2) \/ (height*3\/10)\n        mandel[x,y] = RGBColour.mandel_colour(mandel_iters(x_ish, y_ish))\n      end\n      pb.update(x) if $DEBUG\n    end\n    pb.close if $DEBUG\n    mandel\n  end\n\n  def self.mandel_iters(cx,cy)\n    x = y = 0.0\n    count = 0\n    while Math.hypot(x,y) < 2 and count < 255\n      x, y = (x**2 - y**2 + cx), (2*x*y + cy)\n      count += 1\n    end\n    count\n  end\nend\n\nPixmap.mandelbrot(300,300).save('mandel.ppm')\nLibrary: RubyGems\nLibrary: JRubyArt\n\n# frozen_string_literal: true\n\ndef setup\n  sketch_title 'Mandelbrot'\n  load_pixels\n  no_loop\nend\n\ndef draw\n  grid(900, 600) do |x, y|\n    const = Complex(\n      map1d(x, (0...900), (-3..1.5)), map1d(y, (0...600), (-1.5..1.5))\n    )\n    pixels[x + y * 900] = color(\n      constrained_map(mandel(const, 20), (5..20), (255..0))\n    )\n  end\n  update_pixels\nend\n\ndef mandel(z, max)\n  score = 0\n  const = z\n  while score < max\n    # z = z^2 + c\n    z *= z\n    z += const\n    break if z.abs > 2\n\n    score += 1\n  end\n  score\nend\n\ndef settings\n  size(900, 600)\nend\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. The code also prints an 80-character by 41-line depiction of the set. It utilizes Raster graphics operations in Ruby and JRubyArt, a port of processing to Ruby.","id":1685}
    {"lang_cluster":"Ruby","source_code":"\narr = [1,2,3,4,5]     # or ary = *1..5, or ary = (1..5).to_a\np sum = arr.inject(0) { |sum, item| sum + item }\n# => 15\np product = arr.inject(1) { |prod, element| prod * element }\n# => 120\nWorks with: Ruby version 1.8.7\narr = [1,2,3,4,5]\np sum = arr.inject(0,\u00a0:+)         #=> 15\np product = arr.inject(1,\u00a0:*)     #=> 120\n\n# If you do not explicitly specify an initial value for memo,\n# then the first element of collection is used as the initial value of memo.\np sum = arr.inject(:+)            #=> 15\np product = arr.inject(:*)        #=> 120\n\narr = []\np arr.inject(0,\u00a0:+)               #=> 0\np arr.inject(1,\u00a0:*)               #=> 1\np arr.inject(:+)                  #=> nil\np arr.inject(:*)                  #=> nil\n\nWorks with: Ruby version 1.9.3\narr = [1,2,3,4,5]\np sum = arr.sum                   #=> 15\np [].sum                          #=> 0\n","human_summarization":"Computes the sum and product of an array of integers, returning the initial value for empty arrays and nil if no initial value is provided. The code uses the Enumerable#reduce method, which is an alias of Enumerable#inject.","id":1686}
    {"lang_cluster":"Ruby","source_code":"\nrequire 'date'\n\nDate.leap?(year)\n\n","human_summarization":"The code determines if a given year is a leap year in the Gregorian calendar, using the 'leap?' method, which is also referred to as 'gregorian_leap?'. There is also a 'julian_leap?' method available.","id":1687}
    {"lang_cluster":"Ruby","source_code":"\n(1..7).to_a.permutation(3){|p| puts p.join if p.first.even? && p.sum == 12 }\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":1688}
    {"lang_cluster":"Ruby","source_code":"\n\noriginal = \"hello\"\nreference = original          # copies reference\ncopy1 = original.dup          # instance of original.class\ncopy2 = String.new(original)  # instance of String\n\noriginal << \" world!\"         # append\np reference                   #=> \"hello world!\"\np copy1                       #=> \"hello\"\np copy2                       #=> \"hello\"\n\noriginal = \"hello\".freeze     # prevents further modifications\ncopy1 = original.dup          # copies contents (without status)\ncopy2 = original.clone        # copies contents (with status)\np copy1.frozen?               #=> false\np copy1 << \" world!\"          #=> \"hello world!\"\np copy2.frozen?               #=> true\np copy2 << \" world!\"          #=> can't modify frozen String (RuntimeError)\n","human_summarization":"demonstrate how to copy a string in Ruby, differentiating between copying the string content and creating an additional reference to the existing string using the Object#clone method.","id":1689}
    {"lang_cluster":"Ruby","source_code":"\ndef F(n)\n  n == 0\u00a0? 1\u00a0: n - M(F(n-1))\nend\ndef M(n)\n  n == 0\u00a0? 0\u00a0: n - F(M(n-1))\nend\n\np (Array.new(20) {|n| F(n) })\np (Array.new(20) {|n| M(n) })\n\n","human_summarization":"define two mutually recursive functions to compute the Hofstadter Female and Male sequences. The Female function is defined as F(n) = n - M(F(n-1)) for n > 0 and F(0) = 1. The Male function is defined as M(n) = n - F(M(n-1)) for n > 0 and M(0) = 0. In Ruby, the Male function doesn't need to be pre-declared to be used in the Female function, but it must be defined before the Female function calls it.","id":1690}
    {"lang_cluster":"Ruby","source_code":"\n%w(north east south west).sample   # => \"west\"\n(1..100).to_a.sample(2)            # => [17, 79]\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":1691}
    {"lang_cluster":"Ruby","source_code":"\n\nrequire 'cgi'\nputs CGI.unescape(\"http%3A%2F%2Ffoo%20bar%2F\")\n# => \"http:\/\/foo bar\/\"\n\nWorks with: Ruby version 1.9.2\nrequire 'uri'\nputs URI.decode_www_form_component(\"http%3A%2F%2Ffoo%20bar%2F\")\n# => \"http:\/\/foo bar\/\"\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back to their original unencoded form. The function uses methods like CGI.unescape or URI.decode_www_form_component, which also convert \"+\" to \" \". It handles various test cases including converting encoded URLs like \"http%3A%2F%2Ffoo%20bar%2F\" back to \"http:\/\/foo bar\/\". Note that URI.unescape is obsolete since Ruby 1.9.2 due to issues with URI.escape.","id":1692}
    {"lang_cluster":"Ruby","source_code":"\n\nclass Array\n  def binary_search(val, low=0, high=(length - 1))\n    return nil if high < low\n    mid = (low + high) >> 1\n    case val <=> self[mid]\n      when -1\n        binary_search(val, low, mid - 1)\n      when 1\n        binary_search(val, mid + 1, high)\n      else mid\n    end\n  end\nend\n\nary = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324]\n\n[0,42,45,24324,99999].each do |val|\n  i = ary.binary_search(val)\n  if i\n    puts \"found #{val} at index #{i}: #{ary[i]}\"\n  else\n    puts \"#{val} not found in array\"\n  end\nend\n\nclass Array\n  def binary_search_iterative(val)\n    low, high = 0, length - 1\n    while low <= high\n      mid = (low + high) >> 1\n      case val <=> self[mid]\n        when 1\n          low = mid + 1\n        when -1\n          high = mid - 1\n        else\n          return mid\n      end\n    end\n    nil\n  end\nend\n\nary = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324]\n\n[0,42,45,24324,99999].each do |val|\n  i = ary.binary_search_iterative(val)\n  if i\n    puts \"found #{val} at index #{i}: #{ary[i]}\"\n  else\n    puts \"#{val} not found in array\"\n  end\nend\n\n","human_summarization":"The code implements a binary search algorithm on a sorted integer array. It takes as input the starting and ending points of a range, and a \"secret value\". The algorithm divides the range into halves, and continues to narrow down the search until the secret value is found. The search can be implemented either recursively or iteratively. The code also handles multiple values equal to the given value and indicates whether the element was found or not. It also prints the index of the found number. The code also includes a fix for potential overflow bugs.","id":1693}
    {"lang_cluster":"Ruby","source_code":"\n\n#! \/usr\/bin\/env ruby\np ARGV\n myprog a -h b c\n => [\"a\",\"-h\",\"b\",\"c\"]\n\n","human_summarization":"The code retrieves the list of command-line arguments provided to the program and prints them when run directly. It uses the constant Object::ARGV to access these arguments. It also includes an example of how to use the command line arguments with the program. Furthermore, it provides references for understanding the program name and parsing command line arguments intelligently.","id":1694}
    {"lang_cluster":"Ruby","source_code":"\nrequire 'tk'\n\n$root = TkRoot.new(\"title\" => \"Pendulum Animation\")\n$canvas = TkCanvas.new($root) do\n  width 320\n  height 200\n  create TkcLine, 0,25,320,25,   'tags' => 'plate', 'width' => 2, 'fill' => 'grey50'\n  create TkcOval, 155,20,165,30, 'tags' => 'pivot', 'outline' => \"\", 'fill' => 'grey50'\n  create TkcLine, 1,1,1,1, 'tags' => 'rod', 'width' => 3, 'fill' => 'black'\n  create TkcOval, 1,1,2,2, 'tags' => 'bob', 'outline' => 'black', 'fill' => 'yellow'\nend\n$canvas.raise('pivot')\n$canvas.pack('fill' => 'both', 'expand' => true)\n\n$Theta = 45.0\n$dTheta = 0.0\n$length = 150\n$homeX = 160\n$homeY = 25\n\ndef show_pendulum\n  angle = $Theta * Math::PI \/ 180\n  x = $homeX + $length * Math.sin(angle)\n  y = $homeY + $length * Math.cos(angle)\n  $canvas.coords('rod', $homeX, $homeY, x, y)\n  $canvas.coords('bob', x-15, y-15, x+15, y+15)\nend\n\ndef recompute_angle\n  scaling = 3000.0 \/ ($length ** 2)\n  # first estimate\n  firstDDTheta = -Math.sin($Theta * Math::PI \/ 180) * scaling\n  midDTheta = $dTheta + firstDDTheta\n  midTheta = $Theta + ($dTheta + midDTheta)\/2\n  # second estimate\n  midDDTheta = -Math.sin(midTheta * Math::PI \/ 180) * scaling\n  midDTheta = $dTheta + (firstDDTheta + midDDTheta)\/2\n  midTheta = $Theta + ($dTheta + midDTheta)\/2\n  # again, first\n  midDDTheta = -Math.sin(midTheta * Math::PI \/ 180) * scaling\n  lastDTheta = midDTheta + midDDTheta\n  lastTheta = midTheta + (midDTheta + lastDTheta)\/2\n  # again, second\n  lastDDTheta = -Math.sin(lastTheta * Math::PI\/180) * scaling\n  lastDTheta = midDTheta + (midDDTheta + lastDDTheta)\/2\n  lastTheta = midTheta + (midDTheta + lastDTheta)\/2\n  # Now put the values back in our globals\n  $dTheta  = lastDTheta\n  $Theta = lastTheta\nend\n\ndef animate\n  recompute_angle\n  show_pendulum\n  $after_id = $root.after(15) {animate}\nend\n\nshow_pendulum\n$after_id = $root.after(500) {animate}\n\n$canvas.bind('<Destroy>') {$root.after_cancel($after_id)}\n\nTk.mainloop\n\nShoes.app(:width => 320, :height => 200) do\n  @centerX = 160\n  @centerY = 25\n  @length = 150\n  @diameter = 15\n\n  @Theta = 45.0\n  @dTheta = 0.0\n\n  stroke gray\n  strokewidth 3\n  line 0,25,320,25\n  oval 155,20,10\n\n  stroke black\n  @rod = line(@centerX, @centerY, @centerX, @centerY + @length)\n  @bob = oval(@centerX - @diameter, @centerY + @length - @diameter, 2*@diameter)\n\n  animate(24) do |i|\n    recompute_angle\n    show_pendulum\n  end\n\n  def show_pendulum\n    angle = (90 + @Theta) * Math::PI \/ 180\n    x = @centerX + (Math.cos(angle) * @length).to_i\n    y = @centerY + (Math.sin(angle) * @length).to_i\n\n    @rod.remove\n    strokewidth 3\n    @rod = line(@centerX, @centerY, x, y)\n    @bob.move(x-@diameter, y-@diameter)\n  end\n\n  def recompute_angle\n    scaling = 3000.0 \/ (@length **2)\n    # first estimate\n    firstDDTheta = -Math.sin(@Theta * Math::PI \/ 180) * scaling\n    midDTheta = @dTheta + firstDDTheta\n    midTheta = @Theta + (@dTheta + midDTheta)\/2\n    # second estimate\n    midDDTheta = -Math.sin(midTheta * Math::PI \/ 180) * scaling\n    midDTheta = @dTheta + (firstDDTheta + midDDTheta)\/2\n    midTheta = @Theta + (@dTheta + midDTheta)\/2\n    # again, first\n    midDDTheta = -Math.sin(midTheta * Math::PI \/ 180) * scaling\n    lastDTheta = midDTheta + midDDTheta\n    lastTheta = midTheta + (midDTheta + lastDTheta)\/2\n    # again, second\n    lastDDTheta = -Math.sin(lastTheta * Math::PI\/180) * scaling\n    lastDTheta = midDTheta + (midDDTheta + lastDDTheta)\/2\n    lastTheta = midTheta + (midDTheta + lastDTheta)\/2\n    # Now put the values back in our globals\n    @dTheta  = lastDTheta\n    @Theta = lastTheta\n  end\nend\n\n#!\/bin\/ruby\n\nbegin; require 'rubygems'; rescue; end\n\nrequire 'gosu'\ninclude Gosu\n\n# Screen size\nW = 640\nH = 480\n\n# Full-screen mode\nFS = false\n\n# Screen update rate (Hz)\nFPS = 60\n\nclass Pendulum\n\n  attr_accessor :theta, :friction\n\n  def initialize( win, x, y, length, radius, bob = true, friction = false)\n    @win = win\n    @centerX = x\n    @centerY = y\n    @length = length\n    @radius = radius\n    @bob = bob\n    @friction = friction\n\n    @theta = 60.0\n    @omega = 0.0\n    @scale = 2.0 \/ FPS\n  end\n\n  def draw\n    @win.translate(@centerX, @centerY) {\n      @win.rotate(@theta) {\n        @win.draw_quad(-1, 0, 0x3F_FF_FF_FF, 1, 0, 0x3F_FF_FF_00, 1, @length, 0x3F_FF_FF_00, -1, @length, 0x3F_FF_FF_FF )\n        if @bob\n          @win.translate(0, @length) {\n            @win.draw_quad(0, -@radius, Color::RED, @radius, 0, Color::BLUE, 0, @radius, Color::WHITE, -@radius, 0, Color::BLUE )\n          }\n        end\n      }\n    }\n  end\n\n  def update\n    # Thanks to Hugo Elias for the formula (and explanation thereof)\n    @theta += @omega\n    @omega = @omega - (Math.sin(@theta * Math::PI \/ 180) \/ (@length * @scale))\n    @theta *= 0.999 if @friction\n  end\n\nend # Pendulum class\n\nclass GfxWindow < Window\n\n  def initialize\n    # Initialize the base class\n    super W, H, FS, 1.0 \/ FPS * 1000\n    # self.caption = \"You're getting sleeeeepy...\"\n    self.caption = \"Ruby\/Gosu Pendulum Simulator (Space toggles friction)\"\n\n    @n = 1  # Try changing this number!\n    @pendulums = []\n    (1..@n).each do |i|\n      @pendulums.push Pendulum.new( self, W \/ 2, H \/ 10, H * 0.75 * (i \/ @n.to_f), H \/ 60 )\n    end\n\n  end\n\n  def draw\n    @pendulums.each { |pen| pen.draw }\n  end\n\n  def update\n    @pendulums.each { |pen| pen.update }\n  end\n\n  def button_up(id)\n    if id == KbSpace\n      @pendulums.each { |pen|\n        pen.friction = !pen.friction\n        pen.theta = (pen.theta <=> 0) * 45.0 unless pen.friction\n      }\n    else\n      close\n    end\n  end\n\n  def needs_cursor?()\n    true\n  end\n\nend # GfxWindow class\n\nbegin\n  GfxWindow.new.show\nrescue Exception => e\n  puts e.message, e.backtrace\n  gets\nend\n\n","human_summarization":"simulate and animate a simple gravity pendulum. The animation does not handle window resizing and may run at a different speed compared to a Tcl-based pendulum animation.","id":1695}
    {"lang_cluster":"Ruby","source_code":"\nrequire 'json'\n\nruby_obj = JSON.parse('{\"blue\": [1, 2], \"ocean\": \"water\"}')\nputs ruby_obj\n\nruby_obj[\"ocean\"] = { \"water\" => [\"fishy\", \"salty\"] }\nputs JSON.generate(ruby_obj)\nputs JSON.pretty_generate(ruby_obj)\n\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":1696}
    {"lang_cluster":"Ruby","source_code":"\ndef nthroot(n, a, precision = 1e-5)\n  x = Float(a)\n  begin\n    prev = x\n    x = ((n - 1) * prev + a \/ (prev ** (n - 1))) \/ n\n  end while (prev - x).abs > precision\n  x \nend\n\np nthroot(5,34)  # => 2.02439745849989\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":1697}
    {"lang_cluster":"Ruby","source_code":"\nrequire 'socket'\nhost = Socket.gethostname\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":1698}
    {"lang_cluster":"Ruby","source_code":"\n\ndef leonardo(l0=1, l1=1, add=1)\n  return to_enum(__method__,l0,l1,add) unless block_given?\n  loop do  \n    yield l0\n    l0, l1 = l1, l0+l1+add\n  end\nend\n\np leonardo.take(25)\np leonardo(0,1,0).take(25)\n\n\n","human_summarization":"The code calculates and displays the first 25 Leonardo numbers, starting from L(0). It allows customization of the first two Leonardo numbers (L(0) and L(1)) and the add number, with default being 1. It also has a feature to display the first 25 Fibonacci numbers by setting L(0) and L(1) to 0 and 1 respectively, and the add number to 0.","id":1699}
    {"lang_cluster":"Ruby","source_code":"\nclass Guess < String\n  def self.play\n    nums = Array.new(4){rand(1..9)}\n    loop do\n      result = get(nums).evaluate!\n      break if result == 24.0\n      puts \"Try again! That gives #{result}!\"\n    end\n    puts \"You win!\"\n  end\n  \n  def self.get(nums)\n    loop do\n      print \"\\nEnter a guess using #{nums}: \"\n      input = gets.chomp\n      return new(input) if validate(input, nums)\n    end\n  end\n  \n  def self.validate(guess, nums)\n    name, error =\n      {\n        invalid_character:  ->(str){ !str.scan(%r{[^\\d\\s()+*\/-]}).empty? },\n        wrong_number:       ->(str){ str.scan(\/\\d\/).map(&:to_i).sort != nums.sort },\n        multi_digit_number: ->(str){ str.match(\/\\d\\d\/) }\n      }\n        .find {|name, validator| validator[guess] }\n    \n    error ? puts(\"Invalid input of a(n) #{name.to_s.tr('_',' ')}!\") : true\n  end\n  \n  def evaluate!\n    as_rat = gsub(\/(\\d)\/, '\\1r')        # r\u00a0: Rational suffix\n    eval \"(#{as_rat}).to_f\"\n  rescue SyntaxError\n    \"[syntax error]\"\n  end\nend\n\nGuess.play\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":1700}
    {"lang_cluster":"Ruby","source_code":"\n\n# run_encode(\"aaabbbbc\") #=> [[\"a\", 3], [\"b\", 4], [\"c\", 1]]\ndef run_encode(string)\n  string\n    .chars\n    .chunk{|i| i}\n    .map {|kind, array| [kind, array.length]}\nend\n\n# run_decode([[\"a\", 3], [\"b\", 4], [\"c\", 1]]) #=> \"aaabbbbc\"\ndef run_decode(char_counts)\n  char_counts\n    .map{|char, count| char * count}\n    .join\nend\ndef encode(string)\n  string.scan(\/(.)(\\1*)\/).collect do |char, repeat|\n    [1 + repeat.length, char] \n  end.join\nend\n\ndef decode(string)\n  string.scan(\/(\\d+)(\\D)\/).collect {|length, char| char * length.to_i}.join\nend\n\ndef encode(string)\n  string.scan(\/(.)(\\1*)\/).inject(\"\") do |encoding, (char, repeat)|\n    encoding << (1 + repeat.length).to_s << char\n  end\nend\n\ndef decode(string)\n  string.scan(\/(\\d+)(\\D)\/).inject(\"\") do |decoding, (length, char)|\n    decoding << char * length.to_i\n  end\nend\n\ndef encode(str)\n    str.gsub(\/(.)\\1*\/) {$&.length.to_s + $1}\nend\n\ndef decode(str)\n    str.gsub(\/(\\d+)(\\D)\/) {$2 * $1.to_i}\nend\n\norig = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\np enc = encode(orig)\np dec = decode(enc)\nputs \"success!\" if dec == orig\n\n","human_summarization":"The code implements a run-length encoding algorithm for a string containing uppercase characters (A-Z). It compresses repeated characters by storing the length of the run. It also provides a function to reverse the compression. The output can be used to recreate the original input. The code also includes a built-in Ruby method for run-length encoding and a regular expression method for encoding and decoding.","id":1701}
    {"lang_cluster":"Ruby","source_code":"\ns = \"hello\"\n\nputs \"#{s} template\"       #=> \"hello template\"\n# Variable s is intact\nputs s                     #=> \"hello\" \n\nputs s + \" literal\"        #=> \"hello literal\"\n# Variable s is still the same\nputs s                     #=> \"hello\"\n\n# Mutating s variable:\n\ns += \" literal\"\nputs s                     #=> \"hello literal\"\ns << \" another\" # append to s, use only when string literals are not frozen\nputs s                     #=> \"hello literal another\"\n\ns = \"hello\"\nputs s.concat(\" literal\")  #=> \"hello literal\"\nputs s                     #=> \"hello literal\"\nputs s.prepend(\"Alice said: \")  #=> \"Alice said: hello literal\"\nputs s                     #=> \"Alice said: hello literal\"\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":1702}
    {"lang_cluster":"Ruby","source_code":"\n\nrequire 'cgi'\nputs CGI.escape(\"http:\/\/foo bar\/\").gsub(\"+\", \"%20\")\n# => \"http%3A%2F%2Ffoo%20bar%2F\"\n\n\nWorks with: Ruby version 1.9.2\nrequire 'uri'\nputs URI.encode_www_form_component(\"http:\/\/foo bar\/\").gsub(\"+\", \"%20\")\n# => \"http%3A%2F%2Ffoo%20bar%2F\"\n\n","human_summarization":"The code provides a function to convert a given string into URL encoding representation. It transforms special, control, and extended characters into a percent symbol followed by a two-digit hexadecimal code. It primarily converts characters except 0-9, A-Z, and a-z, including various ASCII control codes and symbols, and extended characters with codes of 128 and above. The code also supports lowercase escapes and different encoding standards like RFC 3986 and HTML 5. An optional feature allows the use of an exception string to preserve certain symbols. The code avoids using URI.escape due to its obsoleteness and potential encoding failures.","id":1703}
    {"lang_cluster":"Ruby","source_code":"\nnums = [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]\np nums.inject(:+).sort.uniq\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":1704}
    {"lang_cluster":"Ruby","source_code":"\nitems = [ [:beef   , 3.8, 36],\n          [:pork   , 5.4, 43],\n          [:ham    , 3.6, 90],\n          [:greaves, 2.4, 45],\n          [:flitch , 4.0, 30],\n          [:brawn  , 2.5, 56],\n          [:welt   , 3.7, 67],\n          [:salami , 3.0, 95],\n          [:sausage, 5.9, 98] ].sort_by{|item, weight, price| -price \/ weight}\nmaxW, value = 15.0, 0\nitems.each do |item, weight, price|\n  if (maxW -= weight) > 0\n    puts \"Take all #{item}\"\n    value += price\n  else\n    puts \"Take %gkg of %s\" % [t=weight+maxW, item], \"\",\n         \"Total value of swag is %g\" % (value+(price\/weight)*t)\n    break\n  end\nend\n\n\n","human_summarization":"determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.","id":1705}
    {"lang_cluster":"Ruby","source_code":"\nrequire 'open-uri'\n\nanagram = Hash.new {|hash, key| hash[key] = []} # map sorted chars to anagrams\n\nURI.open('http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt') do |f|\n  words = f.read.split\n  for word in words\n    anagram[word.split('').sort] << word\n  end\nend\n\ncount = anagram.values.map {|ana| ana.length}.max\nanagram.each_value do |ana|\n  if ana.length >= count\n    p ana\n  end\nend\n\n","human_summarization":"\"Find the largest sets of anagrams from a given word list, with results ordered lexically.\"","id":1706}
    {"lang_cluster":"Ruby","source_code":"def sierpinski_carpet(n)\n  carpet = [\"#\"]\n  n.times do\n    carpet = carpet.collect {|x| x + x + x} +\n             carpet.collect {|x| x + x.tr(\"#\",\" \") + x} +\n             carpet.collect {|x| x + x + x}\n  end\n  carpet\nend\n\n4.times{|i| puts \"\\nN=#{i}\", sierpinski_carpet(i)}\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses specific placement of whitespace and non-whitespace characters, with the non-whitespace characters not necessarily needing to be the '#' character. The code also includes a related task of generating a Sierpinski triangle and a graphical version using JRubyArt.","id":1707}
    {"lang_cluster":"Ruby","source_code":"\nUses a Library: RubyGems package PriorityQueue\nrequire 'priority_queue'\n\ndef huffman_encoding(str)\n  char_count = Hash.new(0)\n  str.each_char {|c| char_count[c] += 1}\n  \n  pq = CPriorityQueue.new\n  # chars with fewest count have highest priority\n  char_count.each {|char, count| pq.push(char, count)}\n  \n  while pq.length > 1\n    key1, prio1 = pq.delete_min\n    key2, prio2 = pq.delete_min\n    pq.push([key1, key2], prio1 + prio2)\n  end\n  \n  Hash[*generate_encoding(pq.min_key)]\nend\n\ndef generate_encoding(ary, prefix=\"\")\n  case ary\n  when Array\n    generate_encoding(ary[0], \"#{prefix}0\") + generate_encoding(ary[1], \"#{prefix}1\")\n  else\n    [ary, prefix]\n  end\nend\n\ndef encode(str, encoding)\n  str.each_char.collect {|char| encoding[char]}.join\nend\n\ndef decode(encoded, encoding)\n  rev_enc = encoding.invert\n  decoded = \"\"\n  pos = 0\n  while pos < encoded.length\n    key = \"\"\n    while rev_enc[key].nil?\n      key << encoded[pos]\n      pos += 1\n    end\n    decoded << rev_enc[key]\n  end\n  decoded\nend\n\nstr = \"this is an example for huffman encoding\"\nencoding = huffman_encoding(str)\nencoding.to_a.sort.each {|x| p x}\n\nenc = encode(str, encoding)\ndec = decode(enc, encoding)\nputs \"success!\" if str == dec\n\n[\" \", \"111\"]\n[\"a\", \"1011\"]\n[\"c\", \"00001\"]\n[\"d\", \"00000\"]\n[\"e\", \"1101\"]\n[\"f\", \"1100\"]\n[\"g\", \"00100\"]\n[\"h\", \"1000\"]\n[\"i\", \"1001\"]\n[\"l\", \"01110\"]\n[\"m\", \"10101\"]\n[\"n\", \"010\"]\n[\"o\", \"0001\"]\n[\"p\", \"00101\"]\n[\"r\", \"00111\"]\n[\"s\", \"0110\"]\n[\"t\", \"00110\"]\n[\"u\", \"01111\"]\n[\"x\", \"10100\"]\nsuccess!\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":1708}
    {"lang_cluster":"Ruby","source_code":"\nLibrary: Ruby\/Tk\nrequire 'tk'\nstr = TkVariable.new(\"no clicks yet\")\ncount = 0\nroot = TkRoot.new\nTkLabel.new(root, \"textvariable\" => str).pack\nTkButton.new(root) do\n  text \"click me\"\n  command {str.value = count += 1}\n  pack\nend\nTk.mainloop\n\nLibrary: Shoes\nShoes.app do\n  stack do\n    @count = 0\n    @label = para \"no clicks yet\"\n    button \"click me\" do \n      @count += 1\n      @label.text = \"click: #@count\"\n    end\n  end\nend\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":1709}
    {"lang_cluster":"Ruby","source_code":"\n\nrequire 'pstore'\nrequire 'set'\n\nAddress = Struct.new :id, :street, :city, :state, :zip\n\ndb = PStore.new(\"addresses.pstore\")\ndb.transaction do\n  db[:next] ||= 0       # Next available Address#id\n  db[:ids] ||= Set[]    # Set of all ids in db\nend\n\n\ndb.transaction do\n  id = (db[:next] += 1)\n  db[id] = Address.new(id,\n                       \"1600 Pennsylvania Avenue NW\",\n                       \"Washington\", \"DC\", 20500)\n  db[:ids].add id\nend\nLibrary: sqlite3-ruby\nrequire 'sqlite3'\n\ndb = SQLite3::Database.new(':memory:')\ndb.execute(\"\n    CREATE TABLE address (\n        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,\n        addrStreet TEXT NOT NULL,\n        addrCity   TEXT NOT NULL,\n        addrState  TEXT NOT NULL,\n        addrZIP    TEXT NOT NULL\n    )\n\")\n\n","human_summarization":"\"Create a table in a database to store US postal addresses, including fields for unique identifier, street address, city, state code, and zipcode. The code also demonstrates how to open a database connection in non-database languages and insert an address into the created table using a NoSQL database, PStore.\"","id":1710}
    {"lang_cluster":"Ruby","source_code":"\n10.downto(0) do |i|\n   puts i\nend\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":1711}
    {"lang_cluster":"Ruby","source_code":"\nmodule VigenereCipher\n  \n  BASE = 'A'.ord\n  SIZE = 'Z'.ord - BASE + 1\n  \n  def encrypt(text, key)\n    crypt(text, key, :+)\n  end\n  \n  def decrypt(text, key)\n    crypt(text, key, :-)\n  end\n  \n  def crypt(text, key, dir)\n    text = text.upcase.gsub(\/[^A-Z]\/, '')\n    key_iterator = key.upcase.gsub(\/[^A-Z]\/, '').chars.map{|c| c.ord - BASE}.cycle\n    text.each_char.inject('') do |ciphertext, char|\n      offset = key_iterator.next\n      ciphertext << ((char.ord - BASE).send(dir, offset) % SIZE + BASE).chr\n    end\n  end\n  \nend\n\n\ninclude VigenereCipher\n\nplaintext = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!'\nkey = 'Vigenere cipher'\nciphertext = VigenereCipher.encrypt(plaintext, key)\nrecovered  = VigenereCipher.decrypt(ciphertext, key)\n\nputs \"Original: #{plaintext}\"\nputs \"Encrypted: #{ciphertext}\"\nputs \"Decrypted: #{recovered}\"\n\n\n","human_summarization":"Implement and demonstrate a Vigen\u00e8re cipher for both encryption and decryption. The code handles keys and text of unequal length, capitalizes all characters, and discards non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":1712}
    {"lang_cluster":"Ruby","source_code":"\n2.step(8,2) {|n| print \"#{n}, \"}\nputs \"who do we appreciate?\"\n\n(2..8).step(2) {|n| print \"#{n}, \"}\nputs \"who do we appreciate?\"\n\nfor n in (2..8).step(2)\n  print \"#{n}, \"\nend\nputs \"who do we appreciate?\"\n\nfor n in 2.step(by: 2, to: 8)\n  print \"#{n}, \"\nend\nputs \"who do we appreciate?\"\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":1713}
    {"lang_cluster":"Ruby","source_code":"\n\ndef sum(var, lo, hi, term, context)\n  sum = 0.0\n  lo.upto(hi) do |n|\n    sum += eval \"#{var} = #{n}; #{term}\", context\n  end\n  sum\nend\np sum \"i\", 1, 100, \"1.0 \/ i\", binding   # => 5.18737751763962\n\n\ndef sum2(lo, hi)\n  lo.upto(hi).inject(0.0) {|sum, n| sum += yield n}\nend\np sum2(1, 100) {|i| 1.0\/i}  # => 5.18737751763962\n\n\ndef sum lo, hi, &term\n  (lo..hi).sum(&term)\nend\np sum(1,100){|i| 1.0\/i}   # => 5.187377517639621\n# or using Rational:\np sum(1,100){|i| Rational(1,i)}  # => 14466636279520351160221518043104131447711 \/ 2788815009188499086581352357412492142272\n\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique involves call by name and is illustrated through a program that computes the 100th harmonic number. The program exploits call by name to produce the correct result, relying on the re-evaluation of an expression passed as an actual parameter in the caller's context every time the corresponding formal parameter's value is required. The first parameter to the sum function, representing the \"bound\" variable of the summation, is also passed by name to ensure changes to it are visible in the caller's context. The global variable does not need to use the same identifier as the formal parameter. The code also includes a comparison to the Man or Boy Test proposed by Donald Knuth.","id":1714}
    {"lang_cluster":"Ruby","source_code":"\n\nSample output from Ruby program\nload 'raster_graphics.rb'\n\nclass Pixmap\n  def self.xor_pattern(width, height, rgb1, rgb2)\n    # create colour table\n    size = 256\n    colours = Array.new(size) do |i|\n      RGBColour.new(\n        (rgb1.red + (rgb2.red - rgb1.red) * i \/ size), \n        (rgb1.green + (rgb2.green - rgb1.green) * i \/ size), \n        (rgb1.blue + (rgb2.blue - rgb1.blue) * i \/ size), \n      )\n    end\n\n    # create the image\n    pixmap = new(width, height)\n    pixmap.each_pixel do |x, y|\n      pixmap[x,y] = colours[(x^y)%size]\n    end\n    pixmap\n  end\nend\n\nimg = Pixmap.xor_pattern(384, 384, RGBColour::RED, RGBColour::YELLOW)\nimg.save_as_png('xorpattern.png')\n\n","human_summarization":"\"Generates a graphical pattern using Ruby and raster graphics operations, where each pixel's color is determined by the 'x xor y' value from a given color table.\"","id":1715}
    {"lang_cluster":"Ruby","source_code":"\nclass Maze\n  DIRECTIONS = [ [1, 0], [-1, 0], [0, 1], [0, -1] ]\n  \n  def initialize(width, height)\n    @width   = width\n    @height  = height\n    @start_x = rand(width)\n    @start_y = 0\n    @end_x   = rand(width)\n    @end_y   = height - 1\n    \n    # Which walls do exist? Default to \"true\". Both arrays are\n    # one element bigger than they need to be. For example, the\n    # @vertical_walls[x][y] is true if there is a wall between\n    # (x,y) and (x+1,y). The additional entry makes printing easier.\n    @vertical_walls   = Array.new(width) { Array.new(height, true) }\n    @horizontal_walls = Array.new(width) { Array.new(height, true) }\n    # Path for the solved maze.\n    @path             = Array.new(width) { Array.new(height) }\n    \n    # \"Hack\" to print the exit.\n    @horizontal_walls[@end_x][@end_y] = false\n    \n    # Generate the maze.\n    generate\n  end\n  \n  # Print a nice ASCII maze.\n  def print\n    # Special handling: print the top line.\n    puts @width.times.inject(\"+\") {|str, x| str << (x == @start_x ? \"   +\" : \"---+\")}\n    \n    # For each cell, print the right and bottom wall, if it exists.\n    @height.times do |y|\n      line = @width.times.inject(\"|\") do |str, x|\n        str << (@path[x][y] ? \" * \" : \"   \") << (@vertical_walls[x][y] ? \"|\" : \" \")\n      end\n      puts line\n      \n      puts @width.times.inject(\"+\") {|str, x| str << (@horizontal_walls[x][y] ? \"---+\" : \"   +\")}\n    end\n  end\n  \n  private\n  \n  # Reset the VISITED state of all cells.\n  def reset_visiting_state\n    @visited = Array.new(@width) { Array.new(@height) }\n  end\n  \n  # Is the given coordinate valid and the cell not yet visited?\n  def move_valid?(x, y)\n    (0...@width).cover?(x) && (0...@height).cover?(y) && !@visited[x][y]\n  end\n  \n  # Generate the maze.\n  def generate\n    reset_visiting_state\n    generate_visit_cell(@start_x, @start_y)\n  end\n  \n  # Depth-first maze generation.\n  def generate_visit_cell(x, y)\n    # Mark cell as visited.\n    @visited[x][y] = true\n    \n    # Randomly get coordinates of surrounding cells (may be outside\n    # of the maze range, will be sorted out later).\n    coordinates = DIRECTIONS.shuffle.map { |dx, dy| [x + dx, y + dy] }\n    \n    for new_x, new_y in coordinates\n      next unless move_valid?(new_x, new_y)\n      \n      # Recurse if it was possible to connect the current and\n      # the cell (this recursion is the \"depth-first\" part).\n      connect_cells(x, y, new_x, new_y)\n      generate_visit_cell(new_x, new_y)\n    end\n  end\n  \n  # Try to connect two cells. Returns whether it was valid to do so.\n  def connect_cells(x1, y1, x2, y2)\n    if x1 == x2\n      # Cells must be above each other, remove a horizontal wall.\n      @horizontal_walls[x1][ [y1, y2].min ] = false\n    else\n      # Cells must be next to each other, remove a vertical wall.\n      @vertical_walls[ [x1, x2].min ][y1] = false\n    end\n  end\nend\n\n# Demonstration:\nmaze = Maze.new 20, 10\nmaze.print\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":1716}
    {"lang_cluster":"Ruby","source_code":"pi_digits = Enumerator.new do |y|\n  q, r, t, k, n, l = 1, 0, 1, 1, 3, 3\n  loop do\n    if 4*q+r-t < n*t\n      y << n \n      nr = 10*(r-n*t)\n      n = ((10*(3*q+r)) \/ t) - 10*n\n      q *= 10\n      r = nr\n    else\n      nr = (2*q+r) * l\n      nn = (q*(7*k+2)+r*l) \/ (t*l)\n      q *= k\n      t *= l\n      l += 2\n      k += 1\n      n = nn\n      r = nr\n    end\n  end\nend\n\nprint pi_digits.next, \".\"\nloop { print pi_digits.next }\n\n","human_summarization":"are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.","id":1717}
    {"lang_cluster":"Ruby","source_code":"\n\n>> ([1,2,1,3,2] <=> [1,2,0,4,4,0,0,0]) < 0\n=> false\n\n","human_summarization":"\"Function to compare two numerical lists lexicographically and return true if the first list should be ordered before the second, false otherwise.\"","id":1718}
    {"lang_cluster":"Ruby","source_code":"def ack(m, n)\n  if m == 0\n    n + 1\n  elsif n == 0\n    ack(m-1, 1)\n  else\n    ack(m-1, ack(m, n-1))\n  end\nend\n\n(0..3).each do |m|\n  puts (0..6).map { |n| ack(m, n) }.join(' ')\nend\n\n","human_summarization":"implement the Ackermann function, a non-primitive recursive function that takes two non-negative arguments and returns a rapidly growing value. The function should ideally support arbitrary precision due to the rapid growth of the function's output.","id":1719}
    {"lang_cluster":"Ruby","source_code":"$a = [ 1.00000_00000_00000_00000,  0.57721_56649_01532_86061, -0.65587_80715_20253_88108,\n      -0.04200_26350_34095_23553,  0.16653_86113_82291_48950, -0.04219_77345_55544_33675,\n      -0.00962_19715_27876_97356,  0.00721_89432_46663_09954, -0.00116_51675_91859_06511,\n      -0.00021_52416_74114_95097,  0.00012_80502_82388_11619, -0.00002_01348_54780_78824,\n      -0.00000_12504_93482_14267,  0.00000_11330_27231_98170, -0.00000_02056_33841_69776,\n       0.00000_00061_16095_10448,  0.00000_00050_02007_64447, -0.00000_00011_81274_57049,\n       0.00000_00001_04342_67117,  0.00000_00000_07782_26344, -0.00000_00000_03696_80562,\n       0.00000_00000_00510_03703, -0.00000_00000_00020_58326, -0.00000_00000_00005_34812,\n       0.00000_00000_00001_22678, -0.00000_00000_00000_11813,  0.00000_00000_00000_00119,\n       0.00000_00000_00000_00141, -0.00000_00000_00000_00023,  0.00000_00000_00000_00002 ]\n \ndef gamma(x)\n  y = Float(x) - 1\n  1.0 \/ $a.reverse.inject {|sum, an| sum * y + an}\nend\n\n(1..10).each {|i| puts format(\"%.14e\", gamma(i\/3.0))}\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":1720}
    {"lang_cluster":"Ruby","source_code":"\n\n# 1. Divide n by 12. Remember the remainder (n is 8 for the eight queens\n#    puzzle).\n# 2. Write a list of the even numbers from 2 to n in order.\n# 3. If the remainder is 3 or 9, move 2 to the end of the list.\n# 4. Append the odd numbers from 1 to n in order, but, if the remainder is 8,\n#    switch pairs (i.e. 3, 1, 7, 5, 11, 9, \u2026).\n# 5. If the remainder is 2, switch the places of 1 and 3, then move 5 to the\n#    end of the list.\n# 6. If the remainder is 3 or 9, move 1 and 3 to the end of the list.\n# 7. Place the first-column queen in the row with the first number in the\n#    list, place the second-column queen in the row with the second number in\n#    the list, etc.\n\n\ndef n_queens(n)\n  if n == 1\n    return \"Q\"\n  elsif n < 4\n    puts \"no solutions for n=#{n}\"\n    return \"\"\n  end\n \n  evens = (2..n).step(2).to_a\n  odds = (1..n).step(2).to_a\n \n  rem = n\u00a0% 12  # (1)\n  nums = evens  # (2)\n \n  nums.rotate if rem == 3 or rem == 9  # (3)\n \n  # (4)\n  if rem == 8\n    odds = odds.each_slice(2).flat_map(&:reverse)\n  end\n  nums.concat(odds)\n \n  # (5)\n  if rem == 2\n    nums[nums.index(1)], nums[nums.index(3)] = nums[nums.index(3)], nums[nums.index(1)]\n    nums << nums.delete(5)\n  end\n \n  # (6)\n  if rem == 3 or rem == 9\n    nums << nums.delete(1)\n    nums << nums.delete(3)\n  end\n \n  # (7)\n  nums.map do |q|\n    a = Array.new(n,\".\")\n    a[q-1] = \"Q\"\n    a*(\" \")\n  end\nend\n \n(1 .. 15).each {|n| puts \"n=#{n}\"; puts n_queens(n); puts}\n\n","human_summarization":"\"Code implements a solution to the N-queens problem, including the eight queens puzzle. It uses heuristics from Wikipedia to return one solution or all solutions if not specified. It also provides the number of solutions for small values of N.\"","id":1721}
    {"lang_cluster":"Ruby","source_code":"\n\narr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2  # => [1, 2, 3, 4, 5, 6]\narr4.concat(arr3)  # => [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n# concat multiple arrays:\n[arr1,arr2,arr3].flatten(1)\n# ignore nil:\n[arr1,arr2,arr3].compact.flatten(1)\n","human_summarization":"demonstrate how to concatenate two arrays using either the Array#+ method, the Array#concat method, or the flatten(1) method in the given programming language.","id":1722}
    {"lang_cluster":"Ruby","source_code":"\nKnapsackItem = Struct.new(:name, :weight, :value)\npotential_items = [\n  KnapsackItem['map', 9, 150],              KnapsackItem['compass', 13, 35],\n  KnapsackItem['water', 153, 200],          KnapsackItem['sandwich', 50, 160],\n  KnapsackItem['glucose', 15, 60],          KnapsackItem['tin', 68, 45],\n  KnapsackItem['banana', 27, 60],           KnapsackItem['apple', 39, 40],\n  KnapsackItem['cheese', 23, 30],           KnapsackItem['beer', 52, 10],\n  KnapsackItem['suntan cream', 11, 70],     KnapsackItem['camera', 32, 30],\n  KnapsackItem['t-shirt', 24, 15],          KnapsackItem['trousers', 48, 10],\n  KnapsackItem['umbrella', 73, 40],         KnapsackItem['waterproof trousers', 42, 70],\n  KnapsackItem['waterproof overclothes', 43, 75], KnapsackItem['note-case', 22, 80],\n  KnapsackItem['sunglasses', 7, 20],        KnapsackItem['towel', 18, 12],\n  KnapsackItem['socks', 4, 50],             KnapsackItem['book', 30, 10],\n]\nknapsack_capacity = 400\n\nclass Array\n  # do something for each element of the array's power set\n  def power_set\n    yield [] if block_given?\n    self.inject([[]]) do |ps, elem|\n      ps.each_with_object([]) do |i,r|\n        r << i\n        new_subset = i + [elem]\n        yield new_subset if block_given?\n        r << new_subset\n      end\n    end\n  end\nend\n\nmaxval, solutions = potential_items.power_set.group_by {|subset|\n  weight = subset.inject(0) {|w, elem| w + elem.weight}\n  weight>knapsack_capacity ? 0 : subset.inject(0){|v, elem| v + elem.value}\n}.max\n\nputs \"value: #{maxval}\"\nsolutions.each do |set|\n  wt, items = 0, []\n  set.each {|elem| wt += elem.weight; items << elem.name}\n  puts \"weight: #{wt}\"\n  puts \"items: #{items.join(',')}\"\nend\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg, to maximize the total value of the items. The items cannot be divided and only one of each item is available. The items, their weights, and their values are provided in a list.","id":1723}
    {"lang_cluster":"Ruby","source_code":"\nclass Person\n  def initialize(name)\n    @name = name\n    @fiance = nil\n    @preferences = []\n    @proposals = []\n  end\n  attr_reader :name, :proposals\n  attr_accessor :fiance, :preferences\n\n  def to_s\n    @name\n  end\n\n  def free\n    @fiance = nil\n  end\n\n  def single?\n    @fiance == nil\n  end\n\n  def engage(person)\n    self.fiance = person\n    person.fiance = self\n  end\n\n  def better_choice?(person)\n    @preferences.index(person) < @preferences.index(@fiance)\n  end\n\n  def propose_to(person)\n    puts \"#{self} proposes to #{person}\" if $DEBUG\n    @proposals << person\n    person.respond_to_proposal_from(self)\n  end\n\n  def respond_to_proposal_from(person)\n    if single?\n      puts \"#{self} accepts proposal from #{person}\" if $DEBUG\n      engage(person)\n    elsif better_choice?(person)\n      puts \"#{self} dumps #{@fiance} for #{person}\" if $DEBUG\n      @fiance.free\n      engage(person)\n    else\n      puts \"#{self} rejects proposal from #{person}\" if $DEBUG\n    end\n  end\nend\n\n########################################################################\n# initialize data\n\nprefs = {\n  'abe'  => %w[abi eve cath ivy jan dee fay bea hope gay],\n  'bob'  => %w[cath hope abi dee eve fay bea jan ivy gay],\n  'col'  => %w[hope eve abi dee bea fay ivy gay cath jan],\n  'dan'  => %w[ivy fay dee gay hope eve jan bea cath abi],\n  'ed'   => %w[jan dee bea cath fay eve abi ivy hope gay],\n  'fred' => %w[bea abi dee gay eve ivy cath jan hope fay],\n  'gav'  => %w[gay eve ivy bea cath abi dee hope jan fay],\n  'hal'  => %w[abi eve hope fay ivy cath jan bea gay dee],\n  'ian'  => %w[hope cath dee gay bea abi fay ivy jan eve],\n  'jon'  => %w[abi fay jan gay eve bea dee cath ivy hope],\n  'abi'  => %w[bob fred jon gav ian abe dan ed col hal],\n  'bea'  => %w[bob abe col fred gav dan ian ed jon hal],\n  'cath' => %w[fred bob ed gav hal col ian abe dan jon],\n  'dee'  => %w[fred jon col abe ian hal gav dan bob ed],\n  'eve'  => %w[jon hal fred dan abe gav col ed ian bob],\n  'fay'  => %w[bob abe ed ian jon dan fred gav col hal],\n  'gay'  => %w[jon gav hal fred bob abe col ed dan ian],\n  'hope' => %w[gav jon bob abe ian dan hal ed col fred],\n  'ivy'  => %w[ian col hal gav fred bob abe ed jon dan],\n  'jan'  => %w[ed hal gav abe bob jon col ian fred dan],\n}\n\n@men = Hash[\n  %w[abe bob col dan ed fred gav hal ian jon].collect do |name|\n    [name, Person.new(name)]\n  end\n]\n\n@women = Hash[\n  %w[abi bea cath dee eve fay gay hope ivy jan].collect do |name|\n    [name, Person.new(name)]\n  end\n]\n\n@men.each {|name, man| man.preferences = @women.values_at(*prefs[name])}\n@women.each {|name, woman| woman.preferences = @men.values_at(*prefs[name])}\n\n########################################################################\n# perform the matching\n\ndef match_couples(men, women)\n  men.each_value {|man| man.free}\n  women.each_value {|woman| woman.free}\n\n  while m = men.values.find {|man| man.single?} do\n    puts \"considering single man #{m}\" if $DEBUG\n    w = m.preferences.find {|woman| not m.proposals.include?(woman)}\n    m.propose_to(w)\n  end\nend\n\nmatch_couples @men, @women\n\n@men.each_value.collect {|man| puts \"#{man} + #{man.fiance}\"}\n\n########################################################################\n# check for stability\n\nclass Person\n  def more_preferable_people\n    ( @preferences.partition {|p| better_choice?(p)} ).first\n  end\nend\n\nrequire 'set'\n\ndef stability(men)\n  unstable = Set.new\n  men.each_value do |man|\n    woman = man.fiance\n    puts \"considering #{man} and #{woman}\" if $DEBUG\n\n    man.more_preferable_people.each do |other_woman|\n      if other_woman.more_preferable_people.include?(man)\n        puts \"an unstable pairing: #{man} and #{other_woman}\" if $DEBUG\n        unstable << [man, other_woman]\n      end\n    end\n    woman.more_preferable_people.each do |other_man|\n      if other_man.more_preferable_people.include?(woman)\n        puts \"an unstable pairing: #{woman} and #{other_man}\" if $DEBUG\n        unstable << [other_man, woman]\n      end\n    end\n  end\n\n  if unstable.empty?\n    puts \"these couples are stable\"\n  else\n    puts \"uh oh\"\n    unstable.each do |a,b|\n      puts \"#{a} is engaged to #{a.fiance} but would prefer #{b}, and #{b} is engaged to #{b.fiance} but would prefer #{a}\"\n    end\n  end\nend\n\nstability @men\n\n########################################################################\n# perturb\n\nputs \"\\nwhat if abe and bob swap...\"\n\ndef swap(m1, m2)\n  w1 = m1.fiance\n  w2 = m2.fiance\n  m1.fiance = w2\n  w1.fiance = m2\n  m2.fiance = w1\n  w2.fiance = m1\nend\n\nswap *@men.values_at('abe','bob')\n\n@men.each_value.collect {|man| puts \"#{man} + #{man.fiance}\"}\nstability @men\n\n\n","human_summarization":"The code implements the Gale-Shapley algorithm to solve the Stable Marriage problem. It takes as input the preferences of ten men and ten women for each other, and generates a stable set of engagements. The code then perturbs this set to create an unstable set of engagements, and checks the stability of this new set.","id":1724}
    {"lang_cluster":"Ruby","source_code":"\n\ndef a( bool )\n  puts \"a( #{bool} ) called\"\n  bool\nend\n\ndef b( bool )\n  puts \"b( #{bool} ) called\"\n  bool\nend\n\n [true, false].each do |a_val|\n   [true, false].each do |b_val|\n     puts \"a( #{a_val} ) and b( #{b_val} ) is #{a( a_val ) and b( b_val )}.\"\n     puts\n     puts \"a( #{a_val} ) or b( #{b_val} ) is #{a( a_val)  or b( b_val )}.\"\n     puts\n   end\n end\n\n\n","human_summarization":"The code defines two functions, a and b, which take a boolean value as input, return the same value, and print their names when called. The code then calculates the values of two equations, x = a(i) and b(j) and y = a(i) or b(j), using short-circuit evaluation to ensure that function b is only called when necessary. If the programming language does not support short-circuit evaluation, this is achieved using nested if statements.","id":1725}
    {"lang_cluster":"Ruby","source_code":"\nWorks with: Ruby version 1.8.7+ (uses each_char)\nLibrary: win32-utils\nrequire 'win32\/sound'\n\nclass MorseCode\n  MORSE = {\n      \"!\" => \"---.\", \"\\\"\" => \".-..-.\", \"$\" => \"...-..-\", \"'\" => \".----.\",\n      \"(\" => \"-.--.\", \")\" => \"-.--.-\", \"+\" => \".-.-.\", \",\" => \"--..--\",\n      \"-\" => \"-....-\", \".\" => \".-.-.-\", \"\/\" => \"-..-.\", \"0\" => \"-----\",\n      \"1\" => \".----\", \"2\" => \"..---\", \"3\" => \"...--\", \"4\" => \"....-\", \"5\" => \".....\",\n      \"6\" => \"-....\", \"7\" => \"--...\", \"8\" => \"---..\", \"9\" => \"----.\", \":\" => \"---...\",\n      \";\" => \"-.-.-.\", \"=\" => \"-...-\", \"?\" => \"..--..\", \"@\" => \".--.-.\", \"A\" => \".-\",\n      \"B\" => \"-...\", \"C\" => \"-.-.\", \"D\" => \"-..\", \"E\" => \".\", \"F\" => \"..-.\",\n      \"G\" => \"--.\", \"H\" => \"....\", \"I\" => \"..\", \"J\" => \".---\", \"K\" => \"-.-\",\n      \"L\" => \".-..\", \"M\" => \"--\", \"N\" => \"-.\", \"O\" => \"---\", \"P\" => \".--.\",\n      \"Q\" => \"--.-\", \"R\" => \".-.\", \"S\" => \"...\", \"T\" => \"-\", \"U\" => \"..-\",\n      \"V\" => \"...-\", \"W\" => \".--\", \"X\" => \"-..-\", \"Y\" => \"-.--\", \"Z\" => \"--..\",\n      \"[\" => \"-.--.\", \"]\" => \"-.--.-\", \"_\" => \"..--.-\",\n  }\n\n  T_UNIT = 75 # ms\n  FREQ = 700\n  DIT = 1 * T_UNIT\n  DAH = 3 * T_UNIT\n  CHARGAP = 1 * T_UNIT\n  WORDGAP = 7 * T_UNIT\n\n  def initialize(string)\n    @message = string\n    puts \"your message is #{string.inspect}\"\n  end\n\n  def send\n    @message.strip.upcase.split.each do |word|\n      word.each_char do |char|\n        send_char char\n        pause CHARGAP\n        print \" \"\n      end\n      pause WORDGAP\n      puts \"\"\n    end\n  end\n\n  private\n  def send_char(char)\n    MORSE[char].each_char do |code|\n      case code\n      when '.' then beep DIT\n      when '-' then beep DAH\n      end\n      pause CHARGAP\n      print code\n    end\n  end\n\n  def beep(ms)\n    ::Win32::Sound.beep(FREQ, ms)\n  end\n\n  def pause(ms)\n    sleep(ms.to_f\/1000.0)\n  end\nend\n\nMorseCode.new('sos').send\nMorseCode.new('this is a test.').send\n\n\n","human_summarization":"<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":1726}
    {"lang_cluster":"Ruby","source_code":"\n\nwords = %w(A BaRK BOoK tREaT COmMOn SqUAD CoNfuSE) << \"\"\n\nwords.each do |word|\n  blocks = \"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\"\n  res = word.each_char.all?{|c| blocks.sub!(\/\\w?#{c}\\w?\/i, \"\")}  #regexps can be interpolated like strings\n  puts \"#{word.inspect}: #{res}\"\nend\n\n","human_summarization":"The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive. It tests the function with seven example words and displays the results.","id":1727}
    {"lang_cluster":"Ruby","source_code":"\nrequire 'digest'\nDigest::MD5.hexdigest(\"The quick brown fox jumped over the lazy dog's back\")\n# => \"e38ca1d920c4b8b8d3946b2c72f01680\"\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":1728}
    {"lang_cluster":"Ruby","source_code":"\n%w[\n  1.3.6.1.4.1.11.2.17.19.3.4.0.10\n  1.3.6.1.4.1.11.2.17.5.2.0.79\n  1.3.6.1.4.1.11.2.17.19.3.4.0.4\n  1.3.6.1.4.1.11150.3.4.0.1\n  1.3.6.1.4.1.11.2.17.19.3.4.0.1\n  1.3.6.1.4.1.11150.3.4.0\n]\n.sort_by{|oid| oid.split(\".\").map(&:to_i)}\n.each{|oid| puts oid}\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs). The OIDs are strings used to identify objects in network data and are composed of one or more non-negative integers in base 10, separated by dots. The sorting is done lexicographically with regard to the dot-separated fields, using numeric comparison between fields.","id":1729}
    {"lang_cluster":"Ruby","source_code":"\nrequire 'socket'\nsock = TCPSocket.open(\"localhost\", 256)\nsock.write(\"hello socket world\")\nsock.close\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":1730}
    {"lang_cluster":"Ruby","source_code":"\nUses the Library: RubyGems gems TMail which allows us to manipulate email objects conveniently, and mime-types which guesses a file's mime type based on its filename.\nrequire 'base64'\nrequire 'net\/smtp'\nrequire 'tmail'\nrequire 'mime\/types'\n\nclass Email\n  def initialize(from, to, subject, body, options={})\n    @opts = {:attachments => [], :server => 'localhost'}.update(options)\n    @msg = TMail::Mail.new\n    @msg.from    = from\n    @msg.to      = to\n    @msg.subject = subject\n    @msg.cc      = @opts[:cc]  if @opts[:cc]\n    @msg.bcc     = @opts[:bcc] if @opts[:bcc]\n\n    if @opts[:attachments].empty?\n      # just specify the body\n      @msg.body = body\n    else\n      # attach attachments, including the body\n      @msg.body = \"This is a multi-part message in MIME format.\\n\"\n\n      msg_body = TMail::Mail.new\n      msg_body.body = body\n      msg_body.set_content_type(\"text\",\"plain\", {:charset => \"ISO-8859-1\"})\n      @msg.parts << msg_body\n\n      octet_stream = MIME::Types['application\/octet-stream'].first\n\n      @opts[:attachments].select {|file| File.readable?(file)}.each do |file|\n        mime_type = MIME::Types.type_for(file).first || octet_stream\n        @msg.parts << create_attachment(file, mime_type)\n      end\n    end\n  end\n  attr_reader :msg\n\n  def create_attachment(file, mime_type)\n    attach = TMail::Mail.new\n    if mime_type.binary?\n      attach.body = Base64.encode64(File.read(file))\n      attach.transfer_encoding = 'base64'\n    else\n      attach.body = File.read(file)\n    end\n    attach.set_disposition(\"attachment\", {:filename => file})\n    attach.set_content_type(mime_type.media_type, mime_type.sub_type, {:name=>file})\n    attach\n  end\n\n  # instance method to send an Email object\n  def send\n    args = @opts.values_at(:server, :port, :helo, :username, :password, :authtype)\n    Net::SMTP.start(*args) do |smtp|\n      smtp.send_message(@msg.to_s, @msg.from[0], @msg.to)\n    end\n  end\n\n  # class method to construct an Email object and send it\n  def self.send(*args)\n    self.new(*args).send\n  end\nend\n\nEmail.send(\n  'sender@sender.invalid',\n  %w{ recip1@recipient.invalid recip2@example.com },\n  'the subject',\n  \"the body\\nhas lines\",\n  {\n    :attachments => %w{ file1 file2 file3 },\n    :server => 'mail.example.com',\n    :helo => 'sender.invalid',\n    :username => 'user',\n    :password => 'secret'\n  }\n)\n\n","human_summarization":"Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.","id":1731}
    {"lang_cluster":"Ruby","source_code":"\nn = 0\nloop do\n  puts \"%o\" % n\n  n += 1\nend\n\n# or\nfor n in (0..)\n  puts n.to_s(8)\nend\n\n# or\n0.upto(1\/0.0) do |n|\n  printf \"%o\\n\", n\nend\n\n# version 2.1 later\n0.step do |n|\n  puts format(\"%o\", n)\nend\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":1732}
    {"lang_cluster":"Ruby","source_code":"\n\na, b = b, a\n\ndef swap(a, b)\n    return b, a\nend\n\nx = 42\ny = \"string\"\nx, y = swap x, y\nputs x  # prints string\nputs y  # prints 42\n","human_summarization":"implements a generic swap function or operator that exchanges the values of two variables or storage places, regardless of their types. The function is designed to work with statically typed languages and dynamically typed languages. It ensures that the two variables have a mutually compatible type to avoid type violation. However, the function does not destructively swap two variables. Instead, it returns a new array with the swapped values. The original variables can be assigned with the return value.","id":1733}
    {"lang_cluster":"Ruby","source_code":"\n\ndef palindrome?(s)\n  s == s.reverse\nend\n\ndef r_palindrome?(s)\n  if s.length <= 1\n    true\n  elsif s[0]\u00a0!= s[-1]\n    false\n  else\n    r_palindrome?(s[1..-2])\n  end\nend\n\nstr = \"A man, a plan, a caret, [...2110 chars deleted...] a canal--Panama.\".downcase.delete('^a-z')\nputs palindrome?(str)    # => true\nputs r_palindrome?(str)  # => true\n\nrequire 'benchmark'\nBenchmark.bm do |b|\n  b.report('iterative') {10000.times {palindrome?(str)}}\n  b.report('recursive') {10000.times {r_palindrome?(str)}}\nend\n\n","human_summarization":"The code is a function that checks if a given sequence of characters is a palindrome. It supports Unicode characters and has an additional function to detect inexact palindromes, ignoring white-space, punctuation, and case. The code uses both non-recursive and recursive methods, with the recursive method being slower.","id":1734}
    {"lang_cluster":"Ruby","source_code":"\n\nENV['HOME']\n\n","human_summarization":"demonstrate how to retrieve a specific environment variable from a process using the ENV hash, which maps variable names to their values. Common Unix environment variables include PATH, HOME, and USER.","id":1735}
    {"lang_cluster":"Ruby","source_code":"\ndef sudan(n, x, y)\n  return x + y if n == 0\n  return x if y == 0\n\n  sudan(n - 1, sudan(n, x, y - 1), sudan(n, x, y - 1) + y)\nend\n\n\nputs sudan(1, 3, 3)\n> 35\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function. The function takes two parameters x and y, and returns the value of F(x, y) based on the defined rules of the Sudan function.","id":1736}
    {"lang_cluster":"Lua","source_code":"\n\nstack = {}\ntable.insert(stack,3)\nprint(table.remove(stack)) --> 3\n\n","human_summarization":"implement a stack data structure that supports basic operations such as push (adding an element to the top of the stack), pop (removing the topmost element from the stack and returning it), and empty (checking if the stack is empty).","id":1737}
    {"lang_cluster":"Lua","source_code":"\n--calculates the nth fibonacci number. Breaks for negative or non-integer n.\nfunction fibs(n) \n  return n < 2 and n or fibs(n - 1) + fibs(n - 2) \nend\nPedantic --more pedantic version, returns 0 for non-integer n\nfunction pfibs(n)\n  if n ~= math.floor(n) then return 0\n  elseif n < 0 then return pfibs(n + 2) - pfibs(n + 1)\n  elseif n < 2 then return n\n  else return pfibs(n - 1) + pfibs(n - 2)\n  end\nend\nTail function a(n,u,s) if n<2 then return u+s end return a(n-1,u+s,u) end\nfunction trfib(i) return a(i-1,1,0) end\nTable fib_n = setmetatable({1, 1}, {__index = function(z,n) return n<=0 and 0 or z[n-1] + z[n-2] end})\n-- table recursive done properly (values are actually saved into table;\n-- also the first element of Fibonacci sequence is 0, so the initial table should be {0, 1}).\nfib_n = setmetatable({0, 1}, {\n  __index = function(t,n)\n    if n <= 0 then return 0 end\n    t[n] = t[n-1] + t[n-2]\n    return t[n]\n  end\n})\nfunction ifibs(n)\n  local p0,p1=0,1\n  for _=1,n do p0,p1 = p1,p0+p1 end\n  return p0\nend\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":1738}
    {"lang_cluster":"Lua","source_code":"\nfunction filter(t, func)\n  local ret = {}\n  for i, v in ipairs(t) do\n    ret[#ret+1] = func(v) and v or nil\n  end\n  return ret\nend\n\nfunction even(a) return a % 2 == 0 end\n\nprint(unpack(filter({1, 2, 3, 4 ,5, 6, 7, 8, 9, 10}, even)))\n\n\nfunction filter(t, func)\n  for i, v in ipairs(t) do\n    if not func(v) then table.remove(t, i) end\n  end\nend\n\nfunction even(a) return a % 2 == 0 end\n\nlocal values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\nfilter(values, even)\nprint(unpack(values))\n\n","human_summarization":"select certain elements from an array into a new array in a generic way, specifically all even numbers. Optionally, it also provides a destructive version that modifies the original array instead of creating a new one.","id":1739}
    {"lang_cluster":"Lua","source_code":"\nstr = \"abcdefghijklmnopqrstuvwxyz\"\nn, m = 5, 15\n\nprint( string.sub( str, n, m ) )    -- efghijklmno\nprint( string.sub( str, n, -1 ) )   -- efghijklmnopqrstuvwxyz\nprint( string.sub( str, 1, -2 ) )   -- abcdefghijklmnopqrstuvwxy\n\npos = string.find( str, \"i\" )\nif pos ~= nil then print( string.sub( str, pos, pos+m ) ) end -- ijklmnopqrstuvwx\n\npos = string.find( str, \"ijk\" )\nif pos ~= nil then print( string.sub( str, pos, pos+m ) ) end-- ijklmnopqrstuvwx \n\n-- Alternative (more modern) notation\n\nprint ( str:sub(n,m) )         -- efghijklmno\nprint ( str:sub(n) )           -- efghijklmnopqrstuvwxyz\nprint ( str:sub(1,-2) )        -- abcdefghijklmnopqrstuvwxy\n\npos = str:find \"i\"\nif pos then print (str:sub(pos,pos+m)) end -- ijklmnopqrstuvwx \n\npos = str:find \"ijk\"\nif pos then print (str:sub(pos,pos+m)) end d-- ijklmnopqrstuvwx\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":1740}
    {"lang_cluster":"Lua","source_code":"\n\nexample = 'asdf'\nstring.reverse(example) -- fdsa\nexample:reverse() -- fdsa\n\n","human_summarization":"\"Reverses a given string while preserving the order of Unicode combining characters. Note: Lua's built-in string.reverse() function is not used due to lack of Unicode support.\"","id":1741}
    {"lang_cluster":"Lua","source_code":"\n\n-- Graph definition\nlocal edges = {\n    a = {b = 7, c = 9, f = 14},\n    b = {c = 10, d = 15},\n    c = {d = 11, f = 2},\n    d = {e = 6},\n    e = {f = 9}\n}\n\n-- Fill in paths in the opposite direction to the stated edges\nfunction complete (graph)\n    for node, edges in pairs(graph) do\n        for edge, distance in pairs(edges) do\n            if not graph[edge] then graph[edge] = {} end\n            graph[edge][node] = distance\n        end\n    end\nend\n\n-- Create path string from table of previous nodes\nfunction follow (trail, destination)\n    local path, nextStep = destination, trail[destination]\n    while nextStep do\n        path = nextStep .. \" \" .. path \n        nextStep = trail[nextStep]\n    end\n    return path\nend\n\n-- Find the shortest path between the current and destination nodes\nfunction dijkstra (graph, current, destination, directed)\n    if not directed then complete(graph) end\n    local unvisited, distanceTo, trail = {}, {}, {}\n    local nearest, nextNode, tentative\n    for node, edgeDists in pairs(graph) do\n        if node == current then\n            distanceTo[node] = 0\n            trail[current] = false\n        else\n            distanceTo[node] = math.huge\n            unvisited[node] = true\n        end\n    end\n    repeat\n        nearest = math.huge\n        for neighbour, pathDist in pairs(graph[current]) do\n            if unvisited[neighbour] then\n                tentative = distanceTo[current] + pathDist\n                if tentative < distanceTo[neighbour] then\n                    distanceTo[neighbour] = tentative\n                    trail[neighbour] = current\n                end\n                if tentative < nearest then\n                    nearest = tentative\n                    nextNode = neighbour\n                end\n            end\n        end\n        unvisited[current] = false\n        current = nextNode\n    until unvisited[destination] == false or nearest == math.huge\n    return distanceTo[destination], follow(trail, destination)\nend\n\n-- Main procedure\nprint(\"Directed:\", dijkstra(edges, \"a\", \"e\", true))\nprint(\"Undirected:\", dijkstra(edges, \"a\", \"e\", false))\n\n\n","human_summarization":"Implement Dijkstra's algorithm to find the shortest path from a given source node to all other nodes in a directed, weighted graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges representing the shortest path to each reachable node from the source. The code also includes functionality to interpret the output and display the shortest path from the source node to specific nodes.","id":1742}
    {"lang_cluster":"Lua","source_code":"\nAVL={balance=0}\nAVL.__mt={__index = AVL}\n\n\nfunction AVL:new(list)\n  local o={}  \n  setmetatable(o, AVL.__mt)\n  for _,v in ipairs(list or {}) do\n    o=o:insert(v)\n  end\n  return o\nend\n  \nfunction AVL:rebalance()\n  local rotated=false\n  if self.balance>1 then\n    if self.right.balance<0 then\n      self.right, self.right.left.right, self.right.left = self.right.left, self.right, self.right.left.right\n      self.right.right.balance=self.right.balance>-1 and 0 or 1\n      self.right.balance=self.right.balance>0 and 2 or 1\n    end\n    self, self.right.left, self.right = self.right, self, self.right.left\n    self.left.balance=1-self.balance\n    self.balance=self.balance==0 and -1 or 0\n    rotated=true\n  elseif self.balance<-1 then\n    if self.left.balance>0 then\n      self.left, self.left.right.left, self.left.right = self.left.right, self.left, self.left.right.left\n      self.left.left.balance=self.left.balance<1 and 0 or -1\n      self.left.balance=self.left.balance<0 and -2 or -1\n    end\n    self, self.left.right, self.left = self.left, self, self.left.right\n    self.right.balance=-1-self.balance\n    self.balance=self.balance==0 and 1 or 0\n    rotated=true\n  end\n  return self,rotated\nend\n\nfunction AVL:insert(v)\n  if not self.value then \n    self.value=v\n    self.balance=0\n    return self,1\n  end\n  local grow\n  if v==self.value then\n    return self,0\n  elseif v<self.value then\n    if not self.left then self.left=self:new() end\n    self.left,grow=self.left:insert(v)\n    self.balance=self.balance-grow\n  else\n    if not self.right then self.right=self:new() end\n    self.right,grow=self.right:insert(v)\n    self.balance=self.balance+grow\n  end\n  self,rotated=self:rebalance()\n  return self, (rotated or self.balance==0) and 0 or grow \nend\n\nfunction AVL:delete_move(dir,other,mul)\n  if self[dir] then\n    local sb2,v\n    self[dir], sb2, v=self[dir]:delete_move(dir,other,mul)\n    self.balance=self.balance+sb2*mul\n    self,sb2=self:rebalance()\n    return self,(sb2 or self.balance==0) and -1 or 0,v\n  else\n    return self[other],-1,self.value\n  end\nend\n\nfunction AVL:delete(v,isSubtree)\n  local grow=0\n  if v==self.value then\n    local v\n    if self.balance>0 then\n      self.right,grow,v=self.right:delete_move(\"left\",\"right\",-1)\n    elseif self.left then\n      self.left,grow,v=self.left:delete_move(\"right\",\"left\",1)\n      grow=-grow\n    else\n      return not isSubtree and AVL:new(),-1\n    end\n    self.value=v\n    self.balance=self.balance+grow\n  elseif v<self.value and self.left then\n    self.left,grow=self.left:delete(v,true)\n    self.balance=self.balance-grow\n  elseif v>self.value and self.right then\n    self.right,grow=self.right:delete(v,true)\n    self.balance=self.balance+grow\n  else\n    return self,0\n  end\n  self,rotated=self:rebalance()\n  return self, grow~=0 and (rotated or self.balance==0) and -1 or 0\nend\n\n-- output functions\n\nfunction AVL:toList(list)\n  if not self.value then return {} end\n  list=list or {}\n  if self.left then self.left:toList(list) end\n  list[#list+1]=self.value\n  if self.right then self.right:toList(list) end\n  return list\nend\n\nfunction AVL:dump(depth)\n  if not self.value then return end\n  depth=depth or 0\n  if self.right then self.right:dump(depth+1) end\n  print(string.rep(\"    \",depth)..self.value..\" (\"..self.balance..\")\")\n  if self.left then self.left:dump(depth+1) end\nend\n\n-- test\n\nlocal test=AVL:new{1,10,5,15,20,3,5,14,7,13,2,8,3,4,5,10,9,8,7}\n\ntest:dump()\nprint(\"\\ninsert 17:\")\ntest=test:insert(17)\ntest:dump()\nprint(\"\\ndelete 10:\")\ntest=test:delete(10)\ntest:dump()\nprint(\"\\nlist:\")\nprint(unpack(test:toList()))\n\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.","id":1743}
    {"lang_cluster":"Lua","source_code":"function distance(p1, p2)\n    local dx = (p1.x-p2.x)\n    local dy = (p1.y-p2.y)\n    return math.sqrt(dx*dx + dy*dy)\nend\n\nfunction findCircles(p1, p2, radius)\n    local seperation = distance(p1, p2)\n    if seperation == 0.0 then\n        if radius == 0.0 then\n            print(\"No circles can be drawn through (\"..p1.x..\", \"..p1.y..\")\")\n        else\n            print(\"Infinitely many circles can be drawn through (\"..p1.x..\", \"..p1.y..\")\")\n        end\n    elseif seperation == 2*radius then\n        local cx = (p1.x+p2.x)\/2\n        local cy = (p1.y+p2.y)\/2\n        print(\"Given points are opposite ends of a diameter of the circle with center (\"..cx..\", \"..cy..\") and radius \"..radius)\n    elseif seperation > 2*radius then\n        print(\"Given points are further away from each other than a diameter of a circle with radius \"..radius)\n    else\n        local mirrorDistance = math.sqrt(math.pow(radius,2) - math.pow(seperation\/2,2))\n        local dx = p2.x - p1.x\n        local dy = p1.y - p2.y\n        local ax = (p1.x + p2.x) \/ 2\n        local ay = (p1.y + p2.y) \/ 2\n        local mx = mirrorDistance * dx \/ seperation\n        local my = mirrorDistance * dy \/ seperation\n        c1 = {x=ax+my, y=ay+mx}\n        c2 = {x=ax-my, y=ay-mx}\n\n        print(\"Two circles are possible.\")\n        print(\"Circle C1 with center (\"..c1.x..\", \"..c1.y..\"), radius \"..radius)\n        print(\"Circle C2 with center (\"..c2.x..\", \"..c2.y..\"), radius \"..radius)\n    end\n    print()\nend\n\ncases = {\n    {x=0.1234, y=0.9876},   {x=0.8765, y=0.2345},\n    {x=0.0000, y=2.0000},   {x=0.0000, y=0.0000},\n    {x=0.1234, y=0.9876},   {x=0.1234, y=0.9876},\n    {x=0.1234, y=0.9876},   {x=0.8765, y=0.2345},\n    {x=0.1234, y=0.9876},   {x=0.1234, y=0.9876}\n}\nradii = { 2.0, 1.0, 2.0, 0.5, 0.0 }\nfor i=1, #radii do\n    print(\"Case \"..i)\n    findCircles(cases[i*2-1], cases[i*2], radii[i])\nend\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":1744}
    {"lang_cluster":"Lua","source_code":"\nrepeat\n  k = math.random(19)\n  print(k)\n  if k == 10 then break end\n  print(math.random(19)\nuntil false\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":1745}
    {"lang_cluster":"Lua","source_code":"\n\nrequire 'lxp'\ndata = [[<inventory title=\"OmniCorp Store #45x10^3\">\n  <section name=\"health\">\n    <item upc=\"123456789\" stock=\"12\">\n      <name>Invisibility Cream<\/name>\n      <price>14.50<\/price>\n      <description>Makes you invisible<\/description>\n    <\/item>\n    <item upc=\"445322344\" stock=\"18\">\n      <name>Levitation Salve<\/name>\n      <price>23.99<\/price>\n      <description>Levitate yourself for up to 3 hours per application<\/description>\n    <\/item>\n  <\/section>\n  <section name=\"food\">\n    <item upc=\"485672034\" stock=\"653\">\n      <name>Blork and Freen Instameal<\/name>\n      <price>4.95<\/price>\n      <description>A tasty meal in a tablet; just add water<\/description>\n    <\/item>\n    <item upc=\"132957764\" stock=\"44\">\n      <name>Grob winglets<\/name>\n      <price>3.56<\/price>\n      <description>Tender winglets of Grob. Just add water<\/description>\n    <\/item>\n  <\/section>\n<\/inventory>]]\nlocal first = true\nlocal names, prices = {}, {}\np = lxp.new({StartElement = function (parser, name)\n\tlocal a, b, c = parser:pos() --line, offset, pos\n\tif name == 'item' and first then \n\t\tprint(data:match('.-<\/item>', c - b + 1))\n\t\tfirst = false\n\tend\n\tif name == 'name' then names[#names+1] = data:match('>(.-)<', c) end\n\tif name == 'price' then prices[#prices+1] = data:match('>(.-)<', c) end\nend})\n\np:parse(data)\np:close()\n\nprint('Name: ', table.concat(names, ', '))\nprint('Price: ', table.concat(prices, ', '))\n\n","human_summarization":"The code retrieves the first \"item\" element, prints out each \"price\" element, and gathers an array of all the \"name\" elements from a given XML document using XPath queries. The XML document represents an inventory of a store. LuaExpat is required for XML parsing.","id":1746}
    {"lang_cluster":"Lua","source_code":"\nWorks with: lua version 5.1\nfunction emptySet()         return { }  end\nfunction insert(set, item)  set[item] = true  end\nfunction remove(set, item)  set[item] = nil  end\nfunction member(set, item)  return set[item]  end\nfunction size(set)\n\tlocal result = 0\n\tfor _ in pairs(set) do result = result + 1 end\n\treturn result\nend\nfunction fromTable(tbl) -- ignore the keys of tbl\n\tlocal result = { }\n\tfor _, val in pairs(tbl) do\n\t\tresult[val] = true\n\tend\n\treturn result\nend\nfunction toArray(set)\n\tlocal result = { }\n\tfor key in pairs(set) do\n\t\ttable.insert(result, key)\n\tend\n\treturn result\nend\nfunction printSet(set)\n\tprint(table.concat(toArray(set), \", \"))\nend\nfunction union(setA, setB)\n\tlocal result = { }\n\tfor key, _ in pairs(setA) do\n\t\tresult[key] = true\n\tend\n\tfor key, _ in pairs(setB) do\n\t\tresult[key] = true\n\tend\n\treturn result\nend\nfunction intersection(setA, setB)\n\tlocal result = { }\n\tfor key, _ in pairs(setA) do\n\t\tif setB[key] then\n\t\t\tresult[key] = true\n\t\tend\n\tend\n\treturn result\nend\nfunction difference(setA, setB)\n\tlocal result = { }\n\tfor key, _ in pairs(setA) do\n\t\tif not setB[key] then\n\t\t\tresult[key] = true\n\t\tend\n\tend\n\treturn result\nend\nfunction subset(setA, setB)\n\tfor key, _ in pairs(setA) do\n\t\tif not setB[key] then\n\t\t\treturn false\n\t\tend\n\tend\n\treturn true\nend\nfunction properSubset(setA, setB)\n\treturn subset(setA, setB) and (size(setA) ~= size(setB))\nend\nfunction equals(setA, setB)\n\treturn subset(setA, setB) and (size(setA) == size(setB))\nend\n\nWorks with: lua version 5.3\n\nlocal function new(_, ...)\n  local r = {}\n  local s = setmetatable({}, {\n    -- API operations\n    __index = {\n\n      -- single value insertion\n      insert = function(s, v)\n        if not r[v] then\n          table.insert(s, v)\n          r[v] = #s\n        end\n        return s\n      end,\n\n      -- single value removal\n      remove = function(s, v)\n        local i = r[v]\n        if i then\n          r[v] = nil\n          local t = table.remove(s)\n          if t ~= v then\n            r[t] = i\n            s[i] = t\n          end\n        end\n        return s\n      end,\n\n      -- multi-value insertion\n      batch_insert = function(s, ...)\n        for _,v in pairs {...} do\n          s:insert(v)\n        end\n        return s\n      end,\n\n      -- multi-value removal\n      batch_remove = function(s, ...)\n        for _,v in pairs {...} do\n          s:remove(v)\n        end\n        return s\n      end,\n\n      -- membership test\n      has = function(s, e)\n        return r[e] ~= nil\n      end\n    },\n\n    -- set manipulation operators\n\n    -- union\n    __add = function(s1, s2)\n      r = set()\n      r:batch_insert(table.unpack(s1))\n      r:batch_insert(table.unpack(s2))\n      return r\n    end,\n\n    -- subtraction\n    __sub = function(s1, s2)\n      r = set()\n      r:batch_insert(table.unpack(s1))\n      r:batch_remove(table.unpack(s2))\n      return r\n    end,\n\n    -- intersection\n    __mul = function(s1, s2)\n      r = set()\n      for _,v in ipairs(s1) do\n        if s2:has(v) then\n          r:insert(v)\n        end\n      end\n      return r\n    end,\n\n    -- equality\n    __eq = function(s1, s2)\n      if #s1 ~= #s2 then return false end\n      for _,v in ipairs(s1) do\n        if not s2:has(v) then return false end\n      end\n      return true\n    end,\n\n    -- proper subset\n    __lt = function(s1, s2)\n      if s1 == s2 then return false end\n      for _,v in ipairs(s1) do\n        if not s2:has(v) then return false end\n      end\n      return true\n    end,\n\n    -- subset\n    __lte = function(s1, s2)\n      return (s1 == s2) or (s1 < s2)\n    end,\n\n    -- metatable type tag\n    __type__ = 'set'\n  })\n  s:batch_insert(...)\n  return s\nend\n\nreturn setmetatable({}, { __call = new })\n\n","human_summarization":"implement a mutable set type with various operations. These operations include set creation, testing if an element is in a set, union, intersection, and difference of two sets, checking if a set is a subset or equal to another set. Additional operations may include modifications to the mutable set and other set operations. The set can be implemented using an associative array, a binary search tree, a hash table, or an ordered array of binary bits. The code is designed to be used as a module.","id":1747}
    {"lang_cluster":"Lua","source_code":"\n\nrequire(\"date\")\n\nfor year=2008,2121 do\n   if date(year, 12, 25):getweekday() == 1 then\n      print(year)\n   end\nend\n\n\n","human_summarization":"The code calculates the years between 2008 and 2121 when Christmas (25th December) falls on a Sunday using LuaDate library. It also compares the results with other programming languages to identify any discrepancies in date handling, potentially caused by issues like overflow in date\/time representation.","id":1748}
    {"lang_cluster":"Lua","source_code":"\nitems = {1,2,3,4,1,2,3,4,\"bird\",\"cat\",\"dog\",\"dog\",\"bird\"}\nflags = {}\nio.write('Unique items are:')\nfor i=1,#items do\n   if not flags[items[i]] then\n      io.write(' ' .. items[i])\n      flags[items[i]] = true\n   end\nend\nio.write('\\n')\n\n\n","human_summarization":"removes duplicate elements from an array using three possible methods: 1) Using a hash table, 2) Sorting the elements and removing consecutive duplicates, 3) Iterating through the list and discarding any repeated elements. It also handles exceptions for Lua 5.3 where Not-a-Number (NaN) and nil are not accepted as table keys.","id":1749}
    {"lang_cluster":"Lua","source_code":"\nNOTE: If you want to use quicksort in a Lua script, you don't need to implement it yourself. Just do: table.sort(tableName)\n--in-place quicksort\nfunction quicksort(t, start, endi)\n  start, endi = start or 1, endi or #t\n  --partition w.r.t. first element\n  if(endi - start < 1) then return t end\n  local pivot = start\n  for i = start + 1, endi do\n    if t[i] <= t[pivot] then\n      if i == pivot + 1 then\n        t[pivot],t[pivot+1] = t[pivot+1],t[pivot]\n      else\n        t[pivot],t[pivot+1],t[i] = t[i],t[pivot],t[pivot+1]\n      end\n      pivot = pivot + 1\n    end\n  end\n  t = quicksort(t, start, pivot - 1)\n  return quicksort(t, pivot + 1, endi)\nend\n\n--example\nprint(unpack(quicksort{5, 2, 7, 3, 4, 7, 1}))\n\nnon function quicksort(t)\n  if #t<2 then return t end\n  local pivot=t[1]\n  local a,b,c={},{},{}\n  for _,v in ipairs(t) do\n    if     v<pivot then a[#a+1]=v\n    elseif v>pivot then c[#c+1]=v\n    else                b[#b+1]=v\n    end\n  end\n  a=quicksort(a)\n  c=quicksort(c)\n  for _,v in ipairs(b) do a[#a+1]=v end\n  for _,v in ipairs(c) do a[#a+1]=v end\n  return a\nend\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":1750}
    {"lang_cluster":"Lua","source_code":"\nprint( os.date( \"%Y-%m-%d\" ) )\nprint( os.date( \"%A, %B %d, %Y\" ) )\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":1751}
    {"lang_cluster":"Lua","source_code":"\n--returns the powerset of s, out of order.\nfunction powerset(s, start)\n  start = start or 1\n  if(start > #s) then return {{}} end\n  local ret = powerset(s, start + 1)\n  for i = 1, #ret do\n    ret[#ret + 1] = {s[start], unpack(ret[i])}\n  end\n  return ret\nend\n\n--non-recurse implementation\nfunction powerset(s)\n   local t = {{}}\n   for i = 1, #s do\n      for j = 1, #t do\n         t[#t+1] = {s[i],unpack(t[j])}\n      end\n   end\n   return t\nend\n\n--alternative, copied from the Python implementation\nfunction powerset2(s)\n  local ret = {{}}\n  for i = 1, #s do\n    local k = #ret\n    for j = 1, k do\n      ret[k + j] = {s[i], unpack(ret[j])}\n    end\n  end\n  return ret\nend\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":1752}
    {"lang_cluster":"Lua","source_code":"\nromans = {\n{1000, \"M\"},\n{900, \"CM\"}, {500, \"D\"}, {400, \"CD\"}, {100, \"C\"},\n{90, \"XC\"}, {50, \"L\"}, {40, \"XL\"}, {10, \"X\"},\n{9, \"IX\"}, {5, \"V\"}, {4, \"IV\"}, {1, \"I\"} }\n\nk = io.read() + 0\nfor _, v in ipairs(romans) do --note that this is -not- ipairs.\n  val, let = unpack(v)\n  while k >= val do\n    k = k - val\n\tio.write(let)\n  end\nend\nprint()\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":1753}
    {"lang_cluster":"Lua","source_code":"\n\nl = {}\nl[1] = 1      -- Index starts with 1, not 0.\nl[0] = 'zero' -- But you can use 0 if you want\nl[10] = 2     -- Indexes need not be continuous\nl.a = 3       -- Treated as l['a']. Any object can be used as index\nl[l] = l      -- Again, any object can be used as an index. Even other tables\nfor i,v in next,l do print (i,v) end\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. It includes the creation of an array, assigning a value to it, and retrieving an element from it. It also showcases the use of both fixed-length and dynamic arrays, and how to push a value into them. In the context of Lua, it explains how to emulate different types of containers using its table structure.","id":1754}
    {"lang_cluster":"Lua","source_code":"\ninFile  = io.open(\"input.txt\", \"r\")\ndata = inFile:read(\"*all\") -- may be abbreviated to \"*a\";\n                           -- other options are \"*line\", \n                           -- or the number of characters to read.\ninFile:close()\n\noutFile = io.open(\"output.txt\", \"w\")\noutfile:write(data)\noutfile:close()\n\n-- Oneliner version:\nio.open(\"output.txt\", \"w\"):write(io.open(\"input.txt\", \"r\"):read(\"*a\"))\n\n","human_summarization":"demonstrate reading the contents of \"input.txt\" file into a variable and then writing this variable's contents into a new file called \"output.txt\".","id":1755}
    {"lang_cluster":"Lua","source_code":"\nstr = \"alphaBETA\"\n\nprint( string.upper(str) ) -- ALPHABETA\nprint( string.lower(str) ) -- alphabeta\n\nprint ( str:upper() ) -- ALPHABETA\nprint ( str:lower() ) -- alphabeta\n\n\nprint ( string.upper(\"a\u00e7\u00e3o\") ) -- returns A\u00e7\u00e3O instead of A\u00c7\u00c3O\nprint ( string.upper(\"\u0125\u00e5\u00e7\u00fd\u0434\u0436\u043a\") ) -- returns \u0125\u00e5\u00e7\u00fd\u0434\u0436\u043a instead of \u0124\u00c5\u00c7\u00dd\u0414\u0416\u041a\n\n","human_summarization":"The code takes the input string \"alphaBETA\", and demonstrates conversion to both upper-case and lower-case using the default string literal encoding or ASCII. It also showcases additional case conversion functions such as swapping case, capitalizing the first letter, etc. available in the language's library. The code works properly for ASCII and extended ASCII ranges but not for Unicode.","id":1756}
    {"lang_cluster":"Lua","source_code":"\n\ncollection = {0, '1'}\nprint(collection[1]) -- prints 0\n\ncollection = {[\"foo\"] = 0, [\"bar\"] = '1'} -- a collection of key\/value pairs\nprint(collection[\"foo\"]) -- prints 0\nprint(collection.foo) -- syntactic sugar, also prints 0\n\ncollection = {0, '1', [\"foo\"] = 0, [\"bar\"] = '1'}\n\n\n","human_summarization":"create a collection in Lua using the table data structure, add a few values to it, and represent a Set data structure with a table of keys set to true. The table features both traditional arrays and hash maps, with numeric indices starting at 1.","id":1757}
    {"lang_cluster":"Lua","source_code":"\nitems = {   [\"panaea\"] = { [\"value\"] = 3000, [\"weight\"] = 0.3, [\"volume\"] = 0.025 },\n            [\"ichor\"]  = { [\"value\"] = 1800, [\"weight\"] = 0.2, [\"volume\"] = 0.015 },\n            [\"gold\"]   = { [\"value\"] = 2500, [\"weight\"] = 2.0, [\"volume\"] = 0.002 }\n        }\n\nmax_weight = 25\nmax_volume = 0.25\n\nmax_num_items = {}\nfor i in pairs( items ) do\n   max_num_items[i] = math.floor( math.min( max_weight \/ items[i].weight, max_volume \/ items[i].volume ) )\nend\n\nbest = { [\"value\"] = 0.0, [\"weight\"] = 0.0, [\"volume\"] = 0.0 }\nbest_amounts = {}\n\nfor i = 1, max_num_items[\"panaea\"] do\n    for j = 1, max_num_items[\"ichor\"] do\n        for k = 1, max_num_items[\"gold\"] do\n            current = { [\"value\"]  = i*items[\"panaea\"][\"value\"] + j*items[\"ichor\"][\"value\"] + k*items[\"gold\"][\"value\"],\n                        [\"weight\"] = i*items[\"panaea\"][\"weight\"] + j*items[\"ichor\"][\"weight\"] + k*items[\"gold\"][\"weight\"],\n                        [\"volume\"] = i*items[\"panaea\"][\"volume\"] + j*items[\"ichor\"][\"volume\"] + k*items[\"gold\"][\"volume\"]\n                      }\n                      \n            if current.value > best.value and current.weight <= max_weight and current.volume <= max_volume then\n                best = { [\"value\"] = current.value, [\"weight\"] = current.weight, [\"volume\"] = current.volume }\n                best_amounts = { [\"panaea\"] = i, [\"ichor\"] = j, [\"gold\"] = k }\n            end\n        end\n    end\nend\n\nprint( \"Maximum value:\", best.value )\nfor k, v in pairs( best_amounts ) do\n    print( k, v )\nend\n\n","human_summarization":"determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.","id":1758}
    {"lang_cluster":"Lua","source_code":"\n\nfor i = 1, 10 do\n  io.write(i)\n  if i == 10 then break end\n  io.write\", \"\nend\n\n","human_summarization":"generates a comma-separated list of numbers from 1 to 10, using separate output statements for the number and the comma within a loop. The loop is designed to execute only part of its body in the last iteration.","id":1759}
    {"lang_cluster":"Lua","source_code":"\ns1 = \"string\"\ns2 = \"str\"\ns3 = \"ing\"\ns4 = \"xyz\"\n\nprint( \"s1 starts with s2: \", string.find( s1, s2 ) == 1 )\nprint( \"s1 starts with s3: \", string.find( s1, s3 ) == 1, \"\\n\" )\n\nprint( \"s1 contains s3: \", string.find( s1, s3 ) ~= nil )\nprint( \"s1 contains s3: \", string.find( s1, s4 ) ~= nil, \"\\n\" )   \n   \nprint( \"s1 ends with s2: \", select( 2, string.find( s1, s2 ) ) == string.len( s1 ) )\nprint( \"s1 ends with s3: \", select( 2, string.find( s1, s3 ) ) == string.len( s1 ) )\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":1760}
    {"lang_cluster":"Lua","source_code":"function valid(unique,needle,haystack)\n    if unique then\n        for _,value in pairs(haystack) do\n            if needle == value then\n                return false\n            end\n        end\n    end\n    return true\nend\n\nfunction fourSquare(low,high,unique,prnt)\n    count = 0\n    if prnt then\n        print(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\")\n    end\n    for a=low,high do\n        for b=low,high do\n            if valid(unique, a, {b}) then\n                fp = a + b\n                for c=low,high do\n                    if valid(unique, c, {a, b}) then\n                        for d=low,high do\n                            if valid(unique, d, {a, b, c}) and fp == b + c + d then\n                                for e=low,high do\n                                    if valid(unique, e, {a, b, c, d}) then\n                                        for f=low,high do\n                                            if valid(unique, f, {a, b, c, d, e}) and fp == d + e + f then\n                                                for g=low,high do\n                                                    if valid(unique, g, {a, b, c, d, e, f}) and fp == f + g then\n                                                        count = count + 1\n                                                        if prnt then\n                                                            print(a, b, c, d, e, f, g)\n                                                        end\n                                                    end\n                                                end\n                                            end\n                                        end\n                                    end\n                                end\n                            end\n                        end\n                    end\n                end\n            end\n        end\n    end\n    if unique then\n        print(string.format(\"There are %d unique solutions in [%d, %d]\", count, low, high))\n    else\n        print(string.format(\"There are %d non-unique solutions in [%d, %d]\", count, low, high))\n    end\nend\n\nfourSquare(1,7,true,true)\nfourSquare(3,9,true,true)\nfourSquare(0,9,false,false)\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":1761}
    {"lang_cluster":"Lua","source_code":"\n\n","human_summarization":"create a visual representation of a time-keeping device that updates every second, in sync with the system clock, using efficient system or language events instead of constant polling. The code is kept simple and clear, avoiding unnecessary complexity.","id":1762}
    {"lang_cluster":"Lua","source_code":"\n\nFUNCTION PRINT_CAL(YEAR)\n  LOCAL MONTHS={\"JANUARY\",\"FEBRUARY\",\"MARCH\",\"APRIL\",\"MAY\",\"JUNE\",\n                \"JULY\",\"AUGUST\",\"SEPTEMBER\",\"OCTOBER\",\"NOVEMBER\",\"DECEMBER\"}\n  LOCAL DAYSTITLE=\"MO TU WE TH FR SA SU\"\n  LOCAL DAYSPERMONTH={31,28,31,30,31,30,31,31,30,31,30,31}\n  LOCAL STARTDAY=((YEAR-1)*365+MATH.FLOOR((YEAR-1)\/4)-MATH.FLOOR((YEAR-1)\/100)+MATH.FLOOR((YEAR-1)\/400))%7\n  IF YEAR%4==0 AND YEAR%100~=0 OR YEAR%400==0 THEN\n    DAYSPERMONTH[2]=29\n  END\n  LOCAL SEP=5\n  LOCAL MONTHWIDTH=DAYSTITLE:LEN()\n  LOCAL CALWIDTH=3*MONTHWIDTH+2*SEP\n \n  FUNCTION CENTER(STR, WIDTH)\n    LOCAL FILL1=MATH.FLOOR((WIDTH-STR:LEN())\/2)\n    LOCAL FILL2=WIDTH-STR:LEN()-FILL1\n    RETURN STRING.REP(\" \",FILL1)..STR..STRING.REP(\" \",FILL2)\n  END\n \n  FUNCTION MAKEMONTH(NAME, SKIP,DAYS)\n    LOCAL CAL={\n      CENTER(NAME,MONTHWIDTH),\n      DAYSTITLE\n    }\n    LOCAL CURDAY=1-SKIP\n    WHILE #CAL<9 DO\n      LINE={}\n      FOR I=1,7 DO\n        IF CURDAY<1 OR CURDAY>DAYS THEN\n          LINE[I]=\"  \"\n        ELSE\n          LINE[I]=STRING.FORMAT(\"%2D\",CURDAY)\n        END\n        CURDAY=CURDAY+1\n      END\n      CAL[#CAL+1]=TABLE.CONCAT(LINE,\" \")\n    END\n    RETURN CAL\n  END\n \n  LOCAL CALENDAR={}\n  FOR I,MONTH IN IPAIRS(MONTHS) DO\n    LOCAL DPM=DAYSPERMONTH[I]\n    CALENDAR[I]=MAKEMONTH(MONTH, STARTDAY, DPM)\n    STARTDAY=(STARTDAY+DPM)%7\n  END\n \n \n  PRINT(CENTER(\"[SNOOPY]\",CALWIDTH):UPPER(),\"\\N\")\n  PRINT(CENTER(\"--- \"..YEAR..\" ---\",CALWIDTH):UPPER(),\"\\N\")\n \n  FOR Q=0,3 DO\n    FOR L=1,9 DO\n      LINE={}\n      FOR M=1,3 DO\n        LINE[M]=CALENDAR[Q*3+M][L]\n      END\n      PRINT(TABLE.CONCAT(LINE,STRING.REP(\" \",SEP)):UPPER())\n    END\n  END\nEND\n \nPRINT_CAL(1969)\n\n\ndo io.input( arg[ 1 ] ); local s = io.read( \"*a\" ):lower(); io.close(); assert( load( s ) )() end\n\n\n\n","human_summarization":"The code provides an algorithm for a calendar task, formatted to fit a page that is 132 characters wide. The entire code is written in uppercase, inspired by the 1969 era line printers and the article \"Real programmers think in UPPERCASE\". The code does not include Snoopy generation but outputs a placeholder instead. The code is tested with Lua 5.3.2 and uses a pre-processor to execute the upper-cased source.","id":1763}
    {"lang_cluster":"Lua","source_code":"\nLibrary: IUPLua\nlocal iup = require \"iuplua\"\n\niup.dialog{\n  title = \"Window\";\n  iup.vbox{\n    margin = \"10x10\";\n    iup.label{title = \"A window\"}\n  }\n}:show()\n\niup.MainLoop()\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":1764}
    {"lang_cluster":"Lua","source_code":"\n\n-- Return entire contents of named file\nfunction readFile (filename)\n  local file = assert(io.open(filename, \"r\"))\n  local contents = file:read(\"*all\")\n  file:close()\n  return contents\nend\n\n-- Return a closure to keep track of letter counts\nfunction tally ()\n  local t = {}\n  \n  -- Add x to tally if supplied, return tally list otherwise\n  local function count (x)\n    if x then\n      if t[x] then\n        t[x] = t[x] + 1\n      else\n        t[x] = 1\n      end\n    else\n      return t\n    end\n  end\n  \n  return count\nend\n\n-- Main procedure\nlocal letterCount = tally()\nfor letter in readFile(arg[1] or arg[0]):gmatch(\"%a\") do\n  letterCount(letter)\nend\nfor k, v in pairs(letterCount()) do\n  print(k, v)\nend\n\n\ni       24\nf       16\nR       2\nv       2\nc       19\nk       4\nM       1\ns       14\nd       17\nl       40\ne       61\nt       54\nm       4\nr       34\nu       18\nC       3\no       32\nA       1\ng       3\nx       7\nF       2\ny       4\nw       1\nn       42\nh       4\na       25\np       7\n","human_summarization":"open a text file and count the frequency of each letter. It only counts letters A-Z and treats upper and lower case letters as distinct. The functionality can be modified to count all characters or to ignore case sensitivity.","id":1765}
    {"lang_cluster":"Lua","source_code":"\n\ng, angle = love.graphics, 26 * math.pi \/ 180\nwid, hei = g.getWidth(), g.getHeight()\nfunction rotate( x, y, a )\n  local s, c = math.sin( a ), math.cos( a )\n  local a, b = x * c - y * s, x * s + y * c\n  return a, b\nend\nfunction branches( a, b, len, ang, dir )\n  len = len * .76\n  if len < 5 then return end\n  g.setColor( len * 16, 255 - 2 * len , 0 )\n  if dir > 0 then ang = ang - angle\n  else ang = ang + angle \n  end\n  local vx, vy = rotate( 0, len, ang )\n  vx = a + vx; vy = b - vy\n  g.line( a, b, vx, vy )\n  branches( vx, vy, len, ang, 1 )\n  branches( vx, vy, len, ang, 0 )\nend\nfunction createTree()\n  local lineLen = 127\n  local a, b = wid \/ 2, hei - lineLen\n  g.setColor( 160, 40 , 0 )\n  g.line( wid \/ 2, hei, a, b )\n  branches( a, b, lineLen, 0, 1 ) \n  branches( a, b, lineLen, 0, 0 )\nend\nfunction love.load()\n  canvas = g.newCanvas( wid, hei )\n  g.setCanvas( canvas )\n  createTree()\n  g.setCanvas()\nend\nfunction love.draw()\n  g.draw( canvas )\nend\n\n\nfunction Bitmap:tree(x, y, angle, depth, forkfn, lengfn)\n  if depth <= 0 then return end\n  local fork, leng = forkfn(), lengfn()\n  local x2 = x + depth * leng * math.cos(angle)\n  local y2 = y - depth * leng * math.sin(angle)\n  self:line(math.floor(x), math.floor(y), math.floor(x2), math.floor(y2))\n  self:tree(x2, y2, angle+fork, depth-1, forkfn, lengfn)\n  self:tree(x2, y2, angle-fork, depth-1, forkfn, lengfn)\nend\n\nbitmap = Bitmap(128*3,128)\nbitmap:tree( 64, 120, math.pi\/2, 8, function() return 0.3 end, function() return 3 end)\nbitmap:tree(192, 120, math.pi\/2, 8, function() return 0.6 end, function() return 2.5 end)\nbitmap:tree(320, 120, math.pi\/2, 8, function() return 0.2+math.random()*0.3 end, function() return 2.0+math.random()*2.0 end)\nbitmap:render({[0x000000]='.', [0xFFFFFFFF]='\u2588'})\n\n\n","human_summarization":"Generates and draws a fractal tree using L\u00d6VE 2D Engine and Bitmap class with text renderer, by drawing a trunk, splitting it at the end by a certain angle into two branches, and repeating this process until a desired level of branching is achieved. The final output is displayed at 25% scale.","id":1766}
    {"lang_cluster":"Lua","source_code":"\nfunction Factors( n ) \n    local f = {}\n    \n    for i = 1, n\/2 do\n        if n\u00a0% i == 0 then \n            f[#f+1] = i\n        end\n    end\n    f[#f+1] = n\n    \n    return f\nend\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":1767}
    {"lang_cluster":"Lua","source_code":"\nWorks with: Lua version 5.1\nlocal tWord = {}        -- word table\nlocal tColLen = {}      -- maximum word length in a column\nlocal rowCount = 0      -- row counter\n--store maximum column lengths at 'tColLen'; save words into 'tWord' table\nlocal function readInput(pStr)\n    for line in pStr:gmatch(\"([^\\n]+)[\\n]-\") do  -- read until '\\n' character\n        rowCount = rowCount + 1\n        tWord[rowCount] = {}                     -- create new row\n        local colCount = 0\n        for word in line:gmatch(\"[^$]+\") do      -- read non '$' character\n            colCount = colCount + 1\n            tColLen[colCount] = math.max((tColLen[colCount] or 0), #word)   -- store column length\n            tWord[rowCount][colCount] = word                                -- store words\n        end--for word\n    end--for line\nend--readInput\n--repeat space to align the words in the same column\nlocal align = {\n    [\"left\"] = function (pWord, pColLen)\n        local n = (pColLen or 0) - #pWord + 1\n        return pWord .. (\" \"):rep(n)\n    end;--[\"left\"]\n    [\"right\"] = function (pWord, pColLen)\n        local n = (pColLen or 0) - #pWord + 1\n        return (\" \"):rep(n) .. pWord\n    end;--[\"right\"]\n    [\"center\"] = function (pWord, pColLen)\n        local n = (pColLen or 0) - #pWord + 1\n        local n1 = math.floor(n\/2)\n        return (\" \"):rep(n1) .. pWord .. (\" \"):rep(n-n1)\n    end;--[\"center\"]\n}\n--word table padder\nlocal function padWordTable(pAlignment)\n    local alignFunc = align[pAlignment]                         -- selecting the spacer function\n    for rowCount, tRow in ipairs(tWord) do\n        for colCount, word in ipairs(tRow) do\n            tRow[colCount] = alignFunc(word, tColLen[colCount]) -- save the padded words into the word table\n        end--for colCount, word\n    end--for rowCount, tRow\nend--padWordTable\n--main interface\n--------------------------------------------------[]\nfunction alignColumn(pStr, pAlignment, pFileName)\n--------------------------------------------------[]\n    readInput(pStr)                           -- store column lengths and words\n    padWordTable(pAlignment or \"left\")        -- pad the stored words\n    local output = \"\"\n    for rowCount, tRow in ipairs(tWord) do\n        local line = table.concat(tRow)       -- concatenate words in one row\n        print(line)                           -- print the line\n        output = output .. line .. \"\\n\"       -- concatenate the line for output, add line break\n    end--for rowCount, tRow\n    if (type(pFileName) == \"string\") then\n        local file = io.open(pFileName, \"w+\")\n        file:write(output)                    -- write output to file\n        file:close()\n    end--if type(pFileName)\n    return output\nend--alignColumn\n\n\ninput =\n[[Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.]]\n\n\noutputLeft = alignColumn(input)\noutputRight = alignColumn(input, \"right\")\nalignColumn(input, \"center\", \"output.txt\")\n\n","human_summarization":"The code reads a text file where fields within a line are separated by a dollar character. It aligns each column by ensuring at least one space between words in each column. The words in a column can be left justified, right justified, or center justified. The code also handles trailing dollar characters, shared alignment across columns, and insignificant consecutive spaces at the end of lines. The minimum space between columns is computed from the text and not hard-coded. The code does not add separating characters between or around columns.","id":1768}
    {"lang_cluster":"Lua","source_code":"\n\n-- needed for actual task\ncube.scale = function(self, sx, sy, sz)\n  for i,v in ipairs(self.verts) do\n    v[1], v[2], v[3] = v[1]*sx, v[2]*sy, v[3]*sz\n  end\nend\n-- only needed for output\n-- (to size it for screen, given a limited camera)\ncube.translate = function(self, tx, ty, tz)\n  for i,v in ipairs(self.verts) do\n    v[1], v[2], v[3] = v[1]+tx, v[2]+ty, v[3]+tz\n  end\nend\n\n\n--\nbitmap:init(40,40)\ncube:scale(2,3,4)\ncube:rotate(-pi\/4, -pi\/6)\ncube:translate(0,0,10)\nbitmap:clear(\"\u00b7\u00b7\")\nrenderer:render(cube, camera, bitmap)\nscreen:clear()\nbitmap:render()\n\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, showing three visible faces. The cuboid can be either static or rotating, extending from the Draw_a_rotating_cube task.","id":1769}
    {"lang_cluster":"Lua","source_code":"\nfunction rot13(s)\n\tlocal a = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\tlocal b = \"NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm\"\n\treturn (s:gsub(\"%a\", function(c) return b:sub(a:find(c)) end))\nend\n\nfunction rot13(s)\n  return (s:gsub(\"%a\", function(c) c=c:byte() return string.char(c+(c%32<14 and 13 or -13)) end))\nend\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":1770}
    {"lang_cluster":"Lua","source_code":"\nfunction sorting( a, b ) \n    return a[1] < b[1] \nend\n \ntab = { {\"C++\", 1979}, {\"Ada\", 1983}, {\"Ruby\", 1995}, {\"Eiffel\", 1985} }\n\ntable.sort( tab, sorting )\nfor _, v in ipairs( tab ) do \n    print( unpack(v) ) \nend\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":1771}
    {"lang_cluster":"Lua","source_code":"\nfor i=1,5 do\n  for j=1,i do\n    io.write(\"*\")\n  end\n  io.write(\"\\n\")\nend\n\n\nfor i = 1, 5 do\n  print(string.rep(\"*\", i))\nend\n\nfor i = 1, 5 do\n  print((\"*\"):rep(i))\nend\n","human_summarization":"Code summarization: The code demonstrates the use of nested \"for\" loops, where the number of iterations of the inner loop is controlled by the outer loop. It prints a pattern of asterisks, with each line containing one more asterisk than the previous line.","id":1772}
    {"lang_cluster":"Lua","source_code":"\n\nhash = {}\nhash[ \"key-1\" ] = \"val1\"\nhash[ \"key-2\" ] = 1\nhash[ \"key-3\" ] = {}\n\n\n","human_summarization":"create an associative array (dictionary, map, or hash) in Lua where unknown keys return nil.","id":1773}
    {"lang_cluster":"Lua","source_code":"\nWorks with: Lua version 5.3\n\nlocal RNG = {\n  new = function(class, a, c, m, rand) \n    local self = setmetatable({}, class)\n    local state = 0\n    self.rnd = function() \n      state = (a * state + c) % m\n      return rand and rand(state) or state\n    end\n    self.seed = function(new_seed)\n      state = new_seed % m\n    end\n    return self\n  end\n}\n\nbsd = RNG:new(1103515245, 12345, 1<<31)\nms = RNG:new(214013, 2531011, 1<<31, function(s) return s>>16 end)\n\nprint\"BSD:\"\nfor _ = 1,10 do\n  print((\"\\t%10d\"):format(bsd.rnd()))\nend\nprint\"Microsoft:\"\nfor _ = 1,10 do\n  print((\"\\t%10d\"):format(ms.rnd()))\nend\n\n\n","human_summarization":"The code replicates two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). It uses the Linear Congruential Generator (LCG) formula to generate a sequence of random numbers. The code is designed to produce the same sequence of integers as the original generators when starting from the same seed. It requires Lua 5.3 or later due to the need for large integers and integral arithmetic operations.","id":1774}
    {"lang_cluster":"Lua","source_code":"\nfunction halve(a)\n    return a\/2\nend\n\nfunction double(a)\n    return a*2\nend\n\nfunction isEven(a)\n    return a%2 == 0\nend\n\nfunction ethiopian(x, y)\n    local result = 0\n\n    while (x >= 1) do\n        if not isEven(x) then\n            result = result + y\n        end\n\n        x = math.floor(halve(x))\n        y = double(y)\n    end\n\n    return result;\nend\n\nprint(ethiopian(17, 34))\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":1775}
    {"lang_cluster":"Lua","source_code":"\n\nlocal SIZE = #arg[1]\nlocal GOAL = tonumber(arg[2]) or 24\n\nlocal input = {}\nfor v in arg[1]:gmatch(\"%d\") do\n\ttable.insert(input, v)\nend\nassert(#input == SIZE, 'Invalid input')\n\nlocal operations = {'+', '-', '*', '\/'}\n\nlocal function BinaryTrees(vert)\n\tif vert == 0 then\n\t\treturn {false}\n\telse\n\t\tlocal buf = {}\n\t\tfor leften = 0, vert - 1 do\n\t\t\tlocal righten = vert - leften - 1\n\t\t\tfor _, left in pairs(BinaryTrees(leften)) do\n\t\t\t\tfor _, right in pairs(BinaryTrees(righten)) do\n\t\t\t\t\ttable.insert(buf, {left, right})\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\treturn buf\n\tend\nend\nlocal trees = BinaryTrees(SIZE-1)\nlocal c, opc, oper, str\nlocal max = math.pow(#operations, SIZE-1)\nlocal function op(a,b)\n\topc = opc + 1\n\tlocal i = math.floor(oper\/math.pow(#operations, opc-1))%#operations+1\n\treturn '('.. a .. operations[i] .. b ..')'\nend\n\nlocal function EvalTree(tree)\n\tif tree == false then\n\t\tc = c + 1\n\t\treturn input[c-1]\n\telse\n\t\treturn op(EvalTree(tree[1]), EvalTree(tree[2]))\n\tend\nend\n\nlocal function printResult()\n\tfor _, v in ipairs(trees) do\n\t\tfor i = 0, max do\n\t\t\tc, opc, oper = 1, 0, i\n\t\t\tstr = EvalTree(v)\n\t\t\tloadstring('res='..str)()\n\t\t\tif(res == GOAL) then print(str, '=', res) end\n\t\tend\n\tend\nend\n\nlocal uniq = {}\nlocal function permgen (a, n)\n\tif n == 0 then\n\t\tlocal str = table.concat(a)\n\t\tif not uniq[str] then \n\t\t\tprintResult()\n\t\t\tuniq[str] = true\n\t\tend\n\telse\n\t\tfor i = 1, n do\n\t\t\ta[n], a[i] = a[i], a[n]\n\t\t\tpermgen(a, n - 1)\n\t\t\ta[n], a[i] = a[i], a[n]\n\t\tend\n\tend\nend\n\npermgen(input, SIZE)\n\n\n","human_summarization":"The code takes four digits as input, either user-provided or randomly generated, and calculates arithmetic expressions based on the rules of the 24 game. It also displays examples of solutions it generates. Additionally, it includes a generic solver that accepts a card of any size as the first argument and the target number as the second.","id":1776}
    {"lang_cluster":"Lua","source_code":"\nfunction fact(n)\n  return n > 0 and n * fact(n-1) or 1\nend\nTail function fact(n, acc)\n  acc = acc or 1\n  if n == 0 then\n    return acc\n  end\n  return fact(n-1, n*acc)\nend\n\nfact = setmetatable({[0] = 1}, {\n  __call = function(t,n)\n    if n < 0 then return 0 end\n    if not t[n] then t[n] = n * t(n-1) end\n    return t[n]\n  end\n})\n","human_summarization":"The code calculates and returns the factorial of a given number, either through an iterative or recursive method. It optionally handles negative input errors. The factorial function multiplies a sequence of descending positive integers from the input number to 1. The code also features memoization, storing previously calculated factorials for efficient retrieval.","id":1777}
    {"lang_cluster":"Lua","source_code":"\nfunction ShuffleArray(array)\n   for i=1,#array-1 do\n      local t = math.random(i, #array)\n      array[i], array[t] = array[t], array[i]\n   end\nend\n\nfunction GenerateNumber()\n   local digits = {1,2,3,4,5,6,7,8,9}\n\n   ShuffleArray(digits)\n\n   return digits[1] * 1000 +\n          digits[2] *  100 +\n          digits[3] *   10 +\n          digits[4]\nend\n\nfunction IsMalformed(input)\n   local malformed = false\n\n   if #input == 4 then\n      local already_used = {}\n      for i=1,4 do\n         local digit = input:byte(i) - string.byte('0')\n         if digit < 1 or digit > 9 or already_used[digit] then\n            malformed = true\n            break\n         end\n         already_used[digit] = true\n      end\n   else\n      malformed = true\n   end\n\n   return malformed\nend\n\nmath.randomseed(os.time())\nmath.randomseed(math.random(2^31-1)) -- since os.time() only returns seconds\n\nprint(\"\\nWelcome to Bulls and Cows!\")\nprint(\"\")\nprint(\"The object of this game is to guess the random 4-digit number that the\")\nprint(\"computer has chosen. The number is generated using only the digits 1-9,\")\nprint(\"with no repeated digits. Each time you enter a guess, you will score one\")\nprint(\"\\\"bull\\\" for each digit in your guess that matches the corresponding digit\")\nprint(\"in the computer-generated number, and you will score one \\\"cow\\\" for each\")\nprint(\"digit in your guess that appears in the computer-generated number, but is\")\nprint(\"in the wrong position. Use this information to refine your guesses. When\")\nprint(\"you guess the correct number, you win.\");\nprint(\"\")\n\nquit = false\n\nrepeat\n   magic_number = GenerateNumber()\n   magic_string = tostring(magic_number) -- Easier to do scoring with a string\n   repeat\n      io.write(\"\\nEnter your guess (or 'Q' to quit): \")\n      user_input = io.read()\n      if user_input == 'Q' or user_input == 'q' then\n         quit = true\n         break\n      end\n\n      if not IsMalformed(user_input) then\n         if user_input == magic_string then\n            print(\"YOU WIN!!!\")\n         else\n            local bulls, cows = 0, 0\n            for i=1,#user_input do\n               local find_result = magic_string:find(user_input:sub(i,i))\n\n               if find_result and find_result == i then\n                  bulls = bulls + 1\n               elseif find_result then\n                  cows = cows + 1\n               end\n            end\n            print(string.format(\"You scored %d bulls, %d cows\", bulls, cows))\n         end\n      else\n         print(\"Malformed input. You must enter a 4-digit number with\")\n         print(\"no repeated digits, using only the digits 1-9.\")\n      end\n\n   until user_input == magic_string\n\n   if not quit then\n      io.write(\"\\nPress <Enter> to play again or 'Q' to quit: \")\n      user_input = io.read()\n      if user_input == 'Q' or user_input == 'q' then\n         quit = true\n      end\n   end\n\n   if quit then\n      print(\"\\nGoodbye!\")\n   end\nuntil quit\n\n\nfunction createNewNumber ()\n\tmath.randomseed(os.time())\n\tlocal numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}\n\tlocal tNumb = {} -- list of numbers\n\tfor i = 1, 4 do\n\t\ttable.insert(tNumb, math.random(#tNumb+1), table.remove(numbers, math.random(#numbers)))\n\tend\n\treturn tNumb\nend\n\nTNumber = createNewNumber ()\nprint ('(right number: ' .. table.concat (TNumber) .. ')')\n\nfunction isValueInList (value, list)\n\tfor i, v in ipairs (list) do\n\t\tif v == value then return true end\n\tend\n\treturn false\nend\n\nlocal nGuesses = 0\n\nwhile not GameOver do\n\tnGuesses = nGuesses + 1\n\tprint(\"Enter your guess (or 'q' to quit): \")\n\tlocal input\n\twhile not input do\n\t\tinput = io.read()\n\tend\n\tif input == \"q\" then\n\t\tGameOver = true\n\t\treturn\n\tend\n\tlocal tInput = {}\n\tfor i=1, string.len(input) do\n\t\tlocal number = tonumber(string.sub(input,i,i))\n\t\tif number and not isValueInList (number, tInput) then\n\t\t\ttable.insert (tInput, number)\n\t\tend\n\tend\n\tlocal malformed = false\n\tif not (string.len(input) == 4) or not (#tInput == 4) then \n\t\tprint (nGuesses, 'bad input: too short or too long')\n\t\tmalformed = true \n\tend\n\t\n\tif not malformed then\n\t\tprint (nGuesses, 'parsed input:', table.concat(tInput, ', '))\n\t\tlocal nBulls, nCows = 0, 0\n\t\tfor i, number in ipairs (tInput) do\n\t\t\tif TNumber[i] == number then\n\t\t\t\tnBulls = nBulls + 1\n\t\t\telseif isValueInList (number, TNumber) then\n\t\t\t\tnCows = nCows + 1\n\t\t\tend\n\t\tend\n\t\tprint (nGuesses, 'Bulls: '.. nBulls .. ' Cows: ' .. nCows)\n\t\tif nBulls == 4 then\n\t\t\tprint (nGuesses, 'Win!')\n\t\t\tGameOver = true\n\t\tend\n\tend\nend\n\n","human_summarization":"\"Generates a four-digit random number without duplication from 1 to 9. The program prompts the user for guesses, rejects malformed guesses, and prints the score for each guess. The score is calculated based on the number of 'bulls' and 'cows', where a 'bull' is a correctly guessed digit in the correct position and a 'cow' is a correctly guessed digit in the wrong position. The game ends when the user's guess matches the randomly generated number.\"","id":1778}
    {"lang_cluster":"Lua","source_code":"\nlocal list = {}\nfor i = 1, 1000 do\n  list[i] = 1 + math.sqrt(-2 * math.log(math.random())) * math.cos(2 * math.pi * math.random()) \/ 2\nend\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":1779}
    {"lang_cluster":"Lua","source_code":"\nfunction dotprod(a, b)\n  local ret = 0\n  for i = 1, #a do\n    ret = ret + a[i] * b[i]\n  end\n  return ret\nend\n\nprint(dotprod({1, 3, -5}, {4, -2, 1}))\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":1780}
    {"lang_cluster":"Lua","source_code":"\nlines = {}\nstr = io.read()\nwhile str do\n    table.insert(lines,str)\n    str = io.read()\nend\n\n\nlines = {}\n\nfor line in io.lines() do\n    table.insert(lines, line) -- add the line to the list of lines\nend\n\n","human_summarization":"The code reads data from a text stream, either word-by-word or line-by-line, until there's no data left. It uses an iterator to read line-by-line from stdin, but can be modified to read from a file by substituting io.lines() with io.open(filename, \"r\"):lines().","id":1781}
    {"lang_cluster":"Lua","source_code":"\n\nrequire(\"LuaXML\")\nlocal dom = xml.new(\"root\")\nlocal element = xml.new(\"element\")\ntable.insert(element, \"Some text here\")\ndom:append(element)\ndom:save(\"dom.xml\")\n\n\n<?xml version=\"1.0\"?>\n<!-- file \"dom.xml\", generated by LuaXML -->\n\n<root>\n  <element>Some text here<\/element>\n<\/root>\n","human_summarization":"The code creates a simple DOM using the 'LuaXML' module and serializes it into the specified XML format, with the resulting contents stored in 'dom.xml'.","id":1782}
    {"lang_cluster":"Lua","source_code":"\nprint(os.date())\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":1783}
    {"lang_cluster":"Lua","source_code":"Works with: Lua version 5.1.4\nrequire (\"math\")\n\nshades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'}\n\nfunction normalize (vec)\n    len = math.sqrt(vec[1]^2 + vec[2]^2 + vec[3]^2)\n    return {vec[1]\/len, vec[2]\/len, vec[3]\/len}\nend\n\nlight = normalize{30, 30, -50}\n\nfunction dot (vec1, vec2)\n    d = vec1[1]*vec2[1] + vec1[2]*vec2[2] + vec1[3]*vec2[3]\n    return d < 0 and -d or 0\nend\n\nfunction draw_sphere (radius, k, ambient)\n    for i = math.floor(-radius),-math.floor(-radius) do\n        x = i + .5\n        local line = ''\n        for j = math.floor(-2*radius),-math.floor(-2*radius) do\n            y = j \/ 2 + .5\n            if x^2 + y^2 <= radius^2 then\n                vec = normalize{x, y, math.sqrt(radius^2 - x^2 - y^2)}\n                b = dot(light,vec) ^ k + ambient\n                intensity = math.floor ((1 - b) * #shades)\n                line = line .. (shades[intensity] or shades[1])\n            else\n                line = line .. ' '\n            end\n        end\n        print (line)\n    end\nend\n\ndraw_sphere (20, 4, 0.1)\ndraw_sphere (10, 2, 0.4)\n\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":1784}
    {"lang_cluster":"Lua","source_code":"\n\nfunction getSuffix (n)\n    local lastTwo, lastOne = n % 100, n % 10\n    if lastTwo > 3 and lastTwo < 21 then return \"th\" end\n    if lastOne == 1 then return \"st\" end\n    if lastOne == 2 then return \"nd\" end\n    if lastOne == 3 then return \"rd\" end\n    return \"th\"\nend\n \nfunction Nth (n) return n .. \"'\" .. getSuffix(n) end\n \nfor i = 0, 25 do print(Nth(i), Nth(i + 250), Nth(i + 1000)) end\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with its ordinal suffix. The function is tested with integer ranges 0..25, 250..265, and 1000..1025. The use of apostrophes in the output is optional.","id":1785}
    {"lang_cluster":"Lua","source_code":"\nfunction stripchars(str, chrs)\n  local s = str:gsub(\"[\"..chrs:gsub(\"%W\",\"%%%1\")..\"]\", '')\n  return s\nend\n \nprint( stripchars( \"She was a soul stripper. She took my heart!\", \"aei\" ) )\n--> Sh ws  soul strppr. Sh took my hrt!\nprint( stripchars( \"She was a soul stripper. She took my heart!\", \"a-z\" ) )\n--> She ws  soul stripper. She took my hert!\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":1786}
    {"lang_cluster":"Lua","source_code":"\nfunction genFizz (param)\n  local response\n  print(\"\\n\")\n  for n = 1, param.limit do\n    response = \"\"\n    for i = 1, 3 do\n      if n % param.factor[i] == 0 then\n        response = response .. param.word[i]\n      end\n    end\n    if response == \"\" then print(n) else print(response) end\n  end\nend\n\nlocal param = {factor = {}, word = {}}\nparam.limit = io.read()\nfor i = 1, 3 do\n  param.factor[i], param.word[i] = io.read(\"*number\", \"*line\")\nend\ngenFizz(param)\nlocal function fizzbuzz(n, mods)\n  local res = {}\n\n  for i = 1, #mods, 2 do\n    local mod, name = mods[i], mods[i+1]\n    for i = mod, n, mod do\n      res[i] = (res[i] or '') .. name\n    end\n  end\n\n  for i = 1, n do\n    res[i] = res[i] or i\n  end\n\n  return table.concat(res, '\\n')\nend\n\ndo\n  local n = tonumber(io.read())     -- number of lines, eg. 100\n  local mods = {}\n\n  local n_mods = 0\n  while n_mods ~= 3 do              -- for reading until EOF, change 3 to -1\n    local line = io.read()\n    if not line then break end\n    local s, e = line:find(' ')\n    local num  = tonumber(line:sub(1, s-1))\n    local name = line:sub(e+1)\n    mods[#mods+1] = num\n    mods[#mods+1] = name\n    n_mods = n_mods + 1\n  end\n\n  print(fizzbuzz(n, mods))\nend\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":1787}
    {"lang_cluster":"Lua","source_code":"\n\ns = \"12345678\"\ns = \"0\" .. s\nprint(s)\n\n\ns = \"12345678\"\ns = string.format(\"%s%s\", \"0\", s)\nprint(s)\n\n\ns = \"12345678\"\ns = table.concat({\"0\", s})\nprint(s)\n\n\n","human_summarization":"- Initializes a string variable with any text value\n- Prepends another string literal to the initialized string variable\n- Includes idiomatic solutions for the operation if supported by the language, without referring to the variable twice in one expression\n- Displays the content of the variable after the operation\n- Illustrates the operation through concatenation, string formatting, and list joining.","id":1788}
    {"lang_cluster":"Lua","source_code":"\nWorks with: Lua version 5.1.4\n\nfunction dragon()\n    local l = \"l\"\n    local r = \"r\"\n    local inverse = {l = r, r = l}\n    local field = {r}\n    local num = 1 \n    local loop_limit = 6 --increase this number to render a bigger curve\n    for discard=1,loop_limit do \n        field[num+1] = r\n        for i=1,num do\n            field[i+num+1] = inverse[field[num-i+1]]\n        end\n        num = num*2+1\n    end\n    return field\nend\n\nfunction render(field, w, h, l)\n    local x = 0\n    local y = 0\n    local points = {}\n    local highest_x = 0\n    local highest_y = 0\n    local lowest_x = 0\n    local lowest_y = 0\n    local l = \"l\"\n    local r = \"r\"\n    local u = \"u\"\n    local d = \"d\"\n    local heading = u\n    local turn = {r = {r = d, d = l, l = u, u = r}, l = {r = u, u = l, l = d, d = r}}\n    for k, v in ipairs(field) do\n        heading = turn[v][heading]\n        for i=1,3 do\n            points[#points+1] = {x, y}\n            if heading == l then\n                x = x-w\n            elseif heading == r then\n                x = x+w\n            elseif heading == u then\n                y = y-h\n            elseif heading == d then\n                y = y+h\n            end\n            if x > highest_x then\n                highest_x = x\n            elseif x < lowest_x then\n                lowest_x = x\n            end\n            if y > highest_y then\n                highest_y = y\n            elseif y < lowest_y then\n                lowest_y = y\n            end\n        end\n    end\n    points[#points+1] = {x, y}\n    highest_x = highest_x - lowest_x + 1\n    highest_y = highest_y - lowest_y + 1\n    for k, v in ipairs(points) do\n        v[1] = v[1] - lowest_x + 1\n        v[2] = v[2] - lowest_y + 1\n    end\n    return highest_x, highest_y, points\nend\n\nfunction render_text_mode()\n    local width, height, points = render(dragon(), 1, 1, 1)\n    local rows = {}\n    for i=1,height do\n        rows[i] = {}\n        for j=1,width do\n            rows[i][j] = ' '\n        end\n    end\n    for k, v in ipairs(points) do\n        rows[v[2]][v[1]] = \"*\"\n    end\n\n    for i=1,height do\n        print(table.concat(rows[i], \"\"))\n    end\nend\n\nfunction dump_points()\n    local width, height, points = render(dragon(), 4, 4, 1)\n    for k, v in ipairs(points) do\n        print(unpack(v))\n    end\nend\n\n--replace this line with dump_points() to output a list of coordinates:\nrender_text_mode()\n\n\n      ****  ****                     \n      *  *  *  *                     \n      *  *  *  *                     \n   ****  *******                     \n   *        *                        \n   *        *                        \n   ****     ****  ****               \n               *  *  *               \n               *  *  *               \n            **********               \n            *  *  *                  \n            *  *  *                  \n            *******                  \n               *                     \n               *                     \n      ****  ****                     \n      *  *  *                        \n      *  *  *                        \n      **********  ****               \n         *  *  *  *  *               \n         *  *  *  *  *               \n****  ****************               \n*  *  *  *  *  *  *                  \n*  *  *  *  *  *  *                  \n*******************                  \n   *  *  *  *  *                     \n   *  *  *  *  *                     \n*******  *******              ****   \n*  *        *                    *   \n*  *        *                    *   \n*******     ****  ****           ****\n   *  *        *  *  *              *\n   *  *        *  *  *              *\n   ****     **********           ****\n            *  *  *              *   \n            *  *  *              *   \n            **********  ****  *******\n               *  *  *  *  *  *  *  *\n               *  *  *  *  *  *  *  *\n            *******  **********  ****\n            *  *        *  *         \n            *  *        *  *         \n            *******     *******      \n               *  *        *  *      \n               *  *        *  *      \n               ****        ****      \n\n","human_summarization":"The code generates a dragon curve fractal, which can be displayed directly or written to an image file. It uses various algorithms, including recursive, successive approximation, iterative, absolute direction, absolute coordinates, predicate test, and Lindenmayer system methods. The code also offers two rendering modes: text mode and a mode for external rendering applications. It is designed for speed and can be used to draw other curves defined by L-systems.","id":1789}
    {"lang_cluster":"Lua","source_code":"\nmath.randomseed( os.time() )\nn = math.random( 1, 10 )\n\nprint( \"I'm thinking of a number between 1 and 10. Try to guess it: \" )\n\nrepeat\n    x = tonumber( io.read() )\n\n    if x == n then\n\tprint \"Well guessed!\"\n    else\n\tprint \"Guess again: \"\n    end\nuntil x == n\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":1790}
    {"lang_cluster":"Lua","source_code":"\nfunction getAlphabet ()\n    local letters = {}\n    for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end\n    return letters\nend\n\nlocal alpha = getAlphabet()\nprint(alpha[25] .. alpha[1] .. alpha[25])\n\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":1791}
    {"lang_cluster":"Lua","source_code":"\nfunction dec2bin(n)\n    local bin = \"\"\n    while n > 1 do\n        bin = n % 2 .. bin\n        n = math.floor(n \/ 2)\n    end\n    return n .. bin\nend\n\nprint(dec2bin(5))\nprint(dec2bin(50))\nprint(dec2bin(9000))\n\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":1792}
    {"lang_cluster":"Lua","source_code":"\n\nlocal SDL = require \"SDL\"\n\nlocal ret = SDL.init { SDL.flags.Video }\nlocal window = SDL.createWindow {\n\ttitle\t= \"Pixel\",\n\theight\t= 320,\n\twidth\t= 240\n}\n\nlocal renderer = SDL.createRenderer(window, 0, 0)\n\nrenderer:clear()\nrenderer:setDrawColor(0xFF0000)\nrenderer:drawPoint({x = 100,y = 100})\nrenderer:present()\n\nSDL.delay(5000)\n\n","human_summarization":"Creates a 320x240 window using the luasdl2 library and draws a red pixel at the position (100,100).","id":1793}
    {"lang_cluster":"Lua","source_code":"\nconf = {}\n\nfp = io.open( \"conf.txt\", \"r\" )\n\nfor line in fp:lines() do\n    line = line:match( \"%s*(.+)\" )\n    if line and line:sub( 1, 1 ) ~= \"#\" and line:sub( 1, 1 ) ~= \";\" then\n \toption = line:match( \"%S+\" ):lower()\n\tvalue  = line:match( \"%S*%s*(.*)\" )\n\n\tif not value then\n \t    conf[option] = true\n\telse\n\t    if not value:find( \",\" ) then\n\t\tconf[option] = value\n\t    else\n\t\tvalue = value .. \",\"\n\t\tconf[option] = {}\n\t\tfor entry in value:gmatch( \"%s*(.-),\" ) do\n\t\t    conf[option][#conf[option]+1] = entry\n\t\tend\n\t    end\n\tend\n\n    end\nend\n\nfp:close()\n\n\nprint( \"fullname = \", conf[\"fullname\"] )\nprint( \"favouritefruit = \", conf[\"favouritefruit\"] )\nif conf[\"needspeeling\"] then print( \"needspeeling = true\" ) else print( \"needspeeling = false\" ) end\nif conf[\"seedsremoved\"] then print( \"seedsremoved = true\" ) else print( \"seedsremoved = false\" ) end\nif conf[\"otherfamily\"] then\n    print \"otherfamily:\"\n    for _, entry in pairs( conf[\"otherfamily\"] ) do\n\tprint( \"\", entry )\n    end\nend\n\n","human_summarization":"read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.","id":1794}
    {"lang_cluster":"Lua","source_code":"\nlocal function haversine(x1, y1, x2, y2)\nr=0.017453292519943295769236907684886127;\nx1= x1*r; x2= x2*r; y1= y1*r; y2= y2*r; dy = y2-y1; dx = x2-x1;\na = math.pow(math.sin(dx\/2),2) + math.cos(x1) * math.cos(x2) * math.pow(math.sin(dy\/2),2); c = 2 * math.asin(math.sqrt(a)); d = 6372.8 * c;\nreturn d;\nend\n\n\nprint(haversine(36.12, -86.67, 33.94, -118.4));\n\n\n2887.2599506071\n","human_summarization":"implement the Haversine formula to calculate the great-circle distance between Nashville International Airport (BNA) and Los Angeles International Airport (LAX) using the given latitude and longitude coordinates. The code uses either the authalic radius (6371.0 km) or the average great-circle radius (6372.8 km) for calculations, with the latter being recommended. The results may vary based on the radius used. The code also takes into account the recommendations by the International Union of Geodesy and Geophysics to use the mean earth radius (6371 km) for real applications.","id":1795}
    {"lang_cluster":"Lua","source_code":"\nLibrary: LuaSocket\nlocal http = require(\"socket.http\")\nlocal url = require(\"socket.url\")\nlocal page = http.request('http:\/\/www.google.com\/m\/search?q=' .. url.escape(\"lua\"))\nprint(page)\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":1796}
    {"lang_cluster":"Lua","source_code":"\nfunction luhn(n)\n  n=string.reverse(n)\n  print(n)\n  local s1=0\n  --sum odd digits\n  for i=1,n:len(),2 do\n    s1=s1+n:sub(i,i)\n  end\n  --evens\n  local s2=0\n  for i=2,n:len(),2 do\n    local doubled=n:sub(i,i)*2\n    doubled=string.gsub(doubled,'(%d)(%d)',function(a,b)return a+b end)\n    s2=s2+doubled\n  end\n  print(s1)\n  print(s2)\n  local total=s1+s2\n  if total%10==0 then\n    return true\n  end\n  return false\nend \n\n-- Note that this function takes strings, not numbers.\n-- 16-digit numbers tend to be problematic\n-- when looking at individual digits.\nprint(luhn'49927398716')\nprint(luhn'49927398717')\nprint(luhn'1234567812345678')\nprint(luhn'1234567812345670')\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":1797}
    {"lang_cluster":"Lua","source_code":"\n\nfunction josephus(n, k, m)\n    local positions={}\n    for i=1,n do\n        table.insert(positions, i-1)\n    end\n    local i,j=1,1\n    local s='Execution order: '\n    while #positions>m do\n        if j==k then\n            s=s .. positions[i] .. ', '\n            table.remove(positions, i)\n            i=i-1\n        end\n        i=i+1\n        j=j+1\n        if i>#positions then i=1 end\n        if j>k then j=1 end\n    end\n    print(s:sub(1,#s-2) .. '.')\n    local s='Survivors: '\n    for _,v in pairs(positions) do s=s .. v .. ', ' end\n    print(s:sub(1,#s-2) .. '.')\nend\njosephus(41,3, 1)\n\n\n","human_summarization":"The code calculates the final survivor in the Josephus problem, given any number of prisoners (n) and a step count (k). It also provides a way to determine the position of any prisoner in the killing sequence. The code can handle scenarios where multiple survivors (m) are allowed. It follows the execution procedure described in the problem, with complexity O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die. The prisoners can be numbered from either 0 to n-1 or 1 to n.","id":1798}
    {"lang_cluster":"Lua","source_code":"\nfunction repeats(s, n) return n > 0 and s .. repeats(s, n-1) or \"\" end\n\nstring.rep(s,n)\n","human_summarization":"The code repeats a given string a specified number of times. It also includes a more efficient method for repeating a single character. Additionally, it demonstrates the use of native string library functions for these tasks.","id":1799}
    {"lang_cluster":"Lua","source_code":"\n\ntest = \"My name is Lua.\"\npattern = \".*name is (%a*).*\"\n\nif test:match(pattern) then\n    print(\"Name found.\")\nend\n\nsub, num_matches = test:gsub(pattern, \"Hello, %1!\")\nprint(sub)\n\n","human_summarization":"use Lua's string manipulation methods to match and substitute parts of a string using patterns similar to regular expressions, with the percent sign (%) used to start a character class or a reference for a match in a substitution.","id":1800}
    {"lang_cluster":"Lua","source_code":"\nlocal x = io.read()\nlocal y = io.read()\n\nprint (\"Sum: \"       , (x + y))\nprint (\"Difference: \", (x - y))\nprint (\"Product: \"   , (x * y))\nprint (\"Quotient: \"  , (x \/ y)) -- Does not truncate\nprint (\"Remainder: \" , (x % y)) -- Result has sign of right operand\nprint (\"Exponent: \"  , (x ^ y))\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":1801}
    {"lang_cluster":"Lua","source_code":"\n\nfunction countSubstring(s1, s2)\n    return select(2, s1:gsub(s2, \"\"))\nend\n\nprint(countSubstring(\"the three truths\", \"th\"))\nprint(countSubstring(\"ababababab\", \"abab\"))\n\n3\n2\n\nfunction countSubstring(s1, s2)\n    local count = 0\n    for eachMatch in s1:gmatch(s2) do \n        count = count + 1 \n    end\n    return count\nend\n\nprint(countSubstring(\"the three truths\", \"th\"))\nprint(countSubstring(\"ababababab\", \"abab\"))\n\n3\n2\n","human_summarization":"\"Implement a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function does not count overlapping substrings and matches from left-to-right or right-to-left for the highest number of non-overlapping matches.\"","id":1802}
    {"lang_cluster":"Lua","source_code":"\nfunction move(n, src, dst, via)\n    if n > 0 then\n        move(n - 1, src, via, dst)\n        print(src, 'to', dst)\n        move(n - 1, via, dst, src)\n    end\nend\n\nmove(4, 1, 2, 3)\n\n\nfunction move(n, src, via, dst)\n    if n > 0 then\n        move(n - 1, src, dst, via)\n        print('Disk ',n,' from ' ,src, 'to', dst)\n        move(n - 1, via, src, dst)\n        \n    end\nend\n \nmove(4, 1, 2, 3)\n\n#!\/usr\/bin\/env luajit\nlocal function printf(fmt, ...) io.write(string.format(fmt, ...)) end\nlocal runs=0\nlocal function move(tower, from, to)\n\tif #tower[from]==0 \n\t\tor (#tower[to]>0 \n\t\tand tower[from][#tower[from]]>tower[to][#tower[to]]) then\n\t\t\tto,from=from,to\n\tend\n\tif #tower[from]>0 then\n\t\ttower[to][#tower[to]+1]=tower[from][#tower[from]]\n\t\ttower[from][#tower[from]]=nil\n\n\t\tio.write(tower[to][#tower[to]],\":\",from, \"\u2192\", to, \" \")\n\tend\nend\n\nlocal function hanoi(n)\n\tlocal src,dst,via={},{},{}\n\tlocal tower={src,dst,via}\n\tfor i=1,n do src[i]=n-i+1 end\n\tlocal one,nxt,lst\n\tif n%2==1 then -- odd\n\t\tone,nxt,lst=1,2,3\n\telse\n\t\tone,nxt,lst=1,3,2\n\tend\n\t--repeat\n\t::loop::\n\t\tmove(tower, one, nxt)\n\t\tif #dst==n then return end\n\t\tmove(tower, one, lst)\n\t\tone,nxt,lst=nxt,lst,one\n\tgoto loop\n\t--until false\nend\n\nlocal num=arg[1] and tonumber(arg[1]) or 4\n\nhanoi(num)\n\n\n","human_summarization":"Implement a recursive solution to solve the Towers of Hanoi problem.","id":1803}
    {"lang_cluster":"Lua","source_code":"\nfunction Binomial( n, k )\n    if k > n then return nil end\n    if k > n\/2 then k = n - k end       --   (n k) = (n n-k)\n    \n    numer, denom = 1, 1\n    for i = 1, k do\n        numer = numer * ( n - i + 1 )\n        denom = denom * i\n    end\n    return numer \/ denom\nend\n\n\nlocal Binomial = setmetatable({},{\n __call = function(self,n,k)\n   local hash = (n<<32) | (k & 0xffffffff)\n   local ans = self[hash]\n   if not ans then \n    if n<0 or k>n then\n      return 0 -- not save\n    elseif n<=1 or k==0 or k==n then \n      ans = 1\n    else\n      if 2*k > n then \n        ans = self(n, n - k) \n      else\n        local lhs = self(n-1,k)\n        local rhs = self(n-1,k-1)        \n        local sum = lhs + rhs\n        if sum<0 or not math.tointeger(sum)then \n          -- switch to double\n          ans = lhs\/1.0 + rhs\/1.0 -- approximate\n        else\n          ans = sum\n        end\n      end\n    end\n    rawset(self,hash,ans)\n   end\n   return ans\n end \n})\nprint( Binomial(100,50)) -- 1.0089134454556e+029\n\n","human_summarization":"\"Calculates any binomial coefficient using a given formula. It specifically outputs the binomial coefficient of 5 and 3, which is 10. The code also handles tasks related to combinations and permutations, both with and without replacement. It utilizes additive recursion with memoization by hashing 2 input integers and supports bit-wise operations assuming a 64-bit integer implementation.\"","id":1804}
    {"lang_cluster":"Lua","source_code":"\nfunction shellsort( a )\n    local inc = math.ceil( #a \/ 2 )\n    while inc > 0 do\n        for i = inc, #a do\n            local tmp = a[i]\n            local j = i\n            while j > inc and a[j-inc] > tmp do\n                a[j] = a[j-inc]\n                j = j - inc\n            end\n            a[j] = tmp\n        end\n        inc = math.floor( 0.5 + inc \/ 2.2 )\n    end \n    \n    return a\nend\n\na = { -12, 3, 0, 4, 7, 4, 8, -5, 9 }\na = shellsort( a )\n\nfor _, i in pairs(a) do\n    print(i)\nend\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":1805}
    {"lang_cluster":"Lua","source_code":"\nfunction ConvertToGrayscaleImage( bitmap )\n    local size_x, size_y = #bitmap, #bitmap[1]\n    local gray_im = {}\n  \n    for i = 1, size_x do\n        gray_im[i] = {}\n        for j = 1, size_y do \n            gray_im[i][j] = math.floor( 0.2126*bitmap[i][j][1] + 0.7152*bitmap[i][j][2] + 0.0722*bitmap[i][j][3] )\n        end\n    end\n    \n    return gray_im\nend\n\nfunction ConvertToColorImage( gray_im )\n    local size_x, size_y = #gray_im, #gray_im[1]    \n    local bitmap = Allocate_Bitmap( size_x, size_y )         -- this function is defined at http:\/\/rosettacode.org\/wiki\/Basic_bitmap_storage#Lua\n\n    for i = 1, size_x do\n        for j = 1, size_y do \n            bitmap[i][j] = { gray_im[i][j], gray_im[i][j], gray_im[i][j] }\n        end\n    end\n    \n    return bitmap\nend\n\n","human_summarization":"extend the data storage type to support grayscale images, define operations to convert a color image to grayscale and vice versa using the CIE recommended formula for luminance, and ensure no rounding errors or distorted results occur when storing calculated luminance as an unsigned integer.","id":1806}
    {"lang_cluster":"Lua","source_code":"\nWorks with: L\u00d6VE\nfunction love.load()\n\ttext = \"Hello World! \"\n\tlength = string.len(text)\n\t\n\t\n\tupdate_time = 0.3\n\ttimer = 0\n\tright_direction = true\n\t\n\t\n\tlocal width, height = love.graphics.getDimensions( )\n\n\tlocal size = 100\n\tlocal font = love.graphics.setNewFont( size )\n\tlocal twidth = font:getWidth( text )\n\tlocal theight = font:getHeight( )\n\tx = width\/2 - twidth\/2\n\ty = height\/2-theight\/2\n\t\nend\n\n \nfunction love.update(dt)\n\ttimer = timer + dt\n\tif timer > update_time then\n\t\ttimer = timer - update_time\n\t\tif right_direction then\n\t\t\ttext = string.sub(text, 2, length) .. string.sub(text, 1, 1)\n\t\telse\n\t\t\ttext = string.sub(text, length, length) .. string.sub(text, 1, length-1)\n\t\tend\n\tend\nend\n\n\nfunction love.draw()\n\tlove.graphics.print (text, x, y)\nend\n\nfunction love.keypressed(key, scancode, isrepeat)\n\tif false then\n\telseif key == \"escape\" then\n\t\tlove.event.quit()\n\tend\nend\n\nfunction love.mousepressed( x, y, button, istouch, presses )\n\tright_direction = not right_direction\nend\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":1807}
    {"lang_cluster":"Lua","source_code":"\n\ni=0\nrepeat\n  i=i+1\n  print(i)\nuntil i%6 == 0\n\n","human_summarization":"Initializes a value at 0, then enters a loop where it increments the value by 1 and prints it each iteration. The loop continues until the value modulo 6 equals 0. The loop is guaranteed to run at least once. Note: Lua does not support do-while loops.","id":1808}
    {"lang_cluster":"Lua","source_code":"\nWorks with: Lua version 5.0+\n\n\nstr = \"Hello world\"\nlength = #str\n\nstr = \"Hello world\"\nlength = string.len(str)\n\nstr = \"Hello world\"\nlength = #str\n\nstr = \"Hello world\"\nlength = string.len(str)\n\nutf8.len(\"m\u00f8\u00f8se\")\nutf8.len(\"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\")\nutf8.len(\"J\u0332o\u0332s\u0332\u00e9\u0332\")\n\n","human_summarization":"determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. The codes also handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. Additionally, the codes can provide the string length in graphemes if the language supports it. For Lua language, the codes consider a character as the size of one byte, so there is no difference between byte length and character length.","id":1809}
    {"lang_cluster":"Lua","source_code":"\nprint (string.sub(\"knights\",2))    -- remove the first character\nprint (string.sub(\"knights\",1,-2))    -- remove the last character\nprint (string.sub(\"knights\",2,-2))    -- remove the first and last characters\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":1810}
    {"lang_cluster":"Lua","source_code":"\nnw = require(\"nw\")\nwin = nw:app():window(320, 240)\nwin:show()\nwin:maximize()\ncw, ch = win:client_size()\nprint(cw .. \" x \" .. ch)\n\n\n\n","human_summarization":"\"Determines the maximum height and width of a window that can fit on the screen's physical display area without scrolling, considering window decorations, menubars, multiple monitors, and tiling window managers.\"","id":1811}
    {"lang_cluster":"Lua","source_code":"\n--9x9 sudoku solver in lua\n--based on a branch and bound solution\n--fields are not tried in plain order\n--but in a way to detect dead ends earlier\nconcat=table.concat\ninsert=table.insert\nconstraints = { }   --contains a table with 3 constraints for every field\n-- a contraint \"cons\" is a table containing all fields which must not have the same value\n-- a field \"f\" is an integer from 1 to 81\ncolumns = { }       --contains all column-constraints   variable \"c\"\nrows = { }          --contains all row-constraints      variable \"r\"\nblocks = { }        --contains all block-constraints    variable \"b\"\n\n--initialize all constraints\nfor f = 1, 81 do\n  constraints[f] = { }\nend\nall_constraints = { } --union of colums, rows and blocks\nfor i = 1, 9 do\n  columns[i] = {\n    unknown = 9, --number of fields not yet solved\n    unknowns = { } --fields not yet solved\n  }\n  insert(all_constraints, columns[i])\n  rows[i] = {\n    unknown = 9, -- see l.15\n    unknowns = { } -- see l.16\n  }\n  insert(all_constraints, rows[i])\n  blocks[i] = {\n    unknown = 9, --see l.15\n    unknowns = { } --see l.16\n  }\n  insert(all_constraints, blocks[i])\nend\nconstraints_by_unknown = { } --contraints sorted by their number of unknown fields\nfor i = 0, 9 do\n  constraints_by_unknown[i] = {\n    count = 0 --how many contraints are in here\n  }\nend\nfor r = 1, 9 do\n  for c = 1, 9 do\n    local f = (r - 1) * 9 + c\n    insert(rows[r], f)\n    insert(constraints[f], rows[r])\n    insert(columns[c], f)\n    insert(constraints[f], columns[c])\n  end\nend\nfor i = 1, 3 do\n  for j = 1, 3 do\n    local r = (i - 1) * 3 + j\n    for k = 1, 3 do\n      for l = 1, 3 do\n        local c = (k - 1) * 3 + l\n        local f = (r - 1) * 9 + c\n        local b = (i - 1) * 3 + k\n        insert(blocks[b], f)\n        insert(constraints[f], blocks[b])\n      end\n    end\n  end\nend\nworking = { } --save the read values in here\nfunction read() --read the values from stdin\n  local f = 1\n  local l = io.read(\"*a\")\n  for d in l:gmatch(\"(%d)\") do\n    local n = tonumber(d)\n    if n > 0 then\n      working[f] = n\n      for _,cons in pairs(constraints[f]) do\n        cons.unknown = cons.unknown - 1\n      end\n    else\n      for _,cons in pairs(constraints[f]) do\n        cons.unknowns[f] = f\n      end\n    end\n    f = f + 1\n  end\n  assert((f == 82), \"Wrong number of digits\")\nend\nread()\nfunction printer(t) --helper function for printing a 1-81 table \n  local pattern = {1,2,3,false,4,5,6,false,7,8,9} --place seperators for better readability\n  for _,r in pairs(pattern) do\n    if r then\n      local function p(c)\n        return c and t[(r - 1) * 9 + c] or \"|\" \n      end\n      local line={}\n      for k,v in pairs(pattern) do\n        line[k]=p(v)\n      end\n      print(concat(line))\n    else\n      print(\"---+---+---\")\n    end\n  end\nend\norder = { } --when to try a field\nfor _,cons in pairs(all_constraints) do --put all constraints in the corresponding constraints_by_unknown set\n  local level = constraints_by_unknown[cons.unknown]\n  level[cons] = cons\n  level.count = level.count + 1\nend\nfunction first(t) --helper function to get a value from a set\n  for k, v in pairs(t) do\n    if k == v then\n      return k\n    end\n  end\nend\nfunction establish_order() -- determine the sequence in which the fields are to be tried\n  local solved = constraints_by_unknown[0].count\n  while solved < 27 do --there 27 constraints\n  --contraints with no unknown fields are considered \"solved\"\n  --keep in mind the actual solving happens in function branch\n    local i = 1\n    while constraints_by_unknown[i].count == 0 do\n      i = i + 1\n      -- find a unsolved contraint with the least number of unsolved fields\n    end\n    local cons = first(constraints_by_unknown[i])\n    local f = first(cons.unknowns)\n    -- take one of its unknown fields and append it to \"order\"\n    insert(order, f)\n    for _,c in pairs(constraints[f]) do\n    --each constraint \"c\" of \"f\" is moved up one \"level\"\n    --delete \"f\" from the constraints unknown fields\n    --decrease unknown of \"c\"\n      c.unknowns[f] = nil\n      local level = constraints_by_unknown[c.unknown]\n      level[c] = nil\n      level.count = level.count - 1\n      c.unknown = c.unknown - 1\n      level = constraints_by_unknown[c.unknown]\n      level[c] = c\n      level.count = level.count + 1\n      constraints_by_unknown[c.unknown][c] = c\n    end\n    solved = constraints_by_unknown[0].count\n  end\nend\nestablish_order()\nmax = #order --how many fields are to be solved\nfunction bound(f,i)\n  for _,c in pairs(constraints[f]) do\n    for _,x in pairs(c) do\n      if i == working[x] then \n        return false --i is already used in fs column\/row\/block\n      end\n    end\n  end\n  return true\nend\nfunction branch(n)\n  local f = order[n] --recursively iterate over fields in order\n  if n > max then\n    return working --all fields solved without collision\n  else\n    for i = 1, 9 do --check all values\n      if bound(f, i) then --if there is no collision\n        working[f] = i\n        local res = branch(n + 1) --try next field\n        if res then\n          return res --all fields solved without collision\n        else\n          working[f] = nil --this lead to a dead end\n        end\n      else\n        working[f] = nil --reset field because of a collision\n      end\n    end\n    return false --this is a dead end\n  end\nend\nx = branch(1)\nif x then\n  return printer(x)\nend\n\n\n003 000 000\n400 080 036\n008 000 100\n\n040 060 073\n000 900 000\n000 002 005\n\n004 070 068\n600 000 000\n700 600 500\n\n\n","human_summarization":"implement a Sudoku solver that takes a partially filled 9x9 grid as input and displays the solved Sudoku in a human-readable format. The speed of the code is approximately half as fast as optimized C.","id":1812}
    {"lang_cluster":"Lua","source_code":"\nfunction table.shuffle(t)\n  for n = #t, 1, -1 do\n    local k = math.random(n)\n    t[n], t[k] = t[k], t[n]\n  end\n \n  return t\nend\n\nmath.randomseed( os.time() )\na = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}\ntable.shuffle(a)\nfor i,v in ipairs(a) do print(i,v) end\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":1813}
    {"lang_cluster":"Lua","source_code":"\nfunction isLeapYear (y)\n    return (y % 4 == 0 and y % 100 ~=0) or y % 400 == 0\nend\n\nfunction dayOfWeek (y, m, d)\n    local t = os.time({year = y, month = m, day = d})\n    return os.date(\"%A\", t)\nend\n\nfunction lastWeekdays (wday, year)\n    local monthLength, day = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}\n    if isLeapYear(year) then monthLength[2] = 29 end\n    for month = 1, 12 do\n        day = monthLength[month]\n        while dayOfWeek(year, month, day) ~= wday do day = day - 1 end\n        print(year .. \"-\" .. month .. \"-\" .. day)\n    end\nend\n\nlastWeekdays(\"Friday\", tonumber(arg[1]))\n\n\n>lua lastFridays.lua 2012\n2012-1-27\n2012-2-24\n2012-3-30\n2012-4-27\n2012-5-25\n2012-6-29\n2012-7-27\n2012-8-31\n2012-9-28\n2012-10-26\n2012-11-30\n2012-12-28\n\n>\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":1814}
    {"lang_cluster":"Lua","source_code":"\nio.write(\"Goodbye, World!\")\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":1815}
    {"lang_cluster":"Lua","source_code":"\nlocal function encrypt(text, key)\n\treturn text:gsub(\"%a\", function(t)\n\t\t\tlocal base = (t:lower() == t and string.byte('a') or string.byte('A'))\n\n\t\t\tlocal r = t:byte() - base\n\t\t\tr = r + key\n\t\t\tr = r%26 -- works correctly even if r is negative\n\t\t\tr = r + base\n\t\t\treturn string.char(r)\n\t\tend)\nend\n\nlocal function decrypt(text, key)\n\treturn encrypt(text, -key)\nend\n\ncaesar = {\n\tencrypt = encrypt,\n\tdecrypt = decrypt,\n}\n\n-- test\ndo\n\tlocal text = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz\"\n\tlocal encrypted = caesar.encrypt(text, 7)\n\tlocal decrypted = caesar.decrypt(encrypted, 7)\n\tprint(\"Original text:  \", text)\n\tprint(\"Encrypted text: \", encrypted)\n\tprint(\"Decrypted text: \", decrypted)\nend\n\n\nlocal memo = {}\n\nlocal function make_table(k)\n    local t = {}\n    local a, A = ('a'):byte(), ('A'):byte()\n\n    for i = 0,25 do\n        local  c = a + i\n        local  C = A + i\n        local rc = a + (i+k) % 26\n        local RC = A + (i+k) % 26\n        t[c], t[C] = rc, RC\n    end\n\n    return t\nend\n\nlocal function caesar(str, k, decode)\n    k = (decode and -k or k) % 26\n\n    local t = memo[k]\n    if not t then\n        t = make_table(k)\n        memo[k] = t\n    end\n\n    local res_t = { str:byte(1,-1) }\n    for i,c in ipairs(res_t) do\n        res_t[i] = t[c] or c\n    end\n    return string.char(unpack(res_t))\nend\n\n","human_summarization":"implement both encoding and decoding functionalities of a Caesar cipher. The cipher uses a key between 1 and 25 to rotate the letters of the alphabet, replacing each letter with the next 1st to 25th letter in the alphabet. It also includes the ability to wrap from Z to A. The codes also highlight the cipher's lack of security due to its vulnerability to frequency analysis or brute force attacks. The Caesar cipher is shown to be identical to the Vigen\u00e8re cipher with a key length of 1 and to the Rot-13 cipher with a key of 13.","id":1816}
    {"lang_cluster":"Lua","source_code":"\nfunction gcd( m, n )\n    while n ~= 0 do\n        local q = m\n        m = n\n        n = q % n\n    end\n    return m\nend\n\nfunction lcm( m, n )\n    return ( m ~= 0 and n ~= 0 ) and m * n \/ gcd( m, n ) or 0\nend\n\nprint( lcm(12,18) )\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":1817}
    {"lang_cluster":"Lua","source_code":"\n\nfunction checkDigit (cusip)\n  if #cusip ~= 8 then return false end\n  \n  local sum, c, v, p = 0\n  for i = 1, 8 do\n    c = cusip:sub(i, i)\n    if c:match(\"%d\") then\n      v = tonumber(c)\n    elseif c:match(\"%a\") then\n      p = string.byte(c) - 55\n      v = p + 9\n    elseif c == \"*\" then\n      v = 36\n    elseif c == \"@\" then\n      v = 37\n    elseif c == \"#\" then\n      v = 38\n    end\n    if i % 2 == 0 then\n      v = v * 2\n    end\n    \n    sum = sum + math.floor(v \/ 10) + v % 10\n  end\n  \n  return tostring((10 - (sum % 10)) % 10)\nend\n\nlocal testCases = {\n  \"037833100\",\n  \"17275R102\",\n  \"38259P508\",\n  \"594918104\",\n  \"68389X106\",\n  \"68389X105\"\n}\nfor _, CUSIP in pairs(testCases) do\n  io.write(CUSIP .. \": \")\n  if checkDigit(CUSIP:sub(1, 8)) == CUSIP:sub(9, 9) then\n    print(\"VALID\")\n  else\n    print(\"INVALID\")\n  end\nend\n\n\n","human_summarization":"The code validates the last digit (check digit) of a CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. It uses an algorithm that calculates the check digit based on the first eight characters of the CUSIP, considering both numeric and alphabetic characters, as well as special characters \"*\", \"@\", and \"#\". The function returns the calculated check digit for verification.","id":1818}
    {"lang_cluster":"Lua","source_code":"\n\nffi = require(\"ffi\")\nprint(\"size of int (in bytes):  \" .. ffi.sizeof(ffi.new(\"int\")))\nprint(\"size of pointer (in bytes):  \" .. ffi.sizeof(ffi.new(\"int*\")))\nprint((ffi.abi(\"le\") and \"little\" or \"big\") .. \" endian\")\n\n\n","human_summarization":"uses ffi to print the word size and endianness of the host machine in a scripting environment where Lua is used, as pure\/native Lua cannot perform this task. The support for this operation is expected to be provided by the host or an external library.","id":1819}
    {"lang_cluster":"Lua","source_code":"\n\nt={monday=1, tuesday=2, wednesday=3, thursday=4, friday=5, saturday=6, sunday=0, [7]=\"fooday\"}\nfor key, value in pairs(t) do                       \n  print(value, key)\nend\n\n\n0\tsunday\nfooday\t7\n2\ttuesday\n3\twednesday\n5\tfriday\n4\tthursday\n6\tsaturday\n1\tmonday\n\n\nl={'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday', not_a_number='fooday', [0]='today', [-1]='yesterday' }\nfor key, value in ipairs(l) do                                                                         \n  print(key, value)\nend\n\n\n1\tmonday\n2\ttuesday\n3\twednesday\n4\tthursday\n5\tfriday\n6\tsaturday\n7\tsunday\n\n\n","human_summarization":"utilize a \"for each\" loop or another type of loop to iterate through a collection in order and print each element. In Lua, two built-in iterators, pairs() and ipairs(), are used for this task. Pairs() iterates over all entries in a table without a specific order, while ipairs() iterates over table entries with positive integer keys in order, ignoring non-numeric and non-positive integer keys.","id":1820}
    {"lang_cluster":"Lua","source_code":"\n\nfunction string:split (sep)\n    local sep, fields = sep or \":\", {}\n    local pattern = string.format(\"([^%s]+)\", sep)\n    self:gsub(pattern, function(c) fields[#fields+1] = c end)\n    return fields\nend\n\nlocal str = \"Hello,How,Are,You,Today\"\nprint(table.concat(str:split(\",\"), \".\"))\n\n\n","human_summarization":"\"Tokenizes a string by separating it into an array using commas as delimiters, then displays the words to the user separated by a period, including a trailing period.\"","id":1821}
    {"lang_cluster":"Lua","source_code":"function gcd(a,b)\n\tif b ~= 0 then\n\t\treturn gcd(b, a\u00a0% b)\n\telse\n\t\treturn math.abs(a)\n\tend\nend\n\nfunction demo(a,b)\n\tprint(\"GCD of \" .. a .. \" and \" .. b .. \" is \" .. gcd(a, b))\nend\n\ndemo(100, 5)\ndemo(5, 100)\ndemo(7, 23)\n\nGCD of 100 and 5 is 5\nGCD of 5 and 100 is 5\nGCD of 7 and 23 is 1\n\n\nfunction gcd(a,b)\n    while b~=0 do \n        a,b=b,a%b\n    end\n    return math.abs(a)\nend\n","human_summarization":"implement a faster iterative solution of Euclid to find the greatest common divisor (GCD), also known as greatest common factor (gcf) and greatest common measure, of two integers. The code is related to the task of finding the least common multiple.","id":1822}
    {"lang_cluster":"Lua","source_code":"\nWorks with: Lua version 5.3\nLibrary: LuaSocket\nlocal socket = require(\"socket\")\n\nlocal function has_value(tab, value)\n    for i, v in ipairs(tab) do\n        if v == value then return i end\n    end\n    return false\nend\n\nlocal function checkOn(client)\n   local line, err = client:receive()\n\tif line then\n\t\tclient:send(line .. \"\\n\")\n\tend\n\tif err and err ~= \"timeout\" then\n\t\tprint(tostring(client) .. \" \" .. err)\n\t\tclient:close()\n\t\treturn true  -- end this connection\n   end\n\treturn false  -- do not end this connection\nend\n\nlocal server = assert(socket.bind(\"*\",12321))\nserver:settimeout(0)  -- make non-blocking\nlocal connections = { }  -- a list of the client connections\nwhile true do\n\tlocal newClient = server:accept()\n\tif newClient then\n\t\tnewClient:settimeout(0)  -- make non-blocking\n\t\ttable.insert(connections, newClient)\n\tend\n\tlocal readList = socket.select({server, table.unpack(connections)})\n\tfor _, conn in ipairs(readList) do\n\t\tif conn ~= server and checkOn(conn) then\n\t\t\ttable.remove(connections, has_value(connections, conn))\n\t\tend\n\tend\nend\n\n\n\nlocal socket=require(\"socket\")\n\nfunction checkOn (client)\n    local line, err = client:receive()\n    if line then\n        print(tostring(client) .. \" said \" .. line)\n        client:send(line .. \"\\n\")\n    end\n    if err and err ~= \"timeout\" then\n        print(tostring(client) .. \" \" .. err)\n        client:close()\n        return true  -- end this connection\n    end\n    return false    -- do not end this connection\nend\n\nlocal delay = 0.004  -- anything less than this uses up my CPU\nlocal connections = {}  -- an array of connections\nlocal newClient\nlocal server = assert(socket.bind(\"*\", 12321))\nserver:settimeout(delay)\nwhile true do\n    repeat\n        newClient = server:accept()\n        for idx, client in ipairs(connections) do\n            if checkOn(client) then table.remove(connections, idx) end\n        end\n    until newClient\n    newClient:settimeout(delay)\n    print(tostring(newClient) .. \" connected\")\n    table.insert(connections, newClient)\nend\n\n\nWorks with: Luvit\nlocal http = require(\"http\")\n\nhttp.createServer(function(req, res)\n\tprint((\"Connection from %s\"):format(req.socket:address().ip))\n\n\tlocal chunks = {}\n\tlocal function dumpChunks()\n\t\tfor i=1,#chunks do\n\t\t\tres:write(table.remove(chunks, 1))\n\t\tend\n\tend\n\n\treq:on(\"data\", function(data)\n\t\tfor line, nl in data:gmatch(\"([^\\n]+)(\\n?)\") do\n\t\t\tif nl == \"\\n\" then\n\t\t\t\tdumpChunks()\n\t\t\t\tres:write(line)\n\t\t\t\tres:write(\"\\n\")\n\t\t\telse\n\t\t\t\ttable.insert(chunks, line)\n\t\t\tend\n\t\tend\n\tend)\n\n\treq:on(\"end\", function()\n\t\tdumpChunks()\n\t\tres:finish()\n\tend)\nend):listen(12321, \"127.0.0.1\")\n\nprint(\"Server running at http:\/\/127.0.0.1:12321\/\")\n\n","human_summarization":"\"Implement an echo server that runs on TCP port 12321, accepts and handles multiple simultaneous connections from localhost only, echoes back complete lines received from clients, and logs connection information. The server uses a table of client socket objects with tiny delays to prevent CPU overuse, and continues to respond to other clients even if one client sends a partial line or stops reading responses.\"","id":1823}
    {"lang_cluster":"Lua","source_code":"\n\nif tonumber(a) ~= nil then\n   --it's a number\nend;\n\n","human_summarization":"The code defines a boolean function that checks if a given string can be interpreted as a numeric value, including floating point, negative numbers, and numbers in different formats like hexadecimal or scientific notation.","id":1824}
    {"lang_cluster":"Lua","source_code":"\nWorks with: Lua version 5.1 - 5.3\nLibrary: lua-http\nlocal request = require('http.request')\nlocal headers, stream = request.new_from_uri(\"https:\/\/sourceforge.net\/\"):go()\nlocal body = stream:get_body_as_string()\nlocal status = headers:get(':status')\nio.write(string.format('Status: %d\\nBody: %s\\n', status, body)\n\n\n","human_summarization":"send a GET request to the URL \"https:\/\/www.w3.org\/\" without authentication, print the obtained resource to the console, and check the host certificate for validity. The code does not support redirects and uses lua-http library.","id":1825}
    {"lang_cluster":"Lua","source_code":"\nsubjectPolygon = {\n  {50, 150}, {200, 50}, {350, 150}, {350, 300},\n  {250, 300}, {200, 250}, {150, 350}, {100, 250}, {100, 200}\n}\n \nclipPolygon = {{100, 100}, {300, 100}, {300, 300}, {100, 300}}\n\nfunction inside(p, cp1, cp2)\n  return (cp2.x-cp1.x)*(p.y-cp1.y) > (cp2.y-cp1.y)*(p.x-cp1.x)\nend\n\nfunction intersection(cp1, cp2, s, e)\n  local dcx, dcy = cp1.x-cp2.x, cp1.y-cp2.y\n  local dpx, dpy = s.x-e.x, s.y-e.y\n  local n1 = cp1.x*cp2.y - cp1.y*cp2.x\n  local n2 = s.x*e.y - s.y*e.x\n  local n3 = 1 \/ (dcx*dpy - dcy*dpx)\n  local x = (n1*dpx - n2*dcx) * n3\n  local y = (n1*dpy - n2*dcy) * n3\n  return {x=x, y=y}\nend\n\nfunction clip(subjectPolygon, clipPolygon)\n  local outputList = subjectPolygon\n  local cp1 = clipPolygon[#clipPolygon]\n  for _, cp2 in ipairs(clipPolygon) do  -- WP clipEdge is cp1,cp2 here\n    local inputList = outputList\n    outputList = {}\n    local s = inputList[#inputList]\n    for _, e in ipairs(inputList) do\n      if inside(e, cp1, cp2) then\n        if not inside(s, cp1, cp2) then\n          outputList[#outputList+1] = intersection(cp1, cp2, s, e)\n        end\n        outputList[#outputList+1] = e\n      elseif inside(s, cp1, cp2) then\n        outputList[#outputList+1] = intersection(cp1, cp2, s, e)\n      end\n      s = e\n    end\n    cp1 = cp2\n  end\n  return outputList\nend\n\nfunction main()\n  local function mkpoints(t)\n    for i, p in ipairs(t) do\n      p.x, p.y = p[1], p[2]\n    end\n  end\n  mkpoints(subjectPolygon)\n  mkpoints(clipPolygon)\n\n  local outputList = clip(subjectPolygon, clipPolygon)\n\n  for _, p in ipairs(outputList) do\n    print(('{%f, %f},'):format(p.x, p.y))\n  end\nend\n\nmain()\n\n\n","human_summarization":"Implement the Sutherland-Hodgman clipping algorithm to find the intersection of a given polygon and a rectangle. The code takes a polygon defined by a sequence of points and clips it by a rectangle. It then prints the sequence of points that define the resulting clipped polygon. Additionally, it displays all three polygons on a graphical surface, each in a different color, and fills the resulting polygon.","id":1826}
    {"lang_cluster":"Lua","source_code":"\nprint(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4))\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":1827}
    {"lang_cluster":"Lua","source_code":"\n\n> -- A STRING THAT CAN BE IMPLICITLY CONVERTED TO A NUMBER\n> s = \"1234\"\n> s+1 -- implicitly convert to number, add 1, remain a number\n1235\n> type(s+1)\nnumber\n> (s+1)..'' -- implicitly convert to number, add 1, implicitly convert back to string\n1235\n> type((s+1)..'')\nstring\n> tostring(s+1) -- implicitly convert to number, add 1, explicitly convert back to string\n1235\n> type(tostring(s+1))\nstring\n> -- A STRING THAT CANNOT BE IMPLICITLY CONVERTED TO A NUMBER\n> s = \"hello\"\n> s+1\nstdin:1: attempt to add a 'string' with a 'number'\nstack traceback:\n        [C]: in metamethod 'add'\n        stdin:1: in main chunk\n        [C]: in\u00a0?\n> -- ONE-LINER EXPLICIT VERSION\n> tostring(tonumber(\"1234\")+1)\n1235\n","human_summarization":"increment a numerical string using Lua's implicit type conversion feature.","id":1828}
    {"lang_cluster":"Lua","source_code":"\nfunction sattolo (items)\n    local j\n    for i = #items, 2, -1 do\n        j = math.random(i - 1)\n        items[i], items[j] = items[j], items[i]\n    end\nend\n\nmath.randomseed(os.time())\nlocal testCases = {\n    {},\n    {10},\n    {10, 20},\n    {10, 20, 30},\n    {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22}\n}\nfor _, array in pairs(testCases) do\n    sattolo(array)\n    print(\"[\" .. table.concat(array, \", \") .. \"]\")\nend\n\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":1829}
    {"lang_cluster":"Lua","source_code":"\nfunction median (numlist)\n    if type(numlist) ~= 'table' then return numlist end\n    table.sort(numlist)\n    if #numlist %2 == 0 then return (numlist[#numlist\/2] + numlist[#numlist\/2+1]) \/ 2 end\n    return numlist[math.ceil(#numlist\/2)]\nend\n\nprint(median({4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2}))\nprint(median({4.1, 7.2, 1.7, 9.3, 4.4, 3.2}))\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.","id":1830}
    {"lang_cluster":"Lua","source_code":"\nfor i = 1, 100 do\n\tif i\u00a0% 15 == 0 then\n\t\tprint(\"FizzBuzz\")\n\telseif i\u00a0% 3 == 0 then\n\t\tprint(\"Fizz\")\n\telseif i\u00a0% 5 == 0 then\n\t\tprint(\"Buzz\")\n\telse\n\t\tprint(i)\n\tend\nend\nfor i = 1, 100 do\n\toutput = \"\"\n\tif i\u00a0% 3 == 0 then\n\t\toutput = output..\"Fizz\"\n\tend\n\tif i\u00a0% 5 == 0 then\n\t\toutput = output..\"Buzz\"\n\tend\n\tif(output == \"\") then\n\t\toutput = i\n\tend\n\tprint(output)\nend\nword = {\"Fizz\", \"Buzz\", \"FizzBuzz\"}\n\nfor i = 1, 100 do\n        print(word[(i\u00a0% 3 == 0 and 1 or 0) + (i\u00a0% 5 == 0 and 2 or 0)] or i)\nend\nlocal t = {\n        [0]  = \"FizzBuzz\",\n        [3]  = \"Fizz\",\n        [5]  = \"Buzz\",\n        [6]  = \"Fizz\",\n        [9]  = \"Fizz\",\n        [10] = \"Buzz\",\n        [12] = \"Fizz\"\n}\n\nfor i = 1, 100 do\n        print(t[i%15] or i)\nend\n\nlocal mt = {\n\t__newindex = (function (t, k, v)\n\t\tif type(k) ~= \"number\" then\trawset(t, k, v)\n\t\telseif 0 == (k\u00a0% 15) then\trawset(t, k, \"fizzbuzz\") \n\t\telseif 0 == (k\u00a0% 5) then\trawset(t, k, \"fizz\") \n\t\telseif 0 == (k\u00a0% 3) then\trawset(t, k, \"buzz\") \n\t\telse \t\t\t\t\t\trawset(t, k, k) end\n\t\treturn t[k]\nend)\n}\n\nlocal fizzbuzz = {}\nsetmetatable(fizzbuzz, mt)\n\nfor i=1,100 do fizzbuzz[i] = i end\nfor i=1,100 do print(fizzbuzz[i]) end\n#!\/usr\/bin\/env luajit\nlocal to=arg[1] or tonumber(arg[1]) or 100\nlocal CF,CB=3,5\nlocal cf,cb=CF,CB\nfor i=1,to do\n\tcf,cb=cf-1,cb-1\n\tif cf~=0 and cb~=0 then\n\t\tio.write(i)\n\telse\n\t\tif cf==0 then\n\t\t\tcf=CF\n\t\t\tio.write(\"Fizz\")\n\t\tend\n\t\tif cb==0 then\n\t\t\tcb=CB\n\t\t\tio.write(\"Buzz\")\n\t\tend\n\tend\n\tio.write(\", \")\nend\n\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":1831}
    {"lang_cluster":"Lua","source_code":"\n\nlocal maxIterations = 250\nlocal minX, maxX, minY, maxY = -2.5, 2.5, -2.5, 2.5\nlocal miX, mxX, miY, mxY\nfunction remap( x, t1, t2, s1, s2 )\n    local f = ( x - t1 ) \/ ( t2 - t1 )\n    local g = f * ( s2 - s1 ) + s1\n    return g;\nend\nfunction drawMandelbrot()\n    local pts, a, as, za, b, bs, zb, cnt, clr = {}\n    for j = 0, hei - 1 do\n        for i = 0, wid - 1 do\n            a = remap( i, 0, wid, minX, maxX )\n            b = remap( j, 0, hei, minY, maxY )\n            cnt = 0; za = a; zb = b\n            while( cnt < maxIterations ) do\n                as = a * a - b * b; bs = 2 * a * b\n                a = za + as; b = zb + bs\n                if math.abs( a ) + math.abs( b ) > 16 then break end\n                cnt = cnt + 1\n            end\n            if cnt == maxIterations then clr = 0\n            else clr = remap( cnt, 0, maxIterations, 0, 255 )\n            end\n            pts[1] = { i, j, clr, clr, 0, 255 }\n            love.graphics.points( pts )\n        end\n    end\nend\nfunction startFractal()\n    love.graphics.setCanvas( canvas ); love.graphics.clear()\n    love.graphics.setColor( 255, 255, 255 )\n    drawMandelbrot(); love.graphics.setCanvas()\nend\nfunction love.load()\n    wid, hei = love.graphics.getWidth(), love.graphics.getHeight()\n    canvas = love.graphics.newCanvas( wid, hei )\n    startFractal()\nend\nfunction love.mousepressed( x, y, button, istouch )\n    if button ==  1 then\n        startDrag = true; miX = x; miY = y\n    else\n        minX = -2.5; maxX = 2.5; minY = minX; maxY = maxX\n        startFractal()\n        startDrag = false\n    end\nend\nfunction love.mousereleased( x, y, button, istouch )\n    if startDrag then\n        local l\n        if x > miX then mxX = x\n        else l = x; mxX = miX; miX = l\n        end\n        if y > miY then mxY = y\n        else l = y; mxY = miY; miY = l\n        end\n        miX = remap( miX, 0, wid, minX, maxX ) \n        mxX = remap( mxX, 0, wid, minX, maxX )\n        miY = remap( miY, 0, hei, minY, maxY ) \n        mxY = remap( mxY, 0, hei, minY, maxY )\n        minX = miX; maxX = mxX; minY = miY; maxY = mxY\n        startFractal()\n    end\nend\nfunction love.draw()\n    love.graphics.draw( canvas )\nend\n-- Mandelbrot set in Lua 6\/15\/2020 db\nlocal charmap = { [0]=\" \", \".\", \":\", \"-\", \"=\", \"+\", \"*\", \"#\", \"%\", \"@\" }\nfor y = -1.3, 1.3, 0.1 do\n  for x = -2.1, 1.1, 0.04 do\n    local zi, zr, i = 0, 0, 0\n    while i < 100 do\n      if (zi*zi+zr*zr >= 4) then break end\n      zr, zi, i = zr*zr-zi*zi+x, 2*zr*zi+y, i+1\n    end\n    io.write(charmap[i%10])\n  end\n  print()\nend\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. It requires the L\u00d6VE 2D Engine for execution. The code also allows for zooming in and out using mouse interactions. It produces an 80x25 ASCII Mandelbrot set with a limited iteration count to fit within two lines of 80 columns.","id":1832}
    {"lang_cluster":"Lua","source_code":"\nfunction sumf(a, ...) return a and a + sumf(...) or 0 end\nfunction sumt(t) return sumf(unpack(t)) end\nfunction prodf(a, ...) return a and a * prodf(...) or 1 end\nfunction prodt(t) return prodf(unpack(t)) end\n\nprint(sumt{1, 2, 3, 4, 5})\nprint(prodt{1, 2, 3, 4, 5})\n\nfunction table.sum(arr, length) \n      --same as if <> then <> else <>\n      return length == 1 and arr[1] or arr[length] + table.sum(arr, length -1)\nend\n\nfunction table.product(arr, length)\n      return length == 1 and arr[1] or arr[length] * table.product(arr, length -1)\nend\n\nt = {1,2,3}\nprint(table.sum(t,#t))\nprint(table.product(t,3))\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":1833}
    {"lang_cluster":"Lua","source_code":"\nfunction isLeapYear(year)\n  return year%4==0 and (year%100~=0 or year%400==0)\nend\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":1834}
    {"lang_cluster":"Lua","source_code":"\n\n-- shift amounts\nlocal s = {\n  7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n  5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20,\n  4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n  6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21\n}\n\n-- constants\nlocal K = {\n  0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,\n  0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,\n  0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,\n  0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,\n  0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,\n  0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,\n  0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,\n  0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,\n  0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,\n  0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,\n  0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,\n  0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,\n  0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,\n  0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n  0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,\n  0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,\n}\n\nlocal function leftRotate(x, c)\n  return (x << c) | (x >> (32-c))\nend\n\nlocal function getInt(byteArray, n)\n  return (byteArray[n+3]<<24) + (byteArray[n+2]<<16) + (byteArray[n+1]<<8) + byteArray[n]\nend\n\n--- converts 32bit integer n to a little endian hex representation\n-- @tparam integer n\nlocal function lE(n)\n  local s = ''\n  for i = 0, 3 do\n    s = ('%s%02x'):format(s, (n>>(i*8))&0xff)\n  end\n  return s\nend\n\n--- md5\n-- @tparam string message\nlocal function md5(message)\n  local a0, b0, c0, d0 = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476\n  local bytes = {message:byte(1, -1)}\n  \n  -- insert 1 bit (and the rest of the byte)\n  table.insert(bytes, 0x80)\n\n  -- pad with zeros until we have *just enough*\n  local p = #bytes%64\n  if p > 56 then\n    p = p - 64\n  end\n  for _ = p+1, 56 do\n    table.insert(bytes, 0)\n  end\n\n  -- insert the initial message length, in little-endian\n  local len = ((#message)<<3)&0xffffffffffffffff -- length in bits\n  for i = 0, 7 do\n    table.insert(bytes, (len>>(i*8))&0xff)\n  end\n\n  \n  for i = 0, #bytes\/\/64-1 do\n    local a, b, c, d = a0, b0, c0, d0\n    for j = 0, 63 do\n      local F, g\n      -- permutate\n      if j <= 15 then\n        F = (b & c) | (~b & d)\n        g = j\n      elseif j <= 31 then\n        F = (d & b) | (~d & c)\n        g = (5*j + 1) & 15\n      elseif j <= 47 then\n        F = b ~ c ~ d\n        g = (3*j + 5) & 15\n      else\n        F = c ~ (b | ~d)\n        g = (7*j) & 15\n      end\n\n      F = (F + a + K[j+1] + getInt(bytes, i*64+g*4+1))&0xffffffff\n      -- shuffle\n      a = d\n      d = c\n      c = b\n      b = (b + leftRotate(F, s[j+1]))&0xffffffff\n    end\n    -- update internal state\n    a0 = (a0 + a)&0xffffffff\n    b0 = (b0 + b)&0xffffffff\n    c0 = (c0 + c)&0xffffffff\n    d0 = (d0 + d)&0xffffffff\n  end\n\n  -- lua doesn't support any other byte strings. Could convert to a wacky string but this is more printable.\n  return lE(a0)..lE(b0)..lE(c0)..lE(d0)\nend\n\nlocal demo = {\n  [\"\"] = \"d41d8cd98f00b204e9800998ecf8427e\",  \n  [\"a\"] = \"0cc175b9c0f1b6a831c399e269772661\",\n  [\"abc\"] = \"900150983cd24fb0d6963f7d28e17f72\",\n  [\"message digest\"] = \"f96b697d7cb7938d525a2f31aaf161d0\",\n  [\"abcdefghijklmnopqrstuvwxyz\"] = \"c3fcd3d76192e4007dfb496cca67e13b\",\n  [\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"] = \"d174ab98d277d9f5a5611c2c9f419d9f\",\n  [\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"] = \"57edf4a22be3c955ac49da2e2107b67a\",\n}\n\nfor k, v in pairs(demo) do\n  local m = md5(k)\n  print((\"%s [%2s] <== \\\"%s\\\"\"):format(m, m==v and 'OK' or '', k))\nend\n\n\nf96b697d7cb7938d525a2f31aaf161d0 [OK] <== \"message digest\"\nd174ab98d277d9f5a5611c2c9f419d9f [OK] <== \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\nc3fcd3d76192e4007dfb496cca67e13b [OK] <== \"abcdefghijklmnopqrstuvwxyz\"\nd41d8cd98f00b204e9800998ecf8427e [OK] <== \"\"\n900150983cd24fb0d6963f7d28e17f72 [OK] <== \"abc\"\n57edf4a22be3c955ac49da2e2107b67a [OK] <== \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"\n0cc175b9c0f1b6a831c399e269772661 [OK] <== \"a\"\n\n","human_summarization":"implement the MD5 Message Digest Algorithm directly without using built-in or external hashing libraries. The implementation produces a correct message digest for an input string. The code also handles bit manipulation, unsigned integers, and works with little-endian data. It also pays attention to details such as boundary conditions, padding, endianness, and data layout. The code includes verification strings and hashes from RFC 1321 for testing.","id":1835}
    {"lang_cluster":"Lua","source_code":"\nprint( \"Fire\", \"Police\", \"Sanitation\" )\nsol = 0\nfor f = 1, 7 do\n    for p = 1, 7 do\n        for s = 1, 7 do\n            if s + p + f == 12 and p % 2 == 0 and f ~= p and f ~= s and p ~= s then\n                print( f, p, s ); sol = sol + 1\n            end\n        end\n    end\nend\nprint( string.format( \"\\n%d solutions found\", sol ) )\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":1836}
    {"lang_cluster":"Lua","source_code":"\n\na = \"string\"\nb = a\nprint(a == b) -->true\nprint(b) -->string\n\n","human_summarization":"distinguish between copying a string's content and creating an additional reference to an existing string in Lua, considering that Lua strings are immutable.","id":1837}
    {"lang_cluster":"Lua","source_code":"\nfunction m(n) return n > 0 and n - f(m(n-1)) or 0 end\nfunction f(n) return n > 0 and n - m(f(n-1)) or 1 end\n\n\nlocal m,n\nfunction m(n) return n > 0 and n - f(m(n-1)) or 0 end\nfunction f(n) return n > 0 and n - m(f(n-1)) or 1 end\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions take an integer as input and return the corresponding sequence value. If the input is 0, the Female function returns 1 and the Male function returns 0. For any other positive integer, the Female function returns the input minus the Male function's output for the previous Female function's output. Similarly, the Male function returns the input minus the Female function's output for the previous Male function's output. The functions are locally scoped and forward declared.","id":1838}
    {"lang_cluster":"Lua","source_code":"\nmath.randomseed(os.time())\nlocal a = {1,2,3}\nprint(a[math.random(1,#a)])\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":1839}
    {"lang_cluster":"Lua","source_code":"\nfunction decodeChar(hex)\n\treturn string.char(tonumber(hex,16))\nend\n\nfunction decodeString(str)\n\tlocal output, t = string.gsub(str,\"%%(%x%x)\",decodeChar)\n\treturn output\nend\n\n-- will print \"http:\/\/foo bar\/\"\nprint(decodeString(\"http%3A%2F%2Ffoo%20bar%2F\"))\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":1840}
    {"lang_cluster":"Lua","source_code":"\n\nfunction binarySearch (list,value)\n    local low = 1\n    local high = #list\n    while low <= high do\n        local mid = math.floor((low+high)\/2)\n        if list[mid] > value then high = mid - 1\n        elseif list[mid] < value then low = mid + 1\n        else return mid\n        end\n    end\n    return false\nend\n\n\nfunction binarySearch (list, value)\n    local function search(low, high)\n        if low > high then return false end\n        local mid = math.floor((low+high)\/2)\n        if list[mid] > value then return search(low,mid-1) end\n        if list[mid] < value then return search(mid+1,high) end\n        return mid\n    end\n    return search(1,#list)\nend\n","human_summarization":"The code implements a binary search algorithm, which finds a specific value in a sorted integer array. The algorithm divides the range of values into halves until the desired value is found. It includes both recursive and iterative implementations, and it handles cases where there are multiple equal values. The code also identifies the leftmost and rightmost insertion points for the given value. Additionally, it includes a fix for potential overflow bugs.","id":1841}
    {"lang_cluster":"Lua","source_code":"\n\nprint( \"Program name:\", arg[0] )\n\nprint \"Arguments:\"\nfor i = 1, #arg do\n    print( i,\" \", arg[i] )\nend\n\n","human_summarization":"\"Code retrieves and prints command-line arguments given to the program using the global table arg in Lua scripting language, without using argc and argv conventions. It also parses these arguments intelligently.\"","id":1842}
    {"lang_cluster":"Lua","source_code":"\n\nfunction degToRad( d )\n    return d * 0.01745329251\nend\n\nfunction love.load()\n    g = love.graphics\n    rodLen, gravity, velocity, acceleration = 260, 3, 0, 0\n    halfWid, damp = g.getWidth() \/ 2, .989\n    posX, posY, angle = halfWid\n    TWO_PI, angle = math.pi * 2, degToRad( 90 )\nend\n\nfunction love.update( dt )\n    acceleration = -gravity \/ rodLen * math.sin( angle )\n    angle = angle + velocity; if angle > TWO_PI then angle = 0 end\n    velocity = velocity + acceleration\n    velocity = velocity * damp\n    posX = halfWid + math.sin( angle ) * rodLen\n    posY = math.cos( angle ) * rodLen\nend\n\nfunction love.draw()\n    g.setColor( 250, 0, 250 )\n    g.circle( \"fill\", halfWid, 0, 8 )\n    g.line( halfWid, 4, posX, posY )\n    g.setColor( 250, 100, 20 )\n    g.circle( \"fill\", posX, posY, 20 )\nend\n\n","human_summarization":"Creates and animates a simple physical model of a gravity pendulum using the L\u00d6VE 2D Engine.","id":1843}
    {"lang_cluster":"Lua","source_code":"\n\nlocal json = require(\"json\")\n\nlocal json_data = [=[[\n    42,\n    3.14159,\n    [ 2, 4, 8, 16, 32, 64, \"apples\", \"bananas\", \"cherries\" ],\n    { \"H\": 1, \"He\": 2, \"X\": null, \"Li\": 3 },\n    null,\n    true,\n    false\n]]=]\n\nprint(\"Original JSON: \" .. json_data)\nlocal data = json.decode(json_data)\njson.util.printValue(data, 'Lua')\nprint(\"JSON re-encoded: \" .. json.encode(data))\n\nlocal data = {\n    42,\n    3.14159,\n    {\n        2, 4, 8, 16, 32, 64,\n        \"apples\",\n        \"bananas\",\n        \"cherries\"\n    },\n    {\n        H = 1,\n        He = 2,\n        X = json.util.null(),\n        Li = 3\n    },\n    json.util.null(),\n    true,\n    false\n}\n\nprint(\"JSON from new Lua data: \" .. json.encode(data))\n\n\n\n","human_summarization":"The code loads a JSON string into a data structure and creates a new data structure, serializing it into JSON. It uses objects and arrays, ensuring the JSON is valid. In Lua, it handles null values in JSON using the luajson library, specifically the json.util.null function.","id":1844}
    {"lang_cluster":"Lua","source_code":"\nfunction nroot(root, num)\n  return num^(1\/root)\nend\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":1845}
    {"lang_cluster":"Lua","source_code":"\n\nsocket = require \"socket\"\nprint( socket.dns.gethostname() )\n\n","human_summarization":"Determines and outputs the hostname of the system where the routine is executed using LuaSocket.","id":1846}
    {"lang_cluster":"Lua","source_code":"\nfunction leoNums (n, L0, L1, add)\n  local L0, L1, add = L0 or 1, L1 or 1, add or 1\n  local lNums, nextNum = {L0, L1}\n  while #lNums < n do\n    nextNum = lNums[#lNums] + lNums[#lNums - 1] + add\n    table.insert(lNums, nextNum)\n  end\n  return lNums\nend\n\nfunction show (msg, t)\n  print(msg .. \":\")\n  for i, x in ipairs(t) do\n    io.write(x .. \" \")\n  end\n  print(\"\\n\")\nend\n\nshow(\"Leonardo numbers\", leoNums(25))\nshow(\"Fibonacci numbers\", leoNums(25, 0, 1, 0))\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":1847}
    {"lang_cluster":"Lua","source_code":"\nlocal function help()\n\tprint [[\n The 24 Game\n\n Given any four digits in the range 1 to 9, which may have repetitions,\n Using just the +, -, *, and \/ operators; and the possible use of\n brackets, (), show how to make an answer of 24.\n\n An answer of \"q\" will quit the game.\n An answer of \"!\" will generate a new set of four digits.\n\n Note: you cannot form multiple digit numbers from the supplied digits,\n so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n ]]\nend\n\nlocal function generate(n)\n\tresult = {}\n\tfor i=1,n do\n\t\tresult[i] = math.random(1,9)\n\tend\n\treturn result\nend\n\nlocal function check(answer, digits)\n\tlocal adig = {}\n\tlocal ddig = {}\n\tlocal index\n\tlocal lastWasDigit = false\n\tfor i=1,9 do adig[i] = 0 ddig[i] = 0 end\n\tallowed = {['(']=true,[')']=true,[' ']=true,['+']=true,['-']=true,['*']=true,['\/']=true,['\\t']=true,['1']=true,['2']=true,['3']=true,['4']=true,['5']=true,['6']=true,['7']=true,['8']=true,['9']=true}\n\tfor i=1,string.len(answer) do\n\t\tif not allowed[string.sub(answer,i,i)] then\n\t\t\treturn false\n\t\tend\n\t\tindex = string.byte(answer,i)-48\n\t\tif index > 0 and index < 10 then\n\t\t\tif lastWasDigit then\n\t\t\t\treturn false\n\t\t\tend\n\t\t\tlastWasDigit = true\n\t\t\tadig[index] = adig[index] + 1\n\t\telse\n\t\t\tlastWasDigit = false\n\t\tend\n\tend\n\tfor i,digit in next,digits do\n\t\tddig[digit] = ddig[digit]+1\n\tend\n\tfor i=1,9 do\n\t\tif adig[i] ~= ddig[i] then\n\t\t\treturn false\n\t\tend\n\tend\n\treturn loadstring('return '..answer)()\nend\n\nlocal function game24()\n\thelp()\n\tmath.randomseed(os.time())\n\tmath.random()\n\tlocal digits = generate(4)\n\tlocal trial = 0\n\tlocal answer = 0\n\tlocal ans = false\n\tio.write 'Your four digits:'\n\tfor i,digit in next,digits do\n\t\tio.write (' ' .. digit)\n\tend\n\tprint()\n\twhile ans ~= 24 do\n\t\ttrial = trial + 1\n\t\tio.write(\"Expression \"..trial..\": \")\n\t\tanswer = io.read()\n\t\tif string.lower(answer) == 'q' then\n\t\t\tbreak\n\t\tend\n\t\tif answer == '!' then\n\t\t\tdigits = generate(4)\n\t\t\tio.write (\"New digits:\")\n\t\t\tfor i,digit in next,digits do\n\t\t\t\tio.write (' ' .. digit)\n\t\t\tend\n\t\t\tprint()\n\t\telse\n\t\t\tans = check(answer,digits)\n\t\t\tif ans == false then\n\t\t\t\tprint ('The input '.. answer ..' was wonky!')\n\t\t\telse\n\t\t\t\tprint (' = '.. ans)\n\t\t\t\tif ans == 24 then\n\t\t\t\t\tprint (\"Thats right!\")\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\nend\ngame24()\n\n\nfunction twentyfour()\n   print [[\n The 24 Game\n \n Given any four digits in the range 1 to 9, which may have repetitions,\n Using just the +, -, *, and \/ operators; and the possible use of\n brackets, (), show how to make an answer of 24.\n \n An answer of \"q\" will quit the game.\n An answer of \"!\" will generate a new set of four digits.\n \n Note: you cannot form multiple digit numbers from the supplied digits,\n so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n \n ]]\n   expr = re.compile[[   --matches properly formatted infix expressions and returns all numerals as captures\n         expr <- (!.) \/ (<paren> \/ <number>) (<ws> <oper> <ws> <expr>)?\n         number <- {[0-9]}\n         ws <- \" \"*\n         oper <- [-+\/*]\n         paren <- \"(\" <ws> <expr> <ws> \")\"   ]]\n   local val_t = {math.random(9), math.random(9), math.random(9), math.random(9)}\n   table.sort(val_t)\n   print(\"the digits are \" .. table.concat(val_t, \", \"))\n   local ex = io.read()\n   a, b, c, d, e = expr:match(ex)\n   if a and b and c and d and not e then --if there is a fifth numeral the player is cheating\n      local digs = {a + 0, b + 0, c + 0, d + 0}\n      local flag = false -- (terrorism!)\n      table.sort(digs)\n      for i = 1, 4 do\n\t   flag = digs[i] ~= val_t[i] and not print\"Wrong digits!\" or flag\n      end\n      if not flag and loadstring(\"return \" .. ex)() == 24 then\n         print\"You win!\"\n      else\n         print\"You lose.\"\n      end\n   else print\"wat\" --expression could not be interpreted as arithmetic\n   end\nend\ntwentyfour()\n\n","human_summarization":"The code generates four random digits from 1 to 9 and prompts the player to form an arithmetic expression using these digits exactly once. The expression should evaluate to 24 using only multiplication, division, addition, and subtraction. The division operation preserves remainders. The program checks and evaluates the player's expression, but does not generate or test the feasibility of the expression itself. The order of the digits in the expression doesn't need to match the original order.","id":1848}
    {"lang_cluster":"Lua","source_code":"\nlocal C, Ct, R, Cf, Cc = lpeg.C, lpeg.Ct, lpeg.R, lpeg.Cf, lpeg.Cc\nastable = Ct(C(1)^0)\n\nfunction compress(t)\n    local ret = {}\n    for i, v in ipairs(t) do\n      if t[i-1] and v == t[i-1] then\n        ret[#ret - 1] = ret[#ret - 1] + 1\n      else\n        ret[#ret + 1] = 1\n        ret[#ret + 1] = v\n      end\n    end\n    t = ret\n    return table.concat(ret)\nend\nq = io.read()\nprint(compress(astable:match(q))) \n\nundo = Ct((Cf(Cc\"0\" * C(R\"09\")^1, function(a, b) return 10 * a + b end) * C(R\"AZ\"))^0)\n\nfunction decompress(s)\n  t = undo:match(s)\n  local ret = \"\"\n  for i = 1, #t - 1, 2 do\n    for _ = 1, t[i] do\n      ret = ret .. t[i+1]\n    end\n  end\n  return ret\nend\n\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":1849}
    {"lang_cluster":"Lua","source_code":"\na = \"hello \"\nprint(a .. \"world\")\nc = a .. \"world\"\nprint(c)\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":1850}
    {"lang_cluster":"Lua","source_code":"\nfunction encodeChar(chr)\n\treturn string.format(\"%%%X\",string.byte(chr))\nend\n\nfunction encodeString(str)\n\tlocal output, t = string.gsub(str,\"[^%w]\",encodeChar)\n\treturn output\nend\n\n-- will print \"http%3A%2F%2Ffoo%20bar%2F\"\nprint(encodeString(\"http:\/\/foo bar\/\"))\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":1851}
    {"lang_cluster":"Lua","source_code":"\n\nfunction sort(word)\n  local bytes = {word:byte(1, -1)}\n  table.sort(bytes)\n  return string.char(table.unpack(bytes))\nend\n\n-- Read in and organize the words.\n-- word_sets[<alphabetized_letter_list>] = {<words_with_those_letters>}\nlocal word_sets = {}\nlocal max_size = 0\nfor word in io.lines('unixdict.txt') do\n  local key = sort(word)\n  if word_sets[key] == nil then word_sets[key] = {} end\n  table.insert(word_sets[key], word)\n  max_size = math.max(max_size, #word_sets[key])\nend\n\n-- Print out the answer sets.\nfor _, word_set in pairs(word_sets) do\n  if #word_set == max_size then\n    for _, word in pairs(word_set) do io.write(word .. ' ') end\n    print('')  -- Finish with a newline.\n  end\nend\n\n\n","human_summarization":"\"Output: The code identifies sets of words from the provided URL that are anagrams, i.e., they share the same characters but in a different order. It specifically finds the sets with the most words in them. The code assumes the use of a networking library for Lua, as Lua's core library does not support network functionality.\"","id":1852}
    {"lang_cluster":"Lua","source_code":"\n\nlocal function carpet(n, f)\n  print(\"n = \" .. n)\n  local function S(x, y)\n    if x==0 or y==0 then return true\n    elseif x%3==1 and y%3==1 then return false end\n    return S(x\/\/3, y\/\/3)\n  end\n  for y = 0, 3^n-1 do\n    for x = 0, 3^n-1 do\n      io.write(f(S(x, y)))\n    end\n    print()\n  end\n  print()\nend\n\nfor n = 0, 4 do\n  carpet(n, function(b) return b and \"\u25a0 \" or \"  \" end)\nend\n\n\n","human_summarization":"generate an ASCII or graphical representation of a Sierpinski carpet of a given order N. The representation uses specific placement of whitespace and non-whitespace characters. The code utilizes recursion and tail calls.","id":1853}
    {"lang_cluster":"Lua","source_code":"\n\nlocal build_freqtable = function (data)\n  local freq = { }\n\n  for i = 1, #data do\n    local cur = string.sub (data, i, i)\n    local count = freq [cur] or 0\n    freq [cur] = count + 1\n  end\n\n  local nodes = { }\n  for w, f in next, freq do\n    nodes [#nodes + 1] = { word = w, freq = f }\n  end\n\n  table.sort (nodes, function (a, b) return a.freq > b.freq end) --- reverse order!\n\n  return nodes\nend\n\nlocal build_hufftree = function (nodes)\n  while true do\n    local n = #nodes\n    local left = nodes [n]\n    nodes [n] = nil\n\n    local right = nodes [n - 1]\n    nodes [n - 1] = nil\n\n    local new = { freq = left.freq + right.freq, left = left, right = right }\n\n    if n == 2 then return new end\n\n    --- insert new node at correct priority\n    local prio = 1\n    while prio < #nodes and nodes [prio].freq > new.freq do\n      prio = prio + 1\n    end\n    table.insert (nodes, prio, new)\n  end\nend\n\nlocal print_huffcodes do\n  local rec_build_huffcodes\n  rec_build_huffcodes = function (node, bits, acc)\n    if node.word == nil then\n      rec_build_huffcodes (node.left,  bits .. \"0\", acc)\n      rec_build_huffcodes (node.right, bits .. \"1\", acc)\n      return acc\n    else --- leaf\n      acc [#acc + 1] = { node.freq, node.word, bits }\n    end\n    return acc\n  end\n\n  print_huffcodes = function (root)\n    local codes = rec_build_huffcodes (root, \"\", { })\n    table.sort (codes, function (a, b) return a [1] < b [1] end)\n    print (\"frequency\\tword\\thuffman code\")\n    for i = 1, #codes do\n      print (string.format (\"%9d\\t\u2018%s\u2019\\t\u201c%s\u201d\", table.unpack (codes [i])))\n    end\n  end\nend\n\n\nlocal huffcode = function (data)\n  local nodes = build_freqtable (data)\n  local huff = build_hufftree (nodes)\n  print_huffcodes (huff)\n  return 0\nend\n\nreturn huffcode \"this is an example for huffman encoding\"\n\nfrequency\tword\thuffman code\n        1\t\u2018g\u2019\t\u201c01111\u201d\n        1\t\u2018p\u2019\t\u201c01011\u201d\n        1\t\u2018d\u2019\t\u201c01100\u201d\n        1\t\u2018c\u2019\t\u201c01101\u201d\n        1\t\u2018t\u2019\t\u201c01010\u201d\n        1\t\u2018r\u2019\t\u201c10000\u201d\n        1\t\u2018u\u2019\t\u201c11110\u201d\n        1\t\u2018x\u2019\t\u201c10001\u201d\n        1\t\u2018l\u2019\t\u201c01110\u201d\n        2\t\u2018o\u2019\t\u201c11111\u201d\n        2\t\u2018m\u2019\t\u201c0011\u201d\n        2\t\u2018h\u2019\t\u201c0010\u201d\n        2\t\u2018s\u2019\t\u201c0100\u201d\n        3\t\u2018i\u2019\t\u201c1101\u201d\n        3\t\u2018f\u2019\t\u201c1110\u201d\n        3\t\u2018a\u2019\t\u201c1100\u201d\n        3\t\u2018e\u2019\t\u201c1001\u201d\n        4\t\u2018n\u2019\t\u201c000\u201d\n        6\t\u2018 \u2019\t\u201c101\u201d\n\n","human_summarization":"The code takes a string input, calculates the frequency of each character, and generates a Huffman encoding for each character. It constructs a Huffman tree based on character frequencies and assigns binary codes to each character, ensuring that more frequent characters have shorter codes. The output is a table of characters and their corresponding Huffman encodings.","id":1854}
    {"lang_cluster":"Lua","source_code":"\nrequire\"iuplua\"\nl = iup.label{title=\"There have been no clicks yet.\"}\nb = iup.button{title=\"Click me!\"}\nclicks = 0\nfunction b:button_cb()\n  clicks = clicks + 1\n  l.title = \"There have been \" .. clicks\/2 .. \" clicks so far.\" --yes, this is correct.\nend\ndlg = iup.dialog{iup.vbox{l, b}, title=\"Simple Windowed Application\"}\ndlg:show()\n\nif (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then\n  iup.MainLoop()\nend\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":1855}
    {"lang_cluster":"Lua","source_code":"\n\n-- Import module\nlocal sql = require(\"ljsqlite3\")\n\n-- Open connection to database file\nlocal conn = sql.open(\"address.sqlite\")\n\n-- Create address table unless it already exists\nconn:exec[[\nCREATE TABLE IF NOT EXISTS address(\n  id INTEGER PRIMARY KEY AUTOINCREMENT,\n  street TEXT NOT NULL, \n  city TEXT NOT NULL, \n  state TEXT NOT NULL, \n  zip TEXT NOT NULL)\n]]\n\n-- Explicitly close connection\nconn:close()\n\n","human_summarization":"\"Create a table in a database to store US postal addresses, including fields for unique identifier, street address, city, state code, and zipcode. The code also demonstrates how to open a database connection in non-database languages using LJSQLite3.\"","id":1856}
    {"lang_cluster":"Lua","source_code":"\nfor i=10,0,-1 do\n  print(i)\nend\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":1857}
    {"lang_cluster":"Lua","source_code":"\nfunction Encrypt( _msg, _key )    \n    local msg = { _msg:upper():byte( 1, -1 ) }\n    local key = { _key:upper():byte( 1, -1 ) }    \n    local enc = {}\n\n    local j, k = 1, 1\n    for i = 1, #msg do    \n        if msg[i] >= string.byte('A') and msg[i] <= string.byte('Z') then\n            enc[k] = ( msg[i] + key[j] - 2*string.byte('A') ) % 26 + string.byte('A')\n            \n            k = k + 1\n            if j == #key then j = 1 else j = j + 1 end\n        end\n    end\n    \n    return string.char( unpack(enc) )\nend\n\nfunction Decrypt( _msg, _key )\n    local msg = { _msg:byte( 1, -1 ) }\n    local key = { _key:upper():byte( 1, -1 ) }      \n    local dec = {}\n\n    local j = 1\n    for i = 1, #msg do            \n       dec[i] = ( msg[i] - key[j] + 26 ) % 26 + string.byte('A')\n            \n       if j == #key then j = 1 else j = j + 1 end\n    end    \n    \n    return string.char( unpack(dec) )\nend\n\n\noriginal = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nkey = \"VIGENERECIPHER\";\n\nencrypted = Encrypt( original, key )\ndecrypted = Decrypt( encrypted, key )\n\nprint( encrypted )\nprint( decrypted )\n\nWMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\nBEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":1858}
    {"lang_cluster":"Lua","source_code":"\nfor i=2,9,2 do\n  print(i)\nend\n\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":1859}
    {"lang_cluster":"Lua","source_code":"\nfunction sum(var, a, b, str)\n  local ret = 0\n  for i = a, b do\n    ret = ret + setfenv(loadstring(\"return \"..str), {[var] = i})()\n  end\n  return ret\nend\nprint(sum(\"i\", 1, 100, \"1\/i\"))\n\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":1860}
    {"lang_cluster":"Lua","source_code":"\nWorks with: L\u00d6VE version 11.0 or higher\nlocal clr =  {}\nfunction drawMSquares()\n\tlocal points = {}\n\tfor y = 0, hei-1 do\n\t\tfor x = 0, wid-1 do\n\t\t\tlocal idx = bit.bxor(x, y)%256\n\t\t\tlocal r, g, b = clr[idx][1], clr[idx][2], clr[idx][3]\n\t\t\tlocal point = {x+1, y+1, r\/255, g\/255, b\/255, 1}\n\t\t\ttable.insert (points, point)\n\t\tend\n\tend\n\tlove.graphics.points(points)\nend\n\nfunction createPalette()\n\tfor i = 0, 255 do\n\t\tclr[i] = {i*2.8%256, i*3.2%256, i*1.5%256}\n\tend\nend\n\nfunction love.load()\n\twid, hei = 256, 256\n\tlove.window.setMode(wid, hei)\n\tcanvas = love.graphics.newCanvas()\n\tlove.graphics.setCanvas(canvas)\n\t\tcreatePalette()\n\t\tdrawMSquares()\n\tlove.graphics.setCanvas()\nend\n\nfunction love.draw()\n\tlove.graphics.setColor(1,1,1)\n\tlove.graphics.draw(canvas)\nend\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":1861}
    {"lang_cluster":"Lua","source_code":"\nWorks with: Lua version 5.1\nmath.randomseed( os.time() )\n\n-- Fisher-Yates shuffle from http:\/\/santos.nfshost.com\/shuffling.html\nfunction shuffle(t)\n  for i = 1, #t - 1 do\n    local r = math.random(i, #t)\n    t[i], t[r] = t[r], t[i]\n  end\nend\n\n-- builds a width-by-height grid of trues\nfunction initialize_grid(w, h)\n  local a = {}\n  for i = 1, h do\n    table.insert(a, {})\n    for j = 1, w do\n      table.insert(a[i], true)\n    end\n  end\n  return a\nend\n\n-- average of a and b\nfunction avg(a, b)\n  return (a + b) \/ 2\nend\n\n\ndirs = {\n  {x = 0, y = -2}, -- north\n  {x = 2, y = 0}, -- east\n  {x = -2, y = 0}, -- west\n  {x = 0, y = 2}, -- south\n}\n\nfunction make_maze(w, h)\n  w = w or 16\n  h = h or 8\n\n  local map = initialize_grid(w*2+1, h*2+1)\n\n  function walk(x, y)\n    map[y][x] = false\n\n    local d = { 1, 2, 3, 4 }\n    shuffle(d)\n    for i, dirnum in ipairs(d) do\n      local xx = x + dirs[dirnum].x\n      local yy = y + dirs[dirnum].y\n      if map[yy] and map[yy][xx] then\n        map[avg(y, yy)][avg(x, xx)] = false\n        walk(xx, yy)\n      end\n    end\n  end\n\n  walk(math.random(1, w)*2, math.random(1, h)*2)\n\n  local s = {}\n  for i = 1, h*2+1 do\n    for j = 1, w*2+1 do\n      if map[i][j] then\n        table.insert(s, '#')\n      else\n        table.insert(s, ' ')\n      end\n    end\n    table.insert(s, '\\n')\n  end\n  return table.concat(s)\nend\n\nprint(make_maze())\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":1862}
    {"lang_cluster":"Lua","source_code":"a = {}\nn = 1000\nlen = math.modf( 10 * n \/ 3 )\n\nfor j = 1, len do\n    a[j] = 2\nend\nnines = 0\npredigit = 0\nfor j = 1, n do\n    q = 0\n    for i = len, 1, -1 do\n        x = 10 * a[i] + q * i\n        a[i] = math.fmod( x, 2 * i - 1 )\n        q = math.modf( x \/ ( 2 * i - 1 ) )\n    end\n    a[1] = math.fmod( q, 10 )\n    q = math.modf( q \/ 10 )\n    if q == 9 then\n        nines = nines + 1\n    else\n        if q == 10 then\n            io.write( predigit + 1 )\n            for k = 1, nines do\n                io.write(0)\n            end\n            predigit = 0\n            nines = 0\n        else\n            io.write( predigit )\n            predigit = q\n            if nines ~= 0 then\n                for k = 1, nines do\n                    io.write( 9 )\n                end\n                nines = 0\n            end\n        end\n    end\nend\nprint( predigit )\n\n03141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086 ...\n","human_summarization":"are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.","id":1863}
    {"lang_cluster":"Lua","source_code":"\n\nfunction arraycompare(a, b)\n    for i = 1, #a do\n        if b[i] == nil then\n            return true\n        end\n        if a[i] ~= b[i] then\n            return a[i] < b[1]\n        end\n    end\n    return true\nend\n\n\nfunction randomarray()\n    local t = {}\n    for i = 1, math.random(1, 10) do\n        t[i] = math.random(1, 10)\n    end\n    return t\nend\n\nmath.randomseed(os.time())\n\nfor i = 1, 10 do\n    local a = randomarray()\n    local b = randomarray()\n\n    print(\n        string.format(\"{%s} %s {%s}\",\n        table.concat(a, ', '),\n        arraycompare(a, b) and \"<=\" or \">\",\n        table.concat(b, ', ')))\nend\n\n\n","human_summarization":"implement a function to compare two numerical lists or arrays lexicographically. The function returns true if the first list should be ordered before the second, and false otherwise. It compares elements sequentially until one list runs out of elements. If the first list ends first, the function returns true, but if the second list or both lists end simultaneously, it returns false. This function is particularly useful in Lua, where tables with numerical indices do not support comparison by default.","id":1864}
    {"lang_cluster":"Lua","source_code":"\nfunction ack(M,N)\n    if M == 0 then return N + 1 end\n    if N == 0 then return ack(M-1,1) end\n    return ack(M-1,ack(M, N-1))\nend\n \n#!\/usr\/bin\/env luajit\nlocal gmp = require 'gmp' ('libgmp')\nlocal mpz, \t\tz_mul, \t\tz_add, \t\tz_add_ui, \t\tz_set_d = \n\tgmp.types.z, gmp.z_mul,\tgmp.z_add,\tgmp.z_add_ui, \tgmp.z_set_d\nlocal z_cmp, \tz_cmp_ui, \t\tz_init_d, \t\t\tz_set=\n\tgmp.z_cmp,\tgmp.z_cmp_ui, \tgmp.z_init_set_d, \tgmp.z_set\nlocal printf = gmp.printf\n\nlocal function ack(i,n)\n\tlocal nxt=setmetatable({},  {__index=function(t,k) local z=mpz() z_init_d(z, 0) t[k]=z return z end})\n\tlocal goal=setmetatable({}, {__index=function(t,k) local o=mpz() z_init_d(o, 1) t[k]=o return o end})\n\tgoal[i]=mpz() z_init_d(goal[i], -1)\n\tlocal v=mpz() z_init_d(v, 0) \n\tlocal ic\n\tlocal END=n+1\n\tlocal ntmp,gtmp\n\trepeat\n\t\tic=0\n\t\tntmp,gtmp=nxt[ic], goal[ic]\n\t\tz_add_ui(v, ntmp, 1)\n\t\twhile z_cmp(ntmp, gtmp) == 0 do\n\t\t\tz_set(gtmp,v)\n\t\t\tz_add_ui(ntmp, ntmp, 1)\n\t\t\tnxt[ic], goal[ic]=ntmp, gtmp\n\t\t\tic=ic+1\n\t\t\tntmp,gtmp=nxt[ic], goal[ic]\n\t\tend\n\t\tz_add_ui(ntmp, ntmp, 1)\n\t\tnxt[ic]=ntmp\n\tuntil z_cmp_ui(nxt[i], END) == 0\n\treturn v\nend\n\nif #arg<1 then\n\tprint(\"Ackermann: \"..arg[0]..\" <num1> [num2]\")\nelse\n\tprintf(\"%Zd\\n\", ack(tonumber(arg[1]), arg[2] and tonumber(arg[2]) or 0))\nend\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":1865}
    {"lang_cluster":"Lua","source_code":"\n\ngamma, coeff, quad, qui, set = 0.577215664901, -0.65587807152056, -0.042002635033944, 0.16653861138228,\t-0.042197734555571\nfunction recigamma(z)\n  return z + gamma * z^2 + coeff * z^3 + quad * z^4 + qui * z^5 + set * z^6\nend\n\nfunction gammafunc(z)\n  if z == 1 then return 1\n  elseif math.abs(z) <= 0.5 then return 1 \/ recigamma(z)\n  else return (z - 1) * gammafunc(z-1)\n  end\nend\n\n","human_summarization":"Implement and compare the Gamma function using built-in\/library function and other algorithms like Lanczos approximation, Stirling's approximation, and Reciprocal gamma function for small values. The Gamma function is computed through numerical integration.","id":1866}
    {"lang_cluster":"Lua","source_code":"\nN = 8\n\n-- We'll use nil to indicate no queen is present.\ngrid = {}\nfor i = 0, N do\n  grid[i] = {}\nend\n\nfunction can_find_solution(x0, y0)\n  local x0, y0 = x0 or 0, y0 or 1  -- Set default vals (0, 1).\n  for x = 1, x0 - 1 do\n    if grid[x][y0] or grid[x][y0 - x0 + x] or grid[x][y0 + x0 - x] then\n      return false\n    end\n  end\n  grid[x0][y0] = true\n  if x0 == N then return true end\n  for y0 = 1, N do\n    if can_find_solution(x0 + 1, y0) then return true end\n  end\n  grid[x0][y0] = nil\n  return false\nend\n\nif can_find_solution() then\n  for y = 1, N do\n    for x = 1, N do\n      -- Print \"|Q\" if grid[x][y] is true; \"|_\" otherwise.\n      io.write(grid[x][y] and \"|Q\" or \"|_\")\n    end\n    print(\"|\")\n  end\nelse\n  print(string.format(\"No solution for %d queens.\\n\", N))\nend\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":1867}
    {"lang_cluster":"Lua","source_code":"\na = {1, 2, 3}\nb = {4, 5, 6}\n\nfor _, v in pairs(b) do\n    table.insert(a, v)\nend\n\nprint(table.concat(a, \", \"))\n\n\n","human_summarization":"demonstrate how to concatenate two arrays.","id":1868}
    {"lang_cluster":"Lua","source_code":"\n\nitems = {\n    {\"map\", 9, 150},\n    {\"compass\", 13, 35},\n    {\"water\", 153, 200},\n    {\"sandwich\", 50, 160},\n    {\"glucose\", 15, 60},\n    {\"tin\", 68, 45},\n    {\"banana\", 27, 60},\n    {\"apple\", 39,  40},\n    {\"cheese\", 23, 30},\n    {\"beer\", 52, 10},\n    {\"suntan cream\", 11, 70},\n    {\"camera\", 32, 30},\n    {\"t-shirt\", 24, 15},\n    {\"trousers\", 48, 10},\n    {\"umbrella\", 73, 40},\n    {\"waterproof trousers\", 42, 70},\n    {\"waterproof overclothes\", 43, 75},\n    {\"note-case\", 22, 80},\n    {\"sunglasses\", 7, 20},\n    {\"towel\", 18, 12},\n    {\"socks\", 4, 50},\n    {\"book\", 30, 10},\n}\n\nlocal unpack = table.unpack\n\nfunction m(i, w)\n    if i<1 or w==0 then\n        return 0, {}\n    else\n        local _, wi, vi = unpack(items[i])\n        if wi > w then\n            return mm(i - 1, w)\n        else\n            local vn, ln = mm(i - 1, w)\n            local vy, ly = mm(i - 1, w - wi)\n            if vy + vi > vn then\n                return vy + vi, { i, ly }\n            else\n                return vn, ln\n            end\n        end\n    end\nend\n\nlocal memo, mm_calls = {}, 0\nfunction mm(i, w) -- memoization function for m\n    mm_calls = mm_calls + 1\n    local key = 10000*i + w\n    local result = memo[key]\n    if not result then\n        result = { m(i, w) }\n        memo[key] = result\n    end\n    return unpack(result)\nend\n\nlocal total_value, index_list = m(#items, 400)\n\nfunction list_items(head) -- makes linked list iterator function \n    return function()\n        local item, rest = unpack(head)\n        head = rest\n        return item\n    end\nend\n\nlocal names = {}\nlocal total_weight = 0\nfor i in list_items(index_list) do\n    local name, weight = unpack(items[i])\n    table.insert(names, 1, name)\n    total_weight = total_weight + weight\nend\n\nlocal function printf(fmt, ...) print(string.format(fmt, ...)) end\nprintf(\"items to pack: %s\", table.concat(names, \", \"))\nprintf(\"total value: %d\", total_value)\nprintf(\"total weight: %d\", total_weight)\n\n-- out of curiosity\nlocal count = 0\nfor k,v in pairs(memo) do count = count + 1 end\nprintf(\"\\n(memo count: %d; mm call count: %d)\", count, mm_calls)\n\n\n","human_summarization":"The code implements a solution to the 0-1 Knapsack problem. It helps a tourist to determine the combination of items to carry in his knapsack, with a weight limit of 4kg, in a way that maximizes the total value of the items. The items, their weights and values are given in a list, and only one unit of each item can be taken.","id":1869}
    {"lang_cluster":"Lua","source_code":"local Person = {}\nPerson.__index = Person\n\nfunction Person.new(inName)\n    local o = {\n        name            = inName,\n        prefs           = nil,\n        fiance          = nil,\n        _candidateIndex = 1,\n    }\n    return setmetatable(o, Person)\nend\n\nfunction Person:indexOf(other)\n    for i, p in pairs(self.prefs) do\n        if p == other then return i end\n    end\n    return 999\nend\n\nfunction Person:prefers(other)\n    return self:indexOf(other) < self:indexOf(self.fiance)\nend\n\nfunction Person:nextCandidateNotYetProposedTo()\n    if self._candidateIndex >= #self.prefs then return nil end\n    local c = self.prefs[self._candidateIndex];\n    self._candidateIndex = self._candidateIndex + 1\n    return c;\nend\n\nfunction Person:engageTo(other)\n    if other.fiance then\n        other.fiance.fiance = nil\n    end\n    other.fiance = self\n    if self.fiance then\n        self.fiance.fiance = nil\n    end\n    self.fiance = other;\nend\n\nlocal function isStable(men)\n    local women = men[1].prefs\n    local stable = true\n    for _, guy in pairs(men) do\n        for _, gal in pairs(women) do\n            if guy:prefers(gal) and gal:prefers(guy) then\n                stable = false\n                print(guy.name .. ' and ' .. gal.name ..\n                      ' prefer each other over their partners ' ..\n                      guy.fiance.name .. ' and ' .. gal.fiance.name)\n            end\n        end\n    end\n    return stable\nend\n\nlocal abe  = Person.new(\"Abe\")\nlocal bob  = Person.new(\"Bob\")\nlocal col  = Person.new(\"Col\")\nlocal dan  = Person.new(\"Dan\")\nlocal ed   = Person.new(\"Ed\")\nlocal fred = Person.new(\"Fred\")\nlocal gav  = Person.new(\"Gav\")\nlocal hal  = Person.new(\"Hal\")\nlocal ian  = Person.new(\"Ian\")\nlocal jon  = Person.new(\"Jon\")\n\nlocal abi  = Person.new(\"Abi\")\nlocal bea  = Person.new(\"Bea\")\nlocal cath = Person.new(\"Cath\")\nlocal dee  = Person.new(\"Dee\")\nlocal eve  = Person.new(\"Eve\")\nlocal fay  = Person.new(\"Fay\")\nlocal gay  = Person.new(\"Gay\")\nlocal hope = Person.new(\"Hope\")\nlocal ivy  = Person.new(\"Ivy\")\nlocal jan  = Person.new(\"Jan\")\n\nabe.prefs  = { abi,  eve,  cath, ivy,  jan,  dee,  fay,  bea,  hope, gay  }\nbob.prefs  = { cath, hope, abi,  dee,  eve,  fay,  bea,  jan,  ivy,  gay  }\ncol.prefs  = { hope, eve,  abi,  dee,  bea,  fay,  ivy,  gay,  cath, jan  }\ndan.prefs  = { ivy,  fay,  dee,  gay,  hope, eve,  jan,  bea,  cath, abi  }\ned.prefs   = { jan,  dee,  bea,  cath, fay,  eve,  abi,  ivy,  hope, gay  }\nfred.prefs = { bea,  abi,  dee,  gay,  eve,  ivy,  cath, jan,  hope, fay  }\ngav.prefs  = { gay,  eve,  ivy,  bea,  cath, abi,  dee,  hope, jan,  fay  }\nhal.prefs  = { abi,  eve,  hope, fay,  ivy,  cath, jan,  bea,  gay,  dee  }\nian.prefs  = { hope, cath, dee,  gay,  bea,  abi,  fay,  ivy,  jan,  eve  }\njon.prefs  = { abi,  fay,  jan,  gay,  eve,  bea,  dee,  cath, ivy,  hope }\n\nabi.prefs  = { bob,  fred, jon,  gav,  ian,  abe,  dan,  ed,   col,  hal  }\nbea.prefs  = { bob,  abe,  col,  fred, gav,  dan,  ian,  ed,   jon,  hal  }\ncath.prefs = { fred, bob,  ed,   gav,  hal,  col,  ian,  abe,  dan,  jon  }\ndee.prefs  = { fred, jon,  col,  abe,  ian,  hal,  gav,  dan,  bob,  ed   }\neve.prefs  = { jon,  hal,  fred, dan,  abe,  gav,  col,  ed,   ian,  bob  }\nfay.prefs  = { bob,  abe,  ed,   ian,  jon,  dan,  fred, gav,  col,  hal  }\ngay.prefs  = { jon,  gav,  hal,  fred, bob,  abe,  col,  ed,   dan,  ian  }\nhope.prefs = { gav,  jon,  bob,  abe,  ian,  dan,  hal,  ed,   col,  fred }\nivy.prefs  = { ian,  col,  hal,  gav,  fred, bob,  abe,  ed,   jon,  dan  }\njan.prefs  = { ed,   hal,  gav,  abe,  bob,  jon,  col,  ian,  fred, dan  }\n\nlocal men = abi.prefs\nlocal freeMenCount = #men\nwhile freeMenCount > 0 do\n    for _, guy in pairs(men) do\n        if not guy.fiance then\n            local gal = guy:nextCandidateNotYetProposedTo()\n            if not gal.fiance then\n                guy:engageTo(gal)\n                freeMenCount = freeMenCount - 1\n            elseif gal:prefers(guy) then\n                guy:engageTo(gal)\n            end\n        end\n    end\nend\n\nprint(' ')\nfor _, guy in pairs(men) do\n    print(guy.name .. ' is engaged to ' .. guy.fiance.name)\nend\nprint('Stable: ', isStable(men))\n\nprint(' ')\nprint('Switching ' .. fred.name .. \"'s & \" .. jon.name .. \"'s partners\")\njon.fiance, fred.fiance = fred.fiance, jon.fiance\nprint('Stable: ', isStable(men))\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":1870}
    {"lang_cluster":"Lua","source_code":"\nfunction a(i)\n    print \"Function a(i) called.\"\n    return i\nend\n\nfunction b(i)\n    print \"Function b(i) called.\"\n    return i\nend\n\ni = true\nx = a(i) and b(i);  print \"\"\ny = a(i) or  b(i);  print \"\"\n\ni = false\nx = a(i) and b(i);  print \"\"\ny = a(i) or  b(i)\n\n","human_summarization":"create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.","id":1871}
    {"lang_cluster":"Lua","source_code":"\n\nlocal M = {}\n\n-- module-local variables\nlocal BUZZER = pio.PB_10\nlocal dit_length, dah_length, word_length\n\n-- module-local functions\nlocal buzz, dah, dit, init, inter_element_gap, medium_gap, pause, sequence, short_gap\n\nbuzz = function(duration)\n  pio.pin.output(BUZZER)\n  pio.pin.setlow(BUZZER)\n  tmr.delay(tmr.SYS_TIMER, duration)\n  pio.pin.sethigh(BUZZER)\n  pio.pin.input(BUZZER)\nend\n\ndah = function()\n  buzz(dah_length)\nend\n\ndit = function()\n  buzz(dit_length)\nend\n\ninit = function(baseline)\n  dit_length = baseline\n  dah_length = 2 * baseline\n  word_length = 4 * baseline\nend\n\ninter_element_gap = function()\n  pause(dit_length)\nend\n\nmedium_gap = function()\n  pause(word_length)\nend\n\npause = function(duration)\n  tmr.delay(tmr.SYS_TIMER, duration)\nend\n\nsequence = function(codes)\n  if codes then\n    for _,f in ipairs(codes) do\n      f()\n      inter_element_gap()\n    end\n    short_gap()\n  end\nend\n\nshort_gap = function()\n  pause(dah_length)\nend\n\nlocal morse = {\n  a = { dit, dah }, b = { dah, dit, dit, dit }, c = { dah, dit, dah, dit },\n  d = { dah, dit, dit }, e = { dit }, f = { dit, dit, dah, dit },\n  g = { dah, dah, dit }, h = { dit, dit, dit ,dit }, i = { dit, dit },\n  j = { dit, dah, dah, dah }, k = { dah, dit, dah }, l = { dit, dah, dit, dit },\n  m = { dah, dah }, n = { dah, dit }, o = { dah, dah, dah },\n  p = { dit, dah, dah, dit }, q = { dah, dah, dit, dah }, r = { dit, dah, dit },\n  s = { dit, dit, dit }, t = { dah }, u = { dit, dit, dah },\n  v = { dit, dit, dit, dah }, w = { dit, dah, dah }, x = { dah, dit, dit, dah },\n  y = { dah, dit, dah, dah }, z = { dah, dah, dit, dit },\n\n  [\"0\"] = { dah, dah, dah, dah, dah }, [\"1\"] = { dit, dah, dah, dah, dah },\n  [\"2\"] = { dit, dit, dah, dah, dah }, [\"3\"] = { dit, dit, dit, dah, dah },\n  [\"4\"] = { dit, dit, dit, dit, dah }, [\"5\"] = { dit, dit, dit, dit, dit },\n  [\"6\"] = { dah, dit, dit, dit, dit }, [\"7\"] = { dah, dah, dit, dit, dit },\n  [\"8\"] = { dah, dah, dah, dit, dit }, [\"9\"] = { dah, dah, dah, dah, dit },\n\n  [\" \"] = { medium_gap }\n}\n\n-- public interface\nM.beep = function(message)\n  message = message:lower()\n  for _,ch in ipairs { message:byte(1, #message) } do\n    sequence(morse[string.char(ch)])\n  end\nend\n\nM.set_dit = function(duration)\n  init(duration)\nend\n\n-- initialization code\ninit(50000)\n\nreturn M\n\n\nmorse = require 'morse'\nmorse.beep \"I am the very model of a modern major-general.\"\n\n","human_summarization":"send a string as audible Morse code to an audio device, ignoring unknown characters or indicating them with a different pitch. It uses eLua code to beep the speaker in Morse code on a specific evaluation board. The code can be converted for other Lua 5.n environments with a sound library.","id":1872}
    {"lang_cluster":"Lua","source_code":"\nblocks = {\n\t{\"B\",\"O\"};\t{\"X\",\"K\"};\t{\"D\",\"Q\"};\t{\"C\",\"P\"};\n\t{\"N\",\"A\"};\t{\"G\",\"T\"};\t{\"R\",\"E\"};\t{\"T\",\"G\"};\n\t{\"Q\",\"D\"};\t{\"F\",\"S\"};\t{\"J\",\"W\"};\t{\"H\",\"U\"};\n\t{\"V\",\"I\"};\t{\"A\",\"N\"};\t{\"O\",\"B\"};\t{\"E\",\"R\"};\n\t{\"F\",\"S\"};\t{\"L\",\"Y\"};\t{\"P\",\"C\"};\t{\"Z\",\"M\"};\n\t};\n\nfunction canUse(table, letter)\n\tfor i,v in pairs(blocks) do\n\t\tif (v[1] == letter:upper() or v[2] == letter:upper())  and table[i] then\n\t\t\ttable[i] = false;\n\t\t\treturn true;\n\t\tend\n\tend\n\treturn false;\nend\n\nfunction canMake(Word)\n\tlocal Taken = {};\n\tfor i,v in pairs(blocks) do\n\t\ttable.insert(Taken,true);\n\tend\n\tlocal found = true;\n\tfor i = 1,#Word do\n\t\tif not canUse(Taken,Word:sub(i,i)) then\n\t\t\tfound = false;\n\t\tend\n\tend\n\tprint(found)\nend\n\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":1873}
    {"lang_cluster":"Lua","source_code":"\n\nrequire \"md5\"\n\n--printing a sum:\nprint(md5.sumhexa\"The quick brown fox jumps over the lazy dog\")\n\n--running the test suite:\n\nlocal function test(msg,sum) assert(md5.sumhexa(msg)==sum) end\n\ntest(\"\",\"d41d8cd98f00b204e9800998ecf8427e\")\ntest(\"a\",\"0cc175b9c0f1b6a831c399e269772661\")\ntest(\"abc\",\"900150983cd24fb0d6963f7d28e17f72\")\ntest(\"message digest\",\"f96b697d7cb7938d525a2f31aaf161d0\")\ntest(\"abcdefghijklmnopqrstuvwxyz\",\"c3fcd3d76192e4007dfb496cca67e13b\")\ntest(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",\"d174ab98d277d9f5a5611c2c9f419d9f\")\ntest(\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\",\"57edf4a22be3c955ac49da2e2107b67a\")\n\n","human_summarization":"Implement and validate an MD5 encoding for a given string, with optional testing against IETF RFC (1321) values. Note the known weaknesses of MD5 and consider alternatives for production-grade cryptography. The code may use the Kepler MD5 library.","id":1874}
    {"lang_cluster":"Lua","source_code":"\n\nlocal OIDs = {\n    \"1.3.6.1.4.1.11.2.17.19.3.4.0.10\",\n    \"1.3.6.1.4.1.11.2.17.5.2.0.79\",\n    \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\",\n    \"1.3.6.1.4.1.11150.3.4.0.1\",\n    \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\",\n    \"1.3.6.1.4.1.11150.3.4.0\"\n}\n \nfunction compare (a, b)\n    local aList, bList, Na, Nb = {}, {}\n    for num in a:gmatch(\"%d+\") do table.insert(aList, num) end\n    for num in b:gmatch(\"%d+\") do table.insert(bList, num) end\n    for i = 1, math.max(#aList, #bList) do\n        Na, Nb = tonumber(aList[i]) or 0, tonumber(bList[i]) or 0\n        if Na ~= Nb then return Na < Nb end\n    end\nend\n \ntable.sort(OIDs, compare)\nfor _, oid in pairs(OIDs) do print(oid) end\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots. The sorting is done using a custom compare function with the in-built table.sort.","id":1875}
    {"lang_cluster":"Lua","source_code":"\nLibrary: LuaSocket\nsocket = require \"socket\"\nhost, port = \"127.0.0.1\", 256\n\nsid = socket.udp()\nsid:sendto( \"hello socket world\", host, port )\nsid:close()\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":1876}
    {"lang_cluster":"Lua","source_code":"\n\n-- load the smtp support\nlocal smtp = require(\"socket.smtp\")\n\n-- Connects to server \"localhost\" and sends a message to users\n-- \"fulano@example.com\",  \"beltrano@example.com\", \n-- and \"sicrano@example.com\".\n-- Note that \"fulano\" is the primary recipient, \"beltrano\" receives a\n-- carbon copy and neither of them knows that \"sicrano\" received a blind\n-- carbon copy of the message.\nfrom = \"<luasocket@example.com>\"\n\nrcpt = {\n  \"<fulano@example.com>\",\n  \"<beltrano@example.com>\",\n  \"<sicrano@example.com>\"\n}\n\nmesgt = {\n  headers = {\n    to = \"Fulano da Silva <fulano@example.com>\",\n    cc = '\"Beltrano F. Nunes\" <beltrano@example.com>',\n    subject = \"My first message\"\n  },\n  body = \"I hope this works. If it does, I can send you another 1000 copies.\"\n}\n\nr, e = smtp.send{\n  from = from,\n  rcpt = rcpt, \n  source = smtp.message(mesgt)\n}\n\n","human_summarization":"implement a function to send an email using LuaSocket's SMTP module. The function includes parameters for setting From, To, Cc addresses, Subject, and message text, with optional fields for server name and login details. The code may also provide notifications for success or issues. The solution is portable across multiple operating systems.","id":1877}
    {"lang_cluster":"Lua","source_code":"\nfor l=1,2147483647 do\n  print(string.format(\"%o\",l))\nend\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":1878}
    {"lang_cluster":"Lua","source_code":"\n\nx, y = y, x                -- swap the values inside x and y\nt[1], t[2] = t[2], t[1]    -- swap the first and second values inside table t\n\nx, y = 3, 4\nprint(x, y)                --> 3 4\nx, y = y, x                -- swap\nprint(x, y)                --> 4 3\n","human_summarization":"implement a generic swap function or operator that exchanges the values of two variables, regardless of their types. The function handles the constraints of statically typed languages and dynamically typed languages, and also manages issues related to parametric polymorphism. It doesn't necessarily support swapping of incompatible types like string and integer. The function also considers the evaluation behavior of languages like Lua.","id":1879}
    {"lang_cluster":"Lua","source_code":"\nfunction ispalindrome(s) return s == string.reverse(s) end\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":1880}
    {"lang_cluster":"Lua","source_code":"\nprint( os.getenv( \"PATH\" ) )\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":1881}
    {"lang_cluster":"Lua","source_code":"\nfunction F (n, x, y)\n    if n == 0 then\n        return x + y\n    elseif y == 0 then\n        return x\n    else\n        return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y)\n    end\nend\n\nlocal testCases = {\n    {0, 0, 0},\n    {1, 1, 1},\n    {1, 3, 3},\n    {2, 1, 1},\n    {2, 2, 1},\n    {3, 1, 1}\n}\n\nfor _, v in pairs(testCases) do\n    io.write(\"F(\" .. table.concat(v, \",\") .. \") = \")\n    print(F(unpack(v)))\nend\n\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.","id":1882}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\nstack = Int[]           # []\n@show push!(stack, 1)   # [1]\n@show push!(stack, 2)   # [1, 2]\n@show push!(stack, 3)   # [1, 2, 3]\n@show pop!(stack)       # 3\n@show length(stack)     # 2\n@show empty!(stack)     # []\n@show isempty(stack)    # true\n\n","human_summarization":"implement a stack data structure with basic operations such as push (adds an element to the top of the stack), pop (removes and returns the last added element from the stack), and empty (checks if the stack is empty). The stack follows a Last In, First Out (LIFO) access policy. The top operation is also supported for accessing the topmost element without modifying the stack.","id":1883}
    {"lang_cluster":"Julia","source_code":"\nfib(n) = n < 2\u00a0? n\u00a0: fib(n-1) + fib(n-2)\nfunction fib(n)\n  x,y = (0,1)\n  for i = 1:n x,y = (y, x+y) end\n  x\nend\nfib(n) = ([1 1\u00a0; 1 0]^n)[1,2]\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":1884}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n@show filter(iseven, 1:10)\n\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":1885}
    {"lang_cluster":"Julia","source_code":"\n\njulia> s = \"abcdefg\"\n\"abcdefg\"\n\njulia> n = 3\n3\n\njulia> s[n:end]\n\"cdefg\"\n\njulia> m=2\n2\n\njulia> s[n:n+m]\n\"cde\"\n\njulia> s[1:end-1]\n\"abcdef\"\n\njulia> s[search(s,'c')]\n'c'\n\njulia> s[search(s,'c'):search(s,'c')+m]\n\"cde\"\n\n","human_summarization":"The code performs various operations on a string such as displaying a substring starting from a specific character position and of a certain length, displaying a substring from a specific character position to the end of the string, displaying the whole string minus the last character, and displaying a substring starting from a known character or substring within the string. The code is designed to work with any valid Unicode code point, referencing logical characters rather than 8-bit or 16-bit code units. The string type is inferred from its elements and can be interpreted as an UTF8 string with logical access to its argument using the CharString declaration.","id":1886}
    {"lang_cluster":"Julia","source_code":"\njulia> reverse(\"hey\")\n\"yeh\"\n\njulia> join(reverse(collect(graphemes(\"as\u20dddf\u0305\"))))\n\"f\u0305ds\u20dda\"\n","human_summarization":"The code reverses a given string, for instance, \"asdf\" is transformed to \"fdsa\". It also preserves Unicode combining characters during the reversal. For example, \"as\u20dddf\u0305\" is reversed to \"f\u0305ds\u20dda\". The code primarily reverses codepoints, suitable for string reversal applications in external C libraries. However, from Julia 0.4, it also offers the option to reverse graphemes for reversing \"visual order\" including combining characters.","id":1887}
    {"lang_cluster":"Julia","source_code":"\nfunction playfair(key, txt, isencode=true, from = \"J\", to = \"\")\n    to = (to == \"\" && from == \"J\") ? \"I\" : to\n\n    function canonical(s, dup_toX=true)\n        s = replace(replace(uppercase(s), from => to), r\"[^A-Z]\" => \"\")\n        a, dupcount = [c for c in s], 0\n        for i in 1:2:length(a)-1\n            if s[i] == s[i + 1]\n                dup_toX && splice!(a, i+1+dupcount:i+dupcount, 'X')\n                dupcount += 1\n            end\n        end\n        s = String(a)\n        return isodd(length(s)) ? s * \"X\" : s\n    end\n\n    # Translate key into an encoding 5x5 translation matrix.\n    keyletters = unique([c for c in canonical(key * \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\", false)])\n    m = Char.((reshape(UInt8.(keyletters[1:25]), 5, 5)'))\n\n    # encod is a dictionary of letter pairs for encoding.\n    encod = Dict()\n\n    # Map pairs in same row or same column of matrix m.\n    for i in 1:5, j in 1:5, k in 1:5\n        if j != k\n            encod[m[i, j] * m[i, k]] = m[i, mod1(j + 1, 5)] * m[i, mod1(k + 1, 5)]\n        end\n        if i != k\n            encod[m[i, j] * m[k, j]] = m[mod1(i + 1, 5), j] * m[mod1(k + 1, 5), j]\n        end\n        # Map pairs not on same row or same column.\n        for l in 1:5\n            if i != k && j != l\n                encod[m[i, j] * m[k, l]] = m[i, l] * m[k, j]\n            end\n        end\n    end\n\n    # Get array of pairs of letters from text.\n    canontxt = canonical(txt)\n    letterpairs = [canontxt[i:i+1] for i in 1:2:length(canontxt)-1]\n\n    if isencode\n        # Encode text\n        return join([encod[pair] for pair in letterpairs], \" \")\n    else\n        # Decode text\n        decod = Dict((v, k) for (k, v) in encod)\n        return join([decod[pair] for pair in letterpairs], \" \")\n    end\nend\n\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprintln(\"Original: \", orig)\n\nencoded = playfair(\"Playfair example\", orig)\nprintln(\"Encoded: \", encoded)\n\nprintln(\"Decoded: \", playfair(\"Playfair example\", encoded, false))\n\n","human_summarization":"Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.","id":1888}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 1.8\nusing Printf\n\nstruct Digraph{T <: Real,U}\n    edges::Dict{Tuple{U,U},T}\n    verts::Set{U}\nend\n\nfunction Digraph(edges::Vector{Tuple{U,U,T}}) where {T <: Real,U}\n    vnames = Set{U}(v for edge in edges for v in edge[1:2])\n    adjmat = Dict((edge[1], edge[2]) => edge[3] for edge in edges)\n    return Digraph(adjmat, vnames)\nend\n\nvertices(g::Digraph) = g.verts\nedges(g::Digraph)    = g.edges\n\nneighbours(g::Digraph, v) = Set((b, c) for ((a, b), c) in edges(g) if a == v)\n\nfunction dijkstrapath(g::Digraph{T,U}, source::U, dest::U) where {T, U}\n    @assert source \u2208 vertices(g) \"$source is not a vertex in the graph\"\n\n    # Easy case\n    if source == dest return [source], 0 end\n    # Initialize variables\n    inf  = typemax(T)\n    dist = Dict(v => inf for v in vertices(g))\n    prev = Dict(v => v   for v in vertices(g))\n    dist[source] = 0\n    Q = copy(vertices(g))\n    neigh = Dict(v => neighbours(g, v) for v in vertices(g))\n\n    # Main loop\n    while !isempty(Q)\n        u = reduce((x, y) -> dist[x] < dist[y] ? x : y, Q)\n        pop!(Q, u)\n        if dist[u] == inf || u == dest break end\n        for (v, cost) in neigh[u]\n            alt = dist[u] + cost\n            if alt < dist[v]\n                dist[v] = alt\n                prev[v] = u\n            end\n        end\n    end\n\n    # Return path\n    rst, cost = U[], dist[dest]\n    if prev[dest] == dest\n        return rst, cost\n    else\n        while dest != source\n            pushfirst!(rst, dest)\n            dest = prev[dest]\n        end\n        pushfirst!(rst, dest)\n        return rst, cost\n    end\nend\n\n# testgraph = [(\"a\", \"b\", 1), (\"b\", \"e\", 2), (\"a\", \"e\", 4)]\nconst testgraph = [(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n             (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n             (\"e\", \"f\", 9)]\n\nfunction testpaths()\n    g = Digraph(testgraph)\n    src, dst = \"a\", \"e\"\n    path, cost = dijkstrapath(g, src, dst)\n    println(\"Shortest path from $src to $dst: \", isempty(path) ?\n       \"no possible path\" : join(path, \" \u2192 \"), \" (cost $cost)\")\n    # Print all possible paths\n    @printf(\"\\n%4s | %3s | %s\\n\", \"src\", \"dst\", \"path\")\n    @printf(\"----------------\\n\")\n    for src in vertices(g), dst in vertices(g)\n        path, cost = dijkstrapath(g, src, dst)\n        @printf(\"%4s | %3s | %s\\n\", src, dst, isempty(path) ? \"no possible path\" : join(path, \" \u2192 \") * \" ($cost)\")\n    end\nend\n\ntestpaths()\n\n","human_summarization":"Implement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges representing the shortest path to each reachable node. The program also interprets the output to display the shortest path from the source node to specific nodes.","id":1889}
    {"lang_cluster":"Julia","source_code":"module AVLTrees\n\nimport Base.print\nexport AVLNode, AVLTree, insert, deletekey, deletevalue, findnodebykey, findnodebyvalue, allnodes\n\n@enum Direction LEFT RIGHT\navlhash(x) = Int32(hash(x) & 0xfffffff)\nconst MIDHASH = Int32(div(0xfffffff, 2))\n\nmutable struct AVLNode{T}\n    value::T\n    key::Int32\n    balance::Int32\n    left::Union{AVLNode, Nothing}\n    right::Union{AVLNode, Nothing}\n    parent::Union{AVLNode, Nothing}\nend\nAVLNode(v::T, b, l, r, p) where T <: Real = AVLNode(v, avlhash(v), Int32(b), l, r, p)\nAVLNode(v::T, h, b::Int64, l, r, p) where T <: Real = AVLNode(v, h, Int32(b), l, r, p)\nAVLNode(v::T) where T <: Real = AVLNode(v, avlhash(v), Int32(0), nothing, nothing, nothing)\n\nAVLTree(typ::Type) = AVLNode(typ(0), MIDHASH, Int32(0), nothing, nothing, nothing)\nconst MaybeAVL = Union{AVLNode, Nothing}\n\nheight(node::MaybeAVL) = (node == nothing) ? 0 : 1 + max(height(node.right), height(node.left))\n\nfunction insert(node, value)\n    if node == nothing\n        node = AVLNode(value)\n        return true\n    end\n    key, n, parent::MaybeAVL = avlhash(value), node, nothing\n    while true\n        if n.key == key\n            return false\n        end\n        parent = n\n        ngreater = n.key > key\n        n = ngreater ? n.left : n.right\n        if n == nothing\n            if ngreater\n                parent.left = AVLNode(value, key, 0, nothing, nothing, parent)\n            else\n                parent.right = AVLNode(value, key, 0, nothing, nothing, parent)\n            end\n            rebalance(parent)\n            break\n        end\n    end\n    return true\nend\n\nfunction deletekey(node, delkey)\n    node == nothing && return nothing\n    n, parent = MaybeAVL(node), MaybeAVL(node)\n    delnode, child = MaybeAVL(nothing), MaybeAVL(node)\n    while child != nothing\n        parent, n = n, child\n        child = delkey >= n.key ? n.right : n.left\n        if delkey == n.key\n            delnode = n\n        end\n    end\n    if delnode != nothing\n        delnode.key = n.key\n        delnode.value = n.value\n        child = (n.left != nothing) ? n.left : n.right\n        if node.key == delkey\n            root = child\n        else\n            if parent.left == n\n                parent.left = child\n            else\n                parent.right = child\n            end\n            rebalance(parent)\n        end\n    end\nend\n\ndeletevalue(node, val) = deletekey(node, avlhash(val))\n\nfunction rebalance(node::MaybeAVL)\n    node == nothing && return nothing\n    setbalance(node)\n    if node.balance < -1\n        if height(node.left.left) >= height(node.left.right)\n            node = rotate(node, RIGHT)\n        else\n            node = rotatetwice(node, LEFT, RIGHT)\n        end\n    elseif node.balance > 1\n        if node.right != nothing && height(node.right.right) >= height(node.right.left)\n            node = rotate(node, LEFT)\n        else\n            node = rotatetwice(node, RIGHT, LEFT)\n        end\n    end\n    if node != nothing && node.parent != nothing\n        rebalance(node.parent)\n    end\nend\n\nfunction rotate(a, direction)\n    (a == nothing || a.parent == nothing) && return nothing\n    b = direction == LEFT ? a.right : a.left\n    b == nothing && return\n    b.parent = a.parent\n    if direction == LEFT\n        a.right = b.left\n    else\n        a.left  = b.right\n    end\n    if a.right != nothing\n        a.right.parent = a\n    end\n    if direction == LEFT\n        b.left = a\n    else\n        b.right = a\n    end\n    a.parent = b\n    if b.parent != nothing\n        if b.parent.right == a\n            b.parent.right = b\n        else\n            b.parent.left = b\n        end\n    end\n    setbalance([a, b])\n    return b\nend\n\nfunction rotatetwice(n, dir1, dir2)\n    n.left = rotate(n.left, dir1)\n    rotate(n, dir2)\nend\n\nsetbalance(n::AVLNode) = begin n.balance = height(n.right) - height(n.left) end\nsetbalance(n::Nothing) = 0\nsetbalance(nodes::Vector) = for n in nodes setbalance(n) end\n\nfunction findnodebykey(node, key)\n    result::MaybeAVL = node == nothing ? nothing : node.key == key ? node : \n        node.left != nothing && (n = findbykey(n, key) != nothing) ? n :\n        node.right != nothing ? findbykey(node.right, key) : nothing\n    return result\nend\nfindnodebyvalue(node, val) = findnodebykey(node, avlhash(v))\n\nfunction allnodes(node)\n    result = AVLNode[]\n    if node != nothing\n        append!(result, allnodes(node.left))\n        if node.key != MIDHASH\n            push!(result, node)\n        end\n        append!(result, node.right)\n    end\n    return result\nend\n\nfunction Base.print(io::IO, n::MaybeAVL)\n    if n != nothing\n        n.left != nothing && print(io, n.left)\n        print(io, n.key == MIDHASH ? \"<ROOT> \" : \"<$(n.key):$(n.value):$(n.balance)> \")\n        n.right != nothing && print(io, n.right)\n    end\nend\n\nend # module\n\nusing .AVLTrees\n\nconst tree = AVLTree(Int)\n\nprintln(\"Inserting 10 values.\")\nforeach(x -> insert(tree, x), rand(collect(1:80), 10))\nprintln(\"Printing tree after insertion: \")\nprintln(tree)\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.","id":1890}
    {"lang_cluster":"Julia","source_code":"\n\nimmutable Point{T<:FloatingPoint}\n    x::T\n    y::T\nend\n\nimmutable Circle{T<:FloatingPoint}\n    c::Point{T}\n    r::T\nend\nCircle{T<:FloatingPoint}(a::Point{T}) = Circle(a, zero(T))\n\nusing AffineTransforms\n\nfunction circlepoints{T<:FloatingPoint}(a::Point{T}, b::Point{T}, r::T)\n    cp = Circle{T}[]\n    r >= 0 || return (cp, \"No Solution, Negative Radius\")\n    if a == b\n        if abs(r) < 2eps(zero(T))\n            return (push!(cp, Circle(a)), \"Point Solution, Zero Radius\")\n        else\n            return (cp, \"Infinite Solutions, Indefinite Center\")\n        end\n    end\n    ca = Complex(a.x, a.y)\n    cb = Complex(b.x, b.y)\n    d = (ca + cb)\/2\n    tfd = tformtranslate([real(d), imag(d)])\n    tfr = tformrotate(angle(cb-ca))\n    tfm = tfd*tfr\n    u = abs(cb-ca)\/2\n    r-u > -5eps(r) || return(cp, \"No Solution, Radius Too Small\")\n    if r-u < 5eps(r)\n        push!(cp, Circle(apply(Point, tfm*[0.0, 0.0]), r))\n        return return (cp, \"Single Solution, Degenerate Centers\")\n    end\n    v = sqrt(r^2 - u^2)\n    for w in [v, -v]\n        push!(cp, Circle(apply(Point, tfm*[0.0, w]), r))\n    end\n    return (cp, \"Two Solutions\")\nend\n\n\ntp = [Point(0.1234, 0.9876),\n      Point(0.0000, 2.0000),\n      Point(0.1234, 0.9876),\n      Point(0.1234, 0.9876),\n      Point(0.1234, 0.9876)]\n\ntq = [Point(0.8765, 0.2345),\n      Point(0.0000, 0.0000),\n      Point(0.1234, 0.9876),\n      Point(0.8765, 0.2345),\n      Point(0.1234, 0.9876)]\n\ntr = [2.0, 1.0, 2.0, 0.5, 0.0]\n\nprintln(\"Testing circlepoints:\")\nfor i in 1:length(tp)\n    p = tp[i]\n    q = tq[i]\n    r = tr[i]\n    (cp, rstatus) = circlepoints(p, q, r)\n    println(@sprintf(\"(%.4f, %.4f), (%.4f, %.4f), %.4f => %s\",\n                     p.x, p.y, q.x, q.y, r, rstatus))\n    for c in cp\n        println(@sprintf(\"    (%.4f, %.4f), %.4f\",\n                         c.c.x, c.c.y, c.r))\n    end\nend\n\n\n","human_summarization":"The code defines a function that takes two 2D points and a radius as inputs and returns two circles that pass through these points. The function also handles special cases such as when the radius is zero, the points are coincident, the points form a diameter, or the points are too far apart. The function uses the AffineTransforms.jl package to create a coordinate system centered on the midpoint between the two points. The points are treated as complex numbers to help determine the midpoint and rotation angle. The code also includes a task to calculate the total area of the circles.","id":1891}
    {"lang_cluster":"Julia","source_code":"const k8 = [ 4, 10,  9,  2, 13,  8,  0, 14,  6, 11,  1, 12,  7, 15,  5,  3]\nconst k7 = [14, 11,  4, 12,  6, 13, 15, 10,  2,  3,  8,  1,  0,  7,  5,  9]\nconst k6 = [ 5,  8,  1, 13, 10,  3,  4,  2, 14, 15, 12,  7,  6,  0,  9, 11]\nconst k5 = [ 7, 13, 10,  1,  0,  8,  9, 15, 14,  4,  6, 12, 11,  2,  5,  3]\nconst k4 = [ 6, 12,  7,  1,  5, 15, 13,  8,  4, 10,  9, 14,  0,  3, 11,  2]\nconst k3 = [ 4, 11, 10,  0,  7,  2,  1, 13,  3,  6,  8,  5,  9, 12, 15, 14]\nconst k2 = [13, 11,  4,  1,  3, 15,  5,  9,  0, 10, 14,  7,  6,  8,  2, 12]\nconst k1 = [ 1, 15, 13,  0,  5,  7, 10,  4,  9,  2,  3, 14,  6, 11,  8, 12]\nconst k87 = zeros(UInt32,256)\nconst k65 = zeros(UInt32,256)\nconst k43 = zeros(UInt32,256)\nconst k21 = zeros(UInt32,256)\nfor i in 1:256\n    j = (i-1) >> 4 + 1\n    k = (i-1) & 15 + 1\n    k87[i] = (k1[j] << 4) | k2[k]\n    k65[i] = (k3[j] << 4) | k4[k]\n    k43[i] = (k5[j] << 4) | k6[k]\n    k21[i] = (k7[j] << 4) | k8[k]\nend\n\nfunction f(x)\n    y = (k87[(x>>24) & 0xff + 1] << 24) | (k65[(x>>16) & 0xff + 1] << 16) |\n        (k43[(x>> 8) & 0xff + 1] <<  8) | k21[x & 0xff + 1]\n    (y << 11) | (y >> (32-11))\nend\n\nbytes2int(arr) = arr[1] + (UInt32(arr[2]) << 8) + (UInt32(arr[3]) << 16) + (UInt32(arr[4])) << 24\nint2bytes(x) = [UInt8(x&0xff), UInt8((x&0xff00)>>8), UInt8((x&0xff0000)>>16), UInt8(x>>24)]\n\nfunction mainstep(inputbytes, keybytes)\n    intkey = bytes2int(keybytes)\n    lowint = bytes2int(inputbytes[1:4])\n    topint = bytes2int(inputbytes[5:8])\n    xorbytes = f(UInt32(intkey) + UInt32(lowint)) \u22bb topint\n    vcat(int2bytes(xorbytes), inputbytes[1:4])\nend\n\nconst input = [0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04]\nconst key = [0xF9, 0x04, 0xC1, 0xE2]   \nprintln(\"The encoded bytes are $(mainstep(input, key))\")\n\n\n","human_summarization":"Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.","id":1892}
    {"lang_cluster":"Julia","source_code":"\nwhile true\n    n = rand(0:19)\n    @printf \"%4d\" n\n    if n == 10\n        println()\n        break\n    end\n    n = rand(0:19)\n    @printf \"%4d\\n\" n\nend\n\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":1893}
    {"lang_cluster":"Julia","source_code":"\n# v0.6\n\nusing Primes\n\nfunction mersennefactor(p::Int)::Int\n    q = 2p + 1\n    while true\n        if log2(q) > p \/ 2\n            return -1\n        elseif q % 8 in (1, 7) && Primes.isprime(q) && powermod(2, p, q) == 1\n            return q\n        end\n    q += 2p\n    end\nend\n\nfor i in filter(Primes.isprime, push!(collect(1:20), 929))\n    mf = mersennefactor(i)\n    if mf != -1 println(\"M$i = \", mf, \" \u00d7 \", (big(2) ^ i - 1) \u00f7 mf)\n    else println(\"M$i is prime\") end\nend\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":1894}
    {"lang_cluster":"Julia","source_code":"\n\nusing LibExpat\n\nxdoc = raw\"\"\"<inventory title=\"OmniCorp Store #45x10^3\">\n  <section name=\"health\">\n    <item upc=\"123456789\" stock=\"12\">\n      <name>Invisibility Cream<\/name>\n      <price>14.50<\/price>\n      <description>Makes you invisible<\/description>\n    <\/item>\n    <item upc=\"445322344\" stock=\"18\">\n      <name>Levitation Salve<\/name>\n      <price>23.99<\/price>\n      <description>Levitate yourself for up to 3 hours per application<\/description>\n    <\/item>\n  <\/section>\n  <section name=\"food\">\n    <item upc=\"485672034\" stock=\"653\">\n      <name>Blork and Freen Instameal<\/name>\n      <price>4.95<\/price>\n      <description>A tasty meal in a tablet; just add water<\/description>\n    <\/item>\n    <item upc=\"132957764\" stock=\"44\">\n      <name>Grob winglets<\/name>\n      <price>3.56<\/price>\n      <description>Tender winglets of Grob. Just add water<\/description>\n    <\/item>\n  <\/section>\n<\/inventory>\n\"\"\"\n\ndebracket(s) = replace(s, r\".+\\>(.+)\\<.+\" => s\"\\1\") \n\netree = xp_parse(xdoc)\nfirstshow = LibExpat.find(etree, \"\/\/item\")[1]\nprintln(\"The first item's node XML entry is:\\n\", firstshow, \"\\n\\n\")\n\nprices = LibExpat.find(etree, \"\/\/price\")\nprintln(\"Prices:\")\nfor p in prices\n    println(\"\\t\", debracket(string(p)))\nend\nprintln(\"\\n\")\n\nnamearray = LibExpat.find(etree, \"\/\/name\")\nprintln(\"Array of names of items:\\n\\t\", map(s -> debracket(string(s)), namearray))\n\n","human_summarization":"The code performs three XPath queries on a given XML document. It retrieves the first \"item\" element, prints out each \"price\" element, and gets an array of all the \"name\" elements. The XML document represents an inventory of a store. The LibExpat module is used for XML pathing.","id":1895}
    {"lang_cluster":"Julia","source_code":"\njulia> S1 = Set(1:4)\u00a0; S2 = Set(3:6)\u00a0; println(S1,\"\\n\",S2)\nSet{Int64}({4,2,3,1})\nSet{Int64}({5,4,6,3})\n\njulia> 5 in S1 , 5 in S2\n(false,true)\n\njulia> intersect(S1,S2)\nSet{Int64}({4,3})\n\njulia> union(S1,S2)\nSet{Int64}({5,4,6,2,3,1})\n\njulia> setdiff(S1,S2)\nSet{Int64}({2,1})\n\njulia> issubset(S1,S2)\nfalse\n\njulia> isequal(S1,S2)\nfalse\n\njulia> symdiff(S1,S2)\nSet{Int64}({5,6,2,1})\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":1896}
    {"lang_cluster":"Julia","source_code":"\nusing Dates\n\nlo, hi = 2008, 2121\nxmas = collect(Date(lo, 12, 25):Year(1):Date(hi, 12, 25))\nfilter!(xmas) do dt\n    dayofweek(dt) == Dates.Sunday\nend\n\nprintln(\"Years from $lo to $hi having Christmas on Sunday: \")\nforeach(println, year.(xmas))\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":1897}
    {"lang_cluster":"Julia","source_code":"\n\nQ, R = qr([12 -51 4; 6 167 -68; -4 24 -41])\n\n\n","human_summarization":"The code performs QR decomposition on a given matrix using the Householder reflections method. It demonstrates this process on an example matrix and uses the decomposition for solving linear least squares problems. The code also handles cases where the matrix is not square by removing zero padded bottom rows. It finally solves the upper triangular system by back substitution.","id":1898}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\na = [1, 2, 3, 4, 1, 2, 3, 4]\n@show unique(a) Set(a)\n\n\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":1899}
    {"lang_cluster":"Julia","source_code":"\n\nsort!(A, alg=QuickSort)\n\n\nfunction quicksort!(A,i=1,j=length(A))\n    if j > i\n        pivot = A[rand(i:j)] # random element of A\n        left, right = i, j\n        while left <= right\n            while A[left] < pivot\n                left += 1\n            end\n            while A[right] > pivot\n                right -= 1\n            end\n            if left <= right\n                A[left], A[right] = A[right], A[left]\n                left += 1\n                right -= 1\n            end\n        end\n        quicksort!(A,i,right)\n        quicksort!(A,left,j)\n    end\n    return A\nend\n\n\nqsort(L) = isempty(L) ? L : vcat(qsort(filter(x -> x < L[1], L[2:end])), L[1:1], qsort(filter(x -> x >= L[1], L[2:end])))\n\n\n","human_summarization":"implement the Quicksort algorithm. It sorts an array or list of elements with a strict weak order. The algorithm works by selecting a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts both partitions and joins them together with the pivot. The codes also include a version of the Quicksort algorithm that works in place by swapping elements within the array to avoid additional memory allocation. The pivot selection method is not specified.","id":1900}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nts = Dates.today()\n\nprintln(\"Today's date is:\")\nprintln(\"\\t$ts\")\nprintln(\"\\t\", Dates.format(ts, \"E, U dd, yyyy\"))\n\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":1901}
    {"lang_cluster":"Julia","source_code":"\nfunction powerset(x::Vector{T})::Vector{Vector{T}} where T\n    result = Vector{T}[[]]\n    for elem in x, j in eachindex(result)\n        push!(result, [result[j] ; elem])\n    end\n    result\nend\n\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":1902}
    {"lang_cluster":"Julia","source_code":"\nusing Printf\n\nfunction romanencode(n::Integer)\n    if n < 1 || n > 4999 throw(DomainError()) end\n\n    DR = [[\"I\", \"X\", \"C\", \"M\"] [\"V\", \"L\", \"D\", \"MMM\"]]\n    rnum = \"\"\n    for (omag, d) in enumerate(digits(n))\n        if d == 0\n            omr = \"\"\n        elseif d <  4\n            omr = DR[omag, 1] ^ d\n        elseif d == 4\n            omr = DR[omag, 1] * DR[omag, 2]\n        elseif d == 5\n            omr = DR[omag, 2]\n        elseif d <  9\n            omr = DR[omag, 2] * DR[omag, 1] ^ (d - 5)\n        else\n            omr = DR[omag, 1] * DR[omag + 1, 1]\n        end\n        rnum = omr * rnum\n    end\n    return rnum\nend\n\ntestcases = [1990, 2008, 1668]\nappend!(testcases, rand(1:4999, 12))\ntestcases = unique(testcases)\n\nprintln(\"Test romanencode, arabic => roman:\")\nfor n in testcases\n    @printf(\"%-4i => %s\\n\", n, romanencode(n))\nend\n\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":1903}
    {"lang_cluster":"Julia","source_code":"\n\njulia> A = Vector(undef, 3)   # create an heterogeneous 1-D array of length 3\n3-element Vector{Any}:\n #undef\n #undef\n #undef\n\njulia> A[1] = 4.5\u00a0; A[3] =  \"some string\"\u00a0; show(A)\n{4.5,#undef,\"some string\"}\n\njulia> A[1]          # access a value. Arrays are 1-indexed\n4.5\n\njulia> push!(A, :symbol)\u00a0; show(A)    # append an element\n{4.5,#undef,\"some string\",:symbol}\n\njulia> A[10]         # error if the index is out of range\nERROR: BoundsError()\n\njulia> B = Array(String, 3)\u00a0; B[1]=\"first\"\u00a0; push!(B, \"fourth\")\u00a0; show(B)\n[\"first\",#undef,#undef,\"fourth\"]\n\njulia> push!(B, 3)   # type error\nERROR: no method convert(Type{String}, Int64)\n in push! at array.jl:488\n\njulia> ['a':'c'...]     # type inference\n3-element Vector{Char}:\n 'a': ASCII\/Unicode U+0061 (category Ll: Letter, lowercase)\n 'b': ASCII\/Unicode U+0062 (category Ll: Letter, lowercase)\n 'c': ASCII\/Unicode U+0063 (category Ll: Letter, lowercase)\n","human_summarization":"demonstrate the basic syntax of arrays in Julia, including creating both heterogeneous and typed arrays, assigning values to them, and retrieving elements. The code also shows how to handle both fixed-length and dynamic arrays.","id":1904}
    {"lang_cluster":"Julia","source_code":"\n\nmystring = read(\"file1\", String)\nopen(io->write(io, mystring), \"file2\", \"w\")\n\n\ncp(\"file1\",\"file2\")\n\n\ninfile = open(\"file1\", \"r\")\noutfile = open(\"file2\", \"w\")\nwrite(outfile, read(infile, String))\nclose(outfile)\nclose(infile)\n\n\nopen(IO ->write(IO, read(\"file1\", String)), \"file2\", \"w\")\n\n","human_summarization":"demonstrate how to create a file named \"output.txt\" and write into it the contents of \"input.txt\" file via an intermediate variable. It also showcases how to read from a file into a variable and how to write a variable's contents into a file. The code also includes a one-liner that ensures the file handle is closed even if an error occurs during the read\/write process. It also mentions the use of Julia's `cp` function to copy file contents.","id":1905}
    {"lang_cluster":"Julia","source_code":"\njulia> uppercase(\"alphaBETA\")\n\"ALPHABETA\"\n\njulia> lowercase(\"alphaBETA\")\n\"alphabeta\"\n\n\njulia> a = '\u00df'\n'\u00df': Unicode U+00DF (category Ll: Letter, lowercase)\n\njulia> uppercase(a)\n'\u1e9e': Unicode U+1E9E (category Lu: Letter, uppercase)\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default encoding. The codes also showcase additional case conversion functions such as swapping case, capitalizing the first letter, etc. that are available in the language's library. It also handles special cases like the transformation of \"\u00df\" to \"\u1e9e\" in Julia.","id":1906}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\nfunction closestpair(P::Vector{Vector{T}}) where T <: Number\n    N = length(P)\n    if N < 2 return (Inf, ()) end\n    mindst = norm(P[1] - P[2])\n    minpts = (P[1], P[2])\n    for i in 1:N-1, j in i+1:N\n        tmpdst = norm(P[i] - P[j])\n        if tmpdst < mindst\n            mindst = tmpdst\n            minpts = (P[i], P[j])\n        end\n    end\n    return mindst, minpts\nend\n\nclosestpair([[0, -0.3], [1., 1.], [1.5, 2], [2, 2], [3, 3]])\n\n","human_summarization":"The code provides two algorithms to solve the Closest Pair of Points problem in a two-dimensional plane. The first algorithm is a brute-force approach with a time complexity of O(n^2), which iterates over all pairs of points to find the minimum distance. The second algorithm uses a recursive divide-and-conquer approach with a time complexity of O(n log n), which sorts the points by x and y coordinates, divides them into two halves, and recursively finds the closest pairs in each half and the strip between them.","id":1907}
    {"lang_cluster":"Julia","source_code":"\n\njulia> collection = []\n0-element Array{Any,1}\n\njulia> push!(collection, 1,2,4,7)\n4-element Array{Any,1}:\n 1\n 2\n 4\n 7\n\n","human_summarization":"create a collection in Julia, add a few values to it, and utilize various collection types including vectors, matrices, lists, associative arrays, and bitsets. The code also demonstrates slicing notation and list comprehensions similar to Python, but with a base index of 1.","id":1908}
    {"lang_cluster":"Julia","source_code":"\nLibrary: JuMPusing JuMP\nusing GLPKMathProgInterface\n\nmodel = Model(solver=GLPKSolverMIP())\n\n@variable(model, vials_of_panacea >= 0, Int)\n@variable(model, ampules_of_ichor >= 0, Int)\n@variable(model, bars_of_gold >= 0, Int)\n\n@objective(model, Max, 3000*vials_of_panacea + 1800*ampules_of_ichor + 2500*bars_of_gold)\n\n@constraint(model, 0.3*vials_of_panacea + 0.2*ampules_of_ichor + 2.0*bars_of_gold <= 25.0)\n@constraint(model, 0.025*vials_of_panacea + 0.015*ampules_of_ichor + 0.002*bars_of_gold <= 0.25)\n\nprintln(\"The optimization problem to be solved is:\")\nprintln(model)\n\nstatus = solve(model)\n\nprintln(\"Objective value: \", getobjectivevalue(model))\nprintln(\"vials of panacea = \", getvalue(vials_of_panacea))\nprintln(\"ampules of ichor = \", getvalue(ampules_of_ichor))\nprintln(\"bars of gold = \", getvalue(bars_of_gold))\n\n\n","human_summarization":"determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.","id":1909}
    {"lang_cluster":"Julia","source_code":"\n\nfor i = 1:10\n  print(i)\n  i == 10 && break\n  print(\", \")\nend\n\n\n1, 2, 3, 4, 5, 6, 7, 8, 9, 10\n\n","human_summarization":"demonstrate a loop in Julia that prints a comma-separated list from 1 to 10, using separate output statements for the number and the comma. The loop uses the short-circuiting && operator to ensure the comma is not printed on the last iteration.","id":1910}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6function toposort(data::Dict{T,Set{T}}) where T\n    data = copy(data)\n    for (k, v) in data\n        delete!(v, k)\n    end\n    extraitems = setdiff(reduce(\u222a, values(data)), keys(data))\n    for item in extraitems\n        data[item] = Set{T}()\n    end\n    rst = Vector{T}()\n    while true\n        ordered = Set(item for (item, dep) in data if isempty(dep))\n        if isempty(ordered) break end\n        append!(rst, ordered)\n        data = Dict{T,Set{T}}(item => setdiff(dep, ordered) for (item, dep) in data if item \u2209 ordered)\n    end\n    @assert isempty(data) \"a cyclic dependency exists amongst $(keys(data))\"\n    return rst\nend\n\ndata = Dict{String,Set{String}}(\n    \"des_system_lib\" => Set(split(\"std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\")),\n    \"dw01\" =>           Set(split(\"ieee dw01 dware gtech\")),\n    \"dw02\" =>           Set(split(\"ieee dw02 dware\")),\n    \"dw03\" =>           Set(split(\"std synopsys dware dw03 dw02 dw01 ieee gtech\")),\n    \"dw04\" =>           Set(split(\"dw04 ieee dw01 dware gtech\")),\n    \"dw05\" =>           Set(split(\"dw05 ieee dware\")),\n    \"dw06\" =>           Set(split(\"dw06 ieee dware\")),\n    \"dw07\" =>           Set(split(\"ieee dware\")),\n    \"dware\" =>          Set(split(\"ieee dware\")),\n    \"gtech\" =>          Set(split(\"ieee gtech\")),\n    \"ramlib\" =>         Set(split(\"std ieee\")),\n    \"std_cell_lib\" =>   Set(split(\"ieee std_cell_lib\")),\n    \"synopsys\" =>       Set(),\n    )\n\nprintln(\"# Topologically sorted:\\n - \", join(toposort(data), \"\\n - \"))\n\n\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":1911}
    {"lang_cluster":"Julia","source_code":"\nstartswith(\"abcd\",\"ab\")            #returns true\nfindfirst(\"ab\", \"abcd\")            #returns 1:2, indices range where string was found\nendswith(\"abcd\",\"zn\")              #returns false\nmatch(r\"ab\",\"abcd\") != Nothing     #returns true where 1st arg is regex string\nfor r in eachmatch(r\"ab\",\"abab\")\n\tprintln(r.offset)\nend                                #returns 1, then 3 matching the two starting indices where the substring was found\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":1912}
    {"lang_cluster":"Julia","source_code":"using Combinatorics\n\nfunction foursquares(low, high, onlyunique=true, showsolutions=true)\n    integers = collect(low:high)\n    count = 0\n    sumsallequal(c) = c[1] + c[2] == c[2] + c[3] + c[4] == c[4] + c[5] + c[6] == c[6] + c[7]\n    combos = onlyunique ? combinations(integers) :\n                          with_replacement_combinations(integers, 7)\n    for combo in combos, plist in unique(collect(permutations(combo, 7)))\n        if sumsallequal(plist)\n            count += 1\n            if showsolutions\n                println(\"$plist is a solution for the list $integers\")\n            end\n        end\n    end\n    println(\"\"\"Total $(onlyunique?\"unique \":\"\")solutions for HIGH $high, LOW $low: $count\"\"\")\nend\n\nfoursquares(1, 7, true, true)\nfoursquares(3, 9, true, true)\nfoursquares(0, 9, false, false)\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":1913}
    {"lang_cluster":"Julia","source_code":"\nusing Gtk, Colors, Graphics, Dates\n\nconst radius = 300\nconst win = GtkWindow(\"Clock\", radius, radius)\nconst can = GtkCanvas()\npush!(win, can)\n\nglobal drawcontext = []\n\nfunction drawline(ctx, l, color)\n    isempty(l) && return\n    p = first(l)\n    move_to(ctx, p.x, p.y)\n    set_source(ctx, color)\n    for i = 2:length(l)\n        p = l[i]\n        line_to(ctx, p.x, p.y)\n    end\n    stroke(ctx)\nend\n\nfunction clockbody(ctx)\n    set_coordinates(ctx, BoundingBox(0, 100, 0, 100))\n    rectangle(ctx, 0, 0, 100, 100)\n    set_source(ctx, colorant\"yellow\")\n    fill(ctx)\n    set_source(ctx, colorant\"blue\")\n    arc(ctx, 50, 50, 45, 45, 360)\n    stroke(ctx)\n    for hr in 1:12\n        radians = hr * pi \/ 6.0\n        drawline(ctx, [Point(50 + 0.95 * 45 * sin(radians),\n            50 - 0.95 * 45 * cos(radians)),\n            Point(50 + 1.0 * 45 * sin(radians),\n            50 - 1.0 * 45 * cos(radians))], colorant\"blue\")\n    end\nend\n\nGtk.draw(can) do widget\n    ctx = getgc(can)\n    if length(drawcontext) < 1\n        push!(drawcontext, ctx)\n    else\n        drawcontext[1] = ctx\n    end\n    clockbody(ctx)\nend\n\nfunction update(can)\n    dtim = now()\n    hr = hour(dtim)\n    mi = minute(dtim)\n    sec = second(dtim)\n    if length(drawcontext) < 1\n        return\n    end\n    ctx = drawcontext[1]\n    clockbody(ctx)\n    rad = (hr % 12) * pi \/ 6.0 + mi * pi \/ 360.0\n    drawline(ctx, [Point(50, 50),\n        Point(50 + 45 * 0.5 * sin(rad), 50 - 45 * 0.5 * cos(rad))], colorant\"black\")\n    stroke(ctx)\n    rad = mi * pi \/ 30.0  + sec * pi \/ 1800.0\n    drawline(ctx, [Point(50, 50),\n        Point(50 + 0.7 * 45 * sin(rad), 50 - 0.7 * 45 * cos(rad))], colorant\"darkgreen\")\n    stroke(ctx)\n    rad = sec * pi \/ 30.0\n    drawline(ctx, [Point(50, 50),\n        Point(50 + 0.9 * 45 * sin(rad), 50 - 0.9 * 45 * cos(rad))], colorant\"red\")\n    stroke(ctx)\n    reveal(can)\nend\n\nGtk.showall(win)\nsloc = Base.Threads.SpinLock()\nlock(sloc)\nsignal_connect(win, :destroy) do widget\n    unlock(sloc)\nend\nwhile !trylock(sloc)\n    update(win)\n    sleep(1.0)\nend\n\n","human_summarization":"illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.","id":1914}
    {"lang_cluster":"Julia","source_code":"\n\n# IF THIS SMALL FUNCTION IS PLACED IN THE STARTUP.JL\n# FILE, IT WILL BE LOADED ON STARTUP. THE REST OF\n# THIS EXAMPLE IS IN ALL UPPERCASE.\nfunction RUNUPPERCASECODE(CO)\n    COD = replace(lowercase(CO), \"date\" => \"Date\")\n    for E in Meta.parse(COD, 1) eval(E) end\nend\n\n\nCODE = \"\"\"BEGIN\n\nUSING DATES;\nCENTEROBJECT(X, N) = BEGIN S = UPPERCASE(STRING(X)); RPAD(LPAD(S, DIV(N + LENGTH(S), 2)), N) END;\nFUNCTION FORMATMONTH(YR, MO)\n    DT = DATE(\\\"\\$YR-\\$MO-01\\\");\n    DAYOFWEEKFIRST = DAYOFWEEK(DT);\n    NUMWEEKLINES = 1;\n    STR = UPPERCASE(CENTEROBJECT(MONTHNAME(DT), 20) * \\\"\\\\NMO TU WE TH FR SA SU\\\\N\\\");\n    STR *= \\\" \\\" ^ (3 * (DAYOFWEEKFIRST - 1)) * LPAD(STRING(1), 2);\n    FOR I = 2:DAYSINMONTH(DT)\n        IF (I + DAYOFWEEKFIRST + 5)\u00a0% 7 == 0\n            STR *= \\\"\\\\N\\\" * LPAD(I, 2);\n            NUMWEEKLINES += 1;\n        ELSE\n            STR *= LPAD(STRING(I), 3);\n        END;\n    END;\n    STR *= NUMWEEKLINES < 6\u00a0? \\\"\\\\N\\\\N\\\\N\\\"\u00a0: \\\"\\\\N\\\\N\\\";\n    ARR = [];\n    FOR S IN SPLIT(STR, \\\"\\\\N\\\")\n        PUSH!(ARR, RPAD(S, 20)[1:20])\n    END;\n    JOIN(ARR, \\\"\\\\N\\\");\nEND;\n \nFUNCTION FORMATYEAR(DISPLAYYEAR)\n    CALMONTHS = [FORMATMONTH(DISPLAYYEAR, MO) FOR MO IN 1:12];\n    MONTHSPERLINE = 6;\n    JOINSPACES = 2;\n    STR = \\\"\\\\N\\\" * CENTEROBJECT(DISPLAYYEAR, 132) * \\\"\\\\N\\\";\n    MONTHCAL = [SPLIT(FORMATMONTH(DISPLAYYEAR, I), \\\"\\\\N\\\") FOR I IN 1:12];\n    FOR I IN 1:MONTHSPERLINE:LENGTH(CALMONTHS) - 1\n        FOR J IN 1:LENGTH(MONTHCAL[1])\n            MONTHLINES = MAP(X->MONTHCAL[X][J], I:I + MONTHSPERLINE - 1);\n            STR *= RPAD(JOIN(MONTHLINES, \\\" \\\" ^ JOINSPACES), 132) * \\\"\\\\N\\\";\n        END;\n        STR *= \\\"\\\\N\\\";\n    END;\n    STR;\nEND;\n\nPRINTLN(FORMATYEAR(1969));\n\nEND;\n\"\"\"\n\nRUNUPPERCASECODE(CODE)\n \n","human_summarization":"provide an algorithm for a calendar task, formatted to fit a 132-character wide page, inspired by 1969 era line printers. The code must be entirely in uppercase, mimicking the constraints of 1960s programming. The code does not include Snoopy generation, but rather a placeholder. The code is written in Julia and can be executed from a string using Meta.parse() and eval functions.","id":1915}
    {"lang_cluster":"Julia","source_code":"\n\nfunction primitiven{T<:Integer}(m::T)\n    1 < m || return T[]\n    m != 2 || return T[1]\n    !isprime(m) || return T[2:2:m-1]\n    rp = trues(m-1)\n    if isodd(m)\n        rp[1:2:m-1] = false\n    end\n    for p in keys(factor(m))\n        rp[p:p:m-1] = false\n    end\n    T[1:m-1][rp]\nend\n\nfunction pythagoreantripcount{T<:Integer}(plim::T)\n    primcnt = 0\n    fullcnt = 0\n    11 < plim || return (primcnt, fullcnt)\n    for m in 2:plim\n        p = 2m^2\n        p+2m <= plim || break\n        for n in primitiven(m)\n            q = p + 2m*n\n            q <= plim || break\n            primcnt += 1\n            fullcnt += div(plim, q)\n        end\n    end\n    return (primcnt, fullcnt)\nend\n\nprintln(\"Counting Pythagorian Triplets within perimeter limits:\")\nprintln(\"    Limit          All   Primitive\")\nfor om in 1:10\n    (pcnt, fcnt) = pythagoreantripcount(10^om)\n    println(@sprintf \"    10^%02d  %11d   %9d\" om fcnt pcnt)\nend\n\n\n","human_summarization":"The code determines the number of Pythagorean triples with a perimeter not exceeding 100 and identifies how many of these are primitive. It also handles large values up to a maximum perimeter of 100,000,000. The solution utilizes the Euclidean concept of m and n as generators of Pythagorean triplets, ensuring that the generated triplets are primitive when m and n are coprime and have opposite parity.","id":1916}
    {"lang_cluster":"Julia","source_code":"\n# v0.6\n\nusing Tk\n\nw = Toplevel(\"Example\")\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":1917}
    {"lang_cluster":"Julia","source_code":"\nusing DataStructures\n \nfunction letterfreq(file::AbstractString; fltr::Function=(_) -> true)\n    sort(Dict(counter(filter(fltr, read(file, String)))))\nend\n \ndisplay(letterfreq(\"src\/Letter_frequency.jl\"; fltr=isletter))\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":1918}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nabstract type AbstractNode{T} end\n\nstruct EmptyNode{T} <: AbstractNode{T} end\nmutable struct Node{T} <: AbstractNode{T}\n    data::T\n    next::AbstractNode{T}\nend\nNode{T}(x) where T = Node{T}(x::T, EmptyNode{T}())\n\nmutable struct LinkedList{T}\n    head::AbstractNode{T}\nend\nLinkedList{T}() where T = LinkedList{T}(EmptyNode{T}())\nLinkedList() = LinkedList{Any}()\n\nBase.isempty(ll::LinkedList) = ll.head isa EmptyNode\nfunction lastnode(ll::LinkedList)\n    if isempty(ll) throw(BoundsError()) end\n    nd = ll.head\n    while !(nd.next isa EmptyNode)\n        nd = nd.next\n    end\n    return nd\nend\n\nfunction Base.push!(ll::LinkedList{T}, x::T) where T\n    nd = Node{T}(x)\n    if isempty(ll)\n        ll.head = nd\n    else\n        tail = lastnode(ll)\n        tail.next = nd\n    end\n    return ll\nend\nfunction Base.pop!(ll::LinkedList{T}) where T\n    if isempty(ll)\n        throw(ArgumentError(\"list must be non-empty\"))\n    elseif ll.head.next isa EmptyNode\n        nd = ll.head\n        ll.head = EmptyNode{T}()\n    else\n        nx = ll.head\n        while !isa(nx.next.next, EmptyNode)\n            nx = nx.next\n        end\n        nd = nx.next\n        nx.next = EmptyNode{T}()\n    end\n    return nd.data\nend\n\nlst = LinkedList{Int}()\npush!(lst, 1)\npush!(lst, 2)\npush!(lst, 3)\npop!(lst) # 3\npop!(lst) # 2\npop!(lst) # 1\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":1919}
    {"lang_cluster":"Julia","source_code":"const width = height = 1000.0\nconst trunklength = 400.0\nconst scalefactor = 0.6\nconst startingangle = 1.5 * pi\nconst deltaangle = 0.2 * pi\n\nfunction tree(fh, x, y, len, theta)\n   if len >= 1.0\n       x2 = x + len * cos(theta)\n       y2 = y + len * sin(theta)\n       write(fh, \"<line x1='$x' y1='$y' x2='$x2' y2='$y2' style='stroke:rgb(0,0,0);stroke-width:1'\/>\\n\")\n       tree(fh, x2, y2, len * scalefactor, theta + deltaangle)\n       tree(fh, x2, y2, len * scalefactor, theta - deltaangle)\n    end\nend\n\noutsvg = open(\"tree.svg\", \"w\")\nwrite(outsvg, \n    \"\"\"<?xml version='1.0' encoding='utf-8' standalone='no'?>\n    <!DOCTYPE svg PUBLIC '-\/\/W3C\/\/DTD SVG 1.1\/\/EN'\n    'http:\/\/www.w3.org\/Graphics\/SVG\/1.1\/DTD\/svg11.dtd'>\n    <svg width='100%%' height='100%%' version='1.1'\n    xmlns='http:\/\/www.w3.org\/2000\/svg'>\\n\"\"\")\n\ntree(outsvg, 0.5 * width, height, trunklength, startingangle)\n\nwrite(outsvg, \"<\/svg>\\n\") # view file tree.svg in browser\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":1920}
    {"lang_cluster":"Julia","source_code":"\nusing Primes\n\n\"\"\" Return the factors of n, including 1, n \"\"\"\nfunction factors(n::T)::Vector{T} where T <: Integer\n  sort(vec(map(prod, Iterators.product((p.^(0:m) for (p, m) in eachfactor(n))...))))\nend\n\nconst examples = [28, 45, 53, 64, 6435789435768]\n\nfor n in examples\n    @time println(\"The factors of $n are: $(factors(n))\")\nend\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":1921}
    {"lang_cluster":"Julia","source_code":"txt = \"\"\"Given\\$a\\$txt\\$file\\$of\\$many\\$lines,\\$where\\$fields\\$within\\$a\\$line\\$\nare\\$delineated\\$by\\$a\\$single\\$'dollar'\\$character,\\$write\\$a\\$program\nthat\\$aligns\\$each\\$column\\$of\\$fields\\$by\\$ensuring\\$that\\$words\\$in\\$each\\$\ncolumn\\$are\\$separated\\$by\\$at\\$least\\$one\\$space.\nFurther,\\$allow\\$for\\$each\\$word\\$in\\$a\\$column\\$to\\$be\\$either\\$left\\$\njustified,\\$right\\$justified,\\$or\\$center\\$justified\\$within\\$its\\$column.\"\"\"\n\n# left\/right\/center justification of strings:\nljust(s, width) = s * \" \"^max(0, width - length(s))\nrjust(s, width) = \" \"^max(0, width - length(s)) * s\nfunction center(s, width)\n  pad = width - length(s)\n  if pad <= 0\n    return s\n  else\n    pad2 = div(pad, 2)\n    return \" \"^pad2 * s * \" \"^(pad - pad2)\n  end\nend\n \nparts = [split(rstrip(line, '$'), '$') for line in split(txt, '\\n')]\n \nmax_widths = zeros(Int, maximum(length, parts))\nfor line in parts\n  for (i, word) in enumerate(line)\n    max_widths[i] = max(max_widths[i], length(word))\n  end\nend    \nmax_widths += 1 # separate cols by at least one space\n\nfor (label, justify) in ((\"Left\", ljust), (\"Right\",rjust), (\"Center\",center))\n  println(label, \" column-aligned output:\")\n  for line in parts\n    for (j, word) in enumerate(line)\n      print(justify(word, max_widths[j]))\n    end\n    println()\n  end\n  println(\"-\"^sum(max_widths))\nend\n\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":1922}
    {"lang_cluster":"Julia","source_code":"Works with: Julia version 0.6\n_pr(t::Dict, x::Int, y::Int, z::Int) = join((rstrip(join(t[(n, m)] for n in range(0, 3+x+z))) for m in reverse(range(0, 3+y+z))), \"\\n\")\n\nfunction cuboid(x::Int, y::Int, z::Int)\n    t = Dict((n, m) => \" \" for n in range(0, 3 + x + z), m in range(0, 3 + y + z))\n    xrow = vcat(\"+\", collect(\"$(i % 10)\" for i in range(0, x)), \"+\")\n    for (i, ch) in enumerate(xrow) t[(i, 0)] = t[(i, 1+y)] = t[(1+z+i, 2+y+z)] = ch end\n    yrow = vcat(\"+\", collect(\"$(j % 10)\" for j in range(0, y)), \"+\")\n    for (j, ch) in enumerate(yrow) t[(0, j)] = t[(x+1, j)] = t[(2+x+z, 1+z+j)] = ch end\n    zdep = vcat(\"+\", collect(\"$(k % 10)\" for k in range(0, y)), \"+\")\n    for (k, ch) in enumerate(xrow) t[(k, 1+y+k)] = t[(1+x+k, 1+y+k)] = t[(1+x+k, k)] = ch end\n\n    return _pr(t, x, y, z)\nend\n\nfor (x, y, z) in [(2, 3, 4), (3, 4, 2), (4, 2, 3), (5, 5, 6)]\n    println(\"\\nCUBOID($x, $y, $z)\\n\")\n    println(cuboid(x, y, z))\nend\n\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":1923}
    {"lang_cluster":"Julia","source_code":"\nusing LDAPClient\n\nconn = LDAPClient.LDAPConnection(\"ldap:\/\/localhost:10389\")\nLDAPClient.simple_bind(conn, \"user\", \"password\")\nLDAPClient.unbind(conn)\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server.","id":1924}
    {"lang_cluster":"Julia","source_code":"\n# Julia 1.0\nfunction rot13(c::Char)\n    shft = islowercase(c) ? 'a' : 'A'\n    isletter(c) ? c = shft + (c - shft + 13) % 26 : c\nend\n\nrot13(str::AbstractString) = map(rot13, str)\n\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":1925}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nlst = Pair[Pair(\"gold\", \"shiny\"),\n           Pair(\"neon\", \"inert\"),\n           Pair(\"sulphur\", \"yellow\"),\n           Pair(\"iron\", \"magnetic\"),\n           Pair(\"zebra\", \"striped\"),\n           Pair(\"star\", \"brilliant\"),\n           Pair(\"apple\", \"tasty\"),\n           Pair(\"ruby\", \"red\"),\n           Pair(\"dice\", \"random\"),\n           Pair(\"coffee\", \"stimulating\"),\n           Pair(\"book\", \"interesting\")]\n\nprintln(\"The original list: \\n - \", join(lst, \"\\n - \"))\nsort!(lst; by=first)\nprintln(\"\\nThe list, sorted by name: \\n - \", join(lst, \"\\n - \"))\nsort!(lst; by=last)\nprintln(\"\\nThe list, sorted by value: \\n - \", join(lst, \"\\n - \"))\n\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":1926}
    {"lang_cluster":"Julia","source_code":"\nfor i in 1:5\n    for j in 1:i\n        print(\"*\")\n    end\n    println()\nend\n\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":1927}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\ndict = Dict('a' => 97, 'b' => 98) # list keys\/values\n# Dict{Char,Int64} with 2 entries:\n#   'b' => 98\n#   'a' => 97\n\ndict = Dict(c => Int(c) for c = 'a':'d') # dict comprehension\n# Dict{Char,Int64} with 4 entries:\n#   'b' => 98\n#   'a' => 97\n#   'd' => 100\n#   'c' => 99\n\ndict['\u00e9'] = 233; dict # add an element\n# Dict{Char,Int64} with 3 entries:\n#   'b' => 98\n#   'a' => 97\n#   '\u00e9' => 233\n\nemptydict = Dict() # create an empty dict\n# Dict{Any,Any} with 0 entries\n\ndict[\"a\"] = 1 # type mismatch\n# ERROR: MethodError: Cannot `convert` an object of type String to an object of type Char\n\ntypeof(dict) # type is infered correctly\n# Dict{Char,Int64}\n\n","human_summarization":"\"Creates an associative array, also known as a dictionary, map, or hash, associating characters with their code points. This is achieved through dictionary comprehension, creating an empty dictionary and filling it, and using the specific syntax for typed dictionaries.\"","id":1928}
    {"lang_cluster":"Julia","source_code":"\n\nusing Printf\n\nfunction getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer)\n    state = r\n    return function lgcrand()\n        state = mod(a * state + c, m)\n        return state >> sh\n    end\nend\n\nseed, nrep = 0, 10\nbsdrand = getlgc(seed, 1103515245, 12345, 2 ^ 31, 0)\n\nprintln(\"The first $nrep results for a BSD rand seeded with $seed:\")\nfor _ in 1:nrep\n    @printf(\"%14d\\n\", bsdrand())\nend\n\nmsrand = getlgc(seed, 214013, 2531011, 2 ^ 31, 16)\n\nprintln(\"\\nThe first $nrep results for a M\\$ rand seeded with $seed:\")\nfor _ in 1:nrep\n    @printf(\"%14d\\n\", msrand())\nend\n\n\n","human_summarization":"The code replicates two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). It uses a linear congruential generator formula to generate a sequence of random numbers, given a seed. The generated sequence matches the original generator when starting from the same seed. The code also includes a function, getlgc, which creates a linear congruential generator as a closure.","id":1929}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\nfunction Base.insert!(ll::LinkedList{T}, index::Integer, item::T) where T\n    if index == 1\n        if isempty(ll)\n            return push!(ll, item)\n        else\n            ll.head = Node{T}(item, ll.head)\n        end\n    else\n        nd = ll.head\n        while index > 2\n            if nd.next isa EmptyNode\n                throw(BoundsError())\n            else\n                nd = nd.next\n                index -= 1\n            end\n        end\n        nd.next = Node{T}(item, nd.next)\n    end\n    return ll\nend\n\n","human_summarization":"define a method to insert an element 'C' into a singly-linked list after a specified element 'A'. This is implemented in the context of a list comprised of elements A->B. The functionality also references the LinkedList implementation found in Singly-linked_list\/Element_definition#Julia.","id":1930}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\nhalve(x::Integer) = x >> one(x)\ndouble(x::Integer) = Int8(2) * x\neven(x::Integer) = x & 1 != 1\n\n\nfunction ethmult(a::Integer, b::Integer)\n    r = 0\n    while a > 0\n        r += b * !even(a)\n        a = halve(a)\n        b = double(b)\n    end\n    return r\nend\n\n@show ethmult(17, 34)\n\n\nfunction ethmult2(a::Integer, b::Integer)\n    A = [a]\n    B = [b]\n    while A[end] > 1\n        push!(A, halve(A[end]))\n        push!(B, double(B[end]))\n    end\n    return sum(B[map(!even, A)])\nend\n\n@show ethmult2(17, 34)\n\n\n","human_summarization":"The code defines three helper functions to halve, double, and check if an integer is even. These functions are then used to implement the Ethiopian multiplication method. The Ethiopian multiplication function takes two integers as input and uses the helper functions to repeatedly halve the first number and double the second number. It discards rows where the halved number is even and sums the remaining doubled numbers to produce the multiplication result.","id":1931}
    {"lang_cluster":"Julia","source_code":"\n\nfunction solve24(nums)\n    length(nums) != 4 && error(\"Input must be a 4-element Array\")\n    syms = [+,-,*,\/]\n    for x in syms, y in syms, z in syms\n        for i = 1:24\n            a,b,c,d = nthperm(nums,i)\n            if round(x(y(a,b),z(c,d)),5) == 24\n                return \"($a$y$b)$x($c$z$d)\"\n            elseif round(x(a,y(b,z(c,d))),5) == 24 \n                return \"$a$x($b$y($c$z$d))\"\n            elseif round(x(y(z(c,d),b),a),5) == 24 \n                return \"(($c$z$d)$y$b)$x$a\"\n            elseif round(x(y(b,z(c,d)),a),5) == 24 \n                return \"($b$y($c$z$d))$x$a\"\n            end\n        end\n    end\n    return \"0\"\nend\n\n\n","human_summarization":"The code takes four digits as input, either from the user or randomly generated, and computes arithmetic expressions according to the rules of the 24 game. It also displays examples of the solutions it generates. For Julia version 0.5 and higher, it requires the Combinatorics package for combinatorial functions like `nthperm`.","id":1932}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\nhelp?> factorial\nsearch: factorial Factorization factorize\n\n  factorial(n)\n\n  Factorial of n. If n is an Integer, the factorial is computed as an integer (promoted to at\n  least 64 bits). Note that this may overflow if n is not small, but you can use factorial(big(n))\n  to compute the result exactly in arbitrary precision. If n is not an Integer, factorial(n) is\n  equivalent to gamma(n+1).\n\n  julia> factorial(6)\n  720\n\n  julia> factorial(21)\n  ERROR: OverflowError()\n  [...]\n\n  julia> factorial(21.0)\n  5.109094217170944e19\n\n  julia> factorial(big(21))\n  51090942171709440000\n\nfunction fact(n::Integer)\n    n < 0 && return zero(n)\n    f = one(n)\n    for i in 2:n\n        f *= i\n    end\n    return f\nend\n\nfor i in 10:20\n\tprintln(\"$i -> \", fact(i))\nend\n\n","human_summarization":"The code is a function that calculates the factorial of a given number. It can be implemented either iteratively or recursively. The function may optionally handle errors for negative input values.","id":1933}
    {"lang_cluster":"Julia","source_code":"\nfunction cowsbulls()\n\tprint(\"Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\\n\n\t\tYou get one bull for every right number in the right position.\\n\n\t\tYou get one cow for every right number, but in the wrong position.\\n\n\t\tEnter 'n' to pick a new number and 'q' to quit.\\n>\")\n\tfunction new_number() \n\t\ts = [1:9]\n\t\tn = \"\"\n\t\tfor i = 9:-1:6\n\t\t\tn *= string(delete!(s,rand(1:i)))\n\t\tend\n\t\treturn n\n\tend\n\tanswer = new_number()\n\twhile true\n\t\tinput = chomp(readline(STDIN))\n\t\tinput == \"q\" && break\n\t\tif input == \"n\" \n\t\t\tanswer = new_number()\n\t\t\tprint(\"\\nI've picked a new number, go ahead and guess\\n>\")\n\t\t\tcontinue\n\t\tend\n\t\t!ismatch(r\"^[1-9]{4}$\",input) && (print(\"Invalid guess: Please enter a 4-digit number\\n>\"); continue)\n\t\tif input == answer \n\t\t\tprint(\"\\nYou're right! Good guessing!\\nEnter 'n' for a new number or 'q' to quit\\n>\")\n\t\telse\n\t\t\tbulls = sum(answer.data .== input.data)\n\t\t\tcows = sum([answer[x] != input[x] && contains(input.data,answer[x]) for x = 1:4])\n\t\t\tprint(\"\\nNot quite! Your guess is worth:\\n$bulls Bulls\\n$cows Cows\\nPlease guess again\\n\\n>\")\n\t\tend\n\tend\nend\n\n\nfunction bullsandcows ()\n    bulls = cows = turns = 0\n    result = (s = [] ; while length(unique(s))<4 push!(s,rand('1':'9')) end; unique(s))\n    println(\"A game of bulls and cows!\")\n    while (bulls != 4)\n      print(\"Your guess? \")\n      guess = collect(chomp(readline(STDIN)))\n      if ! (length(unique(guess)) == length(guess) == 4 && all(isdigit,guess))\n         println(\"please, enter four distincts digits\") \n         continue \n      end\n      bulls = sum(map(==, guess, result))\n      cows = length(intersect(guess,result)) - bulls\n      println(\"$bulls bulls and $cows cows!\") ; turns += 1\n    end\n    println(\"You win! You succeeded in $turns guesses.\")\n  end\n\n\n","human_summarization":"generate a four-digit random number without duplication, take player's guesses, validate the guesses, calculate and print the score based on the matching digits and their positions. The game ends when the player's guess matches the generated number.","id":1934}
    {"lang_cluster":"Julia","source_code":"\n\nrandn(1000) * 0.5 + 1\n\n","human_summarization":"generates a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using Julia's standard library function randn.","id":1935}
    {"lang_cluster":"Julia","source_code":"\n\nx = [1, 3, -5]\ny = [4, -2, -1]\nz = dot(x, y)\nz = x'*y\nz = x \u22c5 y\n\n","human_summarization":"implement a function to calculate the dot product of two vectors. The vectors can be of arbitrary length, but must be the same length for the dot product operation. The function multiplies corresponding elements from each vector and sums the results. The functionality is similar to built-in linear algebra functions in Julia.","id":1936}
    {"lang_cluster":"Julia","source_code":"\n\nstream = IOBuffer(\"1\\n2\\n3\\n4\\n\\n6\")\n\nwhile !eof(stream)\n    line = readline(stream)\n    println(line)\nend\n\n\n","human_summarization":"The code reads data from a text stream either word-by-word or line-by-line until there is no more data. It creates a text stream, reads and prints each line on the screen. The lines end with a newline except the last one. When the end of the stream is reached, an empty string is returned.","id":1937}
    {"lang_cluster":"Julia","source_code":"\nusing LightXML\n\n# Modified from the documentation for LightXML.jl. The underlying library requires an encoding string be printed.\n\n# create an empty XML document\nxdoc = XMLDocument()\n\n# create & attach a root node\nxroot = create_root(xdoc, \"root\")\n\n# create the first child\nxs1 = new_child(xroot, \"element\")\n\n# add the inner content\nadd_text(xs1, \"some text here\")\n\nprintln(xdoc)\n\n","human_summarization":"Create a simple DOM and serialize it into the specified XML format.","id":1938}
    {"lang_cluster":"Julia","source_code":"\nts = time()\n\nprintln(\"The system time is (in ISO 8601 format):\")\nprintln(strftime(\"    %F %T %Z\", ts))\n\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":1939}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nusing Base.Test\n\nfunction appendchecksum(chars::AbstractString)\n    if !all(isalnum, chars) throw(ArgumentError(\"invalid SEDOL number '$chars'\")) end\n    weights = [1, 3, 1, 7, 3, 9, 1]\n\n    s = 0\n    for (w, c) in zip(weights, chars)\n        s += w * parse(Int, c, 36)\n    end\n    return string(chars, (10 - s % 10) % 10)\nend\n\ntests = [\"710889\", \"B0YBKJ\", \"406566\", \"B0YBLH\", \"228276\", \"B0YBKL\", \"557910\", \"B0YBKR\", \"585284\", \"B0YBKT\", \"B00030\"]\ncsums = [\"7108899\", \"B0YBKJ7\", \"4065663\", \"B0YBLH2\", \"2282765\", \"B0YBKL9\", \"5579107\", \"B0YBKR5\", \"5852842\", \"B0YBKT7\", \"B000300\"]\n\n@testset \"Checksums\" begin\n    for (t, c) in zip(tests, csums)\n        @test appendchecksum(t) == c\n    end\nend\n\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":1940}
    {"lang_cluster":"Julia","source_code":"function draw_sphere(r, k, ambient, light)\n    shades = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@')\n    for i in floor(Int, -r):ceil(Int, r)\n        x = i + 0.5\n        line = IOBuffer()\n        for j in floor(Int, -2r):ceil(2r)\n            y = j \/ 2 + 0.5\n            if x ^ 2 + y ^ 2 \u2264 r ^ 2\n                v = normalize([x, y, sqrt(r ^ 2 - x ^ 2 - y ^ 2)])\n                b = dot(light, v) ^ k + ambient\n                intensity = ceil(Int, (1 - b) * (length(shades) - 1))\n                if intensity < 1\n                    intensity = 1 end\n                if intensity > length(shades)\n                    intensity = length(shades) end\n                print(shades[intensity])\n            else\n                print(' ')\n            end\n        end\n        println()\n    end\nend\n\nlight = normalize([30, 30, -50])\ndraw_sphere(20, 4, 0.1, light)\ndraw_sphere(10, 2, 0.4, light)\n\n# run from REPL\n\nusing Makie\n\n\u03c6 = 0:\u03c0\/100:2\u03c0\n\n\u03b8 = 0:\u03c0\/200:\u03c0\n\nx = [cos(\u03b8) * sin(\u03c6) for \u03b8 in \u03b8, \u03c6 in \u03c6]\ny = [sin(\u03b8)*sin(\u03c6) for \u03b8 in \u03b8, \u03c6 in \u03c6]\nz = [cos(\u03c6) for \u03b8 in \u03b8, \u03c6 in \u03c6]\n\nsurface(x, y, z, backgroundcolor = :black, show_axis = false)\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":1941}
    {"lang_cluster":"Julia","source_code":"\nusing Printf\n\n\nfunction ordinal(n::Integer)\n    n < 0 && throw(DomainError())\n    suffixes = (\"st\", \"nd\", \"rd\")\n    u = n % 10\n    t = n \u00f7 10 % 10\n    if u > 3 || u == 0 || t == 1\n        suf = \"th\"\n    else\n        suf = suffixes[u]\n    end\n    return string(n, suf)\nend\n\n\nprintln(\"Tests of ordinal formatting of integers.\")\nfor (i, n) in enumerate(0:25)\n    (i - 1) % 10 == 0 && println()\n    @printf(\"%7s\", ordinal(n))\nend\n\nprintln()\nfor (i, n) in enumerate(250:265)\n    (i - 1) % 10 == 0 && println()\n    @printf(\"%7s\", ordinal(n))\nend\n\nprintln()\nfor (i, n) in enumerate(1000:1025)\n    (i - 1) % 10 == 0 && println()\n    @printf(\"%7s\", ordinal(n))\nend\n\n\nNth(x::Integer) = if x % 100 \u2208 [11, 12, 13] \"th\" else [\"th\", \"st\", \"nd\", \"rd\", \"th\"][min(x % 10 + 1, 5)] end\nNthA(x::Integer) = \"$(x)'$(Nth(x)) \"\n[0:25..., 250:265..., 1000:1025...] .|> NthA .|> print;\n\n\n","human_summarization":"Code summarization: The given code defines a function that accepts an integer greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is used to display the output for specific ranges of integer inputs: 0-25, 250-265, and 1000-1025. The use of apostrophes in the ordinal suffix is optional.","id":1942}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 1.0\nstripChar = (s, r) -> replace(s, Regex(\"[$r]\") => \"\")\n\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":1943}
    {"lang_cluster":"Julia","source_code":"\n\nfunction fizzbuzz(triggers :: Vector{Tuple{Int, ASCIIString}}, upper :: Int)\n    for i = 1 : upper\n        triggered = false\n\n        for trigger in triggers\n            if i % trigger[1] == 0\n                triggered = true\n                print(trigger[2])\n            end\n        end\n\n        !triggered && print(i)\n        println()\n    end\nend\n\nprint(\"Enter upper limit:\\n> \")\nupper = parse(Int, readline())\n\ntriggers = Tuple{Int, ASCIIString}[]\nprint(\"Enter factor\/string pairs (space delimited; ^D when done):\\n> \")\nwhile (r = readline()) != \"\"\n    input = split(r)\n    push!(triggers, (parse(Int, input[1]), input[2]))\n    print(\"> \")\nend\n\nprintln(\"EOF\\n\")\nfizzbuzz(triggers, upper)\n\n\n","human_summarization":"The code takes a maximum number and a list of factor-word pairs as input from the user. It then prints numbers from 1 to the maximum number, replacing multiples of the factors with the corresponding words. If a number is a multiple of more than one factor, it prints all associated words in the order of the factors. For instance, for the number 15 and factors 3 (\"Fizz\") and 5 (\"Buzz\"), it prints \"FizzBuzz\". The user is assumed to provide valid input.","id":1944}
    {"lang_cluster":"Julia","source_code":"\ns = \"world!\"\ns = \"Hello \" * s\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":1945}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\nusing Luxor\nfunction dragon(turtle::Turtle, level=4, size=200, direction=45)\n    if level != 0\n        Turn(turtle, -direction)\n        dragon(turtle, level-1, size\/sqrt(2), 45)\n        Turn(turtle, direction*2)\n        dragon(turtle, level-1, size\/sqrt(2), -45)\n        Turn(turtle, -direction)\n    else\n        Forward(turtle, size)\n    end\nend\n\nDrawing(900, 500, \".\/Dragon.png\")\nt = Turtle(300, 300, true, 0, (0., 0.0, 0.0)); \ndragon(t, 10,400)\nfinish()\npreview()\n\n\n","human_summarization":"The code generates a dragon curve fractal, either displaying it directly or writing it to an image file. It uses various algorithms including recursive, successive approximation, iterative, and Lindenmayer system of expansions. It also includes functionalities to determine the curl direction, calculate absolute direction, and X,Y coordinates of a point, and to test if a given point or segment is on the curve. The code uses the Luxor library for its operations.","id":1946}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nfunction guess()\n    number = dec(rand(1:10))\n    print(\"Guess my number! \")\n    while readline() != number\n        print(\"Nope, try again... \")\n    end\n    println(\"Well guessed!\")\nend\n\nguess()\n\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":1947}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n@show collect('a':'z')\n@show join('a':'z')\n\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":1948}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 1.0\nusing Printf\n\nfor n in (0, 5, 50, 9000)\n    @printf(\"%6i \u2192 %s\\n\", n, string(n, base=2))\nend\n \n# with pad\nprintln(\"\\nwith pad\")\nfor n in (0, 5, 50, 9000)\n    @printf(\"%6i \u2192 %s\\n\", n, string(n, base=2, pad=20))\nend\n\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":1949}
    {"lang_cluster":"Julia","source_code":"using CSV, DataFrames, Statistics\n\n# load data from csv files\n#df_patients = CSV.read(\"patients.csv\", DataFrame)\n#df_visits = CSV.read(\"visits.csv\", DataFrame)\n\n# create DataFrames from text that is hard coded, so use IOBuffer(String) as input\nstr_patients = IOBuffer(\"\"\"PATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\n\"\"\")\ndf_patients = CSV.read(str_patients, DataFrame)\nstr_visits = IOBuffer(\"\"\"PATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\n\"\"\")\ndf_visits = CSV.read(str_visits, DataFrame)\n\n# merge on PATIENT_ID, using an :outer join or we lose Kurtz, who has no data, sort by ID\ndf_merge = sort(join(df_patients, df_visits, on=\"PATIENT_ID\", kind=:outer), (:PATIENT_ID,))\n\nfnonmissing(a, f) = isempty(a) ? [] : isempty(skipmissing(a)) ? a[1] : f(skipmissing(a))\n\n# group by patient id \/ last name and then aggregate to get latest visit and mean score\ndf_result = by(df_merge, [:PATIENT_ID, :LASTNAME]) do df\n    DataFrame(LATEST_VISIT = fnonmissing(df[:VISIT_DATE], maximum),\n              SUM_SCORE = fnonmissing(df[:SCORE], sum),\n              MEAN_SCORE = fnonmissing(df[:SCORE], mean))\nend\nprintln(df_result)\n\n","human_summarization":"\"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file.\"","id":1950}
    {"lang_cluster":"Julia","source_code":"\nusing Gtk, Graphics\n \nconst can = @GtkCanvas()\nconst win = GtkWindow(can, \"Draw a Pixel\", 320, 240)\n\ndraw(can) do widget\n    ctx = getgc(can)\n    set_source_rgb(ctx, 255, 0, 0)\n    move_to(ctx, 100, 100)\n    line_to(ctx, 101,100)\n    stroke(ctx)\nend\n \nshow(can)\nconst cond = Condition()\nendit(w) = notify(cond)\nsignal_connect(endit, win, :destroy)\nwait(cond)\n\n","human_summarization":"\"Creates a 320x240 window and draws a single red pixel at position (100, 100).\"","id":1951}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nfunction readconf(file)\n    vars = Dict()\n    for line in eachline(file)\n        line = strip(line)\n        if !isempty(line) && !startswith(line, '#') && !startswith(line, ';')\n            fspace  = searchindex(line, \" \")\n            if fspace == 0\n                vars[Symbol(lowercase(line))] = true\n            else\n                vname, line = Symbol(lowercase(line[1:fspace-1])), line[fspace+1:end]\n                value = ',' \u2208 line ? strip.(split(line, ',')) : line\n                vars[vname] = value\n            end\n        end\n    end\n    for (vname, value) in vars\n        eval(:($vname = $value))\n    end\n    return vars\nend\n\nreadconf(\"test.conf\")\n\n@show fullname favouritefruit needspeeling otherfamily\n\n\n","human_summarization":"read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.","id":1952}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nhaversine(lat1, lon1, lat2, lon2) =\n    2 * 6372.8 * asin(sqrt(sind((lat2 - lat1) \/ 2) ^ 2 +\n    cosd(lat1) * cosd(lat2) * sind((lon2 - lon1) \/ 2) ^ 2))\n\n@show haversine(36.12, -86.67, 33.94, -118.4)\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":1953}
    {"lang_cluster":"Julia","source_code":"\nreadurl(url) = open(readlines, download(url))\n\nreadurl(\"http:\/\/rosettacode.org\/index.html\")\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":1954}
    {"lang_cluster":"Julia","source_code":"\n\nluhntest(x::Integer) = (sum(digits(x)[1:2:end]) + sum(map(x -> sum(digits(x)), 2 * digits(x)[2:2:end]))) % 10 == 0\n\n\nfunction luhntest(x::Integer)\n    d = reverse(digits(x))\n    s = sum(d[1:2:end])\n    s += sum(sum.(digits.(2d[2:2:end])))\n    return s % 10 == 0\nend\n\nfor card in [49927398716, 49927398717, 1234567812345678, 1234567812345670]\n    println(luhntest(card) ? \"PASS \" : \"FAIL \", card)\nend\n\n\n","human_summarization":"\"Implement a function to validate credit card numbers using the Luhn algorithm. The function takes a number as input, reverses the digits, calculates two partial sums s1 and s2 by summing odd digits and summing the digits of twice the even digits respectively, and checks if the total sum ends in zero. The function is used to validate a set of given numbers.\"","id":1955}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\nusing Memoize\n@memoize josephus(n::Integer, k::Integer, m::Integer=1) = n == m ? collect(0:m .- 1) : mod.(josephus(n - 1, k, m) + k, n)\n\n@show josephus(41, 3)\n@show josephus(41, 3, 5)\n\n\n","human_summarization":"The code determines the final survivor in the Josephus problem, given a number of prisoners and a step count for execution. It also provides a way to calculate which prisoner is at any given position on the killing sequence. The prisoners can be numbered either from 0 to n-1 or from 1 to n. The code uses both recursive and iterative methods. The complexity of the solution is O(kn) for the complete killing sequence and O(m) for the m-th prisoner to die.","id":1956}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 1.0\n@show \"ha\" ^ 5\n\n# The ^ operator is really just call to the `repeat` function\n@show repeat(\"ha\", 5)\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":1957}
    {"lang_cluster":"Julia","source_code":"\ns = \"I am a string\"\nif ismatch(r\"string$\", s)\n    println(\"'$s' ends with 'string'\")\nend\n\n\ns = \"I am a string\"\ns = replace(s, r\" (a|an) \", \" another \")\n\n\n","human_summarization":"implement Perl-compatible regular expressions in Julia using the built-in PCRE library. They test for a match in a string and perform substitutions in part of a string using a regular expression.","id":1958}
    {"lang_cluster":"Julia","source_code":"\nfunction arithmetic (a = parse(Int, readline()), b = parse(Int, readline()))\n  for op in  [+,-,*,div,rem]\n    println(\"a $op b = $(op(a,b))\")\n  end\nend\n\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":1959}
    {"lang_cluster":"Julia","source_code":"\n\nmatchall(r::Regex, s::String[, overlap::Bool=false]) -> Vector{String}\n\n   Return a vector of the matching substrings from eachmatch.\n\n\nts = [\"the three truths\", \"ababababab\"]\ntsub = [\"th\", \"abab\"]\n\nprintln(\"Test of non-overlapping substring counts.\")\nfor i in 1:length(ts)\n    print(ts[i], \" (\", tsub[i], \") => \")\n    println(length(matchall(Regex(tsub[i]), ts[i])))\nend\nprintln()\nprintln(\"Test of overlapping substring counts.\")\nfor i in 1:length(ts)\n    print(ts[i], \" (\", tsub[i], \") => \")\n    println(length(matchall(Regex(tsub[i]), ts[i], true)))\nend\n\n\n","human_summarization":"The code defines a function that counts the number of non-overlapping occurrences of a specific substring within a given string. It takes two arguments: the main string and the substring to search for. The function returns an integer representing the count of non-overlapping occurrences. The matching process is done either from left-to-right or right-to-left to yield the maximum number of matches.","id":1960}
    {"lang_cluster":"Julia","source_code":"function solve(n::Integer, from::Integer, to::Integer, via::Integer)\n  if n == 1\n    println(\"Move disk from $from to $to\")\n  else\n    solve(n - 1, from, via, to)\n    solve(1, from, to, via)\n    solve(n - 1, via, to, from)\n  end\nend\n\nsolve(4, 1, 2, 3)\n\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":1961}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 1.2\n\n@show binomial(5, 3)\n\n\nfunction binom(n::Integer, k::Integer)\n    n \u2265 k || return 0 # short circuit base cases\n    (n == 1 || k == 0) && return 1\n\n    n * binom(n - 1, k - 1) \u00f7 k\nend\n\n@show binom(5, 3)\n\n\n","human_summarization":"The code calculates binomial coefficients, specifically it is able to output the binomial coefficient of 5 choose 3, which is 10. It uses the formula for binomial coefficients and can handle tasks related to combinations, permutations, combinations with repetitions, and permutations with repetitions. It also includes a built-in recursive version.","id":1962}
    {"lang_cluster":"Julia","source_code":"# v0.6\n\nfunction shellsort!(a::Array{Int})::Array{Int}\n    incr = div(length(a), 2)\n    while incr > 0\n        for i in incr+1:length(a)\n            j = i\n            tmp = a[i]\n            while j > incr && a[j - incr] > tmp\n                a[j] = a[j-incr]\n                j -= incr\n            end\n            a[j] = tmp\n        end\n        if incr == 2\n            incr = 1\n        else\n            incr = floor(Int, incr * 5.0 \/ 11)\n        end\n    end\n    return a\nend\n\nx = rand(1:10, 10)\n@show x shellsort!(x)\n@assert issorted(x)\n\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":1963}
    {"lang_cluster":"Julia","source_code":"\n\nusing Color, Images, FixedPointNumbers\n\nconst M_RGB_Y = reshape(Color.M_RGB_XYZ[2,:], 3)\n\nfunction rgb2gray(img::Image)\n    g = red(img)*M_RGB_Y[1] + green(img)*M_RGB_Y[2] + blue(img)*M_RGB_Y[3]\n    g = clamp(g, 0.0, 1.0)\n    return grayim(g)\nend\n\nfunction gray2rgb(img::Image)\n    colorspace(img) == \"Gray\" || return img\n    g = map((x)->RGB{Ufixed8}(x, x, x), img.data)\n    return Image(g, spatialorder=spatialorder(img))\nend\n \nima = imread(\"grayscale_image_color.png\")\nimb = rgb2gray(ima)\nimc = gray2rgb(imb)\nimwrite(imc, \"grayscale_image_rc.png\")\n\n\nusing Color, Images, FixedPointNumbers\n\nima = imread(\"grayscale_image_color.png\")\nimb = convert(Image{Gray{Ufixed8}}, ima)\nimwrite(imb, \"grayscale_image_julia.png\")\n\n\n","human_summarization":"The code extends the data storage type to support grayscale images. It defines two operations: one to convert a color image to a grayscale image and another for the reverse conversion. The conversion uses the CIE recommended formula for luminance calculation. The code also ensures that rounding errors from floating-point arithmetic do not cause run-time issues or distorted results. The code may also reverse compansion before applying the CIE transformation to extract luminance from RGB.","id":1964}
    {"lang_cluster":"Julia","source_code":"\nLibrary: Julia\/Tk\nusing Tk\n\nconst frameinterval = 0.12 # partial seconds between change on screen display\n\nfunction windowanim(stepinterval::Float64)\n    wind = Window(\"Animation\", 300, 100)\n    frm = Frame(wind)\n    hello = \"Hello World!                                           \"\n    but = Button(frm, width=30, text=hello)\n    rightward = true\n    callback(s) = (rightward = !rightward)\n    bind(but, \"command\", callback)\n    pack(frm, expand=true, fill = \"both\")\n    pack(but, expand=true, fill = \"both\")\n    permut = [hello[i:end] * hello[1:i-1] for i in length(hello)+1:-1:2]\n    ppos = 1\n    pmod = length(permut)\n    while true\n        but[:text] = permut[ppos]\n        sleep(stepinterval)\n        if rightward\n            ppos += 1\n            if ppos > pmod\n                ppos = 1\n            end\n        else\n            ppos -= 1\n            if ppos < 1\n                ppos = pmod\n            end\n        end\n    end\nend\n\nwindowanim(frameinterval)\n\nLibrary: Julia\/Gtk\nusing Gtk.ShortNames\n \nconst frameinterval = 0.12 # partial seconds between change on screen display\n \nfunction textanimation(stepinterval::Float64)\n    hello = \"Hello World!                        \"\n    win = Window(\"Animation\", 210, 40) |> (Frame() |> (but = Button(\"Switch Directions\")))\n    rightward = true\n    switchdirections(s) = (rightward = !rightward)\n    signal_connect(switchdirections, but, \"clicked\")\n    permut = [hello[i:end] * hello[1:i-1] for i in length(hello)+1:-1:2]\n    ppos = 1\n    pmod = length(permut)\n    nobreak = true\n    endit(w) = (nobreak = false)    \n    signal_connect(endit, win, :destroy)\n    showall(win)\n    while nobreak\n        setproperty!(but, :label, permut[ppos])        \n        sleep(stepinterval)\n        if rightward\n            ppos += 1\n            if(ppos > pmod)\n                ppos = 1\n            end\n        else\n            ppos -= 1\n            if(ppos < 1)\n                ppos = pmod\n            end\n        end\n    end\nend\n\ntextanimation(frameinterval)\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":1965}
    {"lang_cluster":"Julia","source_code":"\n\njulia> i = 0\n0\n\njulia> while true\n           println(i)\n           i += 1\n           i % 6 == 0 && break\n       end\n0\n1\n2\n3\n4\n5\n\n\njulia> @eval macro $(:do)(block, when::Symbol, condition)\n           when \u2260 :when && error(\"@do expected `when` got `$s`\")\n           quote\n               let\n                   $block\n                   while $condition\n                       $block\n                   end\n               end\n           end |> esc\n       end\n@do (macro with 1 method)\n\njulia> i = 0\n0\n\njulia> @do begin\n           @show i\n           i += 1\n       end when i % 6 \u2260 0\ni = 0\ni = 1\ni = 2\ni = 3\ni = 4\ni = 5\n\n\njulia> macro do_while(condition, block)\n           quote\n               let\n                   $block\n                   while $condition\n                       $block\n                   end\n               end\n           end |> esc\n       end\n@do_while (macro with 1 method)\n\njulia> i = 0\n0\n\njulia> @do_while i % 6 \u2260 0 begin\n           @show i\n           i += 1\n       end\ni = 0\ni = 1\ni = 2\ni = 3\ni = 4\ni = 5\n\n","human_summarization":"implement a do-while loop in Julia that starts with a value at 0 and continues to loop while the value mod 6 is not equal to 0. In each iteration, the value is incremented by 1 and then printed. The loop is executed at least once. The do-while behavior is mimicked using a macro that resembles the classic C style do-while, using 'when' instead of 'while' due to keyword restrictions in Julia.","id":1966}
    {"lang_cluster":"Julia","source_code":"\n\nsizeof(\"m\u00f8\u00f8se\") # 7\nsizeof(\"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\") # 28\nsizeof(\"J\u0332o\u0332s\u0332\u00e9\u0332\") # 13\nlength(\"m\u00f8\u00f8se\") # 5\nlength(\"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\") # 7\nlength(\"J\u0332o\u0332s\u0332\u00e9\u0332\") # 8\nimport Unicode\nlength(Unicode.graphemes(\"m\u00f8\u00f8se\")) # 5\nlength(Unicode.graphemes(\"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\")) # 7\nlength(Unicode.graphemes(\"J\u0332o\u0332s\u0332\u00e9\u0332\")) # 4\n","human_summarization":"determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. It handles non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The code also provides the string length in graphemes if possible. In Julia, the byte length is determined using sizeof and the string length is determined using length.","id":1967}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Linux\nconst rdev = \"\/dev\/random\"\nrstream = try\n    open(rdev, \"r\")\ncatch\n    false\nend\n\nif isa(rstream, IOStream)\n    b = readbytes(rstream, 4)\n    close(rstream)\n    i = reinterpret(Int32, b)[1]\n    println(\"A hardware random number is:  \", i)\nelse\n    println(\"The hardware random number stream, \", rdev, \", was unavailable.\")\nend\n\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.","id":1968}
    {"lang_cluster":"Julia","source_code":"\njulia> \"My String\"[2:end] # without first character\n\"y String\"\n\njulia> \"My String\"[1:end-1] # without last character\n\"My Strin\"\n\njulia> \"My String\"[2:end-1] # without first and last characters\n\"y Strin\"\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":1969}
    {"lang_cluster":"Julia","source_code":"\nconst portnum = 12345\n\nfunction canopen()\n    try\n        server = listen(portnum)\n        println(\"This is the only instance.\")\n        sleep(20)\n    catch y\n        if findfirst(\"EADDRINUSE\", string(y)) != nothing\n            println(\"There is already an instance running.\")\n        end\n    end\nend\n\ncanopen()\n\n","human_summarization":"\"Check if an application instance is already running, display a message if so, and terminate the program.\"","id":1970}
    {"lang_cluster":"Julia","source_code":"\n\nwin = GtkWindow(\"hello\", 100, 100)\nfullscreen(win)\nsleep(10)\nprintln(width(win), \" \", height(win))\ndestroy(win)\n\n\n","human_summarization":"\"Determines the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations and menubars. It adjusts for multiple monitors and tiling window managers, using the Gtk library.\"","id":1971}
    {"lang_cluster":"Julia","source_code":"\nfunction check(i, j)\n    id, im = div(i, 9), mod(i, 9)\n    jd, jm = div(j, 9), mod(j, 9)\n\n    jd == id && return true\n    jm == im && return true\n\n    div(id, 3) == div(jd, 3) &&\n    div(jm, 3) == div(im, 3)\nend\n\nconst lookup = zeros(Bool, 81, 81)\n\nfor i in 1:81\n    for j in 1:81\n        lookup[i,j] = check(i-1, j-1)\n    end\nend\n\nfunction solve_sudoku(callback::Function, grid::Array{Int64})\n    (function solve()\n        for i in 1:81\n            if grid[i] == 0\n                t = Dict{Int64, Nothing}()\n\n                for j in 1:81\n                    if lookup[i,j]\n                        t[grid[j]] = nothing\n                    end\n                end\n\n                for k in 1:9\n                    if !haskey(t, k)\n                        grid[i] = k\n                        solve()\n                    end\n                end\n\n                grid[i] = 0\n                return\n            end\n        end\n\n        callback(grid)\n    end)()\nend\n\nfunction display(grid)\n    for i in 1:length(grid)\n        print(grid[i], \" \")\n        i %  3 == 0 && print(\" \")\n        i %  9 == 0 && print(\"\\n\")\n        i % 27 == 0 && print(\"\\n\")\n    end\nend\n\ngrid = Int64[5, 3, 0, 0, 2, 4, 7, 0, 0,\n             0, 0, 2, 0, 0, 0, 8, 0, 0,\n             1, 0, 0, 7, 0, 3, 9, 0, 2,\n             0, 0, 8, 0, 7, 2, 0, 4, 9,\n             0, 2, 0, 9, 8, 0, 0, 7, 0,\n             7, 9, 0, 0, 0, 0, 0, 8, 0,\n             0, 0, 0, 0, 3, 0, 5, 0, 6,\n             9, 6, 0, 0, 1, 0, 3, 0, 0,\n             0, 5, 0, 6, 9, 0, 0, 1, 0]\n\nsolve_sudoku(display, grid)\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":1972}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nfunction knuthshuffle!(r::AbstractRNG, v::AbstractVector)\n    for i in length(v):-1:2\n        j = rand(r, 1:i)\n        v[i], v[j] = v[j], v[i]\n    end\n    return v\nend\nknuthshuffle!(v::AbstractVector) = knuthshuffle!(Base.Random.GLOBAL_RNG, v)\n\nv = collect(1:20)\nprintln(\"# v = $v\\n   -> \", knuthshuffle!(v))\n\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":1973}
    {"lang_cluster":"Julia","source_code":"\nusing Dates\n\nconst wday = Dates.Fri\nconst lo = 1\nconst hi = 12\n\nprint(\"\\nThis script will print the last \", Dates.dayname(wday))\nprintln(\"s of each month of the year given.\")\nprintln(\"(Leave input empty to quit.)\")\n\nwhile true\n    print(\"\\nYear> \")\n    y = chomp(readline())\n    0 < length(y) || break\n    y = try\n        parseint(y)\n    catch\n        println(\"Sorry, but \\\"\", y, \"\\\" does not compute as a year.\")\n        continue\n    end\n    println()\n    for m in Date(y, lo):Month(1):Date(y, hi)\n        println(\"    \", tolast(m, wday))\n    end\nend\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":1974}
    {"lang_cluster":"Julia","source_code":"\n\nprint(\"Goodbye, World!\")\n\n","human_summarization":"display the string \"Goodbye, World!\" without appending a newline at the end, using Julia's print function which doesn't automatically insert a newline.","id":1975}
    {"lang_cluster":"Julia","source_code":"\nusing Gtk\n\nfunction twoentrywindow()\n    txt = \"Enter Text Here\"\n    txtchanged = false\n    \n    win = GtkWindow(\"Keypress Test\", 500, 100) |> (GtkFrame() |> (vbox = GtkBox(:v)))\n    lab = GtkLabel(\"Enter some text in the first box and 7500 into the second box.\")\n    txtent = GtkEntry()\n    set_gtk_property!(txtent,:text,\"Enter Some Text Here\")\n    nument = GtkEntry()\n    set_gtk_property!(nument,:text,\"Enter the number seventy-five thousand here\")\n    push!(vbox, lab, txtent, nument)\n    \n    function keycall(w, event)\n        strtxt = get_gtk_property(txtent, :text, String)\n        numtxt = get_gtk_property(nument, :text, String)\n        if strtxt != txt && occursin(\"75000\", numtxt)\n            set_gtk_property!(lab, :label, \"You have accomplished the task.\")\n        end\n    end\n    signal_connect(keycall, win, \"key-press-event\")\n\n    cond = Condition()\n    endit(w) = notify(cond)\n    signal_connect(endit, win, :destroy)\n    showall(win)\n    wait(cond)\nend\n\ntwoentrywindow()\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":1976}
    {"lang_cluster":"Julia","source_code":"\n# Caeser cipher\n# Julia 1.5.4\n# author: manuelcaeiro | https:\/\/github.com\/manuelcaeiro\n\nfunction csrcipher(text, key)\n    ciphtext = \"\"\n    for l in text\n        numl = Int(l)\n        ciphnuml = numl + key\n        if numl in 65:90\n            if ciphnuml > 90\n                rotciphnuml = ciphnuml - 26\n                ciphtext = ciphtext * Char(rotciphnuml)\n            else\n                ciphtext = ciphtext * Char(ciphnuml)\n            end\n        elseif numl in 97:122\n            if ciphnuml > 122\n                rotciphnuml = ciphnuml - 26\n                ciphtext = ciphtext * Char(rotciphnuml)\n            else\n                ciphtext = ciphtext * Char(ciphnuml)\n            end\n        else\n            ciphtext = ciphtext * Char(numl)\n        end\n    end\n    return ciphtext\nend\n\ntext = \"Magic Encryption\"; key = 13\ncsrcipher(text, key)\n\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":1977}
    {"lang_cluster":"Julia","source_code":"\n\nlcm(m,n)\n\n","human_summarization":"Computes the least common multiple (LCM) of two integers, m and n, which is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":1978}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nmodule CUSIP\n\nfunction _lastdigitcusip(input::AbstractString)\n    input = uppercase(input)\n    s = 0\n\n    for (i, c) in enumerate(input)\n        if isdigit(c)\n            v = Int(c) - 48\n        elseif isalpha(c)\n            v = Int(c) - 64 + 9\n        elseif c == '*'\n            v = 36\n        elseif c == '@'\n            v = 37\n        elseif c == '#'\n            v = 38\n        end\n\n        if iseven(i); v *= 2 end\n        s += div(v, 10) + rem(v, 10)\n    end\n\n    return Char(rem(10 - rem(s, 10), 10) + 48)\nend\n\ncheckdigit(input::AbstractString) = input[9] == _lastdigitcusip(input[1:8])\n\nend  # module CUSIP\n\nfor code in (\"037833100\", \"17275R102\", \"38259P508\", \"594918104\", \"68389X106\", \"68389X105\")\n    println(\"$code is \", CUSIP.checkdigit(code) ? \"correct.\" : \"not correct.\")\nend\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":1979}
    {"lang_cluster":"Julia","source_code":"\n\nprint(\"This host's word size is \", WORD_SIZE, \".\")\nif ENDIAN_BOM == 0x04030201\n    println(\"And it is a little-endian machine.\")\nelseif ENDIAN_BOM == 0x01020304\n    println(\"And it is a big-endian machine.\")\nelse\n    println(\"ENDIAN_BOM = \", ENDIAN_BOM, \", which is confusing\")\nend\n\n\n","human_summarization":"The code prints the word size and endianness of the host machine, using Julia's ENDIAN_BOM, a 32-bit unsigned integer created from an array of four 8-bit unsigned integers, as an endianness marker.","id":1980}
    {"lang_cluster":"Julia","source_code":"\n\n\"\"\" Rosetta code task rosettacode.org\/wiki\/Rosetta_Code\/Rank_languages_by_popularity \"\"\"\n\nusing Dates\nusing DataFrames\nusing HTTP\nusing JSON3\n\n\"\"\" Get listing of all tasks and draft tasks with authors and dates created, with the counts as popularity \"\"\"\nfunction rosetta_code_language_example_counts(verbose = false)\n    URL = \"https:\/\/rosettacode.org\/w\/api.php?\"\n    LANGPARAMS = [\"action\" => \"query\", \"format\" => \"json\", \"formatversion\" => \"2\", \"generator\" => \"categorymembers\",\n       \"gcmtitle\" => \"Category:Programming_Languages\", \"gcmlimit\" => \"500\", \"rawcontinue\" => \"\", \"prop\" => \"title\"]\n    queryparams = copy(LANGPARAMS)\n    df = empty!(DataFrame([[\"\"], [0]], [\"ProgrammingLanguage\", \"ExampleCount\"]))\n\n    while true  # get all the languages listed, with curid, eg rosettacode.org\/w\/index.php?curid=196 for C\n        resp = HTTP.get(URL * join(map(p -> p[1] * (p[2] == \"\" ? \"\" : (\"=\" * p[2])), queryparams), \"&\"))\n        json = JSON3.read(String(resp.body))\n        pages = json.query.pages\n        reg = r\"The following \\d+ pages are in this category, out of ([\\d\\,]+) total\"\n        for p in pages\n            lang = replace(p.title, \"Category:\" => \"\")\n            langpage = String(HTTP.get(\"https:\/\/rosettacode.org\/w\/index.php?curid=\" * string(p.pageid)).body)\n            if !((m = match(reg, langpage)) isa Nothing)\n                push!(df, [lang, parse(Int, replace(m.captures[1], \",\" => \"\"))])\n                verbose && println(\"Language: $lang, count: \", m.captures[1])\n            end\n        end\n        !haskey(json, \"query-continue\") && break  # break if no more pages, else continue to next pages\n        queryparams = vcat(LANGPARAMS, \"gcmcontinue\" => json[\"query-continue\"][\"categorymembers\"][\"gcmcontinue\"])\n    end\n\n    return sort!(df, :ExampleCount, rev = true)\nend\n\nprintln(\"Top 20 Programming Languages on Rosetta Code by Number of Examples, As of: \", now())\nprintln(rosetta_code_language_example_counts()[begin:begin+19, :])\n\n","human_summarization":"The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It uses both web scraping and API methods to access data. The code also includes optional functionality to filter incorrect results. It generates a complete ranked list of all programming languages, which is updated periodically.","id":1981}
    {"lang_cluster":"Julia","source_code":"for i in collection\n   println(i)\nend\n\n\n","human_summarization":"utilize Julia's \"for each\" loop or \"range\" syntax to iterate over and print each element in a collection, including arrays, tuples, strings, dictionaries, and numeric scalars.","id":1982}
    {"lang_cluster":"Julia","source_code":"\ns = \"Hello,How,Are,You,Today\"\na = split(s, \",\")\nt = join(a, \".\")\n\nprintln(\"The string \\\"\", s, \"\\\"\")\nprintln(\"Splits into \", a)\nprintln(\"Reconstitutes to \\\"\", t, \"\\\"\")\n\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":1983}
    {"lang_cluster":"Julia","source_code":"\n\njulia> gcd(4,12)\n4\njulia> gcd(6,12)\n6\njulia> gcd(7,12)\n1\n\nfunction gcd{T<:Integer}(a::T, b::T)\n    neg = a < 0\n    while b\u00a0!= 0\n        t = b\n        b = rem(a, b)\n        a = t\n    end\n    g = abs(a)\n    neg\u00a0? -g\u00a0: g\nend\n\n","human_summarization":"find the greatest common divisor (GCD), also known as the greatest common factor (gcf) and greatest common measure, of two integers using Julia's built-in gcd function. This function is implemented in Julia 0.2's standard library and uses a different implementation from the GMP library for arbitrary-precision integers. The code is related to the task of finding the least common multiple.","id":1984}
    {"lang_cluster":"Julia","source_code":"\nusing Sockets # for version 1.0\nprintln(\"Echo server on port 12321\")\ntry\n    server = listen(12321)\n    instance = 0\n    while true\n        sock = accept(server)\n        instance += 1\n        socklabel = \"$(getsockname(sock)) number $instance\"\n        @async begin \n            println(\"Server connected to socket $socklabel\")\n            write(sock, \"Connected to echo server.\\r\\n\")\n            while isopen(sock)\n                str = readline(sock)\n                write(sock,\"$str\\r\\n\")\n                println(\"Echoed $str to socket $socklabel\")\n            end\n            println(\"Closed socket $socklabel\")\n        end\n    end\ncatch y\n    println(\"Caught exception: $y\")\nend\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":1985}
    {"lang_cluster":"Julia","source_code":"\n\nusing Printf\n\nisnumber(s::AbstractString) = tryparse(Float64, s) isa Number\n\ntests = [\"1\", \"-121\", \"one\", \"pi\", \"1 + 1\", \"NaN\", \"1234567890123456789\", \"1234567890123456789123456789\",\n        \"1234567890123456789123456789.0\", \"1.3\", \"1.4e10\", \"Inf\", \"1\/\/2\", \"1.0 + 1.0im\"]\n\nfor t in tests\n    fl = isnumber(t) ? \"is\" : \"is not\"\n    @printf(\"%35s %s a direct numeric literal.\\n\", t, fl)\nend\n\n\n","human_summarization":"The code defines a boolean function, isnumber, that checks if a given string can be parsed directly into a numeric value, including floating point and negative numbers. It does not consider symbols, expressions, or complex number literals that can evaluate to numbers.","id":1986}
    {"lang_cluster":"Julia","source_code":"\n# v0.6.0\n\nusing Requests\n\nstr = readstring(get(\"https:\/\/sourceforge.net\/\"))\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":1987}
    {"lang_cluster":"Julia","source_code":"\nusing Luxor\n\nisinside(p, a, b) = (b.x - a.x) * (p.y - a.y) > (b.y - a.y) * (p.x - a.x)\n\nfunction intersection(a, b, s, f)\n    dc = [a.x - b.x, a.y - b.y]\n    dp = [s.x - f.x, s.y - f.y]\n    n1 = a.x * b.y - a.y * b.x\n    n2 = s.x * f.y - s.y * f.x\n    n3 = 1.0 \/ (dc[1] * dp[2] - dc[2] * dp[1])\n    Point((n1 * dp[1] - n2 * dc[1]) * n3, (n1 * dp[2] - n2 * dc[2]) * n3)\nend\n\nfunction clipSH(spoly, cpoly)\n    outarr = spoly\n    q = cpoly[end]\n    for p in cpoly\n        inarr = outarr\n        outarr = Point[]\n        s = inarr[end]\n        for vtx in inarr\n            if isinside(vtx, q, p)\n                if !isinside(s, q, p)\n                    push!(outarr, intersection(q, p, s, vtx))\n                end\n                push!(outarr, vtx)\n            elseif isinside(s, q, p)\n                push!(outarr, intersection(q, p, s, vtx))\n            end\n            s = vtx\n        end\n        q = p\n    end\n    outarr\nend\n\nsubjectp = [Point(50, 150), Point(200, 50), Point(350, 150), Point(350, 300),\n    Point(250, 300), Point(200, 250), Point(150, 350), Point(100, 250), Point(100, 200)]\n\nclipp = [Point(100, 100), Point(300, 100), Point(300, 300), Point(100, 300)]\n\nDrawing(400, 400, \"intersecting-polygons.png\")\nbackground(\"white\")\nsethue(\"red\")\npoly(subjectp, :stroke, close=true)\nsethue(\"blue\")\npoly(clipp, :stroke, close=true)\nclipped = clipSH(subjectp, clipp)\nsethue(\"gold\")\npoly(clipped, :fill, close=true)\nfinish()\npreview()\nprintln(clipped)\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":1988}
    {"lang_cluster":"Julia","source_code":"\n\nfunction ties{T<:Real}(a::Array{T,1})\n    unique(a[2:end][a[2:end] .== a[1:end-1]])\nend\n\n\nfunction rankstandard{T<:Real}(a::Array{T,1})\n    r = collect(1:length(a))\n    1 < r[end] || return r\n    for i in ties(a)\n        r[a.==i] = r[a.==i][1]\n    end\n    return r\nend\n\n\nfunction rankmodified{T<:Real}(a::Array{T,1})\n    indexin(a, a)\nend\n\n\nfunction rankdense{T<:Real}(a::Array{T,1})\n    indexin(a, unique(a))\nend\n\n\nfunction rankordinal{T<:Real}(a::Array{T,1})\n    collect(1:length(a))\nend\n\n\nfunction rankfractional{T<:Real}(a::Array{T,1})\n    r = float64(collect(1:length(a)))\n    1.0 < r[end] || return r\n    for i in ties(a)\n        r[a.==i] = mean(r[a.==i])\n    end\n    return r\nend\n\n\nscores = [44, 42, 42, 41, 41, 41, 39]\nnames = [\"Solomon\", \"Jason\", \"Errol\", \"Garry\",\n         \"Bernard\", \"Barry\", \"Stephen\"]\n\nsrank = rankstandard(scores)\nmrank = rankmodified(scores)\ndrank = rankdense(scores)\norank = rankordinal(scores)\nfrank = rankfractional(scores)\n\nprintln(\"    Name    Score  Std  Mod  Den  Ord  Frac\")\nfor i in 1:length(scores)\n    print(@sprintf(\"   %-7s\", names[i]))\n    print(@sprintf(\"%5d \", scores[i]))\n    print(@sprintf(\"%5d\", srank[i]))\n    print(@sprintf(\"%5d\", mrank[i]))\n    print(@sprintf(\"%5d\", drank[i]))\n    print(@sprintf(\"%5d\", orank[i]))\n    print(@sprintf(\"%7.2f\", frank[i]))\n    println()\nend\n\n\n","human_summarization":"The code includes functions to apply different ranking methods (Standard, Modified, Dense, Ordinal, Fractional) on a given list of competition scores. It also includes a helper function to identify duplicated scores. The ranking methods handle ties differently as per their definitions. The ordinal ranking function assumes that the list position already reflects any tie-breaking policy.","id":1989}
    {"lang_cluster":"Julia","source_code":"\n# v0.6.0\n\nrad = \u03c0 \/ 4\ndeg = 45.0\n\n@show rad deg\n@show sin(rad) sin(deg2rad(deg))\n@show cos(rad) cos(deg2rad(deg))\n@show tan(rad) tan(deg2rad(deg))\n@show asin(sin(rad)) asin(sin(rad)) |> rad2deg\n@show acos(cos(rad)) acos(cos(rad)) |> rad2deg\n@show atan(tan(rad)) atan(tan(rad)) |> rad2deg\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":1990}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\nusing MathProgBase, Cbc\n\nstruct KPDSupply{T<:Integer}\n    item::String\n    weight::T\n    value::T\n    quant::T\nend\nBase.show(io::IO, kdps::KPDSupply) = print(io, kdps.quant, \" \", kdps.item, \" ($(kdps.weight) kg, $(kdps.value) \u20ac)\")\n\nfunction solve(gear::Vector{KPDSupply{T}}, capacity::Integer) where T<:Integer\n    w = getfield.(gear, :weight)\n    v = getfield.(gear, :value)\n    q = getfield.(gear, :quant)\n    sol = mixintprog(-v, w', '<', capacity, :Int, 0, q, CbcSolver())\n    sol.status == :Optimal || error(\"this problem could not be solved\")\n\n    if all(q .== 1) # simpler case\n        return gear[sol.sol == 1.0]\n    else\n        pack = similar(gear, 0)\n        s = round.(Int, sol.sol)\n        for (i, g) in enumerate(gear)\n            iszero(s[i]) && continue\n            push!(pack, KPDSupply(g.item, g.weight, g.value, s[i]))\n        end\n        return pack\n    end\nend\n\n\ngear = [KPDSupply(\"map\", 9, 150, 1),\n        KPDSupply(\"compass\", 13, 35, 1),\n        KPDSupply(\"water\", 153, 200, 2),\n        KPDSupply(\"sandwich\", 50, 60, 2),\n        KPDSupply(\"glucose\", 15, 60, 2),\n        KPDSupply(\"tin\", 68, 45, 3),\n        KPDSupply(\"banana\", 27, 60, 3),\n        KPDSupply(\"apple\", 39, 40, 3),\n        KPDSupply(\"cheese\", 23, 30, 1),\n        KPDSupply(\"beer\", 52, 10, 3),\n        KPDSupply(\"suntan cream\", 11, 70, 1),\n        KPDSupply(\"camera\", 32, 30, 1),\n        KPDSupply(\"T-shirt\", 24, 15, 2),\n        KPDSupply(\"trousers\", 48, 10, 2),\n        KPDSupply(\"umbrella\", 73, 40, 1),\n        KPDSupply(\"waterproof trousers\", 42, 70, 1),\n        KPDSupply(\"waterproof overclothes\", 43, 75, 1),\n        KPDSupply(\"note-case\", 22, 80, 1),\n        KPDSupply(\"sunglasses\", 7, 20, 1),\n        KPDSupply(\"towel\", 18, 12, 2),\n        KPDSupply(\"socks\", 4, 50, 1),\n        KPDSupply(\"book\", 30, 10, 2)]\n\npack = solve(gear, 400)\nprintln(\"The hiker should pack: \\n - \", join(pack, \"\\n - \"))\nprintln(\"\\nPacked weight: \", sum(getfield.(pack, :weight)), \" kg\")\nprintln(\"Packed value: \", sum(getfield.(pack, :value)), \" \u20ac\")\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. It uses Julia's MathProgBase package and the mixintprog function to solve the bounded Knapsack problem. The aim is to maximize the total value of items without exceeding the weight limit. The items cannot be divided, only whole units can be taken.","id":1991}
    {"lang_cluster":"Julia","source_code":"\nccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)\n\nfunction timeit()\n    ticks = 0\n    try\n        while true\n            sleep(0.5)\n            ticks += 1\n            println(ticks)\n        end\n    catch\n    end\nend\n\n@time timeit()\nprintln(\"Done.\")\n\n\n\n","human_summarization":"The code outputs an integer every half second. It handles the SIGINT or SIGQUIT signal, typically generated by user's ctrl-C or ctrl-\\ input respectively, to stop the output, display the program's runtime in seconds, and then terminate the program. The code uses 'ccall' to pass the SIGINT signal to Julia as an error when running in the main() function, which is not required in Julia's REPL.","id":1992}
    {"lang_cluster":"Julia","source_code":"\nimport Base.+\nBase.:+(s::AbstractString, n::Real) = string((x = tryparse(Int, s)) isa Int ? x + 1 : parse(Float64, s) + 1)\n@show \"125\" + 1\n@show \"125.15\" + 1\n@show \"1234567890987654321\" + 1\n\n","human_summarization":"\"Increments a given numerical string.\"","id":1993}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nfunction commonpath(ds::Vector{<:AbstractString}, dlm::Char='\/')\n    0 < length(ds) || return \"\"\n    1 < length(ds) || return String(ds[1])\n    p = split(ds[1], dlm)\n    mincnt = length(p)\n    for d in ds[2:end]\n        q = split(d, dlm)\n        mincnt = min(mincnt, length(q))\n        hits = findfirst(p[1:mincnt] .!= q[1:mincnt])\n        if hits != 0 mincnt = hits - 1 end\n        if mincnt == 0 return \"\" end\n    end\n    1 < mincnt || p[1] != \"\" || return convert(T, string(dlm))\n    return join(p[1:mincnt], dlm)\nend\n\ntest = [\"\/home\/user1\/tmp\/coverage\/test\", \"\/home\/user1\/tmp\/covert\/operator\", \"\/home\/user1\/tmp\/coven\/members\"]\n\nprintln(\"Comparing:\\n - \", join(test, \"\\n - \"))\nprintln(\"for their common directory path yields:\\n\", commonpath(test))\n\n\n","human_summarization":"The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '\/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.","id":1994}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nfunction sattolocycle!(arr::Array, last::Int=length(arr))\n    for i in last:-1:2\n        j = rand(1:i-1)\n        arr[i], arr[j] = arr[j], arr[i]\n    end\n    return arr\nend\n\n@show sattolocycle!([])\n@show sattolocycle!([10])\n@show sattolocycle!([10, 20, 30])\n@show sattolocycle!([11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22])\n\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":1995}
    {"lang_cluster":"Julia","source_code":"using LibCURL\n\nfunction callSOAP(url, infilename, outfilename)\n    rfp = open(infilename, \"r\")\n    wfp = open(outfilename, \"w+\")\n\n    header = curl_slist_append(header, \"Content-Type:text\/xml\")\n    header = curl_slist_append(header, \"SOAPAction: rsc\");\n    header = curl_slist_append(header, \"Transfer-Encoding: chunked\")\n    header = curl_slist_append(header, \"Expect:\")\n\n    curl = curl_easy_init();\n    curl_easy_setopt(curl, CURLOPT_URL, URL)\n    curl_easy_setopt(curl, CURLOPT_POST, 1L)\n    curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data)\n    curl_easy_setopt(curl, CURLOPT_READDATA, rfp)\n    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data)\n    curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp)\n    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header)\n    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1)\n    curl_easy_setopt(curl, CURLOPT_VERBOSE,1L)\n    curl_easy_perform(curl)\n\n    curl_easy_cleanup(curl)\nend\n\ntry\n    callSOAP(ARGS[1], ARGS[2], ARGS[3])\ncatch y\n    println(\"Usage\u00a0: $(@__FILE__) <URL of WSDL> <Input file path> <Output File Path>\")\nend\n\n","human_summarization":"The code establishes a SOAP client to access and call the functions soapFunc() and anotherSoapFunc() from the WSDL located at http:\/\/example.com\/soap\/wsdl. Note, the task and corresponding code may require further clarification.","id":1996}
    {"lang_cluster":"Julia","source_code":"\n\nusing Statistics\nfunction median2(n)\n\ts = sort(n)\n\tlen = length(n)\n\tif len % 2 == 0\n\t\treturn (s[floor(Int, len \/ 2) + 1] + s[floor(Int, len \/ 2)]) \/ 2\n\telse\n\t\treturn  s[floor(Int, len \/ 2) + 1]\n\tend\nend\n\na = [4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]\nb = [4.1, 7.2, 1.7, 9.3, 4.4, 3.2]\n\n@show a b median2(a) median(a) median2(b) median(b)\n\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It can handle vectors with an even number of elements, returning the average of the two middle values. The code uses the selection algorithm for efficiency. It also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation. The code uses Julia's built-in median() function.","id":1997}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 1.8.5\n\nfor i in 1:100\n    if i\u00a0% 15 == 0\n        println(\"FizzBuzz\")\n    elseif i\u00a0% 3 == 0\n        println(\"Fizz\")\n    elseif i\u00a0% 5 == 0\n        println(\"Buzz\")\n    else\n        println(i)\n    end\nend\n\ncollect(i\u00a0% 15 == 0\u00a0? \"FizzBuzz\"\u00a0: i\u00a0% 5 == 0\u00a0? \"Buzz\"\u00a0: i\u00a0% 3 == 0\u00a0? \"Fizz\"\u00a0: i for i in 1:100) |> println\n\nfb(i::Integer) = \"Fizz\" ^ (i\u00a0% 3 == 0) * \"Buzz\" ^ (i\u00a0% 5 == 0) * string(i) ^ (i\u00a0% 3\u00a0!= 0 && i\u00a0% 5\u00a0!= 0)\nfor i in 1:100 println(fb(i)) end\n\nprintln.(map(fb, 1:100))\n\nfor i in 1:100\n    msg = \"Fizz\" ^ (i\u00a0% 3 == 0) * \"Buzz\" ^ (i\u00a0% 5 == 0)\n    println(isempty(msg)\u00a0? i\u00a0: msg)\nend\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both with 'FizzBuzz'.","id":1998}
    {"lang_cluster":"Julia","source_code":"\n\nfunction mandelbrot(a)\n    z = 0\n    for i=1:50\n        z = z^2 + a\n    end\n    return z\nend\n\nfor y=1.0:-0.05:-1.0\n    for x=-2.0:0.0315:0.5\n        abs(mandelbrot(complex(x, y))) < 2 ? print(\"*\") : print(\" \")\n    end\n    println()\nend\n\n\nusing Images\n\n@inline function hsv2rgb(h, s, v)\n    c = v * s\n    x = c * (1 - abs(((h\/60) % 2) - 1))\n    m = v - c\n    r,g,b = if     h < 60   (c, x, 0)\n            elseif h < 120  (x, c, 0)\n            elseif h < 180  (0, c, x)\n            elseif h < 240  (0, x, c)\n            elseif h < 300  (x, 0, c)\n            else            (c, 0, x) end\n    (r + m), (b + m), (g + m)\nend\n\nfunction mandelbrot()\n    w       = 1600\n    h       = 1200\n    zoom    = 0.5\n    moveX   = -0.5\n    moveY   = 0\n    maxIter = 30\n    img = Array{RGB{Float64},2}(undef,h,w)\n    for x in 1:w\n      for y in 1:h\n        i = maxIter\n        z = c = Complex( (2*x - w) \/ (w * zoom) + moveX,\n                         (2*y - h) \/ (h * zoom) + moveY )\n        while abs(z) < 2 && (i -= 1) > 0\n            z = z^2 + c\n        end\n        r,g,b = hsv2rgb(i \/ maxIter * 360, 1, i \/ maxIter)\n        img[y,x] = RGB{Float64}(r, g, b)\n      end\n    end\n    return img\nend\n\nimg = mandelbrot()\nsave(\"mandelbrot.png\", img)\n\n\nusing Plots\ngr(aspect_ratio=:equal, legend=false, axis=false, ticks=false, dpi=100)\n\nd, h = 400, 300  # pixel density (= image width) and image height\nn, r = 40, 1000  # number of iterations and escape radius (r > 2)\n\nx = range(-1.0, 1.0, length=d+1)\ny = range(-h\/d, h\/d, length=h+1)\n\nC = 2.0 .* (x' .+ y .* im) .- 0.5\nZ, S = zero(C), zeros(size(C))\n\nanimation = Animation()\nsmoothing = Animation()\n\nfor k in 1:n\n    M = abs.(Z) .< r\n    S[M] = S[M] .+ exp.(.-abs.(Z[M]))\n    Z[M] = Z[M] .^ 2 .+ C[M]\n    heatmap(exp.(.-abs.(Z)), c=:jet)\n    frame(animation)\n    heatmap(S .+ exp.(.-abs.(Z)), c=:jet)\n    frame(smoothing)\nend\n\ngif(animation, \"Mandelbrot_animation.gif\", fps=2)\ngif(smoothing, \"Mandelbrot_smoothing.gif\", fps=2)\n\n\nusing Plots\ngr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)\n\nd, h = 800, 500  # pixel density (= image width) and image height\nn, r = 200, 500  # number of iterations and escape radius (r > 2)\n\nx = range(0, 2, length=d+1)\ny = range(0, 2 * h \/ d, length=h+1)\n\nA, B = collect(x) .- 1, collect(y) .- h \/ d\nC = 2.0 .* (A' .+ B .* im) .- 0.5\n\nZ, dZ = zero(C), zero(C)\nD, S, T = zeros(size(C)), zeros(size(C)), zeros(size(C))\n\nfor k in 1:n\n    M = abs.(Z) .< r\n    S[M], T[M] = S[M] .+ exp.(.- abs.(Z[M])), T[M] .+ 1\n    Z[M], dZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1\nend\n\nheatmap(S .^ 0.1, c=:balance)\nsavefig(\"Mandelbrot_set_1.png\")\n\nN = abs.(Z) .>= r  # normalized iteration count\nT[N] = T[N] .- log2.(log.(abs.(Z[N])) .\/ log(r))\n\nheatmap(T .^ 0.1, c=:balance)\nsavefig(\"Mandelbrot_set_2.png\")\n\nN = abs.(Z) .> 2  # exterior distance estimation\nD[N] = log.(abs.(Z[N])) .* abs.(Z[N]) .\/ abs.(dZ[N])\n\nheatmap(D .^ 0.1, c=:balance)\nsavefig(\"Mandelbrot_set_3.png\")\n\nN, thickness = D .> 0, 0.01  # boundary detection\nD[N] = max.(1 .- D[N] .\/ thickness, 0)\n\nheatmap(D .^ 2.0, c=:binary)\nsavefig(\"Mandelbrot_set_4.png\")\n\n\nusing Plots\ngr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)\n\nd, h = 800, 500  # pixel density (= image width) and image height\nn, r = 200, 500  # number of iterations and escape radius (r > 2)\n\ndirection, height = 45, 1.5  # direction and height of the incoming light\nstripes, damping = 4.0, 2.0  # stripe density and damping parameter\n\nx = range(0, 2, length=d+1)\ny = range(0, 2 * h \/ d, length=h+1)\n\nA, B = collect(x) .- 1, collect(y) .- h \/ d\nC = (2.0 + 1.0im) .* (A' .+ B .* im) .- 0.5\n\nZ, dZ, ddZ = zero(C), zero(C), zero(C)\nD, S, T = zeros(size(C)), zeros(size(C)), zeros(size(C))\n\nfor k in 1:n\n    M = abs.(Z) .< r\n    S[M], T[M] = S[M] .+ sin.(stripes .* angle.(Z[M])), T[M] .+ 1\n    Z[M], dZ[M], ddZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1, 2 .* (dZ[M] .^ 2 .+ Z[M] .* ddZ[M])\nend\n\nN = abs.(Z) .>= r  # basic normal map effect and stripe average coloring (potential function)\nP, Q = S[N] .\/ T[N], (S[N] .+ sin.(stripes .* angle.(Z[N]))) .\/ (T[N] .+ 1)\nU, V = Z[N] .\/ dZ[N], 1 .+ (log2.(log.(abs.(Z[N])) .\/ log(r)) .* (P .- Q) .+ Q) .\/ damping\nU, v = U .\/ abs.(U), exp(direction \/ 180 * pi * im)  # unit normal vectors and light\nD[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ V .* height) .\/ (1 + height), 0)\n\nheatmap(D .^ 1.0, c=:bone_1)\nsavefig(\"Mandelbrot_normal_map_1.png\")\n\nN = abs.(Z) .> 2  # advanced normal map effect using higher derivatives (distance estimation)\nU = Z[N] .* dZ[N] .* ((1 .+ log.(abs.(Z[N]))) .* conj.(dZ[N] .^ 2) .- log.(abs.(Z[N])) .* conj.(Z[N] .* ddZ[N]))\nU, v = U .\/ abs.(U), exp(direction \/ 180 * pi * im)  # unit normal vectors and light\nD[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) .\/ (1 + height), 0)\n\nheatmap(D .^ 1.0, c=:afmhot)\nsavefig(\"Mandelbrot_normal_map_2.png\")\n\n\nusing Plots\ngr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)\n\nd, h = 200, 1200  # pixel density (= image width) and image height\nn, r = 8000, 10000  # number of iterations and escape radius (r > 2)\n\na = -.743643887037158704752191506114774  # https:\/\/mathr.co.uk\/web\/m-location-analysis.html\nb = 0.131825904205311970493132056385139  # try: a, b, n = -1.748764520194788535, 3e-13, 800\n\nx = range(0, 2, length=d+1)\ny = range(0, 2 * h \/ d, length=h+1)\n\nA, B = collect(x) .* pi, collect(y) .* pi\nC = 8.0 .* exp.((A' .+ B .* im) .* im) .+ (a + b * im)\n\nZ, dZ = zero(C), zero(C)\nD = zeros(size(C))\n\nfor k in 1:n\n    M = abs2.(Z) .< abs2(r)\n    Z[M], dZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1\nend\n\nN = abs.(Z) .> 2  # exterior distance estimation\nD[N] = log.(abs.(Z[N])) .* abs.(Z[N]) .\/ abs.(dZ[N])\n\nheatmap(D' .^ 0.05, c=:nipy_spectral)\nsavefig(\"Mercator_Mandelbrot_map.png\")\n\nX, Y = real(C), imag(C)  # zoom images (adjust circle size 50 and zoom level 20 as needed)\nR, c, z = 50 * (2 \/ d) * pi .* exp.(.- B), min(d, h) + 1, max(0, h - d) \u00f7 20\n\ngr(c=:nipy_spectral, axis=true, ticks=true, legend=false, markerstrokewidth=0)\np1 = scatter(X[1z+1:1z+c,1:d], Y[1z+1:1z+c,1:d], markersize=R[1:c].^.5, marker_z=D[1z+1:1z+c,1:d].^.5)\np2 = scatter(X[2z+1:2z+c,1:d], Y[2z+1:2z+c,1:d], markersize=R[1:c].^.5, marker_z=D[2z+1:2z+c,1:d].^.4)\np3 = scatter(X[3z+1:3z+c,1:d], Y[3z+1:3z+c,1:d], markersize=R[1:c].^.5, marker_z=D[3z+1:3z+c,1:d].^.3)\np4 = scatter(X[4z+1:4z+c,1:d], Y[4z+1:4z+c,1:d], markersize=R[1:c].^.5, marker_z=D[4z+1:4z+c,1:d].^.2)\nplot(p1, p2, p3, p4, layout=(2, 2))\nsavefig(\"Mercator_Mandelbrot_zoom.png\")\n\n\nusing Plots\ngr(aspect_ratio=:equal, axis=true, ticks=true, legend=false, dpi=200)\n\nsetprecision(BigFloat, 256)  # set precision to 256 bits (default)\nsetrounding(BigFloat, RoundNearest)  # set rounding mode (default)\n\nd, h = 50, 1000  # pixel density (= image width) and image height\nn, r = 80000, 100000  # number of iterations and escape radius (r > 2)\n\na = BigFloat(\"-1.256827152259138864846434197797294538253477389787308085590211144291\")\nb = BigFloat(\".37933802890364143684096784819544060002129071484943239316486643285025\")\n\nS = zeros(Complex{Float64}, n+1)\nlet c = a + b * im, z = zero(c)\n    for k in 1:n+1\n        S[k] = z\n        if abs2(z) < abs2(r)\n            z = z ^ 2 + c\n        else\n            println(\"The reference sequence diverges within $(k-1) iterations.\")\n            break\n        end\n    end\nend\n\nx = range(0, 2, length=d+1)\ny = range(0, 2 * h \/ d, length=h+1)\n\nA, B = collect(x) .* pi, collect(y) .* pi\nC = 8.0 .* exp.((A' .+ B .* im) .* im)\n\nE, Z, dZ = zero(C), zero(C), zero(C)\nD, I, J = zeros(size(C)), ones(Int64, size(C)), ones(Int64, size(C))\n\nfor k in 1:n\n    M, R = abs2.(Z) .< abs2(r), abs2.(Z) .< abs2.(E)\n    E[R], I[R] = Z[R], J[R]  # rebase when z is closer to zero\n    E[M], I[M] = (2 .* S[I[M]] .+ E[M]) .* E[M] .+ C[M], I[M] .+ 1\n    Z[M], dZ[M] = S[I[M]] .+ E[M], 2 .* Z[M] .* dZ[M] .+ 1\nend\n\nN = abs.(Z) .> 2  # exterior distance estimation\nD[N] = log.(abs.(Z[N])) .* abs.(Z[N]) .\/ abs.(dZ[N])\n\nheatmap(D' .^ 0.015, c=:nipy_spectral)\nsavefig(\"Mercator_Mandelbrot_deep_map.png\")\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. The codes include features for generating an ASCII representation and a PNG image file. They also apply e^(-|z|)-smoothing, normalization, distance estimation, and boundary detection. The codes use normal map effect and stripe average coloring for representation. They also allow for the creation of Mercator maps and zoom images of the Mandelbrot set. For deep zoom images, the codes utilize perturbation theory and deep Mercator maps.","id":1999}
    {"lang_cluster":"Julia","source_code":"\njulia> sum([4,6,8])\n18\n\njulia> +((1:10)...)\n55\n\njulia +([1,2,3]...)\n6\n\njulia> prod([4,6,8])\n192\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":2000}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nisleap(yr::Integer) = yr % 4 == 0 && (yr < 1582 || yr % 400 == 0 || yr % 100 != 0)\n\n@assert all(isleap, [2400, 2012, 2000, 1600, 1500, 1400])\n@assert !any(isleap, [2100, 2014, 1900, 1800, 1700, 1499])\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":2001}
    {"lang_cluster":"Julia","source_code":"\nusing Dates, HTTP\n\nconst configs = Dict(\"OTPdir\" => \".\")\n\nstringtohash(s) = string(hash(s), base=16)\n\nvencode(a::Char, b) = Char((Int(a) + Int(b) - 130) % 26 + 65)\nvencode(atxt::String, btxt) = String(map((a, b) -> vencode(a, b), atxt, btxt))\nvdecode(a::Char, b) = Char((Int(a) + 26 - Int(b)) % 26 + 65)\nvdecode(atxt::String, btxt) = String(map((a, b) -> vdecode(a, b), atxt, btxt))\n\nfunction getrandom()\n    bytes, ret, source = UInt8[], Char[], \"local\"\n    try\n        hx = HTTP.get(\"https:\/\/www.random.org\/cgi-bin\/randbyte?nbytes=1024&format=hex\").body\n        if length(hx) < 100\n            throw(\"not enough bytes gotten from internet\")\n        end\n        bytes = map(s -> parse(UInt8, s, base=16), split(strip(String(hx)), r\"\\s+\"))\n        source = \"random.org\"\n        bytes = map((a, b) -> xor(a, b), bytes, rand(UInt8, length(bytes)))\n    catch y\n        @warn(\"internet source failure: $y\")\n        bytes = rand(UInt8, 1568)\n    end\n    for b in bytes\n        ch = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ***\"[div(b, 9) + 1]\n        if ch != '*'\n            push!(ret, ch)\n        end\n    end\n    source, ret\nend\n\nfunction newOTPfilename()\n    dircontents = readdir(configs[\"OTPdir\"])\n    while true\n        nam = \"OTP\" * replace(string(now()), \":\" => \"_\") * \".1tp\"\n        if (i = findfirst(x -> x == nam, dircontents)) != nothing\n            sleep(0.5)\n        else\n            return nam\n        end\n    end\nend\n\nfunction lines40by5(s)\n    ret = \"\"\n    for (i, ch) in enumerate(s)\n        ret *= (i % 40 == 0) ? ch * \"\n\" :\n            (i % 5 == 1) ? \" \" * ch : ch\n    end\n    ret\nend\n\nfunction createOTPfile(nletters, partnername=\"\")\n    newname, source = newOTPfilename(), \"unknown\"\n    fp = open(newname, \"w\")\n    needed = nletters + (nletters % 40 == 0 ? 0 : 40 - n % 40)\n    data = Char[]\n    while true\n        source, randomdata = getrandom()\n        println(\"Got \", length(randomdata), \" letters from \", source)\n        data = append!(data, randomdata)\n        if length(data) >= needed\n            data = data[1:needed]\n            break\n        end\n    end\n    s = lines40by5(data)\n    write(fp, \"# $source OTP \", stringtohash(partnername), \"\n\", s)\n    close(fp)\n    newname, needed, source\nend\n\nfunction readOTPfile(filename, n, skiplines=0, useused=false)\n    fp = open(filename, \"r+\")\n    seekpositions, ret = Vector{Int}(), \"\"\n    while length(ret) < n\n        if eof(fp)\n            throw(\"Not enough letters in file\")\n        end\n        if skiplines < 1\n            push!(seekpositions, position(fp))\n        end\n        line = readline(fp)\n        if skiplines > 0\n            skiplines -= 1\n            continue\n        end\n        if (useused || line[1] != '-') && line[1] != '#'\n            ret *= replace(line, r\"[^A-Z]\" => \"\")\n        else\n            pop!(seekpositions)\n        end\n    end\n    seekstart(fp)\n    for pos in seekpositions\n        seek(fp, pos)\n        write(fp, '-')\n    end\n    close(fp)\n    ret[1:n]\nend\n\nfunction getOTPfiles(dir=configs[\"OTPdir\"])\n    namedict = Dict{String, Pair{String,String}}()\n    filenames = filter(nam -> occursin(r\"\\.1tp$\", nam), readdir(dir))\n    for (i, nam) in enumerate(filenames)\n        fp = open(dir * \"\/\" * nam, \"r\")\n        lin = readline(fp)\n        m = match(r\"#\\s+([\\w\\.]+)\\s+OTP\\s+([01-9a-fA-F]+)\", lin)\n        if m != nothing\n            namedict[nam] = Pair(m.captures[1], m.captures[2])\n        end\n    end\n    namedict\nend\n\nfunction listOTPfiles(partnername=\"\")\n    phash = stringtohash(partnername)\n    files = Dict{Int, String}()\n    println(\"Number            File name               partner code       source     count\")\n    for (i, p) in enumerate(getOTPfiles())\n        if partnername == \"\" || phash == p[2][2]\n            pathname = configs[\"OTPdir\"] * \"\/\" * p[1]\n            files[i] = p[1]\n            println(rpad(i, 8), rpad(p[1], 32), rpad(p[2][2], 20),\n                rpad(p[2][1], 12), stat(pathname).size)\n        end\n    end\n    files\nend\n\nfunction getconsoleinput(asInt=false, yn=false, default=\"\")\n    while true\n        println(\"Enter choice \", asInt ? \"number \" : \"\", \"or <enter> \", asInt ? \"for 0:\" : \"to exit:\")\n        s = readline()\n        if s == \"\"\n            return asInt ? 0 : \"\"\n        elseif !asInt\n            if !yn || (s = string(uppercase(s)[1])) in [\"Y\", \"N\"]\n                return s\n            end\n        else\n            choice = tryparse(Int, s)\n            if choice != nothing\n                return choice\n            end\n        end\n    end\nend\n\nfunction chooseOTPfiledialog()\n    println(\"Enter partner name or <enter> for all.\")\n    pname = getconsoleinput()\n    files = listOTPfiles(pname)\n    println(\"Choose file number (0 to quit routine).\")\n    while true\n        fnum = getconsoleinput(true)\n        if fnum == 0\n            return \"\"\n        elseif haskey(files, fnum)\n            return files[fnum]\n        end\n    end\nend\n\nfunction encryptdialog()\n    if(fname = chooseOTPfiledialog()) == \"\"\n        return\n    end\n    println(\"Skip lines marked as used?\")\n    useused = getconsoleinput(false, true) == \"N\"\n    skiplines = 0\n    println(\"Start file read at beginning?\")\n    if getconsoleinput(false, true) == \"N\"\n        println(\"Enter number of lines to skip:\")\n        skiplines = getconsoleinput(true)\n    end\n    println(\"Enter lines of text to encrypt. Non-alphabet will be ignored. A blank line ends entry.\")\n    txt = \"\"\n    while (lin = readline()) != \"\"\n        txt *= lin\n    end\n    txt = replace(uppercase(txt), r\"[^A-Z]\" => \"\")\n    otp = readOTPfile(fname, length(txt), skiplines, useused)\n    println(lines40by5(vencode(txt, otp)))\nend\n\nfunction decryptdialog()\n    if(fname = chooseOTPfiledialog()) == \"\"\n        return\n    end\n    println(\"Skip lines marked as used?\")\n    useused = getconsoleinput(false, true) == \"N\"\n    skiplines = 0\n    println(\"Start file read at beginning?\")\n    if getconsoleinput(false, true) == \"N\"\n        println(\"Enter number of lines to skip:\")\n        skiplines = getconsoleinput(true)\n    end\n    println(\"Enter lines of text to decrypt. A blank line ends entry.\")\n    txt = \"\"\n    while (lin = readline()) != \"\"\n        txt *= lin\n    end\n    txt = replace(txt, r\"[^A-Z]\" => \"\")\n    otp = readOTPfile(fname, length(txt), skiplines, useused)\n    println(vdecode(txt, otp))\nend\n\nfunction securedeletefile(filename, writes=100)\n    ltrs = [\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"[i] for i in 1:26]\n    pathname, len = configs[\"OTPdir\"] * \"\/\" * filename, stat(filename).size\n    fp = open(pathname, \"w\")\n    for _ in 1:writes\n        write(fp, rand(ltrs, len))\n        seekstart(fp)\n    end\n    close(fp)\n    try rm(pathname); catch y; @warn(y) end\nend\n\nfunction createfiledialog()\n    println(\"Enter partner name or press <enter> for none:\")\n    nam = getconsoleinput()\n    println(\"Enter number of letters or <enter> for 2000:\")\n    n = getconsoleinput(true)\n    newname, nletters, source = createOTPfile(n, nam)\n    println(\"Created file $newname in directory $(configs[\"OTPdir\"])\",\n        \"\nwith $nletters letters. The source was $source.\n\")\nend\n\nfunction deletefiledialog()\n    fnam = chooseOTPfiledialog()\n    if fnam != \"\"\n        println(\"Confim by entering file name time string as (hh_mm_ss):\")\n        if occursin(getconsoleinput(), fnam)\n            securedeletefile(fnam)\n            println(\"File $fnam has been overwritten and deleted.\")\n        else\n            println(\"No files deleted.\")\n        end\n    end\nend\n\nfunction configure()\n    println(\"The current subdirectory is: \", configs[\"OTPdir\"])\n    println(\"Enter new dirpath or <enter> to leave unchanged:\")\n    dirname = getconsoleinput()\n    if dirname != \"\"\n        try\n            readdir(dirname)\n            configs[\"OTPdir\"] = dirname\n        catch\n            @warn(\"Invalid directory pathname: $dirname\")\n        end\n    end\nend\n\nconst mainmenu = \"\"\"\nWelcome to One Time Pad manager.\n\nSelect menu item:\n\nA - Add new OTP file\nD - Decrypt text\nE - Encrypt text\nR - Remove file (secure deletion)\nC - Configure subdirectory\nX - eXit\n\"\"\"\n\nfunction onetimepadapp()\n    while true\n        println(mainmenu)\n        inchar = getconsoleinput()\n        ltr = (inchar == \"\") ? \"X\" : string(uppercase(inchar)[1])\n        if ltr == \"A\"\n            createfiledialog()\n        elseif ltr == \"D\"\n            decryptdialog()\n        elseif ltr == \"E\"\n            encryptdialog()\n        elseif ltr == \"R\"\n            deletefiledialog()\n        elseif ltr == \"C\"\n            configure()\n        elseif ltr == \"X\"\n            break\n        else\n            println(\"Unknown choice $ltr, type $(typeof(ltr))\")\n        end\n    end\n    println(\"Close the console to keep past session text from being seen.\")\nend\n\nonetimepadapp()\n","human_summarization":"The code implements a One-time pad for encrypting and decrypting messages using only letters. It generates data for a One-time pad where the user specifies a filename and length, and uses \"true random\" numbers from \/dev\/random. The encryption and decryption process is similar to Rot-13 and reuses much of the Vigen\u00e8re cipher with the key read from the One-time pad file. The code also optionally manages One-time pads, allowing users to list, mark as used, delete, and track which pad to use for which partner. The pad-files have a \".1tp\" extension, and lines starting with \"#\" or \"-\" are used for comments and marking as \"used\" respectively. Whitespace within the otp-data is ignored.","id":2002}
    {"lang_cluster":"Julia","source_code":"\n# a rather literal translation of the pseudocode at https:\/\/en.wikipedia.org\/wiki\/MD5\n\nconst s = UInt32[7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n                 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, \n                 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,  4, 11, 16, 23, \n                 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]\n\nconst K = UInt32[0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf,\n    0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1,\n    0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562,\n    0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681,\n    0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905,\n    0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,\n    0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6,\n    0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8,\n    0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3,\n    0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314,\n    0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]\n\nfunction md5(msgbytes)\n    a0::UInt32 = 0x67452301  # A\n    b0::UInt32 = 0xefcdab89  # B\n    c0::UInt32 = 0x98badcfe  # C\n    d0::UInt32 = 0x10325476  # D\n\n    oldlen = length(msgbytes)\n    umsg = push!([UInt8(b) for b in msgbytes], UInt8(0x80))\n    while length(umsg) % 64 != 56\n        push!(umsg, UInt8(0))\n    end\n    append!(umsg, reinterpret(UInt8, [htol(UInt64(oldlen) * 8)]))\n\n    for j in 1:64:length(umsg)-1\n        arr = view(umsg, j:j+63)\n        M = [reinterpret(UInt32, arr[k:k+3])[1] for k in 1:4:62]\n        A = a0\n        B = b0\n        C = c0\n        D = d0\n\n        for i in 0:63\n            if 0 \u2264 i \u2264 15\n                F = D \u22bb (B & (C \u22bb D))\n                g = i\n            elseif 16 \u2264 i \u2264 31\n                F = C \u22bb (D & (B \u22bb C))\n                g = (5 * i + 1) % 16\n            elseif 32 \u2264 i \u2264 47\n                F = B \u22bb C \u22bb D\n                g = (3 * i + 5) % 16\n            elseif 48 \u2264 i \u2264 63\n                F = C \u22bb (B | (~D))\n                g = (7 * i) % 16\n            end\n            F += A + K[i+1] + M[g+1]\n            A = D\n            D = C\n            C = B\n            B += ((F) << s[i+1]) | (F >> (32 - s[i+1]))\n        end\n\n        a0 += A\n        b0 += B\n        c0 += C\n        d0 += D\n    end\n    digest = join(map(x -> lpad(string(x, base=16), 2, '0'), reinterpret(UInt8, [a0, b0, c0, d0])), \"\") # Output is in little-endian\nend\n\nfor pair in [0xd41d8cd98f00b204e9800998ecf8427e => \"\", 0x0cc175b9c0f1b6a831c399e269772661 => \"a\",\n   0x900150983cd24fb0d6963f7d28e17f72 => \"abc\", 0xf96b697d7cb7938d525a2f31aaf161d0 => \"message digest\",\n   0xc3fcd3d76192e4007dfb496cca67e13b => \"abcdefghijklmnopqrstuvwxyz\",\n   0xd174ab98d277d9f5a5611c2c9f419d9f => \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",\n   0x57edf4a22be3c955ac49da2e2107b67a => \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"]\n   println(\"MD5 of $(pair[2]) is $(md5(pair[2])), which checks with $(string(pair[1], base=16)).\")\nend\n\n","human_summarization":"The code is an implementation of the MD5 Message Digest Algorithm, developed directly from the algorithm specification without using built-in or external hashing libraries. It produces a correct message digest for an input string but does not mimic all calling modes. The code also includes handling of bit manipulation, unsigned integers, and little-endian data, with attention to details like boundary conditions and padding. The implementation is validated against the verification strings and hashes from RFC 1321.","id":2003}
    {"lang_cluster":"Julia","source_code":"\nusing Printf\n\nfunction findsolution(rng=1:7)\n    rst = Matrix{Int}(0, 3)\n    for p in rng, f in rng, s in rng\n        if p != s != f != p && p + s + f == 12 && iseven(p)\n            rst = [rst; p s f]\n        end\n    end\n    return rst\nend\n\nfunction printsolutions(sol::Matrix{Int})\n    println(\"      Pol.   Fire   San.\")\n    println(\"      ----   ----   ----\")\n    for row in 1:size(sol, 1)\n        @printf(\"%2i | %4i%7i%7i\\n\", row, sol[row, :]...)\n    end\nend\n\nprintsolutions(findsolution())\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":2004}
    {"lang_cluster":"Julia","source_code":"\n\ns = \"Rosetta Code\"\nt = s\n\nprintln(\"s = \\\"\", s, \"\\\" and, after \\\"t = s\\\", t = \\\"\", t, \"\\\"\")\n\ns = \"Julia at \"*s\n\nprintln(\"s = \\\"\", s, \"\\\" and, after this change, t = \\\"\", t, \"\\\"\")\n\n\n","human_summarization":"The code copies a string in Julia, differentiating between duplicating the string's content and creating an additional reference to the existing string. Due to Julia's string immutability, assigning one string variable to another effectively makes a copy, as changes to one variable don't affect the other.","id":2005}
    {"lang_cluster":"Julia","source_code":"\nF(n) = n < 1 ? one(n) : n - M(F(n - 1))\nM(n) = n < 1 ? zero(n) : n - F(M(n - 1))\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":2006}
    {"lang_cluster":"Julia","source_code":"\narray = [1,2,3]\nrand(array)\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":2007}
    {"lang_cluster":"Julia","source_code":"\nusing URIParser\n\nenc = \"http%3A%2F%2Ffoo%20bar%2F\"\n\ndcd = unescape(enc)\n\nprintln(enc, \" => \", dcd)\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":2008}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\nfunction binarysearch(lst::Vector{T}, val::T) where T\n    low = 1\n    high = length(lst)\n    while low \u2264 high\n        mid = (low + high) \u00f7 2\n        if lst[mid] > val\n            high = mid - 1\n        elseif lst[mid] < val\n            low = mid + 1\n        else\n            return mid\n        end\n    end\n    return 0\nend\n\n\nfunction binarysearch(lst::Vector{T}, value::T, low=1, high=length(lst)) where T\n    if isempty(lst) return 0 end\n    if low \u2265 high\n        if low > high || lst[low] != value\n            return 0\n        else\n            return low\n        end\n    end\n    mid = (low + high) \u00f7 2\n    if lst[mid] > value\n        return binarysearch(lst, value, low, mid-1)\n    elseif lst[mid] < value\n        return binarysearch(lst, value, mid+1, high)\n    else\n        return mid\n    end\nend\n\n","human_summarization":"Implement a binary search algorithm that takes a sorted integer array, a starting point, an ending point, and a \"secret value\" as inputs. The algorithm divides the range of values into halves and continues to narrow down the search field until the secret value is found. It can be implemented in both recursive and iterative methods. The algorithm also handles multiple values equal to the given value and indicates whether the element was found or not. It also calculates the insertion point for the secret value if it's not found in the array. The code also includes a fix for potential overflow bugs.","id":2009}
    {"lang_cluster":"Julia","source_code":"\n\nusing Printf\n\nprog = Base.basename(Base.source_path())\n\nprintln(prog, \"'s command-line arguments are:\")\nfor s in ARGS\n    println(\"    \", s)\nend\n\n\n","human_summarization":"\"Retrieves and prints the list of command-line arguments given to the program when run directly. It also works when the Julia program is run as a file argument to julia.exe. The program can parse arguments intelligently. For example, it can handle command lines like 'myprogram -c \"alpha beta\" -h \"gamma\"'. The program name can also be retrieved.\"","id":2010}
    {"lang_cluster":"Julia","source_code":"\nDifferential equation based solution using the Luxor graphics library.using Luxor\nusing Colors\nusing BoundaryValueDiffEq\n \n# constants for differential equations and movie\nconst g = 9.81\nconst L = 1.0                         # pendulum length in meters\nconst bobd = 0.10                     # pendulum bob diameter in meters\nconst framerate = 50.0                # intended frame rate\/sec\nconst t0 = 0.0                        # start time (s)\nconst tf = 2.3                        # end simulation time (s)\nconst dtframe = 1.0\/framerate         # time increment per frame\nconst tspan = LinRange(t0, tf, Int(floor(tf*framerate)))  # array of time points in animation\n \nconst bgcolor = \"black\"               # gif background\nconst leaderhue = (0.80, 0.70, 0.20)  # gif swing arm hue light gold\nconst hslcolors = [HSL(col) for col in (distinguishable_colors(\n                   Int(floor(tf*framerate)+3),[RGB(1,1,1)])[2:end])]\nconst giffilename = \"pendulum.gif\"    # output file\n \n# differential equations\nsimplependulum(du, u, p, t) = (\u03b8=u[1]; d\u03b8=u[2]; du[1]=d\u03b8; du[2]=-(g\/L)*sin(\u03b8))\nbc2(residual, u, p, t) = (residual[1] = u[end\u00f72][1] + pi\/2; residual[2] = u[end][1] - pi\/2)\nbvp2 = BVProblem(simplependulum, bc2, [pi\/2,pi\/2], (tspan[1],tspan[end]))\nsol2 = solve(bvp2, MIRK4(), dt=dtframe) # use the MIRK4 solver for TwoPointBVProblem\n \n# movie making background\nbackdrop(scene, framenumber) = background(bgcolor)\n \nfunction frame(scene, framenumber)\n    u1, u2 = sol2.u[framenumber]\n    y, x = L*cos(u1), L*sin(u1)\n    sethue(leaderhue)\n    poly([Point(-4.0, 0.0), Point(4.0, 0.0),\n          Point(160.0x,160.0y)], :fill)\n    sethue(Colors.HSV(framenumber*4.0, 1, 1))\n    circle(Point(160.0x,160.0y), 160bobd, :fill)\n    text(string(\"frame $framenumber of $(scene.framerange.stop)\"),\n        Point(0.0, -190.0),\n        halign=:center)\nend\n \nmuv = Movie(400, 400, \"Pendulum Demo\", 1:length(tspan))\nanimate(muv, [Scene(muv, backdrop),\n              Scene(muv, frame, easingfunction=easeinoutcubic)],\n              creategif=true, pathname=giffilename)\n\n\n","human_summarization":"simulate and animate a simple gravity pendulum.","id":2011}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n# Pkg.add(\"JSON\") ... an external library http:\/\/docs.julialang.org\/en\/latest\/packages\/packagelist\/\nusing JSON\n\nsample = Dict()\nsample[\"blue\"] = [1, 2]\nsample[\"ocean\"] = \"water\"\n\n@show sample jsonstring = json(sample)\n@show jsonobj = JSON.parse(jsonstring)\n\n@assert jsonstring == \"{\\\"ocean\\\":\\\"water\\\",\\\"blue\\\":[1,2]}\"\n@assert jsonobj == Dict(\"ocean\" => \"water\", \"blue\" => [1, 2])\n@assert typeof(jsonobj) == Dict{String, Any}\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":2012}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 1.2\n\nfunction nthroot(n::Integer, r::Real)\n    r < 0 || n == 0 && throw(DomainError())\n    n < 0 && return 1 \/ nthroot(-n, r)\n    r > 0 || return 0\n    x = r \/ n\n    prevdx = r\n    while true\n        y = x ^ (n - 1)\n        dx = (r - y * x) \/ (n * y)\n        abs(dx) \u2265 abs(prevdx) && return x\n        x += dx\n        prevdx = dx\n    end\nend\n\n@show nthroot.(-5:2:5, 5.0)\n@show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 .\/ (-5:2:5))\n\n\n","human_summarization":"implement the algorithm to compute the principal nth root of a positive real number using Newton's method, as per the specifications provided on the Wikipedia page. The code does not use Julia's built-in exponentiation function.","id":2013}
    {"lang_cluster":"Julia","source_code":"\nprintln(gethostname())\n\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":2014}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nfunction L(n, add::Int=1, firsts::Vector=[1, 1])\n    l = max(maximum(n) .+ 1, length(firsts))\n    r = Vector{Int}(l)\n    r[1:length(firsts)] = firsts\n    for i in 3:l\n        r[i] = r[i - 1] + r[i - 2] + add\n    end\n    return r[n .+ 1]\nend\n\n# Task 1\nprintln(\"First 25 Leonardo numbers: \", join(L(0:24), \", \"))\n\n# Task 2\n@show L(0) L(1)\n\n# Task 4\nprintln(\"First 25 Leonardo numbers starting with [0, 1]: \", join(L(0:24, 0, [0, 1]), \", \"))\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":2015}
    {"lang_cluster":"Julia","source_code":"\n\nvalidexpr(ex::Expr) = ex.head == :call && ex.args[1] in [:*,:\/,:+,:-] && all(validexpr, ex.args[2:end])\nvalidexpr(ex::Int) = true\nvalidexpr(ex::Any) = false\nfindnumbers(ex::Number) = Int[ex]\nfindnumbers(ex::Expr) = vcat(map(findnumbers, ex.args)...)\nfindnumbers(ex::Any) = Int[]\nfunction twentyfour()\n    digits = sort!(rand(1:9, 4))\n    while true\n        print(\"enter expression using $digits => \")\n        ex = parse(readline())\n        try\n            validexpr(ex) || error(\"only *, \/, +, - of integers is allowed\")\n            nums = sort!(findnumbers(ex))\n            nums == digits || error(\"expression $ex used numbers $nums\u00a0!= $digits\")\n            val = eval(ex)\n            val == 24 || error(\"expression $ex evaluated to $val, not 24\")\n            println(\"you won!\")\n            return\n        catch e\n            if isa(e, ErrorException)\n                println(\"incorrect: \", e.msg)\n            else\n                rethrow()\n            end\n        end\n    end\nend\n\n\n","human_summarization":"The code generates four random digits from 1 to 9 and prompts the player to form an arithmetic expression using these digits exactly once. The expression should evaluate to 24 using only addition, subtraction, multiplication, and division operators. The code checks and evaluates the player's expression, ensuring it only includes the allowed operations. The order of the digits does not need to be preserved in the expression. The code does not generate the expression or test its possibility.","id":2016}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nusing IterTools\n\nencode(str::String) = collect((length(g), first(g)) for g in groupby(first, str))\ndecode(cod::Vector) = join(repeat(\"$l\", n) for (n, l) in cod)\n\nfor original in [\"aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa\", \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"]\n    encoded = encode(original)\n    decoded = decode(encoded)\n    println(\"Original: $original\\n -> encoded: $encoded\\n -> decoded: $decoded\")\nend\n\n\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":2017}
    {"lang_cluster":"Julia","source_code":"\ns = \"hello\"\nprintln(s * \" there!\")\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":2018}
    {"lang_cluster":"Julia","source_code":"\n \n\/\/version 1.0.1\nimport HTTP.URIs: escapeuri\n\ndcd = \"http:\/\/foo bar\/\"\nenc = escapeuri(dcd)\n\nprintln(dcd, \" => \", enc)\n\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":2019}
    {"lang_cluster":"Julia","source_code":"\njulia> sort(union([5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9]))\n7-element Array{Int64,1}:\n 1\n 3\n 4\n 5\n 7\n 8\n 9\n\njulia> sort(union([2, 3, 4], split(\"3.14 is not an integer\", r\"\\s+\")), lt=(x, y) -> \"$x\" < \"$y\")\n8-element Array{Any,1}:\n 2\n 3\n  \"3.14\"\n 4\n  \"an\"\n  \"integer\"\n  \"is\"\n  \"not\"\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":2020}
    {"lang_cluster":"Julia","source_code":"\n\nusing Printf\n\nstruct KPCSupply{T<:Real}\n    item::String\n    weight::T\n    value::T\n    uvalue::T\nend\nfunction KPCSupply(item::AbstractString, weight::Real, value::Real)\n    w, v = promote(weight, value)\n    KPCSupply(item, w, v, v \/ w)\nend\n\nBase.show(io::IO, s::KPCSupply) = print(io, s.item, @sprintf \" (%.2f kg, %.2f \u20ac, %.2f \u20ac\/kg)\" s.weight s.value s.uvalue)\nBase.isless(a::KPCSupply, b::KPCSupply) = a.uvalue < b.uvalue\n\nfunction solve(store::Vector{KPCSupply{T}}, capacity::Real) where T<:Real\n    sack = similar(store, 0) # vector like store, but of length 0\n    kweight = zero(T)\n    for s in sort(store, rev = true)\n        if kweight + s.weight \u2264 capacity\n            kweight += s.weight\n            push!(sack, s)\n        else\n            w = capacity - kweight\n            v = w * s.uvalue\n            push!(sack, KPCSupply(s.item, w, v, s.value))\n            break\n        end\n    end\n    return sack\nend\n\n\nstore = [KPCSupply(\"beef\", 38\/\/10, 36),\n         KPCSupply(\"pork\", 54\/\/10, 43),\n         KPCSupply(\"ham\", 36\/\/10, 90),\n         KPCSupply(\"greaves\", 24\/\/10, 45),\n         KPCSupply(\"flitch\", 4\/\/1, 30),\n         KPCSupply(\"brawn\", 25\/\/10, 56),\n         KPCSupply(\"welt\", 37\/\/10, 67),\n         KPCSupply(\"salami\", 3\/\/1, 95),\n         KPCSupply(\"sausage\", 59\/\/10, 98)]\n\nsack = solve(store, 15)\nprintln(\"The store contains:\\n - \", join(store, \"\\n - \"))\nprintln(\"\\nThe thief should take::\\n - \", join(sack, \"\\n - \"))\n@printf(\"\\nTotal value in the sack: %.2f \u20ac\\n\", sum(getfield.(sack, :value)))\n\n\n","human_summarization":"The code implements a solution to the continuous knapsack problem. It defines a type KPCSupply to hold item data including its unit value. The code sorts the items by their unit value and selects the highest value items until the knapsack's capacity is reached. It uses an outer constructor method to create instances of KPCSupply and a method isless for sorting. The code supports any real type for weight, value, and uvalue and uses Rational numbers to avoid rounding errors.","id":2021}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 1.6\nurl = \"http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt\"\nwordlist = open(readlines, download(url))\n\nwsort(word::AbstractString) = join(sort(collect(word)))\n\nfunction anagram(wordlist::Vector{<:AbstractString})\n    dict = Dict{String, Set{String}}()\n    for word in wordlist\n        sorted = wsort(word)\n        push!(get!(dict, sorted, Set{String}()), word)\n    end\n    wcnt = maximum(length, values(dict))\n    return collect(Iterators.filter((y) -> length(y) == wcnt, values(dict)))\nend\n\nprintln.(anagram(wordlist))\n\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":2022}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nfunction sierpinski(n::Integer, token::AbstractString=\"*\")\n    x = fill(token, 1, 1)\n    for _ in 1:n\n        t = fill(\" \", size(x))\n        x = [x x x; x t x; x x x]\n    end\n    return x\nend\n\nfunction printsierpinski(m::Matrix)\n    for r in 1:size(m, 1)\n        println(join(m[r, :]))\n    end\nend\n\nsierpinski(2, \"#\") |> printsierpinski\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":2023}
    {"lang_cluster":"Julia","source_code":"\nabstract type HuffmanTree end\n\nstruct HuffmanLeaf <: HuffmanTree\n    ch::Char\n    freq::Int\nend\n\nstruct HuffmanNode <: HuffmanTree\n    freq::Int\n    left::HuffmanTree\n    right::HuffmanTree\nend\n\nfunction makefreqdict(s::String)\n    d = Dict{Char, Int}()\n    for c in s\n        if !haskey(d, c)\n            d[c] = 1\n        else\n            d[c] += 1\n        end\n    end\n    d\nend\n\nfunction huffmantree(ftable::Dict)\n    trees::Vector{HuffmanTree} = [HuffmanLeaf(ch, fq) for (ch, fq) in ftable]\n    while length(trees) > 1\n        sort!(trees, lt = (x, y) -> x.freq < y.freq, rev = true)\n        least = pop!(trees)\n        nextleast = pop!(trees)\n        push!(trees, HuffmanNode(least.freq + nextleast.freq, least, nextleast))\n    end\n    trees[1]\nend\n\nprintencoding(lf::HuffmanLeaf, code) = println(lf.ch == ' ' ? \"space\" : lf.ch, \"\\t\", lf.freq, \"\\t\", code)\n\nfunction printencoding(nd::HuffmanNode, code)\n    code *= '0'\n    printencoding(nd.left, code)\n    code = code[1:end-1]\n\n    code *= '1'\n    printencoding(nd.right, code)\n    code = code[1:end-1]\nend\n\nconst msg = \"this is an example for huffman encoding\"\n\nprintln(\"Char\\tFreq\\tHuffman code\")\n\nprintencoding(huffmantree(makefreqdict(msg)), \"\")\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":2024}
    {"lang_cluster":"Julia","source_code":"\n\nusing Gtk.ShortNames\n\nfunction clickwindow()\n    clicks = 0\n    win = Window(\"Click Counter\", 300, 100) |> (Frame() |> (vbox = Box(:v)))\n    lab = Label(\"There have been no clicks yet.\")\n    but = Button(\"click me\")\n    push!(vbox, lab)\n    push!(vbox, but)\n    set_gtk_property!(vbox, :expand, lab, true)\n    set_gtk_property!(vbox, :spacing, 20)\n    callback(w) = (clicks += 1; set_gtk_property!(lab, :label, \"There have been $clicks button clicks.\"))\n    id = signal_connect(callback, but, :clicked)\n    Gtk.showall(win)\n    c = Condition()\n    endit(w) = notify(c)\n    signal_connect(endit, win, :destroy)\n    wait(c)\nend\n\nclickwindow()\n\n","human_summarization":"The code creates a simple windowed application using the Gtk library. It features a label displaying \"There have been no clicks yet\" and a button labeled \"click me\". The label updates to show the number of times the button has been clicked.","id":2025}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nusing SQLite\n\ndb = SQLite.DB()\nSQLite.execute!(db, \"\"\"\\\n\tCREATE TABLE address (\n\taddrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\n\taddrStreet\tTEXT NOT NULL,\n\taddrCity\tTEXT NOT NULL,\n\taddrState\tTEXT NOT NULL,\n\taddrZIP\t\tTEXT NOT NULL)\n\t\"\"\")\n\n","human_summarization":"create a table in a database to store US postal addresses, including fields for a unique identifier, street address, city, state code, and zipcode. The codes also demonstrate how to establish a database connection in non-database languages.","id":2026}
    {"lang_cluster":"Julia","source_code":"\nfor i in 10:-1:0\n    println(i)\nend\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":2027}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 1.5\n\u2192(a::Char, b::Char, \u00b1 = +) = 'A'+((a-'A')\u00b1(b-'A')+26)%26\n\u2190(a::Char, b::Char) = \u2192(a,b,-)\n\ncleanup(str) = filter(a-> a in 'A':'Z', collect(uppercase.(str)))\nmatch_length(word, len) = repeat(word,len)[1:len]\n\nfunction \u2192(message::String, codeword::String, \u2194 = \u2192)\n    plaintext = cleanup(message)\n    key = match_length(cleanup(codeword),length(plaintext))\n    return String(plaintext .\u2194 key)\nend\n\u2190(message::String, codeword::String) = \u2192(message,codeword,\u2190)\n\ncyphertext = \"I want spearmint gum\" \u2192 \"Gimme!\"\nprintln(cyphertext)\nprintln(cyphertext \u2190 \"Gimme!\")\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":2028}
    {"lang_cluster":"Julia","source_code":"\nfor i in 2:2:8\n    print(i, \", \")\nend\nprintln(\"whom do we appreciate?\")\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":2029}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6macro sum(i, loname, hiname, term)\n    return quote\n        lo = $loname\n        hi = $hiname\n        tmp = 0.0\n        for i in lo:hi\n            tmp += $term\n        end\n        return tmp\n    end\nend\n\ni = 0\n@sum(i, 1, 100, 1.0 \/ i)\n\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":2030}
    {"lang_cluster":"Julia","source_code":"\nusing Gtk, Cairo\n\nconst can = @GtkCanvas()\nconst win = GtkWindow(can, \"Munching Squares\", 512, 512)\n\n@guarded draw(can) do widget\n    ctx = getgc(can)\n    for x in 0:255, y in 0:255\n        set_source_rgb(ctx, abs(255 - x - y) \/ 255, ((255 - x) \u22bb y) \/ 255, (x \u22bb (255 - y)) \/ 255)\n        circle(ctx, 2x, 2y, 2)\n        fill(ctx)\n    end\nend\n\nshow(can)\nconst cond = Condition()\nendit(w) = notify(cond)\nsignal_connect(endit, win, :destroy)\nwait(cond)\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":2031}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version >0.6\n\nusing Random\ncheck(bound::Vector) = cell -> all([1, 1] .\u2264 cell .\u2264 bound)\nneighbors(cell::Vector, bound::Vector, step::Int=2) =\n    filter(check(bound), map(dir -> cell + step * dir, [[0, 1], [-1, 0], [0, -1], [1, 0]]))\n\nfunction walk(maze::Matrix, nxtcell::Vector, visited::Vector=[])\n    push!(visited, nxtcell)\n    for neigh in shuffle(neighbors(nxtcell, collect(size(maze))))\n        if neigh \u2209 visited\n            maze[round.(Int, (nxtcell + neigh) \/ 2)...] = 0\n            walk(maze, neigh, visited)\n        end\n    end\n    maze\nend\nfunction maze(w::Int, h::Int)\n    maze = collect(i % 2 | j % 2 for i in 1:2w+1, j in 1:2h+1)\n    firstcell = 2 * [rand(1:w), rand(1:h)]\n    return walk(maze, firstcell)\nend\n\n\npprint(matrix) = for i = 1:size(matrix, 1) println(join(matrix[i, :])) end\nfunction printmaze(maze)\n    walls = split(\"\u2579 \u2578 \u251b \u257a \u2517 \u2501 \u253b \u257b \u2503 \u2513 \u252b \u250f \u2523 \u2533 \u254b\")\n    h, w = size(maze)\n    f = cell -> 2 ^ ((3cell[1] + cell[2] + 3) \/ 2)\n    wall(i, j) = if maze[i,j] == 0 \" \" else\n        walls[Int(sum(f, filter(x -> maze[x...] != 0, neighbors([i, j], [h, w], 1)) .- [[i, j]]))]\n    end\n    mazewalls = collect(wall(i, j) for i in 1:2:h, j in 1:w)\n    pprint(mazewalls)\nend\n\nprintmaze(maze(10, 10))\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts at a random cell, marks it as visited, and obtains a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, then recursively performs the same process for the neighbor. The code includes functions for generating and printing the maze.","id":2032}
    {"lang_cluster":"Julia","source_code":"\n\nlet prec = precision(BigFloat), spi = \"\", digit = 1\n    while true\n      if digit > lastindex(spi)\n        prec *= 2\n        setprecision(prec)\n        spi = string(big(\u03c0))\n      end\n      print(spi[digit])\n      digit += 1\n    end\nend\n\n\n3.141592653589793238462643383279502884195e69399375105820974944592307816406286198e9862803482534211706798214808651328230664709384460955058223172535940812848115e450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724586997e0631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912983367336244065664308602139494639522473719070217986094370277053921717629317675238467481846766940513200056812714526357e8277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201...\n","human_summarization":"continuously calculate and print the next decimal digit of Pi, starting from 3.14159265, until the program is manually terminated by the user. The precision of Pi is computed using the built-in support in Julia with the GNU MPFR library, and the precision is doubled as more digits are needed.","id":2033}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nfunction islexless(a::AbstractArray{<:Real}, b::AbstractArray{<:Real})\n    for (x, y) in zip(a, b)\n        if x == y continue end\n        return x < y\n    end\n    return length(a) < length(b)\nend\n\nusing Primes, Combinatorics\ntests = [[1, 2, 3], primes(10), 0:2:6, [-Inf, 0.0, Inf], [\u03c0, e, \u03c6, catalan], [2015, 5], [-sqrt(50.0), 50.0 ^ 2]]\nprintln(\"List not sorted:\\n - \", join(tests, \"\\n - \"))\nsort!(tests; lt=islexless)\nprintln(\"List sorted:\\n - \", join(tests, \"\\n - \"))\n\n\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise.\"","id":2034}
    {"lang_cluster":"Julia","source_code":"\nfunction ack(m,n)\n    if m == 0\n        return n + 1\n    elseif n == 0\n        return ack(m-1,1)\n    else\n        return ack(m-1,ack(m,n-1))\n    end\nend\n\nack2(m::Integer, n::Integer) = m == 0\u00a0? n + 1\u00a0: n == 0\u00a0? ack2(m - 1, 1)\u00a0: ack2(m - 1, ack2(m, n - 1))\n\nusing Memoize\n@memoize ack3(m::Integer, n::Integer) = m == 0\u00a0? n + 1\u00a0: n == 0\u00a0? ack3(m - 1, 1)\u00a0: ack3(m - 1, ack3(m, n - 1))\n\njulia> @time ack2(4,1)\nelapsed time: 71.98668457 seconds (96 bytes allocated)\n65533\n\njulia> @time ack3(4,1)\nelapsed time: 0.49337724 seconds (30405308 bytes allocated)\n65533\n","human_summarization":"Implement the Ackermann function, a non-primitive recursive function. The function takes two non-negative arguments and returns a value based on the conditions: if the first argument is zero, it returns the second argument plus one; if the first argument is greater than zero and the second argument is zero, it calls itself with the first argument decreased by one and one as the second argument; if both arguments are greater than zero, it calls itself with the first argument decreased by one and the second argument as the result of a recursive call with the first argument and the second argument decreased by one. The function should terminate and return a value. The function should preferably support arbitrary precision due to its rapid growth.","id":2035}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n\n@show gamma(1)\n\n\nusing QuadGK\ngammaquad(t::Float64) = first(quadgk(x -> x ^ (t - 1) * exp(-x), zero(t), Inf, reltol = 100eps(t)))\n@show gammaquad(1.0)\n\n\n","human_summarization":"implement and compare the Gamma function using different methods including numerical integration, Lanczos approximation, Stirling's approximation, built-in function, and library function. The Gamma function is computed in the real field only.","id":2036}
    {"lang_cluster":"Julia","source_code":"\n\"\"\"\n# EightQueensPuzzle\n\nPorted to **Julia** from examples in several languages from\nhere: https:\/\/hbfs.wordpress.com\/2009\/11\/10\/is-python-slow\n\"\"\"\nmodule EightQueensPuzzle\n\nexport Board, solve!\n\nmutable struct Board\n    cols::Int\n    nodes::Int\n    diag45::Int\n    diag135::Int\n    solutions::Int\n\n    Board() = new(0, 0, 0, 0, 0)\nend\n\n\"Marks occupancy.\"\nfunction mark!(b::Board, k::Int, j::Int)\n    b.cols    \u22bb= (1 << j)\n    b.diag135 \u22bb= (1 << (j+k))\n    b.diag45  \u22bb= (1 << (32+j-k))\nend\n\n\"Tests if a square is menaced.\"\nfunction test(b::Board, k::Int, j::Int)\n    b.cols    & (1 << j)        +\n    b.diag135 & (1 << (j+k))    +\n    b.diag45  & (1 << (32+j-k)) == 0\nend\n\n\"Backtracking solver.\"\nfunction solve!(b::Board, niv::Int, dx::Int)\n    if niv > 0\n        for i in 0:dx-1\n            if test(b, niv, i) == true\n                mark!(b, niv, i)\n                solve!(b, niv-1, dx)\n                mark!(b, niv, i)\n            end\n        end\n    else\n        for i in 0:dx-1\n            if test(b, 0, i) == true\n                b.solutions += 1\n            end\n        end\n    end\n    b.nodes += 1\n    b.solutions\nend\n\nend # module\n\nusing  .EightQueensPuzzle\n\nfor n = 1:17\n    b = Board()\n    @show n\n    print(\"elapsed:\")\n    solutions = @time solve!(b, n-1, n)\n    @show solutions\n    println()\nend\n \n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":2037}
    {"lang_cluster":"Julia","source_code":"\na = [1,2,3]\nb = [4,5,6]\nab = [a;b]\n# the above bracket notation simply generates a call to vcat\nab = vcat(a,b)\n# hcat is short for `horizontal concatenation`\nab = hcat(a,b) \t#ab -> 3x2 matrix\n# the append!(a,b) method is mutating, appending `b` to `a`\nappend!(a,b)\t# a now equals [1,2,3,4,5,6]\n\n","human_summarization":"demonstrate how to concatenate two arrays.","id":2038}
    {"lang_cluster":"Julia","source_code":"\n\nstruct KPDSupply{T<:Integer}\n    item::String\n    weight::T\n    value::T\n    quant::T\nend\n\nKPDSupply{T<:Integer}(itm::AbstractString, w::T, v::T, q::T=one(T)) = KPDSupply(itm, w, v, q)\nBase.show(io::IO, kdps::KPDSupply) = print(io, kdps.quant, \" \", kdps.item, \" ($(kdps.weight) kg, $(kdps.value) \u20ac)\")\n\nusing MathProgBase, Cbc\nfunction solve(gear::Vector{<:KPDSupply}, capacity::Integer)\n    w = getfield.(gear, :weight)\n    v = getfield.(gear, :value)\n    sol = mixintprog(-v, w', '<', capacity, :Bin, 0, 1, CbcSolver())\n    gear[sol.sol .\u2248 1]\nend\n\n\ngear = [KPDSupply(\"map\", 9, 150),\n        KPDSupply(\"compass\", 13, 35),\n        KPDSupply(\"water\", 153, 200),\n        KPDSupply(\"sandwich\", 50, 160),\n        KPDSupply(\"glucose\", 15, 60),\n        KPDSupply(\"tin\", 68, 45),\n        KPDSupply(\"banana\", 27, 60),\n        KPDSupply(\"apple\", 39, 40),\n        KPDSupply(\"cheese\", 23, 30),\n        KPDSupply(\"beer\", 52, 10),\n        KPDSupply(\"suntan cream\", 11, 70),\n        KPDSupply(\"camera\", 32, 30),\n        KPDSupply(\"T-shirt\", 24, 15),\n        KPDSupply(\"trousers\", 48, 10),\n        KPDSupply(\"umbrella\", 73, 40),\n        KPDSupply(\"waterproof trousers\", 42, 70),\n        KPDSupply(\"waterproof overclothes\", 43, 75),\n        KPDSupply(\"note-case\", 22, 80),\n        KPDSupply(\"sunglasses\", 7, 20),\n        KPDSupply(\"towel\", 18, 12),\n        KPDSupply(\"socks\", 4, 50),\n        KPDSupply(\"book\", 30, 10)]\n\npack = solve(gear, 400)\nprintln(\"The hicker should pack: \\n - \", join(pack, \"\\n - \"))\nprintln(\"\\nPacked weight: \", mapreduce(x -> x.weight, +, pack), \" kg\")\nprintln(\"Packed value: \", mapreduce(x -> x.value, +, pack), \" \u20ac\")\n\n\n","human_summarization":"The code determines the optimal combination of items that a tourist can carry in his knapsack, given a weight limit of 4kg. It uses the 0-1 Knapsack problem algorithm, considering the weight and importance of each item, to maximize the total value without exceeding the weight limit. The solution is implemented using the MathProgBase package and the Cbc solver package.","id":2039}
    {"lang_cluster":"Julia","source_code":"\n# This is not optimized, but tries to follow the pseudocode given the Wikipedia entry below.\n# Reference: https:\/\/en.wikipedia.org\/wiki\/Stable_marriage_problem#Algorithm\n\nconst males = [\"abe\", \"bob\", \"col\", \"dan\", \"ed\", \"fred\", \"gav\", \"hal\", \"ian\", \"jon\"]\nconst females = [\"abi\", \"bea\", \"cath\", \"dee\", \"eve\", \"fay\", \"gay\", \"hope\", \"ivy\", \"jan\"]\n\nconst malepreferences = Dict(\n  \"abe\" => [\"abi\", \"eve\", \"cath\", \"ivy\", \"jan\", \"dee\", \"fay\", \"bea\", \"hope\", \"gay\"],\n  \"bob\" => [\"cath\", \"hope\", \"abi\", \"dee\", \"eve\", \"fay\", \"bea\", \"jan\", \"ivy\", \"gay\"],\n  \"col\" => [\"hope\", \"eve\", \"abi\", \"dee\", \"bea\", \"fay\", \"ivy\", \"gay\", \"cath\", \"jan\"],\n  \"dan\" => [\"ivy\", \"fay\", \"dee\", \"gay\", \"hope\", \"eve\", \"jan\", \"bea\", \"cath\", \"abi\"],\n   \"ed\" => [\"jan\", \"dee\", \"bea\", \"cath\", \"fay\", \"eve\", \"abi\", \"ivy\", \"hope\", \"gay\"],\n \"fred\" => [\"bea\", \"abi\", \"dee\", \"gay\", \"eve\", \"ivy\", \"cath\", \"jan\", \"hope\", \"fay\"],\n  \"gav\" => [\"gay\", \"eve\", \"ivy\", \"bea\", \"cath\", \"abi\", \"dee\", \"hope\", \"jan\", \"fay\"],\n  \"hal\" => [\"abi\", \"eve\", \"hope\", \"fay\", \"ivy\", \"cath\", \"jan\", \"bea\", \"gay\", \"dee\"],\n  \"ian\" => [\"hope\", \"cath\", \"dee\", \"gay\", \"bea\", \"abi\", \"fay\", \"ivy\", \"jan\", \"eve\"],\n  \"jon\" => [\"abi\", \"fay\", \"jan\", \"gay\", \"eve\", \"bea\", \"dee\", \"cath\", \"ivy\", \"hope\"]\n)\n\nconst femalepreferences = Dict(\n  \"abi\"=> [\"bob\", \"fred\", \"jon\", \"gav\", \"ian\", \"abe\", \"dan\", \"ed\", \"col\", \"hal\"],\n  \"bea\"=> [\"bob\", \"abe\", \"col\", \"fred\", \"gav\", \"dan\", \"ian\", \"ed\", \"jon\", \"hal\"],\n \"cath\"=> [\"fred\", \"bob\", \"ed\", \"gav\", \"hal\", \"col\", \"ian\", \"abe\", \"dan\", \"jon\"],\n  \"dee\"=> [\"fred\", \"jon\", \"col\", \"abe\", \"ian\", \"hal\", \"gav\", \"dan\", \"bob\", \"ed\"],\n  \"eve\"=> [\"jon\", \"hal\", \"fred\", \"dan\", \"abe\", \"gav\", \"col\", \"ed\", \"ian\", \"bob\"],\n  \"fay\"=> [\"bob\", \"abe\", \"ed\", \"ian\", \"jon\", \"dan\", \"fred\", \"gav\", \"col\", \"hal\"],\n  \"gay\"=> [\"jon\", \"gav\", \"hal\", \"fred\", \"bob\", \"abe\", \"col\", \"ed\", \"dan\", \"ian\"],\n \"hope\"=> [\"gav\", \"jon\", \"bob\", \"abe\", \"ian\", \"dan\", \"hal\", \"ed\", \"col\", \"fred\"],\n  \"ivy\"=> [\"ian\", \"col\", \"hal\", \"gav\", \"fred\", \"bob\", \"abe\", \"ed\", \"jon\", \"dan\"],\n  \"jan\"=> [\"ed\", \"hal\", \"gav\", \"abe\", \"bob\", \"jon\", \"col\", \"ian\", \"fred\", \"dan\"]\n)\n\nfunction pshuf(d)\n    ret = Dict()\n    for (k,v) in d\n        ret[k] = shuffle(v)\n    end\n    ret\nend\n\n# helper functions for the verb: p1 \"prefers\" p2 over p3\npindexin(a, p) = ([i for i in 1:length(a) if a[i] == p])[1]\nprefers(d, p1, p2, p3) = (pindexin(d[p1], p2) < pindexin(d[p1], p3))\n\nfunction isstable(mmatchup, fmatchup, mpref, fpref)\n    for (mmatch, fmatch) in mmatchup\n        for f in mpref[mmatch]\n            if(f != fmatch && prefers(mpref, mmatch, f, fmatch)\n                           && prefers(fpref, f, mmatch, fmatchup[f]))\n                println(\"$mmatch prefers $f and $f prefers $mmatch over their current partners.\")\n                return false\n            end\n        end\n    end\n    true\nend\n\nfunction galeshapley(men, women, malepref, femalepref)\n    # Initialize all m \u2208 M and w \u2208 W to free\n    mfree = Dict([(p, true) for p in men])\n    wfree = Dict([(p, true) for p in women])\n    mpairs = Dict()\n    wpairs = Dict()\n    while true                    # while \u2203 free man m who still has a woman w to propose to\n        bachelors = [p for p in keys(mfree) if mfree[p]]\n        if(length(bachelors) == 0)\n            return mpairs, wpairs\n        end\n        for m in bachelors\n            for w in malepref[m]  # w = first woman on m\u2019s list to whom m has not yet proposed\n                if(wfree[w])      # if w is free (else some pair (m', w) already exists)\n                    #println(\"Free match: $m, $w\")\n                    mpairs[m] = w # (m, w) become engaged\n                    wpairs[w] = m # double entry bookeeping\n                    mfree[m] = false\n                    wfree[w] = false\n                    break\n                elseif(prefers(femalepref, w, m, wpairs[w])) # if w prefers m to m'\n                    #println(\"Unmatch $(wpairs[w]), match: $m, $w\")\n                    mfree[wpairs[w]] = true # m' becomes free\n                    mpairs[m] = w           # (m, w) become engaged\n                    wpairs[w] = m\n                    mfree[m] = false\n                    break\n                end                         # else (m', w) remain engaged, so continue\n            end\n        end\n    end\nend\n\nfunction tableprint(txt, ans, stab)\n    println(txt)\n    println(\"   Man     Woman\")\n    println(\"   -----   -----\")\n    show(STDOUT, \"text\/plain\", ans)\n    if(stab)\n        println(\"\\n  ----STABLE----\\n\\n\")\n    else\n        println(\"\\n  ---UNSTABLE---\\n\\n\")\n    end\nend\n\nprintln(\"Use the Gale Shapley algorithm to find a stable set of engagements.\")\nanswer = galeshapley(males, females, malepreferences, femalepreferences)\nstabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)\ntableprint(\"Original Data Table\", answer[1], stabl)\n\nprintln(\"To check this is not a one-off solution, run the function on a randomized sample.\")\nnewmpref = pshuf(malepreferences)\nnewfpref = pshuf(femalepreferences)\nanswer = galeshapley(males, females, newmpref, newfpref)\nstabl = isstable(answer[1], answer[2], newmpref, newfpref)\ntableprint(\"Shuffled Preferences\", answer[1], stabl)\n\n# trade abe with bob\nprintln(\"Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.\")\nanswer = galeshapley(males, females, malepreferences, femalepreferences)\nfia1 = (answer[1])[\"abe\"]\nfia2 = (answer[1])[\"bob\"]\nanswer[1][\"abe\"] = fia2\nanswer[1][\"bob\"] = fia1\nanswer[2][fia1] = \"bob\"\nanswer[2][fia2] = \"abe\"\nstabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)\ntableprint(\"Original Data With Bob and Abe Switched\", answer[1], stabl)\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":2040}
    {"lang_cluster":"Julia","source_code":"\n\na(x) = (println(\"\\t# Called a($x)\"); return x)\nb(x) = (println(\"\\t# Called b($x)\"); return x)\n\nfor i in [true,false], j in [true, false]\n    println(\"\\nCalculating: x = a($i) && b($j)\"); x = a(i) && b(j)\n    println(\"\\tResult: x = $x\")\n    println(\"\\nCalculating: y = a($i) || b($j)\"); y = a(i) || b(j)\n    println(\"\\tResult: y = $y\")\nend\n\n\n","human_summarization":"The code defines two functions, a and b, which both take and return the same boolean value, and print their name when called. It then calculates the values of two equations, x = a(i) and b(j), and y = a(i) or b(j), using short-circuit evaluation to ensure that function b is only called when necessary. If the language doesn't support short-circuit evaluation, this is achieved using nested if statements.","id":2041}
    {"lang_cluster":"Julia","source_code":"\n\nusing PortAudio\n\nconst pstream = PortAudioStream(0, 2)\nsendmorsesound(t, f) = write(pstream, SinSource(eltype(stream), samplerate(stream)*0.8, [f]), (t\/1000)s)\n\nchar2morse = Dict[\n      \"!\" => \"---.\", \"\\\"\" => \".-..-.\", \"$\" => \"...-..-\", \"'\" => \".----.\",\n      \"(\" => \"-.--.\", \")\" => \"-.--.-\", \"+\" => \".-.-.\", \",\" => \"--..--\",\n      \"-\" => \"-....-\", \".\" => \".-.-.-\", \"\/\" => \"-..-.\", \"0\" => \"-----\",\n      \"1\" => \".----\", \"2\" => \"..---\", \"3\" => \"...--\", \"4\" => \"....-\", \"5\" => \".....\",\n      \"6\" => \"-....\", \"7\" => \"--...\", \"8\" => \"---..\", \"9\" => \"----.\", \":\" => \"---...\",\n      \";\" => \"-.-.-.\", \"=\" => \"-...-\", \"?\" => \"..--..\", \"@\" => \".--.-.\", \"A\" => \".-\",\n      \"B\" => \"-...\", \"C\" => \"-.-.\", \"D\" => \"-..\", \"E\" => \".\", \"F\" => \"..-.\",\n      \"G\" => \"--.\", \"H\" => \"....\", \"I\" => \"..\", \"J\" => \".---\", \"K\" => \"-.-\",\n      \"L\" => \".-..\", \"M\" => \"--\", \"N\" => \"-.\", \"O\" => \"---\", \"P\" => \".--.\",\n      \"Q\" => \"--.-\", \"R\" => \".-.\", \"S\" => \"...\", \"T\" => \"-\", \"U\" => \"..-\",\n      \"V\" => \"...-\", \"W\" => \".--\", \"X\" => \"-..-\", \"Y\" => \"-.--\", \"Z\" => \"--..\",\n      \"[\" => \"-.--.\", \"]\" => \"-.--.-\", \"_\" => \"..--.-\"]\n \nfunction sendmorsesound(freq, duration)\ncpause() = sleep(0.080)\nwpause = sleep(0.400)\n\ndit() = sendmorsesound(0.070, 700)\ndash() = sensmorsesound(0.210, 700)\nsendmorsechar(c) = for d in char2morse(c) d == '.' ? dit(): dash() end end\nsendmorseword(w) = for c in w sendmorsechar(c) cpause() end wpause() end\nsendmorse(msg) = for word in uppercase(msg) sendmorseword(word) end\n\nsendmorse(\"sos sos sos\")\nsendmorse(\"The case of letters in Morse coding is ignored.\"\n\n","human_summarization":"The code converts a given string into audible Morse code, which is then sent to an audio device like a PC speaker. It handles unknown characters by either ignoring them or indicating them with a different pitch. It requires a sound card and the PortAudio libraries for operation.","id":2042}
    {"lang_cluster":"Julia","source_code":"\nusing Printf\n\nfunction abc(str::AbstractString, list)\n    isempty(str) && return true\n    for i in eachindex(list)\n        str[end] in list[i] &&\n            any([abc(str[1:end-1], deleteat!(copy(list), i))]) &&\n            return true\n    end\n    return false\nend\n\nlet test = [\"A\", \"BARK\",\"BOOK\",\"TREAT\",\"COMMON\",\"SQUAD\",\"CONFUSE\"],\n    list = [\"BO\",\"XK\",\"DQ\",\"CP\",\"NA\",\"GT\",\"RE\",\"TG\",\"QD\",\"FS\",\n            \"JW\",\"HU\",\"VI\",\"AN\",\"OB\",\"ER\",\"FS\",\"LY\",\"PC\",\"ZM\"]\n    for str in test\n        @printf(\"%-8s |  %s\\n\", str, abc(str, list))\n    end\nend\n\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":2043}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\nusing Nettle\n\nfunction Base.trunc(s::AbstractString, n::Integer)\n    n > 0 || throw(DomainError())\n    l = length(s)\n    l > n || return s\n    n > 3 || return s[1:n]\n    return s[1:n-3] * \"...\"\nend\n\ntests = [\"\"    => \"d41d8cd98f00b204e9800998ecf8427e\",\n         \"a\"   => \"0cc175b9c0f1b6a831c399e269772661\",\n         \"abc\" => \"900150983cd24fb0d6963f7d28e17f72\",\n         \"message digest\" => \"f96b697d7cb7938d525a2f31aaf161d0\",\n         \"abcdefghijklmnopqrstuvwxyz\" => \"c3fcd3d76192e4007dfb496cca67e13b\",\n         \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\" =>\n         \"d174ab98d277d9f5a5611c2c9f419d9f\",\n         \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\" =>\n         \"57edf4a22be3c955ac49da2e2107b67a\",\n         \"foobad\" => \"3858f62230ac3c915f300c664312c63f\"]\n\nprintln(\"Testing Julia's MD5 hash against RFC 1321.\")\nfor (k, h) in sort(tests, by = length \u2218 first)\n    md5sum = hexdigest(\"md5\", k)\n    @printf(\"%20s \u2192 %s \", trunc(k, 15), md5sum)\n    if md5sum == h\n        println(\"MD5 OK\")\n    else\n        println(\"MD5 Bad\")\n        println(\"* The sum should be  \", h)\n    end\nend\n\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":2044}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\noidlist = [\"1.3.6.1.4.1.11.2.17.19.3.4.0.10\",\n           \"1.3.6.1.4.1.11.2.17.5.2.0.79\",\n           \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\",\n           \"1.3.6.1.4.1.11150.3.4.0.1\",\n           \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\",\n           \"1.3.6.1.4.1.11150.3.4.0\"]\n\nsort!(oidlist; lt=lexless,\n    by=x -> parse.(Int, String.(split(x, \".\"))))\nprintln.(oidlist)\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":2045}
    {"lang_cluster":"Julia","source_code":"\nsocket = connect(\"localhost\",256)\nwrite(socket, \"hello socket world\")\nclose(socket)\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":2046}
    {"lang_cluster":"Julia","source_code":"\nusing SMTPClient\n\naddbrackets(s) = replace(s, r\"^\\s*([^\\<\\>]+)\\s*$\", s\"<\\1>\")\n\nfunction wrapRFC5322(from, to, subject, msg)\n    timestr = Libc.strftime(\"%a, %d %b %Y %H:%M:%S %z\", time())\n    IOBuffer(\"Date: $timestr\\nTo: $to\\nFrom: $from\\nSubject: $subject\\n\\n$msg\")\nend\n\nfunction sendemail(from, to, subject, messagebody, serverandport;\n                   cc=[], user=\"\", password=\"\", isSSL=true, blocking=true)\n    opt = SendOptions(blocking=blocking, isSSL=isSSL, username=user, passwd=password)\n    send(serverandport, map(s -> addbrackets(s), vcat(to, cc)), addbrackets(from),\n         wrapRFC5322(addbrackets(from), addbrackets(to), subject, messagebody), opt)\nend\n\nsendemail(\"to@example.com\", \"from@example.com\", \"TEST\", \"hello there test message text here\", \"smtps:\/\/smtp.gmail.com\",\n          user=\"from@example.com\", password=\"example.com\")\n\n","human_summarization":"Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.","id":2047}
    {"lang_cluster":"Julia","source_code":"\nfor i in one(Int64):typemax(Int64)\n    print(oct(i), \" \")\n    sleep(0.1)\nend\n\n\n\n","human_summarization":"generate a sequential count in octal format, starting from zero and incrementing by one. Each number is printed on a separate line until the program is terminated or the maximum value of the numeric type is reached. The loop is slowed down with a sleep function to allow for clear visibility of the results.","id":2048}
    {"lang_cluster":"Julia","source_code":"\n\na, b = b, a\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain constraints for type compatibility. The function may not support swapping of incompatible types like string and integer, if not permitted by the language. It also addresses challenges in generic programming, particularly in static languages and functional languages that may not support destructive operations.","id":2049}
    {"lang_cluster":"Julia","source_code":"\npalindrome(s) = s == reverse(s)\n\nfunction palindrome(s)\n    len = length(s)\n    for i = 1:(len\/2)\n        if(s[len-i+1]!=s[i])\n            return false\n        end\n    end\n    return true\nend\n\nfunction palindrome(s)\n    len = length(s)\n    if(len==0 || len==1)\n        return true\n    end\n    if(s[1] == s[len])\n        return palindrome(SubString(s,2,len-1))\n    end\n    return false\nend\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. The function supports Unicode characters and has an additional feature to detect inexact palindromes by ignoring white-space, punctuation, and case sensitivity. The function can be tested both recursively and non-recursively.","id":2050}
    {"lang_cluster":"Julia","source_code":"\nWorks with: Julia version 0.6\n@show ENV[\"PATH\"]\n@show ENV[\"HOME\"]\n@show ENV[\"USER\"]\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":2051}
    {"lang_cluster":"Julia","source_code":"\nusing Memoize\n\n@memoize function sudan(n, x, y)\n   return n == 0 ? x + y : y == 0 ? x : sudan(n - 1, sudan(n, x, y - 1), sudan(n, x, y - 1) + y)\nend\n\nforeach(t -> println(\"sudan($(t[1]), $(t[2]), $(t[3])) = \",\n   sudan(t[1], t[2], t[3])), ((0,0,0), (1,1,1), (2,1,1), (3,1,1), (2,2,1)))\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.","id":2052}
    {"lang_cluster":"PHP","source_code":"\n\n$stack = array();\n\nempty( $stack ); \/\/ true\n\narray_push( $stack, 1 ); \/\/ or $stack[] = 1;\narray_push( $stack, 2 ); \/\/ or $stack[] = 2;\n\nempty( $stack ); \/\/ false\n\necho array_pop( $stack ); \/\/ outputs \"2\"\necho array_pop( $stack ); \/\/ outputs \"1\"\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and is accessed through its top. The push operation stores a new element onto the stack top, the pop operation returns and removes the last pushed stack element, and the empty operation checks if the stack contains no elements. The top operation returns the topmost element without modifying the stack. The stack is commonly used in programming for resource management, particularly memory, and is implemented in various algorithms in pattern matching, compiler construction, and machine learning.","id":2053}
    {"lang_cluster":"PHP","source_code":"\nfunction fibIter($n) {\n    if ($n < 2) {\n        return $n;\n    }\n    $fibPrev = 0;\n    $fib = 1;\n    foreach (range(1, $n-1) as $i) {\n        list($fibPrev, $fib) = array($fib, $fib + $fibPrev);\n    }\n    return $fib;\n}\nfunction fibRec($n) {\n    return $n < 2\u00a0? $n\u00a0: fibRec($n-1) + fibRec($n-2);\n}\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":2054}
    {"lang_cluster":"PHP","source_code":"\n\n$arr = range(1,5);\n$evens = array();\nforeach ($arr as $val){\n      if ($val\u00a0% 2 == 0) $evens[] = $val);\n}\nprint_r($evens);\n\nfunction is_even($var) { return(!($var & 1)); }\n$arr = range(1,5);\n$evens = array_filter($arr, \"is_even\");\nprint_r($evens);\n","human_summarization":"- Selects specific elements from an array to create a new array.\n- Demonstrates this by selecting all even numbers from an array.\n- Optionally, provides a second solution that destructively filters, modifying the original array instead of creating a new one.\n- Implements this task using a standard loop and a filter function.","id":2055}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$str = 'abcdefgh';\n$n = 2;\n$m = 3;\necho substr($str, $n, $m), \"\\n\"; \/\/cde\necho substr($str, $n), \"\\n\"; \/\/cdefgh\necho substr($str, 0, -1), \"\\n\"; \/\/abcdefg\necho substr($str, strpos($str, 'd'), $m), \"\\n\"; \/\/def\necho substr($str, strpos($str, 'de'), $m), \"\\n\"; \/\/def\n?>\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":2056}
    {"lang_cluster":"PHP","source_code":"\n\n\/\/ Will split every Unicode character to array, reverse array and will convert it to string.\njoin('', array_reverse(preg_split('\"\"u', $string, -1, PREG_SPLIT_NO_EMPTY)));\n\nimplode('', array_reverse(mb_str_split($string)));\n\n$a = mb_convert_encoding('👦🏻👋', 'UTF-8', 'HTML-ENTITIES'); \/\/ \ud83d\udc66\ud83c\udffb\ud83d\udc4b\n\nfunction str_to_array($string)\n{\n  $length = grapheme_strlen($string);\n  $ret = [];\n\n  for ($i = 0; $i < $length; $i += 1) {\n\n    $ret[] = grapheme_substr($string, $i, 1);\n  }\n\n  return $ret;\n}\n\nfunction utf8_strrev($string)\n{\n  return implode(array_reverse(str_to_array($string)));\n}\n\nprint_r(utf8_strrev($a)); \/\/ \ud83d\udc4b\ud83d\udc66\ud83c\udffb\nstrrev($string);\n","human_summarization":"The code takes a string as input and reverses its characters. It preserves Unicode combining characters when reversing the string. For Unicode support, it uses a multibyte function such as preg_split() or mb_str_split() for PHP 7.4+ and 8+. It ensures the correct reversal of strings with combining characters by reversing the graphemes instead of code points. It implements this functionality using grapheme_strlen and grapheme_substr functions. The code also includes a method to specify characters by code point using HTML entities escape sequence and converting it to a Unicode encoding like UTF-8.","id":2057}
    {"lang_cluster":"PHP","source_code":"\n\n<?php\nfunction dijkstra($graph_array, $source, $target) {\n    $vertices = array();\n    $neighbours = array();\n    foreach ($graph_array as $edge) {\n        array_push($vertices, $edge[0], $edge[1]);\n        $neighbours[$edge[0]][] = array(\"end\" => $edge[1], \"cost\" => $edge[2]);\n        $neighbours[$edge[1]][] = array(\"end\" => $edge[0], \"cost\" => $edge[2]);\n    }\n    $vertices = array_unique($vertices);\n\n    foreach ($vertices as $vertex) {\n        $dist[$vertex] = INF;\n        $previous[$vertex] = NULL;\n    }\n\n    $dist[$source] = 0;\n    $Q = $vertices;\n    while (count($Q) > 0) {\n    \n        \/\/ TODO - Find faster way to get minimum\n        $min = INF;\n        foreach ($Q as $vertex){\n            if ($dist[$vertex] < $min) {\n                $min = $dist[$vertex];\n                $u = $vertex;\n            }\n        }\n        \n        $Q = array_diff($Q, array($u));\n        if ($dist[$u] == INF or $u == $target) {\n            break;\n        }\n\n        if (isset($neighbours[$u])) {\n            foreach ($neighbours[$u] as $arr) {\n                $alt = $dist[$u] + $arr[\"cost\"];\n                if ($alt < $dist[$arr[\"end\"]]) {\n                    $dist[$arr[\"end\"]] = $alt;\n                    $previous[$arr[\"end\"]] = $u;\n                }\n            }\n        }\n    }\n    $path = array();\n    $u = $target;\n    while (isset($previous[$u])) {\n        array_unshift($path, $u);\n        $u = $previous[$u];\n    }\n    array_unshift($path, $u);\n    return $path;\n}\n\n$graph_array = array(\n                    array(\"a\", \"b\", 7),\n                    array(\"a\", \"c\", 9),\n                    array(\"a\", \"f\", 14),\n                    array(\"b\", \"c\", 10),\n                    array(\"b\", \"d\", 15),\n                    array(\"c\", \"d\", 11),\n                    array(\"c\", \"f\", 2),\n                    array(\"d\", \"e\", 6),\n                    array(\"e\", \"f\", 9)\n               );\n\n$path = dijkstra($graph_array, \"a\", \"e\");\n\necho \"path is: \".implode(\", \", $path).\"\\n\";\n\n\npath is: a, c, f, e\n","human_summarization":"The code implements Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a directed and weighted graph. The graph is represented by an adjacency matrix or list and a start node. The algorithm outputs a set of edges depicting the shortest path to each reachable node from the source. The code also includes a function to interpret the output and display the shortest path from the source node to specific nodes. The code can handle graphs where vertices are represented either by numbers or names.","id":2058}
    {"lang_cluster":"PHP","source_code":"\nwhile (true) {\n    $a = rand(0,19);\n    echo \"$a\\n\";\n    if ($a == 10)\n        break;\n    $b = rand(0,19);\n    echo \"$b\\n\";\n}\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":2059}
    {"lang_cluster":"PHP","source_code":"\necho 'M929 has a factor: ',  mersenneFactor(929), '<\/br>';\n\nfunction mersenneFactor($p) {\n    $limit = sqrt(pow(2, $p) - 1);\n    for ($k = 1; 2 * $p * $k - 1 < $limit; $k++) { \n        $q = 2 * $p * $k + 1;\n        if (isPrime($q) && ($q % 8 == 1 || $q % 8 == 7) && bcpowmod(\"2\", \"$p\", \"$q\") == \"1\") {\n            return $q;\n        }\n    }\n    return 0;\n}\n\nfunction isPrime($n) {\n    if ($n < 2 || $n % 2 == 0) return $n == 2;\n    for ($i = 3; $i * $i <= $n; $i += 2) {\n        if ($n % $i == 0) {\n            return false;\n        }\n    }\n    return true;\n}\n\n\n","human_summarization":"The code implements a method to find a factor of the Mersenne number 2^929-1 (M929). It uses efficient algorithms to determine if a number divides 2^P-1 by checking if 2^P mod (the number) = 1. The code also includes a custom implementation of the exponent-and-mod operation (modPow). It further refines the process by applying properties of Mersenne numbers, such as the form of any factor q of 2^P-1 and the condition that q must be prime. The code stops when 2kP+1 > sqrt(N). The method only works on Mersenne numbers where P is prime. The code requires bcmath.","id":2060}
    {"lang_cluster":"PHP","source_code":"\n<?php\n\/\/PHP5 only example due to changes in XML extensions between version 4 and 5 (Tested on PHP5.2.0)\n$doc = DOMDocument::loadXML('<inventory title=\"OmniCorp Store #45x10^3\">...<\/inventory>');\n\/\/Load from file instead with $doc = DOMDocument::load('filename');\n$xpath = new DOMXPath($doc);\n\/* \n    1st Task: Retrieve the first \"item\" element\n*\/\n$nodelist = $xpath->query('\/\/item');\n$result = $nodelist->item(0);\n\/* \n    2nd task: Perform an action on each \"price\" element (print it out)\n*\/\n$nodelist = $xpath->query('\/\/price');\nfor($i = 0; $i < $nodelist->length; $i++)\n{\n  \/\/print each price element in the DOMNodeList instance, $nodelist, as text\/xml followed by a newline\n  print $doc->saveXML($nodelist->item($i)).\"\\n\";\n}\n\/* \n    3rd Task: Get an array of all the \"name\" elements\n*\/\n$nodelist = $xpath->query('\/\/name');\n\/\/our array to hold all the name elements, though in practice you'd probably not need to do this and simply use the DOMNodeList\n$result = array(); \n\/\/a different way of iterating through the DOMNodeList\nforeach($nodelist as $node)\n{\n  $result[] = $node; \n}\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":2061}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfor($i=2008; $i<2121; $i++)\n{\n  $datetime = new DateTime(\"$i-12-25 00:00:00\");\n  if ( $datetime->format(\"w\") == 0 )\n  {\n     echo \"25 Dec $i is Sunday\\n\";\n  }\n}\n?>\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":2062}
    {"lang_cluster":"PHP","source_code":"\n$list = array(1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd');\n$unique_list = array_unique($list);\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":2063}
    {"lang_cluster":"PHP","source_code":"\nfunction quicksort($arr){\n\t$lte = $gt = array();\n\tif(count($arr) < 2){\n\t\treturn $arr;\n\t}\n\t$pivot_key = key($arr);\n\t$pivot = array_shift($arr);\n\tforeach($arr as $val){\n\t\tif($val <= $pivot){\n\t\t\t$lte[] = $val;\n\t\t} else {\n\t\t\t$gt[] = $val;\n\t\t}\n\t}\n\treturn array_merge(quicksort($lte),array($pivot_key=>$pivot),quicksort($gt));\n}\n\n$arr = array(1, 3, 5, 7, 9, 8, 6, 4, 2);\n$arr = quicksort($arr);\necho implode(',',$arr);\n1,2,3,4,5,6,7,8,9\nfunction quickSort(array $array) {\n    \/\/ base case\n    if (empty($array)) {\n        return $array;\n    }\n    $head = array_shift($array);\n    $tail = $array;\n    $lesser = array_filter($tail, function ($item) use ($head) {\n        return $item <= $head;\n    });\n    $bigger = array_filter($tail, function ($item) use ($head) {\n        return $item > $head;\n    });\n    return array_merge(quickSort($lesser), [$head], quickSort($bigger));\n}\n$testCase = [1, 4, 8, 2, 8, 0, 2, 8];\n$result = quickSort($testCase);\necho sprintf(\"[%s] ==> [%s]\\n\", implode(', ', $testCase), implode(', ', $result));\n[1, 4, 8, 2, 8, 0, 2, 8] ==> [0, 1, 2, 2, 4, 8, 8, 8]\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":2064}
    {"lang_cluster":"PHP","source_code":"\n\n<?php\necho date('Y-m-d', time()).\"\\n\";\necho date('l, F j, Y', time()).\"\\n\";\n?>\n\n","human_summarization":"display the current date in the formats \"2007-11-23\" and \"Friday, November 23, 2007\" according to the formatting rules provided at http:\/\/www.php.net\/date.","id":2065}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfunction get_subset($binary, $arr) {\n  \/\/ based on true\/false values in $binary array, include\/exclude\n  \/\/ values from $arr\n  $subset = array();\n  foreach (range(0, count($arr)-1) as $i) {\n    if ($binary[$i]) {\n      $subset[] = $arr[count($arr) - $i - 1];\n    } \n  }\n  return $subset;\n}\n\nfunction print_array($arr) {\n  if (count($arr) > 0) {\n    echo join(\" \", $arr);\n  } else {\n    echo \"(empty)\";\n  }\n  echo '<br>';\n}\n\nfunction print_power_sets($arr) {\n  echo \"POWER SET of [\" . join(\", \", $arr) . \"]<br>\";\n  foreach (power_set($arr) as $subset) {\n    print_array($subset);\n  }\n}\n  \nfunction power_set($arr) {  \n  $binary = array();\n  foreach (range(1, count($arr)) as $i) {\n    $binary[] = false;\n  }\n  $n = count($arr);\n  $powerset = array();\n  \n  while (count($binary) <= count($arr)) {\n    $powerset[] = get_subset($binary, $arr);\n    $i = 0;\n    while (true) {\n      if ($binary[$i]) {\n        $binary[$i] = false;\n        $i += 1;\n      } else {\n        $binary[$i] = true;\n        break;\n      }\n    }\n    $binary[$i] = true;\n  }\n  \n  return $powerset;\n}\n \nprint_power_sets(array());\nprint_power_sets(array('singleton'));\nprint_power_sets(array('dog', 'c', 'b', 'a'));\n?>\n\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":2066}
    {"lang_cluster":"PHP","source_code":"\nWorks with: PHP version 4+ tested in 5.2.12\n\/**\n * int2roman\n * Convert any positive value of a 32-bit signed integer to its modern roman \n * numeral representation. Numerals within parentheses are multiplied by \n * 1000. ie. M == 1 000, (M) == 1 000 000, ((M)) == 1 000 000 000\n * \n * @param number - an integer between 1 and 2147483647\n * @return roman numeral representation of number\n *\/\nfunction int2roman($number)\n{\n\tif (!is_int($number) || $number < 1) return false; \/\/ ignore negative numbers and zero\n\t\n\t$integers = array(900, 500,  400, 100,   90,  50,   40,  10,    9,   5,    4,   1);\n\t$numerals = array('CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I');\n\t$major = intval($number \/ 1000) * 1000;\n\t$minor = $number - $major;\n\t$numeral = $leastSig = '';\n\t\n\tfor ($i = 0; $i < sizeof($integers); $i++) {\n\t\twhile ($minor >= $integers[$i]) {\n\t\t\t$leastSig .= $numerals[$i];\n\t\t\t$minor  -= $integers[$i];\n\t\t}\n\t}\n\t\n\tif ($number >= 1000 && $number < 40000) {\n\t\tif ($major >= 10000) {\n\t\t\t$numeral .= '(';\n\t\t\twhile ($major >= 10000) {\n\t\t\t\t$numeral .= 'X';\n\t\t\t\t$major -= 10000;\n\t\t\t}\n\t\t\t$numeral .= ')';\n\t\t}\n\t\tif ($major == 9000) {\n\t\t\t$numeral .= 'M(X)';\n\t\t\treturn $numeral . $leastSig;\n\t\t}\n\t\tif ($major == 4000) {\n\t\t\t$numeral .= 'M(V)';\n\t\t\treturn $numeral . $leastSig;\n\t\t}\n\t\tif ($major >= 5000) {\n\t\t\t$numeral .= '(V)';\n\t\t\t$major -= 5000;\n\t\t}\n\t\twhile ($major >= 1000) {\n\t\t\t$numeral .= 'M';\n\t\t\t$major -= 1000;\n\t\t}\n\t}\n\t\n\tif ($number >= 40000) {\n\t\t$major = $major\/1000;\n\t\t$numeral .= '(' . int2roman($major) . ')';\n\t}\n\t\n\treturn $numeral . $leastSig;\n}\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":2067}
    {"lang_cluster":"PHP","source_code":"\n$NumberArray = array(0, 1, 2, 3, 4, 5, 6);\n$LetterArray = array(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\");\n$simpleForm = ['apple', 'orange'];\n$MultiArray = array(\n                array(0, 0, 0, 0, 0, 0),\n                array(1, 1, 1, 1, 1, 1),\n                array(2, 2, 2, 2, 2, 2),\n                array(3, 3, 3, 3, 3, 3)\n          );\n$arr = ['apple', 'orange'];\narray_push($arr, 'pear');\nprint implode(',', $arr); \/\/ Returns apple,orange,pear\n\necho $NumberArray[5]; \/\/ Returns 5\necho $LetterArray[5]; \/\/ Returns f\n\necho $MultiArray[1][5]; \/\/ 2\n\nprint_r($MultiArray);\n\nArray(\n    0 => array(\n            0 => 0\n            1 => 0\n            2 => 0\n            3 => 0\n            4 => 0\n            5 => 0\n         )\n    1 => array(\n            0 => 1\n            1 => 1\n            2 => 1\n            3 => 1\n            4 => 1\n            5 => 1\n         )\n    2 => array(\n            0 => 2\n            1 => 2\n            2 => 2\n            3 => 2\n            4 => 2\n            5 => 2\n         )\n    3 => array(\n            0 => 3\n            1 => 3\n            2 => 3\n            3 => 3\n            4 => 3\n            5 => 3\n         )\n)\n\n$StartIndexAtOne = array(1 => \"A\", \"B\", \"C\", \"D\");\n\n$CustomKeyArray = array(\"d\" => \"A\", \"c\" => \"B\", \"b\" =>\"C\", \"a\" =>\"D\");\n\necho $CustomKeyArray[\"b\"]; \/\/ Returns C\n\n$BlankArray = array();\n\n$BlankArray[] = \"Not Blank Anymore\";\n\n$AssignArray[\"CertainKey\"] = \"Value\";\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. This includes creating an array, assigning a value to it, and retrieving an element. It also shows how to work with both fixed-length and dynamic arrays, and how to push a value into an array. The code also demonstrates how to read the 5th value and the 2nd line, column 5 in an array, how to view the contents of an array during development, and how to start indexing from 1 instead of 0. It also shows how to assign any key to an array, read the 3rd value of the second array, create a blank array, set a value for the next key in the array, and assign a value to a certain key.","id":2068}
    {"lang_cluster":"PHP","source_code":"\nWorks with: PHP version 4\n<?php\n\nif (!$in = fopen('input.txt', 'r')) {\n    die('Could not open input file.');\n}\n\nif (!$out = fopen('output.txt', 'w')) {\n    die('Could not open output file.');\n}\n\nwhile (!feof($in)) {\n    $data = fread($in, 512);\n    fwrite($out, $data);\n}\n\nfclose($out);\nfclose($in);\n?>\nWorks with: PHP version 5\n<?php\nif ($contents = file_get_contents('input.txt')) {\n    if (!file_put_contents('output.txt', $contents)) {\n        echo('Could not write output file.');\n    }\n} else {\n    echo('Could not open input file.');\n}\n?>\n","human_summarization":"demonstrate reading the contents of \"input.txt\" file into a variable and then writing this variable's contents into a new file called \"output.txt\".","id":2069}
    {"lang_cluster":"PHP","source_code":"\n$str = \"alphaBETA\";\necho strtoupper($str), \"\\n\"; \/\/ ALPHABETA\necho strtolower($str), \"\\n\"; \/\/ alphabeta\n\necho ucfirst($str), \"\\n\"; \/\/ AlphaBETA\necho lcfirst(\"FOObar\"), \"\\n\"; \/\/ fOObar\necho ucwords(\"foO baR baZ\"), \"\\n\"; \/\/ FoO BaR BaZ\necho lcwords(\"FOo BAr BAz\"), \"\\n\"; \/\/ fOo bAr bAz\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":2070}
    {"lang_cluster":"PHP","source_code":"\n\n<?php\n$a = array();\n# add elements \"at the end\"\narray_push($a, 55, 10, 20);\nprint_r($a);\n# using an explicit key\n$a['one'] = 1;\n$a['two'] = 2;\nprint_r($a);\n?>\n\n","human_summarization":"The code creates a collection in a statically-typed language, adds a few values of a common data type to it, and reviews the programming examples to ensure they meet the task requirements. It also includes the use of associative arrays in PHP as a collection. The code may involve concepts of arrays, associative arrays, collections, compound data types, doubly-linked lists, linked lists, queues, sets, singly-linked lists, and stacks.","id":2071}
    {"lang_cluster":"PHP","source_code":"\nfor ($i = 1; $i <= 11; $i++) {\n    echo $i;\n    if ($i == 10)\n        break;\n    echo ', ';\n}\necho \"\\n\";\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":2072}
    {"lang_cluster":"PHP","source_code":"\n<?php\n\/**********************************************************************************\n* This program gets needle and haystack from the caller (chm.html) (see below)\n* and checks for occurrences of the needle in the haystack\n* 02.05.2013 Walter Pachl\n* Comments or Suggestions welcome\n**********************************************************************************\/\n$haystack = $_POST['haystack']; if ($haystack=='') {$haystack='no haystack given';}\n$needle   = $_POST['needle'];   if ($needle=='')   {$needle='no needle given';}\n\nfunction rexxpos($h,$n) {\n  $pos = strpos($h,$n);\n  if ($pos === false) { $pos=-1; }\n  else                { $pos=$pos+1; }\n  return ($pos);\n }\n\n$pos=rexxpos($haystack,$needle);\n$tx1 = \"\";\nif ($pos==-1){ $n=0; }  \/\/ not found\nelse         { $n=1; }  \/\/ found once (so far)\n\/\/ Special cases\nif ($pos==1){ $tx1=\"needle found to be the start of the haystack\"; }\nif ($pos==strlen($haystack)-strlen($needle)+1)\n            { $tx1=\"needle found at end of haystack\"; }\n\nif ($n>0) { \/\/ look for other occurrences\n  $pl=$pos; \/\/ list of positions\n  $p=$pos;  \/\/\n  $x=\"*************************************\";\n  $h=$haystack;\n  while ($p>0) {\n    $h=substr($x,0,$p).substr($h,$p);\n    $p=rexxpos($h,$needle);\n    if ( $p>0 ) { $n=$n+1; $pl=$pl.\", \".$p; }\n  }\n       if ($n==1) { $txt=\"needle found once in haystack, position: $pl.\"; }\n  else if ($n==2) { $txt=\"needle found twice in haystack, position(s): $pl.\"; }\n  else            { $txt=\"needle found $n times in haystack, position(s): $pl.\"; }\n}\nelse              { $txt=\"needle not found in haystack.\"; }\n?>\n<html>\n  <head>\n    <title>Character Matching<\/title>\n    <meta name=\"author\" content=\"Walter Pachl\">\n    <meta name=\"date\" content=\"02.05.2013\">\n    <style>\n      p { font: 120% courier; }\n    <\/style>\n  <\/head>\n  <body>\n    <p><strong>Haystack: '<?php echo \"$haystack\" ?>'<\/strong><\/p>\n    <p><strong>Needle:   '<?php echo \"$needle\" ?>'<\/strong><\/p>\n    <p><strong><?php echo \"$txt\" ?><\/strong><\/p>\n    <!-- special message: -->\n    <p  style=\"color: red\";><strong><?php echo \"$tx1\" ?><\/strong><\/p>\n  <\/body>\n<\/html>\n\n<?php\n<!DOCTYPE html>\n<!--\n\/************************************************************************\n* Here we prompt the user for a haystack and a needle\n* We then invoke program chmx.php\n* to check for occurrences of the needle in the haystack\n* 02.05.2013 Walter Pachl\n* Comments or Suggestions welcome\n************************************************************************\/\n-->\n<html>\n  <head>\n    <meta http-equiv=\"Content-Type\" content=\"text\/html; charset=UTF-8\" \/>\n    <title>Character matching<\/title>\n  <\/head>\n  <body>\n    <form id=\"test\" name=\"test\" method=\"post\" action=\"chmx.php\">\n    <h1>Character matching<\/h1>\n    <p>Given two strings, demonstrate the following 3 types of matchings:\n    <ol style=\"margin-top:2; margin-bottom:2;\">\n    <li>Determining if the first string starts with second string\n    <li>Determining if the first string contains the second string at any location\n    <li>Determining if the first string ends with the second string\n    <\/ol>\n    <p>Optional requirements:\n    <ol style=\"margin-top:2; margin-bottom:2;\">\n    <li>Print the location of the match(es) for part 2\n    <li>Handle multiple occurrences of a string for part 2.\n    <\/ol>\n    <p style=\"margin-top:5; margin-bottom:3;\">\n       <font face=\"Courier\"><strong>Haystack:<\/strong>\n       <strong><input type=\"text\" name=\"haystack\" size=\"80\"><\/strong><\/font><\/p>\n    <p style=\"margin-top:5; margin-bottom:3;\">\n       <font face=\"Courier\"><strong>Needle:  <\/strong>\n       <strong><input type=\"text\" name=\"needle\" size=\"80\"><\/strong><\/font><\/p>\n    <p>Press <input name=\"Submit\" type=\"submit\" class=\"erfolg\" value=\"CHECK\"\/>\n       to invoke chmx.php.<\/p>\n  <\/form>\n  <\/body>\n<\/html>\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":2073}
    {"lang_cluster":"PHP","source_code":"\n\n<?PHP\nECHO <<<REALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n       JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n        1  2  3  4  5                  1  2                  1  2      1  2  3  4  5  6            1  2  3  4                     1\n  6  7  8  9 10 11 12   3  4  5  6  7  8  9   3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11   2  3  4  5  6  7  8\n 13 14 15 16 17 18 19  10 11 12 13 14 15 16  10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18   9 10 11 12 13 14 15\n 20 21 22 23 24 25 26  17 18 19 20 21 22 23  17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25  16 17 18 19 20 21 22\n 27 28 29 30 31        24 25 26 27 28        24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31     23 24 25 26 27 28 29\n                                             31                                                                30 \n\n         JULY                 AUGUST               SEPTEMBER              OCTOBER              NOVEMBER              DECEMBER\n MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO  MO TU WE TH FR SA SO\n     1  2  3  4  5  6               1  2  3   1  2  3  4  5  6  7         1  2  3  4  5                  1  2   1  2  3  4  5  6  7\n  7  8  9 10 11 12 13   4  5  6  7  8  9 10   8  9 10 11 12 13 14   6  7  8  9 10 11 12   3  4  5  6  7  8  9   8  9 10 11 12 13 14\n 14 15 16 17 18 19 20  11 12 13 14 15 16 17  15 16 17 18 19 20 21  13 14 15 16 17 18 19  10 11 12 13 14 15 16  15 16 17 18 19 20 21\n 21 22 23 24 25 26 27  18 19 20 21 22 23 24  22 23 24 25 26 27 28  20 21 22 23 24 25 26  17 18 19 20 21 22 23  22 23 24 25 26 27 28\n 28 29 30 31           25 26 27 28 29 30 31  29 30                 27 28 29 30 31        24 25 26 27 28 29 30  29 30 31\nREALPROGRAMMERSTHINKINUPPERCASEANDCHEATBYUSINGPRINT\n                                                                                                             ; \/\/ MAGICAL SEMICOLON\n\n","human_summarization":"provide an algorithm similar to the Calendar task but written entirely in uppercase. The calendar is formatted to fit a 132 characters wide page, mimicking the formatting of 1969 era line printers. The code does not include Snoopy generation but instead outputs a placeholder.","id":2074}
    {"lang_cluster":"PHP","source_code":"\n<?php\n \nfunction gcd($a, $b)\n{\n    if ($a == 0)\n       return $b;\n    if ($b == 0)\n       return $a;\n    if($a == $b)\n        return $a;\n    if($a > $b)\n        return gcd($a-$b, $b);\n    return gcd($a, $b-$a);\n}\n\n$pytha = 0;\n$prim = 0;\n$max_p = 100;\n\nfor ($a = 1; $a <= $max_p \/ 3; $a++) {\n    $aa = $a**2;\n    for ($b = $a + 1; $b < $max_p\/2; $b++) {\n        $bb = $b**2;\n        for ($c = $b + 1; $c < $max_p\/2; $c++) {\n            $cc = $c**2;\n            if ($aa + $bb < $cc) break;\n            if ($a + $b + $c > $max_p) break;\n\n            if ($aa + $bb == $cc) {\n                $pytha++;\n                if (gcd($a, $b) == 1) $prim++;\n            }\n        }\n    }\n}\n\necho 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":2075}
    {"lang_cluster":"PHP","source_code":"\n<?php\nprint_r(array_count_values(str_split(file_get_contents($argv[1]))));\n?>\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":2076}
    {"lang_cluster":"PHP","source_code":"\n\n<?php\nheader(\"Content-type: image\/png\");\n\n$width = 512;\n$height = 512;\n$img = imagecreatetruecolor($width,$height);\n$bg = imagecolorallocate($img,255,255,255);\nimagefilledrectangle($img, 0, 0, $width, $width, $bg);\n\n$depth = 8;\nfunction drawTree($x1, $y1, $angle, $depth){\n    \n    global $img;\n    \n    if ($depth != 0){\n        $x2 = $x1 + (int)(cos(deg2rad($angle)) * $depth * 10.0);\n        $y2 = $y1 + (int)(sin(deg2rad($angle)) * $depth * 10.0);\n        \n        imageline($img, $x1, $y1, $x2, $y2, imagecolorallocate($img,0,0,0));\n        \n        drawTree($x2, $y2, $angle - 20, $depth - 1);\n        drawTree($x2, $y2, $angle + 20, $depth - 1);\n    }\n}\n\ndrawTree($width\/2, $height, -90, $depth);\n\nimagepng($img);\nimagedestroy($img);\n?>\n\n","human_summarization":"Generates and draws a fractal tree by first drawing the trunk, then splitting it at an angle to create branches, and repeating this process until a desired level of branching is achieved. The image is created using the GD module, with the code adapted from a JavaScript version.","id":2077}
    {"lang_cluster":"PHP","source_code":"\nfunction GetFactors($n){\n   $factors = array(1, $n);\n   for($i = 2; $i * $i <= $n; $i++){\n      if($n\u00a0% $i == 0){\n         $factors[] = $i;\n         if($i * $i\u00a0!= $n)\n            $factors[] = $n\/$i;\n      }\n   }\n   sort($factors);\n   return $factors;\n}\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":2078}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$j2justtype = array('L' => STR_PAD_RIGHT,\n                    'R' => STR_PAD_LEFT,\n                    'C' => STR_PAD_BOTH);\n \n\/**\n Justify columns of textual tabular input where the record separator is the newline\n and the field separator is a 'dollar' character.\n justification can be L, R, or C; (Left, Right, or Centered).\n \n Return the justified output as a string\n*\/\nfunction aligner($str, $justification = 'L') {\n  global $j2justtype;\n  assert(array_key_exists($justification, $j2justtype));\n  $justtype = $j2justtype[$justification];\n\n  $fieldsbyrow = array();\n  foreach (explode(\"\\n\", $str) as $line)\n    $fieldsbyrow[] = explode('$', $line);\n  $maxfields = max(array_map('count', $fieldsbyrow));\n\n  foreach (range(0, $maxfields - 1) as $col) {\n    $maxwidth = 0;\n    foreach ($fieldsbyrow as $fields)\n      $maxwidth = max($maxwidth, strlen(array_key_exists($col, $fields) ? $fields[$col] : 0));\n    foreach ($fieldsbyrow as &$fields)\n      $fields[$col] = str_pad(array_key_exists($col, $fields) ? $fields[$col] : \"\", $maxwidth, ' ', $justtype);\n    unset($fields); \/\/ see http:\/\/bugs.php.net\/29992\n  }\n  $result = '';\n  foreach ($fieldsbyrow as $fields)\n    $result .= implode(' ', $fields) . \"\\n\";\n  return $result;\n}\n\n$textinfile = 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$\\'dollar\\'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.';\n \nforeach (array('L', 'R', 'C') as $j)\n  echo aligner($textinfile, $j);\n\n?>\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":2079}
    {"lang_cluster":"PHP","source_code":"\n\n<?php\n$ldap = ldap_connect($hostname, $port);\n$success = ldap_bind($ldap, $username, $password);\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server using PHP LDAP.","id":2080}
    {"lang_cluster":"PHP","source_code":"\n\necho str_rot13('foo'), \"\\n\";\n\nsbb\n\n\n<?php\nfunction rot13($s) {\n    return strtr($s, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n                     'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm');\n}\n\necho rot13('foo'), \"\\n\";\n?>\n\nsbb\n\n","human_summarization":"Implement a rot-13 function or procedure that performs a rot-13 encoding on every line of input from each file listed on its command line or acts as a filter on its standard input. The function should replace every ASCII letter with the letter rotated 13 characters around the 26 letter alphabet, wrapping from z to a as necessary. It should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters in the input stream through without alteration.","id":2081}
    {"lang_cluster":"PHP","source_code":"\nfor ($i = 1; $i <= 5; $i++) {\n  for ($j = 1; $j <= $i; $j++) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n\nforeach (range(1, 5) as $i) {\n  foreach (range(1, $i) as $j) {\n    echo '*';\n  }\n  echo \"\\n\";\n}\n\nforeach (range(1, 5) as $i)\n  echo str_repeat('*', $i) , PHP_EOL;\n","human_summarization":"Code summarization: The code demonstrates the use of nested 'for' loops, where the number of iterations of the inner loop is controlled by the outer loop, to print a specific pattern of asterisks.","id":2082}
    {"lang_cluster":"PHP","source_code":"\n$array = array();\n$array = []; \/\/ Simpler form of array initialization\n$array['foo'] = 'bar';\n$array['bar'] = 'foo';\n\necho($array['foo']); \/\/ bar\necho($array['moo']); \/\/ Undefined index\n\n\/\/ Alternative (inline) way\n$array2 = array('fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green');\n\n\/\/ Another alternative (simpler) way\n$array2 = ['fruit' => 'apple',\n                'price' => 12.96,\n                'colour' => 'green'];\n\n\/\/ Check if key exists in the associative array\necho(isset($array['foo'])); \/\/ Faster, but returns false if the value of the element is set to null\necho(array_key_exists('foo', $array)); \/\/ Slower, but returns true if the value of the element is null\nforeach($array as $key => $value)\n{\n   echo \"Key: $key Value: $value\";\n}\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":2083}
    {"lang_cluster":"PHP","source_code":"\nWorks with: PHP version 5.3+\n<?php\nfunction bsd_rand($seed) {\n    return function() use (&$seed) {\n        return $seed = (1103515245 * $seed + 12345) % (1 << 31);\n    };\n}\n\nfunction msvcrt_rand($seed) {\n    return function() use (&$seed) {\n        return ($seed = (214013 * $seed + 2531011) % (1 << 31)) >> 16;\n    };\n}\n\n$lcg = bsd_rand(0);\necho \"BSD \";\nfor ($i = 0; $i < 10; $i++)\n    echo $lcg(), \" \";\necho \"\\n\";\n\n$lcg = msvcrt_rand(0);\necho \"Microsoft \";\nfor ($i = 0; $i < 10; $i++)\n    echo $lcg(), \" \";\necho \"\\n\";\n?>\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":2084}
    {"lang_cluster":"PHP","source_code":"\nNot object oriented version:<?php\nfunction halve($x)\n{\n  return floor($x\/2);\n}\n\nfunction double($x)\n{\n  return $x*2;\n}\n\nfunction iseven($x)\n{\n  return !($x & 0x1);\n}\n\nfunction ethiopicmult($plier, $plicand, $tutor)\n{\n  if ($tutor) echo \"ethiopic multiplication of $plier and $plicand\\n\";\n  $r = 0;\n  while($plier >= 1) {\n    if ( !iseven($plier) ) $r += $plicand;\n    if ($tutor)\n      echo \"$plier, $plicand \", (iseven($plier) ? \"struck\" : \"kept\"), \"\\n\";\n    $plier = halve($plier);\n    $plicand = double($plicand);\n  }\n  return $r;\n}\n\necho ethiopicmult(17, 34, true), \"\\n\";\n\n?>\n\n","human_summarization":"The code defines three functions to perform Ethiopian multiplication. The first function halves an integer, the second function doubles an integer, and the third function checks if an integer is even. These functions are used to create a fourth function that performs Ethiopian multiplication by repeatedly halving the first number, doubling the second number, discarding rows where the first number is even, and summing the remaining values in the second column.","id":2085}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfunction factorial($n) {\n  if ($n < 0) {\n    return 0;\n  }\n\n  $factorial = 1;\n  for ($i = $n; $i >= 1; $i--) {\n    $factorial = $factorial * $i;\n  }\n\n  return $factorial;\n}\n?>\n<?php\nfunction factorial($n) {\n  if ($n < 0) {\n    return 0;\n  }\n\n  if ($n == 0) {\n    return 1;\n  }\n\n  else {\n    return $n * factorial($n-1);\n  }\n}\n?>\n<?php\nfunction factorial($n) { return $n == 0\u00a0? 1\u00a0: array_product(range(1, $n)); }\n?>\n\ngmp_fact($n)\n","human_summarization":"The code is a function that calculates and returns the factorial of a given number. It can be implemented either iteratively or recursively. The function may optionally handle errors for negative input numbers. The code may require the GMP library for compilation.","id":2086}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$size = 4;\n\n$chosen = implode(array_rand(array_flip(range(1,9)), $size));\n\necho \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ($guesses = 1; ; $guesses++) {\n    while (true) {\n        echo \"\\nNext guess [$guesses]: \";\n        $guess = rtrim(fgets(STDIN));\n        if (!checkguess($guess))\n            echo \"$size digits, no repetition, no 0... retry\\n\";\n        else\n            break;\n    }\n    if ($guess == $chosen) {\n        echo \"You did it in $guesses attempts!\\n\";\n        break;\n    } else {\n        $bulls = 0;\n        $cows = 0;\n        foreach (range(0, $size-1) as $i) {\n            if ($guess[$i] == $chosen[$i])\n                $bulls++;\n            else if (strpos($chosen, $guess[$i]) !== FALSE)\n                $cows++;\n        }\n        echo \"$cows cows, $bulls bulls\\n\";\n    }\n}\n\nfunction checkguess($g)\n{\n  global $size;\n  return count(array_unique(str_split($g))) == $size &&\n    preg_match(\"\/^[1-9]{{$size}}$\/\", $g);\n}\n?>\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":2087}
    {"lang_cluster":"PHP","source_code":"\nfunction random() {\n    return mt_rand() \/ mt_getrandmax();\n}\n\n$pi \t= pi();          \/\/ Set PI\n\n$a = array();\nfor ($i = 0; $i < 1000; $i++) {\n    $a[$i] = 1.0 + ((sqrt(-2 * log(random())) * cos(2 * $pi * random())) * 0.5);\n    \n}\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":2088}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfunction dot_product($v1, $v2) {\n  if (count($v1) != count($v2))\n    throw new Exception('Arrays have different lengths');\n  return array_sum(array_map('bcmul', $v1, $v2));\n}\n\necho dot_product(array(1, 3, -5), array(4, -2, -1)), \"\\n\";\n?>\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":2089}
    {"lang_cluster":"PHP","source_code":"\n$fh = fopen($filename, 'r');\nif ($fh) {\n    while (!feof($fh)) {\n        $line = rtrim(fgets($fh)); # removes trailing newline\n        # process $line\n    }\n    fclose($fh);\n}\n\n\n$lines = file($filename);\n\n\n$contents = file_get_contents($filename);\n\n","human_summarization":"read data from a text stream either word-by-word or line-by-line until there's no more data, and can also retrieve an array of all lines in the file or the entire file as a string.","id":2090}
    {"lang_cluster":"PHP","source_code":"\nWorks with: PHP version 5\n<?php\n$dom = new DOMDocument();\/\/the constructor also takes the version and char-encoding as it's two respective parameters\n$dom->formatOutput = true;\/\/format the outputted xml\n$root = $dom->createElement('root');\n$element = $dom->createElement('element');\n$element->appendChild($dom->createTextNode('Some text here'));\n$root->appendChild($element);\n$dom->appendChild($root);\n$xmlstring = $dom->saveXML();\n\n","human_summarization":"Create a simple DOM and serialize it into the specified XML format.","id":2091}
    {"lang_cluster":"PHP","source_code":"\nSeconds since the Unix epoch:echo time(), \"\\n\";\n\nMicroseconds since the Unix epoch:echo microtime(), \"\\n\";\nFormatted time:echo date('D M j H:i:s Y'), \"\\n\";  \/\/ custom format; see format characters here:\n                                   \/\/ http:\/\/us3.php.net\/manual\/en\/function.date.php\necho date('c'), \"\\n\";  \/\/ ISO 8601 format\necho date('r'), \"\\n\";  \/\/ RFC 2822 format\necho date(DATE_RSS), \"\\n\";  \/\/ can also use one of the predefined formats here:\n                            \/\/ http:\/\/us3.php.net\/manual\/en\/class.datetime.php#datetime.constants.types\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":2092}
    {"lang_cluster":"PHP","source_code":"\nfunction char2value($c) {\n  assert(stripos('AEIOU', $c) === FALSE);\n  return intval($c, 36);\n}\n\n$sedolweight = array(1,3,1,7,3,9);\n\nfunction checksum($sedol) {\n    global $sedolweight;\n    $tmp = array_sum(array_map(create_function('$ch, $weight', 'return char2value($ch) * $weight;'),\n                               str_split($sedol), $sedolweight)\n                    );\n    return strval((10 - ($tmp % 10)) % 10);\n}\n\nforeach (array('710889',\n               'B0YBKJ',\n               '406566',\n               'B0YBLH',\n               '228276',\n               'B0YBKL',\n               '557910',\n               'B0YBKR',\n               '585284',\n               'B0YBKT') as $sedol)\n    echo $sedol, checksum($sedol), \"\\n\";\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":2093}
    {"lang_cluster":"PHP","source_code":"\nfunction nth($num) {\n  $os = \"th\";\n  if ($num % 100 <= 10 or $num % 100 > 20) {\n    switch ($num % 10) {\n      case 1:\n        $os = \"st\";\n        break;\n      case 2:\n        $os = \"nd\";\n        break;\n      case 3:\n        $os = \"rd\";\n        break;\n    }\n  } \n  return $num . $os;\n}\n\nforeach ([[0,25], [250,265], [1000,1025]] as $i) {\n  while ($i[0] <= $i[1]) {\n    echo nth($i[0]) . \" \";\n    $i[0]++;\n  }\n  echo \"\\n\";\n}\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":2094}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfunction stripchars($s, $chars) {\n    return str_replace(str_split($chars), \"\", $s);\n}\n\necho stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n?>\n\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":2095}
    {"lang_cluster":"PHP","source_code":"\n<?php\n\n$max = 20;\n$factor = array(3 => 'Fizz', 5 => 'Buzz', 7 => 'Jazz');\n\nfor ($i = 1 ; $i <= $max ; $i++) {\n    $matched = false;\n    foreach ($factor AS $number => $word) {\n        if ($i % $number == 0) {\n            echo $word;\n            $matched = true;\n        }\n    }\n    echo ($matched ? '' : $i), PHP_EOL;\n}\n\n?>\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":2096}
    {"lang_cluster":"PHP","source_code":"\n<?php\n\nsession_start();\n\nif(isset($_SESSION['number']))\n{\n   $number = $_SESSION['number'];\n}\nelse\n{\n   $_SESSION['number'] = rand(1,10);\n}\n\n\nif(isset($_POST[\"guess\"])){\n\tif($_POST[\"guess\"]){\n\t    $guess  = htmlspecialchars($_POST['guess']);\n\t \n\t\techo $guess . \"<br \/>\";\n\t    if ($guess != $number)\n\t\t{ \n\t        echo \"Your guess is not correct\";\n\t    }\n\t\telseif($guess == $number)\n\t\t{\n\t        echo \"You got the correct number!\";\n\t    }\n\t} \n}\n?>\n\n<!DOCTYPE html PUBLIC \"-\/\/W3C\/\/DTD XHTML 1.0 Transitional\/\/EN\" \"http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-transitional.dtd\">\n<html xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n\t<head>\n\t\t<meta http-equiv=\"Content-Type\" content=\"text\/html; charset=UTF-8\" \/>\n\t\t<title>Guess A Number<\/title>\n\t<\/head>\n\n\t<body>\n\t\t<form action=\"<?=$_SERVER['PHP_SELF'] ?>\" method=\"post\" name=\"guess-a-number\">\n\t\t    <label for=\"guess\">Guess number:<\/label><br\/ >\n\t\t    <input type=\"text\" name=\"guess\" \/>\n\t\t    <input name=\"number\" type=\"hidden\" value=\"<?= $number ?>\" \/>\n\t\t    <input name=\"submit\" type=\"submit\" \/>\n\t\t<\/form>\n\t<\/body>\n<\/html>\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":2097}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$lower = range('a', 'z');\nvar_dump($lower);\n?>\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":2098}
    {"lang_cluster":"PHP","source_code":"\n<?php\necho decbin(5);\necho decbin(50);\necho decbin(9000);\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":2099}
    {"lang_cluster":"PHP","source_code":"\n\n<?php\n\n$conf = file_get_contents('parse-conf-file.txt');\n\n\/\/ Add an \"=\" after entry name\n$conf = preg_replace('\/^([a-z]+)\/mi', '$1 =', $conf);\n\n\/\/ Replace multiple parameters separated by commas\u00a0:\n\/\/   name = value1, value2\n\/\/ by multiple lines\u00a0:\n\/\/   name[] = value1\n\/\/   name[] = value2\n$conf = preg_replace_callback(\n    '\/^([a-z]+)\\s*=((?=.*\\,.*).*)$\/mi',\n    function ($matches) {\n        $r = '';\n        foreach (explode(',', $matches[2]) AS $val) {\n            $r .= $matches[1] . '[] = ' . trim($val) . PHP_EOL;\n        }\n        return $r;\n    },\n    $conf\n);\n\n\/\/ Replace empty values by \"true\"\n$conf = preg_replace('\/^([a-z]+)\\s*=$\/mi', '$1 = true', $conf);\n\n\/\/ Parse configuration file\n$ini = parse_ini_string($conf);\n\necho 'Full name       = ', $ini['FULLNAME'], PHP_EOL;\necho 'Favourite fruit = ', $ini['FAVOURITEFRUIT'], PHP_EOL;\necho 'Need spelling   = ', (empty($ini['NEEDSPEELING']) ? 'false' : 'true'), PHP_EOL;\necho 'Seeds removed   = ', (empty($ini['SEEDSREMOVED']) ? 'false' : 'true'), PHP_EOL;\necho 'Other family    = ', print_r($ini['OTHERFAMILY'], true), PHP_EOL;\n\n\n","human_summarization":"The code reads a standard configuration file, ignores lines beginning with a hash or semicolon and blank lines. It sets variables based on the configuration parameters, treating the data as case sensitive. It also handles optional equals signs and multiple parameters separated by commas. The configuration entries are set to four variables: fullname, favouritefruit, needspeeling, and seedsremoved. An additional variable, otherfamily, is stored in an array. The configuration file format is slightly modified before it's passed to the parse_ini_string() function.","id":2100}
    {"lang_cluster":"PHP","source_code":"\nclass POI {\n    private $latitude;\n    private $longitude;\n\n    public function __construct($latitude, $longitude) {\n        $this->latitude = deg2rad($latitude);\n        $this->longitude = deg2rad($longitude);\n    }\n\n    public function getLatitude() {\n        return $this->latitude;\n    }\n\n    public function getLongitude() {\n        return $this->longitude;\n    }\n\n    public function getDistanceInMetersTo(POI $other) {\n        $radiusOfEarth = 6371; \/\/ Earth's radius in kilometers.\n\n        $diffLatitude = $other->getLatitude() - $this->latitude;\n        $diffLongitude = $other->getLongitude() - $this->longitude;\n\n        $a = sin($diffLatitude \/ 2) ** 2 +\n             cos($this->latitude) *\n             cos($other->getLatitude()) *\n             sin($diffLongitude \/ 2) ** 2;\n\n        $c = 2 * asin(sqrt($a));\n        $distance = $radiusOfEarth * $c;\n\n        return $distance;\n    }\n}\n\n\n$bna = new POI(36.12, -86.67); \/\/ Nashville International Airport\n$lax = new POI(33.94, -118.40); \/\/ Los Angeles International Airport\nprintf('%.2f km', $bna->getDistanceInMetersTo($lax));\n\n\n","human_summarization":"implement the Haversine formula to calculate the great-circle distance between Nashville International Airport and Los Angeles International Airport using both the authalic radius (6371.0 km) and the average great-circle radius (6372.8 km) of the Earth. The results may vary based on the radius used. The code also considers the recommendation by the International Union of Geodesy and Geophysics to use the mean Earth radius (6371 km) for real applications.","id":2101}
    {"lang_cluster":"PHP","source_code":"\nreadfile(\"http:\/\/www.rosettacode.org\");\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":2102}
    {"lang_cluster":"PHP","source_code":"$numbers = \"49927398716 49927398717 1234567812345678 1234567812345670\";\nforeach (split(' ', $numbers) as $n)\n    echo \"$n is \", luhnTest($n) ? 'valid' : 'not valid', '<\/br>';\n\nfunction luhnTest($num) {\n    $len = strlen($num);\n    for ($i = $len-1; $i >= 0; $i--) {\n        $ord = ord($num[$i]);\n        if (($len - 1) & $i) {\n            $sum += $ord;\n        } else {\n            $sum += $ord \/ 5 + (2 * $ord) % 10;\n        }\n    }       \n    return $sum % 10 == 0;\n}\n\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It first reverses the order of the digits in the number, then it sums every other odd digit to form a partial sum (s1). For the even digits, it multiplies each by two and sums the digits if the result is greater than nine to form another partial sum (s2). If the sum of s1 and s2 ends in zero, the number is a valid credit card number. The code tests this functionality with the numbers 49927398716, 49927398717, 1234567812345678, and 1234567812345670.","id":2103}
    {"lang_cluster":"PHP","source_code":"\n<?php \/\/Josephus.php\nfunction Jotapata($n=41,$k=3,$m=1){$m--;\n\t$prisoners=array_fill(0,$n,false);\/\/make a circle of n prisoners, store false ie: dead=false\n\t$deadpool=1;\/\/count to next execution\n\t$order=0;\/\/death order and *dead* flag, ie. deadpool\n\twhile((array_sum(array_count_values($prisoners))<$n)){\/\/while sum of count of unique values dead times < n (they start as all false)\n\t\tforeach($prisoners as $thisPrisoner=>$dead){\n\t\t\tif(!$dead){\/\/so yeah...if not dead...\n\t\t\t\tif($deadpool==$k){\/\/if their time is up in the deadpool...\n\t\t\t\t\t$order++;\n\t\t\t\t\t\/\/set the deadpool value or enumerate as survivor\n\t\t\t\t\t$prisoners[$thisPrisoner]=((($n-$m)>($order)?$order:(($n)==$order?'Call me *Titus Flavius* Josephus':'Joe\\'s friend '.(($order)-($n-$m-1)))));\n\t\t\t\t\t$deadpool=1;\/\/reset count to next execution\n\t\t\t\t}else{$duckpool++;}\n\t\t\t}\n\t\t}\n\t}\n\treturn $prisoners;\n}\necho '<pre>'.print_r(Jotapata(41,3,5),true).'<pre>';\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":2104}
    {"lang_cluster":"PHP","source_code":"\nstr_repeat(\"ha\", 5)\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":2105}
    {"lang_cluster":"PHP","source_code":"\nWorks with: PHP version 5.2.0\n$string = 'I am a string';\n# Test\nif (preg_match('\/string$\/', $string))\n{\n    echo \"Ends with 'string'\\n\";\n}\n# Replace\n$string = preg_replace('\/\\ba\\b\/', 'another', $string);\necho \"Found 'a' and replace it with 'another', resulting in this string: $string\\n\";\n\n\n","human_summarization":"\"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression.\"","id":2106}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$a = fgets(STDIN);\n$b = fgets(STDIN);\n\necho\n    \"sum:                 \", $a + $b, \"\\n\",\n    \"difference:          \", $a - $b, \"\\n\",\n    \"product:             \", $a * $b, \"\\n\",\n    \"truncating quotient: \", (int)($a \/ $b), \"\\n\",\n    \"flooring quotient:   \", floor($a \/ $b), \"\\n\",\n    \"remainder:           \", $a % $b, \"\\n\",\n    \"power:               \", $a ** $b, \"\\n\"; \/\/ PHP 5.6+ only\n?>\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":2107}
    {"lang_cluster":"PHP","source_code":"\n<?php\necho substr_count(\"the three truths\", \"th\"), PHP_EOL; \/\/ prints \"3\"\necho substr_count(\"ababababab\", \"abab\"), PHP_EOL; \/\/ prints \"2\"\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":2108}
    {"lang_cluster":"PHP","source_code":"function move($n,$from,$to,$via) {\n    if ($n === 1) {\n        print(\"Move disk from pole $from to pole $to\");\n    } else {\n        move($n-1,$from,$via,$to);\n        move(1,$from,$to,$via);\n        move($n-1,$via,$to,$from);\n    }\n}\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":2109}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$n=5;\n$k=3;\nfunction factorial($val){\n    for($f=2;$val-1>1;$f*=$val--);\n    return $f;\n}\n$binomial_coefficient=factorial($n)\/(factorial($k)*factorial($n-$k));\necho $binomial_coefficient;\n?>\n\n\nfunction binomial_coefficient($n, $k) {\n  if ($k == 0) return 1;\n  $result = 1;\n  foreach (range(0, $k - 1) as $i) {\n    $result *= ($n - $i) \/ ($i + 1);\n  }\n  return $result;\n}\n\n","human_summarization":"The code calculates any binomial coefficient, specifically able to output the binomial coefficient of 5 and 3, which is 10. It uses the formula for binomial coefficients and also considers combinations and permutations, both with and without replacement. The code also includes an alternative version not based on factorial.","id":2110}
    {"lang_cluster":"PHP","source_code":"\nfunction shellSort($arr)\n{\n\t$inc = round(count($arr)\/2);\n\twhile($inc > 0)\n\t{\n\t\tfor($i = $inc; $i < count($arr);$i++){\n\t\t\t$temp = $arr[$i];\n\t\t\t$j = $i;\n\t\t\twhile($j >= $inc && $arr[$j-$inc] > $temp)\n\t\t\t{\n\t\t\t\t$arr[$j] = $arr[$j - $inc];\n\t\t\t\t$j -= $inc;\n\t\t\t}\n\t\t\t$arr[$j] = $temp;\n\t\t}\n\t\t$inc = round($inc\/2.2);\n\t}\n\treturn $arr;\n}\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":2111}
    {"lang_cluster":"PHP","source_code":"\n\nclass BitmapGrayscale extends Bitmap {\n  public function toGrayscale(){\n    for ($i = 0; $i < $this->h; $i++){\n      for ($j = 0; $j < $this->w; $j++){\n        $l = ($this->data[$j][$i][0] * 0.2126)\n           + ($this->data[$j][$i][1] * 0.7152)\n           + ($this->data[$j][$i][2] * 0.0722);\n        $l = round($l);\n        $this->data[$j][$i] = array($l,$l,$l);\n      }\n    }\n  }\n}\n\n$b = new BitmapGrayscale(16,16);\n$b->fill(0,0,null,null, array(255,255,0));\n$b->setPixel(0, 15, array(255,0,0));\n$b->setPixel(0, 14, array(0,255,0));\n$b->setPixel(0, 13, array(0,0,255));\n$b->toGrayscale();\n$b->writeP6('p6-grayscale.ppm');\n\n","human_summarization":"extend the data storage type to support grayscale images, convert a color image to a grayscale image and vice versa using the CIE recommended formula for luminance. The code ensures no rounding errors that could cause run-time issues or distort results when storing luminance as an unsigned integer. It also uses the Bitmap class for writing a PPM file.","id":2112}
    {"lang_cluster":"PHP","source_code":"\n$val = 0;\ndo {\n   $val++;\n   print \"$val\\n\";\n} while ($val\u00a0% 6\u00a0!= 0);\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":2113}
    {"lang_cluster":"PHP","source_code":"\n\n<?php\nforeach (array('m\u00f8\u00f8se', '\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22', 'J\u0332o\u0332s\u0332\u00e9\u0332') as $s1) { \n   printf('String \"%s\" measured with strlen: %d mb_strlen: %s grapheme_strlen %s%s', \n                  $s1, strlen($s1),mb_strlen($s1), grapheme_strlen($s1), PHP_EOL);\n}\n\nString \"m\u00f8\u00f8se\" measured with strlen: 7 mb_strlen: 7 grapheme_strlen 5\nString \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\" measured with strlen: 28 mb_strlen: 28 grapheme_strlen 7\nString \"J\u0332o\u0332s\u0332\u00e9\u0332\" measured with strlen: 13 mb_strlen: 13 grapheme_strlen 4\n\n","human_summarization":"The code calculates the character and byte length of a string, considering UTF-8 encoding. It correctly handles non-BMP code points and provides actual character counts in code points, not in code unit counts. It also has the capability to provide the string length in graphemes if the programming language supports it.","id":2114}
    {"lang_cluster":"PHP","source_code":"\n<?php\necho substr(\"knight\", 1), \"\\n\";       \/\/ strip first character\necho substr(\"socks\", 0, -1), \"\\n\";    \/\/ strip last character\necho substr(\"brooms\", 1, -1), \"\\n\";   \/\/ strip both first and last characters\n?>\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":2115}
    {"lang_cluster":"PHP","source_code":"\tclass SudokuSolver {\n\t\tprotected $grid = [];\n\t\tprotected $emptySymbol;\n\t\tpublic static function parseString($str, $emptySymbol = '0')\n\t\t{\n\t\t\t$grid = str_split($str);\n\t\t\tforeach($grid as &$v)\n\t\t\t{\n\t\t\t\tif($v == $emptySymbol)\n\t\t\t\t{\n\t\t\t\t\t$v = 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t$v = (int)$v;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn $grid;\n\t\t}\n\t\t\n\t\tpublic function __construct($str, $emptySymbol = '0') {\n\t\t\tif(strlen($str) !== 81)\n\t\t\t{\n\t\t\t\tthrow new \\Exception('Error sudoku');\n\t\t\t}\n\t\t\t$this->grid = static::parseString($str, $emptySymbol);\n\t\t\t$this->emptySymbol = $emptySymbol;\n\t\t}\n\t\t\n\t\tpublic function solve()\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\t$this->placeNumber(0);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tcatch(\\Exception $e)\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t\n\t\tprotected function placeNumber($pos)\n\t\t{\n\t\t\tif($pos == 81)\n\t\t\t{\n\t\t\t\tthrow new \\Exception('Finish');\n\t\t\t}\n\t\t\tif($this->grid[$pos] > 0)\n\t\t\t{\n\t\t\t\t$this->placeNumber($pos+1);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tfor($n = 1; $n <= 9; $n++)\n\t\t\t{\n\t\t\t\tif($this->checkValidity($n, $pos%9, floor($pos\/9)))\n\t\t\t\t{\n\t\t\t\t\t$this->grid[$pos] = $n;\n\t\t\t\t\t$this->placeNumber($pos+1);\n\t\t\t\t\t$this->grid[$pos] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tprotected function checkValidity($val, $x, $y)\n\t\t{\n\t\t\tfor($i = 0; $i < 9; $i++)\n\t\t\t{\n\t\t\t\tif(($this->grid[$y*9+$i] == $val) || ($this->grid[$i*9+$x] == $val))\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\t$startX = (int) ((int)($x\/3)*3);\n\t\t\t$startY = (int) ((int)($y\/3)*3);\n\n\t\t\tfor($i = $startY; $i<$startY+3;$i++)\n\t\t\t{\n\t\t\t\tfor($j = $startX; $j<$startX+3;$j++)\n\t\t\t\t{\n\t\t\t\t\tif($this->grid[$i*9+$j] == $val)\n\t\t\t\t\t{\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tpublic function display() {\n\t\t\t$str = '';\n\t\t\tfor($i = 0; $i<9; $i++)\n\t\t\t{\n\t\t\t\tfor($j = 0; $j<9;$j++)\n\t\t\t\t{\n\t\t\t\t\t$str .= $this->grid[$i*9+$j];\n\t\t\t\t\t$str .= \" \";\n\t\t\t\t\tif($j == 2 || $j == 5)\n\t\t\t\t\t{\n\t\t\t\t\t\t$str .= \"| \";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t$str .= PHP_EOL;\n\t\t\t\tif($i == 2 || $i == 5)\n\t\t\t\t{\n\t\t\t\t\t$str .=  \"------+-------+------\".PHP_EOL;\n\t\t\t\t}\n\t\t\t}\n\t\t\techo $str;\n\t\t}\n\t\t\n\t\tpublic function __toString() {\n\t\t\tforeach ($this->grid as &$item)\n\t\t\t{\n\t\t\t\tif($item == 0)\n\t\t\t\t{\n\t\t\t\t\t$item = $this->emptySymbol;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn implode('', $this->grid);\n\t\t}\n\t}\n\t$solver = new SudokuSolver('009170000020600001800200000200006053000051009005040080040000700006000320700003900');\n\t$solver->solve();\n\t$solver->display();\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":2116}
    {"lang_cluster":"PHP","source_code":"\n\/\/The Fisher-Yates original Method\nfunction yates_shuffle($arr){\n\t$shuffled = Array();\n\twhile($arr){\n\t\t$rnd = array_rand($arr);\n\t\t$shuffled[] = $arr[$rnd];\n\t\tarray_splice($arr, $rnd, 1);\n\t}\n\treturn $shuffled;\n}\n\n\/\/The modern Durstenfeld-Knuth algorithm\nfunction knuth_shuffle(&$arr){\n\tfor($i=count($arr)-1;$i>0;$i--){\n\t\t$rnd = mt_rand(0,$i);\n\t\tlist($arr[$i], $arr[$rnd]) = array($arr[$rnd], $arr[$i]);\n\t}\n}\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":2117}
    {"lang_cluster":"PHP","source_code":"\n\n<?php\nfunction last_friday_of_month($year, $month) {\n  $day = 0;\n  while(True) {\n    $last_day = mktime(0, 0, 0, $month+1, $day, $year); \n    if (date(\"w\", $last_day) == 5) {\n      return date(\"Y-m-d\", $last_day);\n    }\n    $day -= 1;\n  }\n}\n \nfunction print_last_fridays_of_month($year) {\n  foreach(range(1, 12) as $month) {\n    echo last_friday_of_month($year, $month), \"<br>\";\n  }\n}\n \ndate_default_timezone_set(\"GMT\");\n$year = 2012;\nprint_last_fridays_of_month($year);\n?>\n\n\n","human_summarization":"The code takes a year as input and returns the dates of the last Fridays of each month for that given year. The input year can be provided through any simple method like command line or standard input. The code does not include a command-line component as it is typically used for web applications in PHP.","id":2118}
    {"lang_cluster":"PHP","source_code":"\necho \"Goodbye, World\u00a0!\";\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":2119}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfunction caesarEncode( $message, $key ){\n    $plaintext = strtolower( $message );\n    $ciphertext = \"\";\n    $ascii_a = ord( 'a' );\n    $ascii_z = ord( 'z' );\n    while( strlen( $plaintext ) ){\n        $char = ord( $plaintext );\n        if( $char >= $ascii_a && $char <= $ascii_z ){\n            $char = ( ( $key + $char - $ascii_a ) % 26 ) + $ascii_a;\n        }\n        $plaintext = substr( $plaintext, 1 );\n        $ciphertext .= chr( $char );\n    }\n    return $ciphertext;\n}\n\necho caesarEncode( \"The quick brown fox Jumped over the lazy Dog\", 12 ), \"\\n\";\n?>\n\n\n","human_summarization":"implement a Caesar cipher for both encoding and decoding. The cipher rotates the alphabet letters based on a key ranging from 1 to 25. It replaces each letter with the next 1st to 25th letter in the alphabet, wrapping Z to A. The key 2 encrypts \"HI\" to \"JK\", while key 20 encrypts \"HI\" to \"BC\". The code also highlights that this cipher provides minimal security as the encoded message can be easily decrypted. It also mentions that the Caesar cipher is identical to the Vigen\u00e8re cipher with a key length of 1 and to the Rot-13 with a key of 13. The PHP's strtr() function is used in the implementation.","id":2120}
    {"lang_cluster":"PHP","source_code":"echo lcm(12, 18) == 36;\n\nfunction lcm($m, $n) {\n    if ($m == 0 || $n == 0) return 0;\n    $r = ($m * $n) \/ gcd($m, $n);\n    return abs($r);\n}\n\nfunction gcd($a, $b) {\n    while ($b != 0) {\n        $t = $b;\n        $b = $a % $b;\n        $a = $t;\n    }\n    return $a;\n}\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":2121}
    {"lang_cluster":"PHP","source_code":"\nfunction IsCusip(string $s) {\n    if (strlen($s) != 9) return false;\n    $sum = 0;\n    for ($i = 0; $i <= 7; $i++) {\n        $c = $s[$i];\n        if (ctype_digit($c)) {\n            \/\/ if character is numeric, get character's numeric value\n            $v = intval($c);\n        } elseif (ctype_alpha($c)) {\n            \/\/ if character is alphabetic, get character's ordinal position in alphabet\n            $position = ord(strtoupper($c)) - ord('A') + 1;\n            $v = $position + 9;\n        } elseif ($c == \"*\") {\n            $v = 36;\n        } elseif ($c == \"@\") {\n            $v = 37;\n        } elseif ($c == \"#\") {\n            $v = 38;\n        } else {\n            return false;\n        }\n        \/\/ is this character position even?\n        if ($i % 2 == 1) {\n            $v *= 2;\n        }\n        \/\/ calculate the checksum digit\n        $sum += floor($v \/ 10 ) + ( $v % 10 );\n    }\n    return ord($s[8]) - 48 == (10 - ($sum % 10)) % 10;\n}\n\n$cusips = array(\"037833100\",\n                \"17275R102\",\n                \"38259P508\",\n                \"594918104\",\n                \"68389X106\",\n                \"68389X105\");\n\nforeach ($cusips as $cusip) echo $cusip . \" -> \" . (IsCusip($cusip) ? \"valid\" : \"invalid\") . \"\\n\";\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":2122}
    {"lang_cluster":"PHP","source_code":"\nforeach ($collect as $i) {\n   echo \"$i\\n\";\n}\n\nforeach ($collect as $key => $i) {\n   echo \"\\$collect[$key] = $i\\n\";\n}\n\n","human_summarization":"Iterates over each element in a collection in sequence using a \"for each\" loop or an alternative loop if \"for each\" is not available. It can also iterate over all visible fields of an object.","id":2123}
    {"lang_cluster":"PHP","source_code":"\nWorks with: PHP version 5.x\n<?php\n$str = 'Hello,How,Are,You,Today';\necho implode('.', explode(',', $str));\n?>\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":2124}
    {"lang_cluster":"PHP","source_code":"\nfunction gcdIter($n, $m) {\n    while(true) {\n        if($n == $m) {\n            return $m;\n        }\n        if($n > $m) {\n            $n -= $m;\n        } else {\n            $m -= $n;\n        }\n    }\n}\nfunction gcdRec($n, $m)\n{\n    if($m > 0)\n        return gcdRec($m, $n\u00a0% $m);\n    else\n        return abs($n);\n}\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":2125}
    {"lang_cluster":"PHP","source_code":"\n$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);\nsocket_bind($socket, '127.0.0.1', 12321);\nsocket_listen($socket);\n\n$client_count = 0;\nwhile (true){\n  if (($client = socket_accept($socket)) === false) continue;\n  $client_count++;\n\n  $client_name = 'Unknown';\n  socket_getpeername($client, $client_name);\n  echo \"Client {$client_count} ({$client_name}) connected\\n\";\n  $pid = pcntl_fork();\n  if($pid == -1) die('Could not fork');\n  if($pid){\n    pcntl_waitpid(-1, $status, WNOHANG);\n    continue;\n  }\n\n  \/\/In a child process\n  while(true){\n    if($input = socket_read($client, 1024)){\n      socket_write($client, $input);\n    } else {\n      socket_shutdown($client);\n      socket_close($client);\n      echo \"Client {$client_count} ({$client_name}) disconnected\\n\";\n      exit();\n    }\n  }\n}\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":2126}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$string = '123';\nif(is_numeric(trim($string))) {\n}\n?>\n\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":2127}
    {"lang_cluster":"PHP","source_code":"\necho file_get_contents('https:\/\/sourceforge.net');\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":2128}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfunction clip ($subjectPolygon, $clipPolygon) {\n\n    function inside ($p, $cp1, $cp2) {\n        return ($cp2[0]-$cp1[0])*($p[1]-$cp1[1]) > ($cp2[1]-$cp1[1])*($p[0]-$cp1[0]);\n    }\n    \n    function intersection ($cp1, $cp2, $e, $s) {\n        $dc = [ $cp1[0] - $cp2[0], $cp1[1] - $cp2[1] ];\n        $dp = [ $s[0] - $e[0], $s[1] - $e[1] ];\n        $n1 = $cp1[0] * $cp2[1] - $cp1[1] * $cp2[0];\n        $n2 = $s[0] * $e[1] - $s[1] * $e[0];\n        $n3 = 1.0 \/ ($dc[0] * $dp[1] - $dc[1] * $dp[0]);\n\n        return [($n1*$dp[0] - $n2*$dc[0]) * $n3, ($n1*$dp[1] - $n2*$dc[1]) * $n3];\n    }\n    \n    $outputList = $subjectPolygon;\n    $cp1 = end($clipPolygon);\n    foreach ($clipPolygon as $cp2) {\n        $inputList = $outputList;\n        $outputList = [];\n        $s = end($inputList);\n        foreach ($inputList as $e) {\n            if (inside($e, $cp1, $cp2)) {\n                if (!inside($s, $cp1, $cp2)) {\n                    $outputList[] = intersection($cp1, $cp2, $e, $s);\n                }\n                $outputList[] = $e;\n            }\n            else if (inside($s, $cp1, $cp2)) {\n                $outputList[] = intersection($cp1, $cp2, $e, $s);\n            }\n            $s = $e;\n        }\n        $cp1 = $cp2;\n    }\n    return $outputList;\n}\n\n$subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]];\n$clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n$clippedPolygon = clip($subjectPolygon, $clipPolygon);\n\necho json_encode($clippedPolygon);\necho \"\\n\";\n?>\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":2129}
    {"lang_cluster":"PHP","source_code":"\n$radians = M_PI \/ 4;\n$degrees = 45 * M_PI \/ 180;\necho sin($radians) . \" \" . sin($degrees);\necho cos($radians) . \" \" . cos($degrees);\necho tan($radians) . \" \" . tan($degrees);\necho asin(sin($radians)) . \" \" . asin(sin($radians)) * 180 \/ M_PI;\necho acos(cos($radians)) . \" \" . acos(cos($radians)) * 180 \/ M_PI;\necho atan(tan($radians)) . \" \" . atan(tan($radians)) * 180 \/ M_PI;\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":2130}
    {"lang_cluster":"PHP","source_code":"<?php\ndeclare(ticks = 1);\n\n$start = microtime(true);\n\nfunction mySigHandler() {\n  global $start;\n  $elapsed = microtime(true) - $start;\n  echo \"Ran for $elapsed seconds.\\n\";\n  exit();\n}\n\npcntl_signal(SIGINT, 'mySigHandler');\n\nfor ($n = 0; ; usleep(500000)) \/\/ 0.5 seconds\n   echo ++$n, \"\\n\";\n?>\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.","id":2131}
    {"lang_cluster":"PHP","source_code":"\n$s = \"12345\";\n$s++;\n","human_summarization":"\"Increments a given numerical string.\"","id":2132}
    {"lang_cluster":"PHP","source_code":"\n<?php\n\n\/*\n This works with dirs and files in any number of combinations.\n*\/\n\nfunction _commonPath($dirList)\n{\n\t$arr = array();\n\tforeach($dirList as $i => $path)\n\t{\n\t\t$dirList[$i]\t= explode('\/', $path);\n\t\tunset($dirList[$i][0]);\n\t\t\n\t\t$arr[$i] = count($dirList[$i]);\n\t}\n\t\n\t$min = min($arr);\n\t\n\tfor($i = 0; $i < count($dirList); $i++)\n\t{\n\t\twhile(count($dirList[$i]) > $min)\n\t\t{\n\t\t\tarray_pop($dirList[$i]);\n\t\t}\n\t\t\n\t\t$dirList[$i] = '\/' . implode('\/' , $dirList[$i]);\n\t}\n\t\n\t$dirList = array_unique($dirList);\n\twhile(count($dirList) !== 1)\n\t{\n\t\t$dirList = array_map('dirname', $dirList);\n\t\t$dirList = array_unique($dirList);\n\t}\n\treset($dirList);\n\t\n\treturn current($dirList);\n}\n\n \/* TEST *\/\n\n$dirs = array(\n '\/home\/user1\/tmp\/coverage\/test',\n '\/home\/user1\/tmp\/covert\/operator',\n '\/home\/user1\/tmp\/coven\/members',\n);\n\n\nif('\/home\/user1\/tmp' !== common_path($dirs))\n{\n  echo 'test fail';\n} else {\n  echo 'test success';\n}\n\n?>\n\n\n<?php\n\n\/* A more compact string-only version, which I assume would be much faster *\/\n\/* If you want the trailing \/, return $common; *\/\n\nfunction getCommonPath($paths) {\n\t$lastOffset = 1;\n\t$common = '\/';\n\twhile (($index = strpos($paths[0], '\/', $lastOffset)) !== FALSE) {\n\t\t$dirLen = $index - $lastOffset + 1;\t\/\/ include \/\n\t\t$dir = substr($paths[0], $lastOffset, $dirLen);\n\t\tforeach ($paths as $path) {\n\t\t\tif (substr($path, $lastOffset, $dirLen) != $dir)\n\t\t\t\treturn $common;\n\t\t}\n\t\t$common .= $dir;\n\t\t$lastOffset = $index + 1;\n\t}\n\treturn substr($common, 0, -1);\n}\n\n?>\n\n","human_summarization":"\"Output: The code creates a routine that finds the common directory path from a set of given directory paths using a specified directory separator character. It has been tested with '\/' as the directory separator and three specific strings as input paths. The routine returns the valid common directory, not the longest common string.\"","id":2133}
    {"lang_cluster":"PHP","source_code":"\nfunction sattoloCycle($items) {\n   for ($i = 0; $i < count($items); $i++) {\n        $j = floor((mt_rand() \/ mt_getrandmax()) * $i);\n        $tmp = $items[$i];\n        $items[$i] = $items[$j];\n        $items[$j] = $tmp;\n    } \n    return $items;\n}\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":2134}
    {"lang_cluster":"PHP","source_code":"\nWorks with: PHP version 5.0.0+\n<?php\n\/\/load the wsdl file\n$client = new SoapClient(\"http:\/\/example.com\/soap\/definition.wsdl\");\n\/\/functions are now available to be called\n$result = $client->soapFunc(\"hello\");\n$result = $client->anotherSoapFunc(34234);\n\n\/\/SOAP Information\n$client = new SoapClient(\"http:\/\/example.com\/soap\/definition.wsdl\");\n\/\/list of SOAP types\nprint_r($client->__getTypes());\n\/\/list if SOAP Functions\nprint_r($client->__getFunctions());\n?>\n\n","human_summarization":"The code establishes a SOAP client to access and call the functions soapFunc() and anotherSoapFunc() from the WSDL located at http:\/\/example.com\/soap\/wsdl. Note, the task and corresponding code may require further clarification.","id":2135}
    {"lang_cluster":"PHP","source_code":"\n\nfunction median($arr)\n{\n    sort($arr);\n    $count = count($arr); \/\/count the number of values in array\n    $middleval = floor(($count-1)\/2); \/\/ find the middle value, or the lowest middle value\n    if ($count % 2) { \/\/ odd number, middle is the median\n        $median = $arr[$middleval];\n    } else { \/\/ even number, calculate avg of 2 medians\n        $low = $arr[$middleval];\n        $high = $arr[$middleval+1];\n        $median = (($low+$high)\/2);\n    }\n    return $median;\n}\n\necho median(array(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)) . \"\\n\";  \/\/ 4.4\necho median(array(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)) . \"\\n\";       \/\/ 4.25\n\n","human_summarization":"\"Output: The code calculates the median value of a vector of floating-point numbers. It handles cases with an even number of elements by returning the average of the two middle values. The code uses the selection algorithm for efficient computation. It also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation. The median calculation uses a sorting method.\"","id":2136}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfor ($i = 1; $i <= 100; $i++)\n{\n    if (!($i\u00a0% 15))\n        echo \"FizzBuzz\\n\";\n    else if (!($i\u00a0% 3))\n        echo \"Fizz\\n\";\n    else if (!($i\u00a0% 5))\n        echo \"Buzz\\n\";\n    else\n        echo \"$i\\n\";\n}\n?>\n\n<?php\nfor ( $i = 1; $i <= 100; ++$i )\n{\n     $str = \"\";\n\n     if (!($i\u00a0% 3 ) )\n          $str .= \"Fizz\";\n\n     if (!($i\u00a0% 5 ) )\n          $str .= \"Buzz\";\n\n     if ( empty( $str ) )\n          $str = $i;\n\n     echo $str . \"\\n\";\n}\n?>\n<?php\nfor (\n    $i = 0;\n    $i++ < 100;\n    $o = ($i\u00a0% 3\u00a0? ''\u00a0: 'Fizz') . ($i\u00a0% 5\u00a0? ''\u00a0: 'Buzz')\n)\n    echo $o\u00a0?\u00a0: $i, PHP_EOL;\n?>\n<?php\nfor($i = 1; $i <= 100 and print(($i\u00a0% 15\u00a0? $i\u00a0% 5\u00a0? $i\u00a0% 3\u00a0? $i\u00a0: 'Fizz'\u00a0: 'Buzz'\u00a0: 'FizzBuzz') . \"\\n\"); ++$i);\n?>\nCompact for($i=0;$i++<100;)echo($i%3?'':'Fizz').($i%5?'':'Buzz')?:$i,\"\\n\";\nArray for($i = 0; $i++ < 100;) echo [$i, 'Fizz', 'Buzz', 'FizzBuzz'][!($i\u00a0% 3) + 2 *\u00a0!($i\u00a0% 5)], \"\\n\";\n","human_summarization":"The code prints integers from 1 to 100. For multiples of three, it prints 'Fizz' and for multiples of five, it prints 'Buzz'. For numbers that are multiples of both three and five, it prints 'FizzBuzz'. It uses PHP's concatenation operator to build the output string, appending 'Buzz' to 'Fizz' when necessary. It avoids checking if a number is divisible by both 3 and 5 by resetting the string to an empty string when necessary and includes a separate check to see if the string is empty, indicating the number was not divisible by 3 or 5.","id":2137}
    {"lang_cluster":"PHP","source_code":"\nLibrary: GD Graphics Library\nWorks with: PHP version 5.3.5\nSample output\n$min_x=-2;\n$max_x=1;\n$min_y=-1;\n$max_y=1;\n\n$dim_x=400;\n$dim_y=300;\n\n$im = @imagecreate($dim_x, $dim_y)\n  or die(\"Cannot Initialize new GD image stream\");\nheader(\"Content-Type: image\/png\");\n$black_color = imagecolorallocate($im, 0, 0, 0);\n$white_color = imagecolorallocate($im, 255, 255, 255);\n\nfor($y=0;$y<=$dim_y;$y++) {\n  for($x=0;$x<=$dim_x;$x++) {\n    $c1=$min_x+($max_x-$min_x)\/$dim_x*$x;\n    $c2=$min_y+($max_y-$min_y)\/$dim_y*$y;\n\n    $z1=0;\n    $z2=0;\n\n    for($i=0;$i<100;$i++) {\n      $new1=$z1*$z1-$z2*$z2+$c1;\n      $new2=2*$z1*$z2+$c2;\n      $z1=$new1;\n      $z2=$new2;\n      if($z1*$z1+$z2*$z2>=4) {\n        break;\n      }\n    }\n    if($i<100) {\n      imagesetpixel ($im, $x, $y, $white_color);\n    }\n  }\n}\n\nimagepng($im);\nimagedestroy($im);\n","human_summarization":"generate and draw the Mandelbrot set using various available algorithms and functions.","id":2138}
    {"lang_cluster":"PHP","source_code":"\n$array = array(1,2,3,4,5,6,7,8,9);\necho array_sum($array);\necho array_product($array);\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":2139}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfunction isLeapYear($year) {\n    if ($year\u00a0% 100 == 0) {\n        return ($year\u00a0% 400 == 0);\n    }\n    return ($year\u00a0% 4 == 0);\n}\n\n<?php\nfunction isLeapYear($year) {\n    return (date('L', mktime(0, 0, 0, 2, 1, $year)) === '1')\n}\n","human_summarization":"\"Determines if a given year is a leap year in the Gregorian calendar using date('L').\"","id":2140}
    {"lang_cluster":"PHP","source_code":"\n<?php\n\n$valid = 0;\nfor ($police = 2 ; $police <= 6 ; $police += 2) {\n    for ($sanitation = 1 ; $sanitation <= 7 ; $sanitation++) {\n        $fire = 12 - $police - $sanitation;\n        if ((1 <= $fire) and ($fire <= 7) and ($police != $sanitation) and ($sanitation != $fire)) {\n            echo 'Police: ', $police, ', Sanitation: ', $sanitation, ', Fire: ', $fire, PHP_EOL;\n            $valid++;\n        }\n    }\n}\necho $valid, ' valid combinations found.', PHP_EOL;\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":2141}
    {"lang_cluster":"PHP","source_code":"\n$src = \"Hello\";\n$dst = $src;\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":2142}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfunction F($n)\n{\n  if ( $n == 0 ) return 1;\n  return $n - M(F($n-1));\n}\n\nfunction M($n)\n{\n  if ( $n == 0) return 0;\n  return $n - F(M($n-1));\n}\n\n$ra = array();\n$rb = array();\nfor($i=0; $i < 20; $i++)\n{\n  array_push($ra, F($i));\n  array_push($rb, M($i));\n}\necho implode(\" \", $ra) . \"\\n\";\necho implode(\" \", $rb) . \"\\n\";\n?>\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":2143}
    {"lang_cluster":"PHP","source_code":"\n$arr = array('foo', 'bar', 'baz');\n$x = $arr[array_rand($arr)];\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":2144}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$encoded = \"http%3A%2F%2Ffoo%20bar%2F\";\n$unencoded = rawurldecode($encoded);\necho \"The unencoded string is $unencoded\u00a0!\\n\";\n?>\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":2145}
    {"lang_cluster":"PHP","source_code":"\n\nfunction binary_search( $array, $secret, $start, $end )\n{\n        do\n        {\n                $guess = (int)($start + ( ( $end - $start ) \/ 2 ));\n\n                if ( $array[$guess] > $secret )\n                        $end = $guess;\n\n                if ( $array[$guess] < $secret )\n                        $start = $guess;\n\n                if ( $end < $start)\n                        return -1;\n\n        } while ( $array[$guess]\u00a0!= $secret );\n\n        return $guess;\n}\n\nfunction binary_search( $array, $secret, $start, $end )\n{\n        $guess = (int)($start + ( ( $end - $start ) \/ 2 ));\n\n        if ( $end < $start)\n                return -1;\n\n        if ( $array[$guess] > $secret )\n                return (binary_search( $array, $secret, $start, $guess ));\n\n        if ( $array[$guess] < $secret )\n                return (binary_search( $array, $secret, $guess, $end ) );\n\n        return $guess;\n}\n","human_summarization":"Implement a binary search algorithm that divides a range of values into halves until it finds the target value. The algorithm can be implemented both recursively and iteratively. It also handles multiple equal values and returns the index of the target value if found, or the index where it would be inserted if not found. The code also includes variations for finding the leftmost and rightmost insertion points. It ensures no overflow bugs occur during the calculation of the mid-point.","id":2146}
    {"lang_cluster":"PHP","source_code":"\n\n<?php\n$program_name = $argv[0];\n$second_arg = $argv[2];\n$all_args_without_program_name = array_shift($argv);\n\n","human_summarization":"are designed to retrieve the list of command-line arguments provided to the program. The arguments are stored in the special variables $argv and $argc, which represent the array of arguments and the number of arguments respectively. The program name is passed as the first argument. The code also includes an example command line for reference. For intelligent parsing of these arguments, additional functionality is referenced.","id":2147}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$data = json_decode('{ \"foo\": 1, \"bar\": [10, \"apples\"] }'); \/\/ dictionaries will be returned as objects\n$data2 = json_decode('{ \"foo\": 1, \"bar\": [10, \"apples\"] }', true); \/\/ dictionaries will be returned as arrays\n\n$sample = array( \"blue\" => array(1,2), \"ocean\" => \"water\" );\n$json_string = json_encode($sample);\n?>\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":2148}
    {"lang_cluster":"PHP","source_code":"\nfunction nthroot($number, $root, $p = P)\n{\n    $x[0] = $number;\n    $x[1] = $number\/$root;\n    while(abs($x[1]-$x[0]) > $p)\n    {\n        $x[0] = $x[1];\n        $x[1] = (($root-1)*$x[1] + $number\/pow($x[1], $root-1))\/$root;\n    }\n    return $x[1];\n}\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":2149}
    {"lang_cluster":"PHP","source_code":"\necho $_SERVER['HTTP_HOST'];\n\necho php_uname('n');\n\nWorks with: PHP version 5.3+\necho gethostname();\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":2150}
    {"lang_cluster":"PHP","source_code":"#!\/usr\/bin\/env php\nThe 24 Game\n \nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and \/ operators; and the possible use of\nbrackets, (), show how to make an answer of 24.\n \nAn answer of \"q\" will quit the game.\nAn answer of \"!\" will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24\n \nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n<?php\n\nwhile (true) {\n    $numbers = make_numbers();\n\n    for ($iteration_num = 1; ; $iteration_num++) {\n        echo \"Expresion $iteration_num: \";\n\n        $entry = rtrim(fgets(STDIN));\n\n        if ($entry === '!') break;\n        if ($entry === 'q') exit;\n\n        $result = play($numbers, $entry);\n\n        if ($result === null) {\n            echo \"That's not valid\\n\";\n            continue;\n        }\n        elseif ($result != 24) {\n            echo \"Sorry, that's $result\\n\";\n            continue;\n        }\n        else {\n            echo \"That's right! 24!!\\n\";\n            exit;\n        }\n    }\n}\n\nfunction make_numbers() {\n    $numbers = array();\n\n    echo \"Your four digits: \";\n\n    for ($i = 0; $i < 4; $i++) {\n        $number = rand(1, 9);\n        \/\/ The check is needed to avoid E_NOTICE from PHP\n        if (!isset($numbers[$number])) {\n            $numbers[$number] = 0;\n        }\n        $numbers[$number]++;\n        print \"$number \";\n    }\n\n    print \"\\n\";\n\n    return $numbers;\n}\n\nfunction play($numbers, $expression) {\n    $operator = true;\n    for ($i = 0, $length = strlen($expression); $i < $length; $i++) {\n        $character = $expression[$i];\n\n        if (in_array($character, array('(', ')', ' ', \"\\t\"))) continue;\n\n        $operator = !$operator;\n\n        if (!$operator) {\n            if (!empty($numbers[$character])) {\n                $numbers[$character]--;\n                continue;\n            }\n            return;\n        }\n        elseif (!in_array($character, array('+', '-', '*', '\/'))) {\n            return;\n        }\n    }\n\n    foreach ($numbers as $remaining) {\n        if ($remaining > 0) {\n            return;\n        }\n    }\n    \n    return eval(\"return $expression;\");\n}\n?>\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":2151}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfunction encode($str)\n{\n    return preg_replace_callback('\/(.)\\1*\/', function ($match) {\n        return strlen($match[0]) . $match[1];\n    }, $str);\n}\n\nfunction decode($str)\n{\n    return preg_replace_callback('\/(\\d+)(\\D)\/', function($match) {\n        return str_repeat($match[2], $match[1]);\n    }, $str);\n}\n\necho encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'), PHP_EOL;\necho decode('12W1B12W3B24W1B14W'), PHP_EOL;\n?>\n\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":2152}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$s = \"hello\";\necho $s . \" literal\" . \"\\n\";\n$s1 = $s . \" literal\";\necho $s1 . \"\\n\";\n?>\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":2153}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$s = 'http:\/\/foo\/bar\/';\n$s = rawurlencode($s);\n?>\n\n\n","human_summarization":"\"Implement a function to convert a given string into URL encoding format. It converts special, control, and extended characters into a percent symbol followed by a two-digit hexadecimal code, with space character encoding as %20. Characters outside the range of 0-9, A-Z, and a-z are converted. The function also supports variations like lowercase escapes and different encoding standards like RFC 3986, HTML 5, and encodeURI in Javascript. An optional feature is the use of an exception string for symbols that don't need conversion. The function can also encode spaces as '+' signs similar to urlencode().\"","id":2154}
    {"lang_cluster":"PHP","source_code":"\n\/* Added by @1x24. Translated from C++. Uses the PHP 7.x spaceship operator *\/\n$data = [\n\t\t\t[\n\t\t\t\t'name'=>'beef',\n\t\t\t\t'weight'=>3.8,\n\t\t\t\t'cost'=>36,\n\t\t\t],\n\t\t\t[\n\t\t\t\t'name'=>'pork',\n\t\t\t\t'weight'=>5.4,\n\t\t\t\t'cost'=>43,\n\t\t\t],\n\t\t\t[\n\t\t\t\t'name'=>'ham',\n\t\t\t\t'weight'=>3.6,\n\t\t\t\t'cost'=>90,\n\t\t\t],\n\t\t\t[\n\t\t\t\t'name'=>'greaves',\n\t\t\t\t'weight'=>2.4,\n\t\t\t\t'cost'=>45,\n\t\t\t],\n\t\t\t[\n\t\t\t\t'name'=>'flitch',\n\t\t\t\t'weight'=>4.0,\n\t\t\t\t'cost'=>30,\n\t\t\t],\n\t\t\t[\n\t\t\t\t'name'=>'brawn',\n\t\t\t\t'weight'=>2.5,\n\t\t\t\t'cost'=>56,\n\t\t\t],\n\t\t\t[\n\t\t\t\t'name'=>'welt',\n\t\t\t\t'weight'=>3.7,\n\t\t\t\t'cost'=>67,\n\t\t\t],\n\t\t\t[\n\t\t\t\t'name'=>'salami',\n\t\t\t\t'weight'=>3.0,\n\t\t\t\t'cost'=>95,\n\t\t\t],\n\t\t\t[\n\t\t\t\t'name'=>'sausage',\n\t\t\t\t'weight'=>5.9,\n\t\t\t\t'cost'=>98,\n\t\t\t],\n\t\t];\n\nuasort($data, function($a, $b) {\n    return ($b['cost']\/$b['weight']) <=> ($a['cost']\/$a['weight']);\n});\n\n$limit = 15;\n\nforeach ($data as $item):\n\tif ($limit >= $item['weight']):\n\t\techo \"Take all the {$item['name']}<br\/>\";\n\telse:\n\t\techo \"Take $limit kg of {$item['name']}<br\/>\";\n\t\tbreak;\n\tendif;\n\t$limit -= $item['weight'];\nendforeach;\n\n\nTake all the salami\nTake all the ham\nTake all the brawn\nTake all the greaves\nTake 3.5 kg of welt\n","human_summarization":"\"Output: The code calculates the optimal combination of items a thief can carry in his knapsack, given a maximum weight limit of 15 kg. The items can be cut to fit the weight limit, with the price proportionally reduced. The goal is to maximize the total value of the items in the knapsack.\"","id":2155}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$words = explode(\"\\n\", file_get_contents('http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt'));\nforeach ($words as $word) {\n    $chars = str_split($word);\n    sort($chars);\n    $anagram[implode($chars)][] = $word;\n}\n\n$best = max(array_map('count', $anagram));\nforeach ($anagram as $ana)\n    if (count($ana) == $best)\n        print_r($ana);\n?>\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":2156}
    {"lang_cluster":"PHP","source_code":"\n<?php\n\nfunction isSierpinskiCarpetPixelFilled($x, $y) {\n    while (($x > 0) or ($y > 0)) {\n        if (($x % 3 == 1) and ($y % 3 == 1)) {\n            return false;\n        }\n        $x \/= 3;\n        $y \/= 3;\n    }\n    return true;\n}\n\nfunction sierpinskiCarpet($order) {\n    $size = pow(3, $order);\n    for ($y = 0 ; $y < $size ; $y++) {\n        for ($x = 0 ; $x < $size ; $x++) {\n            echo isSierpinskiCarpetPixelFilled($x, $y) ? '#' : ' ';\n        }\n        echo PHP_EOL;\n    }\n}\n\nfor ($order = 0 ; $order <= 3 ; $order++) {\n    echo 'N=', $order, PHP_EOL;\n    sierpinskiCarpet($order);\n    echo PHP_EOL;\n}\n\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":2157}
    {"lang_cluster":"PHP","source_code":"\nWorks with: PHP version 5.3+<?php\nfunction encode($symb2freq) {\n    $heap = new SplPriorityQueue;\n    $heap->setExtractFlags(SplPriorityQueue::EXTR_BOTH);\n    foreach ($symb2freq as $sym => $wt)\n        $heap->insert(array($sym => ''), -$wt);\n\n    while ($heap->count() > 1) {\n        $lo = $heap->extract();\n        $hi = $heap->extract();\n        foreach ($lo['data'] as &$x)\n            $x = '0'.$x;\n        foreach ($hi['data'] as &$x)\n            $x = '1'.$x;\n        $heap->insert($lo['data'] + $hi['data'],\n                      $lo['priority'] + $hi['priority']);\n    }\n    $result = $heap->extract();\n    return $result['data'];\n}\n\n$txt = 'this is an example for huffman encoding';\n$symb2freq = array_count_values(str_split($txt));\n$huff = encode($symb2freq);\necho \"Symbol\\tWeight\\tHuffman Code\\n\";\nforeach ($huff as $sym => $code)\n    echo \"$sym\\t$symb2freq[$sym]\\t$code\\n\";\n?>\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":2158}
    {"lang_cluster":"PHP","source_code":"\nfor ($i = 10; $i >= 0; $i--)\n  echo \"$i\\n\";\n\nforeach (range(10, 0) as $i)\n  echo \"$i\\n\";\n","human_summarization":"Implement a for loop that counts down from 10 to 0.","id":2159}
    {"lang_cluster":"PHP","source_code":"<?php\n\n$str = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n$key = \"VIGENERECIPHER\";\n\nprintf(\"Text: %s\\n\", $str);\nprintf(\"key:  %s\\n\", $key);\n\n$cod = encipher($str, $key, true); printf(\"Code: %s\\n\", $cod);\n$dec = encipher($cod, $key, false); printf(\"Back: %s\\n\", $dec);\n\nfunction encipher($src, $key, $is_encode)\n{\n    $key = strtoupper($key);\n    $src = strtoupper($src);\n    $dest = '';\n\n    \/* strip out non-letters *\/\n    for($i = 0; $i <= strlen($src); $i++) {\n        $char = substr($src, $i, 1);\n        if(ctype_upper($char)) {\n            $dest .= $char;\n        }\n    }\n\n    for($i = 0; $i <= strlen($dest); $i++) {\n        $char = substr($dest, $i, 1);\n        if(!ctype_upper($char)) {\n            continue;\n        }\n        $dest = substr_replace($dest,\n            chr (\n                ord('A') +\n                ($is_encode\n                   ? ord($char) - ord('A') + ord($key[$i % strlen($key)]) - ord('A')\n                   : ord($char) - ord($key[$i % strlen($key)]) + 26\n                ) % 26\n            )\n        , $i, 1);\n    }\n\n    return $dest;\n}\n\n?>\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":2160}
    {"lang_cluster":"PHP","source_code":"\n<?php\nforeach (range(2, 8, 2) as $i)\n    echo \"$i, \";\necho \"who do we appreciate?\\n\";\n?>\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":2161}
    {"lang_cluster":"PHP","source_code":"\n$i;\nfunction sum (&$i, $lo, $hi, $term) {\n    $temp = 0;\n    for ($i = $lo; $i <= $hi; $i++) {\n        $temp += $term();\n    }\n    return $temp;\n}\n\necho sum($i, 1, 100, create_function('', 'global $i; return 1 \/ $i;')), \"\\n\";\n\/\/","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":2162}
    {"lang_cluster":"PHP","source_code":"\nheader(\"Content-Type: image\/png\");\n\n$w = 256;\n$h = 256;\n\n$im = imagecreate($w, $h)\n    or die(\"Cannot Initialize new GD image stream\");\n\n$color = array();\nfor($i=0;$i<256;$i++)\n{\n        array_push($color,imagecolorallocate($im,sin(($i)*(2*3.14\/256))*128+128,$i\/2,$i));\n}\n\nfor($i=0;$i<$w;$i++)\n{\n        for($j=0;$j<$h;$j++)\n        {\n                imagesetpixel($im,$i,$j,$color[$i^$j]);\n        }\n}\n\nimagepng($im);\nimagedestroy($im);\n\n\n","human_summarization":"\"Generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table.\"","id":2163}
    {"lang_cluster":"PHP","source_code":"\n\n<?php\nclass Maze \n{\n    protected $width;\n    protected $height;\n    protected $grid;\n    protected $path;\n    protected $horWalls;\n    protected $vertWalls;\n    protected $dirs;\n    protected $isDebug;\n\n    public function __construct($x, $y, $debug = false)\n    {\n        $this->width = $x;\n        $this->height = $y;\n        $this->path = [];        \n        $this->dirs = [ [0, -1], [0, 1], [-1, 0], [1, 0]]; \/\/ array of coordinates of N,S,W,E\n        $this->horWalls = []; \/\/ list of removed horizontal walls (---+)        \n        $this->vertWalls = [];\/\/ list of removed vertical walls (|)        \n        $this->isDebug = $debug; \/\/ debug flag\n\n        \/\/ generate the maze:\n        $this->generate();\n    }\n\n    protected function generate()\n    {        \n        $this->initMaze(); \/\/ init the stack and an unvisited grid\n        \/\/ start from a random cell and then proceed recursively\n        $this->walk(mt_rand(0, $this->width-1), mt_rand(0, $this->height-1));\n    }\n\n    \/**\n    * Actually prints the Maze, on stdOut. Put in a separate method to allow extensibility\n    * For simplicity sake doors are positioned on the north wall and east wall\n    *\/\n    public function printOut()\n    {\n        $this->log(\"Horizontal walls: %s\", json_encode($this->horWalls));\n        $this->log(\"Vertical walls: %s\", json_encode($this->vertWalls));        \n        \n        $northDoor = mt_rand(0,$this->width-1);\n        $eastDoor = mt_rand(0, $this->height-1);\n\n        $str = '+';\n        for ($i=0;$i<$this->width;$i++) {\n            $str .= ($northDoor == $i) ? '   +' : '---+';\n        }\n        $str .= PHP_EOL;\n        for ($i=0; $i<$this->height; $i++) {\n            \n            for ($j=0; $j<$this->width; $j++) {\n                $str .= (!empty($this->vertWalls[$j][$i]) ? $this->vertWalls[$j][$i] : '|   ');\n            }\n            $str .= ($i == $eastDoor ? '  ' : '|').PHP_EOL.'+';\n            for ($j=0; $j<$this->width; $j++) {\n                $str .= (!empty($this->horWalls[$j][$i]) ? $this->horWalls[$j][$i] : '---+');\n            }\n            $str .= PHP_EOL;\n        }\n        echo $str;\n    }\n\n    \/**\n    * Logs to stdOut if debug flag is enabled\n    *\/\n    protected function log(...$params)\n    {\n        if ($this->isDebug) {\n            echo vsprintf(array_shift($params), $params).PHP_EOL;\n        }\n    }\n\n    private function walk($x, $y)\n    {\n        $this->log('Entering cell %d,%d', $x, $y);\n        \/\/ mark current cell as visited     \n        $this->grid[$x][$y] = true; \n        \/\/ add cell to path\n        $this->path[] = [$x, $y];\n        \/\/ get list of all neighbors\n        $neighbors = $this->getNeighbors($x, $y);       \n        $this->log(\"Valid neighbors: %s\", json_encode($neighbors));\n\n        if(empty($neighbors)) {\n            \/\/ Dead end, we need now to backtrack, if there's still any cell left to be visited\n            $this->log(\"Start backtracking along path: %s\", json_encode($this->path));\n            array_pop($this->path);\n            if (!empty($this->path)) {\n                $next = array_pop($this->path);\n                return $this->walk($next[0], $next[1]);\n            }\n        } else {            \n            \/\/ randomize neighbors, as per request\n            shuffle($neighbors);\n\n            foreach ($neighbors as $n) {\n                $nextX = $n[0];\n                $nextY = $n[1];\n                if ($nextX == $x) {\n                    $wallY = max($nextY, $y);\n                    $this->log(\"New cell is on the same column (%d,%d), removing %d, (%d-1) horizontal wall\", $nextX, $nextY, $x, $wallY);\n                    $this->horWalls[$x][min($nextY, $y)] = \"   +\";\n                }\n                if ($nextY == $y) {\n                    $wallX = max($nextX, $x);\n                    $this->log(\"New cell is on the same row (%d,%d), removing %d,%d vertical wall\", $nextX, $nextY, $wallX, $y);\n                    $this->vertWalls[$wallX][$y] = \"    \";              \n                }\n                return $this->walk($nextX, $nextY);\n            }\n        }\n    }\n    \n    \/**\n    * Initialize an empty grid of $width * $height dimensions\n    *\/\n    private function initMaze()\n    {\n        for ($i=0;$i<$this->width;$i++) {\n            for ($j = 0;$j<$this->height;$j++) {\n                $this->grid[$i][$j] = false;\n            }\n        }\n    }\n\n    \/**\n    * @param int $x\n    * @param int $y\n    * @return array\n    *\/\n    private function getNeighbors($x, $y) \n    {       \n        $neighbors = [];\n        foreach ($this->dirs as $dir) {\n            $nextX = $dir[0] + $x;\n            $nextY = $dir[1] + $y;\n            if (($nextX >= 0 && $nextX < $this->width && $nextY >= 0 && $nextY < $this->height) && !$this->grid[$nextX][$nextY]) {\n                $neighbors[] = [$nextX, $nextY];\n            }\n        }\n        return $neighbors;\n    }\n}\n\n$maze = new Maze(10,10);\n$maze->printOut();\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts at a random cell, marks it as visited, and processes its neighbors. If a neighbor is unvisited, it removes the wall between the current cell and the neighbor, then recursively applies the same process to the neighbor. The code is inspired by D and Python solutions and includes a debug flag for tracking the process. It is compatible with PHP versions greater than 5.6.","id":2164}
    {"lang_cluster":"PHP","source_code":"\nfunction ackermann( $m , $n )\n{\n    if ( $m==0 )\n    {\n        return $n + 1;\n    }\n    elseif ( $n==0 )\n    {\n        return ackermann( $m-1 , 1 );\n    }\n    return ackermann( $m-1, ackermann( $m , $n-1 ) );\n}\n\necho ackermann( 3, 4 );\n\/\/ prints 125\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":2165}
    {"lang_cluster":"PHP","source_code":"\n<html>\n<head>\n<title>\nn x n Queen solving program\n<\/title>\n<\/head>\n<body>\n<?php\necho \"<h1>n x n Queen solving program<\/h1>\";\n \n\/\/Get the size of the board\n$boardX = $_POST['boardX'];\n$boardY = $_POST['boardX'];\n \n\/\/ Function to rotate a board 90 degrees\nfunction rotateBoard($p, $boardX) {\n    $a=0;\n    while ($a < count($p)) {\n        $b = strlen(decbin($p[$a]))-1;\n        $tmp[$b] = 1 << ($boardX - $a - 1);\n        ++$a;\n    }\n    ksort($tmp);\n    return $tmp;\n}\n \n\/\/ This function will find rotations of a solution\nfunction findRotation($p, $boardX,$solutions){\n    $tmp = rotateBoard($p,$boardX);\n    \/\/ Rotated 90\n    if (in_array($tmp,$solutions)) {}\n    else {$solutions[] = $tmp;}\n    \n    $tmp = rotateBoard($tmp,$boardX);\n    \/\/ Rotated 180\n    if (in_array($tmp,$solutions)){}\n    else {$solutions[] = $tmp;}\n    \n    $tmp = rotateBoard($tmp,$boardX);\n    \/\/ Rotated 270\n    if (in_array($tmp,$solutions)){}\n    else {$solutions[] = $tmp;}\n    \n    \/\/ Reflected\n    $tmp = array_reverse($p);\n    if (in_array($tmp,$solutions)){}\n    else {$solutions[] = $tmp;}\n    \n    $tmp = rotateBoard($tmp,$boardX);\n    \/\/ Reflected and Rotated 90\n    if (in_array($tmp,$solutions)){}\n    else {$solutions[] = $tmp;}\n    \n    $tmp = rotateBoard($tmp,$boardX);\n    \/\/ Reflected and Rotated 180\n    if (in_array($tmp,$solutions)){}\n    else {$solutions[] = $tmp;}\n    \n    $tmp = rotateBoard($tmp,$boardX);\n    \/\/ Reflected and Rotated 270\n    if (in_array($tmp,$solutions)){}\n    else {$solutions[] = $tmp;}\n    return $solutions;\n}\n \n\/\/ This is a function which will render the board\nfunction renderBoard($p,$boardX) {\n$img = 'data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAtCAYAAAA6GuKaAAAABmJLR0QA\/wD\/AP+gvaeTAAAGFUlEQVRYhe2YXWibVRjHf2lqP9JmaRi4YW1IalY3rbZsaddMgsquBm676b6KyNDhLiaUeSEMvPNCcNuNyJjgLiboCnoxKFlv6lcHy7AtMhhaWTVZWhisjDTEtEuW5PHiPWnfvH2TvNk6vekfDm\/O+Z\/zPP\/3PM\/5eAMb2MAG\/nfYn4LNVuBj4ENgB\/Ar8Ogp+KkJbwLfqvKGgbMBPwKiK+Oq3aqNdcebQEEnqAC8ruO7KBVcLF012KiKuhpFv0\/prNlU239qw0x0pdBJFXt30NJDjx9Uu1Ub1TSYdq4UutcNfI61oW0Bflb8T6quRzUbNafPFdbm4zcmTucV91kZO18o\/osy\/GeKnzcRVFWDMT2shO4X4IL6\/UqZPv2GpxHFcReUvVo1lMAYunKh+UTxeeB5A\/cMkFF8RtX1eF6NE2XHTIN+ltekoHGmf0HLqe9V3Qb8ZWK4Xjf+HQP3KtCgfjeouh7v6PzWsxZ6f98De1kbjbIovumoCfcp2gzkgb8p3cJOUjpTJ3WcTfXPq\/Gfmtge1Y01RaV9+jv1fAsYMnAu3XgfENJxfUoU6tmn40Kqf9Gvi1IMKX96\/zWJnlLP4i7wrIEvzkQeeFfXvltnt07Vi3iX1RcyzuSzrO46ev81YS+rYcqjbUVFfIl2CSryS4ATcKCF3biQHIpf0rU\/UnaKuMLqAhXlv2a4Dc4FOKi4bwyiBTgBvGYyRlT7CUPbI1b334MmY9zlhFVKjwQQ09ULaDNTNKYPbx54j9L81aNP8XldW3G8W9kt6LiY8m8Ksy1Hj0mgA+3eXYeWd2eBRkpf2A4MoO3JOYPdHPA2sMtgu07ZOavsFnegvPL72PiItWEroB0axtwtmPStxOeUHbNxH1USVe1qOm3SVkA7NIwX+1phU3YKJpyZX8swW4y1FOMsVotG1UUI1mbrH9ZeL\/UQi3b0C7dS\/2W0LbIsqi1E0K6PL5oRdrudHTt22Px+Pz6fD6\/XS3NzM21tbSt9FhcXWVpaIhqN2mKxGLOzs8zMzJDP581MQukHw2OLPgt8VRQZDAbZv38\/wWCQnTt30tKyGoRUKsWDBw\/IZrOkUimcTicNDQ1s3rwZp9O50i+dTjM9Pc2NGzcIh8NEIhH9S3xuQVNV2IArp06dkoWFBRERefjwoUxMTMi5c+fk8OHD0tPTIy6Xq2Keulwu6enpkSNHjsj58+dlYmJCMpmMiIgsLCzIxYsXBe1UfNIFvoL6M2fO\/Hn58uXC4OCgtLa2PsniXClOp1MGBwfl0qVLhdOnT\/+BtcjX9FYe4Pe+vj6Hy+Vat9lIJpMyOTm5BLwExNfL7gpCodAFeQoIhUIXqntfhaVwFHH9+nXp7+8vuFyuWv8vKYtkMlmYnJwse+F\/Urzi9\/ulqanJ6gFhqTQ1NeW7u7sF6Fx3xd3d3bdERNLptITDYRkeHpZgMCgOh6MmkQ6HQ\/bs2SPDw8MSDoclnU6LiMju3buvlHG9BlYX1F5gfGhoiEAgwL59+9i+fTsAuVyOWCxGPB4nHo+TSCTIZrMkEgncbjeNjY243W46OjrweDx4vV7q67WsnJmZYWxsjGvXrjE+Pm5Zj1XRX3d2dg7Nz8\/bs9ksAFu2bGHXrl0EAgG2bduG1+vF4\/HgdDrZtGkTdrudXC5HKpUilUpx9+5dYrEYd+7cYXp6mqmpKe7fvw9AQ0MDXV1d3L59+2Xgd4uaKqO3t\/cnEZFkMikjIyNy9OhRaW9vf6Jcbm9vl2PHjsnIyIgkk0kRETl06NAHVvRYnenA8ePHJ4PBIAcOHGDr1q0AxONxbt68yezsLNFolLm5ORKJBMvLy6TTaVpaWmhubl5JD5\/Ph9\/vZ2BgAI\/HA8C9e\/cYHR3l6tWry2NjY88Bi+slGqAHOFVXVxfq7e3tGhgYqAsGgwQCAfH5fLbGxsaqBjKZDNFoVKampmyRSIRIJFK4devWn4VC4TpwEfjNipDHPdlagADaf3X9NpvthY6Ojk6Px+Mq3vLsdjv5fJ7FxUWWl5eJx+OJubm5mIjMon1O\/Yr2N0G6VufrdhwrtAJtaN9+bWihzqB9pNYsbgMbeAz8C3N\/JQD4H5KCAAAAAElFTkSuQmCC';\necho \"<table border=1 cellspacing=0 style='text-align:center;display:inline'>\";\nfor ($y = 0; $y < $boardX; ++$y) {\n\techo '<tr>';\n\tfor ($x = 0; $x < $boardX; ++$x){\n\tif (($x+$y) & 1) { $cellCol = '#9C661F';}\n\telse {$cellCol = '#FCE6C9';}\n \n\tif ($p[$y] == 1 << $x) { echo \"<td bgcolor=\".$cellCol.\"><img width=30 height=30 src='\".$img.\"'><\/td>\";}\n\telse { echo \"<td bgcolor=\".$cellCol.\"> <\/td>\";}\n\t}\n\techo '<tr>';\n}\necho '<tr><\/tr><\/table> ';\n \n}\n \n\/\/This function allows me to generate the next order of rows.\nfunction pc_next_permutation($p) {\n    $size = count($p) - 1;\n    \/\/ slide down the array looking for where we're smaller than the next guy \n    \n    for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { } \n    \n    \/\/ if this doesn't occur, we've finished our permutations \n    \/\/ the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1) \n    if ($i == -1) { return false; } \n    \n    \/\/ slide down the array looking for a bigger number than what we found before \n    for ($j = $size; $p[$j] <= $p[$i]; --$j) { } \n    \/\/ swap them \n    $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; \n    \/\/ now reverse the elements in between by swapping the ends \n    for (++$i, $j = $size; $i < $j; ++$i, --$j) \n    { $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; } \n    return $p; \n}\n \n\/\/This function needs to check the current state to see if there are any \nfunction checkBoard($p,$boardX) {\n\t$a = 0; \/\/this is the row being checked\n\twhile ($a < count($p)) { \n\t\t$b = 1;\n\t\twhile ($b < ($boardX - $a)){\n            $x = $p[$a+$b] << $b;\n            $y = $p[$a+$b] >> $b;\n            if ($p[$a] == $x | $p[$a] == $y) { \n                return false;\n            }\t\t\n            ++$b;\n\t\t}\n\t++$a; \n\t}\n\treturn true;\n}\n \n \nif (isset($_POST['process']) && isset($_POST['boardX']))\n{\n\/\/Within here is the code that needs to be run if process is clicked.\n \n \n\/\/First I need to create the different possible rows\nfor ($x = 0; $x < $boardX; ++$x){\n\t$row[$x] = 1 << $x;\n}\n \n\/\/Now I need to create all the possible orders of rows, will be equal to [boardY]!\n$solcount = 0;\n$solutions = array();\nwhile ($row != false) {\n\tif (checkBoard($row,$boardX)){\n\tif(!in_array($row,$solutions)){\n\t\t$solutions[] = $row;\n\t\t\trenderBoard($row,$boardX);\n\t\t\t$solutions = findRotation($row,$boardX,$solutions);\n\t\t\t++$solcount;\n\t\t}\n \n\t}\n\t$row = pc_next_permutation($row);\t\n}\necho \"<br><br>    Rows\/Columns: \".$boardX.\"<br>    Unique Solutions: \".$solcount.\"<br>    Total Solutions: \".count($solutions).\"  - Note: This includes symmetrical solutions<br>\";\n\/\/print_r($solutions);\n}\n \n\/\/This code collects the starting parameters\necho <<<_END\n<form name=\"input\" action=\"index.php\" method=\"post\">\n    Number of columns\/rows <select name=\"boardX\" \/>\n<option value=\"1\">One<\/option>\n<option value=\"2\">Two<\/option>\n<option value=\"3\">Three<\/option>\n<option value=\"4\" >Four<\/option>\n<option value=\"5\">Five<\/option>\n<option value=\"6\">Six<\/option>\n<option value=\"7\">Seven<\/option>\n<option value=\"8\" selected=\"selected\">Eight<\/option>\n<option value=\"9\">Nine<\/option>\n<option value=\"10\">Ten<\/option>\n<\/select>\n    <input type=\"hidden\" name=\"process\" value=\"yes\" \/>\n <input type=\"submit\" value=\"Process\" \/>\n<\/form>\n \n_END;\n \n?>\n<\/body>\n<\/html>\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":2166}
    {"lang_cluster":"PHP","source_code":"\n$arr1 = array(1, 2, 3);\n$arr2 = array(4, 5, 6);\n$arr3 = array_merge($arr1, $arr2);\n","human_summarization":"demonstrate how to concatenate two arrays.","id":2167}
    {"lang_cluster":"PHP","source_code":"\n#########################################################\n# 0-1 Knapsack Problem Solve with memoization optimize and index returns\n# $w = weight of item\n# $v = value of item\n# $i = index\n# $aW = Available Weight\n# $m = Memo items array\n# PHP Translation from Python, Memoization,\n# and index return functionality added by Brian Berneker\n#\n#########################################################\n\nfunction knapSolveFast2($w, $v, $i, $aW, &$m) {\n\n\tglobal $numcalls;\n\t$numcalls ++;\n\t\/\/ echo \"Called with i=$i, aW=$aW<br>\";\n\n\t\/\/ Return memo if we have one\n\tif (isset($m[$i][$aW])) {\n\t\treturn array( $m[$i][$aW], $m['picked'][$i][$aW] );\n\t} else {\n\n\t\t\/\/ At end of decision branch\n\t\tif ($i == 0) {\n\t\t\tif ($w[$i] <= $aW) { \/\/ Will this item fit?\n\t\t\t\t$m[$i][$aW] = $v[$i]; \/\/ Memo this item\n\t\t\t\t$m['picked'][$i][$aW] = array($i); \/\/ and the picked item\n\t\t\t\treturn array($v[$i],array($i)); \/\/ Return the value of this item and add it to the picked list\n\n\t\t\t} else {\n\t\t\t\t\/\/ Won't fit\n\t\t\t\t$m[$i][$aW] = 0; \/\/ Memo zero\n\t\t\t\t$m['picked'][$i][$aW] = array(); \/\/ and a blank array entry...\n\t\t\t\treturn array(0,array()); \/\/ Return nothing\n\t\t\t}\n\t\t}\t\n\t\n\t\t\/\/ Not at end of decision branch..\n\t\t\/\/ Get the result of the next branch (without this one)\n\t\tlist ($without_i, $without_PI) = knapSolveFast2($w, $v, $i-1, $aW, $m);\n\n\t\tif ($w[$i] > $aW) { \/\/ Does it return too many?\n\t\t\t\n\t\t\t$m[$i][$aW] = $without_i; \/\/ Memo without including this one\n\t\t\t$m['picked'][$i][$aW] = $without_PI; \/\/ and a blank array entry...\n\t\t\treturn array($without_i, $without_PI); \/\/ and return it\n\n\t\t} else {\n\t\t\n\t\t\t\/\/ Get the result of the next branch (WITH this one picked, so available weight is reduced)\n\t\t\tlist ($with_i,$with_PI) = knapSolveFast2($w, $v, ($i-1), ($aW - $w[$i]), $m);\n\t\t\t$with_i += $v[$i];  \/\/ ..and add the value of this one..\n\t\t\t\n\t\t\t\/\/ Get the greater of WITH or WITHOUT\n\t\t\tif ($with_i > $without_i) {\n\t\t\t\t$res = $with_i;\n\t\t\t\t$picked = $with_PI;\n\t\t\t\tarray_push($picked,$i);\n\t\t\t} else {\n\t\t\t\t$res = $without_i;\n\t\t\t\t$picked = $without_PI;\n\t\t\t}\n\t\t\t\t\t\t\n\t\t\t$m[$i][$aW] = $res; \/\/ Store it in the memo\n\t\t\t$m['picked'][$i][$aW] = $picked; \/\/ and store the picked item\n\t\t\treturn array ($res,$picked); \/\/ and then return it\n\t\t}\t\n\t}\n}\n\n\n\n$items4 = array(\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\"camera\",\"t-shirt\",\"trousers\",\"umbrella\",\"waterproof trousers\",\"waterproof overclothes\",\"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\");\n$w4 = array(9,13,153,50,15,68,27,39,23,52,11,32,24,48,73,42,43,22,7,18,4,30);\n$v4 = array(150,35,200,160,60,45,60,40,30,10,70,30,15,10,40,70,75,80,20,12,50,10);\n\n## Initialize\n$numcalls = 0; $m = array(); $pickedItems = array();\n\n## Solve\nlist ($m4,$pickedItems) = knapSolveFast2($w4, $v4, sizeof($v4) -1, 400, $m);\n\n# Display Result \necho \"<b>Items:<\/b><br>\".join(\", \",$items4).\"<br>\";\necho \"<b>Max Value Found:<\/b><br>$m4 (in $numcalls calls)<br>\";\necho \"<b>Array Indices:<\/b><br>\".join(\",\",$pickedItems).\"<br>\";\n\n\necho \"<b>Chosen Items:<\/b><br>\";\necho \"<table border cellspacing=0>\";\necho \"<tr><td>Item<\/td><td>Value<\/td><td>Weight<\/td><\/tr>\";\n$totalVal = $totalWt = 0;\nforeach($pickedItems as $key) {\n\t$totalVal += $v4[$key];\n\t$totalWt += $w4[$key];\n\techo \"<tr><td>\".$items4[$key].\"<\/td><td>\".$v4[$key].\"<\/td><td>\".$w4[$key].\"<\/td><\/tr>\";\n}\necho \"<tr><td align=right><b>Totals<\/b><\/td><td>$totalVal<\/td><td>$totalWt<\/td><\/tr>\";\necho \"<\/table><hr>\";\n\n\n","human_summarization":"The code is designed to solve the 0-1 Knapsack problem. It helps a tourist to determine the best combination of items to pack for a trip to maximize the total value without exceeding a weight limit of 4kg. The items, their weights, and values are listed in a table, and the code ensures only whole units of any item are considered, and each item can only be taken once. The algorithm is implemented based on a minimal PHP algorithm.","id":2168}
    {"lang_cluster":"PHP","source_code":"\n<?php\n$words = array(\"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"Confuse\");\n\nfunction canMakeWord($word) {\n    $word = strtoupper($word);\n    $blocks = array(\n            \"BO\", \"XK\", \"DQ\", \"CP\", \"NA\",\n            \"GT\", \"RE\", \"TG\", \"QD\", \"FS\",\n            \"JW\", \"HU\", \"VI\", \"AN\", \"OB\",\n            \"ER\", \"FS\", \"LY\", \"PC\", \"ZM\",\n    );\n\n    foreach (str_split($word) as $char) {\n        foreach ($blocks as $k => $block) {\n            if (strpos($block, $char) !== FALSE) {\n                unset($blocks[$k]);\n                continue(2);\n            }\n        }\n        return false;\n    }\n    return true;\n}\n\nforeach ($words as $word) {\n    echo $word.': ';\n    echo canMakeWord($word) ? \"True\" : \"False\";\n    echo \"\\r\\n\";\n}\n\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":2169}
    {"lang_cluster":"PHP","source_code":"\n$string = \"The quick brown fox jumped over the lazy dog's back\";\necho md5( $string );\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":2170}
    {"lang_cluster":"PHP","source_code":"\n$socket = fsockopen('localhost', 256);\nfputs($socket, 'hello socket world');\nfclose($socket);\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":2171}
    {"lang_cluster":"PHP","source_code":"\nmail('hello@world.net', 'My Subject', \"A Message!\", \"From: my@address.com\");\n\n","human_summarization":"Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.","id":2172}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfor ($n = 0; is_int($n); $n++) {\n  echo decoct($n), \"\\n\";\n}\n?>\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":2173}
    {"lang_cluster":"PHP","source_code":"\nfunction swap(&$a, &$b) {\n    list($a, $b) = array($b, $a);\n}\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.","id":2174}
    {"lang_cluster":"PHP","source_code":"\n<?php\nfunction is_palindrome($string) {\n  return $string == strrev($string);\n}\n?>\n\n<?php\nfunction is_palindrome($string) {\n  return preg_match('\/^(?:(.)(?=.*(\\1(?(2)\\2|))$))*.?\\2?$\/', $string);\n}\n?>\n","human_summarization":"The code includes a function to check if a given sequence of characters is a palindrome. It supports Unicode characters and has an additional function to detect inexact palindromes, ignoring white-space, punctuation, and case differences. It also includes a string reversal function and may be used to test other functions. The solution is based on regular expressions.","id":2175}
    {"lang_cluster":"PHP","source_code":"\n\n$_ENV['HOME']\n\n","human_summarization":"demonstrate how to retrieve a specific environment variable from the process's environment in Unix systems, such as PATH, HOME, or USER, using the $_ENV associative array.","id":2176}
    {"lang_cluster":"PHP","source_code":"#Aamrun , 11th July 2022\n\n<?php\nfunction F(int $n,int $x,int $y) {\n  if ($n == 0) {\n    return $x + $y;\n  }\n \n  else if ($y == 0) {\n    return $x;\n  }\n \n  return F($n - 1, F($n, $x, $y - 1), F($n, $x, $y - 1) + $y);\n}\necho \"F(1,3,3) = \" . F(1,3,3); \n?>\n\n\nF(1,3,3) = 35\n\n","human_summarization":"implement the Sudan function, a non-primitive recursive function. The function takes two parameters x and y, and returns their sum if the recursion depth is zero, returns x if y is zero, and for other cases, it recursively calls itself with updated parameters.","id":2177}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version 6\nDebug.Print VBA.StrReverse(\"Visual Basic\")\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":2178}
    {"lang_cluster":"Visual_Basic","source_code":"Works with: Visual Basic version VB6 Standard\nSub mersenne()\n    Dim q As Long, k As Long, p As Long, d As Long\n    Dim factor As Long, i As Long, y As Long, z As Long\n    Dim prime As Boolean\n    q = 929   'input value\n    For k = 1 To 1048576   '2**20\n        p = 2 * k * q + 1\n        If (p And 7) = 1 Or (p And 7) = 7 Then    'p=*001 or p=*111\n            'p is prime?\n            prime = False\n            If p Mod 2 = 0 Then GoTo notprime\n            If p Mod 3 = 0 Then GoTo notprime\n            d = 5\n            Do While d * d <= p\n                If p Mod d = 0 Then GoTo notprime\n                d = d + 2\n                If p Mod d = 0 Then GoTo notprime\n                d = d + 4\n            Loop\n            prime = True\n        notprime:   'modpow\n            i = q: y = 1: z = 2\n            Do While i   'i <> 0\n                On Error GoTo okfactor\n                If i And 1 Then y = (y * z) Mod p  'test first bit\n                z = (z * z) Mod p\n                On Error GoTo 0\n                i = i \\ 2\n            Loop\n            If prime And y = 1 Then factor = p: GoTo okfactor\n        End If\n    Next k\n    factor = 0\nokfactor:\n    Debug.Print \"M\" & q, \"factor=\" & factor\nEnd Sub\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":2179}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version 5\nWorks with: Visual Basic version 6\n\nSub QuickSort(arr() As Integer, ByVal f As Integer, ByVal l As Integer)\n    i = f 'First\n    j = l 'Last\n    Key = arr(i) 'Pivot\n    Do While i < j\n        Do While i < j And Key < arr(j)\n            j = j - 1\n        Loop\n        If i < j Then arr(i) = arr(j): i = i + 1\n        Do While i < j And Key > arr(i)\n            i = i + 1\n        Loop\n        If i < j Then arr(j) = arr(i): j = j - 1\n    Loop\n    arr(i) = Key\n    If i - 1 > f Then QuickSort arr(), f, i - 1\n    If j + 1 < l Then QuickSort arr(), j + 1, l\nEnd Sub\n","human_summarization":"implement the Quicksort algorithm for sorting an array or list. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions, one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts both partitions and joins them together with the pivot. The codes also include an optimized version of Quicksort that sorts the array in place by swapping elements, reducing memory allocation. The pivot selection method is not specified.","id":2180}
    {"lang_cluster":"Visual_Basic","source_code":"\n\nFunction Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function 'small Helper-Function\n\nSub Main()\nConst Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5\nDim P&, I&, G&, A&, M, Cur(Value To Volume)\nDim S As New Collection: S.Add Array(0) '<- init Solutions-Coll.\n\nConst SackW = 25, SackV = 0.25\nDim Panacea: Panacea = Array(3000, 0.3, 0.025)\nDim Ichor:     Ichor = Array(1800, 0.2, 0.015)\nDim Gold:       Gold = Array(2500, 2, 0.002)\n\n  For P = 0 To Int(Min(SackW \/ Panacea(Weight), SackV \/ Panacea(Volume)))\n    For I = 0 To Int(Min(SackW \/ Ichor(Weight), SackV \/ Ichor(Volume)))\n      For G = 0 To Int(Min(SackW \/ Gold(Weight), SackV \/ Gold(Volume)))\n        For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next\n        If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _\n          S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1\n  Next G, I, P\n  \n  Debug.Print \"Value\", \"Weight\", \"Volume\", \"PanaceaCount\", \"IchorCount\", \"GoldCount\"\n  For Each M In S '<- enumerate the Attributes of the Maxima\n    If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC)\n  Next\nEnd Sub\n\n","human_summarization":"The code determines the maximum value of items a traveler can carry in his knapsack, given the weight and volume constraints. It considers items such as panacea, ichor, and gold, each with specific values, weights, and volumes. The code provides one of the four possible solutions to maximize the value of items carried.","id":2181}
    {"lang_cluster":"Visual_Basic","source_code":"\nPublic Sub string_matching()\n    word = \"the\"                                        '-- (also try this with \"th\"\/\"he\")\n    sentence = \"the last thing the man said was the\"\n    '--       sentence = \"thelastthingthemansaidwasthe\" '-- (practically the same results)\n     \n    '-- A common, but potentially inefficient idiom for checking for a substring at the start is:\n    If InStr(1, sentence, word) = 1 Then\n        Debug.Print \"yes(1)\"\n    End If\n    '-- A more efficient method is to test the appropriate slice\n    If Len(sentence) >= Len(word) _\n        And Mid(sentence, 1, Len(word)) = word Then\n        Debug.Print \"yes(2)\"\n    End If\n    '-- Which is almost identical to checking for a word at the end\n    If Len(sentence) >= Len(word) _\n        And Mid(sentence, Len(sentence) - Len(word) + 1, Len(word)) = word Then\n        Debug.Print \"yes(3)\"\n    End If\n    '-- Or sometimes you will see this, a tiny bit more efficient:\n    If Len(sentence) >= Len(word) _\n    And InStr(Len(sentence) - Len(word) + 1, sentence, word) Then\n        Debug.Print \"yes(4)\"\n    End If\n    '-- Finding all occurences is a snap:\n    r = InStr(1, sentence, word)\n    Do While r <> 0\n        Debug.Print r\n        r = InStr(r + 1, sentence, word)\n    Loop\nEnd Sub\n","human_summarization":"The code checks if a given string starts with, contains, or ends with another string. It can also print the location of the match and handle multiple occurrences of the string.","id":2182}
    {"lang_cluster":"Visual_Basic","source_code":"Works with: Visual Basic version 5\nWorks with: Visual Basic version 6\nWorks with: VBA version Access 97\nWorks with: VBA version 6.5\nWorks with: VBA version 7.1\nOption Explicit\n\nDim total As Long, prim As Long, maxPeri As Long\n\nPublic Sub NewTri(ByVal s0 As Long, ByVal s1 As Long, ByVal s2 As Long)\nDim p As Long, x1 As Long, x2 As Long\n    p = s0 + s1 + s2\n    If p <= maxPeri Then\n        prim = prim + 1\n        total = total + maxPeri \\ p\n        x1 = s0 + s2\n        x2 = s1 + s2\n        NewTri s0 + 2 * (-s1 + s2), 2 * x1 - s1, 2 * (x1 - s1) + s2\n        NewTri s0 + 2 * x2, 2 * x1 + s1, 2 * (x1 + s1) + s2\n        NewTri -s0 + 2 * x2, 2 * (-s0 + s2) + s1, 2 * (-s0 + x2) + s2\n    End If\nEnd Sub\n\nPublic Sub Main()\n    maxPeri = 100\n    Do While maxPeri <= 10& ^ 8\n        prim = 0\n        total = 0\n        NewTri 3, 4, 5\n        Debug.Print \"Up to \"; maxPeri; \": \"; total; \" triples, \"; prim; \" primitives.\"\n        maxPeri = maxPeri * 10\n    Loop\nEnd Sub\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":2183}
    {"lang_cluster":"Visual_Basic","source_code":"\nSub AlignCols(Lines, Optional Align As AlignmentConstants, Optional Sep$ = \"$\", Optional Sp% = 1)\nDim i&, j&, D&, L&, R&: ReDim W(UBound(Lines)): ReDim C&(0)\n \n  For j = 0 To UBound(W)\n    W(j) = Split(Lines(j), Sep)\n    If UBound(W(j)) > UBound(C) Then ReDim Preserve C(UBound(W(j)))\n    For i = 0 To UBound(W(j)): If Len(W(j)(i)) > C(i) Then C(i) = Len(W(j)(i))\n  Next i, j\n\n  For j = 0 To UBound(W): For i = 0 To UBound(W(j))\n    D = C(i) - Len(W(j)(i))\n    L = Choose(Align + 1, 0, D, D \\ 2)\n    R = Choose(Align + 1, D, 0, D - L) + Sp\n    Debug.Print Space(L); W(j)(i); Space(R); IIf(i < UBound(W(j)), \"\", vbLf);\n  Next i, j\nEnd Sub\nUsage:Sub Main() 'usage of the above\nConst Text$ = \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\" & vbLf & _\n              \"are$delineated$by$a$single$'dollar'$character,$write$a$program\" & vbLf & _\n              \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\" & vbLf & _\n              \"column$are$separated$by$at$least$one$space.\" & vbLf & _\n              \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\" & vbLf & _\n              \"justified,$right$justified,$or$center$justified$within$its$column.\"\n \n  Debug.Print vbLf; \"-- Left:\":   AlignCols Split(Text, vbLf), vbLeftJustify\n  Debug.Print vbLf; \"-- Center:\": AlignCols Split(Text, vbLf), vbCenter\n  Debug.Print vbLf; \"-- Right:\":  AlignCols Split(Text, vbLf), vbRightJustify\nEnd Sub\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":2184}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version VB6 Standard\nFunction ROT13(ByVal a As String) As String\n  Dim i As Long\n  Dim n As Integer, e As Integer\n\n  ROT13 = a\n  For i = 1 To Len(a)\n    n = Asc(Mid$(a, i, 1))\n    Select Case n\n      Case 65 To 90\n        e = 90\n        n = n + 13\n      Case 97 To 122\n        e = 122\n        n = n + 13\n      Case Else\n        e = 255\n    End Select\n  \n    If n > e Then\n      n = n - 26\n    End If\n    Mid$(ROT13, i, 1) = Chr$(n)\n  Next i\nEnd Function\n\nSub Main()\n  Debug.Assert ROT13(\"abc\") = \"nop\"\n  Debug.Assert ROT13(\"nop\") = \"abc\"\nEnd Sub\n","human_summarization":"implement a rot-13 function that encodes every line of input from each file listed on its command line or acts as a filter on its standard input. This function replaces every letter of the ASCII alphabet with the letter rotated 13 characters around the 26 letter alphabet. It preserves case and passes all non-alphabetic characters in the input stream without alteration. It can be optionally wrapped in a utility program.","id":2185}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version 6\nOption Explicit\n\nFunction DotProduct(a() As Long, b() As Long) As Long\nDim l As Long, u As Long, i As Long\n  Debug.Assert DotProduct = 0 'return value automatically initialized with 0\n  l = LBound(a())\n  If l = LBound(b()) Then\n    u = UBound(a())\n    If u = UBound(b()) Then\n      For i = l To u\n        DotProduct = DotProduct + a(i) * b(i)\n      Next i\n    Exit Function\n    End If\n  End If\n  Err.Raise vbObjectError + 123, , \"invalid input\"\nEnd Function\n\nSub Main()\nDim a() As Long, b() As Long, x As Long\n  ReDim a(2)\n  a(0) = 1\n  a(1) = 3\n  a(2) = -5\n  ReDim b(2)\n  b(0) = 4\n  b(1) = -2\n  b(2) = -1\n  x = DotProduct(a(), b())\n  Debug.Assert x = 3\n  ReDim Preserve a(3)\n  a(3) = 10\n  ReDim Preserve b(3)\n  b(3) = 2\n  x = DotProduct(a(), b())\n  Debug.Assert x = 23\n  ReDim Preserve a(4)\n  a(4) = 10\n  On Error Resume Next\n  x = DotProduct(a(), b())\n  Debug.Assert Err.Number = vbObjectError + 123\n  Debug.Assert Err.Description = \"invalid input\"\nEnd Sub\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":2186}
    {"lang_cluster":"Visual_Basic","source_code":"\nOption Explicit\n\nSub Main_Lower_Case_Ascii_Alphabet()\nDim Alpha() As String\n\n    Alpha = Alphabet(97, 122)\n    Debug.Print Join(Alpha, \", \")\nEnd Sub\n\nFunction Alphabet(FirstAscii As Byte, LastAscii As Byte) As String()\nDim strarrTemp() As String, i&\n\n    ReDim strarrTemp(0 To LastAscii - FirstAscii)\n    For i = FirstAscii To LastAscii\n        strarrTemp(i - FirstAscii) = Chr(i)\n    Next\n    Alphabet = strarrTemp\n    Erase strarrTemp\nEnd Function\n","human_summarization":"generate an array, list, or string of all lower case ASCII characters from 'a' to 'z'. It demonstrates both accessing a standard library sequence and generating a similar sequence manually, using a reliable coding style and strong typing if available. The code avoids manually enumerating all the lowercase characters to prevent bugs. It is also compatible with VB6 without any changes.","id":2187}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version VB6 Standard\nPublic Function Bin(ByVal l As Long) As String\nDim i As Long\n  If l Then\n    If l And &H80000000 Then 'negative number\n      Bin = \"1\" & String$(31, \"0\")\n      l = l And (Not &H80000000)\n      \n      For i = 0 To 30\n      If l And (2& ^ i) Then\n        Mid$(Bin, Len(Bin) - i) = \"1\"\n      End If\n      Next i\n      \n    Else                     'positive number\n      Do While l\n      If l Mod 2 Then\n        Bin = \"1\" & Bin\n      Else\n        Bin = \"0\" & Bin\n      End If\n      l = l \\ 2\n      Loop\n    End If\n  Else\n    Bin = \"0\"                'zero\n  End If\nEnd Function\n\n'testing:\nPublic Sub Main()\n  Debug.Print Bin(5)\n  Debug.Print Bin(50)\n  Debug.Print Bin(9000)\nEnd Sub\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":2188}
    {"lang_cluster":"Visual_Basic","source_code":"\n' Configuration file parser routines.\n'\n' (c) Copyright 1993 - 2011 Mark Hobley\n'\n' This configuration parser contains code ported from an application program\n' written in Microsoft Quickbasic\n'\n' This code can be redistributed or modified under the terms of version 1.2 of\n' the GNU Free Documentation Licence as published by the Free Software Foundation.\n\nSub readini()\n  var.filename = btrim$(var.winpath) & ini.inifile\n  var.filebuffersize = ini.inimaxlinelength\n  Call openfileread\n  If flg.error = \"Y\" Then\n    flg.abort = \"Y\"\n    Exit Sub\n  End If\n  If flg.exists <> \"Y\" Then\n    flg.abort = \"Y\"\n    Exit Sub\n  End If\n  var.inistream = var.stream\nreadinilabela:\n  Call readlinefromfile\n  If flg.error = \"Y\" Then\n    flg.abort = \"Y\"\n    Call closestream\n    flg.error = \"Y\"\n    Exit Sub\n  End If\n  If flg.endoffile <> \"Y\" Then\n    iniline$ = message$\n    If iniline$ <> \"\" Then\n      If Left$(iniline$, 1) <> ini.commentchar AND Left$(iniline$, 1) <> ini.ignorechar Then\n        endofinicommand% = 0\n        For l% = 1 To Len(iniline$)\n          If Mid$(iniline$, l%, 1) < \" \" Then\n            endofinicommand% = l%\n          End If\n          If Not (endofinicommand%) Then\n            If Mid$(iniline$, l%, 1) = \" \" Then\n              endofinicommand% = l%\n            End If\n          End If\n          If endofinicommand% Then\n            l% = Len(iniline$)\n          End If\n        Next l%\n        iniarg$ = \"\"\n        If endofinicommand% Then\n          If endofinicommand% <> Len(iniline$) Then\n            iniarg$ = btrim$(Mid$(iniline$, endofinicommand% + 1))\n            If iniarg$ = \"\" Then\n              GoTo readinilabelb\n            End If\n            inicommand$ = Left$(iniline$, endofinicommand% - 1)\n          End If\n        Else\n          inicommand$ = btrim$(iniline$)\n        End If\nreadinilabelb:\n        'interpret command\n        inicommand$ = UCase$(inicommand$)\n        Select Case inicommand$\n          Case \"FULLNAME\"\n            If iniarg$ <> \"\" Then\n              ini.fullname = iniarg$\n            End If\n          Case \"FAVOURITEFRUIT\"\n            If iniarg$ <> \"\" Then\n              ini.favouritefruit = iniarg$\n            End If\n          Case \"NEEDSPEELING\"\n            ini.needspeeling = \"Y\"\n          Case \"SEEDSREMOVED\"\n            ini.seedsremoved = \"Y\"\n          Case \"OTHERFAMILY\"\n            If iniarg$ <> \"\" Then\n              ini.otherfamily = iniarg$\n              CALL familyparser\n            End If\n          Case Else\n            '!! error handling required\n        End Select\n      End If\n    End If\n    GoTo readinilabela\n  End If\n  Call closestream\n  Exit Sub\nreadinierror:\n\nEnd Sub\n\nSub openfileread()\n  flg.streamopen = \"N\"\n  Call checkfileexists\n  If flg.error = \"Y\" Then Exit Sub\n  If flg.exists <> \"Y\" Then Exit Sub\n  Call getfreestream\n  If flg.error = \"Y\" Then Exit Sub\n  var.errorsection = \"Opening File\"\n  var.errordevice = var.filename\n  If ini.errortrap = \"Y\" Then\n    On Local Error GoTo openfilereaderror\n  End If\n  flg.endoffile = \"N\"\n  Open var.filename For Input As #var.stream Len = var.filebuffersize\n  flg.streamopen = \"Y\"\n  Exit Sub\nopenfilereaderror:\n  var.errorcode = Err\n  Call errorhandler\n  resume '!!\nEnd Sub\n\nPublic Sub checkfileexists()\n  var.errorsection = \"Checking File Exists\"\n  var.errordevice = var.filename\n  If ini.errortrap = \"Y\" Then\n    On Local Error GoTo checkfileexistserror\n  End If\n  flg.exists = \"N\"\n  If Dir$(var.filename, 0) <> \"\" Then\n    flg.exists = \"Y\"\n  End If\n  Exit Sub\ncheckfileexistserror:\n  var.errorcode = Err\n  Call errorhandler\nEnd Sub\n\nPublic Sub getfreestream()\n  var.errorsection = \"Opening Free Data Stream\"\n  var.errordevice = \"\"\n  If ini.errortrap = \"Y\" Then\n    On Local Error GoTo getfreestreamerror\n  End If\n  var.stream = FreeFile\n  Exit Sub\ngetfreestreamerror:\n  var.errorcode = Err\n  Call errorhandler\n  resume '!!\nEnd Sub\n\nSub closestream()\n  If ini.errortrap = \"Y\" Then\n    On Local Error GoTo closestreamerror\n  End If\n  var.errorsection = \"Closing Stream\"\n  var.errordevice = \"\"\n  flg.resumenext = \"Y\"\n  Close #var.stream\n  If flg.error = \"Y\" Then\n    flg.error = \"N\"\n    '!! Call unexpectederror\n  End If\n  flg.streamopen = \"N\"\n  Exit Sub\nclosestreamerror:\n  var.errorcode = Err\n  Call errorhandler\n  resume next\nEnd Sub\n\nSub readlinefromfile()\n  If ini.errortrap = \"Y\" Then\n    On Local Error GoTo readlinefromfileerror\n  End If\n  If EOF(var.stream) Then\n    flg.endoffile = \"Y\"\n    Exit Sub\n  End If\n  Line Input #var.stream, tmp$\n  message$ = tmp$\n  Exit Sub\nreadlinefromfileerror:\n  var.errorcode = Err\n  Call errorhandler\n  resume '!!\nEnd Sub\n\nPublic Sub errorhandler()\n  tmp$ = btrim$(var.errorsection)\n  tmp2$ = btrim$(var.errordevice)\n  If tmp2$ <> \"\" Then\n    tmp$ = tmp$ + \" (\" + tmp2$ + \")\"\n  End If\n  tmp$ = tmp$ + \"\u00a0: \" + Str$(var.errorcode)\n  tmp1% = MsgBox(tmp$, 0, \"Error!\")\n  flg.error = \"Y\"\n  If flg.resumenext = \"Y\" Then\n    flg.resumenext = \"N\"\n'    Resume Next\n  Else\n    flg.error = \"N\"\n'    Resume\n  End If\nEnd Sub\n\nPublic Function btrim$(arg$)\n  btrim$ = LTrim$(RTrim$(arg$))\nEnd Function\n\n","human_summarization":"read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.","id":2189}
    {"lang_cluster":"Visual_Basic","source_code":"\nLibrary: Microsoft.WinHttp\nWorks with: Visual Basic version 5\nWorks with: Visual Basic version 6\nWorks with: VBA version Access 97\nWorks with: VBA version 6.5\nWorks with: VBA version 7.1\nSub Main()\nDim HttpReq As WinHttp.WinHttpRequest\n'  in the \"references\" dialog of the IDE, check\n'  \"Microsoft WinHTTP Services, version 5.1\" (winhttp.dll)\nConst HTTPREQUEST_PROXYSETTING_PROXY As Long = 2\n#Const USE_PROXY = 1\n  Set HttpReq = New WinHttp.WinHttpRequest\n  HttpReq.Open \"GET\", \"http:\/\/rosettacode.org\/robots.txt\"\n#If USE_PROXY Then\n  HttpReq.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, \"my_proxy:80\"\n#End If\n  HttpReq.SetTimeouts 1000, 1000, 1000, 1000\n  HttpReq.Send\n  Debug.Print HttpReq.ResponseText\nEnd Sub\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":2190}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version VB6 Standard\nPublic Function LuhnCheckPassed(ByVal dgts As String) As Boolean\nDim i As Long, s As Long, s1 As Long\n  dgts = VBA.StrReverse(dgts)\n    For i = 1 To Len(dgts) Step 2\n        s = s + CInt(Mid$(dgts, i, 1))\n    Next i\n    For i = 2 To Len(dgts) Step 2\n        s1 = 2 * (CInt(Mid$(dgts, i, 1)))\n        If s1 >= 10 Then\n            s = s - 9\n        End If\n        s = s + s1\n    Next i\n  LuhnCheckPassed = Not CBool(s Mod 10)\nEnd Function\n\nSub Main()\n  Debug.Assert LuhnCheckPassed(\"49927398716\")\n  Debug.Assert Not LuhnCheckPassed(\"49927398717\")\n  Debug.Assert Not LuhnCheckPassed(\"1234567812345678\")\n  Debug.Assert LuhnCheckPassed(\"1234567812345670\")\nEnd Sub\n","human_summarization":"The code validates credit card numbers using the Luhn test. It first reverses the order of the digits in the number, then calculates two partial sums: s1 from the sum of every other odd digit, and s2 from the sum of each even digit multiplied by two (if the result is greater than nine, the digits are summed). If the total sum (s1 + s2) ends in zero, the number is validated as a credit card number. The function is used to validate four specific numbers.","id":2191}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version VB6 Standard\n\nPublic Function StrRepeat(s As String, n As Integer) As String\n\tDim r As String, i As Integer\n\tr = \"\"\n\tFor i = 1 To n\n\t\tr = r & s\n\tNext i\n\tStrRepeat = r\nEnd Function\n \nDebug.Print StrRepeat(\"ha\", 5)\n\n","human_summarization":"\"Code repeats a given string or character a specified number of times.\"","id":2192}
    {"lang_cluster":"Visual_Basic","source_code":"\nSub arrShellSort(ByVal arrData As Variant)\n  Dim lngHold, lngGap As Long\n  Dim lngCount, lngMin, lngMax As Long\n  Dim varItem As Variant\n  '\n  lngMin = LBound(arrData)\n  lngMax = UBound(arrData)\n  lngGap = lngMin\n  Do While (lngGap < lngMax)\n    lngGap = 3 * lngGap + 1\n  Loop\n  Do While (lngGap > 1)\n    lngGap = lngGap \\ 3\n    For lngCount = lngGap + lngMin To lngMax\n      varItem = arrData(lngCount)\n      lngHold = lngCount\n      Do While ((arrData(lngHold - lngGap) > varItem))\n        arrData(lngHold) = arrData(lngHold - lngGap)\n        lngHold = lngHold - lngGap\n        If (lngHold < lngMin + lngGap) Then Exit Do\n      Loop\n      arrData(lngHold) = varItem\n    Next\n  Loop\n  arrShellSort = arrData\nEnd Sub'\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":2193}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version 5\nWorks with: Visual Basic version 6\nLibrary: Win32\nOption Explicit\n\nPrivate Type BITMAP\n  bmType As Long\n  bmWidth As Long\n  bmHeight As Long\n  bmWidthBytes As Long\n  bmPlanes As Integer\n  bmBitsPixel As Integer\n  bmBits As Long\nEnd Type\n\nPrivate Type RGB\n  Red As Byte\n  Green As Byte\n  Blue As Byte\n  Alpha As Byte\nEnd Type\n\nPrivate Type RGBColor\n  Color As Long\nEnd Type\n\nPublic Declare Function CreateCompatibleDC Lib \"gdi32.dll\" (ByVal hdc As Long) As Long\nPublic Declare Function GetObjectA Lib \"gdi32.dll\" (ByVal hObject As Long, ByVal nCount As Long, ByRef lpObject As Any) As Long\nPublic Declare Function SelectObject Lib \"gdi32.dll\" (ByVal hdc As Long, ByVal hObject As Long) As Long\nPublic Declare Function GetPixel Lib \"gdi32.dll\" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long) As Long\nPublic Declare Function SetPixel Lib \"gdi32.dll\" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long, ByVal crColor As Long) As Long\nPublic Declare Function DeleteDC Lib \"gdi32.dll\" (ByVal hdc As Long) As Long\n\n\nSub Main()\nDim p As stdole.IPictureDisp\nDim hdc As Long\nDim bmp As BITMAP\nDim i As Long, x As Long, y As Long\nDim tRGB As RGB, cRGB As RGBColor\n\nSet p = VB.LoadPicture(\"T:\\TestData\\Input_Colored.bmp\")\nGetObjectA p.Handle, Len(bmp), bmp\n\nhdc = CreateCompatibleDC(0)\nSelectObject hdc, p.Handle\n\nFor x = 0 To bmp.bmWidth - 1\n  For y = 0 To bmp.bmHeight - 1\n    cRGB.Color = GetPixel(hdc, x, y)\n    LSet tRGB = cRGB\n    i = (0.2126 * tRGB.Red + 0.7152 * tRGB.Green + 0.0722 * tRGB.Blue)\n    SetPixel hdc, x, y, RGB(i, i, i)\n  Next y\nNext x\n\nVB.SavePicture p, \"T:\\TestData\\Output_GrayScale.bmp\"\nDeleteDC hdc\n\nEnd Sub\n\n","human_summarization":"extend the data storage type to support grayscale images, define operations to convert a color image to grayscale and vice versa using the CIE recommended formula for luminance, and ensure no rounding errors or distorted results occur when storing calculated luminance as an unsigned integer.","id":2194}
    {"lang_cluster":"Visual_Basic","source_code":"\n\nVERSION 5.00\nBegin VB.Form Form1\n   Begin VB.Timer Timer1\n      Interval = 250\n   End\n   Begin VB.Label Label1\n      AutoSize = -1  'True\n      Caption  = \"Hello World! \"\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n'Everything above this line is hidden when in the IDE.\n\nPrivate goRight As Boolean\n\nPrivate Sub Label1_Click()\n    goRight = Not goRight\nEnd Sub\n\nPrivate Sub Timer1_Timer()\n    If goRight Then\n        x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)\n    Else\n        x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)\n    End If\n    Label1.Caption = x\nEnd Sub\n\n","human_summarization":"create a GUI window displaying a rotating \"Hello World!\" text. The rotation direction of the text changes whenever the user clicks on it. The rotation is achieved by periodically moving one letter from the end of the string to the front. The animation remains responsive to user interactions.","id":2195}
    {"lang_cluster":"Visual_Basic","source_code":"\nModule ByteLength\n    Function GetByteLength(s As String, encoding As Text.Encoding) As Integer\n        Return encoding.GetByteCount(s)\n    End Function\nEnd Module\nModule CharacterLength\n    Function GetUTF16CodeUnitsLength(s As String) As Integer\n        Return s.Length\n    End Function\n\n    Private Function GetUTF16SurrogatePairCount(s As String) As Integer\n        GetUTF16SurrogatePairCount = 0\n        For i = 1 To s.Length - 1\n            If Char.IsSurrogatePair(s(i - 1), s(i)) Then GetUTF16SurrogatePairCount += 1\n        Next\n    End Function\n\n    Function GetCharacterLength_FromUTF16(s As String) As Integer\n        Return GetUTF16CodeUnitsLength(s) - GetUTF16SurrogatePairCount(s)\n    End Function\n\n    Function GetCharacterLength_FromUTF32(s As String) As Integer\n        Return GetByteLength(s, Text.Encoding.UTF32) \\ 4\n    End Function\nEnd Module\nModule GraphemeLength\n    ' Wraps an IEnumerator, allowing it to be used as an IEnumerable.\n    Private Iterator Function AsEnumerable(enumerator As IEnumerator) As IEnumerable\n        Do While enumerator.MoveNext()\n            Yield enumerator.Current\n        Loop\n    End Function\n\n    Function GraphemeCount(s As String) As Integer\n        Dim elements = Globalization.StringInfo.GetTextElementEnumerator(s)\n        Return AsEnumerable(elements).OfType(Of String).Count()\n    End Function\nEnd Module\n#Const PRINT_TESTCASE = True\nModule Program\n    ReadOnly TestCases As String() =\n    {\n        \"Hello, world!\",\n        \"m\u00f8\u00f8se\",\n        \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\", ' String normalization of the file makes the e and diacritic in \u00e9\u0332 one character, so use VB's char \"escapes\"\n        $\"J{ChrW(&H332)}o{ChrW(&H332)}s{ChrW(&H332)}e{ChrW(&H301)}{ChrW(&H332)}\"\n    }\n\n    Sub Main()\n        Const INDENT = \"    \"\n        Console.OutputEncoding = Text.Encoding.Unicode\n\n        Dim writeResult = Sub(s As String, result As Integer) Console.WriteLine(\"{0}{1,-20}{2}\", INDENT, s, result)\n\n        For i = 0 To TestCases.Length - 1\n            Dim c = TestCases(i)\n\n            Console.Write(\"Test case \" & i)\n#If PRINT_TESTCASE Then\n            Console.WriteLine(\": \" & c)\n#Else\n            Console.WriteLine()\n#End If\n            writeResult(\"graphemes\", GraphemeCount(c))\n            writeResult(\"UTF-16 units\", GetUTF16CodeUnitsLength(c))\n            writeResult(\"Cd pts from UTF-16\", GetCharacterLength_FromUTF16(c))\n            writeResult(\"Cd pts from UTF-32\", GetCharacterLength_FromUTF32(c))\n            Console.WriteLine()\n            writeResult(\"bytes (UTF-8)\", GetByteLength(c, Text.Encoding.UTF8))\n            writeResult(\"bytes (UTF-16)\", GetByteLength(c, Text.Encoding.Unicode))\n            writeResult(\"bytes (UTF-32)\", GetByteLength(c, Text.Encoding.UTF32))\n            Console.WriteLine()\n        Next\n\n    End Sub\nEnd Module\n","human_summarization":"determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. The character count is based on individual Unicode code points, not user-visible graphemes. The code also handles non-BMP code points correctly, providing the actual character counts in code points, not in code unit counts. It also has the capability to provide the string length in graphemes if the language supports it.","id":2196}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version 4\nWorks with: Visual Basic version 5\nWorks with: Visual Basic version 6\nDim onlyInstance as Boolean\nonlyInstance = not App.PrevInstance\n\n","human_summarization":"\"Check if an application instance is already running, display a message if so, and terminate the program.\"","id":2197}
    {"lang_cluster":"Visual_Basic","source_code":"\n\nTYPE syswindowstru\n  screenheight AS INTEGER\n  screenwidth AS INTEGER\n  maxheight AS INTEGER\n  maxwidth AS INTEGER\nEND TYPE\n\nDIM syswindow AS syswindowstru\n\n' Determine the height and width of the screen\n\nsyswindow.screenwidth = Screen.Width \/ Screen.TwipsPerPixelX\nsyswindow.screenheight=Screen.Height \/ Screen.TwipsPerPixelY\n\n' Make adjustments for window decorations and menubars\n\n\n","human_summarization":"determine the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations, menubars, multiple monitors, and tiling window managers. It either queries the screen dimensions and subtracts pixels used by the frame and desktop bars, or creates a maximized form and queries its dimensions.","id":2198}
    {"lang_cluster":"Visual_Basic","source_code":"\nstrUserIn = InputBox(\"Enter Data\")\nWscript.Echo strUserIn\n","human_summarization":"The code enables the input of a string and the integer 75000 via a graphical user interface, potentially using a form created in the IDE. This functionality can be implemented using Visual Basic, with possible adaptations from VBScript or PowerBASIC examples.","id":2199}
    {"lang_cluster":"Visual_Basic","source_code":"\nLibrary: Microsoft.WinHttp\nWorks with: Visual Basic version 5\nWorks with: Visual Basic version 6\nWorks with: VBA version Access 97\nWorks with: VBA version 6.5\nWorks with: VBA version 7.1\nSub Main()\nDim HttpReq As WinHttp.WinHttpRequest\n'  in the \"references\" dialog of the IDE, check\n'  \"Microsoft WinHTTP Services, version 5.1\" (winhttp.dll)\nConst HTTPREQUEST_PROXYSETTING_PROXY        As Long = 2\nConst WINHTTP_FLAG_SECURE_PROTOCOL_TLS1     As Long = &H80&\nConst WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1   As Long = &H200&\nConst WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2   As Long = &H800&\n#Const USE_PROXY = 1\n  Set HttpReq = New WinHttp.WinHttpRequest\n  HttpReq.Open \"GET\", \"https:\/\/groups.google.com\/robots.txt\"\n  HttpReq.Option(WinHttpRequestOption_SecureProtocols) = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 Or _\n                                                         WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 Or _\n                                                         WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2\n#If USE_PROXY Then\n  HttpReq.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, \"my_proxy:80\"\n#End If\n  HttpReq.SetTimeouts 1000, 1000, 1000, 1000\n  HttpReq.Send\n  Debug.Print HttpReq.ResponseText\nEnd Sub\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":2200}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version 5\nWorks with: Visual Basic version 6\nWorks with: VBA version 6.5\nWorks with: VBA version 7.1\nPublic Function CommonDirectoryPath(ParamArray Paths()) As String\nDim v As Variant\nDim Path() As String, s As String\nDim i As Long, j As Long, k As Long\nConst PATH_SEPARATOR As String = \"\/\"\n  \n  For Each v In Paths\n    ReDim Preserve Path(0 To i)\n    Path(i) = v\n    i = i + 1\n  Next v\n  \n  k = 1\n  \n  Do\n    For i = 0 To UBound(Path)\n      If i Then\n        If InStr(k, Path(i), PATH_SEPARATOR) <> j Then\n          Exit Do\n        ElseIf Left$(Path(i), j) <> Left$(Path(0), j) Then\n          Exit Do\n        End If\n      Else\n        j = InStr(k, Path(i), PATH_SEPARATOR)\n        If j = 0 Then\n          Exit Do\n        End If\n      End If\n    Next i\n    s = Left$(Path(0), j + CLng(k <> 1))\n    k = j + 1\n  Loop\n  CommonDirectoryPath = s\n  \nEnd Function\n\nSub Main()\n\n' testing the above function\n\nDebug.Assert CommonDirectoryPath( _\n \"\/home\/user1\/tmp\/coverage\/test\", _\n \"\/home\/user1\/tmp\/covert\/operator\", _\n \"\/home\/user1\/tmp\/coven\/members\") = _\n \"\/home\/user1\/tmp\"\n \n Debug.Assert CommonDirectoryPath( _\n \"\/home\/user1\/tmp\/coverage\/test\", _\n \"\/home\/user1\/tmp\/covert\/operator\", _\n \"\/home\/user1\/tmp\/coven\/members\", _\n \"\/home\/user1\/abc\/coven\/members\") = _\n \"\/home\/user1\"\n\nDebug.Assert CommonDirectoryPath( _\n \"\/home\/user1\/tmp\/coverage\/test\", _\n \"\/hope\/user1\/tmp\/covert\/operator\", _\n \"\/home\/user1\/tmp\/coven\/members\") = _\n \"\/\"\n\nEnd Sub\n\n","human_summarization":"The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '\/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.","id":2201}
    {"lang_cluster":"Visual_Basic","source_code":"\n\nSub Main\n    MsgBox Command$\nEnd Sub\n","human_summarization":"retrieve and print the list of command-line arguments provided to the program. It also parses the arguments intelligently. For instance, if the command line is 'myprogram -c \"alpha beta\" -h \"gamma\"', the code will handle these arguments appropriately. In Visual Basic, these arguments are returned in the built-in variable Command$.","id":2202}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version 5\nWorks with: Visual Basic version 6\nWorks with: VBA version Access 97\nWorks with: VBA version 6.5\nWorks with: VBA version 7.1\nOption Explicit\n\nPrivate Declare Function GetComputerName Lib \"kernel32.dll\" Alias \"GetComputerNameW\" _\n  (ByVal lpBuffer As Long, ByRef nSize As Long) As Long\n \nPrivate Const MAX_COMPUTERNAME_LENGTH As Long = 31\nPrivate Const NO_ERR As Long = 0\n\nPrivate Function Hostname() As String\nDim i As Long, l As Long, s As String\n  s = Space$(MAX_COMPUTERNAME_LENGTH)\n  l = Len(s) + 1\n  i = GetComputerName(StrPtr(s), l)\n  Debug.Assert i <> 0\n  Debug.Assert l <> 0\n  Hostname = Left$(s, l)\nEnd Function\n\nSub Main()\n  Debug.Assert Hostname() = Environ$(\"COMPUTERNAME\")\nEnd Sub\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":2203}
    {"lang_cluster":"Visual_Basic","source_code":"\nOption Explicit\n\nSub String_Concatenation()\nDim str1 As String, str2 As String\n\n    str1 = \"Rosetta\"\n    Debug.Print str1\n    Debug.Print str1 & \" code!\"\n    str2 = str1 & \" code...\"\n    Debug.Print str2 & \" based on concatenation of : \" & str1 & \" and code...\"\nEnd Sub\n","human_summarization":"initializes two string variables, concatenates the second string with another string literal, and displays the content of the variables.","id":2204}
    {"lang_cluster":"Visual_Basic","source_code":"\n\nVERSION 5.00\nBegin VB.Form Form2 \n   Caption         =   \"There have been no clicks yet\"\n   ClientHeight    =   2940\n   ClientLeft      =   60\n   ClientTop       =   600\n   ClientWidth     =   8340\n   LinkTopic       =   \"Form1\"\n   ScaleHeight     =   2940\n   ScaleWidth      =   8340\n   StartUpPosition =   3  'Windows Default\n   Begin VB.CommandButton Command1 \n      Caption         =   \"Click me!\"\n      Height          =   495\n      Left            =   3600\n      TabIndex        =   0\n      Top             =   1200\n      Width           =   1215\n   End\nEnd\nAttribute VB_Name = \"Form1\"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = False\n'-----user-written code begins here; everything above this line is hidden in the GUI-----\nPrivate clicked As Long\n\nPrivate Sub Command1_Click()\n    clicked = clicked + 1\n    Me.Caption = clicked & \" clicks.\"\nEnd Sub\n\n","human_summarization":"implement a windowed application in VB. The application features a label initially displaying \"There have been no clicks yet\" and a button labeled \"click me\". The label updates to show the number of times the button has been clicked each time the button is clicked. The window creation process is typically handled in the IDE and the generated code is usually hidden from the programmer.","id":2205}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version 5\nWorks with: Visual Basic version 6\nWorks with: VBA version Access 97\nWorks with: VBA version 6.5\nWorks with: VBA version 7.1\nOption Explicit\n\nSub Main()\nConst VECSIZE As Long = 3350\nConst BUFSIZE As Long = 201\nDim buffer(1 To BUFSIZE) As Long\nDim vect(1 To VECSIZE) As Long\nDim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long\n\n  For n = 1 To VECSIZE\n    vect(n) = 2\n  Next n\n  For n = 1 To BUFSIZE\n    karray = 0\n    For l = VECSIZE To 1 Step -1\n      num = 100000 * vect(l) + karray * l\n      karray = num \\ (2 * l - 1)\n      vect(l) = num - karray * (2 * l - 1)\n    Next l\n    k = karray \\ 100000\n    buffer(n) = more + k\n    more = karray - k * 100000\n  Next n\n  Debug.Print CStr(buffer(1));\n  Debug.Print \".\"\n  l = 0\n  For n = 2 To BUFSIZE\n    Debug.Print Format$(buffer(n), \"00000\");\n    l = l + 1\n    If l = 10 Then\n      l = 0\n      Debug.Print 'line feed\n    End If\n  Next n\nEnd Sub\n\n\n","human_summarization":"are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.","id":2206}
    {"lang_cluster":"Visual_Basic","source_code":"Works with: Visual Basic version VB6 Standard\nOption Explicit\nDim calls As Long\nSub main()\n    Const maxi = 4\n    Const maxj = 9\n    Dim i As Long, j As Long\n    For i = 0 To maxi\n        For j = 0 To maxj\n            Call print_acker(i, j)\n        Next j\n    Next i\nEnd Sub 'main\nSub print_acker(m As Long, n As Long)\n    calls = 0\n    Debug.Print \"ackermann(\"; m; \",\"; n; \")=\";\n    Debug.Print ackermann(m, n), \"calls=\"; calls\nEnd Sub 'print_acker\nFunction ackermann(m As Long, n As Long) As Long\n    calls = calls + 1\n    If m = 0 Then\n        ackermann = n + 1\n    Else\n        If n = 0 Then\n            ackermann = ackermann(m - 1, 1)\n        Else\n            ackermann = ackermann(m - 1, ackermann(m, n - 1))\n        End If\n    End If\nEnd Function 'ackermann\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":2207}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version VB6 Standard'N-queens problem - non recursive & structured - vb6 - 25\/02\/2017\nSub n_queens()\n    Const l = 15  'number of queens\n    Const b = False  'print option\n    Dim a(l), s(l), u(4 * l - 2)\n    Dim n, m, i, j, p, q, r, k, t, z\n    For i = 1 To UBound(a): a(i) = i: Next i\n    For n = 1 To l\n        m = 0\n        i = 1\n        j = 0\n        r = 2 * n - 1\n        Do\n            i = i - 1\n            j = j + 1\n            p = 0\n            q = -r\n            Do\n                i = i + 1\n                u(p) = 1\n                u(q + r) = 1\n                z = a(j): a(j) = a(i): a(i) = z  'Swap a(i), a(j)\n                p = i - a(i) + n\n                q = i + a(i) - 1\n                s(i) = j\n                j = i + 1\n            Loop Until j > n Or u(p) Or u(q + r)\n            If u(p) = 0 Then\n                If u(q + r) = 0 Then\n                    m = m + 1  'm: number of solutions\n                    If b Then\n                        Debug.Print \"n=\"; n; \"m=\"; m\n                        For k = 1 To n\n                            For t = 1 To n\n                                Debug.Print IIf(a(n - k + 1) = t, \"Q\", \".\");\n                            Next t\n                            Debug.Print\n                        Next k\n                    End If\n                End If\n            End If\n            j = s(i)\n            Do While j >= n And i <> 0\n                Do\n                    z = a(j): a(j) = a(i): a(i) = z  'Swap a(i), a(j)\n                    j = j - 1\n                Loop Until j < i\n                i = i - 1\n                p = i - a(i) + n\n                q = i + a(i) - 1\n                j = s(i)\n                u(p) = 0\n                u(q + r) = 0\n            Loop\n        Loop Until i = 0\n        Debug.Print n, m  'number of queens, number of solutions\n    Next n\nEnd Sub 'n_queens\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":2208}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version VB6 Standard\n'Knapsack problem\/0-1 - 12\/02\/2017\nOption Explicit\nConst maxWeight = 400\nDim DataList As Variant\nDim xList(64, 3) As Variant\nDim nItems As Integer\nDim s  As String, xss As String\nDim xwei As Integer, xval As Integer, nn As Integer\n\nPrivate Sub Form_Load()\n    Dim i As Integer, j As Integer\n    DataList = Array(\"map\", 9, 150, \"compass\", 13, 35, \"water\", 153, 200, \"sandwich\", 50, 160, _\n           \"glucose\", 15, 60, \"tin\", 68, 45, \"banana\", 27, 60, \"apple\", 39, 40, _\n           \"cheese\", 23, 30, \"beer\", 52, 10, \"suntan cream\", 11, 70, \"camera\", 32, 30, _\n           \"T-shirt\", 24, 15, \"trousers\", 48, 10, \"umbrella\", 73, 40, \"book\", 30, 10, _\n           \"waterproof trousers\", 42, 70, \"waterproof overclothes\", 43, 75, _\n           \"note-case\", 22, 80, \"sunglasses\", 7, 20, \"towel\", 18, 12, \"socks\", 4, 50)\n    nItems = (UBound(DataList) + 1) \/ 3\n    j = 0\n    For i = 1 To nItems\n        xList(i, 1) = DataList(j)\n        xList(i, 2) = DataList(j + 1)\n        xList(i, 3) = DataList(j + 2)\n        j = j + 3\n    Next i\n    For i = 1 To nItems\n        xListBox.AddItem xList(i, 1)\n    Next i\nEnd Sub\n\nPrivate Sub cmdOK_Click()\n    Dim i As Integer, j As Integer\n    For i = 1 To xListBox.ListCount\n        xListBox.RemoveItem 0\n    Next i\n    s = \"\"\n    For i = 1 To nItems\n        s = s & Chr(i)\n    Next\n    nn = 0\n    Call ChoiceBin(1, \"\")\n    For i = 1 To Len(xss)\n        j = Asc(Mid(xss, i, 1))\n        xListBox.AddItem xList(j, 1)\n    Next i\n    xListBox.AddItem \"*Total* \" & xwei & \" \" & xval\nEnd Sub\n\nPrivate Sub ChoiceBin(n As String, ss As String)\n    Dim r As String\n    Dim i As Integer, j As Integer, iwei As Integer, ival As Integer\n    Dim ipct As Integer\n    If n = Len(s) + 1 Then\n        iwei = 0: ival = 0\n        For i = 1 To Len(ss)\n            j = Asc(Mid(ss, i, 1))\n            iwei = iwei + xList(j, 2)\n            ival = ival + xList(j, 3)\n        Next\n        If iwei <= maxWeight And ival > xval Then\n            xss = ss: xwei = iwei: xval = ival\n        End If\n    Else\n        r = Mid(s, n, 1)\n        Call ChoiceBin(n + 1, ss & r)\n        Call ChoiceBin(n + 1, ss)\n    End If\nEnd Sub 'ChoiceBin\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":2209}
    {"lang_cluster":"Visual_Basic","source_code":"\nOption Explicit\n\nPrivate Declare Function Beep Lib \"kernel32\" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long\nPrivate Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)\n\nPrivate Const MORSE_ALPHA As String = \".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--..\"\nPrivate Const MORSE_NUMERIC As String = \"-----,.----,..---,...--,....-,.....,-....,--...,---..,----.\"\n\nPrivate Const ONE_UNIT As Integer = 100\n\nPrivate Const BEEP_DOT As Integer = ONE_UNIT\nPrivate Const BEEP_DASH As Integer = 3 * ONE_UNIT\nPrivate Const BEEP_OTHER As Integer = 7 * ONE_UNIT\nPrivate Const DELAY As Integer = ONE_UNIT\nPrivate Const LETTERS_DELAY As Integer = 3 * ONE_UNIT\nPrivate Const SPACE_DELAY As Integer = 7 * ONE_UNIT\n\nPrivate Const FREQUENCY_CHARS As Integer = 1200\nPrivate Const FREQUENCY_OTHERCHARS As Integer = 400\n\nSub Main()\nDim p$, temp$\n    p = ToMorse(\"Hel\/lo 123 world\")\n    temp = Replace(p, \"+\", \"\")\n    Debug.Print Replace(temp, \"_\", \"\")\n    PlayMorse p\nEnd Sub\n\nPrivate Function ToMorse(s As String) As String\nDim i&, t$, j&\n    s = UCase(s)\n    For i = 1 To Len(s)\n        j = Asc(Mid(s, i, 1))\n        Select Case j\n            Case 65 To 90 'alpha\n                t = t & Split(MORSE_ALPHA, \",\")(j - 65) & \"+\" ' \"+\" ==> separate each characters\n            Case 48 To 57 'numerics\n                t = t & Split(MORSE_NUMERIC, \",\")(j - 48) & \"+\"\n            Case 32 'space\n                t = t & \" \" & \"+\"\n            Case Else 'others\n                t = t & \"_\" & \"+\"\n        End Select\n    Next i\n    ToMorse = t\nEnd Function\n\nPrivate Sub PlayMorse(s As String)\nDim i&\n    For i = 1 To Len(s)\n        Select Case Mid(s, i, 1)\n            Case \".\": Beep FREQUENCY_CHARS, BEEP_DOT\n            Case \"-\": Beep FREQUENCY_CHARS, BEEP_DASH\n            Case \"_\": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER\n            Case \"+\": Sleep LETTERS_DELAY\n            Case \" \": Sleep SPACE_DELAY\n        End Select\n        Sleep DELAY\n    Next i\nEnd Sub\n","human_summarization":"The code takes a string input and converts it into audible Morse code, which is then sent to an audio device such as a PC speaker. It handles unknown characters by either ignoring them or indicating them with a different pitch. The code is compatible with both VBA and VB6 without any modifications.","id":2210}
    {"lang_cluster":"Visual_Basic","source_code":"\nWorks with: Visual Basic version VB6 Standard\nDebug.Print Environ$(\"PATH\")\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":2211}
    {"lang_cluster":"SQL","source_code":"\n\nselect round ( exp ( sum (ln ( ( 1 + sqrt( 5 ) ) \/ 2)\n        ) over ( order by level ) ) \/ sqrt( 5 ) ) fibo\nfrom dual\nconnect by level <= 10;\n       FIB\n----------\n         1\n         1\n         2\n         3\n         5\n         8\n        13\n        21\n        34\n        55\n\n10 rows selected.\n\n\nselect round ( power( ( 1 + sqrt( 5 ) ) \/ 2, level ) \/ sqrt( 5 ) ) fib\nfrom dual\nconnect by level <= 10;\n       FIB\n----------\n         1\n         1\n         2\n         3\n         5\n         8\n        13\n        21\n        34\n        55\n\n10 rows selected.\n\nWorks with: Oracle\n\nSQL> with fib(e,f) as (select 1, 1 from dual union all select e+f,e from fib where e <= 55) select f from fib;\n\n         F\n----------\n         1\n         1\n         2\n         3\n         5\n         8\n        13\n        21\n        34\n        55\n\n10 rows selected.\nWorks with: PostgreSQL\nCREATE FUNCTION fib(n int) RETURNS numeric AS $$\n    -- This recursive with generates endless list of Fibonacci numbers.\n    WITH RECURSIVE fibonacci(current, previous) AS (\n        -- Initialize the current with 0, so the first value will be 0.\n        -- The previous value is set to 1, because its only goal is not\n        -- special casing the zero case, and providing 1 as the second\n        -- number in the sequence.\n        --\n        -- The numbers end with dots to make them numeric type in\n        -- Postgres. Numeric type has almost arbitrary precision\n        -- (technically just 131,072 digits, but that's good enough for\n        -- most purposes, including calculating huge Fibonacci numbers)\n        SELECT 0., 1.\n    UNION ALL\n        -- To generate Fibonacci number, we need to add together two\n        -- previous Fibonacci numbers. Current number is saved in order\n        -- to be accessed in the next iteration of recursive function.\n        SELECT previous + current, current FROM fibonacci\n    )\n    -- The user is only interested in current number, not previous.\n    SELECT current FROM fibonacci\n    -- We only need one number, so limit to 1\n    LIMIT 1\n    -- Offset the query by the requested argument to get the correct\n    -- position in the list.\n    OFFSET n\n$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE;\n","human_summarization":"\"Generates the nth Fibonacci number using either an iterative or recursive approach. The function also optionally supports negative n values by inversely applying the Fibonacci sequence formula.\"","id":2212}
    {"lang_cluster":"SQL","source_code":"\n\nWorks with: MS SQL\n--Create the original array (table #nos) with numbers from 1 to 10\ncreate table #nos (v int)\ndeclare @n int set @n=1\nwhile @n<=10 begin insert into #nos values (@n) set @n=@n+1 end\n\n--Select the subset that are even into the new array (table #evens)\nselect v into #evens from #nos where v\u00a0% 2 = 0\n\n-- Show #evens\nselect * from #evens\n\n-- Clean up so you can edit and repeat:\ndrop table #nos\ndrop table #evens\n'Works with: MySQL\ncreate temporary table nos (v int);\ninsert into nos values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10);\ncreate temporary table evens (v int);\ninsert into evens select v from nos where v%2=0;\nselect * from evens order by v; \/*2,4,6,8,10*\/\ndrop table nos;\ndrop table evens;\n\ncreate temporary table evens select * from nos where v%2=0;\n","human_summarization":"\"Selects specific elements from an array into a new array, specifically even numbers. Alternatively, it can also modify the original array destructively.\"","id":2213}
    {"lang_cluster":"SQL","source_code":"\n--Clean up previous run  \nIF EXISTS (SELECT * \n           FROM   SYS.TYPES \n           WHERE  NAME = 'FairPlayTable') \n  DROP TYPE FAIRPLAYTABLE \n\n--Set Types  \nCREATE TYPE FAIRPLAYTABLE AS TABLE (LETTER VARCHAR(1), COLID INT, ROWID INT) \n\nGO \n\n--Configuration Variables  \nDECLARE @KEYWORD VARCHAR(25) = 'CHARLES' --Keyword for encryption  \nDECLARE @INPUT VARCHAR(MAX) = 'Testing Seeconqz' --Word to be encrypted  \nDECLARE @Q INT = 0 -- Q removed?  \nDECLARE @ENCRYPT INT = 1 --Encrypt?  \n--Setup Variables  \nDECLARE @WORDS TABLE \n  ( \n     WORD_PRE  VARCHAR(2), \n     WORD_POST VARCHAR(2) \n  ) \nDECLARE @T_TABLE FAIRPLAYTABLE \nDECLARE @NEXTLETTER CHAR(1) \nDECLARE @WORD VARCHAR(2), \n        @COL1 INT, \n        @COL2 INT, \n        @ROW1 INT, \n        @ROW2 INT, \n        @TMP  INT \nDECLARE @SQL     NVARCHAR(MAX) = '', \n        @COUNTER INT = 1, \n        @I       INT = 1 \nDECLARE @COUNTER_2 INT = 1 \n\nSET @INPUT = REPLACE(@INPUT, ' ', '') \nSET @KEYWORD = UPPER(@KEYWORD) \n\nDECLARE @USEDLETTERS VARCHAR(MAX) = '' \nDECLARE @TESTWORDS VARCHAR(2), \n        @A         INT = 0 \n\nWHILE @COUNTER_2 <= 5 \n  BEGIN \n      WHILE @COUNTER <= 5 \n        BEGIN \n            IF LEN(@KEYWORD) > 0 \n              BEGIN \n                  SET @NEXTLETTER = LEFT(@KEYWORD, 1) \n                  SET @KEYWORD = RIGHT(@KEYWORD, LEN(@KEYWORD) - 1) \n\n                  IF CHARINDEX(@NEXTLETTER, @USEDLETTERS) = 0 \n                    BEGIN \n                        INSERT INTO @T_TABLE \n                        SELECT @NEXTLETTER, \n                               @COUNTER, \n                               @COUNTER_2 \n\n                        SET @COUNTER = @COUNTER + 1 \n                        SET @USEDLETTERS = @USEDLETTERS + @NEXTLETTER \n                    END \n              END \n            ELSE \n              BEGIN \n                  WHILE 1 = 1 \n                    BEGIN \n                        IF CHARINDEX(CHAR(64 + @I), @USEDLETTERS) = 0 \n                           AND NOT ( CHAR(64 + @I) = 'Q' \n                                     AND @Q = 1 ) \n                           AND NOT ( @Q = 0 \n                                     AND CHAR(64 + @I) = 'J' ) \n                          BEGIN \n                              SET @NEXTLETTER = CHAR(64 + @I) \n                              SET @USEDLETTERS = @USEDLETTERS + CHAR(64 + @I) \n                              SET @I = @I + 1 \n\n                              BREAK \n                          END \n\n                        SET @I = @I + 1 \n                    END \n\n                  -- SELECT 1 AS [T] \n                  --BREAK \n                  INSERT INTO @T_TABLE \n                  SELECT @NEXTLETTER, \n                         @COUNTER, \n                         @COUNTER_2 \n\n                  SET @COUNTER = @COUNTER + 1 \n              END \n        END \n\n      SET @COUNTER_2 = @COUNTER_2 + 1 \n      SET @COUNTER = 1 \n  END \n\n--Split word into Digraphs  \nWHILE @A < 1 \n  BEGIN \n      SET @TESTWORDS = UPPER(LEFT(@INPUT, 2)) \n\n      IF LEN(@TESTWORDS) = 1 \n        BEGIN \n            SET @TESTWORDS = @TESTWORDS + 'X' \n            SET @A = 1 \n        END \n      ELSE IF RIGHT(@TESTWORDS, 1) = LEFT(@TESTWORDS, 1) \n        BEGIN \n            SET @TESTWORDS = RIGHT(@TESTWORDS, 1) + 'X' \n            SET @INPUT = RIGHT(@INPUT, LEN(@INPUT) - 1) \n        END \n      ELSE \n        SET @INPUT = RIGHT(@INPUT, LEN(@INPUT) - 2) \n\n      IF LEN(@INPUT) = 0 \n        SET @A = 1 \n\n      INSERT @WORDS \n      SELECT @TESTWORDS, \n             '' \n  END \n\n--Start Encryption \nIF @ENCRYPT = 1 \n  BEGIN \n      --Loop through Digraphs amd encrypt  \n      DECLARE WORDS_LOOP CURSOR LOCAL FORWARD_ONLY FOR \n        SELECT WORD_PRE \n        FROM   @WORDS \n        FOR UPDATE OF WORD_POST \n\n      OPEN WORDS_LOOP \n\n      FETCH NEXT FROM WORDS_LOOP INTO @WORD \n\n      WHILE @@FETCH_STATUS = 0 \n        BEGIN \n            --Find letter positions  \n            SET @ROW1 = (SELECT ROWID \n                         FROM   @T_TABLE \n                         WHERE  LETTER = LEFT(@WORD, 1)) \n            SET @ROW2 = (SELECT ROWID \n                         FROM   @T_TABLE \n                         WHERE  LETTER = RIGHT(@WORD, 1)) \n            SET @COL1 = (SELECT COLID \n                         FROM   @T_TABLE \n                         WHERE  LETTER = LEFT(@WORD, 1)) \n            SET @COL2 = (SELECT COLID \n                         FROM   @T_TABLE \n                         WHERE  LETTER = RIGHT(@WORD, 1)) \n\n            --Move positions according to encryption rules  \n            IF @COL1 = @COL2 \n              BEGIN \n                  SET @ROW1 = @ROW1 + 1 \n                  SET @ROW2 = @ROW2 + 1 \n              --select 'row'  \n              END \n            ELSE IF @ROW1 = @ROW2 \n              BEGIN \n                  SET @COL1 = @COL1 + 1 \n                  SET @COL2 = @COL2 + 1 \n              --select 'col'  \n              END \n            ELSE \n              BEGIN \n                  SET @TMP = @COL2 \n                  SET @COL2 = @COL1 \n                  SET @COL1 = @TMP \n              --select 'reg'  \n              END \n\n            IF @ROW1 = 6 \n              SET @ROW1 = 1 \n\n            IF @ROW2 = 6 \n              SET @ROW2 = 1 \n\n            IF @COL1 = 6 \n              SET @COL1 = 1 \n\n            IF @COL2 = 6 \n              SET @COL2 = 1 \n\n            --Find encrypted letters by positions  \n            UPDATE @WORDS \n            SET    WORD_POST = (SELECT (SELECT LETTER \n                                        FROM   @T_TABLE \n                                        WHERE  ROWID = @ROW1 \n                                               AND COLID = @COL1) \n                                       + (SELECT LETTER \n                                          FROM   @T_TABLE \n                                          WHERE  COLID = @COL2 \n                                                 AND ROWID = @ROW2)) \n            WHERE  WORD_PRE = @WORD \n\n            FETCH NEXT FROM WORDS_LOOP INTO @WORD \n        END \n\n      CLOSE WORDS_LOOP \n\n      DEALLOCATE WORDS_LOOP \n  END \n--Start Decryption \nELSE \n  BEGIN \n      --Loop through Digraphs amd decrypt  \n      DECLARE WORDS_LOOP CURSOR LOCAL FORWARD_ONLY FOR \n        SELECT WORD_PRE \n        FROM   @WORDS \n        FOR UPDATE OF WORD_POST \n\n      OPEN WORDS_LOOP \n\n      FETCH NEXT FROM WORDS_LOOP INTO @WORD \n\n      WHILE @@FETCH_STATUS = 0 \n        BEGIN \n            --Find letter positions  \n            SET @ROW1 = (SELECT ROWID \n                         FROM   @T_TABLE \n                         WHERE  LETTER = LEFT(@WORD, 1)) \n            SET @ROW2 = (SELECT ROWID \n                         FROM   @T_TABLE \n                         WHERE  LETTER = RIGHT(@WORD, 1)) \n            SET @COL1 = (SELECT COLID \n                         FROM   @T_TABLE \n                         WHERE  LETTER = LEFT(@WORD, 1)) \n            SET @COL2 = (SELECT COLID \n                         FROM   @T_TABLE \n                         WHERE  LETTER = RIGHT(@WORD, 1)) \n\n            --Move positions according to encryption rules  \n            IF @COL1 = @COL2 \n              BEGIN \n                  SET @ROW1 = @ROW1 - 1 \n                  SET @ROW2 = @ROW2 - 1 \n              --select 'row'  \n              END \n            ELSE IF @ROW1 = @ROW2 \n              BEGIN \n                  SET @COL1 = @COL1 - 1 \n                  SET @COL2 = @COL2 - 1 \n              --select 'col'  \n              END \n            ELSE \n              BEGIN \n                  SET @TMP = @COL2 \n                  SET @COL2 = @COL1 \n                  SET @COL1 = @TMP \n              --select 'reg'  \n              END \n\n            IF @ROW1 = 0 \n              SET @ROW1 = 5 \n\n            IF @ROW2 = 0 \n              SET @ROW2 = 5 \n\n            IF @COL1 = 0 \n              SET @COL1 = 5 \n\n            IF @COL2 = 0 \n              SET @COL2 = 5 \n\n            --Find decrypted letters by positions  \n            UPDATE @WORDS \n            SET    WORD_POST = (SELECT (SELECT LETTER \n                                        FROM   @T_TABLE \n                                        WHERE  ROWID = @ROW1 \n                                               AND COLID = @COL1) \n                                       + (SELECT LETTER \n                                          FROM   @T_TABLE \n                                          WHERE  COLID = @COL2 \n                                                 AND ROWID = @ROW2)) \n            WHERE  WORD_PRE = @WORD \n\n            FETCH NEXT FROM WORDS_LOOP INTO @WORD \n        END \n\n      CLOSE WORDS_LOOP \n\n      DEALLOCATE WORDS_LOOP \n  END \n\n--Output \nDECLARE WORDS CURSOR LOCAL FAST_FORWARD FOR \n  SELECT WORD_POST \n  FROM   @WORDS \n\nOPEN WORDS \n\nFETCH NEXT FROM WORDS INTO @WORD \n\nWHILE @@FETCH_STATUS = 0 \n  BEGIN \n      SET @SQL = @SQL + @WORD + ' '\n\n      FETCH NEXT FROM WORDS INTO @WORD \n  END \n\nCLOSE WORDS \n\nDEALLOCATE WORDS \n\nSELECT @SQL \n\n--Cleanup  \nIF EXISTS (SELECT * \n           FROM   SYS.TYPES \n           WHERE  NAME = 'FairPlayTable') \n  DROP TYPE FAIRPLAYTABLE\n\n","human_summarization":"Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.","id":2214}
    {"lang_cluster":"SQL","source_code":"\nWorks with: Oracle\n-- set of numbers is a table\n-- create one set with 3 elements\n\ncreate table myset1 (element number);\n\ninsert into myset1 values (1);\ninsert into myset1 values (2);\ninsert into myset1 values (3);\n        \ncommit;\n\n-- check if 1 is an element\n\nselect 'TRUE' BOOL from dual\nwhere 1 in \n(select element from myset1);\n\n-- create second set with 3 elements\n\ncreate table myset2 (element number);\n\ninsert into myset2 values (1);\ninsert into myset2 values (5);\ninsert into myset2 values (6);\n        \ncommit;\n\n-- union sets\n\nselect element from myset1\nunion\nselect element from myset2;\n\n-- intersection\n\nselect element from myset1\nintersect\nselect element from myset2;\n\n-- difference\n\nselect element from myset1\nminus\nselect element from myset2;\n\n-- subset\n\n-- change myset2 to only have 1 as element\n\ndelete from myset2 where not element = 1;\n\ncommit;\n\n-- check if myset2 subset of myset1\n\nselect 'TRUE' BOOL from dual\nwhere 0 =  (select count(*) from \n(select element from myset2\nminus\nselect element from myset1));\n\n-- equality\n\n-- change myset1 to only have 1 as element\n\ndelete from myset1 where not element = 1;\n\ncommit;\n\n -- check if myset2 subset of myset1 and\n -- check if myset1 subset of myset2 and\n \nselect 'TRUE' BOOL from dual\nwhere \n0 =  (select count(*) from \n(select element from myset2\nminus\nselect element from myset1)) and\n0 =\n(select count(*) from \n(select element from myset1\nminus\nselect element from myset2));\n\nSQL> \nSQL> -- set of numbers is a table\nSQL> -- create one set with 3 elements\nSQL> \nSQL> create table myset1 (element number);\n\nTable created.\n\nSQL> \nSQL> insert into myset1 values (1);\n\n1 row created.\n\nSQL> insert into myset1 values (2);\n\n1 row created.\n\nSQL> insert into myset1 values (3);\n\n1 row created.\n\nSQL> \nSQL> commit;\n\nCommit complete.\n\nSQL> \nSQL> -- check if 1 is an element\nSQL> \nSQL> select 'TRUE' BOOL from dual\n  2  where 1 in\n  3  (select element from myset1);\n\nBOOL                                                                            \n----                                                                            \nTRUE                                                                            \n\nSQL> \nSQL> -- create second set with 3 elements\nSQL> \nSQL> create table myset2 (element number);\n\nTable created.\n\nSQL> \nSQL> insert into myset2 values (1);\n\n1 row created.\n\nSQL> insert into myset2 values (5);\n\n1 row created.\n\nSQL> insert into myset2 values (6);\n\n1 row created.\n\nSQL> \nSQL> commit;\n\nCommit complete.\n\nSQL> \nSQL> -- union sets\nSQL> \nSQL> select element from myset1\n  2  union\n  3  select element from myset2;\n\n   ELEMENT                                                                      \n----------                                                                      \n         1                                                                      \n         2                                                                      \n         3                                                                      \n         5                                                                      \n         6                                                                      \n\nSQL> \nSQL> -- intersection\nSQL> \nSQL> select element from myset1\n  2  intersect\n  3  select element from myset2;\n\n   ELEMENT                                                                      \n----------                                                                      \n         1                                                                      \n\nSQL> \nSQL> -- difference\nSQL> \nSQL> select element from myset1\n  2  minus\n  3  select element from myset2;\n\n   ELEMENT                                                                      \n----------                                                                      \n         2                                                                      \n         3                                                                      \n\nSQL> \nSQL> -- subset\nSQL> \nSQL> -- change myset2 to only have 1 as element\nSQL> \nSQL> delete from myset2 where not element = 1;\n\n2 rows deleted.\n\nSQL> \nSQL> commit;\n\nCommit complete.\n\nSQL> \nSQL> -- check if myset2 subset of myset1\nSQL> \nSQL> select 'TRUE' BOOL from dual\n  2  where 0 =  (select count(*) from\n  3  (select element from myset2\n  4  minus\n  5  select element from myset1));\n\nBOOL                                                                            \n----                                                                            \nTRUE                                                                            \n\nSQL> \nSQL> -- equality\nSQL> \nSQL> -- change myset1 to only have 1 as element\nSQL> \nSQL> delete from myset1 where not element = 1;\n\n2 rows deleted.\n\nSQL> \nSQL> commit;\n\nCommit complete.\n\nSQL> \nSQL>  -- check if myset2 subset of myset1 and\nSQL>  -- check if myset1 subset of myset2 and\nSQL> \nSQL> select 'TRUE' BOOL from dual\n  2  where\n  3  0 =  (select count(*) from\n  4  (select element from myset2\n  5  minus\n  6  select element from myset1)) and\n  7  0 =\n  8  (select count(*) from\n  9  (select element from myset1\n 10  minus\n 11  select element from myset2));\n\nBOOL                                                                            \n----                                                                            \nTRUE            \n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":2215}
    {"lang_cluster":"SQL","source_code":"\n\nselect extract(year from dt) as year_with_xmas_on_sunday\nfrom   ( \n         select  add_months(date '2008-12-25', 12 * (level - 1)) as dt\n         from    dual\n         connect by level <= 2121 - 2008 + 1\n       ) \nwhere  to_char(dt, 'Dy', 'nls_date_language=English') = 'Sun'\norder  by 1\n;\n\n\n","human_summarization":"determine the years between 2008 and 2121 when Christmas (25th December) falls on a Sunday. It uses standard date handling libraries of the programming language and compares the results with other languages to identify any anomalies due to issues like overflow in date\/time representation. It also takes into account language settings in SQL and uses the TRUNC function to avoid complications related to these settings.","id":2216}
    {"lang_cluster":"SQL","source_code":"\nWorks with: ORACLE 19c\n\n\/*\nThis code is an implementation of \"Remove duplicate elements\" in SQL ORACLE 19c \np_in_str    -- input string  \np_delimiter -- delimeter \n*\/\nwith\n  function remove_duplicate_elements(p_in_str in varchar2, p_delimiter in varchar2 default ',') return varchar2 is\n  v_in_str varchar2(32767)\u00a0:= replace(p_in_str,p_delimiter,',');\n  v_res    varchar2(32767);\nbegin\n  --\n  execute immediate 'select listagg(distinct cv,:p_delimiter) from (select (column_value).getstringval() cv from xmltable(:v_in_str))' \n     into v_res using p_delimiter, v_in_str;\n  --\n  return v_res;\n  --\nend;\n\n--Test\nselect remove_duplicate_elements('1, 2, 3, \"a\", \"b\", \"c\", 2, 3, 4, \"b\", \"c\", \"d\"') as res from dual\nunion all \nselect remove_duplicate_elements('3 9 1 10 3 7 6 5 2 7 4 7 4 2 2 2 2 8 2 10 4 9 2 4 9 3 4 3 4 7',' ') as res from dual\n;\n\n","human_summarization":"\"Implements a function to remove duplicate elements from an array using three possible methods: 1) Using a hash table, 2) Sorting the elements and removing consecutive duplicates, 3) Iterating through the list and discarding any repeated elements.\"","id":2217}
    {"lang_cluster":"SQL","source_code":"\nWorks with: Oracle\nselect to_char(sysdate,'YYYY-MM-DD') date_fmt_1 from dual;\n\nselect to_char(sysdate,'fmDay, Month DD, YYYY') date_fmt_2 from dual;\nSQL>\nDATE_FMT_1\n----------\n2016-12-12\n\nSQL> SQL>\nDATE_FMT_2\n--------------------------------------------------------------------------------\nMonday, December 12, 2016\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":2218}
    {"lang_cluster":"SQL","source_code":"\n-- \n-- This only works under Oracle and has the limitation of 1 to 3999\n\n\nSQL> select to_char(1666, 'RN') urcoman, to_char(1666, 'rn') lcroman from dual;\n\nURCOMAN         LCROMAN\n--------------- ---------------\n        MDCLXVI         mdclxvi\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":2219}
    {"lang_cluster":"SQL","source_code":"\nWorks with: MS SQL version  2005\ndeclare @s varchar(10)\nset @s = 'alphaBETA'\nprint upper(@s)\nprint lower(@s)\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":2220}
    {"lang_cluster":"SQL","source_code":"\nselect translate(\n        'The quick brown fox jumps over the lazy dog.',\n        'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',\n        'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm'\n        )\n        from dual;\nWorks with: T-SQL\nwith cte(num) as \n(\n select 1\n union all\n select num+1\n from cte\n)\nselect cast((\nselect char(ascii(chr) +\n\t\tcase \n\t\t\twhen    ascii(chr) between ascii('a') and ascii('m') or\n\t\t\t\tascii(chr) between ascii('A') and ascii('M') then 13\n\t\t\twhen    ascii(chr) between ascii('n') and ascii('z') or\n\t\t\t\tascii(chr) between ascii('N') and ascii('Z') then -13\n\t\t\telse    0\n\t\tend)\nfrom\n(\nselect top(1000) num, \n\t\t -- your string to be converted to ROT13\n                 substring('The Quick Brown Fox Jumps Over The Lazy Dog',num,1) chr\nfrom cte\n) tmp\nFor XML PATH ('')) as xml).value('.', 'VARCHAR(max)') rot13\noption (maxrecursion 0)\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":2221}
    {"lang_cluster":"SQL","source_code":"\nWe can treat the array of data structures as a table. An order by clause in a query will sort the data.-- setup\ncreate table pairs (name varchar(16), value varchar(16));\ninsert into pairs values ('Fluffy', 'cat');\ninsert into pairs values ('Fido', 'dog');\ninsert into pairs values ('Francis', 'fish');\n-- order them by name\nselect * from pairs order by name;\n\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":2222}
    {"lang_cluster":"SQL","source_code":"\nREM Create a table to associate keys with values\nCREATE TABLE  associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); .\nREM Insert a Key Value Pair\nINSERT (KEY_COLUMN, VALUE_COLUMN) VALUES ( 'VALUE','KEY');.\nREM Retrieve a key value pair\nSELECT aa.value_column FROM associative_array aa where aa.key_column = 'KEY';\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":2223}
    {"lang_cluster":"SQL","source_code":"\n\nselect i, k, sum(A.N*B.N) as N\n        from A inner join B on A.j=B.j\n        group by i, k\n","human_summarization":"implement a function to compute the dot product of two vectors of arbitrary length. The vectors need to be of the same length and the dot product is calculated by multiplying corresponding terms from each vector and summing the products. The code also includes a specification for calculating the inner product in SQL given two tables A and B with key columns i, j, and k, and value columns N.","id":2224}
    {"lang_cluster":"SQL","source_code":"\n\nselect level card,\n        to_char(to_date(level,'j'),'fmjth') ord\nfrom dual\nconnect by level <= 15;\n\nselect to_char(to_date(5373485,'j'),'fmjth')\nfrom dual;\n\n      CARD ORD\n---------- ------------------------------\n         1 1st\n         2 2nd\n         3 3rd\n         4 4th\n         5 5th\n         6 6th\n         7 7th\n         8 8th\n         9 9th\n        10 10th\n        11 11th\n        12 12th\n        13 13th\n        14 14th\n        15 15th\n\n15 rows selected.\n\nselect to_char(to_date(5373485,'j'),'fmjth')\n                       *\nERROR at line 1:\nORA-01854: julian date must be between 1 and 5373484\n\n","human_summarization":"The code is a function that takes an integer input greater than or equal to zero and returns a string of the number followed by an apostrophe and the corresponding ordinal suffix. The function is tested with the ranges 0..25, 250..265, and 1000..1025. The use of apostrophes in the output is optional.","id":2225}
    {"lang_cluster":"SQL","source_code":"\nWorks with: ORACLE 19c\n\n\/*\nThis code is an implementation of \"General FizzBuzz\" in SQL ORACLE 19c \n*\/\nselect lpad( nvl(   case when mod(level, 3) = 0 then 'Fizz' end \n                 || case when mod(level, 5) = 0 then 'Buzz' end \n                 || case when mod(level, 7) = 0 then 'Baxx' end\n                , level)\n            ,12) as output\n  from dual\nconnect by level <= 107\n;\n\/\n\n\n","human_summarization":"The code takes a maximum number and a list of factors with corresponding words as input from the user. It then prints numbers from 1 to the maximum number, replacing multiples of the given factors with their corresponding words. If a number is a multiple of multiple factors, it prints all associated words in the order of the factors.","id":2226}
    {"lang_cluster":"SQL","source_code":"\n-- drop tables\nDROP TABLE IF EXISTS tmp_patients;\nDROP TABLE IF EXISTS tmp_visits;\n\n-- create tables\nCREATE TABLE tmp_patients(\n\tPATIENT_ID INT,\n\tLASTNAME VARCHAR(20)\n);\n\nCREATE TABLE tmp_visits(\n\tPATIENT_ID INT,\n\tVISIT_DATE DATE,\n\tSCORE NUMERIC(4,1)\n);\n\n-- load data from csv files\n\/*\n-- Note: LOAD DATA LOCAL requires `local-infile` enabled on both the client and server else you get error \"#1148 command is not allowed..\"\nLOAD DATA LOCAL INFILE '\/home\/csv\/patients.csv' INTO TABLE `tmp_patients` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n' IGNORE 1 LINES;\nLOAD DATA LOCAL INFILE '\/home\/csv\/visits.csv' INTO TABLE `tmp_visits` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n' IGNORE 1 LINES;\n*\/\n\n-- load data hard coded\nINSERT INTO tmp_patients(PATIENT_ID, LASTNAME)\nVALUES\n(1001, 'Hopper'),\n(4004, 'Wirth'),\n(3003, 'Kemeny'),\n(2002, 'Gosling'),\n(5005, 'Kurtz');\n\nINSERT INTO tmp_visits(PATIENT_ID, VISIT_DATE, SCORE)\nVALUES\n(2002, '2020-09-10', 6.8),\n(1001, '2020-09-17', 5.5),\n(4004, '2020-09-24', 8.4),\n(2002, '2020-10-08', NULL),\n(1001, NULL, 6.6),\n(3003, '2020-11-12', NULL),\n(4004, '2020-11-05', 7.0),\n(1001, '2020-11-19', 5.3);\n\n-- join tables and group\nSELECT\n\tp.PATIENT_ID,\n\tp.LASTNAME,\n\tMAX(VISIT_DATE) AS LAST_VISIT,\n\tSUM(SCORE) AS SCORE_SUM,\n\tCAST(AVG(SCORE) AS DECIMAL(10,2)) AS SCORE_AVG\nFROM\n\ttmp_patients p\n\tLEFT JOIN tmp_visits v\n\t\tON v.PATIENT_ID = p.PATIENT_ID\nGROUP BY\n\tp.PATIENT_ID,\n\tp.LASTNAME\nORDER BY\n\tp.PATIENT_ID;\n\n\n","human_summarization":"\"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file.\"","id":2227}
    {"lang_cluster":"SQL","source_code":"\nselect rpad('', 10, 'ha')\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":2228}
    {"lang_cluster":"SQL","source_code":"\nWorks with: Oracle\n-- test.sql\n-- Tested in SQL*plus\n\ndrop table test;\n\ncreate table test (a integer, b integer);\n\ninsert into test values ('&&A','&&B');\n\ncommit;\n\nselect a-b difference from test;\n\nselect a*b product from test;\n\nselect trunc(a\/b) integer_quotient from test;  \n\nselect mod(a,b) remainder from test;\n\nselect power(a,b) exponentiation from test;\nSQL> @test.sql\n\nTable dropped.\n\n\nTable created.\n\nEnter value for a: 3\nEnter value for b: 4\nold   1: insert into test values ('&&A','&&B')\nnew   1: insert into test values ('3','4')\n\n1 row created.\n\n\nCommit complete.\n\n\nDIFFERENCE\n----------\n        -1\n\n\n   PRODUCT\n----------\n        12\n\n\nINTEGER_QUOTIENT\n----------------\n               0\n\n\n REMAINDER\n----------\n         3\n\n\nEXPONENTIATION\n--------------\n            81\n   \n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":2229}
    {"lang_cluster":"SQL","source_code":"\n\n\n","human_summarization":"calculate the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. The codes handle Unicode code points correctly, distinguishing between character counts in code points and code unit counts. The codes also provide the string length in graphemes if the language supports it. The examples provided use the string \"m\u00f8\u00f8se\" and \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\" to demonstrate the functionality.","id":2230}
    {"lang_cluster":"SQL","source_code":"\nWorks with: oracle version 11.2 and higher\n\nwith\n  symbols (d) as (select to_char(level) from dual connect by level <=  9)\n, board   (i) as (select level          from dual connect by level <= 81)\n, neighbors (i, j) as (\n    select b1.i, b2.i\n    from   board b1 inner join board b2\n      on   b1.i != b2.i\n           and (\n                    mod(b1.i - b2.i, 9) = 0\n                 or ceil(b1.i \/  9) = ceil(b2.i \/  9)\n                 or ceil(b1.i \/ 27) = ceil(b2.i \/ 27) and trunc(mod(b1.i - 1, 9) \/ 3) = trunc(mod(b2.i - 1, 9) \/ 3)\n               )\n  )\n, r (str, pos) as (\n    select  :game, instr(:game, ' ')\n      from  dual\n    union all\n    select  substr(r.str, 1, r.pos - 1) || s.d || substr(r.str, r.pos + 1), instr(r.str, ' ', r.pos + 1)\n      from  r inner join symbols s\n        on  r.pos > 0 and not exists (\n                                       select *\n                                       from   neighbors n\n                                       where  r.pos = n.i and s.d = substr(r.str, n.j, 1)\n                                     )\n  )\nselect str\nfrom   r\nwhere  pos = 0\n;\n\n\n","human_summarization":"implement a Sudoku solver that fills in a partially completed 9x9 grid and displays the result in a human-readable format. The solution uses a recursive WITH clause, supported by some SQL dialects, and was tested in Oracle SQL. It employs a brute force algorithm that can solve most problems in less than a second. The input and output are presented as strings of 81 characters, with each character representing a digit or a space for an empty cell. The solution can be optimized by creating a table NEIGHBORS and an index on column I of that table.","id":2231}
    {"lang_cluster":"SQL","source_code":"\nselect to_char( next_day( last_day( add_months( to_date(\n        :yr||'01','yyyymm' ),level-1))-7,'Fri') ,'yyyy-mm-dd Dy') lastfriday\nfrom dual\nconnect by level <= 12;\n\nLASTFRIDAY\n-----------------------\n2012-01-27 Fri\n2012-02-24 Fri\n2012-03-30 Fri\n2012-04-27 Fri\n2012-05-25 Fri\n2012-06-29 Fri\n2012-07-27 Fri\n2012-08-31 Fri\n2012-09-28 Fri\n2012-10-26 Fri\n2012-11-30 Fri\n2012-12-28 Fri\n\n12 rows selected.\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":2232}
    {"lang_cluster":"SQL","source_code":"\n\ndrop table tbl;\ncreate table tbl\n(\n        u       number,\n        v       number\n);\n\ninsert into tbl ( u, v ) values ( 20, 50 );\ninsert into tbl ( u, v ) values ( 21, 50 );\ninsert into tbl ( u, v ) values ( 21, 51 );\ninsert into tbl ( u, v ) values ( 22, 50 );\ninsert into tbl ( u, v ) values ( 22, 55 );\n\ncommit;\n\nwith\n        function gcd ( ui in number, vi in number )\n        return number\n        is\n                u number\u00a0:= ui;\n                v number\u00a0:= vi;\n                t number;\n        begin\n                while v > 0\n                loop\n                        t\u00a0:= u;\n                        u\u00a0:= v;\n                        v:= mod(t, v );\n                end loop;\n                return abs(u);\n        end gcd;\n        select u, v, gcd ( u, v )\n        from tbl\n\/\n\n","human_summarization":"find the greatest common divisor (GCD) or greatest common factor (GCF) of two integers. This is related to the task of finding the least common multiple. The code also includes demonstrations of Oracle 12c WITH Clause Enhancements, SQL Server 2008, and a PostgreSQL function using a recursive common table expression.","id":2233}
    {"lang_cluster":"SQL","source_code":"\nWorks with: MS SQL version Server 2005\ndeclare @s varchar(10)\nset @s = '1234.56'\n\nprint isnumeric(@s) --prints 1 if numeric, 0 if not.\n\nif isnumeric(@s)=1 begin print 'Numeric' end \nelse print 'Non-numeric'\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":2234}
    {"lang_cluster":"SQL","source_code":"\nLibrary: SQL\nSELECT CASE\n    WHEN MOD(level,15)=0 THEN 'FizzBuzz'\n    WHEN MOD(level,3)=0 THEN 'Fizz'\n    WHEN MOD(level,5)=0 THEN 'Buzz'\n    ELSE TO_CHAR(level)\n    END FizzBuzz\n    FROM dual\n    CONNECT BY LEVEL <= 100;\n\nSELECT nvl(decode(MOD(level,3),0,'Fizz')||decode(MOD(level,5),0,'Buzz'),level)\nFROM dual\nCONNECT BY level<=100;\nSELECT i, fizzbuzz \n  FROM \n    (SELECT i, \n            CASE \n              WHEN i\u00a0% 15 = 0 THEN 'FizzBuzz' \n              WHEN i\u00a0%  5 = 0 THEN 'Buzz' \n              WHEN i\u00a0%  3 = 0 THEN 'Fizz' \n              ELSE NULL \n            END AS fizzbuzz \n       FROM generate_series(1,100) AS i) AS fb \n WHERE fizzbuzz IS NOT NULL;\n\nSELECT COALESCE(FIZZ || BUZZ, FIZZ, BUZZ, OUTPUT) AS FIZZBUZZ FROM\n(SELECT GENERATE_SERIES AS FULL_SERIES, TO_CHAR(GENERATE_SERIES,'99') AS OUTPUT \nFROM GENERATE_SERIES(1,100)) F LEFT JOIN \n(SELECT TEXT 'Fizz' AS FIZZ, GENERATE_SERIES AS FIZZ_SERIES FROM GENERATE_SERIES(0,100,3)) FIZZ ON\nFIZZ.FIZZ_SERIES = F.FULL_SERIES LEFT JOIN\n(SELECT TEXT 'Buzz' AS BUZZ, GENERATE_SERIES AS BUZZ_SERIES FROM GENERATE_SERIES(0,100,5)) BUZZ ON\nBUZZ.BUZZ_SERIES = F.FULL_SERIES;\nWITH nums (n, fizzbuzz ) AS (\n\tSELECT 1, CONVERT(nvarchar, 1) UNION ALL\n\tSELECT\n\t\t(n + 1) as n1, \n\t\tCASE\n\t\t\tWHEN (n + 1)\u00a0% 15 = 0 THEN 'FizzBuzz'\n\t\t\tWHEN (n + 1)\u00a0% 3  = 0 THEN 'Fizz'\n\t\t\tWHEN (n + 1)\u00a0% 5  = 0 THEN 'Buzz'\n\t\t\tELSE CONVERT(nvarchar, (n + 1))\n\t\tEND\n\tFROM nums WHERE n < 100\n)\nSELECT n, fizzbuzz FROM nums\nORDER BY n ASC\nOPTION ( MAXRECURSION 100 )\nSELECT \n        isnull(if row_num\u00a0% 3 = 0 then 'Fizz' endif + if row_num\u00a0% 5 = 0 then 'Buzz' endif, str(row_num)) \nFROM \n        sa_rowgenerator(1,100)\n\n-- Load some numbers\nCREATE TABLE numbers(i INTEGER);\nINSERT INTO numbers VALUES(1);\nINSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;\nINSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;\nINSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;\nINSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;\nINSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;\nINSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;\nINSERT INTO numbers SELECT i + (SELECT MAX(i) FROM numbers) FROM numbers;\n-- Define the fizzes and buzzes\nCREATE TABLE fizzbuzz (message VARCHAR(8), divisor INTEGER);\nINSERT INTO fizzbuzz VALUES('fizz',      3);\nINSERT INTO fizzbuzz VALUES('buzz',      5);\nINSERT INTO fizzbuzz VALUES('fizzbuzz', 15);\n-- Play fizzbuzz\nSELECT COALESCE(max(message),CAST(i AS VARCHAR(99))) as result\nFROM numbers LEFT OUTER JOIN fizzbuzz ON MOD(i,divisor) = 0\nGROUP BY i\nHAVING i <= 100\nORDER BY i;\n-- Tidy up\nDROP TABLE fizzbuzz;\nDROP TABLE numbers;\n","human_summarization":"The code prints integers from 1 to 100. For multiples of three, it prints 'Fizz' instead of the number. For multiples of five, it prints 'Buzz' instead of the number. For numbers that are multiples of both three and five, it prints 'FizzBuzz'. This is a solution to the FizzBuzz problem.","id":2235}
    {"lang_cluster":"SQL","source_code":"\nWorks with: Oracle\nselect host_name from v$instance;\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":2236}
    {"lang_cluster":"SQL","source_code":"\nWorks with: PL\/pgSQL\n\nRLE encoding\n-- variable table\ndrop table if exists var;\ncreate temp table var (\tvalue varchar(1000) );\ninsert into var(value) select 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW';\n\n-- select\nwith recursive\nints(num) as \n(\n\tselect 1\n\tunion all\n\tselect num+1\n\tfrom ints\n\twhere num+1 <= length((select value from var))\n)\n,\nchars(num,chr,nextChr,isGroupEnd) as\n(\n\tselect tmp.*, case when tmp.nextChr <> tmp.chr then 1 else 0 end groupEnds\n\tfrom (\n\tselect num, \n\t\t   substring((select value from var), num, 1) chr,\n\t\t   (select substring((select value from var), num+1, 1)) nextChr\n\tfrom ints\n\t) tmp\n)\nselect (select value from var) plain_text, (\n\tselect string_agg(concat(cast(maxNoWithinGroup as varchar(10)) , chr), '' order by num)\n\tfrom (\n\t\tselect *, max(noWithinGroup) over (partition by chr, groupNo) maxNoWithinGroup\n\t\tfrom (\n\t\t\tselect\tnum, \n\t\t\t\t\tchr, \n\t\t\t\t\tgroupNo, \n\t\t\t\t\trow_number() over( partition by chr, groupNo order by num) noWithinGroup\n\t\t\tfrom (\n\t\t\tselect *, (select count(*) \n\t\t\t\t\t   from chars chars2 \n\t\t\t\t\t   where chars2.isGroupEnd = 1 and \n\t\t\t\t\t   chars2.chr = chars.chr and \n\t\t\t\t\t   chars2.num < chars.num) groupNo \n\t\t\tfrom chars\n\t\t\t) tmp\n\t\t) sub\n\t) final\n\twhere noWithinGroup = 1\n\t) Rle_Compressed\nRLE decoding\n-- variable table\nDROP TABLE IF EXISTS var;\nCREATE temp TABLE var (\tVALUE VARCHAR(1000) );\nINSERT INTO var(VALUE) SELECT '1A2B3C4D5E6F';\n\n-- select\nWITH recursive\nints(num) AS \n(\n\tSELECT 1\n\tUNION ALL\n\tSELECT num+1\n\tFROM ints\n\tWHERE num+1 <= LENGTH((SELECT VALUE FROM var))\n)\n,\nchars(num,chr,nextChr) AS\n(\n\tSELECT tmp.*\n\tFROM (\n\tSELECT num, \n\t\tSUBSTRING((SELECT VALUE FROM var), num, 1) chr,\n\t\t(SELECT SUBSTRING((SELECT VALUE FROM var), num+1, 1)) nextChr\n\tFROM ints\n\t) tmp\n)\n,\ncharsWithGroup(num,chr,nextChr,group_no) AS\n(\n\tSELECT *,(SELECT COUNT(*) \n\t\tFROM chars chars2 \n\t\tWHERE chars2.chr\u00a0!~ '[0-9]' AND \n\t\tchars2.num < chars.num) group_No\n\tFROM chars\n)\n,\ncharsWithGroupAndLetter(num,chr,nextChr,group_no,group_letter) AS\n(\n\tSELECT *,(SELECT chr \n\t\tFROM charsWithGroup g2 \n\t\twhere g2.group_no = charsWithGroup.group_no \n\t\tORDER BY num DESC \n\t\tLIMIT 1)\n\tFROM charsWithGroup\n)\n,\nlettersWithCount(group_no,amount,group_letter) AS\n(\n\tSELECT group_no, string_agg(chr, '' ORDER BY num), group_letter\n\tFROM charsWithGroupAndLetter\n\tWHERE chr ~ '[0-9]'\n\tGROUP BY group_no, group_letter\n)\n,\nlettersReplicated(group_no,amount,group_letter, replicated_Letter) AS\n(\n\tSELECT *, rpad(group_letter, cast(amount as int), group_letter) \n\tFROM lettersWithCount\n)\nselect (SELECT value FROM var) rle_encoded, \n\tstring_agg(replicated_Letter, '' ORDER BY group_no) decoded_string \nFROM lettersReplicated\n","human_summarization":"implement a run-length encoding algorithm that compresses a string of uppercase characters by storing the length of consecutive runs of the same character. It also provides a function to reverse the compression.","id":2237}
    {"lang_cluster":"SQL","source_code":"\n\nWITH RECURSIVE\n  positions(i) as (\n    VALUES(0)\n    UNION SELECT ALL\n    i+1 FROM positions WHERE i < 63\n    ),\n  solutions(board, n_queens) AS (\n    SELECT '----------------------------------------------------------------', cast(0 AS bigint) \n      FROM positions\n    UNION\n    SELECT\n      substr(board, 1, i) || '*' || substr(board, i+2),n_queens + 1 as n_queens\n      FROM positions AS ps, solutions \n    WHERE n_queens < 8\n      AND substr(board,1,i)\u00a0!= '*'\n      AND NOT EXISTS (\n        SELECT 1 FROM positions WHERE\n          substr(board,i+1,1) = '*' AND\n            (\n                i\u00a0% 8 = ps.i %8 OR\n                cast(i \/ 8 AS INT) = cast(ps.i \/ 8 AS INT) OR\n                cast(i \/ 8 AS INT) + (i\u00a0% 8) = cast(ps.i \/ 8 AS INT) + (ps.i\u00a0% 8) OR\n                cast(i \/ 8 AS INT) - (i\u00a0% 8) = cast(ps.i \/ 8 AS INT) - (ps.i\u00a0% 8)\n            )\n        LIMIT 1\n        ) \n   ORDER BY n_queens DESC -- remove this when using Postgres (they don't support ORDER BY in CTEs)\n  )\nSELECT board,n_queens FROM solutions WHERE n_queens = 8;\n","human_summarization":"implement a solution to the N-queens problem, specifically for an 8x8 board, using Common Table Expressions. The solution has been tested with SQLite (>=3.8.3) and Postgres and may be compatible with other SQL dialects. The code and a Python script to run it are available on Github.","id":2238}
    {"lang_cluster":"SQL","source_code":"\n\nWITH KnapsackItems (item, [weight], value) AS\n(\n    SELECT 'map',9,  150  \n    UNION ALL SELECT 'compass',13,  35  \n    UNION ALL SELECT 'water',153,  200  \n    UNION ALL SELECT 'sandwich',50,  160  \n    UNION ALL SELECT 'glucose',15,  60  \n    UNION ALL SELECT 'tin',68,  45  \n    UNION ALL SELECT 'banana',27,  60  \n    UNION ALL SELECT 'apple',39,  40  \n    UNION ALL SELECT 'cheese',23,  30  \n    UNION ALL SELECT 'beer',52,  10  \n    UNION ALL SELECT 'suntan cream',11,  70  \n    UNION ALL SELECT 'camera',32,  30  \n    UNION ALL SELECT 'T-shirt',24,  15  \n    UNION ALL SELECT 'trousers',48,  10  \n    UNION ALL SELECT 'umbrella',73,  40  \n    UNION ALL SELECT 'waterproof trousers',42,  70  \n    UNION ALL SELECT 'waterproof overclothes',43,  75  \n    UNION ALL SELECT 'note-case',22,  80  \n    UNION ALL SELECT 'sunglasses',7,  20  \n    UNION ALL SELECT 'towel',18,  12  \n    UNION ALL SELECT 'socks',4,  50  \n    UNION ALL SELECT 'book',30,  10  \n)\nSELECT *\nINTO #KnapsackItems\nFROM KnapsackItems;\n\nWITH UNIQUEnTuples (n, Tuples, ID, [weight], value) AS (\n    SELECT 1, CAST(item AS VARCHAR(8000)), item, [weight], value\n    FROM #KnapsackItems\n    UNION ALL\n    SELECT 1 + n.n, t.item + ',' + n.Tuples, item, n.[weight] + t.[weight], n.value + t.value\n    FROM UNIQUEnTuples n \n    CROSS APPLY (\n        SELECT item, [weight], value \n        FROM #KnapsackItems t \n        WHERE t.item < n.ID AND n.[weight] + t.[weight] < 400) t\n    )\nSELECT TOP 5 *\nFROM UNIQUEnTuples\nORDER BY value DESC, n, Tuples;\n\nGO\nDROP TABLE #KnapsackItems;\n\n\n","human_summarization":"Implement a solution for the 0-1 Knapsack problem where a tourist needs to maximize the total value of items he can carry in his knapsack without exceeding a weight limit of 4kg. The solution uses a recursive CTE and runs on SQL Server 2005 or later, displaying the top 5 optimal combinations of items.","id":2239}
    {"lang_cluster":"SQL","source_code":"\nWorks with: MySQL\nSELECT MD5('The quick brown fox jumped over the lazy dog\\'s back')\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":2240}
    {"lang_cluster":"SQL","source_code":"\nSET @txt = REPLACE('In girum imus nocte et consumimur igni', ' ', '');\nSELECT REVERSE(@txt) = @txt;\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":2241}
    {"lang_cluster":"Logo","source_code":"\n\nmake \"stack []\npush \"stack 1\npush \"stack 2\npush \"stack 3\nprint pop \"stack  \u00a0; 3\nprint empty? :stack\u00a0; false\n","human_summarization":"implement a stack with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and allows access to the topmost element without modifying the stack. It also includes features for testing if the stack is empty.","id":2242}
    {"lang_cluster":"Logo","source_code":"\nto fib :n [:a 0] [:b 1]\n  if :n < 1 [output :a]\n  output (fib :n-1 :b :a+:b)\nend\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":2243}
    {"lang_cluster":"Logo","source_code":"\nto even? :n\n  output equal? 0 modulo :n 2\nend\nshow filter \"even? [1 2 3 4]   \u00a0; [2 4]\n\nshow filter [equal? 0 modulo\u00a0? 2] [1 2 3 4]\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":2244}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\n\nto items :n :thing\n  if :n >= count :thing [output :thing]\n  output items :n butlast :thing\nend\n\nto butitems :n :thing \n  if or :n <= 0 empty? :thing [output :thing]\n  output butitems :n-1 butfirst :thing\nend\n\nto middle :n :m :thing\n  output items :m-(:n-1) butitems :n-1 :thing\nend\n\nto lastitems :n :thing\n  if :n >= count :thing [output :thing]\n output lastitems :n butfirst :thing\nend\n\nto starts.with :sub :thing\n  if empty? :sub [output \"true]\n  if empty? :thing [output \"false]\n  if not equal? first :sub first :thing [output \"false]\n  output starts.with butfirst :sub butfirst :thing\nend\n\nto members :sub :thing\n  output cascade [starts.with :sub\u00a0?] [bf\u00a0?] :thing\nend\n\n; note: Logo indices start at one\nmake \"s \"abcdefgh\nprint items 3 butitems 2 :s\u00a0; cde\nprint middle 3 5  :s  \u00a0; cde\nprint butitems 2  :s  \u00a0; cdefgh\nprint butlast     :s  \u00a0; abcdefg\nprint items 3 member  \"d  :s\u00a0; def\nprint items 3 members \"de :s\u00a0; def\n","human_summarization":"\"Output: The code displays a substring from a string in various ways: starting from a specific character position and of a certain length, starting from a specific character position to the end of the string, excluding the last character of the string, starting from a known character within the string of a certain length, and starting from a known substring within the string of a certain length. The code works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not 8-bit or 16-bit code units. It is not designed to handle all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.\"","id":2245}
    {"lang_cluster":"Logo","source_code":"\n\nprint reverse \"cat  \u00a0; tac\n","human_summarization":"take a string as input, reverse it, and return the reversed string. It also ensures the preservation of Unicode combining characters. It can handle both words and lists.","id":2246}
    {"lang_cluster":"Logo","source_code":"\n; Determine if a Gregorian calendar year is leap \nto leap? :year\n  output (and \n    equal? 0 modulo :year 4\n    not member? modulo :year 400 [100 200 300]\n  )\nend\n\n; Convert Gregorian calendar date to a simple day count from \n; day 1 = January 1, 1 CE \nto day_number :year :month :day\n  local \"elapsed make \"elapsed difference :year 1\n  output (sum  product 365 :elapsed\n              int quotient :elapsed 4\n              minus int quotient :elapsed 100\n              int quotient :elapsed 400\n              int quotient difference product 367 :month 362 12\n              ifelse lessequal? :month 2 0 ifelse leap? :year -1 -2\n              :day)\nend\n\n; Find the day of the week from a day number; 0 = Sunday through 6 = Saturday\nto day_of_week :day_number\n  output modulo :day_number 7\nend\n\n; True if the given day is a Sunday\nto sunday? :year :month :day\n  output equal? 0 day_of_week day_number :year :month :day\nend\n\n; Put it all together to answer the question posed in the problem\nprint filter [sunday?\u00a0? 12 25] iseq 2008 2121\nbye\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":2247}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\nshow remdup [1 2 3 a b c 2 3 4 b c d]  \u00a0; [1 a 2 3 4 b c d]\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":2248}
    {"lang_cluster":"Logo","source_code":"\n; quicksort (lists, functional)\n\nto small? :list\n  output or [empty? :list] [empty? butfirst :list]\nend\nto quicksort :list\n  if small? :list [output :list]\n  localmake \"pivot first :list\n  output (sentence\n    quicksort filter [? < :pivot] butfirst :list\n              filter [? = :pivot]          :list\n    quicksort filter [? > :pivot] butfirst :list\n  )\nend\n\nshow quicksort [1 3 5 7 9 8 6 4 2]\n; quicksort (arrays, in-place)\n\nto incr :name\n  make :name (thing :name) + 1\nend\nto decr :name\n  make :name (thing :name) - 1\nend\nto swap :i :j :a\n  localmake \"t item :i :a\n  setitem :i :a item :j :a\n  setitem :j :a :t\nend\n\nto quick :a :low :high\n  if :high <= :low [stop]\n  localmake \"l :low\n  localmake \"h :high\n  localmake \"pivot item ashift (:l + :h) -1  :a\n  do.while [\n    while [(item :l :a) < :pivot] [incr \"l]\n    while [(item :h :a) > :pivot] [decr \"h]\n    if :l <= :h [swap :l :h :a  incr \"l  decr \"h]\n  ] [:l <= :h]\n  quick :a :low :h\n  quick :a :l :high\nend\nto sort :a\n  quick :a first :a count :a\nend\n\nmake \"test {1 3 5 7 9 8 6 4 2}\nsort :test\nshow :test\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":2249}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\n\nprint first shell [date +%F]\nprint first shell [date +\"%A, %B %d, %Y\"]\n\n","human_summarization":"display the current date in two different formats: \"2007-11-23\" and \"Friday, November 23, 2007\". It uses UCB Logo to call out to the shell due to the absence of standard built-in time and date functions in Logo.","id":2250}
    {"lang_cluster":"Logo","source_code":"\nto powerset :set\n  if empty? :set [output [[]]]\n  localmake \"rest powerset butfirst :set\n  output sentence  map [sentence first :set\u00a0?] :rest  :rest\nend\n\nshow powerset [1 2 3]\n[[1 2 3] [1 2] [1 3] [1] [2 3] [2] [3] []]\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":2251}
    {"lang_cluster":"Logo","source_code":"\nmake \"roman.rules [\n  [1000 M] [900 CM] [500 D] [400 CD]\n  [ 100 C] [ 90 XC] [ 50 L] [ 40 XL]\n  [  10 X] [  9 IX] [  5 V] [  4 IV]\n  [   1 I]\n]\n\nto roman :n [:rules :roman.rules] [:acc \"||]\n  if empty? :rules [output :acc]\n  if :n < first first :rules [output (roman :n bf :rules :acc)]\n  output (roman :n - first first :rules  :rules  word :acc last first :rules)\nend\nWorks with: UCB Logo\nmake \"patterns [[?] [?\u00a0?] [?\u00a0?\u00a0?] [? ?2] [?2] [?2\u00a0?] [?2\u00a0?\u00a0?] [?2\u00a0?\u00a0?\u00a0?] [? ?3]]\n\nto digit :d :numerals\n  if :d = 0 [output \"||]\n  output apply (sentence \"\\( \"word (item :d :patterns) \"\\)) :numerals\nend\nto digits :n :numerals\n  output word ifelse :n < 10 [\"||] [digits int :n\/10 bf bf :numerals] ~\n              digit modulo :n 10 :numerals\nend\nto roman :n\n  if or :n < 0 :n >= 4000 [output [EX MODVS!]]\n  output digits :n [I V X L C D M]\nend\n\nprint roman 1999 \u00a0; MCMXCIX \nprint roman 25   \u00a0; XXV\nprint roman 944  \u00a0; CMXLIV\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":2252}
    {"lang_cluster":"Logo","source_code":"\narray 5     \u00a0; default origin is 1, every item is empty\n(array 5 0) \u00a0; custom origin\nmake \"a {1 2 3 4 5} \u00a0; array literal\nsetitem 1 :a \"ten      \u00a0; Logo is dynamic; arrays can contain different types\nprint item 1 :a  \u00a0; ten\n","human_summarization":"demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and includes the functionality of pushing a value into the array.","id":2253}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\nto copy :from :to \n  openread :from\n  openwrite :to\n  setread :from   \n  setwrite :to\n  until [eof?] [print readrawline]\n  closeall\nend\n\ncopy \"input.txt \"output.txt\n","human_summarization":"demonstrate reading the contents of \"input.txt\" file into a variable and then writing this variable's contents into a new file called \"output.txt\".","id":2254}
    {"lang_cluster":"Logo","source_code":"\nprint uppercase \"alphaBETA \u00a0; ALPHABETA\nprint lowercase \"alphaBETA \u00a0; alphabeta\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":2255}
    {"lang_cluster":"Logo","source_code":"\n\nmembers of a list: [one two three]\nitems in an array: {one two three}\ncharacters in a word: \"123\n","human_summarization":"create a collection in a statically-typed language, add values to it, and review the programming examples for compliance with the task requirements. The code also involves the use of different data types and collection abstractions such as arrays, associative arrays, compound data types, linked lists, queues, sets, stacks, and list-like protocols in Logo.","id":2256}
    {"lang_cluster":"Logo","source_code":"\nto comma.list :n\n  repeat :n-1 [type repcount type \"|, |]\n  print :n\nend\n\ncomma.list 10\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":2257}
    {"lang_cluster":"Logo","source_code":"\nto starts.with? :sub :thing\n  if empty? :sub [output \"true]\n  if empty? :thing [output \"false]\n  if not equal? first :sub first :thing [output \"false]\n  output starts.with? butfirst :sub butfirst :thing\nend\n\nto ends.with? :sub :thing\n  if empty? :sub [output \"true]\n  if empty? :thing [output \"false]\n  if not equal? last :sub last :thing [output \"false]\n  output ends.with? butlast :sub butlast :thing\nend\n\nshow starts.with? \"dog \"doghouse   \u00a0; true\nshow ends.with? \"house \"doghouse   \u00a0; true\nshow substring? \"gho \"doghouse      \u00a0; true  (built-in)\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":2258}
    {"lang_cluster":"Logo","source_code":"\n\nfput item list\u00a0; add item to the head of a list\n\nfirst list \u00a0; get the data\nbutfirst list\u00a0; get the remainder\nbf list      \u00a0; contraction for \"butfirst\"\n\n.setfirst list value\n.setbf list remainder\n","human_summarization":"define a data structure for a singly-linked list element. This element holds a numeric value and a mutable link to the next element.","id":2259}
    {"lang_cluster":"Logo","source_code":"\nto tree :depth :length :scale :angle\n  if :depth=0 [stop]\n  setpensize round :depth\/2\n  forward :length\n  right :angle\n  tree :depth-1 :length*:scale :scale :angle\n  left 2*:angle\n  tree :depth-1 :length*:scale :scale :angle\n  right :angle\n  back :length\nend\n\nclearscreen\ntree 10 80 0.7 30\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":2260}
    {"lang_cluster":"Logo","source_code":"\nto factors :n\n  output filter [equal? 0 modulo :n\u00a0?] iseq 1 :n\nend\n\nshow factors 28      \u00a0; [1 2 4 7 14 28]\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":2261}
    {"lang_cluster":"Logo","source_code":"\n\nWorks with: MSWlogo\n\nto cuboid :l1 :l2 :l3\ncs perspective ;making the room ready to use\nsetxyz :l1   0    0\nsetxyz :l1 :l2    0\nsetxyz   0 :l2    0\nsetxyz   0   0    0\nsetxyz :l1   0    0\nsetxyz :l1   0 -:l3\nsetxyz :l1 :l2 -:l3\nsetxyz :l1 :l2    0\nsetxyz   0 :l2    0\nsetxyz   0 :l2 -:l3\nsetxyz :l1 :l2 -:l3\nend\n\ncuboid 50 100 150\n","human_summarization":"\"Generates a graphical or ASCII art representation of a 2x3x4 cuboid, with three visible faces, using either static or rotational projection. Implemented in Logo using the perspective function for easier 3D object drawing.\"","id":2262}
    {"lang_cluster":"Logo","source_code":"\nto rot13 :c\n  make \"a difference ascii lowercase :c  ascii \"a\n  if or :a < 0 :a > 25 [output :c]\n  make \"delta ifelse :a < 13 [13] [-13]\n  output char sum :delta ascii :c\nend\n\nprint map \"rot13 \"|abjurer NOWHERE|\nnowhere ABJURER\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":2263}
    {"lang_cluster":"Logo","source_code":"\nfor [i 1 5] [repeat :i [type \"*] (print)]\nrepeat 5 [repeat repcount [type \"*] (print)]\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":2264}
    {"lang_cluster":"Logo","source_code":"\n\npprop \"animals \"cat 5\npprop \"animals \"dog 4\npprop \"animals \"mouse 11\nprint gprop \"animals \"cat   \u00a0; 5\nremprop \"animals \"dog\nshow plist \"animals   \u00a0;  [mouse 11 cat 5]\n","human_summarization":"\"Creates an associative array, dictionary, map, or hash using UCB Logo's property lists to associate names with values.\"","id":2265}
    {"lang_cluster":"Logo","source_code":"\n\n; Configuration parameters for Microsoft and BSD implementations\nmake \"LCG_MS [214013 2531011 65536 2147483648]\nmake \"LCG_BSD [1103515245 12345 1 2147483648]\n\n; Default seed is 0\nmake \"_lcg_value 0\n\n; set the seed\nto lcg_seed :seed\n  make \"_lcg_value :seed\nend\n\n; generate the next number in the series using the given parameters\nto lcg_rand [:config :LCG_MS]\n  local \"a local \"c local \"d local \"m\n  foreach [a c d m] [\n    make\u00a0? item # :config\n  ]\n  make \"_lcg_value (modulo (sum (product :a :_lcg_value) :c) :m)\n  output int quotient :_lcg_value :d\nend\n\nforeach (list :LCG_BSD :LCG_MS) [\n  lcg_seed 0\n  repeat 10 [\n    print (lcg_rand\u00a0?)\n  ]\n  print []\n]\nbye\n","human_summarization":"The code replicates two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). It uses the Linear Congruential Generator (LCG) formula to generate a sequence of random numbers, starting from a seed value. The generated sequence should match the original generator's sequence when started from the same seed. The BSD formula generates random numbers in the range of 0 to 2147483647, while the Microsoft formula generates random numbers in the range of 0 to 32767.","id":2266}
    {"lang_cluster":"Logo","source_code":"\nto insert :after :list :value\n  localmake \"tail member :after :list\n  if not empty? :tail [.setbf :tail fput :value bf :tail]\n  output :list\nend\n\nshow insert 5 [3 5 1 8] 2\n[3 5 2 1 8]\n\n","human_summarization":"\"Defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element C into a list of elements A->B, after element A.\"","id":2267}
    {"lang_cluster":"Logo","source_code":"\nto double :x\n  output ashift :x  1\nend\nto halve :x\n  output ashift :x -1\nend\nto even? :x\n  output equal? 0 bitand 1 :x\nend\nto eproduct :x :y\n  if :x = 0 [output 0]\n  ifelse even? :x ~\n    [output      eproduct halve :x double :y] ~\n    [output :y + eproduct halve :x double :y]\nend\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":2268}
    {"lang_cluster":"Logo","source_code":"\nto factorial :n\n  if :n < 2 [output 1]\n  output :n * factorial :n-1\nend\n\nto factorial :n \n\tmake \"fact 1 \n\tmake \"i 1 \n\trepeat :n [make \"fact :fact * :i make \"i :i + 1] \n\tprint :fact \nend\n","human_summarization":"The code implements a function to calculate the factorial of a positive integer number. The factorial is the product of all positive integers from the input number down to one. The function can be either iterative or recursive. It optionally handles errors for negative input numbers. The code may require slight modifications to run on different Logo implementations.","id":2269}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\nto ok? :n\n  output (and [number? :n] [4 = count :n] [4 = count remdup :n] [not member? 0 :n])\nend\n\nto init\n  do.until [make \"hidden random 10000] [ok? :hidden]\nend\n\nto guess :n\n  if not ok? :n [print [Bad guess! (4 unique digits, 1-9)]  stop]\n  localmake \"bulls 0\n  localmake \"cows  0\n  foreach :n [cond [\n    [[? = item # :hidden] make \"bulls 1 + :bulls]\n    [[member? \u00a0? :hidden] make \"cows  1 + :cows ]\n  ]]\n  (print :bulls \"bulls, :cows \"cows)\n  if :bulls = 4 [print [You guessed it!]]\nend\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":2270}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\n\nto random.float  \u00a0; 0..1\n  localmake \"max.int lshift -1 -1\n  output quotient random :max.int :max.int\nend\n\nto random.gaussian\n  output product cos random 360  sqrt -2 \/ ln random.float\nend\n\nmake \"randoms cascade 1000 [fput random.gaussian \/ 2 + 1\u00a0?] []\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using a built-in floating point random generator or an algorithm for uniformly distributed random numbers.","id":2271}
    {"lang_cluster":"Logo","source_code":"\nto dotprod :a :b\n  output apply \"sum (map \"product :a :b)\nend\n\nshow dotprod [1 3 -5] [4 -2 -1]   \u00a0; 3\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":2272}
    {"lang_cluster":"Logo","source_code":"\n\nreadline - returns a line as a list of words\nreadword - returns a line as a single word, or an empty list if it reached the end of file\nreadrawline - returns a line as a single word, with no characters escaped\nwhile [not eof?] [print readline]\n","human_summarization":"continuously read data from a text stream either word-by-word or line-by-line until there is no more data available.","id":2273}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\nOther Logo variants might have a built-in command, but UCB Logo must access the Unix shell to get time.to time\n  output first first shell [date +%s]\nend\n\nmake \"start time\nwait 300             \u00a0; 60ths of a second\nprint time - :start  \u00a0; 5\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":2274}
    {"lang_cluster":"Logo","source_code":"\n\nWorks with: MSWlogo\nto sphere :r\ncs perspective ht ;making the room ready to use\nrepeat 180 [polystart circle :r polyend down 1]\npolyview\nend\n","human_summarization":"represent the functionality of drawing a sphere, either graphically or in ASCII art, with the option of static or rotational projection. The drawing process is simplified in logo using the perspective function.","id":2275}
    {"lang_cluster":"Logo","source_code":"\nto strip :string :chars\n  output filter [not substringp\u00a0? :chars] :string\nend\n\nprint strip \"She\\ was\\ a\\ soul\\ stripper.\\ She\\ took\\ my\\ heart! \"aei\n\nbye\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":2276}
    {"lang_cluster":"Logo","source_code":"\nto dcr :step :length\n  make \"step :step - 1\n  make \"length :length \/ 1.41421\n  if :step > 0 [rt 45 dcr :step :length lt 90 dcl :step :length rt 45]\n  if :step = 0 [rt 45 fd :length lt 90 fd :length rt 45]\nend\n\nto dcl :step :length\n  make \"step :step - 1\n  make \"length :length \/ 1.41421\n  if :step > 0 [lt 45 dcr :step :length rt 90 dcl :step :length lt 45]\n  if :step = 0 [lt 45 fd :length rt 90 fd :length lt 45]\nend\n\nto dc :step :length :dir\n  if :step = 0 [fd :length stop]\n  rt :dir\n  dc :step-1 :length\/1.41421  45\n  lt :dir lt :dir\n  dc :step-1 :length\/1.41421 -45\n  rt :dir\nend\nto dragon :step :length\n  dc :step :length 45\nend\n\nto O :step :length\n  if :step=1 [Rt 90 fd :length Lt 90] [O (:step - 1) (:length \/ 1.41421) N (:step - 1) (:length \/ 1.41421)]\nend\n\nto N :step :length\n  if :step=1 [fd :length] [W (:step - 1) (:length \/ 1.41421) N (:step - 1) (:length \/ 1.41421)]\nend\n\nto W :step :length\n  if :step=1 [Lt 90 fd :length Rt 90] [W (:step - 1) (:length \/ 1.41421) S (:step - 1) (:length \/ 1.41421)]\nend \n\nto S :step :length\n  if :step=1 [Rt 180 fd :length Lt 180] [O (:step - 1) (:length \/ 1.41421) S (:step - 1) (:length \/ 1.41421)]\nend\n\nWorks with: UCB Logo\n; Return the bit above the lowest 1-bit in :n.\n; If :n = binary \"...z100..00\" then the return is \"z000..00\".\n; Eg. n=22 is binary 10110 the lowest 1-bit is the \"...1.\" and the return is\n; bit above that \"..1.,\" which is 4.\nto bit.above.lowest.1bit :n\n  output bitand :n (1 + (bitxor :n (:n - 1)))\nend\n\n; Return angle +90 or -90 for dragon curve turn at point :n.\n; The curve is reckoned as starting from n=0 so the first turn is at n=1.\nto dragon.turn.angle :n\n  output ifelse (bit.above.lowest.1bit :n) = 0  [90] [-90]\nend\n\n; Draw :steps many segments of the dragon curve.\nto dragon :steps\n  localmake \"step.len 12 \u00a0; length of each step\n  repeat :steps [\n    forward :step.len\n    left    dragon.turn.angle repcount \u00a0; repcount = 1 to :steps inclusive\n  ]\nend\n\ndragon 256\n; Draw :steps many segments of the dragon curve, with corners chamfered\n; off with little 45-degree diagonals.\n; Done this way the vertices don't touch.\nto dragon.chamfer :steps\n  localmake \"step.len       12 \u00a0; length of each step\n  localmake \"straight.frac  0.5\u00a0; fraction of the step to go straight\n\n  localmake \"straight.len   :step.len * :straight.frac\n  localmake \"diagonal.len   (:step.len - :straight.len) * sqrt(1\/2)\n\n  repeat :steps [\n     localmake \"turn  (dragon.turn.angle repcount)\/2  \u00a0; +45 or -45\n     forward :straight.len\n     left    :turn\n     forward :diagonal.len\n     left    :turn\n  ]\nend\n\ndragon.chamfer 256\n","human_summarization":"The code generates a dragon curve fractal, which can be displayed directly or written to an image file. It uses recursive and iterative methods, as well as successive approximation and Lindenmayer system of expansions. The dragon curve is constructed by following specific algorithms that determine the curl direction and the angle of the curve. The code also includes functions to calculate the absolute direction, X,Y coordinates of a point, and to test whether a given point or segment is on the curve. It can be started with parameters to determine the desired expansion level and curl direction.","id":2277}
    {"lang_cluster":"Logo","source_code":"\n\nshow map \"char iseq 97 122\n\nshow map \"char apply \"iseq map \"ascii [a z]\n\n\n","human_summarization":"generate an array, list, or string of all lowercase ASCII characters from 'a' to 'z'. The code should be written in a reliable style suitable for a large program and use strong typing if possible. It should avoid manually enumerating all the lowercase characters to prevent bugs. It should be straightforward and avoid using magic numbers.","id":2278}
    {"lang_cluster":"Logo","source_code":"\nto small? :list\n  output or [empty? :list] [empty? bf :list]\nend\nto every.other :list\n  if small? :list [output :list]\n  output fput first :list every.other bf bf :list\nend\nto wordtolist :word\n  output map.se [?] :word\nend\n\nto double.digit :digit\n  output item :digit {0 2 4 6 8 1 3 5 7 9}@0\n \u00a0; output ifelse :digit < 5 [2*:digit] [1 + modulo 2*:digit 10]\nend\n\nto luhn :credit\n  localmake \"digits reverse filter [number?\u00a0?] wordtolist :credit\n  localmake \"s1 apply \"sum every.other :digits\n  localmake \"s2 apply \"sum map \"double.digit every.other bf :digits\n  output equal? 0 last sum :s1 :s2\nend\n\nshow luhn \"49927398716         \u00a0; true\nshow luhn \"49927398717         \u00a0; false\nshow luhn \"1234-5678-1234-5678 \u00a0; false\nshow luhn \"1234-5678-1234-5670 \u00a0; true\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":2279}
    {"lang_cluster":"Logo","source_code":"\nto copies :n :thing [:acc \"||]\n  if :n = 0 [output :acc]\n  output (copies :n-1 :thing combine :acc :thing)\nend\n\nshow cascade 5 [combine \"ha\u00a0?] \"||   \u00a0; hahahahaha\n\nto copies :n :thing :acc\n  if :n = 0 [output :acc]\n  output (copies :n-1 :thing combine :acc :thing)\nend\n\nprint copies 5 \"ha \"||\n","human_summarization":"implement a function to repeat a given string a specified number of times. It also demonstrates an efficient way to repeat a single character to create a new string. The code does not include the cascade feature or the ability to initialize a missing parameter.","id":2280}
    {"lang_cluster":"Logo","source_code":"\nto operate :a :b\n  (print [a =] :a)\n  (print [b =] :b)\n  (print [a + b =] :a + :b)\n  (print [a - b =] :a - :b)\n  (print [a * b =] :a * :b)\n  (print [a \/ b =] int :a \/ :b)\n  (print [a mod b =] modulo :a :b)\nend\n\n","human_summarization":"take two integers as input from the user and calculate their sum, difference, product, integer quotient, remainder and exponentiation. It also indicates the rounding direction for quotient and the sign of the remainder. Additionally, it includes an example of the integer `divmod` operator. The code does not handle errors.","id":2281}
    {"lang_cluster":"Logo","source_code":"\nto move :n :from :to :via\n  if :n = 0 [stop]\n  move :n-1 :from :via :to\n  (print [Move disk from] :from [to] :to)\n  move :n-1 :via :to :from\nend\nmove 4 \"left \"middle \"right\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":2282}
    {"lang_cluster":"Logo","source_code":"\nto choose :n :k\n  if :k = 0 [output 1]\n  output (choose :n :k-1) * (:n - :k + 1) \/ :k\nend\n\nshow choose 5 3  \u00a0; 10\nshow choose 60 30\u00a0; 1.18264581564861e+17\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":2283}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\nto rotate.left :thing\n  output lput first :thing butfirst :thing\nend\nto rotate.right :thing\n  output fput last :thing butlast :thing\nend\n\nmake \"text \"|Hello World! |\nmake \"right? \"true\n\nto step.animation\n  label :text\t\t\t; graphical\n \u00a0; type char 13  type :text\t; textual\n  wait 6\t\t\t; 1\/10 second\n  if button <> 0 [make \"right? not :right?]\n  make \"text ifelse :right? [rotate.right :text] [rotate.left :text]\nend\n\nhideturtle\nuntil [key?] [step.animation]\n\n","human_summarization":"create a GUI window displaying a rotating \"Hello World!\" text. The rotation direction reverses when the text is clicked by the user.","id":2284}
    {"lang_cluster":"Logo","source_code":"\nmake \"val 0\ndo.while [make \"val :val + 1  print :val] [notequal? 0 modulo :val 6]\ndo.until [make \"val :val + 1  print :val] [equal? 0 modulo :val 6]\n\nto my.loop :n\n  make \"n :n + 1\n  print :n\n  if notequal? 0 modulo :n 6 [my.loop :n]\nend\nmy.loop 0\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":2285}
    {"lang_cluster":"Logo","source_code":"\n\nprint count \"|Hello World| \u00a0; 11\nprint count \"m\u00f8\u00f8se           \u00a0; 5\nprint char 248  \u00a0; \u00f8 - implies ISO-Latin character set\n","human_summarization":"The code calculates the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. It correctly handles Unicode code points, including Non-BMP ones, and provides the actual character counts in code points, not in code unit counts. It also has the capability to provide the string length in graphemes if the language supports it. However, it only supports ASCII encoding for Logo due to its age.","id":2286}
    {"lang_cluster":"Logo","source_code":"\nmake \"s \"|My string|\nprint butfirst :s\nprint butlast :s\nprint butfirst butlast :s\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":2287}
    {"lang_cluster":"Logo","source_code":"\nto swap :i :j :a\n  localmake \"t item :i :a\n  setitem :i :a item :j :a\n  setitem :j :a :t\nend\nto shuffle :a\n  for [i [count :a] 2] [swap 1 + random :i :i :a]\nend\n\nmake \"a {1 2 3 4 5 6 7 8 9 10}\nshuffle :a\nshow :a\n\nto slice :lst :start :finish\n\tlocal \"res\n\tmake \"res []\n\tfor \"i [:start :finish 1] [\n\t\tmake \"j item :i :lst\n\t\tmake \"res se :res :j\n\t]\n\top :res\nend\n\nto setitem :n :lst :val\n\tlocal \"lhs\n\tlocal \"rhs\n\tmake \"lhs slice :lst 1 :n-1\n\tmake \"rhs slice :lst :n+1 count :lst\n\top (se :lhs :val :rhs)\nend\n\nto swap :i :j :a\n\tlocal \"t\n\tmake \"t item :i :a\n\tmake \"a setitem :i :a item :j :a\n\tmake \"a setitem :j :a :t\n\top :a\nend\n\nto shuffle :a\n\tfor \"i [count :a 2] \n\t[\n\t\tmake \"a swap 1 + random :i :i :a\n\t]\n\top :a\nend\n \nmake \"a ( list 1 2 3 4 5 6 7 8 9 10 )\nmake \"a shuffle :a\nshow :a\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an input array in-place. If in-place modification is not possible, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be adjusted to iterate from left to right if necessary.","id":2288}
    {"lang_cluster":"Logo","source_code":"\n; Determine if a Gregorian calendar year is leap \nto leap? :year\n  output (and \n    equal? 0 modulo :year 4\n    not member? modulo :year 400 [100 200 300]\n  )\nend\n\n; Convert Gregorian calendar date to a simple day count from \n; RD 1 = January 1, 1 CE \nto day_number :year :month :day\n  local \"elapsed make \"elapsed difference :year 1\n  output (sum  product 365 :elapsed\n              int quotient :elapsed 4\n              minus int quotient :elapsed 100\n              int quotient :elapsed 400\n              int quotient difference product 367 :month 362 12\n              ifelse lessequal? :month 2 0 ifelse leap? :year -1 -2\n              :day)\nend\n\n; Find the day of the week from a day number, 0 = Sunday through 6 = Saturday\nto day_of_week :day_number\n  output modulo :day_number 7\nend\n\n; Find the date of the last Friday of a given month\nto last_friday :year :month\n  local \"zero make \"zero day_number :year :month 0\n  local \"last make \"last day_number :year sum 1 :month 0\n  local \"wday make \"wday day_of_week :last\n  local \"friday make \"friday sum :last remainder difference -2 :wday 7\n  output difference :friday :zero\nend\n\nlocal \"year\nmake \"year ifelse empty? :command.line 2012 :command.line\n\nrepeat 12 [\n  local \"month make \"month #\n  local \"day make \"day last_friday :year :month\n  if (less? :month 10) [make \"month word \"0 :month]\n  print reduce [(word ?1 \"- ?2)] (list :year :month :day)\n]\nbye\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":2289}
    {"lang_cluster":"Logo","source_code":"Works with: UCB Logo\n; some useful constants\nmake \"lower_a ascii \"a\nmake \"lower_z ascii \"z\nmake \"upper_a ascii \"A\nmake \"upper_z ascii \"Z\n\n; encipher a single character\nto encipher_char :char :key\n local \"code make \"code ascii :char\n local \"base make \"base 0\n ifelse [and (:code >= :lower_a) (:code <= :lower_z)] [make \"base :lower_a] [\n     if [and (:code >= :upper_a) (:code <= :upper_z)] [make \"base :upper_a] ]\n ifelse [:base > 0] [\n   output char (:base + (modulo ( :code - :base + :key ) 26 ))\n ] [\n   output :char\n ]\nend\n\n; encipher a whole string\nto caesar_cipher :string :key\n  output map [encipher_char\u00a0? :key] :string\nend\n\n; Demo\nmake \"plaintext \"|The five boxing wizards jump quickly|\nmake \"key 3\nmake \"ciphertext caesar_cipher :plaintext :key\nmake \"recovered  caesar_cipher :ciphertext -:key\n\nprint sentence \"| Original:| :plaintext\nprint sentence \"|Encrypted:| :ciphertext\nprint sentence \"|Recovered:| :recovered\nbye\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":2290}
    {"lang_cluster":"Logo","source_code":"\nto abs :n\n  output sqrt product :n :n\nend\n\nto gcd :m :n\n  output ifelse :n = 0 [ :m ] [ gcd :n modulo :m :n ]\nend\n\nto lcm :m :n\n  output quotient (abs product :m :n) gcd :m :n\nend\n\nprint lcm 38 46\n\n874\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all multiples of m until one is found that is also a multiple of n, or by using the formula lcm(m, n) = |m x n| \/ gcd(m, n), where gcd is the greatest common divisor. Additionally, the LCM can be found by merging the prime decompositions of both m and n.","id":2291}
    {"lang_cluster":"Logo","source_code":"\nforeach [red green blue] [print\u00a0?]\n","human_summarization":"Iterates through each element in a collection in order and prints it, using a \"for each\" loop or another loop if \"for each\" is not available in the language.","id":2292}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\nto split :str :sep\n  output parse map [ifelse\u00a0? = :sep [\"| |] [?]] :str\nend\n\nto split :str :by [:acc []] [:w \"||]\n  if empty? :str [output lput :w :acc]\n  ifelse equal? first :str :by ~\n    [output (split butfirst :str :by lput :w :acc)] ~\n    [output (split butfirst :str :by         :acc  lput first :str :w)]\nend\n? show split \"Hello,How,Are,You,Today \",\n[Hello How Are You Today]\n","human_summarization":"tokenize a string by commas into an array, and display the words separated by a period, handling embedded spaces.","id":2293}
    {"lang_cluster":"Logo","source_code":"\nto gcd :a :b\n  if :b = 0 [output :a]\n  output gcd :b  modulo :a :b\nend\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":2294}
    {"lang_cluster":"Logo","source_code":"\nshow number? \"-1.23   \u00a0; true\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":2295}
    {"lang_cluster":"Logo","source_code":"\n\nprint sin 45\nprint cos 45\nprint arctan 1\nmake \"pi (radarctan 0 1) * 2\u00a0; based on quadrant if uses two parameters\nprint radsin :pi \/ 4\nprint radcos :pi \/ 4\nprint 4 * radarctan 1\n\nprint sin 45\nprint cos 45\nprint arctan 1\nprint radsin pi \/ 4\nprint radcos pi \/ 4\nprint 4 * radarctan 1\n","human_summarization":"demonstrate the usage of trigonometric functions such as sine, cosine, tangent and their inverses in a specific programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the same angle is used for both sine calls. For inverse functions, the same number is used and its result is converted to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities. The code also includes specific features of UCB Logo and Lhogho languages.","id":2296}
    {"lang_cluster":"Logo","source_code":"\n\nshow \"123 + 1 \u00a0; 124\nshow word? (\"123 + 1)\u00a0;  true\n","human_summarization":"\"Code increments a numerical string, leveraging Logo's weakly typed nature to treat strings as numbers and vice versa.\"","id":2297}
    {"lang_cluster":"Logo","source_code":"\nto fizzbuzz :n\n  output cond [ [[equal? 0 modulo :n 15] \"FizzBuzz]\n                [[equal? 0 modulo :n  5] \"Buzz]\n                [[equal? 0 modulo :n  3] \"Fizz]\n                [else :n] ]\nend\n\nrepeat 100 [print fizzbuzz #]\n\nto fizzbuzz :n\n make \"c \"\n  if equal? 0 modulo :n 5 [make \"c \"Buzz]\n  if equal? 0 modulo :n 3 [make \"c word \"Fizz :c]\n output ifelse equal? :c \" [:n] [:c]\nend\n\nrepeat 100 [print fizzbuzz repcount]\n\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":2298}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\nto mandelbrot :left :bottom :side :size\n  cs setpensize [1 1]\n  make \"inc :side\/:size\n  make \"zr :left\n  repeat :size [\n    make \"zr :zr + :inc\n    make \"zi :bottom\n    pu\n    setxy repcount - :size\/2  minus :size\/2\n    pd\n    repeat :size [\n      make \"zi :zi + :inc\n      setpencolor count.color calc :zr :zi\n      fd 1 ] ]\nend\n\nto count.color :count\n  ;op (list :count :count :count)\n  if :count > 256 [op 0]\t; black\n  if :count > 128 [op 7]\t; white\n  if :count >  64 [op 5]\t; magenta\n  if :count >  32 [op 6]\t; yellow\n  if :count >  16 [op 4]\t; red\n  if :count >   8 [op 2]\t; green\n  if :count >   4 [op 1]\t; blue\n  op 3\t\t\t\t; cyan\nend\n\nto calc :zr :zi [:count 0] [:az 0] [:bz 0]\n  if :az*:az + :bz*:bz > 4 [op :count]\n  if :count > 256 [op :count]\n  op (calc :zr :zi (:count + 1) (:zr + :az*:az - :bz*:bz) (:zi + 2*:az*:bz))\nend\n\nmandelbrot -2 -1.25 2.5 400\n","human_summarization":"generate and draw the Mandelbrot set using various available algorithms and functions.","id":2299}
    {"lang_cluster":"Logo","source_code":"\nprint apply \"sum arraytolist {1 2 3 4 5}\nprint apply \"product arraytolist {1 2 3 4 5}\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":2300}
    {"lang_cluster":"Logo","source_code":"\nto multiple? :n :d\n  output equal? 0 modulo :n :d\nend\nto leapyear? :y\n  output ifelse multiple? :y 100 [multiple? :y 400] [multiple? :y 4]\nend\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":2301}
    {"lang_cluster":"Logo","source_code":"\n\nmake \"a \"foo\nmake \"b \"foo\nprint .eq :a :b  \u00a0; true, identical symbols are reused\n\nmake \"c :a\nprint .eq :a :c  \u00a0; true, copy a reference\n\nmake \"c word :b \"|| \u00a0; force a copy of the contents of a word by appending the empty word\nprint equal? :b :c  \u00a0; true\nprint .eq :b :c    \u00a0; false\n","human_summarization":"\"Implements a function to copy a string, distinguishing between copying the content of a string and creating an additional reference to an existing string. In the context of UCB Logo, it uses the EQUAL? predicate for content comparison and the .EQ predicate for identity comparison due to its functional language nature where words are treated as symbols.\"","id":2302}
    {"lang_cluster":"Logo","source_code":"\n\nto m :n\n  if 0 = :n [output 0]\n  output :n - f m :n-1\nend\nto f :n\n  if 0 = :n [output 1]\n  output :n - m f :n-1\nend\n\nshow cascade 20 [lput m #-1\u00a0?] []\n[1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12]\nshow cascade 20 [lput f #-1\u00a0?] []\n[0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12]\n","human_summarization":"implement two mutually recursive functions to calculate the Hofstadter Female and Male sequences. The functions use each other to compute the sequence values based on the provided formulas. If the programming language does not support mutual recursion, it should be stated.","id":2303}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\npick [1 2 3]\n","human_summarization":"demonstrate how to select a random element from a list.","id":2304}
    {"lang_cluster":"Logo","source_code":"\nto bsearch :value :a :lower :upper\n  if :upper < :lower [output []]\n  localmake \"mid int (:lower + :upper) \/ 2\n  if item :mid :a > :value [output bsearch :value :a :lower :mid-1]\n  if item :mid :a < :value [output bsearch :value :a :mid+1 :upper]\n  output :mid\nend\n","human_summarization":"The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It takes a sorted integer array, a starting point, an ending point, and a \"secret value\" as inputs. The algorithm can be either recursive or iterative and returns whether the number was in the array and its index if found. The code also includes variations of the binary search algorithm that return the leftmost or rightmost insertion point for the given value. It also handles potential overflow bugs.","id":2305}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo version 5.6\n\nlogo file.logo - arg1 arg2 arg3\n\n\nshow :COMMAND.LINE\n[arg1 arg2 arg3]\n\n#! \/usr\/bin\/logo -\n\n\nfile.logo arg1 arg2 arg3\n\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program. It can intelligently parse these arguments. For instance, in the command line 'myprogram -c \"alpha beta\" -h \"gamma\"', the arguments after the \"-\" are stored in a list in the variable :COMMAND.LINE. The code also allows the execution of a logo script with arguments.","id":2306}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB Logo\nmake \"angle 45\nmake \"L 1\nmake \"bob 10\n\nto draw.pendulum\n  clearscreen\n  seth :angle+180\t\t; down on screen is 180\n  forward :L*100-:bob\n  penup\n  forward :bob\n  pendown\n  arc 360 :bob\nend\n\nmake \"G   9.80665\nmake \"dt  1\/30\nmake \"acc 0\nmake \"vel 0\n\nto step.pendulum\n  make \"acc  -:G \/ :L * sin :angle\n  make \"vel   :vel   + :acc * :dt\n  make \"angle :angle + :vel * :dt\n  wait :dt*60\n  draw.pendulum\nend\n\nhideturtle\nuntil [key?] [step.pendulum]\n","human_summarization":"create and animate a simple physical model of a gravity pendulum.","id":2307}
    {"lang_cluster":"Logo","source_code":"\nto about :a :b\n  output and [:a - :b < 1e-5] [:a - :b > -1e-5]\nend\n\nto root :n :a [:guess :a]\n  localmake \"next ((:n-1) * :guess + :a \/ power :guess (:n-1)) \/ n\n  if about :guess :next [output :next]\n  output (root :n :a :next)\nend\n\nshow root 5 34  \u00a0; 2.02439745849989\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":2308}
    {"lang_cluster":"Logo","source_code":"\nWorks with: UCB_Logo version 5.5\n; useful constants\nmake \"false 1=0\nmake \"true  1=1\nmake \"lf char 10\nmake \"sp char 32\n\n; non-digits legal in expression\nmake \"operators (lput sp [+ - * \/ \\( \\)])\n\n; display help message\nto show_help :digits\n  type lf\n  print sentence quoted [Using only these digits:] :digits \n  print sentence quoted [and these operators:] [* \/ + -]\n  print quoted [\\(and parentheses as needed\\),]\n  print quoted [enter an arithmetic expression \n     which evaluates to exactly 24.]\n  type lf\n  print quoted [Enter \\\"!\\\" to get fresh numbers.]\n  print quoted [Enter \\\"q\\\" to quit.]\n  type lf\nend\n\nmake \"digits []\nmake \"done false\nuntil [done] [\n\n  if empty? digits [\n    make \"digits (map [(random 9) + 1] [1 2 3 4])\n  ]\n\n  (type \"Solution sp \"for sp digits \"? sp )\n  make \"expression readrawline\n\n  ifelse [expression = \"?] [\n\n    show_help digits\n\n  ] [ifelse [expression = \"q] [\n\n    print \"Bye!\n    make \"done true\n\n  ] [ifelse [expression = \"!] [\n\n    make \"digits []\n\n  ] [\n    make \"exprchars ` expression\n    make \"allowed (sentence digits operators)\n\n    ifelse (member? false (map [[c] member? c allowed] exprchars)) [\n      (print quoted [Illegal character in input.])\n    ] [\n      catch \"error [\n        make \"syntax_error true\n        make \"testval (run expression)\n        make \"syntax_error false\n      ]\n      ifelse syntax_error [\n        (print quoted [Invalid expression.])\n      ] [\n        ifelse (testval = 24) [\n          print quoted [You win!]\n          make \"done true\n        ] [\n          (print (sentence \n            quoted [Incorrect \\(got ] testval quoted [instead of 24\\).]))\n        ]\n      ]\n    ]\n  ]]]\n] \nbye\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":2309}
    {"lang_cluster":"Logo","source_code":"\nto encode :str [:out \"||] [:count 0] [:last first :str]\n  if empty? :str [output (word :out :count :last)]\n  if equal? first :str :last [output (encode bf :str :out :count+1 :last)]\n  output (encode bf :str (word :out :count :last) 1 first :str)\nend\n\nto reps :n :w\n  output ifelse :n = 0 [\"||] [word :w reps :n-1 :w]\nend\nto decode :str [:out \"||] [:count 0]\n  if empty? :str [output :out]\n  if number? first :str [output (decode bf :str :out 10*:count + first :str)]\n  output (decode bf :str word :out reps :count first :str)\nend\n\nmake \"foo \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nmake \"rle encode :foo\nshow equal? :foo decode :rle\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":2310}
    {"lang_cluster":"Logo","source_code":"\nmake \"s \"hello\nprint word :s \"| there!|\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":2311}
    {"lang_cluster":"Logo","source_code":"\nWorks with: MSWlogo\nto clickwindow\nwindowCreate \"root \"clickWin [Click that button!!!] 0 0 100 100 []\nMake \"i 0\nstaticCreate \"clickWin \"clickSt [There have been no clicks yet] 0 0 100 20\nbuttonCreate \"clickWin \"clickBtn [click me] 10 20 80 20 ~\n\t[Make \"i :i+1 ~\n\tifelse :i=1 [staticUpdate \"clickSt (list \"clicked :i \"time)] ~\n\t            [staticUpdate \"clickSt (list \"clicked :i \"times)]]\nend\n\nclickwindow\n","human_summarization":"\"Creates a windowed application with a label and a button. The label initially displays 'There have been no clicks yet'. The button labeled 'click me' updates the label to show the number of times it has been clicked when interacted with.\"","id":2312}
    {"lang_cluster":"Logo","source_code":"\n\nfor [i 10 0] [print :i]\n","human_summarization":"The code uses a for loop to perform a countdown from 10 to 0. If the limit is less than the start, the control variable is decremented. A fourth parameter can be provided for a custom increment.","id":2313}
    {"lang_cluster":"Logo","source_code":"\nfor [i 2 8 2] [type :i type \"|, |] print [who do we appreciate?]\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":2314}
    {"lang_cluster":"Logo","source_code":"\nto ack :i :j\n  if :i = 0 [output :j+1]\n  if :j = 0 [output ack :i-1 1]\n  output ack :i-1 ack :i :j-1\nend\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":2315}
    {"lang_cluster":"Logo","source_code":"\nto try :files :diag1 :diag2 :tried\n  if :files = 0 [make \"solutions :solutions+1  show :tried  stop]\n  localmake \"safe (bitand :files :diag1 :diag2)\n  until [:safe = 0] [\n    localmake \"f bitnot bitand :safe minus :safe\n    try bitand :files :f  ashift bitand :diag1 :f -1  (ashift bitand :diag2 :f 1)+1  fput bitnot :f :tried\n    localmake \"safe bitand :safe :safe-1\n  ]\nend\n\nto queens :n\n  make \"solutions 0\n  try (lshift 1 :n)-1 -1 -1 []\n  output :solutions\nend\n\nprint queens 8 \u00a0; 92\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":2316}
    {"lang_cluster":"Logo","source_code":"\n\nto combine-arrays :a1 :a2        \n  output listtoarray sentence arraytolist :a1 arraytolist :a2\nend\nshow combine-arrays {1 2 3} {4 5 6}  \u00a0; {1 2 3 4 5 6}\n","human_summarization":"demonstrate how to concatenate two arrays, possibly using the '+' operator or the 'COMBINE' and 'SENTENCE' functions.","id":2317}
    {"lang_cluster":"Logo","source_code":"\n\nand [notequal? :x 0] [1\/:x > 3]\n(or [:x < 0] [:y < 0] [sqrt :x + sqrt :y <  3])\n","human_summarization":"The code defines two functions, a and b, both of which accept and return a boolean value and print their names when called. The code then calculates the values of two equations, x = a(i) and b(j), and y = a(i) or b(j), using short-circuit evaluation to ensure that function b is only called when necessary. If the programming language does not support short-circuit evaluation, this is achieved using nested if statements. The AND and OR operators are used in a way that evaluates expressions from left to right until the overall value can be determined.","id":2318}
    {"lang_cluster":"Logo","source_code":"\nmake \"blocks [[B O] [X K] [D Q] [C P] [N A] [G T] [R E] [T G] [Q D] [F S]\n              [J W] [H U] [V I] [A N] [O B] [E R] [F S] [L Y] [P C] [Z M]]\n\nto can_make? :word [:avail :blocks]\n  if empty? :word [output \"true]\n  local \"letter make \"letter first :word\n  foreach :avail [\n    local \"i     make \"i     #\n    local \"block make \"block\u00a0?\n    if member? :letter :block [\n      if (can_make? bf :word filter [notequal? # :i] :avail) [output \"true]\n    ]\n  ]\n  output \"false\nend\n\nforeach [A BARK BOOK TREAT COMMON SQUAD CONFUSE] [\n  print sentence word\u00a0? \": can_make?\u00a0?\n]\n\nbye\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":2319}
    {"lang_cluster":"Logo","source_code":"\n\nto increment_octal :n\n  ifelse [empty? :n] [\n    output 1\n  ] [\n    local \"last\n    make \"last last :n\n    local \"butlast\n    make \"butlast butlast :n\n    make \"last sum :last 1\n    ifelse [:last < 8] [\n      output word :butlast :last\n    ] [\n      output word (increment_octal :butlast) 0\n    ]\n  ]\nend\n\nmake \"oct 0\nwhile [\"true] [\n  print :oct\n  make \"oct increment_octal :oct\n]\n","human_summarization":"generate a sequential count in octal format, starting from zero and incrementing by one. Each number is printed on a separate line and the count continues until the program is terminated or the maximum value of the numeric type is reached. The program avoids the use of built-in octal-formatting for efficiency and instead manually increments a string.","id":2320}
    {"lang_cluster":"Logo","source_code":"\nto swap :s1 :s2\n  localmake \"t thing :s1\n  make :s1 thing :s2\n  make :s2 :t\nend\n\nmake \"a 4\nmake \"b \"dog\nswap \"a \"b       \u00a0; pass the names of the variables to swap\nshow list :a :b \u00a0; [dog 4]\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.","id":2321}
    {"lang_cluster":"Logo","source_code":"\nto palindrome? :w\n  output equal? :w reverse :w\nend\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":2322}
    {"lang_cluster":"Scala","source_code":"\n\nclass Stack[T] {\n  private var items = List[T]()\n\n  def isEmpty = items.isEmpty\n\n  def peek = items match {\n    case List()       => error(\"Stack empty\")\n    case head\u00a0:: rest => head\n  }\n\n  def pop = items match {\n    case List()       => error(\"Stack empty\")\n    case head\u00a0:: rest => items = rest; head\n  }\n\n  def push(value: T) = items = value +: items\n}\n\nimport collection.mutable.{ Stack => Stak }\n\nclass Stack[T] extends Stak[T] {\n  override def pop: T = {\n    if (this.length == 0) error(\"Can't Pop from an empty Stack.\")\n    else super.pop\n  }\n  def peek: T = this.head\n}A test could be:object StackTest extends App {\n\n  val stack = new Stack[String]\n\n  stack.push(\"Peter Pan\")\n  stack.push(\"Suske & Wiske\", \"Alice in Wonderland\")\n\n  assert(stack.peek == \"Alice in Wonderland\")\n  assert(stack.pop() == \"Alice in Wonderland\")\n  assert(stack.pop() == \"Suske & Wiske\")\n  assert(stack.pop() == \"Peter Pan\")\n  println(\"Completed without errors\")\n}\n","human_summarization":"implement a stack with basic operations including push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and is accessed through its top. The push operation stores a new element onto the stack top, pop operation returns and removes the last pushed stack element, and empty operation checks if the stack contains no elements. The top operation returns the topmost element without modifying the stack.","id":2323}
    {"lang_cluster":"Scala","source_code":"\ndef fib(i: Int): Int = i match {\n  case 0 => 0\n  case 1 => 1\n  case _ => fib(i - 1) + fib(i - 2)\n}\nlazy val fib: LazyList[Int] = 0 #:: 1 #:: fib.zip(fib.tail).map { case (a, b) => a + b }\nimport scala.annotation.tailrec\n@tailrec\nfinal def fib(x: Int, prev: BigInt = 0, next: BigInt = 1): BigInt = x match {\n  case 0 => prev\n  case _ => fib(x - 1, next, next + prev)\n}\n\/\/ Fibonacci using BigInt with LazyList.foldLeft optimized for GC (Scala v2.13 and above)\n\/\/ Does not run out of memory for very large Fibonacci numbers\ndef fib(n: Int): BigInt = {\n\n  def series(i: BigInt, j: BigInt): LazyList[BigInt] = i #:: series(j, i + j)\n\n  series(1, 0).take(n).foldLeft(BigInt(\"0\"))(_ + _)\n}\n\n\/\/ Small test\n(0 to 13) foreach {n => print(fib(n).toString + \" \")}\n\n\/\/ result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233\nval it: Iterator[Int] = Iterator.iterate((0, 1)) { case (a, b) => (b, a + b) }.map(_._1)\n\ndef fib(n: Int): Int = it.drop(n).next()\n\n\/\/ example:\nprintln(it.take(13).mkString(\",\")) \/\/ prints: 0,1,1,2,3,5,8,13,21,34,55,89,144\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":2324}
    {"lang_cluster":"Scala","source_code":"\n(1 to 100).filter(_\u00a0% 2 == 0)\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":2325}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nobject Substring {\n  \/\/ Ruler             1         2         3         4         5         6\n  \/\/         012345678901234567890123456789012345678901234567890123456789012\n  val str = \"The good life is one inspired by love and guided by knowledge.\"\n  val (n, m) = (21, 16) \/\/ An one-liner to set n = 21, m = 16\n\n  \/\/ Starting from n characters in and of m length\n  assert(\"inspired by love\" == str.slice(n, n + m))\n  \n  \/\/ Starting from n characters in, up to the end of the string\n  assert(\"inspired by love and guided by knowledge.\" == str.drop(n))\n  \n  \/\/ Whole string minus last character\n  assert(\"The good life is one inspired by love and guided by knowledge\" == str.init)\n  \n  \/\/ Starting from a known character within the string and of m length\n  assert(\"life is one insp\" == str.dropWhile(_\u00a0!= 'l').take(m) )\n  \n  \/\/ Starting from a known substring within the string and of m length\n  assert(\"good life is one\" == { val i = str.indexOf(\"good\"); str.slice(i, i + m) })\n  \/\/ Alternatively\n  assert(\"good life is one\" == str.drop(str.indexOf(\"good\")).take(m))\n}\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":2326}
    {"lang_cluster":"Scala","source_code":"\n\n\"asdf\".reverse\n\n\"asdf\".foldRight(\"\")((a,b) => b+a)\n\ndef reverse(s: String) = {\n  import java.text.{Normalizer,BreakIterator}\n  val norm = Normalizer.normalize(s, Normalizer.Form.NFKC) \/\/ wa\ufb04e -> waffle (optional)\n  val it = BreakIterator.getCharacterInstance\n  it setText norm\n  def break(it: BreakIterator, prev: Int, result: List[String] = Nil): List[String] = it.next match {\n    case BreakIterator.DONE => result\n    case cur => break(it, cur, norm.substring(prev, cur)\u00a0:: result)\n  }\n  break(it, it.first).mkString\n}\n\n","human_summarization":"\"Reverses a given string while preserving the order of Unicode combining characters. For instance, \"asdf\" is transformed to \"fdsa\" and \"as\u20dddf\u0305\" is transformed to \"f\u0305ds\u20dda\". The code also handles supplementary characters but does not preserve the order of newline characters or consider directionality. The output is displayed in bytes on Windows due to REPL's inability to handle Unicode.\"","id":2327}
    {"lang_cluster":"Scala","source_code":"\n\nobject Dijkstra {\n  \n  type Path[Key] = (Double, List[Key])\n  \n  def Dijkstra[Key](lookup: Map[Key, List[(Double, Key)]], fringe: List[Path[Key]], dest: Key, visited: Set[Key]): Path[Key] = fringe match {\n    case (dist, path) :: fringe_rest => path match {case key :: path_rest =>\n      if (key == dest) (dist, path.reverse)\n      else {\n        val paths = lookup(key).flatMap {case (d, key) => if (!visited.contains(key)) List((dist + d, key :: path)) else Nil}\n        val sorted_fringe = (paths ++ fringe_rest).sortWith {case ((d1, _), (d2, _)) => d1 < d2}\n        Dijkstra(lookup, sorted_fringe, dest, visited + key)\n      }\n    }\n    case Nil => (0, List())\n  }\n\n  def main(x: Array[String]): Unit = {\n    val lookup = Map(\n      \"a\" -> List((7.0, \"b\"), (9.0, \"c\"), (14.0, \"f\")),\n      \"b\" -> List((10.0, \"c\"), (15.0, \"d\")),\n      \"c\" -> List((11.0, \"d\"), (2.0, \"f\")),\n      \"d\" -> List((6.0, \"e\")),\n      \"e\" -> List((9.0, \"f\")),\n      \"f\" -> Nil\n    )\n    val res = Dijkstra[String](lookup, List((0, List(\"a\"))), \"e\", Set())\n    println(res)\n  }\n}\n\n\n","human_summarization":"implement Dijkstra's algorithm to find the shortest path from a given source node to all other nodes in a directed and weighted graph. The graph is represented by an adjacency matrix or list, and the output is a set of edges depicting the shortest path to each destination node. The algorithm is run on a specific graph with nodes labeled 'a' through 'f' and the shortest path from node 'a' to nodes 'e' and 'f' is determined.","id":2328}
    {"lang_cluster":"Scala","source_code":"\nimport scala.collection.mutable\n\nclass AVLTree[A](implicit val ordering: Ordering[A]) extends mutable.SortedSet[A] {\n\n  if (ordering eq null) throw new NullPointerException(\"ordering must not be null\")\n\n  private var _root: AVLNode = _\n  private var _size = 0\n\n  override def size: Int = _size\n\n  override def foreach[U](f: A => U): Unit = {\n    val stack = mutable.Stack[AVLNode]()\n    var current = root\n    var done = false\n\n    while (!done) {\n      if (current != null) {\n        stack.push(current)\n        current = current.left\n      } else if (stack.nonEmpty) {\n        current = stack.pop()\n        f.apply(current.key)\n\n        current = current.right\n      } else {\n        done = true\n      }\n    }\n  }\n\n  def root: AVLNode = _root\n\n  override def isEmpty: Boolean = root == null\n\n  override def min[B >: A](implicit cmp: Ordering[B]): A = minNode().key\n\n  def minNode(): AVLNode = {\n    if (root == null) throw new UnsupportedOperationException(\"empty tree\")\n    var node = root\n    while (node.left != null) node = node.left\n    node\n  }\n\n  override def max[B >: A](implicit cmp: Ordering[B]): A = maxNode().key\n\n  def maxNode(): AVLNode = {\n    if (root == null) throw new UnsupportedOperationException(\"empty tree\")\n    var node = root\n    while (node.right != null) node = node.right\n    node\n  }\n\n  def next(node: AVLNode): Option[AVLNode] = {\n    var successor = node\n    if (successor != null) {\n      if (successor.right != null) {\n        successor = successor.right\n        while (successor != null && successor.left != null) {\n          successor = successor.left\n        }\n      } else {\n        successor = node.parent\n        var n = node\n        while (successor != null && successor.right == n) {\n          n = successor\n          successor = successor.parent\n        }\n      }\n    }\n    Option(successor)\n  }\n\n  def prev(node: AVLNode): Option[AVLNode] = {\n    var predecessor = node\n    if (predecessor != null) {\n      if (predecessor.left != null) {\n        predecessor = predecessor.left\n        while (predecessor != null && predecessor.right != null) {\n          predecessor = predecessor.right\n        }\n      } else {\n        predecessor = node.parent\n        var n = node\n        while (predecessor != null && predecessor.left == n) {\n          n = predecessor\n          predecessor = predecessor.parent\n        }\n      }\n    }\n    Option(predecessor)\n  }\n\n  override def rangeImpl(from: Option[A], until: Option[A]): mutable.SortedSet[A] = ???\n\n  override def +=(key: A): AVLTree.this.type = {\n    insert(key)\n    this\n  }\n\n  def insert(key: A): AVLNode = {\n    if (root == null) {\n      _root = new AVLNode(key)\n      _size += 1\n      return root\n    }\n\n    var node = root\n    var parent: AVLNode = null\n    var cmp = 0\n\n    while (node != null) {\n      parent = node\n      cmp = ordering.compare(key, node.key)\n      if (cmp == 0) return node \/\/ duplicate\n      node = node.matchNextChild(cmp)\n    }\n\n    val newNode = new AVLNode(key, parent)\n    if (cmp <= 0) parent._left = newNode\n    else parent._right = newNode\n\n    while (parent != null) {\n      cmp = ordering.compare(parent.key, key)\n      if (cmp < 0) parent.balanceFactor -= 1\n      else parent.balanceFactor += 1\n\n      parent = parent.balanceFactor match {\n        case -1 | 1 => parent.parent\n        case x if x < -1 =>\n          if (parent.right.balanceFactor == 1) rotateRight(parent.right)\n          val newRoot = rotateLeft(parent)\n          if (parent == root) _root = newRoot\n          null\n        case x if x > 1 =>\n          if (parent.left.balanceFactor == -1) rotateLeft(parent.left)\n          val newRoot = rotateRight(parent)\n          if (parent == root) _root = newRoot\n          null\n        case _ => null\n      }\n    }\n\n    _size += 1\n    newNode\n  }\n\n  override def -=(key: A): AVLTree.this.type = {\n    remove(key)\n    this\n  }\n\n  override def remove(key: A): Boolean = {\n    var node = findNode(key).orNull\n    if (node == null) return false\n\n    if (node.left != null) {\n      var max = node.left\n\n      while (max.left != null || max.right != null) {\n        while (max.right != null) max = max.right\n\n        node._key = max.key\n        if (max.left != null) {\n          node = max\n          max = max.left\n        }\n      }\n      node._key = max.key\n      node = max\n    }\n\n    if (node.right != null) {\n      var min = node.right\n\n      while (min.left != null || min.right != null) {\n        while (min.left != null) min = min.left\n\n        node._key = min.key\n        if (min.right != null) {\n          node = min\n          min = min.right\n        }\n      }\n      node._key = min.key\n      node = min\n    }\n\n    var current = node\n    var parent = node.parent\n    while (parent != null) {\n      parent.balanceFactor += (if (parent.left == current) -1 else 1)\n\n      current = parent.balanceFactor match {\n        case x if x < -1 =>\n          if (parent.right.balanceFactor == 1) rotateRight(parent.right)\n          val newRoot = rotateLeft(parent)\n          if (parent == root) _root = newRoot\n          newRoot\n        case x if x > 1 =>\n          if (parent.left.balanceFactor == -1) rotateLeft(parent.left)\n          val newRoot = rotateRight(parent)\n          if (parent == root) _root = newRoot\n          newRoot\n        case _ => parent\n      }\n\n      parent = current.balanceFactor match {\n        case -1 | 1 => null\n        case _ => current.parent\n      }\n    }\n\n    if (node.parent != null) {\n      if (node.parent.left == node) {\n        node.parent._left = null\n      } else {\n        node.parent._right = null\n      }\n    }\n\n    if (node == root) _root = null\n\n    _size -= 1\n    true\n  }\n\n  def findNode(key: A): Option[AVLNode] = {\n    var node = root\n    while (node != null) {\n      val cmp = ordering.compare(key, node.key)\n      if (cmp == 0) return Some(node)\n      node = node.matchNextChild(cmp)\n    }\n    None\n  }\n\n  private def rotateLeft(node: AVLNode): AVLNode = {\n    val rightNode = node.right\n    node._right = rightNode.left\n    if (node.right != null) node.right._parent = node\n\n    rightNode._parent = node.parent\n    if (rightNode.parent != null) {\n      if (rightNode.parent.left == node) {\n        rightNode.parent._left = rightNode\n      } else {\n        rightNode.parent._right = rightNode\n      }\n    }\n\n    node._parent = rightNode\n    rightNode._left = node\n\n    node.balanceFactor += 1\n    if (rightNode.balanceFactor < 0) {\n      node.balanceFactor -= rightNode.balanceFactor\n    }\n\n    rightNode.balanceFactor += 1\n    if (node.balanceFactor > 0) {\n      rightNode.balanceFactor += node.balanceFactor\n    }\n    rightNode\n  }\n\n  private def rotateRight(node: AVLNode): AVLNode = {\n    val leftNode = node.left\n    node._left = leftNode.right\n    if (node.left != null) node.left._parent = node\n\n    leftNode._parent = node.parent\n    if (leftNode.parent != null) {\n      if (leftNode.parent.left == node) {\n        leftNode.parent._left = leftNode\n      } else {\n        leftNode.parent._right = leftNode\n      }\n    }\n\n    node._parent = leftNode\n    leftNode._right = node\n\n    node.balanceFactor -= 1\n    if (leftNode.balanceFactor > 0) {\n      node.balanceFactor -= leftNode.balanceFactor\n    }\n\n    leftNode.balanceFactor -= 1\n    if (node.balanceFactor < 0) {\n      leftNode.balanceFactor += node.balanceFactor\n    }\n    leftNode\n  }\n\n  override def contains(elem: A): Boolean = findNode(elem).isDefined\n\n  override def iterator: Iterator[A] = ???\n\n  override def keysIteratorFrom(start: A): Iterator[A] = ???\n\n  class AVLNode private[AVLTree](k: A, p: AVLNode = null) {\n\n    private[AVLTree] var _key: A = k\n    private[AVLTree] var _parent: AVLNode = p\n    private[AVLTree] var _left: AVLNode = _\n    private[AVLTree] var _right: AVLNode = _\n    private[AVLTree] var balanceFactor: Int = 0\n\n    def parent: AVLNode = _parent\n\n    private[AVLTree] def selectNextChild(key: A): AVLNode = matchNextChild(ordering.compare(key, this.key))\n\n    def key: A = _key\n\n    private[AVLTree] def matchNextChild(cmp: Int): AVLNode = cmp match {\n      case x if x < 0 => left\n      case x if x > 0 => right\n      case _ => null\n    }\n\n    def left: AVLNode = _left\n\n    def right: AVLNode = _right\n  }\n\n}\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.","id":2329}
    {"lang_cluster":"Scala","source_code":"\nimport org.scalatest.FunSuite\nimport math._\n\ncase class V2(x: Double, y: Double) {\n  val distance = hypot(x, y)\n  def \/(other: V2) = V2((x+other.x) \/ 2.0, (y+other.y) \/ 2.0)\n  def -(other: V2) = V2(x-other.x,y-other.y)\n  override def equals(other: Any) = other match {\n    case p: V2 => abs(x-p.x) <  0.0001 && abs(y-p.y) <  0.0001\n    case _ => false\n  }\n  override def toString = f\"($x%.4f, $y%.4f)\"\n}\n\ncase class Circle(center: V2, radius: Double)\n\nclass PointTest extends FunSuite {\n  println(\"       p1               p2         r    result\")\n  Seq(\n    (V2(0.1234, 0.9876), V2(0.8765, 0.2345), 2.0, Seq(Circle(V2(1.8631, 1.9742), 2.0), Circle(V2(-0.8632, -0.7521), 2.0))),\n    (V2(0.0000, 2.0000), V2(0.0000, 0.0000), 1.0, Seq(Circle(V2(0.0, 1.0), 1.0))),\n    (V2(0.1234, 0.9876), V2(0.1234, 0.9876), 2.0, \"coincident points yields infinite circles\"),\n    (V2(0.1234, 0.9876), V2(0.8765, 0.2345), 0.5, \"radius is less then the distance between points\"),\n    (V2(0.1234, 0.9876), V2(0.1234, 0.9876), 0.0, \"radius of zero yields no circles\")\n  ) foreach { v =>\n    print(s\"${v._1} ${v._2}  ${v._3}: \")\n    circles(v._1, v._2, v._3) match {\n      case Right(list) => println(list mkString \",\")\n        assert(list === v._4)\n      case Left(error) => println(error)\n        assert(error === v._4)\n    }\n  }\n\n  def circles(p1: V2, p2: V2, radius: Double) = if (radius == 0.0) {\n      Left(\"radius of zero yields no circles\")\n    } else if (p1 == p2) {\n      Left(\"coincident points yields infinite circles\")\n    } else if (radius * 2 < (p1-p2).distance) {\n      Left(\"radius is less then the distance between points\")\n    } else {\n      Right(circlesThruPoints(p1, p2, radius))\n    } ensuring { result =>\n      result.isLeft || result.right.get.nonEmpty\n    }\n\n  def circlesThruPoints(p1: V2, p2: V2, radius: Double): Seq[Circle] = {\n    val diff = p2 - p1\n    val d = pow(pow(radius, 2) - pow(diff.distance \/ 2, 2), 0.5)\n    val mid = p1 \/ p2\n    Seq(\n      Circle(V2(mid.x - d * diff.y \/ diff.distance, mid.y + d * diff.x \/ diff.distance), abs(radius)),\n      Circle(V2(mid.x + d * diff.y \/ diff.distance, mid.y - d * diff.x \/ diff.distance), abs(radius))).distinct\n  }\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":2330}
    {"lang_cluster":"Scala","source_code":"\nscala> import util.control.Breaks.{breakable, break}\nimport util.control.Breaks.{breakable, break}\n\nscala> import util.Random\nimport util.Random\n\nscala> breakable {\n     |   while(true) {\n     |     val a = Random.nextInt(20)\n     |     println(a)\n     |     if(a == 10)\n     |       break\n     |     val b = Random.nextInt(20)\n     |     println(b)\n     |   }\n     | }\n5\n4\n10\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":2331}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\n\/** Find factors of a Mersenne number\n *\n * The implementation finds factors for M929 and further.\n *\n * @example M59 = 2^059 - 1 =             576460752303423487  (   2 msec)\n * @example = 179951 \u00d7 3203431780337.\n *\/\nobject FactorsOfAMersenneNumber extends App {\n\n  val two: BigInt = 2\n  \/\/ An infinite stream of primes, lazy evaluation and memo-ized\n  val oddPrimes = sieve(LazyList.from(3, 2))\n\n  def sieve(nums: LazyList[Int]): LazyList[Int] =\n    LazyList.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0)))\n\n  def primes: LazyList[Int] = sieve(2 #:: oddPrimes)\n\n  def factorMersenne(p: Int): Option[Long] = {\n    val limit = (mersenne(p) - 1 min Int.MaxValue).toLong\n\n    def factorTest(p: Long, q: Long): Boolean = {\n      (List(1, 7) contains (q % 8)) && two.modPow(p, q) == 1 && BigInt(q).isProbablePrime(7)\n    }\n\n    \/\/ Build a stream of factors from (2*p+1) step-by (2*p)\n    def s(a: Long): LazyList[Long] = a #:: s(a + (2 * p)) \/\/ Build stream of possible factors\n\n    \/\/ Limit and Filter Stream and then take the head element\n    val e = s(2 * p + 1).takeWhile(_ < limit).filter(factorTest(p, _))\n    e.headOption\n  }\n\n  def mersenne(p: Int): BigInt = (two pow p) - 1\n\n  \/\/ Test\n  (primes takeWhile (_ <= 97)) ++ List(929, 937) foreach { p => { \/\/ Needs some intermediate results for nice formatting\n    val nMersenne = mersenne(p);\n    val lit = s\"${nMersenne}\"\n    val preAmble = f\"${s\"M${p}\"}%4s = 2^$p%03d - 1 = ${lit}%s\"\n\n    val datum = System.nanoTime\n    val result = factorMersenne(p)\n    val mSec = ((System.nanoTime - datum) \/ 1.0e+6).round\n\n    def decStr = {\n      if (lit.length > 30) f\"(M has ${lit.length}%3d dec)\" else \"\"\n    }\n\n    def sPrime: String = {\n      if (result.isEmpty) \" is a Mersenne prime number.\" else \" \" * 28\n    }\n\n    println(f\"$preAmble${sPrime} ${f\"($mSec%,1d\"}%13s msec)\")\n    if (result.isDefined)\n      println(f\"${decStr}%-17s = ${result.get} \u00d7 ${nMersenne \/ result.get}\")\n  }\n  }\n}\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":2332}
    {"lang_cluster":"Scala","source_code":"\n\nscala> val xml: scala.xml.Elem =\n     | <inventory title=\"OmniCorp Store #45x10^3\">\n     |   <section name=\"health\">\n     |     <item upc=\"123456789\" stock=\"12\">\n     |       <name>Invisibility Cream<\/name>\n     |       <price>14.50<\/price>\n     |       <description>Makes you invisible<\/description>\n     |     <\/item>\n     |     <item upc=\"445322344\" stock=\"18\">\n     |       <name>Levitation Salve<\/name>\n     |       <price>23.99<\/price>\n     |       <description>Levitate yourself for up to 3 hours per application<\/description>\n     |     <\/item>\n     |   <\/section>\n     |   <section name=\"food\">\n     |     <item upc=\"485672034\" stock=\"653\">\n     |       <name>Blork and Freen Instameal<\/name>\n     |       <price>4.95<\/price>\n     |       <description>A tasty meal in a tablet; just add water<\/description>\n     |     <\/item>\n     |     <item upc=\"132957764\" stock=\"44\">\n     |       <name>Grob winglets<\/name>\n     |       <price>3.56<\/price>\n     |       <description>Tender winglets of Grob. Just add water<\/description>\n     |     <\/item>\n     |   <\/section>\n     | <\/inventory>\n\nscala> val firstItem = xml \\\\ \"item\" take 1\nfirstItem: scala.xml.NodeSeq =\nNodeSeq(<item upc=\"123456789\" stock=\"12\">\n      <name>Invisibility Cream<\/name>\n      <price>14.50<\/price>\n      <description>Makes you invisible<\/description>\n    <\/item>)\n\nscala> xml \\\\ \"price\" map (_.text) foreach println\n14.50\n23.99\n4.95\n3.56\n\nscala> val names = (xml \\\\ \"name\").toArray\nnames: Array[scala.xml.Node] = Array(<name>Invisibility Cream<\/name>, <name>Levitation Salve<\/name>, <name>Blork and Freen Instameal<\/name>, <name>Grob winglets<\/name>)\n\n","human_summarization":"The code performs three XPath queries on a given XML document. It retrieves the first \"item\" element, prints out each \"price\" element, and generates an array of all the \"name\" elements. The XML document represents an inventory of an OmniCorp Store. The code is designed to be run in Scala's REPL for better result visualization.","id":2333}
    {"lang_cluster":"Scala","source_code":"\nobject sets {\n  val set1 = Set(1,2,3,4,5)\n  val set2 = Set(3,5,7,9)\n  println(set1 contains 3)\n  println(set1 | set2)\n  println(set1 & set2)\n  println(set1 diff set2)\n  println(set1 subsetOf set2)\n  println(set1 == set2)\n}\n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":2334}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nimport java.util.{ Calendar, GregorianCalendar }\nimport Calendar.{ DAY_OF_WEEK, DECEMBER, SUNDAY }\n\nobject DayOfTheWeek extends App {\n  val years = 2008 to 2121\n\n  val yuletide =\n    years.filter(year => (new GregorianCalendar(year, DECEMBER, 25)).get(DAY_OF_WEEK) == SUNDAY)\n\n  \/\/ If you want a test: (optional)\n  assert(yuletide ==\n    Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,\n      2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))\n\n  println(yuletide.mkString(\n    s\"${yuletide.length} Years between ${years.head} and ${years.last}\" +\n      \" including where Christmas is observed on Sunday:\\n\", \", \", \".\"))\n}\nimport java.time.{ DayOfWeek, LocalDate }\n\nobject DayOfTheWeek1 extends App {\n  val years = 2008 to 2121\n  val yuletide = for {\n    year <- years\n    if LocalDate.of(year, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY\n  } yield year\n\n  println(yuletide.mkString(\n    s\"${yuletide.count(p => true)} Years between ${years.head} and ${years.last}\" +\n      \" including where Christmas is observed on Sunday:\\n\", \", \", \".\"))\n}\nimport java.time.{ DayOfWeek, LocalDate }\n\nobject DayOfTheWeek1 extends App {\n  val years = 2008 to 2121\n  val yuletide =\n    years.filter(year => (LocalDate.of(year, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY))\n\n  \/\/ If you want a test: (optional)\n  assert(yuletide ==\n    Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,\n      2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))\n\n  println(yuletide.mkString(\n    s\"${yuletide.length} Years between ${years.head} and ${years.last}\" +\n      \" including where Christmas is observed on Sunday:\\n\", \", \", \".\"))\n}\nimport java.time.{ DayOfWeek, LocalDate }\nimport scala.annotation.tailrec\n\nobject DayOfTheWeek3 extends App {\n  val years = 2008 to 2121\n  val yuletide = {\n    @tailrec\n    def inner(anni: List[Int], accu: List[Int]): List[Int] = {\n      if (anni == Nil) accu\n      else inner(anni.tail, accu ++\n        (if (LocalDate.of(anni.head, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY) List(anni.head)\n        else Nil))\n    }\n    inner(years.toList, Nil)\n  }\n\n  \/\/ If you want a test: (optional)\n  assert(yuletide ==\n    Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061,\n      2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118))\n\n  println(yuletide.mkString(\n    s\"${yuletide.length} Years between ${years.head} and ${years.last}\" +\n      \" including where Christmas is observed on Sunday:\\n\", \", \", \".\"))\n}\n\nOutput of all solutions:\nYears between 2008 and 2121 including when Christmas is observed on Sunday:\n2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118.\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":2335}
    {"lang_cluster":"Scala","source_code":"\nimport java.io.{PrintWriter, StringWriter}\n\nimport Jama.{Matrix, QRDecomposition}\n\nobject QRDecomposition extends App {\n  val matrix =\n    new Matrix(\n      Array[Array[Double]](Array(12, -51, 4),\n        Array(6, 167, -68),\n        Array(-4, 24, -41)))\n  val d = new QRDecomposition(matrix)\n\n  def toString(m: Matrix): String = {\n    val sw = new StringWriter\n    m.print(new PrintWriter(sw, true), 8, 6)\n    sw.toString\n  }\n\n  print(toString(d.getQ))\n  print(toString(d.getR))\n\n}\n","human_summarization":"The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.","id":2336}
    {"lang_cluster":"Scala","source_code":"\nval list = List(1,2,3,4,2,3,4,99)\nval l2 = list.distinct\n\/\/ l2: scala.List[scala.Int] = List(1,2,3,4,99)\n\nval arr = Array(1,2,3,4,2,3,4,99)\nval arr2 = arr.distinct\n\/\/ arr2: Array[Int] = Array(1, 2, 3, 4, 99)\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":2337}
    {"lang_cluster":"Scala","source_code":"\n\n  def sort(xs: List[Int]): List[Int] = xs match {\n    case Nil => Nil\n    case head\u00a0:: tail =>\n      val (less, notLess) = tail.partition(_ < head) \/\/ Arbitrarily partition list in two\n      sort(less) ++ (head\u00a0:: sort(notLess))          \/\/ Sort each half\n  }\n\n  def sort[T](xs: List[T], lessThan: (T, T) => Boolean): List[T] = xs match {\n    case Nil => Nil\n    case x\u00a0:: xx =>\n      val (lo, hi) = xx.partition(lessThan(_, x))\n      sort(lo, lessThan) ++ (x\u00a0:: sort(hi, lessThan))\n  }\n\n  def sort[T](xs: List[T])(implicit ord: Ordering[T]): List[T] = xs match {\n    case Nil => Nil\n    case x\u00a0:: xx =>\n      val (lo, hi) = xx.partition(ord.lt(_, x))\n      sort[T](lo) ++ (x\u00a0:: sort[T](hi))\n  }\n\n  def sort[T <: Ordered[T]](xs: List[T]): List[T] = xs match {\n    case Nil => Nil\n    case x\u00a0:: xx =>\n      val (lo, hi) = xx.partition(_ < x)\n      sort(lo) ++ (x\u00a0:: sort(hi))\n  }\n\n  def sort[T, C[T] <: scala.collection.TraversableLike[T, C[T]]]\n    (xs: C[T])\n    (implicit ord: scala.math.Ordering[T],\n      cbf: scala.collection.generic.CanBuildFrom[C[T], T, C[T]]): C[T] = {\n    \/\/ Some collection types can't pattern match\n    if (xs.isEmpty) {\n      xs\n    } else {\n      val (lo, hi) = xs.tail.partition(ord.lt(_, xs.head))\n      val b = cbf()\n      b.sizeHint(xs.size)\n      b ++= sort(lo)\n      b += xs.head\n      b ++= sort(hi)\n      b.result()\n    }\n  }\n\n","human_summarization":"The code implements the Quicksort algorithm for sorting an array or list. It provides two versions of the algorithm: a simple one that creates new arrays for partitions, and an optimized one that sorts in place by swapping elements. The pivot element for partitioning can be any element of the array. The algorithm is efficient with a time complexity ranging from O(n log n) to O(n2) depending on the choice of pivot. The code also discusses the comparison of Quicksort with Merge sort, highlighting their differences and use cases.","id":2338}
    {"lang_cluster":"Scala","source_code":"\nimport java.util.Date\n\nval now=new Date()\nprintln(\"%tF\".format(now))\nprintln(\"%1$tA, %1$tB %1$td, %1$tY\".format(now))\n\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":2339}
    {"lang_cluster":"Scala","source_code":"\nimport scala.compat.Platform.currentTime\n\nobject Powerset extends App {\n  def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el)}\n\n  assert(powerset(Set(1, 2, 3, 4)) == Set(Set.empty, Set(1), Set(2), Set(3), Set(4), Set(1, 2), Set(1, 3), Set(1, 4),\n    Set(2, 3), Set(2, 4), Set(3, 4), Set(1, 2, 3), Set(1, 3, 4), Set(1, 2, 4), Set(2, 3, 4), Set(1, 2, 3, 4)))\n  println(s\"Successfully completed without errors. [total ${currentTime - executionStart} ms]\")\n}\n\ndef powerset[A](s: Set[A]) = (0 to s.size).map(s.toSeq.combinations(_)).reduce(_ ++ _).map(_.toSet)\n\ndef powerset[A](s: Set[A]) = {\n  def powerset_rec(acc: List[Set[A]], remaining: List[A]): List[Set[A]] = remaining match {\n    case Nil => acc\n    case head\u00a0:: tail => powerset_rec(acc ++ acc.map(_ + head), tail)\n  }\n  powerset_rec(List(Set.empty[A]), s.toList)\n}\n","human_summarization":"The code takes a set S as input and generates its power set, which includes all possible subsets of S. It also handles edge cases like an empty set and a set containing only the empty set. The code supports lazy sequence generation and tail-recursion.","id":2340}
    {"lang_cluster":"Scala","source_code":"\nWorks with: Scala version 2.8\nval romanDigits = Map(\n  1 -> \"I\", 5 -> \"V\", \n  10 -> \"X\", 50 -> \"L\", \n  100 -> \"C\", 500 -> \"D\", \n  1000 -> \"M\", \n  4 -> \"IV\", 9 -> \"IX\", \n  40 -> \"XL\", 90 -> \"XC\", \n  400 -> \"CD\", 900 -> \"CM\")\nval romanDigitsKeys = romanDigits.keysIterator.toList sortBy (x => -x)\ndef toRoman(n: Int): String = romanDigitsKeys find (_ >= n) match {\n  case Some(key) => romanDigits(key) + toRoman(n - key)\n  case None => \"\"\n}\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":2341}
    {"lang_cluster":"Scala","source_code":"\n\n\/\/ Create a new integer array with capacity 10\nval a = new Array[Int](10)\n\n\/\/ Create a new array containing specified items\nval b = Array(\"foo\", \"bar\", \"baz\")\n\n\/\/ Assign a value to element zero\na(0) = 42\n\n\/\/ Retrieve item at element 2\nval c = b(2)\n\nval a = new collection.mutable.ArrayBuffer[Int] \na += 5   \/\/ Append value 5 to the end of the list\na(0) = 6 \/\/ Assign value 6 to element 0\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. It includes creating an array, assigning a value to it, and retrieving an element from it. It covers both fixed-length and dynamic arrays, and also shows how to push a value into the array. The code also discusses the use of ArrayBuffers for creating dynamic arrays in Scala, as an alternative to the less commonly used mutable arrays.","id":2342}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nimport java.io.{ FileNotFoundException, PrintWriter }\n\nobject FileIO extends App {\n  try {\n    val MyFileTxtTarget = new PrintWriter(\"output.txt\")\n\n    scala.io.Source.fromFile(\"input.txt\").getLines().foreach(MyFileTxtTarget.println)\n    MyFileTxtTarget.close()\n  } catch {\n    case e: FileNotFoundException => println(e.getLocalizedMessage())\n    case e: Throwable => {\n      println(\"Some other exception type:\")\n      e.printStackTrace()\n    }\n  }\n}\n","human_summarization":"demonstrate reading the contents of \"input.txt\" file into a variable and then writing this variable's contents into a new file called \"output.txt\".","id":2343}
    {"lang_cluster":"Scala","source_code":"\nval s=\"alphaBETA\"\nprintln(s.toUpperCase)   \/\/-> ALPHABETA\nprintln(s.toLowerCase)   \/\/-> alphabeta\nprintln(s.capitalize)    \/\/-> AlphaBETA\nprintln(s.reverse)       \/\/-> ATEBahpla\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":2344}
    {"lang_cluster":"Scala","source_code":"\nimport scala.collection.mutable.ListBuffer\nimport scala.util.Random\n\nobject ClosestPair {\n  case class Point(x: Double, y: Double){\n    def distance(p: Point) = math.hypot(x-p.x, y-p.y)\n\n    override def toString = \"(\" + x + \", \" + y + \")\"\n  }\n\n  case class Pair(point1: Point, point2: Point) {\n    val distance: Double = point1 distance point2\n\n    override def toString = {\n      point1 + \"-\" + point2 + \"\u00a0: \" + distance\n    }\n  }\n\n  def sortByX(points: List[Point]) = {\n    points.sortBy(point => point.x)\n  }\n\n  def sortByY(points: List[Point]) = {\n    points.sortBy(point => point.y)\n  }\n\n  def divideAndConquer(points: List[Point]): Pair = {\n    val pointsSortedByX = sortByX(points)\n    val pointsSortedByY = sortByY(points)\n\n    divideAndConquer(pointsSortedByX, pointsSortedByY)\n  }\n\n  def bruteForce(points: List[Point]): Pair = {\n    val numPoints = points.size\n    if (numPoints < 2)\n      return null\n    var pair = Pair(points(0), points(1))\n    if (numPoints > 2) {\n      for (i <- 0 until numPoints - 1) {\n        val point1 = points(i)\n        for (j <- i + 1 until numPoints) {\n          val point2 = points(j)\n          val distance = point1 distance point2\n          if (distance < pair.distance)\n            pair = Pair(point1, point2)\n        }\n      }\n    }\n    return pair\n  }\n\n\n  private def divideAndConquer(pointsSortedByX: List[Point], pointsSortedByY: List[Point]): Pair = {\n    val numPoints = pointsSortedByX.size\n    if(numPoints <= 3) {\n      return bruteForce(pointsSortedByX)\n    }\n\n    val dividingIndex = numPoints >>> 1\n    val leftOfCenter = pointsSortedByX.slice(0, dividingIndex)\n    val rightOfCenter = pointsSortedByX.slice(dividingIndex, numPoints)\n\n    var tempList = leftOfCenter.map(x => x)\n    \/\/println(tempList)\n    tempList = sortByY(tempList)\n    var closestPair = divideAndConquer(leftOfCenter, tempList)\n\n    tempList = rightOfCenter.map(x => x)\n    tempList = sortByY(tempList)\n\n    val closestPairRight = divideAndConquer(rightOfCenter, tempList)\n\n    if (closestPairRight.distance < closestPair.distance)\n      closestPair = closestPairRight\n\n    tempList = List[Point]()\n    val shortestDistance = closestPair.distance\n    val centerX = rightOfCenter(0).x\n\n    for (point <- pointsSortedByY) {\n      if (Math.abs(centerX - point.x) < shortestDistance)\n        tempList = tempList :+ point\n    }\n\n    closestPair = shortestDistanceF(tempList, shortestDistance, closestPair)\n    closestPair\n  }\n\n  private def shortestDistanceF(tempList: List[Point], shortestDistance: Double, closestPair: Pair ): Pair = {\n    var shortest = shortestDistance\n    var bestResult = closestPair\n    for (i <- 0 until tempList.size) {\n      val point1 = tempList(i)\n      for (j <- i + 1 until tempList.size) {\n        val point2 = tempList(j)\n        if ((point2.y - point1.y) >= shortestDistance)\n          return closestPair\n        val distance = point1 distance point2\n        if (distance < closestPair.distance)\n        {\n          bestResult = Pair(point1, point2)\n          shortest = distance\n        }\n      }\n    }\n\n    closestPair\n  }\n\n  def main(args: Array[String]) {\n    val numPoints = if(args.length == 0) 1000 else args(0).toInt\n\n    val points = ListBuffer[Point]()\n    val r = new Random()\n    for (i <- 0 until numPoints) {\n      points.+=:(new Point(r.nextDouble(), r.nextDouble()))\n    }\n    println(\"Generated \" + numPoints + \" random points\")\n\n    var startTime = System.currentTimeMillis()\n    val bruteForceClosestPair = bruteForce(points.toList)\n    var elapsedTime = System.currentTimeMillis() - startTime\n    println(\"Brute force (\" + elapsedTime + \" ms): \" + bruteForceClosestPair)\n\n    startTime = System.currentTimeMillis()\n    val dqClosestPair = divideAndConquer(points.toList)\n    elapsedTime = System.currentTimeMillis() - startTime\n    println(\"Divide and conquer (\" + elapsedTime + \" ms): \" + dqClosestPair)\n    if (bruteForceClosestPair.distance != dqClosestPair.distance)\n      println(\"MISMATCH\")\n  }\n}\n\n\n","human_summarization":"provide two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute force algorithm with a complexity of O(n^2) to find the two closest points. The second function uses a recursive divide and conquer approach with a complexity of O(n log n) to find the two closest points. Both functions return the minimum distance and the pair of points.","id":2345}
    {"lang_cluster":"Scala","source_code":"\nLibrary: ScalaScala has in his run-time library a rich set set of collections. Due to use of traits is this library easily realized and consistent. Collections provide the same operations on any type where it makes sense to do so. For instance, a string is conceptually a sequence of characters. Consequently, in Scala collections, strings support all sequence operations. The same holds for arrays.\n\nThese examples were taken from a Scala REPL session. The second lines are the REPL responces.Windows PowerShell\nCopyright (C) 2012 Microsoft Corporation. All rights reserved.\n\nPS C:\\Users\\FransAdm> scala\nWelcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_25).\nType in expressions to have them evaluated.\nType :help for more information.\n\nscala> \/\/ Immutable collections do not and cannot change the instantiated object\n\nscala> \/\/ Lets start with Lists\n\nscala> val list = Nil \/\/ Empty List\nlist: scala.collection.immutable.Nil.type = List()\n\nscala> val list2 = List(\"one\", \"two\") \/\/ List with two elements (Strings)\nlist2: List[String] = List(one, two)\n\nscala> val list3 = 3\u00a0:: list2 \/\/ prepend 3 to list2, using a special operator\nlist3: List[Any] = List(3, one, two)\n\nscala> \/\/ The result was a mixture with a Int and Strings, so the common superclass Any is used.\n\nscala> \/\/ Let test the Set collection\n\nscala> val set = Set.empty[Char] \/\/ Empty Set of Char type\nset: scala.collection.immutable.Set[Char] = Set()\n\nscala> val set1 = set + 'c' \/\/ add an element\nset1: scala.collection.immutable.Set[Char] = Set(c)\n\nscala> val set2 = set + 'a' + 'c' + 'c' \/\/ try to add another and  the same element twice\nset2: scala.collection.immutable.Set[Char] = Set(a, c)\n\nscala> \/\/ Let's look at the most universal map: TrieMap (Cache-aware lock-free concurrent hash trie)\n\nscala> val capital = collection.concurrent.TrieMap(\"US\" -> \"Washington\", \"France\" -> \"Paris\") \/\/ This map is mutable\ncapital: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington, France -> Paris)\n\nscala> capital - \"France\" \/\/ This is only an expression, does not modify the map itself\nres0: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington)\n\nscala> capital += (\"Tokio\" -> \"Japan\") \/\/ Adding an element, object is changed - not the val capital\nres1: capital.type = TrieMap(US -> Washington, Tokio -> Japan, France -> Paris)\n\nscala> capital \/\/ Check what we have sofar\nres2: scala.collection.concurrent.TrieMap[String,String] = TrieMap(US -> Washington, Tokio -> Japan, France -> Paris)\n\nscala>  val queue = new scala.collection.mutable.Queue[String]\nqueue: scala.collection.mutable.Queue[String] = Queue()\n\nscala> queue += \"first\"\nres17: queue.type = Queue(\"first\")\n\nscala> queue += \"second\"\nres19: queue.type = Queue(\"first\", \"second\")\n\nscala>\n    import collection.concurrent.TrieMap\n\n    \/\/ super concurrent mutable hashmap\n    val map = TrieMap(\"Amsterdam\" -> \"Netherlands\",\n      \"New York\" -> \"USA\",\n      \"Heemstede\" -> \"Netherlands\")\n\n    map(\"Laussanne\") = \"Switzerland\" \/\/ 2 Ways of updating\n    map += (\"Tokio\" -> \"Japan\")\n\n    assert(map(\"New York\") == \"USA\")\n    assert(!map.isDefinedAt(\"Gent\")) \/\/ isDefinedAt is false\n    assert(map.isDefinedAt(\"Laussanne\")) \/\/ true\n\n    val hash = new TrieMap[Int, Int]\n    hash(1) = 2\n    hash += (1 -> 2) \/\/ same as hash(1) = 2\n    hash += (3 -> 4, 5 -> 6, 44 -> 99)\n    hash(44) \/\/ 99\n    hash.contains(33) \/\/ false\n    hash.isDefinedAt(33) \/\/ same as contains\n    hash.contains(44) \/\/ true\n    \/\/ iterate over key\/value\n    \/\/    hash.foreach { case (key, val) => println(  \"key \" + e._1 + \" value \" + e._2) } \/\/ e is a 2 element Tuple\n    \/\/ same with for syntax\n    for ((k, v) <- hash) println(\"key \" + k + \" value \" + v)\n    \/\/    \/\/ items in map where the key is greater than 3\n        map.filter { k => k._1 > 3 } \/\/  Map(5 -> 6, 44 -> 99)\n    \/\/    \/\/ same with for syntax\n        for ((k, v) <- map; if k > 3) yield (k, v)\n","human_summarization":"create a collection in a statically-typed language, add a few values to it, and demonstrate the difference between immutable and mutable collections. It also shows how to switch between sequential and parallel processing using .seq or .par postfix.","id":2346}
    {"lang_cluster":"Scala","source_code":"\nimport scala.annotation.tailrec\n \nobject UnboundedKnapsack extends App {\n  private val (maxWeight, maxVolume) = (BigDecimal(25.0), BigDecimal(0.25))\n  private val items = Seq(Item(\"panacea\", 3000, 0.3, 0.025), Item(\"ichor\", 1800, 0.2, 0.015), Item(\"gold\", 2500, 2.0, 0.002))\n \n  @tailrec\n  private def packer(notPacked: Seq[Knapsack], packed: Seq[Knapsack]): Seq[Knapsack] = {\n    def fill(knapsack: Knapsack): Seq[Knapsack] = items.map(i => Knapsack(i +: knapsack.bagged))\n \n    def stuffer(Seq: Seq[Knapsack]): Seq[Knapsack] = \/\/ Cause brute force\n      Seq.map(k => Knapsack(k.bagged.sortBy(_.name))).distinct\n \n    if (notPacked.isEmpty) packed.sortBy(-_.totValue).take(4)\n    else packer(stuffer(notPacked.flatMap(fill)).filter(_.isNotFull), notPacked ++ packed)\n  }\n \n  private case class Item(name: String, value: Int, weight: BigDecimal, volume: BigDecimal)\n \n  private case class Knapsack(bagged: Seq[Item]) {\n    def isNotFull: Boolean = totWeight <= maxWeight && totVolume <= maxVolume\n \n    override def toString = s\"[${show(bagged)} | value: $totValue, weight: $totWeight, volume: $totVolume]\"\n \n    def totValue: Int = bagged.map(_.value).sum\n \n    private def totVolume = bagged.map(_.volume).sum\n \n    private def totWeight = bagged.map(_.weight).sum\n \n    private def show(is: Seq[Item]) =\n      (items.map(_.name) zip items.map(i => is.count(_ == i)))\n        .map { case (i, c) => f\"$i:$c%3d\" }\n        .mkString(\", \")\n  }\n \n  packer(items.map(i => Knapsack(Seq(i))), Nil).foreach(println)\n}\n\n\n","human_summarization":"determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.","id":2347}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nvar i = 1\nwhile ({\n  print(i)\n  i < 10\n}) {\n  print(\", \")\n  i += 1\n}\nprintln()\nprintln((1 to 10).mkString(\", \"))\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":2348}
    {"lang_cluster":"Scala","source_code":"\n\"abcd\".startsWith(\"ab\") \/\/returns true\n\"abcd\".endsWith(\"zn\") \/\/returns false\n\"abab\".contains(\"bb\") \/\/returns false\n\"abab\".contains(\"ab\") \/\/returns true\n\t\t\nvar loc=\"abab\".indexOf(\"bb\") \/\/returns -1\nloc = \"abab\".indexOf(\"ab\") \/\/returns 0\nloc = \"abab\".indexOf(\"ab\", loc+1) \/\/returns 2\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":2349}
    {"lang_cluster":"Scala","source_code":"object FourRings {\n \n  def fourSquare(low: Int, high: Int, unique: Boolean, print: Boolean): Unit = {\n    def isValid(needle: Integer, haystack: Integer*) = !unique || !haystack.contains(needle)\n\n    if (print) println(\"a b c d e f g\")\n\n    var count = 0\n    for {\n      a <- low to high\n      b <- low to high if isValid(a, b)\n      fp = a + b\n      c <- low to high if isValid(c, a, b)\n      d <- low to high if isValid(d, a, b, c) && fp == b + c + d\n      e <- low to high if isValid(e, a, b, c, d)\n      f <- low to high if isValid(f, a, b, c, d, e) && fp == d + e + f\n      g <- low to high if isValid(g, a, b, c, d, e, f) && fp == f + g\n    } {\n      count += 1\n      if (print) println(s\"$a $b $c $d $e $f $g\")\n    }\n    \n    println(s\"There are $count ${if(unique) \"unique\" else \"non-unique\"} solutions in [$low, $high]\")\n  }\n \n  def main(args: Array[String]): Unit = {\n    fourSquare(1, 7, unique = true, print = true)\n    fourSquare(3, 9, unique = true, print = true)\n    fourSquare(0, 9, unique = false, print = false)\n  }\n}\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":2350}
    {"lang_cluster":"Scala","source_code":"\n\nimport java.util.{ Timer, TimerTask }\nimport java.time.LocalTime\nimport scala.math._\n\nobject Clock extends App {\n  private val (width, height) = (80, 35)\n\n  def getGrid(localTime: LocalTime): Array[Array[Char]] = {\n    val (minute, second) = (localTime.getMinute, localTime.getSecond())\n    val grid = Array.fill[Char](height, width)(' ')\n\n    def toGridCoord(x: Double, y: Double): (Int, Int) =\n      (floor((y + 1.0) \/ 2.0 * height).toInt, floor((x + 1.0) \/ 2.0 * width).toInt)\n\n    def makeText(grid: Array[Array[Char]], r: Double, theta: Double, str: String) {\n      val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))\n      (0 until str.length).foreach(i =>\n        if (row >= 0 && row < height && col + i >= 0 && col + i < width) grid(row)(col + i) = str(i))\n    }\n\n    def makeCircle(grid: Array[Array[Char]], r: Double, c: Char) {\n      var theta = 0.0\n      while (theta < 2 * Pi) {\n        val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))\n        if (row >= 0 && row < height && col >= 0 && col < width) grid(row)(col) = c\n        theta = theta + 0.01\n      }\n    }\n\n    def makeHand(grid: Array[Array[Char]], maxR: Double, theta: Double, c: Char) {\n      var r = 0.0\n      while (r < maxR) {\n        val (row, col) = toGridCoord(r * cos(theta), r * sin(theta))\n        if (row >= 0 && row < height && col >= 0 && col < width) grid(row)(col) = c\n        r = r + 0.01\n      }\n    }\n\n    makeCircle(grid, 0.98, '@')\n    makeHand(grid, 0.6, (localTime.getHour() + minute \/ 60.0 + second \/ 3600.0) * Pi \/ 6 - Pi \/ 2, 'O')\n    makeHand(grid, 0.85, (minute + second \/ 60.0) * Pi \/ 30 - Pi \/ 2, '*')\n    makeHand(grid, 0.90, second * Pi \/ 30 - Pi \/ 2, '.')\n\n    (1 to 12).foreach(n => makeText(grid, 0.87, n * Pi \/ 6 - Pi \/ 2, n.toString))\n    grid\n  } \/\/ def getGrid(\n\n  private val timerTask = new TimerTask {\n    private def printGrid(grid: Array[Array[Char]]) = grid.foreach(row => println(row.mkString))\n    def run() = printGrid(getGrid(LocalTime.now()))\n  }\n  (new Timer).schedule(timerTask, 0, 1000)\n}\n\n\nimport java.time.LocalTime\nimport java.awt.{ Color, Graphics }\n\n\/** The Berlin clock as a Java (8.0) applet\n *\/\nclass QDclock extends java.applet.Applet with Runnable {\n  val bclockThread: Thread = new Thread(this, \"QDclock\")\n\n  override def init() = resize(242, 180) \/\/ fixed size, at first... doesn't work...\n\n  override def start() = if (!bclockThread.isAlive()) bclockThread.start()\n\n  def run() {\n    while (true) {\n      repaint()\n      try Thread.sleep(1000) catch { case _: Throwable => sys.exit(-1) }\n    }\n  }\n\n  override def update(g: Graphics) {\n    val now = LocalTime.now\n\n    def booleanToColor(cond: Boolean, colorOn: Color = Color.red): Color =\n      if (cond) colorOn else Color.black\n\n    g.setColor(booleanToColor(now.getSecond() % 2 == 0, Color.yellow))\n    g.fillOval(100, 4, 40, 40)\n\n    val (stu, min) = (now.getHour(), now.getMinute()) match {\n      case (0, 0)     => (24, 0)\n      case (hrs, min) => (hrs, min)\n    }\n\n    def drawRectangle(color: Color, rect: (Int, Int, Int, Int)) {\n      g.setColor(color)\n      g.fillRoundRect(rect._1, rect._2, rect._3, rect._4, 4, 4)\n    }\n\n    for (i <- 0 until 4) {\n      drawRectangle(booleanToColor(stu \/ ((i + 1) * 5) > 0), (i * 60 + 2, 46, 58, 30))\n      drawRectangle(booleanToColor(stu % 5 > i), (i * 60 + 2, 78, 58, 30))\n      drawRectangle(booleanToColor(min % 5 > i, Color.yellow), (i * 60 + 2, 142, 58, 30))\n    }\n\n    for (i <- 0 until 11) {\n      drawRectangle(booleanToColor(min \/ ((i + 1) * 5) > 0,\n        if (2 to 8 by 3 contains i) Color.red else Color.yellow), (i * 20 + 10, 110, 18, 30))\n    }\n  }\n}\n\n","human_summarization":"generate a graphical or text-based representation of a timekeeping device that updates every second in sync with the system clock, without excessively using system resources or CPU. The code is kept simple and clear. An ASCII clock is printed every second as an example.","id":2351}
    {"lang_cluster":"Scala","source_code":"\nobject PythagoreanTriples extends App {\n\n  println(\"               Limit Primatives          All\")\n\n  for {e <- 2 to 7\n       limit = math.pow(10, e).longValue()\n  } {\n    var primCount, tripCount = 0\n\n    def parChild(a: BigInt, b: BigInt, c: BigInt): Unit = {\n      val perim = a + b + c\n      val (a2, b2, c2, c3) = (2 * a, 2 * b, 2 * c, 3 * c)\n      if (limit >= perim) {\n        primCount += 1\n        tripCount += (limit \/ perim).toInt\n        parChild(a - b2 + c2, a2 - b + c2, a2 - b2 + c3)\n        parChild(a + b2 + c2, a2 + b + c2, a2 + b2 + c3)\n        parChild(-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3)\n      }\n    }\n\n    parChild(BigInt(3), BigInt(4), BigInt(5))\n    println(f\"a + b + c <= ${limit.toFloat}%3.1e  $primCount%9d $tripCount%12d\")\n  }\n}\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":2352}
    {"lang_cluster":"Scala","source_code":"\nLibrary: sdljava\nLibrary: Scala Java Swing interoperability\nimport javax.swing.JFrame\n\nobject ShowWindow{\n  def main(args: Array[String]){\n    var jf = new JFrame(\"Hello!\")\n\n    jf.setSize(800, 600)\n    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\n    jf.setVisible(true)\n  }\n}\n\n\nimport scala.swing._\nimport scala.swing.Swing._\n\nobject SimpleWindow extends SimpleSwingApplication {\n  def top = new MainFrame {\n    title = \"Hello!\"\n    preferredSize = ((800, 600):Dimension)\n  }\n}\n\n","human_summarization":"create a GUI window using native Scala libraries, which can respond to close requests.","id":2353}
    {"lang_cluster":"Scala","source_code":"\nimport io.Source.fromFile\n\ndef letterFrequencies(filename: String) = \n  fromFile(filename).mkString groupBy (c => c) mapValues (_.length)\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":2354}
    {"lang_cluster":"Scala","source_code":"\n\nsealed trait List[+A]\ncase class Cons[+A](head: A, tail: List[A]) extends List[A]\ncase object Nil extends List[Nothing]\n\nobject List {\n  def apply[A](as: A*): List[A] =\n    if (as.isEmpty) Nil else Cons(as.head, apply(as.tail: _*))\n}\n\n\ndef main(args: Array[String]): Unit = {\n  val words = List(\"Rosetta\", \"Code\", \"Scala\", \"Example\")\n}\n\n","human_summarization":"define a data structure for a singly-linked list element, which includes a data member for storing a numeric value and a mutable link to the next element.","id":2355}
    {"lang_cluster":"Scala","source_code":"\n\nimport swing._\nimport java.awt.{RenderingHints, BasicStroke, Color}\n\nobject FractalTree extends SimpleSwingApplication {\n  val DEPTH = 9\n\n  def top = new MainFrame {\n    contents = new Panel {\n      preferredSize = new Dimension(600, 500)\n\n      override def paintComponent(g: Graphics2D) {\n        draw(300, 460, -90, DEPTH)\n\n        def draw(x1: Int, y1: Int, angle: Double, depth: Int) {\n          if (depth > 0) {\n            val x2 = x1 + (math.cos(angle.toRadians) * depth * 10).toInt\n            val y2 = y1 + (math.sin(angle.toRadians) * depth * 10).toInt\n\n            g.setColor(Color.getHSBColor(0.25f - depth * 0.125f \/ DEPTH, 0.9f, 0.6f))\n            g.setStroke(new BasicStroke(depth))\n            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n            g.drawLine(x1, y1, x2, y2)\n\n            draw(x2, y2, angle - 20, depth - 1)\n            draw(x2, y2, angle + 20, depth - 1)\n          }\n        }\n      }\n    }\n  }\n}\n\n\n","human_summarization":"generates and draws a fractal tree by first drawing the trunk, then splitting the end of the trunk by a certain angle to create two branches, and repeating this process until a desired level of branching is achieved. This is adapted from the Java version.","id":2356}
    {"lang_cluster":"Scala","source_code":"\n\ndef factors(num: Int) = {\n    (1 to num).filter { divisor =>\n      num\u00a0% divisor == 0\n    }\n}\n\ndef factors(num: Int) = {\n    val list = (1 to math.sqrt(num).floor.toInt).filter(num\u00a0% _ == 0)\n    list ++ list.reverse.dropWhile(d => d*d == num).map(num \/ _)\n}\n","human_summarization":"calculate the factors of a positive integer using a brute force approach up to the square root of the number. The program does not handle factors of zero or negative integers. It also notes that every prime number has two factors: 1 and itself.","id":2357}
    {"lang_cluster":"Scala","source_code":"\nWorks with: scala version 2.8.0.r18997-b20091009021954\n\nobject ColumnAligner {\n  val eol = System.getProperty(\"line.separator\")\n  def getLines(filename: String) = scala.io.Source.fromPath(filename).getLines(eol)\n  def splitter(line: String) = line split '$'\n  def getTable(filename: String) = getLines(filename) map splitter\n  def fieldWidths(fields: Array[String]) = fields map (_ length)\n  def columnWidths(txt: Iterator[Array[String]]) = (txt map fieldWidths).toList.transpose map (_ max)\n\n  def alignField(alignment: Char)(width: Int)(field: String) = alignment match {\n    case 'l' | 'L' => \"%-\"+width+\"s\" format field\n    case 'r' | 'R' => \"%\"+width+\"s\" format field\n    case 'c' | 'C' => val padding = (width - field.length) \/ 2; \" \"*padding+\"%-\"+(width-padding)+\"s\" format field\n    case _ => throw new IllegalArgumentException\n  }\n\n  def align(aligners: List[String => String])(fields: Array[String]) =\n    aligners zip fields map Function.tupled(_ apply _)\n  \n  def alignFile(filename: String, alignment: Char) = {\n    def table = getTable(filename)\n    val aligners = columnWidths(table) map alignField(alignment)\n    table map align(aligners) map (_ mkString \" \")\n  }\n  \n  def printAlignedFile(filename: String, alignment: Char) {\n    alignFile(filename, alignment) foreach println\n  }\n}\n\n\ndef pad(s:String, i:Int, d:String) = {\n  val padsize = (i-s.length).max(0)\n  d match {\n    case \"left\" => s+\" \"*padsize\n    case \"right\" => \" \"*padsize+s\n    case \"center\" => \" \"*(padsize\/2) + s + \" \"*(padsize-padsize\/2)\n  }\n}\n \nval lines = scala.io.Source.fromFile(\"c:\\\\text.txt\").getLines.map(_.trim())\nval words = lines.map(_.split(\"\\\\$\").toList).toList\nval lens = words.map(l => l.map(_.length)).toList\n \nvar maxlens = Map[Int,Int]() withDefaultValue 0\nlens foreach (l =>\n  for(i <- (0 until l.length)){\n    maxlens += i -> l(i).max(maxlens(i))\n  }\n)\n  \nval padded = words map ( _.zipWithIndex.map{case(s,i)=>pad(s,maxlens(i),\"center\")+\" \"} )\npadded map (_.reduceLeft(_ + _)) foreach println\n\n","human_summarization":"The code reads a text file where each line's fields are separated by a dollar sign. It aligns each column by ensuring at least one space between words in each column. It also allows for each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters, consecutive spaces at the end of lines, and separating characters between or around columns are not considered. The output is viewed in a mono-spaced font on a plain text editor or basic terminal.","id":2358}
    {"lang_cluster":"Scala","source_code":"\nimport java.awt._\nimport java.awt.event.{MouseAdapter, MouseEvent}\n\nimport javax.swing._\n\nimport scala.math.{Pi, cos, sin}\n\nobject Cuboid extends App {\n  SwingUtilities.invokeLater(() => {\n\n    class Cuboid extends JPanel {\n      private val nodes: Array[Array[Double]] =\n        Array(Array(-1, -1, -1), Array(-1, -1, 1), Array(-1, 1, -1), Array(-1, 1, 1),\n          Array(1, -1, -1), Array(1, -1, 1), Array(1, 1, -1), Array(1, 1, 1))\n      private var mouseX, prevMouseX, mouseY, prevMouseY: Int = _\n\n      private def edges =\n        Seq(Seq(0, 1), Seq(1, 3), Seq(3, 2), Seq(2, 0),\n          Seq(4, 5), Seq(5, 7), Seq(7, 6), Seq(6, 4),\n          Seq(0, 4), Seq(1, 5), Seq(2, 6), Seq(3, 7))\n\n      override def paintComponent(gg: Graphics): Unit = {\n        val g = gg.asInstanceOf[Graphics2D]\n\n        def drawCube(g: Graphics2D): Unit = {\n          g.translate(getWidth \/ 2, getHeight \/ 2)\n          for (edge <- edges) {\n            g.drawLine(nodes(edge.head)(0).round.toInt, nodes(edge.head)(1).round.toInt,\n              nodes(edge(1))(0).round.toInt, nodes(edge(1))(1).round.toInt)\n          }\n          for (node <- nodes) g.fillOval(node(0).round.toInt - 4, node(1).round.toInt - 4, 8, 8)\n        }\n\n        super.paintComponent(gg)\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n        drawCube(g)\n      }\n\n      private def scale(sx: Double, sy: Double, sz: Double): Unit = {\n        for (node <- nodes) {\n          node(0) *= sx\n          node(1) *= sy\n          node(2) *= sz\n        }\n      }\n\n      private def rotateCube(angleX: Double, angleY: Double): Unit = {\n        val (sinX, cosX, sinY, cosY) = (sin(angleX), cos(angleX), sin(angleY), cos(angleY))\n        for (node <- nodes) {\n          val (x, y, z) = (node.head, node(1), node(2))\n          node(0) = x * cosX - z * sinX\n          node(2) = z * cosX + x * sinX\n          node(1) = y * cosY - node(2) * sinY\n          node(2) = node(2) * cosY + y * sinY\n        }\n      }\n\n      addMouseListener(new MouseAdapter() {\n        override def mousePressed(e: MouseEvent): Unit = {\n          mouseX = e.getX\n          mouseY = e.getY\n        }\n      })\n\n      addMouseMotionListener(new MouseAdapter() {\n        override def mouseDragged(e: MouseEvent): Unit = {\n          prevMouseX = mouseX\n          prevMouseY = mouseY\n          mouseX = e.getX\n          mouseY = e.getY\n          rotateCube((mouseX - prevMouseX) * 0.01, (mouseY - prevMouseY) * 0.01)\n          repaint()\n        }\n      })\n\n      scale(80, 120, 160)\n      rotateCube(Pi \/ 5, Pi \/ 9)\n      setPreferredSize(new Dimension(640, 640))\n      setBackground(Color.white)\n    }\n\n    new JFrame(\"Cuboid\") {\n      add(new Cuboid, BorderLayout.CENTER)\n      pack()\n      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)\n      setLocationRelativeTo(null)\n      setResizable(false)\n      setVisible(true)\n    }\n  })\n}\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":2359}
    {"lang_cluster":"Scala","source_code":"\nimport java.io.IOException\n\nimport org.apache.directory.api.ldap.model.exception.LdapException\nimport org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection}\n\nobject LdapConnectionDemo {\n  @throws[LdapException]\n  @throws[IOException]\n  def main(args: Array[String]): Unit = {\n    try {\n      val connection: LdapConnection = new LdapNetworkConnection(\"localhost\", 10389)\n      try {\n        connection.bind()\n        connection.unBind()\n      } finally if (connection != null) connection.close()\n    }\n  }\n}\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server.","id":2360}
    {"lang_cluster":"Scala","source_code":"\nscala> def rot13(s: String) = s map {\n     |   case c if 'a' <= c.toLower && c.toLower <= 'm' => c + 13 toChar\n     |   case c if 'n' <= c.toLower && c.toLower <= 'z' => c - 13 toChar\n     |   case c => c\n     | }\nrot13: (s: String)String\n\nscala> rot13(\"7 Cities of Gold.\")\nres61: String = 7 Pvgvrf bs Tbyq.\n\nscala> rot13(res61)\nres62: String = 7 Cities of Gold.\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":2361}
    {"lang_cluster":"Scala","source_code":"\ncase class Pair(name:String, value:Double)\nval input = Array(Pair(\"Krypton\", 83.798), Pair(\"Beryllium\", 9.012182), Pair(\"Silicon\", 28.0855))\ninput.sortBy(_.name) \/\/ Array(Pair(Beryllium,9.012182), Pair(Krypton,83.798), Pair(Silicon,28.0855))\n\n\/\/ alternative versions:\ninput.sortBy(struct => (struct.name, struct.value)) \/\/ additional sort field (name first, then value)\ninput.sortWith((a,b) => a.name.compareTo(b.name) < 0) \/\/ arbitrary comparison function\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":2362}
    {"lang_cluster":"Scala","source_code":"\nfor (i <- 1 to 5) {\n    for (j <- 1 to i)\n        print(\"*\")\n    println()\n}\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":2363}
    {"lang_cluster":"Scala","source_code":"\n\/\/ immutable maps\nvar map = Map(1 -> 2, 3 -> 4, 5 -> 6)\nmap(3) \/\/ 4\nmap = map + (44 -> 99) \/\/ maps are immutable, so we have to assign the result of adding elements\nmap.isDefinedAt(33) \/\/ false\nmap.isDefinedAt(44) \/\/ true\n\/\/ mutable maps (HashSets)\nimport scala.collection.mutable.HashMap\nval hash = new HashMap[Int, Int]\nhash(1) = 2\nhash += (1 -> 2)  \/\/ same as hash(1) = 2\nhash += (3 -> 4, 5 -> 6, 44 -> 99)\nhash(44) \/\/ 99\nhash.contains(33) \/\/ false\nhash.isDefinedAt(33) \/\/ same as contains\nhash.contains(44) \/\/ true\n\/\/ iterate over key\/value\nhash.foreach {e => println(\"key \"+e._1+\" value \"+e._2)} \/\/ e is a 2 element Tuple\n\/\/ same with for syntax\nfor((k,v) <- hash) println(\"key \" + k + \" value \" + v)\n\/\/ items in map where the key is greater than 3\nmap.filter {k => k._1 > 3} \/\/  Map(5 -> 6, 44 -> 99)\n\/\/ same with for syntax\nfor((k, v) <- map; if k > 3) yield (k,v)\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":2364}
    {"lang_cluster":"Scala","source_code":"\nobject LinearCongruentialGenerator {\n  def bsdRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{\n    var seed=rseed\n    override def hasNext:Boolean=true\n    override def next:Int={seed=(seed * 1103515245 + 12345) & Int.MaxValue; seed}\n  }\n\n  def msRandom(rseed:Int):Iterator[Int]=new Iterator[Int]{\n    var seed=rseed\n    override def hasNext:Boolean=true\n    override def next:Int={seed=(seed * 214013 + 2531011) & Int.MaxValue; seed >> 16}\n  }\n\t\t\n  def toString(it:Iterator[Int], n:Int=20)=it take n mkString \", \"\n\t\t\n  def main(args:Array[String]){\n    println(\"-- seed 0 --\")\n    println(\"BSD: \"+ toString(bsdRandom(0)))\n    println(\"MS\u00a0: \"+ toString(msRandom(0)))\n\t\t\t\t\t\t\n    println(\"-- seed 1 --\")\n    println(\"BSD: \"+ toString(bsdRandom(1)))\n    println(\"MS\u00a0: \"+ toString( msRandom(1)))\n  }\n}\n\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":2365}
    {"lang_cluster":"Scala","source_code":"\n\n\/*\nHere is a basic list definition\n\nsealed trait List[+A]\ncase class Cons[+A](head: A, tail: List[A]) extends List[A]\ncase object Nil extends List[Nothing]\n*\/\n\nobject List {\n  def add[A](as: List[A], a: A): List[A] = Cons(a, as)\n}\n\n","human_summarization":"define a method to insert an element 'C' into a singly-linked list after a specified element 'A'. In the context of functional programming like Scala, a new list is created instead of modifying the existing one.","id":2366}
    {"lang_cluster":"Scala","source_code":"\n\ndef ethiopian(i:Int, j:Int):Int=\n   pairIterator(i,j).filter(x=> !isEven(x._1)).map(x=>x._2).foldLeft(0){(x,y)=>x+y}\n\ndef ethiopian2(i:Int, j:Int):Int=\n   pairIterator(i,j).map(x=>if(isEven(x._1)) 0 else x._2).foldLeft(0){(x,y)=>x+y}\n\ndef ethiopian3(i:Int, j:Int):Int=\n{\n   var res=0;\n   for((h,d) <- pairIterator(i,j) if !isEven(h)) res+=d;\n   res\n}\n\ndef ethiopian4(i: Int, j: Int): Int = if (i == 1) j else ethiopian(halve(i), double(j)) + (if (isEven(i)) 0 else j)\n\ndef isEven(x:Int)=(x&1)==0\ndef halve(x:Int)=x>>>1\ndef double(x:Int)=x<<1\n\n\/\/ generates pairs of values (halve,double)\ndef pairIterator(x:Int, y:Int)=new Iterator[(Int, Int)]\n{\n   var i=(x, y)\n   def hasNext=i._1>0\n   def next={val r=i; i=(halve(i._1), double(i._2)); r}\n}\n","human_summarization":"The code defines three functions: one for halving an integer, one for doubling an integer, and one for checking if an integer is even. These functions are used to implement the Ethiopian multiplication method, which multiplies two numbers using only addition, doubling, and halving operations. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":2367}
    {"lang_cluster":"Scala","source_code":"\n\ndef permute(l: List[Double]): List[List[Double]] = l match {\n  case Nil => List(Nil)\n  case x :: xs =>\n    for {\n      ys <- permute(xs)\n      position <- 0 to ys.length\n      (left, right) = ys splitAt position\n    } yield left ::: (x :: right)\n}\n\ndef computeAllOperations(l: List[Double]): List[(Double,String)] = l match {\n  case Nil => Nil\n  case x :: Nil => List((x, \"%1.0f\" format x))\n  case x :: xs =>\n    for {\n      (y, ops) <- computeAllOperations(xs)\n      (z, op) <- \n        if (y == 0) \n          List((x*y, \"*\"), (x+y, \"+\"), (x-y, \"-\")) \n        else \n          List((x*y, \"*\"), (x\/y, \"\/\"), (x+y, \"+\"), (x-y, \"-\"))\n    } yield (z, \"(%1.0f%s%s)\" format (x,op,ops))\n}\n\ndef hasSolution(l: List[Double]) = permute(l) flatMap computeAllOperations filter (_._1 == 24) map (_._2)\n\n\nval problemsIterator = (\n    Iterator\n    continually List.fill(4)(scala.util.Random.nextInt(9) + 1 toDouble)\n    filter (!hasSolution(_).isEmpty)\n)\n\nval solutionIterator = problemsIterator map hasSolution\n\nscala> solutionIterator.next\nres8: List[String] = List((3*(5-(3-6))), (3*(5-(3-6))), (3*(5+(6-3))), (3+(6+(3*5))), (3*(6-(3-5))), (3+(6+(5*3))), (3*(\n6+(5-3))), (3*(5+(6-3))), (3+(6+(5*3))), (3*(6+(5-3))), (6+(3+(5*3))), (6*(5-(3\/3))), (6*(5-(3\/3))), (3+(6+(3*5))), (3*(\n6-(3-5))), (6+(3+(3*5))), (6+(3+(3*5))), (6+(3+(5*3))))\n\nscala> solutionIterator.next\nres9: List[String] = List((4-(5*(5-9))), (4-(5*(5-9))), (4+(5*(9-5))), (4+(5*(9-5))), (9-(5-(4*5))), (9-(5-(5*4))), (9-(\n5-(4*5))), (9-(5-(5*4))))\n\nscala> solutionIterator.next\nres10: List[String] = List((2*(4+(3+5))), (2*(3+(4+5))), (2*(3+(5+4))), (4*(3-(2-5))), (4*(3+(5-2))), (2*(4+(5+3))), (2*\n(5+(4+3))), (2*(5+(3+4))), (4*(5-(2-3))), (4*(5+(3-2))))\n\nscala> solutionIterator.next\nres11: List[String] = List((4*(5-(2-3))), (2*(4+(5+3))), (2*(5+(4+3))), (2*(5+(3+4))), (2*(4+(3+5))), (2*(3+(4+5))), (2*\n(3+(5+4))), (4*(5+(3-2))), (4*(3+(5-2))), (4*(3-(2-5))))\n\n","human_summarization":"\"Code generates arithmetic expressions from four input digits, following the rules of the 24 game, and displays example solutions.\"","id":2368}
    {"lang_cluster":"Scala","source_code":"\n\ndef factorial(n: Int) = {\n  var res = 1\n  for (i <- 1 to n)\n    res *= i \n  res\n}\n\ndef factorial(n: Int): Int = \n  if (n < 1) 1 \n  else       n * factorial(n - 1)\n\ndef factorial(n: Int) = {\n  @tailrec def fact(x: Int, acc: Int): Int = {\n    if (x < 2) acc else fact(x - 1, acc * x)\n  }\n  fact(n, 1)\n}\n\ndef factorial(n: Int) = (2 to n).product\n\ndef factorial(n: Int) =\n  (2 to n).foldLeft(1)(_ * _)\n\nimplicit def IntToFac(i\u00a0: Int) = new {\n  def\u00a0! = (2 to i).foldLeft(BigInt(1))(_ * _)\n}\n\nExample used in the REPL:\nscala> 20!\nres0: scala.math.BigInt = 2432902008176640000\n\nscala> 100!\nres1: scala.math.BigInt = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000\n\n","human_summarization":"implement a function that calculates the factorial of a given number. The function can be either iterative or recursive. It optionally handles negative input errors. The factorial of a number is the product of all positive integers less than or equal to that number, with the factorial of zero defined as one. The code may include various methods such as naive recursion, tail recursion with a helper function, using standard library builtin, using folding, and enriching the integer type to support unary exclamation mark operator and implicit conversion to big integer.","id":2369}
    {"lang_cluster":"Scala","source_code":"\nimport scala.util.Random\n\nobject BullCow {\n   def main(args: Array[String]): Unit = {\n      val number=chooseNumber\n      var guessed=false\n      var guesses=0\n\n      while(!guessed){\n         Console.print(\"Guess a 4-digit number with no duplicate digits: \")\n         val input=Console.readInt\n         val digits=input.toString.map(_.asDigit).toList\n         if(input>=1111 && input<=9999 && !hasDups(digits)){\n            guesses+=1\n            var bulls, cows=0\n            for(i <- 0 to 3)\n               if(number(i)==digits(i))\n                  bulls+=1\n               else if(number.contains(digits(i)))\n                  cows+=1\n\n            if(bulls==4)\n               guessed=true\n            else\n               println(\"%d Cows and %d Bulls.\".format(cows, bulls))\n         }\n      }\n      println(\"You won after \"+guesses+\" guesses!\");\n   }\n\n   def chooseNumber={\n      var digits=List[Int]()\n      while(digits.size<4){\n         val d=Random.nextInt(9)+1\n         if (!digits.contains(d))\n            digits=digits:+d\n      }\n      digits\n   }\n\n   def hasDups(input:List[Int])=input.size!=input.distinct.size\n}\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":2370}
    {"lang_cluster":"Scala","source_code":"\nList.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian)\n\nobject RandomNumbers extends App {\n\n  val distribution: LazyList[Double] = {\n    def randomNormal: Double = 1.0 + 0.5 * scala.util.Random.nextGaussian\n\n    def normalDistribution(a: Double): LazyList[Double] = a #:: normalDistribution(randomNormal)\n\n    normalDistribution(randomNormal)\n  }\n\n  \/*\n   * Let's test it\n   *\/\n  def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {\n    val mean: T =\n      num.div(ts.sum, num.fromInt(ts.size)) \/\/ Leaving with type of function T\n\n    \/\/ Root of mean diffs\n    val stdDev = Math.sqrt(ts.map { x =>\n      val diff = num.toDouble(num.minus(x, mean))\n      diff * diff\n    }.sum \/ ts.size)\n\n    (mean, stdDev)\n  }\n\n  println(calcAvgAndStddev(distribution.take(1000))) \/\/ e.g. (1.0061433267806525,0.5291834867560893)\n}\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":2371}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scalaclass Dot[T](v1: Seq[T])(implicit n: Numeric[T]) {\n  import n._ \/\/ import * operator\n  def dot(v2: Seq[T]) = {\n    require(v1.size == v2.size)\n    (v1 zip v2).map{ Function.tupled(_ * _)}.sum\n  }\n}\n\nobject Main extends App {\n  implicit def toDot[T: Numeric](v1: Seq[T]) = new Dot(v1)\n\n  val v1 = List(1, 3, -5)\n  val v2 = List(4, -2, -1)\n  println(v1 dot v2)\n}\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":2372}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nWorks with: Scala version 2.10.3\n  scala.io.Source.fromFile(\"input.txt\").getLines().foreach {\n    line => ... }\n\n","human_summarization":"\"Continuously read words or lines from a text stream until there is no more data available.\"","id":2373}
    {"lang_cluster":"Scala","source_code":"\nval xml = <root><element>Some text here<\/element><\/root>\nscala.xml.XML.save(filename=\"output.xml\", node=xml, enc=\"UTF-8\", xmlDecl=true, doctype=null)\n\n","human_summarization":"Create a simple DOM and serialize it into the specified XML format.","id":2374}
    {"lang_cluster":"Scala","source_code":"\nLibrary: ScalaAd hoc solution as REPL scripts:\nprintln(new java.util.Date)\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":2375}
    {"lang_cluster":"Scala","source_code":"\nclass SEDOL(s: String) {\n  require(s.size == 6 || s.size == 7, \"SEDOL length must be 6 or 7 characters\")\n  require(s.size == 6 || s(6).asDigit == chksum, \"Incorrect SEDOL checksum\")\n  require(s forall (c => !(\"aeiou\" contains c.toLower)), \"Vowels not allowed in SEDOL\")\n  def chksum = 10 - ((s zip List(1, 3, 1, 7, 3, 9) map { case (c, w) => c.asDigit * w } sum) % 10)\n  override def toString = s.take(6) + chksum\n}\n\n\nscala> \"\"\"710889\n     | B0YBKJ\n     | 406566\n     | B0YBLH\n     | 228276\n     | B0YBKL\n     | 557910\n     | B0YBKR\n     | 585284\n     | B0YBKT\"\"\".lines.map(_.trim).foreach(s => println(new SEDOL(s)))\n7108899\nB0YBKJ7\n4065663\nB0YBLH2\n2282765\nB0YBKL9\n5579107\nB0YBKR5\n5852842\nB0YBKT7\n\n\nscala> new SEDOL(\"12\")\njava.lang.IllegalArgumentException: requirement failed: SEDOL length must be 6 or 7 characters\n\nscala> new SEDOL(\"7108890\")\njava.lang.IllegalArgumentException: requirement failed: Incorrect SEDOL checksum\n\nscala> new SEDOL(\"71088A\")\njava.lang.IllegalArgumentException: requirement failed: Vowels not allowed in SEDOL\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":2376}
    {"lang_cluster":"Scala","source_code":"\nobject Sphere extends App {\n  private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d))\n\n  private def drawSphere(r: Double, k: Double, ambient: Double): Unit = {\n    def dot(x: Array[Double], y: Array[Double]) = {\n      val d = x.head * y.head + x(1) * y(1) + x.last * y.last\n      if (d < 0) -d else 0D\n    }\n\n    for (i <- math.floor(-r).toInt to math.ceil(r).toInt; x = i + .5)\n      println(\n        (for (j <- math.floor(-2 * r).toInt to math.ceil(2 * r).toInt; y = j \/ 2.0 + .5)\n          yield if (x * x + y * y <= r * r) {\n\n            def intensity(vec: Array[Double]) = {\n              val b = math.pow(dot(light, vec), k) + ambient\n              if (b <= 0) shades.length - 2\n              else math.max((1 - b) * (shades.length - 1), 0).toInt\n            }\n\n            shades(intensity(normalize(Array(x, y, scala.math.sqrt(r * r - x * x - y * y)))))\n          } else ' ').mkString)\n  }\n\n  private def normalize(v: Array[Double]): Array[Double] = {\n    val len = math.sqrt(v.head * v.head + v(1) * v(1) + v.last * v.last)\n    v.map(_ \/ len)\n  }\n\n  normalize(light).copyToArray(light)\n  drawSphere(20, 4, .1)\n  drawSphere(10, 2, .4)\n\n}\n\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":2377}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scalaobject Nth extends App {\n  def abbrevNumber(i: Int) = print(s\"$i${ordinalAbbrev(i)} \")\n\n  def ordinalAbbrev(n: Int) = {\n    val ans = \"th\" \/\/most of the time it should be \"th\"\n    if (n % 100 \/ 10 == 1) ans \/\/teens are all \"th\"\n    else (n % 10) match {\n      case 1 => \"st\"\n      case 2 => \"nd\"\n      case 3 => \"rd\"\n      case _ => ans\n    }\n  }\n\n  (0 to 25).foreach(abbrevNumber)\n  println()\n  (250 to 265).foreach(abbrevNumber)\n  println();\n  (1000 to 1025).foreach(abbrevNumber)\n}\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":2378}
    {"lang_cluster":"Scala","source_code":"\ndef stripChars(s:String, ch:String)= s filterNot (ch contains _)\n\nstripChars(\"She was a soul stripper. She took my heart!\", \"aei\")\n\/\/ => Sh ws  soul strppr. Sh took my hrt!\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":2379}
    {"lang_cluster":"Scala","source_code":"\n\nOutput for all examples:\n$ scala GeneralFizzBuzz.scala\n20\n3 Fizz\n5 Buzz\n7 Baxx\n^D\n\n1\n2\nFizz\n4\nBuzz\nFizz\nBaxx\n8\nFizz\nBuzz\n11\nFizz\n13\nBaxx\nFizzBuzz\n16\n17\nFizz\n19\nBuzz\n\nimport scala.io.{Source, StdIn}\n\nobject GeneralFizzBuzz extends App {\n  val max = StdIn.readInt()\n  val factors = Source.stdin.getLines().toSeq\n    .map(_.split(\" \", 2))\n    .map(f => f(0).toInt -> f(1))\n    .sorted\n\n  (1 to max).foreach { i =>\n    val words = factors.collect { case (k, v) if i % k == 0 => v }\n    println(if (words.nonEmpty) words.mkString else i)\n  }\n}\n\nimport scala.io.{Source, StdIn}\n\nobject GeneralFizzBuzz extends App {\n  def fizzBuzzTerm(n: Int, factors: Seq[(Int, String)]): String = {\n    val words = factors.collect { case (k, v) if n % k == 0 => v }\n    if (words.nonEmpty) words.mkString else n.toString\n  }\n\n  def fizzBuzz(factors: Seq[(Int, String)]): LazyList[String] =\n    LazyList.from(1).map(fizzBuzzTerm(_, factors))\n\n  val max = StdIn.readInt()\n  val factors = Source.stdin.getLines().toSeq\n    .map(_.split(\" \", 2))\n    .map { case Array(k, v) => k.toInt -> v }\n    .sorted\n  fizzBuzz(factors).take(max).foreach(println)\n}\nimport scala.io.{Source, StdIn}\n\ndef fizzBuzzTerm(n: Int, factors: Seq[(Int, String)]): String | Int =\n  val words = factors.collect { case (k, v) if n % k == 0 => v }\n  if words.nonEmpty then words.mkString else n\n\ndef fizzBuzz(factors: Seq[(Int, String)]): LazyList[String | Int] =\n  LazyList.from(1).map(i => fizzBuzzTerm(i, factors))\n\n@main def run(): Unit =\n  val max = StdIn.readInt()\n  val factors: Seq[(Int, String)] = Source.stdin.getLines().toSeq\n    .map(_.split(\" \", 2))\n    .map { case Array(k, v) => k.toInt -> v }\n    .sorted\n  fizzBuzz(factors).take(max).foreach(println)\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":2380}
    {"lang_cluster":"Scala","source_code":"\n\n  val s = \"World\" \/\/ Immutables are recommended   \/\/> s \u00a0: String = World\n  val f2 = () => \", \" \/\/Function assigned to variable\n                                                  \/\/> f2 \u00a0: () => String = <function0>\n  val s1 = \"Hello\" + f2() + s                     \/\/> s1 \u00a0: String = Hello, World\n  println(s1);                                    \/\/> Hello, World\n\n","human_summarization":"create a string variable, prepend another string to it, and display the result. If possible, the solution should avoid referencing the variable twice in one expression. The functionality is demonstrated using Scala.","id":2381}
    {"lang_cluster":"Scala","source_code":"\nimport javax.swing.JFrame\nimport java.awt.Graphics\n\nclass DragonCurve(depth: Int) extends JFrame(s\"Dragon Curve (depth $depth)\") {\n  \n  setBounds(100, 100, 800, 600);\n  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n  \n  val len = 400 \/ Math.pow(2, depth \/ 2.0);\n  val startingAngle = -depth * (Math.PI \/ 4);\n  val steps = getSteps(depth).filterNot(c => c == 'X' || c == 'Y')\n  \n  def getSteps(depth: Int): Stream[Char] = {\n    if (depth == 0) {\n      \"FX\".toStream\n    } else {\n      getSteps(depth - 1).flatMap{\n        case 'X' => \"XRYFR\"\n        case 'Y' => \"LFXLY\"\n        case c => c.toString\n      }\n    }\n  }\n  \n  override def paint(g: Graphics): Unit = {\n    var (x, y) = (230, 350)\n    var (dx, dy) = ((Math.cos(startingAngle) * len).toInt, (Math.sin(startingAngle) * len).toInt)\n    for (c <- steps) c match {\n      case 'F' => {\n        g.drawLine(x, y, x + dx, y + dy)\n        x = x + dx\n        y = y + dy\n      }\n      case 'L' => {\n        val temp = dx\n        dx = dy\n        dy = -temp\n      }\n      case 'R' => {\n        val temp = dx\n        dx = -dy\n        dy = temp\n      }\n    }\n  }\n\n}\n\nobject DragonCurve extends App {\n  new DragonCurve(14).setVisible(true);\n}\n\n","human_summarization":"generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.","id":2382}
    {"lang_cluster":"Scala","source_code":"\nval n = (math.random * 10 + 1).toInt\nprint(\"Guess the number: \")\nwhile(readInt != n) print(\"Wrong! Guess again: \")\nprintln(\"Well guessed!\")\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":2383}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nobject Abc extends App {\n  val lowAlpha = 'a' to 'z' \/\/That's all\n  \/\/ Now several tests\n  assert(lowAlpha.toSeq == Seq('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',\n    'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'),\n    \"No complete lowercase alphabet.\")\n  assert(lowAlpha.size == 26, \"No 26 characters in alphabet\")\n  assert(lowAlpha.start == 'a', \"Character 'a' not first char!\u00a0???\")\n  assert(lowAlpha.head == 'a', \"Character 'a' not heading!\u00a0???\")\n  assert(lowAlpha.head == lowAlpha(0), \"Heading char is not first char.\")\n  assert(lowAlpha contains 'n', \"Character n not present.\")\n  assert(lowAlpha.indexOf('n') == 13, \"Character n not on the 14th position.\")\n  assert(lowAlpha.last == lowAlpha(25), \"Expected character (z)on the last and 26th pos.\")\n\n  println(s\"Successfully completed without errors. [within ${\n    scala.compat.Platform.currentTime - executionStart\n  } ms]\")\n}\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":2384}
    {"lang_cluster":"Scala","source_code":"\n\nscala> (5 toBinaryString)\nres0: String = 101\n\nscala> (50 toBinaryString)\nres1: String = 110010\n\nscala> (9000 toBinaryString)\nres2: String = 10001100101000\n","human_summarization":"The code takes a non-negative integer as input and outputs its binary representation. It uses either built-in radix functions or a user-defined function to generate the binary sequence. The output consists of binary digits followed by a newline, with no additional whitespace, radix, or sign markers, and no leading zeros. In Scala, this can be achieved using the toBinaryString method.","id":2385}
    {"lang_cluster":"Scala","source_code":"\nimport java.awt.image.BufferedImage\nimport java.awt.Color\nimport scala.language.reflectiveCalls\n\nobject RgbBitmap extends App {\n\n  class RgbBitmap(val dim: (Int, Int)) {\n    def width = dim._1\n    def height = dim._2\n\n    private val image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)\n\n    def apply(x: Int, y: Int) = new Color(image.getRGB(x, y))\n\n    def update(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB)\n\n    def fill(c: Color) = {\n      val g = image.getGraphics\n      g.setColor(c)\n      g.fillRect(0, 0, width, height)\n    }\n  }\n\n  object RgbBitmap {\n    def apply(width: Int, height: Int) = new RgbBitmap(width, height)\n  }\n\n  \/** Even Javanese style testing is still possible.\n    *\/\n  private val img0 = new RgbBitmap(50, 60) { \/\/ Wrappers to enable adhoc Javanese style\n    def getPixel(x: Int, y: Int) = this(x, y)\n    def setPixel(x: Int, y: Int, c: Color) = this(x, y) = c\n  }\n\n  img0.fill(Color.CYAN)\n  img0.setPixel(5, 6, Color.BLUE)\n  \/\/ Testing in Java style\n  assert(img0.getPixel(0, 1) == Color.CYAN)\n  assert(img0.getPixel(5, 6) == Color.BLUE)\n  assert(img0.width == 50)\n  assert(img0.height == 60)\n  println(\"Tests successfully completed with no errors found.\")\n\n}\n","human_summarization":"create a 320x240 window and draw a red pixel at position (100, 100). It is best viewed in a browser with Scastie (remote JVM).","id":2386}
    {"lang_cluster":"Scala","source_code":"\n\nFilters out empty and comment lines\nSplits field name and value(s)\nAdds \"true\" to value-less fields\nConverts values to (k, List(values)\nConverts the entire collection to a Map\nval conf = scala.io.Source.fromFile(\"config.file\").\n  getLines.\n  toList.\n  filter(_.trim.size > 0).\n  filterNot(\"#;\" contains _(0)).\n  map(_ split(\" \", 2) toList).\n  map(_ :+ \"true\" take 2).\n  map {\n    s:List[String] => (s(0).toLowerCase, s(1).split(\",\").map(_.trim).toList)\n  }.toMap\n\n\nfor ((k,v) <- conf) {\n  if (v.size == 1)\n    println(\"%s: %s\" format (k, v(0)))\n  else\n    for (i <- 0 until v.size)\n      println(\"%s(%s): %s\" format (k, i+1, v(i)))\n\n}\n\n\n","human_summarization":"Code summarization: The code reads a configuration file, ignores lines starting with a hash or semicolon, and sets variables based on the configuration parameters. It also handles multiple parameters, storing them in an array. The variables include fullname, favouritefruit, needspeeling, seedsremoved, and otherfamily.","id":2387}
    {"lang_cluster":"Scala","source_code":"\nimport math._\n\nobject Haversine {\n   val R = 6372.8  \/\/radius in km\n\n   def haversine(lat1:Double, lon1:Double, lat2:Double, lon2:Double)={\n      val dLat=(lat2 - lat1).toRadians\n      val dLon=(lon2 - lon1).toRadians\n \n      val a = pow(sin(dLat\/2),2) + pow(sin(dLon\/2),2) * cos(lat1.toRadians) * cos(lat2.toRadians)\n      val c = 2 * asin(sqrt(a))\n      R * c\n   }\n\t\n   def main(args: Array[String]): Unit = {\n      println(haversine(36.12, -86.67, 33.94, -118.40))\n  }\n}\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":2388}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nimport scala.io.Source\n\nobject HttpTest extends App {\n  System.setProperty(\"http.agent\", \"*\")\n\n  Source.fromURL(\"http:\/\/www.rosettacode.org\").getLines.foreach(println)\n}\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":2389}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nobject Luhn {\n  private def parse(s: String): Seq[Int] = s.map{c =>\n    assert(c.isDigit)\n    c.asDigit\n  }\n  def checksum(digits: Seq[Int]): Int = {\n    digits.reverse.zipWithIndex.foldLeft(0){case (sum,(digit,i))=>\n      if (i%2 == 0) sum + digit\n      else sum + (digit*2)\/10 + (digit*2)%10\n    }\u00a0% 10\n  }\n  def validate(digits: Seq[Int]): Boolean = checksum(digits) == 0\n  def checksum(number: String): Int = checksum(parse(number))\n  def validate(number: String): Boolean = validate(parse(number))\n}\n\nobject LuhnTest extends App {\n  Seq((\"49927398716\", true),\n    (\"49927398717\", false),\n    (\"1234567812345678\", false),\n    (\"1234567812345670\", true)\n  ).foreach { case (n, expected) =>\n    println(s\"$n ${Luhn.validate(n)}\")\n    assert(Luhn.validate(n) == expected)\n  }\n}\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":2390}
    {"lang_cluster":"Scala","source_code":"\n\ndef executed( prisonerCount:Int, step:Int ) = {\n\n  val prisoners = ((0 until prisonerCount) map (_.toString)).toList\n\n  def behead( dead:Seq[String], alive:Seq[String] )(countOff:Int) : (Seq[String], Seq[String]) = {\n    val group = if( alive.size < countOff ) countOff - alive.size else countOff\n\t\n    (dead ++ alive.take(group).drop(group-1), alive.drop(group) ++ alive.take(group-1))\n  }\n\n  def beheadN( dead:Seq[String], alive:Seq[String] ) : (Seq[String], Seq[String]) =\n    behead(dead,alive)(step)\n\n  def execute( t:(Seq[String], Seq[String]) ) : (Seq[String], Seq[String]) = t._2 match {\n    case x :: Nil => (t._1, Seq(x))\n    case x :: xs => execute(beheadN(t._1,t._2))\n  }\n\n  execute((List(),prisoners))\n}\n\nval (dead,alive) = executed(41,3)\n  \nprintln( \"Prisoners executed in order:\" )\nprint( dead.mkString(\" \") )\n\t\nprintln( \"\\n\\nJosephus is prisoner \" + alive(0) )\n\n\n","human_summarization":"The code calculates the final survivor in the Josephus problem, given the total number of prisoners (n) and the step count (k). It also provides a method to determine the position of any prisoner in the killing sequence. The prisoners are numbered from 0 to n-1. The code also accounts for scenarios where multiple survivors (m) are allowed. The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":2391}
    {"lang_cluster":"Scala","source_code":"\n\"ha\" * 5 \/\/ ==> \"hahahahaha\"\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":2392}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\n\nval Bottles1 = \"(\\\\d+) bottles of beer\".r                                            \/\/ syntactic sugar\nval Bottles2 = \"\"\"(\\d+) bottles of beer\"\"\".r                                         \/\/ using triple-quotes to preserve backslashes\nval Bottles3 = new scala.util.matching.Regex(\"(\\\\d+) bottles of beer\")               \/\/ standard\nval Bottles4 = new scala.util.matching.Regex(\"\"\"(\\d+) bottles of beer\"\"\", \"bottles\") \/\/ with named groups\n\n\"99 bottles of beer\" matches \"(\\\\d+) bottles of beer\" \/\/ the full string must match\n\"99 bottles of beer\" replace (\"99\", \"98\") \/\/ Single replacement\n\"99 bottles of beer\" replaceAll (\"b\", \"B\") \/\/ Multiple replacement\n\n\"\\\\d+\".r findFirstIn \"99 bottles of beer\" \/\/ returns first partial match, or None\n\"\\\\w+\".r findAllIn \"99 bottles of beer\" \/\/ returns all partial matches as an iterator\n\"\\\\s+\".r findPrefixOf \"99 bottles of beer\" \/\/ returns a matching prefix, or None\nBottles4 findFirstMatchIn \"99 bottles of beer\" \/\/ returns a \"Match\" object, or None\nBottles4 findPrefixMatchOf \"99 bottles of beer\" \/\/ same thing, for prefixes\nval bottles = (Bottles4 findFirstMatchIn \"99 bottles of beer\").get.group(\"bottles\") \/\/ Getting a group by name\n\nval Some(bottles) = Bottles4 findPrefixOf \"99 bottles of beer\" \/\/ throws an exception if the matching fails; full string must match\nfor {\n  line <- \"\"\"|99 bottles of beer on the wall\n             |99 bottles of beer\n             |Take one down, pass it around\n             |98 bottles of beer on the wall\"\"\".stripMargin.lines\n} line match {\n  case Bottles1(bottles) => println(\"There are still \"+bottles+\" bottles.\") \/\/ full string must match, so this will match only once\n  case _ =>\n}\nfor {\n  matched <- \"(\\\\w+)\".r findAllIn \"99 bottles of beer\" matchData \/\/ matchData converts to an Iterator of Match\n} println(\"Matched from \"+matched.start+\" to \"+matched.end)\n\nBottles2 replaceFirstIn (\"99 bottles of beer\", \"98 bottles of beer\")\nBottles3 replaceAllIn (\"99 bottles of beer\", \"98 bottles of beer\")\n","human_summarization":"1. Matches a string against a specific regular expression.\n2. Substitutes a portion of a string using a defined regular expression.\n3. Implements search and replace functionalities using string methods.\n4. Executes search operations using regex methods.\n5. Utilizes pattern matching with regular expressions.\n6. Performs replacements in a string using regular expressions.","id":2393}
    {"lang_cluster":"Scala","source_code":"\nval a = Console.readInt\nval b = Console.readInt\n \nval sum = a + b \/\/integer addition is discouraged in print statements due to confusion with String concatenation\nprintln(\"a + b = \" + sum)\nprintln(\"a - b = \" + (a - b))\nprintln(\"a * b = \" + (a * b))\nprintln(\"quotient of a \/ b = \" + (a \/ b)) \/\/ truncates towards 0\nprintln(\"remainder of a \/ b = \" + (a\u00a0% b)) \/\/ same sign as first operand\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":2394}
    {"lang_cluster":"Scala","source_code":"\nimport scala.annotation.tailrec\ndef countSubstring(str1:String, str2:String):Int={\n   @tailrec def count(pos:Int, c:Int):Int={\n      val idx=str1 indexOf(str2, pos)\n      if(idx == -1) c else count(idx+str2.size, c+1)\n   }\n   count(0,0)\n}\n\ndef countSubstring(str: String, sub: String): Int =\n  str.sliding(sub.length).count(_ == sub)\n\ndef countSubstring( str:String, substr:String ) = substr.r.findAllMatchIn(str).length\n\n\nprintln(countSubstring(\"ababababab\", \"abab\"))\nprintln(countSubstring(\"the three truths\", \"th\"))\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the main string and the substring to search for, and returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches and does not count overlapping substrings.","id":2395}
    {"lang_cluster":"Scala","source_code":"\ndef move(n: Int, from: Int, to: Int, via: Int)\u00a0: Unit = {\n    if (n == 1) {\n      Console.println(\"Move disk from pole \" + from + \" to pole \" + to)\n    } else {\n      move(n - 1, from, via, to)\n      move(1, from, to, via)\n      move(n - 1, via, to, from)\n    }\n  }\n\nobject TowersOfHanoi {\n  import scala.reflect.Manifest\n  \n  def simpleName(m:Manifest[_]):String = {\n    val name = m.toString\n    name.substring(name.lastIndexOf('$')+1)\n  }\n  \n  trait Nat\n  final class _0 extends Nat\n  final class Succ[Pre<:Nat] extends Nat\n \n  type _1 = Succ[_0]\n  type _2 = Succ[_1]\n  type _3 = Succ[_2]\n  type _4 = Succ[_3]\n \n  case class Move[N<:Nat,A,B,C]()\n \n  implicit def move0[A,B,C](implicit a:Manifest[A],b:Manifest[B]):Move[_0,A,B,C] = {\n        System.out.println(\"Move from \"+simpleName(a)+\" to \"+simpleName(b));null\n  }\n \n  implicit def moveN[P<:Nat,A,B,C](implicit m1:Move[P,A,C,B],m2:Move[_0,A,B,C],m3:Move[P,C,B,A])\n   :Move[Succ[P],A,B,C] = null\n  \n  def run[N<:Nat,A,B,C](implicit m:Move[N,A,B,C]) = null\n  \n  case class Left()\n  case class Center()\n  case class Right()\n  \n  def main(args:Array[String]){\n    run[_2,Left,Right,Center]\n  }\n}\n","human_summarization":"use recursion to solve the Towers of Hanoi problem. The solution is a Scala translation of a Prolog solution from http:\/\/gist.github.com\/66925, which solves the problem at compile time.","id":2396}
    {"lang_cluster":"Scala","source_code":"\nobject Binomial {\n   def main(args: Array[String]): Unit = {\n      val n=5\n      val k=3\n      val result=binomialCoefficient(n,k)\n      println(\"The Binomial Coefficient of %d and %d equals %d.\".format(n, k, result))\n   }\n\n   def binomialCoefficient(n:Int, k:Int)=fact(n) \/ (fact(k) * fact(n-k))\n   def fact(n:Int):Int=if (n==0) 1 else n*fact(n-1)\n}\n\n\n","human_summarization":"The code calculates any binomial coefficient, with a specific focus on outputting the binomial coefficient of 5 choose 3, which is 10. It uses the formula for binomial coefficients and can handle coefficients of arbitrary size due to the use of BigInts. The code also includes functionality for combinations and permutations, with and without replacement.","id":2397}
    {"lang_cluster":"Scala","source_code":"\nobject ShellSort {\n  def incSeq(len:Int)=new Iterator[Int]{\n    private[this] var x:Int=len\/2\n    def hasNext=x>0\n    def next()={x=if (x==2) 1 else x*5\/11; x}\n  }\n\n  def InsertionSort(a:Array[Int], inc:Int)={\n    for (i <- inc until a.length; temp=a(i)){ \n      var j=i;\n      while (j>=inc && a(j-inc)>temp){ \n        a(j)=a(j-inc)\n        j=j-inc\n      }\n      a(j)=temp\n    }\n  }\n  \n  def shellSort(a:Array[Int])=for(inc<-incSeq(a.length)) InsertionSort(a, inc)\n  \n  def main(args: Array[String]): Unit = {\n    var a=Array(2, 5, 3, 4, 3, 9, 3, 2, 5, 4, 1, 3, 22, 7, 2, -5, 8, 4)\n    println(a.mkString(\",\"))\n    shellSort(a)\n    println(a.mkString(\",\"))\n  }\n}\n\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":2398}
    {"lang_cluster":"Scala","source_code":"\n\nobject BitmapOps {\n   def luminosity(c:Color)=(0.2126*c.getRed + 0.7152*c.getGreen + 0.0722*c.getBlue+0.5).toInt\n\n   def grayscale(bm:RgbBitmap)={\n      val image=new RgbBitmap(bm.width, bm.height)\n      for(x <- 0 until bm.width; y <- 0 until bm.height; l=luminosity(bm.getPixel(x,y)))\n         image.setPixel(x, y, new Color(l,l,l))\n      image\n   }\n}\n\n","human_summarization":"extend the data storage type to support grayscale images, convert color images to grayscale and vice versa using the CIE recommended formula for luminance. The codes also ensure that rounding errors in floating-point arithmetic do not cause run-time problems or distorted results. The codes utilize the Scala Basic Bitmap Storage class.","id":2399}
    {"lang_cluster":"Scala","source_code":"\nWorks with: Scala version 2.8\nimport scala.actors.Actor.{actor, loop, reactWithin, exit}\nimport scala.actors.TIMEOUT\nimport scala.swing.{SimpleSwingApplication, MainFrame, Label}\nimport scala.swing.event.MouseClicked\n\ncase object Revert\n\nobject BasicAnimation extends SimpleSwingApplication {\n  val label = new Label(\"Hello World! \")\n  val rotator = actor {\n    var goingRight = true\n    loop {\n      reactWithin(250 \/*ms*\/) {\n        case Revert => goingRight = !goingRight\n        case TIMEOUT =>\n          if (goingRight)\n            label.text = label.text.last + label.text.init\n          else\n            label.text = label.text.tail + label.text.head\n        case unknown => println(\"Unknown message \"+unknown); exit()\n      }\n    }\n  }\n  def top = new MainFrame {\n    title = \"Basic Animation\"\n    contents = label\n  }\n  listenTo(label.mouse.clicks) \/\/ use \"Mouse\" instead of \"mouse\" on Scala 2.7\n  reactions += {\n    case _ : MouseClicked => rotator ! Revert\n  }\n}\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":2400}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\n  {\n    var (x, l) = (0, List[Int]())\n    do {\n      x += 1\n      l\u00a0:+= x \/\/ A new copy of this list with List(x) appended.\n    } while (x\u00a0% 6\u00a0!= 0)\n    l\n  }.foreach(println(_))\n\tdef loop(iter: Int, cond: (Int) => Boolean, accu: List[Int]): List[Int] = {\n\t  val succ = iter + 1\n\t  val temp = accu\u00a0:+ succ\n\t  if (cond(succ)) loop(succ, cond, temp) else temp\n\t}\n\tprintln(loop(0, (_\u00a0% 6\u00a0!= 0), Nil))\n  def loop(i: Int, cond: (Int) => Boolean): Stream[Int] = {\n    val succ = i + 1;\n    succ #:: (if (cond(succ)) loop(succ, cond) else Stream.empty)\n  }\n  loop(0, (_\u00a0% 6\u00a0!= 0)).foreach(println(_))\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":2401}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nobject StringLength extends App {\n  val s1 = \"m\u00f8\u00f8se\"\n  val s3 = List(\"\\uD835\\uDD18\", \"\\uD835\\uDD2B\", \"\\uD835\\uDD26\",\n    \"\\uD835\\uDD20\", \"\\uD835\\uDD2C\", \"\\uD835\\uDD21\", \"\\uD835\\uDD22\").mkString\n  val s4 = \"J\\u0332o\\u0332s\\u0332e\\u0301\\u0332\"\n\n    List(s1, s3, s4).foreach(s => println(\n        s\"The string: $s, characterlength= ${s.length} UTF8bytes= ${\n      s.getBytes(\"UTF-8\").size\n    } UTF16bytes= ${s.getBytes(\"UTF-16LE\").size}\"))\n}\n\n","human_summarization":"calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.","id":2402}
    {"lang_cluster":"Scala","source_code":"\nimport java.security.SecureRandom\n\nobject RandomExample extends App {\n  new SecureRandom {\n    val newSeed: Long = this.nextInt().toLong * this.nextInt()\n    this.setSeed(newSeed) \/\/ reseed using the previous 2 random numbers\n    println(this.nextInt()) \/\/ get random 32-bit number and print it\n  }\n}\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.","id":2403}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nprintln(\"knight\".tail)               \/\/ strip first character\nprintln(\"socks\".init)         \/\/ strip last character\nprintln(\"brooms\".tail.init)   \/\/ strip both first and last characters\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":2404}
    {"lang_cluster":"Scala","source_code":"\nimport java.io.IOException\nimport java.net.{InetAddress, ServerSocket}\n\nobject SingletonApp extends App {\n  private val port = 65000\n\n  try {\n    val s = new ServerSocket(port, 10, InetAddress.getLocalHost)\n  }\n  catch {\n    case _: IOException =>\n      \/\/ port taken, so app is already running\n      println(\"Application is already running, so terminating this instance.\")\n      sys.exit(-1)\n  }\n\n  println(\"OK, only this instance is running but will terminate in 10 seconds.\")\n\n  Thread.sleep(10000)\n\n  sys.exit(0)\n\n}\n","human_summarization":"\"Check if an application instance is already running, display a message if so, and terminate the program.\"","id":2405}
    {"lang_cluster":"Scala","source_code":"\nimport java.awt.{Dimension, Insets, Toolkit}\n\nimport javax.swing.JFrame\n\nclass MaxWindowDims() extends JFrame {\n  val toolkit: Toolkit = Toolkit.getDefaultToolkit\n  val (insets0, screenSize) = (toolkit.getScreenInsets(getGraphicsConfiguration),  toolkit.getScreenSize)\n\n  println(\"Physical screen size: \" + screenSize)\n  System.out.println(\"Insets: \" + insets0)\n  screenSize.width -= (insets0.left + insets0.right)\n  screenSize.height -= (insets0.top + insets0.bottom)\n  System.out.println(\"Max available: \" + screenSize)\n}\n\nobject MaxWindowDims {\n  def main(args: Array[String]): Unit = {\n    new MaxWindowDims\n  }\n}\n\n","human_summarization":"calculate the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations, menubars, multiple monitors, and tiling window managers.","id":2406}
    {"lang_cluster":"Scala","source_code":"\n\nWorks with: Scala version 2.9.1\nobject SudokuSolver extends App {\n\n  class Solver {\n\n    var solution = new Array[Int](81)   \/\/listOfFields toArray\n\n    val fp2m: Int => Tuple2[Int,Int] = pos => Pair(pos\/9+1,pos%9+1) \/\/get row, col from array position\n    val setAll = (1 to 9) toSet \/\/all possibilities\n\n    val arrayGroups = new Array[List[List[Int]]](81)\n    val sv: Int => Int = (row: Int) => (row-1)*9 \/\/start value group row\n    val ev: Int => Int = (row: Int) => sv(row)+8 \/\/end value group row\n    val fgc: (Int,Int) => Int = (i,col) => i*9+col-1 \/\/get group col\n    val fgs: Int => (Int,Int) = p => Pair(p, p\/(27)*3+p%9\/3) \/\/get group square box\n    for (pos <- 0 to 80) {\n      val (row,col) = fp2m(pos)\n      val gRow = (sv(row) to ev(row)).toList\n      val gCol = ((0 to 8) toList) map (fgc(_,col))\n      val gSquare = (0 to 80 toList) map fgs filter (_._2==(fgs(pos))._2) map (_._1)\n      arrayGroups(pos) = List(gRow,gCol,gSquare)\n    }\n    val listGroups = arrayGroups toList \n    \n    val fpv4s: (Int) => List[Int] = pos => {   \/\/get possible values for solving\n      val setRow = (listGroups(pos)(0) map (solution(_))).toSet\n      val setCol = listGroups(pos)(1).map(solution(_)).toSet\n      val setSquare = listGroups(pos)(2).map(solution(_)).toSet\n      val setG = setRow++setCol++setSquare--Set(0)\n      val setPossible = setAll--setG\n      setPossible.toList.sortWith(_<_)\n    }\n    \n    \n    \/\/solve the riddle: Nil ==> solution does not exist\n    def solve(listOfFields: List[Int]): List[Int] = {\n      solution = listOfFields toArray\n\n      def checkSol(uncheckedSol: List[Int]): List[Int] = {\n        if (uncheckedSol == Nil) return Nil\n        solution = uncheckedSol toArray\n        val check = (0 to 80).map(fpv4s(_)).filter(_.size>0)\n        if (check == Nil) return uncheckedSol\n        return Nil\n      }\n    \n      val f1: Int => Pair[Int,Int] = p => Pair(p,listOfFields(p))\n      val numFields = (0 to 80 toList) map f1 filter (_._2==0)\n      val iter = numFields map ((_: (Int,Int))._1)\n      var p_iter = 0\n\n      val first: () => Int = () => {\n        val ret = numFields match {\n          case Nil => -1\n          case _   => numFields(0)._1\n        }\n        ret\n      }\n  \n      val last: () => Int = () => {\n        val ret = numFields match {\n          case Nil => -1\n          case _   => numFields(numFields.size-1)._1\n        }\n        ret\n      }\n  \n      val hasPrev: () => Boolean = () => p_iter > 0\n      val prev: () => Int = () => {p_iter -= 1; iter(p_iter)}\n      val hasNext: () => Boolean = () => p_iter < iter.size-1\n      val next: () => Int = () => {p_iter += 1; iter(p_iter)}\n      val fixed: Int => Boolean = pos => listOfFields(pos) != 0  \n      val possiArray = new Array[List[Int]](numFields.size)\n      val firstUF = first() \/\/first unfixed\n      if (firstUF < 0) return checkSol(solution.toList) \/\/that is it!\n      var pif = iter(p_iter) \/\/pos in fields\n      val lastUF = last() \/\/last unfixed\n      val (row,col) = fp2m(pif)\n      possiArray(p_iter) = fpv4s(pif).toList.sortWith(_<_)\n\n      while(pif <= lastUF) {\n        val (row,col) = fp2m(pif)\n        if (possiArray(p_iter) == null) possiArray(p_iter) = fpv4s(pif).toList.sortWith(_<_)\n        val possis = possiArray(p_iter)\n        if (possis.isEmpty) {\n          if (hasPrev()) {\n            possiArray(p_iter) = null\n            solution(pif) = 0\n            pif = prev()\n          } else {\n            return Nil\n          }\n        } else {\n          solution(pif) = possis(0)\n          possiArray(p_iter) = (possis.toSet - possis(0)).toList.sortWith(_<_)\n          if (hasNext()) {\n            pif = next()\n          } else {\n            return checkSol(solution.toList)\n          }\n        }\n      }\n      checkSol(solution.toList)\n    }\n  }  \n\n  val f2Str: List[Int] => String = fields => {\n    val sepLine = \"+---+---+---+\"\n    val sepPoints = Set(2,5,8)\n    val fs: (Int, Int) => String = (i, v) => v.toString.replace(\"0\",\" \")+(if (sepPoints.contains(i%9)) \"|\" else \"\")\n    sepLine+\"\\n\"+(0 to fields.size-1).map(i => (if (i%9==0) \"|\" else \"\")+fs(i,fields(i))+(if (i%9==8) if (sepPoints.contains(i\/9)) \"\\n\"+sepLine+\"\\n\" else \"\\n\" else \"\")).foldRight(\"\")(_+_)\n  }\n  \n  val solver = new Solver()\n\n  val riddle = List(3,9,4,0,0,2,6,7,0,\n                    0,0,0,3,0,0,4,0,0,\n                    5,0,0,6,9,0,0,2,0,\n                    0,4,5,0,0,0,9,0,0,\n                    6,0,0,0,0,0,0,0,7,\n                    0,0,7,0,0,0,5,8,0,\n                    0,1,0,0,6,7,0,0,8,\n                    0,0,9,0,0,8,0,0,0,\n                    0,2,6,4,0,0,7,3,5)\n\n  println(\"riddle:\")\n  println(f2Str(riddle))\n  var solution = solver.solve(riddle)\n\n  println(\"solution:\")\n  println(solution match {case Nil => \"no solution!!!\" case _ => f2Str(solution)})\n \n}\n\n\n","human_summarization":"\"Implement a Sudoku solver that can solve a partially filled 9x9 Sudoku grid and display the result in a human-readable format. The solver can handle standard and jigsaw type Sudokus, as well as Sudokus with additional constraints such as a diagonal constraint. The code is inspired by the Java section and works effectively, despite not being the most elegant or functional programming solution.\"","id":2407}
    {"lang_cluster":"Scala","source_code":"\ndef shuffle[T](a: Array[T]) = {\n  for (i <- 1 until a.size reverse) {\n    val j = util.Random nextInt (i + 1)\n    val t = a(i)\n    a(i) = a(j)\n    a(j) = t\n  }\n  a\n}\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":2408}
    {"lang_cluster":"Scala","source_code":"\nimport java.util.Calendar\nimport java.text.SimpleDateFormat\n\nobject Fridays {\n\n  def lastFridayOfMonth(year:Int, month:Int)={\n    val cal=Calendar.getInstance\n    cal.set(Calendar.YEAR, year)\n    cal.set(Calendar.MONTH, month)\n    cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY)\n    cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, -1)\n    cal.getTime\n  }\n\t\n  def fridaysOfYear(year:Int)=for(month <- 0 to 11) yield lastFridayOfMonth(year, month)\n\t\n  def main(args:Array[String]){\n    val year=args(0).toInt\n    val formatter=new SimpleDateFormat(\"yyyy-MMM-dd\")\n    fridaysOfYear(year).foreach{date=>\n      println(formatter.format(date))\n    }\n  }\n}\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":2409}
    {"lang_cluster":"Scala","source_code":"\nLibrary: scala\n\nprint(\"Goodbye, World!\")\n","human_summarization":"display the string \"Goodbye, World!\" without appending a newline at the end.","id":2410}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nimport swing.Dialog.{Message, showInput}\nimport scala.swing.Swing\n \nobject UserInput extends App {\n  def responce = showInput(null,\n    \"Complete the sentence:\\n\\\"Green eggs and...\\\"\",\n    \"Customized Dialog\",\n    Message.Plain,\n    Swing.EmptyIcon,\n    Nil, \"ham\")\n  println(responce)\n}\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":2411}
    {"lang_cluster":"Scala","source_code":"\nobject Caesar {\n  private val alphaU='A' to 'Z'\n  private val alphaL='a' to 'z'\n\n  def encode(text:String, key:Int)=text.map{\n    case c if alphaU.contains(c) => rot(alphaU, c, key)\n    case c if alphaL.contains(c) => rot(alphaL, c, key)\n    case c => c\n  }\n  def decode(text:String, key:Int)=encode(text,-key)\n  private def rot(a:IndexedSeq[Char], c:Char, key:Int)=a((c-a.head+key+a.size)%a.size)\n}\nval text=\"The five boxing wizards jump quickly\"\nprintln(\"Plaintext  => \" + text)\nval encoded=Caesar.encode(text, 3)\nprintln(\"Ciphertext => \" + encoded)\nprintln(\"Decrypted  => \" + Caesar.decode(encoded, 3))\n\n","human_summarization":"Implement a Caesar cipher for both encoding and decoding. The cipher uses a key between 1 and 25 to rotate the letters of the alphabet. It replaces each letter with the next 1st to 25th letter in the alphabet, looping from Z back to A. The codes also consider the vulnerabilities of the cipher, such as frequency analysis and brute force attacks. The implementation is similar to Vigen\u00e8re cipher with a key length of 1 and Rot-13 with key 13. The codes first create non-shifted and shifted character sequences, then perform encoding and decoding by indexing between these sequences.","id":2412}
    {"lang_cluster":"Scala","source_code":"\ndef gcd(a: Int, b: Int):Int=if (b==0) a.abs else gcd(b, a%b)\ndef lcm(a: Int, b: Int)=(a*b).abs\/gcd(a,b)\n\nlcm(12, 18)   \/\/ 36\nlcm( 2,  0)   \/\/ 0\nlcm(-6, 14)   \/\/ 42\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":2413}
    {"lang_cluster":"Scala","source_code":"\nobject Cusip extends App {\n\n  val candidates = Seq(\"037833100\", \"17275R102\", \"38259P508\", \"594918104\", \"68389X106\", \"68389X105\")\n\n  for (candidate <- candidates)\n    printf(f\"$candidate%s -> ${if (isCusip(candidate)) \"correct\" else \"incorrect\"}%s%n\")\n\n  private def isCusip(s: String): Boolean = {\n    if (s.length != 9) false\n    else {\n      var sum = 0\n      for (i <- 0 until 7) {\n        val c = s(i)\n        var v = 0\n        if (c >= '0' && c <= '9') v = c - 48\n        else if (c >= 'A' && c <= 'Z') v = c - 55 \/\/ lower case letters apparently invalid\n        else if (c == '*') v = 36\n        else if (c == '@') v = 37\n        else if (c == '#') v = 38\n        else return false\n        if (i % 2 == 1) v *= 2 \/\/ check if odd as using 0-based indexing\n        sum += v \/ 10 + v % 10\n      }\n      s(8) - 48 == (10 - (sum % 10)) % 10\n    }\n  }\n\n}\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":2414}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scalaimport java.nio.ByteOrder\n\nobject ShowByteOrder extends App {\n  println(ByteOrder.nativeOrder())\n  println(s\"Word size: ${System.getProperty(\"sun.arch.data.model\")}\")\n  println(s\"Endianness: ${System.getProperty(\"sun.cpu.endian\")}\")\n}\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":2415}
    {"lang_cluster":"Scala","source_code":"\n\nimport akka.actor.{Actor, ActorSystem, Props}\nimport scala.collection.immutable.TreeSet\nimport scala.xml.XML\n\n\/\/ Reports a list with all languages recorded in the Wiki\n\nprivate object Acquisition {\n  val (endPoint, prefix) = (\"http:\/\/rosettacode.org\/mw\/api.php\", \"Category:\")\n  val (maxPlaces, correction) = (50, 2)\n\n  def convertPathArgsToURL(endPoint: String, pathArgs: Map[String, String]) = {\n    pathArgs.map(argPair => argPair._1 + \"=\" + argPair._2)\n      .mkString(endPoint + (if (pathArgs.nonEmpty) \"?\" else \"\"), \"&\", \"\")\n  }\n\n  \/* The categories include a page for the language and a count of the pages\n   * linked therein, this count is the data we need to scrape.\n   * Reports a list with language, count pair recorded in the Wiki\n   * All strings starts with the prefixes \"Category:\"\n   *\/\n  def mineCatos = {\n    val endPoint = \"http:\/\/rosettacode.org\/mw\/index.php\"\n    Concurrent.logInfo(\"Acquisition of categories started.\")\n    val categories =\n      (XML.load(convertPathArgsToURL(endPoint,\n        Map(\"title\" -> \"Special:Categories\", \"limit\" -> \"5000\"))) \\\\ \"ul\" \\ \"li\")\n        .withFilter(p => (p \\ \"a\" \\ \"@title\").text.startsWith(prefix))\n        .map \/\/ Create a tuple pair, eg. (\"Category:Erlang\", 195)\n        { cat =>\n          ((cat \\ \"a\" \\ \"@title\").text, \/\/ Takes the sibling of \"a\" and extracts the number\n            \"[0-9]+\".r.findFirstIn(cat.child.drop(1).text).getOrElse(\"0\").toInt)\n        }\n    Concurrent.logInfo(s\"Got ${categories.size} categories..\")\n    categories\n  }\n\n  \/\/ The languages\n  \/\/ All strings starts with the prefixes \"Category:\"\n  def mineLangs = {\n    Concurrent.logInfo(\"Acquisition of languages started...\")\n    def getLangs(first: Boolean = true, continue: String = \"\"): TreeSet[String] = (first, continue) match {\n      case (false, \"\") => TreeSet[String]()\n      case _ => {\n        val xml = XML.load(convertPathArgsToURL(endPoint, Map(\n            \"action\" -> \"query\",\n            \"list\" -> \"categorymembers\",\n            \"cmtitle\" -> (prefix + \"Programming_Languages\"),\n            \"cmlimit\" -> \"500\",\n            \"rawcontinue\" -> \"\",\n            \"format\" -> \"xml\",\n            \"cmcontinue\" -> continue)))\n        getLangs(false, (xml \\\\ \"query-continue\" \\ \"categorymembers\" \\ \"@cmcontinue\").text) ++ (xml \\\\ \"categorymembers\" \\ \"cm\").map(c => (c \\ \"@title\").text)\n      }\n    }\n    val languages = getLangs()\n    Concurrent.logInfo(s\"Got ${languages.size} languages..\")\n    languages\n  }\n\n  def joinRosettaCodeWithLanguage(catos: Seq[(String, Int)],\n                                  langs: TreeSet[String]) =\n    for {\n      cato <- catos \/\/Clean up the tuple pairs, eg (\"Category:Erlang\", 195) becomes (\"Erlang\", 192)\n      if langs.contains(cato._1)\n    } yield (cato._1.drop(prefix.length), cato._2 - correction max 0) \/\/ Correct count\n\n  def printScrape(languages: TreeSet[String], category: Seq[(String, Int)]) {\n\n    val join = joinRosettaCodeWithLanguage(category, languages)\n    val total = join.foldLeft(0)(_ + _._2)\n\n    Concurrent.logInfo(\"Data processed\")\n\n    println(f\"\\nTop$maxPlaces%3d Rosetta Code Languages by Popularity as ${new java.util.Date}%tF:\\n\")\n    (join.groupBy(_._2).toSeq.sortBy(-_._1).take(maxPlaces) :+ (0, Seq((\"...\", 0))))\n      .zipWithIndex \/\/ Group the ex aequo\n      .foreach {\n        case ((score, langs), rank) =>\n          println(f\"${rank + 1}%2d. $score%3d - ${langs.map(_._1).mkString(\", \")}\")\n      }\n\n    println(s\"\\nCross section yields ${join.size} languages, total of $total solutions\")\n    println(s\"Resulting average is ${total \/ join.size} solutions per language\")\n  }\n\n  def printScrape(): Unit = printScrape(mineLangs, mineCatos)\n} \/\/ object Acquisition\n\nprivate object Concurrent extends AppCommons {\n  var (category: Option[Seq[(String, Int)]], language: Option[TreeSet[String]]) = (None, None)\n\n  class Worker extends Actor {\n    def receive = {\n      case 'Catalogue => sender ! Acquisition.mineCatos\n      case 'Language => sender ! Acquisition.mineLangs\n    }\n  }\n\n  class Listener extends Actor {\n    \/\/ Create and signal the worker actors\n    context.actorOf(Props[Worker], \"worker0\") ! 'Catalogue\n    context.actorOf(Props[Worker], \"worker1\") ! 'Language\n\n    def printCompleteScape() =\n      if (category.isDefined && language.isDefined) {\n        Acquisition.printScrape(language.get, category.get)\n        context.system.shutdown()\n        appEnd()\n      }\n\n    def receive = {\n      case content: TreeSet[String] =>\n        language = Some(content)\n        printCompleteScape()\n      case content: Seq[(String, Int)] =>\n        category = Some(content)\n        printCompleteScape()\n      case whatever => logInfo(whatever.toString)\n    } \/\/ def receive\n  }\n} \/\/ object Concurrent\n\ntrait AppCommons {\n  val execStart = System.currentTimeMillis()\n  System.setProperty(\"http.agent\", \"*\")\n\n  def logInfo(info: String) {\n    println(f\"[Info][${System.currentTimeMillis() - execStart}%5d ms]\" + info)\n  }\n\n  def appEnd() { logInfo(\"Run succesfully completed\") }\n}\n\n\/\/ Main entry for sequential version (slower)\nobject GhettoParserSeq extends App with AppCommons {\n  Concurrent.logInfo(\"Sequential version started\")\n  Acquisition.printScrape()\n  appEnd()\n}\n\n\/\/ Entry for parallel version (faster)\nobject GhettoParserPar extends App {\n  Concurrent.logInfo(\"Parallel version started\")\n  ActorSystem(\"Main\").actorOf(Props[Concurrent.Listener])\n}\n\n\n\nOutput for both solutions: but parallel run chosen. Notice the synchronous start time.\n[Info][    0 ms]Sequential version started\n[Info][    3 ms]Acquisition of languages started...\n[Info][ 1458 ms]Got 642 languages..\n[Info][ 1458 ms]Acquisition of categories started.\n[Info][19385 ms]Got 2647 categories..\n[Info][19389 ms]Data processed\n\nTop 50 Rosetta Code Languages by Popularity as 2016-11-11:\n\n 1. 907 - Racket\n 2. 896 - Python, Tcl\n 3. 859 - J\n 4. 846 - Perl 6\n 5. 810 - Ruby\n 6. 807 - Zkl\n 7. 795 - C\n 8. 774 - Java\n 9. 773 - Go\n10. 754 - Haskell\n11. 753 - Perl\n12. 751 - REXX\n13. 750 - D\n14. 729 - PicoLisp\n15. 689 - Mathematica\n16. 674 - Sidef\n17. 634 - C++\n18. 631 - Ada\n19. 609 - AutoHotkey\n20. 592 - Common Lisp\n21. 583 - Unicon\n22. 569 - Scala\n23. 560 - C sharp\n24. 546 - BBC BASIC\n25. 526 - Icon\n26. 522 - Clojure\n27. 520 - JavaScript\n28. 519 - OCaml\n29. 517 - PureBasic\n30. 513 - PARI\/GP\n31. 510 - Lua\n32. 509 - Nim\n33. 497 - ALGOL 68\n34. 491 - Elixir\n35. 488 - Fortran\n36. 474 - Erlang\n37. 430 - PowerShell\n38. 428 - Julia\n39. 414 - Jq\n40. 413 - F Sharp\n41. 409 - Phix\n42. 407 - Pascal\n43. 405 - Forth, Seed7\n44. 398 - PL\/I\n45. 383 - R\n46. 382 - PHP\n47. 377 - Groovy\n48. 370 - AWK\n49. 340 - MATLAB\n50. 333 - Liberty BASIC\n51.   0 - ...\n\nCross section yields 619 languages, total of 50835 solutions\nResulting average is 82 solutions per language\n[Info][19413 ms]Run succesfully completed\n","human_summarization":"The code sorts and ranks computer programming languages based on their popularity, determined by the number of members in their respective Rosetta Code categories. It uses either web scraping or API methods to access the data. The code also provides an option to filter incorrect results. The results are checked against a complete, accurate, and periodically updated list of all programming languages. The code also includes an entry point at object GhettoParserPar and GhettoParserSeq.","id":2416}
    {"lang_cluster":"Scala","source_code":"\nval collection = Array(1, 2, 3, 4)\ncollection.foreach(println)\n\n(element <- 1 to 4).foreach(println)\n","human_summarization":"Iterates through each element in a collection in order using a \"for each\" loop or another loop if \"for each\" is not available, and prints each element.","id":2417}
    {"lang_cluster":"Scala","source_code":"\nprintln(\"Hello,How,Are,You,Today\" split \",\" mkString \".\")\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":2418}
    {"lang_cluster":"Scala","source_code":"\ndef gcd(a: Int, b: Int): Int = if (b == 0) a.abs else gcd(b, a\u00a0% b)\n\n@tailrec\ndef gcd(a: Int, b: Int): Int = {\n  b match {\n    case 0 => a\n    case _ => gcd(b, (a\u00a0% b))\n  }\n}\n","human_summarization":"find the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It also relates to the task of finding the least common multiple.","id":2419}
    {"lang_cluster":"Scala","source_code":"\nimport java.io.PrintWriter\nimport java.net.{ServerSocket, Socket}\n\nimport scala.io.Source\n\nobject EchoServer extends App {\n  private val serverSocket = new ServerSocket(23)\n  private var numConnections = 0\n\n  class ClientHandler(clientSocket: Socket) extends Runnable {\n    private val (connectionId, closeCmd) = ({numConnections += 1; numConnections}, \":exit\")\n\n    override def run(): Unit =\n      new PrintWriter(clientSocket.getOutputStream, true) {\n        println(s\"Connection opened, close with entering '$closeCmd'.\")\n        Source.fromInputStream(clientSocket.getInputStream).getLines\n          .takeWhile(!_.toLowerCase.startsWith(closeCmd))\n          .foreach { line =>\n            Console.println(s\"Received on #$connectionId: $line\")\n            println(line)  \/\/ Echo\n          }\n        Console.println(s\"Gracefully closing connection, #$connectionId\")\n        clientSocket.close()\n    }\n\n    println(s\"Handling connection, $connectionId\")\n  }\n\n  while (true) new Thread(new ClientHandler(serverSocket.accept())).start()\n}\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":2420}
    {"lang_cluster":"Scala","source_code":"\nimport scala.util.control.Exception.allCatch\n\ndef isNumber(s: String): Boolean = (allCatch opt s.toDouble).isDefined\ndef isNumeric(input: String): Boolean = input.forall(_.isDigit)\n\ndef isNumeric2(str: String): Boolean = {\n  str.matches(s\"\"\"[+-]?((\\d+(e\\d+)?[lL]?)|(((\\d+(\\.\\d*)?)|(\\.\\d+))(e\\d+)?[fF]?))\"\"\")\n}\n\ndef isNumeric(str: String): Boolean = {\n  !throwsNumberFormatException(str.toLong) || !throwsNumberFormatException(str.toDouble)\n}\n  \ndef throwsNumberFormatException(f: => Any): Boolean = {\n  try { f; false } catch { case e: NumberFormatException => true }\n}\n","human_summarization":"\"Implement a boolean function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers. The function uses either a complex regular expression or built-in number parsing with exception handling.\"","id":2421}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nimport scala.io.Source\n\nobject HttpsTest extends App {\n  System.setProperty(\"http.agent\", \"*\")\n   \n  Source.fromURL(\"https:\/\/sourceforge.net\").getLines.foreach(println)\n}\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":2422}
    {"lang_cluster":"Scala","source_code":"\n\nimport javax.swing.{ JFrame, JPanel }\n\nobject SutherlandHodgman extends JFrame with App {\n    import java.awt.BorderLayout\n\n    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\n    setVisible(true)\n    val content = getContentPane()\n    content.setLayout(new BorderLayout())\n    content.add(SutherlandHodgmanPanel, BorderLayout.CENTER)\n    setTitle(\"SutherlandHodgman\")\n    pack()\n    setLocationRelativeTo(null)\n}\n\nobject SutherlandHodgmanPanel extends JPanel {\n    import java.awt.{ Color, Graphics, Graphics2D }\n\n    setPreferredSize(new java.awt.Dimension(600, 500))\n\n    \/\/ subject and clip points are assumed to be valid\n    val subject = Seq((50D, 150D), (200D, 50D), (350D, 150D), (350D, 300D), (250D, 300D), (200D, 250D), (150D, 350D), (100D, 250D), (100D, 200D))\n    val clipper = Seq((100D, 100D), (300D, 100D), (300D, 300D), (100D, 300D))\n    var result = subject\n\n    val len = clipper.size\n    for (i <- 0 until len) {\n        val len2 = result.size\n        val input = result\n        result = Seq()\n\n        val A = clipper((i + len - 1) % len)\n        val B = clipper(i)\n\n        for (j <- 0 until len2) {\n            val P = input((j + len2 - 1) % len2)\n            val Q = input(j)\n\n            if (inside(A, B, Q)) {\n                if (!inside(A, B, P))\n                    result = result :+ intersection(A, B, P, Q)\n                result = result :+ Q\n            }\n            else if (inside(A, B, P))\n                result = result :+ intersection(A, B, P, Q)\n        }\n    }\n\n    override def paintComponent(g: Graphics) {\n        import java.awt.RenderingHints._\n\n        super.paintComponent(g)\n        val g2 = g.asInstanceOf[Graphics2D]\n        g2.translate(80, 60)\n        g2.setStroke(new java.awt.BasicStroke(3))\n        g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON)\n        g2.draw_polygon(subject, Color.blue)\n        g2.draw_polygon(clipper, Color.red)\n        g2.draw_polygon(result, Color.green)\n    }\n\n    private def inside(a: (Double, Double), b: (Double, Double), c: (Double, Double)) =\n        (a._1 - c._1) * (b._2 - c._2) > (a._2 - c._2) * (b._1 - c._1)\n\n    private def intersection(a: (Double, Double), b: (Double, Double), p: (Double, Double), q: (Double, Double)) = {\n        val A1 = b._2 - a._2\n        val B1 = a._1 - b._1\n        val C1 = A1 * a._1 + B1 * a._2\n        val A2 = q._2 - p._2\n        val B2 = p._1 - q._1\n        val C2 = A2 * p._1 + B2 * p._2\n\n        val det = A1 * B2 - A2 * B1\n        ((B2 * C1 - B1 * C2) \/ det, (A1 * C2 - A2 * C1) \/ det)\n    }\n\n    private implicit final class Polygon_drawing(g: Graphics2D) {\n        def draw_polygon(points: Seq[(Double, Double)], color: Color) {\n            g.setColor(color)\n            val len = points.length\n            val line = new java.awt.geom.Line2D.Double()\n            for (i <- 0 until len) {\n                val p1 = points(i)\n                val p2 = points((i + 1) % len)\n                line.setLine(p1._1, p1._2, p2._1, p2._2)\n                g.draw(line)\n            }\n        }\n    }\n}\n\n","human_summarization":"Implement the Sutherland-Hodgman clipping algorithm to find the intersection of a given polygon and a rectangle. The polygon and rectangle are defined by a sequence of points. The code also includes an extra feature to visually display all three polygons (the original polygon, the rectangle, and the resulting clipped polygon) on a graphical surface, each in a different color.","id":2423}
    {"lang_cluster":"Scala","source_code":"\n\nobject RankingMethods extends App {\n    case class Score(score: Int, name: String) \/\/ incoming data\n    case class Rank[Precision](rank: Precision, names: List[String]) \/\/ outgoing results (can be int or double)\n    case class State[Precision](n: Int, done: List[Rank[Precision]]) { \/\/ internal state, no mutable variables\n        def next(n: Int, next: Rank[Precision]) = State(n, next :: done)\n    }\n    def grouped[Precision](list: List[Score]) = \/\/ group names together by score, with highest first\n        (scala.collection.immutable.TreeMap[Int, List[Score]]() ++ list.groupBy(-_.score))\n        .values.map(_.map(_.name)).foldLeft(State[Precision](1, Nil)) _\n\n    \/\/ Ranking methods:\n\n    def rankStandard(list: List[Score]) =\n        grouped[Int](list){case (state, names) => state.next(state.n+names.length, Rank(state.n, names))}.done.reverse\n\n    def rankModified(list: List[Score]) =\n        rankStandard(list).map(r => Rank(r.rank+r.names.length-1, r.names))\n\n    def rankDense(list: List[Score]) =\n        grouped[Int](list){case (state, names) => state.next(state.n+1, Rank(state.n, names))}.done.reverse\n\n    def rankOrdinal(list: List[Score]) =\n        list.zipWithIndex.map{case (score, n) => Rank(n+1, List(score.name))}\n\n    def rankFractional(list: List[Score]) =\n        rankStandard(list).map(r => Rank((2*r.rank+r.names.length-1.0)\/2, r.names))\n\n    \/\/ Tests:\n\n    def parseScores(s: String) = s split \"\\\\s+\" match {case Array(s,n) => Score(s.toInt, n)}\n    val test = List(\"44 Solomon\", \"42 Jason\", \"42 Errol\", \"41 Garry\", \"41 Bernard\", \"41 Barry\", \"39 Stephen\").map(parseScores)\n\n    println(\"Standard:\")\n    println(rankStandard(test) mkString \"\\n\")\n    println(\"\\nModified:\")\n    println(rankModified(test) mkString \"\\n\")\n    println(\"\\nDense:\")\n    println(rankDense(test) mkString \"\\n\")\n    println(\"\\nOrdinal:\")\n    println(rankOrdinal(test) mkString \"\\n\")\n    println(\"\\nFractional:\")\n    println(rankFractional(test) mkString \"\\n\")\n\n}\n\n\n","human_summarization":"The code implements various ranking methods for a competition, including Standard, Modified, Dense, Ordinal, and Fractional. It assigns numerical ranks to competitors based on their scores, handling ties differently for each method. The ranking is applied to an ordered list of scores with scorers. The code uses a type-safe singly-linked object model with no mutable state variables, demonstrating an object-oriented functional programming approach.","id":2424}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scalaimport scala.math._\n\nobject Gonio extends App {\n  \/\/Pi \/ 4 rad is 45 degrees. All answers should be the same.\n  val radians = Pi \/ 4\n  val degrees = 45.0\n\n  println(s\"${sin(radians)} ${sin(toRadians(degrees))}\")\n  \/\/cosine\n  println(s\"${cos(radians)} ${cos(toRadians(degrees))}\")\n  \/\/tangent\n  println(s\"${tan(radians)} ${tan(toRadians(degrees))}\")\n  \/\/arcsine\n  val bgsin = asin(sin(radians))\n  println(s\"$bgsin ${toDegrees(bgsin)}\")\n  val bgcos = acos(cos(radians))\n  println(s\"$bgcos ${toDegrees(bgcos)}\")\n  \/\/arctangent\n  val bgtan = atan(tan(radians))\n  println(s\"$bgtan ${toDegrees(bgtan)}\")\n  val bgtan2 = atan2(1, 1)\n  println(s\"$bgtan ${toDegrees(bgtan)}\")\n}\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":2425}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nimport sun.misc.Signal\nimport sun.misc.SignalHandler\n\nobject SignalHandl extends App {\n  val start = System.nanoTime()\n  var counter = 0\n\n  Signal.handle(new Signal(\"INT\"), new SignalHandler() {\n    def handle(sig: Signal) {\n      println(f\"\\nProgram execution took ${(System.nanoTime() - start) \/ 1e9f}%f seconds\\n\")\n      exit(0)\n    }\n  })\n\n  while (true) {\n    counter += 1\n    println(counter)\n    Thread.sleep(500)\n  }\n}\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.","id":2426}
    {"lang_cluster":"Scala","source_code":"\n\nimplicit def toSucc(s: String) = new { def succ = BigDecimal(s) + 1 toString }\n\nscala> \"123\".succ\nres5: String = 124\n\n","human_summarization":"Code summarization: The following codes define a method to increment a numerical string by converting it to a BigDecimal numeric type.","id":2427}
    {"lang_cluster":"Scala","source_code":"\n\nobject FindCommonDirectoryPath extends App {\n  def commonPath(paths: List[String]): String = {\n    def common(a: List[String], b: List[String]): List[String] = (a, b) match {\n      case (a :: as, b :: bs) if a equals b => a :: common(as, bs)\n      case _ => Nil\n    }\n    if (paths.length < 2) paths.headOption.getOrElse(\"\")\n    else paths.map(_.split(\"\/\").toList).reduceLeft(common).mkString(\"\/\")\n  }\n\n  val test = List(\n    \"\/home\/user1\/tmp\/coverage\/test\",\n    \"\/home\/user1\/tmp\/covert\/operator\",\n    \"\/home\/user1\/tmp\/coven\/members\"\n  )\n  println(commonPath(test))\n}\n\n\n\/home\/user1\/tmp\n\nobject FindCommonDirectoryPathRelative extends App {\n  def commonPath(paths: List[String]): String = {\n    val SEP = \"\/\"\n    val BOUNDARY_REGEX = s\"(?=[$SEP])(?<=[^$SEP])|(?=[^$SEP])(?<=[$SEP])\"\n    def common(a: List[String], b: List[String]): List[String] = (a, b) match {\n      case (a :: as, b :: bs) if a equals b => a :: common(as, bs)\n      case _ => Nil\n    }\n    if (paths.length < 2) paths.headOption.getOrElse(\"\")\n    else paths.map(_.split(BOUNDARY_REGEX).toList).reduceLeft(common).mkString\n  }\n\n  val test = List(\n    \"\/home\/user1\/tmp\/coverage\/test\",\n    \"\/home\/user1\/tmp\/covert\/operator\",\n    \"\/home\/user1\/tmp\/coven\/members\"\n  )\n  println(commonPath(test).replaceAll(\"\/$\", \"\"))\n\n  \/\/ test cases\n  assert(commonPath(test.take(1)) == test.head)\n  assert(commonPath(Nil) == \"\")\n  assert(commonPath(List(\"\")) == \"\")\n  assert(commonPath(List(\"\/\")) == \"\/\")\n  assert(commonPath(List(\"\/\", \"\")) == \"\")\n  assert(commonPath(List(\"\/\", \"\/a\")) == \"\/\")\n  assert(commonPath(List(\"\/a\", \"\/b\")) == \"\/\")\n  assert(commonPath(List(\"\/a\", \"\/a\")) == \"\/a\")\n  assert(commonPath(List(\"\/a\/a\", \"\/b\")) == \"\/\")\n  assert(commonPath(List(\"\/a\/a\", \"\/b\")) == \"\/\")\n  assert(commonPath(List(\"\/a\/a\", \"\/a\")) == \"\/a\")\n  assert(commonPath(List(\"\/a\/a\", \"\/a\/b\")) == \"\/a\/\")\n  assert(commonPath(List(\"\/a\/b\", \"\/a\/b\")) == \"\/a\/b\")\n  assert(commonPath(List(\"a\", \"\/a\")) == \"\")\n  assert(commonPath(List(\"a\/a\", \"\/a\")) == \"\")\n  assert(commonPath(List(\"a\/a\", \"\/b\")) == \"\")\n  assert(commonPath(List(\"a\", \"a\")) == \"a\")\n  assert(commonPath(List(\"a\/a\", \"b\")) == \"\")\n  assert(commonPath(List(\"a\/a\", \"b\")) == \"\")\n  assert(commonPath(List(\"a\/a\", \"a\")) == \"a\")\n  assert(commonPath(List(\"a\/a\", \"a\/b\")) == \"a\/\")\n  assert(commonPath(List(\"a\/b\", \"a\/b\")) == \"a\/b\")\n  assert(commonPath(List(\"\/a\/\", \"\/b\/\")) == \"\/\")\n  assert(commonPath(List(\"\/a\/\", \"\/a\/\")) == \"\/a\/\")\n  assert(commonPath(List(\"\/a\/a\/\", \"\/b\/\")) == \"\/\")\n  assert(commonPath(List(\"\/a\/a\/\", \"\/b\/\")) == \"\/\")\n  assert(commonPath(List(\"\/a\/a\/\", \"\/a\/\")) == \"\/a\/\")\n  assert(commonPath(List(\"\/a\/a\/\", \"\/a\/b\/\")) == \"\/a\/\")\n  assert(commonPath(List(\"\/a\/b\/\", \"\/a\/b\/\")) == \"\/a\/b\/\")\n}\n\n","human_summarization":"The code creates a function that takes a set of directory paths and a directory separator as inputs. It then returns the common directory path among all provided directories. The function is tested using '\/' as the directory separator and three specific strings as input paths. The function is designed to handle various edge cases and relative paths, and includes any common trailing '\/'. If the language used already has a function that performs this task, it is mentioned as part of the task.","id":2428}
    {"lang_cluster":"Scala","source_code":"\ndef shuffle[T](a: Array[T]): Array[T] = {\n  scala.util.Random.shuffle(a)\n  a\n}\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":2429}
    {"lang_cluster":"Scala","source_code":"\nWorks with: Scala version 2.8 (See the Scala discussion on Mean for more information.)\ndef median[T](s: Seq[T])(implicit n: Fractional[T]) = {\n  import n._\n  val (lower, upper) = s.sortWith(_<_).splitAt(s.size \/ 2)\n  if (s.size\u00a0% 2 == 0) (lower.last + upper.head) \/ fromInt(2) else upper.head\n}\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even numbers of elements by returning the average of the two middle values. It uses the selection algorithm for optimal performance. Additionally, the code calculates various statistical measures like arithmetic, geometric, harmonic, quadratic, and circular averages, as well as mode and standard deviation. However, the methods splitAt and last may not be optimal due to their time complexity.","id":2430}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nobject FizzBuzz extends App {\n  1 to 100 foreach { n =>\n    println((n\u00a0% 3, n\u00a0% 5) match {\n      case (0, 0) => \"FizzBuzz\"\n      case (0, _) => \"Fizz\"\n      case (_, 0) => \"Buzz\"\n      case _ => n\n    })\n  }\n}\ndef replaceMultiples(x: Int, rs: (Int, String)*): Either[Int, String] =\n  rs map { case (n, s) => Either cond(x\u00a0% n == 0, s, x)} reduceLeft ((a, b) => \n    a fold(_ => b, s => b fold(_ => a, t => Right(s + t))))\n\ndef fizzbuzz = replaceMultiples(_: Int, 3 -> \"Fizz\", 5 -> \"Buzz\") fold(_.toString, identity)\n\n1 to 100 map fizzbuzz foreach println\ndef f(n: Int, div: Int, met: String, notMet: String): String = if (n\u00a0% div == 0) met else notMet\nfor (i <- 1 to 100) println(f(i, 15, \"FizzBuzz\", f(i, 3, \"Fizz\", f(i, 5, \"Buzz\", i.toString))))\nfor (i <- 1 to 100) println(Seq(15 -> \"FizzBuzz\", 3 -> \"Fizz\", 5 -> \"Buzz\").find(i\u00a0% _._1 == 0).map(_._2).getOrElse(i))\ndef fizzBuzzTerm(n: Int): String =\n  if (n\u00a0% 15 == 0) \"FizzBuzz\"\n  else if (n\u00a0% 3 == 0) \"Fizz\"\n  else if (n\u00a0% 5 == 0) \"Buzz\"\n  else n.toString\n\ndef fizzBuzz(): Unit = LazyList.from(1).take(100).map(fizzBuzzTerm).foreach(println)\n\ndef fizzBuzzTerm(n: Int): String | Int = \/\/ union types\n  (n\u00a0% 3, n\u00a0% 5) match \/\/ optional semantic indentation; no braces\n    case (0, 0) => \"FizzBuzz\"\n    case (0, _) => \"Fizz\"\n    case (_, 0) => \"Buzz\"\n    case _      => n \/\/ no need for `.toString`, thanks to union type\n  end match \/\/ optional `end` keyword, with what it's ending\nend fizzBuzzTerm \/\/ `end` also usable for identifiers\n\nval fizzBuzz = \/\/ no namespace object is required; all top level\n  LazyList.from(1).map(fizzBuzzTerm)\n\n@main def run(): Unit = \/\/ @main for main method; can take custom args\n  fizzBuzz.take(100).foreach(println)\n","human_summarization":"The code prints integers from 1 to 100. It replaces multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":2431}
    {"lang_cluster":"Scala","source_code":"\nWorks with: Scala version 2.8\n\nimport org.rosettacode.ArithmeticComplex._\nimport java.awt.Color\n\nobject Mandelbrot\n{\n   def generate(width:Int =600, height:Int =400)={\n      val bm=new RgbBitmap(width, height)\n\n      val maxIter=1000\n      val xMin = -2.0\n      val xMax =  1.0\n      val yMin = -1.0\n      val yMax =  1.0\n\n      val cx=(xMax-xMin)\/width\n      val cy=(yMax-yMin)\/height\n\n      for(y <- 0 until bm.height; x <- 0 until bm.width){\n         val c=Complex(xMin+x*cx, yMin+y*cy)\n         val iter=itMandel(c, maxIter, 4)\n         bm.setPixel(x, y, getColor(iter, maxIter))\n      }\n      bm\n   }\n\n   def itMandel(c:Complex, imax:Int, bailout:Int):Int={\n      var z=Complex()\n      for(i <- 0 until imax){\n         z=z*z+c;\n         if(z.abs > bailout) return i\n      }\n      imax;\n   }\n\n   def getColor(iter:Int, max:Int):Color={\n      if (iter==max) return Color.BLACK\n\n      var c=3*math.log(iter)\/math.log(max-1.0)\n      if(c<1) new Color((255*c).toInt, 0, 0)\n      else if(c<2) new Color(255, (255*(c-1)).toInt, 0)\n      else new Color(255, 255, (255*(c-2)).toInt)\n   }\n}\n\nimport scala.swing._\nimport javax.swing.ImageIcon\nval imgMandel=Mandelbrot.generate()\nval mainframe=new MainFrame(){title=\"Test\"; visible=true\n   contents=new Label(){icon=new ImageIcon(imgMandel.image)}\n}\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. It utilizes the RgbBitmap from the Basic Bitmap Storage task and the Complex number class from the given programming task. The code also includes a read-eval-print loop.","id":2432}
    {"lang_cluster":"Scala","source_code":"\nval seq = Seq(1, 2, 3, 4, 5)\nval sum = seq.foldLeft(0)(_ + _)\nval product = seq.foldLeft(1)(_ * _)\n\nval sum = seq.sum\nval product = seq.product\n\n","human_summarization":"Computes the sum and product of an array of integers, compatible with all numeric data types.","id":2433}
    {"lang_cluster":"Scala","source_code":"\n\n\/\/use Java's calendar class\nnew java.util.GregorianCalendar().isLeapYear(year)\n\njava.time.LocalDate.ofYearDay(year, 1).isLeapYear()\n\ndef isLeapYear(year:Int)=if (year%100==0) year%400==0 else year%4==0;\n\n\/\/or use Java's calendar class\ndef isLeapYear(year:Int):Boolean = {\n  val c = new java.util.GregorianCalendar\n  c.setGregorianChange(new java.util.Date(Long.MinValue))\n  c.isLeapYear(year)\n}\n","human_summarization":"determine if a given year is a leap year in the Gregorian calendar, considering the switch from Julian to Gregorian calendar on October 15, 1582, using java.util.GregorianCalendar and JSR-310 java.time for proleptic Gregorian calendar.","id":2434}
    {"lang_cluster":"Scala","source_code":"\n\n\nThis example is incorrect. It does not accomplish the given task. Please fix the code and remove this message.\n\nobject MD5 extends App {\n\n  def hash(s: String) = {\n    def b = s.getBytes(\"UTF-8\")\n\n    def m = java.security.MessageDigest.getInstance(\"MD5\").digest(b)\n\n    BigInt(1, m).toString(16).reverse.padTo(32, \"0\").reverse.mkString\n  }\n\n  assert(\"d41d8cd98f00b204e9800998ecf8427e\" == hash(\"\"))\n  assert(\"0000045c5e2b3911eb937d9d8c574f09\" == hash(\"iwrupvqb346386\"))\n  assert(\"0cc175b9c0f1b6a831c399e269772661\" == hash(\"a\"))\n  assert(\"900150983cd24fb0d6963f7d28e17f72\" == hash(\"abc\"))\n  assert(\"f96b697d7cb7938d525a2f31aaf161d0\" == hash(\"message digest\"))\n  assert(\"c3fcd3d76192e4007dfb496cca67e13b\" == hash(\"abcdefghijklmnopqrstuvwxyz\"))\n  assert(\"d174ab98d277d9f5a5611c2c9f419d9f\" == hash(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"))\n  assert(\"57edf4a22be3c955ac49da2e2107b67a\" == hash(\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"))\n\n}\n\n","human_summarization":"The code is an implementation of the MD5 Message Digest Algorithm, developed directly from the algorithm specification without using built-in or external hashing libraries. It produces a correct message digest for an input string but does not mimic all calling modes. The code also includes handling of bit manipulation, unsigned integers, and little-endian data, with attention to details like boundary conditions and padding. The implementation is validated against the verification strings and hashes from RFC 1321.","id":2435}
    {"lang_cluster":"Scala","source_code":"\nval depts = {\n  (1 to 7).permutations.map{ n => (n(0),n(1),n(2)) }.toList.distinct  \/\/ All permutations of possible department numbers\n  .filter{ n => n._1 % 2 == 0 }                                       \/\/ Keep only even numbers favored by Police Chief\n  .filter{ n => n._1 + n._2 + n._3 == 12 }                            \/\/ Keep only numbers that add to 12\n}\n\n{\nprintln( \"(Police, Sanitation, Fire)\")\nprintln( depts.mkString(\"\\n\") )\n}\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":2436}
    {"lang_cluster":"Scala","source_code":"\n  val src = \"Hello\"\n  \/\/ Its actually not a copy but a reference\n  \/\/ That is not a problem because String is immutable\n  \/\/ In fact its a feature\n  val des = src\n  assert(src eq des) \/\/ Proves the same reference is used. \n  \/\/ To make a real copy makes no sense.\n  \/\/ Actually its hard to make a copy, the compiler is too smart.\n  \/\/ mkString, toString makes also not a real copy\n  val cop = src.mkString.toString\n  assert((src eq cop))                 \/\/ Still no copyed image\n  val copy = src.reverse.reverse       \/\/ Finally double reverse makes a copy\n  assert(src == copy &&\u00a0!(src eq copy))\/\/ Prove, but it really makes no sense.\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":2437}
    {"lang_cluster":"Scala","source_code":"\ndef F(n:Int):Int =\n  if (n == 0) 1 else n - M(F(n-1))\ndef M(n:Int):Int =\n  if (n == 0) 0 else n - F(M(n-1))\n\nprintln((0 until 20).map(F).mkString(\", \"))\nprintln((0 until 20).map(M).mkString(\", \"))\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":2438}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nval a = (1 to 10).toList\n\nprintln(scala.util.Random.shuffle(a).head)\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":2439}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scalaimport java.net.{URLDecoder, URLEncoder}\nimport scala.compat.Platform.currentTime\n\nobject UrlCoded extends App {\n  val original = \"\"\"http:\/\/foo bar\/\"\"\"\n  val encoded: String = URLEncoder.encode(original, \"UTF-8\")\n\n  assert(encoded == \"http%3A%2F%2Ffoo+bar%2F\", s\"Original: $original not properly encoded: $encoded\")\n\n  val percentEncoding = encoded.replace(\"+\", \"%20\")\n  assert(percentEncoding == \"http%3A%2F%2Ffoo%20bar%2F\", s\"Original: $original not properly percent-encoded: $percentEncoding\")\n\n  assert(URLDecoder.decode(encoded, \"UTF-8\") == URLDecoder.decode(percentEncoding, \"UTF-8\"))\n\n  println(s\"Successfully completed without errors. [total ${currentTime - executionStart} ms]\")\n}\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":2440}
    {"lang_cluster":"Scala","source_code":"\n\ndef binarySearch[A <% Ordered[A]](a: IndexedSeq[A], v: A) = {\n  def recurse(low: Int, high: Int): Option[Int] = (low + high) \/ 2 match {\n    case _ if high < low => None\n    case mid if a(mid) > v => recurse(low, mid - 1)\n    case mid if a(mid) < v => recurse(mid + 1, high)\n    case mid => Some(mid)\n  }\n  recurse(0, a.size - 1)\n}\n\ndef binarySearch[T](xs: Seq[T], x: T)(implicit ordering: Ordering[T]): Option[Int] = {\n    var low: Int = 0\n    var high: Int = xs.size - 1\n\n    while (low <= high)\n      low + high >>> 1 match {\n        case guess if ordering.gt(xs(guess), x) => high = guess - 1 \/\/too high\n        case guess if ordering.lt(xs(guess), x) => low = guess + 1 \/\/ too low\n        case guess => return Some(guess) \/\/found it\n      }\n    None \/\/not found\n  }\n\ndef testBinarySearch(n: Int) = {\n  val odds = 1 to n by 2\n  val result = (0 to n).flatMap(binarySearch(odds, _))\n  assert(result == (0 until odds.size))\n  println(s\"$odds are odd natural numbers\")\n  for (it <- result)\n    println(s\"$it is ordinal of ${odds(it)}\")\n}\n\ndef main() = testBinarySearch(12)\n\nRange(1, 3, 5, 7, 9, 11) are odd natural numbers\n0 is ordinal of 1\n1 is ordinal of 3\n2 is ordinal of 5\n3 is ordinal of 7\n4 is ordinal of 9\n5 is ordinal of 11\n","human_summarization":"The code implements a binary search algorithm to find a specific number in a sorted integer array. It divides the range of values into halves until the target number is found. The code includes both recursive and iterative versions of the binary search. It also handles scenarios where multiple values in the array are equal to the target value. The code provides the index of the target number if it is found, or the index where it would be inserted while maintaining the sorted order of the array if it is not found. The code also ensures there are no overflow bugs during the calculation of the midpoint.","id":2441}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\n\nobject CommandLineArguments extends App { \n    println(s\"Received the following arguments: + ${args.mkString(\"\", \", \", \".\")}\")\n}\n\nprintln(s\"Received the following arguments: + ${argv.mkString(\"\", \", \", \".\")}\")\n","human_summarization":"The code retrieves the list of command-line arguments provided to the program. It specifically prints these arguments when the program is run directly. It uses a main method defined on an object, which receives an array of strings (command line arguments) and returns unit. In the case of a Scala script, the arguments are stored in an array of strings called argv. The example command line used is: myprogram -c \"alpha beta\" -h \"gamma\".","id":2442}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nimport java.awt.Color\nimport java.util.concurrent.{Executors, TimeUnit}\n\nimport scala.swing.{Graphics2D, MainFrame, Panel, SimpleSwingApplication}\nimport scala.swing.Swing.pair2Dimension\n\nobject Pendulum extends SimpleSwingApplication {\n  val length = 100\n\n  lazy val ui = new Panel {\n    import scala.math.{cos, Pi, sin}\n\n    background = Color.white\n    preferredSize = (2 * length + 50, length \/ 2 * 3)\n    peer.setDoubleBuffered(true)\n\n    var angle: Double = Pi \/ 2\n\n    override def paintComponent(g: Graphics2D): Unit = {\n      super.paintComponent(g)\n\n      val (anchorX, anchorY) = (size.width \/ 2, size.height \/ 4)\n      val (ballX, ballY) =\n        (anchorX + (sin(angle) * length).toInt, anchorY + (cos(angle) * length).toInt)\n      g.setColor(Color.lightGray)\n      g.drawLine(anchorX - 2 * length, anchorY, anchorX + 2 * length, anchorY)\n      g.setColor(Color.black)\n      g.drawLine(anchorX, anchorY, ballX, ballY)\n      g.fillOval(anchorX - 3, anchorY - 4, 7, 7)\n      g.drawOval(ballX - 7, ballY - 7, 14, 14)\n      g.setColor(Color.yellow)\n      g.fillOval(ballX - 7, ballY - 7, 14, 14)\n    }\n\n    val animate: Runnable = new Runnable {\n      var angleVelocity = 0.0\n      var dt = 0.1\n\n      override def run(): Unit = {\n        angleVelocity += -9.81 \/ length * Math.sin(angle) * dt\n        angle += angleVelocity * dt\n        repaint()\n      }\n    }\n  }\n\n  override def top = new MainFrame {\n    title = \"Rosetta Code >>> Task: Animate a pendulum | Language: Scala\"\n    contents = ui\n    centerOnScreen()\n    Executors.\n      newSingleThreadScheduledExecutor().\n      scheduleAtFixedRate(ui.animate, 0, 15, TimeUnit.MILLISECONDS)\n  }\n}\n\n","human_summarization":"create and animate a simple physical model of a gravity pendulum.","id":2443}
    {"lang_cluster":"Scala","source_code":"\n\nscala> import scala.util.parsing.json.{JSON, JSONObject}\nimport scala.util.parsing.json.{JSON, JSONObject}\n\nscala> JSON.parseFull(\"\"\"{\"foo\": \"bar\"}\"\"\")\nres0: Option[Any] = Some(Map(foo -> bar))\n\nscala> JSONObject(Map(\"foo\" -> \"bar\")).toString()\nres1: String = {\"foo\" : \"bar\"}\n\n","human_summarization":"\"Code loads a JSON string into a data structure, creates a new data structure and serializes it into JSON using built-in parsing library. It ensures the JSON is valid and uses objects and arrays as per the language's suitability.\"","id":2444}
    {"lang_cluster":"Scala","source_code":"\n\ndef nroot(n: Int, a: Double): Double = {\n  @tailrec\n  def rec(x0: Double) : Double = {\n    val x1 = ((n - 1) * x0 + a\/math.pow(x0, n-1))\/n\n    if (x0 <= x1) x0 else rec(x1)\n  }\n  \n  rec(a)\n}\n\n\ndef fallPrefix(itr: Iterator[Double]): Iterator[Double] = itr.sliding(2).dropWhile(p => p(0) > p(1)).map(_.head)\ndef nrootLazy(n: Int)(a: Double): Double = fallPrefix(Iterator.iterate(a){r => (((n - 1)*r) + (a\/math.pow(r, n - 1)))\/n}).next\n\n","human_summarization":"implement the principal nth root computation algorithm for a positive real number A, using tail recursion or an iterator.","id":2445}
    {"lang_cluster":"Scala","source_code":"\nprintln(java.net.InetAddress.getLocalHost.getHostName)\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":2446}
    {"lang_cluster":"Scala","source_code":"\ndef leo( n:Int, n1:Int=1, n2:Int=1, addnum:Int=1 ) : BigInt = n match {\n  case 0 => n1\n  case 1 => n2\n  case n => leo(n - 1, n1, n2, addnum) + leo(n - 2, n1, n2, addnum) + addnum\n}\n\n{\nprintln( \"The first 25 Leonardo Numbers:\")\n(0 until 25) foreach { n => print( leo(n) + \" \" ) }\n\nprintln( \"\\n\\nThe first 25 Fibonacci Numbers:\")\n(0 until 25) foreach { n => print( leo(n, n1=0, n2=1, addnum=0) + \" \" ) }\n}\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":2447}
    {"lang_cluster":"Scala","source_code":"\n\nobject TwentyFourGame {\n  def main(args: Array[String]) {\n    import Parser.TwentyFourParser\n    \n    println(welcome)\n    \n    var parser = new TwentyFourParser(problemsIterator.next)\n    println(\"Your four digits: \"+parser+\".\")\n    \n    var finished = false\n    var expressionCount = 1\n    do {\n      val line = Console.readLine(\"Expression \"+expressionCount+\": \")\n      line match {\n        case \"!\" =>\n          parser = new TwentyFourParser(problemsIterator.next)\n          println(\"New digits: \"+parser+\".\")\n          \n        case \"q\" =>\n          finished = true\n        \n        case _ =>\n          parser readExpression line match {\n            case Some(24) => println(\"That's right!\"); finished = true\n            case Some(n) => println(\"Sorry, that's \"+n+\".\")\n            case None =>\n          }\n      }\n      expressionCount += 1\n    } while (!finished)\n    \n    println(\"Thank you and goodbye!\")\n  }\n  \n  val welcome = \"\"\"|The 24 Game\n                   |\n                   |Given any four digits in the range 1 to 9, which may have repetitions,\n                   |Using just the +, -, *, and \/ operators; and the possible use of\n                   |brackets, (), show how to make an answer of 24.\n                   |\n                   |An answer of \"q\" will quit the game.\n                   |An answer of \"!\" will generate a new set of four digits.\n                   |Otherwise you are repeatedly asked for an expression until it evaluates to 24\n                   |\n                   |Note: you cannot form multiple digit numbers from the supplied digits,\n                   |so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n                   |\"\"\".stripMargin\n  \n  val problemsIterator = (\n    Iterator \n    continually List.fill(4)(scala.util.Random.nextInt(9) + 1 toDouble) \n    filter hasSolution\n  )\n  \n  def hasSolution(l: List[Double]) = permute(l) flatMap computeAllOperations exists (_ == 24)\n  \n  def computeAllOperations(l: List[Double]): List[Double] = l match {\n    case Nil => Nil\n    case x :: Nil => l\n    case x :: xs =>\n      for {\n        y <- computeAllOperations(xs)\n        z <- if (y == 0) List(x*y, x+y, x-y) else List(x*y, x\/y, x+y, x-y)\n      } yield z\n  }\n  \n  def permute(l: List[Double]): List[List[Double]] = l match {\n    case Nil => List(Nil)\n    case x :: xs =>\n      for {\n        ys <- permute(xs)\n        position <- 0 to ys.length\n        (left, right) = ys splitAt position\n      } yield left ::: (x :: right)\n  }\n  \n  object Parser {\n    \/*  Arithmetic expression grammar production rules in EBNF form:\n     *\n     * <expr> --> <term> ( '+' <term> | '-' <term> )*\n     * <term> --> <factor> ( '*'  <factor> | '\/'  <factor> )*\n     * <factor> --> '(' <expr> ')' | <digit>\n     * <digit> --> 0 | 1  | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9\n     * \n     * Semantically, <digit> can only be a digit from the list of remaining digits.\n     *\/\n    \n    class TwentyFourParser(digits: List[Double]) extends scala.util.parsing.combinator.RegexParsers {\n      require(digits.length == 4 && digits.forall(d => 0 <= d && d <= 9))\n      override val toString = digits.map(_.toInt).mkString(\", \")\n      \n      \/\/ Grammar\n      def exprConsumingAllDigits = expr ^? (remainingDigits.allDigitsConsumed, digitsRemainingError) \/\/ Guarantees all digits consumed\n      def expr : Parser[Double] = term ~ rep( \"+\" ~ term | \"-\" ~ term) ^^ solveOperationChain\n      def term = factor ~ rep( \"*\" ~ factor | \"\/\" ~ factor) ^^ solveOperationChain\n      def factor = \"(\" ~> expr <~ \")\" | digit\n      def digit = digitRegex ^? (remainingDigits.consumeDigit, digitNotAllowedError) \n      def digitRegex = \"\\\\d\".r | digitExpected\n      def digitExpected: Parser[String] = \".\".r <~ failure(expectedDigitError) \/\/ Produces clear error messages\n    \n      \/\/ Evaluate expressions\n      def readExpression(input: String): Option[Double] = {\n        remainingDigits = new DigitList(digits) \/\/ Initialize list of digits to be consumed\n        parseAll(exprConsumingAllDigits, input) match {\n          case Success(result, _) => Some(result)\n          case NoSuccess(msg, next) =>\n            println(ParsingErrorFormatter(msg, next))\n            None\n        }\n      }\n      \n      \/\/ List of digits to be consumed\n      private var remainingDigits: DigitList = _\n      \n      \/\/ Solve partial results from parsing\n      private def solveOperationChain(partialResult: ~[Double,List[~[String,Double]]]): Double = partialResult match {\n        case first ~ chain => chain.foldLeft(first)(doOperation)\n      }\n      private def doOperation(acc: Double, op: ~[String, Double]): Double = op match {\n        case \"+\" ~ operand => acc + operand\n        case \"-\" ~ operand => acc - operand\n        case \"*\" ~ operand => acc * operand\n        case \"\/\" ~ operand => acc \/ operand\n        case x => error(\"Unknown operation \"+x+\".\") \n      }\n      \n      \/\/ Error messages\n      private def digitNotAllowedError(d: String) = \"Digit \"+d+\" is not allowed here. Available digits: \"+remainingDigits+\".\"\n      private def digitsRemainingError(x: Any) = \"Not all digits were consumed. Digits remaining: \"+remainingDigits+\".\"\n      private def expectedDigitError = \"Unexpected input. Expected a digit from the list: \"+remainingDigits+\".\"\n    }\n    \n    private object ParsingErrorFormatter {\n      def apply[T](msg: String, next: scala.util.parsing.input.Reader[T]) =\n        \"%s\\n%s\\n%s\\n\" format (msg, next.source.toString.trim, \" \"*(next.offset - 1)+\"^\")\n    }\n    \n    private class DigitList(digits: List[Double]) {\n      private var remainingDigits = digits\n      override def toString = remainingDigits.map(_.toInt).mkString(\", \")\n      \n      def consumeDigit: PartialFunction[String, Double] = {\n        case d if remainingDigits contains d.toDouble =>\n          val n = d.toDouble\n          remainingDigits = remainingDigits diff List(n)\n          n\n      }\n      \n      def allDigitsConsumed: PartialFunction[Double, Double] = {\n        case n if remainingDigits.isEmpty => n\n      }\n    }\n  }\n}\n\n\n","human_summarization":"The code randomly selects and displays four digits from 1 to 9, allows the player to input an arithmetic expression using these digits exactly once each, and checks if the expression evaluates to 24. The code supports operations of addition, subtraction, multiplication, and division with floating point or rational arithmetic. The code also allows the use of brackets in the expression but does not permit forming multiple digit numbers from the given digits. The order of the digits does not need to be preserved in the expression. The code does not generate or test the expression. It uses Scala's Parser library to construct parsers from EBNF grammars and displays only the problems with the solution to the user.","id":2448}
    {"lang_cluster":"Scala","source_code":"\n\ndef encode(s: String) = (1 until s.size).foldLeft((1, s(0), new StringBuilder)) {\n  case ((len, c, sb), index) if c\u00a0!= s(index) => sb.append(len); sb.append(c); (1, s(index), sb)\n  case ((len, c, sb), _) => (len + 1, c, sb)\n} match {\n  case (len, c, sb) => sb.append(len); sb.append(c); sb.toString\n}\n\ndef decode(s: String) = {\n  val sb = new StringBuilder\n  val Code = \"\"\"(\\d+)([A-Z])\"\"\".r\n  for (Code(len, c) <- Code findAllIn s) sb.append(c * len.toInt)\n  sb.toString\n}\n\ndef encode(s:String) = {\n  s.foldLeft((0,s(0),\"\"))( (t,c) => t match {case (i,p,s) => if (p==c) (i+1,p,s) else (1,c,s+i+p)})\n    match {case (i,p,s) => s+i+p}\n}\n\ndef decode(s: String, Code: scala.util.matching.Regex = \"\"\"(\\d+)?([a-zA-Z])\"\"\".r) =\n  Code.findAllIn(s).foldLeft(\"\") { case (acc, Code(len, c)) =>\n    acc + c * Option(len).map(_.toInt).getOrElse(1)\n  }\n","human_summarization":"The code implements run-length encoding and decoding for a string of uppercase characters. It compresses repeated characters by storing the length of the run. It also provides a function to reverse the compression. The code uses StringBuilder for better performance. It can handle strings like \"2AB\", producing \"AAB\".","id":2449}
    {"lang_cluster":"Scala","source_code":"\n\n  val s = \"hello\"                                 \/\/> s \u00a0: String = hello\n  val s2 = s + \" world\"                           \/\/> s2 \u00a0: String = hello world\n  val f2 = () =>  \"\u00a0!\"                            \/\/> f2 \u00a0: () => String = <function0>\n\n  println(s2 + f2())                              \/\/> hello world\u00a0!\n","human_summarization":"The code creates two string variables, one with a text value and another that concatenates the first variable with a string literal. The content of these variables is then displayed. Additionally, an anonymous function is assigned to the variable 'f2' in a Scala worksheet.","id":2450}
    {"lang_cluster":"Scala","source_code":"\nimport scala.annotation.tailrec\n\nobject ContinousKnapsackForRobber extends App {\n  val MaxWeight = 15.0\n  val items = Seq(\n    Item(\"Beef\",    3.8, 3600),\n    Item(\"Pork\",    5.4, 4300),\n    Item(\"Ham\",     3.6, 9000),\n    Item(\"Greaves\", 2.4, 4500),\n    Item(\"Flitch\",  4.0, 3000),\n    Item(\"Brawn\",   2.5, 5600),\n    Item(\"Welt\",    3.7, 6700),\n    Item(\"Salami\",  3.0, 9500),\n    Item(\"Sausage\", 5.9, 9800))\n\n  \/\/ sort items by value per unit weight in descending order\n  def sortedItems = items.sortBy(it => -it.value \/ it.weight)\n\n  @tailrec\n  def packer(notPacked: Seq[Item], packed: Lootsack): Lootsack = {\n\n    if (!packed.isNotFull || notPacked.isEmpty) packed\n    else {\n      val try2fit = packed.copy(bagged = notPacked.head +: packed.bagged)\n      if (try2fit.isNotFull) packer(notPacked.tail, try2fit)\n      else {\n        try2fit.copy(lastPiece = packed.weightLeft \/ notPacked.head.weight)\n      }\n    }\n  }\n\n  case class Item(name: String, weight: Double, value: Int)\n\n  case class Lootsack(bagged: Seq[Item], lastPiece: Double = 1.0) {\n    private val totWeight = if (bagged.isEmpty) 0.0\n    else bagged.tail.map(_.weight).sum + bagged.head.weight * lastPiece\n\n    def isNotFull: Boolean = weightLeft > 0\n\n    def weightLeft: Double = MaxWeight - totWeight\n\n    override def toString = f\"${show(bagged, lastPiece)}Totals: weight: $totWeight%4.1f, value: $totValue%6.2f\"\n\n    private def totValue: BigDecimal = if (bagged.isEmpty) 0.0\n    else (bagged.tail.map(_.value).sum + bagged.head.value * lastPiece) \/ 100\n\n    private def show(is: Seq[Item], percentage: Double) = {\n      def toStr(is: Seq[Item], percentage: Double = 1): String =\n        is.map(it => f\"${percentage * 100}%6.2f%% ${it.name}%-7s ${\n          it.weight * percentage}%4.1f ${it.value * percentage \/ 100}%6.2f\\n\").mkString\n\n      toStr(is.tail.reverse) + toStr(Seq(is.head), percentage)\n    }\n  }\n\n  println(packer(sortedItems, Lootsack(Nil)))\n}\n\n\n","human_summarization":"determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.","id":2451}
    {"lang_cluster":"Scala","source_code":"\nval src = io.Source fromURL \"http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt\"\nval vls = src.getLines.toList.groupBy(_.sorted).values\nval max = vls.map(_.size).max\nvls filter (_.size == max) map (_ mkString \" \") mkString \"\\n\"\n\n","human_summarization":"\"Find the largest sets of anagrams from the word list provided at http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt.\"","id":2452}
    {"lang_cluster":"Scala","source_code":"def nextCarpet(carpet: List[String]): List[String] = (\n  carpet.map(x => x + x + x)\u00a0:::\n  carpet.map(x => x + x.replace('#', ' ') + x)\u00a0:::\n  carpet.map(x => x + x + x))\n\ndef sierpinskiCarpets(n: Int) = (Iterator.iterate(List(\"#\"))(nextCarpet) drop n next) foreach println\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":2453}
    {"lang_cluster":"Scala","source_code":"\nWorks with: scala version 2.8\nobject Huffman {\n  import scala.collection.mutable.{Map, PriorityQueue}\n  \n  sealed abstract class Tree\n  case class Node(left: Tree, right: Tree) extends Tree\n  case class Leaf(c: Char) extends Tree\n  \n  def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] { \n     def compare(x: Tree, y: Tree) = m(y).compare(m(x))\n  }\n\n  def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length)\n  \n  def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) {\n    val right = queue.dequeue\n    val left = queue.dequeue\n    val node = Node(left, right)\n    map(node) = map(left) + map(right)\n    queue.enqueue(node)\n  }\n\n  def codify(tree: Tree, map: Map[Tree, Int]) = {\n    def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match {\n      case Node(left, right) => recurse(left, prefix+\"0\") ::: recurse(right, prefix+\"1\")\n      case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil\n    }\n    recurse(tree, \"\")\n  }\n\n  def encode(text: String) = {\n    val map = Map.empty[Tree,Int] ++= stringMap(text)\n    val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator\n    \n    while(queue.size > 1) {\n      buildNode(queue, map)\n    }\n    codify(queue.dequeue, map)\n  }\n  \n  \n  def main(args: Array[String]) {\n    val text = \"this is an example for huffman encoding\"\n    val code = encode(text)\n    println(\"Char\\tWeight\\t\\tEncoding\")\n    code sortBy (_._2._1) foreach { \n      case (c, (weight, encoding)) => println(\"%c:\\t%3d\/%-3d\\t\\t%s\" format (c, weight, text.length, encoding)) \n    }\n  }\n}\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":2454}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nimport scala.swing.{ BorderPanel, Button, Label, MainFrame, SimpleSwingApplication }\nimport scala.swing.event.ButtonClicked\n\nobject SimpleApp extends SimpleSwingApplication {\n  def top = new MainFrame {\n    contents = new BorderPanel {\n      var nClicks = 0\n\n      val (button, label) = (new Button { text = \"click me\" },\n        new Label { text = \"There have been no clicks yet\" })\n\n      layout(button) = BorderPanel.Position.South\n      layout(label) = BorderPanel.Position.Center\n      listenTo(button)\n      reactions += {\n        case ButtonClicked(_) =>\n          nClicks += 1\n          label.text = s\"There have been ${nClicks} clicks\"\n      }\n    }\n  }\n}\n\n\n","human_summarization":"\"Creates a windowed application with a label and a button. The label initially displays 'There have been no clicks yet'. The button is labeled 'click me'. On each button click, the label updates to show the total number of button clicks.\"","id":2455}
    {"lang_cluster":"Scala","source_code":"\nfor(i <- 10 to 0 by -1) println(i)\n\/\/or\n10 to 0 by -1 foreach println\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":2456}
    {"lang_cluster":"Scala","source_code":"\n\nobject Vigenere {\n  def encrypt(msg: String, key: String) : String = {\n    var result: String = \"\"\n    var j = 0\n\n    for (i <- 0 to msg.length - 1) {\n      val c = msg.charAt(i)\n      if (c >= 'A' && c <= 'Z') {\n        result += ((c + key.charAt(j) - 2 * 'A') % 26 + 'A').toChar\n        j = (j + 1) % key.length\n      }\n    }\n\n    return result\n  }\n\n  def decrypt(msg: String, key: String) : String = {\n    var result: String = \"\"\n    var j = 0\n\n    for (i <- 0 to msg.length - 1) {\n      val c = msg.charAt(i)\n      if (c >= 'A' && c <= 'Z') {\n        result += ((c - key.charAt(j) + 26) % 26 + 'A').toChar\n        j = (j + 1) % key.length\n      }\n    }\n\n    return result\n  }\n}\n\nprintln(\"Encrypt text ABC => \" + Vigenere.encrypt(\"ABC\", \"KEY\"))\nprintln(\"Decrypt text KFA => \" + Vigenere.decrypt(\"KFA\", \"KEY\"))\n\n\n","human_summarization":"Implement the Vigen\u00e8re cipher for both encryption and decryption. It handles keys and text of unequal length, capitalizes all characters, and discards non-alphabetic characters. It accepts valid characters from A to Z, 0 to 9, and a full-stop (.).","id":2457}
    {"lang_cluster":"Scala","source_code":"\nfor (i <- 2 to 8 by 2) println(i)\n\n(2 to 8 by 2) foreach println\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":2458}
    {"lang_cluster":"Scala","source_code":"\n\nclass MyInt { var i: Int = _ }\nval i = new MyInt\ndef sum(i: MyInt, lo: Int, hi: Int, term: => Double) = {\n  var temp = 0.0\n  i.i = lo\n  while(i.i <= hi) {\n    temp = temp + term\n    i.i += 1\n  }\n  temp\n}\nsum(i, 1, 100, 1.0 \/ i.i)\n\n\nres2: Double = 5.187377517639621\n\n","human_summarization":"The code is an implementation of Jensen's Device, a programming technique that uses call by name. It calculates the 100th harmonic number using a sum procedure. The sum procedure takes four parameters: an integer, two range values, and a term. The term and integer are passed by name, allowing their values to be re-evaluated in the caller's context each time they are required. The code also demonstrates the importance of passing the first parameter by name or reference, to ensure changes made within the sum procedure are visible in the caller's context. A mutable integer class is used to simulate passing by reference in Scala.","id":2459}
    {"lang_cluster":"Scala","source_code":"\nLibrary: org.scala-lang.modules scala-swing\nimport scala.swing.Swing.pair2Dimension\nimport scala.swing.{Color, Graphics2D, MainFrame, Panel, SimpleSwingApplication}\n\nobject XorPattern extends SimpleSwingApplication {\n\n  def top = new MainFrame {\n    preferredSize = (300, 300)\n    title = \"Rosetta Code >>> Task: Munching squares | Language: Scala\"\n    contents = new Panel {\n\n      protected override def paintComponent(g: Graphics2D) = {\n        super.paintComponent(g)\n        for {\n          y <- 0 until size.getHeight.toInt\n          x <- 0 until size.getWidth.toInt\n        } {\n          g.setColor(new Color(0, (x ^ y) % 256, 0))\n          g.drawLine(x, y, x, y)\n        }\n      }\n    }\n\n    centerOnScreen()\n  }\n}\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":2460}
    {"lang_cluster":"Scala","source_code":"\nimport scala.util.Random\n\nobject MazeTypes {\n  case class Direction(val dx: Int, val dy: Int)\n\n  case class Loc(val x: Int, val y: Int) {\n    def +(that: Direction): Loc = Loc(x + that.dx, y + that.dy)\n  }\n  \n  case class Door(val from: Loc, to: Loc)\n\n  val North = Direction(0,-1)\n  val South = Direction(0,1)\n  val West = Direction(-1,0)\n  val East = Direction(1,0)\n  val directions = Set(North, South, West, East)\n}\n\nobject MazeBuilder {\n  import MazeTypes._\n\n  def shuffle[T](set: Set[T]): List[T] = Random.shuffle(set.toList)\n  \n  def buildImpl(current: Loc, grid: Grid): Grid = {\n    var newgrid = grid.markVisited(current)\n    val nbors = shuffle(grid.neighbors(current))\n    nbors.foreach { n =>\n      if (!newgrid.isVisited(n)) {\n        newgrid = buildImpl(n, newgrid.markVisited(current).addDoor(Door(current, n)))\n      }\n    }\n    newgrid\n  }\n    \n  def build(width: Int, height: Int): Grid = {\n    val exit = Loc(width-1, height-1)\n    buildImpl(exit, new Grid(width, height, Set(), Set()))\n  }  \n}\n\nclass Grid(val width: Int, val height: Int, val doors: Set[Door], val visited: Set[Loc]) {\n\n  def addDoor(door: Door): Grid = \n    new Grid(width, height, doors + door, visited)\n  \n  def markVisited(loc: Loc): Grid = \n    new Grid(width, height, doors, visited + loc)\n  \n  def isVisited(loc: Loc): Boolean = \n    visited.contains(loc)\n    \n  def neighbors(current: Loc): Set[Loc] = \n    directions.map(current + _).filter(inBounds(_)) -- visited\n    \n  def printGrid(): List[String] = {\n    (0 to height).toList.flatMap(y => printRow(y))\n  }\n  \n  private def inBounds(loc: Loc): Boolean = \n    loc.x >= 0 && loc.x < width && loc.y >= 0 && loc.y < height\n\n  private def printRow(y: Int): List[String] = {\n    val row = (0 until width).toList.map(x => printCell(Loc(x, y)))\n    val rightSide = if (y == height-1) \" \" else \"|\"\n    val newRow = row :+ List(\"+\", rightSide)\n    List.transpose(newRow).map(_.mkString)\n  }\n  \n  private val entrance = Loc(0,0)\n\n  private def printCell(loc: Loc): List[String] = {\n    if (loc.y == height) \n      List(\"+--\")\n    else List(\n      if (openNorth(loc)) \"+  \" else \"+--\", \n      if (openWest(loc) || loc == entrance) \"   \" else \"|  \"\n    )\n  }\n  \n  def openNorth(loc: Loc): Boolean = openInDirection(loc, North)\n  \n  def openWest(loc: Loc): Boolean = openInDirection(loc, West)\n    \n  private def openInDirection(loc: Loc, dir: Direction): Boolean = \n    doors.contains(Door(loc, loc + dir)) || doors.contains(Door(loc + dir, loc))\n}\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":2461}
    {"lang_cluster":"Scala","source_code":"\nobject Pi {\n  class PiIterator extends Iterable[BigInt] {\n    var r: BigInt = 0\n    var q, t, k: BigInt = 1\n    var n, l: BigInt = 3\n\n    def iterator: Iterator[BigInt] = new Iterator[BigInt] {\n      def hasNext = true\n\n      def next(): BigInt = {\n        while ((4 * q + r - t) >= (n * t)) {\n          val nr = (2 * q + r) * l\n          val nn = (q * (7 * k) + 2 + (r * l)) \/ (t * l)\n          q = q * k\n          t = t * l\n          l = l + 2\n          k = k + 1\n          n = nn\n          r = nr\n        }\n        val ret = n\n        val nr = 10 * (r - n * t)\n        n = ((10 * (3 * q + r)) \/ t) - (10 * n)\n        q = q * 10\n        r = nr\n        ret\n      }\n    }\n  }\n\n  def main(args: Array[String]): Unit = {\n    val it = new PiIterator\n    println(\"\" + (it.head) + \".\" + (it.take(300).mkString))\n  }\n\n}\n\n\n3.141592653589793238462643383279502884197169399375105820974944592307816406286208998\n62803482534211706798214808651328230664709384460955058223172535940812848111745028410\n27019385211055596446229489549303819644288109756659334461284756482337867831652712019\n09145648566923460348610454326648213393607260249141273\n","human_summarization":"continuously calculate and display the next decimal digit of Pi until the program is manually terminated by the user. The sequence begins with 3.14159265.","id":2462}
    {"lang_cluster":"Scala","source_code":"\ndef lessThan1(a: List[Int], b: List[Int]): Boolean =\n  if (b.isEmpty) false\n  else if (a.isEmpty) true\n  else if (a.head != b.head) a.head < b.head\n  else lessThan1(a.tail, b.tail)\ndef lessThan2(a: List[Int], b: List[Int]): Boolean = (a, b) match {\n  case (_, Nil) => false\n  case (Nil, _) => true\n  case (a :: _, b :: _) if a != b => a < b\n  case _ => lessThan2(a.tail, b.tail)\n}\ndef lessThan3(a: List[Int], b: List[Int]): Boolean =\n  a.zipAll(b, Integer.MIN_VALUE, Integer.MIN_VALUE)\n   .find{case (a, b) => a != b}\n   .map{case (a, b) => a < b}\n   .getOrElse(false)\nval tests = List(\n  (List(1, 2, 3), List(1, 2, 3)) -> false,\n  (List(3, 2, 1), List(3, 2, 1)) -> false,\n  (List(1, 2, 3), List(3, 2, 1)) -> true,\n  (List(3, 2, 1), List(1, 2, 3)) -> false,\n  (List(1, 2), List(1, 2, 3)) -> true,\n  (List(1, 2, 3), List(1, 2)) -> false\n)\n\ntests.foreach{case test @ ((a, b), c) =>\n  assert(lessThan1(a, b) == c, test)\n  assert(lessThan2(a, b) == c, test)\n  assert(lessThan3(a, b) == c, test)\n}\n\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise.\"","id":2463}
    {"lang_cluster":"Scala","source_code":"\ndef ack(m: BigInt, n: BigInt): BigInt = {\n  if (m==0) n+1\n  else if (n==0) ack(m-1, 1)\n  else ack(m-1, ack(m, n-1))\n}\n\nExample:\nscala> for ( m <- 0 to 3; n <- 0 to 6 ) yield ack(m,n)\nres0: Seq.Projection[BigInt] = RangeG(1, 2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 7, 8, 3, 5, 7, 9, 11, 13, 15, 5, 13, 29, 61, 125, 253, 509)\n\n\nval ackMap = new mutable.HashMap[(BigInt,BigInt),BigInt]\ndef ackMemo(m: BigInt, n: BigInt): BigInt = {\n  ackMap.getOrElseUpdate((m,n), ack(m,n))\n}\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the conditions defined. The function is expected to terminate always. It is preferred to have arbitrary precision due to the rapid growth of the function. A memoized version using a mutable hash map is also provided.","id":2464}
    {"lang_cluster":"Scala","source_code":"\nimport java.util.Locale._\n\nobject Gamma {\n  def stGamma(x:Double):Double=math.sqrt(2*math.Pi\/x)*math.pow((x\/math.E), x)\n  \n  def laGamma(x:Double):Double={\n    val p=Seq(676.5203681218851, -1259.1392167224028, 771.32342877765313, \n             -176.61502916214059, 12.507343278686905, -0.13857109526572012,\n                9.9843695780195716e-6, 1.5056327351493116e-7)\n\n    if(x < 0.5) {\n      math.Pi\/(math.sin(math.Pi*x)*laGamma(1-x))\n    } else {\n      val x2=x-1\n      val t=x2+7+0.5\n      val a=p.zipWithIndex.foldLeft(0.99999999999980993)((r,v) => r+v._1\/(x2+v._2+1))\n      math.sqrt(2*math.Pi)*math.pow(t, x2+0.5)*math.exp(-t)*a\n    }\n  }\n  \n  def main(args: Array[String]): Unit = {\n    println(\"Gamma    Stirling             Lanczos\")\n    for(x <- 0.1 to 2.0 by 0.1)\n      println(\"%.1f  -> \u00a0%.16f  \u00a0%.16f\".formatLocal(ENGLISH, x, stGamma(x), laGamma(x)))\n  }\n}\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":2465}
    {"lang_cluster":"Scala","source_code":"\n\nobject NQueens {\n\n  private implicit class RichPair[T](\n    pair: (T,T))(\n    implicit num: Numeric[T]\n  ) {\n    import num._\n\n    def safe(x: T, y: T): Boolean =\n      pair._1 - pair._2\u00a0!= abs(x - y)\n  }\n  \n  def solve(n: Int): Iterator[Seq[Int]] = {\n    (0 to n-1)\n      .permutations\n      .filter { v =>\n        (0 to n-1).forall { y =>\n          (y+1 to n-1).forall { x =>\n            (x,y).safe(v(x),v(y))\n          }\n        }\n      }\n  }\n\n  def main(args: Array[String]): Unit = {\n    val n = args.headOption.getOrElse(\"8\").toInt\n    val (solns1, solns2) = solve(n).duplicate\n    solns1\n      .zipWithIndex\n      .foreach { case (soln, i) =>\n        Console.out.println(s\"Solution #${i+1}\")\n        output(n)(soln)\n      }\n    val n_solns = solns2.size\n    if (n_solns == 1) {\n      Console.out.println(\"Found 1 solution\")\n    } else {\n      Console.out.println(s\"Found $n_solns solutions\")\n    }\n  }\n\n  def output(n: Int)(board: Seq[Int]): Unit = {\n    board.foreach { queen =>\n      val row = \n        \"_|\" * queen + \"Q\" + \"|_\" * (n-queen-1)\n      Console.out.println(row)\n    }\n  }\n}\nscala> NQueens.main(Array(\"8\"))\nSolution #1\nQ|_|_|_|_|_|_|_\n_|_|_|_|Q|_|_|_\n_|_|_|_|_|_|_|Q\n_|_|_|_|_|Q|_|_\n_|_|Q|_|_|_|_|_\n_|_|_|_|_|_|Q|_\n_|Q|_|_|_|_|_|_\n_|_|_|Q|_|_|_|_\n\nSolution #2\nQ|_|_|_|_|_|_|_\n_|_|_|_|_|Q|_|_\n_|_|_|_|_|_|_|Q\n_|_|Q|_|_|_|_|_\n_|_|_|_|_|_|Q|_\n_|_|_|Q|_|_|_|_\n_|Q|_|_|_|_|_|_\n_|_|_|_|Q|_|_|_\n...\nFound 92 solutions\n\n","human_summarization":"The code solves the N-queens puzzle for a board of size NxN, extending the eight queens puzzle. It uses an enriched implicit class to extend a Tuple2[T,T] to check if positions are safe or threatened. It also lazily generates permutations with an Iterator. The code also provides the number of solutions for small values of N, referencing OEIS: A000170.","id":2466}
    {"lang_cluster":"Scala","source_code":"\nval arr1 = Array( 1, 2, 3 )\nval arr2 = Array( 4, 5, 6 )\nval arr3 = Array( 7, 8, 9 )\n\narr1 ++ arr2 ++ arr3\n\/\/or:\nArray concat ( arr1, arr2, arr3 )\n\/\/ res0: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)\n","human_summarization":"demonstrate how to concatenate two arrays.","id":2467}
    {"lang_cluster":"Scala","source_code":"\nWorks with: Scala version 2.9.2\nobject Knapsack extends App {\n\n  case class Item(name: String, weight: Int, value: Int)\n\n  val elapsed: (=> Unit) => Long = f => {val s = System.currentTimeMillis; f; (System.currentTimeMillis - s)\/1000}\n\n  \/\/===== brute force (caution: increase the heap!) ====================================\n  val ks01b: List[Item] => Unit = loi => {\n    val tw:Set[Item]=>Int=ps=>(ps:\\0)((a,b)=>a.weight+b) \/\/total weight\n    val tv:Set[Item]=>Int=ps=>(ps:\\0)((a,b)=>a.value+b) \/\/total value\n    val pis = (loi.toSet.subsets).toList.filterNot(_==Set())\n\n   #[test]\nfn test_dp_results() {\n    let dp_results = knap_01_dp(items, 400);\n    let dp_weights= dp_results.iter().fold(0, |a, &b| a + b.weight);\n    let dp_values = dp_results.iter().fold(0, |a, &b| a + b.value);\n    assert_eq!(dp_weights, 396);\n    assert_eq!(dp_values, 1030);\n} val res = pis.map(ss=>Pair(ss,tw(ss)))\n      .filter(p=>p._2>350 && p._2<401).map(p=>Pair(p,tv(p._1)))\n      .sortWith((s,t)=>s._2.compareTo(t._2) < 0)\n      .last\n    println{val h = \"packing list of items (brute force):\"; h+\"\\n\"+\"=\"*h.size}\n    res._1._1.foreach{p=>print(\"  \"+p.name+\": weight=\"+p.weight+\" value=\"+p.value+\"\\n\")}\n    println(\"\\n\"+\"  resulting items: \"+res._1._1.size+\" of \"+loi.size) \n    println(\"  total weight: \"+res._1._2+\", total value: \"+res._2)\n  }\n\n  \/\/===== dynamic programming ==========================================================\n  val ks01d: List[Item] => Unit = loi => { \n    val W = 400\n    val N = loi.size\n\n    val m = Array.ofDim[Int](N+1,W+1)\n    val plm = (List((for {w <- 0 to W} yield Set[Item]()).toArray)++(\n                for {\n                  n <- 0 to N-1\n                  colN = (for {w <- 0 to W} yield Set[Item](loi(n))).toArray\n                } yield colN)).toArray\n\n    1 to N foreach {n =>\n      0 to W foreach {w =>\n        def in = loi(n-1)\n        def wn = loi(n-1).weight\n        def vn = loi(n-1).value\n        if (w<wn) {\n          m(n)(w) = m(n-1)(w)\n          plm(n)(w) = plm(n-1)(w)\n        } \n        else {\n          if (m(n-1)(w)>=m(n-1)(w-wn)+vn) {\n            m(n)(w) = m(n-1)(w)\n            plm(n)(w) = plm(n-1)(w)\n          }\n          else {\n            m(n)(w) = m(n-1)(w-wn)+vn\n\t    plm(n)(w) = plm(n-1)(w-wn)+in\n\t  }\n\t}\n      }\n    }\n\n    println{val h = \"packing list of items (dynamic programming):\"; h+\"\\n\"+\"=\"*h.size}\n    plm(N)(W).foreach{p=>print(\"  \"+p.name+\": weight=\"+p.weight+\" value=\"+p.value+\"\\n\")}\n    println(\"\\n\"+\"  resulting items: \"+plm(N)(W).size+\" of \"+loi.size) \n    println(\"  total weight: \"+(0\/:plm(N)(W).toVector.map{item=>item.weight})(_+_)+\", total value: \"+m(N)(W))\n  }\n\n  val items = List(\n     Item(\"map\", 9, 150)\n    ,Item(\"compass\", 13, 35) \n    ,Item(\"water\", 153, 200)\n    ,Item(\"sandwich\", 50, 160)\n    ,Item(\"glucose\", 15, 60)\n    ,Item(\"tin\", 68, 45)\n    ,Item(\"banana\", 27, 60)\n    ,Item(\"apple\", 39, 40)\n    ,Item(\"cheese\", 23, 30)\n    ,Item(\"beer\", 52, 10)\n    ,Item(\"suntan cream\", 11, 70)\n    ,Item(\"camera\", 32, 30)\n    ,Item(\"t-shirt\", 24, 15)\n    ,Item(\"trousers\", 48, 10)\n    ,Item(\"umbrella\", 73, 40)\n    ,Item(\"waterproof trousers\", 42, 70)\n    ,Item(\"waterproof overclothes\", 43, 75)\n    ,Item(\"note-case\", 22, 80)\n    ,Item(\"sunglasses\", 7, 20)\n    ,Item(\"towel\", 18, 12)\n    ,Item(\"socks\", 4, 50)\n    ,Item(\"book\", 30, 10)\n  ) \n\n  List(ks01b, ks01d).foreach{f=>\n    val t = elapsed{f(items)}\n    println(\"  elapsed time: \"+t+\" sec\"+\"\\n\")\n  }\n}\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":2468}
    {"lang_cluster":"Scala","source_code":"object SMP extends App {\n    private def checkMarriages(): Unit =\n        if (check)\n            println(\"Marriages are stable\")\n        else\n            println(\"Marriages are unstable\")\n\n    private def swap() {\n        val girl1 = girls.head\n        val girl2 = girls(1)\n        val tmp = girl2 -> matches(girl1)\n        matches += girl1 -> matches(girl2)\n        matches += tmp\n        println(girl1 + \" and \" + girl2 + \" have switched partners\")\n    }\n\n    private type TM = scala.collection.mutable.TreeMap[String, String]\n\n    private def check: Boolean = {\n        if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet))\n            return false\n\n        val invertedMatches = new TM\n        matches foreach { invertedMatches += _.swap }\n\n        for ((k, v) <- matches) {\n            val shePrefers = girlPrefers(k)\n            val sheLikesBetter = shePrefers.slice(0, shePrefers.indexOf(v))\n            val hePrefers = guyPrefers(v)\n            val heLikesBetter = hePrefers.slice(0, hePrefers.indexOf(k))\n\n            for (guy <- sheLikesBetter) {\n                val fiance = invertedMatches(guy)\n                val guy_p = guyPrefers(guy)\n                if (guy_p.indexOf(fiance) > guy_p.indexOf(k)) {\n                    println(s\"$k likes $guy better than $v and $guy likes $k better than their current partner\")\n                    return false\n                }\n            }\n\n            for (girl <- heLikesBetter) {\n                val fiance = matches(girl)\n                val girl_p = girlPrefers(girl)\n                if (girl_p.indexOf(fiance) > girl_p.indexOf(v)) {\n                    println(s\"$v likes $girl better than $k and $girl likes $v better than their current partner\")\n                    return false\n                }\n            }\n        }\n        true\n    }\n\n    private val guys = \"abe\" :: \"bob\" :: \"col\" :: \"dan\" :: \"ed\" :: \"fred\" :: \"gav\" :: \"hal\" :: \"ian\" :: \"jon\" :: Nil\n    private val girls = \"abi\" :: \"bea\" :: \"cath\" :: \"dee\" :: \"eve\" :: \"fay\" :: \"gay\" :: \"hope\" :: \"ivy\" :: \"jan\" :: Nil\n    private val guyPrefers = Map(\"abe\" -> List(\"abi\", \"eve\", \"cath\", \"ivy\", \"jan\", \"dee\", \"fay\", \"bea\", \"hope\", \"gay\"),\n        \"bob\" -> List(\"cath\", \"hope\", \"abi\", \"dee\", \"eve\", \"fay\", \"bea\", \"jan\", \"ivy\", \"gay\"),\n        \"col\" -> List(\"hope\", \"eve\", \"abi\", \"dee\", \"bea\", \"fay\", \"ivy\", \"gay\", \"cath\", \"jan\"),\n        \"dan\" -> List(\"ivy\", \"fay\", \"dee\", \"gay\", \"hope\", \"eve\", \"jan\", \"bea\", \"cath\", \"abi\"),\n        \"ed\" -> List(\"jan\", \"dee\", \"bea\", \"cath\", \"fay\", \"eve\", \"abi\", \"ivy\", \"hope\", \"gay\"),\n        \"fred\" -> List(\"bea\", \"abi\", \"dee\", \"gay\", \"eve\", \"ivy\", \"cath\", \"jan\", \"hope\", \"fay\"),\n        \"gav\" -> List(\"gay\", \"eve\", \"ivy\", \"bea\", \"cath\", \"abi\", \"dee\", \"hope\", \"jan\", \"fay\"),\n        \"hal\" -> List(\"abi\", \"eve\", \"hope\", \"fay\", \"ivy\", \"cath\", \"jan\", \"bea\", \"gay\", \"dee\"),\n        \"ian\" -> List(\"hope\", \"cath\", \"dee\", \"gay\", \"bea\", \"abi\", \"fay\", \"ivy\", \"jan\", \"eve\"),\n        \"jon\" -> List(\"abi\", \"fay\", \"jan\", \"gay\", \"eve\", \"bea\", \"dee\", \"cath\", \"ivy\", \"hope\"))\n    private val girlPrefers = Map(\"abi\" -> List(\"bob\", \"fred\", \"jon\", \"gav\", \"ian\", \"abe\", \"dan\", \"ed\", \"col\", \"hal\"),\n        \"bea\" -> List(\"bob\", \"abe\", \"col\", \"fred\", \"gav\", \"dan\", \"ian\", \"ed\", \"jon\", \"hal\"),\n        \"cath\" -> List(\"fred\", \"bob\", \"ed\", \"gav\", \"hal\", \"col\", \"ian\", \"abe\", \"dan\", \"jon\"),\n        \"dee\" -> List(\"fred\", \"jon\", \"col\", \"abe\", \"ian\", \"hal\", \"gav\", \"dan\", \"bob\", \"ed\"),\n        \"eve\" -> List(\"jon\", \"hal\", \"fred\", \"dan\", \"abe\", \"gav\", \"col\", \"ed\", \"ian\", \"bob\"),\n        \"fay\" -> List(\"bob\", \"abe\", \"ed\", \"ian\", \"jon\", \"dan\", \"fred\", \"gav\", \"col\", \"hal\"),\n        \"gay\" -> List(\"jon\", \"gav\", \"hal\", \"fred\", \"bob\", \"abe\", \"col\", \"ed\", \"dan\", \"ian\"),\n        \"hope\" -> List(\"gav\", \"jon\", \"bob\", \"abe\", \"ian\", \"dan\", \"hal\", \"ed\", \"col\", \"fred\"),\n        \"ivy\" -> List(\"ian\", \"col\", \"hal\", \"gav\", \"fred\", \"bob\", \"abe\", \"ed\", \"jon\", \"dan\"),\n        \"jan\" -> List(\"ed\", \"hal\", \"gav\", \"abe\", \"bob\", \"jon\", \"col\", \"ian\", \"fred\", \"dan\"))\n    \n    private lazy val matches = {\n        val engagements = new TM\n        val freeGuys = scala.collection.mutable.Queue.empty ++ guys\n        while (freeGuys.nonEmpty) {\n            val guy = freeGuys.dequeue()\n            val guy_p = guyPrefers(guy)\n            var break = false\n            for (girl <- guy_p)\n                if (!break)\n                    if (!engagements.contains(girl)) {\n                        engagements(girl) = guy\n                        break = true\n                    }\n                    else {\n                        val other_guy = engagements(girl)\n                        val girl_p = girlPrefers(girl)\n                        if (girl_p.indexOf(guy) < girl_p.indexOf(other_guy)) {\n                            engagements(girl) = guy\n                            freeGuys += other_guy\n                            break = true\n                        }\n                    }\n        }\n\n        engagements foreach { e => println(s\"${e._1} is engaged to ${e._2}\") }\n        engagements\n    }\n    \n    checkMarriages()\n    swap()\n    checkMarriages()\n}\n\n\n","human_summarization":"The code implements the Gale\/Shapley algorithm to solve the Stable Marriage problem. It takes as input a list of ten males and ten females, each with a ranked list of preferences. The code then generates a stable set of engagements based on these preferences. It also perturbs this set to create an unstable set of engagements and checks the stability of this new set.","id":2469}
    {"lang_cluster":"Scala","source_code":"\nobject ShortCircuit {\n   def a(b:Boolean)={print(\"Called A=%5b\".format(b));b}\n   def b(b:Boolean)={print(\" -> B=%5b\".format(b));b}\n\n   def main(args: Array[String]): Unit = {\n      val boolVals=List(false,true)\n      for(aa<-boolVals; bb<-boolVals){\n         print(\"\\nTesting A=%5b AND B=%5b   -> \".format(aa, bb))\n         a(aa) && b(bb)\n      }\n      for(aa<-boolVals; bb<-boolVals){\n         print(\"\\nTesting A=%5b  OR B=%5b   -> \".format(aa, bb))\n         a(aa) || b(bb)\n      }\n      println\n   }\n}\n\n\n","human_summarization":"create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.","id":2470}
    {"lang_cluster":"Scala","source_code":"\nobject MorseCode extends App {\n\n  private val code = Map(\n    ('A', \".-     \"), ('B', \"-...   \"), ('C', \"-.-.   \"), ('D', \"-..    \"),\n    ('E', \".      \"), ('F', \"..-.   \"), ('G', \"--.    \"), ('H', \"....   \"),\n    ('I', \"..     \"), ('J', \".---   \"), ('K', \"-.-    \"), ('L', \".-..   \"),\n    ('M', \"--     \"), ('N', \"-.     \"), ('O', \"---    \"), ('P', \".--.   \"),\n    ('Q', \"--.-   \"), ('R', \".-.    \"), ('S', \"...    \"), ('T', \"-      \"),\n    ('U', \"..-    \"), ('V', \"...-   \"), ('W', \".-   - \"), ('X', \"-..-   \"),\n    ('Y', \"-.--   \"), ('Z', \"--..   \"), ('0', \"-----  \"), ('1', \".----  \"),\n    ('2', \"..---  \"), ('3', \"...--  \"), ('4', \"....-  \"), ('5', \".....  \"),\n    ('6', \"-....  \"), ('7', \"--...  \"), ('8', \"---..  \"), ('9', \"----.  \"),\n    (''', \".----.\"), (':', \"---... \"), (',', \"--..-- \"), ('-', \"-....- \"),\n    ('(', \"-.--.- \"), ('.', \".-.-.- \"), ('?', \"..--.. \"), (';', \"-.-.-. \"),\n    ('\/', \"-..-.  \"), ('-', \"..--.- \"), (')', \"---..  \"), ('=', \"-...-  \"),\n    ('@', \".--.-. \"), ('\"', \".-..-. \"), ('+', \".-.-.  \"), (' ', \"\/\")) \/\/ cheat a little\n\n  private def printMorse(input: String): Unit = {\n    println(input)\n    println(input.trim.replaceAll(\"[ ]+\", \" \").toUpperCase\n      .map(code.getOrElse(_, \"\").trim).mkString(\" \"))\n  }\n\n  printMorse(\"sos\")\n  printMorse(\"   Hello     World!\")\n  printMorse(\"Rosetta Code\")\n\n}\n","human_summarization":"<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":2471}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scalaobject AbcBlocks extends App {\n\n  protected class Block(face1: Char, face2: Char) {\n\n    def isFacedWith(that: Char) = { that == face1 || that == face2 }\n    override def toString() = face1.toString + face2\n  }\n  protected object Block {\n    def apply(faces: String) = new Block(faces.head, faces.last)\n  }\n\n  type word = Seq[Block]\n\n  private val blocks = List(Block(\"BO\"), Block(\"XK\"), Block(\"DQ\"), Block(\"CP\"), Block(\"NA\"),\n    Block(\"GT\"), Block(\"RE\"), Block(\"TG\"), Block(\"QD\"), Block(\"FS\"),\n    Block(\"JW\"), Block(\"HU\"), Block(\"VI\"), Block(\"AN\"), Block(\"OB\"),\n    Block(\"ER\"), Block(\"FS\"), Block(\"LY\"), Block(\"PC\"), Block(\"ZM\"))\n\n  private def isMakeable(word: String, blocks: word) = {\n\n    def getTheBlocks(word: String, blocks: word) = {\n\n      def inner(word: String, toCompare: word, rest: word, accu: word): word = {\n        if (word.isEmpty || rest.isEmpty || toCompare.isEmpty) accu\n        else if (toCompare.head.isFacedWith(word.head)) {\n          val restant = rest diff List(toCompare.head)\n          inner(word.tail, restant, restant, accu\u00a0:+ toCompare.head)\n        } else inner(word, toCompare.tail, rest, accu)\n      }\n      inner(word, blocks, blocks, Nil)\n    }\n\n    word.lengthCompare(getTheBlocks(word, blocks).size) == 0\n  }\n\n  val words = List(\"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"CONFUSED\", \"ANBOCPDQERSFTGUVWXLZ\")\n  \/\/ Automatic tests\n  assert(isMakeable(words(0), blocks))\n  assert(isMakeable(words(1), blocks))\n  assert(!isMakeable(words(2), blocks)) \/\/ BOOK not\n  assert(isMakeable(words(3), blocks))\n  assert(!isMakeable(words(4), blocks)) \/\/ COMMON not\n  assert(isMakeable(words(5), blocks))\n  assert(isMakeable(words(6), blocks))\n  assert(isMakeable(words(7), blocks))\n\n  \/\/words(7).mkString.permutations.foreach(s => assert(isMakeable(s, blocks)))\n\n  words.foreach(w => println(s\"$w can${if (isMakeable(w, blocks)) \" \" else \"not \"}be made.\"))\n}\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":2472}
    {"lang_cluster":"Scala","source_code":"\nobject RosettaMD5 extends App {\n\n  def MD5(s: String): String = {\n    \/\/ Besides \"MD5\", \"SHA-256\", and other hashes are available\n    val m = java.security.MessageDigest.getInstance(\"MD5\").digest(s.getBytes(\"UTF-8\"))\n    m.map(\"%02x\".format(_)).mkString\n  }\n\n  assert(\"d41d8cd98f00b204e9800998ecf8427e\" == MD5(\"\"))\n  assert(\"0cc175b9c0f1b6a831c399e269772661\" == MD5(\"a\"))\n  assert(\"900150983cd24fb0d6963f7d28e17f72\" == MD5(\"abc\"))\n  assert(\"f96b697d7cb7938d525a2f31aaf161d0\" == MD5(\"message digest\"))\n  assert(\"c3fcd3d76192e4007dfb496cca67e13b\" == MD5(\"abcdefghijklmnopqrstuvwxyz\"))\n  assert(\"e38ca1d920c4b8b8d3946b2c72f01680\" == MD5(\"The quick brown fox jumped over the lazy dog's back\"))\n  assert(\"d174ab98d277d9f5a5611c2c9f419d9f\" ==\n    MD5(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"))\n  assert(\"57edf4a22be3c955ac49da2e2107b67a\" ==\n    MD5(\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"))\n  import scala.compat.Platform.currentTime\n  println(s\"Successfully completed without errors. [total ${currentTime - executionStart} ms]\")\n}\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":2473}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nimport java.net.Socket\n\nobject sendSocketData {\n\n  def sendData(host: String, msg: String) {\n    val sock = new Socket(host, 256)\n    sock.getOutputStream().write(msg.getBytes())\n    sock.getOutputStream().flush()\n    sock.close()\n  }\n\n  sendData(\"localhost\", \"hello socket world\")\n}\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":2474}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\nimport java.util.Properties\n\nimport javax.mail.internet.{ InternetAddress, MimeMessage }\nimport javax.mail.Message.RecipientType\nimport javax.mail.{ Session, Transport }\n\n\/** Mail constructor.\n *  @constructor Mail\n *  @param host Host\n *\/\nclass Mail(host: String) {\n  val session = Session.getDefaultInstance(new Properties() { put(\"mail.smtp.host\", host) })\n\n  \/** Send email message.\n   *\n   *  @param from From\n   *  @param tos Recipients\n   *  @param ccs CC Recipients\n   *  @param subject Subject\n   *  @param text Text\n   *  @throws MessagingException\n   *\/\n  def send(from: String, tos: List[String], ccs: List[String], subject: String, text: String) {\n    val message = new MimeMessage(session)\n    message.setFrom(new InternetAddress(from))\n    for (to <- tos)\n      message.addRecipient(RecipientType.TO, new InternetAddress(to))\n    for (cc <- ccs)\n      message.addRecipient(RecipientType.TO, new InternetAddress(cc))\n    message.setSubject(subject)\n    message.setText(text)\n    Transport.send(message)\n  }\n}\n\n","human_summarization":"Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.","id":2475}
    {"lang_cluster":"Scala","source_code":"\nStream from 0 foreach (i => println(i.toOctalString))\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":2476}
    {"lang_cluster":"Scala","source_code":"\n\ndef swap[A,B](a: A, b: B): (B, A) = (b, a)\n","human_summarization":"implement a generic swap function or operator that can exchange the values of two variables or storage places, regardless of their types. In statically typed languages, the function should be described in a way that provides genericity. The function should be able to handle mutually compatible types and does not necessarily need to swap different types like strings and integers. The function uses type parameters and abstract types in Scala, and returns a tuple with inverted values as it cannot swap values in-place.","id":2477}
    {"lang_cluster":"Scala","source_code":"\nLibrary: Scala\n  def isPalindrome(s: String): Boolean = (s.size >= 2) && s == s.reverse\n  def isPalindromeSentence(s: String): Boolean =\n    (s.size >= 2) && {\n      val p = s.replaceAll(\"[^\\\\p{L}]\", \"\").toLowerCase\n      p == p.reverse\n    }\nimport scala.annotation.tailrec\n\n  def isPalindromeRec(s: String) = {\n    @tailrec\n    def inner(s: String): Boolean =\n      (s.length <= 1) || (s.head == s.last) && inner(s.tail.init)\n\n    (s.size >= 2) && inner(s)\n  }\n\n  \/\/ Testing\n  assert(!isPalindrome(\"\"))\n  assert(!isPalindrome(\"z\"))\n  assert(isPalindrome(\"amanaplanacanalpanama\"))\n  assert(!isPalindrome(\"Test 1,2,3\"))\n  assert(isPalindrome(\"1 2 1\"))\n  assert(!isPalindrome(\"A man a plan a canal Panama.\"))\n\n  assert(!isPalindromeSentence(\"\"))\n  assert(!isPalindromeSentence(\"z\"))\n  assert(isPalindromeSentence(\"amanaplanacanalpanama\"))\n  assert(!isPalindromeSentence(\"Test 1,2,3\"))\n  assert(isPalindromeSentence(\"1 2 1\"))\n  assert(isPalindromeSentence(\"A man a plan a canal Panama.\"))\n\n  assert(!isPalindromeRec(\"\"))\n  assert(!isPalindromeRec(\"z\"))\n  assert(isPalindromeRec(\"amanaplanacanalpanama\"))\n  assert(!isPalindromeRec(\"Test 1,2,3\"))\n  assert(isPalindromeRec(\"1 2 1\"))\n  assert(!isPalindromeRec(\"A man a plan a canal Panama.\"))\n\n  println(\"Successfully completed without errors.\")\n","human_summarization":"The code provides a function to check if a given sequence of characters or bytes is a palindrome. It supports Unicode characters and has an additional function to detect inexact palindromes, ignoring white-space, punctuation, and case sensitivity. The code also includes a method to reverse a string.","id":2478}
    {"lang_cluster":"Scala","source_code":"\nsys.env.get(\"HOME\")\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":2479}
    {"lang_cluster":"AWK","source_code":"\nfunction deque(arr) {\n    arr[\"start\"] = 0\n    arr[\"end\"] = 0\n}\n\nfunction dequelen(arr) {\n    return arr[\"end\"] - arr[\"start\"]\n}\n\nfunction empty(arr) {\n    return dequelen(arr) == 0\n}\n\nfunction push(arr, elem) {\n    arr[++arr[\"end\"]] = elem\n}\n\nfunction pop(arr) {\n    if (empty(arr)) {\n        return\n    }\n    return arr[arr[\"end\"]--]\n}\n\nfunction unshift(arr, elem) {\n    arr[arr[\"start\"]--] = elem\n}\n\nfunction shift(arr) {\n    if (empty(arr)) {\n        return\n    }\n    return arr[++arr[\"start\"]]\n}\n\nfunction peek(arr) {\n    if (empty(arr)) {\n        return\n    }\n    return arr[arr[\"end\"]]\n}\n\nfunction printdeque(arr,    i, sep) {\n    printf(\"[\")\n    for (i = arr[\"start\"] + 1; i <= arr[\"end\"]; i++) {\n        printf(\"%s%s\", sep, arr[i])\n        sep = \", \"\n    }\n    printf(\"]\\n\")\n}\n\nBEGIN {\n    deque(q)\n    for (i = 1; i <= 10; i++) {\n        push(q, i)\n    }\n    printdeque(q)\n    for (i = 1; i <= 10; i++) {\n        print pop(q)\n    }\n    printdeque(q)\n}\n\n","human_summarization":"implement a stack data structure with basic operations such as push (to add elements), pop (to remove and return the last added element), and empty (to check if the stack is empty). This stack follows a Last-In-First-Out (LIFO) access policy.","id":2480}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk 'func fib(n){return(n<2?n:fib(n-1)+fib(n-2))}{print \"fib(\"$1\")=\"fib($1)}'\n10\nfib(10)=55\n\n","human_summarization":"generate the nth Fibonacci number, supporting both positive and negative indices. The function can be implemented either iteratively or recursively.","id":2481}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk 'BEGIN{split(\"1 2 3 4 5 6 7 8 9\",a);for(i in a)if(!(a[i]%2))r=r\" \"a[i];print r}'\n\n\n","human_summarization":"select specific elements from an array, in this case, all even numbers, and place them into a new array. Optionally, it can also modify the original array instead of creating a new one. The sequence of elements may not be maintained.","id":2482}
    {"lang_cluster":"AWK","source_code":"BEGIN {\n\tstr = \"abcdefghijklmnopqrstuvwxyz\"\n\tn = 12\n\tm = 5\n\n\tprint substr(str, n, m)\n\tprint substr(str, n)\n\tprint substr(str, 1, length(str) - 1)\n\tprint substr(str, index(str, \"q\"), m)\n\tprint substr(str, index(str, \"pq\"), m)\n}\n\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":2483}
    {"lang_cluster":"AWK","source_code":"\nfunction reverse(s)\n{\n  p = \"\"\n  for(i=length(s); i > 0; i--) { p = p substr(s, i, 1) }\n  return p\n}\n\nBEGIN {\n  print reverse(\"edoCattesoR\")\n}\n\nRecursive\nfunction reverse(s   ,l)\n{\n  l = length(s)\n  return l < 2 ? s:( substr(s,l,1) reverse(substr(s,1,l-1)) )\n}\n\nBEGIN {\n  print reverse(\"edoCattesoR\")\n}\n\nusing split, then joining in front\n\n# Usage: awk -f reverse.awk -v s=Rosetta\n\nfunction rev(s,   i,len,a,r) {\n   len = split(s, a, \"\")\n  #for (i in a) r = a[i] r\t# may not work - order is not guaranteed\u00a0!\n   for (i=1; i<=len; i++) r = a[i] r\n   return r\n}\nBEGIN { \n   if(!s) s = \"Hello, world!\" \n   print s, \"<-->\", rev(s)\n}\n\n\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":2484}
    {"lang_cluster":"AWK","source_code":"\n\nNF == 3 { graph[$1,$2] = $3 }\nNF == 2 {\n    weight = shortest($1, $2)\n    n = length(path)\n    p = $1\n    for (i = 2; i < n; i++)\n        p = p \"-\" path[i]\n    print p \"-\" $2 \" (\" weight \")\"\n}\n\n# Edge weights are in graph[node1,node2]\n# Returns the weight of the shortest path\n# Shortest path is in path[1] ... path[n]\nfunction shortest(from, to,    queue, q, dist, v, i, min, edge, e, prev, n) {\n    delete path\n    dist[from] = 0\n    queue[q=1] = from\n\n    while (q > 0) {\n        min = 1\n        for (i = 2; i <= q; i++)\n            if (dist[queue[i]] < dist[queue[min]])\n                min = i\n        v = queue[min]\n        queue[min] = queue[q--]\n\n        if (v == to)\n            break\n        for (edge in graph) {\n            split(edge, e, SUBSEP)\n            if (e[1] != v)\n                continue\n            if (!(e[2] in dist) || dist[e[1]] + graph[edge] < dist[e[2]]) {\n                dist[e[2]] = dist[e[1]] + graph[edge]\n                prev[e[2]] = e[1]\n                queue[++q] = e[2]\n            }\n        }\n    }\n    if (v != to)\n        return \"n\/a\"\n\n    # Build the path\n    n = 1\n    for (v = to; v != from; v = prev[v])\n        n++\n    for (v = to; n > 0; v = prev[v])\n       path[n--] = v \n    return dist[to]\n}\n\n\n$ cat dijkstra.txt\na b 7\na c 9\na f 14\nb c 10\nb d 15\nc d 11\nc f 2\nd e 6\ne f 9\na e\na f\nf a\n\n$ awk -f dijkstra.awk dijkstra.txt\na-c-d-e (26)\na-c-f (11)\nf-a (n\/a)\n\n","human_summarization":"The code implements Dijkstra's algorithm to find the shortest path from a single source to all other vertices in a given graph. The graph is represented by an adjacency matrix or list and a start node. The algorithm iteratively updates the cost of reaching each vertex and keeps track of the path leading to the minimum cost. The output is a set of edges depicting the shortest path to each reachable node from the source. The code also includes functionality to interpret the output and display the shortest path from the source node to specific nodes.","id":2485}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f CIRCLES_OF_GIVEN_RADIUS_THROUGH_TWO_POINTS.AWK\n# converted from PL\/I\nBEGIN {\n    split(\"0.1234,0,0.1234,0.1234,0.1234\",m1x,\",\")\n    split(\"0.9876,2,0.9876,0.9876,0.9876\",m1y,\",\")\n    split(\"0.8765,0,0.1234,0.8765,0.1234\",m2x,\",\")\n    split(\"0.2345,0,0.9876,0.2345,0.9876\",m2y,\",\")\n    leng = split(\"2,1,2,0.5,0\",r,\",\")\n    print(\"     x1      y1      x2      y2    r   cir1x   cir1y   cir2x   cir2y\")\n    print(\"------- ------- ------- ------- ---- ------- ------- ------- -------\")\n    for (i=1; i<=leng; i++) {\n      printf(\"%7.4f %7.4f %7.4f %7.4f %4.2f %s\\n\",m1x[i],m1y[i],m2x[i],m2y[i],r[i],main(m1x[i],m1y[i],m2x[i],m2y[i],r[i]))\n    }\n    exit(0)\n}\nfunction main(m1x,m1y,m2x,m2y,r,  bx,by,pb,x,x1,y,y1) {\n    if (r == 0) { return(\"radius of zero gives no circles\") }\n    x = (m2x - m1x) \/ 2\n    y = (m2y - m1y) \/ 2\n    bx = m1x + x\n    by = m1y + y\n    pb = sqrt(x^2 + y^2)\n    if (pb == 0) { return(\"coincident points give infinite circles\") }\n    if (pb > r) { return(\"points are too far apart for the given radius\") }\n    cb = sqrt(r^2 - pb^2)\n    x1 = y * cb \/ pb\n    y1 = x * cb \/ pb\n    return(sprintf(\"%7.4f %7.4f %7.4f %7.4f\",bx-x1,by+y1,bx+x1,by-y1))\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":2486}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n    srand()  # randomize the RNG\n\tfor (;;) {\n\t\tprint n = int(rand() * 20)\n\t\tif (n == 10)\n\t\t\tbreak\n\t\tprint int(rand() * 20)\n\t}\n}\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":2487}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f DAY_OF_THE_WEEK.AWK\n# runtime does not support years > 2037 on my 32-bit Windows XP O\/S\nBEGIN {\n    for (i=2008; i<=2121; i++) {\n      x = strftime(\"%Y\/%m\/%d %a\",mktime(sprintf(\"%d 12 25 0 0 0\",i)))\n      if (x ~ \/Sun\/) { print(x) }\n    }\n}\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":2488}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk 'BEGIN{split(\"a b c d c b a\",a);for(i in a)b[a[i]]=1;r=\"\";for(i in b)r=r\" \"i;print r}'\na b c d\n\n","human_summarization":"\"Removes duplicate elements from an array using three possible methods: hashing, sorting and removing consecutive duplicates, or checking the rest of the list for each element. The output is a string representation of a new array with unique elements only.\"","id":2489}
    {"lang_cluster":"AWK","source_code":"\n# the following qsort implementation extracted from:\n#\n#       ftp:\/\/ftp.armory.com\/pub\/lib\/awk\/qsort\n#\n# Copyleft GPLv2 John DuBois\n#\n# @(#) qsort 1.2.1 2005-10-21\n# 1990 john h. dubois iii (john@armory.com)\n#\n# qsortArbIndByValue(): Sort an array according to the values of its elements.\n#\n# Input variables:\n#\n# Arr[] is an array of values with arbitrary (associative) indices.\n#\n# Output variables:\n#\n# k[] is returned with numeric indices 1..n.  The values assigned to these\n# indices are the indices of Arr[], ordered so that if Arr[] is stepped\n# through in the order Arr[k[1]] .. Arr[k[n]], it will be stepped through in\n# order of the values of its elements.\n#\n# Return value: The number of elements in the arrays (n).\n#\n# NOTES:\n#\n# Full example for accessing results:\n#\n#       foolist[\"second\"] = 2;\n#       foolist[\"zero\"] = 0;\n#       foolist[\"third\"] = 3;\n#       foolist[\"first\"] = 1;\n#\n#       outlist[1] = 0;\n#       n = qsortArbIndByValue(foolist, outlist)\n#\n#       for (i = 1; i <= n; i++) {\n#               printf(\"item at %s has value %d\\n\", outlist[i], foolist[outlist[i]]);\n#       }\n#      delete outlist; \n#\nfunction qsortArbIndByValue(Arr, k,\n                            ArrInd, ElNum)\n{\n        ElNum = 0;\n        for (ArrInd in Arr) {\n                k[++ElNum] = ArrInd;\n        }\n        qsortSegment(Arr, k, 1, ElNum);\n        return ElNum;\n}\n#\n# qsortSegment(): Sort a segment of an array.\n#\n# Input variables:\n#\n# Arr[] contains data with arbitrary indices.\n#\n# k[] has indices 1..nelem, with the indices of Arr[] as values.\n#\n# Output variables:\n#\n# k[] is modified by this function.  The elements of Arr[] that are pointed to\n# by k[start..end] are sorted, with the values of elements of k[] swapped\n# so that when this function returns, Arr[k[start..end]] will be in order.\n#\n# Return value: None.\n#\nfunction qsortSegment(Arr, k, start, end,\n                      left, right, sepval, tmp, tmpe, tmps)\n{\n        if ((end - start) < 1) {        # 0 or 1 elements\n                return;\n        }\n        # handle two-element case explicitly for a tiny speedup\n        if ((end - start) == 1) {\n                if (Arr[tmps = k[start]] > Arr[tmpe = k[end]]) {\n                        k[start] = tmpe;\n                        k[end] = tmps;\n                }\n                return;\n        }\n        # Make sure comparisons act on these as numbers\n        left = start + 0;\n        right = end + 0;\n        sepval = Arr[k[int((left + right) \/ 2)]];\n        # Make every element <= sepval be to the left of every element > sepval\n        while (left < right) {\n                while (Arr[k[left]] < sepval) {\n                        left++;\n                }\n                while (Arr[k[right]] > sepval) {\n                        right--;\n                }\n                if (left < right) {\n                        tmp = k[left];\n                        k[left++] = k[right];\n                        k[right--] = tmp;\n                }\n        }\n        if (left == right)\n                if (Arr[k[left]] < sepval) {\n                        left++;\n                } else {\n                        right--;\n                }\n        if (start < right) {\n                qsortSegment(Arr, k, start, right);\n        }\n        if (left < end) {\n                qsortSegment(Arr, k, left, end);\n        }\n}\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":2490}
    {"lang_cluster":"AWK","source_code":"\nWorks with: Gawk\n$ awk 'BEGIN{t=systime();print strftime(\"%Y-%m-%d\",t)\"\\n\"strftime(\"%A, %B %d, %Y\",t)}'\n2009-05-15\nFriday, May 15, 2009\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":2491}
    {"lang_cluster":"AWK","source_code":"\ncat power_set.awk\n#!\/usr\/local\/bin\/gawk -f\n\n# User defined function\nfunction tochar(l,n,\tr) {\n while (l) { n--; if (l%2 != 0) r = r sprintf(\" %c \",49+n); l = int(l\/2) }; return r\n}\n\n# For each input\n{ for (i=0;i<=2^NF-1;i++) if (i == 0) printf(\"empty\\n\"); else printf(\"(%s)\\n\",tochar(i,NF)) }\n\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":2492}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f ROMAN_NUMERALS_ENCODE.AWK\nBEGIN {\n    leng = split(\"1990 2008 1666\",arr,\" \")\n    for (i=1; i<=leng; i++) {\n      n = arr[i]\n      printf(\"%s = %s\\n\",n,dec2roman(n))\n    }\n    exit(0)\n}\nfunction dec2roman(number,  v,w,x,y,roman1,roman10,roman100,roman1000) {\n    number = int(number) # force to integer\n    if (number < 1 || number > 3999) { # number is too small | big\n      return\n    }\n    split(\"I II III IV V VI VII VIII IX\",roman1,\" \")   # 1 2 ... 9\n    split(\"X XX XXX XL L LX LXX LXXX XC\",roman10,\" \")  # 10 20 ... 90\n    split(\"C CC CCC CD D DC DCC DCCC CM\",roman100,\" \") # 100 200 ... 900\n    split(\"M MM MMM\",roman1000,\" \")                    # 1000 2000 3000\n    v = (number - (number % 1000)) \/ 1000\n    number = number % 1000\n    w = (number - (number % 100)) \/ 100\n    number = number % 100\n    x = (number - (number % 10)) \/ 10\n    y = number % 10\n    return(roman1000[v] roman100[w] roman10[x] roman1[y])\n}\n\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":2493}
    {"lang_cluster":"AWK","source_code":"\n\nBEGIN {\n  # to make an array, assign elements to it\n  array[1] = \"first\"\n  array[2] = \"second\"\n  array[3] = \"third\"\n  alen = 3  # want the length? store in separate variable\n\n  # or split a string\n  plen = split(\"2 3 5 7 11 13 17 19 23 29\", primes)\n  clen = split(\"Ottawa;Washington DC;Mexico City\", cities, \";\")\n\n  # retrieve an element\n  print \"The 6th prime number is \" primes[6]\n\n  # push an element\n  cities[clen += 1] = \"New York\"\n\n  dump(\"An array\", array, alen)\n  dump(\"Some primes\", primes, plen)\n  dump(\"A list of cities\", cities, clen)\n}\n\nfunction dump(what, array, len,    i) {\n  print what;\n\n  # iterate an array in order\n  for (i = 1; i <= len; i++) {\n    print \"  \" i \": \" array[i]\n  }\n}\n\n\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. They create both fixed-length and dynamic arrays, assign values to them, and retrieve an element from them. The codes also show how to push a value into a dynamic array. In the context of AWK, every array is an associative array and the array subscripts can start at 1 or any other integer. The codes also utilize the built-in split() function to create arrays that start at 1.","id":2494}
    {"lang_cluster":"AWK","source_code":"\n\nBEGIN {\n  while ( (getline <\"input.txt\") > 0 ) {\n    print >\"output.txt\"\n  }\n}\n\n","human_summarization":"demonstrate how to read contents from \"input.txt\" file into an intermediate variable and then write the contents of this variable into a new file called \"output.txt\". The codes do not handle binary files properly.","id":2495}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n  a = \"alphaBETA\";\n  print toupper(a), tolower(a)\n}\n\n\nBEGIN {\n  a = \"alphaBETA\"; \n  print toupper(substr(a, 1, 1)) tolower(substr(a, 2))\n}\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default encoding of a string literal or plain ASCII. The code also showcases additional case conversion functions such as swapping case, capitalizing the first letter, etc. available in the language's library. It also notes that in some languages, the toLower and toUpper functions may not be reversible.","id":2496}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f CLOSEST-PAIR_PROBLEM.AWK\nBEGIN {\n    x[++n] = 0.654682 ; y[n] = 0.925557\n    x[++n] = 0.409382 ; y[n] = 0.619391\n    x[++n] = 0.891663 ; y[n] = 0.888594\n    x[++n] = 0.716629 ; y[n] = 0.996200\n    x[++n] = 0.477721 ; y[n] = 0.946355\n    x[++n] = 0.925092 ; y[n] = 0.818220\n    x[++n] = 0.624291 ; y[n] = 0.142924\n    x[++n] = 0.211332 ; y[n] = 0.221507\n    x[++n] = 0.293786 ; y[n] = 0.691701\n    x[++n] = 0.839186 ; y[n] = 0.728260\n    min = 1E20\n    for (i=1; i<=n-1; i++) {\n      for (j=i+1; j<=n; j++) {\n        dsq = (x[i]-x[j])^2 + (y[i]-y[j])^2\n        if (dsq < min) {\n          min = dsq\n          mini = i\n          minj = j\n        }\n      }\n    }\n    printf(\"distance between (%.6f,%.6f) and (%.6f,%.6f) is %g\\n\",x[mini],y[mini],x[minj],y[minj],sqrt(min))\n    exit(0)\n}\n\n\n","human_summarization":"provide two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute force algorithm with a complexity of O(n^2) to find the two closest points. The second function uses a recursive divide and conquer approach with a complexity of O(n log n) to find the two closest points. Both functions return the minimum distance and the pair of points.","id":2497}
    {"lang_cluster":"AWK","source_code":"\n\na[0]=\"hello\"\n\n\nsplit(\"one two three\",a)\n\n\nprint a[0]\n\n\nfor(i in a) print i\":\"a[i]\n\n","human_summarization":"create a collection in a statically-typed language, add a few values to it, and provide examples of how to access and iterate over the elements. The code also discusses the concept of collections in the context of awk, where arrays serve a similar purpose.","id":2498}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk 'BEGIN{for(i=1;i<=10;i++){printf i;if(i<10)printf \", \"};print}'\n\n\n","human_summarization":"generates a comma-separated list from 1 to 10 using separate output statements for the number and the comma within the loop body.","id":2499}
    {"lang_cluster":"AWK","source_code":"\n#!\/usr\/bin\/awk -f\n{ pos=index($2,$1)\n print $2, (pos==1 ? \"begins\" : \"does not begin\" ), \"with \" $1\n print $2, (pos ? \"contains an\" : \"does not contain\" ), \"\\\"\" $1 \"\\\"\"\n if (pos) {\n\tl=length($1)\n\tPos=pos\n\ts=$2\n\twhile (Pos){\n\t\tprint \" \" $1 \" is at index\", x+Pos\n\t\tx+=Pos\n\t\ts=substr(s,Pos+l)\n\t\tPos=index(s,$1)\n\t}\n }\n print $2, (substr($2,pos)==$1 ? \"ends\" : \"does not end\"), \"with \" $1\n}\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":2500}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f 4-RINGS_OR_4-SQUARES_PUZZLE.AWK\n# converted from C\nBEGIN {\n    cmd = \"SORT \/+16\"\n    four_squares(1,7,1,1)\n    four_squares(3,9,1,1)\n    four_squares(0,9,0,0)\n    four_squares(0,6,1,0)\n    four_squares(2,8,1,0)\n    exit(0)\n}\nfunction four_squares(plo,phi,punique,pshow) {\n    lo = plo\n    hi = phi\n    unique = punique\n    show = pshow\n    solutions = 0\n    print(\"\")\n    if (show) {\n      print(\"A B C D E F G  sum  A+B B+C+D D+E+F F+G\")\n      print(\"-------------  ---  -------------------\")\n    }\n    acd()\n    close(cmd)\n    tmp = (unique) ? \"unique\" : \"non-unique\"\n    printf(\"%d-%d: %d %s solutions\\n\",lo,hi,solutions,tmp)\n}\nfunction acd() {\n    for (c=lo; c<=hi; c++) {\n      for (d=lo; d<=hi; d++) {\n        if (!unique || c != d) {\n          a = c + d\n          if (a >= lo && a <= hi && (!unique || (c != 0 && d != 0))) {\n            ge()\n          }\n        }\n      }\n    }\n}\nfunction bf() {\n    for (f=lo; f<=hi; f++) {\n      if (!unique || (f != a && f != c && f != d && f != g && f != e)) {\n        b = e + f - c\n        if (b >= lo && b <= hi && (!unique || (b != a && b != c && b != d && b != g && b != e && b != f))) {\n          solutions++\n          if (show) {\n            printf(\"%d %d %d %d %d %d %d %4d  \",a,b,c,d,e,f,g,a+b) | cmd\n            printf(\"%d+%d \",a,b) | cmd\n            printf(\"%d+%d+%d \",b,c,d) | cmd\n            printf(\"%d+%d+%d \",d,e,f) | cmd\n            printf(\"%d+%d\\n\",f,g) | cmd\n          }\n        }\n      }\n    }\n}\nfunction ge() {\n    for (e=lo; e<=hi; e++) {\n      if (!unique || (e != a && e != c && e != d)) {\n        g = d + e\n        if (g >= lo && g <= hi && (!unique || (g != a && g != c && g != d && g != e))) {\n          bf()\n        }\n      }\n    }\n}\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":2501}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f DRAW_A_CLOCK.AWK [-v xc=\"*\"]\nBEGIN {\n#   clearscreen_cmd = \"clear\"\u00a0; sleep_cmd = \"sleep 1s\" # Unix\n    clearscreen_cmd = \"CLS\" ; sleep_cmd = \"TIMEOUT \/T 1 >NUL\" # MS-Windows\n    clock_build_digits()\n    while (1) {\n      now = strftime(\"%H:%M:%S\")\n      t[1] = substr(now,1,1)\n      t[2] = substr(now,2,1)\n      t[3] = 10\n      t[4] = substr(now,4,1)\n      t[5] = substr(now,5,1)\n      t[6] = 10\n      t[7] = substr(now,7,1)\n      t[8] = substr(now,8,1)\n      if (prev_now != now) {\n        system(clearscreen_cmd)\n        for (v=1; v<=8; v++) {\n          printf(\"\\t\")\n          for (h=1; h<=8; h++) {\n            printf(\"%-8s\",a[t[h],v])\n          }\n          printf(\"\\n\")\n        }\n        prev_now = now\n      }\n      system(sleep_cmd)\n    }\n    exit(0)\n}\nfunction clock_build_digits(  arr,i,j,x,y) {\n    arr[1] = \" 0000     1    2222   3333      4  555555  6666   777777 8888   9999         \"\n    arr[2] = \"0    0   11   2    2 3    3    44  5      6      7     78    8 9    9        \"\n    arr[3] = \"0   00  1 1        2      3   4 4  5      6           7 8    8 9    9  \u00a0::   \"\n    arr[4] = \"0  0 0    1       2    333   4  4  555555 66666      7   8888  9    9  \u00a0::   \"\n    arr[5] = \"0 0  0    1     22        3 444444      5 6    6    7   8    8  99999        \"\n    arr[6] = \"00   0    1    2          3     4       5 6    6   7    8    8      9  \u00a0::   \"\n    arr[7] = \"0    0    1   2      3    3     4  5    5 6    6  7     8    8      9  \u00a0::   \"\n    arr[8] = \" 0000  1111111222222  3333      4   5555   6666   7      8888   9999         \"\n    for (i=1; i<=8; i++) {\n      if (xc != \"\") {\n        gsub(\/[0-9:]\/,substr(xc,1,1),arr[i]) # change \"0-9\" and \":\" to substitution character\n      }\n      y++\n      x = -1\n      for (j=1; j<=77; j=j+7) {\n        a[++x,y] = substr(arr[i],j,7)\n      }\n    }\n}\n\n\nSample run and output:\nGAWK -f DRAW_A_CLOCK.AWK -v xc=\"#\"\n\n         ####    ####              #     ####            ####    ####\n        #    #  #    #            ##    #    #          #    #  #    #\n        #   ##  #    #    ##     # #    #    #    ##    #   ##  #   ##\n        #  # #   ####     ##       #    #    #    ##    #  # #  #  # #\n        # #  #  #    #             #     #####          # #  #  # #  #\n        ##   #  #    #    ##       #         #    ##    ##   #  ##   #\n        #    #  #    #    ##       #         #    ##    #    #  #    #\n         ####    ####           #######  ####            ####    ####\n\n","human_summarization":"illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.","id":2502}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f PYTHAGOREAN_TRIPLES.AWK\n# converted from Go\nBEGIN {\n    printf(\"%5s %11s %11s %11s %s\\n\",\"limit\",\"limit\",\"triples\",\"primitives\",\"seconds\")\n    for (max_peri=10; max_peri<=1E9; max_peri*=10) {\n      t = systime()\n      prim = 0\n      total = 0\n      new_tri(3,4,5)\n      printf(\"10^%-2d %11d %11d %11d %d\\n\",++n,max_peri,total,prim,systime()-t)\n    }\n    exit(0)\n}\nfunction new_tri(s0,s1,s2,  p) {\n    p = s0 + s1 + s2\n    if (p <= max_peri) {\n      prim++\n      total += int(max_peri \/ p)\n      new_tri(+1*s0-2*s1+2*s2,+2*s0-1*s1+2*s2,+2*s0-2*s1+3*s2)\n      new_tri(+1*s0+2*s1+2*s2,+2*s0+1*s1+2*s2,+2*s0+2*s1+3*s2)\n      new_tri(-1*s0+2*s1+2*s2,-2*s0+1*s1+2*s2,-2*s0+2*s1+3*s2)\n    }\n}\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":2503}
    {"lang_cluster":"AWK","source_code":"\n# usage: awk -f letters.awk HolyBible.txt\n\nBEGIN { FS=\"\" }\n      { for(i=1;i<=NF;i++) m[$i]++}\nEND   { for(i in m) printf(\"%9d\u00a0%-14s\\n\", m[i],i) }\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":2504}
    {"lang_cluster":"AWK","source_code":"\n\nBEGIN {\n    NIL = 0\n    HEAD = 1\n    LINK = 1\n    VALUE = 2\n \n    delete list\n    initList()\n}\n\nfunction initList() {\n    delete list\n    list[HEAD] = makeNode(NIL, NIL)\n}\n\nfunction makeNode(link, value) {\n    return link SUBSEP value\n}\n\nfunction getNode(part, nodePtr,    linkAndValue) {\n    split(list[nodePtr], linkAndValue, SUBSEP)\n    return linkAndValue[part]\n}\n\n","human_summarization":"The code defines a data structure for a singly-linked list element, capable of holding a numeric value. It uses global associative arrays with numerical indexes as node pointers. The next node pointer is separated from the value by a pre-defined SUBSEP value. A function is used to access a node's next node pointer or value given a node pointer. The first array element serves as the list head.","id":2505}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f FACTORS_OF_AN_INTEGER.AWK\nBEGIN {\n    print(\"enter a number or C\/R to exit\")\n}\n{   if ($0 == \"\") { exit(0) }\n    if ($0 !~ \/^[0-9]+$\/) {\n      printf(\"invalid: %s\\n\",$0)\n      next\n    }\n    n = $0\n    printf(\"factors of %s:\",n)\n    for (i=1; i<=n; i++) {\n      if (n % i == 0) {\n        printf(\" %d\",i)\n      }\n    }\n    printf(\"\\n\")\n}\n\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":2506}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f ALIGN_COLUMNS.AWK ALIGN_COLUMNS.TXT\nBEGIN {\n    colsep = \" \" # separator between columns\n    report(\"raw data\")\n}\n{   printf(\"%s\\n\",$0)\n    arr[NR] = $0\n    n = split($0,tmp_arr,\"$\")\n    for (j=1; j<=n; j++) {\n      width = max(width,length(tmp_arr[j]))\n    }\n}\nEND {\n    report(\"left justified\")\n    report(\"right justified\")\n    report(\"center justified\")\n    exit(0)\n}\nfunction report(text,  diff,i,j,l,n,r,tmp_arr) {\n    printf(\"\\nreport: %s\\n\",text)\n    for (i=1; i<=NR; i++) {\n      n = split(arr[i],tmp_arr,\"$\")\n      if (tmp_arr[n] == \"\") { n-- }\n      for (j=1; j<=n; j++) {\n        if (text ~ \/^[Ll]\/) { # left\n          printf(\"%-*s%s\",width,tmp_arr[j],colsep)\n        }\n        else if (text ~ \/^[Rr]\/) { # right\n          printf(\"%*s%s\",width,tmp_arr[j],colsep)\n        }\n        else if (text ~ \/^[Cc]\/) { # center\n          diff = width - length(tmp_arr[j])\n          l = r = int(diff \/ 2)\n          if (diff != l + r) { r++ }\n          printf(\"%*s%s%*s%s\",l,\"\",tmp_arr[j],r,\"\",colsep)\n        }\n      }\n      printf(\"\\n\")\n    }\n}\nfunction max(x,y) { return((x > y) ? x : y) }\n\n\nreport: raw data\nGiven$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\n\nreport: left justified\nGiven      a          text       file       of         many       lines,     where      fields     within     a          line\nare        delineated by         a          single     'dollar'   character, write      a          program\nthat       aligns     each       column     of         fields     by         ensuring   that       words      in         each\ncolumn     are        separated  by         at         least      one        space.\nFurther,   allow      for        each       word       in         a          column     to         be         either     left\njustified, right      justified, or         center     justified  within     its        column.\n\nreport: right justified\n     Given          a       text       file         of       many     lines,      where     fields     within          a       line\n       are delineated         by          a     single   'dollar' character,      write          a    program\n      that     aligns       each     column         of     fields         by   ensuring       that      words         in       each\n    column        are  separated         by         at      least        one     space.\n  Further,      allow        for       each       word         in          a     column         to         be     either       left\njustified,      right justified,         or     center  justified     within        its    column.\n\nreport: center justified\n  Given        a         text       file        of        many      lines,     where      fields     within       a         line\n   are     delineated     by         a        single    'dollar'  character,   write        a       program\n   that      aligns      each      column       of       fields       by      ensuring     that      words        in        each\n  column      are     separated      by         at       least       one       space.\n Further,    allow       for        each       word        in         a        column       to         be       either      left\njustified,   right    justified,     or       center   justified    within      its      column.\n\n","human_summarization":"The code reads a text file, where each line contains fields separated by a dollar sign. It aligns each column of fields by ensuring at least one space between words in each column. The words in a column can be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. No additional separating characters are added between or around columns. The output is viewed in a mono-spaced font on a plain text editor or basic terminal.","id":2507}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f DRAW_A_CUBOID.AWK [-v x=?] [-v y=?] [-v z=?]\n# example: GAWK -f DRAW_A_CUBOID.AWK -v x=12 -v y=4 -v z=6\n# converted from VBSCRIPT\nBEGIN {\n    init_sides()\n    draw_cuboid(2,3,4)\n    draw_cuboid(1,1,1)\n    draw_cuboid(6,2,1)\n    exit (errors == 0) ? 0 : 1\n}\nfunction draw_cuboid(nx,ny,nz,  esf,i,i_max,j,j_max,lx,ly,lz) {\n    esf = errors # errors so far\n    if (nx !~ \/^[0-9]+$\/ || nx <= 0) { error(nx,ny,nz,1) }\n    if (ny !~ \/^[0-9]+$\/ || ny <= 0) { error(nx,ny,nz,2) }\n    if (nz !~ \/^[0-9]+$\/ || nz <= 0) { error(nx,ny,nz,3) }\n    if (errors > esf) { return }\n    lx = x * nx\n    ly = y * ny\n    lz = z * nz\n# define the array size\n    i_max = ly + lz\n    j_max = lx + ly\n    delete arr\n    printf(\"%s %s %s (%d rows x %d columns)\\n\",nx,ny,nz,i_max+1,j_max+1)\n# draw lines\n    for (i=0; i<=nz-1; i++) { draw_line(lx,0,z*i,\"-\") }\n    for (i=0; i<=ny; i++)   { draw_line(lx,y*i,lz+y*i,\"-\") }\n    for (i=0; i<=nx-1; i++) { draw_line(lz,x*i,0,\"|\") }\n    for (i=0; i<=ny; i++)   { draw_line(lz,lx+y*i,y*i,\"|\") }\n    for (i=0; i<=nz-1; i++) { draw_line(ly,lx,z*i,\"\/\") }\n    for (i=0; i<=nx; i++)   { draw_line(ly,x*i,lz,\"\/\") }\n# output the cuboid\n    for (i=i_max; i>=0; i--) {\n      for (j=0; j<=j_max; j++) {\n        printf(\"%1s\",arr[i,j])\n      }\n      printf(\"\\n\")\n    }\n}\nfunction draw_line(n,x,y,c,  dx,dy,i,xi,yi) {\n    if      (c == \"-\") { dx = 1 ; dy = 0 }\n    else if (c == \"|\") { dx = 0 ; dy = 1 }\n    else if (c == \"\/\") { dx = 1 ; dy = 1 }\n    for (i=0; i<=n; i++) {\n      xi = x + i * dx\n      yi = y + i * dy\n      arr[yi,xi] = (arr[yi,xi] ~ \/^\u00a0?$\/) ? c : \"+\"\n    }\n}\nfunction error(x,y,z,arg) {\n    printf(\"error: '%s,%s,%s' argument %d is invalid\\n\",x,y,z,arg)\n    errors++\n}\nfunction init_sides() {\n# to change the defaults on the command line use: -v x=? -v y=? -v z=?\n    if (x+0 < 2) { x = 6 } # top\n    if (y+0 < 2) { y = 2 } # right\n    if (z+0 < 2) { z = 3 } # front\n}\n\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":2508}
    {"lang_cluster":"AWK","source_code":"\nWorks with: gawk\n# usage: awk -f rot13.awk \nBEGIN {\n  for(i=0; i < 256; i++) {\n    amap[sprintf(\"%c\", i)] = i\n  }\n  for(l=amap[\"a\"]; l <= amap[\"z\"]; l++) {\n    rot13[l] = sprintf(\"%c\", (((l-amap[\"a\"])+13) % 26 ) + amap[\"a\"])\n  }\n  FS = \"\"\n}\n{\n  o = \"\"\n  for(i=1; i <= NF; i++) {\n    if ( amap[tolower($i)] in rot13 ) {\n      c = rot13[amap[tolower($i)]]\n      if ( tolower($i) != $i ) c = toupper(c)\n      o = o c\n    } else {\n      o = o $i\n    }\n  }\n  print o\n}\n\n\nInput:\nHello, HAL\u00a0!\n\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":2509}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f SORT_AN_ARRAY_OF_COMPOSITE_STRUCTURES.AWK\nBEGIN {\n# AWK lacks structures but one can be simulated using an associative array.\n    arr[\"eight  8 \"]\n    arr[\"two    2 \"]\n    arr[\"five   5 \"]\n    arr[\"nine   9 \"]\n    arr[\"one    1 \"]\n    arr[\"three  3 \"]\n    arr[\"six    6 \"]\n    arr[\"seven  7 \"]\n    arr[\"four   4 \"]\n    arr[\"ten    10\"]\n    arr[\"zero   0 \"]\n    arr[\"twelve 12\"]\n    arr[\"minus2 -2\"]\n    show(1,7,\"@val_str_asc\",\"name\") # use name part of name-value pair\n    show(8,9,\"@val_num_asc\",\"value\") # use value part of name-value pair\n    exit(0)\n}\nfunction show(a,b,sequence,description,  i,x) {\n    PROCINFO[\"sorted_in\"] = \"@unsorted\"\n    for (i in arr) {\n      x = substr(i,a,b)\n      sub(\/ +\/,\"\",x)\n      arr[i] = x\n    }\n    PROCINFO[\"sorted_in\"] = sequence\n    printf(\"sorted by %s:\",description)\n    for (i in arr) {\n      printf(\" %s\",arr[i])\n    }\n    printf(\"\\n\")\n}\n\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":2510}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n  for(i=1; i < 6; i++) {\n    for(j=1; j <= i; j++ ) {\n      printf \"*\"\n    }\n    print\n  }\n}\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":2511}
    {"lang_cluster":"AWK","source_code":"\n\nBEGIN {\n  a[\"red\"] = 0xff0000\n  a[\"green\"] = 0x00ff00\n  a[\"blue\"] = 0x0000ff\n  for (i in a) {\n    printf \"%8s %06x\\n\", i, a[i] \n  }\n  # deleting a key\/value\n  delete a[\"red\"]\n  for (i in a) {\n    print i\n  }\n  # check if a key exists\n  print ( \"red\" in a )   # print 0\n  print ( \"blue\" in a )  # print 1\n}\n\n","human_summarization":"create an associative array (dictionary, map, or hash) in AWK.","id":2512}
    {"lang_cluster":"AWK","source_code":"\n\nfunction halve(x)\n{\n  return int(x\/2)\n}\n\nfunction double(x)\n{\n  return x*2\n}\n\nfunction iseven(x)\n{\n  return x%2 == 0\n}\n\nfunction ethiopian(plier, plicand)\n{\n  r = 0\n  while(plier >= 1) {\n    if ( !iseven(plier) ) {\n      r += plicand\n    }\n    plier = halve(plier)\n    plicand = double(plicand)\n  }\n  return r\n}\n\nBEGIN {\n  print ethiopian(17, 34)\n}\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are then used to implement Ethiopian multiplication, a method of multiplying integers using only addition, doubling, and halving. The multiplication process involves repeatedly halving and doubling the two input numbers, discarding rows where the halved number is even, and summing the remaining doubled numbers to get the multiplication result.","id":2513}
    {"lang_cluster":"AWK","source_code":"\n\nfunction fact_r(n)\n{\n  if ( n <= 1 ) return 1;\n  return n*fact_r(n-1);\n}\n\n\nfunction fact(n)\n{\n  if ( n < 1 ) return 1;\n  r = 1\n  for(m = 2; m <= n; m++) {\n    r *= m;\n  }\n  return r\n}\n\n","human_summarization":"The code calculates the factorial of a given number either iteratively or recursively. It may optionally handle errors for negative input values. The factorial is the product of all positive integers from 1 to the given number.","id":2514}
    {"lang_cluster":"AWK","source_code":"\n# Usage: GAWK -f BULLS_AND_COWS.AWK\nBEGIN {\n    srand()\n    secret = \"\"\n    for (i = 1; i <= 4; ) {\n        digit = int(9 * rand()) + 1\n        if (index(secret, digit) == 0) {\n            secret = secret digit\n            i++\n        }\n    }\n    print \"Welcome to 'Bulls and Cows'!\"\n    print \"I thought of a 4-digit number.\"\n    print \"Please enter your guess.\"\n}\niswellformed($0) {\n    if (calcscore($0, secret)) {\n        exit\n    }\n}\nfunction iswellformed(number,    i, digit) {\n    if (number !~ \/[1-9][1-9][1-9][1-9]\/) {\n        print \"Your guess should contain 4 digits, each from 1 to 9. Try again!\"\n        return 0\n    }\n    for (i = 1; i <= 3; i++) {\n        digit = substr(number, 1, 1)\n        number = substr(number, 2)\n        if (index(number, digit) != 0) {\n            print \"Your guess contains a digit twice. Try again!\"\n            return 0\n        }\n    }\n    return 1\n}\nfunction calcscore(guess, secret,    bulls, cows, i, idx) {\n    # Bulls = correct digits at the right position\n    # Cows = correct digits at the wrong position\n    for (i = 1; i <= 4; i++) {\n        idx = index(secret, substr(guess, i, 1))\n        if (idx == i) {\n            bulls++\n        } else if (idx > 0) {\n            cows++\n        }\n    }\n    printf(\"Your score for this guess: Bulls = %d, Cows = %d.\", bulls, cows)\n    if (bulls < 4) {\n        printf(\" Try again!\\n\")\n    } else {\n        printf(\"\\nCongratulations, you win!\\n\")\n    }\n    return bulls == 4\n}\n\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":2515}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk 'func r(){return sqrt(-2*log(rand()))*cos(6.2831853*rand())}BEGIN{for(i=0;i<1000;i++)s=s\" \"1+0.5*r();print s}'\n\n\nfunction r() {\n  return sqrt( -2*log( rand() ) ) * cos(6.2831853*rand() )\n}\n\nBEGIN {\n  n=1000\n  for(i=0;i<n;i++) {\n    x = 1 + 0.5*r()\n    s = s\" \"x\n  }\n  print s\n}\n\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using a library that may only generate uniformly distributed random numbers.","id":2516}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f DOT_PRODUCT.AWK\nBEGIN {\n    v1 = \"1,3,-5\"\n    v2 = \"4,-2,-1\"\n    if (split(v1,v1arr,\",\") != split(v2,v2arr,\",\")) {\n      print(\"error: vectors are of unequal lengths\")\n      exit(1)\n    }\n    printf(\"%g\\n\",dot_product(v1arr,v2arr))\n    exit(0)\n}\nfunction dot_product(v1,v2,  i,sum) {\n    for (i in v1) {\n      sum += v1[i] * v2[i]\n    }\n    return(sum)\n}\n\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":2517}
    {"lang_cluster":"AWK","source_code":"\n\n{ print $0 }\n\n\n1\n\n","human_summarization":"\"Read and print data from a text stream either word-by-word or line-by-line until the end of the stream is reached.\"","id":2518}
    {"lang_cluster":"AWK","source_code":"\n\nWorks with: Gawk\n$ awk 'BEGIN{print systime(),strftime()}'\n\n\n","human_summarization":"the system time in a specified unit. This can be useful for debugging, network information, generating random number seeds, or measuring program performance. The system time is retrieved either through a system command or a built-in language function. The code may also be related to the task of date formatting and retrieving system time.","id":2519}
    {"lang_cluster":"AWK","source_code":"\n\nfunction ord(a)\n{\n  return amap[a]\n}\n\nfunction sedol_checksum(sed)\n{\n  sw[1] = 1; sw[2] = 3; sw[3] = 1\n  sw[4] = 7; sw[5] = 3; sw[6] = 9\n  sum = 0\n  for(i=1; i <= 6; i++) {\n    c = substr(toupper(sed), i, 1)\n    if ( c ~ \/[[:digit:]]\/ ) {\n      sum += c*sw[i]\n    } else {\n      sum += (ord(c)-ord(\"A\")+10)*sw[i]\n    }\n  }\n  return (10 - (sum % 10)) % 10\n}\n\nBEGIN { # prepare amap for ord\n  for(_i=0;_i<256;_i++) {\n    astr = sprintf(\"%c\", _i)\n    amap[astr] = _i\n  }\n}\n\n\/[AEIOUaeiou]\/ {\n  print \"'\" $0 \"' not a valid SEDOL code\"\n  next\n}\n{\n  if ( (length($0) > 7) || (length($0) < 6) ) {\n    print \"'\" $0 \"' is too long or too short to be valid SEDOL\"\n    next\n  }\n  sedol = substr($0, 1, 6)\n  sedolcheck = sedol_checksum(sedol)\n  if ( length($0) == 7 ) {\n    if ( (sedol sedolcheck) != $0 ) {\n      print sedol sedolcheck \" (original \" $0 \" has wrong check digit\"\n    } else {\n      print sedol sedolcheck\n    }\n  } else {\n    print sedol sedolcheck\n  }\n}\n\n","human_summarization":"The code takes a list of 6-digit SEDOL numbers as input, calculates the checksum digit for each number, and appends it to the respective number. It also validates the input to ensure it contains only valid characters allowed in a SEDOL string. The updated SEDOL codes are then outputted.","id":2520}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f DRAW_A_SPHERE.AWK\n# converted from VBSCRIPT\nBEGIN {\n    draw_sphere(20,4,0.1)\n    draw_sphere(10,2,0.4)\n    exit(0)\n}\nfunction draw_sphere(radius,k,ambient, b,i,intensity,j,leng_shades,light,line,shades,vec,x,y) {\n    leng_shades = split0(\".:!*oe&#%@\",shades,\"\")\n    split(\"30,30,-50\",light,\",\")\n    normalize(light)\n    for (i=int(-radius); i<=ceil(radius); i++) {\n      x = i + 0.5\n      line = \"\"\n      for (j=int(-2*radius); j<=ceil(2*radius); j++) {\n        y = j \/ 2 + 0.5\n        if (x*x + y*y <= radius*radius) {\n          vec[1] = x\n          vec[2] = y\n          vec[3] = sqrt(radius*radius - x*x - y*y)\n          normalize(vec)\n          b = dot(light,vec) ^ k + ambient\n          intensity = int((1-b) * leng_shades)\n          if (intensity < 0) {\n            intensity = 0\n          }\n          if (intensity >= leng_shades) {\n            intensity = leng_shades\n          }\n          line = line shades[intensity]\n        }\n        else {\n          line = line \" \"\n        }\n      }\n      printf(\"%s\\n\",line)\n    }\n}\nfunction ceil(x,  tmp) {\n    tmp = int(x)\n    return (tmp != x) ? tmp+1 : tmp\n}\nfunction dot(x,y,  tmp) {\n    tmp = x[1]*y[1] + x[2]*y[2] + x[3]*y[3]\n    return (tmp < 0) ? -tmp : 0\n}\nfunction normalize(v,  tmp) {\n    tmp = sqrt(v[1]*v[1] + v[2]*v[2] + v[3]*v[3])\n    v[1] \/= tmp\n    v[2] \/= tmp\n    v[3] \/= tmp\n}\nfunction split0(str,array,fs,  arr,i,n) { # same as split except indices start at zero\n    n = split(str,arr,fs)\n    for (i=1; i<=n; i++) {\n      array[i-1] = arr[i]\n    }\n    return(n)\n}\n\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":2521}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f NTH.AWK\nBEGIN {\n    prn(0,25)\n    prn(250,265)\n    prn(1000,1025)\n    exit(0)\n}\nfunction prn(start,stop,  i) {\n    printf(\"%d-%d: \",start,stop)\n    for (i=start; i<=stop; i++) {\n      printf(\"%d%s \",i,nth(i))\n    }\n    printf(\"\\n\")\n}\nfunction nth(yearday,  nthday) {\n    if (yearday ~ \/1[1-3]$\/) {         # 11th,12th,13th\n      nthday = \"th\"\n    }\n    else if (yearday ~ \/1$\/) {         # 1st,21st,31st,etc.\n      nthday = \"st\"\n    }\n    else if (yearday ~ \/2$\/) {         # 2nd,22nd,32nd,etc.\n      nthday = \"nd\"\n    }\n    else if (yearday ~ \/3$\/) {         # 3rd,23rd,33rd,etc.\n      nthday = \"rd\"\n    }\n    else if (yearday ~ \/[0456789]$\/) { # 4th-10th,20th,24th-30th,etc.\n      nthday = \"th\"\n    }\n    return(nthday)\n}\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":2522}
    {"lang_cluster":"AWK","source_code":"\n#!\/usr\/bin\/awk -f \nBEGIN {\n   x = \"She was a soul stripper. She took my heart!\";\n   print x;\n   gsub(\/[aei]\/,\"\",x);\n   print x;\n}\n\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":2523}
    {"lang_cluster":"AWK","source_code":"\n\nFirst, we get the parameters, and\ngenerate a file with the list of numbers (writing directly to that file)\ngenerate a custom awk-program for that special case (redirecting standard-output)\nthe custom program is run, and does the actual work to output the desired result\n\n105\n3 Fizz\n5 Buzz\n7 Baxx\nUsage\n\nawk  -f fizzbuzzGenerate.awk  input.txt > fizzbuzzCustom.awk\nawk  -f fizzbuzzCustom.awk  numbers.txt\n\nProgram\n\n# usage:  awk -f fizzbuzzGen.awk > fizzbuzzCustom.awk\n#\nfunction Print(s) {\n    print s > \"\/dev\/stderr\"\n}\n\nBEGIN { Print( \"# FizzBuzz-Generate:\" )\n        q2 = \"\\\"\"\n        fN = \"numbers.txt\"\n       #fP = \"fizzbuzzCustom.awk\"\n}\n\nNF==1 { Print( \"# \" $1 \" Numbers:\" )\n        for( i=1; i <= $1; i++ )\n            print( i ) > fN   # (!!) write to file not allowed in sandbox at ideone.com\n\n        Print( \"# Custom program:\" )\n        print \"BEGIN {print \" q2 \"# CustomFizzBuzz:\" q2 \"} \\n\"\n        next\n}\n\nNF==2 { Print( \"# \" $1 \"-->\" $2 )   ##\n        print \"$1\u00a0%  \"$1\" == 0 {x = x \"q2 $2 q2 \"}\"\n        next\n}\n\nEND {  print \"\"\n       print \"!x  {print $1; next}\"\n       print \"    {print \" q2 \" \" q2 \", x; x=\" q2 q2 \"} \\n\"\n\n       print \"END {print \" q2 \"# Done.\" q2 \"}\"\n       Print( \"# Done.\" )\n}\n\n\n","human_summarization":"The code takes a maximum number and a list of factors with corresponding words as input from the user. It then prints numbers from 1 to the maximum number, replacing multiples of the given factors with the corresponding words. If a number is a multiple of more than one factor, all corresponding words are printed in order of the factors. For example, if the maximum number is 20 and the factors are 3 (Fizz), 5 (Buzz), and 7 (Baxx), the output will replace multiples of 3 with \"Fizz\", multiples of 5 with \"Buzz\", and multiples of 7 with \"Baxx\". If a number is a multiple of both 3 and 5, it will print \"FizzBuzz\".","id":2524}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f STRING_PREPEND.AWK\nBEGIN {\n    s = \"bar\"\n    s = \"foo\" s\n    print(s)\n    exit(0)\n}\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":2525}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f GUESS_THE_NUMBER.AWK\nBEGIN {\n    srand()\n    n = int(rand() * 10) + 1\n    print(\"I am thinking of a number between 1 and 10. Try to guess it.\")\n    while (1) {\n      getline ans\n      if (ans !~ \/^[0-9]+$\/) {\n        print(\"Your input was not a number. Try again.\")\n        continue\n      }\n      if (n == ans) {\n        print(\"Well done you.\")\n        break\n      }\n      print(\"Incorrect. Try again.\")\n    }\n    exit(0)\n}\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":2526}
    {"lang_cluster":"AWK","source_code":"\nWorks with: gawk\n\n# syntax: GAWK -f GENERATE_LOWER_CASE_ASCII_ALPHABET.AWK\nBEGIN {\n    for (i=0; i<=255; i++) {\n      c = sprintf(\"%c\",i)\n      if (c ~ \/[[:lower:]]\/) {\n        lower_chars = lower_chars c\n      }\n    }\n    printf(\"%s %d: %s\\n\",ARGV[0],length(lower_chars),lower_chars)\n    exit(0)\n}\n\n\n","human_summarization":"generate an array, list, or string of all lower case ASCII characters from 'a' to 'z'. The code uses a reliable coding style suitable for large programs and employs strong typing if available. It avoids manual enumeration of characters to prevent bugs. The code also tests each character code to see if it matches the POSIX character class for \"lowercase\", taking into account locale settings and options such as --traditional and --posix.","id":2527}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n  print tobinary(0)\n  print tobinary(1)\n  print tobinary(5)\n  print tobinary(50)\n  print tobinary(9000)\n}\n\nfunction tobinary(num) {\n  outstr = num % 2\n  while (num = int(num \/ 2))\n    outstr = (num % 2) outstr\n  return outstr\n}\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":2528}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f MERGE_AND_AGGREGATE_DATASETS.AWK RC-PATIENTS.CSV RC-VISITS.CSV\n# files may appear in any order\n#\n# sorting:\n#   PROCINFO[\"sorted_in\"] is used by GAWK\n#   SORTTYPE is used by Thompson Automation's TAWK\n#\n{ # printf(\"%s %s\\n\",FILENAME,$0) # print input\n    split($0,arr,\",\")\n    if (FNR == 1) {\n      file = (arr[2] == \"LASTNAME\") ? \"patients\" : \"visits\"\n      next\n    }\n    patient_id_arr[key] = key = arr[1]\n    if (file == \"patients\") {\n      lastname_arr[key] = arr[2]\n    }\n    else if (file == \"visits\") {\n      if (arr[2] > visit_date_arr[key]) {\n        visit_date_arr[key] = arr[2]\n      }\n      if (arr[3] != \"\") {\n        score_arr[key] += arr[3]\n        score_count_arr[key]++\n      }\n    }\n}\nEND {\n    print(\"\")\n    PROCINFO[\"sorted_in\"] = \"@ind_str_asc\" ; SORTTYPE = 1\n    fmt = \"%-10s\u00a0%-10s\u00a0%-10s %9s %9s %6s\\n\"\n    printf(fmt,\"patient_id\",\"lastname\",\"last_visit\",\"score_sum\",\"score_avg\",\"scores\")\n    for (i in patient_id_arr) {\n      avg = (score_count_arr[i] > 0) ? score_arr[i] \/ score_count_arr[i] : \"\"\n      printf(fmt,patient_id_arr[i],lastname_arr[i],visit_date_arr[i],score_arr[i],avg,score_count_arr[i]+0)\n    }\n    exit(0)\n}\n\n\n","human_summarization":"\"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file.\"","id":2529}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f READ_A_CONFIGURATION_FILE.AWK\nBEGIN {\n    fullname = favouritefruit = \"\"\n    needspeeling = seedsremoved = \"false\"\n    fn = \"READ_A_CONFIGURATION_FILE.INI\"\n    while (getline rec <fn > 0) {\n      tmp = tolower(rec)\n      if (tmp ~ \/^ *fullname\/) { fullname = extract(rec) }\n      else if (tmp ~ \/^ *favouritefruit\/) { favouritefruit = extract(rec) }\n      else if (tmp ~ \/^ *needspeeling\/) { needspeeling = \"true\" }\n      else if (tmp ~ \/^ *seedsremoved\/) { seedsremoved = \"true\" }\n      else if (tmp ~ \/^ *otherfamily\/) { split(extract(rec),otherfamily,\",\") }\n    }\n    close(fn)\n    printf(\"fullname=%s\\n\",fullname)\n    printf(\"favouritefruit=%s\\n\",favouritefruit)\n    printf(\"needspeeling=%s\\n\",needspeeling)\n    printf(\"seedsremoved=%s\\n\",seedsremoved)\n    for (i=1; i<=length(otherfamily); i++) {\n      sub(\/^ +\/,\"\",otherfamily[i]) # remove leading spaces\n      sub(\/ +$\/,\"\",otherfamily[i]) # remove trailing spaces\n      printf(\"otherfamily(%d)=%s\\n\",i,otherfamily[i])\n    }\n    exit(0)\n}\nfunction extract(rec,  pos,str) {\n    sub(\/^ +\/,\"\",rec)       # remove leading spaces before parameter name\n    pos = match(rec,\/[= ]\/) # determine where data begins\n    str = substr(rec,pos)   # extract the data\n    gsub(\/^[= ]+\/,\"\",str)   # remove leading \"=\" and spaces\n    sub(\/ +$\/,\"\",str)       # remove trailing spaces\n    return(str)\n}\n\n\n","human_summarization":"read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.","id":2530}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f HAVERSINE_FORMULA.AWK\n# converted from Python\nBEGIN {\n    distance(36.12,-86.67,33.94,-118.40) # BNA to LAX\n    exit(0)\n}\nfunction distance(lat1,lon1,lat2,lon2,  a,c,dlat,dlon) {\n    dlat = radians(lat2-lat1)\n    dlon = radians(lon2-lon1)\n    lat1 = radians(lat1)\n    lat2 = radians(lat2)\n    a = (sin(dlat\/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon\/2))^2\n    c = 2 * atan2(sqrt(a),sqrt(1-a))\n    printf(\"distance:\u00a0%.4f km\\n\",6372.8 * c)\n}\nfunction radians(degree) { # degrees to radians\n    return degree * (3.1415926 \/ 180.)\n}\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":2531}
    {"lang_cluster":"AWK","source_code":"\nWorks with: gawk\nBEGIN {\n  site=\"en.wikipedia.org\"\n  path=\"\/wiki\/\"\n  name=\"Rosetta_Code\"\n\n  server = \"\/inet\/tcp\/0\/\" site \"\/80\"\n  print \"GET \" path name \" HTTP\/1.0\" |& server\n  print \"Host: \" site |& server\n  print \"\\r\\n\\r\\n\" |& server\n\n  while ( (server |& getline fish) > 0 ) {\n    if ( ++scale == 1 )\n      ship = fish\n    else\n      ship = ship \"\\n\" fish\n  }\n  close(server)\n\n  print ship\n}\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":2532}
    {"lang_cluster":"AWK","source_code":"\n#!\/usr\/bin\/awk -f\nBEGIN {\n    A[1] = 49927398716;\n    A[2] = 49927398717;\n    A[3] = 1234567812345678;\n    A[4] = 1234567812345670;\n    A[5] = \"01234567897\";\n    A[6] = \"01234567890\";\n    A[7] = \"00000000000\";\n    for (k in A) print \"isLuhn(\"A[k]\"): \",isLuhn(A[k]);\t\n}\n\nfunction isLuhn(cardno) {\n    s = 0;\n    m = \"0246813579\";\n    n = length(cardno);\n    for (k = n; 0 < k; k -= 2) {\n\ts += substr(cardno, k, 1);\n    }\n    for (k = n-1; 0 < k; k -= 2) {\n\ts += substr(m, substr(cardno, k, 1)+1, 1);\n    }\n    return ((s%10)==0);\t\n}\n\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":2533}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f JOSEPHUS_PROBLEM.AWK\n# converted from PL\/I\nBEGIN {\n    main(5,2,1)\n    main(41,3,1)\n    main(41,3,3)\n    exit(0)\n}\nfunction main(n,k,s,  dead,errors,found,i,killed,nn,p,survived) {\n# n - number of prisoners\n# k - kill every k'th prisoner\n# s - number of survivors\n    printf(\"\\nn=%d k=%d s=%d\\n\",n,k,s) # show arguments\n    if (s > n) { print(\"s>n\"); errors++ }\n    if (k <= 0) { print(\"k<=0\"); errors++ }\n    if (errors > 0) { return(0) }\n    nn = n                             # wrap around boundary\n    p = -1                             # start here\n    while (n != s) {                   # until survivor count is met\n      found = 0                        # start looking\n      while (found != k) {             # until we have the k-th prisoner\n        if (++p == nn) { p = 0 }       # wrap around\n        if (dead[p] != 1) { found++ }  # if prisoner is alive increment found\n      }\n      dead[p] = 1                      # kill the unlucky one\n      killed = killed p \" \"            # build killed list\n      n--                              # reduce size of circle\n    }\n    for (i=0; i<=nn-1; i++) {\n      if (dead[i] != 1) {\n        survived = survived i \" \"      # build survivor list\n      }\n    }\n    printf(\"killed: %s\\n\",killed)\n    printf(\"survived: %s\\n\",survived)\n    return(1)\n}\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":2534}
    {"lang_cluster":"AWK","source_code":"\nfunction repeat( str, n,    rep, i )\n{\n    for( ; i<n; i++ )\n        rep = rep str   \n    return rep\n}\n\nBEGIN {\n    print repeat( \"ha\", 5 )\n}\n\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":2535}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk '{if($0~\/[A-Z]\/)print \"uppercase detected\"}'\nabc\nABC\nuppercase detected\n\n\nawk '\/[A-Z]\/{print \"uppercase detected\"}'\ndef\nDeF\nuppercase detected\n\n\n$ awk '{gsub(\/[A-Z]\/,\"*\");print}'\nabCDefG\nab**ef*\n$ awk '{gsub(\/[A-Z]\/,\"(&)\");print}'\nabCDefGH\nab(C)(D)ef(G)(H)\n\n\n$ awk '{gsub(\/[A-Z]+\/,\"(&)\");print}'\nabCDefGH\nab(CD)ef(GH)\n\n\n print \"Match not found\"\n\n\n","human_summarization":"The code uses AWK's support for regular expressions to match and substitute parts of a string. It includes a condition part that triggers when a match is found in an input line. The substitution function uses a regular expression as its first argument and a constant replacement string. The code also features a variant that matches one or more uppercase letters and demonstrates how to achieve regular expression negation by combining the binding operator with a logical not operator.","id":2536}
    {"lang_cluster":"AWK","source_code":"\n\/^[ \\t]*-?[0-9]+[ \\t]+-?[0-9]+[ \\t]*$\/ {\n\tprint \"add:\", $1 + $2\n\tprint \"sub:\", $1 - $2\n\tprint \"mul:\", $1 * $2\n\tprint \"div:\", int($1 \/ $2) # truncates toward zero\n\tprint \"mod:\", $1 % $2      # same sign as first operand\n\tprint \"exp:\", $1 ^ $2\n\texit }\n\n\n","human_summarization":"take two integers as input from the user and calculate their sum, difference, product, integer quotient, remainder, and exponentiation (if applicable). The code does not include error handling. The rounding method for quotient and the sign for the remainder are specified. The code also includes an example of the integer 'divmod' operator. The behavior of division and modulus is similar to C, and the use of exponentiation operator is in accordance with the POSIX standard.","id":2537}
    {"lang_cluster":"AWK","source_code":"\n#\n# countsubstring(string, pattern)\n#   Returns number of occurrences of pattern in string\n#   Pattern treated as a literal string (regex characters not expanded)\n#\nfunction countsubstring(str, pat,    len, i, c) {\n  c = 0\n  if( ! (len = length(pat) ) ) \n    return 0\n  while(i = index(str, pat)) {\n    str = substr(str, i + len)\n    c++\n  }\n  return c\n}\n#\n# countsubstring_regex(string, regex_pattern)\n#   Returns number of occurrences of pattern in string\n#   Pattern treated as regex       \n#\nfunction countsubstring_regex(str, pat,    c) {\n  c = 0\n  c += gsub(pat, \"\", str)\n  return c\n}\nBEGIN {\n  print countsubstring(\"[do&d~run?d!run&>run&]\", \"run&\")\n  print countsubstring_regex(\"[do&d~run?d!run&>run&]\", \"run[&]\")\n  print countsubstring(\"the three truths\",\"th\")\n}\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":2538}
    {"lang_cluster":"AWK","source_code":"$ awk 'func hanoi(n,f,t,v){if(n>0){hanoi(n-1,f,v,t);print(f,\"->\",t);hanoi(n-1,v,t,f)}}\nBEGIN{hanoi(4,\"left\",\"middle\",\"right\")}'\n\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":2539}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f EVALUATE_BINOMIAL_COEFFICIENTS.AWK\nBEGIN {\n    main(5,3)\n    main(100,2)\n    main(33,17)\n    exit(0)\n}\nfunction main(n,k,  i,r) {\n    r = 1\n    for (i=1; i<k+1; i++) {\n      r *= (n - i + 1) \/ i\n    }\n    printf(\"%d %d = %d\\n\",n,k,r)\n}\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":2540}
    {"lang_cluster":"AWK","source_code":"{\n  line[NR] = $0\n}\nEND { # sort it with shell sort\n  increment = int(NR \/ 2)\n  while ( increment > 0 ) {\n    for(i=increment+1; i <= NR; i++) {\n      j = i\n      temp = line[i]\n      while ( (j >= increment+1) && (line[j-increment] > temp) ) {\n\tline[j] = line[j-increment]\n\tj -= increment\n      }\n      line[j] = temp\n    }\n    if ( increment == 2 )\n      increment = 1\n    else \n      increment = int(increment*5\/11)\n  }\n  #print it\n  for(i=1; i <= NR; i++) {\n    print line[i]\n  }\n}\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":2541}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n  val = 0\n  do {\n    val++\n    print val\n  } while( val % 6 != 0)\n}\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":2542}
    {"lang_cluster":"AWK","source_code":"\n\nw=length(\"Hello, world!\")      # static string example\nx=length(\"Hello,\" s \" world!\") # dynamic string example\ny=length($1)                   # input field example\nz=length(s)                    # variable name example\n\n\n echo \"Hello, w\u00f8rld!\" | awk '{print length($0)}'   # 14\n\n#!\/usr\/bin\/awk -f\n{print\"The length of this line is \"length($0)}\n\n","human_summarization":"The code calculates the character and byte length of a string, considering UTF-8 and UTF-16 encodings. It correctly handles non-BMP code points and provides the actual character counts in code points, not in code unit counts. It also has the ability to provide the string length in graphemes if the language supports it.","id":2543}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n  mystring=\"knights\"\n  print substr(mystring,2)                       # remove the first letter\n  print substr(mystring,1,length(mystring)-1)    # remove the last character\n  print substr(mystring,2,length(mystring)-2)    # remove both the first and last character\n}\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":2544}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f SUDOKU_RC.AWK\nBEGIN {\n#             row1      row2      row3      row4      row5      row6      row7      row8      row9\n#   puzzle = \"111111111 111111111 111111111 111111111 111111111 111111111 111111111 111111111 111111111\" # NG duplicate hints\n#   puzzle = \"1........ ..274.... ...5....4 .3....... 75....... .....96.. .4...6... .......71 .....1.30\" # NG can't use zero\n#   puzzle = \"1........ ..274.... ...5....4 .3....... 75....... .....96.. .4...6... .......71 .....1.39\" # no solution\n#   puzzle = \"1........ ..274.... ...5....4 .3....... 75....... .....96.. .4...6... .......71 .....1.3.\" # OK\n    puzzle = \"123456789 456789123 789123456 ......... ......... ......... ......... ......... .........\" # OK\n    gsub(\/ \/,\"\",puzzle)\n    if (length(puzzle) != 81) { error(\"length of puzzle is not 81\") }\n    if (puzzle !~ \/^[1-9\\.]+$\/) { error(\"only 1-9 and . are valid\") }\n    if (gsub(\/[1-9]\/,\"&\",puzzle) < 17) { error(\"too few hints\") }\n    if (errors > 0) {\n      exit(1)\n    }\n    plot(puzzle,\"unsolved\")\n    if (dup_hints_check(puzzle) == 1) {\n      if (solve(puzzle) == 1) {\n        dup_hints_check(sos)\n        plot(sos,\"solved\")\n        printf(\"\\nbef: %s\\naft: %s\\n\",puzzle,sos)\n        exit(0)\n      }\n      else {\n        error(\"no solution\")\n      }\n    }\n    exit(1)\n}\nfunction dup_hints_check(ss,  esf,msg,Rarr,Carr,Barr,i,r_row,r_col,r_pos,r_hint,c_row,c_col,c_pos,c_hint,box) {\n    esf = errors                       # errors so far\n    for (i=0; i<81; i++) {\n      # row\n      r_row = int(i\/9) + 1             # determine row: 1..9\n      r_col = i%9 + 1                  # determine column: 1..9\n      r_pos = i + 1                    # determine hint position: 1..81\n      r_hint = substr(ss,r_pos,1)      # extract 1 character; the hint\n      Rarr[r_row,r_hint]++             # save row\n      # column\n      c_row = i%9 + 1                  # determine row: 1..9\n      c_col = int(i\/9) + 1             # determine column: 1..9\n      c_pos = (c_row-1) * 9 + c_col    # determine hint position: 1..81\n      c_hint = substr(ss,c_pos,1)      # extract 1 character; the hint\n      Carr[c_col,c_hint]++             # save column\n      # box (there has to be a better way)\n      if      ((r_row r_col) ~ \/[123][123]\/) { box = 1 }\n      else if ((r_row r_col) ~ \/[123][456]\/) { box = 2 }\n      else if ((r_row r_col) ~ \/[123][789]\/) { box = 3 }\n      else if ((r_row r_col) ~ \/[456][123]\/) { box = 4 }\n      else if ((r_row r_col) ~ \/[456][456]\/) { box = 5 }\n      else if ((r_row r_col) ~ \/[456][789]\/) { box = 6 }\n      else if ((r_row r_col) ~ \/[789][123]\/) { box = 7 }\n      else if ((r_row r_col) ~ \/[789][456]\/) { box = 8 }\n      else if ((r_row r_col) ~ \/[789][789]\/) { box = 9 }\n      else { box = 0 }\n      Barr[box,r_hint]++               # save box\n    }\n    dup_hints_print(Rarr,\"row\")\n    dup_hints_print(Carr,\"column\")\n    dup_hints_print(Barr,\"box\")\n    return((errors == esf) ? 1 : 0)\n}\nfunction dup_hints_print(arr,rcb,  hint,i) {\n# rcb - Row Column Box\n    for (i=1; i<=9; i++) {             # \"i\" is either the row, column, or box\n      for (hint=1; hint<=9; hint++) {  # 1..9 only; don't care about \".\" place holder\n        if (arr[i,hint]+0 > 1) {       # was a digit specified more than once\n          error(sprintf(\"duplicate hint in %s %d\",rcb,i))\n        }\n      }\n    }\n}\nfunction plot(ss,text1,text2,  a,b,c,d,ou) {\n# 1st call prints the unsolved puzzle.\n# 2nd call prints the solved puzzle\n    printf(\"| - - - + - - - + - - - | %s\\n\",text1)\n    for (a=0; a<3; a++) {\n      for (b=0; b<3; b++) {\n        ou = \"|\"\n        for (c=0; c<3; c++) {\n          for (d=0; d<3; d++) {\n            ou = sprintf(\"%s %1s\",ou,substr(ss,1+d+3*c+9*b+27*a,1))\n          }\n          ou = ou \" |\"\n        }\n        print(ou)\n      }\n      printf(\"| - - - + - - - + - - - | %s\\n\",(a==2)?text2:\"\")\n    }\n}\nfunction solve(ss,  a,b,c,d,e,r,co,ro,bi,bl,nss) {\n    i = 0\n# first, use some simple logic to fill grid as much as possible\n    do {\n      i++\n      didit = 0\n      delete nr\n      delete nc\n      delete nb\n      delete ca\n      for (a=0; a<81; a++) {\n        b = substr(ss,a+1,1)\n        if (b == \".\") {                # construct row, column and block at cell\n          c = a % 9\n          r = int(a\/9)\n          ro = substr(ss,r*9+1,9)\n          co = \"\"\n          for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) }\n          bi = int(c\/3)*3+(int(r\/3)*3)*9+1\n          bl = \"\"\n          for (d=0; d<3; d++) { bl = bl substr(ss,bi+d*9,3) }\n          e = 0\n# count non-occurrences of digits 1-9 in combined row, column and block, per row, column and block, and flag cell\/digit as candidate\n          for (d=1; d<10; d++) {\n            if (index(ro co bl, d) == 0) {\n              e++\n              nr[r,d]++\n              nc[c,d]++\n              nb[bi,d]++\n              ca[c,r,d] = bi\n            }\n          }\n          if (e == 0) {                # in case no candidate is available, give up\n            return(0)\n          }\n        }\n      }\n# go through all cell\/digit candidates\n# hidden singles\n      for (crd in ca) {\n# a candidate may have been deleted after the loop started\n        if (ca[crd] != \"\") {\n          split(crd,spl,SUBSEP)\n          c = spl[1]\n          r = spl[2]\n          d = spl[3]\n          bi = ca[crd]\n          a = c + r * 9\n# unique solution if at least one non-occurrence counter is exactly 1\n          if ((nr[r,d] == 1) || (nc[c,d] == 1) || (nb[bi,d] == 1)) {\n            ss = substr(ss,1,a) d substr(ss,a+2,length(ss))\n            didit = 1\n# remove candidates from current row, column, block\n            for (e=0; e<9; e++) {\n              delete ca[c,e,d]\n              delete ca[e,r,d]\n            }\n            for (e=0; e<3; e++) {\n              for (b=0; b<3; b++) {\n                delete ca[int(c\/3)*3+b,int(r\/3)*3+e,d]\n              }\n            }\n          }\n        }\n      }\n    } while (didit == 1)\n# second, pick a viable solution for the next empty cell and see if it leads to a solution\n    a = index(ss,\".\")-1\n    if (a == -1) {                     # no more empty cells, done\n      sos = ss\n      return(1)\n    }\n    else {\n      c = a % 9\n      r = int(a\/9)\n# concatenate current row, column and block\n# row\n      co = substr(ss,r*9+1,9)\n# column\n      for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) }\n# block\n      c = int(c\/3)*3+(int(r\/3)*3)*9+1\n      for (d=0; d<3; d++) { co = co substr(ss,c+d*9,3) }\n      for (b=1; b<10; b++) {           # get a viable digit\n        if (index(co,b) == 0) {        # check if candidate digit already exists\n# is viable, put in cell\n          nss = substr(ss,1,a) b substr(ss,a+2,length(ss))\n          d = solve(nss)               # try to solve\n          if (d == 1) {                # if successful, return\n            return(1)\n          }\n        }\n      }\n    }\n    return(0)                          # no digits viable, no solution\n}\nfunction error(message) { printf(\"error: %s\\n\",message) ; errors++ }\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":2545}
    {"lang_cluster":"AWK","source_code":"\n\n# Shuffle an _array_ with indexes from 1 to _len_.\nfunction shuffle(array, len,    i, j, t) {\n\tfor (i = len; i > 1; i--) {\n\t\t# j = random integer from 1 to i\n\t\tj = int(i * rand()) + 1\n\n\t\t# swap array[i], array[j]\n\t\tt = array[i]\n\t\tarray[i] = array[j]\n\t\tarray[j] = t\n\t}\n}\n\n# Test program.\nBEGIN {\n\tlen = split(\"11 22 33 44 55 66 77 88 99 110\", array)\n\tshuffle(array, len)\n\n\tfor (i = 1; i < len; i++) printf \"%s \", array[i]\n\tprintf \"%s\\n\", array[len]\n}\n\n","human_summarization":"implement the Knuth shuffle algorithm (also known as the Fisher-Yates shuffle). This algorithm randomly shuffles the elements of an input array in-place. If in-place modification is not possible, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right for convenience. The input array can contain integers, floating-point numbers, or strings.","id":2546}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f LAST_FRIDAY_OF_EACH_MONTH.AWK year\n# converted from Fortran\nBEGIN {\n    split(\"31,28,31,30,31,30,31,31,30,31,30,31\",daynum_array,\",\") # days per month in non leap year\n    year = ARGV[1]\n    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {\n      daynum_array[2] = 29\n    }\n    y = year - 1\n    k = 44 + y + int(y\/4) + int(6*(y\/100)) + int(y\/400)\n    for (m=1; m<=12; m++) {\n      k += daynum_array[m]\n      d = daynum_array[m] - (k%7)\n      printf(\"%04d-%02d-%02d\\n\",year,m,d)\n    }\n    exit(0)\n}\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":2547}
    {"lang_cluster":"AWK","source_code":"\nBEGIN { printf(\"Goodbye, World!\") }\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":2548}
    {"lang_cluster":"AWK","source_code":"\n#!\/usr\/bin\/awk -f\n\nBEGIN {\n    message = \"My hovercraft is full of eels.\"\n    key = 1\n\n    cypher = caesarEncode(key, message)\n    clear  = caesarDecode(key, cypher)\n\n    print \"message: \" message\n    print \" cypher: \" cypher\n    print \"  clear: \" clear\n    exit\n}\n\nfunction caesarEncode(key, message) {\n    return caesarXlat(key, message, \"encode\")\n}\n\nfunction caesarDecode(key, message) {\n    return caesarXlat(key, message, \"decode\")\n}\n\nfunction caesarXlat(key, message, dir,    plain, cypher, i, num, s) {\n    plain = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n    cypher = substr(plain, key+1) substr(plain, 1, key)\n\n    if (toupper(substr(dir, 1, 1)) == \"D\") {\n        s = plain\n        plain = cypher\n        cypher = s\n    }\n\n    s = \"\"\n    message = toupper(message)\n    for (i = 1; i <= length(message); i++) {\n        num = index(plain, substr(message, i, 1))\n        if (num) s = s substr(cypher, num, 1)\n        else s = s substr(message, i, 1)\n    }\n    return s\n}\n\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":2549}
    {"lang_cluster":"AWK","source_code":"\n# greatest common divisor\nfunction gcd(m, n,    t) {\n\t# Euclid's method\n\twhile (n != 0) {\n\t\tt = m\n\t\tm = n\n\t\tn = t % n\n\t}\n\treturn m\n}\n\n# least common multiple\nfunction lcm(m, n,    r) {\n\tif (m == 0 || n == 0)\n\t\treturn 0\n\tr = m * n \/ gcd(m, n)\n\treturn r < 0 ? -r : r\n}\n\n# Read two integers from each line of input.\n# Print their least common multiple.\n{ print lcm($1, $2) }\n\nExample input and output: $ awk -f lcd.awk\n12 18\n36\n-6 14\n42\n35 0\n0\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":2550}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f CUSIP.AWK\nBEGIN {\n    n = split(\"037833100,17275R102,38259P508,594918104,68389X106,68389X105\",arr,\",\")\n    for (i=1; i<=n; i++) {\n      printf(\"%9s %s\\n\",arr[i],cusip(arr[i]))\n    }\n    exit(0)\n}\nfunction cusip(n,  c,i,sum,v,x) {\n# returns: 1=OK, 0=NG, -1=bad data\n    if (length(n) != 9) {\n      return(-1)\n    }\n    for (i=1; i<=8; i++) {\n      c = substr(n,i,1)\n      if (c ~ \/[0-9]\/) {\n        v = c\n      }\n      else if (c ~ \/[A-Z]\/) {\n        v = index(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",c) + 9\n      }\n      else if (c == \"*\") {\n        v = 36\n      }\n      else if (c == \"@\") {\n        v = 37\n      }\n      else if (c == \"#\") {\n        v = 38\n      }\n      else {\n        return(-1)\n      }\n      if (i ~ \/[02468]\/) {\n        v *= 2\n      }\n      sum += int(v \/ 10) + (v % 10)\n    }\n    x = (10 - (sum % 10)) % 10\n    return(substr(n,9,1) == x ? 1 : 0)\n}\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":2551}
    {"lang_cluster":"AWK","source_code":"\nWorks with: Gawk\n\nfunction join(array, start, end, sep,    result, i) {\n        result = array[start]\n        for (i = start + 1; i <= end; i++)\n            result = result sep array[i]\n        return result\n}\n\nfunction trim(str) {\n        gsub(\/^[[:blank:]]+|[[:blank:]\\n]+$\/, \"\", str)\n        return str\n}\n\nfunction http2var(      site,path,server,j,output) {\n\n        RS = ORS = \"\\r\\n\"\n\n        site = \"rosettacode.org\"\n        path = \"\/mw\/api.php\" \\\n            \"?action=query\" \\\n            \"&generator=categorymembers\" \\\n            \"&gcmtitle=Category:Programming%20Languages\" \\\n            \"&gcmlimit=500\" \\\n            (gcmcontinue \"\" ? \"&gcmcontinue=\" gcmcontinue : \"\") \\\n            \"&prop=categoryinfo\" \\\n            \"&format=txt\"\n\n        server = \"\/inet\/tcp\/0\/\" site \"\/80\"\n        print \"GET \" path \" HTTP\/1.0\" |& server\n        print \"Host: \" site |& server\n        print \"\" |& server\n        while ((server |& getline) > 0) {\n            if($0 != 0) {\n                j++\n                output[j] = $0\n            }\n        }\n        close(server)\n        if(length(output) == 0)\n            return -1\n        else\n            return join(output, 1, j, \"\\n\")\n}\n\nfunction parse(webpage  ,c,a,i,b,e,pages) {\n\n       # Check for API continue code ie. a new page of results available\n        match(webpage, \"gcmcontinue[]] =>[^)]+[^)]\", a)\n        if(a[0] != \"\") {\n            split(a[0], b, \">\")\n            gcmcontinue = trim(b[2])\n        } else gcmcontinue = \"\"\n\n        c = split(webpage, a, \"[[][0-9]{1,7}[]]\")\n\n        while(i++ < c) {\n            if(match(a[i], \/[pages]\/)) {\n                match(a[i], \"pages[]] =>[^[]+[^[]\", b)\n                split(b[0], e, \">\")\n                pages = trim(e[2]) + 0\n            } else pages = 0\n            if(match(a[i], \/[title]\/)) {\n                match(a[i], \"title[]] =>[^[]+[^[]\", b)\n                split(b[0], e, \":\")\n                e[2] = trim(e[2])\n                if ( substr(e[2], length(e[2]), 1) == \")\" )\n                    e[2] = trim( substr(e[2], 1, length(e[2]) - 1) )\n                if(length(e[2]) > 0)\n                    G[e[2]] = pages\n            }\n        }\n}\n\nBEGIN {\n\n        parse( http2var() )     # First 500\n        while ( gcmcontinue != \"\" )\n            parse( http2var() ) # Next 500, etc\n\n        # https:\/\/www.gnu.org\/software\/gawk\/manual\/html_node\/Controlling-Scanning.html\n        PROCINFO[\"sorted_in\"] = \"@val_type_desc\"\n        for ( language in G )\n            print ++i \". \" language \" - \" G[language]\n\n}\n\n\nOutput from 26 May 2015:\n1. Tcl - 867\n2. Racket - 863\n3. Python - 828\n4. J - 777\n5. Ruby - 769\n6. Perl 6 - 755\n7. C - 751\n...\n570. NQP - 0\n571. AspectC++ - 0\n572. Cilk - 0\n573. PL\/M - 0\n574. Agda2 - 0\n\n","human_summarization":"sorts the most popular computer programming languages based on the number of members in Rosetta Code categories. It uses either web scraping or API methods to access the data, and optionally filters incorrect results. The code also provides a complete ranked listing of all languages. The third solution in the code uses native gawk networking to connect to the API at 500 items per request.","id":2552}
    {"lang_cluster":"AWK","source_code":"\n\nBEGIN {\n  split(\"Mary had a little lamb\", strs, \" \")\n  for(el in strs) {\n    print strs[el]\n  }\n}\n\n\nBEGIN {\n  n = split(\"Mary had a little lamb\", strs, \" \")\n  for(i=1; i <= n; i++) {\n    print strs[i]\n  }\n}\n\n\n# This will not work\nBEGIN {\n  for (el in \"apples\",\"bananas\",\"cherries\") {\n    print \"I like \" el\n  }\n}\n\n","human_summarization":"iterate through each element in a collection in a specific order using a \"for each\" loop or an alternative loop if \"for each\" is not available. In AWK, the elements' indexes may not be in order, so keys are generated in the required order. The elements are filled into the array using the split function which starts indexing from 1. A normal loop is used to iterate over the array's elements in the correct order. However, in AWK, foreach loops can only be performed against an associative container and not against an explicit list.","id":2553}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n  s = \"Hello,How,Are,You,Today\"\n  split(s, arr, \",\")\n  for(i=1; i < length(arr); i++) {\n    printf arr[i] \".\"\n  }\n  print\n}\n\n\nBEGIN { FS = \",\" }\n{\n  for(i=1; i <= NF; i++) printf $i \".\";\n  print \"\"\n}\n\n\n","human_summarization":"\"Tokenizes a string by separating it into an array using commas as delimiters, then displays the words to the user, separated by periods. It also allows for a trailing period. The code uses AWK's idiomatic way of tokenizing each line of input by using a comma as a field separator.\"","id":2554}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk 'function gcd(p,q){return(q?gcd(q,(p%q)):p)}{print gcd($1,$2)}'\n12 16\n4\n22 33\n11\n45 67\n1\n\n","human_summarization":"The code defines a function called gcd() that calculates the greatest common divisor (GCD), also known as the greatest common factor or greatest common measure, of two integers. It reads pairs of numbers from the standard input and outputs their GCD to the standard output. It is related to the task of finding the least common multiple.","id":2555}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk 'function isnum(x){return(x==x+0)} BEGIN{print isnum(\"hello\"),isnum(\"-42\")}'\n\n\n","human_summarization":"\"Create a function that checks if a given string can be interpreted as a numeric value, including floating point and negative numbers, using the syntax rules of the language. The function uses the characteristic of AWK where non-numeric strings are treated as 0 in arithmetic operations but not in comparisons.\"","id":2556}
    {"lang_cluster":"AWK","source_code":"\n##\n## Dense ranking in file: ranking_d.awk\n##\n\nBEGIN{ lastresult = \"!\"; lastrank = 0 }\n\nfunction d_rank(){\n    if($1==lastresult){\n        print lastrank, $0\n    }else{\n        lastresult = $1\n        print ++lastrank, $0 }\n}\n\/\/{d_rank() }\n\n##\n## Fractional ranking in file: ranking_f.awk\n##\n\nBEGIN{\n    last = \"!\"\n    flen = 0 }\n\nfunction f_rank(){\n    item = $0\n    if($1!=last){\n        if(flen){\n            sum = 0\n            for(fl=0; fl < flen;){\n                $0 = fifo[fl++]\n                sum += $1 }\n            mean = sum \/ flen\n            for(fl=0; fl < flen;){\n                $0 = fifo[fl++]\n                $1 = \"\"\n                printf(\"%3g %s\\n\", mean, $0) }\n            flen = 0\n    }}\n    $0 = item\n    last = $1\n    fifo[flen++] = sprintf(\"%i %s\", FNR, item)\n}\n\/\/{f_rank()}\n\nEND{ if(flen){\n        sum = 0\n        for(fl=0; fl < flen;){\n            $0 = fifo[fl++]\n            sum += $1 }\n        mean = sum \/ flen\n        for(fl=0; fl < flen;){\n            $0 = fifo[fl++]\n            $1 = \"\"\n            printf(\"%3g %s\\n\", mean, $0) }}}\n\n##\n## Modified competition ranking in file: ranking_mc.awk\n##\n\nBEGIN{\n    lastresult = \"!\"\n    flen = 0 }\n\nfunction mc_rank(){\n    if($1==lastresult){\n        fifo[flen++] = $0\n    }else{\n        for(fl=0; fl < flen;){\n            print FNR-1, fifo[fl++]}\n        flen = 0\n        fifo[flen++] = $0\n        lastresult = $1}\n}\n\/\/{mc_rank()}\n\nEND{ for(fl=0; fl < flen;){\n        print FNR, fifo[fl++]} }\n\n##\n## Ordinal ranking in file: ranking_o.awk\n##\n\nfunction o_rank(){ print FNR, $0 }\n\/\/{o_rank() }\n\n##\n## Standard competition ranking in file: ranking_sc.awk\n##\n\nBEGIN{ lastresult = lastrank = \"!\" }\n\nfunction sc_rank(){\n    if($1==lastresult){\n        print lastrank, $0\n    }else{\n        print FNR, $0\n        lastresult = $1\n        lastrank = FNR}\n}\n\/\/{sc_rank()}\n\n\n44 Solomon\n42 Jason\n42 Errol\n41 Garry\n41 Bernard\n41 Barry\n39 Stephen\n\n","human_summarization":"The code implements five different ranking methods (Standard, Modified, Dense, Ordinal, Fractional) for competitors in a competition. It takes an ordered list of scores with scorers from a file and applies each ranking method to it, outputting the rankings for each method. In case of ties, each method handles them differently as per the task description.","id":2557}
    {"lang_cluster":"AWK","source_code":"\n\n\n\ntangent\n\narcsine\n\narccosine\n\n\n\n\n\n\ntan\n\u2061\n\u03b8\n=\n\n\nsin\n\u2061\n\u03b8\n\n\ncos\n\u2061\n\u03b8\n\n\n\n\n{\\displaystyle \\tan \\theta = \\frac{\\sin \\theta}{\\cos \\theta}}\n\n\n\n\n\n\n\ntan\n\u2061\n(\narcsin\n\u2061\ny\n)\n=\n\ny\n\n1\n\u2212\n\ny\n2\n\n\n\n\n\n{\\displaystyle \\tan(\\arcsin y) = \\frac{y}{\\sqrt{1 - y^2}}}\n\n\n\n\n\n\n\ntan\n\u2061\n(\narccos\n\u2061\nx\n)\n=\n\n\n1\n\u2212\n\nx\n2\n\n\nx\n\n\n\n{\\displaystyle \\tan(\\arccos x) = \\frac{\\sqrt{1 - x^2}}{x}}\n\n\n\n\n# tan(x) = tangent of x\nfunction tan(x) {\n\treturn sin(x) \/ cos(x)\n}\n\n# asin(y) = arcsine of y, domain [-1, 1], range [-pi\/2, pi\/2]\nfunction asin(y) {\n\treturn atan2(y, sqrt(1 - y * y))\n}\n\n# acos(x) = arccosine of x, domain [-1, 1], range [0, pi]\nfunction acos(x) {\n\treturn atan2(sqrt(1 - x * x), x)\n}\n\n# atan(y) = arctangent of y, range (-pi\/2, pi\/2)\nfunction atan(y) {\n\treturn atan2(y, 1)\n}\n\nBEGIN {\n\tpi = atan2(0, -1)\n\tdegrees = pi \/ 180\n\n\tprint \"Using radians:\"\n\tprint \"  sin(-pi \/ 6) =\", sin(-pi \/ 6)\n\tprint \"  cos(3 * pi \/ 4) =\", cos(3 * pi \/ 4)\n\tprint \"  tan(pi \/ 3) =\", tan(pi \/ 3)\n\tprint \"  asin(-1 \/ 2) =\", asin(-1 \/ 2)\n\tprint \"  acos(-sqrt(2) \/ 2) =\", acos(-sqrt(2) \/ 2)\n\tprint \"  atan(sqrt(3)) =\", atan(sqrt(3))\n\n\tprint \"Using degrees:\"\n\tprint \"  sin(-30) =\", sin(-30 * degrees)\n\tprint \"  cos(135) =\", cos(135 * degrees)\n\tprint \"  tan(60) =\", tan(60 * degrees)\n\tprint \"  asin(-1 \/ 2) =\", asin(-1 \/ 2) \/ degrees\n\tprint \"  acos(-sqrt(2) \/ 2) =\", acos(-sqrt(2) \/ 2) \/ degrees\n\tprint \"  atan(sqrt(3)) =\", atan(sqrt(3)) \/ degrees\n}\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions such as sine, cosine, tangent and their inverses in a specific programming language. The functions are applied using the same angle in both radians and degrees. For non-inverse functions, the same angle is used for both sine calls. For inverse functions, the same number is used and its result is converted to radians and degrees. In the case of languages without built-in trigonometric functions, the code provides custom functions based on known approximations or identities. In Awk, which only provides sin(), cos() and atan2(), additional functions are calculated using trigonometric identities.","id":2558}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk 'BEGIN{s=\"42\"; s++; print s\"(\"length(s)\")\" }'\n43(2)\n\n","human_summarization":"increment a given numerical string while maintaining its length.","id":2559}
    {"lang_cluster":"AWK","source_code":"\n# Finds the longest common directory of paths[1], paths[2], ...,\n# paths[count], where sep is a single-character directory separator.\nfunction common_dir(paths, count, sep,    b, c, f, i, j, p) {\n\tif (count < 1)\n\t\treturn \"\"\n\n\tp = \"\"\t# Longest common prefix\n\tf = 0\t# Final index before last sep\n\n\t# Loop for c = each character of paths[1].\n\tfor (i = 1; i <= length(paths[1]); i++) {\n\t\tc = substr(paths[1], i, 1)\n\n\t\t# If c is not the same in paths[2], ..., paths[count]\n\t\t# then break both loops.\n\t\tb = 0\n\t\tfor (j = 2; j <= count; j++) {\n\t\t\tif (c != substr(paths[j], i, 1)) {\n\t\t\t\tb = 1\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif (b)\n\t\t\tbreak\n\n\t\t# Append c to prefix. Update f.\n\t\tp = p c\n\t\tif (c == sep)\n\t\t\tf = i - 1\n\t}\n\n\t# Return only f characters of prefix.\n\treturn substr(p, 1, f)\n}\n\nBEGIN {\n\ta[1] = \"\/home\/user1\/tmp\/coverage\/test\"\n\ta[2] = \"\/home\/user1\/tmp\/covert\/operator\"\n\ta[3] = \"\/home\/user1\/tmp\/coven\/members\"\n\tprint common_dir(a, 3, \"\/\")\n}\n\n\n","human_summarization":"\"Code identifies the common directory path from a set of given directory paths using a specified directory separator character.\"","id":2560}
    {"lang_cluster":"AWK","source_code":"\n\n#!\/usr\/bin\/awk -f\n\nBEGIN {\n    d[1] = 3.0\n    d[2] = 4.0\n    d[3] = 1.0\n    d[4] = -8.4\n    d[5] = 7.2\n    d[6] = 4.0\n    d[7] = 1.0\n    d[8] = 1.2\n    showD(\"Before: \")\n    gnomeSortD()\n    showD(\"Sorted: \")\n    printf \"Median: %f\\n\", medianD()\n    exit\n}\n\nfunction medianD(     len, mid) {\n    len = length(d)\n    mid = int(len\/2) + 1\n    if (len % 2) return d[mid]\n    else return (d[mid] + d[mid-1]) \/ 2.0\n}\n\nfunction gnomeSortD(    i) {\n    for (i = 2; i <= length(d); i++) {\n        if (d[i] < d[i-1]) gnomeSortBackD(i)\n    }\n}\n\nfunction gnomeSortBackD(i,     t) {\n    for (; i > 1 && d[i] < d[i-1]; i--) {\n        t = d[i]\n        d[i] = d[i-1]\n        d[i-1] = t\n    }\n}\n\nfunction showD(p,   i) {\n    printf p\n    for (i = 1; i <= length(d); i++) {\n        printf d[i] \" \"\n    }\n    print \"\"\n}\n\n\nBefore: 3 4 1 -8.4 7.2 4 1 1.2 \nSorted: -8.4 1 1 1.2 3 4 4 7.2 \nMedian: 2.100000\n\n","human_summarization":"\"Code calculates the median value of a vector of floating-point numbers, handling even number of elements by returning the average of the two middle values. It uses the selection algorithm for optimal performance. It also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation. The code does not return AWK arrays, making them global.\"","id":2561}
    {"lang_cluster":"AWK","source_code":"\n# usage: awk  -v n=38  -f FizzBuzz.awk\n#\nBEGIN {\n   if(!n) n=100\n   print \"# FizzBuzz:\"\n\n   for (ii=1; ii<=n; ii++)\n       if (ii % 15 == 0)\n           {print \"FizzBuzz\"}\n       else if (ii % 3 == 0)\n           {printf \"Fizz \"}\n       else if (ii % 5 == 0)\n           {printf \"Buzz \"}\n       else\n           {printf \"%3d \", ii}\n\n    print \"\n# Done.\"\n}","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":2562}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n  XSize=59; YSize=21;\n  MinIm=-1.0; MaxIm=1.0;MinRe=-2.0; MaxRe=1.0;\n  StepX=(MaxRe-MinRe)\/XSize; StepY=(MaxIm-MinIm)\/YSize;\n  for(y=0;y<YSize;y++)\n  {\n    Im=MinIm+StepY*y;\n    for(x=0;x<XSize;x++)\n        {\n      Re=MinRe+StepX*x; Zr=Re; Zi=Im;\n      for(n=0;n<30;n++)\n          {\n        a=Zr*Zr; b=Zi*Zi;\n        if(a+b>4.0) break;\n        Zi=2*Zr*Zi+Im; Zr=a-b+Re;\n      }\n      printf \"%c\",62-n;\n    }\n    print \"\";\n  }\n  exit;\n}\n\n\n","human_summarization":"generate and draw the Mandelbrot set using various available algorithms and functions.","id":2563}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk 'func sum(s){split(s,a);r=0;for(i in a)r+=a[i];return r}{print sum($0)}'\n1 2 3 4 5 6 7 8 9 10\n55\n\n$ awk 'func prod(s){split(s,a);r=1;for(i in a)r*=a[i];return r}{print prod($0)}'\n1 2 3 4 5 6 7 8 9 10\n3628800\n\n","human_summarization":"\"Calculates the sum and product of all integers in an array, which is deserialized from a string using the split() function.\"","id":2564}
    {"lang_cluster":"AWK","source_code":"\nfunction leapyear( year )\n{\n    if ( year % 100 == 0 )\n        return ( year % 400 == 0 )\n    else\n        return ( year % 4 == 0 )            \n}\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":2565}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f DEPARTMENT_NUMBERS.AWK\nBEGIN {\n    print(\" # FD PD SD\")\n    for (fire=1; fire<=7; fire++) {\n      for (police=1; police<=7; police++) {\n        for (sanitation=1; sanitation<=7; sanitation++) {\n          if (rules() ~ \/^1+$\/) {\n            printf(\"%2d %2d %2d %2d\\n\",++count,fire,police,sanitation)\n          }\n        }\n      }\n    }\n    exit(0)\n}\nfunction rules(  stmt1,stmt2,stmt3) {\n    stmt1 = fire != police && fire != sanitation && police != sanitation\n    stmt2 = fire + police + sanitation == 12\n    stmt3 = police % 2 == 0\n    return(stmt1 stmt2 stmt3)\n}\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":2566}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n  a = \"a string\"\n  b = a\n  sub(\/a\/, \"X\", a) # modify a\n  print b  # b is a copy, not a reference to...\n}\n\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":2567}
    {"lang_cluster":"AWK","source_code":"\n\ncat mutual_recursion.awk:\n#!\/usr\/local\/bin\/gawk -f\n\n# User defined functions\nfunction F(n)\n{ return n == 0 ? 1 : n - M(F(n-1)) }\n\nfunction M(n)\n{ return n == 0 ? 0 : n - F(M(n-1)) }\n\nBEGIN {\n  for(i=0; i <= 20; i++) {\n    printf \"%3d \", F(i)\n  }\n  print \"\"\n  for(i=0; i <= 20; i++) {\n    printf \"%3d \", M(i)\n  }\n  print \"\"\n}\n\n\n","human_summarization":"implement two mutually recursive functions to calculate the Hofstadter Female and Male sequences. The Female sequence is initialized with F(0)=1 and calculated using F(n)=n-M(F(n-1)) for n>0. The Male sequence is initialized with M(0)=0 and calculated using M(n)=n-F(M(n-1)) for n>0. The functions are defined in AWK.","id":2568}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f PICK_RANDOM_ELEMENT.AWK\nBEGIN {\n    n = split(\"Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday\",day_of_week,\",\")\n    srand()\n    x = int(n*rand()) + 1\n    printf(\"%s\\n\",day_of_week[x])\n    exit(0)\n}\n\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":2569}
    {"lang_cluster":"AWK","source_code":"\n# syntax:\nawk ' \nBEGIN {\n    str = \"http%3A%2F%2Ffoo%20bar%2F\" # \"http:\/\/foo bar\/\"\n    printf(\"%s\\n\",str)\n    len=length(str)\n    for (i=1;i<=len;i++) {\n      if ( substr(str,i,1) == \"%\") {\n        L = substr(str,1,i-1) # chars to left of \"%\"\n        M = substr(str,i+1,2) # 2 chars to right of \"%\"\n        R = substr(str,i+3)   # chars to right of \"%xx\"\n        str = sprintf(\"%s%c%s\",L,hex2dec(M),R)\n      }\n    }\n    printf(\"%s\\n\",str)\n    exit(0)\n}\nfunction hex2dec(s,  num) {\n    num = index(\"0123456789ABCDEF\",toupper(substr(s,length(s)))) - 1\n    sub(\/.$\/,\"\",s)\n    return num + (length(s)\u00a0? 16*hex2dec(s)\u00a0: 0)\n} '\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back to their original unencoded form. The function handles various test cases including strings with special characters and percentages.","id":2570}
    {"lang_cluster":"AWK","source_code":"\nWorks with: Gawk\nWorks with: Mawk\nWorks with: Nawk\n\nfunction binary_search(array, value, left, right,       middle) {\n    if (right < left) return 0\n    middle = int((right + left) \/ 2)\n    if (value == array[middle]) return 1\n    if (value <  array[middle])\n        return binary_search(array, value, left, middle - 1)\n    return binary_search(array, value, middle + 1, right)\n}\n\n\nfunction binary_search(array, value, left, right,       middle) {\n    while (left <= right) {\n        middle = int((right + left) \/ 2)\n        if (value == array[middle]) return 1\n        if (value <  array[middle]) right = middle - 1\n        else                        left  = middle + 1\n    }\n    return 0\n}\n\n","human_summarization":"The code implements a binary search algorithm on a sorted integer array. It takes the starting and ending points of a range, and a \"secret value\" as inputs. The algorithm divides the range into halves and continues to narrow down the search field until the secret value is found. The implementation can be either recursive or iterative. The code also handles multiple values equal to the given value and returns the index of the secret value if found, or the \"insertion point\" for it if not found. The code also includes fixes for potential overflow bugs.","id":2571}
    {"lang_cluster":"AWK","source_code":"\n#!\/usr\/bin\/awk -f\n\nBEGIN {\n  print \"There are \" ARGC \"command line parameters\"\n  for(l=1; l<ARGC; l++) {\n    print \"Argument \" l \" is \" ARGV[l]\n  }\n}\n\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c \"alpha beta\" -h \"gamma\"'. It also includes functionalities for intelligent parsing of these arguments.","id":2572}
    {"lang_cluster":"AWK","source_code":"\n#!\/usr\/bin\/awk -f\nBEGIN {\n        # test\n\tprint nthroot(8,3)\n\tprint nthroot(16,2)\n\tprint nthroot(16,4)\n\tprint nthroot(125,3)\n\tprint nthroot(3,3)\n\tprint nthroot(3,2)\n}\n\nfunction nthroot(y,n) {\n        eps = 1e-15;   # relative accuracy\n        x   = 1; \n\tdo {\n\t\td  = ( y \/ ( x^(n-1) ) - x ) \/ n ;\n\t\tx += d; \n\t\te = eps*x;   # absolute accuracy\t\n\t} while ( d < -e  || d > e )\n\n\treturn x\n}\n\n\n 2\n 4 \n 2\n 5\n 1.44225\n 1.73205\n\n","human_summarization":"Implement the principal nth root computation algorithm for a positive real number A.","id":2573}
    {"lang_cluster":"AWK","source_code":"\n\n\nWARNING: the following purported solution makes an assumption about environment variables that may not be applicable in all circumstances.\n\n$ awk 'BEGIN{print ENVIRON[\"HOST\"]}'\nE51A08ZD\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":2574}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f LEONARDO_NUMBERS.AWK\nBEGIN {\n    leonardo(1,1,1,\"Leonardo\")\n    leonardo(0,1,0,\"Fibonacci\")\n    exit(0)\n}\nfunction leonardo(L0,L1,step,text,  i,tmp) {\n    printf(\"%s numbers (%d,%d,%d):\\n\",text,L0,L1,step)\n    for (i=1; i<=25; i++) {\n      if (i == 1) {\n        printf(\"%d \",L0)\n      }\n      else if (i == 2) {\n        printf(\"%d \",L1)\n      }\n      else {\n        printf(\"%d \",L0+L1+step)\n        tmp = L0\n        L0 = L1\n        L1 = tmp + L1 + step\n      }\n    }\n    printf(\"\\n\")\n}\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":2575}
    {"lang_cluster":"AWK","source_code":"\nWorks with: gawk\n\nBEGIN {\n FS=\"\"\n}\n\/^[^0-9]+$\/ {\n  cp = $1; j = 0\n  for(i=1; i <= NF; i++) {\n    if ( $i == cp ) {\n      j++; \n    } else {\n      printf(\"%d%c\", j, cp)\n      j = 1\n    }\n    cp = $i\n  }\n  printf(\"%d%c\", j, cp)\n}\n\n\nBEGIN {\n  RS=\"[0-9]+[^0-9]\"\n  final = \"\";\n}\n{\n  match(RT, \/([0-9]+)([^0-9])\/, r)\n  for(i=0; i < int(r[1]); i++) {\n    final = final r[2]\n  }\n}\nEND {\n  print final\n}\n\n","human_summarization":"The code implements run-length encoding and decoding for a string of uppercase characters. It compresses repeated characters by storing the length of the run. It also provides a function to reverse the compression. The code skips lines containing numbers to avoid ambiguity.","id":2576}
    {"lang_cluster":"AWK","source_code":"\n\nBEGIN {\n   s = \"hello\"\n   print s \" literal\"\n   s1 = s \" literal\"\n   print s1\n}\n\n","human_summarization":"Creates two string variables, one with a predefined text value and the other combining the original string with an additional string literal, using AWK's concatenation operator. The content of the variables is then displayed.","id":2577}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n\tfor (i = 0; i <= 255; i++)\n\t\tord[sprintf(\"%c\", i)] = i\n}\n\n# Encode string with application\/x-www-form-urlencoded escapes.\nfunction escape(str,    c, len, res) {\n\tlen = length(str)\n\tres = \"\"\n\tfor (i = 1; i <= len; i++) {\n\t\tc = substr(str, i, 1);\n\t\tif (c ~ \/[0-9A-Za-z]\/)\n\t\t#if (c ~ \/[-._*0-9A-Za-z]\/)\n\t\t\tres = res c\n\t\t#else if (c == \" \")\n\t\t#\tres = res \"+\"\n\t\telse\n\t\t\tres = res \"%\" sprintf(\"%02X\", ord[c])\n\t}\n\treturn res\n}\n\n# Escape every line of input.\n{ print escape($0) }\n\n\n","human_summarization":"The code provides a function to convert a given string into URL encoding format. It changes special characters, control characters, and extended characters into a percent symbol followed by a two-digit hexadecimal code. For instance, a space character is encoded as %20. It converts all characters except 0-9, A-Z, and a-z. It also allows for variations such as lowercase escapes and different encodings for different standards like RFC 3986 and HTML 5. An optional feature is the use of an exception string that contains symbols that don't need conversion. For HTML 5 rules, it can convert \" \" to \"+\" and preserve \"-._*\".","id":2578}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f COMMON_SORTED_LIST.AWK\nBEGIN {\n    PROCINFO[\"sorted_in\"] = \"@ind_num_asc\"\n    nums = \"[5,1,3,8,9,4,8,7],[3,5,9,8,4],[1,3,7,9]\"\n    printf(\"%s\u00a0: \",nums)\n    n = split(nums,arr1,\"],?\") - 1\n    for (i=1; i<=n; i++) {\n      gsub(\/[\\[\\]]\/,\"\",arr1[i])\n      split(arr1[i],arr2,\",\")\n      for (j in arr2) {\n        arr3[arr2[j]]++\n      }\n    }\n    for (j in arr3) {\n      printf(\"%s \",j)\n    }\n    printf(\"\\n\")\n    exit(0)\n}\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":2579}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f KNAPSACK_PROBLEM_CONTINUOUS.AWK\nBEGIN {\n#   arr[\"item,weight,price\"]\n    arr[\"beef,3.8,36\"]\n    arr[\"pork,5.4,43\"]\n    arr[\"ham,3.6,90\"]\n    arr[\"greaves,2.4,45\"]\n    arr[\"flitch,4.0,30\"]\n    arr[\"brawn,2.5,56\"]\n    arr[\"welt,3.7,67\"]\n    arr[\"salami,3.0,95\"]\n    arr[\"sausage,5.9,98\"]\n    for (i in arr) {\n      split(i,tmp,\",\")\n      arr[i] = tmp[3] \/ tmp[2] # $\/unit\n    }\n    sack_size = 15 # kg\n    PROCINFO[\"sorted_in\"] = \"@val_num_desc\"\n    print(\"item    weight  price $\/unit\")\n    for (i in arr) {\n      if (total_weight >= sack_size) {\n        break\n      }\n      split(i,tmp,\",\")\n      weight = tmp[2]\n      if (total_weight + weight <= sack_size) {\n        price = tmp[3]\n        msg = \"all\"\n      }\n      else {\n        weight = sack_size - total_weight\n        price = weight * arr[i]\n        msg = weight \" of \" tmp[2]\n      }\n      printf(\"%-7s %6.2f %6.2f %6.2f take %s\\n\",tmp[1],weight,tmp[3],arr[i],msg)\n      total_items++\n      total_price += price\n      total_weight += weight\n    }\n    printf(\"%7d %6.2f %6.2f total\\n\",total_items,total_weight,total_price)\n    exit(0)\n}\n\n\n","human_summarization":"determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.","id":2580}
    {"lang_cluster":"AWK","source_code":"\n# JUMBLEA.AWK - words with the most duplicate spellings\n# syntax: GAWK -f JUMBLEA.AWK UNIXDICT.TXT\n{   for (i=1; i<=NF; i++) {\n      w = sortstr(toupper($i))\n      arr[w] = arr[w] $i \" \"\n      n = gsub(\/ \/,\"&\",arr[w])\n      if (max_n < n) { max_n = n }\n    }\n}\nEND {\n    for (w in arr) {\n      if (gsub(\/ \/,\"&\",arr[w]) == max_n) {\n        printf(\"%s\\t%s\\n\",w,arr[w])\n      }\n    }\n    exit(0)\n}\nfunction sortstr(str,  i,j,leng) {\n    leng = length(str)\n    for (i=2; i<=leng; i++) {\n      for (j=i; j>1 && substr(str,j-1,1) > substr(str,j,1); j--) {\n        str = substr(str,1,j-2) substr(str,j,1) substr(str,j-1,1) substr(str,j+1)\n      }\n    }\n    return(str)\n}\n\n\n","human_summarization":"\"Code identifies and lists the largest sets of anagrams from a given word list, sourced from a specified URL.\"","id":2581}
    {"lang_cluster":"AWK","source_code":"\n# WSC.AWK - Waclaw Sierpinski's carpet contributed by Dan Nielsen\n#\n# syntax: GAWK -f WSC.AWK [-v o={a|A}{b|B}] [-v X=anychar] iterations\n#\n#   -v o=ab default\n#      a|A  loose weave | tight weave\n#      b|B  don't show | show how the carpet is built\n#   -v X=?  Carpet is built with X's. The character assigned to X replaces all X's.\n#\n#   iterations\n#      The number of iterations. The default is 0 which produces one carpet.\n#\n# what is the difference between a loose weave and a tight weave:\n#   loose                tight\n#   X X X X X X X X X    XXXXXXXXX\n#   X   X X   X X   X    X XX XX X\n#   X X X X X X X X X    XXXXXXXXX\n#   X X X       X X X    XXX   XXX\n#   X   X       X   X    X X   X X\n#   X X X       X X X    XXX   XXX\n#   X X X X X X X X X    XXXXXXXXX\n#   X   X X   X X   X    X XX XX X\n#   X X X X X X X X X    XXXXXXXXX\n#\n# examples:\n#   GAWK -f WSC.AWK 2\n#   GAWK -f WSC.AWK -v o=Ab -v X=# 2\n#   GAWK -f WSC.AWK -v o=Ab -v X=\\xDB 2\n#\nBEGIN {\n    optns = (o == \"\") ? \"ab\" : o\n    n = ARGV[1] + 0 # iterations\n    if (n !~ \/^[0-9]+$\/) { exit(1) }\n    seed = (optns ~ \/A\/) ? \"XXX,X X,XXX\" : \"X X X ,X   X ,X X X \" # tight\/loose weave\n    leng = row = split(seed,A,\",\") # seed the array\n    for (i=1; i<=n; i++) { # build carpet\n      for (a=1; a<=3; a++) {\n        row = 0\n        for (b=1; b<=3; b++) {\n          for (c=1; c<=leng; c++) {\n            row++\n            tmp = (a == 2 && b == 2) ? sprintf(\"%*s\",length(A[c]),\"\") : A[c]\n            B[row] = B[row] tmp\n          }\n          if (optns ~ \/B\/) { # show how the carpet is built\n            if (max_row < row+0) { max_row = row }\n            for (r=1; r<=max_row; r++) {\n              printf(\"i=%d row=%02d a=%d b=%d '%s'\\n\",i,r,a,b,B[r])\n            }\n            print(\"\")\n          }\n        }\n      }\n      leng = row\n      for (j=1; j<=row; j++) { A[j] = B[j] } # re-seed the array\n      for (j in B) { delete B[j] } # delete work array\n    }\n    for (j=1; j<=row; j++) { # print carpet\n      if (X != \"\") { gsub(\/X\/,substr(X,1,1),A[j]) }\n      sub(\/ +$\/,\"\",A[j])\n      printf(\"%s\\n\",A[j])\n    }\n    exit(0)\n}\n\n\nSample:\nGAWK -f WSC.AWK 1\n\nX X X X X X X X X\nX   X X   X X   X\nX X X X X X X X X\nX X X       X X X\nX   X       X   X\nX X X       X X X\nX X X X X X X X X\nX   X X   X X   X\nX X X X X X X X X\n\nGAWK -f WSC.AWK -v o=A 1\n\nXXXXXXXXX\nX XX XX X\nXXXXXXXXX\nXXX   XXX\nX X   X X\nXXX   XXX\nXXXXXXXXX\nX XX XX X\nXXXXXXXXX\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":2582}
    {"lang_cluster":"AWK","source_code":"\n\n#!\/bin\/sh -f\nawk '\nBEGIN {\n    print \"Creating table...\"\n    dbExec(\"address.db\", \"create table address (street, city, state, zip);\")\n    print \"Done.\"\n    exit\n}\n\nfunction dbExec(db, qry,      result) {\n    dbMakeQuery(db, qry) | getline result\n    dbErrorCheck(result)\n}\n\nfunction dbMakeQuery(db, qry,      q) {\n    q = dbEscapeQuery(qry) \";\"\n    return \"echo \\\"\" q \"\\\" | sqlite3 \" db\n}\n\nfunction dbEscapeQuery(qry,      q) {\n    q = qry\n    gsub(\/\"\/, \"\\\\\\\"\", q)\n    return q\n}\n\nfunction dbErrorCheck(res) {\n    if (res ~ \"SQL error\") {\n        print res\n        exit\n    }\n}\n\n'\n\n","human_summarization":"\"Create a table in a database to store US postal addresses, including fields for unique identifier, street address, city, state code, and zipcode. The code also demonstrates how to open a database connection in non-database languages using AWK pipe, 'getline' function, and sqlite3 command line program.\"","id":2583}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n  for(i=10; i>=0; i--) {\n     print i\n  }\n}\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":2584}
    {"lang_cluster":"AWK","source_code":"\nBEGIN {\n  for (i= 2; i <= 8; i = i + 2) {\n    print i\n  }\n  print \"Ain't never too late!\"\n}\n\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":2585}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f JENSENS_DEVICE.AWK\n# converted from FreeBASIC\nBEGIN {\n    evaluation()\n    exit(0)\n}\nfunction evaluation(  hi,i,lo,tmp) {\n    lo = 1\n    hi = 100\n    for (i=lo; i<=hi; i++) {\n      tmp += (1\/i)\n    }\n    printf(\"%.15f\\n\",tmp)\n}\n\n\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":2586}
    {"lang_cluster":"AWK","source_code":"\nWorks with: gawk\n\nBEGIN {\n    # square size\n    s = 256\n    # the PPM image header needs 3 lines:\n    # P3\n    # width height\n    # max colors number (per channel)\n    print(\"P3\\n\", s, s, \"\\n\", s - 1)\n    # and now we generate pixels as a RGB pair in a relaxed\n    # form \"R G B\\n\"\n    for (x = 0; x < s; x++) { \n        for (y = 0; y < s; y++) {\n            p = xor(x, y)\n            print(0, p, p)\n        }\n    }\n}\n\n","human_summarization":"generates a graphical pattern where each pixel's color is determined by the value of 'x xor y' using a specific color table, and produces a PPM image that can be viewed or converted with The GIMP or ImageMagick.","id":2587}
    {"lang_cluster":"AWK","source_code":"\n#!\/usr\/bin\/awk -f\n\n# Remember: AWK is 1-based, for better or worse.\n\nBEGIN {\n    # The maze dimensions.\n    width = 20;  # Global\n    height = 20; # Global\n    resetMaze();\n\n    # Some constants.\n    top = 1;\n    bottom = 2;\n    left = 3;\n    right = 4;\n\n    # Randomize the PRNG.\n    randomize();\n\n    # Visit all the cells starting at a random point.\n    visitCell(getRandX(), getRandY());\n    \n    # Show the result.\n    printMaze();\n}\n\n# Wander through the maze removing walls as we go.\nfunction visitCell(x, y,    dirList, dir, nx, ny, ndir, pi) {\n    setVisited(x, y);   # This cell has been visited.\n\n    # Visit neighbors in a random order.\n    dirList = getRandDirList();\n    for (dir = 1; dir <= 4; dir++) {\n        # Get coordinates of a random neighbor (next in random direction list).\n        ndir = substr(dirList, dir, 1);\n        nx = getNextX(x, ndir);\n        ny = getNextY(y, ndir);\n        \n        # Visit an unvisited neighbor, removing the separating walls.\n        if (wasVisited(nx, ny) == 0) {\n            rmWall(x, y, ndir);\n            rmWall(nx, ny, getOppositeDir(ndir));\n            visitCell(nx, ny)\n        } \n    }\n}\n\n# Display the text-mode maze.\nfunction printMaze(    x, y, r, w) {\n    for (y = 1; y <= height; y++) {\n        for (pass = 1; pass <= 2; pass++) { # Go over each row twice: top, middle\n            for (x = 1; x <= width; x++) {\n                if (pass == 1) { # top\n                    printf(\"+\");\n                    printf(hasWall(x, y, top) == 1 ? \"---\" : \"   \");\n                    if (x == width) printf(\"+\");\n                }\n                else if (pass == 2) { # left, right\n                    printf(hasWall(x, y, left) == 1 ? \"|\" : \" \");\n                    printf(\"   \");\n                    if (x == width) printf(hasWall(x, y, right) == 1 ? \"|\" : \" \");\n                }\n            }\n            print;\n        }\n    }\n    for (x = 1; x <= width; x++) printf(\"+---\"); # bottom row\n    print(\"+\"); # bottom right corner\n}\n\n# Given a direction, get its opposite.\nfunction getOppositeDir(d) {\n    if (d == top) return bottom;\n    if (d == bottom) return top;\n    if (d == left) return right;\n    if (d == right) return left;\n}\n\n# Build a list (string) of the four directions in random order.\nfunction getRandDirList(    dirList, randDir, nx, ny, idx) {\n    dirList = \"\";\n    while (length(dirList) < 4) {\n        randDir = getRandDir();\n        if (!index(dirList, randDir)) {\n            dirList = dirList randDir;\n        }\n    }\n    return dirList;\n}\n\n# Get x coordinate of the neighbor in a given a direction.\nfunction getNextX(x, dir) {\n    if (dir == left) x = x - 1;\n    if (dir == right) x = x + 1;\n    if (!isGoodXY(x, 1)) return -1; # Off the edge.\n    return x;\n}\n\n# Get y coordinate of the neighbor in a given a direction.\nfunction getNextY(y, dir) {\n    if (dir == top) y = y - 1;\n    if (dir == bottom) y = y + 1;\n    if (!isGoodXY(1, y)) return -1; # Off the edge.\n    return y;\n}\n\n# Mark a cell as visited.\nfunction setVisited(x, y,    cell) {\n    cell = getCell(x, y);\n    if (cell == -1) return;\n    cell = substr(cell, 1, 4) \"1\"; # walls plus visited\n    setCell(x, y, cell);\n}\n\n# Get the visited state of a cell.\nfunction wasVisited(x, y,    cell) {\n    cell = getCell(x, y);\n    if (cell == -1) return 1; # Off edges already visited.\n    return substr(getCell(x,y), 5, 1);\n}\n\n# Remove a cell's wall in a given direction.\nfunction rmWall(x, y, d,    i, oldCell, newCell) {\n    oldCell = getCell(x, y);\n    if (oldCell == -1) return;\n    newCell = \"\";\n    for (i = 1; i <= 4; i++) { # Ugly as concat of two substrings and a constant?.\n        newCell = newCell (i == d ? \"0\" : substr(oldCell, i, 1));\n    }\n    newCell = newCell wasVisited(x, y);\n    setCell(x, y, newCell);\n}\n\n# Determine if a cell has a wall in a given direction.\nfunction hasWall(x, y, d,    cell) {\n    cell = getCell(x, y);\n    if (cell == -1) return 1; # Cells off edge always have all walls.\n    return substr(getCell(x, y), d, 1);\n}\n\n# Plunk a cell into the maze.\nfunction setCell(x, y, cell,    idx) {\n    if (!isGoodXY(x, y)) return;\n    maze[x, y] = cell\n}\n\n# Get a cell from the maze.\nfunction getCell(x, y,    idx) {\n    if (!isGoodXY(x, y)) return -1; # Bad cell marker.\n    return maze[x, y];\n}\n\n# Are the given coordinates in the maze?\nfunction isGoodXY(x, y) {\n    if (x < 1 || x > width) return 0;\n    if (y < 1 || y > height) return 0;\n    return 1;\n}\n\n# Build the empty maze.\nfunction resetMaze(    x, y) {\n    delete maze;\n    for (y = 1; y <= height; y++) {\n        for (x = 1; x <= width; x++) {\n            maze[x, y] = \"11110\"; # walls (up, down, left, right) and visited state.\n        }\n    }\n}\n\n# Random things properly scaled.\n\nfunction getRandX() {\n    return 1 + int(rand() * width);\n}\n\nfunction getRandY() {\n    return 1 +int(rand() * height);\n}\n\nfunction getRandDir() {\n    return 1 + int(rand() * 4);\n}\n\nfunction randomize() {\n    \"echo $RANDOM\" | getline t;\n    srand(t);\n}\n\n\n+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n|                       |                   |                       |           |\n+---+   +---+   +---+---+   +---+   +---+---+   +---+   +---+---+   +   +---+   +\n|       |   |   |           |   |           |       |   |   |       |       |   |\n+   +---+   +   +   +---+---+   +---+---+   +   +---+   +   +   +---+---+---+   +\n|       |       |   |                   |       |       |       |               |\n+   +   +   +---+   +---+   +   +---+   +---+---+   +---+---+   +---+   +---+   +\n|   |   |   |   |       |   |   |       |       |   |       |           |       |\n+---+   +   +   +---+   +---+   +   +---+---+   +   +   +   +---+---+---+   +---+\n|       |       |       |       |               |       |   |       |       |   |\n+   +   +---+---+   +---+   +---+---+---+---+   +---+---+   +---+   +   +---+   +\n|   |   |       |   |           |           |   |       |       |   |   |       |\n+   +---+   +   +   +---+---+   +---+   +   +   +   +   +---+   +   +   +   +   +\n|   |       |       |       |       |   |   |   |   |       |   |   |       |   |\n+   +   +---+---+---+   +   +---+   +   +   +   +---+---+   +   +   +---+---+   +\n|   |   |               |           |   |   |               |   |               |\n+   +   +---+---+---+   +---+---+---+   +   +---+---+---+   +   +---+---+   +---+\n|       |               |   |           |           |       |   |       |       |\n+   +---+   +---+---+---+   +   +---+---+---+---+   +   +---+   +   +   +---+   +\n|   |       |           |   |   |       |       |   |   |   |       |   |       |\n+   +   +   +   +---+   +   +   +   +   +   +   +   +   +   +---+---+   +   +---+\n|       |   |       |   |           |   |   |   |   |   |           |   |       |\n+   +---+---+---+   +   +---+---+---+   +   +   +   +   +   +---+   +   +---+   +\n|   |               |           |   |       |   |           |   |   |       |   |\n+---+   +---+---+---+---+---+   +   +---+   +---+---+---+---+   +   +---+   +   +\n|   |   |       |           |   |       |   |           |       |       |   |   |\n+   +   +   +---+   +---+   +   +---+   +   +   +---+   +---+   +---+   +   +   +\n|   |   |           |       |       |       |   |           |           |   |   |\n+   +   +   +---+---+   +---+---+   +   +---+   +---+---+   +---+---+   +   +---+\n|   |   |   |   |       |           |       |       |   |           |   |       |\n+   +   +   +   +   +---+   +---+---+---+---+---+   +   +---+---+   +   +---+   +\n|       |   |   |           |                       |               |       |   |\n+---+---+   +   +---+---+---+---+   +   +---+---+---+   +---+---+---+---+   +   +\n|       |       |               |   |       |       |           |           |   |\n+   +   +---+   +---+---+   +   +   +---+   +   +   +---+---+   +---+---+---+   +\n|   |       |       |       |   |       |   |   |   |       |           |       |\n+   +   +---+---+   +   +---+   +   +---+   +---+   +   +   +---+---+   +   +---+\n|   |           |   |   |       |   |       |       |   |           |   |       |\n+   +---+   +---+   +   +   +---+---+   +---+   +---+   +---+---+   +   +---+   +\n|       |               |               |                       |               |\n+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively repeats the process with the neighbor as the current cell.","id":2588}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f ORDER_TWO_NUMERICAL_LISTS.AWK\nBEGIN {\n    split(\"1,2,1,5,2\",list1,\",\")\n    split(\"1,2,1,5,2,2\",list2,\",\")\n    split(\"1,2,3,4,5\",list3,\",\")\n    split(\"1,2,3,4,5\",list4,\",\")\n    x = compare_array(list1,list2) ? \"<\" : \">=\" ; printf(\"list1%slist2\\n\",x)\n    x = compare_array(list2,list3) ? \"<\" : \">=\" ; printf(\"list2%slist3\\n\",x)\n    x = compare_array(list3,list4) ? \"<\" : \">=\" ; printf(\"list3%slist4\\n\",x)\n    exit(0)\n}\nfunction compare_array(arr1,arr2,  ans,i) {\n    ans = 0\n    for (i=1; i<=length(arr1); i++) {\n      if (arr1[i] != arr2[i]) {\n        ans = 1\n        break\n      }\n    }\n    if (length(arr1) != length(arr2)) {\n      ans = 1\n    }\n    return(ans)\n}\n\n\n","human_summarization":"\"Function to compare two numerical lists in lexicographic order and return true if the first list should be ordered before the second, false otherwise.\"","id":2589}
    {"lang_cluster":"AWK","source_code":"\nfunction ackermann(m, n) \n{\n  if ( m == 0 ) { \n    return n+1\n  }\n  if ( n == 0 ) { \n    return ackermann(m-1, 1)\n  }\n  return ackermann(m-1, ackermann(m, n-1))\n}\n\nBEGIN {\n  for(n=0; n < 7; n++) {\n    for(m=0; m < 4; m++) {\n      print \"A(\" m \",\" n \") = \" ackermann(m,n)\n    }\n  }\n}\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":2590}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f GAMMA_FUNCTION.AWK\nBEGIN {\n    e = (1+1\/100000)^100000\n    pi = atan2(0,-1)\n\n    print(\"X    Stirling\")\n    for (i=1; i<=20; i++) {\n      d = i \/ 10\n      printf(\"%4.2f %9.5f\\n\",d,gamma_stirling(d))\n    }\n    exit(0)\n}\nfunction gamma_stirling(x) {\n    return sqrt(2*pi\/x) * pow(x\/e,x)\n}\nfunction pow(a,b) {\n    return exp(b*log(a))\n}\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":2591}
    {"lang_cluster":"AWK","source_code":"\n\n#!\/usr\/bin\/gawk -f\n# Solve the Eight Queens Puzzle\n#    Inspired by Raymond Hettinger [https:\/\/code.activestate.com\/recipes\/576647\/]\n#    Just the vector of row positions per column is kept,\n#    and filled with all possibilities from left to right recursively,\n#    then checked against the columns left from the current one:\n#    - is a queen in the same row\n#    - is a queen in the digonal\n#    - is a queen in the reverse diagonal\nBEGIN {\n    dim = ARGC < 2 ? 8 : ARGV[1]\n    # make vec an array\n    vec[1] = 0\n    # scan for a solution\n    if (tryqueen(1, vec, dim))\n        result(vec, dim)\n    else \n        print \"No solution with \" dim \" queens.\"\n}\n    \n# try if a queen can be set in column (col)\nfunction tryqueen(col, vec, dim,        new)  {\n    for (new = 1; new <= dim; ++new) {\n        # check all previous columns\n        if (noconflict(new, col, vec, dim)) {\n            vec[col] = new\n            if (col == dim)\n                return 1        \n            # must try next column(s)\n           if (tryqueen(col+1, vec, dim))\n                return 1\n        }\n    }\n    # all tested, failed\n    return 0   \n}\n\n#  check if setting the queen (new) in column (col) is ok\n#  by checking the previous colums conflicts\nfunction noconflict(new, col, vec, dim,    j) {\n    for (j = 1; j < col; j++) {\n        if (vec[j] == new)\n            return 0    # same row\n        if (vec[j] == new - col + j) \n            return 0        # diagonal conflict\n        if (vec[j] == new + col - j)\n            return 0        # reverse diagonal conflict\n    }\n    # no test failed, no conflict\n    return 1   \n}\n\n# print matrix\nfunction result(vec, dim,    row, col, sep, lne) {\n    # print the solution vector\n    for (row  = 1; row <= dim; ++row)\n        printf \" %d\", vec[row] \n    print\n    \n    # print a board matrix\n    for (row = 1; row <= dim; ++row) {\n        lne = \"|\"\n        for (col = 1; col <= dim; ++col) {\n            if (row == vec[col])\n                lne = lne \"Q|\" \n            else\n                lne = lne \"_|\"\n        }\n        print lne\n    }\n}\n\n\n","human_summarization":"\"Code to incrementally build a vector and solve the N-queens problem, including the eight queens puzzle, inspired by Raymond Hettinger's Python solution. It also provides the number of solutions for small values of N as per OEIS: A000170.\"","id":2592}
    {"lang_cluster":"AWK","source_code":"\n#!\/usr\/bin\/awk -f\nBEGIN {\n    split(\"cul-de-sac\",a,\"-\")\n    split(\"1-2-3\",b,\"-\")\n    concat_array(a,b,c)\n\n    for (i in c) {\n        print i,c[i]\n    }\n}\n\nfunction concat_array(a,b,c, nc) {\n    for (i in a) {\n        c[++nc]=a[i]\t\n    }\n    for (i in b) {\n       c[++nc]=b[i]\t\n    }\n}\n\n","human_summarization":"demonstrate how to concatenate two arrays.","id":2593}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f KNAPSACK_PROBLEM_0-1.AWK\nBEGIN {\n#   arr[\"item,weight\"] = value\n    arr[\"map,9\"] = 150\n    arr[\"compass,13\"] = 35\n    arr[\"water,153\"] = 200\n    arr[\"sandwich,50\"] = 160\n    arr[\"glucose,15\"] = 60\n    arr[\"tin,68\"] = 45\n    arr[\"banana,27\"] = 60\n    arr[\"apple,39\"] = 40\n    arr[\"cheese,23\"] = 30\n    arr[\"beer,52\"] = 10\n    arr[\"suntan cream,11\"] = 70\n    arr[\"camera,32\"] = 30\n    arr[\"T-shirt,24\"] = 15\n    arr[\"trousers,48\"] = 10\n    arr[\"umbrella,73\"] = 40\n    arr[\"waterproof trousers,42\"] = 70\n    arr[\"waterproof overclothes,43\"] = 75\n    arr[\"note-case,22\"] = 80\n    arr[\"sunglasses,7\"] = 20\n    arr[\"towel,18\"] = 12\n    arr[\"socks,4\"] = 50\n    arr[\"book,30\"] = 10\n    sack_size = 400 # dag\n    PROCINFO[\"sorted_in\"] = \"@val_num_desc\"\n    for (i in arr) {\n      if (total_weight >= sack_size) {\n        break\n      }\n      split(i,tmp,\",\")\n      weight = tmp[2]\n      if (total_weight + weight <= sack_size) {\n        printf(\"%s\\n\",tmp[1])\n        total_items++\n        total_value += arr[i]\n        total_weight += weight\n      }\n    }\n    printf(\"items=%d (out of %d) weight=%d value=%d\\n\",total_items,length(arr),total_weight,total_value)\n    exit(0)\n}\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":2594}
    {"lang_cluster":"AWK","source_code":"\n\n#!\/usr\/bin\/awk -f \nBEGIN {\n\tprint (a(1) && b(1))\n\tprint (a(1) || b(1))\n\tprint (a(0) && b(1))\n\tprint (a(0) || b(1))\n}\n\n\nfunction a(x) {\n\tprint \"  x:\"x\n\treturn x\n}\nfunction b(y) {\n\tprint \"  y:\"y\n\treturn y\n}\n\n\n","human_summarization":"The code defines two functions, a and b, which both take and return a boolean value while printing their name when called. The code then calculates and assigns the values of two equations, x = a(i) and b(j) and y = a(i) or b(j), to variables. The calculations are done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in logical AND and OR operations. If the language doesn't support short-circuit evaluation, nested if statements are used to achieve the same effect.","id":2595}
    {"lang_cluster":"AWK","source_code":"\n\n# usage: awk -f morse.awk [inputfile]\nBEGIN { FS=\"\";\n m=\"A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-.\";\n m=m \"O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--..  \";\n}\n                                                                                \n{ for(i=1; i<=NF; i++)\n  {\n    c=toupper($i); n=1; b=\".\";\n                                                                               \n    while((c!=b)&&(b!=\" \")) { b=substr(m,n,1); n++; }\n                                                                                \n    b=substr(m,n,1);\n                                                                                \n    while((b==\".\")||(b==\"-\")) { printf(\"%s\",b); n++; b=substr(m,n,1); }\n \n    printf(\"|\");\n  }\n  printf(\"\\n\");\n}\n\n\n","human_summarization":"translates a given string into Morse code and sends it as audible signals to an audio device such as a PC speaker. It ignores unknown characters or indicates them with a different pitch. Note that AWK is used for text translation into Morse code but it cannot play sounds.","id":2596}
    {"lang_cluster":"AWK","source_code":"\n\n#!\/usr\/bin\/awk -f\n# tested with mawk 1.3.3 on Raspberry Pi 3\n#        also GNU awk 3.1.5, busybox 1.21.1 and 1.27.1 on AMD Sempron 2800+\n#\nfunction setblocks() {\n# key to the algorithm is the representation of a block\n# each block is represented by 4 characters in the string \"blocks\"\n# for example, the \"BO\" block becomes \"-BO-\"\n#\nblocks=\"-BO--XK--DQ--CP--NA--GT--RE--TG--QD--FS--JW--HU--VI--AN--OB--ER--FS--LY--PC--ZM-\"\ntrue=1\nfalse=0\n}\nfunction found(letter){\n#\n# the function \"found\" scans for the letter on the top of a block\n# using the pattern \"-B\", for example, to find a \"B\",\n# returning \"true\" (or 1) if found\n# if not found on the top, look on the bottoms using the pattern \"B-\"\n# again returning \"true\" if found\n# if the letter is found on either top or bottom, the 4 character block is set to \"----\"\n# so that block is unavailable \n# finally, if no available copy of letter is found,\n# the function returns \"false\" (0)\nposition= index(blocks,\"-\" letter)\nif (position > 0)\n   { \n  blocks = substr(blocks,1,position-1) \"----\" substr(blocks,position+4)\n  return true\n   }\nposition = index(blocks,letter \"-\")\nif (position > 0)\n   {blocks = substr(blocks,1,position-3) \"----\" substr(blocks,position+2)\n     return true\n    }\nreturn false\n}\n# awk's BEGIN statement allows for initialization before processing input;\n# in this case, initializing the string \"blocks\"\n#\nBEGIN{\nsetblocks()\n}\n# in awk, the input record is contained in the string variable \"$0\"\n# the main process checks each letter in turn to see if it is on a usable block,\n# summing the values returned by \"found\"\n# if the sum equals the number of input characters the word can be spelled with the blocks\n# otherwise it is not possible\n#\n{\nnchars=length($0)\npossible=false\nfor (i=1;i<=nchars;i++){\n     possible=possible + found(substr($0,i,1))\n}\nif (possible==nchars) print $0 \" is possible\"\n   else print $0 \" is not possible\"\nsetblocks()\n}\n\n and -----------------\n#!\/usr\/bin\/awk -f\n# tested with mawk 1.3.3 on Raspberry Pi 3\n#        also GNU awk 3.1.5, busybox 1.21.1 and 1.27.1 on AMD Sempron 2800+\n#\nfunction setblocks() {\n#\n#  key to the algorithm is the representation of the blocks\n# each block is represented by 1 character in the string \"tops\"\n# and by 1 character in the string \"bottoms\"\n#\n   tops=\"BXDCNGRTQFJHVAOEFLPZ\"\nbottoms=\"OKQPATEGDSWUINBRSYCM\"\ntrue=1\nfalse=0\n}\nfunction found(letter){\n#\n# the function \"found\" scans first the string \"tops\" for a letter and\n# then the string \"bottoms\" if the letter is not in \"tops\"\n# if the letter is found, it marks \"tops\" and \"bottoms\" to show\n# the block is unavailable by changing the letters on the block to \"-\"\n# and returns \"true\" (1); if the letter is not found\n# the function returns \"false\" (0)\n#\nposition= index(tops,letter)\nif (position > 0)\n   { \n  tops = substr(tops,1,position-1) \"-\" substr(tops,position+1)\n  bottoms = substr(bottoms,1,position-1) \"-\" substr(bottoms,position+1)\n  return true\n   }\nposition = index(bottoms,letter)\nif (position > 0)\n   {bottoms = substr(bottoms,1,position-1) \"-\" substr(bottoms,position+1)\n    tops = substr(tops,1,position-1) \"-\" substr(tops,position+1)\n     return true\n    }\nreturn false\n}\n# awk's BEGIN statement allows for initialization before processing input;\n# in this case, initializing the string \"blocks\"\n#\nBEGIN{\nsetblocks()\n}\n# in awk, the input record is contained in the string variable \"$0\"\n# the main process checks each letter in turn to see if it is on a usable block,\n# summing the values returned by \"found\"\n# if the sum equals the number of input characters the word can be spelled with the blocks\n# otherwise it is not possible\n#\n{\nnchars=length($0)\npossible=false\nfor (i=1;i<=nchars;i++){\n     possible=possible + found(substr($0,i,1))\n}\nif (possible==nchars) print $0 \" is possible\"\n   else print $0 \" is not possible\"\nsetblocks()\n}\n\n\n","human_summarization":"\"Function to determine if a given word can be spelled using a specific collection of ABC blocks. Each block can only be used once and the function is case-insensitive.\"","id":2597}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f SORT_A_LIST_OF_OBJECT_IDENTIFIERS.AWK\n#\n# sorting:\n#   PROCINFO[\"sorted_in\"] is used by GAWK\n#   SORTTYPE is used by Thompson Automation's TAWK\n#\nBEGIN {\n    width = 10\n    oid_arr[++n] = \"1.3.6.1.4.1.11.2.17.19.3.4.0.10\"\n    oid_arr[++n] = \"1.3.6.1.4.1.11.2.17.5.2.0.79\"\n    oid_arr[++n] = \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\"\n    oid_arr[++n] = \"1.3.6.1.4.1.11150.3.4.0.1\"\n    oid_arr[++n] = \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\"\n    oid_arr[++n] = \"1.3.6.1.4.1.11150.3.4.0\"\n#   oid_arr[++n] = \"1.11111111111.1\" # un-comment to test error\n    for (i=1; i<=n; i++) {\n      str = \"\"\n      for (j=1; j<=split(oid_arr[i],arr2,\".\"); j++) {\n        str = sprintf(\"%s%*s.\",str,width,arr2[j])\n        if ((leng = length(arr2[j])) > width) {\n          printf(\"error: increase sort key width from %d to %d for entry %s\\n\",width,leng,oid_arr[i])\n          exit(1)\n        }\n      }\n      arr3[str] = \"\"\n    }\n    PROCINFO[\"sorted_in\"] = \"@ind_str_asc\" ; SORTTYPE = 1\n    for (i in arr3) {\n      str = i\n      gsub(\/ \/,\"\",str)\n      sub(\/\\.$\/,\"\",str)\n      printf(\"%s\\n\",str)\n    }\n    exit(0)\n}\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":2598}
    {"lang_cluster":"AWK","source_code":"\nWorks with: GAWK\n\nBEGIN { \n    s=\"\/inet\/tcp\/256\/0\/0\"\n    print strftime() |& s\n    close(s)\n}\n\n\nBEGIN {\n    s=\"\/inet\/tcp\/0\/localhost\/256\"\n    s |& getline\n    print $0\n    close(s)\n}\n\n","human_summarization":"The code opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket. It does not handle exceptions or errors.","id":2599}
    {"lang_cluster":"AWK","source_code":"\n\nBEGIN {\n  for (l = 0; l <= 2147483647; l++) {\n    printf(\"%o\\n\", l);\n  }\n}\n\n","human_summarization":"\"Generate a sequential count in octal format starting from zero with an increment of one. Each number is printed on a separate line. The program continues to count until it is terminated or the maximum value of the numeric type in use is reached. The code uses the printf command from the C library, supported by the awk extraction and reporting language, to output the counter value in octal.\"","id":2600}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f GENERIC_SWAP.AWK\nBEGIN {\n    printf(\"%s version %s\\n\",ARGV[0],PROCINFO[\"version\"])\n    foo = 1\n    bar = \"a\"\n    printf(\"\\n%s %s\\n\",foo,bar)\n    rc = swap(\"foo\",\"bar\") # ok\n    printf(\"%s %s %s\\n\",foo,bar,rc?\"ok\":\"ng\")\n    printf(\"\\n%s %s\\n\",foo,bar)\n    rc = swap(\"FOO\",\"BAR\") # ng\n    printf(\"%s %s %s\\n\",foo,bar,rc?\"ok\":\"ng\")\n    exit(0)\n}\nfunction swap(a1,a2,  tmp) { # strings or numbers only; no arrays\n    if (a1 in SYMTAB && a2 in SYMTAB) {\n      if (isarray(SYMTAB[a1]) || isarray(SYMTAB[a2])) {\n        return(0)\n      }\n      tmp = SYMTAB[a1]\n      SYMTAB[a1] = SYMTAB[a2]\n      SYMTAB[a2] = tmp\n      return(1)\n    }\n    return(0)\n}\n\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.","id":2601}
    {"lang_cluster":"AWK","source_code":"\n\nfunction is_palindro(s)\n{\n  if ( s == reverse(s) ) return 1\n  return 0\n}\n\n\nfunction is_palindro_r(s)\n{\n  if ( length(s) < 2 ) return 1\n  if ( substr(s, 1, 1) != substr(s, length(s), 1) ) return 0\n  return is_palindro_r(substr(s, 2, length(s)-2))\n}\n\n\nBEGIN {\n  pal = \"ingirumimusnocteetconsumimurigni\"\n  print is_palindro(pal)\n  print is_palindro_r(pal)\n}\n\n","human_summarization":"The code is a program that checks if a given sequence of characters is a palindrome. It supports Unicode characters and also detects inexact palindromes by ignoring white-space, punctuation, and case sensitivity. It uses both non-recursive and recursive methods for string reversal and testing.","id":2602}
    {"lang_cluster":"AWK","source_code":"\n\n$ awk 'BEGIN{print \"HOME:\"ENVIRON[\"HOME\"],\"USER:\"ENVIRON[\"USER\"]}'\n\n\n","human_summarization":"demonstrate how to retrieve a specific environment variable from a process, list all the environment variables, and assign environment variables to awk variables prior to execution. The code also explains that the ENVIRON array contains the current environment values and highlights common Unix environment variables such as PATH, HOME, and USER.","id":2603}
    {"lang_cluster":"AWK","source_code":"\n# syntax: GAWK -f SUDAN_FUNCTION.AWK\nBEGIN {\n    for (n=0; n<=1; n++) {\n      printf(\"sudan(%d,x,y)\\n\",n)\n      printf(\"y\/x    0   1   2   3   4   5\\n\")\n      printf(\"%s\\n\",strdup(\"-\",28))\n      for (y=0; y<=6; y++) {\n        printf(\"%2d | \",y)\n        for (x=0; x<=5; x++) {\n          printf(\"%3d \",sudan(n,x,y))\n        }\n        printf(\"\\n\")\n      }\n      printf(\"\\n\")\n    }\n    n=1; x=3; y=3; printf(\"sudan(%d,%d,%d)=%d\\n\",n,x,y,sudan(n,x,y))\n    n=2; x=1; y=1; printf(\"sudan(%d,%d,%d)=%d\\n\",n,x,y,sudan(n,x,y))\n    n=2; x=2; y=1; printf(\"sudan(%d,%d,%d)=%d\\n\",n,x,y,sudan(n,x,y))\n    n=3; x=1; y=1; printf(\"sudan(%d,%d,%d)=%d\\n\",n,x,y,sudan(n,x,y))\n    exit(0)\n}\nfunction sudan(n,x,y) {\n    if (n == 0) { return(x+y) }\n    if (y == 0) { return(x) }\n    return sudan(n-1, sudan(n,x,y-1), sudan(n,x,y-1)+y)\n}\nfunction strdup(str,n,  i,new_str) {\n    for (i=1; i<=n; i++) {\n      new_str = new_str str\n    }\n    return(new_str)\n}\n\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.","id":2604}
    {"lang_cluster":"ABAP","source_code":"\n\nreport z_stack.\n\ninterface stack.\n  methods:\n    push\n      importing\n        new_element      type any\n      returning\n        value(new_stack) type ref to stack,\n\n    pop\n      exporting\n        top_element      type any\n      returning\n        value(new_stack) type ref to stack,\n\n    empty\n      returning\n        value(is_empty) type abap_bool,\n\n    peek\n      exporting\n        top_element type any,\n\n    get_size\n      returning\n        value(size) type int4,\n\n    stringify\n      returning\n        value(stringified_stack) type string.\nendinterface.\n\n\nclass character_stack definition.\n  public section.\n    interfaces:\n      stack.\n\n\n    methods:\n      constructor\n        importing\n          characters type string optional.\n\n\n  private section.\n    data:\n      characters type string.\nendclass.\n\n\nclass character_stack implementation.\n  method stack~push.\n    characters = |{ new_element }{ characters }|.\n\n    new_stack = me.\n  endmethod.\n\n\n  method stack~pop.\n    if not me->stack~empty( ).\n      top_element = me->characters(1).\n\n      me->characters = me->characters+1.\n    endif.\n\n    new_stack = me.\n  endmethod.\n\n\n  method stack~empty.\n    is_empty = xsdbool( strlen( me->characters ) eq 0 ).\n  endmethod.\n\n\n  method stack~peek.\n    check not me->stack~empty( ).\n\n    top_element = me->characters(1).\n  endmethod.\n\n\n  method stack~get_size.\n    size = strlen( me->characters ).\n  endmethod.\n\n\n  method stack~stringify.\n    stringified_stack = cond string(\n      when me->stack~empty( )\n      then `empty`\n      else me->characters ).\n  endmethod.\n\n\n  method constructor.\n    check characters is not initial.\n\n    me->characters = characters.\n  endmethod.\nendclass.\n\n\nclass integer_stack definition.\n  public section.\n    interfaces:\n      stack.\n\n\n    methods:\n      constructor\n        importing\n          integers type int4_table optional.\n\n\n  private section.\n    data:\n      integers type int4_table.\nendclass.\n\n\nclass integer_stack implementation.\n  method stack~push.\n    append new_element to me->integers.\n\n    new_stack = me.\n  endmethod.\n\n\n  method stack~pop.\n    if not me->stack~empty( ).\n      top_element = me->integers[ me->stack~get_size( ) ].\n\n      delete me->integers index me->stack~get_size( ).\n    endif.\n\n    new_stack = me.\n  endmethod.\n\n\n  method stack~empty.\n    is_empty = xsdbool( lines( me->integers ) eq 0 ).\n  endmethod.\n\n\n  method stack~peek.\n    check not me->stack~empty( ).\n\n    top_element = me->integers[ lines( me->integers ) ].\n  endmethod.\n\n\n  method stack~get_size.\n    size = lines( me->integers ).\n  endmethod.\n\n\n  method stack~stringify.\n    stringified_stack = cond string(\n      when me->stack~empty( )\n      then `empty`\n      else reduce string(\n        init stack = ``\n        for integer in me->integers\n        next stack = |{ integer }{ stack }| ) ).\n  endmethod.\n\n\n  method constructor.\n    check integers is not initial.\n\n    me->integers = integers.\n  endmethod.\nendclass.\n\n\nstart-of-selection.\n  data:\n    stack1        type ref to stack,\n    stack2        type ref to stack,\n    stack3        type ref to stack,\n\n    top_character type char1,\n    top_integer   type int4.\n\n  stack1 = new character_stack( ).\n  stack2 = new integer_stack( ).\n  stack3 = new integer_stack( ).\n\n  write: |Stack1 = { stack1->stringify( ) }|, \/.\n  stack1->push( 'a' )->push( 'b' )->push( 'c' )->push( 'd' ).\n  write: |push a, push b, push c, push d -> Stack1 = { stack1->stringify( ) }|, \/.\n  stack1->pop( )->pop( importing top_element = top_character ).\n  write: |pop, pop and return element -> { top_character }, Stack1 = { stack1->stringify( ) }|, \/, \/.\n\n  write: |Stack2 = { stack2->stringify( ) }|, \/.\n  stack2->push( 1 )->push( 2 )->push( 3 )->push( 4 ).\n  write: |push 1, push 2, push 3, push 4 -> Stack2 = { stack2->stringify( ) }|, \/.\n  stack2->pop( )->pop( importing top_element = top_integer ).\n  write: |pop, pop and return element -> { top_integer }, Stack2 = { stack2->stringify( ) }|, \/, \/.\n\n  write: |Stack3 = { stack3->stringify( ) }|, \/.\n  stack3->pop( ).\n  write: |pop -> Stack3 = { stack3->stringify( ) }|, \/, \/.\n\n\n","human_summarization":"Implement a stack with basic operations such as push (to add an element to the top of the stack), pop (to remove and return the last pushed element from the stack), and empty (to check if the stack contains no elements). The stack follows a Last In, First Out (LIFO) access policy. This code is compatible with ABAP Version 7.40 and above.","id":2605}
    {"lang_cluster":"ABAP","source_code":"\nFORM fibonacci_iter USING index TYPE i\n                    CHANGING number_fib TYPE i.\n  DATA: lv_old type i,\n        lv_cur type i.\n  Do index times.\n    If sy-index = 1 or sy-index = 2.\n      lv_cur = 1.\n      lv_old = 0.\n    endif.\n    number_fib = lv_cur + lv_old.\n    lv_old = lv_cur.\n    lv_cur = number_fib.\n  enddo.\nENDFORM.\n\nWorks with: ABAP version 7.4 SP08 Or above only\ncl_demo_output=>display( REDUCE #( INIT fibnm = VALUE stringtab( ( |0| ) ( |1| ) )\n                                        n TYPE string\n                                        x = `0`\n                                        y = `1`\n                                      FOR i = 1 WHILE i <= 100\n                                     NEXT n = ( x + y )\n                                          fibnm = VALUE #( BASE fibnm ( n ) )\n                                          x = y\n                                          y = n ) ).\n\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":2606}
    {"lang_cluster":"ABAP","source_code":"\nreport zday_of_week\ndata: lv_start type i value 2007,\n      lv_n type i value 114,\n      lv_date type sy-datum,\n      lv_weekday type string,\n      lv_day type c,\n      lv_year type n length 4.\n\nwrite 'December 25 is a Sunday in: '.\ndo lv_n times.\n   lv_year = lv_start + sy-index.\n   concatenate lv_year '12' '25' into lv_date.\n   call function 'DATE_COMPUTE_DAY'\n    exporting date = lv_date\n    importing day  = lv_day.\n\n   select single langt from t246 into lv_weekday\n     where sprsl = sy-langu and\n     wotnr = lv_day.\n\n   if lv_weekday eq 'Sunday'.\n     write \/ lv_year.\n   endif.\nenddo.\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":2607}
    {"lang_cluster":"ABAP","source_code":"\n\nreport z_quicksort.\n\ndata(numbers) = value int4_table( ( 4 ) ( 65 ) ( 2 ) ( -31 ) ( 0 ) ( 99 ) ( 2 ) ( 83 ) ( 782 ) ( 1 ) ).\nperform quicksort changing numbers.\n\nwrite `[`.\nloop at numbers assigning field-symbol(<numbers>).\n  write <numbers>.\nendloop.\nwrite `]`.\n\nform quicksort changing numbers type int4_table.\n  data(less) = value int4_table( ).\n  data(equal) = value int4_table( ).\n  data(greater) = value int4_table( ).\n\n  if lines( numbers ) > 1.\n    data(pivot) = numbers[ lines( numbers ) \/ 2 ].\n\n    loop at numbers assigning field-symbol(<number>).\n      if <number> < pivot.\n        append <number> to less.\n      elseif <number> = pivot.\n        append <number> to equal.\n      elseif <number> > pivot.\n        append <number> to greater.\n      endif.\n    endloop.\n\n    perform quicksort changing less.\n    perform quicksort changing greater.\n\n    clear numbers.\n    append lines of less to numbers.\n    append lines of equal to numbers.\n    append lines of greater to numbers.\n  endif.\nendform.\n\n\n","human_summarization":"implement the quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and combines them with the pivot to produce a sorted array. The codes also consider different scenarios for optimal and worst-case pivots. The codes can either allocate new arrays or sort in place, and the pivot element can be chosen in various ways. The codes are optimized for ABAP Version 7.40 and above.","id":2608}
    {"lang_cluster":"ABAP","source_code":"\nreport zdate.\ndata: lv_month type string,\n      lv_weekday type string,\n      lv_date type string,\n      lv_day type c.\n\ncall function 'DATE_COMPUTE_DAY'\n  exporting date = sy-datum\n  importing day  = lv_day.\nselect single ltx from t247 into lv_month\n  where spras = sy-langu and\n  mnr = sy-datum+4(2).\n\nselect single langt from t246 into lv_weekday\n  where sprsl = sy-langu and\n  wotnr = lv_day.\n\nconcatenate lv_weekday ', ' lv_month ' ' sy-datum+6(2) ', ' sy-datum(4) into lv_date respecting blanks.\nwrite lv_date.\nconcatenate sy-datum(4) '-' sy-datum+4(2) '-' sy-datum+6(2) into lv_date.\nwrite \/ lv_date.\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":2609}
    {"lang_cluster":"ABAP","source_code":"\n\nreport z_powerset.\n\ninterface set.\n  methods:\n    add_element\n      importing\n        element_to_be_added type any\n      returning\n        value(new_set)      type ref to set,\n\n    remove_element\n      importing\n        element_to_be_removed type any\n      returning\n        value(new_set)        type ref to set,\n\n    contains_element\n      importing\n        element_to_be_found type any\n      returning\n        value(contains)     type abap_bool,\n\n    get_size\n      returning\n        value(size) type int4,\n\n    is_equal\n      importing\n        set_to_be_compared_with type ref to set\n      returning\n        value(equal)            type abap_bool,\n\n    get_elements\n      exporting\n        elements type any table,\n\n    stringify\n      returning\n        value(stringified_set) type string.\nendinterface.\n\n\nclass string_set definition.\n  public section.\n    interfaces:\n      set.\n\n\n    methods:\n      constructor\n        importing\n          elements type stringtab optional,\n\n      build_powerset\n        returning\n          value(powerset) type ref to string_set.\n\n\n  private section.\n    data elements type stringtab.\nendclass.\n\n\nclass string_set implementation.\n  method constructor.\n    loop at elements into data(element).\n      me->set~add_element( element ).\n    endloop.\n  endmethod.\n\n\n  method set~add_element.\n    if not line_exists( me->elements[ table_line = element_to_be_added ] ).\n      append element_to_be_added to me->elements.\n    endif.\n\n    new_set = me.\n  endmethod.\n\n\n  method set~remove_element.\n    if line_exists( me->elements[ table_line = element_to_be_removed ] ).\n      delete me->elements where table_line = element_to_be_removed.\n    endif.\n\n    new_set = me.\n  endmethod.\n\n\n  method set~contains_element.\n    contains = cond abap_bool(\n      when line_exists( me->elements[ table_line = element_to_be_found ] )\n      then abap_true\n      else abap_false ).\n  endmethod.\n\n\n  method set~get_size.\n    size = lines( me->elements ).\n  endmethod.\n\n\n  method set~is_equal.\n    if set_to_be_compared_with->get_size( ) ne me->set~get_size( ).\n      equal = abap_false.\n\n      return.\n    endif.\n\n    loop at me->elements into data(element).\n      if not set_to_be_compared_with->contains_element( element ).\n        equal = abap_false.\n\n        return.\n      endif.\n    endloop.\n\n    equal = abap_true.\n  endmethod.\n\n\n  method set~get_elements.\n    elements = me->elements.\n  endmethod.\n\n\n  method set~stringify.\n    stringified_set = cond string(\n      when me->elements is initial\n      then `\u2205`\n      when me->elements eq value stringtab( ( `\u2205` ) )\n      then `{ \u2205 }`\n      else reduce string(\n        init result = `{ `\n        for element in me->elements\n        next result = cond string(\n          when element eq ``\n          then |{ result }\u2205, |\n          when strlen( element ) eq 1 and element ne `\u2205`\n          then |{ result }{ element }, |\n          else |{ result }\\{{ element }\\}, | ) ) ).\n\n    stringified_set = replace(\n      val = stringified_set\n      regex = `, $`\n      with = ` }`).\n  endmethod.\n\n\n  method build_powerset.\n    data(powerset_elements) = value stringtab( ( `` ) ).\n\n    loop at me->elements into data(element).\n      do lines( powerset_elements ) times.\n        if powerset_elements[ sy-index ] ne `\u2205`.\n          append |{ powerset_elements[ sy-index ] }{ element }| to powerset_elements.\n        else.\n          append element to powerset_elements.\n        endif.\n      enddo.\n    endloop.\n\n    powerset = new string_set( powerset_elements ).\n  endmethod.\nendclass.\n\n\nstart-of-selection.\n  data(set1) = new string_set( ).\n  data(set2) = new string_set( ).\n  data(set3) = new string_set( ).\n\n  write: |\ud835\udc77( { set1->set~stringify( ) } ) -> { set1->build_powerset( )->set~stringify( ) }|, \/.\n\n  set2->set~add_element( `\u2205` ).\n  write: |\ud835\udc77( { set2->set~stringify( ) } ) -> { set2->build_powerset( )->set~stringify( ) }|, \/.\n\n  set3->set~add_element( `1` )->add_element( `2` )->add_element( `3` )->add_element( `3` )->add_element( `4`\n    )->add_element( `4` )->add_element( `4` ).\n  write: |\ud835\udc77( { set3->set~stringify( ) } ) -> { set3->build_powerset( )->set~stringify( ) }|, \/.\n\n\n","human_summarization":"The code takes a set S as input and generates its power set. The power set includes all possible subsets of the input set, including the empty set and the set itself. It also handles edge cases where the input set is empty or contains only the empty set. The code is compatible with ABAP Version 7.40 and above.","id":2610}
    {"lang_cluster":"ABAP","source_code":"\n\nTYPES: tty_int TYPE STANDARD TABLE OF i\n                    WITH NON-UNIQUE DEFAULT KEY.\n\nDATA(itab) = VALUE tty_int( ( 1 )\n                            ( 2 )\n                            ( 3 ) ).\n\nINSERT 4 INTO TABLE itab.\nAPPEND 5 TO itab.\nDELETE itab INDEX 1.\n\ncl_demo_output=>display( itab ).\ncl_demo_output=>display( itab[ 2 ] ).\n\n\n","human_summarization":"demonstrate the basic syntax of arrays in a specific language, including the creation of an array, assignment of values, and retrieval of elements. It covers both fixed-length and dynamic arrays, and also showcases the use of a construct called internal tables in the absence of real arrays in ABAP.","id":2611}
    {"lang_cluster":"ABAP","source_code":"\nREPORT z_test_rosetta_collection.\n\nCLASS lcl_collection DEFINITION CREATE PUBLIC.\n\n  PUBLIC SECTION.\n    METHODS: start.\nENDCLASS.\n\nCLASS lcl_collection IMPLEMENTATION.\n  METHOD start.\n    DATA(itab) = VALUE int4_table( ( 1 ) ( 2 ) ( 3 ) ).\n\n    cl_demo_output=>display( itab ).\n  ENDMETHOD.\nENDCLASS.\n\nSTART-OF-SELECTION.\n  NEW lcl_collection( )->start( ).\n\n","human_summarization":"Create and populate a collection in a statically-typed language. Review and ensure the code examples meet the task requirements.","id":2612}
    {"lang_cluster":"ABAP","source_code":"\nreport z_align no standard page header.\nstart-of-selection.\n\ndata: lt_strings type standard table of string,\n      lv_strings type string.\nappend: 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$' to lt_strings,\n        'are$delineated$by$a$single$''dollar''$character,$write$a$program' to lt_strings,\n        'that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$' to lt_strings,\n        'column$are$separated$by$at$least$one$space.' to lt_strings,\n        'Further,$allow$for$each$word$in$a$column$to$be$either$left$' to lt_strings,\n        'justified,$right$justified,$or$center$justified$within$its$column.' to lt_strings.\ntypes ty_strings type standard table of string.\n\nperform align_col using 'LEFT' lt_strings.\nskip.\nperform align_col using 'RIGHT' lt_strings.\nskip.\nperform align_col using 'CENTER' lt_strings.\n\n\nform align_col using iv_just type string iv_strings type ty_strings.\n  constants: c_del value '$'.\n  data: lv_string type string,\n        lt_strings type table of string,\n        lt_tables like table of lt_strings,\n        lv_first type string,\n        lv_second type string,\n        lv_longest type i value 0,\n        lv_off type i value 0,\n        lv_len type i.\n  \" Loop through the supplied text. It is expected at the input is a table of strings, with each\n  \" entry in the table representing a new line of the input.\n  loop at iv_strings into lv_string.\n    \" Split the current line at the delimiter.\n    split lv_string at c_del into lv_first lv_second.\n    \" Loop through the line splitting at every delimiter.\n    do.\n      append lv_first to lt_strings.\n      lv_len = strlen( lv_first ).\n      \" Check if the length of the new string is greater than the currently stored length.\n      if lv_len > lv_longest.\n        lv_longest = lv_len.\n      endif.\n      if lv_second na c_del.\n        \" Check if the string is longer than the recorded maximum.\n        lv_len = strlen( lv_second ).\n        if lv_len > lv_longest.\n          lv_longest = lv_len.\n        endif.\n        append lv_second to lt_strings.\n        exit.\n      endif.\n      split lv_second at c_del into lv_first lv_second.\n    enddo.\n\n    append lt_strings to lt_tables.\n    clear lt_strings.\n  endloop.\n\n  \" Loop through each line of input.\n  loop at lt_tables into lt_strings.\n    \" Loop through each word in the line (Separated by specified delimiter).\n    loop at lt_strings into lv_string.\n      lv_off = ( sy-tabix - 1 ) * ( lv_longest + 2 ).\n      case iv_just.\n        when 'LEFT'.\n          write : at (lv_longest) lv_string left-justified.\n        when 'RIGHT'.\n          write at (lv_longest) lv_string right-justified.\n        when 'CENTER'.\n          write at (lv_longest) lv_string centered.\n      endcase.\n    endloop.\n    skip.\n    sy-linno = sy-linno - 1.\n  endloop.\nendform.\n\nGiven      a          text       file       of         many       lines,     where      fields     within     a          line\nare        delineated by         a          single     'dollar'   character, write      a          program\nthat       aligns     each       column     of         fields     by         ensuring   that       words      in         each\ncolumn     are        separated  by         at         least      one        space.\nFurther,   allow      for        each       word       in         a          column     to         be         either     left\njustified, right      justified, or         center     justified  within     its        column.\n\n     Given          a       text       file         of       many     lines,      where     fields     within          a       line\n       are delineated         by          a     single   'dollar' character,      write          a    program\n      that     aligns       each     column         of     fields         by   ensuring       that      words         in       each\n    column        are  separated         by         at      least        one     space.\n  Further,      allow        for       each       word         in          a     column         to         be     either       left\njustified,      right justified,         or     center  justified     within        its    column.\n\n  Given        a         text       file        of        many      lines,     where      fields     within       a         line\n   are     delineated     by         a        single    'dollar'  character,   write        a       program\n   that      aligns      each      column       of       fields       by      ensuring     that      words        in        each\n  column      are     separated      by         at       least       one       space.\n Further,    allow       for        each       word        in         a        column       to         be       either      left\njustified,   right    justified,     or       center   justified    within      its      column.\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":2613}
    {"lang_cluster":"ABAP","source_code":"\n\ndata: lv_flag type c,\n      lv_number type i,\n      lt_numbers type table of i.\n\nconstants: c_no_val type i value 9999.\n\nappend 1 to lt_numbers.\nappend 1 to lt_numbers.\nappend 2 to lt_numbers.\nappend 7 to lt_numbers.\n\nwrite 'Evaluating 24 with the following input: '.\nloop at lt_numbers into lv_number.\n  write lv_number.\nendloop.  \nperform solve_24 using lt_numbers.\n\nform eval_formula using iv_eval type string changing ev_out type i.\n  call function 'EVAL_FORMULA' \"analysis of a syntactically correct formula\n    exporting\n      formula = iv_eval\n    importing\n      value   = ev_out\n    exceptions\n   others     = 1.\n\n  if sy-subrc <> 0.\n    ev_out = -1.\n  endif.\nendform.\n\n\" Solve a 24 puzzle.\nform solve_24 using it_numbers like lt_numbers.\n  data: lv_flag   type c,\n        lv_op1    type c,\n        lv_op2    type c,\n        lv_op3    type c,\n        lv_var1   type c,\n        lv_var2   type c,\n        lv_var3   type c,\n        lv_var4   type c,\n        lv_eval   type string,\n        lv_result type i,\n        lv_var     type i.\n\n  define retrieve_var.\n    read table it_numbers index &1 into lv_var.\n    &2 = lv_var.\n  end-of-definition.\n\n  define retrieve_val.\n    perform eval_formula using lv_eval changing lv_result.\n    if lv_result = 24.\n        write \/ lv_eval.\n    endif.\n  end-of-definition.\n  \" Loop through all the possible number permutations.\n  do.\n    \" Init. the operations table.\n\n    retrieve_var: 1 lv_var1, 2 lv_var2, 3 lv_var3, 4 lv_var4.\n    do 4 times.\n      case sy-index.\n        when 1.\n          lv_op1 = '+'.\n        when 2.\n          lv_op1 = '*'.\n        when 3.\n          lv_op1 = '-'.\n        when 4.\n          lv_op1 = '\/'.\n      endcase.\n      do 4 times.\n        case sy-index.\n        when 1.\n          lv_op2 = '+'.\n        when 2.\n          lv_op2 = '*'.\n        when 3.\n          lv_op2 = '-'.\n        when 4.\n          lv_op2 = '\/'.\n        endcase.\n        do 4 times.\n          case sy-index.\n          when 1.\n            lv_op3 = '+'.\n          when 2.\n            lv_op3 = '*'.\n          when 3.\n            lv_op3 = '-'.\n          when 4.\n            lv_op3 = '\/'.\n          endcase.\n          concatenate '(' '(' lv_var1 lv_op1 lv_var2 ')' lv_op2 lv_var3 ')' lv_op3 lv_var4  into lv_eval separated by space.\n          retrieve_val.\n          concatenate '(' lv_var1 lv_op1 lv_var2 ')' lv_op2 '(' lv_var3 lv_op3 lv_var4 ')'  into lv_eval separated by space.\n          retrieve_val.\n          concatenate '(' lv_var1 lv_op1 '(' lv_var2 lv_op2 lv_var3 ')' ')' lv_op3 lv_var4  into lv_eval separated by space.\n          retrieve_val.\n          concatenate lv_var1 lv_op1 '(' '(' lv_var2 lv_op2 lv_var3 ')' lv_op3 lv_var4 ')'  into lv_eval separated by space.\n          retrieve_val.\n          concatenate lv_var1 lv_op1 '(' lv_var2 lv_op2 '(' lv_var3 lv_op3 lv_var4 ')' ')'  into lv_eval separated by space.\n          retrieve_val.\n        enddo.\n      enddo.\n    enddo.\n\n    \" Once we've reached the last permutation -> Exit.\n    perform permute using it_numbers changing lv_flag.\n    if lv_flag = 'X'.\n      exit.\n    endif.\n  enddo.\nendform.\n\n\n\" Permutation function - this is used to permute:\n\" A = {A1...AN} -> Set of supplied variables.\n\" B = {B1...BN - 1} -> Set of operators.\n\" Can be used for an unbounded size set. Relies\n\" on lexicographic ordering of the set.\nform permute using iv_set like lt_numbers\n             changing ev_last type c.\n  data: lv_len     type i,\n        lv_first   type i,\n        lv_third   type i,\n        lv_count   type i,\n        lv_temp    type i,\n        lv_temp_2  type i,\n        lv_second  type i,\n        lv_changed type c,\n        lv_perm    type i.\n  describe table iv_set lines lv_len.\n\n  lv_perm = lv_len - 1.\n  lv_changed = ' '.\n  \" Loop backwards through the table, attempting to find elements which\n  \" can be permuted. If we find one, break out of the table and set the\n  \" flag indicating a switch.\n  do.\n    if lv_perm <= 0.\n      exit.\n    endif.\n    \" Read the elements.\n    read table iv_set index lv_perm into lv_first.\n    add 1 to lv_perm.\n    read table iv_set index lv_perm into lv_second.\n    subtract 1 from lv_perm.\n    if lv_first < lv_second.\n      lv_changed = 'X'.\n      exit.\n    endif.\n    subtract 1 from lv_perm.\n  enddo.\n\n  \" Last permutation.\n  if lv_changed <> 'X'.\n    ev_last = 'X'.\n    exit.\n  endif.\n\n  \" Swap tail decresing to get a tail increasing.\n  lv_count = lv_perm + 1.\n  do.\n    lv_first = lv_len + lv_perm - lv_count + 1.\n    if lv_count >= lv_first.\n      exit.\n    endif.\n\n    read table iv_set index lv_count into lv_temp.\n    read table iv_set index lv_first into lv_temp_2.\n    modify iv_set index lv_count from lv_temp_2.\n    modify iv_set index lv_first from lv_temp.\n    add 1 to lv_count.\n  enddo.\n\n  lv_count = lv_len - 1.\n  do.\n    if lv_count <= lv_perm.\n      exit.\n    endif.\n\n    read table iv_set index lv_count into lv_first.\n    read table iv_set index lv_perm into lv_second.\n    read table iv_set index lv_len into lv_third.\n    if ( lv_first < lv_third ) and ( lv_first > lv_second ).\n      lv_len = lv_count.\n    endif.\n\n    subtract 1 from lv_count.\n  enddo.\n\n  read table iv_set index lv_perm into lv_temp.\n  read table iv_set index lv_len into lv_temp_2.\n  modify iv_set index lv_perm from lv_temp_2.\n  modify iv_set index lv_len from lv_temp.\nendform.\n\n\n","human_summarization":"The code takes four digits as input, either from the user or randomly generated, and computes all possible arithmetic expressions following the rules of the 24 game. It also displays examples of the solutions it generates.","id":2614}
    {"lang_cluster":"ABAP","source_code":"\nform factorial using iv_val type i.\n  data: lv_res type i value 1.\n  do iv_val times.\n    multiply lv_res by sy-index.\n  enddo.\n\n  iv_val = lv_res.\nendform.\n\nform fac_rec using iv_val type i.\n  data: lv_temp type i.\n\n  if iv_val = 0.\n    iv_val = 1.\n  else.\n    lv_temp = iv_val - 1.\n    perform fac_rec using lv_temp.\n    multiply iv_val by lv_temp.\n  endif.\nendform.\n\n","human_summarization":"The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.","id":2615}
    {"lang_cluster":"ABAP","source_code":"\nreport zdot_product\ndata: lv_n type i,\n      lv_sum type i,\n      lt_a type standard table of i,\n      lt_b type standard table of i.\n\nappend: '1' to lt_a, '3' to lt_a, '-5' to lt_a.\nappend: '4' to lt_b, '-2' to lt_b, '-1' to lt_b.\ndescribe table lt_a lines lv_n.\n\nperform dot_product using lt_a lt_b lv_n changing lv_sum.\n\nwrite lv_sum left-justified.\n\nform dot_product using it_a like lt_a\n                       it_b like lt_b\n                       iv_n type i\n                 changing\n                       ev_sum type i.\n  field-symbols: <wa_a> type i, <wa_b> type i.\n\n  do iv_n times.\n    read table: it_a assigning <wa_a> index sy-index, it_b assigning <wa_b> index sy-index.\n    lv_sum = lv_sum + ( <wa_a> * <wa_b> ).\n  enddo.\nendform.\n\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":2616}
    {"lang_cluster":"ABAP","source_code":"\nDATA: xml_string TYPE string.\n\nDATA(xml)  = cl_ixml=>create( ).\nDATA(doc)  = xml->create_document( ).\nDATA(root) = doc->create_simple_element( name   = 'root'\n                                         parent = doc ).\n\ndoc->create_simple_element( name   = 'element'\n                            parent = root\n                            value  = 'Some text here' ).\n\nDATA(stream_factory) = xml->create_stream_factory( ).\nDATA(stream)         = stream_factory->create_ostream_cstring( string = xml_string ).\nDATA(renderer)       = xml->create_renderer( document = doc\n                                             ostream  = stream ).\nstream->set_pretty_print( abap_true ).\nrenderer->render( ).\n\ncl_demo_output=>display_text( xml_string ).\n\n\n<?xml version=\"1.0\" encoding=\"utf-16\"?>\n<root>\n<element>Some text here<\/element>\n<\/root>\n","human_summarization":"Create a simple DOM and serialize it into XML format. The XML output includes a root element containing a single element with some text.","id":2617}
    {"lang_cluster":"ABAP","source_code":"\nREPORT system_time.\n\nWRITE: sy-uzeit.\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":2618}
    {"lang_cluster":"ABAP","source_code":"\nREPORT guess_the_number.\n\nDATA prng TYPE REF TO cl_abap_random_int.\n\ncl_abap_random_int=>create(\n  EXPORTING\n    seed = cl_abap_random=>seed( )\n    min  = 1\n    max  = 10\n  RECEIVING\n    prng = prng ).\n\nDATA(number) = prng->get_next( ).\n\nDATA(field) = VALUE i( ).\n\ncl_demo_input=>add_field( EXPORTING text = |Choice one number between 1 and 10| CHANGING field = field ).\ncl_demo_input=>request( ).\n\nWHILE number <> field.\n  cl_demo_input=>add_field( EXPORTING text = |You miss, try again| CHANGING field = field ).\n  cl_demo_input=>request( ).\nENDWHILE.\n\ncl_demo_output=>display( |Well Done| ).\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":2619}
    {"lang_cluster":"ABAP","source_code":"\nREPORT lower_case_ascii.\n\nWRITE: \/ to_lower( sy-abcde ).\n\nREPORT lower_case_ascii.\n\ncl_demo_output=>new(\n          )->begin_section( |Generate lower case ASCII alphabet|\n          )->write( REDUCE string( INIT out TYPE string\n                                    FOR char = 1 UNTIL char > strlen( sy-abcde )\n                                   NEXT out = COND #( WHEN out IS INITIAL THEN sy-abcde(1)\n                                                      ELSE |{ out } { COND string( WHEN char <> strlen( sy-abcde ) THEN sy-abcde+char(1) ) }| ) )\n          )->write( |Or use the system field: { sy-abcde }|\n          )->display( ).\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":2620}
    {"lang_cluster":"ABAP","source_code":"\n  DATA: X1 TYPE F, Y1 TYPE F,\n        X2 TYPE F, Y2 TYPE F, YD TYPE F,\n        PI TYPE F,\n        PI_180 TYPE F,\n        MINUS_1 TYPE F VALUE '-1'.\n\nPI     = ACOS( MINUS_1 ).\nPI_180 = PI \/ 180.\n\nLATITUDE1 = 36,12 . LONGITUDE1 = -86,67 .\nLATITUDE2 = 33,94 . LONGITUDE2 = -118,4 .\n\n  X1 = LATITUDE1  * PI_180.\n  Y1 = LONGITUDE1 * PI_180.\n  X2 = LATITUDE2  * PI_180.\n  Y2 = LONGITUDE2 * PI_180.\n  YD = Y2 - Y1.\n\n  DISTANCE = 20000 \/ PI *\n    ACOS( SIN( X1 ) * SIN( X2 ) + COS( X1 ) * COS( X2 ) * COS( YD ) ).\n\nWRITE : 'Distance between given points = ' , distance , 'km .' .\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":2621}
    {"lang_cluster":"ABAP","source_code":"\n\nreport z_http.\n\ncl_http_client=>create_by_url(\n  exporting\n    url                = `http:\/\/rosettacode.org\/robots.txt`\n  importing\n    client             = data(http_client)\n  exceptions\n    argument_not_found = 1\n    plugin_not_active  = 2\n    internal_error     = 3\n    others             = 4 ).\n\nif sy-subrc <> 0.\n  data(error_message) = switch string( sy-subrc\n    when 1 then `argument_not_found`\n    when 2 then `plugin_not_active`\n    when 3 then `internal_error`\n    when 4 then `other error` ).\n\n  write error_message.\n  exit.\nendif.\n\ndata(rest_http_client) = cast if_rest_client( new cl_rest_http_client( http_client ) ).\n\nrest_http_client->get( ).\n\ndata(response_string) = rest_http_client->get_response_entity( )->get_string_data( ).\n\nsplit response_string at cl_abap_char_utilities=>newline into table data(output_table).\n\nloop at output_table assigning field-symbol(<output_line>).\n  write \/ <output_line>.\nendloop.\n\n\n","human_summarization":"Accesses and prints the content of a specified URL to the console using HTTP protocol, compatible with ABAP Version 7.40 and above.","id":2622}
    {"lang_cluster":"ABAP","source_code":"\nMETHOD luhn_check.\n\n  DATA: sum(1) TYPE n VALUE 0. \" Sum of checksum.\n  DATA: current TYPE i. \" Current digit.\n  DATA: odd TYPE i VALUE 1. \" Multiplier.\n  DATA: len TYPE i. \" String crowler.\n\n\n  \" Luhn algorithm.\n  len = NUMOFCHAR( pi_string ) - 1.\n  WHILE ( len >= 0 ).\n    current = pi_string+len(1) * odd.\n    IF ( current > 9 ).\n      current = current - 9. \" Digits sum.\n    ENDIF.\n    sum = sum + current.\n    odd = 3 - odd. \" 1 <--> 2 Swich\n    len = len - 1. \" Move to next charcter.\n  ENDWHILE.\n\n  \" Validation check.\n  IF ( sum = 0 ).\n    pr_valid = abap_true.\n  ELSE.\n    pr_valid = abap_false.\n  ENDIF.\n\nENDMETHOD.\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":2623}
    {"lang_cluster":"ABAP","source_code":"\n\nreport z_repeat_string.\n\nwrite repeat( val = `ha`  occ = 5 ).\n\n\n","human_summarization":"The code takes a string and a number as input, repeats the string the given number of times and returns the resulting string. It also includes a more efficient method to repeat a single character. This is applicable for ABAP Version 7.40 and above.","id":2624}
    {"lang_cluster":"ABAP","source_code":"\nDATA: text TYPE string VALUE 'This is a Test'.\n\nFIND FIRST OCCURRENCE OF REGEX 'is' IN text.\nIF sy-subrc = 0.\n  cl_demo_output=>write( 'Regex matched' ).\nENDIF.\n\nREPLACE ALL OCCURRENCES OF REGEX '[t|T]est' IN text WITH 'Regex'.\n\ncl_demo_output=>write( text ).\ncl_demo_output=>display( ).\n\n\nRegex matched\n\nThis is a Regex\n\n","human_summarization":"\"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression.\"","id":2625}
    {"lang_cluster":"ABAP","source_code":"\nreport zz_arithmetic no standard page heading.\n\n\" Read in the two numbers from the user.\nselection-screen begin of block input.\n  parameters: p_first type i,\n              p_second type i.\nselection-screen end of block input.\n\n\" Set the text value that is displayed on input request.\nat selection-screen output.\n  %_p_first_%_app_%-text  = 'First Number: '.\n  %_p_second_%_app_%-text = 'Second Number: '.\n\nend-of-selection.\n  data: lv_result type i.\n  lv_result = p_first + p_second.\n  write: \/ 'Addition:', lv_result.\n  lv_result = p_first - p_second.\n  write: \/ 'Substraction:', lv_result.\n  lv_result = p_first * p_second.\n  write: \/ 'Multiplication:', lv_result.\n  lv_result = p_first div p_second.\n  write: \/ 'Integer quotient:', lv_result. \" Truncated towards zero.\n  lv_result = p_first mod p_second.\n  write: \/ 'Remainder:',  lv_result.\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":2626}
    {"lang_cluster":"ABAP","source_code":"\nCLASS lcl_binom DEFINITION CREATE PUBLIC.\n\n  PUBLIC SECTION.\n    CLASS-METHODS:\n      calc\n        IMPORTING n               TYPE i\n                  k               TYPE i\n        RETURNING VALUE(r_result) TYPE f.\n\nENDCLASS.\n\nCLASS lcl_binom IMPLEMENTATION.\n\n  METHOD calc.\n\n    r_result = 1.\n    DATA(i) = 1.\n    DATA(m) = n.\n\n    WHILE i <= k.\n      r_result = r_result * m \/ i.\n      i = i + 1.\n      m = m - 1.\n    ENDWHILE.\n\n  ENDMETHOD.\n\nENDCLASS.\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":2627}
    {"lang_cluster":"ABAP","source_code":"\nreport zz_incstring\nperform test using: '0', '1', '-1', '10000000', '-10000000'.\n\nform test using iv_string type string.\n  data: lv_int  type i,\n        lv_string type string.\n  lv_int = iv_string + 1.\n  lv_string = lv_int.\n  concatenate '\"' iv_string '\" + 1 = \"' lv_string '\"' into lv_string.\n  write \/ lv_string.\nendform.\n\n\n","human_summarization":"\"Increments a given numerical string.\"","id":2628}
    {"lang_cluster":"ABAP","source_code":"\nWorks with: ABAP version 7.4 SP05 or Above only\nDATA: tab TYPE TABLE OF string.\n\ntab = VALUE #(\n  FOR i = 1 WHILE i <= 100 (\n    COND string( LET r3 = i MOD 3\n                     r5 = i MOD 5 IN\n                 WHEN r3 = 0 AND r5 = 0 THEN |FIZZBUZZ|\n                 WHEN r3 = 0            THEN |FIZZ|\n                 WHEN r5 = 0            THEN |BUZZ|\n                 ELSE i ) ) ).\n\ncl_demo_output=>write( tab ).\ncl_demo_output=>display( ).\n\nWorks with: ABAP version 7.4 SP05 or Above only\ncl_demo_output=>display( value stringtab( for i = 1 until i > 100\n                                          let fizz = cond #( when i mod 3 = 0 then |fizz| else space )\n                                              buzz = cond #( when i mod 5 = 0 then |buzz| else space )\n                                              fb   = |{ fizz }{ buzz }| in\n                                         ( switch #( fb when space then i else fb ) ) ) ).\n\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":2629}
    {"lang_cluster":"ABAP","source_code":"\ndata: lv_string1 type string value 'Test',\n      lv_string2 type string.\nlv_string2 = lv_string1.\n\nWorks with: ABAP version 7.4 Or above only\nDATA(string1) = |Test|.\nDATA(string2) = string1.\n\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":2630}
    {"lang_cluster":"ABAP","source_code":"\n\nreport z_mutual_recursion.\n\nclass hoffstadter_sequences definition.\n  public section.\n    class-methods:\n      f\n        importing\n          n             type int4\n        returning\n          value(result) type int4,\n\n      m\n        importing\n          n             type int4\n        returning\n          value(result) type int4.\nendclass.\n\n\nclass hoffstadter_sequences implementation.\n  method f.\n    result = cond int4(\n      when n eq 0\n      then 1\n      else n - m( f( n - 1 ) ) ).\n  endmethod.\n\n\n  method m.\n    result = cond int4(\n      when n eq 0\n      then 0\n      else n - f( m( n - 1 ) ) ).\n  endmethod.\nendclass.\n\n\nstart-of-selection.\n  write: |{ reduce string(\n    init results = |f(0 - 19): { hoffstadter_sequences=>f( 0 ) }|\n    for i = 1 while i < 20\n    next results = |{ results }, { hoffstadter_sequences=>f( i ) }| ) }|, \/.\n\n  write: |{ reduce string(\n    init results = |m(0 - 19): { hoffstadter_sequences=>m( 0 ) }|\n    for i = 1 while i < 20\n    next results = |{ results }, { hoffstadter_sequences=>m( i ) }| ) }|, \/.\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions are defined such that each function calls the other during its computation. The solution is applicable for ABAP Version 7.40 and can be implemented in procedural ABAP, with enhanced readability when used with classes.","id":2631}
    {"lang_cluster":"ABAP","source_code":"\nREPORT Z_DECODE_URL.\n\nDATA: lv_encoded_url TYPE string VALUE 'http%3A%2F%2Ffoo%20bar%2F',\n      lv_decoded_url TYPE string.\n\nCALL METHOD CL_HTTP_UTILITY=>UNESCAPE_URL\n  EXPORTING\n    ESCAPED   = lv_encoded_url\n  RECEIVING\n    UNESCAPED = lv_decoded_url.\n\nWRITE: 'Encoded URL: ', lv_encoded_url, \/, 'Decoded URL: ', lv_decoded_url.\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":2632}
    {"lang_cluster":"ABAP","source_code":"\nreport z24_with_rpn\nconstants: c_eval_to   type i value 24,\n           c_tolerance type f value '0.0001'.\ndata: gt_val type table of f,\n      gv_val type f,\n      gv_pac type p,\n      gv_chk type c.\n\" Log a message from the RPN Calculator.\nform rpn_log using lv_msg type string.\n  write : \/ 'RPN Message: ', lv_msg.\nendform.\n\n\" Performs add in Reverse Polish Notation.\nform rpn_add.\n  data: lv_val1 type f,\n        lv_val2 type f.\n  \" Get the last two values from the stack to add together.\n  perform rpn_pop changing: lv_val1, lv_val2.\n  add lv_val2 to lv_val1.\n  \" Add them and then add them back to the \"top\".\n  perform rpn_push using lv_val1.\nendform.\n\n\" Perform subtraction in RPN.\nform rpn_sub.\n  data: lv_val1 type f,\n        lv_val2 type f.\n  \" Get the last two values, subtract them, and push them back on.\n  perform rpn_pop changing: lv_val1, lv_val2.\n  subtract lv_val1 from lv_val2.\n  perform rpn_push using lv_val2.\nendform.\n\n\" Perform multiplication in RPN.\nform rpn_mul.\n  data: lv_val1 type f,\n        lv_val2 type f.\n  \" Get the last two values, multiply, and push them back.\n  perform rpn_pop changing: lv_val1, lv_val2.\n  multiply lv_val1 by lv_val2.\n  perform rpn_push using lv_val1.\nendform.\n\n\" Perform division in RPN.\nform rpn_div.\n  data: lv_val1 type f,\n        lv_val2 type f.\n  \" Get the last two values, divide the first by the second\n  \" and then add it back to the stack.\n  perform rpn_pop changing: lv_val1, lv_val2.\n  divide lv_val1 by lv_val2.\n  perform rpn_push using lv_val1.\nendform.\n\n\" Negate a number in RPN.\nform rpn_neg.\n  data: lv_val type f.\n  \" Simply get the last number and negate it before pushing it back.\n  perform rpn_pop changing lv_val.\n  multiply lv_val by -1.\n  perform rpn_push using lv_val.\nendform.\n\n\" Swap the top two values on the RPN Stack.\nform rpn_swap.\n  data: lv_val1 type f,\n        lv_val2 type f.\n  \" Get the top two values and then add them back in reverse order.\n  perform rpn_pop changing: lv_val1, lv_val2.\n  perform rpn_push using: lv_val2, lv_val1.\nendform.\n\n\" Call the relevant RPN operation.\nform rpn_call_op using iv_op type string.\n  case iv_op.\n    when '+'.\n      perform rpn_add.\n    when '-'.\n      perform rpn_sub.\n    when '*'.\n      perform rpn_mul.\n    when '\/'.\n      perform rpn_div.\n    when 'n'.\n      perform rpn_neg.\n    when 's'.\n      perform rpn_swap.\n    when others. \" Bad op-code found!\n      perform rpn_log using 'Operation not found!'.\n    endcase.\nendform.\n\n\" Reverse_Polish_Notation Parser.\nform rpn_pop changing ev_out type f.\n  \" Attempt to get the entry from the 'top' of the table.\n  \" If it's empty --> log an error and bail.\n  data: lv_lines type i.\n\n  describe table gt_val lines lv_lines.\n  if lv_lines > 0.\n    \" After we have retrieved the value, we must remove it from the table.\n    read table gt_val index lv_lines into ev_out.\n    delete gt_val index lv_lines.\n  else.\n    perform rpn_log using 'RPN Stack is empty! Underflow!'.\n    ev_out = 0.\n  endif.\nendform.\n\n\" Pushes the supplied value onto the RPN table \/ stack.\nform rpn_push using iv_val type f.\n  \" Simple append - other languages this involves a stack of a certain size.\n  append iv_val to gt_val.\nendform.\n\n\" Refreshes the RPN stack \/ table.\nform rpn_reset.\n  \" Clear the stack to start anew.\n  refresh gt_val.\nendform.\n\n\" Checks if the supplied string is numeric.\n\" Lazy evaluation - only checkcs for numbers without formatting.\nform rpn_numeric using    iv_in  type string\n                 changing ev_out type c.\n  data: lv_moff type i,\n        lv_len  type i.\n  \" Match digits with optional decimal places.\n  find regex '\\d+(\\.\\d+)*' in iv_in\n    match offset lv_moff\n    match length lv_len.\n  \" Get the offset and length of the first occurence, and work\n  \" out the length of the match.\n  subtract lv_moff from lv_len.\n  \" If the length is different to the length of the whole string,\n  \" then it's NOT a match, else it is.\n  if lv_len ne strlen( iv_in ).\n    ev_out = ' '.\n  else.\n    ev_out = 'X'.\n  endif.\nendform.\n\n\" Convert input to a number. Added safety net of is_numeric.\nform rpn_get_num using iv_in type string changing ev_num type f.\n  data: lv_check type c.\n  \" Check if it's numeric - built in redundancy.\n  perform rpn_numeric using iv_in changing lv_check.\n  if lv_check = 'X'.\n    ev_num = iv_in.\n  else.\n    perform rpn_log using 'Wrong call!'.\n  endif.\nendform.\n\n\" Evaluate the RPN expression and return true if success in eval.\nform rpn_eval using in_expr type string changing ev_out type c.\n  data: lv_len  type i,\n        lv_off  type i value 0,\n        lv_num  type c,\n        lv_val  type f,\n        lv_tok  type string.\n\n  lv_len = strlen( in_expr ).\n  do lv_len times.\n    lv_tok = in_expr+lv_off(1).\n    perform rpn_numeric using lv_tok changing lv_num.\n    if lv_num = 'X'.\n      perform: rpn_get_num using lv_tok changing lv_val,\n               rpn_push    using lv_val.\n    else.\n\n      perform rpn_call_op using lv_tok.\n    endif.\n    add 1 to lv_off.\n  enddo.\n\n  ev_out = 'X'.\nendform.\nselection-screen begin of block main with frame title lv_title.\n  parameters:\n    p_first  type i,\n    p_second type i,\n    p_third  type i,\n    p_fourth type i,\n    p_expr   type string.\nselection-screen end of block main.\n\ninitialization.\n  perform ranged_rand using 1 9 changing p_first.\n  perform ranged_rand using 1 9 changing p_second.\n  perform ranged_rand using 1 9 changing p_third.\n  perform ranged_rand using 1 9 changing p_fourth.\n\nat selection-screen output.\n  \" Set-up paramter texts.\n  lv_title = 'Reverse Polish Notation Tester - Enter expression that evaluates to 24.'.\n  %_p_first_%_app_%-text  = 'First Number: '.\n  %_p_second_%_app_%-text = 'Second Number: '.\n  %_p_third_%_app_%-text  = 'Third Number: '.\n  %_p_fourth_%_app_%-text = 'Fourth Number: '.\n  %_p_expr_%_app_%-text   = 'Expression: '.\n  \" Disallow modification of supplied numbers.\n  loop at screen.\n    if screen-name = 'P_FIRST' or  screen-name = 'P_SECOND' or\n       screen-name = 'P_THIRD' or  screen-name = 'P_FOURTH'.\n      screen-input = '0'.\n      modify screen.\n    endif.\n  endloop.\n\nstart-of-selection.\n  \" Check the expression is valid.\n  perform check_expr using p_expr changing gv_chk.\n  if gv_chk <> 'X'.\n    write : \/ 'Invalid input!'.\n    stop.\n  endif.\n  \" Check if the expression actually evalutes.\n  perform rpn_eval using p_expr changing gv_chk.\n  \" If it doesn't, warning!.\n  if gv_chk <> 'X'.\n    write : \/ 'Invalid expression!'.\n    stop.\n  endif.\n  \" Get the evaluated value. Transform it to something that displays a bit better.\n  \" Then check if it's a valid answer, with a certain tolerance.\n  \" If they're wrong, give them instructions to on how to go back.\n  perform rpn_pop changing gv_val.\n  gv_pac = gv_val.\n  gv_val = abs( gv_val - c_eval_to ).\n  if gv_val < c_tolerance.\n    write : \/ 'Answer correct'.\n  else.\n    write : \/ 'Your expression evalutes to ', gv_pac.\n    write : \/ 'Press \"F3\" to go back and try again!'.\n  endif.\n  write : \/ 'Re-run the program to generate a new set.'.\n\n \" Check that the input expression is valid - i.e. all supplied numbers\n \" appears exactly once. This does not validate the expression itself.\nform check_expr using iv_exp type string changing ev_ok type c.\n  data: lv_chk  type c,\n        lv_tok  type string,\n        lv_val  type i value 0,\n        lv_len  type i,\n        lv_off  type i,\n        lv_num  type i,\n        lt_nums type standard table of i.\n  ev_ok = 'X'.\n  \" Update the number count table - indexes 1-9 correspond to numbers.\n  \" The value stored corresponds to the number of occurences.\n  do 9 times.\n    if p_first = sy-index.\n      add 1 to lv_val.\n    endif.\n    if p_second = sy-index.\n      add 1 to lv_val.\n    endif.\n    if p_third = sy-index.\n      add 1 to lv_val.\n    endif.\n    if p_fourth = sy-index.\n      add 1 to lv_val.\n    endif.\n\n    append lv_val to lt_nums.\n    lv_val = 0.\n  enddo.\n  \" Loop through the expression parsing the numbers.\n  lv_len = strlen( p_expr ).\n  do lv_len times.\n    lv_tok = p_expr+lv_off(1). \" Check if the current token is a number.\n    perform rpn_numeric using lv_tok changing lv_chk.\n    if lv_chk = 'X'.\n      lv_num = lv_tok. \" If it's a number, it must be from 1 - 9.\n      if lv_num < 1 or lv_num > 9.\n        ev_ok = ' '.\n        write : \/ 'Numbers must be between 1 and 9!'.\n        return.\n      else.\n        \" Check how many times the number was supplied. If it wasn't supplied\n        \" or if we have used it up, we should give an error.\n        read table lt_nums index lv_num into lv_val.\n        if lv_val <= 0.\n          ev_ok = ' '.\n          write : \/ 'You can not use numbers more than once'.\n          return.\n        endif.\n        \" If we have values left for this number, we decrement the remaining amount.\n        subtract 1 from lv_val.\n        modify lt_nums index lv_num from lv_val.\n      endif.\n    endif.\n    add 1 to lv_off.\n  enddo.\n  \" Loop through the table and check we have no numbers left for use.\n  do 9 times.\n    read table lt_nums index  sy-index into lv_val.\n    if lv_val > 0.\n      write : \/ 'You must use all numbers'.\n      ev_ok = ' '.\n      return.\n     endif.\n  enddo.\nendform.\n\n\" Generate a random number within the given range.\nform ranged_rand using iv_min type i iv_max type i\n                 changing ev_val type i.\n  call function 'QF05_RANDOM_INTEGER'\n    exporting\n      ran_int_max = iv_max\n      ran_int_min = iv_min\n    importing\n      ran_int     = ev_val.\nendform.\n","human_summarization":"The code randomly selects and displays four digits from 1 to 9. It then prompts the player to input an arithmetic expression using these digits exactly once each. The code checks and evaluates the expression to see if it equals 24. The allowed operations are multiplication, division, addition, and subtraction, with division preserving remainders. The code does not allow the formation of multi-digit numbers from the given digits. The order of the digits does not have to be preserved. The type of expression evaluator used is not specified. The code does not generate the expression or test if an expression is possible.","id":2633}
    {"lang_cluster":"ABAP","source_code":"\nDATA: s1 TYPE string,\n      s2 TYPE string.\n\ns1 = 'Hello'.\nCONCATENATE s1 ' literal' INTO s2 RESPECTING BLANKS.\nWRITE: \/ s1.\nWRITE: \/ s2.\n\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":2634}
    {"lang_cluster":"ABAP","source_code":"\nreport zz_anagrams no standard page heading.\ndefine update_progress.\n  call function 'SAPGUI_PROGRESS_INDICATOR'\n    exporting\n      text = &1.\nend-of-definition.\n\n\" Selection screen segment allowing the person to choose which file will act as input.\nselection-screen begin of block file_choice.\n  parameters p_file type string lower case.\nselection-screen end of block file_choice.\n\n\" When the user requests help with input, run the routine to allow them to navigate the presentation server.\nat selection-screen on value-request for p_file.\n  perform getfile using p_file.\n\nat selection-screen output.\n  %_p_file_%_app_%-text = 'Input File: '.\n\nstart-of-selection.\n  data: gt_data type table of string.\n\n  \" Read the specified file from the presentation server into memory.\n  perform readfile using p_file changing gt_data.\n  \" After the file has been read into memory, loop through it line-by-line and make anagrams.\n  perform anagrams using gt_data.\n\n\" Subroutine for generating a list of anagrams.\n\" The supplied input is a table, with each entry corresponding to a word.\nform anagrams using it_data like gt_data.\n  types begin of ty_map.\n    types key type string.\n    types value type string.\n  types end of ty_map.\n\n  data: lv_char     type c,\n        lv_len      type i,\n        lv_string   type string,\n        ls_entry    type ty_map,\n        lt_anagrams type standard table of ty_map,\n        lt_c_tab    type table of string.\n\n  field-symbols: <fs_raw> type string.\n  \" Loop through each word in the table, and make an associative array.\n  loop at gt_data assigning <fs_raw>.\n    \" First, we need to re-order the word alphabetically. This generated a key. All anagrams will use this same key.\n    \" Add each character to a table, which we will then sort alphabetically.\n    lv_len = strlen( <fs_raw> ).\n    refresh lt_c_tab.\n    do lv_len times.\n      lv_len = sy-index  - 1.\n      append <fs_raw>+lv_len(1) to lt_c_tab.\n    enddo.\n    sort lt_c_tab as text.\n    \" Now append the characters to a string and add it as a key into the map.\n    clear lv_string.\n    loop at lt_c_tab into lv_char.\n      concatenate lv_char lv_string into lv_string respecting blanks.\n    endloop.\n    ls_entry-key = lv_string.\n    ls_entry-value = <fs_raw>.\n    append ls_entry to lt_anagrams.\n  endloop.\n  \" After we're done processing, output a list of the anagrams.\n  clear lv_string.\n  loop at lt_anagrams into ls_entry.\n    \" Is it part of the same key --> Output in the same line, else a new entry.\n    if lv_string = ls_entry-key.\n        write: ', ', ls_entry-value.\n    else.\n      if sy-tabix <> 1.\n        write: ']'.\n      endif.\n      write:  \/ '[', ls_entry-value.\n    endif.\n    lv_string = ls_entry-key.\n  endloop.\n  \" Close last entry.\n  write ']'.\nendform.\n\n\" Read a specified file from the presentation server.\nform readfile using i_file type string changing it_raw like gt_data.\n  data: l_datat type string,\n        l_msg(2048),\n        l_lines(10).\n\n  \" Read the file into memory.\n  update_progress 'Reading file...'.\n  call method cl_gui_frontend_services=>gui_upload\n    exporting\n      filename = i_file\n    changing\n      data_tab = it_raw\n    exceptions\n      others   = 1.\n  \" Output error if the file could not be uploaded.\n  if sy-subrc <> 0.\n    write : \/ 'Error reading the supplied file!'.\n    return.\n  endif.\nendform.\n\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":2635}
    {"lang_cluster":"ABAP","source_code":"\nREPORT  zhuberv_ackermann.\n\nCLASS zcl_ackermann DEFINITION.\n  PUBLIC SECTION.\n    CLASS-METHODS ackermann IMPORTING m TYPE i\n                                      n TYPE i\n                            RETURNING value(v) TYPE i.\nENDCLASS.            \"zcl_ackermann DEFINITION\n\n\nCLASS zcl_ackermann IMPLEMENTATION.\n\n  METHOD: ackermann.\n\n    DATA: lv_new_m TYPE i,\n          lv_new_n TYPE i.\n\n    IF m = 0.\n      v = n + 1.\n    ELSEIF m > 0 AND n = 0.\n      lv_new_m = m - 1.\n      lv_new_n = 1.\n      v = ackermann( m = lv_new_m n = lv_new_n ).\n    ELSEIF m > 0 AND n > 0.\n      lv_new_m = m - 1.\n\n      lv_new_n = n - 1.\n      lv_new_n = ackermann( m = m n = lv_new_n ).\n\n      v = ackermann( m = lv_new_m n = lv_new_n ).\n    ENDIF.\n\n  ENDMETHOD.                    \"ackermann\n\nENDCLASS.                    \"zcl_ackermann IMPLEMENTATION\n\n\nPARAMETERS: pa_m TYPE i,\n            pa_n TYPE i.\n\nDATA: lv_result TYPE i.\n\nSTART-OF-SELECTION.\n  lv_result = zcl_ackermann=>ackermann( m = pa_m n = pa_n ).\n  WRITE: \/ lv_result.\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":2636}
    {"lang_cluster":"ABAP","source_code":"\nTYPES: BEGIN OF gty_matrix,\n         1  TYPE c,\n         2  TYPE c,\n         3  TYPE c,\n         4  TYPE c,\n         5  TYPE c,\n         6  TYPE c,\n         7  TYPE c,\n         8  TYPE c,\n         9  TYPE c,\n         10 TYPE c,\n       END OF gty_matrix,\n       gty_t_matrix TYPE STANDARD TABLE OF gty_matrix INITIAL SIZE 8.\n\nDATA: gt_matrix TYPE gty_t_matrix,\n      gs_matrix TYPE gty_matrix,\n      gv_count  TYPE i VALUE 0,\n      gv_solut  TYPE i VALUE 0.\n\n\nSELECTION-SCREEN BEGIN OF BLOCK b01 WITH FRAME TITLE text-b01.\nPARAMETERS: p_number TYPE i OBLIGATORY DEFAULT 8.\nSELECTION-SCREEN END OF BLOCK b01.\n\n\" Filling empty table\nSTART-OF-SELECTION.\n  DO p_number TIMES.\n    APPEND gs_matrix TO gt_matrix.\n  ENDDO.\n\n\" Recursive Function\n  PERFORM fill_matrix USING gv_count 1 1 CHANGING gt_matrix.\n  BREAK-POINT.\n*&---------------------------------------------------------------------*\n*&      Form  FILL_MATRIX\n*----------------------------------------------------------------------*\nFORM fill_matrix  USING    p_count TYPE i\n                           p_i     TYPE i\n                           p_j     TYPE i\n                  CHANGING p_matrix TYPE gty_t_matrix.\n\n  DATA: lv_i      TYPE i,\n        lv_j      TYPE i,\n        lv_result TYPE c LENGTH 1,\n        lt_matrix TYPE gty_t_matrix,\n        lv_count  TYPE i,\n        lv_value  TYPE c.\n\n  lt_matrix[] = p_matrix[].\n  lv_count = p_count.\n  lv_i = p_i.\n  lv_j = p_j.\n\n  WHILE lv_i LE p_number.\n    WHILE lv_j LE p_number.\n      CLEAR lv_result.\n      PERFORM check_position USING lv_i lv_j CHANGING lv_result lt_matrix.\n      IF lv_result NE 'X'.\n        MOVE 'X' TO lv_value.\n        PERFORM get_position USING lv_i lv_j 'U' CHANGING lv_value lt_matrix.\n        ADD 1 TO lv_count.\n        IF lv_count EQ p_number.\n          PERFORM show_matrix USING lt_matrix.\n        ELSE.\n          PERFORM fill_matrix USING lv_count lv_i lv_j CHANGING lt_matrix.\n        ENDIF.\n        lv_value = space.\n        PERFORM get_position USING lv_i lv_j 'U' CHANGING lv_value lt_matrix.\n        SUBTRACT 1 FROM lv_count.\n      ENDIF.\n      ADD 1 TO lv_j.\n    ENDWHILE.\n    ADD 1 TO lv_i.\n    lv_j = 1.\n  ENDWHILE.\nENDFORM.                    \" FILL_MATRIX\n\n*&---------------------------------------------------------------------*\n*&      Form  CHECK_POSITION\n*&---------------------------------------------------------------------*\nFORM check_position  USING value(p_i)  TYPE i\n                           value(p_j)  TYPE i\n                     CHANGING p_result TYPE c\n                              p_matrix TYPE gty_t_matrix.\n\n  PERFORM get_position USING p_i p_j 'R' CHANGING p_result p_matrix.\n  CHECK p_result NE 'X'.\n\n  PERFORM check_horizontal USING p_i p_j CHANGING p_result p_matrix.\n  CHECK p_result NE 'X'.\n\n  PERFORM check_vertical USING p_i p_j CHANGING p_result p_matrix.\n  CHECK p_result NE 'X'.\n\n  PERFORM check_diagonals USING p_i p_j CHANGING p_result p_matrix.\n\nENDFORM.                    \" CHECK_POSITION\n\n*&---------------------------------------------------------------------*\n*&      Form  GET_POSITION\n*&---------------------------------------------------------------------*\nFORM get_position  USING value(p_i)      TYPE i\n                         value(p_j)      TYPE i\n                         value(p_action) TYPE c\n                      CHANGING p_result  TYPE c\n                               p_matrix  TYPE gty_t_matrix.\n\n  FIELD-SYMBOLS: <fs_lmatrix> TYPE gty_matrix,\n                 <fs_lfield> TYPE any.\n\n  READ TABLE p_matrix ASSIGNING <fs_lmatrix> INDEX p_i.\n  ASSIGN COMPONENT p_j OF STRUCTURE <fs_lmatrix> TO <fs_lfield>.\n\n  CASE p_action.\n    WHEN 'U'.\n      <fs_lfield> = p_result.\n    WHEN 'R'.\n      p_result = <fs_lfield>.\n    WHEN OTHERS.\n  ENDCASE.\n\nENDFORM.                    \" GET_POSITION\n\n*&---------------------------------------------------------------------*\n*&      Form  CHECK_HORIZONTAL\n*&---------------------------------------------------------------------*\nFORM check_horizontal  USING value(p_i)      TYPE i\n                             value(p_j)      TYPE i\n                          CHANGING p_result  TYPE c\n                                   p_matrix  TYPE gty_t_matrix.\n  DATA: lv_j TYPE i,\n        ls_matrix TYPE gty_matrix.\n\n  FIELD-SYMBOLS <fs> TYPE c.\n\n  lv_j = 1.\n  READ TABLE p_matrix INTO ls_matrix INDEX p_i.\n  WHILE lv_j LE p_number.\n    ASSIGN COMPONENT lv_j OF STRUCTURE ls_matrix TO <fs>.\n    IF <fs> EQ 'X'.\n      p_result = 'X'.\n      RETURN.\n    ENDIF.\n    ADD 1 TO lv_j.\n  ENDWHILE.\nENDFORM.                    \" CHECK_HORIZONTAL\n\n*&---------------------------------------------------------------------*\n*&      Form  CHECK_VERTICAL\n*&---------------------------------------------------------------------*\nFORM check_vertical  USING value(p_i)      TYPE i\n                           value(p_j)      TYPE i\n                        CHANGING p_result  TYPE c\n                                 p_matrix  TYPE gty_t_matrix.\n  DATA: lv_i TYPE i,\n        ls_matrix TYPE gty_matrix.\n\n  FIELD-SYMBOLS <fs> TYPE c.\n\n  lv_i = 1.\n  WHILE lv_i LE p_number.\n    READ TABLE p_matrix INTO ls_matrix INDEX lv_i.\n    ASSIGN COMPONENT p_j OF STRUCTURE ls_matrix TO <fs>.\n    IF <fs> EQ 'X'.\n      p_result = 'X'.\n      RETURN.\n    ENDIF.\n    ADD 1 TO lv_i.\n  ENDWHILE.\nENDFORM.                    \" CHECK_VERTICAL\n\n*&---------------------------------------------------------------------*\n*&      Form  CHECK_DIAGONALS\n*&---------------------------------------------------------------------*\nFORM check_diagonals  USING value(p_i)      TYPE i\n                            value(p_j)      TYPE i\n                         CHANGING p_result  TYPE c\n                                  p_matrix  TYPE gty_t_matrix.\n  DATA: lv_dx TYPE i,\n        lv_dy TYPE i.\n\n* I++ J++ (Up Right)\n  lv_dx = 1.\n  lv_dy = 1.\n  PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix.\n  CHECK p_result NE 'X'.\n\n* I-- J-- (Left Down)\n  lv_dx = -1.\n  lv_dy = -1.\n  PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix.\n  CHECK p_result NE 'X'.\n\n* I++ J-- (Right Down)\n  lv_dx = 1.\n  lv_dy = -1.\n  PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix.\n  CHECK p_result NE 'X'.\n\n* I-- J++ (Left Up)\n  lv_dx = -1.\n  lv_dy = 1.\n  PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix.\n  CHECK p_result NE 'X'.\nENDFORM.                    \" CHECK_DIAGONALS\n\n*&---------------------------------------------------------------------*\n*&      Form  CHECK_DIAGONAL\n*&---------------------------------------------------------------------*\nFORM check_diagonal  USING value(p_i)      TYPE i\n                            value(p_j)      TYPE i\n                            value(p_dx)      TYPE i\n                            value(p_dy)      TYPE i\n                         CHANGING p_result  TYPE c\n                                  p_matrix  TYPE gty_t_matrix.\n  DATA: lv_i TYPE i,\n        lv_j TYPE i,\n        ls_matrix TYPE gty_matrix.\n\n  FIELD-SYMBOLS <fs> TYPE c.\n\n  lv_i = p_i.\n  lv_j = p_j.\n  WHILE 1 EQ 1.\n    ADD: p_dx TO lv_i, p_dy TO lv_j.\n\n    IF p_dx EQ 1.\n      IF lv_i GT p_number. EXIT. ENDIF.\n    ELSE.\n      IF lv_i LT 1. EXIT. ENDIF.\n    ENDIF.\n\n    IF p_dy EQ 1.\n      IF lv_j GT p_number. EXIT. ENDIF.\n    ELSE.\n      IF lv_j LT 1. EXIT. ENDIF.\n    ENDIF.\n\n    READ TABLE p_matrix INTO ls_matrix INDEX lv_i.\n    ASSIGN COMPONENT lv_j OF STRUCTURE ls_matrix TO <fs>.\n    IF <fs> EQ 'X'.\n      p_result = 'X'.\n      RETURN.\n    ENDIF.\n  ENDWHILE.\nENDFORM.                    \" CHECK_DIAGONAL\n*&---------------------------------------------------------------------*\n*&      Form  SHOW_MATRIX\n*----------------------------------------------------------------------*\nFORM show_matrix USING p_matrix TYPE gty_t_matrix.\n  DATA: lt_matrix TYPE gty_t_matrix,\n        lv_j      TYPE i VALUE 1,\n        lv_colum  TYPE string VALUE '-'.\n\n  FIELD-SYMBOLS: <fs_matrix> TYPE gty_matrix,\n                 <fs_field>  TYPE c.\n\n  ADD 1 TO gv_solut.\n\n  WRITE:\/ 'Solution: ', gv_solut.\n\n  DO p_number TIMES.\n    CONCATENATE lv_colum '----' INTO lv_colum.\n  ENDDO.\n\n  LOOP AT p_matrix ASSIGNING <fs_matrix>.\n    IF sy-tabix EQ 1.\n      WRITE:\/ lv_colum.\n    ENDIF.\n    WRITE:\/ '|'.\n    DO p_number TIMES.\n      ASSIGN COMPONENT lv_j OF STRUCTURE <fs_matrix> TO <fs_field>.\n      IF <fs_field> EQ space.\n        WRITE: <fs_field> ,'|'.\n      ELSE.\n        WRITE: <fs_field> COLOR 2 HOTSPOT ON,'|'.\n      ENDIF.\n      ADD 1 TO lv_j.\n    ENDDO.\n    lv_j = 1.\n    WRITE: \/ lv_colum.\n  ENDLOOP.\n\n  SKIP 1.\nENDFORM.                    \" SHOW_MATRIX\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":2637}
    {"lang_cluster":"ABAP","source_code":"\n\nreport z_array_concatenation.\n\ndata(itab1) = value int4_table( ( 1 ) ( 2 ) ( 3 ) ).\ndata(itab2) = value int4_table( ( 4 ) ( 5 ) ( 6 ) ).\n\nappend lines of itab2 to itab1.\n\nloop at itab1 assigning field-symbol(<line>).\n    write <line>.\nendloop.\n\n\n","human_summarization":"demonstrate how to concatenate two arrays in the given language, or in the case of ABAP, how to use internal tables as an alternative to arrays. This is applicable for ABAP version 7.40 and above.","id":2638}
    {"lang_cluster":"ABAP","source_code":"\nREPORT morse_code.\nTYPES: BEGIN OF y_morse_code,\n         letter TYPE string,\n         code   TYPE string,\n       END OF y_morse_code,\n       ty_morse_code TYPE STANDARD TABLE OF y_morse_code WITH EMPTY KEY.\n\ncl_demo_output=>new(\n          )->begin_section( |Morse Code|\n          )->write( REDUCE stringtab( LET words = VALUE stringtab( ( |sos|                 )\n                                                                   ( |   Hello     World!| )\n                                                                   ( |Rosetta Code|        ) )\n                                          morse_code = VALUE ty_morse_code( ( letter = 'A'   code = '.-     ' )\n                                                                            ( letter = 'B'   code = '-...   ' )\n                                                                            ( letter = 'C'   code = '-.-.   ' )\n                                                                            ( letter = 'D'   code = '-..    ' )\n                                                                            ( letter = 'E'   code = '.      ' )\n                                                                            ( letter = 'F'   code = '..-.   ' )\n                                                                            ( letter = 'G'   code = '--.    ' )\n                                                                            ( letter = 'H'   code = '....   ' )\n                                                                            ( letter = 'I'   code = '..     ' )\n                                                                            ( letter = 'J'   code = '.---   ' )\n                                                                            ( letter = 'K'   code = '-.-    ' )\n                                                                            ( letter = 'L'   code = '.-..   ' )\n                                                                            ( letter = 'M'   code = '--     ' )\n                                                                            ( letter = 'N'   code = '-.     ' )\n                                                                            ( letter = 'O'   code = '---    ' )\n                                                                            ( letter = 'P'   code = '.--.   ' )\n                                                                            ( letter = 'Q'   code = '--.-   ' )\n                                                                            ( letter = 'R'   code = '.-.    ' )\n                                                                            ( letter = 'S'   code = '...    ' )\n                                                                            ( letter = 'T'   code = '-      ' )\n                                                                            ( letter = 'U'   code = '..-    ' )\n                                                                            ( letter = 'V'   code = '...-   ' )\n                                                                            ( letter = 'W'   code = '.-   - ' )\n                                                                            ( letter = 'X'   code = '-..-   ' )\n                                                                            ( letter = 'Y'   code = '-.--   ' )\n                                                                            ( letter = 'Z'   code = '--..   ' )\n                                                                            ( letter = '0'   code = '-----  ' )\n                                                                            ( letter = '1'   code = '.----  ' )\n                                                                            ( letter = '2'   code = '..---  ' )\n                                                                            ( letter = '3'   code = '...--  ' )\n                                                                            ( letter = '4'   code = '....-  ' )\n                                                                            ( letter = '5'   code = '.....  ' )\n                                                                            ( letter = '6'   code = '-....  ' )\n                                                                            ( letter = '7'   code = '--...  ' )\n                                                                            ( letter = '8'   code = '---..  ' )\n                                                                            ( letter = '9'   code = '----.  ' )\n                                                                            ( letter = ''''  code = '.----. ' )\n                                                                            ( letter = ':'   code = '---... ' )\n                                                                            ( letter = ','   code = '--..-- ' )\n                                                                            ( letter = '-'   code = '-....- ' )\n                                                                            ( letter = '('   code = '-.--.- ' )\n                                                                            ( letter = '.'   code = '.-.-.- ' )\n                                                                            ( letter = '?'   code = '..--.. ' )\n                                                                            ( letter = ';'   code = '-.-.-. ' )\n                                                                            ( letter = '\/'   code = '-..-.  ' )\n                                                                            ( letter = '_'   code = '..--.- ' )\n                                                                            ( letter = ')'   code = '---..  ' )\n                                                                            ( letter = '='   code = '-...-  ' )\n                                                                            ( letter = '@'   code = '.--.-. ' )\n                                                                            ( letter = '\\'   code = '.-..-. ' )\n                                                                            ( letter = '+'   code = '.-.-.  ' )\n                                                                            ( letter = ' '   code = '\/'       ) )\n                                      IN INIT word_coded_tab TYPE stringtab\n                                          FOR word IN words\n                                         NEXT word_coded_tab = VALUE #( BASE word_coded_tab ( REDUCE string( INIT word_coded TYPE string\n                                                                                                              FOR index = 1 UNTIL index > strlen( word )\n                                                                                                              LET _morse_code = VALUE #( morse_code[ letter = COND #( WHEN index = 1 THEN to_upper( word(index) )\n                                                                                                                                                                      ELSE LET prev = index - 1 IN to_upper( word+prev(1) ) ) ]-code OPTIONAL )\n                                                                                                               IN NEXT word_coded = |{ word_coded } { _morse_code }| ) ) ) )\n          )->display( ).\n\n","human_summarization":"<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":2639}
    {"lang_cluster":"ABAP","source_code":"\nREPORT z_rosetta_abc.\n\n\" Type declaration for blocks of letters\nTYPES: BEGIN OF block,\n         s1 TYPE char1,\n         s2 TYPE char1,\n       END OF block,\n\n       blocks_table TYPE STANDARD TABLE OF block.\n\nDATA: blocks TYPE blocks_table.\n\nCLASS word_maker DEFINITION.\n  PUBLIC SECTION.\n    CLASS-METHODS:\n      can_make_word\n        IMPORTING word          TYPE string\n                  letter_blocks TYPE blocks_table\n        RETURNING VALUE(found)  TYPE abap_bool.\nENDCLASS.\n\nCLASS word_maker IMPLEMENTATION.\n  METHOD can_make_word.\n\n    \" Create a reader stream that reads 1 character at a time\n    DATA(reader) = NEW cl_abap_string_c_reader( word ).\n\n    DATA(blocks) = letter_blocks.\n\n    WHILE reader->data_available( ).\n\n      DATA(ch) = to_upper( reader->read( 1 ) ).\n      found = abap_false.\n\n      LOOP AT blocks REFERENCE INTO DATA(b).\n        IF ch = b->s1 OR ch = b->s2.\n          found = abap_true.\n          DELETE blocks INDEX sy-tabix.\n          EXIT. \" the inner loop once a character is found\n        ENDIF.\n      ENDLOOP.\n\n      \" If a character could not be found, stop looking further\n      IF found = abap_false.\n        RETURN.\n      ENDIF.\n    ENDWHILE.\n\n  ENDMETHOD.\nENDCLASS.\n\nSTART-OF-SELECTION.\n\n  blocks = VALUE #( ( s1 = 'B' s2 = 'O' ) ( s1 = 'X' s2 = 'K' )\n                    ( s1 = 'D' s2 = 'Q' ) ( s1 = 'C' s2 = 'P' )\n                    ( s1 = 'N' s2 = 'A' ) ( s1 = 'G' s2 = 'T' )\n                    ( s1 = 'R' s2 = 'E' ) ( s1 = 'T' s2 = 'G' )\n                    ( s1 = 'Q' s2 = 'D' ) ( s1 = 'F' s2 = 'S' )\n                    ( s1 = 'J' s2 = 'W' ) ( s1 = 'H' s2 = 'U' )\n                    ( s1 = 'V' s2 = 'I' ) ( s1 = 'A' s2 = 'N' )\n                    ( s1 = 'O' s2 = 'B' ) ( s1 = 'E' s2 = 'R' )\n                    ( s1 = 'F' s2 = 'S' ) ( s1 = 'L' s2 = 'Y' )\n                    ( s1 = 'P' s2 = 'C' ) ( s1 = 'Z' s2 = 'M' )\n                  ).\n\n  WRITE:\/ COND string( WHEN word_maker=>can_make_word( word = 'A'        letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).\n  WRITE:\/ COND string( WHEN word_maker=>can_make_word( word = 'BARK'     letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).\n  WRITE:\/ COND string( WHEN word_maker=>can_make_word( word = 'BOOK'     letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).\n  WRITE:\/ COND string( WHEN word_maker=>can_make_word( word = 'TREAT'    letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).\n  WRITE:\/ COND string( WHEN word_maker=>can_make_word( word = 'COMMON'   letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).\n  WRITE:\/ COND string( WHEN word_maker=>can_make_word( word = 'SQUAD'    letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).\n  WRITE:\/ COND string( WHEN word_maker=>can_make_word( word = 'CONFUSE'  letter_blocks = blocks ) = abap_true THEN 'True' ELSE 'False' ).\n\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":2640}
    {"lang_cluster":"Rust","source_code":"\n\nfn main() {\n    let mut stack = Vec::new();\n    stack.push(\"Element1\");\n    stack.push(\"Element2\");\n    stack.push(\"Element3\");\n\n    assert_eq!(Some(&\"Element3\"), stack.last());\n    assert_eq!(Some(\"Element3\"), stack.pop());\n    assert_eq!(Some(\"Element2\"), stack.pop());\n    assert_eq!(Some(\"Element1\"), stack.pop());\n    assert_eq!(None, stack.pop());\n}\n\ntype Link<T> = Option<Box<Frame<T>>>;\n\npub struct Stack<T> {\n    head: Link<T>,\n}\nstruct Frame<T> { \n    elem: T,\n    next: Link<T>,\n}\n\n\/\/\/ Iterate by value (consumes list)\npub struct IntoIter<T>(Stack<T>); \nimpl<T> Iterator for IntoIter<T> {\n    type Item = T;\n    fn next(&mut self) -> Option<Self::Item> {\n        self.0.pop()\n    }\n}\n\n\/\/\/ Iterate by immutable reference\npub struct Iter<'a, T: 'a> { \n    next: Option<&'a Frame<T>>,\n}\nimpl<'a, T> Iterator for Iter<'a, T> { \/\/ Iterate by immutable reference\n    type Item = &'a T;\n    fn next(&mut self) -> Option<Self::Item> {\n        self.next.take().map(|frame| {\n            self.next = frame.next.as_ref().map(|frame| &**frame);\n            &frame.elem\n        })\n    }\n}\n\n\/\/\/ Iterate by mutable reference\npub struct IterMut<'a, T: 'a> {\n    next: Option<&'a mut Frame<T>>,\n}\nimpl<'a, T> Iterator for IterMut<'a, T> {\n    type Item = &'a mut T;\n    fn next(&mut self) -> Option<Self::Item> {\n        self.next.take().map(|frame| {\n            self.next = frame.next.as_mut().map(|frame| &mut **frame);\n            &mut frame.elem\n        })\n    }\n}\n\n\nimpl<T> Stack<T> {\n    \/\/\/ Return new, empty stack\n    pub fn new() -> Self {\n        Stack { head: None }\n    }\n\n    \/\/\/ Add element to top of the stack\n    pub fn push(&mut self, elem: T) {\n        let new_frame = Box::new(Frame {\n            elem: elem,\n            next: self.head.take(),\n        });\n        self.head = Some(new_frame);\n    }\n\n    \/\/\/ Remove element from top of stack, returning the value\n    pub fn pop(&mut self) -> Option<T> {\n        self.head.take().map(|frame| { \n            let frame = *frame;\n            self.head = frame.next;\n            frame.elem\n        })\n    }\n\n    \/\/\/ Get immutable reference to top element of the stack\n    pub fn peek(&self) -> Option<&T> {\n        self.head.as_ref().map(|frame| &frame.elem)\n    }\n\n    \/\/\/ Get mutable reference to top element on the stack\n    pub fn peek_mut(&mut self) -> Option<&mut T> {\n        self.head.as_mut().map(|frame| &mut frame.elem)\n    }\n\n    \/\/\/ Iterate over stack elements by value\n    pub fn into_iter(self) -> IntoIter<T> {\n        IntoIter(self)\n    }\n\n    \/\/\/ Iterate over stack elements by immutable reference\n    pub fn iter<'a>(&'a self) -> Iter<'a,T> {\n        Iter { next: self.head.as_ref().map(|frame| &**frame) }\n    }\n\n    \/\/\/ Iterate over stack elements by mutable reference\n    pub fn iter_mut(&mut self) -> IterMut<T> {\n        IterMut { next: self.head.as_mut().map(|frame| &mut **frame) }\n    }\n}\n\n\/\/ The Drop trait tells the compiler how to free an object after it goes out of scope. \n\/\/ By default, the compiler would do this recursively which *could* blow the stack for\n\/\/ extraordinarily long lists. This simply tells it to do it iteratively.\nimpl<T> Drop for Stack<T> {\n    fn drop(&mut self) {\n        let mut cur_link = self.head.take();\n        while let Some(mut boxed_frame) = cur_link {\n            cur_link = boxed_frame.next.take();\n        }\n    }\n}\n","human_summarization":"implement a stack data structure that supports basic operations such as push (adding an element to the top of the stack), pop (removing the topmost element from the stack and returning it), and empty (checking if the stack contains no elements). The stack follows a last in, first out (LIFO) access policy. It can be implemented using a vector or a singly-linked list.","id":2641}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    let mut prev = 0;\n    \/\/ Rust needs this type hint for the checked_add method\n    let mut curr = 1usize;\n\n    while let Some(n) = curr.checked_add(prev) {\n        prev = curr;\n        curr = n;\n        println!(\"{}\", n);\n    }\n}\nuse std::mem;\nfn main() {\n    fibonacci(0,1);\n}\n\nfn fibonacci(mut prev: usize, mut curr: usize) {\n    mem::swap(&mut prev, &mut curr);\n    if let Some(n) = curr.checked_add(prev) {\n        println!(\"{}\", n);\n        fibonacci(prev, n);\n    }\n}\nfn fib(n: u32) -> u32 {\n    match n {\n        0 => 0,\n        1 => 1,\n        n => fib(n - 1) + fib(n - 2),\n    }\n}\nfn fib_tail_recursive(nth: usize) -> usize {\n  fn fib_tail_iter(n: usize, prev_fib: usize, fib: usize) -> usize {\n    match n {\n      0 => prev_fib,\n      n => fib_tail_iter(n - 1, fib, prev_fib + fib),\n    }\n  }\n  fib_tail_iter(nth, 0, 1)\n}\nfn main() {\n    for num in fibonacci_sequence() {\n        println!(\"{}\", num);\n    }\n}\n\nfn fibonacci_sequence() -> impl Iterator<Item = u64> {\n    let sqrt_5 = 5.0f64.sqrt();\n    let p = (1.0 + sqrt_5) \/ 2.0;\n    let q = 1.0 \/ p;\n    \/\/ The range is sufficient up to 70th Fibonacci number\n    (0..1).chain((1..70).map(move |n| ((p.powi(n) + q.powi(n)) \/ sqrt_5 + 0.5) as u64))\n}\n\nuse std::mem;\n\nstruct Fib {\n    prev: usize,\n    curr: usize,\n} \n\nimpl Fib {\n    fn new() -> Self {\n        Fib {prev: 0, curr: 1}\n    }\n}\n\nimpl Iterator for Fib {\n    type Item = usize;\n    fn next(&mut self) -> Option<Self::Item>{\n        mem::swap(&mut self.curr, &mut self.prev);\n        self.curr.checked_add(self.prev).map(|n| { \n            self.curr = n;\n            n\n        })\n    }\n}\n\nfn main() {\n    for num in Fib::new() {\n        println!(\"{}\", num);\n    }\n}\n\nfn main() {\n    std::iter::successors(Some((1u128, 0)), |&(a, b)| a.checked_add(b).map(|s| (b, s)))\n        .for_each(|(_, u)| println!(\"{}\", u));\n}\n\n","human_summarization":"The code defines a function to generate the nth Fibonacci number, which can be either iterative or recursive. It optionally supports negative n values by using an inverse of the positive definition. The function utilizes idiomatic Rust iterators, although they might be overkill for this simple problem.","id":2642}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    println!(\"new vec filtered: \");\n    let nums: Vec<i32> = (1..20).collect();\n    let evens: Vec<i32> = nums.iter().cloned().filter(|x| x\u00a0% 2 == 0).collect();\n    println!(\"{:?}\", evens);\n\n    \/\/ Filter an already existing vector\n    println!(\"original vec filtered: \");\n    let mut nums: Vec<i32> = (1..20).collect();\n    nums.retain(|x| x\u00a0% 2 == 0);\n    println!(\"{:?}\", nums);\n}\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":2643}
    {"lang_cluster":"Rust","source_code":"\nlet s = \"abc\u6587\u5b57\u5316\u3051def\";\nlet n = 2;\nlet m = 3;\n\n    \/\/ Print 3 characters starting at index 2 (c\u6587\u5b57)\nprintln!(\"{}\", s.chars().skip(n).take(m).collect::<String>());\n\n    \/\/ Print all characters starting at index 2 (c\u6587\u5b57\u5316\u3051def)\nprintln!(\"{}\", s.chars().skip(n).collect::<String>());\n\n    \/\/ Print all characters except the last (abc\u6587\u5b57\u5316\u3051de)\nprintln!(\"{}\", s.chars().rev().skip(1).collect::<String>());\n\n    \/\/ Print 3 characters starting with 'b' (bc\u6587)\nlet cpos = s.find('b').unwrap();\nprintln!(\"{}\", s[cpos..].chars().take(m).collect::<String>());\n\n    \/\/ Print 3 characters starting with \"\u3051d\" (\u3051de)\nlet spos = s.find(\"\u3051d\").unwrap();\nprintln!(\"{}\", s[spos..].chars().take(m).collect::<String>());\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":2644}
    {"lang_cluster":"Rust","source_code":"\n\nlet mut buffer = b\"abcdef\".to_vec();\nbuffer.reverse();\nassert_eq!(buffer, b\"fedcba\");\n\nlet output: String = \"\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\".chars().rev().collect();\nassert_eq!(output, \"\u5341\u4e5d\u516b\u4e03\u516d\u4e94\u56db\u4e09\u4e8c\u4e00\");\n\nlet output: String = \"as\u20dddf\u0305\".chars().rev().collect();\nassert_ne!(output, \"f\u0305ds\u20dda\"); \/\/ should be this\nassert_eq!(output, \"\u0305fd\u20ddsa\");\n\nuse unicode_segmentation::UnicodeSegmentation;\n\nlet output: String = \"as\u20dddf\u0305\".graphemes(true).rev().collect();\nassert_eq!(output, \"f\u0305ds\u20dda\");\n","human_summarization":"The code takes an input string and reverses it. It also ensures the preservation of Unicode combining characters during the reversal process. The code handles the reversal of ASCII byte-slice in-place, Unicode scalar values, and graphemes clusters, which accounts for combining marks. The reversal of graphemes clusters is facilitated by the unicode-segmentation crate.","id":2645}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::cmp::Ordering;\nuse std::collections::BinaryHeap;\nuse std::usize;\n\n\nstruct Grid<T> {\n    nodes: Vec<Node<T>>,\n}\n\nstruct Node<T> {\n    data: T,\n    edges: Vec<(usize,usize)>,\n}\n\n#[derive(Copy, Clone, Eq, PartialEq)]\nstruct State {\n    node: usize,\n    cost: usize,\n}\n\n\/\/ Manually implement Ord so we get a min-heap instead of a max-heap\nimpl Ord for State {\n    fn cmp(&self, other: &Self) -> Ordering {\n        other.cost.cmp(&self.cost)\n    }\n}\n\nimpl PartialOrd for State {\n    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n        Some(self.cmp(other))\n    }\n}\n\ntype WeightedEdge = (usize, usize, usize);\n\nimpl<T> Grid<T> {\n    fn new() -> Self {\n        Grid { nodes: Vec::new() }\n    }\n\n    fn add_node(&mut self, data: T) -> usize {\n        let node = Node {\n            edges: Vec::new(),\n            data: data,\n        };\n        self.nodes.push(node);\n        self.nodes.len() - 1\n    }\n\n    fn create_edges<'a, I>(&mut self, iterator: I) where I: IntoIterator<Item=&'a WeightedEdge> {\n        for &(start,end,weight) in iterator.into_iter() {\n            self.nodes[start].edges.push((end,weight));\n            self.nodes[end].edges.push((start,weight));\n        }\n    \n    }\n\n    fn find_path(&self, start: usize, end: usize) -> Option<(Vec<usize>, usize)> {\n        let mut dist = vec![(usize::MAX, None); self.nodes.len()];\n\n        let mut heap = BinaryHeap::new();\n        dist[start] = (0, None);\n        heap.push(State {\n            node: start,\n            cost: 0,\n        });\n\n        while let Some(State { node, cost }) = heap.pop() {\n            if node == end {\n                let mut path = Vec::with_capacity(dist.len() \/ 2);\n                let mut current_dist = dist[end];\n                path.push(end);\n                while let Some(prev) = current_dist.1 {\n                    path.push(prev);\n                    current_dist = dist[prev];\n                }\n                path.reverse();\n                return Some((path, cost));\n            }\n\n            if cost > dist[node].0 {\n                continue;\n            }\n            for edge in &self.nodes[node].edges {\n                let next = State {\n                    node: edge.0,\n                    cost: cost + edge.1,\n                };\n                if next.cost < dist[next.node].0 {\n                    dist[next.node] = (next.cost, Some(node));\n                    heap.push(next);\n                }\n            }\n        }\n        None\n    }\n}\n\nfn main() {\n    let mut grid = Grid::new();\n    let (a,b,c,d,e,f) = (grid.add_node(\"a\"), grid.add_node(\"b\"),\n                         grid.add_node(\"c\"), grid.add_node(\"d\"),\n                         grid.add_node(\"e\"), grid.add_node(\"f\"));\n\n    grid.create_edges(&[\n        (a,b,7) ,(a,c,9) ,(a,f,14),\n        (b,c,10),(b,d,15),(c,d,11),\n        (c,f,2) ,(d,e,6) ,(e,f,9) ,\n    ]);\n\n    let (path, cost) = grid.find_path(a,e).unwrap();\n\n    print!(\"{}\", grid.nodes[path[0]].data);\n    for i in path.iter().skip(1) {\n        print!(\" -> {}\", grid.nodes[*i].data);\n    }\n    println!(\"\\nCost: {}\", cost);\n\n}\n\n\n","human_summarization":"The code implements Dijkstra's algorithm to find the shortest path from a single source to all other vertices in a given graph. The graph is represented using an adjacency list. The algorithm starts from a given node, finds the path with the lowest cost to every other node, and outputs a set of edges depicting these shortest paths. The code also includes functionality to interpret the output and display the shortest path from the starting node to specific nodes.","id":2646}
    {"lang_cluster":"Rust","source_code":"\nextern crate rand;\nextern crate term_painter;\n\nuse std::cmp::Ordering;\nuse std::fmt::{Debug, Display, Formatter, Result};\n\nuse rand::distributions::Uniform;\nuse rand::Rng;\nuse term_painter::Color::*;\nuse term_painter::ToStyle;\n\npub type NodePtr = Option<usize>;\n\n#[derive(Debug, PartialEq, Clone, Copy)]\npub enum Side {\n    Left,\n    Right,\n    Up,\n    Root,\n}\n\n#[derive(Debug, PartialEq, Clone, Copy)]\nenum DisplayElement {\n    TrunkSpace,\n    SpaceLeft,\n    SpaceRight,\n    SpaceSpace,\n    Root,\n}\n\nimpl DisplayElement {\n    fn string(&self) -> String {\n        match *self {\n            DisplayElement::TrunkSpace => \"    \u2502   \".to_string(),\n            DisplayElement::SpaceRight => \"    \u250c\u2500\u2500\u2500\".to_string(),\n            DisplayElement::SpaceLeft => \"    \u2514\u2500\u2500\u2500\".to_string(),\n            DisplayElement::SpaceSpace => \"        \".to_string(),\n            DisplayElement::Root => \"\u251c\u2500\u2500\".to_string(),\n        }\n    }\n}\n\n\/\/\/ Handedness of balanced insert and delete operations differs only by values encapsulated here.\nstruct BalanceConstants {\n    bal_incr: i8,\n    this_side: Side,\n    that_side: Side,\n    key_order: Ordering, \/\/ Ins only\n    \/\/ These are used in the +1\/-1 & -1\/+1 deletion cases\n    gcm1_child_adj: i8, \/\/ Del only, balance adjustment to child for b = -1 grandchild\n    gcm1_parent_adj: i8, \/\/ Del only, balance adjustment to parent for b = -1 grandchild\n    gcp1_child_adj: i8, \/\/ Del only, balance adjustment to child for b = 1 grandchild\n    gcp1_parent_adj: i8, \/\/ Del only, balance adjustment to parent for b = 1 grandchild\n}\n\nconst BALANCE_CONSTANTS_A: BalanceConstants = BalanceConstants {\n    bal_incr: -1,\n    this_side: Side::Left,\n    that_side: Side::Right,\n    key_order: Ordering::Greater,\n    gcm1_child_adj: 0,\n    gcm1_parent_adj: 1,\n    gcp1_child_adj: -1,\n    gcp1_parent_adj: 0,\n};\n\nconst BALANCE_CONSTANTS_B: BalanceConstants = BalanceConstants {\n    bal_incr: 1,\n    this_side: Side::Right,\n    that_side: Side::Left,\n    key_order: Ordering::Less,\n    gcm1_child_adj: 1,\n    gcm1_parent_adj: 0,\n    gcp1_child_adj: 0,\n    gcp1_parent_adj: -1,\n};\n\n#[derive(Debug, Clone, Copy)]\npub struct Node<K, V> {\n    key: K,\n    value: V,\n    balance: i8,\n    left: NodePtr,\n    right: NodePtr,\n    up: NodePtr,\n}\n\n#[derive(Debug)]\npub struct AVLTree<K, V> {\n    root: NodePtr,\n    store: Vec<Node<K, V>>,\n}\n\nimpl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Default for AVLTree<K, V> {\n    fn default() -> Self {\n        AVLTree::new()\n    }\n}\n\nimpl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> AVLTree<K, V> {\n    pub fn get_node(&self, np: NodePtr) -> Node<K, V> {\n        assert!(np.is_some());\n        self.store[np.unwrap()]\n    }\n\n    pub fn get_balance(&self, np: NodePtr) -> i8 {\n        assert!(np.is_some());\n        self.store[np.unwrap()].balance\n    }\n\n    pub fn get_key(&self, np: NodePtr) -> K {\n        assert!(np.is_some());\n        self.store[np.unwrap()].key\n    }\n\n    pub fn get_value(&self, np: NodePtr) -> V {\n        assert!(np.is_some());\n        self.store[np.unwrap()].value\n    }\n\n    pub fn get_pointer(&self, np: NodePtr, side: Side) -> NodePtr {\n        assert!(np.is_some());\n        self.store[np.unwrap()].get_ptr(side)\n    }\n\n    pub fn set_balance(&mut self, np: NodePtr, bal: i8) {\n        assert!(np.is_some());\n        self.store[np.unwrap()].balance = bal;\n    }\n\n    pub fn set_key(&mut self, np: NodePtr, to: K) {\n        assert!(np.is_some());\n        self.store[np.unwrap()].key = to;\n    }\n\n    pub fn set_value(&mut self, np: NodePtr, to: V) {\n        assert!(np.is_some());\n        self.store[np.unwrap()].value = to;\n    }\n\n    pub fn set_pointer(&mut self, np: NodePtr, side: Side, to: NodePtr) {\n        assert!(np.is_some());\n        self.store[np.unwrap()].set_ptr(side, to);\n    }\n\n    pub fn increment_balance(&mut self, np: NodePtr, delta: i8) -> i8 {\n        assert!(np.is_some());\n        self.store[np.unwrap()].balance += delta;\n        self.store[np.unwrap()].balance\n    }\n\n    pub fn new() -> Self {\n        AVLTree {\n            root: None,\n            store: Vec::<Node<K, V>>::with_capacity(20_000),\n        }\n    }\n\n    \/\/\/ Insert key-value\n    pub fn insert(&mut self, k: K, v: V) -> Option<Node<K, V>> {\n        let (n, _) = self.insert_node(Node::new(k, v));\n        n\n    }\n\n    \/\/\/ Insert Node struct\n    pub fn insert_node(&mut self, mut n: Node<K, V>) -> (Option<Node<K, V>>, Side) {\n        if self.root.is_none() {\n            assert!(self.store.is_empty());\n            self.store.push(n);\n            self.root = Some(0);\n            return (Some(n), Side::Root);\n        }\n\n        let mut p = self.root; \/\/ Possibly None\n        let mut prev = p;\n        let mut side = Side::Left;\n        while p.is_some() {\n            prev = p;\n            match n.key.cmp(&self.get_key(p)) {\n                Ordering::Less => {\n                    side = Side::Left;\n                    p = self.get_pointer(p, side);\n                }\n                Ordering::Greater => {\n                    side = Side::Right;\n                    p = self.get_pointer(p, side);\n                }\n                Ordering::Equal => {\n                    println!(\"Key exists\");\n                    return (None, side);\n                }\n            }\n        }\n        \/\/ Set child's pointer\n        n.up = prev;\n        \/\/ Stow the node\n        self.store.push(n);\n        \/\/ Set parent's pointer\n        let ptr = Some(self.store.len() - 1);\n        self.set_pointer(prev, side, ptr);\n        (Some(n), side)\n    }\n\n    \/\/\/ Insert key-value and rebalance\n    pub fn insert_bal(&mut self, k: K, v: V) -> Option<Node<K, V>> {\n        self.insert_node_bal(Node::new(k, v))\n    }\n\n    \/\/\/ Insert Node struct and rebalance\n    pub fn insert_node_bal(&mut self, n: Node<K, V>) -> Option<Node<K, V>> {\n        let (nins, side) = self.insert_node(n);\n        if nins.is_none() || side == Side::Root {\n            return nins;\n        }\n\n        let mut p = nins.unwrap().up;\n        let mut is_left = side == Side::Left;\n\n        while p.is_some() {\n            let i_c = get_insertion_constants(is_left);\n\n            let b = self.increment_balance(p, i_c.bal_incr);\n            if b == 0 {\n                break; \/\/ No further adjustments necessary\n            } else if b.abs() > 1 {\n                let child_p = self.get_pointer(p, i_c.this_side);\n                match self.get_balance(child_p) * b {\n                    2 => {\n                        \/\/ -2\/-1 & +2\/+1 patterns\n                        self.single_rotation(i_c.this_side, p, child_p);\n                        self.set_balance(p, 0);\n                        self.set_balance(child_p, 0);\n                        break;\n                    }\n                    -2 => {\n                        \/\/ -2\/+1 & +2\/-1 patterns\n                        let grand_p = self.get_pointer(child_p, i_c.that_side);\n                        self.double_rotation(i_c.this_side, p, child_p, grand_p);\n                        if self.get_pointer(child_p, i_c.this_side).is_none() {\n                            \/\/ Degenerate case, no subtrees\n                            self.set_balance(child_p, 0);\n                            self.set_balance(p, 0);\n                        } else if n.key.cmp(&self.get_key(grand_p)) == i_c.key_order {\n                            self.set_balance(child_p, i_c.bal_incr);\n                            self.set_balance(p, 0);\n                        } else {\n                            self.set_balance(child_p, 0);\n                            self.set_balance(p, -i_c.bal_incr);\n                        }\n                        self.set_balance(grand_p, 0);\n                        break;\n                    }\n                    _ => unreachable!(),\n                }\n            }\n\n            let child_p = p;\n            p = self.get_pointer(p, Side::Up);\n            if p.is_some() {\n                let left_p = self.get_pointer(p, Side::Left);\n                is_left = left_p.is_some() && left_p == child_p;\n            }\n        }\n\n        nins\n    }\n\n    \/\/\/ Remove the node at index from the store and patch the hole in the vector,\n    \/\/\/ modifying pointers in the moved node's parents and children.\n    fn remove_carefully(&mut self, p: NodePtr) {\n        assert!(p.is_some());\n        let index = p.unwrap();\n        let old_index = self.store.len() - 1;\n        self.store.swap_remove(index);\n\n        if index == old_index {\n            \/\/ Nothing moved\n            return;\n        }\n\n        \/\/ Element -1 has moved into the spot _index_. The in-pointers that need modifying\n        \/\/ belong to that element's parent and children.\n\n        \/\/ Fix child pointer in parent:\n        let parent_p = self.get_pointer(p, Side::Up);\n        if parent_p.is_some() {\n            let l = self.get_pointer(parent_p, Side::Left);\n            if l == Some(old_index) {\n                self.set_pointer(parent_p, Side::Left, Some(index));\n            } else {\n                self.set_pointer(parent_p, Side::Right, Some(index));\n            }\n        }\n\n        \/\/ Fix parent pointers in children:\n        let l = self.get_pointer(p, Side::Left);\n        let r = self.get_pointer(p, Side::Right);\n        if l.is_some() {\n            self.set_pointer(l, Side::Up, Some(index));\n        }\n        if r.is_some() {\n            self.set_pointer(r, Side::Up, Some(index));\n        }\n\n        \/\/ Fix root if necessary\n        if self.root == Some(old_index) {\n            self.root = Some(index);\n        }\n    }\n\n    \/\/\/ Uses delete-by-copy procedure if node with key k has two children.\n    \/\/\/ Returns (parent, side) tuple.\n    pub fn delete(&mut self, k: K) -> (NodePtr, Side) {\n        let mut p = self.root;\n        let mut prev = None;\n        let mut res = None;\n        let mut side = Side::Root;\n        while p.is_some() {\n            match k.cmp(&self.get_key(p)) {\n                Ordering::Equal => {\n                    break;\n                }\n                Ordering::Less => {\n                    prev = p;\n                    side = Side::Left;\n                    p = self.get_pointer(p, side);\n                }\n                Ordering::Greater => {\n                    prev = p;\n                    side = Side::Right;\n                    p = self.get_pointer(p, side);\n                }\n            }\n        }\n\n        if p.is_none() {\n            println!(\"Key {:?} not found\", k);\n            return (res, side);\n        }\n\n        let n = self.get_node(p);\n        \/\/ Is this a leaf?\n        if n.is_leaf() {\n            if n.key.cmp(&self.get_key(self.root)) == Ordering::Equal {\n                self.root = None;\n                assert_eq!(self.store.len(), 1);\n            } else {\n                self.set_pointer(prev, side, None);\n            }\n            self.remove_carefully(p);\n            \/\/ The prev pointer is now stale\n            res = if prev == Some(self.store.len()) {\n                p\n            } else {\n                prev\n            };\n\n        \/\/ Is this a one-child node?\n        } else if n.left.is_none() || n.right.is_none() {\n            let ch = if n.left.is_some() { n.left } else { n.right };\n            if n.key.cmp(&self.get_key(self.root)) == Ordering::Equal {\n                self.set_pointer(ch, Side::Up, None);\n                self.root = ch;\n            } else {\n                self.set_pointer(prev, side, ch);\n                self.set_pointer(ch, Side::Up, prev);\n            }\n            self.remove_carefully(p);\n            \/\/ The prev pointer is now stale\n            res = if prev == Some(self.store.len()) {\n                p\n            } else {\n                prev\n            };\n\n        \/\/ Complicated case:  two children, do delete-by-copy. Replace n with its first\n        \/\/ predecessor (the mirror image using the first successor would work as well).\n        } else {\n            let mut tmp = n.left;\n            let mut last = tmp;\n            prev = self.get_pointer(tmp, Side::Up);\n            while tmp.is_some() && self.get_pointer(last, Side::Right).is_some() {\n                prev = self.get_pointer(tmp, Side::Up);\n                last = tmp;\n                tmp = self.get_pointer(tmp, Side::Right);\n            }\n            tmp = last;\n            \/\/ Copy ...\n            let the_key = self.get_key(tmp);\n            let the_value = self.get_value(tmp);\n            self.set_key(p, the_key);\n            self.set_value(p, the_value);\n\n            let left_ptr = self.get_pointer(tmp, Side::Left);\n            if prev == p {\n                self.set_pointer(p, Side::Left, left_ptr);\n                if left_ptr.is_some() {\n                    self.set_pointer(left_ptr, Side::Up, p);\n                }\n                side = Side::Left;\n            } else {\n                self.set_pointer(prev, Side::Right, left_ptr);\n                if left_ptr.is_some() {\n                    self.set_pointer(left_ptr, Side::Up, prev);\n                }\n                side = Side::Right;\n            }\n\n            self.remove_carefully(tmp);\n            \/\/ The prev pointer is now stale\n            res = if prev.unwrap() == self.store.len() {\n                tmp\n            } else {\n                prev\n            };\n        }\n\n        (res, side)\n    }\n\n    \/\/\/ Rebalance on delete\n    pub fn delete_bal(&mut self, k: K) -> Option<Node<K, V>> {\n        \/\/ slug: (pointer to parent of deleted node, side of deleted node)\n        let slug = self.delete(k);\n        let (pdel, side) = slug;\n        if pdel.is_none() {\n            return None;\n        };\n        let ndel = self.get_node(pdel);\n\n        let mut p = pdel;\n        let mut is_left = side == Side::Left;\n\n        \/\/ Rebalance and update balance factors. There are two different rotation sequences that\n        \/\/ are the same within handedness,\n        \/\/ and the +1\/-1 \/ -1\/+1 sequence has three possible balance adjustments\n        \/\/ depending on the grandchild.\n        while p.is_some() {\n            let d_c = get_deletion_constants(is_left);\n\n            let b = self.increment_balance(p, d_c.bal_incr);\n            if b.abs() == 1 {\n                break; \/\/ No further adjustments necessary\n            } else if b.abs() > 1 {\n                let child_p = self.get_pointer(p, d_c.this_side);\n                match self.get_balance(child_p) * b {\n                    2 => {\n                        \/\/ +1\/+1 & -1\/-1 patterns\n                        self.single_rotation(d_c.this_side, p, child_p);\n                        self.set_balance(p, 0);\n                        p = self.get_pointer(p, Side::Up);\n                        self.set_balance(p, 0);\n                    }\n                    0 => {\n                        \/\/ +1\/0 & -1\/0 patterns\n                        self.single_rotation(d_c.this_side, p, child_p);\n                        self.set_balance(p, d_c.bal_incr);\n                        p = self.get_pointer(p, Side::Up);\n                        self.set_balance(p, -d_c.bal_incr);\n                        break; \/\/ No height change\n                    }\n                    -2 => {\n                        \/\/ +1\/-1\/x & -1\/+1\/x patterns\n                        let grand_p = self.get_pointer(child_p, d_c.that_side);\n                        self.double_rotation(d_c.this_side, p, child_p, grand_p);\n                        \/\/ p is now one child, grand_p is the other, child_p is their parent\n                        match self.get_balance(grand_p) {\n                            -1 => {\n                                self.set_balance(p, d_c.gcm1_parent_adj);\n                                self.set_balance(child_p, d_c.gcm1_child_adj);\n                            }\n                            0 => {\n                                self.set_balance(p, 0);\n                                self.set_balance(child_p, 0);\n                            }\n                            1 => {\n                                self.set_balance(p, d_c.gcp1_parent_adj);\n                                self.set_balance(child_p, d_c.gcp1_child_adj);\n                            }\n                            _ => unreachable!(),\n                        }\n                        self.set_balance(grand_p, 0);\n                        p = self.get_pointer(p, Side::Up);\n                    }\n                    _ => unreachable!(),\n                }\n            }\n\n            let child_p = p;\n            p = self.get_pointer(p, Side::Up);\n            if p.is_some() {\n                let left_p = self.get_pointer(p, Side::Left);\n                is_left = left_p.is_some() && left_p == child_p;\n            }\n        }\n\n        Some(ndel)\n    }\n\n    \/\/\/ Returns node value\n    pub fn lookup(&self, k: K) -> Option<V> {\n        self.search(k).map(|n| n.value)\n    }\n\n    \/\/\/ Returns node (not pointer)\n    pub fn search(&self, k: K) -> Option<Node<K, V>> {\n        let mut p = self.root;\n        let mut res = None;\n\n        while p.is_some() {\n            match k.cmp(&self.get_key(p)) {\n                Ordering::Less => {\n                    p = self.get_pointer(p, Side::Left);\n                }\n                Ordering::Greater => {\n                    p = self.get_pointer(p, Side::Right);\n                }\n                Ordering::Equal => {\n                    res = Some(self.get_node(p));\n                    break;\n                }\n            }\n        }\n        res\n    }\n\n    \/\/\/ Do an in-order traversal, where a \"visit\" prints the row with that node in it.\n    fn display(&self, p: NodePtr, side: Side, e: &[DisplayElement], f: &mut Formatter) {\n        if p.is_none() {\n            return;\n        }\n\n        let mut elems = e.to_vec();\n        let node = self.get_node(p);\n        let mut tail = DisplayElement::SpaceSpace;\n        if node.up != self.root {\n            \/\/ Direction switching, need trunk element to be printed for lines before that node\n            \/\/ is visited.\n            let new_elem = if side == Side::Left && node.right.is_some() {\n                DisplayElement::TrunkSpace\n            } else {\n                DisplayElement::SpaceSpace\n            };\n            elems.push(new_elem);\n        }\n        let hindex = elems.len() - 1;\n        self.display(node.right, Side::Right, &elems, f);\n\n        if p == self.root {\n            elems[hindex] = DisplayElement::Root;\n            tail = DisplayElement::TrunkSpace;\n        } else if side == Side::Right {\n            \/\/ Right subtree finished\n            elems[hindex] = DisplayElement::SpaceRight;\n            \/\/ Prepare trunk element in case there is a left subtree\n            tail = DisplayElement::TrunkSpace;\n        } else\n        \/\/ if side == Side::Left\n        {\n            elems[hindex] = DisplayElement::SpaceLeft;\n            let parent_p = self.get_pointer(p, Side::Up);\n            let gp_p = self.get_pointer(parent_p, Side::Up);\n            if gp_p.is_some() && self.get_pointer(gp_p, Side::Right) == parent_p {\n                \/\/ Direction switched, need trunk element starting with this node\/line\n                elems[hindex - 1] = DisplayElement::TrunkSpace;\n            }\n        }\n\n        \/\/ Visit node => print accumulated elements. Each node gets a line.\n        {\n            for e in elems.clone() {\n                let _ = write!(f, \"{}\", e.string());\n            }\n            let _ = write!(\n                f,\n                \"{key:>width$} \",\n                key = Green.bold().paint(node.key),\n                width = 2\n            );\n            let _ = write!(\n                f,\n                \"{value:>width$} \",\n                value = Blue.bold().paint(format!(\"{:.*}\", 2, node.value)),\n                width = 4\n            );\n            let _ = write!(\n                f,\n                \"{bal:<-width$}\n\",\n                bal = Red.bold().paint(node.balance),\n                width = 2\n            );\n\n            elems[hindex] = tail;\n        }\n\n        self.display(node.left, Side::Left, &elems, f);\n    }\n\n    pub fn gather_balances(&self) -> (Vec<K>, Vec<i8>) {\n        let mut keys = Vec::<K>::new();\n        let mut bals = Vec::<i8>::new();\n\n        self.gather_balances_impl(self.root, &mut keys, &mut bals);\n        (keys, bals)\n    }\n\n    fn gather_balances_impl(&self, p: NodePtr, k: &mut Vec<K>, b: &mut Vec<i8>) {\n        if p.is_none() {\n            return;\n        }\n        let r = self.get_pointer(p, Side::Right);\n        self.gather_balances_impl(r, k, b);\n        k.push(self.get_key(p));\n        b.push(self.get_balance(p));\n        let l = self.get_pointer(p, Side::Left);\n        self.gather_balances_impl(l, k, b)\n    }\n\n    pub fn compute_balances(&mut self, p: NodePtr) -> i8 {\n        self.compute_balances_impl(p, 0)\n    }\n\n    fn compute_balances_impl(&mut self, p: NodePtr, level: i8) -> i8 {\n        if p.is_none() {\n            return level - 1;\n        }\n        let r = self.get_pointer(p, Side::Right);\n        let l = self.get_pointer(p, Side::Left);\n        let rb = self.compute_balances_impl(r, level + 1);\n        let lb = self.compute_balances_impl(l, level + 1);\n        self.set_balance(p, rb - lb);\n        std::cmp::max(rb, lb)\n    }\n\n    \/\/\/     P                Q\n    \/\/\/   \/   \\     =>     \/       \/\/\/  h     Q          P     h'\n    fn rotate_left(&mut self, p: NodePtr, q: NodePtr) {\n        assert!(p.is_some());\n        assert!(q.is_some());\n        let p_parent = self.get_pointer(p, Side::Up);\n        \/\/ Take care of parent pointers\n        self.set_pointer(q, Side::Up, p_parent);\n        self.set_pointer(p, Side::Up, q);\n        let ql = self.get_pointer(q, Side::Left);\n        if ql.is_some() {\n            self.set_pointer(ql, Side::Up, p);\n        }\n\n        \/\/ Take care of child pointers\n        self.set_pointer(q, Side::Left, p);\n        self.set_pointer(p, Side::Right, ql);\n        if p_parent.is_some() {\n            let side = if self.get_pointer(p_parent, Side::Right) == p {\n                Side::Right\n            } else {\n                Side::Left\n            };\n            self.set_pointer(p_parent, side, q);\n        } else {\n            self.root = q;\n        }\n    }\n\n    \/\/\/     P                Q\n    \/\/\/   \/   \\     =>     \/       \/\/\/  Q     h          h'    P\n    fn rotate_right(&mut self, p: NodePtr, q: NodePtr) {\n        assert!(p.is_some());\n        assert!(q.is_some());\n        let p_parent = self.get_pointer(p, Side::Up);\n        \/\/ Take care of parent pointers\n        self.set_pointer(q, Side::Up, p_parent);\n        self.set_pointer(p, Side::Up, q);\n        let qr = self.get_pointer(q, Side::Right);\n        if qr.is_some() {\n            self.set_pointer(qr, Side::Up, p);\n        }\n\n        \/\/ Take care of child pointers\n        self.set_pointer(q, Side::Right, p);\n        self.set_pointer(p, Side::Left, qr);\n        if p_parent.is_some() {\n            let side = if self.get_pointer(p_parent, Side::Right) == p {\n                Side::Right\n            } else {\n                Side::Left\n            };\n            self.set_pointer(p_parent, side, q);\n        } else {\n            self.root = q;\n        }\n    }\n\n    fn single_rotation(&mut self, side: Side, p: NodePtr, q: NodePtr) {\n        if side == Side::Left {\n            self.rotate_right(p, q);\n        } else {\n            self.rotate_left(p, q);\n        }\n    }\n\n    fn double_rotation(&mut self, side: Side, p: NodePtr, child_p: NodePtr, grand_p: NodePtr) {\n        if side == Side::Left {\n            self.rotate_left(child_p, grand_p);\n            self.rotate_right(p, grand_p);\n        } else {\n            self.rotate_right(child_p, grand_p);\n            self.rotate_left(p, grand_p);\n        }\n    }\n}\n\nimpl<K: Ord + Copy, V: Copy> Node<K, V> {\n    pub fn new(k: K, v: V) -> Node<K, V> {\n        Node {\n            key: k,\n            value: v,\n            balance: 0,\n            left: None,\n            right: None,\n            up: None,\n        }\n    }\n\n    pub fn is_leaf(&self) -> bool {\n        self.left.is_none() && self.right.is_none()\n    }\n\n    pub fn set_ptr(&mut self, side: Side, to: NodePtr) {\n        let field = match side {\n            Side::Up => &mut self.up,\n            Side::Left => &mut self.left,\n            _ => &mut self.right,\n        };\n        *field = to;\n    }\n\n    pub fn get_ptr(&self, side: Side) -> NodePtr {\n        match side {\n            Side::Up => self.up,\n            Side::Left => self.left,\n            _ => self.right,\n        }\n    }\n}\n\nimpl<K: Ord + Copy + Debug + Display, V: Debug + Copy + Display> Display for AVLTree<K, V> {\n    fn fmt(&self, f: &mut Formatter) -> Result {\n        if self.root.is_none() {\n            write!(f, \"[empty]\")\n        } else {\n            let v: Vec<DisplayElement> = Vec::new();\n            self.display(self.root, Side::Up, &v, f);\n            Ok(())\n        }\n    }\n}\n\nfn get_insertion_constants(is_left: bool) -> &'static BalanceConstants {\n    if is_left {\n        &BALANCE_CONSTANTS_A\n    } else {\n        &BALANCE_CONSTANTS_B\n    }\n}\n\nfn get_deletion_constants(is_left: bool) -> &'static BalanceConstants {\n    get_insertion_constants(!is_left)\n}\n\npub fn random_bal_tree(n: u32) -> AVLTree<i32, f32> {\n    let mut tree: AVLTree<i32, f32> = AVLTree::new();\n    let mut rng = rand::thread_rng();\n    \/\/ `Uniform` rather than `gen_range`'s `Uniform::sample_single` for speed\n    let key_range = Uniform::new(-(n as i32) \/ 2, (n as i32) \/ 2);\n    let value_range = Uniform::new(-1.0, 1.0);\n    tree.insert_bal(0, rng.sample(value_range));\n    for _ in 0..n {\n        tree.insert_bal(rng.sample(key_range), rng.sample(value_range));\n    }\n    tree\n}\n\n#[cfg(test)]\nmod tests {\n    use rand::{seq, thread_rng};\n\n    use super::AVLTree;\n    use random_bal_tree;\n\n    #[test]\n    fn test_insert() {\n        let mut tree: AVLTree<i32, f32> = AVLTree::new();\n        tree.insert(0, 0.0);\n        tree.insert(8, 8.8);\n        tree.insert(-8, -8.8);\n        assert!(tree.insert(4, 4.4).is_some());\n        tree.insert(12, 12.12);\n\n        assert_eq!(tree.lookup(4), Some(4.4));\n        assert_eq!(tree.lookup(5), None);\n        assert_eq!(tree.lookup(-8), Some(-8.8));\n\n        let s = &tree.store;\n        assert_eq!(\n            s[s[s[tree.root.unwrap()].right.unwrap()].right.unwrap()].value,\n            12.12\n        );\n        assert_eq!(\n            s[s[s[tree.root.unwrap()].right.unwrap()].right.unwrap()].left,\n            None\n        );\n    }\n\n    #[test]\n    fn test_delete() {\n        let mut tree: AVLTree<i32, f32> = AVLTree::new();\n        tree.insert(0, 0.0);\n        tree.insert(8, 8.8);\n        tree.insert(-8, -8.8);\n        assert!(tree.insert(4, 4.4).is_some());\n        tree.insert(12, 12.12);\n\n        \/\/ delete leaf\n        tree.delete(12);\n        assert_eq!(tree.lookup(12), None);\n        let mut n = tree.search(8).unwrap();\n        assert_eq!(n.right, None);\n\n        \/\/ delete one-child node\n        tree.delete(4);\n        assert_eq!(tree.lookup(4), None);\n        n = tree.search(0).unwrap();\n        assert_eq!(tree.store[n.right.unwrap()].key, 8);\n\n        \/\/ delete two-child node\n        tree.insert(6, 6.6);\n        tree.insert(10, 10.10);\n        tree.insert(7, 7.7);\n        tree.delete(8);\n        n = tree.search(7).unwrap();\n        assert_eq!(tree.store[n.left.unwrap()].key, 6);\n        assert_eq!(tree.store[n.right.unwrap()].key, 10);\n        assert_eq!(tree.store[n.up.unwrap()].key, 0);\n\n        \/\/ delete two-child root\n        tree.delete(0);\n        assert_eq!(tree.store[tree.root.unwrap()].key, -8);\n\n        \/\/ delete one-child root\n        tree.delete(-8);\n        assert_eq!(tree.store[tree.root.unwrap()].key, 7);\n\n        \/\/ delete no-child root\n        tree.delete(6);\n        tree.delete(7);\n        tree.delete(10);\n        assert!(tree.root.is_none());\n        assert_eq!(tree.store.len(), 0);\n    }\n\n    #[test]\n    fn test_rotate_left() {\n        let mut tree: AVLTree<i32, f32> = AVLTree::new();\n        tree.insert(0, 0.0);\n        tree.insert(8, 8.8);\n        tree.insert(4, 4.4);\n        tree.insert(-8, -8.8);\n\n        let mut r = tree.root;\n        let mut right = tree.store[r.unwrap()].right;\n        tree.rotate_left(r, right);\n        r = tree.root;\n        right = tree.store[r.unwrap()].right;\n        let left = tree.store[r.unwrap()].left;\n        let left_left = tree.store[left.unwrap()].left;\n        let left_right = tree.store[left.unwrap()].right;\n        assert_eq!(right, None);\n        assert_eq!(tree.store[left.unwrap()].key, 0);\n        assert_eq!(tree.store[left_left.unwrap()].key, -8);\n        assert_eq!(tree.store[left_right.unwrap()].key, 4);\n        assert_eq!(tree.store[r.unwrap()].key, 8);\n    }\n\n    #[test]\n    fn test_rotate_right() {\n        let mut tree: AVLTree<i32, f32> = AVLTree::new();\n        tree.insert(0, 0.0);\n        tree.insert(8, 8.8);\n        tree.insert(-8, -8.8);\n        tree.insert(-4, 4.4);\n\n        let mut r = tree.root;\n        let mut left = tree.store[r.unwrap()].left;\n        tree.rotate_right(r, left);\n        r = tree.root;\n        left = tree.store[r.unwrap()].left;\n        let right = tree.store[r.unwrap()].right;\n        let right_right = tree.store[right.unwrap()].right;\n        let right_left = tree.store[right.unwrap()].left;\n        assert_eq!(left, None);\n        assert_eq!(tree.store[right.unwrap()].key, 0);\n        assert_eq!(tree.store[right_right.unwrap()].key, 8);\n        assert_eq!(tree.store[right_left.unwrap()].key, -4);\n        assert_eq!(tree.store[r.unwrap()].key, -8);\n    }\n\n    #[test]\n    \/\/ This tree tests all four insertion types\n    fn test_balanced_inserts() {\n        let mut tree: AVLTree<i32, f32> = AVLTree::new();\n        tree.insert_bal(0, 0.0);\n        tree.insert_bal(8, 8.8);\n        tree.insert_bal(-8, -8.8);\n        tree.insert_bal(12, 12.12);\n        tree.insert_bal(16, 16.16);\n        tree.insert_bal(11, 11.11);\n        tree.insert_bal(4, 4.4);\n        tree.insert_bal(-10, -8.8);\n        tree.insert_bal(-12, -8.8);\n        tree.insert_bal(-9, -8.8);\n\n        let mut res = tree.gather_balances();\n        let (_, bals) = res;\n        assert!(bals.iter().max().unwrap() < &2);\n        assert!(bals.iter().min().unwrap() > &-2);\n\n        for _ in 0..10 {\n            tree = random_bal_tree(1000);\n            res = tree.gather_balances();\n            let (_, bals) = res;\n            assert!(bals.iter().max().unwrap() < &2);\n            assert!(bals.iter().min().unwrap() > &-2);\n        }\n    }\n\n    #[test]\n    \/\/\/ This sequence hits all five rotation possibilities on each side.\n    fn test_balanced_deletes() {\n        let mut tree: AVLTree<i32, f32> = AVLTree::new();\n        tree.insert_bal(0, 0.0);\n        tree.insert_bal(-32, 0.0);\n        tree.insert_bal(32, 0.0);\n        tree.insert_bal(-64, 0.0);\n        tree.insert_bal(64, 0.0);\n        tree.delete_bal(64);\n        tree.delete_bal(32);\n        tree.delete_bal(-32);\n        tree.delete_bal(-64);\n        tree.delete_bal(0);\n        assert_eq!(tree.root, None);\n        assert_eq!(tree.store.len(), 0);\n\n        tree.insert_bal(0, 0.0);\n        tree.insert_bal(-32, 0.0);\n        tree.insert_bal(32, 0.0);\n        tree.insert_bal(-64, 0.0);\n        tree.insert_bal(64, 0.0);\n        tree.insert_bal(-16, 0.0);\n        tree.insert_bal(16, 0.0);\n        tree.insert_bal(-8, 0.0);\n        tree.insert_bal(8, 0.0);\n        tree.insert_bal(-12, 0.0);\n        tree.insert_bal(-7, 0.0);\n        tree.insert_bal(-6, 0.0);\n        tree.insert_bal(-11, 0.0);\n\n        tree.delete_bal(-64);\n        tree.delete_bal(-32);\n        tree.delete_bal(-7);\n        tree.delete_bal(-6);\n        tree.delete_bal(-16);\n        tree.delete_bal(-11);\n        tree.delete_bal(-12);\n        tree.delete_bal(8);\n        tree.delete_bal(-8);\n        tree.delete_bal(0);\n        tree.insert_bal(24, 0.0);\n        tree.insert_bal(8, 0.0);\n        tree.insert_bal(4, 0.0);\n        tree.insert_bal(128, 0.0);\n        tree.insert_bal(48, 0.0);\n        tree.delete_bal(32);\n        tree.delete_bal(48);\n\n        tree.insert_bal(-24, 0.0);\n        tree.insert_bal(-8, 0.0);\n        tree.insert_bal(-128, 0.0);\n        tree.insert_bal(-48, 0.0);\n        tree.insert_bal(-20, 0.0);\n        tree.insert_bal(-30, 0.0);\n        tree.insert_bal(-22, 0.0);\n        tree.insert_bal(-21, 0.0);\n        tree.delete_bal(24);\n        tree.delete_bal(64);\n        tree.delete_bal(-30);\n        tree.delete_bal(-22);\n        tree.delete_bal(-21);\n        tree.delete_bal(-128);\n        tree.delete_bal(128);\n        tree.delete_bal(-8);\n        tree.insert_bal(-96, 0.0);\n        tree.insert_bal(-95, 0.0);\n        tree.insert_bal(-10, 0.0);\n        tree.insert_bal(6, 0.0);\n        tree.delete_bal(-24);\n\n        let mut res = tree.gather_balances();\n        let (_, bals) = res;\n        assert!(bals.iter().max().unwrap() < &2);\n        assert!(bals.iter().min().unwrap() > &-2);\n\n        let mut p = tree.root;\n        while p.is_some() {\n            let key = tree.store[p.unwrap()].key;\n            tree.delete_bal(key);\n            p = tree.root;\n        }\n        assert_eq!(tree.root, None);\n        assert_eq!(tree.store.len(), 0);\n\n        \/\/ *\/*\/+1 patterns\n        tree.insert(6, 0.0);\n        tree.insert(-1, 0.0);\n        tree.insert(9, 0.0);\n        tree.insert(7, 0.0);\n        tree.insert(3, 0.0);\n        tree.insert(-9, 0.0);\n        tree.insert(4, 0.0);\n        p = tree.root;\n        tree.compute_balances(p);\n        tree.delete_bal(-9);\n        res = tree.gather_balances();\n        let (_, bals) = res;\n        tree.compute_balances(p);\n        res = tree.gather_balances();\n        let (_, bals_after) = res;\n        assert_eq!(bals, bals_after);\n\n        tree.insert(6, 0.0);\n        tree.insert(-1, 0.0);\n        tree.insert(3, 0.0);\n        tree.insert(9, 0.0);\n        tree.insert(7, 0.0);\n        tree.insert(11, 0.0);\n        tree.insert(8, 0.0);\n        p = tree.root;\n        tree.compute_balances(p);\n        tree.delete_bal(-1);\n        res = tree.gather_balances();\n        let (_, bals) = res;\n        tree.compute_balances(p);\n        res = tree.gather_balances();\n        let (_, bals_after) = res;\n        assert_eq!(bals, bals_after);\n\n        let mut rng = thread_rng();\n        for _ in 0..100 {\n            tree = random_bal_tree(100);\n            let sample = seq::sample_iter(&mut rng, -50..50, 80).unwrap();\n            for i in sample {\n                tree.delete_bal(i);\n            }\n        }\n\n        res = tree.gather_balances();\n        let (_, bals) = res;\n\n        if bals.len() > 0 {\n            assert!(*bals.iter().max().unwrap() < 2);\n            assert!(*bals.iter().min().unwrap() > -2);\n        }\n\n        return;\n    }\n}\n","human_summarization":"Implement an AVL tree, a self-balancing binary search tree, in a chosen programming language. The AVL tree ensures the heights of two child subtrees of any node differ by at most one. It supports operations such as lookup, insertion, and deletion, all of which take O(log n) time. The tree may require rebalancing through tree rotations after insertions and deletions. Duplicate node keys are not allowed. The code also compares the performance of AVL trees with red-black trees.","id":2647}
    {"lang_cluster":"Rust","source_code":"use std::fmt;\n\n#[derive(Clone,Copy)]\nstruct Point {\n    x: f64,\n    y: f64\n}\n\nfn distance (p1: Point, p2: Point) -> f64 {\n    ((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt()\n}\n\nimpl fmt::Display for Point {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        write!(f, \"({:.4}, {:.4})\", self.x, self.y)\n    }\n}\n\nfn describe_circle(p1: Point, p2: Point, r: f64) {\n    let sep = distance(p1, p2);\n\n    if sep == 0. {\n        if r == 0. {\n            println!(\"No circles can be drawn through {}\", p1);\n        } else {\n            println!(\"Infinitely many circles can be drawn through {}\", p1);\n        }\n    } else if sep == 2.0 * r {\n        println!(\"Given points are opposite ends of a diameter of the circle with center ({:.4},{:.4}) and r {:.4}\",\n                (p1.x+p2.x) \/ 2.0, (p1.y+p2.y) \/ 2.0, r);\n    } else if sep > 2.0 * r {\n        println!(\"Given points are farther away from each other than a diameter of a circle with r {:.4}\", r);\n    } else {\n        let mirror_dist = (r.powi(2) - (sep \/ 2.0).powi(2)).sqrt();\n\n        println!(\"Two circles are possible.\");\n        println!(\"Circle C1 with center ({:.4}, {:.4}), r {:.4} and Circle C2 with center ({:.4}, {:.4}), r {:.4}\",\n                ((p1.x + p2.x) \/ 2.0) + mirror_dist * (p1.y-p2.y)\/sep, (p1.y+p2.y) \/ 2.0 + mirror_dist*(p2.x-p1.x)\/sep,\n                r,\n                (p1.x+p2.x) \/ 2.0 - mirror_dist*(p1.y-p2.y)\/sep, (p1.y+p2.y) \/ 2.0 - mirror_dist*(p2.x-p1.x)\/sep, r);\n    }\n}\n\nfn main() {\n    let points: Vec<(Point, Point)> = vec![\n        (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.8765, y: 0.2345 }),\n        (Point { x: 0.0000, y: 2.0000 }, Point { x: 0.0000, y: 0.0000 }),\n        (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.1234, y: 0.9876 }),\n        (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.8765, y: 0.2345 }),\n        (Point { x: 0.1234, y: 0.9876 }, Point { x: 0.1234, y: 0.9876 })\n    ];\n    let radii: Vec<f64> = vec![2.0, 1.0, 2.0, 0.5, 0.0];\n\n    for (p, r) in points.into_iter().zip(radii.into_iter()) {\n        println!(\"\\nPoints: ({}, {}), Radius: {:.4}\", p.0, p.1, r);\n        describe_circle(p.0, p.1, r);\n    }\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":2648}
    {"lang_cluster":"Rust","source_code":"\nuse std::convert::TryInto;\nuse std::env;\nuse std::num::Wrapping;\n\nconst REPLACEMENT_TABLE: [[u8; 16]; 8] = [\n    [4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3],\n    [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9],\n    [5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11],\n    [7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3],\n    [6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2],\n    [4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14],\n    [13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12],\n    [1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12],\n];\nconst KEYS: [u32; 8] = [\n    0xE2C1_04F9,\n    0xE41D_7CDE,\n    0x7FE5_E857,\n    0x0602_65B4,\n    0x281C_CC85,\n    0x2E2C_929A,\n    0x4746_4503,\n    0xE00_CE510,\n];\n\nfn main() {\n    let args: Vec<String> = env::args().collect();\n    if args.len() < 2 {\n        let plain_text: Vec<u8> = vec![0x04, 0x3B, 0x04, 0x21, 0x04, 0x32, 0x04, 0x30];\n        println!(\n            \"Before one step: {}\\n\",\n            plain_text\n                .iter()\n                .cloned()\n                .fold(\"\".to_string(), |b, y| b + &format!(\"{:02X} \", y))\n        );\n        let encoded_text = main_step(plain_text, KEYS[0]);\n        println!(\n            \"After one step\u00a0: {}\\n\",\n            encoded_text\n                .iter()\n                .cloned()\n                .fold(\"\".to_string(), |b, y| b + &format!(\"{:02X} \", y))\n        );\n    } else {\n        let mut t = args[1].clone(); \/\/ \"They call him... \u0411\u0430\u0431\u0430 \u042f\u0433\u0430\"\n        t += &\" \".repeat((8 - t.len() % 8) % 8);\n        let text_bytes = t.bytes().collect::<Vec<_>>();\n        let plain_text = text_bytes.chunks(8).collect::<Vec<_>>();\n        println!(\n            \"Plain text \u00a0: {}\\n\",\n            plain_text.iter().cloned().fold(\"\".to_string(), |a, x| a\n                + \"[\"\n                + &x.iter()\n                    .fold(\"\".to_string(), |b, y| b + &format!(\"{:02X} \", y))[..23]\n                + \"]\")\n        );\n        let encoded_text = plain_text\n            .iter()\n            .map(|c| encode(c.to_vec()))\n            .collect::<Vec<_>>();\n        println!(\n            \"Encoded text: {}\\n\",\n            encoded_text.iter().cloned().fold(\"\".to_string(), |a, x| a\n                + \"[\"\n                + &x.into_iter()\n                    .fold(\"\".to_string(), |b, y| b + &format!(\"{:02X} \", y))[..23]\n                + \"]\")\n        );\n        let decoded_text = encoded_text\n            .iter()\n            .map(|c| decode(c.to_vec()))\n            .collect::<Vec<_>>();\n        println!(\n            \"Decoded text: {}\\n\",\n            decoded_text.iter().cloned().fold(\"\".to_string(), |a, x| a\n                + \"[\"\n                + &x.into_iter()\n                    .fold(\"\".to_string(), |b, y| b + &format!(\"{:02X} \", y))[..23]\n                + \"]\")\n        );\n        let recovered_text =\n            String::from_utf8(decoded_text.iter().cloned().flatten().collect::<Vec<_>>()).unwrap();\n        println!(\"Recovered text: {}\\n\", recovered_text);\n    }\n}\n\nfn encode(text_block: Vec<u8>) -> Vec<u8> {\n    let mut step = text_block;\n    for i in 0..24 {\n        step = main_step(step, KEYS[i % 8]);\n    }\n    for i in (0..8).rev() {\n        step = main_step(step, KEYS[i]);\n    }\n    step\n}\n\nfn decode(text_block: Vec<u8>) -> Vec<u8> {\n    let mut step = text_block[4..].to_vec();\n    let mut temp = text_block[..4].to_vec();\n    step.append(&mut temp);\n    for key in &KEYS {\n        step = main_step(step, *key);\n    }\n    for i in (0..24).rev() {\n        step = main_step(step, KEYS[i % 8]);\n    }\n    let mut ans = step[4..].to_vec();\n    let mut temp = step[..4].to_vec();\n    ans.append(&mut temp);\n    ans\n}\n\nfn main_step(text_block: Vec<u8>, key_element: u32) -> Vec<u8> {\n    let mut n = text_block;\n    let mut s = (Wrapping(\n        u32::from(n[0]) << 24 | u32::from(n[1]) << 16 | u32::from(n[2]) << 8 | u32::from(n[3]),\n    ) + Wrapping(key_element))\n    .0;\n    let mut new_s: u32 = 0;\n    for mid in 0..4 {\n        let cell = (s >> (mid << 3)) & 0xFF;\n        new_s += (u32::from(REPLACEMENT_TABLE[(mid * 2) as usize][(cell & 0x0f) as usize])\n            + (u32::from(REPLACEMENT_TABLE[(mid * 2 + 1) as usize][(cell >> 4) as usize]) << 4))\n            << (mid << 3);\n    }\n    s = ((new_s << 11) + (new_s >> 21))\n        ^ (u32::from(n[4]) << 24 | u32::from(n[5]) << 16 | u32::from(n[6]) << 8 | u32::from(n[7]));\n    n[4] = n[0];\n    n[5] = n[1];\n    n[6] = n[2];\n    n[7] = n[3];\n    n[0] = (s >> 24).try_into().unwrap();\n    n[1] = ((s >> 16) & 0xFF).try_into().unwrap();\n    n[2] = ((s >> 8) & 0xFF).try_into().unwrap();\n    n[3] = (s & 0xFF).try_into().unwrap();\n    n\n}\n\n\n","human_summarization":"Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.","id":2649}
    {"lang_cluster":"Rust","source_code":"\nLibrary: rand\n\/\/ cargo-deps: rand\n\nextern crate rand;\nuse rand::{thread_rng, Rng};\n \nfn main() {\n    let mut rng = thread_rng();\n    loop {\n        let num = rng.gen_range(0, 20);\n        if num == 10 {\n            println!(\"{}\", num);\n            break;\n        }\n        println!(\"{}\", rng.gen_range(0, 20));\n    }\n}\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":2650}
    {"lang_cluster":"Rust","source_code":"fn bit_count(mut n: usize) -> usize {\n    let mut count = 0;\n    while n > 0 {\n        n >>= 1;\n        count += 1;\n    }\n    count\n}\n\nfn mod_pow(p: usize, n: usize) -> usize {\n    let mut square = 1;\n    let mut bits = bit_count(p);\n    while bits > 0 {\n        square = square * square;\n        bits -= 1;\n        if (p & (1 << bits)) != 0 {\n            square <<= 1;\n        }\n        square %= n;\n    }\n    return square;\n}\n\nfn is_prime(n: usize) -> bool {\n    if n < 2 {\n        return false;\n    }\n    if n % 2 == 0 {\n        return n == 2;\n    }\n    if n % 3 == 0 {\n        return n == 3;\n    }\n    let mut p = 5;\n    while p * p <= n {\n        if n % p == 0 {\n            return false;\n        }\n        p += 2;\n        if n % p == 0 {\n            return false;\n        }\n        p += 4;\n    }\n    true\n}\n\nfn find_mersenne_factor(p: usize) -> usize {\n    let mut k = 0;\n    loop {\n        k += 1;\n        let q = 2 * k * p + 1;\n        if q % 8 == 1 || q % 8 == 7 {\n            if mod_pow(p, q) == 1 && is_prime(p) {\n                return q;\n            }\n        }\n    }\n}\n\nfn main() {\n    println!(\"{}\", find_mersenne_factor(929));\n}\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":2651}
    {"lang_cluster":"Rust","source_code":"\nuse std::collections::HashSet;\n\nfn main() {\n  let a = vec![1, 3, 4].into_iter().collect::<HashSet<i32>>();\n  let b = vec![3, 5, 6].into_iter().collect::<HashSet<i32>>();\n\n  println!(\"Set A: {:?}\", a.iter().collect::<Vec<_>>());\n  println!(\"Set B: {:?}\", b.iter().collect::<Vec<_>>());\n  println!(\"Does A contain 4? {}\", a.contains(&4));\n  println!(\"Union: {:?}\", a.union(&b).collect::<Vec<_>>());\n  println!(\"Intersection: {:?}\", a.intersection(&b).collect::<Vec<_>>());\n  println!(\"Difference: {:?}\", a.difference(&b).collect::<Vec<_>>());\n  println!(\"Is A a subset of B? {}\", a.is_subset(&b));\n  println!(\"Is A equal to B? {}\", a == b);\n}\n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":2652}
    {"lang_cluster":"Rust","source_code":"\nextern crate chrono;\n\nuse chrono::prelude::*;\n\nfn main() {\n    let years = (2008..2121).filter(|&y| Local.ymd(y, 12, 25).weekday() == Weekday::Sun).collect::<Vec<i32>>();\n    println!(\"Years = {:?}\", years);\n}\n\nYears = [2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118]\n\n","human_summarization":"\"Determines the years between 2008 and 2121 in which Christmas falls on a Sunday using standard date handling libraries, and checks for any discrepancies in date handling across different programming languages.\"","id":2653}
    {"lang_cluster":"Rust","source_code":"\nuse std::collections::HashSet;\nuse std::hash::Hash;\n\nfn remove_duplicate_elements_hashing<T: Hash + Eq>(elements: &mut Vec<T>) {\n    let set: HashSet<_> = elements.drain(..).collect();\n    elements.extend(set.into_iter());\n}\n\nfn remove_duplicate_elements_sorting<T: Ord>(elements: &mut Vec<T>) {\n    elements.sort_unstable(); \/\/ order does not matter\n    elements.dedup();\n}\n\nfn main() {\n    let mut sample_elements = vec![0, 0, 1, 1, 2, 3, 2];\n    println!(\"Before removal of duplicates\u00a0: {:?}\", sample_elements);\n    remove_duplicate_elements_sorting(&mut sample_elements);\n    println!(\"After removal of duplicates\u00a0: {:?}\", sample_elements);\n}\n\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":2654}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    println!(\"Sort numbers in descending order\");\n    let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];\n    println!(\"Before: {:?}\", numbers);\n\n    quick_sort(&mut numbers, &|x,y| x > y);\n    println!(\"After:  {:?}\\n\", numbers);\n\n    println!(\"Sort strings alphabetically\");\n    let mut strings = [\"beach\", \"hotel\", \"airplane\", \"car\", \"house\", \"art\"];\n    println!(\"Before: {:?}\", strings);\n\n    quick_sort(&mut strings, &|x,y| x < y);\n    println!(\"After:  {:?}\\n\", strings);\n    \n    println!(\"Sort strings by length\");\n    println!(\"Before: {:?}\", strings);\n\n    quick_sort(&mut strings, &|x,y| x.len() < y.len());\n    println!(\"After:  {:?}\", strings);    \n}\n\nfn quick_sort<T,F>(v: &mut [T], f: &F) \n    where F: Fn(&T,&T) -> bool\n{\n    let len = v.len();\n    if len >= 2 {\n        let pivot_index = partition(v, f);\n        quick_sort(&mut v[0..pivot_index], f);\n        quick_sort(&mut v[pivot_index + 1..len], f);\n    }\n}\n\nfn partition<T,F>(v: &mut [T], f: &F) -> usize \n    where F: Fn(&T,&T) -> bool\n{\n    let len = v.len();\n    let pivot_index = len \/ 2;\n    let last_index = len - 1;\n\n    v.swap(pivot_index, last_index);\n\n    let mut store_index = 0;\n    for i in 0..last_index {\n        if f(&v[i], &v[last_index]) {\n            v.swap(i, store_index);\n            store_index += 1;\n        }\n    }\n\n    v.swap(store_index, len - 1);\n    store_index\n}\n\n","human_summarization":"implement the Quicksort algorithm for sorting an array or list. The algorithm selects a pivot element and divides the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and combines them with the pivot to produce a sorted array. The code also includes an optimized version of Quicksort that performs the sorting in place to avoid additional memory allocation. The pivot selection method is not specified and can vary. The code also includes a functional style implementation of the algorithm.","id":2655}
    {"lang_cluster":"Rust","source_code":"\n\nfn main() {\n    let now = chrono::Utc::now();\n    println!(\"{}\", now.format(\"%Y-%m-%d\"));\n    println!(\"{}\", now.format(\"%A, %B %d, %Y\"));\n}\n\n","human_summarization":"display the current date in the formats \"2007-11-23\" and \"Friday, November 23, 2007\" using chrono 0.4.6.","id":2656}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::collections::BTreeSet;\n\nfn powerset<T: Ord + Clone>(mut set: BTreeSet<T>) -> BTreeSet<BTreeSet<T>> {\n    if set.is_empty() {\n        let mut powerset = BTreeSet::new();\n        powerset.insert(set);\n        return powerset;\n    }\n    \/\/ Access the first value. This could be replaced with `set.pop_first().unwrap()`\n    \/\/ But this is an unstable feature \n    let entry = set.iter().nth(0).unwrap().clone(); \n    set.remove(&entry);\n    let mut powerset = powerset(set);\n    for mut set in powerset.clone().into_iter() {\n        set.insert(entry.clone());\n        powerset.insert(set);\n    }\n    powerset\n}\n\nfn main() {\n    let set = (1..5).collect();\n    let set = powerset(set);\n    println!(\"{:?}\", set);\n\n    let set = [\"a\", \"b\", \"c\", \"d\"].iter().collect();\n    let set = powerset(set);\n    println!(\"{:?}\", set);\n}\n\n","human_summarization":"implement a function that generates the power set of a given set S. The function can use a library or built-in set type, or define a set type with necessary operations. The power set includes all subsets of S, including the empty set and the set itself. The function should also demonstrate the ability to generate the power set of the empty set and the set containing only the empty set. The implementation requires that the input type T is fully ordered and clonable.","id":2657}
    {"lang_cluster":"Rust","source_code":"\nstruct RomanNumeral {\n    symbol: &'static str,\n    value: u32\n}\n\nconst NUMERALS: [RomanNumeral; 13] = [\n    RomanNumeral {symbol: \"M\",  value: 1000},\n    RomanNumeral {symbol: \"CM\", value: 900},\n    RomanNumeral {symbol: \"D\",  value: 500},\n    RomanNumeral {symbol: \"CD\", value: 400},\n    RomanNumeral {symbol: \"C\",  value: 100},\n    RomanNumeral {symbol: \"XC\", value: 90},\n    RomanNumeral {symbol: \"L\",  value: 50},\n    RomanNumeral {symbol: \"XL\", value: 40},\n    RomanNumeral {symbol: \"X\",  value: 10},\n    RomanNumeral {symbol: \"IX\", value: 9},\n    RomanNumeral {symbol: \"V\",  value: 5},\n    RomanNumeral {symbol: \"IV\", value: 4},\n    RomanNumeral {symbol: \"I\",  value: 1}\n];\n\nfn to_roman(mut number: u32) -> String {\n    let mut min_numeral = String::new();\n    for numeral in NUMERALS.iter() {\n        while numeral.value <= number {\n            min_numeral = min_numeral + numeral.symbol;\n            number -= numeral.value;\n        }\n    }\n    min_numeral\n}\n\nfn main() {\n    let nums = [2014, 1999, 25, 1666, 3888];\n    for &n in nums.iter() {\n        \/\/ 4 is minimum printing width, for alignment\n        println!(\"{:2$} = {}\", n, to_roman(n), 4);\n    }\n}\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":2658}
    {"lang_cluster":"Rust","source_code":"\n\nlet a = [1, 2, 3]; \/\/ immutable array\nlet mut m = [1, 2, 3]; \/\/ mutable array\nlet zeroes = [0; 200]; \/\/ creates an array of 200 zeroes\n\nlet a = [1, 2, 3];\na.len();\nfor e in a.iter() {\n    e;\n}\n\nlet names = [\"Graydon\", \"Brian\", \"Niko\"];\nnames[1]; \/\/ second element\n\nlet v = vec![1, 2, 3];\n\nlet mut v = vec![1, 2, 3];\nv.push(4);\nv.len(); \/\/ 4\n","human_summarization":"demonstrate the basic syntax of arrays in Rust, including the creation of both fixed-length and dynamic arrays (vectors), assigning values to them, and retrieving elements. The codes also show how to make an array mutable, get its length, iterate over it, and use subscript notation to access specific elements. The codes also incorporate elements from obsolete tasks related to array creation, value assignment, and element retrieval.","id":2659}
    {"lang_cluster":"Rust","source_code":"\nuse std::fs::File;\nuse std::io::{Read, Write};\n\nfn main() {\n    let mut file = File::open(\"input.txt\").unwrap();\n    let mut data = Vec::new();\n    file.read_to_end(&mut data).unwrap();\n    let mut file = File::create(\"output.txt\").unwrap();\n    file.write_all(&data).unwrap();\n}\n\nuse std::fs::File;\nuse std::io::{self, Read,  Write};\nuse std::path::Path;\nuse std::{env, fmt, process};\n\nfn main() {\n    let files: Vec<_> = env::args_os().skip(1).take(2).collect();\n\n    if files.len()\u00a0!= 2 {\n        exit_err(\"Both an input file and output file are required\", 1);\n    }\n\n    copy(&files[0], &files[1]).unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));\n}\n\nfn copy<P: AsRef<Path>>(infile: P, outfile: P) -> io::Result<()> {\n    let mut vec = Vec::new();\n\n    Ok(try!(File::open(infile)\n         .and_then(|mut i| i.read_to_end(&mut vec))\n         .and_then(|_| File::create(outfile))\n         .and_then(|mut o| o.write_all(&vec))))\n}\n\nfn exit_err<T: fmt::Display>(msg: T, code: i32) ->\u00a0! {\n    writeln!(&mut io::stderr(), \"ERROR: {}\", msg).expect(\"Could not write to stdout\");\n    process::exit(code);\n}\n","human_summarization":"demonstrate how to read content from \"input.txt\" file into a variable, and then write this variable's content into a new file called \"output.txt\". The program also includes proper error handling.","id":2660}
    {"lang_cluster":"Rust","source_code":"\nWorks with: Rust version  1.3\nfn main() {\n    println!(\"{}\", \"jalape\u00f1o\".to_uppercase()); \/\/ JALAPE\u00d1O\n    println!(\"{}\", \"JALAPE\u00d1O\".to_lowercase()); \/\/ jalape\u00f1o\n}\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":2661}
    {"lang_cluster":"Rust","source_code":"\n\/\/! We interpret complex numbers as points in the Cartesian plane, here. We also use the\n\/\/! [sweepline\/plane sweep closest pairs algorithm][algorithm] instead of the divide-and-conquer\n\/\/! algorithm, since it's (arguably) easier to implement, and an efficient implementation does not\n\/\/! require use of unsafe.\n\/\/!\n\/\/! [algorithm]: http:\/\/www.cs.mcgill.ca\/~cs251\/ClosestPair\/ClosestPairPS.html\nextern crate num;\n\nuse num::complex::Complex;\nuse std::cmp::{Ordering, PartialOrd};\nuse std::collections::BTreeSet;\ntype Point = Complex<f32>;\n\n\/\/\/ Wrapper around `Point` (i.e. `Complex<f32>`) so that we can use a `TreeSet`\n#[derive(PartialEq)]\nstruct YSortedPoint {\n    point: Point,\n}\n\nimpl PartialOrd for YSortedPoint {\n    fn partial_cmp(&self, other: &YSortedPoint) -> Option<Ordering> {\n        (self.point.im, self.point.re).partial_cmp(&(other.point.im, other.point.re))\n    }\n}\n\nimpl Ord for YSortedPoint {\n    fn cmp(&self, other: &YSortedPoint) -> Ordering {\n        self.partial_cmp(other).unwrap()\n    }\n}\n\nimpl Eq for YSortedPoint {}\n\nfn closest_pair(points: &mut [Point]) -> Option<(Point, Point)> {\n    if points.len() < 2 {\n        return None;\n    }\n\n    points.sort_by(|a, b| (a.re, a.im).partial_cmp(&(b.re, b.im)).unwrap());\n\n    let mut closest_pair = (points[0], points[1]);\n    let mut closest_distance_sqr = (points[0] - points[1]).norm_sqr();\n    let mut closest_distance = closest_distance_sqr.sqrt();\n\n    \/\/ the strip that we inspect for closest pairs as we sweep right\n    let mut strip: BTreeSet<YSortedPoint> = BTreeSet::new();\n    strip.insert(YSortedPoint { point: points[0] });\n    strip.insert(YSortedPoint { point: points[1] });\n\n    \/\/ index of the leftmost point on the strip (on points)\n    let mut leftmost_idx = 0;\n\n    \/\/ Start the sweep!\n    for (idx, point) in points.iter().enumerate().skip(2) {\n        \/\/ Remove all points farther than `closest_distance` away from `point`\n        \/\/ along the x-axis\n        while leftmost_idx < idx {\n            let leftmost_point = &points[leftmost_idx];\n            if (leftmost_point.re - point.re).powi(2) < closest_distance_sqr {\n                break;\n            }\n            strip.remove(&YSortedPoint {\n                point: *leftmost_point,\n            });\n            leftmost_idx += 1;\n        }\n\n        \/\/ Compare to points in bounding box\n        {\n            let low_bound = YSortedPoint {\n                point: Point {\n                    re:\u00a0::std::f32::INFINITY,\n                    im: point.im - closest_distance,\n                },\n            };\n            let mut strip_iter = strip.iter().skip_while(|&p| p < &low_bound);\n            loop {\n                let point2 = match strip_iter.next() {\n                    None => break,\n                    Some(p) => p.point,\n                };\n                if point2.im - point.im >= closest_distance {\n                    \/\/ we've reached the end of the box\n                    break;\n                }\n                let dist_sqr = (*point - point2).norm_sqr();\n                if dist_sqr < closest_distance_sqr {\n                    closest_pair = (point2, *point);\n                    closest_distance_sqr = dist_sqr;\n                    closest_distance = dist_sqr.sqrt();\n                }\n            }\n        }\n\n        \/\/ Insert point into strip\n        strip.insert(YSortedPoint { point: *point });\n    }\n\n    Some(closest_pair)\n}\n\npub fn main() {\n    let mut test_data = [\n        Complex::new(0.654682, 0.925557),\n        Complex::new(0.409382, 0.619391),\n        Complex::new(0.891663, 0.888594),\n        Complex::new(0.716629, 0.996200),\n        Complex::new(0.477721, 0.946355),\n        Complex::new(0.925092, 0.818220),\n        Complex::new(0.624291, 0.142924),\n        Complex::new(0.211332, 0.221507),\n        Complex::new(0.293786, 0.691701),\n        Complex::new(0.839186, 0.728260),\n    ];\n    let (p1, p2) = closest_pair(&mut test_data[..]).unwrap();\n    println!(\"Closest pair: {} and {}\", p1, p2);\n    println!(\"Distance: {}\", (p1 - p2).norm_sqr().sqrt());\n}\n\n\n","human_summarization":"provide two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute force algorithm with a complexity of O(n^2) to find the two closest points. The second function uses a recursive divide and conquer approach with a complexity of O(n log n) to find the two closest points. Both functions return the minimum distance and the pair of points.","id":2662}
    {"lang_cluster":"Rust","source_code":"\n\n\nlet a = [1u8,2,3,4,5]; \/\/ a is of type [u8; 5];\nlet b = [0;256] \/\/ Equivalent to `let b = [0,0,0,0,0,0... repeat 256 times]`\n\nlet array = [1,2,3,4,5];\nlet slice = &array[0..2]\nprintln!(\"{:?}\", slice);\n\n","human_summarization":"create a collection and add values to it. The collection can be of various types such as arrays, slices, string slices, vectors, strings, VecDequeue, doubly-linked list, hash map, B-Tree map, set implementations, and priority queue. The type of collection used depends on the specific requirements of the task.","id":2663}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    for i in 1..=10 {\n        print!(\"{}{}\", i, if i < 10 { \", \" } else { \"\\n\" });\n    }\n}\n\nfn main() {\n    for i in 1..=10 {\n        print!(\"{}\", i);\n        if i == 10 { \n            break;\n        }\n        print!(\", \");\n    }\n    println!();\n}\n\nfn main() {\n    println!(\n        \"{}\",\n        (1..=10)\n            .map(|i| i.to_string())\n            .collect::<Vec<_>>()\n            .join(\", \")\n    );\n}\n","human_summarization":"generates a comma-separated list from 1 to 10 using a loop, with separate output statements for the number and the comma in the loop body. An alternative solution uses the join method.","id":2664}
    {"lang_cluster":"Rust","source_code":"\nuse std::boxed::Box;\nuse std::collections::{HashMap, HashSet};\n\n#[derive(Debug, PartialEq, Eq, Hash)]\nstruct Library<'a> {\n    name: &'a str,\n    children: Vec<&'a str>,\n    num_parents: usize,\n}\n\nfn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {\n    let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();\n\n    for input_line in input {\n        let line_split = input_line.split_whitespace().collect::<Vec<&str>>();\n        let name = line_split.get(0).unwrap();\n        let mut num_parents: usize = 0;\n        for parent in line_split.iter().skip(1) {\n            if parent == name {\n                continue;\n            }\n            if !libraries.contains_key(parent) {\n                libraries.insert(\n                    parent,\n                    Box::new(Library {\n                        name: parent,\n                        children: vec![name],\n                        num_parents: 0,\n                    }),\n                );\n            } else {\n                libraries.get_mut(parent).unwrap().children.push(name);\n            }\n            num_parents += 1;\n        }\n\n        if !libraries.contains_key(name) {\n            libraries.insert(\n                name,\n                Box::new(Library {\n                    name,\n                    children: Vec::new(),\n                    num_parents,\n                }),\n            );\n        } else {\n            libraries.get_mut(name).unwrap().num_parents = num_parents;\n        }\n    }\n    libraries\n}\n\nfn topological_sort<'a>(\n    mut libraries: HashMap<&'a str, Box<Library<'a>>>,\n) -> Result<Vec<&'a str>, String> {\n    let mut needs_processing = libraries\n        .iter()\n        .map(|(k, _v)| k.clone())\n        .collect::<HashSet<&str>>();\n    let mut options: Vec<&str> = libraries\n        .iter()\n        .filter(|(_k, v)| v.num_parents == 0)\n        .map(|(k, _v)| *k)\n        .collect();\n    let mut sorted: Vec<&str> = Vec::new();\n    while !options.is_empty() {\n        let cur = options.pop().unwrap();\n        for children in libraries\n            .get_mut(cur)\n            .unwrap()\n            .children\n            .drain(0..)\n            .collect::<Vec<&str>>()\n        {\n            let child = libraries.get_mut(children).unwrap();\n            child.num_parents -= 1;\n            if child.num_parents == 0 {\n                options.push(child.name)\n            }\n        }\n        sorted.push(cur);\n        needs_processing.remove(cur);\n    }\n    match needs_processing.is_empty() {\n        true => Ok(sorted),\n        false => Err(format!(\"Cycle detected among {:?}\", needs_processing)),\n    }\n}\n\nfn main() {\n    let input: Vec<&str> = vec![\n        \"des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\\n\",\n        \"dw01             ieee dw01 dware gtech dw04\\n\",\n        \"dw02             ieee dw02 dware\\n\",\n        \"dw03             std synopsys dware dw03 dw02 dw01 ieee gtech\\n\",\n        \"dw04             dw04 ieee dw01 dware gtech\\n\",\n        \"dw05             dw05 ieee dware\\n\",\n        \"dw06             dw06 ieee dware\\n\",\n        \"dw07             ieee dware\\n\",\n        \"dware            ieee dware\\n\",\n        \"gtech            ieee gtech\\n\",\n        \"ramlib           std ieee\\n\",\n        \"std_cell_lib     ieee std_cell_lib\\n\",\n        \"synopsys\\n\",\n    ];\n\n    let libraries = build_libraries(input);\n    match topological_sort(libraries) {\n        Ok(sorted) => println!(\"{:?}\", sorted),\n        Err(msg) => println!(\"{:?}\", msg),\n    }\n}\n\n\n[\"std\", \"synopsys\", \"ieee\", \"std_cell_lib\", \"ramlib\", \"gtech\", \"dware\", \"dw07\", \"dw06\", \"dw05\", \"dw02\", \"dw01\", \"dw04\", \"dw03\", \"des_system_lib\"]\n\n\n\"des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\\n\",\n        \"dw01             ieee dw01 dware gtech dw04\\n\",\n        \"dw02             ieee dw02 dware\\n\",\n        \"dw03             std synopsys dware dw03 dw02 dw01 ieee gtech\\n\",\n        \"dw04             dw04 ieee dw01 dware gtech\\n\",\n        \"dw05             dw05 ieee dware\\n\",\n        \"dw06             dw06 ieee dware\\n\",\n        \"dw07             ieee dware\\n\",\n        \"dware            ieee dware\\n\",\n        \"gtech            ieee gtech\\n\",\n        \"ramlib           std ieee\\n\",\n        \"std_cell_lib     ieee std_cell_lib\\n\",\n        \"synopsys\\n\",\n\n\"Cycle detected among {\\\"dw03\\\", \\\"des_system_lib\\\", \\\"dw04\\\", \\\"dw01\\\"}\"\n\n","human_summarization":"implement a function that performs a topological sort on VHDL libraries based on their dependencies. The function returns a valid compile order of the libraries, ignoring self-dependencies and flagging un-orderable dependencies. The libraries are assumed to be single words and the order of compiling for libraries mentioned only as dependents is also provided. The function uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":2665}
    {"lang_cluster":"Rust","source_code":"\nfn print_match(possible_match: Option<usize>) {\n    match possible_match {\n        Some(match_pos) => println!(\"Found match at pos {}\", match_pos),\n        None => println!(\"Did not find any matches\")\n    }\n}\n\nfn main() {\n    let s1 = \"abcd\";\n    let s2 = \"abab\";\n    let s3 = \"ab\";\n    \n    \/\/ Determining if the first string starts with second string\n    assert!(s1.starts_with(s3));\n    \/\/ Determining if the first string contains the second string at any location\n    assert!(s1.contains(s3));\n    \/\/ Print the location of the match \n    print_match(s1.find(s3)); \/\/ Found match at pos 0\n    print_match(s1.find(s2)); \/\/ Did not find any matches\n    \/\/ Determining if the first string ends with the second string\n    assert!(s2.ends_with(s3));\n}\n\nfn main(){\n    let hello = String::from(\"Hello world\");\n    println!(\" Start with \\\"he\\\" {} \\n Ends with \\\"rd\\\" {}\\n Contains \\\"wi\\\" {}\", \n                                                        hello.starts_with(\"He\"),\n                                                        hello.ends_with(\"ld\"),\n                                                        hello.contains(\"wi\"));\n}\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":2666}
    {"lang_cluster":"Rust","source_code":"\n#![feature(inclusive_range_syntax)]\n\nfn is_unique(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8) -> bool {\n    a != b && a != c && a != d && a != e && a != f && a != g &&\n    b != c && b != d && b != e && b != f && b != g &&\n    c != d && c != e && c != f && c != g &&\n    d != e && d != f && d != g &&\n    e != f && e != g &&\n    f != g\n}\n\nfn is_solution(a: u8, b: u8, c: u8, d: u8, e: u8, f: u8, g: u8) -> bool {\n    a + b == b + c + d &&\n        b + c + d == d + e + f &&\n        d + e + f == f + g\n}\n\nfn four_squares(low: u8, high: u8, unique: bool) -> Vec<Vec<u8>> {\n    let mut results: Vec<Vec<u8>> = Vec::new();\n\n    for a in low..=high {\n        for b in low..=high {\n            for c in low..=high {\n                for d in low..=high {\n                    for e in low..=high {\n                        for f in low..=high {\n                            for g in low..=high {\n                                if (!unique || is_unique(a, b, c, d, e, f, g)) &&\n                                    is_solution(a, b, c, d, e, f, g) {\n                                    results.push(vec![a, b, c, d, e, f, g]);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    results\n}\n\nfn print_results(solutions: &Vec<Vec<u8>>) {\n    for solution in solutions {\n        println!(\"{:?}\", solution)\n    }\n}\n\nfn print_results_summary(solutions: usize, low: u8, high: u8, unique: bool) {\n    let uniqueness = if unique {\n        \"unique\"\n    } else {\n        \"non-unique\"\n    };\n    println!(\"{} {} solutions in {} to {} range\", solutions, uniqueness, low, high)\n}\n\nfn uniques(low: u8, high: u8) {\n    let solutions = four_squares(low, high, true);\n    print_results(&solutions);\n    print_results_summary(solutions.len(), low, high, true);\n}\n\nfn nonuniques(low: u8, high: u8) {\n    let solutions = four_squares(low, high, false);\n    print_results_summary(solutions.len(), low, high, false);\n}\n\nfn main() {\n    uniques(1, 7);\n    println!();\n    uniques(3, 9);\n    println!();\n    nonuniques(0, 9);\n}\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":2667}
    {"lang_cluster":"Rust","source_code":"\n\/\/ cargo-deps: time=\"0.1\"\nextern crate time;\n\nuse std::thread;\nuse std::time::Duration;\n\nconst TOP: &str = \" \u284e\u2889\u28b5 \u2800\u28ba\u2800 \u280a\u2809\u2871 \u280a\u28c9\u2871 \u2880\u2814\u2847 \u28cf\u28c9\u2849 \u28ce\u28c9\u2841 \u280a\u2889\u281d \u288e\u28c9\u2871 \u284e\u2809\u28b1 \u2800\u2836\u2800\";\nconst BOT: &str = \" \u2897\u28c1\u2878 \u2880\u28f8\u28c0 \u28d4\u28c9\u28c0 \u2884\u28c0\u2878 \u2809\u2809\u284f \u2884\u28c0\u2878 \u2887\u28c0\u2878 \u28b0\u2801\u2800 \u2887\u28c0\u2878 \u2888\u28c9\u2879 \u2800\u2836\u2800\";\n\nfn main() {\n    let top: Vec<&str> = TOP.split_whitespace().collect();\n    let bot: Vec<&str> = BOT.split_whitespace().collect();\n\n    loop {\n        let tm = &time::now().rfc822().to_string()[17..25];\n        let top_str: String = tm.chars().map(|x| top[x as usize - '0' as usize]).collect();\n        let bot_str: String = tm.chars().map(|x| bot[x as usize - '0' as usize]).collect();\n\n        clear_screen();\n        println!(\"{}\", top_str);\n        println!(\"{}\", bot_str);\n\n        thread::sleep(Duration::from_secs(1));\n    }\n}\n\nfn clear_screen() {\n    println!(\"{}[H{}[J\", 27 as char, 27 as char);\n}\n\n","human_summarization":"illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.","id":2668}
    {"lang_cluster":"Rust","source_code":"\nuse std::thread;\n\nfn f1 (a : u64, b : u64, c : u64, d : u64) -> u64 {\n    let mut primitive_count = 0;\n    for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], \n                     [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c],\n                     [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() {\n        let l  = triangle[0] + triangle[1] + triangle[2];\n        if l > d { continue; }\n        primitive_count +=  1 + f1(triangle[0], triangle[1], triangle[2], d);\n    }\n    primitive_count\n}\n\nfn f2 (a : u64, b : u64, c : u64, d : u64) -> u64 {\n    let mut triplet_count = 0;\n    for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], \n                     [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c],\n                     [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() {\n        let l  = triangle[0] + triangle[1] + triangle[2];\n        if l > d { continue; }\n        triplet_count +=  (d\/l) + f2(triangle[0], triangle[1], triangle[2], d);\n    }\n    triplet_count\n}\n\nfn main () {\n    let new_th_1 = thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || {\n        let mut i = 100;\n        while i <= 100_000_000_000 {\n            println!(\" Primitive triples below {}\u00a0: {}\", i, f1(3, 4, 5, i) + 1);\n            i *= 10;\n        }\n    }).unwrap();\n\n    let new_th_2 =thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || {\n        let mut i = 100;\n        while i <= 100_000_000_000 {\n            println!(\" Triples below {}\u00a0: {}\", i, f2(3, 4, 5, i) + i\/12);\n            i *= 10;\n        }\n    }).unwrap();\n\n    new_th_1.join().unwrap();\n    new_th_2.join().unwrap();\n}\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":2669}
    {"lang_cluster":"Rust","source_code":"\nLibrary: winit\nuse winit::event::{Event, WindowEvent};  \/\/ winit 0.24\nuse winit::event_loop::{ControlFlow, EventLoop};\nuse winit::window::WindowBuilder;\n\nfn main() {\n    let event_loop = EventLoop::new();\n    let _win = WindowBuilder::new()\n        .with_title(\"Window\")\n        .build(&event_loop).unwrap();\n\n    event_loop.run(move |ev, _, flow| {\n        match ev {\n            Event::WindowEvent {\n                event: WindowEvent::CloseRequested, ..\n            } => {\n                *flow = ControlFlow::Exit;\n            }\n            _ => {}\n        }\n    });\n}\n\n\n","human_summarization":"Create an empty GUI window that can handle close requests.","id":2670}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::collections::btree_map::BTreeMap;\nuse std::{env, process};\nuse std::io::{self, Read, Write};\nuse std::fmt::Display;\nuse std::fs::File;\n\nfn main() {\n    let filename = env::args().nth(1)\n        .ok_or(\"Please supply a file name\")\n        .unwrap_or_else(|e| exit_err(e, 1));\n\n    let mut buf = String::new();\n    let mut count = BTreeMap::new();\n\n    File::open(&filename)\n        .unwrap_or_else(|e| exit_err(e, 2))\n        .read_to_string(&mut buf)\n        .unwrap_or_else(|e| exit_err(e, 3));\n\n\n    for c in buf.chars() {\n        *count.entry(c).or_insert(0) += 1;\n    }\n\n    println!(\"Number of occurences per character\");\n    for (ch, count) in &count {\n        println!(\"{:?}: {}\", ch, count);\n    }\n}\n\n#[inline]\nfn exit_err<T>(msg: T, code: i32) -> ! where T: Display {\n    writeln!(&mut io::stderr(), \"{}\", msg).expect(\"Could not write to stderr\");\n    process::exit(code)\n}\n\n\nNumber of occurences per character\n'\\n': 35\n' ': 167\n'!': 4\n'\\\"': 10\n'#': 1\n'&': 4\n'(': 25\n')': 25\n'*': 1\n'+': 1\n',': 12\n'-': 1\n'.': 10\n'0': 1\n'1': 3\n'2': 2\n'3': 2\n':': 37\n';': 13\n'<': 1\n'=': 4\n'>': 2\n'?': 1\n'B': 2\n'C': 1\n'D': 2\n'F': 2\n'M': 2\n'N': 1\n'P': 1\n'R': 1\n'S': 1\n'T': 5\n'W': 1\n'[': 1\n']': 1\n'_': 15\n'a': 20\n'b': 5\n'c': 22\n'd': 12\n'e': 75\n'f': 14\n'g': 5\n'h': 6\n'i': 29\n'k': 1\n'l': 23\n'm': 13\n'n': 36\n'o': 28\n'p': 17\n'r': 45\n's': 33\n't': 42\n'u': 24\n'v': 2\n'w': 8\n'x': 6\n'y': 4\n'{': 9\n'|': 6\n'}': 9\n\n","human_summarization":"The code opens a text file and counts the frequency of each letter, including all UTF-8 characters. It can count all characters or only letters from A to Z, depending on the program. The output is generated when run on the source file.","id":2671}
    {"lang_cluster":"Rust","source_code":"\n\n struct Node<T> {\n    elem: T,\n    next: Option<Box<Node<T>>>,\n}\n\n\ntype Link<T> = Option<Box<Node<T>>>; \/\/ Type alias\npub struct List<T> { \/\/ User-facing interface for list\n    head: Link<T>,\n}\n\nstruct Node<T> { \/\/ Private implementation of Node\n    elem: T,\n    next: Link<T>,\n}\n\nimpl<T> List<T> {\n    #[inline]\n    pub fn new() -> Self { \/\/ List constructor\n        List { head: None }\n    \/\/ Add other methods here\n}\n\n\nextern crate LinkedList; \/\/ Name is arbitrary here\n\nuse LinkedList::List;\n\nfn main() {\n    let list = List::new();\n    \/\/ Do stuff\n}\n\n","human_summarization":"define a data structure for a singly-linked list element. This element holds a numeric value and a mutable link to the next element. The implementation uses Rust's Option<T> type and Box<T> for a known size. However, it lacks encapsulation for library use. A separate program can utilize this basic implementation.","id":2672}
    {"lang_cluster":"Rust","source_code":"\nLibrary: Piston\n\/\/Cargo deps\u00a0:\n\/\/  piston = \"0.35.0\"\n\/\/  piston2d-graphics = \"0.23.0\"\n\/\/  piston2d-opengl_graphics = \"0.49.0\"\n\/\/  pistoncore-glutin_window = \"0.42.0\"\n\nextern crate piston;\nextern crate graphics;\nextern crate opengl_graphics;\nextern crate glutin_window;\n\nuse piston::window::WindowSettings;\nuse piston::event_loop::{Events, EventSettings};\nuse piston::input::RenderEvent;\nuse glutin_window::GlutinWindow as Window;\nuse opengl_graphics::{GlGraphics, OpenGL};\nuse graphics::{clear, line, Context};\n\nconst ANG: f64 = 20.0;\nconst COLOR: [f32; 4] = [1.0, 0.0, 0.5, 1.0];\nconst LINE_THICKNESS: f64 = 5.0;\nconst DEPTH: u32 = 11;\n\nfn main() {\n    let mut window: Window = WindowSettings::new(\"Fractal Tree\", [1024, 768])\n        .opengl(OpenGL::V3_2)\n        .exit_on_esc(true)\n        .build()\n        .unwrap();\n    let mut gl = GlGraphics::new(OpenGL::V3_2);\n\n    let mut events = Events::new(EventSettings::new());\n    while let Some(e) = events.next(&mut window) {\n        if let Some(args) = e.render_args() {\n            gl.draw(args.viewport(), |c, g| {\n                clear([1.0, 1.0, 1.0, 1.0], g);\n                draw_fractal_tree(512.0, 700.0, 0.0, DEPTH, c, g);\n            });\n        }\n    }\n}\n\nfn draw_fractal_tree(x1: f64, y1: f64, angle: f64, depth: u32, c: Context, g: &mut GlGraphics) {\n    let x2 = x1 + angle.to_radians().sin() * depth as f64 * 10.0;\n    let y2 = y1 - angle.to_radians().cos() * depth as f64 * 10.0;\n    line(\n        COLOR,\n        LINE_THICKNESS * depth as f64 * 0.2,\n        [x1, y1, x2, y2],\n        c.transform,\n        g,\n    );\n    if depth > 0 {\n        draw_fractal_tree(x2, y2, angle - ANG, depth - 1, c, g);\n        draw_fractal_tree(x2, y2, angle + ANG, depth - 1, c, g);\n    }\n}\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":2673}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    assert_eq!(vec![1, 2, 4, 5, 10, 10, 20, 25, 50, 100], factor(100)); \/\/ asserts that two expressions are equal to each other\n    assert_eq!(vec![1, 101], factor(101));\n\n}\n\nfn factor(num: i32) -> Vec<i32> {\n    let mut factors: Vec<i32> = Vec::new(); \/\/ creates a new vector for the factors of the number\n\n    for i in 1..((num as f32).sqrt() as i32 + 1) { \n        if num\u00a0% i == 0 {\n            factors.push(i); \/\/ pushes smallest factor to factors\n            factors.push(num\/i); \/\/ pushes largest factor to factors\n        }\n    }\n    factors.sort(); \/\/ sorts the factors into numerical order for viewing purposes\n    factors \/\/ returns the factors\n}\n\nfn factor(n: i32) -> Vec<i32> {\n    (1..=n).filter(|i| n\u00a0% i == 0).collect()\n}\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative integers. It also notes that every prime number has two factors: 1 and itself.","id":2674}
    {"lang_cluster":"Rust","source_code":"\nuse std::iter::{repeat, Extend};\n\nenum AlignmentType {\n    Left,\n    Center,\n    Right,\n}\n\nfn get_column_widths(text: &str) -> Vec<usize> {\n    let mut widths = Vec::new();\n    for line in text\n        .lines()\n        .map(|s| s.trim_matches(' ').trim_end_matches('$'))\n    {\n        let lens = line.split('$').map(|s| s.chars().count());\n        for (idx, len) in lens.enumerate() {\n            if idx < widths.len() {\n                widths[idx] = std::cmp::max(widths[idx], len);\n            } else {\n                widths.push(len);\n            }\n        }\n    }\n    widths\n}\n\nfn align_columns(text: &str, alignment: AlignmentType) -> String {\n    let widths = get_column_widths(text);\n    let mut result = String::new();\n    for line in text\n        .lines()\n        .map(|s| s.trim_matches(' ').trim_end_matches('$'))\n    {\n        for (s, w) in line.split('$').zip(widths.iter()) {\n            let blank_count = w - s.chars().count();\n            let (pre, post) = match alignment {\n                AlignmentType::Left => (0, blank_count),\n                AlignmentType::Center => (blank_count \/ 2, (blank_count + 1) \/ 2),\n                AlignmentType::Right => (blank_count, 0),\n            };\n            result.extend(repeat(' ').take(pre));\n            result.push_str(s);\n            result.extend(repeat(' ').take(post));\n            result.push(' ');\n        }\n        result.push_str(\"\\n\");\n    }\n    result\n}\n\nfn main() {\n    let text = r#\"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\"#;\n\n    println!(\"{}\", align_columns(text, AlignmentType::Left));\n    println!(\"{}\", repeat('-').take(110).collect::<String>());\n    println!(\"{}\", align_columns(text, AlignmentType::Center));\n    println!(\"{}\", repeat('-').take(110).collect::<String>());\n    println!(\"{}\", align_columns(text, AlignmentType::Right));\n}\n\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":2675}
    {"lang_cluster":"Rust","source_code":"\n\nlet conn = ldap3::LdapConn::new(\"ldap:\/\/ldap.example.com\")?;\nconn.simple_bind(\"bind_dn\", \"bind_pass\")?.success()?;\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server using the ldap3 crate.","id":2676}
    {"lang_cluster":"Rust","source_code":"\nfn rot13(string: &str) -> String {\n    string.chars().map(|c| {\n        match c {\n            'a'..='m' | 'A'..='M' => ((c as u8) + 13) as char,\n            'n'..='z' | 'N'..='Z' => ((c as u8) - 13) as char,\n            _ => c\n        }\n    }).collect()\n}\n\nfn main () {\n    assert_eq!(rot13(\"abc\"), \"nop\");\n}\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":2677}
    {"lang_cluster":"Rust","source_code":"use std::cmp::Ordering;\n\n#[derive(Debug)]\nstruct Employee {\n    name: String,\n    category: String,\n}\n\nimpl Employee {\n    fn new(name: &str, category: &str) -> Self {\n        Employee {\n            name: name.into(),\n            category: category.into(),\n        }\n    }\n}\n\nimpl PartialEq for Employee {\n    fn eq(&self, other: &Self) -> bool {\n        self.name == other.name\n    }\n}\n\nimpl Eq for Employee {}\n\nimpl PartialOrd for Employee {\n    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {\n        Some(self.cmp(other))\n    }\n}\n\nimpl Ord for Employee {\n    fn cmp(&self, other: &Self) -> Ordering {\n        self.name.cmp(&other.name)\n    }\n}\n\nfn main() {\n    let mut employees = vec![\n        Employee::new(\"David\", \"Manager\"),\n        Employee::new(\"Alice\", \"Sales\"),\n        Employee::new(\"Joanna\", \"Director\"),\n        Employee::new(\"Henry\", \"Admin\"),\n        Employee::new(\"Tim\", \"Sales\"),\n        Employee::new(\"Juan\", \"Admin\"),\n    ];\n    employees.sort();\n    for e in employees {\n        println!(\"{:<6}\u00a0: {}\", e.name, e.category);\n    }\n}\n\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":2678}
    {"lang_cluster":"Rust","source_code":"\n\nfn main() {\n    for i in 0..5 {\n        for _ in 0..=i {\n            print!(\"*\");\n        }\n\n        println!();\n    }\n}\n","human_summarization":"The code demonstrates the use of nested 'for' loops to print a pattern. The outer loop controls the number of iterations of the inner loop, resulting in a pyramid pattern of asterisks. The underscore (_) is used to avoid compiler warnings for unused variables.","id":2679}
    {"lang_cluster":"Rust","source_code":"\nuse std::collections::HashMap;\nfn main() {\n    let mut olympic_medals = HashMap::new();\n    olympic_medals.insert(\"United States\", (1072, 859, 749));\n    olympic_medals.insert(\"Soviet Union\", (473, 376, 355));\n    olympic_medals.insert(\"Great Britain\", (246, 276, 284));\n    olympic_medals.insert(\"Germany\", (252, 260, 270));\n    println!(\"{:?}\", olympic_medals);\n}\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":2680}
    {"lang_cluster":"Rust","source_code":"\nextern crate rand;\n\npub use rand::{Rng, SeedableRng};\n\npub struct BsdLcg {\n    state: u32,\n}\n\nimpl Rng for BsdLcg {\n    \/\/ Because the output is in the range [0, 2147483647], this should technically be `next_u16`\n    \/\/ (the largest integer size which is fully covered, as `rand::Rng` assumes).  The `rand`\n    \/\/ crate does not provide it however.  If serious usage is required, implementing this\n    \/\/ function as a concatenation of two `next_u16`s (elsewhere defined) should work.\n    fn next_u32(&mut self) -> u32 {\n        self.state = self.state.wrapping_mul(1_103_515_245).wrapping_add(12_345);\n        self.state %= 1 << 31;\n        self.state\n    }\n}\n\nimpl SeedableRng<u32> for BsdLcg {\n    fn from_seed(seed: u32) -> Self {\n        Self { state: seed }\n    }\n    fn reseed(&mut self, seed: u32) {\n        self.state = seed;\n    }\n}\n\npub struct MsLcg {\n    state: u32,\n}\n\nimpl Rng for MsLcg {\n    \/\/ Similarly, this outputs in the range [0, 32767] and should output a `u8`.  Concatenate\n    \/\/ four `next_u8`s for serious usage.\n    fn next_u32(&mut self) -> u32 {\n        self.state = self.state.wrapping_mul(214_013).wrapping_add(2_531_011);\n        self.state %= 1 << 31;\n        self.state >> 16 \/\/ rand_n = state_n \/ 2^16\n    }\n}\n\nimpl SeedableRng<u32> for MsLcg {\n    fn from_seed(seed: u32) -> Self {\n        Self { state: seed }\n    }\n    fn reseed(&mut self, seed: u32) {\n        self.state = seed;\n    }\n}\n\nfn main() {\n    println!(\"~~~ BSD ~~~\");\n    let mut bsd = BsdLcg::from_seed(0);\n    for _ in 0..10 {\n        println!(\"{}\", bsd.next_u32());\n    }\n\n    println!(\"~~~ MS ~~~\");\n    let mut ms = MsLcg::from_seed(0);\n    for _ in 0..10 {\n        println!(\"{}\", ms.next_u32());\n    }\n\n    \/\/ Because we have implemented the `rand::Rng` trait, we can generate a variety of other types.\n    println!(\"~~~ Others ~~~\");\n    println!(\"{:?}\", ms.gen::<[u32; 5]>());\n    println!(\"{}\", ms.gen::<bool>());\n    println!(\"{}\", ms.gen_ascii_chars().take(15).collect::<String>());\n}\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":2681}
    {"lang_cluster":"Rust","source_code":"\n\nimpl<T> List<T> {\n    pub fn new() -> Self {\n        List { head: None }\n    }\n\n    pub fn push(&mut self, elem: T) {\n    let new_node = Box::new(Node {\n        elem: elem,\n        next: self.head.take(),\n    });\n    self.head = Some(new_node);\n}\n\n","human_summarization":"implement a method to insert an element into a singly-linked list after a specified element. Specifically, the code inserts element C into a list of elements A->B, after element A. The code also extends the Singly-Linked List (element) in Rust and includes the Linked List struct declarations.","id":2682}
    {"lang_cluster":"Rust","source_code":"\nfn double(a: i32) -> i32 {\n    2*a\n}\n\nfn halve(a: i32) -> i32 {\n    a\/2\n}\n\nfn is_even(a: i32) -> bool {\n    a\u00a0% 2 == 0\n}\n\nfn ethiopian_multiplication(mut x: i32, mut y: i32) -> i32 {\n    let mut sum = 0;\n\n    while x >= 1 {\n        print!(\"{} \\t {}\", x, y);\n        match is_even(x) {\n            true  => println!(\"\\t Not Kept\"),\n            false => {\n                println!(\"\\t Kept\");\n                sum += y;\n            }\n        }\n        x = halve(x);\n        y = double(y);\n    }\n    sum\n}\n\nfn main() {\n    let output = ethiopian_multiplication(17, 34);\n    println!(\"---------------------------------\");\n    println!(\"\\t {}\", output);\n}\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":2683}
    {"lang_cluster":"Rust","source_code":"\nWorks with: Rust version 1.17\n#[derive(Clone, Copy, Debug)]\nenum Operator {\n    Sub,\n    Plus,\n    Mul,\n    Div,\n}\n\n#[derive(Clone, Debug)]\nstruct Factor {\n    content: String,\n    value: i32,\n}\n\nfn apply(op: Operator, left: &[Factor], right: &[Factor]) -> Vec<Factor> {\n    let mut ret = Vec::new();\n    for l in left.iter() {\n        for r in right.iter() {\n            use Operator::*;\n            ret.push(match op {\n                Sub if l.value > r.value => Factor {\n                    content: format!(\"({} - {})\", l.content, r.content),\n                    value: l.value - r.value,\n                },\n                Plus => Factor {\n                    content: format!(\"({} + {})\", l.content, r.content),\n                    value: l.value + r.value,\n                },\n                Mul => Factor {\n                    content: format!(\"({} x {})\", l.content, r.content),\n                    value: l.value * r.value,\n                },\n                Div if l.value >= r.value && r.value > 0 && l.value % r.value == 0 => Factor {\n                    content: format!(\"({} \/ {})\", l.content, r.content),\n                    value: l.value \/ r.value,\n                },\n                _ => continue,\n            })\n        }\n    }\n    ret\n}\n\nfn calc(op: [Operator; 3], numbers: [i32; 4]) -> Vec<Factor> {\n    fn calc(op: &[Operator], numbers: &[i32], acc: &[Factor]) -> Vec<Factor> {\n        use Operator::*;\n        if op.is_empty() {\n            return Vec::from(acc)\n        }\n        let mut ret = Vec::new();\n        let mono_factor = [Factor {\n            content: numbers[0].to_string(),\n            value: numbers[0],\n        }];\n        match op[0] {\n            Mul => ret.extend_from_slice(&apply(op[0], acc, &mono_factor)),\n            Div => {\n                ret.extend_from_slice(&apply(op[0], acc, &mono_factor));\n                ret.extend_from_slice(&apply(op[0], &mono_factor, acc));\n            },\n            Sub => {\n                ret.extend_from_slice(&apply(op[0], acc, &mono_factor));\n                ret.extend_from_slice(&apply(op[0], &mono_factor, acc));\n            },\n            Plus => ret.extend_from_slice(&apply(op[0], acc, &mono_factor)),   \n        }\n        calc(&op[1..], &numbers[1..], &ret)\n    }\n    calc(&op, &numbers[1..], &[Factor { content: numbers[0].to_string(), value: numbers[0] }])\n}\n\nfn solutions(numbers: [i32; 4]) -> Vec<Factor> {\n    use std::collections::hash_set::HashSet;\n    let mut ret = Vec::new();\n    let mut hash_set = HashSet::new();\n    \n    for ops in OpIter(0) {\n        for o in orders().iter() {\n            let numbers = apply_order(numbers, o);\n            let r = calc(ops, numbers);\n            ret.extend(r.into_iter().filter(|&Factor { value, ref content }| value == 24 && hash_set.insert(content.to_owned())))\n        }\n    }\n    ret\n}\n\nfn main() {\n    let mut numbers = Vec::new();\n    if let Some(input) = std::env::args().skip(1).next() {\n        for c in input.chars() {\n            if let Ok(n) = c.to_string().parse() {\n                numbers.push(n)\n            }\n            if numbers.len() == 4 {\n                let numbers = [numbers[0], numbers[1], numbers[2], numbers[3]];\n                let solutions = solutions(numbers);\n                let len = solutions.len();\n                if len == 0 {\n                    println!(\"no solution for {}, {}, {}, {}\", numbers[0], numbers[1], numbers[2], numbers[3]);\n                    return\n                }\n                println!(\"solutions for {}, {}, {}, {}\", numbers[0], numbers[1], numbers[2], numbers[3]);\n                for s in solutions {\n                    println!(\"{}\", s.content)\n                }\n                println!(\"{} solutions found\", len);\n                return\n            }\n        }\n    } else {\n        println!(\"empty input\")\n    }\n}\n\n\nstruct OpIter (usize);\n\nimpl Iterator for OpIter {\n    type Item = [Operator; 3];\n    fn next(&mut self) -> Option<[Operator; 3]> {\n        use Operator::*;\n        const OPTIONS: [Operator; 4] = [Mul, Sub, Plus, Div];\n        if self.0 >= 1 << 6 {\n            return None\n        }\n        let f1 = OPTIONS[(self.0 & (3 << 4)) >> 4];\n        let f2 = OPTIONS[(self.0 & (3 << 2)) >> 2];\n        let f3 = OPTIONS[(self.0 & (3 << 0)) >> 0];\n        self.0 += 1;\n        Some([f1, f2, f3])\n    }\n}\n\nfn orders() -> [[usize; 4]; 24] {\n    [\n        [0, 1, 2, 3],\n        [0, 1, 3, 2],\n        [0, 2, 1, 3],\n        [0, 2, 3, 1],\n        [0, 3, 1, 2],\n        [0, 3, 2, 1],\n        [1, 0, 2, 3],\n        [1, 0, 3, 2],\n        [1, 2, 0, 3],\n        [1, 2, 3, 0],\n        [1, 3, 0, 2],\n        [1, 3, 2, 0],\n        [2, 0, 1, 3],\n        [2, 0, 3, 1],\n        [2, 1, 0, 3],\n        [2, 1, 3, 0],\n        [2, 3, 0, 1],\n        [2, 3, 1, 0],\n        [3, 0, 1, 2],\n        [3, 0, 2, 1],\n        [3, 1, 0, 2],\n        [3, 1, 2, 0],\n        [3, 2, 0, 1],\n        [3, 2, 1, 0]\n    ]\n}\n\nfn apply_order(numbers: [i32; 4], order: &[usize; 4]) -> [i32; 4] {\n    [numbers[order[0]], numbers[order[1]], numbers[order[2]], numbers[order[3]]]\n}\n\n\n","human_summarization":"The code accepts four digits, either from user input or randomly generated, and calculates arithmetic expressions following the 24 game rules. It also displays examples of the solutions it generates.","id":2684}
    {"lang_cluster":"Rust","source_code":"\nfn factorial_recursive (n: u64) -> u64 {\n    match n {\n        0 => 1,\n        _ => n * factorial_recursive(n-1)\n    }\n}\n\nfn factorial_iterative(n: u64) -> u64 {\n    (1..=n).product()\n}\n\nfn main () {\n    for i in 1..10 {\n        println!(\"{}\", factorial_recursive(i))\n    }\n    for i in 1..10 {\n        println!(\"{}\", factorial_iterative(i))\n    }\n}\n","human_summarization":"The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.","id":2685}
    {"lang_cluster":"Rust","source_code":"\nLibrary: rand\nuse std::io;\nuse rand::{Rng,thread_rng};\n\nextern crate rand;\n\nconst NUMBER_OF_DIGITS: usize = 4;\n\nstatic DIGITS: [char; 9] = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];\n\nfn generate_digits() -> Vec<char> {\n    let mut temp_digits: Vec<_> = (&DIGITS[..]).into();\n    thread_rng().shuffle(&mut temp_digits);\n    return temp_digits.iter().take(NUMBER_OF_DIGITS).map(|&a| a).collect();\n}\n\nfn parse_guess_string(guess: &str) -> Result<Vec<char>, String> {\n    let chars: Vec<char> = (&guess).chars().collect();\n\n    if !chars.iter().all(|c| DIGITS.contains(c)) {\n        return Err(\"only digits, please\".to_string());\n    }\n\n    if chars.len() != NUMBER_OF_DIGITS {\n        return Err(format!(\"you need to guess with {} digits\", NUMBER_OF_DIGITS));\n    }\n\n    let mut uniques: Vec<char> = chars.clone();\n    uniques.dedup();\n    if uniques.len() != chars.len() {\n        return Err(\"no duplicates, please\".to_string());\n    }\n\n    return Ok(chars);\n}\n\nfn calculate_score(given_digits: &[char], guessed_digits: &[char]) -> (usize, usize) {\n    let mut bulls = 0;\n    let mut cows = 0;\n    for i in 0..NUMBER_OF_DIGITS {\n        let pos: Option<usize> = guessed_digits.iter().position(|&a| -> bool {a == given_digits[i]});\n        match pos {\n            None              => (),\n            Some(p) if p == i => bulls += 1,\n            Some(_)           => cows += 1\n        }\n    }\n    return (bulls, cows);\n}\n\nfn main() {\n    let reader = io::stdin();\n\n    loop {\n        let given_digits = generate_digits();\n        println!(\"I have chosen my {} digits. Please guess what they are\", NUMBER_OF_DIGITS);\n\n        loop {\n            let guess_string: String = {\n                let mut buf = String::new();\n                reader.read_line(&mut buf).unwrap();\n                buf.trim().into()\n            };\n\n            let digits_maybe = parse_guess_string(&guess_string);\n            match digits_maybe {\n                Err(msg) => {\n                    println!(\"{}\", msg);\n                    continue;\n                },\n                Ok(guess_digits) => {\n                    match calculate_score(&given_digits, &guess_digits) {\n                        (NUMBER_OF_DIGITS, _) => {\n                            println!(\"you win!\");\n                            break;\n                        },\n                        (bulls, cows) => println!(\"bulls: {}, cows: {}\", bulls, cows)\n                    }\n                }\n            }\n        }\n    }\n}\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":2686}
    {"lang_cluster":"Rust","source_code":"\nLibrary: rand\n\nextern crate rand;\nuse rand::distributions::{Normal, IndependentSample};\n\nfn main() {\n    let mut rands = [0.0; 1000];\n    let normal = Normal::new(1.0, 0.5);\n    let mut rng = rand::thread_rng();\n    for num in rands.iter_mut() {\n        *num = normal.ind_sample(&mut rng);\n    }\n}\n\n\nextern crate rand;\nuse rand::distributions::{Normal, IndependentSample};\n\nfn main() {\n    let rands: Vec<_> = {\n        let normal = Normal::new(1.0, 0.5);\n        let mut rng = rand::thread_rng();\n        (0..1000).map(|_| normal.ind_sample(&mut rng)).collect()\n    };\n}\n\n","human_summarization":"generates a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using either a for-loop or iterators. It utilizes libraries that generate uniformly distributed random numbers.","id":2687}
    {"lang_cluster":"Rust","source_code":"\n\n\/\/ alternatively, fn dot_product(a: &Vec<u32>, b: &Vec<u32>)\n\/\/ but using slices is more general and rustic\nfn dot_product(a: &[i32], b: &[i32]) -> Option<i32> {\n    if a.len()\u00a0!= b.len() { return None }\n    Some(\n        a.iter()\n            .zip( b.iter() )\n            .fold(0, |sum, (el_a, el_b)| sum + el_a*el_b)\n    )\n}\n\n\nfn main() {\n    let v1 = vec![1, 3, -5];\n    let v2 = vec![4, -2, -1];\n\n    println!(\"{}\", dot_product(&v1, &v2).unwrap());\n}\n\n#![feature(zero_one)] \/\/ <-- unstable feature\nuse std::ops::{Add, Mul};\nuse std::num::Zero;\n\nfn dot_product<T1, T2, U, I1, I2>(lhs: I1, rhs: I2) -> Option<U>\n    where T1: Mul<T2, Output = U>,\n          U: Add<U, Output = U> + Zero,\n          I1: IntoIterator<Item = T1>,\n          I2: IntoIterator<Item = T2>,\n          I1::IntoIter: ExactSizeIterator,\n          I2::IntoIter: ExactSizeIterator,\n{\n    let (iter_lhs, iter_rhs) = (lhs.into_iter(), rhs.into_iter());\n    match (iter_lhs.len(), iter_rhs.len()) {\n        (0, _) | (_, 0) => None,\n        (a,b) if a\u00a0!= b => None,\n        (_,_) => Some( iter_lhs.zip(iter_rhs)\n           .fold(U::zero(), |sum, (a, b)| sum + (a * b)) )\n    }\n}\n\n\n\nfn main() {\n    let v1 = vec![1, 3, -5];\n    let v2 = vec![4, -2, -1];\n\n    println!(\"{}\", dot_product(&v1, &v2).unwrap());\n}\n","human_summarization":"implement a function to calculate the dot product of two vectors. The vectors can be of arbitrary length but must be the same length to perform the operation. The function multiplies corresponding terms from each vector and sums the products to produce the result. It also includes a check for equal length of vectors and can work with any two types that can be multiplied to result in a third type which can be added with itself. The function is compatible with any argument convertible to an Iterator of known length.","id":2688}
    {"lang_cluster":"Rust","source_code":"\n use std::io::{self, BufReader, Read, BufRead};\nuse std::fs::File;\n\nfn main() {\n    print_by_line(io::stdin())\n        .expect(\"Could not read from stdin\");\n\n    File::open(\"\/etc\/fstab\")\n        .and_then(print_by_line)\n        .expect(\"Could not read from file\");\n}\n\nfn print_by_line<T: Read>(reader: T) -> io::Result<()> {\n    let buffer = BufReader::new(reader);\n    for line in buffer.lines() {\n        println!(\"{}\", line?)\n    }\n    Ok(())\n}\n\n","human_summarization":"\"Continuously read words or lines from a text stream until there is no more data available.\"","id":2689}
    {"lang_cluster":"Rust","source_code":"\n\/\/ 20210210 Rust programming solution\n\nextern crate chrono;\nuse chrono::prelude::*;\n\nfn main() {\n   let utc: DateTime<Utc> = Utc::now();\n   println!(\"{}\", utc.format(\"%d\/%m\/%Y %T\"));\n}\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":2690}
    {"lang_cluster":"Rust","source_code":"\nfn sedol(input: &str) -> Option<String> {\n    let weights = vec![1, 3, 1, 7, 3, 9, 1];\n    let valid_chars = \"0123456789BCDFGHJKLMNPQRSTVWXYZ\";\n\n    if input.len() != 6 {\n        return None;\n    }\n\n    \/\/ could be done by regex if needed\n    for c in input.chars() {\n        if !valid_chars.contains(c) {\n            return None;\n        }\n    }\n\n    let mut result: u32 = input\n        .chars()\n        .map(|c| {\n            if c.is_digit(10) {\n                c as u32 - 48\n            } else {\n                c as u32 - 55\n            }\n        })\n        .zip(weights)\n        .map(|(cnum, w)| w * cnum)\n        .collect::<Vec<u32>>()\n        .iter()\n        .sum();\n\n    result = (10 - result % 10) % 10;\n\n    Some(input.to_owned() + &result.to_string())\n}\n\nfn main() {\n    let inputs = vec![\n        \"710889\", \"B0YBKJ\", \"406566\", \"B0YBLH\", \"228276\", \"B0YBKL\", \"557910\", \"B0YBKR\", \"585284\",\n        \"B0YBKT\", \"B00030\",\n    ];\n\n    for input in inputs {\n        println!(\"{} SEDOL: {:?}\", &input, sedol(&input).unwrap());\n    }\n}\n\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":2691}
    {"lang_cluster":"Rust","source_code":"\/\/ [dependencies]\n\/\/ image = \"0.23\"\n\nuse image::{GrayImage, Luma};\n\ntype Vector = [f64; 3];\n\nfn normalize(v: &mut Vector) {\n    let inv_len = 1.0\/dot_product(v, v).sqrt();\n    v[0] *= inv_len;\n    v[1] *= inv_len;\n    v[2] *= inv_len;\n}\n\nfn dot_product(v1: &Vector, v2: &Vector) -> f64 {\n    v1.iter().zip(v2.iter()).map(|(x, y)| *x * *y).sum()\n}\n\nfn draw_sphere(radius: u32, k: f64, ambient: f64, dir: &Vector) -> GrayImage {\n    let width = radius * 4;\n    let height = radius * 3;\n    let mut image = GrayImage::new(width, height);\n    let mut vec = [0.0; 3];\n    let diameter = radius * 2;\n    let r = radius as f64;\n    let xoffset = (width - diameter)\/2;\n    let yoffset = (height - diameter)\/2;\n    for i in 0..diameter {\n        let x = i as f64 - r;\n        for j in 0..diameter {\n            let y = j as f64 - r;\n            let z = r * r - x * x - y * y;\n            if z >= 0.0 {\n                vec[0] = x;\n                vec[1] = y;\n                vec[2] = z.sqrt();\n                normalize(&mut vec);\n                let mut s = dot_product(&dir, &vec);\n                if s < 0.0 {\n                    s = 0.0;\n                }\n                let mut lum = 255.0 * (s.powf(k) + ambient)\/(1.0 + ambient);\n                if lum < 0.0 {\n                    lum = 0.0;\n                } else if lum > 255.0 {\n                    lum = 255.0;\n                }\n                image.put_pixel(i + xoffset, j + yoffset, Luma([lum as u8]));\n            }\n        }\n    }\n    image\n}\n\nfn main() {\n    let mut dir = [-30.0, -30.0, 50.0];\n    normalize(&mut dir);\n    match draw_sphere(200, 1.5, 0.2, &dir).save(\"sphere.png\") {\n        Ok(()) => {}\n        Err(error) => eprintln!(\"{}\", error),\n    }\n}\n\n\n","human_summarization":"represent the functionality of drawing a sphere, either graphically or in ASCII art, with the option of static or rotational projection, depending on the language capabilities.","id":2692}
    {"lang_cluster":"Rust","source_code":"\nfn nth(num: isize) -> String {\n    format!(\"{}{}\", num, match (num % 10, num % 100) {\n        (1, 11) | (2, 12) | (3, 13) => \"th\",\n        (1, _) => \"st\",\n        (2, _) => \"nd\",\n        (3, _) => \"rd\",\n        _ => \"th\",\n    })\n}\n\nfn main() {\n    let ranges = [(0, 26), (250, 266), (1000, 1026)];\n    for &(s, e) in &ranges {\n        println!(\"[{}, {})\u00a0:\", s, e);\n        for i in s..e {\n            print!(\"{}, \", nth(i));\n        }\n        println!();\n    }\n}\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":2693}
    {"lang_cluster":"Rust","source_code":"\n\nfn strip_characters(original : &str, to_strip : &str) -> String {\n    let mut result = String::new();\n    for c in original.chars() {\n        if !to_strip.contains(c) {\n           result.push(c);\n       }\n    }\n    result\n}\n\n\nfn strip_characters(original : &str, to_strip : &str) -> String {\n    original.chars().filter(|&c| !to_strip.contains(c)).collect()\n}\n\n\nfn main() {\n    println!(\"{}\", strip_characters(\"She was a soul stripper. She took my heart!\", \"aei\"));\n}\n\n","human_summarization":"The code defines a function that removes a specified set of characters from a given string. The function takes two inputs: the original string and a string of characters to be removed. The function then returns the original string with all instances of the specified characters removed.","id":2694}
    {"lang_cluster":"Rust","source_code":"\nuse std::io;\nuse std::io::BufRead;\n\nfn parse_entry(l: &str) -> (i32, String) {\n    let params: Vec<&str> = l.split(' ').collect();\n\n    let divisor = params[0].parse::<i32>().unwrap();\n    let word = params[1].to_string();\n    (divisor, word)\n}\n\nfn main() {\n    let stdin = io::stdin();\n    let mut lines = stdin.lock().lines().map(|l| l.unwrap());\n\n    let l = lines.next().unwrap();\n    let high = l.parse::<i32>().unwrap();\n\n    let mut entries = Vec::new();\n    for l in lines {\n        if &l == \"\" { break }\n        let entry = parse_entry(&l);\n        entries.push(entry);\n    }\n\n    for i in 1..(high + 1) {\n        let mut line = String::new();\n        for &(divisor, ref word) in &entries {\n            if i % divisor == 0 {\n                line = line + &word;\n            }\n        }\n        if line == \"\" {\n            println!(\"{}\", i);\n        } else {\n            println!(\"{}\", line);\n        }\n    }\n}\n\n\nuse std::collections::BTreeMap;\nuse std::fmt::{self, Write};\nuse std::io::{self, Stdin};\n\n#[derive(Debug, PartialEq)]\npub struct FizzBuzz {\n    end: usize,\n    factors: Factors,\n}\n\nimpl FizzBuzz {\n    fn from_reader(rdr: &Stdin) -> Result<FizzBuzz, Box<dyn std::error::Error>> {\n        let mut line = String::new();\n        rdr.read_line(&mut line)?;\n\n        let end = line.trim().parse::<usize>()?;\n\n        let mut factors = Factors::new();\n\n        loop {\n            let mut line = String::new();\n            rdr.read_line(&mut line)?;\n\n            if line.trim().is_empty() { break; }\n\n            let mut split = line.trim().splitn(2, ' ');\n\n            let factor = match split.next() {\n                Some(f) => f.parse::<usize>()?,\n                None => break,\n            };\n\n            let phrase = match split.next() {\n                Some(p) => p,\n                None => break,\n            };\n\n            factors.insert(factor, phrase.to_string());\n        }\n\n        Ok(FizzBuzz { end, factors })\n    }\n}\n\nimpl fmt::Display for FizzBuzz {\n    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n        for n in 1..=self.end {\n            let mut had_factor = false;\n\n            \/\/ check for factors\n            for (factor, phrase) in self.factors.iter() {\n                if n % factor == 0 {\n                    f.write_str(&phrase)?;\n                    had_factor = true;\n                }\n            }\n\n            if !had_factor {\n                f.write_str(n.to_string().as_str())?;\n            }\n            f.write_char('\\n')?;\n        }\n        Ok(())\n    }\n}\n\ntype Factors = BTreeMap<usize, String>;\n\nfn main() -> Result<(), Box<dyn std::error::Error>> {\n    let input = io::stdin();\n\n    let fizz_buzz = FizzBuzz::from_reader(&input)?;\n\n    println!(\"{}\", fizz_buzz);\n\n    Ok(())\n}\n\n#[cfg(test)]\nmod tests {\n    use super::*;\n\n    #[test]\n    fn fizz_buzz_prints_expected_format() {\n        let expected_factors = {\n            let mut map = Factors::new();\n            map.insert(3, \"Fizz\".to_string());\n            map.insert(5, \"Buzz\".to_string());\n            map.insert(7, \"Baxx\".to_string());\n            map\n        };\n\n        let expected_end = 20;\n\n        let fizz_buzz = FizzBuzz {\n            end: expected_end,\n            factors: expected_factors,\n        };\n\n        let expected = r#\"1\n2\nFizz\n4\nBuzz\nFizz\nBaxx\n8\nFizz\nBuzz\n11\nFizz\n13\nBaxx\nFizzBuzz\n16\n17\nFizz\n19\nBuzz\n\"#;\n        let printed = format!(\"{}\", fizz_buzz);\n\n        assert_eq!(expected, &printed);\n    }\n}\n\n","human_summarization":"The code takes a maximum number and three factors with their corresponding words as input from the user. It prints numbers from 1 to the maximum number, replacing multiples of the factors with their corresponding words. If a number is a multiple of more than one factor, it prints all corresponding words in the order of the factors. The FizzBuzz state is stored in a struct for a more generalized solution.","id":2695}
    {"lang_cluster":"Rust","source_code":"\nlet mut s = \"World\".to_string();\ns.insert_str(0, \"Hello \");\nprintln!(\"{}\", s);\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":2696}
    {"lang_cluster":"Rust","source_code":"\nuse ggez::{\n    conf::{WindowMode, WindowSetup},\n    error::GameResult,\n    event,\n    graphics::{clear, draw, present, Color, MeshBuilder},\n    nalgebra::Point2,\n    Context,\n};\nuse std::time::Duration;\n\n\/\/ L-System to create the sequence needed for a Dragon Curve.\n\/\/ This function creates the next generation given the current one\n\/\/ L-System from https:\/\/www.cs.unm.edu\/~joel\/PaperFoldingFractal\/L-system-rules.html\n\/\/\nfn l_system_next_generation(current_generation: &str) -> String {\n    let f_rule = \"f-h\";\n    let h_rule = \"f+h\";\n    let mut next_gen = String::new();\n    for char in current_generation.chars() {\n        match char {\n            'f' => next_gen.push_str(f_rule),\n            'h' => next_gen.push_str(h_rule),\n            '-' | '+' => next_gen.push(char),\n            _ => panic!(\"Unknown char {}\", char),\n        }\n    }\n    next_gen\n}\n\n\/\/ The rest of the code is for drawing the output and is specific to using the\n\/\/ ggez 2d game library: https:\/\/ggez.rs\/\n\nconst WINDOW_WIDTH: f32 = 700.0;\nconst WINDOW_HEIGHT: f32 = 700.0;\nconst START_X: f32 = WINDOW_WIDTH \/ 6.0;\nconst START_Y: f32 = WINDOW_HEIGHT \/ 6.0;\nconst MAX_DEPTH: i32 = 15;\nconst LINE_LENGTH: f32 = 20.0;\n\nstruct MainState {\n    start_gen: String,\n    next_gen: String,\n    line_length: f32,\n    max_depth: i32,\n    current_depth: i32,\n}\n\nimpl MainState {\n    fn new() -> GameResult<MainState> {\n        let start_gen = \"f\";\n        let next_gen = String::new();\n        let line_length = LINE_LENGTH;\n        let max_depth = MAX_DEPTH;\n        let current_depth = 0;\n        Ok(MainState {\n            start_gen: start_gen.to_string(),\n            next_gen,\n            line_length,\n            max_depth,\n            current_depth,\n        })\n    }\n}\n\nimpl event::EventHandler for MainState {\n    \/\/ In each repetition of the event loop a new generation of the L-System\n    \/\/ is generated and drawn, until the maximum depth is reached.\n    \/\/ Each time the line length is reduced so that the overall dragon curve\n    \/\/ can be seen in the window as it spirals and gets bigger.\n    \/\/ The update sleeps for 0.5 seconds just so that its pogression can be watched.\n    \/\/\n    fn update(&mut self, _ctx: &mut Context) -> GameResult {\n        if self.current_depth < self.max_depth {\n            self.next_gen = l_system_next_generation(&self.start_gen);\n            self.start_gen = self.next_gen.clone();\n            self.line_length -= (self.line_length \/ self.max_depth as f32) * 1.9;\n            self.current_depth += 1;\n        }\n        ggez::timer::sleep(Duration::from_millis(500));\n        Ok(())\n    }\n\n    fn draw(&mut self, ctx: &mut Context) -> GameResult {\n        let grey = Color::from_rgb(77, 77, 77);\n        let blue = Color::from_rgb(51, 153, 255);\n        let initial_point_blue = Point2::new(START_X, START_Y);\n        clear(ctx, grey);\n        draw_lines(\n            &self.next_gen,\n            ctx,\n            self.line_length,\n            blue,\n            initial_point_blue,\n        )?;\n        present(ctx)?;\n        Ok(())\n    }\n}\n\nfn next_point(current_point: Point2<f32>, heading: f32, line_length: f32) -> Point2<f32> {\n    let next_point = (\n        (current_point.x + (line_length * heading.to_radians().cos().trunc() as f32)),\n        (current_point.y + (line_length * heading.to_radians().sin().trunc() as f32)),\n    );\n    Point2::new(next_point.0, next_point.1)\n}\n\nfn draw_lines(\n    instructions: &str,\n    ctx: &mut Context,\n    line_length: f32,\n    colour: Color,\n    initial_point: Point2<f32>,\n) -> GameResult {\n    let line_width = 2.0;\n    let mut heading = 0.0;\n    let turn_angle = 90.0;\n    let mut start_point = initial_point;\n    let mut line_builder = MeshBuilder::new();\n    for char in instructions.chars() {\n        let end_point = next_point(start_point, heading, line_length);\n        match char {\n            'f' | 'h' => {\n                line_builder.line(&[start_point, end_point], line_width, colour)?;\n                start_point = end_point;\n            }\n            '+' => heading += turn_angle,\n            '-' => heading -= turn_angle,\n            _ => panic!(\"Unknown char {}\", char),\n        }\n    }\n    let lines = line_builder.build(ctx)?;\n    draw(ctx, &lines, (initial_point,))?;\n    Ok(())\n}\n\nfn main() -> GameResult {\n    let cb = ggez::ContextBuilder::new(\"dragon curve\", \"huw\")\n        .window_setup(WindowSetup::default().title(\"Dragon curve\"))\n        .window_mode(WindowMode::default().dimensions(WINDOW_WIDTH, WINDOW_HEIGHT));\n    let (ctx, event_loop) = &mut cb.build()?;\n    let state = &mut MainState::new()?;\n    event::run(ctx, event_loop, state)\n}\n\nFile:Dragon curve rust.gif\n","human_summarization":"generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.","id":2697}
    {"lang_cluster":"Rust","source_code":"\nLibrary: rand\nextern crate rand;\n\nfn main() {\n    println!(\"Type in an integer between 1 and 10 and press enter.\");\n\n    let n = rand::random::<u32>() % 10 + 1;\n    loop {\n        let mut line = String::new();\n        std::io::stdin().read_line(&mut line).unwrap();\n        let option: Result<u32,_> = line.trim().parse();\n        match option {\n            Ok(guess) => {\n                if guess < 1 || guess > 10 {\n                    println!(\"Guess is out of bounds; try again.\");\n                } else if guess == n {\n                    println!(\"Well guessed!\");\n                    break;\n                } else {\n                    println!(\"Wrong! Try again.\");\n                }\n            },\n            Err(_) => println!(\"Invalid input; try again.\")\n        }\n    }\n}\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":2698}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    \/\/ An iterator over the lowercase alpha's\n    let ascii_iter = (0..26)\n        .map(|x| (x + b'a') as char);\n \n    println!(\"{:?}\", ascii_iter.collect::<Vec<char>>());\n}\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":2699}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    for i in 0..8 {\n        println!(\"{:b}\", i)\n    }\n}\n\n0\n1\n10\n11\n100\n101\n110\n111\n","human_summarization":"The code takes a non-negative integer as input and converts it into a binary sequence. It uses built-in radix functions or a user-defined function to perform the conversion. The output is a sequence of binary digits followed by a newline, with no additional whitespace, radix, sign markers, or leading zeros.","id":2700}
    {"lang_cluster":"Rust","source_code":"\nLibrary: piston_window\nLibrary: image\n\nOutput Image: RustOut\n\nextern crate piston_window;\nextern crate image;\n\nuse piston_window::*;\n\nfn main() {\n    let (width, height) = (320, 240);\n    \n    let mut window: PistonWindow =\n        WindowSettings::new(\"Red Pixel\", [width, height])\n        .exit_on_esc(true).build().unwrap();\n\n    \/\/ Since we cant manipulate pixels directly, we need to manipulate the pixels on a canvas.\n    \/\/ Only issue is that sub-pixels exist (which is probably why the red pixel looks like a smear on the output image)\n    let mut canvas = image::ImageBuffer::new(width, height);\n    canvas.put_pixel(100, 100, image::Rgba([0xff, 0, 0, 0xff]));\n\n    \/\/ Transform into a texture so piston can use it.\n    let texture: G2dTexture = Texture::from_image(\n        &mut window.factory,\n        &canvas,\n        &TextureSettings::new()\n    ).unwrap();\n\n    \/\/ The window event loop.\n    while let Some(event) = window.next() {\n        window.draw_2d(&event, |context, graphics| {\n            clear([1.0; 4], graphics);\n            image(&texture,\n            context.transform,\n            graphics);\n        });\n    }\n}\n\n","human_summarization":"create a 320x240 window and draw a red pixel at position (100, 100).","id":2701}
    {"lang_cluster":"Rust","source_code":"\nuse std::fs::File;\nuse std::io::BufRead;\nuse std::io::BufReader;\nuse std::iter::FromIterator;\nuse std::path::Path;\n\nfn main() {\n    let path = String::from(\"file.conf\");\n    let cfg = config_from_file(path);\n    println!(\"{:?}\", cfg);\n}\n\nfn config_from_file(path: String) -> Config {\n    let path = Path::new(&path);\n    let file = File::open(path).expect(\"File not found or cannot be opened\");\n    let content = BufReader::new(&file);\n    let mut cfg = Config::new();\n\n    for line in content.lines() {\n        let line = line.expect(\"Could not read the line\");\n        \/\/ Remove whitespaces at the beginning and end\n        let line = line.trim();\n\n        \/\/ Ignore comments and empty lines\n        if line.starts_with(\"#\") || line.starts_with(\";\") || line.is_empty() {\n            continue;\n        }\n\n        \/\/ Split line into parameter name and rest tokens\n        let tokens = Vec::from_iter(line.split_whitespace()); \n        let name = tokens.first().unwrap();\n        let tokens = tokens.get(1..).unwrap();\n\n        \/\/ Remove the equal signs\n        let tokens = tokens.iter().filter(|t| !t.starts_with(\"=\"));\n        \/\/ Remove comment after the parameters\n        let tokens = tokens.take_while(|t| !t.starts_with(\"#\") && !t.starts_with(\";\"));\n        \n        \/\/ Concat back the parameters into one string to split for separated parameters\n        let mut parameters = String::new();\n        tokens.for_each(|t| { parameters.push_str(t); parameters.push(' '); });\n        \/\/ Splits the parameters and trims\n        let parameters = parameters.split(',').map(|s| s.trim());\n        \/\/ Converts them from Vec<&str> into Vec<String>\n        let parameters: Vec<String> = parameters.map(|s| s.to_string()).collect();\n        \n        \/\/ Setting the config parameters\n        match name.to_lowercase().as_str() {\n            \"fullname\" => cfg.full_name = parameters.get(0).cloned(),\n            \"favouritefruit\" => cfg.favourite_fruit = parameters.get(0).cloned(),\n            \"needspeeling\" => cfg.needs_peeling = true,\n            \"seedsremoved\" => cfg.seeds_removed = true,\n            \"otherfamily\" => cfg.other_family = Some(parameters),\n            _ => (),\n        }\n    }\n\n    cfg\n}\n\n#[derive(Clone, Debug)]\nstruct Config {\n    full_name: Option<String>,\n    favourite_fruit: Option<String>,\n    needs_peeling: bool,\n    seeds_removed: bool,\n    other_family: Option<Vec<String>>,\n}\n\nimpl Config {\n    fn new() -> Config {\n        Config {\n            full_name: None,\n            favourite_fruit: None,\n            needs_peeling: false,\n            seeds_removed: false,\n            other_family: None,\n        }\n    }\n}\n\n\n","human_summarization":"read a configuration file and set variables based on the contents. It ignores lines starting with a hash or semicolon and blank lines. It sets variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' based on the file entries. It also stores multiple parameters from the 'otherfamily' entry into an array.","id":2702}
    {"lang_cluster":"Rust","source_code":"\nstruct Point {\n    lat: f64,\n    lon: f64,\n}\n\nfn haversine(origin: Point, destination: Point) -> f64 {\n    const R: f64 = 6372.8;\n\n    let lat1 = origin.lat.to_radians();\n    let lat2 = destination.lat.to_radians();\n    let d_lat = lat2 - lat1;\n    let d_lon = (destination.lon - origin.lon).to_radians();\n\n    let a = (d_lat \/ 2.0).sin().powi(2) + (d_lon \/ 2.0).sin().powi(2) * lat1.cos() * lat2.cos();\n    let c = 2.0 * a.sqrt().asin();\n    R * c\n}\n\n#[cfg(test)]\nmod test {\n    use super::{Point, haversine};\n\n    #[test]\n    fn test_haversine() {\n        let origin: Point = Point {\n            lat: 36.12,\n            lon: -86.67\n        };\n        let destination: Point = Point {\n            lat: 33.94,\n            lon: -118.4\n        };\n        let d: f64 = haversine(origin, destination);\n        println!(\"Distance: {} km ({} mi)\", d, d \/ 1.609344);\n        assert_eq!(d, 2887.2599506071106);\n    }\n\n}\nOutput Distance: 2887.2599506071106 km (1794.060157807846 mi)\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":2703}
    {"lang_cluster":"Rust","source_code":"\n\n[dependencies]\nhyper = \"0.6\"\n\n\/\/cargo-deps: hyper=\"0.6\"\n\/\/ The above line can be used with cargo-script which makes cargo's dependency handling more convenient for small programs\nextern crate hyper;\n\nuse std::io::Read;\nuse hyper::client::Client;\n\nfn main() {\n    let client = Client::new();\n    let mut resp = client.get(\"http:\/\/rosettacode.org\").send().unwrap();\n    let mut body = String::new();\n    resp.read_to_string(&mut body).unwrap();\n    println!(\"{}\", body);\n}\n","human_summarization":"The code accesses a specified URL's content and prints it to the console using HTTP requests. Note that handling HTTPS requests is not included in this code.","id":2704}
    {"lang_cluster":"Rust","source_code":"\nextern crate luhn_test_of_credit_card_numbers;\n\nuse luhn_test_of_credit_card_numbers::luhn_test;\n\nfn validate_isin(isin: &str) -> bool {\n    if !isin.chars().all(|x| x.is_alphanumeric()) || isin.len()\u00a0!= 12 {\n        return false;\n    }\n    if !isin[..2].chars().all(|x| x.is_alphabetic())\n        || !isin[2..12].chars().all(|x| x.is_alphanumeric())\n        || !isin.chars().last().unwrap().is_numeric()\n    {\n        return false;\n    }\n\n    let bytes = isin.as_bytes();\n\n    let s2 = bytes\n        .iter()\n        .flat_map(|&c| {\n            if c.is_ascii_digit() {\n                vec![c]\n            } else {\n                (c + 10 - ('A' as u8)).to_string().into_bytes()\n            }\n        })\n        .collect::<Vec<u8>>();\n\n    let string = std::str::from_utf8(&s2).unwrap();\n    let number = string.parse::<u64>().unwrap();\n\n    return luhn_test(number as u64);\n}\n\n#[cfg(test)]\nmod tests {\n    use super::validate_isin;\n\n    #[test]\n    fn test_validate_isin() {\n        assert_eq!(validate_isin(\"US0378331005\"), true);\n        assert_eq!(validate_isin(\"US0373831005\"), false);\n        assert_eq!(validate_isin(\"U50378331005\"), false);\n        assert_eq!(validate_isin(\"US03378331005\"), false);\n        assert_eq!(validate_isin(\"AU0000XVGZA3\"), true);\n        assert_eq!(validate_isin(\"AU0000VXGZA3\"), true);\n        assert_eq!(validate_isin(\"FR0000988040\"), true);\n    }\n}\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":2705}
    {"lang_cluster":"Rust","source_code":"\nconst N: usize = 41;\nconst K: usize = 3;\nconst M: usize = 3;\nconst POSITION: usize = 5;\n\nfn main() {\n    let mut prisoners: Vec<usize> = Vec::new();\n    let mut executed: Vec<usize> = Vec::new();\n    for pos in 0..N {\n        prisoners.push(pos);\n    }\n\n    let mut to_kill: usize = 0;\n    let mut len: usize = prisoners.len();\n\n    while len > M {\n        to_kill = (to_kill + K - 1) % len;\n        executed.push(prisoners.remove(to_kill));\n        len -= 1;\n    }\n\n    println!(\"JOSEPHUS n={}, k={}, m={}\", N, K, M);\n    println!(\"Executed: {:?}\", executed);\n    println!(\"Executed position number {}: {}\", POSITION, executed[POSITION - 1]);\n    println!(\"Survivors: {:?}\", prisoners);\n}\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":2706}
    {"lang_cluster":"Rust","source_code":"\nstd::iter::repeat(\"ha\").take(5).collect::<String>(); \/\/ ==> \"hahahahaha\"\n\n\"ha\".repeat(5); \/\/ ==> \"hahahahaha\"\n","human_summarization":"Code summarization: The code repeats a given string or a single character a specified number of times. For example, it can turn \"ha\" into \"hahahahaha\" when repeated 5 times, or \"*\" into \"*****\" when repeated 5 times.","id":2707}
    {"lang_cluster":"Rust","source_code":"\n\nuse regex::Regex;\n\nfn main() {\n    let s = \"I am a string\";\n\n    if Regex::new(\"string$\").unwrap().is_match(s) {\n        println!(\"Ends with string.\");\n    }\n\n    println!(\"{}\", Regex::new(\" a \").unwrap().replace(s, \" another \"));\n}\n","human_summarization":"The code matches a string against a regular expression and substitutes part of the string using the same regular expression. It also checks for a valid regex using Regex::new, returning a Result<Regex, Error>.","id":2708}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::env;\n\nfn main() {\n    let args: Vec<_> = env::args().collect();\n    let a = args[1].parse::<i32>().unwrap();\n    let b = args[2].parse::<i32>().unwrap();\n\n    println!(\"sum:              {}\", a + b);\n    println!(\"difference:       {}\", a - b);\n    println!(\"product:          {}\", a * b);\n    println!(\"integer quotient: {}\", a \/ b); \/\/ truncates towards zero\n    println!(\"remainder:        {}\", a\u00a0% b); \/\/ same sign as first operand\n}\n","human_summarization":"take two integers as input from the user and calculate their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding method for the quotient and the sign of the remainder. It does not include error handling. Additionally, it provides an example of the 'divmod' operator. However, this code cannot be executed in the Rust playpen due to its lack of console input support.","id":2709}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    println!(\"{}\",\"the three truths\".matches(\"th\").count());\n    println!(\"{}\",\"ababababab\".matches(\"abab\").count());\n}\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":2710}
    {"lang_cluster":"Rust","source_code":"fn move_(n: i32, from: i32, to: i32, via: i32) {\n    if n > 0 {\n        move_(n - 1, from, via, to);\n        println!(\"Move disk from pole {} to pole {}\", from, to);\n        move_(n - 1, via, to, from);\n    }\n}\n\nfn main() {\n    move_(4, 1,2,3);\n}\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":2711}
    {"lang_cluster":"Rust","source_code":"\nfn fact(n:u32) -> u64 {\n  let mut f:u64 = n as u64;\n  for i in 2..n {\n    f *= i as u64;\n  }\n  return f;\n}\n\nfn choose(n: u32, k: u32)  -> u64 {\n   let mut num:u64 = n as u64;\n   for i in 1..k {\n     num *= (n-i) as u64;\n   }\n   return num \/ fact(k);\n}\n\nfn main() {\n  println!(\"{}\", choose(5,3));\n}\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is capable of outputting the binomial coefficient of 5 choose 3, which is 10. The code also includes tasks related to combinations and permutations, both with and without replacement. An alternative version of the code uses a functional style.","id":2712}
    {"lang_cluster":"Rust","source_code":"\nfn shell_sort<T: Ord + Copy>(v: &mut [T]) {\n    let mut gap = v.len() \/ 2;\n    let len = v.len();\n    while gap > 0 {\n        for i in gap..len {\n            let temp = v[i];\n            let mut j = i;\n            while j >= gap && v[j - gap] > temp {\n                v[j] = v[j - gap];\n                j -= gap;\n            }\n            v[j] = temp;\n        }\n        gap \/= 2;\n    }\n}\n\nfn main() {\n    let mut numbers = [4i32, 65, 2, -31, 0, 99, 2, 83, 782, 1];\n    println!(\"Before: {:?}\", numbers);\n    shell_sort(&mut numbers);\n    println!(\"After: {:?}\", numbers);\n}\n\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":2713}
    {"lang_cluster":"Rust","source_code":"\n#[cfg(feature = \"gtk\")]\nmod graphical {\n    extern crate gtk;\n\n    use self::gtk::traits::*;\n    use self::gtk::{Inhibit, Window, WindowType};\n    use std::ops::Not;\n    use std::sync::{Arc, RwLock};\n\n    pub fn create_window() {\n        gtk::init().expect(\"Failed to initialize GTK\");\n\n        let window = Window::new(WindowType::Toplevel);\n        window.connect_delete_event(|_, _| {\n            gtk::main_quit();\n            Inhibit(false)\n        });\n        let button = gtk::Button::new_with_label(\"Hello World! \");\n        window.add(&button);\n\n        let lock = Arc::new(RwLock::new(false));\n\n        let lock_button = lock.clone();\n        button.connect_clicked(move |_| {\n            let mut reverse = lock_button.write().unwrap();\n            *reverse = reverse.not();\n        });\n\n        let lock_thread = lock.clone();\n        gtk::timeout_add(100, move || {\n            let reverse = lock_thread.read().unwrap();\n            let mut text = button.get_label().unwrap();\n            let len = &text.len();\n\n            if *reverse {\n                let begin = &text.split_off(1);\n                text.insert_str(0, begin);\n            } else {\n                let end = &text.split_off(len - 1);\n                text.insert_str(0, end);\n            }\n\n            button.set_label(&text);\n\n            gtk::Continue(true)\n        });\n\n        window.show_all();\n        gtk::main();\n    }\n}\n\n\n#[cfg(feature = \"gtk\")]\nfn main() {\n    graphical::create_window();\n}\n\n#[cfg(not(feature = \"gtk\"))]\nfn main() {}\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":2714}
    {"lang_cluster":"Rust","source_code":"\n\nlet mut x = 0;\n\nloop {\n    x += 1;\n    println!(\"{}\", x);\n\n    if x\u00a0% 6 == 0 { break; }\n}\n","human_summarization":"The code initializes a value to 0 and enters a loop, which continues until the value modulo 6 is not 0. In each iteration, the value is incremented by 1 and then printed. The loop is guaranteed to run at least once. This is implemented in Rust using the 'loop' keyword with a termination condition.","id":2715}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    let s = \"\u6587\u5b57\u5316\u3051\";  \/\/ UTF-8\n    println!(\"Byte Length: {}\", s.len());\n}\nfn main() {\n    let s = \"\u6587\u5b57\u5316\u3051\";  \/\/ UTF-8\n    println!(\"Character length: {}\", s.chars().count());\n}\n","human_summarization":"calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.","id":2716}
    {"lang_cluster":"Rust","source_code":"\n\nextern crate rand;\n\nuse rand::{OsRng, Rng};\n\nfn main() {\n    \/\/ because `OsRng` opens files, it may fail\n    let mut rng = match OsRng::new() {\n        Ok(v) => v,\n        Err(e) => panic!(\"Failed to obtain OS RNG: {}\", e)\n    };\n\n    let rand_num: u32 = rng.gen();\n    println!(\"{}\", rand_num);\n}\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm. It utilizes the 'rand' crate, previously part of the Rust standard library, which supports various platforms including Unix, Windows, BSD, and iOS. Other methods like RDRAND can be found in other crates.","id":2717}
    {"lang_cluster":"Rust","source_code":"\n\nfn main() {\n    let s = String::from(\"\u017elu\u0165ou\u010dk\u00fd k\u016f\u0148\");\n\n    let mut modified = s.clone();\n    modified.remove(0);\n    println!(\"{}\", modified);\n\n    let mut modified = s.clone();\n    modified.pop();\n    println!(\"{}\", modified);\n\n    let mut modified = s;\n    modified.remove(0);\n    modified.pop();\n    println!(\"{}\", modified);\n}\n\n\nfn main() {\n    let s = \"\u017elu\u0165ou\u010dk\u00fd k\u016f\u0148\";\n\n    println!(\n        \"{}\",\n        s.char_indices()\n            .nth(1)\n            .map(|(i, _)| &s[i..])\n            .unwrap_or_default()\n    );\n\n    println!(\n        \"{}\",\n        s.char_indices()\n            .nth_back(0)\n            .map(|(i, _)| &s[..i])\n            .unwrap_or_default()\n    );\n\n    println!(\n        \"{}\",\n        s.char_indices()\n            .nth(1)\n            .and_then(|(i, _)| s.char_indices().nth_back(0).map(|(j, _)| i..j))\n            .map(|range| &s[range])\n            .unwrap_or_default()\n    );\n}\n\n","human_summarization":"demonstrate how to remove the first and\/or last characters from a string, supporting any valid Unicode code point in UTF-8 or UTF-16 encoding. The program handles logical characters, not code units. It provides two methods: modifying the owned string representation or cutting a string slice without assuming the string length. Handling of other encodings like 8-bit ASCII or EUC-JP is not required.","id":2718}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::net::TcpListener;\n\nfn create_app_lock(port: u16) -> TcpListener {\n    match TcpListener::bind((\"0.0.0.0\", port)) {\n        Ok(socket) => {\n            socket\n        },\n        Err(_) => {\n            panic!(\"Couldn't lock port {}: another instance already running?\", port);\n        }\n    }\n}\n\nfn remove_app_lock(socket: TcpListener) {\n    drop(socket);\n}\n\nfn main() {\n    let lock_socket = create_app_lock(12345);\n    \/\/ ...\n    \/\/ your code here\n    \/\/ ...\n    remove_app_lock(lock_socket);\n}\n\n","human_summarization":"\"Check if a single instance of an application is running using TCP socket, display a message and exit if another instance is found.\"","id":2719}
    {"lang_cluster":"Rust","source_code":"type Sudoku = [u8; 81];\n\nfn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool {\n    (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && {\n        let (start_x, start_y) = ((x \/ 3) * 3, (y \/ 3) * 3);\n        (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val))\n    }\n}\n\nfn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool {\n    (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| {\n        let (x, y) = (pos % 9, pos \/ 9);\n        for n in 1..10 {\n            if is_valid(n, x, y, sudoku_ar) {\n                sudoku_ar[pos] = n;\n                if place_number(pos + 1, sudoku_ar) {\n                    return true;\n                }\n                sudoku_ar[pos] = 0;\n            }\n        }\n        false\n    })\n}\n\nfn pretty_print(sudoku_ar: Sudoku) {\n    let line_sep = \"------+-------+------\";\n    println!(\"{}\", line_sep);\n    for (i, e) in sudoku_ar.iter().enumerate() {\n        print!(\"{} \", e);\n        if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 {\n            print!(\"| \");\n        }\n        if (i + 1) % 9 == 0 {\n            println!(\" \");\n        }\n        if (i + 1) % 27 == 0 {\n            println!(\"{}\", line_sep);\n        }\n    }\n}\n\nfn solve(sudoku_ar: &mut Sudoku) -> bool {\n    place_number(0, sudoku_ar)\n}\n\nfn main() {\n    let mut sudoku_ar: Sudoku = [\n        8, 5, 0, 0, 0, 2, 4, 0, 0,\n        7, 2, 0, 0, 0, 0, 0, 0, 9,\n        0, 0, 4, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 1, 0, 7, 0, 0, 2,\n        3, 0, 5, 0, 0, 0, 9, 0, 0,\n        0, 4, 0, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 8, 0, 0, 7, 0,\n        0, 1, 7, 0, 0, 0, 0, 0, 0,\n        0, 0, 0, 0, 3, 6, 0, 4, 0\n    ];\n    if solve(&mut sudoku_ar) {\n        pretty_print(sudoku_ar);\n    } else {\n        println!(\"Unsolvable\");\n    }\n}\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":2720}
    {"lang_cluster":"Rust","source_code":"\nLibrary: rand\nuse rand::Rng;\n\nextern crate rand;\n\nfn knuth_shuffle<T>(v: &mut [T]) {\n    let mut rng = rand::thread_rng();\n    let l = v.len();\n\n    for n in 0..l {\n        let i = rng.gen_range(0, l - n);\n        v.swap(i, l - n - 1);\n    }\n}\n\nfn main() {\n    let mut v: Vec<_> = (0..10).collect();\n\n    println!(\"before: {:?}\", v);\n    knuth_shuffle(&mut v);\n    println!(\"after:  {:?}\", v);\n}\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":2721}
    {"lang_cluster":"Rust","source_code":"\nuse std::env::args;\nuse time::{Date, Duration};\n\nfn main() {\n    let year = args().nth(1).unwrap().parse::<i32>().unwrap();\n    (1..=12)\n        .map(|month| Date::try_from_ymd(year + month \/ 12, ((month % 12) + 1) as u8, 1))\n        .filter_map(|date| date.ok())\n        .for_each(|date| {\n            let days_back =\n                Duration::days(((date.weekday().number_from_sunday() as i64) % 7) + 1);\n            println!(\"{}\", date - days_back);\n        });\n}\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":2722}
    {"lang_cluster":"Rust","source_code":"\nfn main () {\n    print!(\"Goodbye, World!\");\n}\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":2723}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::io::{self, Write};\nuse std::fmt::Display;\nuse std::{env, process};\n\nfn main() {\n    let shift: u8 = env::args().nth(1)\n        .unwrap_or_else(|| exit_err(\"No shift provided\", 2))\n        .parse()\n        .unwrap_or_else(|e| exit_err(e, 3));\n\n    let plain = get_input()\n        .unwrap_or_else(|e| exit_err(&e, e.raw_os_error().unwrap_or(-1)));\n\n    let cipher = plain.chars()\n        .map(|c| {\n            let case = if c.is_uppercase() {'A'} else {'a'} as u8;\n            if c.is_alphabetic() { (((c as u8 - case + shift)\u00a0% 26) + case) as char } else { c }\n        }).collect::<String>();\n\n    println!(\"Cipher text: {}\", cipher.trim());\n}\n\n\nfn get_input() -> io::Result<String> {\n    print!(\"Plain text:  \");\n    try!(io::stdout().flush());\n\n    let mut buf = String::new();\n    try!(io::stdin().read_line(&mut buf));\n    Ok(buf)\n}\n\nfn exit_err<T: Display>(msg: T, code: i32) ->\u00a0! {\n    let _ = writeln!(&mut io::stderr(), \"ERROR: {}\", msg);\n    process::exit(code);\n}\n","human_summarization":"Implement a Caesar cipher for both encoding and decoding operations. The key for the cipher is an integer between 1 and 25. The cipher works by rotating the letters of the alphabet either left or right. The encoding process replaces each letter with the 1st to 25th next letter in the alphabet, wrapping from Z back to A. The cipher provides minimal security as it can be easily cracked through frequency analysis or by trying all 25 possible keys. It is identical to the Vigen\u00e8re cipher with a key length of 1 and to the Rot-13 cipher with a key of 13. The implementation also handles errors properly by skipping non-ASCII characters.","id":2724}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::cmp::{max, min};\n\nfn gcd(a: usize, b: usize) -> usize {\n    match ((a, b), (a & 1, b & 1)) {\n        ((x, y), _) if x == y => y,\n        ((0, x), _) | ((x, 0), _) => x,\n        ((x, y), (0, 1)) | ((y, x), (1, 0)) => gcd(x >> 1, y),\n        ((x, y), (0, 0)) => gcd(x >> 1, y >> 1) << 1,\n        ((x, y), (1, 1)) => {\n            let (x, y) = (min(x, y), max(x, y));\n            gcd((y - x) >> 1, x)\n        }\n        _ => unreachable!(),\n    }\n}\n\nfn lcm(a: usize, b: usize) -> usize {\n    a * b \/ gcd(a, b)\n}\n\nfn main() {\n    println!(\"{}\", lcm(6324, 234))\n}\n\n","human_summarization":"compute the least common multiple (LCM) of two integers, m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM is calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The code also includes a method to find the LCM by merging the prime decompositions of both m and n. The implementation uses a recursive implementation of Stein's algorithm to calculate the gcd.","id":2725}
    {"lang_cluster":"Rust","source_code":"\nfn cusip_check(cusip: &str) -> bool {\n    if cusip.len() != 9 {\n        return false;\n    }\n\n    let mut v = 0;\n    let capital_cusip = cusip.to_uppercase();\n    let char_indices = capital_cusip.as_str().char_indices().take(7);\n\n    let total = char_indices.fold(0, |total, (i, c)| {\n        v = match c {\n            '*' => 36,\n            '@' => 37,\n            '#' => 38,\n            _ if c.is_digit(10) => c.to_digit(10).unwrap() as u8,\n            _ if c.is_alphabetic() => (c as u8) - b'A' + 1 + 9,\n            _ => v,\n        };\n\n        if i % 2 != 0 {\n            v *= 2\n        }\n        total + (v \/ 10) + v % 10\n    });\n\n    let check = (10 - (total % 10)) % 10;\n    (check.to_string().chars().nth(0).unwrap()) == cusip.chars().nth(cusip.len() - 1).unwrap()\n}\n\nfn main() {\n    let codes = [\n        \"037833100\",\n        \"17275R102\",\n        \"38259P508\",\n        \"594918104\",\n        \"68389X106\",\n        \"68389X105\",\n    ];\n    for code in &codes {\n        println!(\"{} -> {}\", code, cusip_check(code))\n    }\n}\n\n\n037833100 -> True\n17275R102 -> True\n38259P508 -> True\n594918104 -> True\n68389X106 -> False\n68389X105 -> True\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric identifier for North American financial securities. It uses a specific algorithm to calculate the check digit from the first 8 characters of the CUSIP code and compares it with the actual last digit. The algorithm considers digits, letters, and special characters '*', '@', and '#'. It also takes into account the position of each character in the CUSIP code. The code is designed to facilitate the clearing and settlement of trades.","id":2726}
    {"lang_cluster":"Rust","source_code":"\n#[derive(Copy, Clone, Debug)]\nenum Endianness {\n    Big, Little,\n}\n\nimpl Endianness {\n    fn target() -> Self {\n        #[cfg(target_endian = \"big\")]\n        {\n            Endianness::Big\n        }\n        #[cfg(not(target_endian = \"big\"))]\n        {\n            Endianness::Little\n        }\n    }\n}\n\nfn main() {\n    println!(\"Word size: {} bytes\", std::mem::size_of::<usize>());\n    println!(\"Endianness: {:?}\", Endianness::target());\n}\n\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":2727}
    {"lang_cluster":"Rust","source_code":"\n\nlet collection = vec![1,2,3,4,5];\nfor elem in collection {\n    println!(\"{}\", elem);\n}\n\nlet mut collection = vec![1,2,3,4,5];\nfor mut_ref in &mut collection {\n\/\/ alternatively:\n\/\/ for mut_ref in collection.iter_mut() {\n    *mut_ref *= 2;\n    println!(\"{}\", *mut_ref);\n}\n\n\/\/ immutable borrow\nfor immut_ref in &collection {\n\/\/ alternatively:\n\/\/ for immut_ref in collection.iter() {\n    println!(\"{}\", *immut_ref);\n}\n\nlet collection = vec![1, 2, 3, 4, 5];\ncollection.iter().for_each(|elem| println!(\"{}\", elem));\n","human_summarization":"The code uses Rust's \"for each\" loop to iterate over and print each element in a collection in order. It ensures the original vector remains usable after the loop by borrowing or using an Iter. It also allows for mutation of values through a mutable borrow or IterMut. From Rust 1.21, a closure is executed on each element using foreach.","id":2728}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    let s = \"Hello,How,Are,You,Today\";\n    let tokens: Vec<&str> = s.split(\",\").collect();\n    println!(\"{}\", tokens.join(\".\"));\n}\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":2729}
    {"lang_cluster":"Rust","source_code":"\nextern crate num;\nuse num::integer::gcd;\nfn gcd(mut m: i32, mut n: i32) -> i32 {\n   while m\u00a0!= 0 {\n       let old_m = m;\n       m = n\u00a0% m;\n       n = old_m;\n   }\n   n.abs()\n}\nfn gcd(m: i32, n: i32) -> i32 {\n   if m == 0 {\n      n.abs()\n   } else {\n      gcd(n\u00a0% m, m)\n   }\n}\n\nuse std::cmp::{min, max};\nfn gcd(a: usize, b: usize) -> usize {\n    match ((a, b), (a & 1, b & 1)) {\n        ((x, y), _) if x == y               => y,\n        ((0, x), _) | ((x, 0), _)           => x,\n        ((x, y), (0, 1)) | ((y, x), (1, 0)) => gcd(x >> 1, y),\n        ((x, y), (0, 0))                    => gcd(x >> 1, y >> 1) << 1,\n        ((x, y), (1, 1))                    => { let (x, y) = (min(x, y), max(x, y)); \n                                                 gcd((y - x) >> 1, x) \n                                               }\n        _                                   => unreachable!(),\n    }\n}\n   println!(\"{}\",gcd(399,-3999));\n   println!(\"{}\",gcd(0,3999));\n   println!(\"{}\",gcd(13*13,13*29));\n\n3\n3999\n13\n","human_summarization":"implement a function to find the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two unsigned integers using Stein's algorithm. This algorithm is similar to Euclid's but uses bitwise operators for better performance. The function uses Rust's pattern matching in a recursive implementation. The code is related to the task of finding the least common multiple.","id":2730}
    {"lang_cluster":"Rust","source_code":"\nuse std::net::{TcpListener, TcpStream};\nuse std::io::{BufReader, BufRead, Write};\nuse std::thread;\n\nfn main() {\n    let listener = TcpListener::bind(\"127.0.0.1:12321\").unwrap();\n    println!(\"server is running on 127.0.0.1:12321 ...\");\n    \n    for stream in listener.incoming() {\n        let stream = stream.unwrap();\n        thread::spawn(move || handle_client(stream));\n    }\n}\n\nfn handle_client(stream: TcpStream) {\n    let mut stream = BufReader::new(stream);\n    loop {\n        let mut buf = String::new();\n        if stream.read_line(&mut buf).is_err() {\n            break;\n        }\n        stream\n            .get_ref()\n            .write(buf.as_bytes())\n            .unwrap();\n    }\n}\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":2731}
    {"lang_cluster":"Rust","source_code":"\n\/\/ This function is not limited to just numeric types but rather anything that implements the FromStr trait.\nfn parsable<T: FromStr>(s: &str) -> bool {\n    s.parse::<T>().is_ok()\n}\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":2732}
    {"lang_cluster":"Rust","source_code":"\nextern crate reqwest;\n\nfn main() {\n    let response = match reqwest::blocking::get(\"https:\/\/sourceforge.net\") {\n        Ok(response) => response,\n        Err(e) => panic!(\"error encountered while making request: {:?}\", e),\n    };\n\n    println!(\"{}\", response.text().unwrap());\n}\n\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":2733}
    {"lang_cluster":"Rust","source_code":"#[derive(Debug, Clone)]\nstruct Point {\n    x: f64,\n    y: f64,\n}\n\n#[derive(Debug, Clone)]\nstruct Polygon(Vec<Point>);\n\nfn is_inside(p: &Point, cp1: &Point, cp2: &Point) -> bool {\n    (cp2.x - cp1.x) * (p.y - cp1.y) > (cp2.y - cp1.y) * (p.x - cp1.x)\n}\n\nfn compute_intersection(cp1: &Point, cp2: &Point, s: &Point, e: &Point) -> Point {\n    let dc = Point {\n        x: cp1.x - cp2.x,\n        y: cp1.y - cp2.y,\n    };\n    let dp = Point {\n        x: s.x - e.x,\n        y: s.y - e.y,\n    };\n    let n1 = cp1.x * cp2.y - cp1.y * cp2.x;\n    let n2 = s.x * e.y - s.y * e.x;\n    let n3 = 1.0 \/ (dc.x * dp.y - dc.y * dp.x);\n    Point {\n        x: (n1 * dp.x - n2 * dc.x) * n3,\n        y: (n1 * dp.y - n2 * dc.y) * n3,\n    }\n}\n\nfn sutherland_hodgman_clip(subject_polygon: &Polygon, clip_polygon: &Polygon) -> Polygon {\n    let mut result_ring = subject_polygon.0.clone();\n    let mut cp1 = clip_polygon.0.last().unwrap();\n    for cp2 in &clip_polygon.0 {\n        let input = result_ring;\n        let mut s = input.last().unwrap();\n        result_ring = vec![];\n        for e in &input {\n            if is_inside(e, cp1, cp2) {\n                if !is_inside(s, cp1, cp2) {\n                    result_ring.push(compute_intersection(cp1, cp2, s, e));\n                }\n                result_ring.push(e.clone());\n            } else if is_inside(s, cp1, cp2) {\n                result_ring.push(compute_intersection(cp1, cp2, s, e));\n            }\n            s = e;\n        }\n        cp1 = cp2;\n    }\n    Polygon(result_ring)\n}\n\nfn main() {\n    let _p = |x: f64, y: f64| Point { x, y };\n    let subject_polygon = Polygon(vec![\n        _p(50.0, 150.0), _p(200.0, 50.0), _p(350.0, 150.0), _p(350.0, 300.0), _p(250.0, 300.0),\n        _p(200.0, 250.0), _p(150.0, 350.0), _p(100.0, 250.0), _p(100.0, 200.0),\n    ]);\n    let clip_polygon = Polygon(vec![\n        _p(100.0, 100.0),_p(300.0, 100.0),_p(300.0, 300.0),_p(100.0, 300.0),\n    ]);\n    let result = sutherland_hodgman_clip(&subject_polygon, &clip_polygon);\n    println!(\"{:?}\", result);\n}\n\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":2734}
    {"lang_cluster":"Rust","source_code":"\/\/ 20210221 Rust programming solution\n\nuse std::f64::consts::PI;\n\nfn main() {\n   let angle_radians: f64 = PI\/4.0;\n   let angle_degrees: f64 = 45.0;\n\n   println!(\"{} {}\", angle_radians.sin(), angle_degrees.to_radians().sin());\n   println!(\"{} {}\", angle_radians.cos(), angle_degrees.to_radians().cos());\n   println!(\"{} {}\", angle_radians.tan(), angle_degrees.to_radians().tan());\n\n   let asin = angle_radians.sin().asin();\n   println!(\"{} {}\", asin, asin.to_degrees());\n   let acos = angle_radians.cos().acos();\n   println!(\"{} {}\", acos, acos.to_degrees());\n   let atan = angle_radians.tan().atan();\n   println!(\"{} {}\", atan, atan.to_degrees());\n}\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":2735}
    {"lang_cluster":"Rust","source_code":"\n#[cfg(unix)]\nfn main() {\n    use std::sync::atomic::{AtomicBool, Ordering};\n    use std::thread;\n    use std::time::{Duration, Instant};\n\n    use libc::{sighandler_t, SIGINT};\n\n    \/\/ The time between ticks of our counter.\n    let duration = Duration::from_secs(1) \/ 2;\n\n    \/\/ \"SIGINT received\" global variable.\n    static mut GOT_SIGINT: AtomicBool = AtomicBool::new(false);\n\n    unsafe {\n        \/\/ Initially, \"SIGINT received\" is false.\n        GOT_SIGINT.store(false, Ordering::Release);\n        \/\/ Interrupt handler that handles the SIGINT signal\n        unsafe fn handle_sigint() {\n            \/\/ It is dangerous to perform any system calls in interrupts, so just set the atomic\n            \/\/ \"SIGINT received\" global to true when it arrives.\n            GOT_SIGINT.store(true, Ordering::Release);\n        }\n        \/\/ Make handle_sigint the signal handler for SIGINT.\n        libc::signal(SIGINT, handle_sigint as sighandler_t);\n    }\n\n    \/\/ Get the start time...\n    let start = Instant::now();\n\n    \/\/ Integer counter\n    let mut i = 0u32;\n\n    \/\/ Every `duration`...\n    loop {\n        thread::sleep(duration);\n\n        \/\/ Break if SIGINT was handled\n        if unsafe { GOT_SIGINT.load(Ordering::Acquire) } {\n            break;\n        }\n\n        \/\/ Otherwise, increment and display the integer and continue the loop.\n        i += 1;\n        println!(\"{}\", i);\n    }\n\n    \/\/ Get the elapsed time.\n    let elapsed = start.elapsed();\n\n    \/\/ Print the difference and exit\n    println!(\"Program has run for {} seconds\", elapsed.as_secs());\n}\n\n#[cfg(not(unix))]\nfn main() {\n    println!(\"Not supported on this platform\");\n}\n\n\n","human_summarization":"an integer every half second, handle SIGINT or SIGQUIT signals to stop output, display the runtime in seconds, and then terminate the program.","id":2736}
    {"lang_cluster":"Rust","source_code":"\nfn next_string(input: &str) -> String {\n    (input.parse::<i64>().unwrap() + 1).to_string()\n}\n\nfn main() {\n    let s = \"-1\";\n    let s2 = next_string(s);\n    println!(\"{:?}\", s2);\n}\n\n","human_summarization":"\"Increments a given numerical string.\"","id":2737}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::path::{Path, PathBuf};\n\nfn main() {\n    let paths = [\n        Path::new(\"\/home\/user1\/tmp\/coverage\/test\"),\n        Path::new(\"\/home\/user1\/tmp\/covert\/operator\"),\n        Path::new(\"\/home\/user1\/tmp\/coven\/members\"),\n    ];\n    match common_path(&paths) {\n        Some(p) => println!(\"The common path is: {:#?}\", p),\n        None => println!(\"No common paths found\"),\n    }\n}\n\nfn common_path<I, P>(paths: I) -> Option<PathBuf>\nwhere\n    I: IntoIterator<Item = P>,\n    P: AsRef<Path>,\n{\n    let mut iter = paths.into_iter();\n    let mut ret = iter.next()?.as_ref().to_path_buf();\n    for path in iter {\n        if let Some(r) = common(ret, path.as_ref()) {\n            ret = r;\n        } else {\n            return None;\n        }\n    }\n    Some(ret)\n}\n\nfn common<A: AsRef<Path>, B: AsRef<Path>>(a: A, b: B) -> Option<PathBuf> {\n    let a = a.as_ref().components();\n    let b = b.as_ref().components();\n    let mut ret = PathBuf::new();\n    let mut found = false;\n    for (one, two) in a.zip(b) {\n        if one == two {\n            ret.push(one);\n            found = true;\n        } else {\n            break;\n        }\n    }\n    if found {\n        Some(ret)\n    } else {\n        None\n    }\n}\n\n","human_summarization":"The code creates a function that takes a set of directory paths and a directory separator as inputs. It then returns the common directory path among all the provided directories. The function is tested with the forward slash '\/' as the directory separator and three specific strings as input paths. The function ensures that the returned path is a valid directory, not just the longest common string. The code also mentions the use of PathBuf and Path types in Rust for handling owned and borrowed paths respectively.","id":2738}
    {"lang_cluster":"Rust","source_code":"\n\nfn median(mut xs: Vec<f64>) -> f64 {\n    \/\/ sort in ascending order, panic on f64::NaN\n    xs.sort_by(|x,y| x.partial_cmp(y).unwrap() );\n    let n = xs.len();\n    if n\u00a0% 2 == 0 {\n        (xs[n\/2] + xs[n\/2 - 1]) \/ 2.0\n    } else {\n        xs[n\/2]\n    }\n}\n\nfn main() {\n    let nums = vec![2.,3.,5.,0.,9.,82.,353.,32.,12.];\n    println!(\"{:?}\", median(nums))\n}\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers, handling even number of elements by returning the average of the two middle values. It employs the selection algorithm for an efficient O(n) time complexity. The code also includes tasks for calculating various statistical measures such as mean, mode, standard deviation, and different types of averages. It does not handle empty vectors.","id":2739}
    {"lang_cluster":"Rust","source_code":"\n\nfn main() {\n    for i in 1..=100 {\n        match (i\u00a0% 3, i\u00a0% 5) {\n            (0, 0) => println!(\"fizzbuzz\"),\n            (0, _) => println!(\"fizz\"),\n            (_, 0) => println!(\"buzz\"),\n            (_, _) => println!(\"{}\", i),\n        }\n    }\n}\n\nuse std::borrow::Cow;\n\nfn main() {\n    (1..=100)\n        .map(|n| match (n\u00a0% 3, n\u00a0% 5) {\n            (0, 0) => \"FizzBuzz\".into(),\n            (0, _) => \"Fizz\".into(),\n            (_, 0) => \"Buzz\".into(),\n            _ => Cow::from(n.to_string()),\n        })\n        .for_each(|n| println!(\"{:?}\", n));\n}\n\nuse std::fmt::Write;\n\nfn fizzbuzz() -> String {\n    (1..=100).fold(String::new(), |mut output, x| {\n        let fizz = if x\u00a0% 3 == 0 { \"fizz\" } else { \"\" };\n        let buzz = if x\u00a0% 5 == 0 { \"buzz\" } else { \"\" };\n        if fizz.len() + buzz.len()\u00a0!= 0 {\n            output + fizz + buzz + \"\\n\"\n        } else {\n            write!(&mut output, \"{}\", x).unwrap();\n            output + \"\\n\"\n        }\n    })\n}\n\nfn main() {\n    println!(\"{}\", fizzbuzz());\n}\n\n#![no_std]\n#![feature(asm, lang_items, libc, no_std, start)]\n \nextern crate libc;\n \nconst LEN: usize = 413;\nstatic OUT: [u8; LEN] = *b\"\\\n    1\\n2\\nFizz\\n4\\nBuzz\\nFizz\\n7\\n8\\nFizz\\nBuzz\\n11\\nFizz\\n13\\n14\\nFizzBuzz\\n\\\n    16\\n17\\nFizz\\n19\\nBuzz\\nFizz\\n22\\n23\\nFizz\\nBuzz\\n26\\nFizz\\n28\\n29\\nFizzBuzz\\n\\\n    31\\n32\\nFizz\\n34\\nBuzz\\nFizz\\n37\\n38\\nFizz\\nBuzz\\n41\\nFizz\\n43\\n44\\nFizzBuzz\\n\\\n    46\\n47\\nFizz\\n49\\nBuzz\\nFizz\\n52\\n53\\nFizz\\nBuzz\\n56\\nFizz\\n58\\n59\\nFizzBuzz\\n\\\n    61\\n62\\nFizz\\n64\\nBuzz\\nFizz\\n67\\n68\\nFizz\\nBuzz\\n71\\nFizz\\n73\\n74\\nFizzBuzz\\n\\\n    76\\n77\\nFizz\\n79\\nBuzz\\nFizz\\n82\\n83\\nFizz\\nBuzz\\n86\\nFizz\\n88\\n89\\nFizzBuzz\\n\\\n    91\\n92\\nFizz\\n94\\nBuzz\\nFizz\\n97\\n98\\nFizz\\nBuzz\\n\";\n \n#[start]\nfn start(_argc: isize, _argv: *const *const u8) -> isize {\n    unsafe {\n        asm!(\n            \"\n            mov $$1, %rax\n            mov $$1, %rdi\n            mov $0, %rsi\n            mov $1, %rdx\n            syscall\n            \"\n           \u00a0:\n           \u00a0: \"r\" (&OUT[0]) \"r\" (LEN)\n           \u00a0: \"rax\", \"rdi\", \"rsi\", \"rdx\"\n           \u00a0:\n        );\n    }\n    0\n}\n \n#[lang = \"eh_personality\"] extern fn eh_personality() {}\n#[lang = \"panic_fmt\"] extern fn panic_fmt() {}\n","human_summarization":"print integers from 1 to 100. It replaces multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'. The code can be implemented with a for loop and match, an iterator and immutable data, a folding iterator version buffered with a single string allocation, or an optimized version with hardcoded output, no standard library or main function, and direct assembly syscalls to write to stdout.","id":2740}
    {"lang_cluster":"Rust","source_code":"\n\nextern crate image;\nextern crate num_complex;\n\nuse num_complex::Complex;\n\nfn main() {\n    let max_iterations = 256u16;\n    let img_side = 800u32;\n    let cxmin = -2f32;\n    let cxmax = 1f32;\n    let cymin = -1.5f32;\n    let cymax = 1.5f32;\n    let scalex = (cxmax - cxmin) \/ img_side as f32;\n    let scaley = (cymax - cymin) \/ img_side as f32;\n\n    \/\/ Create a new ImgBuf\n    let mut imgbuf = image::ImageBuffer::new(img_side, img_side);\n\n    \/\/ Calculate for each pixel\n    for (x, y, pixel) in imgbuf.enumerate_pixels_mut() {\n        let cx = cxmin + x as f32 * scalex;\n        let cy = cymin + y as f32 * scaley;\n\n        let c = Complex::new(cx, cy);\n        let mut z = Complex::new(0f32, 0f32);\n\n        let mut i = 0;\n        for t in 0..max_iterations {\n            if z.norm() > 2.0 {\n                break;\n            }\n            z = z * z + c;\n            i = t;\n        }\n\n        *pixel = image::Luma([i as u8]);\n    }\n\n    \/\/ Save image\n    imgbuf.save(\"fractal.png\").unwrap();\n}\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. Dependencies include the image and num-complex modules.","id":2741}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    let arr = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];\n\n    \/\/ using fold\n    let sum = arr.iter().fold(0i32, |a, &b| a + b);\n    let product = arr.iter().fold(1i32, |a, &b| a * b);\n    println!(\"the sum is {} and the product is {}\", sum, product);\n\n    \/\/ or using sum and product\n    let sum = arr.iter().sum::<i32>();\n    let product = arr.iter().product::<i32>();\n    println!(\"the sum is {} and the product is {}\", sum, product);\n}\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":2742}
    {"lang_cluster":"Rust","source_code":"\nfn is_leap(year: i32) -> bool {\n    let factor = |x| year\u00a0% x == 0;\n    factor(4) && (!factor(100) || factor(400))\n}\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":2743}
    {"lang_cluster":"Rust","source_code":"\n\n#![allow(non_snake_case)] \/\/ RFC 1321 uses many capitalized variables\nuse std::mem;\n\nfn md5(mut msg: Vec<u8>) -> (u32, u32, u32, u32) {\n    let bitcount = msg.len().saturating_mul(8) as u64;\n\n    \/\/ Step 1: Append Padding Bits\n    msg.push(0b10000000);\n    while (msg.len() * 8) % 512 != 448 {\n        msg.push(0u8);\n    }\n\n    \/\/ Step 2. Append Length  (64 bit integer)\n    msg.extend(&[\n        bitcount as u8,\n        (bitcount >> 8) as u8,\n        (bitcount >> 16) as u8,\n        (bitcount >> 24) as u8,\n        (bitcount >> 32) as u8,\n        (bitcount >> 40) as u8,\n        (bitcount >> 48) as u8,\n        (bitcount >> 56) as u8,\n    ]);\n\n    \/\/ Step 3. Initialize MD Buffer\n    \/*A four-word buffer (A,B,C,D) is used to compute the message digest.\n    Here each of A, B, C, D is a 32-bit register.*\/\n    let mut A = 0x67452301u32;\n    let mut B = 0xefcdab89u32;\n    let mut C = 0x98badcfeu32;\n    let mut D = 0x10325476u32;\n\n    \/\/ Step 4. Process Message in 16-Word Blocks\n    \/* We first define four auxiliary functions *\/\n    let F = |X: u32, Y: u32, Z: u32| -> u32 { X & Y | !X & Z };\n    let G = |X: u32, Y: u32, Z: u32| -> u32 { X & Z | Y & !Z };\n    let H = |X: u32, Y: u32, Z: u32| -> u32 { X ^ Y ^ Z };\n    let I = |X: u32, Y: u32, Z: u32| -> u32 { Y ^ (X | !Z) };\n\n    \/* This step uses a 64-element table T[1 ... 64] constructed from the sine function.  *\/\n    let T = [\n        0x00000000, \/\/ enable use as a 1-indexed table\n        0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613,\n        0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193,\n        0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d,\n        0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,\n        0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,\n        0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa,\n        0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244,\n        0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,\n        0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb,\n        0xeb86d391,\n    ];\n\n    \/* Process each 16-word block. (since 1 word is 4 bytes, then 16 words is 64 bytes) *\/\n    for mut block in msg.chunks_exact_mut(64) {\n        \/* Copy block into X. *\/\n        #![allow(unused_mut)]\n        let mut X = unsafe { mem::transmute::<&mut [u8], &mut [u32]>(&mut block) };\n        #[cfg(target_endian = \"big\")]\n        for j in 0..16 {\n            X[j] = X[j].swap_bytes();\n        }\n\n        \/* Save Registers A,B,C,D *\/\n        let AA = A;\n        let BB = B;\n        let CC = C;\n        let DD = D;\n\n        \/* Round 1.  Let [abcd k s i] denote the operation\n        a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). *\/\n        macro_rules! op1 {\n            ($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {\n                $a = $b.wrapping_add(\n                    ($a.wrapping_add(F($b, $c, $d))\n                        .wrapping_add(X[$k])\n                        .wrapping_add(T[$i]))\n                    .rotate_left($s),\n                )\n            };\n        }\n\n        \/* Do the following 16 operations. *\/\n        op1!(A, B, C, D, 0, 7, 1);\n        op1!(D, A, B, C, 1, 12, 2);\n        op1!(C, D, A, B, 2, 17, 3);\n        op1!(B, C, D, A, 3, 22, 4);\n\n        op1!(A, B, C, D, 4, 7, 5);\n        op1!(D, A, B, C, 5, 12, 6);\n        op1!(C, D, A, B, 6, 17, 7);\n        op1!(B, C, D, A, 7, 22, 8);\n\n        op1!(A, B, C, D, 8, 7, 9);\n        op1!(D, A, B, C, 9, 12, 10);\n        op1!(C, D, A, B, 10, 17, 11);\n        op1!(B, C, D, A, 11, 22, 12);\n\n        op1!(A, B, C, D, 12, 7, 13);\n        op1!(D, A, B, C, 13, 12, 14);\n        op1!(C, D, A, B, 14, 17, 15);\n        op1!(B, C, D, A, 15, 22, 16);\n\n        \/* Round 2. Let [abcd k s i] denote the operation\n        a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). *\/\n        macro_rules! op2 {\n            ($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {\n                $a = $b.wrapping_add(\n                    ($a.wrapping_add(G($b, $c, $d))\n                        .wrapping_add(X[$k])\n                        .wrapping_add(T[$i]))\n                    .rotate_left($s),\n                )\n            };\n        }\n\n        \/* Do the following 16 operations. *\/\n        op2!(A, B, C, D, 1, 5, 17);\n        op2!(D, A, B, C, 6, 9, 18);\n        op2!(C, D, A, B, 11, 14, 19);\n        op2!(B, C, D, A, 0, 20, 20);\n\n        op2!(A, B, C, D, 5, 5, 21);\n        op2!(D, A, B, C, 10, 9, 22);\n        op2!(C, D, A, B, 15, 14, 23);\n        op2!(B, C, D, A, 4, 20, 24);\n\n        op2!(A, B, C, D, 9, 5, 25);\n        op2!(D, A, B, C, 14, 9, 26);\n        op2!(C, D, A, B, 3, 14, 27);\n        op2!(B, C, D, A, 8, 20, 28);\n\n        op2!(A, B, C, D, 13, 5, 29);\n        op2!(D, A, B, C, 2, 9, 30);\n        op2!(C, D, A, B, 7, 14, 31);\n        op2!(B, C, D, A, 12, 20, 32);\n\n        \/* Round 3. Let [abcd k s t] denote the operation\n        a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). *\/\n        macro_rules! op3 {\n            ($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {\n                $a = $b.wrapping_add(\n                    ($a.wrapping_add(H($b, $c, $d))\n                        .wrapping_add(X[$k])\n                        .wrapping_add(T[$i]))\n                    .rotate_left($s),\n                )\n            };\n        }\n\n        \/* Do the following 16 operations. *\/\n        op3!(A, B, C, D, 5, 4, 33);\n        op3!(D, A, B, C, 8, 11, 34);\n        op3!(C, D, A, B, 11, 16, 35);\n        op3!(B, C, D, A, 14, 23, 36);\n\n        op3!(A, B, C, D, 1, 4, 37);\n        op3!(D, A, B, C, 4, 11, 38);\n        op3!(C, D, A, B, 7, 16, 39);\n        op3!(B, C, D, A, 10, 23, 40);\n\n        op3!(A, B, C, D, 13, 4, 41);\n        op3!(D, A, B, C, 0, 11, 42);\n        op3!(C, D, A, B, 3, 16, 43);\n        op3!(B, C, D, A, 6, 23, 44);\n\n        op3!(A, B, C, D, 9, 4, 45);\n        op3!(D, A, B, C, 12, 11, 46);\n        op3!(C, D, A, B, 15, 16, 47);\n        op3!(B, C, D, A, 2, 23, 48);\n\n        \/* Round 4. Let [abcd k s t] denote the operation\n        a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). *\/\n        macro_rules! op4 {\n            ($a:ident,$b:ident,$c:ident,$d:ident,$k:expr,$s:expr,$i:expr) => {\n                $a = $b.wrapping_add(\n                    ($a.wrapping_add(I($b, $c, $d))\n                        .wrapping_add(X[$k])\n                        .wrapping_add(T[$i]))\n                    .rotate_left($s),\n                )\n            };\n        }\n\n        \/* Do the following 16 operations. *\/\n        op4!(A, B, C, D, 0, 6, 49);\n        op4!(D, A, B, C, 7, 10, 50);\n        op4!(C, D, A, B, 14, 15, 51);\n        op4!(B, C, D, A, 5, 21, 52);\n\n        op4!(A, B, C, D, 12, 6, 53);\n        op4!(D, A, B, C, 3, 10, 54);\n        op4!(C, D, A, B, 10, 15, 55);\n        op4!(B, C, D, A, 1, 21, 56);\n\n        op4!(A, B, C, D, 8, 6, 57);\n        op4!(D, A, B, C, 15, 10, 58);\n        op4!(C, D, A, B, 6, 15, 59);\n        op4!(B, C, D, A, 13, 21, 60);\n\n        op4!(A, B, C, D, 4, 6, 61);\n        op4!(D, A, B, C, 11, 10, 62);\n        op4!(C, D, A, B, 2, 15, 63);\n        op4!(B, C, D, A, 9, 21, 64);\n\n        \/* . . . increment each of the four registers by the value \n        it had before this block was started.) *\/\n\n        A = A.wrapping_add(AA);\n        B = B.wrapping_add(BB);\n        C = C.wrapping_add(CC);\n        D = D.wrapping_add(DD);\n    }\n    (\n        A.swap_bytes(),\n        B.swap_bytes(),\n        C.swap_bytes(),\n        D.swap_bytes(),\n    )\n}\n\nfn md5_utf8(smsg: &str) -> String {\n    let mut msg = vec![0u8; 0];\n    msg.extend(smsg.as_bytes());\n    let (A, B, C, D) = md5(msg);\n    format!(\"{:08x}{:08x}{:08x}{:08x}\", A, B, C, D)\n}\n\nfn main() {\n    assert!(md5_utf8(\"\") == \"d41d8cd98f00b204e9800998ecf8427e\");\n    assert!(md5_utf8(\"a\") == \"0cc175b9c0f1b6a831c399e269772661\");\n    assert!(md5_utf8(\"abc\") == \"900150983cd24fb0d6963f7d28e17f72\");\n    assert!(md5_utf8(\"message digest\") == \"f96b697d7cb7938d525a2f31aaf161d0\");\n    assert!(md5_utf8(\"abcdefghijklmnopqrstuvwxyz\") == \"c3fcd3d76192e4007dfb496cca67e13b\");\n    assert!(md5_utf8(\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\") == \"d174ab98d277d9f5a5611c2c9f419d9f\");\n    assert!(md5_utf8(\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\") == \"57edf4a22be3c955ac49da2e2107b67a\");\n}\n\n","human_summarization":"implement the MD5 Message Digest Algorithm directly without using built-in or external hashing libraries. The implementation focuses on producing a correct message digest for an input string. It also includes challenges, implementation choices, and limitations encountered during the implementation process. The code does not use built-in MD5 functions, operating system calls, or library routines written in other languages. It provides practical illustrations of bit manipulation, unsigned integers, and working with little-endian data. The code also includes verification strings and hashes from RFC 1321. It does not support bit-lengths non-divisible by 8.","id":2744}
    {"lang_cluster":"Rust","source_code":"extern crate num_iter;\nfn main() {\n    println!(\"Police Sanitation Fire\");\n    println!(\"----------------------\");\n\n    for police in num_iter::range_step(2, 7, 2) {\n        for sanitation in 1..8 {\n            for fire in 1..8 {\n                if police != sanitation\n                    && sanitation != fire\n                    && fire != police\n                    && police + fire + sanitation == 12\n                {\n                    println!(\"{:6}{:11}{:4}\", police, sanitation, fire);\n                }\n            }\n        }\n    }\n}\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":2745}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    let s1 = \"A String\";\n    let mut s2 = s1;\n\n    s2 = \"Another String\";\n\n    println!(\"s1 = {}, s2 = {}\", s1, s2);\n}\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":2746}
    {"lang_cluster":"Rust","source_code":"\nfn f(n: u32) -> u32 {\n    match n {\n        0 => 1,\n        _ => n - m(f(n - 1))\n    }\n}\n\nfn m(n: u32) -> u32 {\n    match n {\n        0 => 0,\n        _ => n - f(m(n - 1))\n    }\n}\n\nfn main() {\n    for i in (0..20).map(f) {\n        print!(\"{} \", i);\n    }\n    println!(\"\");\n\n    for i in (0..20).map(m) {\n        print!(\"{} \", i);\n    }\n    println!(\"\")\n}\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":2747}
    {"lang_cluster":"Rust","source_code":"\nLibrary: rand\nextern crate rand;\n\nuse rand::Rng;\n\nfn main() {\n    let array = [5,1,2,5,6,7,8,1,2,4,5];\n    let mut rng = rand::thread_rng();\n    \n    println!(\"{}\", rng.choose(&array).unwrap());\n}\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":2748}
    {"lang_cluster":"Rust","source_code":"\nconst INPUT1: &str = \"http%3A%2F%2Ffoo%20bar%2F\";\nconst INPUT2: &str = \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\";\n\nfn append_frag(text: &mut String, frag: &mut String) {\n    if !frag.is_empty() {\n        let encoded = frag.chars()\n            .collect::<Vec<char>>()\n            .chunks(2)\n            .map(|ch| {\n                u8::from_str_radix(&ch.iter().collect::<String>(), 16).unwrap()\n            }).collect::<Vec<u8>>();\n        text.push_str(&std::str::from_utf8(&encoded).unwrap());\n        frag.clear();\n    }\n}\n\nfn decode(text: &str) -> String {\n    let mut output = String::new();\n    let mut encoded_ch = String::new();\n    let mut iter = text.chars();\n    while let Some(ch) = iter.next() {\n        if ch == '%' {\n            encoded_ch.push_str(&format!(\"{}{}\", iter.next().unwrap(), iter.next().unwrap()));\n        } else {\n            append_frag(&mut output, &mut encoded_ch);\n            output.push(ch);\n        }\n    }\n    append_frag(&mut output, &mut encoded_ch);\n    output\n}\n\nfn main() {\n    println!(\"{}\", decode(INPUT1));\n    println!(\"{}\", decode(INPUT2));\n}\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":2749}
    {"lang_cluster":"Rust","source_code":"\n\nfn binary_search<T:PartialOrd>(v: &[T], searchvalue: T) -> Option<T> {\n    let mut lower = 0 as usize;\n    let mut upper = v.len() - 1;\n\n    while upper >= lower {\n        let mid = (upper + lower) \/ 2;\n        if v[mid] == searchvalue {\n            return Some(searchvalue);\n        } else if searchvalue < v[mid] {\n            upper = mid - 1;\n        } else {\n            lower = mid + 1;\n        }\n    }\n\n    None\n}\n","human_summarization":"The code implements a binary search algorithm that finds a specific number in a sorted integer array. The search can be either recursive or iterative. The algorithm divides the range into halves until the target number is found or confirmed absent. If the number is found, the index is returned. The code also includes variations of the algorithm that return the leftmost or rightmost insertion point for the target number. It also handles potential overflow bugs.","id":2750}
    {"lang_cluster":"Rust","source_code":"\nuse std::env;\n\nfn main(){\n    let args: Vec<_> = env::args().collect();\n    println!(\"{:?}\", args);\n}\n\n.\/program -c \"alpha beta\" -h \"gamma\"\n[\".\/program\", \"-c\", \"alpha beta\", \"-h\", \"gamma\"]\n","human_summarization":"\"Code retrieves and prints the list of command-line arguments provided to the program. It also includes functionality for intelligent parsing of these arguments. An example command line usage is shown with 'myprogram -c \"alpha beta\" -h \"gamma\"'.\"","id":2751}
    {"lang_cluster":"Rust","source_code":"\nLibrary: piston_window\n\/\/ using version 0.107.0 of piston_window\nuse piston_window::{clear, ellipse, line_from_to, PistonWindow, WindowSettings};\n\nconst PI: f64 = std::f64::consts::PI;\nconst WIDTH: u32 = 640;\nconst HEIGHT: u32 = 480;\n\nconst ANCHOR_X: f64 = WIDTH as f64 \/ 2. - 12.;\nconst ANCHOR_Y: f64 = HEIGHT as f64 \/ 4.;\nconst ANCHOR_ELLIPSE: [f64; 4] = [ANCHOR_X - 3., ANCHOR_Y - 3., 6., 6.];\n\nconst ROPE_ORIGIN: [f64; 2] = [ANCHOR_X, ANCHOR_Y];\nconst ROPE_LENGTH: f64 = 200.;\nconst ROPE_THICKNESS: f64 = 1.;\n\nconst DELTA: f64 = 0.05;\nconst STANDARD_GRAVITY_VALUE: f64 = -9.81;\n\n\/\/ RGBA Colors\nconst BLACK: [f32; 4] = [0., 0., 0., 1.];\nconst RED: [f32; 4] = [1., 0., 0., 1.];\nconst GOLD: [f32; 4] = [216. \/ 255., 204. \/ 255., 36. \/ 255., 1.0];\nfn main() {\n    let mut window: PistonWindow = WindowSettings::new(\"Pendulum\", [WIDTH, HEIGHT])\n        .exit_on_esc(true)\n        .build()\n        .unwrap();\n\n    let mut angle = PI \/ 2.;\n    let mut angular_vel = 0.;\n\n    while let Some(event) = window.next() {\n        let (angle_sin, angle_cos) = angle.sin_cos();\n        let ball_x = ANCHOR_X + angle_sin * ROPE_LENGTH;\n        let ball_y = ANCHOR_Y + angle_cos * ROPE_LENGTH;\n\n        let angle_accel = STANDARD_GRAVITY_VALUE \/ ROPE_LENGTH * angle_sin;\n        angular_vel += angle_accel * DELTA;\n        angle += angular_vel * DELTA;\n        let rope_end = [ball_x, ball_y];\n        let ball_ellipse = [ball_x - 7., ball_y - 7., 14., 14.];\n\n        window.draw_2d(&event, |context, graphics, _device| {\n            clear([1.0; 4], graphics);\n            line_from_to(\n                BLACK,\n                ROPE_THICKNESS,\n                ROPE_ORIGIN,\n                rope_end,\n                context.transform,\n                graphics,\n            );\n            ellipse(RED, ANCHOR_ELLIPSE, context.transform, graphics);\n            ellipse(GOLD, ball_ellipse, context.transform, graphics);\n        });\n    }\n}\n\n","human_summarization":"simulate and animate a simple gravity pendulum model. The animation speed accelerates when the mouse hovers over the viewport. The code is a translation from C# with more explicit constant declarations. Modifications to maintain a constant framerate are welcome.","id":2752}
    {"lang_cluster":"Rust","source_code":"\n\nWorks with: Rust version 1.31\nLibrary: Serde\u00a0version 1.0\n[dependencies]\nserde = { version = \"1.0\", features = [\"derive\"] }\nserde_json = \"1.0\"\n\n\nuse serde::{Serialize, Deserialize};\n\n#[derive(Serialize, Deserialize, Debug)]\nstruct Point {\n    x: i32,\n    y: i32,\n}\n\n\nfn main() {\n    let point = Point { x: 1, y: 2 };\n\n    let serialized = serde_json::to_string(&point).unwrap();\n    let deserialized: Point = serde_json::from_str(&serialized).unwrap();\n\n    println!(\"serialized = {}\", serialized);\n    println!(\"deserialized = {:?}\", deserialized);\n}\n\n\n\n","human_summarization":"\"Load a JSON string into a data structure and serialize a new data structure into JSON using Rust. The code utilizes the Serde library and its JSON implementation for serialization and deserialization. It supports various Rust-specific types and implements traits for HashMap and Vec for handling objects\/arrays. It also handles additional entries in JSON strings.\"","id":2753}
    {"lang_cluster":"Rust","source_code":"\/\/ 20210212 Rust programming solution\n\nfn nthRoot(n: f64, A: f64) -> f64 {\n\n   let      p  =  1e-9_f64 ;\n   let mut x0  =     A \/ n ;\n\n   loop {\n      let mut x1 = ( (n-1.0) * x0 + A \/ f64::powf(x0, n-1.0) ) \/ n;\n      if (x1-x0).abs() < (x0*p).abs() { return x1 };\n      x0 = x1\n   }\n}\n\nfn main() {\n   println!(\"{}\", nthRoot(3. , 8. ));\n}\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":2754}
    {"lang_cluster":"Rust","source_code":"\n\nfn main() {\n    match hostname::get_hostname() {\n        Some(host) => println!(\"hostname: {}\", host),\n        None => eprintln!(\"Could not get hostname!\"),\n    }\n}\n\n","human_summarization":"\"Code retrieves the hostname of the system where the routine is running, compatible with both Windows and Linux using the hostname crate version 0.1.5.\"","id":2755}
    {"lang_cluster":"Rust","source_code":"\nfn leonardo(mut n0: u32, mut n1: u32, add: u32) -> impl std::iter::Iterator<Item = u32> {\n    std::iter::from_fn(move || {\n        let n = n0;\n        n0 = n1;\n        n1 += n + add;\n        Some(n)\n    })\n}\n\nfn main() {\n    println!(\"First 25 Leonardo numbers:\");\n    for i in leonardo(1, 1, 1).take(25) {\n        print!(\"{} \", i);\n    }\n    println!();\n    println!(\"First 25 Fibonacci numbers:\");\n    for i in leonardo(0, 1, 0).take(25) {\n        print!(\"{} \", i);\n    }\n    println!();\n}\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":2756}
    {"lang_cluster":"Rust","source_code":"\n\nLibrary: rand\nuse std::io::{self,BufRead};\nextern crate rand;\nuse rand::Rng;\n\nfn op_type(x: char) -> i32{\n    match x {\n        '-' | '+' => return 1,\n        '\/' | '*' => return 2,\n        '(' | ')' => return -1,\n        _   => return 0,\n    }\n}\n\nfn to_rpn(input: &mut String){\n\n    let mut rpn_string : String = String::new();\n    let mut rpn_stack : String = String::new();\n    let mut last_token = '#';\n    for token in input.chars(){\n        if token.is_digit(10) {\n            rpn_string.push(token);\n        }\n        else if op_type(token) == 0 {\n            continue;\n        }\n        else if op_type(token) > op_type(last_token) || token == '(' {\n                rpn_stack.push(token);\n                last_token=token;\n        }\n        else {\n            while let Some(top) = rpn_stack.pop() {\n                if top=='(' {\n                    break;\n                }\n                rpn_string.push(top);\n            }\n            if token != ')'{\n                rpn_stack.push(token);\n            }\n        }\n    }\n    while let Some(top) = rpn_stack.pop() {\n        rpn_string.push(top);\n    }\n\n    println!(\"you formula results in {}\", rpn_string);\n\n    *input=rpn_string;\n}\n\nfn calculate(input: &String, list : &mut [u32;4]) -> f32{\n    let mut stack : Vec<f32> = Vec::new();\n    let mut accumulator : f32 = 0.0;\n\n    for token in input.chars(){\n        if token.is_digit(10) {\n            let test = token.to_digit(10).unwrap() as u32;\n            match list.iter().position(|&x| x == test){\n                Some(idx) => list[idx]=10 ,\n                _         => println!(\" invalid digit: {} \",test),\n            }\n            stack.push(accumulator);\n            accumulator = test as f32;\n        }else{\n            let a = stack.pop().unwrap();\n            accumulator = match token {\n                '-' => a-accumulator,\n                '+' => a+accumulator,\n                '\/' => a\/accumulator,\n                '*' => a*accumulator,\n                _ => {accumulator},\/\/NOP\n            };\n        }\n    }\n    println!(\"you formula results in {}\",accumulator);\n    accumulator\n}\n\nfn main() {\n\n    let mut rng = rand::thread_rng();\n    let mut list :[u32;4]=[rng.gen::<u32>()%10,rng.gen::<u32>()%10,rng.gen::<u32>()%10,rng.gen::<u32>()%10];\n\n    println!(\"form 24 with using + - \/ * {:?}\",list);\n    \/\/get user input\n    let mut input = String::new();\n    io::stdin().read_line(&mut input).unwrap();\n    \/\/convert to rpn\n    to_rpn(&mut input);\n    let result = calculate(&input, &mut list);\n\n    if list.iter().any(|&list| list !=10){\n        println!(\"and you used all numbers\");\n        match result {\n            24.0 => println!(\"you won\"),\n            _ => println!(\"but your formulla doesn't result in 24\"),\n        }\n    }else{\n        println!(\"you didn't use all the numbers\");\n    }\n\n}\n\n","human_summarization":"generate and display four random digits between 1 and 9. It then prompts the player to input an arithmetic expression using these digits exactly once each. The program checks and evaluates the expression to see if it equals 24. The allowed operators are multiplication, division, addition, and subtraction. Division should preserve remainders. The program also supports the use of brackets and does not require the digits to be in the same order as given. It does not allow forming multiple digit numbers from the supplied digits. The type of expression evaluator used is not specified and the program does not generate or test the possibility of the expression.","id":2757}
    {"lang_cluster":"Rust","source_code":"\nfn encode(s: &str) -> String {\n    s.chars()\n        \/\/ wrap all values in Option::Some\n        .map(Some)\n        \/\/ add an Option::None onto the iterator to clean the pipeline at the end\n        .chain(std::iter::once(None))\n        .scan((0usize, '\\0'), |(n, c), elem| match elem {\n            Some(elem) if *n == 0 || *c == elem => {\n                \/\/ the run continues or starts here\n                *n += 1;\n                *c = elem;\n                \/\/ this will not have an effect on the final string because it is empty\n                Some(String::new())\n            }\n            Some(elem) => {\n                \/\/ the run ends here\n                let run = format!(\"{}{}\", n, c);\n                *n = 1;\n                *c = elem;\n                Some(run)\n            }\n            None => {\n                \/\/ the string ends here\n                Some(format!(\"{}{}\", n, c))\n            }\n        })\n        \/\/ concatenate together all subresults\n        .collect()\n}\n\nfn decode(s: &str) -> String {\n    s.chars()\n        .fold((0usize, String::new()), |(n, text), c| {\n            if c.is_ascii_digit() {\n                \/\/ some simple number parsing\n                (\n                    n * 10 + c.to_digit(10).expect(\"invalid encoding\") as usize,\n                    text,\n                )\n            } else {\n                \/\/ this must be the character that is repeated\n                (0, text + &format!(\"{}\", c.to_string().repeat(n)))\n            }\n        })\n        .1\n}\n\nfn main() {\n    let text = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\";\n    let encoded = encode(text);\n    let decoded = decode(&encoded);\n\n    println!(\"original: {}\\n encoded: {}\\n decoded: {}\", text, encoded, decoded);\n    assert_eq!(text, decoded);\n}\n\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":2758}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    let s = \"hello\".to_owned();\n    println!(\"{}\", s);\n    \n    let s1 = s + \" world\";\n    println!(\"{}\", s1);\n}\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":2759}
    {"lang_cluster":"Rust","source_code":"\nconst INPUT: &str = \"http:\/\/foo bar\/\";\nconst MAX_CHAR_VAL: u32 = std::char::MAX as u32;\n \nfn main() {\n    let mut buff = [0; 4];\n    println!(\"{}\", INPUT.chars()\n        .map(|ch| {\n            match ch as u32 {\n                0 ..= 47 | 58 ..= 64 | 91 ..= 96 | 123 ..= MAX_CHAR_VAL => {\n                    ch.encode_utf8(&mut buff);\n                    buff[0..ch.len_utf8()].iter().map(|&byte| format!(\"%{:X}\", byte)).collect::<String>()\n                },\n                _ => ch.to_string(),\n            }\n        })\n        .collect::<String>()\n    );\n}\n\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":2760}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    let items: [(&str, f32, u8); 9] = [\n        (\"beef\", 3.8, 36),\n        (\"pork\", 5.4, 43),\n        (\"ham\", 3.6, 90),\n        (\"greaves\", 2.4, 45),\n        (\"flitch\", 4.0, 30),\n        (\"brawn\", 2.5, 56),\n        (\"welt\", 3.7, 67),\n        (\"salami\", 3.0, 95),\n        (\"sausage\", 5.9, 98),\n    ];\n    let mut weight: f32 = 15.0;\n    let mut values: Vec<(&str, f32, f32)> = Vec::new();\n    for item in &items {\n        values.push((item.0, f32::from(item.2) \/ item.1, item.1));\n    }\n\n    values.sort_by(|a, b| (a.1).partial_cmp(&b.1).unwrap());\n    values.reverse();\n\n    for choice in values {\n        if choice.2 <= weight {\n            println!(\"Grab {:.1} kgs of {}\", choice.2, choice.0);\n            weight -= choice.2;\n            if (choice.2 - weight).abs() < std::f32::EPSILON {\n                return;\n            }\n        } else {\n            println!(\"Grab {:.1} kgs of {}\", weight, choice.0);\n            return;\n        }\n    }\n}\n ","human_summarization":"determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.","id":2761}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::collections::HashMap;\nuse std::fs::File;\nuse std::io::{BufRead,BufReader};\nuse std::borrow::ToOwned;\n\nextern crate unicode_segmentation;\nuse unicode_segmentation::{UnicodeSegmentation};\n\nfn main () {\n    let file = BufReader::new(File::open(\"unixdict.txt\").unwrap());\n    let mut map = HashMap::new();\n    for line in file.lines() {\n        let s = line.unwrap();\n        \/\/Bytes:      let mut sorted = s.trim().bytes().collect::<Vec<_>>();\n        \/\/Codepoints: let mut sorted = s.trim().chars().collect::<Vec<_>>();\n        let mut sorted = s.trim().graphemes(true).map(ToOwned::to_owned).collect::<Vec<_>>();\n        sorted.sort();\n\n        map.entry(sorted).or_insert_with(Vec::new).push(s);\n    }\n\n    if let Some(max_len) = map.values().map(|v| v.len()).max() {\n        for anagram in map.values().filter(|v| v.len() == max_len) {\n            for word in anagram {\n                print!(\"{} \", word);\n            }\n            println!();\n        }\n    }\n}\n\n","human_summarization":"find the largest sets of anagrams from a given word list. It treats two strings as anagrams if they contain the same bytes or codepoints. It also maps each ASCII character to a prime number to create a unique identifier for each anagram.","id":2762}
    {"lang_cluster":"Rust","source_code":"fn main() {\n    for i in 0..4 {\n        println!(\"\\nN={}\", i);\n        println!(\"{}\", sierpinski_carpet(i));\n    }\n}\n\nfn sierpinski_carpet(n: u32) -> String {\n    let mut carpet = vec![\"#\".to_string()];\n    for _ in 0..n {\n        let mut top: Vec<_> = carpet.iter().map(|x| x.repeat(3)).collect();\n        let middle: Vec<_> = carpet\n            .iter()\n            .map(|x| x.to_string() + &x.replace(\"#\", \" \") + x)\n            .collect();\n        let bottom = top.clone();\n\n        top.extend(middle);\n        top.extend(bottom);\n        carpet = top;\n    }\n    carpet.join(\"\\n\")\n}\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":2763}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::collections::BTreeMap;\nuse std::collections::binary_heap::BinaryHeap;\n\n#[derive(Debug, Eq, PartialEq)]\nenum NodeKind {\n    Internal(Box<Node>, Box<Node>),\n    Leaf(char),\n}\n\n#[derive(Debug, Eq, PartialEq)]\nstruct Node {\n    frequency: usize,\n    kind: NodeKind,\n}\n\nimpl Ord for Node {\n    fn cmp(&self, rhs: &Self) -> std::cmp::Ordering {\n        rhs.frequency.cmp(&self.frequency)\n    }\n}\n\nimpl PartialOrd for Node {\n    fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> {\n        Some(self.cmp(&rhs))\n    }\n}\n\ntype HuffmanCodeMap = BTreeMap<char, Vec<u8>>;\n\nfn main() {\n    let text = \"this is an example for huffman encoding\";\n\n    let mut frequencies = BTreeMap::new();\n    for ch in text.chars() {\n        *frequencies.entry(ch).or_insert(0) += 1;\n    }\n\n    let mut prioritized_frequencies = BinaryHeap::new();\n    for counted_char in frequencies {\n        prioritized_frequencies.push(Node {\n            frequency: counted_char.1,\n            kind: NodeKind::Leaf(counted_char.0),\n        });\n    }\n\n    while prioritized_frequencies.len() > 1 {\n        let left_child = prioritized_frequencies.pop().unwrap();\n        let right_child = prioritized_frequencies.pop().unwrap();\n        prioritized_frequencies.push(Node {\n            frequency: right_child.frequency + left_child.frequency,\n            kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)),\n        });\n    }\n\n    let mut codes = HuffmanCodeMap::new();\n    generate_codes(\n        prioritized_frequencies.peek().unwrap(),\n        vec![0u8; 0],\n        &mut codes,\n    );\n\n    for item in codes {\n        print!(\"{}: \", item.0);\n        for bit in item.1 {\n            print!(\"{}\", bit);\n        }\n        println!();\n    }\n}\n\nfn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) {\n    match node.kind {\n        NodeKind::Internal(ref left_child, ref right_child) => {\n            let mut left_prefix = prefix.clone();\n            left_prefix.push(0);\n            generate_codes(&left_child, left_prefix, out_codes);\n\n            let mut right_prefix = prefix;\n            right_prefix.push(1);\n            generate_codes(&right_child, right_prefix, out_codes);\n        }\n        NodeKind::Leaf(ch) => {\n            out_codes.insert(ch, prefix);\n        }\n    }\n}\n\n\n\u00a0: 110\na: 1001\nc: 101010\nd: 10001\ne: 1111\nf: 1011\ng: 101011\nh: 0101\ni: 1110\nl: 01110\nm: 0011\nn: 000\no: 0010\np: 01000\nr: 01001\ns: 0110\nt: 01111\nu: 10100\nx: 10000\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It creates a priority queue of nodes for each symbol, constructs a binary tree based on the frequency of occurrence, and assigns binary codes to each character. The more frequently a character appears, the fewer bits are used in its encoding. The codes are displayed as a table.","id":2764}
    {"lang_cluster":"Rust","source_code":"\nLibrary: iced\nuse iced::{ \/\/ 0.2.0\n    button, Button, Column, Element, Length,\n    Text, Sandbox, Settings, Space,\n};\n\n#[derive(Debug, Copy, Clone)]\nstruct Pressed;\nstruct Simple {\n    value: i32,\n    button: button::State,\n}\n\nimpl Sandbox for Simple {\n    type Message = Pressed;\n\n    fn new() -> Simple {\n        Simple {\n            value: 0,\n            button: button::State::new(),\n        }\n    }\n\n    fn title(&self) -> String {\n        \"Simple Windowed Application\".into()\n    }\n\n    fn view(&mut self) -> Element<Self::Message> {\n        Column::new()\n            .padding(20)\n            .push({\n                let text = match self.value {\n                    0 => \"there have been no clicks yet\".into(),\n                    1 => \"there has been 1 click\".into(),\n                    n => format!(\"there have been {} clicks\", n),\n                };\n                Text::new(text).size(24)\n            }).push(\n                Space::with_height(Length::Fill)\n            ).push(\n                Button::new(&mut self.button, Text::new(\"Click Me!\"))\n                    .on_press(Pressed)\n            ).into()\n    }\n\n    fn update(&mut self, _: Self::Message) {\n        self.value += 1;\n    }\n}\n\nfn main() {\n    let mut settings = Settings::default();\n    settings.window.size = (600, 400);\n    Simple::run(settings).unwrap();\n}\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":2765}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    for i in (0..=10).rev() {\n        println!(\"{}\", i);\n    }\n}\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":2766}
    {"lang_cluster":"Rust","source_code":"\nuse std::ascii::AsciiExt;\n\nstatic A: u8 = 'A' as u8;\n\nfn uppercase_and_filter(input: &str) -> Vec<u8> {\n    let alphabet = b\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n    let mut result = Vec::new();\n\n    for c in input.chars() {\n        \/\/ Ignore anything that is not in our short list of chars. We can then safely cast to u8.\n        if alphabet.iter().any(|&x| x as char == c) {\n            result.push(c.to_ascii_uppercase() as u8);\n        }\n    }\n\n    return result;\n}\n\nfn vigenere(key: &str, text: &str, is_encoding: bool) -> String {\n\n    let key_bytes = uppercase_and_filter(key);\n    let text_bytes = uppercase_and_filter(text);\n\n    let mut result_bytes = Vec::new();\n\n    for (i, c) in text_bytes.iter().enumerate() {\n        let c2 = if is_encoding {\n            (c + key_bytes[i % key_bytes.len()] - 2 * A) % 26 + A\n        } else {\n            (c + 26 - key_bytes[i % key_bytes.len()]) % 26 + A\n        };\n        result_bytes.push(c2);\n    }\n\n    String::from_utf8(result_bytes).unwrap()\n}\n\nfn main() {\n    let text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\";\n    let key = \"VIGENERECIPHER\";\n\n    println!(\"Text: {}\", text);\n    println!(\"Key:  {}\", key);\n\n    let encoded = vigenere(key, text, true);\n    println!(\"Code: {}\", encoded);\n    let decoded = vigenere(key, &encoded, false);\n    println!(\"Back: {}\", decoded);\n}\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":2767}
    {"lang_cluster":"Rust","source_code":"\n\nfn main() {\n  for i in (2..=8).step_by(2) {\n    print!(\"{}\", i);\n  }\n  println!(\"who do we appreciate?!\");\n}\n\nfn main() {\n    let mut i = 2;\n    while i <= 8 {\n        print!(\"{}, \", i);\n        i += 2;\n    }\n    println!(\"who do we appreciate?!\");\n}\n","human_summarization":"demonstrate a for-loop with a step-value greater than one. It also provides an alternative solution that is compatible with Rust 1.28 and earlier versions.","id":2768}
    {"lang_cluster":"Rust","source_code":"\nuse std::f32;\n\nfn harmonic_sum<F>(lo: usize, hi: usize, term: F) -> f32\nwhere\n    F: Fn(f32) -> f32,\n{\n    (lo..hi + 1).fold(0.0, |acc, item| acc + term(item as f32))\n}\n\nfn main() {\n    println!(\"{}\", harmonic_sum(1, 100, |i| 1.0 \/ i));\n}\n\n\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":2769}
    {"lang_cluster":"Rust","source_code":"\nextern crate image;\n\nuse image::{ImageBuffer, Pixel, Rgb};\n\nfn main() {\n    let mut img = ImageBuffer::new(256, 256);\n\n    for x in 0..256 {\n        for y in 0..256 {\n            let pixel = Rgb::from_channels(0, x as u8 ^ y as u8, 0, 0);\n            img.put_pixel(x, y, pixel);\n        }\n    }\n\n    let _ = img.save(\"output.png\");\n}\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":2770}
    {"lang_cluster":"Rust","source_code":"\n\nuse rand::{thread_rng, Rng, rngs::ThreadRng};\n\nconst WIDTH: usize = 16;\nconst HEIGHT: usize = 16;\n\n#[derive(Clone, Copy)]\nstruct Cell {\n    col: usize,\n    row: usize,\n}\n\nimpl Cell {\n    fn from(col: usize, row: usize) -> Cell {\n        Cell {col, row}\n    }\n}\n\nstruct Maze {\n    cells: [[bool; HEIGHT]; WIDTH],         \/\/cell visited\/non visited\n    walls_h: [[bool; WIDTH]; HEIGHT + 1],   \/\/horizontal walls existing\/removed\n    walls_v: [[bool; WIDTH + 1]; HEIGHT],   \/\/vertical walls existing\/removed\n    thread_rng: ThreadRng,                  \/\/Random numbers generator\n}\n\nimpl Maze {\n\n    \/\/\/Inits the maze, with all the cells unvisited and all the walls active\n    fn new() -> Maze {\n        Maze { \n            cells: [[true; HEIGHT]; WIDTH], \n            walls_h: [[true; WIDTH]; HEIGHT + 1],\n            walls_v: [[true; WIDTH + 1]; HEIGHT],\n            thread_rng: thread_rng(),\n        }\n    }\n\n    \/\/\/Randomly chooses the starting cell\n    fn first(&mut self) -> Cell {\n        Cell::from(self.thread_rng.gen_range(0, WIDTH), self.thread_rng.gen_range(0, HEIGHT))\n    }\n\n    \/\/\/Opens the enter and exit doors\n    fn open_doors(&mut self) {\n        let from_top: bool = self.thread_rng.gen();\n        let limit = if from_top { WIDTH } else { HEIGHT };\n        let door = self.thread_rng.gen_range(0, limit);\n        let exit = self.thread_rng.gen_range(0, limit);\n        if from_top { \n            self.walls_h[0][door] = false;\n            self.walls_h[HEIGHT][exit] = false;\n        } else {\n            self.walls_v[door][0] = false;\n            self.walls_v[exit][WIDTH] = false;\n        }\n    }\n\n    \/\/\/Removes a wall between the two Cell arguments\n    fn remove_wall(&mut self, cell1: &Cell, cell2: &Cell) {\n        if cell1.row == cell2.row {\n            self.walls_v[cell1.row][if cell1.col > cell2.col { cell1.col } else { cell2.col }] = false;\n        } else { \n            self.walls_h[if cell1.row > cell2.row { cell1.row } else { cell2.row }][cell1.col] = false;\n        };\n    }\n\n    \/\/\/Returns a random non-visited neighbor of the Cell passed as argument\n    fn neighbor(&mut self, cell: &Cell) -> Option<Cell> {\n        self.cells[cell.col][cell.row] = false;\n        let mut neighbors = Vec::new();\n        if cell.col > 0 && self.cells[cell.col - 1][cell.row] { neighbors.push(Cell::from(cell.col - 1, cell.row)); }\n        if cell.row > 0 && self.cells[cell.col][cell.row - 1] { neighbors.push(Cell::from(cell.col, cell.row - 1)); }\n        if cell.col < WIDTH - 1 && self.cells[cell.col + 1][cell.row] { neighbors.push(Cell::from(cell.col + 1, cell.row)); }\n        if cell.row < HEIGHT - 1 && self.cells[cell.col][cell.row + 1] { neighbors.push(Cell::from(cell.col, cell.row + 1)); }\n        if neighbors.is_empty() {\n            None\n        } else {\n            let next = neighbors.get(self.thread_rng.gen_range(0, neighbors.len())).unwrap();\n            self.remove_wall(cell, next);\n            Some(*next)\n        }\n    }\n\n    \/\/\/Builds the maze (runs the Depth-first search algorithm)\n    fn build(&mut self) {\n        let mut cell_stack: Vec<Cell> = Vec::new();\n        let mut next = self.first();\n        loop {\n            while let Some(cell) = self.neighbor(&next) {\n                cell_stack.push(cell);\n                next = cell;\n            }\n            match cell_stack.pop() {\n                Some(cell) => next = cell,\n                None => break,\n            }\n        }\n    }\n\n    \/\/\/Displays a wall\n    fn paint_wall(h_wall: bool, active: bool) {\n        if h_wall {\n            print!(\"{}\", if active { \"+---\" } else { \"+   \" });\n        } else {\n            print!(\"{}\", if active { \"|   \" } else { \"    \" });\n        }\n    }\n\n    \/\/\/Displays a final wall for a row\n    fn paint_close_wall(h_wall: bool) {\n        if h_wall { println!(\"+\") } else { println!() }\n    }\n\n    \/\/\/Displays a whole row of walls\n    fn paint_row(&self, h_walls: bool, index: usize) {\n        let iter = if h_walls { self.walls_h[index].iter() } else { self.walls_v[index].iter() };\n        for &wall in iter {\n            Maze::paint_wall(h_walls, wall);\n        }\n        Maze::paint_close_wall(h_walls);\n    } \n\n    \/\/\/Paints the maze\n    fn paint(&self) {\n        for i in 0 .. HEIGHT {\n            self.paint_row(true, i);\n            self.paint_row(false, i);\n        }\n        self.paint_row(true, HEIGHT);\n    }\n}\n\nfn main() {\n    let mut maze = Maze::new();\n    maze.build();\n    maze.open_doors();\n    maze.paint();\n}\n\n\n","human_summarization":"The code generates and displays a maze using the Depth-first search algorithm. It begins at a random cell, marks it as visited, and obtains a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, then recursively repeats the process with the neighbor as the new current cell. The code utilizes the rand library for random selections.","id":2771}
    {"lang_cluster":"Rust","source_code":"use num_bigint::BigInt;\n\nfn main() {\n    calc_pi();\n}\n\nfn calc_pi() {\n    let mut q = BigInt::from(1);\n    let mut r = BigInt::from(0);\n    let mut t = BigInt::from(1);\n    let mut k = BigInt::from(1);\n    let mut n = BigInt::from(3);\n    let mut l = BigInt::from(3);\n    let mut first = true;\n    loop {\n        if &q * 4 + &r - &t < &n * &t {\n            print!(\"{}\", n);\n            if first {\n                print!(\".\");\n                first = false;\n            }\n            let nr = (&r - &n * &t) * 10;\n            n = (&q * 3 + &r) * 10 \/ &t - &n * 10;\n            q *= 10;\n            r = nr;\n        } else {\n            let nr = (&q * 2 + &r) * &l;\n            let nn = (&q * &k * 7 + 2 + &r * &l) \/ (&t * &l);\n            q *= &k;\n            t *= &l;\n            l += 2;\n            k += 1;\n            n = nn;\n            r = nr;\n        }\n    }\n}\n\n","human_summarization":"are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.","id":2772}
    {"lang_cluster":"Rust","source_code":"\n\nvec![1, 2, 1, 3, 2] < vec![1, 2, 0, 4, 4, 0, 0, 0]\n\n","human_summarization":"\"Function to compare and order two numerical lists based on lexicographic order, returning true if the first list should be ordered before the second and false otherwise.\"","id":2773}
    {"lang_cluster":"Rust","source_code":"\nfn ack(m: isize, n: isize) -> isize {\n    if m == 0 {\n        n + 1\n    } else if n == 0 {\n        ack(m - 1, 1)\n    } else {\n        ack(m - 1, ack(m, n - 1))\n    }\n}\n\nfn main() {\n    let a = ack(3, 4);\n    println!(\"{}\", a); \/\/ 125\n}\n\nfn ack(m: u64, n: u64) -> u64 {\n\tmatch (m, n) {\n\t\t(0, n) => n + 1,\n\t\t(m, 0) => ack(m - 1, 1),\n\t\t(m, n) => ack(m - 1, ack(m, n - 1)),\n\t}\n}\n","human_summarization":"implement the Ackermann function, a non-primitive recursive function that takes two non-negative arguments and returns a rapidly growing value. The function should ideally support arbitrary precision due to the rapid growth of the function's output.","id":2774}
    {"lang_cluster":"Rust","source_code":"\nconst N: usize = 8;\n\nfn try(mut board: &mut [[bool; N]; N], row: usize, mut count: &mut i64) {\n   if row == N {\n       *count += 1;\n       for r in board.iter() {\n           println!(\"{}\", r.iter().map(|&x| if x {\"x\"} else {\".\"}.to_string()).collect::<Vec<String>>().join(\" \"))\n       }\n       println!(\"\");\n       return\n   }\n   for i in 0..N {\n       let mut ok: bool = true;\n       for j in 0..row {\n           if board[j][i]\n               || i+j >= row && board[j][i+j-row]\n               || i+row < N+j && board[j][i+row-j]\n           { ok = false }\n       }\n       if ok {\n           board[row][i] = true;\n           try(&mut board, row+1, &mut count);\n           board[row][i] = false;\n       }\n   }\n}\n\nfn main() {\n   let mut board: [[bool; N]; N] = [[false; N]; N];\n   let mut count: i64 = 0;\n   try (&mut board, 0, &mut count);\n   println!(\"Found {} solutions\", count)\n}\n\nuse std::collections::LinkedList;\nuse std::iter::IntoIterator;\n\nfn main() {\n    for (n, s) in NQueens::new(8).enumerate() {\n        println!(\"Solution #{}:\\n{}\\n\", n + 1, s.to_string());\n    }\n}\n\nfn permutations<'a, T, I>(collection: I) -> Box<Iterator<Item=LinkedList<T>> + 'a>\n    where I: 'a + IntoIterator<Item=T> + Clone,\n          T: 'a + PartialEq + Copy + Clone {\n    if collection.clone().into_iter().count() == 0 {\n        Box::new(vec![LinkedList::new()].into_iter())\n    }\n    else { \n        Box::new(\n            collection.clone().into_iter().flat_map(move |i| {\n                permutations(collection.clone().into_iter()\n                    .filter(move |&i0| i\u00a0!= i0)\n                    .collect::<Vec<_>>())\n                    .map(move |mut l| {l.push_front(i); l})\n            })\n        )\n    }\n}\n\npub struct NQueens {\n    iterator: Box<Iterator<Item=NQueensSolution>>\n}\n\nimpl NQueens {\n    pub fn new(n: u32) -> NQueens {\n        NQueens {\n            iterator: Box::new(permutations(0..n)\n                .filter(|vec| {\n                    let iter = vec.iter().enumerate();\n                    iter.clone().all(|(col, &row)| {\n                        iter.clone().filter(|&(c,_)| c\u00a0!= col)\n                            .all(|(ocol, &orow)| {\n                            col as i32 - row as i32\u00a0!= \n                                ocol as i32 - orow as i32 &&\n                            col as u32 + row\u00a0!= ocol as u32 + orow \n                        })\n                    })\n                })\n                .map(|vec| NQueensSolution(vec))\n            )\n        }\n    }\n}\n\nimpl Iterator for NQueens {\n    type Item = NQueensSolution;\n    fn next(&mut self) -> Option<NQueensSolution> {\n        self.iterator.next()\n    }\n}\n\npub struct NQueensSolution(LinkedList<u32>);\n\nimpl ToString for NQueensSolution {\n    fn to_string(&self) -> String {\n        let mut str = String::new();\n        for &row in self.0.iter() {\n            for r in 0..self.0.len() as u32 {\n                if r == row {\n                    str.push_str(\"Q \");\n                } else {\n                    str.push_str(\"- \");\n                }\n            }\n            str.push('\\n');\n        }\n        str\n    }\n}\n","human_summarization":"solve the N-queens problem, extending the eight queens puzzle to a NxN board size, and provide the number of solutions for small values of N. The solution uses an iterator yielding the 92 solutions for 8 queens.","id":2775}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    let a_vec = vec![1, 2, 3, 4, 5];\n    let b_vec = vec![6; 5];\n\n    let c_vec = concatenate_arrays(&a_vec, &b_vec);\n\n    println!(\"{:?} ~ {:?} => {:?}\", a_vec, b_vec, c_vec);\n}\n\nfn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {\n    let mut concat = x.to_vec();\n    concat.extend_from_slice(y);\n\n    concat\n}\n\nfn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {\n    x.iter().chain(y).cloned().collect()\n}\n","human_summarization":"demonstrate how to concatenate two arrays in the given programming language, either directly or using iterators.","id":2776}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::cmp;\n\nstruct Item {\n    name: &'static str,\n    weight: usize,\n    value: usize\n}\n\nfn knapsack01_dyn(items: &[Item], max_weight: usize) -> Vec<&Item> {\n    let mut best_value = vec![vec![0; max_weight + 1]; items.len() + 1];\n    for (i, it) in items.iter().enumerate() {\n        for w in 1 .. max_weight + 1 {\n            best_value[i + 1][w] =\n                if it.weight > w {\n                    best_value[i][w]\n                } else {\n                    cmp::max(best_value[i][w], best_value[i][w - it.weight] + it.value)\n                }\n        }\n    }\n\n    let mut result = Vec::with_capacity(items.len());\n    let mut left_weight = max_weight;\n\n    for (i, it) in items.iter().enumerate().rev() {\n        if best_value[i + 1][left_weight] != best_value[i][left_weight] {\n            result.push(it);\n            left_weight -= it.weight;\n        }\n    }\n\n    result\n}\n\n\nfn main () {\n    const MAX_WEIGHT: usize = 400;\n\n    const ITEMS: &[Item] = &[\n        Item { name: \"map\",                    weight: 9,   value: 150 },\n        Item { name: \"compass\",                weight: 13,  value: 35 },\n        Item { name: \"water\",                  weight: 153, value: 200 },\n        Item { name: \"sandwich\",               weight: 50,  value: 160 },\n        Item { name: \"glucose\",                weight: 15,  value: 60 },\n        Item { name: \"tin\",                    weight: 68,  value: 45 },\n        Item { name: \"banana\",                 weight: 27,  value: 60 },\n        Item { name: \"apple\",                  weight: 39,  value: 40 },\n        Item { name: \"cheese\",                 weight: 23,  value: 30 },\n        Item { name: \"beer\",                   weight: 52,  value: 10 },\n        Item { name: \"suntancream\",            weight: 11,  value: 70 },\n        Item { name: \"camera\",                 weight: 32,  value: 30 },\n        Item { name: \"T-shirt\",                weight: 24,  value: 15 },\n        Item { name: \"trousers\",               weight: 48,  value: 10 },\n        Item { name: \"umbrella\",               weight: 73,  value: 40 },\n        Item { name: \"waterproof trousers\",    weight: 42,  value: 70 },\n        Item { name: \"waterproof overclothes\", weight: 43,  value: 75 },\n        Item { name: \"note-case\",              weight: 22,  value: 80 },\n        Item { name: \"sunglasses\",             weight: 7,   value: 20 },\n        Item { name: \"towel\",                  weight: 18,  value: 12 },\n        Item { name: \"socks\",                  weight: 4,   value: 50 },\n        Item { name: \"book\",                   weight: 30,  value: 10 }\n    ];\n\n    let items = knapsack01_dyn(ITEMS, MAX_WEIGHT);\n\n    \/\/ We reverse the order because we solved the problem backward.\n    for it in items.iter().rev() {\n        println!(\"{}\", it.name);\n    }\n\n    println!(\"Total weight: {}\", items.iter().map(|w| w.weight).sum::<usize>());\n    println!(\"Total value: {}\", items.iter().map(|w| w.value).sum::<usize>());\n}\n\n\n","human_summarization":"\"Output: The code solves the 0-1 Knapsack problem by determining the optimal combination of items a tourist can carry in his knapsack without exceeding a total weight of 4kg (400 dag), while maximizing the total value of the items. The solution uses dynamic programming and assumes that only whole units of each item can be taken.\"","id":2777}
    {"lang_cluster":"Rust","source_code":"\nfn a(foo: bool) -> bool {\n    println!(\"a\");\n    foo\n}\n\nfn b(foo: bool) -> bool {\n    println!(\"b\");\n    foo\n}\n\nfn main() {\n    for i in vec![true, false] {\n        for j in vec![true, false] {\n            println!(\"{} and {} == {}\", i, j, a(i) && b(j));\n            println!(\"{} or {} == {}\", i, j, a(i) || b(j));\n            println!();\n        }\n    }\n}\n\n\n","human_summarization":"create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.","id":2778}
    {"lang_cluster":"Rust","source_code":"\n\n\/\/!\n\/\/! morse_code\/src\/main.rs\n\/\/!\n\/\/! Michael G. Cummings\n\/\/! 2019-08-26\n\/\/!\n\/\/! Since Rust doesn't have build-in audio support text output is used.\n\/\/!\n\nuse std::process;\nuse structopt::StructOpt;\nuse morse_code::{Config, Opt, run};\n\n\/\/\/ Core of the command-line binary.\n\/\/\/\n\/\/\/ By default expects input from stdin and outputs resulting morse code to stdout, but can also\n\/\/\/ read and\/or write to files.\n\/\/\/ Use `morse_code --help` for more information about options.\nfn main() {\n    let opts = Opt::from_args();\n    let mut config = Config::new(opts).unwrap_or_else(|err| {\n        eprintln!(\"Problem parsing arguments: {}\", err);\n        process::exit(1);\n    });\n    if let Err(err) = run(&mut config) {\n        eprintln!(\"Application error: {}\", err);\n        process::exit(2);\n    }\n}\n\n\n\/\/!\n\/\/! morse_code\/src\/lib.rs\n\/\/!\n\/\/! Michael G. Cummings\n\/\/! 2019-08-26\n\/\/!\n\n#[macro_use]\nextern crate structopt;\n\nuse std::{fs, io};\nuse std::collections::HashMap;\nuse std::error::Error;\nuse std::path::PathBuf;\n\n\/\/\/ Main library function that does the actual work.\n\/\/\/\n\/\/\/ Each character has one space between them and there are two spaces between words.\n\/\/\/ Unknown characters in the input are replaced with a '#' in the output.\n\/\/\/\npub fn run(config: &mut Config) -> Result<(), Box<dyn Error>> {\n    let mut contents = String::new();\n    config.read.read_to_string(&mut contents)?;\n    let morse_map = init_code_map();\n    let mut result = String::new();\n    for char in contents.trim().to_uppercase().chars() {\n        match morse_map.get(&char) {\n            Some(hash) => {\n                result = result + *hash;\n            }\n            None => { result = result + \"#\" }\n        }\n        result = result + \" \";\n    }\n    config.write.write(result.as_ref())?;\n    Ok(())\n}\n\n\/\/\/ Configuration structure for the input and output streams.\n#[derive(Debug)]\npub struct Config {\n    read: Box<dyn io::Read>,\n    write: Box<dyn io::Write>,\n}\n\nimpl Config {\n    pub fn new(opts: Opt) -> Result<Config, &'static str> {\n        let input: Box<dyn io::Read> = match opts.input {\n            Some(p) => Box::new(fs::File::open(p).unwrap()),\n            None => Box::new(io::stdin()),\n        };\n        let output: Box<dyn io::Write> = match opts.output {\n            Some(p) => Box::new(fs::File::create(p).unwrap()),\n            None => Box::new(io::stdout()),\n        };\n        Ok(Config { read: input, write: output })\n    }\n}\n\n\/\/\/ Structure used to hold command line opts(parameters) of binary.\n\/\/\/\n\/\/\/ Using StructOpt crate to parse command-line parameters\/options.\n\/\/\/\n#[derive(Debug, StructOpt)]\n#[structopt(rename_all = \"kebab-case\", raw(setting = \"structopt::clap::AppSettings::ColoredHelp\"))]\npub struct Opt {\n    \/\/\/ Input file, stdin if not present\n    #[structopt(short, long, parse(from_os_str))]\n    input: Option<PathBuf>,\n    \/\/\/ Output file, stdout if not present\n    #[structopt(short, long, parse(from_os_str))]\n    output: Option<PathBuf>,\n}\n\n\/\/\/ Initialize hash map of characters to morse code as string.\npub fn init_code_map() -> HashMap<char, &'static str> {\n    let mut morse_map: HashMap<char, &str> = HashMap::with_capacity(37);\n    morse_map.insert(' ', \" \");\n    morse_map.insert('A', \"._\");\n    morse_map.insert('B', \"_...\");\n    morse_map.insert('C', \"_._.\");\n    morse_map.insert('D', \"_..\");\n    morse_map.insert('E', \".\");\n    morse_map.insert('F', \".._.\");\n    morse_map.insert('G', \"__.\");\n    morse_map.insert('H', \"....\");\n    morse_map.insert('I', \"..\");\n    morse_map.insert('J', \".___\");\n    morse_map.insert('K', \"_._\");\n    morse_map.insert('L', \"._..\");\n    morse_map.insert('M', \"__\");\n    morse_map.insert('N', \"_.\");\n    morse_map.insert('O', \"___\");\n    morse_map.insert('P', \".__.\");\n    morse_map.insert('Q', \"__._\");\n    morse_map.insert('R', \"._.\");\n    morse_map.insert('S', \"...\");\n    morse_map.insert('T', \"_\");\n    morse_map.insert('U', \".._\");\n    morse_map.insert('V', \"..._\");\n    morse_map.insert('W', \".__\");\n    morse_map.insert('X', \"_.._\");\n    morse_map.insert('Y', \"_.__\");\n    morse_map.insert('Z', \"__..\");\n    morse_map.insert('1', \".____\");\n    morse_map.insert('2', \"..___\");\n    morse_map.insert('3', \"...__\");\n    morse_map.insert('4', \"...._\");\n    morse_map.insert('5', \".....\");\n    morse_map.insert('6', \"_....\");\n    morse_map.insert('7', \"__...\");\n    morse_map.insert('8', \"___..\");\n    morse_map.insert('9', \"____.\");\n    morse_map.insert('0', \"_____\");\n    morse_map\n}\n\n","human_summarization":"generate audible Morse code from a given string and send it to an audio device such as a PC speaker. It handles unknown characters by either ignoring them or indicating them with a different pitch. The original code can be found on GitHub in the main.rs and lib.rs files under the morse_code\/src directory.","id":2779}
    {"lang_cluster":"Rust","source_code":"\n\nuse std::iter::repeat;\n\nfn rec_can_make_word(index: usize, word: &str, blocks: &[&str], used: &mut[bool]) -> bool {\n    let c = word.chars().nth(index).unwrap().to_uppercase().next().unwrap();\n    for i in 0..blocks.len() {\n        if !used[i] && blocks[i].chars().any(|s| s == c) {\n            used[i] = true;\n            if index == 0 || rec_can_make_word(index - 1, word, blocks, used) {\n                return true;\n            }\n            used[i] = false;\n        }\n    }\n    false\n}\n\nfn can_make_word(word: &str, blocks: &[&str]) -> bool {\n    return rec_can_make_word(word.chars().count() - 1, word, blocks, \n                             &mut repeat(false).take(blocks.len()).collect::<Vec<_>>());\n}\n\nfn main() {\n    let blocks = [(\"BO\"), (\"XK\"), (\"DQ\"), (\"CP\"), (\"NA\"), (\"GT\"), (\"RE\"), (\"TG\"), (\"QD\"), (\"FS\"), \n                  (\"JW\"), (\"HU\"), (\"VI\"), (\"AN\"), (\"OB\"), (\"ER\"), (\"FS\"), (\"LY\"), (\"PC\"), (\"ZM\")];\n    let words = [\"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"CONFUSE\"];\n    for word in &words {\n        println!(\"{} -> {}\", word, can_make_word(word, &blocks))\n    }\n}\n\n","human_summarization":"\"Output: The code implements a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and uses a backtracking search algorithm for the task.\"","id":2780}
    {"lang_cluster":"Rust","source_code":"\n\n[dependencies]\nrust-crypto = \"0.2\"\n\n\nextern crate crypto;\n\nuse crypto::digest::Digest;\nuse crypto::md5::Md5;\n\nfn main() {\n    let mut sh = Md5::new();\n    sh.input_str(\"The quick brown fox jumped over the lazy dog's back\");\n    println!(\"{}\", sh.result_str());\n}\n\n","human_summarization":"encode a string using the MD5 algorithm and optionally validate the implementation using the test values in IETF RFC 1321. However, due to known weaknesses in MD5, consider using stronger alternatives like SHA-256 or SHA-3 for production-grade cryptography. If the solution is a library solution, refer to MD5\/Implementation for a scratch implementation.","id":2781}
    {"lang_cluster":"Rust","source_code":"\nfn split(s: &str) -> impl Iterator<Item = u64> + '_ {\n    s.split('.').map(|x| x.parse().unwrap())\n}\n\nfn main() {\n    let mut oids = vec![\n        \"1.3.6.1.4.1.11.2.17.19.3.4.0.10\",\n        \"1.3.6.1.4.1.11.2.17.5.2.0.79\",\n        \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\",\n        \"1.3.6.1.4.1.11150.3.4.0.1\",\n        \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\",\n        \"1.3.6.1.4.1.11150.3.4.0\",\n    ];\n\n    oids.sort_by(|a, b| Iterator::cmp(split(a), split(b)));\n    \n    println!(\"{:#?}\", oids);\n}\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":2782}
    {"lang_cluster":"Rust","source_code":"\nWorks with: Rust 1.0 stable\nuse std::io::prelude::*;\nuse std::net::TcpStream;\n\nfn main() {\n    \/\/ Open a tcp socket connecting to 127.0.0.1:256, no error handling (unwrap)\n    let mut my_stream = TcpStream::connect(\"127.0.0.1:256\").unwrap();\n\n    \/\/ Write 'hello socket world' to the stream, ignoring the result of write\n    let _ = my_stream.write(b\"hello socket world\");\n\n} \/\/ <- my_stream's drop function gets called, which closes the socket\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":2783}
    {"lang_cluster":"Rust","source_code":"\nfn main() {\n    for i in 0..std::usize::MAX {\n        println!(\"{:o}\", i);\n    }\n}\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":2784}
    {"lang_cluster":"Rust","source_code":"\n\nfn generic_swap<'a, T>(var1: &'a mut T, var2: &'a mut T) {\n    std::mem::swap(var1, var2)\n}\n\nfn main() {\n    let mut a: String = \"Alice\".to_owned();\n    let mut b: String = \"Bob\".to_owned();\n    let mut c: i32 = 1;\n    let mut d: i32 = 2;\n\n    generic_swap(&mut a, &mut b);\n    generic_swap(&mut c, &mut d);\n\n    println!(\"a={}, b={}\", a, b);\n    println!(\"c={}, d={}\", c, d);\n}\n\n","human_summarization":"implement a generic swap function that exchanges the values of two variables of the same type. The function is applicable in statically typed languages with support for genericity and parametric polymorphism. The function does not support swapping values of variables with different types.","id":2785}
    {"lang_cluster":"Rust","source_code":"\nfn is_palindrome(string: &str) -> bool {\n    let half_len = string.len() \/ 2;\n    string\n        .chars()\n        .take(half_len)\n        .eq(string.chars().rev().take(half_len))\n}\n\nmacro_rules! test {\n    ( $( $x:tt ),* ) => { $( println!(\"'{}': {}\", $x, is_palindrome($x)); )* };\n}\n\nfn main() {\n    test!(\n        \"\",\n        \"a\",\n        \"ada\",\n        \"adad\",\n        \"ingirumimusnocteetconsumimurigni\",\n        \"\u4eba\u4eba\u70ba\u6211,\u6211\u70ba\u4eba\u4eba\",\n        \"\u042f \u0438\u0434\u0443 \u0441 \u043c\u0435\u0447\u0435\u043c, \u0441\u0443\u0434\u0438\u044f\",\n        \"\uc544\ub4e4\ub538\ub4e4\uc544\",\n        \"The quick brown fox\"\n    );\n}\n\n","human_summarization":"The code includes a function that checks if a given sequence of characters is a palindrome. It supports Unicode characters and has an additional function to detect inexact palindromes, ignoring white-space, punctuation, and case. It also includes a method to reverse a string and considers whether the graphemes form a palindrome.","id":2786}
    {"lang_cluster":"Rust","source_code":"\nuse std::env;\n\nfn main() {\n    println!(\"{:?}\", env::var(\"HOME\"));\n    println!();\n    for (k, v) in env::vars().filter(|(k, _)| k.starts_with('P')) {\n        println!(\"{}: {}\", k, v);\n    }\n}\n\n\n","human_summarization":"demonstrate how to retrieve a specific environment variable from a process. The code is compatible with non-utf8 systems by using var_os and vars_os, which produce OsString instead of String. The environment variables available may differ based on the system, with PATH, HOME, and USER being common ones on Unix.","id":2787}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar stack = [];\nstack.push(1)\nstack.push(2,3);\nprint(stack.pop());   \/\/ 3\nprint(stack.length);   \/\/ 2, stack empty if 0\n\n\nfunction Stack() {\n    this.data = new Array();\n\n    this.push  = function(element) {this.data.push(element)}\n    this.pop   = function() {return this.data.pop()}\n    this.empty = function() {return this.data.length == 0}\n    this.peek  = function() {return this.data[this.data.length - 1]}\n}\n\n\nfunction makeStack() {\n  var stack = [];\n\n  var popStack = function () {\n    return stack.pop();\n  };\n  var pushStack = function () {\n    return stack.push.apply(stack, arguments);\n  };\n  var isEmpty = function () {\n    return stack.length === 0;\n  };\n  var peekStack = function () {\n    return stack[stack.length-1];\n  };\n    \n  return {\n    pop: popStack,\n    push: pushStack,\n    isEmpty: isEmpty,\n    peek: peekStack,\n    top: peekStack\n  };\n}\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and is accessed through its top. The code also includes the ability to read or write the topmost element of the stack without modifying it.","id":2788}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction fib(n) {\n  return n<2?n:fib(n-1)+fib(n-2);\n}\n\nfunction fib(n) {\n if (n<2) { return n; } else { return fib(n-1)+fib(n-2); }\n}\n\nfunction fib(n) {\n  return function(n,a,b) {\n    return n>0\u00a0? arguments.callee(n-1,b,a+b)\u00a0: a;\n  }(n,0,1);\n}\nfunction fib(n) {\n  var a = 0, b = 1, t;\n  while (n-- > 0) {\n    t = a;\n    a = b;\n    b += t;\n    console.log(a);\n  }\n  return a;\n}\n\nvar fib = (function(cache){\n    return cache = cache || {}, function(n){\n        if (cache[n]) return cache[n];\n        else return cache[n] = n == 0\u00a0? 0\u00a0: n < 0\u00a0? -fib(-n)\n           \u00a0: n <= 2\u00a0? 1\u00a0: fib(n-2) + fib(n-1);\n    };\n})();\n\n(function () {\n    'use strict';\n\n    function fib(n) {\n        return Array.apply(null, Array(n + 1))\n            .map(function (_, i, lst) {\n                return lst[i] = (\n                    i\u00a0? i < 2\u00a0? 1\u00a0:\n                    lst[i - 2] + lst[i - 1]\u00a0:\n                    0\n                );\n            })[n];\n    }\n\n    return fib(32);\n\n})();\n\n\n","human_summarization":"The code generates the nth Fibonacci number using either an iterative or recursive approach. It defines the Fibonacci sequence and includes an optional support for negative n values. The sequence can be extended into negative numbers using a straightforward inverse of the positive definition. The code also provides access to the whole preceding series and a memoized route to a particular member through an accumulating fold, or a simple fold if needed.","id":2789}
    {"lang_cluster":"JavaScript","source_code":"\nThe standard way is to use the Array.prototype.filter function (Works with: JavaScript version 1.6):\nvar arr = [1,2,3,4,5];\nvar evens = arr.filter(function(a) {return a % 2 == 0});\n\n\nvar arr = [1,2,3,4,5];\nvar evens = [];\nfor (var i=0, ilen=arr.length; i<ilen; i++)\n      if (arr[i] % 2 == 0)\n              evens.push(arr[i]);\n\nWorks with: Firefox version 2.0\nvar numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\nvar evens = [i for (i in numbers) if (i % 2 == 0)];\n\nfunction range(limit) {\n  for(var i = 0; i < limit; i++) {\n    yield i;\n  }\n}\n\nvar evens2 = [i for (i in range(100)) if (i % 2 == 0)];\n\nLibrary: Functional\nFunctional.select(\"+1&1\", [1,2,3,4])   \/\/ [2, 4]\n\n(() => {\n    'use strict';\n\n    \/\/ isEven\u00a0:: Int -> Bool\n    const isEven = n => n % 2 === 0;\n\n\n    \/\/ TEST\n\n    return [1,2,3,4,5,6,7,8,9]\n        .filter(isEven);\n\n    \/\/ [2, 4, 6, 8]\n})();\n\n\n","human_summarization":"select certain elements from an array into a new array in a generic way, specifically even numbers. Optionally, it also provides a destructive filtering solution that modifies the original array instead of creating a new one.","id":2790}
    {"lang_cluster":"JavaScript","source_code":"\n\nsubstr(start, [len]) returns a substring beginning at a specified location and having a specified length.\nsubstring(start, [end]) returns a string containing the substring from start up to, but not including, end.\nvar str = \"abcdefgh\";\n\nvar n = 2;\nvar m = 3;\n\n\/\/  *  starting from n characters in and of m length;\nstr.substr(n, m);  \/\/ => \"cde\"\n\n\/\/  * starting from n characters in, up to the end of the string;\nstr.substr(n);  \/\/ => \"cdefgh\"\nstr.substring(n);  \/\/ => \"cdefgh\"\n\n\/\/  * whole string minus last character;\nstr.substring(0, str.length - 1);  \/\/ => \"abcdefg\"\n\n\/\/  * starting from a known character within the string and of m length;\nstr.substr(str.indexOf('b'), m);  \/\/ => \"bcd\"\n\n\/\/  * starting from a known substring within the string and of m length. \nstr.substr(str.indexOf('bc'), m);  \/\/ => \"bcd\"\n\n\n(function () {\n    'use strict';\n\n    \/\/  take :: Int -> Text -> Text\n    function take(n, s) {\n        return s.substr(0, n);\n    }\n\n    \/\/  drop :: Int -> Text -> Text\n    function drop(n, s) {\n        return s.substr(n);\n    }\n\n\n    \/\/ init :: Text -> Text\n    function init(s) {\n        var n = s.length;\n        return (n > 0 ? s.substr(0, n - 1) : undefined);\n    }\n    \n    \/\/ breakOn :: Text -> Text -> (Text, Text)\n    function breakOn(strPattern, s) {\n        var i = s.indexOf(strPattern);\n        return i === -1 ? [strPattern, ''] : [s.substr(0, i), s.substr(i)];\n    }\n    \n\n    var str = '\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341';\n\n\n    return JSON.stringify({\n    \n        'from n in, of m length': (function (n, m) {\n            return take(m, drop(n, str));\n        })(4, 3),\n        \n        \n        'from n in, up to end' :(function (n) {\n            return drop(n, str);\n        })(3),\n        \n        \n        'all but last' : init(str),\n        \n        \n        'from matching char, of m length' : (function (pattern, s, n) {\n            return take(n, breakOn(pattern, s)[1]);\n        })('\u4e94', str, 3),\n        \n        \n        'from matching string, of m length':(function (pattern, s, n) {\n            return take(n, breakOn(pattern, s)[1]);\n        })('\u516d\u4e03', str, 4)\n        \n    }, null, 2);\n\n})();\n\n\n","human_summarization":"The code extracts substrings from a given string in various ways: starting from a specific character index and of a certain length, starting from a specific character index up to the end of the string, excluding the last character of the string, starting from a known character or substring within the string and of a certain length. The code supports any valid Unicode code point and references logical characters, not 8-bit or 16-bit code units. It does not support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":2791}
    {"lang_cluster":"JavaScript","source_code":"\n\nexample = 'Tux \ud83d\udc27 penguin';\n\n\/\/ array expansion operator\n[...example].reverse().join('') \/\/ 'niugnep \ud83d\udc27 xuT'\n\/\/ split regexp separator with Unicode mode\nexample.split(\/(?:)\/u).reverse().join('') \/\/ 'niugnep \ud83d\udc27 xuT'\n\n\/\/ do not use\nexample.split('').reverse().join(''); \/\/ 'niugnep \\udc27\\ud83d xuT'\n\na = \"\\u{1F466}\\u{1F3FB}\\u{1f44b}\"; \/\/ '\ud83d\udc66\ud83c\udffb\ud83d\udc4b'\n\n\/\/ wrong behavior - ASCII sequences\na.split('').reverse().join(''); \/\/ '\\udc4b\ud83c\udc66\\ud83d'\n\n\/\/ wrong behavior - Unicode code points\n[...a].reverse().join(''); \/\/ '\ud83d\udc4b\ud83c\udffb\ud83d\udc66'\na.split(\/(?:)\/u).reverse().join(''); \/\/ '\ud83d\udc4b\ud83c\udffb\ud83d\udc66'\n\n\/\/ correct behavior - Unicode graphemes\n[...new Intl.Segmenter().segment(a)].map(x => x.segment).reverse().join('') \/\/ \ud83d\udc4b\ud83d\udc66\ud83c\udffb\n\/\/using chained methods\nfunction reverseStr(s) {\n  return s.split('').reverse().join('');\n}\n\n\/\/fast method using for loop\nfunction reverseStr(s) {\n  for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }\n  return o;\n}\n\n\/\/fast method using while loop (faster with long strings in some browsers when compared with for loop)\nfunction reverseStr(s) {\n  var i = s.length, o = '';\n  while (i--) o += s[i];\n  return o;\n}\n(() => {\n\n    \/\/ .reduceRight() can be useful when reversals\n    \/\/ are composed with some other process\n\n    let reverse1 = s => Array.from(s)\n        .reduceRight((a, x) => a + (x\u00a0!== ' '\u00a0? x\u00a0: ' <- '), ''),\n\n        \/\/ but ( join . reverse . split ) is faster for\n        \/\/ simple string reversals in isolation\n\n        reverse2 = s => s.split('').reverse().join('');\n\n\n    return [reverse1, reverse2]\n        .map(f => f(\"Some string to be reversed\"));\n\n})();\n\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, \"asdf\" is reversed to \"fdsa\" and \"as\u20dddf\u0305\" is reversed to \"f\u0305ds\u20dda\". The code handles the reversal of Unicode strings properly, including emojis or diacritics, by enumerating over graphemes.","id":2792}
    {"lang_cluster":"JavaScript","source_code":"\n\nconst dijkstra = (edges,source,target) => {\n    const Q = new Set(),\n          prev = {},\n          dist = {},\n          adj = {}\n\n    const vertex_with_min_dist = (Q,dist) => {\n        let min_distance = Infinity,\n            u = null\n\n        for (let v of Q) {\n            if (dist[v] < min_distance) {\n                min_distance = dist[v]\n                u = v\n            }\n        }\n        return u\n    }\n\n    for (let i=0;i<edges.length;i++) {\n        let v1 = edges[i][0], \n            v2 = edges[i][1],\n            len = edges[i][2]\n\n        Q.add(v1)\n        Q.add(v2)\n\n        dist[v1] = Infinity\n        dist[v2] = Infinity\n\n        if (adj[v1] === undefined) adj[v1] = {}\n        if (adj[v2] === undefined) adj[v2] = {}\n\n        adj[v1][v2] = len\n        adj[v2][v1] = len\n    }\n     \n    dist[source] = 0\n\n    while (Q.size) {\n        let u = vertex_with_min_dist(Q,dist),\n            neighbors = Object.keys(adj[u]).filter(v=>Q.has(v)) \/\/Neighbor still in Q \n\n        Q.delete(u)\n\n        if (u===target) break \/\/Break when the target has been found\n\n        for (let v of neighbors) {\n            let alt = dist[u] + adj[u][v]\n            if (alt < dist[v]) {\n                dist[v] = alt\n                prev[v] = u\n            }\n        }\n    }\n\n    {\n        let u = target,\n        S = [u],\n        len = 0\n            \n        while (prev[u] !== undefined) {\n            S.unshift(prev[u])\n            len += adj[u][prev[u]]\n            u = prev[u]\n        }\n        return [S,len]\n    }   \n}\n\n\/\/Testing algorithm\nlet graph = []\ngraph.push([\"a\", \"b\", 7])\ngraph.push([\"a\", \"c\", 9])\ngraph.push([\"a\", \"f\", 14])\ngraph.push([\"b\", \"c\", 10])\ngraph.push([\"b\", \"d\", 15])\ngraph.push([\"c\", \"d\", 11])\ngraph.push([\"c\", \"f\", 2])\ngraph.push([\"d\", \"e\", 6])\ngraph.push([\"e\", \"f\", 9])\n\nlet [path,length] = dijkstra(graph, \"a\", \"e\");\nconsole.log(path) \/\/[ 'a', 'c', 'f', 'e' ]\nconsole.log(length) \/\/20\n\n","human_summarization":"Implement Dijkstra's algorithm to find the shortest path from a single source to all other vertices in a directed and weighted graph. The graph is represented by an adjacency matrix or list, and a starting node. The algorithm outputs a set of edges depicting the shortest path to each destination node. The program also interprets the output to display the shortest path from the starting node to specific nodes.","id":2793}
    {"lang_cluster":"JavaScript","source_code":"\nfunction tree(less, val, more) {\n  return {\n    depth: 1+Math.max(less.depth, more.depth),\n    less: less,\n    val: val,\n    more: more,\n  };\n}\n\nfunction node(val) {\n  return tree({depth: 0}, val, {depth: 0});\n}\n\nfunction insert(x,y) {\n  if (0 == y.depth) return x;\n  if (0 == x.depth) return y;\n  if (1 == x.depth && 1 == y.depth) {\n    switch (Math.sign(y.val)-x.val) {\n      case -1: return tree(y, x.val, {depth: 0});\n      case 0: return y;\n      case 1: return tree(x, y.val, {depth: 0});\n    }\n  }\n  switch (Math.sign(y.val-x.val)) {\n    case -1: return balance(insert(x.less, y), x.val, x.more);\n    case 0: return balance(insert(x.less, y.less), x.val, insert(x.more, y.more));\n    case 1: return balance(x.less. x.val, insert(x.more, y));\n  }\n}\n\nfunction balance(less,val,more) {\n  if (2 > Math.abs(less.depth-more.depth))\n    return tree(less,val,more);\n  if (more.depth > less.depth) {\n    if (more.more.depth >= more.less.depth) {\n      \/\/ 'more' was heavy\n      return moreHeavy(less, val, more);\n    } else {\n      return moreHeavy(less,val,lessHeavy(more.less, more.val, more.more));\n    }\n  } else {\n    if(less.less.depth >= less.more.depth) {\n      return lessHeavy(less, val, more);\n    } else {\n      return lessHeavy(moreHeavy(less.less, less.val, less.more), val, more);\n    }\n  }\n}\n\nfunction moreHeavy(less,val,more) {\n  return tree(tree(less,val,more.less), more.val, more.more)\n}\n\nfunction lessHeavy(less,val,more) {\n  return tree(less.less, less.val, tree(less.more, val, more));\n}\n\nfunction remove(val, y) {\n  switch (y.depth) {\n    case 0: return y;\n    case 1:\n      if (val == y.val) {\n        return y.less;\n      } else {\n        return y;\n      }\n    default:\n      switch (Math.sign(y.val - val)) {\n        case -1: return balance(y.less, y.val, remove(val, y.more));\n        case  0: return insert(y.less, y.more);\n        case  1: return balance(remove(val, y.less), y.val, y.more)\n      }\n  }\n}\n\nfunction lookup(val, y) {\n  switch (y.depth) {\n    case 0: return y;\n    case 1: if (val == y.val) {\n      return y;\n    } else {\n      return {depth: 0};\n    }\n    default: \n      switch (Math.sign(y.val-val)) {\n        case -1: return lookup(val, y.more);\n        case  0: return y;\n        case  1: return lookup(val, y.less);\n      }\n  }\n}\n\n\nfunction dumptree(t) {\n  switch (t.depth) {\n    case 0: return '';\n    case 1: return t.val;\n    default: return '('+dumptree(t.less)+','+t.val+','+dumptree(t.more)+')';\n  }\n}\nfunction example() {\n  let t= node(0);\n  for (let j= 1; j<20; j++) {\n    t= insert(node(j), t);\n  }\n  console.log(dumptree(t));\n  t= remove(2, t);\n  console.log(dumptree(t));\n  console.log(dumptree(lookup(5, t)));\n  console.log(dumptree(remove(5, t)));\n}\n\nexample();\n\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree. It ensures the heights of the two child subtrees of any node differ by at most one. It supports operations such as lookup, insertion, and deletion in O(log n) time. The tree may require rebalancing through tree rotations after insertions and deletions. Duplicate node keys are not allowed. The AVL tree is compared with red-black trees and is faster for lookup-intensive applications.","id":2794}
    {"lang_cluster":"JavaScript","source_code":"\nconst hDist = (p1, p2) => Math.hypot(...p1.map((e, i) => e - p2[i])) \/ 2;\nconst pAng = (p1, p2) => Math.atan(p1.map((e, i) => e - p2[i]).reduce((p, c) => c \/ p, 1));\nconst solveF = (p, r) => t => [r*Math.cos(t) + p[0], r*Math.sin(t) + p[1]];\nconst diamPoints = (p1, p2) => p1.map((e, i) => e + (p2[i] - e) \/ 2);\n\nconst findC = (...args) => {\n  const [p1, p2, s] = args;\n  const solve = solveF(p1, s);\n  const halfDist = hDist(p1, p2);\n\n  let msg = `p1: ${p1}, p2: ${p2}, r:${s} Result: `;\n  switch (Math.sign(s - halfDist)) {\n    case 0:\n      msg += s ? `Points on diameter. Circle at: ${diamPoints(p1, p2)}` :\n        'Radius Zero';\n      break;\n    case 1:\n      if (!halfDist) {\n        msg += 'Coincident point. Infinite solutions';\n      }\n      else {\n        let theta = pAng(p1, p2);\n        let theta2 = Math.acos(halfDist \/ s);\n        [1, -1].map(e => solve(theta + e * theta2)).forEach(\n          e => msg += `Circle at ${e} `);\n      }\n      break;\n    case -1:\n      msg += 'No intersection. Points further apart than circle diameter';\n      break;\n  }\n  return msg;\n};\n\n\n[\n  [[0.1234, 0.9876], [0.8765, 0.2345], 2.0],\n  [[0.0000, 2.0000], [0.0000, 0.0000], 1.0],\n  [[0.1234, 0.9876], [0.1234, 0.9876], 2.0],\n  [[0.1234, 0.9876], [0.8765, 0.2345], 0.5],\n  [[0.1234, 0.9876], [0.1234, 0.9876], 0.0]\n].forEach((t,i) => console.log(`Test: ${i}: ${findC(...t)}`));\n\n\nTest: 0: p1: 0.1234,0.9876, p2: 0.8765,0.2345, r:2 Result: Circle at 1.8631118016581891,1.974211801658189 Circle at -0.863211801658189,-0.7521118016581889 \nTest: 1: p1: 0,2, p2: 0,0, r:1 Result: Points on diameter. Circle at: 0,1\nTest: 2: p1: 0.1234,0.9876, p2: 0.1234,0.9876, r:2 Result: Coincident point. Infinite solutions\nTest: 3: p1: 0.1234,0.9876, p2: 0.8765,0.2345, r:0.5 Result: No intersection. Points further apart than circle diameter\nTest: 4: p1: 0.1234,0.9876, p2: 0.1234,0.9876, r:0 Result: Radius Zero\n\n","human_summarization":"The code takes two points and a radius as input, and calculates the two possible circles that can be drawn through these points with the given radius. It handles special cases such as when the radius is zero, the points are coincident or form a diameter, or are too far apart. It also provides the output for specific inputs and relates to tasks like calculating the total area of the circles.","id":2795}
    {"lang_cluster":"JavaScript","source_code":"\nconst \u0422\u0430\u0431\u043b\u0438\u0446\u0430_\u0437\u0430\u043c\u0435\u043d = [\n\t[ 4, 10,  9,  2, 13,  8,  0, 14,  6, 11,  1, 12,  7, 15,  5,  3],\n\t[14, 11,  4, 12,  6, 13, 15, 10,  2,  3,  8,  1,  0,  7,  5,  9],\n\t[ 5,  8,  1, 13, 10,  3,  4,  2, 14, 15, 12,  7,  6,  0,  9, 11],\n\t[ 7, 13, 10,  1,  0,  8,  9, 15, 14,  4,  6, 12, 11,  2,  5,  3],\n\t[ 6, 12,  7,  1,  5, 15, 13,  8,  4, 10,  9, 14,  0,  3, 11,  2],\n\t[ 4, 11, 10,  0,  7,  2,  1, 13,  3,  6,  8,  5,  9, 12, 15, 14],\n\t[13, 11,  4,  1,  3, 15,  5,  9,  0, 10, 14,  7,  6,  8,  2, 12],\n\t[ 1, 15, 13,  0,  5,  7, 10,  4,  9,  2,  3, 14,  6, 11,  8, 12]\n];\n\nconst \u041e\u0441\u043d\u043e\u0432\u043d\u043e\u0439_\u0448\u0430\u0433 = (\u0431\u043b\u043e\u043a_\u0442\u0435\u043a\u0441\u0442\u0430, \u044d\u043b\u0435\u043c\u0435\u043d\u0442_\u043a\u043b\u044e\u0447\u0430, \u0422\u0417) => {\n\tconst\n\t\tN = \u0431\u043b\u043e\u043a_\u0442\u0435\u043a\u0441\u0442\u0430.slice(0),\n\t\tS = N[0] + \u044d\u043b\u0435\u043c\u0435\u043d\u0442_\u043a\u043b\u044e\u0447\u0430 & 0xFFFFFFFF;\n\tlet \u043d\u043e\u0432_S = 0;\n\tfor (let \u0441\u0447 = 0; \u0441\u0447 < 4; \u0441\u0447++) {\n\t\tconst \u044f\u0447 = (S >>> (\u0441\u0447 << 3)) & 0xFF;\n\t\t\u043d\u043e\u0432_S +=\n\t\t\t\u0422\u0417[\u0441\u0447 * 2][\u044f\u0447 & 0x0F]\n\t\t\t+ (\u0422\u0417[\u0441\u0447 * 2 + 1][\u044f\u0447 >>> 4] << 4)\n\t\t\t<< (\u0441\u0447 << 3);\n\t}\n\t\u043d\u043e\u0432_S =\n\t\t(\u043d\u043e\u0432_S << 11)\n\t\t+ (\u043d\u043e\u0432_S >>> 21)\n\t\t& 0xFFFFFFFF\n\t\t^ N[1];\n\tN[1] = N[0]; N[0] = \u043d\u043e\u0432_S;\n\treturn N;\n};\n\n\n","human_summarization":"implement the main step of the GOST 28147-89 encryption algorithm, which takes a 64-bit block of text and one of the eight 32-bit encryption key elements, uses a replacement table, and returns an encrypted block. The block of text is represented as an array of two 32-bit values.","id":2796}
    {"lang_cluster":"JavaScript","source_code":"\nfor (;;) {\n  var a = Math.floor(Math.random() * 20);\n  print(a);\n  if (a == 10) \n    break;\n  a = Math.floor(Math.random() * 20);\n  print(a);\n}\n\n\n(function streamTillInitialTen() {\n    var nFirst = Math.floor(Math.random() * 20);\n        \n    console.log(nFirst);\n    \n    if (nFirst === 10) return true;\n    \n    console.log(\n        Math.floor(Math.random() * 20)\n    );\n    \n    return streamTillInitialTen();\n})();\n\n\n18\n10\n16\n10\n8\n0\n13\n3\n2\n14\n15\n17\n14\n7\n10\n8\n0\n2\n0\n2\n5\n16\n3\n16\n6\n7\n19\n0\n16\n9\n7\n11\n17\n10\n\nconsole.log(\n  (function streamTillInitialTen() {\n    var nFirst = Math.floor(Math.random() * 20);\n  \n    if (nFirst === 10) return [10];\n  \n    return [\n      nFirst,\n      Math.floor(Math.random() * 20)\n    ].concat(\n      streamTillInitialTen()\n    );\n  })().join('\\n')\n);\n\n\n17\n14\n3\n4\n13\n10\n15\n5\n10\n","human_summarization":"generates and prints random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":2797}
    {"lang_cluster":"JavaScript","source_code":"\nfunction mersenne_factor(p){\n  var limit, k, q\n  limit = Math.sqrt(Math.pow(2,p) - 1)\n  k = 1\n  while ((2*k*p - 1) < limit){\n    q = 2*k*p + 1\n    if (isPrime(q) && (q % 8 == 1 || q % 8 == 7) && trial_factor(2,p,q)){\n      return q \/\/ q is a factor of 2**p-1\n    }\n    k++\n  }\n  return null\n}\n \nfunction isPrime(value){\n  for (var i=2; i < value; i++){\n    if (value % i == 0){\n      return false\n    }\n    if (value % i != 0){\n      return true;\n\t }\n  }\n}\n \nfunction trial_factor(base, exp, mod){\n  var square, bits\n  square = 1\n  bits = exp.toString(2).split('')\n  for (var i=0,ln=bits.length; i<ln; i++){\n    square = Math.pow(square, 2) * (bits[i] == 1 ? base : 1) % mod\n  }\n  return (square == 1)\n}\n \nfunction check_mersenne(p){\n  var f, result\n  console.log(\"M\"+p+\" = 2^\"+p+\"-1 is \")\n  f = mersenne_factor(p)\n  console.log(f == null ? \"prime\" : \"composite with factor \"+f)\n}\n\n> check_mersenne(3)\n\"M3 = 2**3-1 is prime\"\n> check_mersenne(23)\n\"M23 = 2**23-1 is composite with factor 47\"\n> check_mersenne(929)\n\"M929 = 2**929-1 is composite with factor 13007\"\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":2798}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: Firefox version 2.0\n\/\/create XMLDocument object from file\nvar xhr = new XMLHttpRequest();\nxhr.open('GET', 'file.xml', false);\nxhr.send(null);\nvar doc = xhr.responseXML;\n\n\/\/get first <item> element\nvar firstItem = doc.evaluate( '\/\/item[1]', doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;\nalert( firstItem.textContent );\n\n\/\/output contents of <price> elements\nvar prices = doc.evaluate( '\/\/price', doc, null, XPathResult.ANY_TYPE, null );\nfor( var price = prices.iterateNext(); price != null; price = prices.iterateNext() ) {\n  alert( price.textContent );\n}\n\n\/\/add <name> elements to array\nvar names = doc.evaluate( '\/\/name', doc, null, XPathResult.ANY_TYPE, null);\nvar namesArray = [];\nfor( var name = names.iterateNext(); name != null; name = names.iterateNext() ) {\n  namesArray.push( name );\n}\nalert( namesArray );\n\n\n\/\/create XML object from file\nvar xhr = new XMLHttpRequest();\nxhr.open('GET', 'file.xml', false);\nxhr.send(null);\nvar doc = new XML(xhr.responseText);\n\n\/\/get first <item> element\nvar firstItem = doc..item[0];\nalert( firstItem );\n\n\/\/output contents of <price> elements\nfor each( var price in doc..price ) {\n  alert( price );\n}\n\n\/\/add <name> elements to array\nvar names = [];\nfor each( var name in doc..name ) {\n  names.push( name );\n}\nalert( names );\n\n","human_summarization":"1. Retrieves the first \"item\" element from an XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Generates an array of all the \"name\" elements from the XML document. \nThe XML document is an inventory list from OmniCorp Store.","id":2799}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar set = new Set();\n\nset.add(0);\nset.add(1);\nset.add('two');\nset.add('three');\n\nset.has(0); \/\/=> true\nset.has(3); \/\/=> false\nset.has('two'); \/\/ true\nset.has(Math.sqrt(4)); \/\/=> false\nset.has('TWO'.toLowerCase()); \/\/=> true\n\nset.size; \/\/=> 4\n\nset.delete('two');\nset.has('two'); \/\/==> false\nset.size; \/\/=> 3\n\n\/\/iterating set using ES6 for..of\n\/\/Set order is preserved in order items are added.\nfor (var item of set) {\n  console.log('item is ' + item);\n}\n\n","human_summarization":"The code demonstrates various set operations such as creation, checking if an element is part of a set, performing union, intersection, and difference between two sets, checking if one set is a subset or equal to another set. It also optionally shows other set operations and modifications to a mutable set. The set can be implemented using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also handles the basic test of checking if an element is part of a set. It also mentions that JavaScript does not support native sets before ECMAScript 6.","id":2800}
    {"lang_cluster":"JavaScript","source_code":"\nfor (var year = 2008; year <= 2121; year++){\n    var xmas = new Date(year, 11, 25)\n    if ( xmas.getDay() === 0 )\n        console.log(year)\n}\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":2801}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction unique(ary) {\n    \/\/ concat() with no args is a way to clone an array\n    var u = ary.concat().sort();\n    for (var i = 1; i < u.length; ) {\n        if (u[i-1] === u[i])\n            u.splice(i,1);\n        else\n            i++;\n    }\n    return u;\n}\n\nvar ary = [1, 2, 3, \"a\", \"b\", \"c\", 2, 3, 4, \"b\", \"c\", \"d\", \"4\"];\nvar uniq = unique(ary);\nfor (var i = 0; i < uniq.length; i++) \n    print(uniq[i] + \"\\t\" + typeof(uniq[i]));\n\n1 - number\n2 - number\n3 - number\n4 - number\n4 - string\na - string\nb - string\nc - string\nd - string\n\nArray.prototype.unique = function() {\n    var u = this.concat().sort();\n    for (var i = 1; i < u.length; ) {\n        if (u[i-1] === u[i])\n            u.splice(i,1);\n        else\n            i++;\n    }\n    return u;\n}\nvar uniq = [1, 2, 3, \"a\", \"b\", \"c\", 2, 3, 4, \"b\", \"c\", \"d\"].unique();\n\n\nArray.prototype.unique = function() {\n   return this.sort().reduce( (a,e) => e === a[a.length-1] ? a : (a.push(e), a), [] )\n}\n\n\nArray.prototype.unique = function() {\n    return [... new Set(this)]\n}\n\n\nfunction uniq(lst) {\n  var u = [],\n    dct = {},\n    i = lst.length,\n    v;\n\n  while (i--) {\n    v = lst[i], dct[v] || (\n      dct[v] = u.push(v)\n    );\n  }\n  u.sort(); \/\/ optional\n  \n  return u;\n}\n\n(function () {\n    'use strict';\n\n    \/\/ nub\u00a0:: [a] -> [a]\n    function nub(xs) {\n\n        \/\/ Eq\u00a0:: a -> a -> Bool\n        function Eq(a, b) {\n            return a === b;\n        }\n\n        \/\/ nubBy\u00a0:: (a -> a -> Bool) -> [a] -> [a]\n        function nubBy(fnEq, xs) {\n            var x = xs.length ? xs[0] : undefined;\n\n            return x !== undefined ? [x].concat(\n                nubBy(fnEq, xs.slice(1)\n                    .filter(function (y) {\n                        return !fnEq(x, y);\n                    }))\n            ) : [];\n        }\n\n        return nubBy(Eq, xs);\n    }\n\n\n    \/\/ TEST\n    \n    return [\n        nub('4 3 2 8 0 1 9 5 1 7 6 3 9 9 4 2 1 5 3 2'.split(' '))\n        .map(function (x) {\n            return Number(x);\n        }),\n        nub('chthonic eleemosynary paronomasiac'.split(''))\n        .join('')\n    ]\n\n})();\n\n\n","human_summarization":"implement three different methods to remove duplicate elements from an array. The first method uses a hash table, the second one sorts the elements and removes consecutive duplicates, and the third one iterates through the list and discards any element if it appears again. The code also includes the use of strict equality operator, reduce and arrow functions, sets and spread operator, and hash table for homogenous arrays. Additionally, it allows for customised definitions of equality and duplication.","id":2802}
    {"lang_cluster":"JavaScript","source_code":"\nfunction sort(array, less) {\n\n  function swap(i, j) {\n    var t = array[i];\n    array[i] = array[j];\n    array[j] = t;\n  }\n\n  function quicksort(left, right) {\n\n    if (left < right) {\n      var pivot = array[left + Math.floor((right - left) \/ 2)],\n          left_new = left,\n          right_new = right;\n\n      do {\n        while (less(array[left_new], pivot)) {\n          left_new += 1;\n        }\n        while (less(pivot, array[right_new])) {\n          right_new -= 1;\n        }\n        if (left_new <= right_new) {\n          swap(left_new, right_new);\n          left_new += 1;\n          right_new -= 1;\n        }\n      } while (left_new <= right_new);\n\n      quicksort(left, right_new);\n      quicksort(left_new, right);\n\n    }\n  }\n\n  quicksort(0, array.length - 1);\n\n  return array;\n}\n\nExample:var test_array = [10, 3, 11, 15, 19, 1];\nvar sorted_array = sort(test_array, function(a,b) { return a<b; });\n\n\n","human_summarization":"implement the quicksort algorithm to sort an array or list. The algorithm works by selecting a pivot element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then recursively sorted. The codes also include optimized variants of quicksort and a comparison with merge sort. The task does not specify whether to allocate new arrays or sort in place, or how to choose the pivot element.","id":2803}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar now = new Date(),\n    weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],\n    months   = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],\n    fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' + now.getDate(),\n    fmt2 = weekdays[now.getDay()] + ', ' + months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear();\nconsole.log(fmt1);\nconsole.log(fmt2);\n\n2010-1-12\nTuesday, January 12, 2010\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\". Note that JavaScript does not have built-in strftime-type functionality.","id":2804}
    {"lang_cluster":"JavaScript","source_code":"\n\nWorks with: SpiderMonkey\nfunction powerset(ary) {\n    var ps = [[]];\n    for (var i=0; i < ary.length; i++) {\n        for (var j = 0, len = ps.length; j < len; j++) {\n            ps.push(ps[j].concat(ary[i]));\n        }\n    }\n    return ps;\n}\n\nvar res = powerset([1,2,3,4]);\n\nload('json2.js');\nprint(JSON.stringify(res));\n\n\n","human_summarization":"The code takes a set S as input and generates the power set of S. It can handle edge cases such as an empty set and a set containing only the empty set. The code also demonstrates that the language supports these last two power sets.","id":2805}
    {"lang_cluster":"JavaScript","source_code":"var roman = {\n    map: [\n        1000, 'M', 900, 'CM', 500, 'D', 400, 'CD', 100, 'C', 90, 'XC',\n        50, 'L', 40, 'XL', 10, 'X', 9, 'IX', 5, 'V', 4, 'IV', 1, 'I',\n    ],\n    int_to_roman: function(n) {\n        var value = '';\n        for (var idx = 0; n > 0 && idx < this.map.length; idx += 2) {\n            while (n >= this.map[idx]) {\n                value += this.map[idx + 1];\n                n -= this.map[idx];\n            }\n        }\n        return value;\n    }\n}\n\nroman.int_to_roman(1999); \/\/ \"MCMXCIX\"\n\n(function () {\n    'use strict';\n\n\n    \/\/ If the Roman is a string, pass any delimiters through\n\n    \/\/ (Int | String) -> String\n    function romanTranscription(a) {\n        if (typeof a === 'string') {\n            var ps = a.split(\/\\d+\/),\n                dlm = ps.length > 1 ? ps[1] : undefined;\n\n            return (dlm ? a.split(dlm)\n                    .map(function (x) {\n                        return Number(x);\n                    }) : [a])\n                .map(roman)\n                .join(dlm);\n        } else return roman(a);\n    }\n\n    \/\/ roman\u00a0:: Int -> String\n    function roman(n) {\n        return [[1000, \"M\"], [900, \"CM\"], [500, \"D\"], [400, \"CD\"], [100,\n        \"C\"], [90, \"XC\"], [50, \"L\"], [40, \"XL\"], [10, \"X\"], [9,\n        \"IX\"], [5, \"V\"], [4, \"IV\"], [1, \"I\"]]\n            .reduce(function (a, lstPair) {\n                var m = a.remainder,\n                    v = lstPair[0];\n\n                return (v > m ? a : {\n                    remainder: m % v,\n                    roman: a.roman + Array(\n                            Math.floor(m \/ v) + 1\n                        )\n                        .join(lstPair[1])\n                });\n            }, {\n                remainder: n,\n                roman: ''\n            }).roman;   \n    }\n\n    \/\/ TEST\n\n    return [2016, 1990, 2008, \"14.09.2015\", 2000, 1666].map(\n        romanTranscription);\n\n})();\n\n\n","human_summarization":"The code implements a function that converts a positive integer input into its corresponding Roman numeral representation. The function expresses each digit separately, starting from the leftmost digit and ignoring any zeroes. For example, it converts 1990 to MCMXC, 2008 to MMVIII, and 1666 to MDCLXVI.","id":2806}
    {"lang_cluster":"JavaScript","source_code":"\n\n\/\/ Create a new array with length 0\nvar myArray = new Array();\n\n\/\/ Create a new array with length 5\nvar myArray1 = new Array(5);\n\n\/\/ Create an array with 2 members (length is 2) \nvar myArray2 = new Array(\"Item1\",\"Item2\");\n\n\/\/ Create an array with 2 members using an array literal\nvar myArray3 = [\"Item1\", \"Item2\"];\n\n\/\/ Assign a value to member [2] (length is now 3)\nmyArray3[2] = 5;\n\nvar x = myArray[2] + myArray.length;   \/\/ 8\n\n\/\/ You can also add a member to an array with the push function (length is now 4)\nmyArray3.push('Test');\n\n\/\/ Elisions are supported, but are buggy in some implementations\nvar y = [0,1,,];  \/\/ length 3, or 4 in buggy implementations\n","human_summarization":"demonstrate the basic syntax of arrays in JavaScript. They include creating an array, assigning a value to it, and retrieving an element. Both fixed-length and dynamic arrays are shown, with a value being pushed into the dynamic array. The codes also illustrate how JavaScript arrays are objects that inherit from the Array prototype, with a special length property and methods. The Array constructor's behavior based on the number of arguments provided is also demonstrated.","id":2807}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: JScript\nvar fso = new ActiveXObject(\"Scripting.FileSystemObject\");\nvar ForReading = 1, ForWriting = 2;\nvar f_in = fso.OpenTextFile('input.txt', ForReading);\nvar f_out = fso.OpenTextFile('output.txt', ForWriting, true);\n\n\/\/ for small files: \n\/\/ f_out.Write( f_in.ReadAll() );\n\nwhile ( ! f_in.AtEndOfStream) {\n    \/\/ ReadLine() does not include the newline char\n    f_out.WriteLine( f_in.ReadLine() );\n}\n\nf_in.Close();\nf_out.Close();\n\n\nWorks with: Node.js\nvar fs = require('fs');\nrequire('util').pump(fs.createReadStream('input.txt', {flags:'r'}), fs.createWriteStream('output.txt', {flags:'w+'}));\n\n","human_summarization":"demonstrate how to read contents from \"input.txt\" file into a variable and then write these contents into a new file called \"output.txt\".","id":2808}
    {"lang_cluster":"JavaScript","source_code":"\nalert( \"alphaBETA\".toUpperCase() );\nalert( \"alphaBETA\".toLowerCase() );\n\n\nALPHABETA\nalphabeta\n\nWorks with: NJS version  0.2.5\nvar string = \"alphaBETA\";\nvar uppercase = string.toUpperCase();\nvar lowercase = string.toLowerCase();\n\n","human_summarization":"demonstrate the conversion of a string \"alphaBETA\" to upper-case and lower-case using the default encoding of a string literal or plain ASCII. The code also showcases additional case conversion functions that might be present in the language's library, such as swapping case or capitalizing the first letter. Note that in some languages, the functions toLower and toUpper may not be reversible.","id":2809}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction distance(p1, p2) {\n  var dx = Math.abs(p1.x - p2.x);\n  var dy = Math.abs(p1.y - p2.y);\n  return Math.sqrt(dx*dx + dy*dy);\n}\n\nfunction bruteforceClosestPair(arr) {\n  if (arr.length < 2) {\n    return Infinity;\n  } else {\n    var minDist = distance(arr[0], arr[1]);\n    var minPoints = arr.slice(0, 2);\n    \n    for (var i=0; i<arr.length-1; i++) {\n      for (var j=i+1; j<arr.length; j++) {\n        if (distance(arr[i], arr[j]) < minDist) {\n          minDist = distance(arr[i], arr[j]);\n          minPoints = [ arr[i], arr[j] ];\n        }\n      }\n    }\n    return {\n      distance: minDist,\n      points: minPoints\n    };\n  }\n}\n\n\nvar Point = function(x, y) {\n\tthis.x = x;\n\tthis.y = y;\n};\nPoint.prototype.getX = function() {\n\treturn this.x;\n};\nPoint.prototype.getY = function() {\n\treturn this.y;\n};\n\nvar mergeSort = function mergeSort(points, comp) {\n\tif(points.length < 2) return points;\n\n\n\tvar n = points.length,\n\t\ti = 0,\n\t\tj = 0,\n\t\tleftN = Math.floor(n \/ 2),\n\t\trightN = leftN;\n\n\n\tvar leftPart = mergeSort( points.slice(0, leftN), comp),\n\t\trightPart = mergeSort( points.slice(rightN), comp );\n\n\tvar sortedPart = [];\n\n\twhile((i < leftPart.length) && (j < rightPart.length)) {\n\t\tif(comp(leftPart[i], rightPart[j]) < 0) {\n\t\t\tsortedPart.push(leftPart[i]);\n\t\t\ti += 1;\n\t\t}\n\t\telse {\n\t\t\tsortedPart.push(rightPart[j]);\n\t\t\tj += 1;\n\t\t}\n\t}\n\twhile(i < leftPart.length) {\n\t\tsortedPart.push(leftPart[i]);\n\t\ti += 1;\n\t}\n\twhile(j < rightPart.length) {\n\t\tsortedPart.push(rightPart[j]);\n\t\tj += 1;\n\t}\n\treturn sortedPart;\n};\n\nvar closestPair = function _closestPair(Px, Py) {\n\tif(Px.length < 2) return { distance: Infinity, pair: [ new Point(0, 0), new Point(0, 0) ] };\n\tif(Px.length < 3) {\n\t\t\/\/find euclid distance\n\t\tvar d = Math.sqrt( Math.pow(Math.abs(Px[1].x - Px[0].x), 2) + Math.pow(Math.abs(Px[1].y - Px[0].y), 2) );\n\t\treturn {\n\t\t\tdistance: d,\n\t\t\tpair: [ Px[0], Px[1] ]\n\t\t};\n\t}\n\n\tvar\tn = Px.length,\n\t\tleftN = Math.floor(n \/ 2),\n\t\trightN = leftN;\n\n\tvar Xl = Px.slice(0, leftN),\n\t\tXr = Px.slice(rightN),\n\t\tXm = Xl[leftN - 1],\n\t\tYl = [],\n\t\tYr = [];\n\t\/\/separate Py\n\tfor(var i = 0; i < Py.length; i += 1) {\n\t\tif(Py[i].x <= Xm.x)\n\t\t\tYl.push(Py[i]);\n\t\telse\n\t\t\tYr.push(Py[i]);\n\t}\n\n\tvar dLeft = _closestPair(Xl, Yl),\n\t\tdRight = _closestPair(Xr, Yr);\n\n\tvar minDelta = dLeft.distance,\n\t\tclosestPair = dLeft.pair;\n\tif(dLeft.distance > dRight.distance) {\n\t\tminDelta = dRight.distance;\n\t\tclosestPair = dRight.pair;\n\t}\n\n\n\t\/\/filter points around Xm within delta (minDelta)\n\tvar closeY = [];\n\tfor(i = 0; i < Py.length; i += 1) {\n\t\tif(Math.abs(Py[i].x - Xm.x) < minDelta) closeY.push(Py[i]);\n\t}\n\t\/\/find min within delta. 8 steps max\n\tfor(i = 0; i < closeY.length; i += 1) {\n\t\tfor(var j = i + 1; j < Math.min( (i + 8), closeY.length ); j += 1) {\n\t\t\tvar d = Math.sqrt( Math.pow(Math.abs(closeY[j].x - closeY[i].x), 2) + Math.pow(Math.abs(closeY[j].y - closeY[i].y), 2) );\n\t\t\tif(d < minDelta) {\n\t\t\t\tminDelta = d;\n\t\t\t\tclosestPair = [ closeY[i], closeY[j] ]\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tdistance: minDelta,\n\t\tpair: closestPair\n\t};\n};\n\n\nvar points = [\n\tnew Point(0.748501, 4.09624),\n\tnew Point(3.00302, 5.26164),\n\tnew Point(3.61878,  9.52232),\n\tnew Point(7.46911,  4.71611),\n\tnew Point(5.7819,   2.69367),\n\tnew Point(2.34709,  8.74782),\n\tnew Point(2.87169,  5.97774),\n\tnew Point(6.33101,  0.463131),\n\tnew Point(7.46489,  4.6268),\n\tnew Point(1.45428,  0.087596)\n];\n\nvar sortX = function (a, b) { return (a.x < b.x) ? -1 : ((a.x > b.x) ? 1 : 0); }\nvar sortY = function (a, b) { return (a.y < b.y) ? -1 : ((a.y > b.y) ? 1 : 0); }\n\nvar Px = mergeSort(points, sortX);\nvar Py = mergeSort(points, sortY);\n\nconsole.log(JSON.stringify(closestPair(Px, Py))) \/\/ {\"distance\":0.0894096443343775,\"pair\":[{\"x\":7.46489,\"y\":4.6268},{\"x\":7.46911,\"y\":4.71611}]}\n\nvar points2 = [new Point(37100, 13118), new Point(37134, 1963), new Point(37181, 2008), new Point(37276, 21611), new Point(37307, 9320)];\n\nPx = mergeSort(points2, sortX);\nPy = mergeSort(points2, sortY);\n\nconsole.log(JSON.stringify(closestPair(Px, Py))); \/\/ {\"distance\":65.06919393998976,\"pair\":[{\"x\":37134,\"y\":1963},{\"x\":37181,\"y\":2008}]}\n\n","human_summarization":"The code provides two methods to solve the Closest Pair of Points problem in a two-dimensional space. The first method, bruteForceClosestPair, uses a brute force approach with a time complexity of O(n^2). It iterates over each pair of points to find the pair with the minimum distance. The second method, closestPair, uses a divide-and-conquer approach with a time complexity of O(n log n). It sorts the points by x and y coordinates, then recursively divides the problem into smaller subproblems to find the closest pair of points. Both methods return the minimum distance and the pair of points.","id":2810}
    {"lang_cluster":"JavaScript","source_code":"\nvar array = [];\narray.push('abc');\narray.push(123);\narray.push(new MyClass);\nconsole.log( array[2] );\n\nvar obj = {};\nobj['foo'] = 'xyz'; \/\/equivalent to: obj.foo = 'xyz';\nobj['bar'] = new MyClass; \/\/equivalent to: obj.bar = new MyClass;\nobj['1x; ~~:-b'] = 'text'; \/\/no equivalent\nconsole.log(obj['1x; ~~:-b']);\n\n","human_summarization":"Create and populate a collection in a statically-typed language. Review and ensure the code examples meet the task requirements.","id":2811}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar gold = { 'value': 2500, 'weight': 2.0, 'volume': 0.002 },\n    panacea = { 'value': 3000, 'weight': 0.3, 'volume': 0.025 },\n    ichor = { 'value': 1800, 'weight': 0.2, 'volume': 0.015 },\n    \n    items = [gold, panacea, ichor],\n    knapsack = {'weight': 25, 'volume': 0.25},\n    max_val = 0,\n    solutions = [],\n    g, p, i, item, val;\n    \nfor (i = 0; i < items.length; i += 1) {\n    item = items[i];\n    item.max = Math.min(\n        Math.floor(knapsack.weight \/ item.weight),\n        Math.floor(knapsack.volume \/ item.volume)\n    );\n}\n \nfor (g = 0; g <= gold.max; g += 1) {\n    for (p = 0; p <= panacea.max; p += 1) {\n        for (i = 0; i <= ichor.max; i += 1) {\n            if (i * ichor.weight + g * gold.weight + p * panacea.weight > knapsack.weight) {\n                continue;\n            }\n            if (i * ichor.volume + g * gold.volume + p * panacea.volume > knapsack.volume) {\n                continue;\n            }\n            val = i * ichor.value + g * gold.value + p * panacea.value;\n            if (val > max_val) {\n                solutions = [];\n                max_val = val;\n            }\n            if (val === max_val) {\n                solutions.push([g, p, i]);\n            }\n        }\n    }\n}\n \ndocument.write(\"maximum value: \" + max_val + '<br>');\nfor (i = 0; i < solutions.length; i += 1) {\n    item = solutions[i];\n    document.write(\"(gold: \" + item[0] + \", panacea: \" + item[1] + \", ichor: \" + item[2] + \")<br>\");\n}\n\noutput:\n<pre>maximum value: 54500\n(gold: 11, panacea: 0, ichor: 15)\n(gold: 11, panacea: 3, ichor: 10)\n(gold: 11, panacea: 6, ichor: 5)\n(gold: 11, panacea: 9, ichor: 0)<\/pre>\n\n","human_summarization":"\"Determines the maximum value of items a traveler can carry in his knapsack, given a weight limit of 25 and volume limit of 0.25. The items include panacea, ichor, and gold, each with their respective values, weights, and volumes. The solution utilizes a brute force approach to find the optimal combination of items that maximizes the total value while adhering to the weight and volume constraints. The code returns the quantity of each item to be taken.\"","id":2812}
    {"lang_cluster":"JavaScript","source_code":"\nfunction loop_plus_half(start, end) {\n    var str = '',\n        i;\n    for (i = start; i <= end; i += 1) {\n        str += i;\n        if (i === end) {\n          break;\n        }\n        str += ', ';\n    }\n    return str;\n}\n \nalert(loop_plus_half(1, 10));\n\n\nfunction range(m, n) {\n  return Array.apply(null, Array(n - m + 1)).map(\n    function (x, i) {\n      return m + i;\n    }\n  );\n}\n \nconsole.log(\n  range(1, 10).join(', ')\n);\n\n\n1, 2, 3, 4, 5, 6, 7, 8, 9, 10\n\n\nfunction range(m, n) {\n  return Array.apply(null, Array(n - m + 1)).map(function (x, i) {\n    return m + i;\n  });\n}\n\nconsole.log(\n  (function (nFrom, nTo) {\n    var iLast = nTo - 1;\n\n    return range(nFrom, nTo).reduce(\n      function (accumulator, n, i) {\n        return accumulator +\n          n.toString() +\n\n          (i < iLast ? ', ' : ''); \/\/ conditional sub-expression\n\n      }, ''\n    )\n  })(1, 10)\n);\n\n\n1, 2, 3, 4, 5, 6, 7, 8, 9, 10\n\nvar s=1, e=10\nfor (var i=s; i<=e; i+=1) {\n\tdocument.write( i==s ? '' : ', ', i )\n}\n\n\nvar s=1, e=10\nfor (;; s+=1) {\n\tdocument.write( s )\n\tif (s==e) break\n\tdocument.write( ', ' )\n}\n\n\n","human_summarization":"demonstrate how to generate a comma-separated list of integers from 1 to 10 using a loop. The loop uses separate output statements for the number and the comma. It also handles special transitional cases at the end of the pattern by defining conditional values for one or more sub-expressions. Alternatively, the code can map an array of integers to a comma-delimited string using the Array.join() function in JavaScript.","id":2813}
    {"lang_cluster":"JavaScript","source_code":"\nconst libs =\n  `des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n  dw01             ieee dw01 dware gtech\n  dw02             ieee dw02 dware\n  dw03             std synopsys dware dw03 dw02 dw01 ieee gtech\n  dw04             dw04 ieee dw01 dware gtech\n  dw05             dw05 ieee dware\n  dw06             dw06 ieee dware\n  dw07             ieee dware\n  dware            ieee dware\n  gtech            ieee gtech\n  ramlib           std ieee\n  std_cell_lib     ieee std_cell_lib\n  synopsys`;\n\n\/\/ A map of the input data, with the keys as the packages, and the values as\n\/\/ and array of packages on which it depends.\nconst D = libs\n  .split('\\n')\n  .map(e => e.split(' ').filter(e => e != ''))\n  .reduce((p, c) =>\n    p.set(c[0], c.filter((e, i) => i > 0 && e !== c[0] ? e : null)), new Map());\n[].concat(...D.values()).forEach(e => {\n  D.set(e, D.get(e) || [])\n});\n\n\/\/ The above map rotated so that it represents a DAG of the form\n\/\/ Map {\n\/\/    A => [ A, B, C],\n\/\/    B => [C],\n\/\/    C => []\n\/\/ }\n\/\/ where each key represents a node, and the array contains the edges.\nconst G = [...D.keys()].reduce((p, c) =>\n  p.set(\n    c,\n    [...D.keys()].filter(e => D.get(e).includes(c))),\n  new Map()\n);\n\n\/\/ An array of leaf nodes; nodes with 0 in degrees.\nconst Q = [...D.keys()].filter(e => D.get(e).length == 0);\n\n\/\/ The result array.\nconst S = [];\nwhile (Q.length) {\n  const u = Q.pop();\n  S.push(u);\n  G.get(u).forEach(v => {\n    D.set(v, D.get(v).filter(e => e !== u));\n    if (D.get(v).length == 0) {\n      Q.push(v);\n    }\n  });\n}\n\nconsole.log('Solution:', S);\n\n\nSolution: [\n  'ieee',\n  'std_cell_lib',\n  'gtech',\n  'dware',\n  'dw07',\n  'dw06',\n  'dw05',\n  'dw02',\n  'dw01',\n  'dw04',\n  'std',\n  'ramlib',\n  'synopsys',\n  'dw03',\n  'des_system_lib' ]\n\n","human_summarization":"\"Implement a function that performs a topological sort on VHDL libraries based on their dependencies. The function returns a valid compile order, ignoring self dependencies and flagging unorderable ones. Libraries with no dependents are also included in the compile order. The function uses Kahn's 1962 topological sort or depth-first search algorithm for sorting.\"","id":2814}
    {"lang_cluster":"JavaScript","source_code":"\nvar stringA = \"tacoloco\"\n  , stringB = \"co\"\n  , q1, q2, q2multi, m\n  , q2matches = []\n\n\/\/ stringA starts with stringB\nq1 = stringA.substring(0, stringB.length) == stringB\n\n\/\/ stringA contains stringB\nq2  = stringA.indexOf(stringB)\n\n\/\/ multiple matches\nq2multi = new RegExp(stringB,'g')\n\nwhile(m = q2multi.exec(stringA)){\n\tq2matches.push(m.index)\n}\n\n\/\/ stringA ends with stringB\nq3 = stringA.substr(-stringB.length) == stringB\n\nconsole.log(\"1: Does '\"+stringA+\"' start with '\"+stringB+\"'? \" + ( q1 ? \"Yes.\" : \"No.\"))\nconsole.log(\"2: Is '\"+stringB+\"' contained in '\"+stringA+\"'? \" + (~q2 ? \"Yes, at index \"+q2+\".\" : \"No.\"))\nif (~q2 && q2matches.length > 1){\n\tconsole.log(\"   In fact, it happens \"+q2matches.length+\" times within '\"+stringA+\"', at index\"+(q2matches.length > 1 ? \"es\" : \"\")+\" \"+q2matches.join(', ')+\".\")\n}\nconsole.log(\"3: Does '\"+stringA+\"' end with '\"+stringB+\"'? \"   + ( q3 ? \"Yes.\" : \"No.\"))\n\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":2815}
    {"lang_cluster":"JavaScript","source_code":"(() => {\n    \"use strict\";\n\n    \/\/ ----------- 4-RINGS OR 4-SQUARES PUZZLE -----------\n\n    \/\/ rings\u00a0:: noRepeatedDigits -> DigitList -> solutions\n    \/\/ rings\u00a0:: Bool -> [Int] -> [[Int]]\n    const rings = uniq =>\n        digits => Boolean(digits.length) ? (\n            () => {\n                const ns = digits.sort(flip(compare));\n\n                \/\/ CENTRAL DIGIT\u00a0:: d\n                return ns.flatMap(\n                    ringTriage(uniq)(ns)\n                );\n            })() : [];\n\n\n    const ringTriage = uniq => ns => d => {\n        const\n            h = head(ns),\n            ts = ns.filter(x => (x + d) <= h);\n\n        \/\/ LEFT OF CENTRE\u00a0:: c and a\n        return (\n            uniq ? (delete_(d)(ts)) : ns\n        )\n        .flatMap(c => {\n            const a = c + d;\n\n            \/\/ RIGHT OF CENTRE\u00a0:: e and g\n            return a > h ? (\n                []\n            ) : (\n                uniq ? (\n                    difference(ts)([d, c, a])\n                ) : ns\n            )\n            .flatMap(subTriage(uniq)([ns, h, a, c, d]));\n        });\n    };\n\n\n    const subTriage = uniq =>\n        ([ns, h, a, c, d]) => e => {\n            const g = d + e;\n\n            return ((g > h) || (\n                uniq && (g === c))\n            ) ? (\n                    []\n                ) : (() => {\n                    const\n                        agDelta = a - g,\n                        bfs = uniq ? (\n                            difference(ns)([\n                                d, c, e, g, a\n                            ])\n                        ) : ns;\n\n                    \/\/ MID LEFT, MID RIGHT\u00a0:: b and f\n                    return bfs.flatMap(b => {\n                        const f = b + agDelta;\n\n                        return (bfs).includes(f) && (\n                            !uniq || ![\n                                a, b, c, d, e, g\n                            ].includes(f)\n                        ) ? ([\n                                [a, b, c, d, e, f, g]\n                            ]) : [];\n                    });\n                })();\n        };\n\n    \/\/ ---------------------- TEST -----------------------\n    const main = () => unlines([\n        \"rings(true, enumFromTo(1,7))\\n\",\n        unlines(\n            rings(true)(\n                enumFromTo(1)(7)\n            ).map(show)\n        ),\n\n        \"\\nrings(true, enumFromTo(3, 9))\\n\",\n        unlines(\n            rings(true)(\n                enumFromTo(3)(9)\n            ).map(show)\n        ),\n\n        \"\\nlength(rings(false, enumFromTo(0, 9)))\\n\",\n        rings(false)(\n            enumFromTo(0)(9)\n        )\n        .length\n        .toString(),\n        \"\"\n    ]);\n\n\n    \/\/ ---------------- GENERIC FUNCTIONS ----------------\n\n    \/\/ compare\u00a0:: a -> a -> Ordering\n    const compare = (a, b) =>\n        a < b ? -1 : (a > b ? 1 : 0);\n\n\n    \/\/ delete\u00a0:: Eq a => a -> [a] -> [a]\n    const delete_ = x => {\n        \/\/ xs with first instance of x (if any) removed.\n        const go = xs =>\n            Boolean(xs.length) ? (\n                (x === xs[0]) ? (\n                    xs.slice(1)\n                ) : [xs[0]].concat(go(xs.slice(1)))\n            ) : [];\n\n        return go;\n    };\n\n\n    \/\/ difference\u00a0:: Eq a => [a] -> [a] -> [a]\n    const difference = xs =>\n        ys => {\n            const s = new Set(ys);\n\n            return xs.filter(x => !s.has(x));\n        };\n\n\n    \/\/ enumFromTo\u00a0:: Int -> Int -> [Int]\n    const enumFromTo = m =>\n        n => Array.from({\n            length: 1 + n - m\n        }, (_, i) => m + i);\n\n\n    \/\/ flip\u00a0:: (a -> b -> c) -> b -> a -> c\n    const flip = op =>\n        \/\/ The binary function op with\n        \/\/ its arguments reversed.\n        1 !== op.length ? (\n            (a, b) => op(b, a)\n        ) : (a => b => op(b)(a));\n\n\n    \/\/ head\u00a0:: [a] -> a\n    const head = xs =>\n        \/\/ The first item (if any) in a list.\n        Boolean(xs.length) ? (\n            xs[0]\n        ) : null;\n\n\n    \/\/ show\u00a0:: a -> String\n    const show = x =>\n        JSON.stringify(x);\n\n\n    \/\/ unlines\u00a0:: [String] -> String\n    const unlines = xs =>\n        \/\/ A single string formed by the intercalation\n        \/\/ of a list of strings with the newline character.\n        xs.join(\"\\n\");\n\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":2816}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar sec_old = 0;\nfunction update_clock() {\n\tvar t = new Date();\n\tvar arms = [t.getHours(), t.getMinutes(), t.getSeconds()];\n\tif (arms[2] == sec_old) return;\n\tsec_old = arms[2];\n\n\tvar c = document.getElementById('clock');\n\tvar ctx = c.getContext('2d');\n\tctx.fillStyle = \"rgb(0,200,200)\";\n\tctx.fillRect(0, 0, c.width, c.height);\n\tctx.fillStyle = \"white\";\n\tctx.fillRect(3, 3, c.width - 6, c.height - 6);\n\tctx.lineCap = 'round';\n\n\tvar orig = { x: c.width \/ 2, y: c.height \/ 2 };\n\tarms[1] += arms[2] \/ 60;\n\tarms[0] += arms[1] \/ 60;\n\tdraw_arm(ctx, orig, arms[0] * 30, c.width\/2.5 - 15, c.width \/ 20,  \"green\");\n\tdraw_arm(ctx, orig, arms[1] * 6,  c.width\/2.2 - 10, c.width \/ 30,  \"navy\");\n\tdraw_arm(ctx, orig, arms[2] * 6,  c.width\/2.0 - 6,  c.width \/ 100, \"maroon\");\n}\n\nfunction draw_arm(ctx, orig, deg, len, w, style)\n{\n\tctx.save();\n\tctx.lineWidth = w;\n\tctx.lineCap = 'round';\n\tctx.translate(orig.x, orig.y);\n\tctx.rotate((deg - 90) * Math.PI \/ 180);\n\tctx.strokeStyle = style;\n\tctx.beginPath();\n\tctx.moveTo(-len \/ 10, 0);\n\tctx.lineTo(len, 0);\n\tctx.stroke();\n\tctx.restore();\n}\n\nfunction init_clock() {\n\tvar clock = document.createElement('canvas');\n\tclock.width = 100;\n\tclock.height = 100;\n\tclock.id = \"clock\";\n\tdocument.body.appendChild(clock);\n\n\twindow.setInterval(update_clock, 200);\n}\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <style>\n        canvas {\n            background-color: black;\n        }\n    <\/style>\n<\/head>\n<body>\n    <canvas><\/canvas>\n    <script>\n        var canvas = document.querySelector(\"canvas\");\n        canvas.width = window.innerWidth;\n        canvas.height = window.innerHeight;\n\n        var g = canvas.getContext(\"2d\");\n\n        \/\/ which leds are on or off for each digit\n        var masks = [\"1110111\", \"0010010\", \"1011101\", \"1011011\", \"0111010\",\n            \"1101011\", \"1101111\", \"1010010\", \"1111111\", \"1111011\"];\n\n        \/\/ horizontal and vertical layouts in scalable units\n        var vertices = [\n            [\n                [0, 0], [1, 1], [7, 1], [8, 0], [7, -1], [1, -1]\n            ],\n            [\n                [0, 0], [-1, 1], [-1, 7], [0, 8], [1, 7], [1, 1]\n            ]\n        ];        \n\n        function Led(x, y, idx, ox, oy) {\n            \/\/ starting points in scalable units \n            this.x = x;\n            this.y = y;\n\n            \/\/ horizontal or vertical layout\n            this.idx = idx;\n\n            \/\/ pixel values to create small gaps between the leds\n            this.offset_x = ox;\n            this.offset_y = oy;\n        }\n\n        var leds = [];\n        leds.push(new Led(0, 0, 0, 0, -1));\n        leds.push(new Led(0, 0, 1, -1, 0));\n        leds.push(new Led(8, 0, 1, 1, 0));\n        leds.push(new Led(0, 8, 0, 0, 1));\n        leds.push(new Led(0, 8, 1, -1, 2));\n        leds.push(new Led(8, 8, 1, 1, 2));\n        leds.push(new Led(0, 16, 0, 0, 3));\n\n        var onColor, offColor;\n\n        function drawDigitalClock(color1, color2, size) {\n\n            var clockWidth = (6 * 15 + 2 * 10) * size;\n            var clockHeight = 20 * size;\n            var x = (canvas.width - clockWidth) \/ 2;\n            var y = (canvas.height - clockHeight) \/ 2;\n\n            onColor = color1;\n            offColor = color2;\n\n            g.clearRect(0, 0, canvas.width, canvas.height);\n\n            var date = new Date();\n            var segments = [date.getHours(), date.getMinutes(), date.getSeconds()];\n\n            segments.forEach(function (value, index) {\n                x = drawDigits(x, y, size, value);\n                if (index < 2) {\n                    x = drawSeparator(x, y, size);\n                }\n            });\n        }\n\n        function drawDigits(x, y, size, timeUnit) {\n\n            var digit1 = Math.floor(timeUnit \/ 10);\n            var digit2 = timeUnit % 10;\n\n            x = drawLeds(x, y, size, masks[digit1]);\n            x = drawLeds(x, y, size, masks[digit2]);\n\n            return x;\n        }\n\n        function drawSeparator(x, y, size) {\n\n            g.fillStyle = onColor;\n            g.fillRect(x + 0.5 * size, y + 3 * size, 2 * size, 2 * size);\n            g.fillRect(x + 0.5 * size, y + 10 * size, 2 * size, 2 * size);\n\n            return x + size * 10;\n        }\n\n        function drawLeds(x, y, size, mask) {\n\n            leds.forEach(function (led, i) {\n\n                g.fillStyle = mask[i] == '1' ? onColor : offColor;\n\n                var xx = x + led.x * size + led.offset_x;\n                var yy = y + led.y * size + led.offset_y;\n\n                drawLed(xx, yy, size, vertices[led.idx]);\n            });\n\n            return x + size * 15;\n        }\n\n        function drawLed(x, y, size, vertices) {\n\n            g.beginPath();\n            g.moveTo(x, y);\n\n            vertices.forEach(function (vertex) {\n                g.lineTo(x + vertex[0] * size, y + vertex[1] * size);\n            });\n\n            g.closePath();\n            g.fill();\n        }\n\n        setInterval(drawDigitalClock, 1000, \"#00FF00\", \"#002200\", 12);\n    <\/script>\n\n<\/body>\n<\/html>\n\n","human_summarization":"The code is designed to create a simple, animated time-keeping device. It updates every second in sync with the system clock, without excessively polling system resources. The code is kept concise and clear, and it can be initialized with the function init_clock() after the body load.","id":2817}
    {"lang_cluster":"JavaScript","source_code":"\n\n(() => {\n    \"use strict\";\n\n    \/\/ Arguments: predicate, maximum perimeter\n    \/\/ pythTripleCount\u00a0:: ((Int, Int, Int) -> Bool) -> Int -> Int\n    const pythTripleCount = p =>\n        maxPerim => {\n            const\n                xs = enumFromTo(1)(\n                    Math.floor(maxPerim \/ 2)\n                );\n\n            return xs.flatMap(\n                x => xs.slice(x).flatMap(\n                    y => xs.slice(y).flatMap(\n                        z => ((x + y + z <= maxPerim) &&\n                            ((x * x) + (y * y) === z * z) &&\n                            p(x, y, z)) ? [\n                            [x, y, z]\n                        ] : []\n                    )\n                )\n            ).length;\n        };\n\n    \/\/ ---------------------- TEST -----------------------\n    const main = () => [10, 100, 1000]\n        .map(n => ({\n            maxPerimeter: n,\n            triples: pythTripleCount(() => true)(n),\n            primitives: pythTripleCount(\n                (x, y) => gcd(x)(y) === 1\n            )(n)\n        }));\n\n\n    \/\/ ---------------- GENERIC FUNCTIONS ----------------\n\n    \/\/ abs\u00a0:: Num -> Num\n    const abs =\n        \/\/ Absolute value of a given number\n        \/\/ without the sign.\n        x => 0 > x ? (\n            -x\n        ) : x;\n\n\n    \/\/ enumFromTo\u00a0:: Int -> Int -> [Int]\n    const enumFromTo = m =>\n        n => Array.from({\n            length: 1 + n - m\n        }, (_, i) => m + i);\n\n\n    \/\/ gcd\u00a0:: Integral a => a -> a -> a\n    const gcd = x =>\n        y => {\n            const zero = x.constructor(0);\n            const go = (a, b) =>\n                zero === b ? (\n                    a\n                ) : go(b, a % b);\n\n            return go(abs(x), abs(y));\n        };\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples with a perimeter not exceeding 100 and the number of these that are primitive. It is also optimized to handle large values up to a maximum perimeter of 100,000,000. The code avoids exhaustive search of a full Cartesian product for scalability.","id":2818}
    {"lang_cluster":"JavaScript","source_code":"\n   window.open(\"webpage.html\", \"windowname\", \"width=800,height=600\");\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":2819}
    {"lang_cluster":"JavaScript","source_code":"\n\n(function(txt) {\n\n    var cs = txt.split(''),\n        i = cs.length,\n        dct =  {},\n        c = '',\n        keys;\n        \n    while (i--) {\n        c = cs[i];\n        dct[c] = (dct[c] || 0) + 1;\n    }\n    \n    keys = Object.keys(dct);\n    keys.sort();\n    return keys.map(function (c) { return [c, dct[c]]; });\n\n})(\"Not all that Mrs. Bennet, however, with the assistance of her five\\\ndaughters, could ask on the subject, was sufficient to draw from her\\\nhusband any satisfactory description of Mr. Bingley. They attacked him\\\nin various ways--with barefaced questions, ingenious suppositions, and\\\ndistant surmises; but he eluded the skill of them all, and they were at\\\nlast obliged to accept the second-hand intelligence of their neighbour,\\\nLady Lucas. Her report was highly favourable. Sir William had been\\\ndelighted with him. He was quite young, wonderfully handsome, extremely\\\nagreeable, and, to crown the whole, he meant to be at the next assembly\\\nwith a large party. Nothing could be more delightful! To be fond of\\\ndancing was a certain step towards falling in love; and very lively\\\nhopes of Mr. Bingley's heart were entertained.\");\n\n\n","human_summarization":"Open a text file, count the frequency of each letter, and handle both cases: counting all characters including punctuation and only counting letters A to Z. The code is written in JavaScript, and it can be used in various environments, including Node.js and OS X JavaScript for Automation. It uses core JavaScript (ES5) to count characters once the text has been read from a file system. The code also includes a version that uses an object as a hash-table and the reduce method, but this version does not open a text file. The spread operator is used to get unicode characters instead of UTF-16 code units.","id":2820}
    {"lang_cluster":"JavaScript","source_code":"\nfunction LinkedList(value, next) {\n    this._value = value;\n    this._next = next;\n}\nLinkedList.prototype.value = function() {\n    if (arguments.length == 1) \n        this._value = arguments[0];\n    else\n        return this._value;\n}\nLinkedList.prototype.next = function() {\n    if (arguments.length == 1) \n        this._next = arguments[0];\n    else\n        return this._next;\n}\n\n\/\/ convenience function to assist the creation of linked lists.\nfunction createLinkedListFromArray(ary) {\n    var head = new LinkedList(ary[0], null);\n    var prev = head;\n    for (var i = 1; i < ary.length; i++) {\n        var node = new LinkedList(ary[i], null);\n        prev.next(node);\n        prev = node;\n    }\n    return head;\n}\n\nvar head = createLinkedListFromArray([10,20,30,40]);\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":2821}
    {"lang_cluster":"JavaScript","source_code":"\n\n<html>\n<body>\n<canvas id=\"canvas\" width=\"600\" height=\"500\"><\/canvas>\n\n<script type=\"text\/javascript\">\nvar elem = document.getElementById('canvas');\nvar context = elem.getContext('2d');\n\ncontext.fillStyle = '#C0C0C0';\ncontext.lineWidth = 1;\n\nvar deg_to_rad = Math.PI \/ 180.0;\nvar depth = 9;\n\nfunction drawLine(x1, y1, x2, y2, brightness){\n  context.moveTo(x1, y1);\n  context.lineTo(x2, y2);\n}\n\nfunction drawTree(x1, y1, angle, depth){\n  if (depth !== 0){\n    var x2 = x1 + (Math.cos(angle * deg_to_rad) * depth * 10.0);\n    var y2 = y1 + (Math.sin(angle * deg_to_rad) * depth * 10.0);\n    drawLine(x1, y1, x2, y2, depth);\n    drawTree(x2, y2, angle - 20, depth - 1);\n    drawTree(x2, y2, angle + 20, depth - 1);\n  }\n}\n\ncontext.beginPath();\ndrawTree(300, 500, -90, depth);\ncontext.closePath();\ncontext.stroke();\n<\/script>\n\n<\/body>\n<\/html>\n\n","human_summarization":"Implement a fractal tree using HTML5 canvas element. The code starts by drawing the trunk of the tree, then splits at the end of the trunk to draw two branches. This process is repeated at the end of each branch until a desired level of branching is achieved.","id":2822}
    {"lang_cluster":"JavaScript","source_code":"\nfunction factors(num)\n{\n var\n  n_factors = [],\n  i;\n\n for (i = 1; i <= Math.floor(Math.sqrt(num)); i += 1)\n  if (num % i === 0)\n  {\n   n_factors.push(i);\n   if (num \/ i !== i)\n    n_factors.push(num \/ i);\n  }\n n_factors.sort(function(a, b){return a - b;});  \/\/ numeric sort\n return n_factors;\n}\n\nfactors(45);  \/\/ [1,3,5,9,15,45] \nfactors(53);  \/\/ [1,53] \nfactors(64);  \/\/ [1,2,4,8,16,32,64]\n\n\n\/\/ Monadic bind (chain) for lists\nfunction chain(xs, f) {\n  return [].concat.apply([], xs.map(f));\n}\n\n\/\/ [m..n]\nfunction range(m, n) {\n  return Array.apply(null, Array(n - m + 1)).map(function (x, i) {\n    return m + i;\n  });\n}\n\nfunction factors_naive(n) {\n  return chain( range(1, n), function (x) {       \/\/ monadic chain\/bind\n    return n\u00a0% x\u00a0? []\u00a0: [x];                      \/\/ monadic fail or inject\/return\n  });\n}\n\nfactors_naive(6)\n\n[1, 2, 3, 6]\n\nconsole.log(\n  (function (lstTest) {\n\n    \/\/ INTEGER FACTORS\n    function integerFactors(n) {\n      var rRoot = Math.sqrt(n),\n        intRoot = Math.floor(rRoot),\n\n        lows = range(1, intRoot).filter(function (x) {\n          return (n\u00a0% x) === 0;\n        });\n\n      \/\/ for perfect squares, we can drop the head of the 'highs' list\n      return lows.concat(lows.map(function (x) {\n        return n \/ x;\n      }).reverse().slice((rRoot === intRoot) | 0));\n    }\n\n    \/\/ [m .. n]\n    function range(m, n) {\n      return Array.apply(null, Array(n - m + 1)).map(function (x, i) {\n        return m + i;\n      });\n    }\n\n    \/*************************** TESTING *****************************\/\n\n    \/\/ TABULATION OF RESULTS IN SPACED AND ALIGNED COLUMNS\n    function alignedTable(lstRows, lngPad, fnAligned) {\n      var lstColWidths = range(0, lstRows.reduce(function (a, x) {\n        return x.length > a\u00a0? x.length\u00a0: a;\n      }, 0) - 1).map(function (iCol) {\n        return lstRows.reduce(function (a, lst) {\n          var w = lst[iCol]\u00a0? lst[iCol].toString().length\u00a0: 0;\n          return (w > a)\u00a0? w\u00a0: a;\n        }, 0);\n      });\n\n      return lstRows.map(function (lstRow) {\n        return lstRow.map(function (v, i) {\n          return fnAligned(v, lstColWidths[i] + lngPad);\n        }).join('')\n      }).join('\\n');\n    }\n\n    function alignRight(n, lngWidth) {\n      var s = n.toString();\n      return Array(lngWidth - s.length + 1).join(' ') + s;\n    }\n\n    \/\/ TEST\n    return '\\nintegerFactors(n)\\n\\n' + alignedTable(\n      lstTest.map(integerFactors).map(function (x, i) {\n        return [lstTest[i], '-->'].concat(x);\n      }), 2, alignRight\n    ) + '\\n';\n\n  })([25, 45, 53, 64, 100, 102, 120, 12345, 32766, 32767])\n);\n\nintegerFactors(n)\n\n     25  -->  1   5  25\n     45  -->  1   3   5    9   15    45\n     53  -->  1  53\n     64  -->  1   2   4    8   16    32    64\n    100  -->  1   2   4    5   10    20    25     50  100\n    102  -->  1   2   3    6   17    34    51    102\n    120  -->  1   2   3    4    5     6     8     10   12   15   20   24    30     40     60    120\n  12345  -->  1   3   5   15  823  2469  4115  12345\n  32766  -->  1   2   3    6   43    86   127    129  254  258  381  762  5461  10922  16383  32766\n  32767  -->  1   7  31  151  217  1057  4681  32767\n\n(function (lstTest) {\n    'use strict';\n\n    \/\/ INTEGER FACTORS\n\n    \/\/ integerFactors\u00a0:: Int -> [Int]\n    let integerFactors = (n) => {\n            let rRoot = Math.sqrt(n),\n                intRoot = Math.floor(rRoot),\n\n                lows = range(1, intRoot)\n                .filter(x => (n\u00a0% x) === 0);\n\n            \/\/ for perfect squares, we can drop \n            \/\/ the head of the 'highs' list\n            return lows.concat(lows\n                .map(x => n \/ x)\n                .reverse()\n                .slice((rRoot === intRoot) | 0)\n            );\n        },\n\n        \/\/ range\u00a0:: Int -> Int -> [Int]\n        range = (m, n) => Array.from({\n            length: (n - m) + 1\n        }, (_, i) => m + i);\n\n\n\n\n\n    \/*************************** TESTING *****************************\/\n\n    \/\/ TABULATION OF RESULTS IN SPACED AND ALIGNED COLUMNS\n    let alignedTable = (lstRows, lngPad, fnAligned) => {\n            var lstColWidths = range(\n                    0, lstRows\n                    .reduce(\n                        (a, x) => (x.length > a\u00a0? x.length\u00a0: a),\n                        0\n                    ) - 1\n                )\n                .map((iCol) => lstRows\n                    .reduce((a, lst) => {\n                        let w = lst[iCol]\u00a0? lst[iCol].toString()\n                            .length\u00a0: 0;\n                        return (w > a)\u00a0? w\u00a0: a;\n                    }, 0));\n\n            return lstRows.map((lstRow) =>\n                    lstRow.map((v, i) => fnAligned(\n                        v, lstColWidths[i] + lngPad\n                    ))\n                    .join('')\n                )\n                .join('\\n');\n        },\n\n        alignRight = (n, lngWidth) => {\n            let s = n.toString();\n            return Array(lngWidth - s.length + 1)\n                .join(' ') + s;\n        };\n\n    \/\/ TEST\n    return '\\nintegerFactors(n)\\n\\n' + alignedTable(lstTest\n        .map(integerFactors)\n        .map(\n            (x, i) => [lstTest[i], '-->'].concat(x)\n        ), 2, alignRight\n    ) + '\\n';\n\n})([25, 45, 53, 64, 100, 102, 120, 12345, 32766, 32767]);\n\n","human_summarization":"calculate the factors of a positive integer. The factors are the positive integers that can divide the given number to yield a positive integer. It excludes the handling of factors for zero and negative integers. The code also acknowledges that every prime number has two factors: 1 and itself. The code is a translation from a Haskell example using a list monad for comprehension.","id":2823}
    {"lang_cluster":"JavaScript","source_code":"\nvar justification=\"center\",\ninput=[\"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n\"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n\"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n\"column$are$separated$by$at$least$one$space.\",\n\"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n\"justified,$right$justified,$or$center$justified$within$its$column.\"],\nx,y,cols,max,cols=0,diff,left,right\n\nString.prototype.repeat=function(n){return new Array(1 + parseInt(n)).join(this);}\n\nfor(x=0;x<input.length;x++) {\n input[x]=input[x].split(\"$\");\n if(input[x].length>cols) cols=input[x].length;\n}\nfor(x=0;x<cols;x++) {\n max=0;\n for(y=0;y<input.length;y++) if(input[y][x]&&max<input[y][x].length) max=input[y][x].length;\n for(y=0;y<input.length;y++) \n  if(input[y][x]) {\n   diff=(max-input[y][x].length)\/2;\n   left=\" \".repeat(Math.floor(diff));\n   right=\" \".repeat(Math.ceil(diff));\n   if(justification==\"left\") {right+=left;left=\"\"}\n   if(justification==\"right\") {left+=right;right=\"\"}\n   input[y][x]=left+input[y][x]+right;\n  }\n}\nfor(x=0;x<input.length;x++) input[x]=input[x].join(\" \");\ninput=input.join(\"\\n\");\ndocument.write(input);\n\n\/\/break up each string by '$'. The assumption is that the user wants the trailing $.\nvar data = [\n  \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n  \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n  \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n  \"column$are$separated$by$at$least$one$space.\",\n  \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n  \"justified,$right$justified,$or$center$justified$within$its$column.\"\n].map(function (str) { return str.split('$'); })\n\n\/\/boilerplate: get longest array or string in array\nvar getLongest = function (arr) {\n  return arr.reduce(function (acc, item) { return acc.length > item.length ? acc : item; }, 0);\n};\n\n\/\/boilerplate: this function would normally be in a library like underscore, lodash, or ramda\nvar zip = function (items, toInsert) {\n  toInsert = (toInsert === undefined) ? null : toInsert;\n  var longestItem = getLongest(items);\n  return longestItem.map(function (_unused, index) {\n    return items.map(function (item) {\n      return item[index] === undefined ? toInsert : item[index];\n    });\n  });\n};\n\n\/\/here's the part that's not boilerplate\nvar makeColumns = function (formatting, data) {\n  var zipData = zip(data, '');\n  var makeSpaces = function (num) { return new Array(num + 1).join(' '); };\n  var formattedCols = zipData.map(function (column) {\n    var maxLen = getLongest(column).length;\/\/find the maximum word length\n    if (formatting === 'left') {\n      return column.map(function (word) { return word + makeSpaces(maxLen - word.length); });\n    } else if (formatting === 'right') {\n      return column.map(function (word) { return makeSpaces(maxLen - word.length) + word; });\n    } else {\n      return column.map(function (word) {\n        var spaces = maxLen - word.length,\n            first = ~~(spaces \/ 2),\n            last = spaces - first;\n        return makeSpaces(first) + word + makeSpaces(last);\n      });\n    }\n  });\n\n  return zip(formattedCols).map(function (row) { return row.join(' '); }).join('\\n');\n};\n\n\n(function (strText) {\n    'use strict';\n \n    \/\/ [[a]] -> [[a]]\n    function transpose(lst) {\n        return lst[0].map(function (_, iCol) {\n            return lst.map(function (row) {\n                return row[iCol];\n            })\n        });\n    }\n \n    \/\/ (a -> b -> c) -> [a] -> [b] -> [c]\n    function zipWith(f, xs, ys) {\n        return xs.length === ys.length ? (\n            xs.map(function (x, i) {\n                return f(x, ys[i]);\n            })\n        ) : undefined;\n    }\n \n    \/\/ (a -> a -> Ordering) -> [a] -> a \n    function maximumBy(f, xs) {\n        return xs.reduce(function (a, x) {\n            return a === undefined ? x : (\n                f(x) > f(a) ? x : a\n            );\n        }, undefined)\n    }\n \n    \/\/ [String] -> String\n    function widest(lst) {\n        return maximumBy(length, lst)\n            .length;\n    }\n \n    \/\/ [[a]] -> [[a]]\n    function fullRow(lst, n) {\n        return lst.concat(Array.apply(null, Array(n - lst.length))\n            .map(function () {\n                return ''\n            }));\n    }\n \n    \/\/ String -> Int -> String\n    function nreps(s, n) {\n        var o = '';\n        if (n < 1) return o;\n        while (n > 1) {\n            if (n & 1) o += s;\n            n >>= 1;\n            s += s;\n        }\n        return o + s;\n    }\n \n    \/\/ [String] -> String\n    function unwords(xs) {\n        return xs.join('  ');\n    }\n \n    \/\/ [String] -> String\n    function unlines(xs) {\n        return xs.join('\\n');\n    }\n \n    \/\/ [a] -> Int\n    function length(xs) {\n        return xs.length;\n    }\n \n    \/\/ -- Int -> [String] -> [[String]]\n    function padWords(n, lstWords, eAlign) {\n        return lstWords.map(function (w) {\n            var lngPad = n - w.length;\n \n            return (\n                    (eAlign === eCenter) ? (function () {\n                        var lngHalf = Math.floor(lngPad \/ 2);\n \n                        return [\n                            nreps(' ', lngHalf), w,\n                            nreps(' ', lngPad - lngHalf)\n                        ];\n                    })() : (eAlign === eLeft) ? \n                        ['', w, nreps(' ', lngPad)] :\n                        [nreps(' ', lngPad), w, '']\n                )\n                .join('');\n        });\n    }\n \n    \/\/ MAIN\n \n    var eLeft = -1,\n        eCenter = 0,\n        eRight = 1;\n \n    var lstRows = strText.split('\\n')\n        .map(function (x) {\n            return x.split('$');\n        }),\n \n        lngCols = widest(lstRows),\n        lstCols = transpose(lstRows.map(function (r) {\n            return fullRow(r, lngCols)\n        })),\n        lstColWidths = lstCols.map(widest);\n \n    \/\/ THREE PARAGRAPHS, WITH VARIOUS WORD COLUMN ALIGNMENTS:\n \n    return [eLeft, eRight, eCenter]\n        .map(function (eAlign) {\n            var fPad = function (n, lstWords) {\n                return padWords(n, lstWords, eAlign);\n            };\n \n            return transpose(\n                    zipWith(fPad, lstColWidths, lstCols)\n                )\n                .map(unwords);\n        })\n        .map(unlines)\n        .join('\\n\\n');\n \n})(\n    \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\\n\\\nare$delineated$by$a$single$'dollar'$character,$write$a$program\\n\\\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\\n\\\ncolumn$are$separated$by$at$least$one$space.\\n\\\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\\n\\\njustified,$right$justified,$or$center$justified$within$its$column.\"\n);\n\n\n","human_summarization":"The code reads a text file where fields within a line are separated by a dollar character. It then aligns each column of fields by ensuring at least one space between words in each column. The words in a column can be left justified, right justified, or center justified. The minimum space between columns is determined from the text and not hard-coded. The code handles trailing dollar characters and insignificant consecutive spaces at the end of lines. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":2824}
    {"lang_cluster":"JavaScript","source_code":"<!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n    <meta charset=\"UTF-8\">\n    <style>\n        canvas {\n            background-color: black;\n        }\n    <\/style>\n<\/head>\n<body>\n    <canvas><\/canvas>\n    <script>\n        var canvas = document.querySelector(\"canvas\");\n        canvas.width = window.innerWidth;\n        canvas.height = window.innerHeight;\n\n        var g = canvas.getContext(\"2d\");\n\n        canvas.addEventListener(\"mousemove\", function (event) {\n            prevMouseX = mouseX;\n            prevMouseY = mouseY;\n            mouseX = event.x;\n            mouseY = event.y;\n\n            var incrX = (mouseX - prevMouseX) * 0.01;\n            var incrY = (mouseY - prevMouseY) * 0.01;\n\n            rotateCuboid(incrX, incrY);\n            drawCuboid();\n        });\n\n        var nodes = [[-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1],\n        [1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1]];\n\n        var edges = [[0, 1], [1, 3], [3, 2], [2, 0], [4, 5], [5, 7], [7, 6],\n        [6, 4], [0, 4], [1, 5], [2, 6], [3, 7]];\n\n        var mouseX = 0, prevMouseX, mouseY = 0, prevMouseY;\n\n        function scale(factor0, factor1, factor2) {\n            nodes.forEach(function (node) {\n                node[0] *= factor0;\n                node[1] *= factor1;\n                node[2] *= factor2;\n            });\n        }\n\n        function rotateCuboid(angleX, angleY) {\n\n            var sinX = Math.sin(angleX);\n            var cosX = Math.cos(angleX);\n\n            var sinY = Math.sin(angleY);\n            var cosY = Math.cos(angleY);\n\n            nodes.forEach(function (node) {\n                var x = node[0];\n                var y = node[1];\n                var z = node[2];\n\n                node[0] = x * cosX - z * sinX;\n                node[2] = z * cosX + x * sinX;\n\n                z = node[2];\n\n                node[1] = y * cosY - z * sinY;\n                node[2] = z * cosY + y * sinY;\n            });\n        }\n\n        function drawCuboid() {\n            g.save();\n            \n            g.clearRect(0, 0, canvas.width, canvas.height);\n            g.translate(canvas.width \/ 2, canvas.height \/ 2);\n            g.strokeStyle = \"#FFFFFF\";\n            g.beginPath();\n\n            edges.forEach(function (edge) {\n                var p1 = nodes[edge[0]];\n                var p2 = nodes[edge[1]];\n                g.moveTo(p1[0], p1[1]);\n                g.lineTo(p2[0], p2[1]);\n            });\n            \n            g.closePath();\n            g.stroke();\n\n            g.restore();\n        }\n\n        scale(80, 120, 160);\n        rotateCuboid(Math.PI \/ 5, Math.PI \/ 9);\n    <\/script>\n\n<\/body>\n<\/html>\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":2825}
    {"lang_cluster":"JavaScript","source_code":"\nfunction rot13(c) {\n    return c.replace(\/([a-m])|([n-z])\/ig, function($0,$1,$2) {\n        return String.fromCharCode($1 ? $1.charCodeAt(0) + 13 : $2 ? $2.charCodeAt(0) - 13 : 0) || $0;\n    });\n}\nrot13(\"ABJURER nowhere\") \/\/ NOWHERE abjurer\n\n\nfunction rot13(value){\n  if (!value)\n    return \"\";\n\n  function singleChar(c) {\n    if (c.toUpperCase() < \"A\" || c.toUpperCase() > \"Z\")\n      return c;\n\n    if (c.toUpperCase() <= \"M\")\n      return String.fromCharCode(c.charCodeAt(0) + 13);\n\n    return String.fromCharCode(c.charCodeAt(0) - 13);  \n  }\n\n  return _.map(value.split(\"\"), singleChar).join(\"\");\n}\n\ndescribe(\"Rot-13\", function() {\n  it(\"Given nothing will return nothing\", function() {\n    expect(rot13()).toBe(\"\");\n  });\n\n  it(\"Given empty string will return empty string\", function() {\n    expect(rot13(\"\")).toBe(\"\");\n  });\n\n  it(\"Given A will return N\", function() {\n    expect(rot13(\"A\")).toBe(\"N\");\n  });\n\n  it(\"Given B will return O\", function() {\n    expect(rot13(\"B\")).toBe(\"O\");\n  });\n\n  it(\"Given N will return A\", function() {\n    expect(rot13(\"N\")).toBe(\"A\");\n  });\n\n  it(\"Given Z will return M\", function() {\n    expect(rot13(\"Z\")).toBe(\"M\");\n  });\n\n  it(\"Given ZA will return MN\", function() {\n    expect(rot13(\"ZA\")).toBe(\"MN\");\n  });\n\n  it(\"Given HELLO will return URYYB\", function() {\n    expect(rot13(\"HELLO\")).toBe(\"URYYB\");\n  });\n\n  it(\"Given hello will return uryyb\", function() {\n    expect(rot13(\"hello\")).toBe(\"uryyb\");\n  });\n\n\n  it(\"Given hello1 will return uryyb1\", function() {\n    expect(rot13(\"hello1\")).toBe(\"uryyb1\");\n  });\n});\n\n","human_summarization":"implement a rot-13 function that encodes every line of input from a file or standard input, similar to a common UNIX utility. This function is used for obfuscating text to prevent casual reading of spoilers or offensive material. It replaces every ASCII letter with the letter rotated 13 characters around the 26 letter alphabet, preserving case and passing all non-alphabetic characters without alteration. The function can be wrapped in a utility program and is compatible with UNIX scripting languages and utilities. The codes also include TDD with Jasmine using Underscore.js.","id":2826}
    {"lang_cluster":"JavaScript","source_code":"\nvar arr = [\n  {id: 3, value: \"foo\"},\n  {id: 2, value: \"bar\"},\n  {id: 4, value: \"baz\"},\n  {id: 1, value: 42},\n  {id: 5, something: \"another string\"} \/\/ Works with any object declaring 'id' as a number.\n];\narr = arr.sort(function(a, b) {return a.id - b.id}); \/\/ Sort with comparator checking the id.\n\n(() => {\n    'use strict';\n\n    \/\/ GENERIC FUNCTIONS FOR COMPARISONS\n\n    \/\/ compare\u00a0:: a -> a -> Ordering\n    const compare = (a, b) => a < b ? -1 : (a > b ? 1 : 0);\n\n    \/\/ on\u00a0:: (b -> b -> c) -> (a -> b) -> a -> a -> c\n    const on = (f, g) => (a, b) => f(g(a), g(b));\n\n    \/\/ flip\u00a0:: (a -> b -> c) -> b -> a -> c\n    const flip = f => (a, b) => f.apply(null, [b, a]);\n\n    \/\/ arrayCopy\u00a0:: [a] -> [a]\n    const arrayCopy = (xs) => xs.slice(0);\n\n    \/\/ show\u00a0:: a -> String\n    const show = x => JSON.stringify(x, null, 2);\n\n\n    \/\/ TEST\n    const xs = [{\n        name: 'Shanghai',\n        pop: 24.2\n    }, {\n        name: 'Karachi',\n        pop: 23.5\n    }, {\n        name: 'Beijing',\n        pop: 21.5\n    }, {\n        name: 'Sao Paulo',\n        pop: 24.2\n    }, {\n        name: 'Dhaka',\n        pop: 17.0\n    }, {\n        name: 'Delhi',\n        pop: 16.8\n    }, {\n        name: 'Lagos',\n        pop: 16.1\n    }]\n\n    \/\/ population\u00a0:: Dictionary -> Num\n    const population = x => x.pop;\n\n    \/\/ name\u00a0:: Dictionary -> String\n    const name = x => x.name;\n\n    return show({\n        byPopulation: arrayCopy(xs)\n            .sort(on(compare, population)),\n        byDescendingPopulation: arrayCopy(xs)\n            .sort(on(flip(compare), population)),\n        byName: arrayCopy(xs)\n            .sort(on(compare, name)),\n        byDescendingName: arrayCopy(xs)\n            .sort(on(flip(compare), name))\n    });\n})();\n\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":2827}
    {"lang_cluster":"JavaScript","source_code":"\nvar i, j;\nfor (i = 1; i <= 5; i += 1) {\n  s = '';\n  for (j = 0; j < i; j += 1)\n    s += '*';\n  document.write(s + '<br>');\n}\n\n\nfunction range(i) {\n  return i ? range(i - 1).concat(i) : [];\n}\n\nrange(5) --> [1, 2, 3, 4, 5]\n\n\nvar s = '';\n\nrange(5).forEach(\n  function (line) {\n    range(line).forEach(\n      function () { s += '*'; }\n    );\n    s += '\\n';\n  }\n);\n\nconsole.log(s);\n\n\nconsole.log(\n  range(5).reduce(\n    function (a, n) {\n      return a + Array(n + 1).join('*') + '\\n';\n    }, ''\n  )\n);\n\n\nconsole.log(\n  range(5).map(function(a) {\n    return Array(a + 1).join('*');\n  }).join('\\n')\n);\n\n","human_summarization":"demonstrate the use of nested \"for\" loops to print a specific pattern. The number of iterations of the inner loop is controlled by the outer loop. The code also showcases the use of JavaScript's Array.forEach() and Array.reduce() functions for iterating over an array of indices or a range. The code also illustrates how a loop effect can be expressed as a map in certain contexts.","id":2828}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar assoc = {};\n\nassoc['foo'] = 'bar';\nassoc['another-key'] = 3;\n\n\/\/ dot notation can be used if the property name is a valid identifier\nassoc.thirdKey = 'we can also do this!';\nassoc[2] = \"the index here is the string '2'\";\n\n\/\/using JavaScript's object literal notation\nvar assoc = {\n  foo: 'bar',\n  'another-key': 3 \/\/the key can either be enclosed by quotes or not\n};\n\n\/\/iterating keys\nfor (var key in assoc) {\n  \/\/ hasOwnProperty() method ensures the property isn't inherited\n  if (assoc.hasOwnProperty(key)) {\n    alert('key:\"' + key + '\", value:\"' + assoc[key] + '\"');\n  }\n}\n\n\nvar map = new Map(),\n    fn = function () {},\n    obj = {};\n\nmap.set(fn, 123);\nmap.set(obj, 'abc');\nmap.set('key', 'val');\nmap.set(3, x => x + x);\n\nmap.get(fn); \/\/=> 123\nmap.get(function () {}); \/\/=> undefined because not the same function\nmap.get(obj); \/\/=> 'abc'\nmap.get({}); \/\/=> undefined because not the same object\nmap.get('key'); \/\/=> 'val'\nmap.get(3); \/\/=> (x => x + x)\n\nmap.size; \/\/=> 4\n\n\/\/iterating using ES6 for..of syntax\nfor (var key of map.keys()) {\n  console.log(key + ' => ' + map.get(key));\n}\n\n","human_summarization":"Creates an associative array or dictionary using JavaScript Objects as ECMAScript5.1 doesn't support associative arrays. It also uses ECMAScript 6 (ES6) map and weak map implementation, allowing the use of objects, functions, and numbers as keys in addition to strings. The keys are converted to strings to avoid potential collisions with reserved JavaScript keywords.","id":2829}
    {"lang_cluster":"JavaScript","source_code":"\n\nLinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) {\n    if (this._value == searchValue) {\n        nodeToInsert.next(this.next());\n        this.next(nodeToInsert);\n    }\n    else if (this.next() == null) \n        throw new Error(0, \"value '\" + searchValue + \"' not found in linked list.\")\n    else\n        this.next().insertAfter(searchValue, nodeToInsert);\n}\nvar list = createLinkedListFromArray(['A','B']);\nlist.insertAfter('A', new LinkedList('C', null));\n\n","human_summarization":"define a method for inserting an element into a singly-linked list after a specified element. The method is then used to insert element 'C' into a list containing elements 'A' and 'B', specifically after element 'A'.","id":2830}
    {"lang_cluster":"JavaScript","source_code":"\nvar eth = {\n\t\n\thalve : function ( n ){  return Math.floor(n\/2);  },\n\tdouble: function ( n ){  return 2*n;              },\n\tisEven: function ( n ){  return n%2 === 0);       },\n\t\n\tmult: function ( a , b ){\n\t\tvar sum = 0, a = [a], b = [b];\n\t\t\n\t\twhile ( a[0] !== 1 ){\n\t\t\ta.unshift( eth.halve( a[0] ) );\n\t\t\tb.unshift( eth.double( b[0] ) );\n\t\t}\n\t\t\n\t\tfor( var i = a.length - 1; i > 0 ; i -= 1 ){\n\t\t\t\n\t\t\tif( !eth.isEven( a[i] ) ){\n\t\t\t\tsum += b[i];\n\t\t\t}\n\t\t}\t\t\n\t\treturn sum + b[0];\n\t}\n}\n\/\/ eth.mult(17,34) returns 578\n\n\nHalve an integer, in this sense, with a right-shift (n >>= 1)\nDouble an integer by addition to self (m += m)\nTest if an integer is odd by bitwise and (n & 1)\n\nfunction ethMult(m, n) {\n  var o = !isNaN(m) ? 0 : ''; \/\/ same technique works with strings\n  if (n < 1) return o;\n  while (n > 1) {\n    if (n & 1) o += m;  \/\/ 3. integer odd\/even? (bit-wise and 1)\n    n >>= 1;            \/\/ 1. integer halved (by right-shift)\n    m += m;             \/\/ 2. integer doubled (addition to self)\n  }\n  return o + m;\n}\n\nethMult(17, 34)\n\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement the Ethiopian multiplication method, which multiplies two integers using only addition, doubling, and halving operations. The multiplication is performed by repeatedly halving the first number and doubling the second number, discarding rows where the first number is even, and summing the remaining values in the second column. The code can also multiply strings efficiently.","id":2831}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar ar=[],order=[0,1,2],op=[],val=[];\nvar NOVAL=9999,oper=\"+-*\/\",out;\n\nfunction rnd(n){return Math.floor(Math.random()*n)}\n\nfunction say(s){\n try{document.write(s+\"<br>\")}\n catch(e){WScript.Echo(s)}\n}\n\nfunction getvalue(x,dir){\n var r=NOVAL;\n if(dir>0)++x;\n while(1){\n  if(val[x]!=NOVAL){\n   r=val[x];\n   val[x]=NOVAL;\n   break;\n  }\n  x+=dir;\n }\n return r*1;\n}\n\nfunction calc(){\n var c=0,l,r,x;\n val=ar.join('\/').split('\/');\n while(c<3){\n  x=order[c];\n  l=getvalue(x,-1);\n  r=getvalue(x,1);\n  switch(op[x]){\n   case 0:val[x]=l+r;break;\n   case 1:val[x]=l-r;break;\n   case 2:val[x]=l*r;break;\n   case 3:\n   if(!r||l%r)return 0;\n   val[x]=l\/r;\n  }\n  ++c;\n }\n return getvalue(-1,1);\n}\n\nfunction shuffle(s,n){\n var x=n,p=eval(s),r,t;\n while(x--){\n  r=rnd(n);\n  t=p[x];\n  p[x]=p[r];\n  p[r]=t;\n }\n}\n\nfunction parenth(n){\n while(n>0)--n,out+='(';\n while(n<0)++n,out+=')';\n}\n\nfunction getpriority(x){\n for(var z=3;z--;)if(order[z]==x)return 3-z;\n return 0;\n}\n\nfunction showsolution(){\n var x=0,p=0,lp=0,v=0;\n while(x<4){\n  if(x<3){\n   lp=p;\n   p=getpriority(x);\n   v=p-lp;\n   if(v>0)parenth(v);\n  }\n  out+=ar[x];\n  if(x<3){\n   if(v<0)parenth(v);\n   out+=oper.charAt(op[x]);\n  }\n  ++x;\n }\n parenth(-p);\n say(out);\n}\n\nfunction solve24(s){\n var z=4,r;\n while(z--)ar[z]=s.charCodeAt(z)-48;\n out=\"\";\n for(z=100000;z--;){\n  r=rnd(256);\n  op[0]=r&3;\n  op[1]=(r>>2)&3;\n  op[2]=(r>>4)&3;\n  shuffle(\"ar\",4);\n  shuffle(\"order\",3);\n  if(calc()!=24)continue;\n  showsolution();\n  break;\n }\n}\n\nsolve24(\"1234\");\nsolve24(\"6789\");\nsolve24(\"1127\");\n\n\n(((3*1)*4)*2)\n((6*8)\/((9-7)))\n(((1+7))*(2+1))\n","human_summarization":"The code takes four digits as input, either from the user or generated randomly, and computes arithmetic expressions based on the rules of the 24 game. It also displays examples of solutions generated by the program. This code is a translation from the original C code.","id":2832}
    {"lang_cluster":"JavaScript","source_code":"\nfunction factorial(n) {\n  \/\/check our edge case\n  if (n < 0) { throw \"Number must be non-negative\"; }\n\n  var result = 1;\n  \/\/we skip zero and one since both are 1 and are identity\n  while (n > 1) {\n    result *= n;\n    n--;\n  }\n  return result;\n}\n(function(x) {\n\n  var memo = {};\n\n  function factorial(n) {\n    return n < 2\u00a0? 1\u00a0: memo[n] || (memo[n] = n * factorial(n - 1));\n  }\n  \n  return factorial(x);\n  \n})(18);\n\n","human_summarization":"The code calculates the factorial of a given number, either iteratively or recursively. It optionally includes error handling for negative inputs. It can also compute factorials using a fold\/reduce function over a range of integers, with memoization for efficiency. The code can output factorials for each addition to an array and calculate factorial from a single number.","id":2833}
    {"lang_cluster":"JavaScript","source_code":"\n#!\/usr\/bin\/env js\n\nfunction main() {\n    var len = 4;\n    playBullsAndCows(len);\n}\n\nfunction playBullsAndCows(len) {\n    var num = pickNum(len);\n    \/\/ print('The secret number is:\\n  ' + num.join('\\n  '));\n    showInstructions(len);\n    var nGuesses = 0;\n    while (true) {\n        nGuesses++;\n        var guess = getGuess(nGuesses, len);\n        var census = countBovine(num, guess);\n        showScore(census.bulls, census.cows);\n        if (census.bulls == len) {\n            showFinalResult(nGuesses);\n            return;\n        }\n    }\n}\n\nfunction showScore(nBulls, nCows) {\n    print('    Bulls: ' + nBulls + ', cows: ' + nCows);\n}\n\nfunction showFinalResult(guesses) {\n    print('You win!!! Guesses needed: ' + guesses);\n}\n\nfunction countBovine(num, guess) {\n    var count = {bulls:0, cows:0};\n    var g = guess.join('');\n    for (var i = 0; i < num.length; i++) {\n        var digPresent = g.search(num[i]) != -1;\n        if (num[i] == guess[i]) count.bulls++;\n        else if (digPresent) count.cows++;\n    }\n    return count;\n}\n\nfunction getGuess(nGuesses, len) {\n    while (true) {\n        putstr('Your guess #' + nGuesses + ': ');\n        var guess = readline();\n        guess = String(parseInt(guess)).split('');\n        if (guess.length != len) {\n            print('  You must enter a ' + len + ' digit number.');\n            continue;\n        }\n        if (hasDups(guess)) {\n            print('  No digits can be duplicated.');\n            continue;\n        }    \n        return guess;\n    }\n}\n\nfunction hasDups(ary) {\n    var t = ary.concat().sort();\n    for (var i = 1; i < t.length; i++) {\n        if (t[i] == t[i-1]) return true;\n    }\n    return false;\n}\n\nfunction showInstructions(len) {\n    print();\n    print('Bulls and Cows Game');\n    print('-------------------');\n    print('  You must guess the ' + len + ' digit number I am thinking of.');\n    print('  The number is composed of the digits 1-9.');\n    print('  No digit appears more than once.');\n    print('  After each of your guesses, I will tell you:');\n    print('    The number of bulls (digits in right place)');\n    print('    The number of cows (correct digits, but in the wrong place)');\n    print();\n}\n\nfunction pickNum(len) {\n    var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];\n    nums.sort(function(){return Math.random() - 0.5});\n    return nums.slice(0, len);\n}\n\nmain();\n\n\nBulls and Cows Game\n-------------------\n  You must guess the 4 digit number I am thinking of.\n  The number is composed of the digits 1-9.\n  No digit appears more than once.\n  After each of your guesses, I will tell you:\n    The number of bulls (digits in right place)\n    The number of cows (correct digits, but in wrong place)\n\nYour guess #1: 1234\n    Bulls: 0, cows: 2\nYour guess #2: 5678\n    Bulls: 1, cows: 1\nYour guess #3: 3167\n    Bulls: 0, cows: 3\nYour guess #4: 9123\n    Bulls: 1, cows: 1\nYour guess #5: 5137\n    Bulls: 1, cows: 3\nYour guess #6: 5317\n    Bulls: 2, cows: 2\nYour guess #7: 5731\n    Bulls: 2, cows: 2\nYour guess #8: 5713\n    Bulls: 4, cows: 0\nYou win! Guesses needed: 8\n\n","human_summarization":"The code generates a four-digit random number from 1 to 9 without duplication. It then prompts the user for guesses, rejects malformed guesses, and prints the score for each guess. The score is computed based on the number of bulls and cows, where a bull is a correct digit in the correct position and a cow is a correct digit in the wrong position. The game ends when the user's guess matches the randomly generated number.","id":2834}
    {"lang_cluster":"JavaScript","source_code":"\nfunction randomNormal() {\n  return Math.cos(2 * Math.PI * Math.random()) * Math.sqrt(-2 * Math.log(Math.random()))\n}\n\nvar a = []\nfor (var i=0; i < 1000; i++){\n  a[i] = randomNormal() \/ 2 + 1\n}\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":2835}
    {"lang_cluster":"JavaScript","source_code":"\nfunction dot_product(ary1, ary2) {\n    if (ary1.length != ary2.length)\n        throw \"can't find dot product: arrays have different lengths\";\n    var dotprod = 0;\n    for (var i = 0; i < ary1.length; i++)\n        dotprod += ary1[i] * ary2[i];\n    return dotprod;\n}\n\nprint(dot_product([1,3,-5],[4,-2,-1])); \/\/ ==> 3\nprint(dot_product([1,3,-5],[4,-2,-1,0])); \/\/ ==> exception\n\n\nfunction dotp(x,y) {\n    function dotp_sum(a,b) { return a + b; }\n    function dotp_times(a,i) { return x[i] * y[i]; }\n    if (x.length != y.length)\n        throw \"can't find dot product: arrays have different lengths\";\n    return x.map(dotp_times).reduce(dotp_sum,0);\n}\n\ndotp([1,3,-5],[4,-2,-1]); \/\/ ==> 3\ndotp([1,3,-5],[4,-2,-1,0]); \/\/ ==> exception\n\n\n(() => {\n    \"use strict\";\n\n    \/\/ ------------------- DOT PRODUCT -------------------\n\n    \/\/ dotProduct\u00a0:: [Num] -> [Num] -> Either Null Num\n    const dotProduct = xs =>\n        ys => xs.length === ys.length\n            ? sum(zipWith(mul)(xs)(ys))\n            : null;\n\n\n    \/\/ ---------------------- TEST -----------------------\n\n    \/\/ main\u00a0:: IO ()\n    const main = () =>\n        dotProduct([1, 3, -5])([4, -2, -1]);\n\n\n    \/\/ --------------------- GENERIC ---------------------\n\n    \/\/ mul\u00a0:: Num -> Num -> Num\n    const mul = x =>\n        y => x * y;\n\n\n    \/\/ sum\u00a0:: [Num] -> Num\n    const sum = xs =>\n    \/\/ The numeric sum of all values in xs.\n        xs.reduce((a, x) => a + x, 0);\n\n\n    \/\/ zipWith\u00a0:: (a -> b -> c) -> [a] -> [b] -> [c]\n    const zipWith = f =>\n    \/\/ A list constructed by zipping with a\n    \/\/ custom function, rather than with the\n    \/\/ default tuple constructor.\n        xs => ys => xs.map(\n            (x, i) => f(x)(ys[i])\n        ).slice(\n            0, Math.min(xs.length, ys.length)\n        );\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n","human_summarization":"The code implements a function to calculate the dot product of two vectors of arbitrary length. It multiplies corresponding elements from each vector and sums the products to produce the result. The function returns null if the lengths of the vectors do not match. It uses map and reduce functions instead of iteration.","id":2836}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: SpiderMonkey\nWorks with: OSSP js\n\n$ js -e 'while (line = readline()) { do_something_with(line); }' < inputfile\nWorks with: JScript\n\nvar text_stream = WScript.StdIn;\nvar i = 0;\n\nwhile ( ! text_stream.AtEndOfStream ) {\n    var line = text_stream.ReadLine();\n    \/\/ do something with line\n    WScript.echo(++i + \": \" + line);\n}\n\n","human_summarization":"implement a function in JavaScript that reads data from a text stream either word-by-word or line-by-line until there is no more data left. This function operates on standard input.","id":2837}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: Firefox version 2.0\n\nvar doc = document.implementation.createDocument( null, 'root', null );\nvar root = doc.documentElement;\nvar element = doc.createElement( 'element' );\nroot.appendChild( element );\nelement.appendChild( document.createTextNode('Some text here') );\nvar xmlString = new XMLSerializer().serializeToString( doc );\n\n\nvar xml = <root>\n  <element>Some text here<\/element>\n<\/root>;\nvar xmlString = xml.toXMLString();\n\n\nXML.ignoreProcessingInstructions = false;\nvar xml = <?xml version=\"1.0\"?>  \n<root>\n  <element>Some text here<\/element>\n<\/root>;\nvar xmlString = xml.toXMLString();\n\n","human_summarization":"Create a simple DOM and serialize it into XML format with root and element tags, using E4X and processing instruction.<\/output>","id":2838}
    {"lang_cluster":"JavaScript","source_code":"\nconsole.log(new Date()) \/\/ => Sat, 28 May 2011 08:22:53 GMT\nconsole.log(Date.now()) \/\/ => 1306571005417 \/\/ Unix epoch\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":2839}
    {"lang_cluster":"JavaScript","source_code":"\nfunction sedol(input) {\n    return input + sedol_check_digit(input);\n}\n\nvar weight = [1, 3, 1, 7, 3, 9, 1];\nfunction sedol_check_digit(char6) {\n    if (char6.search(\/^[0-9BCDFGHJKLMNPQRSTVWXYZ]{6}$\/) == -1)\n        throw \"Invalid SEDOL number '\" + char6 + \"'\";\n    var sum = 0;\n    for (var i = 0; i < char6.length; i++)\n        sum += weight[i] * parseInt(char6.charAt(i), 36);\n    var check = (10 - sum%10) % 10;\n    return check.toString();\n}\n\nvar input = [ \n    '710889', 'B0YBKJ', '406566', 'B0YBLH', '228276',\n    'B0YBKL', '557910', 'B0YBKR', '585284', 'B0YBKT',\n    \"BOATER\" , \"12345\", \"123456\", \"1234567\"\n];\n\nvar expected = [ \n    '7108899', 'B0YBKJ7', '4065663', 'B0YBLH2', '2282765',\n    'B0YBKL9', '5579107', 'B0YBKR5', '5852842', 'B0YBKT7',\n    null, null, '1234563', null\n];\n\nfor (var i in input) {\n    try {\n        var sedolized = sedol(input[i]);\n        if (sedolized == expected[i]) \n            print(sedolized);\n        else\n            print(\"error: calculated sedol for input \" + input[i] + \n                  \" is \" + sedolized + \", but it should be \" + expected[i]\n            );\n    }\n    catch (e) {\n        print(\"error: \" + e);\n    }\n}\n\n\n7108899\nB0YBKJ7\n4065663\nB0YBLH2\n2282765\nB0YBKL9\n5579107\nB0YBKR5\n5852842\nB0YBKT7\nerror: Invalid SEDOL number 'BOATER'\nerror: Invalid SEDOL number '12345'\n1234563\nerror: Invalid SEDOL number '1234567'\n(() => {\n    'use strict';\n\n    const main = () => {\n\n        \/\/ checkSumLR\u00a0:: String -> Either String String\n        const checkSumLR = s => {\n            const\n                tpl = partitionEithers(map(charValueLR, s));\n            return 0 < tpl[0].length ? (\n                Left(s + ' -> ' + unwords(tpl[0]))\n            ) : Right(rem(10 - rem(\n                sum(zipWith(\n                    (a, b) => a * b,\n                    [1, 3, 1, 7, 3, 9],\n                    tpl[1]\n                )), 10\n            ), 10).toString());\n        };\n\n        \/\/ charValue\u00a0:: Char -> Either String Int\n        const charValueLR = c =>\n            isAlpha(c) ? (\n                isUpper(c) ? (\n                    elem(c, 'AEIOU') ? Left(\n                        'Unexpected vowel: ' + c\n                    ) : Right(ord(c) - ord('A') + 10)\n                ) : Left('Unexpected lower case character: ' + c)\n            ) : isDigit(c) ? Right(\n                parseInt(c, 10)\n            ) : Left('Unexpected character: ' + c);\n\n        \/\/ TESTS ------------------------------------------\n        const [problems, checks] = Array.from(\n            partitionEithers(map(s => bindLR(\n                    checkSumLR(s),\n                    c => Right(s + c)\n                ),\n                [\n                    \"710889\", \"B0YBKJ\", \"406566\",\n                    \"B0YBLH\", \"228276\", \"B0YBKL\",\n                    \"557910\", \"B0YBKR\", \"585284\",\n                    \"B0YBKT\", \"B00030\"\n                ]\n            ))\n        );\n        return unlines(\n            0 < problems.length ? (\n                problems\n            ) : checks\n        );\n    };\n\n    \/\/ GENERIC FUNCTIONS ----------------------------\n\n    \/\/ Left\u00a0:: a -> Either a b\n    const Left = x => ({\n        type: 'Either',\n        Left: x\n    });\n\n    \/\/ Right\u00a0:: b -> Either a b\n    const Right = x => ({\n        type: 'Either',\n        Right: x\n    });\n\n    \/\/ Tuple (,)\u00a0:: a -> b -> (a, b)\n    const Tuple = (a, b) => ({\n        type: 'Tuple',\n        '0': a,\n        '1': b,\n        length: 2\n    });\n\n    \/\/ bindLR (>>=)\u00a0:: Either a -> (a -> Either b) -> Either b\n    const bindLR = (m, mf) =>\n        undefined !== m.Left ? (\n            m\n        ) : mf(m.Right);\n\n    \/\/ elem\u00a0:: Eq a => a -> [a] -> Bool\n    const elem = (x, xs) => xs.includes(x);\n\n    \/\/ isAlpha\u00a0:: Char -> Bool\n    const isAlpha = c =>\n        \/[A-Za-z\\u00C0-\\u00FF]\/.test(c);\n\n    \/\/ isDigit\u00a0:: Char -> Bool\n    const isDigit = c => {\n        const n = ord(c);\n        return 48 <= n && 57 >= n;\n    };\n\n    \/\/ isUpper\u00a0:: Char -> Bool\n    const isUpper = c =>\n        \/[A-Z]\/.test(c);\n\n    \/\/ Returns Infinity over objects without finite length.\n    \/\/ This enables zip and zipWith to choose the shorter\n    \/\/ argument when one is non-finite, like cycle, repeat etc\n\n    \/\/ length\u00a0:: [a] -> Int\n    const length = xs =>\n        (Array.isArray(xs) || 'string' === typeof xs) ? (\n            xs.length\n        ) : Infinity;\n\n    \/\/ map\u00a0:: (a -> b) -> [a] -> [b]\n    const map = (f, xs) =>\n        (Array.isArray(xs) ? (\n            xs\n        ) : xs.split('')).map(f);\n\n    \/\/ ord\u00a0:: Char -> Int\n    const ord = c => c.codePointAt(0);\n\n    \/\/ partitionEithers\u00a0:: [Either a b] -> ([a],[b])\n    const partitionEithers = xs =>\n        xs.reduce(\n            (a, x) => undefined !== x.Left ? (\n                Tuple(a[0].concat(x.Left), a[1])\n            ) : Tuple(a[0], a[1].concat(x.Right)),\n            Tuple([], [])\n        );\n\n    \/\/ rem\u00a0:: Int -> Int -> Int\n    const rem = (n, m) => n % m;\n\n    \/\/ sum\u00a0:: [Num] -> Num\n    const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n    \/\/ take\u00a0:: Int -> [a] -> [a]\n    \/\/ take\u00a0:: Int -> String -> String\n    const take = (n, xs) =>\n        'GeneratorFunction' !== xs.constructor.constructor.name ? (\n            xs.slice(0, n)\n        ) : [].concat.apply([], Array.from({\n            length: n\n        }, () => {\n            const x = xs.next();\n            return x.done ? [] : [x.value];\n        }));\n\n    \/\/ unlines\u00a0:: [String] -> String\n    const unlines = xs => xs.join('\\n');\n\n    \/\/ unwords\u00a0:: [String] -> String\n    const unwords = xs => xs.join(' ');\n\n    \/\/ zipWith\u00a0:: (a -> b -> c) -> [a] -> [b] -> [c]\n    const zipWith = (f, xs, ys) => {\n        const\n            lng = Math.min(length(xs), length(ys)),\n            as = take(lng, xs),\n            bs = take(lng, ys);\n        return Array.from({\n            length: lng\n        }, (_, i) => f(as[i], bs[i], i));\n    };\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates and appends the checksum digit to each SEDOL, and outputs the updated SEDOLs. It also checks if each input SEDOL is correctly formed with valid characters.","id":2840}
    {"lang_cluster":"JavaScript","source_code":"\n<!DOCTYPE html>\n<html>\n<head>\n<meta charset=\"utf-8\">\n<title>Draw a sphere<\/title>\n<script>\nvar light=[30,30,-50],gR,gk,gambient;\n\nfunction normalize(v){\n\tvar len=Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);\n\tv[0]\/=len;\n\tv[1]\/=len;\n\tv[2]\/=len;\n\treturn v;\n}\n \nfunction dot(x,y){\n\tvar d=x[0]*y[0]+x[1]*y[1]+x[2]*y[2];\n\treturn d<0?-d:0;\n}\n \nfunction draw_sphere(R,k,ambient){\n\tvar i,j,intensity,b,vec,x,y,cvs,ctx,imgdata,idx;\n\tcvs=document.getElementById(\"c\");\n\tctx=cvs.getContext(\"2d\");\n\tcvs.width=cvs.height=2*Math.ceil(R)+1;\n\timgdata=ctx.createImageData(2*Math.ceil(R)+1,2*Math.ceil(R)+1);\n\tidx=0;\n\tfor(i=Math.floor(-R);i<=Math.ceil(R);i++){\n\t\tx=i+.5;\n\t\tfor(j=Math.floor(-R);j<=Math.ceil(R);j++){\n\t\t\ty=j+.5;\n\t\t\tif(x*x+y*y<=R*R){\n\t\t\t\tvec=[x,y,Math.sqrt(R*R-x*x-y*y)];\n\t\t\t\tvec=normalize(vec);\n\t\t\t\tb=Math.pow(dot(light,vec),k)+ambient;\n\t\t\t\tintensity=(1-b)*256;\n\t\t\t\tif(intensity<0)intensity=0;\n\t\t\t\tif(intensity>=256)intensity=255;\n\t\t\t\timgdata.data[idx++]=imgdata.data[idx++]=255-~~(intensity); \/\/RG\n\t\t\t\timgdata.data[idx++]=imgdata.data[idx++]=255; \/\/BA\n\t\t\t} else {\n\t\t\t\timgdata.data[idx++]=imgdata.data[idx++]=imgdata.data[idx++]=imgdata.data[idx++]=255; \/\/RGBA\n\t\t\t}\n\t\t}\n\t}\n\tctx.putImageData(imgdata,0,0);\n}\n\nlight=normalize(light);\n<\/script>\n<\/head>\n<body onload=\"gR=200;gk=4;gambient=.2;draw_sphere(gR,gk,gambient)\">\nR=<input type=\"range\" id=\"R\" name=\"R\" min=\"5\" max=\"500\" value=\"200\" step=\"5\" onchange=\"document.getElementById('lR').innerHTML=gR=parseFloat(this.value);draw_sphere(gR,gk,gambient)\">\n<label for=\"R\" id=\"lR\">200<\/label><br>\nk=<input type=\"range\" id=\"k\" name=\"k\" min=\"0\" max=\"10\" value=\"4\" step=\".25\" onchange=\"document.getElementById('lk').innerHTML=gk=parseFloat(this.value);draw_sphere(gR,gk,gambient)\">\n<label for=\"k\" id=\"lk\">4<\/label><br>\nambient=<input type=\"range\" id=\"ambient\" name=\"ambient\" min=\"0\" max=\"1\" value=\".2\" step=\".05\" onchange=\"document.getElementById('lambient').innerHTML=gambient=parseFloat(this.value);draw_sphere(gR,gk,gambient)\">\n<label for=\"ambient\" id=\"lambient\">0.2<\/label><br>\n<canvas id=\"c\">Unsupportive browser...<\/canvas><br>\n<\/body>\n<\/html>\n\n","human_summarization":"The following code allows for the creation of a sphere, either graphically or in ASCII art, with the option for static or rotational projection. It utilizes Javascript with an HTML wrapper for easy execution and interactivity, but can function without the HTML wrapper by calling the draw_sphere function.","id":2841}
    {"lang_cluster":"JavaScript","source_code":"\nconsole.log(function () {\n\n  var lstSuffix = 'th st nd rd th th th th th th'.split(' '),\n\n    fnOrdinalForm = function (n) {\n      return n.toString() + (\n        11 <= n % 100 && 13 >= n % 100 ?\n        \"th\" : lstSuffix[n % 10]\n      );\n    },\n\n    range = function (m, n) {\n      return Array.apply(\n        null, Array(n - m + 1)\n      ).map(function (x, i) {\n        return m + i;\n      });\n    };\n\n  return [[0, 25], [250, 265], [1000, 1025]].map(function (tpl) {\n    return range.apply(null, tpl).map(fnOrdinalForm).join(' ');\n  }).join('\\n\\n');\n  \n}());\n\n\n\n","human_summarization":"The code is a function that takes a non-negative integer as input and returns a string representation of the number with its corresponding ordinal suffix. The function is tested with ranges 0-25, 250-265, and 1000-1025. The use of apostrophes is optional.","id":2842}
    {"lang_cluster":"JavaScript","source_code":"\nfunction stripchars(string, chars) {\n  return string.replace(RegExp('['+chars+']','g'), '');\n}\n\n\n(() => {\n    'use strict';\n\n    \/\/ stripChars\u00a0:: String -> String -> String\n    const stripChars = (strNeedles, strHayStack) =>\n        strHayStack.replace(RegExp(`[${strNeedles}]`, 'g'), '');\n\n    \/\/ GENERIC FUNCTION\n\n    \/\/ curry\u00a0:: ((a, b) -> c) -> a -> b -> c\n    const curry = f => a => b => f(a, b);\n\n    \/\/ TEST FUNCTION\n\n    const noAEI = curry(stripChars)('aeiAEI');\n\n    \/\/ TEST\n    return noAEI('She was a soul stripper. She took my heart!');\n\n    \/\/ 'Sh ws  soul strppr. Sh took my hrt!'\n})();\n\n\n","human_summarization":"\"Function to remove a specified set of characters from a given string.\"","id":2843}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction fizz(d, e) {\n  return function b(a) {\n    return a ? b(a - 1).concat(a) : [];\n  }(e).reduce(function (b, a) {\n    return b + (d.reduce(function (b, c) {\n      return b + (a % c[0] ? \"\" : c[1]);\n    }, \"\") || a.toString()) + \"\\n\";\n  }, \"\");\n}\n\n\nfunction fizz(lstRules, lngMax) {\n\n    return (\n        function rng(i) {\n            return i ? rng(i - 1).concat(i) : []\n        }\n    )(lngMax).reduce(\n        function (strSeries, n) {\n\n            \/\/ The next member of the series of lines:\n            \/\/ a word string or a number string\n            return strSeries + (\n                lstRules.reduce(\n                    function (str, tplNumWord) {\n                        return str + (\n                            n % tplNumWord[0] ? '' : tplNumWord[1]\n                        )\n                    }, ''\n                ) || n.toString()\n            ) + '\\n';\n            \n        }, ''\n    );\n}\n\nfizz([[3, 'Fizz'], [5, 'Buzz'], [7, 'Baxx']], 20);\n\n\n","human_summarization":"The code takes a maximum number and a list of factor-word pairs as input from the user. It then prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. If a number is a multiple of more than one factor, it prints the associated words in ascending order of the factors. The code is written in a functional style of JavaScript, using two nested reduce functions.","id":2844}
    {"lang_cluster":"JavaScript","source_code":"\n\/\/ No built-in prepend\nvar s=\", World\"\ns = \"Hello\" + s\nprint(s);\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":2845}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: Chrome 8.0\n\nvar DRAGON = (function () {\n   \/\/ MATRIX MATH\n   \/\/ -----------\n\n   var matrix = {\n      mult: function ( m, v ) {\n         return [ m[0][0] * v[0] + m[0][1] * v[1],\n                  m[1][0] * v[0] + m[1][1] * v[1] ];\n      },\n\n      minus: function ( a, b ) {\n         return [ a[0]-b[0], a[1]-b[1] ];\n      },\n\n      plus: function ( a, b ) {\n         return [ a[0]+b[0], a[1]+b[1] ];\n      }\n   };\n\n\n   \/\/ SVG STUFF\n   \/\/ ---------\n\n   \/\/ Turn a pair of points into an SVG path like \"M1 1L2 2\".\n   var toSVGpath = function (a, b) {  \/\/ type system fail\n      return \"M\" + a[0] + \" \" + a[1] + \"L\" + b[0] + \" \" + b[1];\n   };\n\n\n   \/\/ DRAGON MAKING\n   \/\/ -------------\n\n   \/\/ Make a dragon with a better fractal algorithm\n   var fractalMakeDragon = function (svgid, ptA, ptC, state, lr, interval) {\n\n      \/\/ make a new <path>\n      var path = document.createElementNS('http:\/\/www.w3.org\/2000\/svg', 'path');\n      path.setAttribute( \"class\",  \"dragon\"); \n      path.setAttribute( \"d\", toSVGpath(ptA, ptC) );\n\n      \/\/ append the new path to the existing <svg>\n      var svg = document.getElementById(svgid); \/\/ call could be eliminated\n      svg.appendChild(path);\n\n      \/\/ if we have more iterations to go...\n      if (state > 1) {\n\n         \/\/ make a new point, either to the left or right\n         var growNewPoint = function (ptA, ptC, lr) {\n            var left  = [[ 1\/2,-1\/2 ], \n                         [ 1\/2, 1\/2 ]]; \n\n            var right = [[ 1\/2, 1\/2 ],\n                         [-1\/2, 1\/2 ]];\n\n            return matrix.plus(ptA, matrix.mult( lr ? left : right, \n                                                 matrix.minus(ptC, ptA) ));\n         }; \n\n         var ptB = growNewPoint(ptA, ptC, lr, state);\n\n         \/\/ then recurse using each new line, one left, one right\n         var recurse = function () {\n            \/\/ when recursing deeper, delete this svg path\n            svg.removeChild(path);\n\n            \/\/ then invoke again for new pair, decrementing the state\n            fractalMakeDragon(svgid, ptB, ptA, state-1, lr, interval);\n            fractalMakeDragon(svgid, ptB, ptC, state-1, lr, interval);\n         };\n\n         window.setTimeout(recurse, interval);\n      }\n   };\n\n\n   \/\/ Export these functions\n   \/\/ ----------------------\n   return {\n      fractal: fractalMakeDragon\n\n      \/\/ ARGUMENTS\n      \/\/ ---------\n      \/\/    svgid    id of <svg> element\n      \/\/    ptA      first point [x,y] (from top left)\n      \/\/    ptC      second point [x,y]\n      \/\/    state    number indicating how many steps to recurse\n      \/\/    lr       true\/false to make new point on left or right\n\n      \/\/ CONFIG\n      \/\/ ------\n      \/\/ CSS rules should be made for the following\n      \/\/    svg#fractal\n      \/\/    svg path.dragon\n   };\n\n}());\n\n\n...\n<script src='.\/dragon.js'><\/script>\n...\n<div>\n   <svg xmlns='http:\/\/www.w3.org\/2000\/svg' id='fractal'><\/svg> \n<\/div>\n<script>\n   DRAGON.fractal('fractal', [100,300], [500,300], 15, false, 700);\n<\/script>\n...\n\nWorks with: Chrome\nFile:DC11.pngOutput DC11.png\nFile:DC19.pngOutput DC19.png\nFile:DC25.pngOutput DC25.png\n<!-- DragonCurve.html -->\n<html>\n<head>\n<script type='text\/javascript'>\nfunction pDragon(cId) {\n  \/\/ Plotting Dragon curves. 2\/25\/17 aev\n  var n=document.getElementById('ord').value;\n  var sc=document.getElementById('sci').value;\n  var hsh=document.getElementById('hshi').value;\n  var vsh=document.getElementById('vshi').value;\n  var clr=document.getElementById('cli').value;\n  var c=c1=c2=c2x=c2y=x=y=0, d=1, n=1<<n;\n  var cvs=document.getElementById(cId);\n  var ctx=cvs.getContext(\"2d\");\n  hsh=Number(hsh); vsh=Number(vsh);\n  x=y=cvs.width\/2;\n  \/\/ Cleaning canvas, init plotting\n  ctx.fillStyle=\"white\"; ctx.fillRect(0,0,cvs.width,cvs.height);\n  ctx.beginPath();\n  for(i=0; i<=n;) {\n    ctx.lineTo((x+hsh)*sc,(y+vsh)*sc);\n    c1=c&1; c2=c&2;\n    c2x=1*d; if(c2>0) {c2x=(-1)*d}; c2y=(-1)*c2x;\n    if(c1>0) {y+=c2y} else {x+=c2x}\n    i++; c+=i\/(i&-i);\n  }\n  ctx.strokeStyle = clr;  ctx.stroke();\n}\n<\/script>\n<\/head>\n<body>\n<p><b>Please input order, scale, x-shift, y-shift, color:<\/><\/p>\n<input id=ord value=11 type=\"number\" min=\"7\" max=\"25\" size=\"2\">\n<input id=sci value=7.0 type=\"number\" min=\"0.001\" max=\"10\" size=\"5\">\n<input id=hshi value=-265 type=\"number\" min=\"-50000\" max=\"50000\" size=\"6\">\n<input id=vshi value=-260 type=\"number\" min=\"-50000\" max=\"50000\" size=\"6\">\n<input id=cli value=\"red\" type=\"text\" size=\"14\">\n<button onclick=\"pDragon('canvId')\">Plot it!<\/button>\n<h3>Dragon curve<\/h3>\n<canvas id=\"canvId\" width=640 height=640 style=\"border: 2px inset;\"><\/canvas>\n<\/body>\n<\/html>\n\n\nInput parameters:\n\nord scale x-shift y-shift color   [File name to save]\n-------------------------------------------\n11  7.    -265   -260   red       DC11.png\n15  2.    -205   -230   brown     DC15.png\n17  1.    -135    70    green     DC17.png\n19  0.6    380    440   navy      DC19.png\n21  0.22   1600   800   blue      DC21.png\n23  0.15   1100   800   violet    DC23.png\n25  0.07   2100   5400  darkgreen DC25.png\n===========================================\n\n\n","human_summarization":"The code generates a Dragon Curve fractal, either displaying it directly or writing it to an image file. It uses recursive algorithms to create the fractal, with the option of curling right or left. The code also includes a feature for successive approximation, which rewrites each straight line as two new segments at a right angle. It can also calculate the absolute direction and coordinates of a point, and test whether a given point or segment is on the curve. Additionally, the code can be invoked as a method for an SVG file.","id":2846}
    {"lang_cluster":"JavaScript","source_code":"\nfunction guessNumber() {\n  \/\/ Get a random integer from 1 to 10 inclusive\n  var num = Math.ceil(Math.random() * 10);\n  var guess;\n\n  while (guess != num) {\n    guess = prompt('Guess the number between 1 and 10 inclusive');\n  }\n  alert('Congratulations!\\nThe number was ' + num);\n}\n\nguessNumber();\n\n\n","human_summarization":"The code generates a random number between 1 and 10, then prompts the user to guess the number. If the guess is incorrect, the user is prompted again until the correct number is guessed. Once the correct number is guessed, a \"Well guessed!\" message is displayed and the program terminates. The code requires a host environment that supports prompt and alert functions, such as a browser.","id":2847}
    {"lang_cluster":"JavaScript","source_code":"\n\n(function (cFrom, cTo) {\n\n  function cRange(cFrom, cTo) {\n    var iStart = cFrom.charCodeAt(0);\n\n    return Array.apply(\n      null, Array(cTo.charCodeAt(0) - iStart + 1)\n    ).map(function (_, i) {\n\n      return String.fromCharCode(iStart + i);\n\n    });\n  }\n\n  return cRange(cFrom, cTo);\n\n})('a', 'z');\n\n\n[\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"]\n\n\n(function (lstRanges) {\n\n  function cRange(cFrom, cTo) {\n    var iStart = cFrom.codePointAt(0);\n\n    return Array.apply(\n      null, Array(cTo.codePointAt(0) - iStart + 1)\n    ).map(function (_, i) {\n\n      return String.fromCodePoint(iStart + i);\n\n    });\n  }\n\n  return lstRanges.map(function (lst) {\n    return cRange(lst[0], lst[1]);\n  });\n\n})([\n  ['a', 'z'],\n  ['\ud83d\udc10', '\ud83d\udc1f']\n]);\n\n\n[[\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\"],\n [\"\ud83d\udc10\", \"\ud83d\udc11\", \"\ud83d\udc12\", \"\ud83d\udc13\", \"\ud83d\udc14\", \"\ud83d\udc15\", \"\ud83d\udc16\", \"\ud83d\udc17\", \"\ud83d\udc18\", \"\ud83d\udc19\", \"\ud83d\udc1a\", \"\ud83d\udc1b\", \"\ud83d\udc1c\", \"\ud83d\udc1d\", \"\ud83d\udc1e\", \"\ud83d\udc1f\"]]\n\nWorks with: ECMAScript version 6\nvar letters = []\nfor (var i = 97; i <= 122; i++) {\n    letters.push(String.fromCodePoint(i))\n}\n\n\n(() => {\n    \/\/ enumFromTo\u00a0:: Enum a => a -> a -> [a]\n    const enumFromTo = (m, n) => {\n        const [intM, intN] = [m, n].map(fromEnum),\n            f = typeof m === 'string' ? (\n                (_, i) => chr(intM + i)\n            ) : (_, i) => intM + i;\n        return Array.from({\n            length: Math.floor(intN - intM) + 1\n        }, f);\n    };\n\n\n    \/\/ GENERIC FUNCTIONS ------------------------------------------------------\n\n    \/\/ compose\u00a0:: (b -> c) -> (a -> b) -> (a -> c)\n    const compose = (f, g) => x => f(g(x));\n\n    \/\/ chr\u00a0:: Int -> Char\n    const chr = x => String.fromCodePoint(x);\n\n    \/\/ ord\u00a0:: Char -> Int\n    const ord = c => c.codePointAt(0);\n\n    \/\/ fromEnum\u00a0:: Enum a => a -> Int\n    const fromEnum = x => {\n        const type = typeof x;\n        return type === 'boolean' ? (\n            x ? 1 : 0\n        ) : type === 'string' ? ord(x) : x;\n    };\n\n    \/\/ map\u00a0:: (a -> b) -> [a] -> [b]\n    const map = (f, xs) => xs.map(f);\n\n    \/\/ show\u00a0:: a -> String\n    const show = x => JSON.stringify(x);\n\n    \/\/ uncurry\u00a0:: Function -> Function\n    const uncurry = f => args => f.apply(null, args);\n\n    \/\/ unlines\u00a0:: [String] -> String\n    const unlines = xs => xs.join('\\n');\n\n    \/\/ unwords\u00a0:: [String] -> String\n    const unwords = xs => xs.join(' ');\n\n    \/\/ TEST -------------------------------------------------------------------\n    return unlines(map(compose(unwords, uncurry(enumFromTo)), [\n        ['a', 'z'],\n        ['\u03b1', '\u03c9'],\n        ['\u05d0', '\u05ea'],\n        ['\ud83d\udc10', '\ud83d\udc1f']\n    ]));\n})();\n\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. The code utilizes strong typing and is written in a style suitable for large programs. It avoids manual enumeration of characters to prevent bugs. It uses String.fromCharCode() in ES5 for Unicode characters represented with one 16-bit number, and String.fromCodePoint() in ES6 for 4-byte characters like emojis.","id":2848}
    {"lang_cluster":"JavaScript","source_code":"\nfunction toBinary(number) {\n    return new Number(number)\n        .toString(2);\n}\nvar demoValues = [5, 50, 9000];\nfor (var i = 0; i < demoValues.length; ++i) {\n    \/\/ alert() in a browser, wscript.echo in WSH, etc.\n    print(toBinary(demoValues[i])); \n}\n\n\n(() => {\n    \"use strict\";\n\n    \/\/ ------------------ BINARY DIGITS ------------------\n\n    \/\/ showBinary\u00a0:: Int -> String\n    const showBinary = n =>\n        showIntAtBase_(2)(n);\n\n\n    \/\/ showIntAtBase_\u00a0:: \/\/ Int -> Int -> String\n    const showIntAtBase_ = base =>\n        n => n.toString(base);\n\n\n    \/\/ ---------------------- TEST -----------------------\n    const main = () => [5, 50, 9000]\n        .map(n => `${n} -> ${showBinary(n)}`)\n        .join(\"\\n\");\n\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n\n","human_summarization":"The code takes a non-negative integer as input and converts it into a binary sequence. It uses built-in radix functions or a user-defined function to achieve this. The output is a sequence of binary digits followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The code also provides flexibility in the set of digits used.","id":2849}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction parseConfig(config) {\n    \/\/ this expression matches a line starting with an all capital word, \n    \/\/ and anything after it\n    var regex = \/^([A-Z]+)(.*)$\/mg;\n    var configObject = {};\n    \n    \/\/ loop until regex.exec returns null\n    var match;\n    while (match = regex.exec(config)) {\n        \/\/ values will typically be an array with one element\n        \/\/ unless we want an array\n        \/\/ match[0] is the whole match, match[1] is the first group (all caps word), \n        \/\/ and match[2] is the second (everything through the end of line)\n        var key = match[1], values = match[2].split(\",\");\n        if (values.length === 1) {\n            configObject[key] = values[0];\n        }\n        else {\n            configObject[key] = values.map(function(value){\n                return value.trim();\n            });\n        }\n    }\n    \n    return configObject;\n}\n\n\n{\n  \"FULLNAME\": \" Foo Barber\",\n  \"FAVOURITEFRUIT\": \" banana\",\n  \"NEEDSPEELING\": \"\",\n  \"OTHERFAMILY\": [\n    \"Rhu Barber\",\n    \"Harry Barber\"\n  ]\n}\n\n","human_summarization":"The code reads a configuration file in standard format, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration parameters. The parameters are not case sensitive, but their data is. An optional equals sign can separate the parameter data from the option name. A configuration option can have multiple parameters separated by commas. The code also handles an option with multiple parameters, storing them in an array. The result is an object represented in JSON.","id":2850}
    {"lang_cluster":"JavaScript","source_code":"function haversine() {\n       var radians = Array.prototype.map.call(arguments, function(deg) { return deg\/180.0 * Math.PI; });\n       var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3];\n       var R = 6372.8; \/\/ km\n       var dLat = lat2 - lat1;\n       var dLon = lon2 - lon1;\n       var a = Math.sin(dLat \/ 2) * Math.sin(dLat \/2) + Math.sin(dLon \/ 2) * Math.sin(dLon \/2) * Math.cos(lat1) * Math.cos(lat2);\n       var c = 2 * Math.asin(Math.sqrt(a));\n       return R * c;\n}\nconsole.log(haversine(36.12, -86.67, 33.94, -118.40));\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":2851}
    {"lang_cluster":"JavaScript","source_code":"\nvar req = new XMLHttpRequest();\nreq.onload = function() {\n  console.log(this.responseText);\n};\n\nreq.open('get', 'http:\/\/rosettacode.org', true);\nreq.send()\n\n\nfetch('http:\/\/rosettacode.org').then(function(response) {\n  return response.text();\n}).then(function(myText) {\n  console.log(myText);\n});\n\n\n\/**\n * @name _http\n * @description Generic API Client using XMLHttpRequest\n * @param {string} url The URI\/URL to connect to\n * @param {string} method The HTTP method to invoke- GET, POST, etc\n * @param {function} callback Once the HTTP request has completed, responseText is passed into this function for execution\n * @param {object} params Query Parameters in a JavaScript Object (Optional)\n * \n *\/\nfunction _http(url, method, callback, params) {\n    var xhr,\n        reqUrl;\n\n    xhr = new XMLHttpRequest();\n    xhr.onreadystatechange = function xhrProc() {\n        if (xhr.readyState == 4 && xhr.status == 200) {\n            callback(xhr.responseText);\n        }\n    };\n\n\n    \/** If Query Parameters are present, handle them... *\/\n    if (typeof params === 'undefined') {\n        reqUrl = url;\n    } else {\n        switch (method) {\n            case 'GET':\n                reqUrl = url + procQueryParams(params);\n                break;\n            case 'POST':\n                reqUrl = url;\n                break;\n            default:\n        }\n    }\n\n\n    \/** Send the HTTP Request *\/\n    if (reqUrl) {\n        xhr.open(method, reqUrl, true);\n        xhr.setRequestHeader(\"Accept\", \"application\/json\");\n\n        if (method === 'POST') {\n            xhr.send(params);\n        } else {\n            xhr.send();\n        }\n    }\n\n\n    \/**\n     * @name procQueryParams\n     * @description Return function that converts Query Parameters from a JavaScript Object to a proper URL encoded string\n     * @param {object} params Query Parameters in a JavaScript Object\n     * \n     *\/\n    function procQueryParams(params) {\n        return \"?\" + Object\n            .keys(params)\n            .map(function (key) {\n                return key + \"=\" + encodeURIComponent(params[key])\n            })\n            .join(\"&\")\n    }\n}\n\n\n$.get('http:\/\/rosettacode.org', function(data) {\n  console.log(data);\n};\n\n\nconst http = require('http');\n \nhttp.get('http:\/\/rosettacode.org', (resp) => {\n\n  let data = '';\n \n  \/\/ A chunk of data has been recieved.\n  resp.on('data', (chunk) => {\n    data += chunk;\n  });\n \n  \/\/ The whole response has been received. Print out the result.\n  resp.on('end', () => {\n    console.log(\"Data:\", data);\n  });\n \n}).on(\"error\", (err) => {\n  console.log(\"Error: \" + err.message);\n});\n\n","human_summarization":"- Access a URL's content using HTTP request\n- Print the retrieved content to the console\n- The function is repeatable\n- The task is accomplished using fetch API, jQuery, and Node.js with the included http module\n- Note: The task does not handle HTTPS requests.","id":2852}
    {"lang_cluster":"JavaScript","source_code":"\n\nmod10check = function(cc) {\n  return $A(cc).reverse().map(Number).inject(0, function(s, d, i) {\n    return s + (i % 2 == 1 ? (d == 9 ? 9 : (d * 2) % 9) : d);\n  }) % 10 == 0;\n};\n['49927398716','49927398717','1234567812345678','1234567812345670'].each(function(i){alert(mod10check(i))});\n\n\nvar LuhnCheck = (function()\n{\n\tvar luhnArr = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9];\n\treturn function(str)\n\t{\n\t\tvar counter = 0;\n\t\tvar incNum;\n\t\tvar odd = false;\n\t\tvar temp = String(str).replace(\/[^\\d]\/g, \"\");\n\t\tif ( temp.length == 0)\n\t\t\treturn false;\n\t\tfor (var i = temp.length-1; i >= 0; --i)\n\t\t{\n\t\t\tincNum = parseInt(temp.charAt(i), 10);\n\t\t\tcounter += (odd = !odd)? incNum : luhnArr[incNum];\n\t\t}\n\t\treturn (counter%10 == 0);\n\t}\n})();\n\n\nvar luhn10 = function(a,b,c,d,e) {\n  for(d = +a[b = a.length-1], e=0; b--;)\n    c = +a[b], d += ++e % 2 ? 2 * c % 10 + (c > 4) : c;\n  return !(d%10)\n};\n\n\/\/ returns true\nluhn10('4111111111111111') \n\n\/\/ returns false\nluhn10('4111111111111112')\n\n\nconst lunhCheck = (str) => {\n    const sumDigit = (c) => (c < 10) ? c :\n              sumDigit( Math.trunc(c \/ 10) + (c % 10));\n    \n    return str.split('').reverse()\n              .map(Number)\n              .map((c, i) => i % 2 !== 0 ? sumDigit(c * 2) : c)\n              .reduce((acc,v) => acc + v) % 10 === 0;\n};\n\nlunhCheck('49927398716'); \/\/ returns true\nlunhCheck('49927398717'); \/\/ returns false\nlunhCheck('1234567812345678'); \/\/ returns false\nlunhCheck('1234567812345670'); \/\/ returns true\n\n","human_summarization":"The code implements the Luhn test for validating credit card numbers. It first reverses the number, then calculates the sum of odd and even digits separately. For even digits, it multiplies each by two and if the result is greater than nine, it sums the digits. It adds the sums of odd and even digits, and if the result ends in zero, the number is considered valid. The code validates four specific credit card numbers. The implementation is a naive, highly compressed version without using any libraries.","id":2853}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar Josephus = {\n  init: function(n) {\n    this.head = {};\n    var current = this.head;\n    for (var i = 0; i < n-1; i++) {\n      current.label = i+1;\n      current.next = {prev: current};\n      current = current.next;\n    }\n    current.label = n;\n    current.next = this.head;\n    this.head.prev = current;\n    return this;\n  },\n  kill: function(spacing) {\n    var current = this.head;\n    while (current.next !== current) {\n      for (var i = 0; i < spacing-1; i++) {\n        current = current.next;\n      }\n      current.prev.next = current.next;\n      current.next.prev = current.prev;\n      current = current.next;\n    }\n    return current.label;\n  }\n}\n\n\n","human_summarization":"The code takes two inputs, the total number of prisoners (n) and the step count (k), and calculates which prisoner will be the last survivor in the Josephus problem. It also provides a method to determine the position of any prisoner in the killing sequence. The prisoners can be numbered from either 0 or 1. The code follows the execution procedure as described, walking around the circle and eliminating every k-th prisoner until only one remains. The complexity of the code is O(kn) for generating the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":2854}
    {"lang_cluster":"JavaScript","source_code":"\n\nString.prototype.repeat = function(n) {\n    return new Array(1 + (n || 0)).join(this);\n}\n\nconsole.log(\"ha\".repeat(5));  \/\/ hahahahaha\n\nconsole.log(\"ha\".repeat(5));  \/\/ hahahahaha\n\n(() => {\n    'use strict';\n\n    \/\/ replicate\u00a0:: Int -> String -> String\n    const replicate = (n, s) => {\n        let v = [s],\n            o = [];\n        if (n < 1) return o;\n        while (n > 1) {\n            if (n & 1) o = o + v;\n            n >>= 1;\n            v = v + v;\n        }\n        return o.concat(v);\n    };\n\n\n    return replicate(5000, \"ha\")\n})();\n\n(() => {\n    'use strict';\n\n    \/\/ repeat\u00a0:: Int -> String -> String\n    const repeat = (n, s) => \n        concat(replicate(n, s));\n        \n\n    \/\/ GENERIC FUNCTIONS ------------------------------------------------------\n\n    \/\/ concat\u00a0:: [[a]] -> [a] | [String] -> String\n    const concat = xs =>\n        xs.length > 0\u00a0? (() => {\n            const unit = typeof xs[0] === 'string'\u00a0? ''\u00a0: [];\n            return unit.concat.apply(unit, xs);\n        })()\u00a0: [];\n\n    \/\/ replicate\u00a0:: Int -> a -> [a]\n    const replicate = (n, x) =>\n        Array.from({\n            length: n\n        }, () => x);\n\n\n    \/\/ TEST -------------------------------------------------------------------\n    return repeat(5, 'ha');\n})();\n\n","human_summarization":"are designed to repeat a given string a specific number of times. The initial solution creates an empty array of the required length and uses the array's join method to concatenate the string. However, for larger repetitions, the code uses a more efficient method of progressively doubling a copy of the original string. This is based on the 'Egyptian Multiplication' technique. As of ES6, the built-in `repeat` function can be used to achieve this. The code also includes a method to repeat a single character to form a new string.","id":2855}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar subject = \"Hello world!\";\n\n\/\/ Two different ways to create the RegExp object\n\/\/ Both examples use the exact same pattern... matching \"hello \"\nvar re_PatternToMatch = \/Hello (World)\/i; \/\/ creates a RegExp literal with case-insensitivity\nvar re_PatternToMatch2 = new RegExp(\"Hello (World)\", \"i\");\n\n\/\/ Test for a match - return a bool\nvar isMatch = re_PatternToMatch.test(subject);\n\n\/\/ Get the match details\n\/\/    Returns an array with the match's details\n\/\/    matches[0] == \"Hello world\"\n\/\/    matches[1] == \"world\"\nvar matches = re_PatternToMatch2.exec(subject);\n\n\nvar subject = \"Hello world!\";\n\n\/\/ Perform a string replacement\n\/\/    newSubject == \"Replaced!\"\nvar newSubject = subject.replace(re_PatternToMatch, \"Replaced\");\n\n","human_summarization":"\"Matches a string with a regular expression and performs substitution on a part of the string using another regular expression.\"","id":2856}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: JScript\nWorks with: SpiderMonkey\n\nvar a = parseInt(get_input(\"Enter an integer\"), 10);\nvar b = parseInt(get_input(\"Enter an integer\"), 10);\n\nWScript.Echo(\"a = \" + a);\nWScript.Echo(\"b = \" + b);\nWScript.Echo(\"sum: a + b = \"        + (a + b));\nWScript.Echo(\"difference: a - b = \" + (a - b));\nWScript.Echo(\"product: a * b = \"    + (a * b));\nWScript.Echo(\"quotient: a \/ b = \"   + (a \/ b | 0)); \/\/ \"| 0\" casts it to an integer\nWScript.Echo(\"remainder: a\u00a0% b = \"  + (a % b));\n\nfunction get_input(prompt) {\n    output(prompt);\n    try {\n        return WScript.StdIn.readLine();\n    } catch(e) {\n        return readline();\n    }\n}\nfunction output(prompt) {\n    try {\n        WScript.Echo(prompt);\n    } catch(e) {\n        print(prompt);\n    }\n}\n\n\n","human_summarization":"take two integers as input from the user and calculate their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding method for the quotient and the sign of the remainder. Additionally, it demonstrates the use of the 'divmod' operator. No error handling is incorporated in the code.","id":2857}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction countSubstring(str, subStr) {\n    var matches = str.match(new RegExp(subStr, \"g\"));\n    return matches ? matches.length : 0;\n}\n\n\nconst countSubString = (str, subStr) => str.split(subStr).length - 1;\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the main string and the substring to search for. It returns an integer representing the count of the non-overlapping occurrences. The function does not count overlapping substrings and matches from left-to-right or right-to-left for the highest number of non-overlapping matches. The function can be implemented using regular expressions or 'split' in ES6 notation.","id":2858}
    {"lang_cluster":"JavaScript","source_code":"\nfunction move(n, a, b, c) {\n  if (n > 0) {\n    move(n-1, a, c, b);\n    console.log(\"Move disk from \" + a + \" to \" + c);\n    move(n-1, b, a, c);\n  }\n}\nmove(4, \"A\", \"B\", \"C\");\n\n\n(function () {\n\n    \/\/ hanoi\u00a0:: Int -> String -> String -> String -> [[String, String]]\n    function hanoi(n, a, b, c) {\n        return n ? hanoi(n - 1, a, c, b)\n            .concat([\n                [a, b]\n            ])\n            .concat(hanoi(n - 1, c, b, a)) : [];\n    }\n\n    return hanoi(3, 'left', 'right', 'mid')\n        .map(function (d) {\n            return d[0] + ' -> ' + d[1];\n        });\n})();\n\n\n","human_summarization":"\"Solve the Towers of Hanoi problem using recursion\"","id":2859}
    {"lang_cluster":"JavaScript","source_code":"\nfunction binom(n, k) {\n    var coeff = 1;\n    var i;\n\n    if (k < 0 || k > n) return 0;\n\n    for (i = 0; i < k; i++) {\n        coeff = coeff * (n - i) \/ (i + 1);\n    }\n  \n    return coeff;\n}\n\nconsole.log(binom(5, 3));\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":2860}
    {"lang_cluster":"JavaScript","source_code":"\nfunction shellSort (a) {\n    for (var h = a.length; h > 0; h = parseInt(h \/ 2)) {\n        for (var i = h; i < a.length; i++) {\n            var k = a[i];\n            for (var j = i; j >= h && k < a[j - h]; j -= h)\n                a[j] = a[j - h];\n            a[j] = k;\n        }\n    }\n    return a;\n}\n\nvar a = [];\nvar n = location.href.match(\/\\?(\\d+)|$\/)[1] || 10;\nfor (var i = 0; i < n; i++)\n    a.push(parseInt(Math.random() * 100));\nshellSort(a);\ndocument.write(a.join(\" \"));\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":2861}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction toGray(img) {\n  let cnv = document.getElementById(\"canvas\");\n  let ctx = cnv.getContext('2d');\n  let imgW = img.width;\n  let imgH = img.height;\n  cnv.width = imgW;\n  cnv.height = imgH;\n  \n  ctx.drawImage(img, 0, 0);\n  let pixels = ctx.getImageData(0, 0, imgW, imgH);\n  for (let y = 0; y < pixels.height; y ++) {\n    for (let x = 0; x < pixels.width; x ++) {\n      let i = (y * 4) * pixels.width + x * 4;\n      let avg = (pixels.data[i] + pixels.data[i + 1] + pixels.data[i + 2]) \/ 3;\n      \n      pixels.data[i] = avg;\n      pixels.data[i + 1] = avg;\n      pixels.data[i + 2] = avg;\n    }\n  }\n  ctx.putImageData(pixels, 0, 0, 0, 0, pixels.width, pixels.height);\n  return cnv.toDataURL();\n}\n\n","human_summarization":"The code extends the data storage type to support grayscale images. It defines two operations: one for converting a color image to a grayscale image and one for the reverse conversion. It uses the CIE recommended formula for luminance calculation and ensures no rounding errors cause runtime issues or distorted results. It also includes a demonstration using HTML 5.","id":2862}
    {"lang_cluster":"JavaScript","source_code":"\nvar val = 0;\ndo {\n  print(++val);\n} while (val % 6);\n\n\nAn initial value,\na Do function which transforms that value repetitively, corresponding to the body of the loop,\nand a conditional While function.\nfunction doWhile(varValue, fnBody, fnTest) {\n  'use strict';\n  var d = fnBody(varValue); \/\/ a transformed value\n\n  return fnTest(d) ? [d].concat(\n    doWhile(d, fnBody, fnTest)\n  ) : [d];\n}\n\nconsole.log(\n  doWhile(0,           \/\/ initial value\n    function (x) {     \/\/ Do body, returning transformed value\n      return x + 1;\n    },\n    function (x) {     \/\/ While condition\n      return x % 6;\n    }\n  ).join('\\n')\n);\n\n\n1\n2\n3\n4\n5\n6\n\n\nfunction range(m, n) {\n  'use strict';\n  return Array.apply(null, Array(n - m + 1)).map(\n    function (x, i) {\n      return m + i;\n    }\n  );\n}\n \nfunction takeWhile(lst, fnTest) {\n 'use strict';\n  var varHead = lst.length ? lst[0] : null;\n \n  return varHead ? (\n    fnTest(varHead) ? [varHead].concat(\n      takeWhile(lst.slice(1), fnTest)\n    ) : []\n  ) : []\n}\n \nconsole.log(\n  takeWhile(\n    range(1, 100),\n    function (x) {\n      return x % 6;\n    }\n  ).join('\\n')\n);\n\n\n1\n2\n3\n4\n5\n\n\n(() => {\n    'use strict';\n\n    \/\/ unfoldr\u00a0:: (b -> Maybe (a, b)) -> b -> [a]\n    function unfoldr(mf, v) {\n        for (var lst = [], a = v, m;\n            (m = mf(a)) && m.valid;) {\n            lst.push(m.value), a = m.new;\n        }\n        return lst;\n    }\n\n    \/\/ until\u00a0:: (a -> Bool) -> (a -> a) -> a -> a\n    function until(p, f, x) {\n        let v = x;\n        while(!p(v)) v = f(v);\n        return v;\n    }\n\n    let result1 = unfoldr(\n        x => {\n            return {\n                value: x,\n                valid: (x % 6) !== 0,\n                new: x + 1\n            }\n        },\n        1\n    );\n\n    let result2 = until(\n        m => (m.n % 6) === 0,\n        m => {\n            return {\n                n : m.n + 1,\n                xs : m.xs.concat(m.n)\n            };\n        },\n        {\n            n: 1,\n            xs: []\n        }\n    ).xs;\n    \n    return [result1, result2];\n})();\n\n[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]\n\n\n\/\/ generator with the do while loop\nfunction* getValue(stop) {\n    var i = 0;\n    do {\n        yield ++i;\n    } while (i % stop != 0);\n}\n\n\/\/ function to print the value and invoke next\nfunction printVal(g, v) {\n    if (!v.done) {\n        console.log(v.value);\n        setImmediate(printVal, g, g.next());\n    }\n}\n\n(() => {\n    var gen = getValue(6);\n    printVal(gen, gen.next());\n})();\n\n1\n2\n3\n4\n5\n6\n\n","human_summarization":"implement a do-while loop that starts with a value of 0 and continues until the value modulo 6 is not equal to 0. In each iteration, the value is incremented by 1 and printed. This is achieved using a composable doWhile function in functional JavaScript, which takes three arguments and returns the output series. The task can also be interpreted as deriving the membership of a set using the takeWhile function. The process can be better expressed with an unfold or until function, returning a list. The code also includes an example of a do-while loop in a generator in ES6, a superset of JavaScript.","id":2863}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar s = \"Hello, world!\";\nvar byteCount = s.length * 2; \/\/ 26\n\n\na = '\ud83d\udc69\u200d\u2764\ufe0f\u200d\ud83d\udc69'\nBuffer.byteLength(a, 'utf16le'); \/\/ 16\nBuffer.byteLength(a, 'utf8'); \/\/ 20\nBuffer.byteLength(s, 'utf16le'); \/\/ 26\nBuffer.byteLength(s, 'utf8'); \/\/ 13\n\n\n(new TextEncoder().encode(a)).length; \/\/ 20\n(new TextEncoder().encode(s)).length; \/\/ 13\n\n\nvar str1 = \"Hello, world!\";\nvar len1 = str1.length; \/\/ 13\n\nvar str2 = \"\\uD834\\uDD2A\"; \/\/ U+1D12A represented by a UTF-16 surrogate pair\nvar len2 = str2.length; \/\/ 2\n\n\n[...str2].length \/\/ 1\n\n\n[...new Intl.Segmenter().segment(a)].length; \/\/ 1\n\nlet\n  str='A\u00f6\u0416\u20ac\ud834\udd1e'\n ,countofcodeunits=str.length \/\/ 6\n ,cparr=[...str],\n ,countofcodepoints=cparr.length; \/\/ 5\n{ let\n    count=0\n  for(let codepoint of str)\n    count++\n  countofcodepoints=count \/\/ 5\n}\n{ let\n    count=0,\n    it=str[Symbol.iterator]()\n  while(!it.next().done)\n    count++\n  countofcodepoints=count \/\/ 5\n}\n{ cparr=Array.from(str)\n  countofcodepoints=cparr.length \/\/ 5\n}\n","human_summarization":"determine the character and byte length of a string, considering different encodings such as UTF-8 and UTF-16. It properly handles Unicode code points, including non-BMP ones, and provides the actual character counts in code points. It also provides the string length in graphemes if possible. The code uses JavaScript's UTF-16 encoding system and utilizes Buffer.byteLength, TextEncoder(), and Intl.Segmenter() functions to accurately calculate the byte size and grapheme count.","id":2864}
    {"lang_cluster":"JavaScript","source_code":"\nalert(\"knight\".slice(1));       \/\/ strip first character\nalert(\"socks\".slice(0, -1));    \/\/ strip last character\nalert(\"brooms\".slice(1, -1));   \/\/ strip both first and last characters\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":2865}
    {"lang_cluster":"JavaScript","source_code":"\n\/\/-------------------------------------------[ Dancing Links and Algorithm X ]--\n\/**\n * The doubly-doubly circularly linked data object.\n * Data object X\n *\/\nclass DoX {\n  \/**\n   * @param {string} V\n   * @param {!DoX=} H\n   *\/\n  constructor(V, H) {\n    this.V = V;\n    this.L = this;\n    this.R = this;\n    this.U = this;\n    this.D = this;\n    this.S = 1;\n    this.H = H || this;\n    H && (H.S += 1);\n  }\n}\n\n\/**\n * Helper function to help build a horizontal doubly linked list.\n * @param {!DoX} e An existing node in the list.\n * @param {!DoX} n A new node to add to the right of the existing node.\n * @return {!DoX}\n *\/\nconst addRight = (e, n) => {\n  n.R = e.R;\n  n.L = e;\n  e.R.L = n;\n  return e.R = n;\n};\n\n\/**\n * Helper function to help build a vertical doubly linked list.\n * @param {!DoX} e An existing node in the list.\n * @param {!DoX} n A new node to add below the existing node.\n *\/\nconst addBelow = (e, n) => {\n  n.D = e.D;\n  n.U = e;\n  e.D.U = n;\n  return e.D = n;\n};\n\n\/**\n * Verbatim copy of DK's search algorithm. The meat of the DLX algorithm.\n * @param {!DoX} h The root node.\n * @param {!Array<!DoX>} s The solution array.\n *\/\nconst search = function(h, s) {\n  if (h.R == h) {\n    printSol(s);\n  } else {\n    let c = chooseColumn(h);\n    cover(c);\n    for (let r = c.D; r != c; r = r.D) {\n      s.push(r);\n      for (let j = r.R; r !=j; j = j.R) {\n        cover(j.H);\n      }\n      search(h, s);\n      r = s.pop();\n      for (let j = r.R; j != r; j = j.R) {\n        uncover(j.H);\n      }\n    }\n    uncover(c);\n  }\n};\n\n\/**\n * Verbatim copy of DK's algorithm for choosing the next column object.\n * @param {!DoX} h\n * @return {!DoX}\n *\/\nconst chooseColumn = h => {\n  let s = Number.POSITIVE_INFINITY;\n  let c = h;\n  for(let j = h.R; j != h; j = j.R) {\n    if (j.S < s) {\n      c = j;\n      s = j.S;\n    }\n  }\n  return c;\n};\n\n\n\/**\n * Verbatim copy of DK's cover algorithm\n * @param {!DoX} c\n *\/\nconst cover = c => {\n  c.L.R = c.R;\n  c.R.L = c.L;\n  for (let i = c.D; i != c; i = i.D) {\n    for (let j = i.R; j != i; j = j.R) {\n      j.U.D = j.D;\n      j.D.U = j.U;\n      j.H.S = j.H.S - 1;\n    }\n  }\n};\n\n\/**\n * Verbatim copy of DK's cover algorithm\n * @param {!DoX} c\n *\/\nconst uncover = c => {\n  for (let i = c.U; i != c; i = i.U) {\n    for (let j = i.L; i != j; j = j.L) {\n      j.H.S = j.H.S + 1;\n      j.U.D = j;\n      j.D.U = j;\n    }\n  }\n  c.L.R = c;\n  c.R.L = c;\n};\n\n\/\/-----------------------------------------------------------[ Print Helpers ]--\n\/**\n * Given the standard string format of a grid, print a formatted view of it.\n * @param {!string|!Array} a\n *\/\nconst printGrid = function(a) {\n\n  const getChar = c => {\n    let r = Number(c);\n    if (isNaN(r)) { return c }\n\n    let o = 48;\n    if (r > 9 && r < 36) { o = 55 }\n    if (r >= 36) { o = 61 }\n    return String.fromCharCode(r + o)\n  };\n\n  a = 'string' == typeof a ? a.split('') : a;\n\n  let U = Math.sqrt(a.length);\n  let N = Math.sqrt(U);\n  let line = new Array(N).fill('+').reduce((p, c) => {\n    p.push(... Array.from(new Array(1 + N*2).fill('-')));\n    p.push(c);\n    return p;\n  }, ['\\n+']).join('') + '\\n';\n\n  a = a.reduce(function(p, c, i) {\n      let d = i && !(i % U), G = i && !(i % N);\n      i = !(i % (U * N));\n      d && !i && (p += '|\\n| ');\n      d && i && (p += '|');\n      i && (p = '' + p + line + '| ');\n      return '' + p + (G && !d ? '| ' : '') + getChar(c) + ' ';\n    }, '') + '|' + line;\n  console.log(a);\n\n};\n\n\/**\n * Given a search solution, print the resultant grid.\n * @param {!Array<!DoX>} a An array of data objects\n *\/\nconst printSol = a => {\n  printGrid(a.reduce((p, c) => {\n    let [i, v] = c.V.split(':');\n    p[i * 1] = v;\n    return p;\n  }, new Array(a.length).fill('.')));\n};\n\n\/\/----------------------------------------------[ Grid to Exact cover Matrix ]--\n\/**\n * Helper to get some meta about the grid.\n * @param {!string} s The standard string representation of a grid.\n * @return {!Array}\n *\/\nconst gridMeta = s => {\n  const g = s.split('');\n  const cellCount = g.length;\n  const tokenCount = Math.sqrt(cellCount);\n  const N = Math.sqrt(tokenCount);\n  const g2D = g.map(e => isNaN(e * 1) ?\n    new Array(tokenCount).fill(1).map((_, i) => i + 1) :\n    [e * 1]);\n  return [cellCount, N, tokenCount, g2D];\n};\n\n\/**\n * Given a cell grid index, return the row, column and box indexes.\n * @param {!number} n The n-value of the grid. 3 for a 9x9 sudoku.\n * @return {!function(!number): !Array<!number>}\n *\/\nconst indexesN = n => i => {\n    let c = Math.floor(i \/ (n * n));\n    i %= n * n;\n    return [c, i, Math.floor(c \/ n) * n + Math.floor(i \/ n)];\n};\n\n\/**\n * Given a puzzle string, reduce it to an exact-cover matrix and use\n * Donald Knuth's DLX algorithm to solve it.\n * @param puzString\n *\/\nconst reduceGrid = puzString => {\n\n  printGrid(puzString);\n  const [\n    numCells,   \/\/ The total number of cells in a grid (81 for a 9x9 grid)\n    N,          \/\/ the 'n' value of the grid. (3 for a 9x9 grid)\n    U,          \/\/ The total number of unique tokens to be placed.\n    g2D         \/\/ A 2D array representation of the grid, with each element\n                \/\/ being an array of candidates for a cell. Known cells are\n                \/\/ single element arrays.\n  ] = gridMeta(puzString);\n\n  const getIndex = indexesN(N);\n\n  \/**\n   * The DLX Header row.\n   * Its length is 4 times the grid's size. This is to be able to encode\n   * each of the 4 Sudoku constrains, onto each of the cells of the grid.\n   * The array is initialised with unlinked DoX nodes, but in the next step\n   * those nodes are all linked.\n   * @type {!Array.<!DoX>}\n   *\/\n  const headRow = new Array(4 * numCells)\n    .fill('')\n    .map((_, i) => new DoX(`H${i}`));\n\n  \/**\n   * The header row root object. This is circularly linked to be to the left\n   * of the first header object in the header row array.\n   * It is used as the entry point into the DLX algorithm.\n   * @type {!DoX}\n   *\/\n  let H = new DoX('ROOT');\n  headRow.reduce((p, c) => addRight(p, c), H);\n\n  \/**\n   * Transposed the sudoku puzzle into a exact cover matrix, so it can be passed\n   * to the DLX algorithm to solve.\n   *\/\n  for (let i = 0; i < numCells; i++) {\n    const [ri, ci, bi] = getIndex(i);\n    g2D[i].forEach(num => {\n      let id = `${i}:${num}`;\n      let candIdx = num - 1;\n\n      \/\/ The 4 columns that we will populate.\n      const A = headRow[i];\n      const B = headRow[numCells + candIdx + (ri * U)];\n      const C = headRow[(numCells * 2) + candIdx + (ci * U)];\n      const D = headRow[(numCells * 3) + candIdx + (bi * U)];\n\n      \/\/ The Row-Column Constraint\n      let rcc = addBelow(A.U, new DoX(id, A));\n\n      \/\/ The Row-Number Constraint\n      let rnc = addBelow(B.U, addRight(rcc, new DoX(id, B)));\n\n      \/\/ The Column-Number Constraint\n      let cnc = addBelow(C.U, addRight(rnc, new DoX(id, C)));\n\n      \/\/ The Block-Number Constraint\n      addBelow(D.U, addRight(cnc, new DoX(id, D)));\n    });\n  }\n  search(H, []);\n};\n\n[\n  '819..5.....2...75..371.4.6.4..59.1..7..3.8..2..3.62..7.5.7.921..64...9.....2..438',\n  '53..247....2...8..1..7.39.2..8.72.49.2.98..7.79.....8.....3.5.696..1.3...5.69..1.',\n  '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..',\n  '394..267....3..4..5..69..2..45...9..6.......7..7...58..1..67..8..9..8....264..735',\n  '97.3...6..6.75.........8.5.......67.....3.....539..2..7...25.....2.1...8.4...73..',\n  '4......6.5...8.9..3....1....2.7....1.9.....4.8....3.5....2....7..6.5...8.1......6',\n  '85...24..72......9..4.........1.7..23.5...9...4...........8..7..17..........36.4.',\n  '..1..5.7.92.6.......8...6...9..2.4.1.........3.4.8..9...7...3.......7.69.1.8..7..',\n  '.9...4..7.....79..8........4.58.....3.......2.....97.6........4..35.....2..6...8.',\n  '12.3....435....1....4........54..2..6...7.........8.9...31..5.......9.7.....6...8',\n  '9..2..5...4..6..3...3.....6...9..2......5..8...7..4..37.....1...5..2..4...1..6..9',\n  '1....7.9..3..2...8..96..5....53..9...1..8...26....4...3......1..4......7..7...3..',\n  '12.4..3..3...1..5...6...1..7...9.....4.6.3.....3..2...5...8.7....7.....5.......98',\n  '..............3.85..1.2.......5.7.....4...1...9.......5......73..2.1........4...9',\n  '.......39.....1..5..3.5.8....8.9...6.7...2...1..4.......9.8..5..2....6..4..7.....',\n  '....839..1......3...4....7..42.3....6.......4....7..1..2........8...92.....25...6',\n  '..3......4...8..36..8...1...4..6..73...9..........2..5..4.7..686........7..6..5..'\n].forEach(reduceGrid);\n\n\/\/ Or of you want to create all the grids of a particular n-size.\n\/\/ I run out of stack space at n = 9\nlet n = 2;\nlet s = new Array(Math.pow(n, 4)).fill('.').join('');\nreduceGrid(s);\n\n+-------+-------+-------+\n| . . 3 | . . . | . . . |\n| 4 . . | . 8 . | . 3 6 |\n| . . 8 | . . . | 1 . . |\n+-------+-------+-------+\n| . 4 . | . 6 . | . 7 3 |\n| . . . | 9 . . | . . . |\n| . . . | . . 2 | . . 5 |\n+-------+-------+-------+\n| . . 4 | . 7 . | . 6 8 |\n| 6 . . | . . . | . . . |\n| 7 . . | 6 . . | 5 . . |\n+-------+-------+-------+\n\n+-------+-------+-------+\n| 1 2 3 | 4 5 6 | 7 8 9 |\n| 4 5 7 | 1 8 9 | 2 3 6 |\n| 9 6 8 | 3 2 7 | 1 5 4 |\n+-------+-------+-------+\n| 2 4 9 | 5 6 1 | 8 7 3 |\n| 5 7 6 | 9 3 8 | 4 1 2 |\n| 8 3 1 | 7 4 2 | 6 9 5 |\n+-------+-------+-------+\n| 3 1 4 | 2 7 5 | 9 6 8 |\n| 6 9 5 | 8 1 4 | 3 2 7 |\n| 7 8 2 | 6 9 3 | 5 4 1 |\n+-------+-------+-------+\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":2866}
    {"lang_cluster":"JavaScript","source_code":"\nfunction knuthShuffle(arr) {\n    var rand, temp, i;\n\n    for (i = arr.length - 1; i > 0; i -= 1) {\n        rand = Math.floor((i + 1) * Math.random());\/\/get random between zero and i (inclusive)\n        temp = arr[rand];\n        arr[rand] = arr[i]; \/\/swap i (last element) with random element.\n        arr[i] = temp;\n    }\n    return arr;\n}\n\nvar res = {\n    '1,2,3': 0, '1,3,2': 0,\n    '2,1,3': 0, '2,3,1': 0,\n    '3,1,2': 0, '3,2,1': 0\n};\n\nfor (var i = 0; i < 100000; i++) {\n    res[knuthShuffle([1,2,3]).join(',')] += 1;\n}\n\nfor (var key in res) {\n    print(key + \"\\t\" + res[key]);\n}\n\n\n1,2,3   16619\n1,3,2   16614\n2,1,3   16752\n2,3,1   16959\n3,1,2   16460\n3,2,1   16596\n(() => {\n\n    \/\/ knuthShuffle\u00a0:: [a] -> [a]\n    const knuthShuffle = xs =>\n        enumFromTo(0, xs.length - 1)\n        .reduceRight((a, i) => {\n            const\n                iRand =  randomRInt(0, i),\n                tmp = a[iRand];\n            return iRand !== i ? (\n                a[iRand] = a[i],\n                a[i] = tmp,\n                a\n            ) : a;\n        }, xs);\n\n    const test = () => knuthShuffle(\n        (`alpha beta gamma delta epsilon zeta\n              eta theta iota kappa lambda mu`)\n        .split(\/\\s+\/)\n    );\n\n    \/\/ GENERIC FUNCTIONS ----------------------------------\n\n    \/\/ enumFromTo\u00a0:: Int -> Int -> [Int]\n    const enumFromTo = (m, n) =>\n        n >= m ? (\n            iterateUntil(x => x >= n, x => 1 + x, m)\n        ) : [];\n\n    \/\/ iterateUntil\u00a0:: (a -> Bool) -> (a -> a) -> a -> [a]\n    const iterateUntil = (p, f, x) => {\n        let vs = [x],\n            h = x;\n        while (!p(h))(h = f(h), vs.push(h));\n        return vs;\n    };\n\n    \/\/ randomRInt\u00a0:: Int -> Int -> Int\n    const randomRInt = (low, high) =>\n        low + Math.floor(\n            (Math.random() * ((high - low) + 1))\n        );\n\n    return test();\n})();\n\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. It can be modified to return a new array if in-place modification is not suitable. The algorithm can also be adjusted to iterate from left to right if needed.","id":2867}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: Nodejs\nvar last_friday_of_month, print_last_fridays_of_month;\n\nlast_friday_of_month = function(year, month) {\n  var i, last_day;\n  i = 0;\n  while (true) {\n    last_day = new Date(year, month, i);\n    if (last_day.getDay() === 5) {\n      return last_day.toDateString();\n    }\n    i -= 1;\n  }\n};\n\nprint_last_fridays_of_month = function(year) {\n  var month, results;\n  results = [];\n  for (month = 1; month <= 12; ++month) {\n    results.push(console.log(last_friday_of_month(year, month)));\n  }\n  return results;\n};\n\n(function() {\n  var year;\n  year = parseInt(process.argv[2]);\n  return print_last_fridays_of_month(year);\n})();\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":2868}
    {"lang_cluster":"JavaScript","source_code":"\n\nprocess.stdout.write(\"Goodbye, World!\");\n\n","human_summarization":"\"Display the string 'Goodbye, World!' in Node JS without a trailing newline.\"","id":2869}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: FireFox or any JavaScript-enabled browser\nvar str = prompt(\"Enter a string\");\nvar value = 0;\nwhile (value != 75000) {\n    value = parseInt( prompt(\"Enter the number 75000\") );\n}\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":2870}
    {"lang_cluster":"JavaScript","source_code":"\nfunction caesar (text, shift) {\n  return text.toUpperCase().replace(\/[^A-Z]\/g,'').replace(\/.\/g, function(a) {\n    return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26);\n  });\n}\n\n\/\/ Tests\nvar text = 'veni, vidi, vici';\nfor (var i = 0; i<26; i++) {\n  console.log(i+': '+caesar(text,i));\n}\n\n\n","human_summarization":"implement a Caesar cipher for encoding and decoding messages. The key used for the cipher is an integer between 1 and 25, which represents the number of positions each letter in the message is shifted in the alphabet. The cipher also supports both lower and upper case letters. The Caesar cipher is a simple mono-alphabetic substitution cipher and is identical to the Vigen\u00e8re cipher with a key of length 1 and to the Rot-13 cipher with a key of 13.","id":2871}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction LCM(A)  \/\/ A is an integer array (e.g. [-50,25,-45,-18,90,447])\n{   \n    var n = A.length, a = Math.abs(A[0]);\n    for (var i = 1; i < n; i++)\n     { var b = Math.abs(A[i]), c = a;\n       while (a && b){ a > b ? a %= b : b %= a; } \n       a = Math.abs(c*A[i])\/(a+b);\n     }\n    return a;\n}\n\n\/* For example:\n   LCM([-50,25,-45,-18,90,447]) -> 67050\n*\/\n\n(() => {\n    'use strict';\n\n    \/\/ gcd\u00a0:: Integral a => a -> a -> a\n    let gcd = (x, y) => {\n        let _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b)),\n            abs = Math.abs;\n        return _gcd(abs(x), abs(y));\n    }\n\n    \/\/ lcm\u00a0:: Integral a => a -> a -> a\n    let lcm = (x, y) =>\n        x === 0 || y === 0 ? 0 : Math.abs(Math.floor(x \/ gcd(x, y)) * y);\n\n    \/\/ TEST\n    return lcm(12, 18);\n\n})();\n\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers. The LCM is the smallest positive integer that is a multiple of both given numbers. If either of the numbers is zero, the LCM is zero. The LCM can be calculated by iterating all multiples of one number until a multiple of the second number is found, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be computed for an array of integers using the associative law.","id":2872}
    {"lang_cluster":"JavaScript","source_code":"\n(() => {\n    'use strict';\n\n    \/\/ cusipValid = Dict Char Int -> String -> Bool\n    const cusipValid = charMap => s => {\n        const\n            ns = fromMaybe([])(\n                traverse(flip(lookupDict)(charMap))(\n                    chars(s)\n                )\n            );\n        return 9 === ns.length && (\n            last(ns) === rem(\n                10 - rem(\n                    sum(apList(\n                        apList([quot, rem])(\n                            zipWith(identity)(\n                                cycle([identity, x => 2 * x])\n                            )(take(8)(ns))\n                        )\n                    )([10]))\n                )(10)\n            )(10)\n        );\n    };\n\n    \/\/----------------------- TEST ------------------------\n    \/\/ main\u00a0:: IO ()\n    const main = () => {\n\n        \/\/ cusipMap\u00a0:: Dict Char Int\n        const cusipMap = dictFromList(\n            zip(chars(\n                \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ*@#\"\n            ))(enumFrom(0)));\n\n        console.log(unlines(map(\n            apFn(\n                s => validity => s + ' -> ' + str(validity)\n            )(cusipValid(cusipMap))\n        )([\n            '037833100',\n            '17275R102',\n            '38259P508',\n            '594918104',\n            '68389X106',\n            '68389X105'\n        ])));\n    };\n\n\n    \/\/----------------- GENERIC FUNCTIONS -----------------\n\n    \/\/ Just\u00a0:: a -> Maybe a\n    const Just = x => ({\n        type: 'Maybe',\n        Nothing: false,\n        Just: x\n    });\n\n\n    \/\/ Nothing\u00a0:: Maybe a\n    const Nothing = () => ({\n        type: 'Maybe',\n        Nothing: true,\n    });\n\n\n    \/\/ Tuple (,)\u00a0:: a -> b -> (a, b)\n    const Tuple = a =>\n        b => ({\n            type: 'Tuple',\n            '0': a,\n            '1': b,\n            length: 2\n        });\n\n\n    \/\/ apFn\u00a0:: (a -> b -> c) -> (a -> b) -> a -> c\n    const apFn = f =>\n        \/\/ Applicative instance for functions.\n        \/\/ f(x) applied to g(x).\n        g => x => f(x)(\n            g(x)\n        );\n\n\n    \/\/ apList (<*>)\u00a0:: [(a -> b)] -> [a] -> [b]\n    const apList = fs =>\n        \/\/ The sequential application of each of a list\n        \/\/ of functions to each of a list of values.\n        xs => fs.flatMap(\n            f => xs.map(f)\n        );\n\n\n    \/\/ append (++)\u00a0:: [a] -> [a] -> [a]\n    \/\/ append (++)\u00a0:: String -> String -> String\n    const append = xs =>\n        \/\/ A list or string composed by\n        \/\/ the concatenation of two others.\n        ys => xs.concat(ys);\n\n\n    \/\/ chars\u00a0:: String -> [Char]\n    const chars = s =>\n        s.split('');\n\n\n    \/\/ cons\u00a0:: a -> [a] -> [a]\n    const cons = x =>\n        xs => Array.isArray(xs) ? (\n            [x].concat(xs)\n        ) : 'GeneratorFunction' !== xs\n        .constructor.constructor.name ? (\n            x + xs\n        ) : ( \/\/ cons(x)(Generator)\n            function*() {\n                yield x;\n                let nxt = xs.next()\n                while (!nxt.done) {\n                    yield nxt.value;\n                    nxt = xs.next();\n                }\n            }\n        )();\n\n\n    \/\/ cycle\u00a0:: [a] -> Generator [a]\n    function* cycle(xs) {\n        const lng = xs.length;\n        let i = 0;\n        while (true) {\n            yield(xs[i])\n            i = (1 + i) % lng;\n        }\n    }\n\n\n    \/\/ dictFromList\u00a0:: [(k, v)] -> Dict\n    const dictFromList = kvs =>\n        Object.fromEntries(kvs);\n\n\n    \/\/ enumFrom\u00a0:: Enum a => a -> [a]\n    function* enumFrom(x) {\n        \/\/ A non-finite succession of enumerable\n        \/\/ values, starting with the value x.\n        let v = x;\n        while (true) {\n            yield v;\n            v = succ(v);\n        }\n    }\n\n\n    \/\/ flip\u00a0:: (a -> b -> c) -> b -> a -> c\n    const flip = f =>\n        1 < f.length ? (\n            (a, b) => f(b, a)\n        ) : (x => y => f(y)(x));\n\n\n    \/\/ fromEnum\u00a0:: Enum a => a -> Int\n    const fromEnum = x =>\n        typeof x !== 'string' ? (\n            x.constructor === Object ? (\n                x.value\n            ) : parseInt(Number(x))\n        ) : x.codePointAt(0);\n\n\n    \/\/ fromMaybe\u00a0:: a -> Maybe a -> a\n    const fromMaybe = def =>\n        \/\/ A default value if mb is Nothing\n        \/\/ or the contents of mb.\n        mb => mb.Nothing ? def : mb.Just;\n\n\n    \/\/ fst\u00a0:: (a, b) -> a\n    const fst = tpl =>\n        \/\/ First member of a pair.\n        tpl[0];\n\n\n    \/\/ identity\u00a0:: a -> a\n    const identity = x =>\n        \/\/ The identity function. (`id`, in Haskell)\n        x;\n\n\n    \/\/ last\u00a0:: [a] -> a\n    const last = xs =>\n        \/\/ The last item of a list.\n        0 < xs.length ? xs.slice(-1)[0] : undefined;\n\n\n    \/\/ length\u00a0:: [a] -> Int\n    const length = xs =>\n        \/\/ Returns Infinity over objects without finite\n        \/\/ length. This enables zip and zipWith to choose\n        \/\/ the shorter argument when one is non-finite,\n        \/\/ like cycle, repeat etc\n        (Array.isArray(xs) || 'string' === typeof xs) ? (\n            xs.length\n        ) : Infinity;\n\n\n    \/\/ liftA2\u00a0:: (a -> b -> c) -> Maybe a -> Maybe b -> Maybe c\n    const liftA2 = f => a => b =>\n        a.Nothing ? a : b.Nothing ? b : Just(f(a.Just)(b.Just));\n\n\n    \/\/ lookupDict\u00a0:: a -> Dict -> Maybe b\n    const lookupDict = k => dct => {\n        const v = dct[k];\n        return undefined !== v ? (\n            Just(v)\n        ) : Nothing();\n    };\n\n    \/\/ map\u00a0:: (a -> b) -> [a] -> [b]\n    const map = f =>\n        \/\/ The list obtained by applying f\n        \/\/ to each element of xs.\n        \/\/ (The image of xs under f).\n        xs => (\n            Array.isArray(xs) ? (\n                xs\n            ) : xs.split('')\n        ).map(f);\n\n\n    \/\/ pureMay\u00a0:: a -> Maybe a\n    const pureMay = x => Just(x);\n\n    \/\/ Given a type name string, returns a\n    \/\/ specialised 'pure', where\n    \/\/ 'pure' lifts a value into a particular functor.\n\n    \/\/ pureT\u00a0:: String -> f a -> (a -> f a)\n    const pureT = t => x =>\n        'List' !== t ? (\n            'Either' === t ? (\n                pureLR(x)\n            ) : 'Maybe' === t ? (\n                pureMay(x)\n            ) : 'Node' === t ? (\n                pureTree(x)\n            ) : 'Tuple' === t ? (\n                pureTuple(x)\n            ) : pureList(x)\n        ) : pureList(x);\n\n\n    \/\/ pureTuple\u00a0:: a -> (a, a)\n    const pureTuple = x =>\n        Tuple('')(x);\n\n    \/\/ quot\u00a0:: Int -> Int -> Int\n    const quot = n =>\n        m => Math.floor(n \/ m);\n\n    \/\/ rem\u00a0:: Int -> Int -> Int\n    const rem = n => m => n % m;\n\n    \/\/ snd\u00a0:: (a, b) -> b\n    const snd = tpl => tpl[1];\n\n    \/\/ str\u00a0:: a -> String\n    const str = x =>\n        x.toString();\n\n    \/\/ succ\u00a0:: Enum a => a -> a\n    const succ = x => {\n        const t = typeof x;\n        return 'number' !== t ? (() => {\n            const [i, mx] = [x, maxBound(x)].map(fromEnum);\n            return i < mx ? (\n                toEnum(x)(1 + i)\n            ) : Error('succ\u00a0:: enum out of range.')\n        })() : x < Number.MAX_SAFE_INTEGER ? (\n            1 + x\n        ) : Error('succ\u00a0:: Num out of range.')\n    };\n\n    \/\/ sum\u00a0:: [Num] -> Num\n    const sum = xs =>\n        \/\/ The numeric sum of all values in xs.\n        xs.reduce((a, x) => a + x, 0);\n\n    \/\/ take\u00a0:: Int -> [a] -> [a]\n    \/\/ take\u00a0:: Int -> String -> String\n    const take = n =>\n        \/\/ The first n elements of a list,\n        \/\/ string of characters, or stream.\n        xs => 'GeneratorFunction' !== xs\n        .constructor.constructor.name ? (\n            xs.slice(0, n)\n        ) : [].concat.apply([], Array.from({\n            length: n\n        }, () => {\n            const x = xs.next();\n            return x.done ? [] : [x.value];\n        }));\n\n    \/\/ The first argument is a sample of the type\n    \/\/ allowing the function to make the right mapping\n\n    \/\/ toEnum\u00a0:: a -> Int -> a\n    const toEnum = e => x =>\n        ({\n            'number': Number,\n            'string': String.fromCodePoint,\n            'boolean': Boolean,\n            'object': v => e.min + v\n        } [typeof e])(x);\n\n\n    \/\/ traverse\u00a0:: (Applicative f) => (a -> f b) -> [a] -> f [b]\n    const traverse = f =>\n        \/\/ Collected results of mapping each element\n        \/\/ of a structure to an action, and evaluating\n        \/\/ these actions from left to right.\n        xs => 0 < xs.length ? (() => {\n            const\n                vLast = f(xs.slice(-1)[0]),\n                t = vLast.type || 'List';\n            return xs.slice(0, -1).reduceRight(\n                (ys, x) => liftA2(cons)(f(x))(ys),\n                liftA2(cons)(vLast)(pureT(t)([]))\n            );\n        })() : [\n            []\n        ];\n\n\n    \/\/ uncons\u00a0:: [a] -> Maybe (a, [a])\n    const uncons = xs => {\n        \/\/ Just a tuple of the head of xs and its tail,\n        \/\/ Or Nothing if xs is an empty list.\n        const lng = length(xs);\n        return (0 < lng) ? (\n            Infinity > lng ? (\n                Just(Tuple(xs[0])(xs.slice(1))) \/\/ Finite list\n            ) : (() => {\n                const nxt = take(1)(xs);\n                return 0 < nxt.length ? (\n                    Just(Tuple(nxt[0])(xs))\n                ) : Nothing();\n            })() \/\/ Lazy generator\n        ) : Nothing();\n    };\n\n\n    \/\/ uncurry\u00a0:: (a -> b -> c) -> ((a, b) -> c)\n    const uncurry = f =>\n        \/\/ A function over a pair, derived\n        \/\/ from a curried function.\n        x => ((...args) => {\n            const\n                xy = 1 < args.length ? (\n                    args\n                ) : args[0];\n            return f(xy[0])(xy[1]);\n        })(x);\n\n\n    \/\/ unlines\u00a0:: [String] -> String\n    const unlines = xs =>\n        \/\/ A single string formed by the intercalation\n        \/\/ of a list of strings with the newline character.\n        xs.join('\\n');\n\n\n    \/\/ zip\u00a0:: [a] -> [b] -> [(a, b)]\n    const zip = xs =>\n        \/\/ Use of `take` and `length` here allows for zipping with non-finite\n        \/\/ lists - i.e. generators like cycle, repeat, iterate.\n        ys => {\n            const\n                lng = Math.min(length(xs), length(ys)),\n                vs = take(lng)(ys);\n            return take(lng)(xs).map(\n                (x, i) => Tuple(x)(vs[i])\n            );\n        };\n\n    \/\/ Use of `take` and `length` here allows zipping with non-finite lists\n    \/\/ i.e. generators like cycle, repeat, iterate.\n\n    \/\/ zipWith\u00a0:: (a -> b -> c) -> [a] -> [b] -> [c]\n    const zipWith = f => xs => ys => {\n        const lng = Math.min(length(xs), length(ys));\n        return Infinity > lng ? (() => {\n            const\n                as = take(lng)(xs),\n                bs = take(lng)(ys);\n            return Array.from({\n                length: lng\n            }, (_, i) => f(as[i])(\n                bs[i]\n            ));\n        })() : zipWithGen(f)(xs)(ys);\n    };\n\n\n    \/\/ zipWithGen\u00a0:: (a -> b -> c) ->\n    \/\/ Gen [a] -> Gen [b] -> Gen [c]\n    const zipWithGen = f => ga => gb => {\n        function* go(ma, mb) {\n            let\n                a = ma,\n                b = mb;\n            while (!a.Nothing && !b.Nothing) {\n                let\n                    ta = a.Just,\n                    tb = b.Just\n                yield(f(fst(ta))(fst(tb)));\n                a = uncons(snd(ta));\n                b = uncons(snd(tb));\n            }\n        }\n        return go(uncons(ga), uncons(gb));\n    };\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":2873}
    {"lang_cluster":"JavaScript","source_code":"\n\n\"alpha beta gamma delta\".split(\" \").forEach(function (x) {\n    console.log(x);\n});\n\n\nconsole.log(\"alpha beta gamma delta\".split(\" \").map(function (x) {\n    return x.toUpperCase(x);\n}).join(\"\\n\"));\n\n\nconsole.log(\"alpha beta gamma delta\".split(\" \").reduce(function (a, x, i, lst) {\n    return lst.length - i + \". \" + x + \"\\n\" + a;\n}, \"\"));\n\n\nfor (var a in o) {\n    print(o[a]);\n}\n\n\nfor (var a in o) {\n    if (o.hasOwnProperty(a)) {\n        print(o[a]);\n    }\n}\n\nWorks with: JavaScript version 1.6\nDeprecated\n\nh = {\"one\":1, \"two\":2, \"three\":3}\nfor (x in h) print(x);\nfor each (y in h) print(y);\n\nWorks with: ECMAScript version 6th edition\n\nh = {\"one\":1, \"two\":2, \"three\":3}\nfor (x in h) print(x);\nfor (y of h) print(y);\n\n","human_summarization":"Iterates through each element in a collection in a specific order using a \"for each\" loop or an alternative loop if \"for each\" is not available. In ES5, it uses Array.forEach(), Array.map(), or Array.reduce() for arrays. It can also iterate over the keys of any object, including arrays, but may list inherited properties and methods. It can also iterate over the values of an object using a for each in or for of construct.","id":2874}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: Firefox version 2.0\nalert( \"Hello,How,Are,You,Today\".split(\",\").join(\".\") );\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":2875}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction gcd(a,b) {\n  a = Math.abs(a);\n  b = Math.abs(b);\n\n  if (b > a) {\n    var temp = a;\n    a = b;\n    b = temp; \n  }\n\n  while (true) {\n    a %= b;\n    if (a === 0) { return b; }\n    b %= a;\n    if (b === 0) { return a; }\n  }\n}\n\n\nfunction gcd_rec(a, b) {\n  return b ? gcd_rec(b, a % b) : Math.abs(a);\n}\n\n\nfunction GCD(arr) {\n  var i, y,\n      n = arr.length,\n      x = Math.abs(arr[0]);\n\n  for (i = 1; i < n; i++) {\n    y = Math.abs(arr[i]);\n\n    while (x && y) {\n      (x > y)\u00a0? x\u00a0%= y\u00a0: y\u00a0%= x;\n    }\n    x += y;\n  }\n  return x;\n}\n\n\/\/For example:\nGCD([57,0,-45,-18,90,447]); \/\/=> 3\n","human_summarization":"find the greatest common divisor (GCD), also known as the greatest common factor (gcf) or greatest common measure, of two integers. The implementation is both iterative and recursive, and can work on an array of integers. Related tasks include finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":2876}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: Node.js\nconst net = require('net');\n\nfunction handleClient(conn) {\n    console.log('Connection from ' + conn.remoteAddress + ' on port ' + conn.remotePort);\n\n    conn.setEncoding('utf-8');\n\n    let buffer = '';\n\n    function handleData(data) {\n        for (let i = 0; i < data.length; i++) {\n            const char = data.charAt(i);\n            buffer += char;\n            if (char === '\\n') {\n                conn.write(buffer);\n                buffer = '';\n            }\n        }\n    }\n\n    conn.on('data', handleData);\n}\n\nnet.createServer(handleClient).listen(12321, 'localhost');\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":2877}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction isNumeric(n) {\n  return !isNaN(parseFloat(n)) && isFinite(n);\n}\nvar value = \"123.45e7\"; \/\/ Assign string literal to value\nif (isNumeric(value)) {\n  \/\/ value is a number\n}\n\/\/Or, in web browser in address field:\n\/\/  javascript:function isNumeric(n) {return !isNaN(parseFloat(n)) && isFinite(n);}; value=\"123.45e4\"; if(isNumeric(value)) {alert('numeric')} else {alert('non-numeric')}\n\n","human_summarization":"implement a boolean function that checks if a given string is a numeric string, including floating point and negative numbers, according to the language's syntax for numeric literals or numbers converted from strings.","id":2878}
    {"lang_cluster":"JavaScript","source_code":"\nfetch(\"https:\/\/sourceforge.net\").then(function (response) {\n    return response.text();\n}).then(function (body) {\n    return body;\n});\n\nrequire(\"https\").get(\"https:\/\/sourceforge.net\", function (resp) {\n    let body = \"\";\n    resp.on(\"data\", function (chunk) {\n        body += chunk;\n    });\n    resp.on(\"end\", function () {\n        console.log(body);\n    });\n}).on(\"error\", function (err) {\n    console.error(\"Error: \" + err.message);\n});\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":2879}
    {"lang_cluster":"JavaScript","source_code":"\n\n<html>\n    <head>\n\t<script>\n        function clip (subjectPolygon, clipPolygon) {\n            \n            var cp1, cp2, s, e;\n            var inside = function (p) {\n                return (cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0]);\n            };\n            var intersection = function () {\n                var dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ],\n                    dp = [ s[0] - e[0], s[1] - e[1] ],\n                    n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0],\n                    n2 = s[0] * e[1] - s[1] * e[0], \n                    n3 = 1.0 \/ (dc[0] * dp[1] - dc[1] * dp[0]);\n                return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3];\n            };\n            var outputList = subjectPolygon;\n            cp1 = clipPolygon[clipPolygon.length-1];\n            for (var j in clipPolygon) {\n                cp2 = clipPolygon[j];\n                var inputList = outputList;\n                outputList = [];\n                s = inputList[inputList.length - 1]; \/\/last on the input list\n                for (var i in inputList) {\n                    e = inputList[i];\n                    if (inside(e)) {\n                        if (!inside(s)) {\n                            outputList.push(intersection());\n                        }\n                        outputList.push(e);\n                    }\n                    else if (inside(s)) {\n                        outputList.push(intersection());\n                    }\n                    s = e;\n                }\n                cp1 = cp2;\n            }\n            return outputList\n        }\n\n        function drawPolygon(context, polygon, strokeStyle, fillStyle) {\n            context.strokeStyle = strokeStyle;\n            context.fillStyle = fillStyle;\n            context.beginPath();\n            context.moveTo(polygon[0][0],polygon[0][1]); \/\/first vertex\n            for (var i = 1; i < polygon.length ; i++)\n                context.lineTo(polygon[i][0],polygon[i][1]);\n            context.lineTo(polygon[0][0],polygon[0][1]); \/\/back to start\n            context.fill();\n            context.stroke();\n            context.closePath();\n        }\n\n        window.onload = function () {\n\t        var context = document.getElementById('canvas').getContext('2d');\n\t        var subjectPolygon = [[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]],\n\t            clipPolygon = [[100, 100], [300, 100], [300, 300], [100, 300]];\n\t        var clippedPolygon = clip(subjectPolygon, clipPolygon);\n\t        drawPolygon(context, clipPolygon, '#888','#88f');\n\t        drawPolygon(context, subjectPolygon, '#888','#8f8');\n\t        drawPolygon(context, clippedPolygon, '#000','#0ff');\n    \t}\n        <\/script>\n    <body>\n    \t<canvas id='canvas' width='400' height='400'><\/canvas>\n    <\/body>\n<\/html>\n\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. It takes a closed polygon defined by given points and clips it by a rectangle defined by another set of points. The sequence of points that define the resulting clipped polygon is then printed. For extra credit, the code also displays all three polygons on a graphical surface, each in a different color, and fills the resulting polygon. The origin for display can be either north-west or south-west.","id":2880}
    {"lang_cluster":"JavaScript","source_code":"\n\n(function () {\n \n    var xs = 'Solomon Jason Errol Garry Bernard Barry Stephen'.split(' '),\n        ns = [44, 42, 42, 41, 41, 41, 39],\n \n        sorted = xs.map(function (x, i) {\n            return { name: x, score: ns[i] };\n        }).sort(function (a, b) {\n            var c = b.score - a.score;\n            return c ? c : a.name < b.name ? -1 : a.name > b.name ? 1 : 0;\n        }),\n \n        names = sorted.map(function (x) { return x.name; }),\n        scores = sorted.map(function (x) { return x.score; }),\n \n        reversed = scores.slice(0).reverse(),\n        unique = scores.filter(function (x, i) {\n            return scores.indexOf(x) === i;\n        });\n \n    \/\/ RANKINGS AS FUNCTIONS OF SCORES: SORTED, REVERSED AND UNIQUE\n \n    var rankings = function (score, index) {\n            return {\n                name: names[index],\n                score: score,\n\n                Ordinal: index + 1,\n\n                Standard: function (n) {\n                    return scores.indexOf(n) + 1;\n                }(score),\n\n                Modified: function (n) {\n                    return reversed.length - reversed.indexOf(n);\n                }(score),\n\n                Dense: function (n) {\n                    return unique.indexOf(n) + 1;\n                }(score),\n\n                Fractional: function (n) {\n                    return (\n                        (scores.indexOf(n) + 1) +\n                        (reversed.length - reversed.indexOf(n))\n                    ) \/ 2;\n                }(score)\n            };\n        },\n \n        tbl = [\n            'Name Score Standard Modified Dense Ordinal Fractional'.split(' ')\n        ].concat(scores.map(rankings).reduce(function (a, x) {\n            return a.concat([\n                [x.name, x.score,\n                    x.Standard, x.Modified, x.Dense, x.Ordinal, x.Fractional\n                ]\n            ]);\n        }, [])),\n \n        \/\/[[a]] -> bool -> s -> s\n        wikiTable = function (lstRows, blnHeaderRow, strStyle) {\n            return '{| class=\"wikitable\" ' + (\n                strStyle ? 'style=\"' + strStyle + '\"' : ''\n            ) + lstRows.map(function (lstRow, iRow) {\n                var strDelim = ((blnHeaderRow && !iRow) ? '!' : '|');\n \n                return '\\n|-\\n' + strDelim + ' ' + lstRow.map(function (v) {\n                    return typeof v === 'undefined' ? ' ' : v;\n                }).join(' ' + strDelim + strDelim + ' ');\n            }).join('') + '\\n|}';\n        };\n \n    return wikiTable(tbl, true, 'text-align:center');\n \n})();\n\n\n","human_summarization":"The code implements five different ranking methods (Standard, Modified, Dense, Ordinal, and Fractional) for competitors in a competition based on their scores. The ranking methods handle ties differently: Standard shares the first ordinal number, Modified shares the last ordinal number, Dense shares the next available integer, Ordinal assigns the next available integer without treating ties, and Fractional shares the mean of their ordinal numbers. The code also sorts players with the same score alphabetically.","id":2881}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar\n radians = Math.PI \/ 4, \/\/ Pi \/ 4 is 45 degrees. All answers should be the same.\n degrees = 45.0,\n sine = Math.sin(radians),\n cosine = Math.cos(radians),\n tangent = Math.tan(radians),\n arcsin = Math.asin(sine),\n arccos = Math.acos(cosine),\n arctan = Math.atan(tangent);\n\n\/\/ sine\nwindow.alert(sine + \" \" + Math.sin(degrees * Math.PI \/ 180));\n\/\/ cosine\nwindow.alert(cosine + \" \" + Math.cos(degrees * Math.PI \/ 180));\n\/\/ tangent\nwindow.alert(tangent + \" \" + Math.tan(degrees * Math.PI \/ 180));\n\/\/ arcsine\nwindow.alert(arcsin + \" \" + (arcsin * 180 \/ Math.PI));\n\/\/ arccosine\nwindow.alert(arccos + \" \" + (arccos * 180 \/ Math.PI));\n\/\/ arctangent\nwindow.alert(arctan + \" \" + (arctan * 180 \/ Math.PI));\n\n","human_summarization":"demonstrate the use of trigonometric functions such as sine, cosine, tangent, and their inverses in JavaScript. The functions accept arguments in radians, and conversion is performed when dealing with degrees. The same angle is used for non-inverse functions, while the same number is used for inverse functions, with results converted to both radians and degrees. If the language lacks certain functions, they are calculated using known approximations or identities.","id":2882}
    {"lang_cluster":"JavaScript","source_code":"\n\n<html><head><title><\/title><\/head><body><\/body><\/html>\n\n<script type=\"text\/javascript\">\nvar data= [\n  {name: 'map',                    weight:  9, value:150, pieces:1},\n  {name: 'compass',                weight: 13, value: 35, pieces:1},\n  {name: 'water',                  weight:153, value:200, pieces:2},\n  {name: 'sandwich',               weight: 50, value: 60, pieces:2},\n  {name: 'glucose',                weight: 15, value: 60, pieces:2},\n  {name: 'tin',                    weight: 68, value: 45, pieces:3},\n  {name: 'banana',                 weight: 27, value: 60, pieces:3},\n  {name: 'apple',                  weight: 39, value: 40, pieces:3},\n  {name: 'cheese',                 weight: 23, value: 30, pieces:1},\n  {name: 'beer',                   weight: 52, value: 10, pieces:3},\n  {name: 'suntan, cream',          weight: 11, value: 70, pieces:1},\n  {name: 'camera',                 weight: 32, value: 30, pieces:1},\n  {name: 'T-shirt',                weight: 24, value: 15, pieces:2},\n  {name: 'trousers',               weight: 48, value: 10, pieces:2},\n  {name: 'umbrella',               weight: 73, value: 40, pieces:1},\n  {name: 'waterproof, trousers',   weight: 42, value: 70, pieces:1},\n  {name: 'waterproof, overclothes',weight: 43, value: 75, pieces:1},\n  {name: 'note-case',              weight: 22, value: 80, pieces:1},\n  {name: 'sunglasses',             weight:  7, value: 20, pieces:1},\n  {name: 'towel',                  weight: 18, value: 12, pieces:2},\n  {name: 'socks',                  weight:  4, value: 50, pieces:1},\n  {name: 'book',                   weight: 30, value: 10, pieces:2}\n];\n\nfunction findBestPack() {\n\tvar m= [[0]]; \/\/ maximum pack value found so far\n\tvar b= [[0]]; \/\/ best combination found so far\n\tvar opts= [0]; \/\/ item index for 0 of item 0 \n\tvar P= [1]; \/\/ item encoding for 0 of item 0\n\tvar choose= 0;\n\tfor (var j= 0; j<data.length; j++) {\n\t\topts[j+1]= opts[j]+data[j].pieces; \/\/ item index for 0 of item j+1\n\t\tP[j+1]= P[j]*(1+data[j].pieces); \/\/ item encoding for 0 of item j+1\n\t}\n\tfor (var j= 0; j<opts[data.length]; j++) {\n\t\tm[0][j+1]= b[0][j+1]= 0; \/\/ best values and combos for empty pack: nothing\n\t}\n\tfor (var w=1; w<=400; w++) {\n\t\tm[w]= [0];\n\t\tb[w]= [0];\n\t\tfor (var j=0; j<data.length; j++) {\n\t\t\tvar N= data[j].pieces; \/\/ how many of these can we have?\n\t\t\tvar base= opts[j]; \/\/ what is the item index for 0 of these?\n\t\t\tfor (var n= 1; n<=N; n++) {\n\t\t\t\tvar W= n*data[j].weight; \/\/ how much do these items weigh?\n\t\t\t\tvar s= w>=W ?1 :0; \/\/ can we carry this many?\n\t\t\t\tvar v= s*n*data[j].value; \/\/ how much are they worth?\n\t\t\t\tvar I= base+n; \/\/ what is the item number for this many?\n\t\t\t\tvar wN= w-s*W; \/\/ how much other stuff can we be carrying?\n\t\t\t\tvar C= n*P[j] + b[wN][base]; \/\/ encoded combination\n\t\t\t\tm[w][I]= Math.max(m[w][I-1], v+m[wN][base]); \/\/ best value\n\t\t\t\tchoose= b[w][I]= m[w][I]>m[w][I-1] ?C :b[w][I-1];\n\t\t\t}\n\t\t}\n\t}\n\tvar best= [];\n\tfor (var j= data.length-1; j>=0; j--) {\n\t\tbest[j]= Math.floor(choose\/P[j]);\n\t\tchoose-= best[j]*P[j];\n\t}\n\tvar out='<table><tr><td><b>Count<\/b><\/td><td><b>Item<\/b><\/td><th>unit weight<\/th><th>unit value<\/th>';\n\tvar wgt= 0;\n\tvar val= 0;\n\tfor (var i= 0; i<best.length; i++) {\n\t\tif (0==best[i]) continue;\n\t\tout+='<\/tr><tr><td>'+best[i]+'<\/td><td>'+data[i].name+'<\/td><td>'+data[i].weight+'<\/td><td>'+data[i].value+'<\/td>'\n\t\twgt+= best[i]*data[i].weight;\n\t\tval+= best[i]*data[i].value;\n\t}\n\tout+= '<\/tr><\/table><br\/>Total weight: '+wgt;\n\tout+= '<br\/>Total value: '+val;\n\tdocument.body.innerHTML= out;\n}\nfindBestPack();\n<\/script>\n\n\n\n\nCount\n\nItem\n\nunit weight\n\nunit value\n\n\n1\n\nmap\n\n9\n\n150\n\n\n1\n\ncompass\n\n13\n\n35\n\n\n1\n\nwater\n\n153\n\n200\n\n\n2\n\nglucose\n\n15\n\n60\n\n\n3\n\nbanana\n\n27\n\n60\n\n\n1\n\ncheese\n\n23\n\n30\n\n\n1\n\nsuntan, cream\n\n11\n\n70\n\n\n1\n\nwaterproof, overclothes\n\n43\n\n75\n\n\n1\n\nnote-case\n\n22\n\n80\n\n\n1\n\nsunglasses\n\n7\n\n20\n\n\n1\n\nsocks\n\n4\n\n50\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a weight limit of 4 kg. It considers the weight, value, and quantity of each item, ensuring the total weight doesn't exceed the limit while maximizing the total value. The items cannot be divided. The output includes the total weight and value of the selected items.","id":2883}
    {"lang_cluster":"JavaScript","source_code":"\n\n(function(){\n    var count=0\n        secs=0\n    \n    var i= setInterval( function (){\n        count++\n        secs+=0.5\n        console.log(count)\n    }, 500);\n    \n    process.on('SIGINT', function() {\n        clearInterval(i)\n        console.log(secs+' seconds elapsed');\n        process.exit()\n    });\n})();\n\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program. This is implemented using the NodeJS engine.","id":2884}
    {"lang_cluster":"JavaScript","source_code":"\n\nlet s = '9999';\nlet splusplus = (+s+1)+\"\"\n\nconsole.log([splusplus, typeof splusplus]) \/\/ 10000,string\n\n(() => {\n    'use strict';\n\n    \/\/ succString\u00a0:: Bool -> String -> String\n    const succString = blnPruned => s => {\n        const go = w => {\n            const\n                v = w.includes('.') ? (\n                    parseFloat(w)\n                ) : parseInt(w);\n            return isNaN(v) ? (\n                blnPruned ? [] : [w]\n            ) : [(1 + v).toString()];\n        };\n        return unwords(concatMap(go, words(s)));\n    };\n\n    \/\/ TEST -----------------------------------------------\n    const main = () =>\n        console.log(\n            unlines(\n                ap(\n                    map(succString, [true, false]),\n                    ['41 pine martens in 1491.3 -1.5 mushrooms \u2260 136']\n                )\n            )\n        );\n\n\n    \/\/ GENERIC FUNCTIONS ----------------------------------\n\n    \/\/ Each member of a list of functions applied to each\n    \/\/ of a list of arguments, deriving a list of new values.\n\n    \/\/ ap (<*>)\u00a0:: [(a -> b)] -> [a] -> [b]\n    const ap = (fs, xs) => \/\/\n        fs.reduce((a, f) => a.concat(\n            xs.reduce((a, x) => a.concat([f(x)]), [])\n        ), []);\n\n    \/\/ concatMap\u00a0:: (a -> [b]) -> [a] -> [b]\n    const concatMap = (f, xs) =>\n        xs.reduce((a, x) => a.concat(f(x)), []);\n\n    \/\/ map\u00a0:: (a -> b) -> [a] -> [b]\n    const map = (f, xs) => xs.map(f);\n\n    \/\/ unlines\u00a0:: [String] -> String\n    const unlines = xs => xs.join('\\n');\n\n    \/\/ unwords\u00a0:: [String] -> String\n    const unwords = xs => xs.join(' ');\n\n    \/\/ words\u00a0:: String -> [String]\n    const words = s => s.split(\/\\s+\/);\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n\n","human_summarization":"\"Increments a numerical string, expands the range of a stringSucc function to accommodate non-numeric noise and multiple numeric expressions in a single string using implicit coercion.\"","id":2885}
    {"lang_cluster":"JavaScript","source_code":"\n\/**\n * Given an array of strings, return an array of arrays, containing the\n * strings split at the given separator\n * @param {!Array<!string>} a\n * @param {string} sep\n * @returns {!Array<!Array<string>>}\n *\/\nconst splitStrings = (a, sep = '\/') => a.map(i => i.split(sep));\n\n\/**\n * Given an index number, return a function that takes an array and returns the\n * element at the given index\n * @param {number} i\n * @return {function(!Array<*>): *}\n *\/\nconst elAt = i => a => a[i];\n\n\/**\n * Transpose an array of arrays:\n * Example:\n * [['a', 'b', 'c'], ['A', 'B', 'C'], [1, 2, 3]] ->\n * [['a', 'A', 1], ['b', 'B', 2], ['c', 'C', 3]]\n * @param {!Array<!Array<*>>} a\n * @return {!Array<!Array<*>>}\n *\/\nconst rotate = a => a[0].map((e, i) => a.map(elAt(i)));\n\n\/**\n * Checks of all the elements in the array are the same.\n * @param {!Array<*>} arr\n * @return {boolean}\n *\/\nconst allElementsEqual = arr => arr.every(e => e === arr[0]);\n\n\nconst commonPath = (input, sep = '\/') => rotate(splitStrings(input, sep))\n    .filter(allElementsEqual).map(elAt(0)).join(sep);\n\nconst cdpInput = [\n  '\/home\/user1\/tmp\/coverage\/test',\n  '\/home\/user1\/tmp\/covert\/operator',\n  '\/home\/user1\/tmp\/coven\/members',\n];\n\nconsole.log(`Common path is: ${commonPath(cdpInput)}`);\n\n\n","human_summarization":"The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '\/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.","id":2886}
    {"lang_cluster":"JavaScript","source_code":"\nfunction sattoloCycle(items) {\n    for (var i = items.length-1; i > 0; i--) {\n        var j = Math.floor(Math.random() * i);\n        var tmp = items[i];\n        items[i] = items[j];\n        items[j] = tmp;\n    }\n}\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":2887}
    {"lang_cluster":"JavaScript","source_code":"\nfunction median(ary) {\n    if (ary.length == 0)\n        return null;\n    ary.sort(function (a,b){return a - b})\n    var mid = Math.floor(ary.length \/ 2);\n    if ((ary.length % 2) == 1)  \/\/ length is odd\n        return ary[mid];\n    else \n        return (ary[mid - 1] + ary[mid]) \/ 2;\n}\n\nmedian([]);   \/\/ null\nmedian([5,3,4]);  \/\/ 4\nmedian([5,4,2,3]);  \/\/ 3.5\nmedian([3,4,1,-8.4,7.2,4,1,1.2]);  \/\/ 2.1\n\n(() => {\n    'use strict';\n\n    \/\/ median\u00a0:: [Num] -> Num\n    function median(xs) {\n        \/\/ nth\u00a0:: [Num] -> Int -> Maybe Num\n        let nth = (xxs, n) => {\n                if (xxs.length > 0) {\n                    let [x, xs] = uncons(xxs), \n                        [ys, zs] = partition(y => y < x, xs),\n                        k = ys.length;\n\n                    return k === n ? x : (\n                        k > n ? nth(ys, n) : nth(zs, n - k - 1)\n                    );\n                } else return undefined;\n            },\n            n = xs.length;\n\n        return even(n) ? (\n            (nth(xs, div(n, 2)) + nth(xs, div(n, 2) - 1)) \/ 2\n        ) : nth(xs, div(n, 2));\n    }\n\n\n\n    \/\/ GENERIC\n\n    \/\/ partition\u00a0:: (a -> Bool) -> [a] -> ([a], [a])\n    let partition = (p, xs) =>\n        xs.reduce((a, x) =>\n            p(x) ? [a[0].concat(x), a[1]] : [a[0], a[1].concat(x)], [\n                [],\n                []\n            ]),\n\n        \/\/ uncons\u00a0:: [a] -> Maybe (a, [a])\n        uncons = xs => xs.length ? [xs[0], xs.slice(1)] : undefined,\n\n        \/\/ even\u00a0:: Integral a => a -> Bool\n        even = n => n % 2 === 0,\n\n        \/\/ div\u00a0:: Num -> Num -> Int\n        div = (x, y) => Math.floor(x \/ y);\n\n    return [\n        [],\n        [5, 3, 4],\n        [5, 4, 2, 3],\n        [3, 4, 1, -8.4, 7.2, 4, 1, 1.2]\n    ].map(median);\n})();\n\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. It uses the selection algorithm for efficient computation. It also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation. The calculation can be done in one go, moving (sliding window), or moving (cumulative). It uses a quick select algorithm for faster computation.","id":2888}
    {"lang_cluster":"JavaScript","source_code":"\nvar fizzBuzz = function () {\n  var i, output;\n  for (i = 1; i < 101; i += 1) {\n    output = '';\n    if (!(i\u00a0% 3)) { output += 'Fizz'; }\n    if (!(i\u00a0% 5)) { output += 'Buzz'; }\n    console.log(output || i);\/\/empty string is false, so we short-circuit\n  }\n};\n\nfor (var i = 1; i <= 100; i++) {\n  console.log({\n    truefalse: 'Fizz', \n    falsetrue: 'Buzz', \n    truetrue: 'FizzBuzz'\n  }[(i%3==0) + '' + (i%5==0)] || i)\n}\n\nfor(i=1;i<101;i++)console.log((x=(i%3?'':'Fizz')+(i%5?'':'Buzz'))?x:i);\n\nfor(i=1;i<101;i++)console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i)\n\n(function rng(i) {\n    return i\u00a0? rng(i - 1).concat(i)\u00a0: []\n})(100).map(\n    function (n) {\n        return n\u00a0% 3\u00a0? (\n            n\u00a0% 5\u00a0? n\u00a0: \"Buzz\"\n        )\u00a0: (\n            n\u00a0% 5\u00a0? \"Fizz\"\u00a0: \"FizzBuzz\"\n        )\n    }\n).join(' ')\n(() => {\n\n    \/\/ FIZZBUZZ --------------------------------------------------------------\n\n    \/\/ fizzBuzz\u00a0:: Int -> String\n    const fizzBuzz = n =>\n        caseOf(n, [\n            [x => x\u00a0% 15 === 0, \"FizzBuzz\"],\n            [x => x\u00a0% 3 === 0, \"Fizz\"],\n            [x => x\u00a0% 5 === 0, \"Buzz\"]\n        ], n.toString());\n\n    \/\/ GENERIC FUNCTIONS -----------------------------------------------------\n\n    \/\/ caseOf\u00a0:: a -> [(a -> Bool, b)] -> b -> b\n    const caseOf = (e, pvs, otherwise) =>\n        pvs.reduce((a, [p, v]) =>\n            a\u00a0!== otherwise\u00a0? a\u00a0: (p(e)\u00a0? v\u00a0: a), otherwise);\n\n    \/\/ enumFromTo\u00a0:: Int -> Int -> [Int]\n    const enumFromTo = (m, n) =>\n        Array.from({\n            length: Math.floor(n - m) + 1\n        }, (_, i) => m + i);\n\n    \/\/ map\u00a0:: (a -> b) -> [a] -> [b]\n    const map = (f, xs) => xs.map(f);\n\n    \/\/ unlines\u00a0:: [String] -> String\n    const unlines = xs => xs.join('\\n');\n\n    \/\/ TEST ------------------------------------------------------------------\n    return unlines(\n        map(fizzBuzz, enumFromTo(1, 100))\n    );\n})();\n\nconst factors = [[3, 'Fizz'], [5, 'Buzz']]\nconst fizzBuzz = num => factors.map(([factor,text]) => (num\u00a0% factor)?'':text).join('') || num\nconst range1 = x => [...Array(x+1).keys()].slice(1)\nconst outputs = range1(100).map(fizzBuzz)\n\nconsole.log(outputs.join('\\n'))\n(() => {\n    'use strict';\n\n    \/\/ main\u00a0:: IO ()\n    const main = () => {\n\n        \/\/ FIZZBUZZ ---------------------------------------\n\n        \/\/ fizzBuzz\u00a0:: Generator [String]\n        const fizzBuzz = () => {\n            const fb = n => k => cycle(\n                replicate(n - 1)('').concat(k)\n            );\n            return zipWith(\n                liftA2(flip)(bool)(isNull)\n            )(\n                zipWith(append)(fb(3)('fizz'))(fb(5)('buzz'))\n            )(fmap(str)(enumFrom(1)));\n        };\n\n        \/\/ TEST -------------------------------------------\n        console.log(\n            unlines(\n                take(100)(\n                    fizzBuzz()\n                )\n            )\n        );\n    };\n\n    \/\/ GENERIC FUNCTIONS ----------------------------------\n\n    \/\/ Just\u00a0:: a -> Maybe a\n    const Just = x => ({\n        type: 'Maybe',\n        Nothing: false,\n        Just: x\n    });\n\n    \/\/ Nothing\u00a0:: Maybe a\n    const Nothing = () => ({\n        type: 'Maybe',\n        Nothing: true,\n    });\n\n    \/\/ Tuple (,)\u00a0:: a -> b -> (a, b)\n    const Tuple = a => b => ({\n        type: 'Tuple',\n        '0': a,\n        '1': b,\n        length: 2\n    });\n\n    \/\/ append (++)\u00a0:: [a] -> [a] -> [a]\n    \/\/ append (++)\u00a0:: String -> String -> String\n    const append = xs => ys => xs.concat(ys);\n\n    \/\/ bool\u00a0:: a -> a -> Bool -> a\n    const bool = f => t => p =>\n        p\u00a0? t\u00a0: f;\n\n    \/\/ cycle\u00a0:: [a] -> Generator [a]\n    function* cycle(xs) {\n        const lng = xs.length;\n        let i = 0;\n        while (true) {\n            yield(xs[i])\n            i = (1 + i)\u00a0% lng;\n        }\n    }\n\n    \/\/ enumFrom\u00a0:: Int => Int -> [Int]\n    function* enumFrom(x) {\n        let v = x;\n        while (true) {\n            yield v;\n            v = 1 + v;\n        }\n    }\n\n    \/\/ flip\u00a0:: (a -> b -> c) -> b -> a -> c\n    const flip = f =>\n        x => y => f(y)(x);\n\n    \/\/ fmap <$>\u00a0:: (a -> b) -> Gen [a] -> Gen [b]\n    const fmap = f =>\n        function*(gen) {\n            let v = take(1)(gen);\n            while (0 < v.length) {\n                yield(f(v[0]))\n                v = take(1)(gen)\n            }\n        };\n\n    \/\/ fst\u00a0:: (a, b) -> a\n    const fst = tpl => tpl[0];\n\n    \/\/ isNull\u00a0:: [a] -> Bool\n    \/\/ isNull\u00a0:: String -> Bool\n    const isNull = xs =>\n        1 > xs.length;\n\n    \/\/ Returns Infinity over objects without finite length.\n    \/\/ This enables zip and zipWith to choose the shorter\n    \/\/ argument when one is non-finite, like cycle, repeat etc\n\n    \/\/ length\u00a0:: [a] -> Int\n    const length = xs =>\n        (Array.isArray(xs) || 'string' === typeof xs)\u00a0? (\n            xs.length\n        )\u00a0: Infinity;\n\n    \/\/ liftA2\u00a0:: (a0 -> b -> c) -> (a -> a0) -> (a -> b) -> a -> c\n    const liftA2 = op => f => g =>\n        \/\/ Lift a binary function to a composition\n        \/\/ over two other functions.\n        \/\/ liftA2 (*) (+ 2) (+ 3) 7 == 90\n        x => op(f(x))(g(x));\n\n    \/\/ replicate\u00a0:: Int -> a -> [a]\n    const replicate = n => x =>\n        Array.from({\n            length: n\n        }, () => x);\n\n    \/\/ snd\u00a0:: (a, b) -> b\n    const snd = tpl => tpl[1];\n\n    \/\/ str\u00a0:: a -> String\n    const str = x => x.toString();\n\n    \/\/ take\u00a0:: Int -> [a] -> [a]\n    \/\/ take\u00a0:: Int -> String -> String\n    const take = n => xs =>\n        'GeneratorFunction'\u00a0!== xs.constructor.constructor.name\u00a0? (\n            xs.slice(0, n)\n        )\u00a0: [].concat.apply([], Array.from({\n            length: n\n        }, () => {\n            const x = xs.next();\n            return x.done\u00a0? []\u00a0: [x.value];\n        }));\n\n    \/\/ The first argument is a sample of the type\n    \/\/ allowing the function to make the right mapping\n\n    \/\/ uncons\u00a0:: [a] -> Maybe (a, [a])\n    const uncons = xs => {\n        const lng = length(xs);\n        return (0 < lng)\u00a0? (\n            lng < Infinity\u00a0? (\n                Just(Tuple(xs[0])(xs.slice(1))) \/\/ Finite list\n            )\u00a0: (() => {\n                const nxt = take(1)(xs);\n                return 0 < nxt.length\u00a0? (\n                    Just(Tuple(nxt[0])(xs))\n                )\u00a0: Nothing();\n            })() \/\/ Lazy generator\n        )\u00a0: Nothing();\n    };\n\n    \/\/ unlines\u00a0:: [String] -> String\n    const unlines = xs => xs.join('\\n');\n\n    \/\/ zipWith\u00a0:: (a -> b -> c) Gen [a] -> Gen [b] -> Gen [c]\n    const zipWith = f => ga => gb => {\n        function* go(ma, mb) {\n            let\n                a = ma,\n                b = mb;\n            while (!a.Nothing && !b.Nothing) {\n                let\n                    ta = a.Just,\n                    tb = b.Just\n                yield(f(fst(ta))(fst(tb)));\n                a = uncons(snd(ta));\n                b = uncons(snd(tb));\n            }\n        }\n        return go(uncons(ga), uncons(gb));\n    };\n\n    \/\/ MAIN ---\n    return main();\n})();\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":2889}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: Firefox version 3.5.11\n\nfunction mandelIter(cx, cy, maxIter) {\n  var x = 0.0;\n  var y = 0.0;\n  var xx = 0;\n  var yy = 0;\n  var xy = 0;\n\n  var i = maxIter;\n  while (i-- && xx + yy <= 4) {\n    xy = x * y;\n    xx = x * x;\n    yy = y * y;\n    x = xx - yy + cx;\n    y = xy + xy + cy;\n  }\n  return maxIter - i;\n}\n\nfunction mandelbrot(canvas, xmin, xmax, ymin, ymax, iterations) {\n  var width = canvas.width;\n  var height = canvas.height;\n\n  var ctx = canvas.getContext('2d');\n  var img = ctx.getImageData(0, 0, width, height);\n  var pix = img.data;\n  \n  for (var ix = 0; ix < width; ++ix) {\n    for (var iy = 0; iy < height; ++iy) {\n      var x = xmin + (xmax - xmin) * ix \/ (width - 1);\n      var y = ymin + (ymax - ymin) * iy \/ (height - 1);\n      var i = mandelIter(x, y, iterations);\n      var ppos = 4 * (width * iy + ix);\n      \n      if (i > iterations) {\n        pix[ppos] = 0;\n        pix[ppos + 1] = 0;\n        pix[ppos + 2] = 0;\n      } else {\n        var c = 3 * Math.log(i) \/ Math.log(iterations - 1.0);\n        \n        if (c < 1) {\n          pix[ppos] = 255 * c;\n          pix[ppos + 1] = 0;\n          pix[ppos + 2] = 0;\n        }\n        else if ( c < 2 ) {\n          pix[ppos] = 255;\n          pix[ppos + 1] = 255 * (c - 1);\n          pix[ppos + 2] = 0;\n        } else {\n          pix[ppos] = 255;\n          pix[ppos + 1] = 255;\n          pix[ppos + 2] = 255 * (c - 2);\n        }\n      }\n      pix[ppos + 3] = 255;\n    }\n  }\n  \n  ctx.putImageData(img, 0, 0);\n}\n\nvar canvas = document.createElement('canvas');\ncanvas.width = 900;\ncanvas.height = 600;\n\ndocument.body.insertBefore(canvas, document.body.childNodes[0]);\n\nmandelbrot(canvas, -2, 1, -1, 1, 1000);\n\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. The code is compatible with modern browsers supporting HTML 5 canvas tag and can be executed directly from the Javascript console. It also utilizes ES6 and WebAssembly for improved performance, requiring a compiled WASM file.","id":2890}
    {"lang_cluster":"JavaScript","source_code":"\nvar array = [1, 2, 3, 4, 5],\n    sum = 0,\n    prod = 1,\n    i;\nfor (i = 0; i < array.length; i += 1) {\n    sum += array[i];\n    prod *= array[i];\n}\nalert(sum + ' ' + prod);\n\n\nWorks with: Javascript version 1.8\n\nvar array = [1, 2, 3, 4, 5],\n    sum = array.reduce(function (a, b) {\n        return a + b;\n    }, 0),\n    prod = array.reduce(function (a, b) {\n        return a * b;\n    }, 1);\nalert(sum + ' ' + prod);\n\n(() => {\n    'use strict';\n\n    \/\/ sum\u00a0:: (Num a) => [a] -> a\n    const sum = xs => xs.reduce((a, x) => a + x, 0);\n\n    \/\/ product\u00a0:: (Num a) => [a] -> a\n    const product = xs => xs.reduce((a, x) => a * x, 1);\n\n\n    \/\/ TEST\n    \/\/ show\u00a0:: a -> String\n    const show = x => JSON.stringify(x, null, 2);\n\n    return show(\n        [sum, product]\n        .map(f => f([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))\n    );\n})();\n\n\n","human_summarization":"Calculates the sum and product of all integers in an array.","id":2891}
    {"lang_cluster":"JavaScript","source_code":"\nvar isLeapYear = function (year) { return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0); };\n\n\n\/\/ Month values start at 0, so 1 is for February\nvar isLeapYear = function (year) { return new Date(year, 1, 29).getDate() === 29; };\n\n","human_summarization":"determine if a given year is a leap year in the Gregorian calendar by setting the day to the 29th and checking if the day remains.","id":2892}
    {"lang_cluster":"JavaScript","source_code":"\n\n(function () {\n    'use strict';\n\n    \/\/ concatMap\u00a0:: (a -> [b]) -> [a] -> [b]\n    function concatMap(f, xs) {\n        return [].concat.apply([], xs.map(f));\n    };\n\n    return '(Police, Sanitation, Fire)\\n' +\n        concatMap(function (x) {\n            return concatMap(function (y) {\n                return concatMap(function (z) {\n                    return z !== y && 1 <= z && z <= 7 ? [\n                        [x, y, z]\n                    ] : [];\n                }, [12 - (x + y)]);\n            }, [1, 2, 3, 4, 5, 6, 7]);\n        }, [2, 4, 6])\n        .map(JSON.stringify)\n        .join('\\n');\n})();\n\n\n","human_summarization":"generate all possible unique combinations of numbers between 1 and 7 for three departments - police, sanitation, and fire, such that the sum of the numbers is 12 and the number for the police department is even.","id":2893}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar container = {myString: \"Hello\"};\nvar containerCopy = container; \/\/ Now both identifiers refer to the same object\n\ncontainerCopy.myString = \"Goodbye\"; \/\/ container.myString will also return \"Goodbye\"\n\n\nvar a = \"Hello\";\nvar b = a; \/\/ Same as saying window.b = window.a\n\nb = \"Goodbye\" \/\/ b contains a copy of a's value and a will still return \"Hello\"\n\n","human_summarization":"demonstrate how to copy a string in JavaScript, distinguishing between copying the string's content and creating an additional reference to the existing string. It also illustrates that changes to one string will reflect in the other when copied via reassignment, and only the value, not the reference, will be copied when copying properties of global objects like window in browsers.","id":2894}
    {"lang_cluster":"JavaScript","source_code":"\nfunction f(num) {\n return (num === 0) ? 1 : num - m(f(num - 1));\n}\n\nfunction m(num) {\n return (num === 0) ? 0 : num - f(m(num - 1));\n}\n\nfunction range(m, n) {\n  return Array.apply(null, Array(n - m + 1)).map(\n    function (x, i) { return m + i; }\n  );\n}\n\nvar a = range(0, 19);\n\n\/\/return a new array of the results and join with commas to print\nconsole.log(a.map(function (n) { return f(n); }).join(', '));\nconsole.log(a.map(function (n) { return m(n); }).join(', '));\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions follow the defined rules: F(0) = 1, M(0) = 0, F(n) = n - M(F(n - 1)) for n > 0, and M(n) = n - F(M(n - 1)) for n > 0. If the programming language does not support mutual recursion, it is stated instead of providing a different solution.","id":2895}
    {"lang_cluster":"JavaScript","source_code":"\nvar array = [1,2,3];\nreturn array[Math.floor(Math.random() * array.length)];\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":2896}
    {"lang_cluster":"JavaScript","source_code":"\ndecodeURIComponent(\"http%3A%2F%2Ffoo%20bar%2F\")\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":2897}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction binary_search_recursive(a, value, lo, hi) {\n  if (hi < lo) { return null; }\n\n  var mid = Math.floor((lo + hi) \/ 2);\n\n  if (a[mid] > value) {\n    return binary_search_recursive(a, value, lo, mid - 1);\n  }\n  if (a[mid] < value) {\n    return binary_search_recursive(a, value, mid + 1, hi);\n  }\n  return mid;\n}\n\n\nfunction binary_search_iterative(a, value) {\n  var mid, lo = 0,\n      hi = a.length - 1;\n\n  while (lo <= hi) {\n    mid = Math.floor((lo + hi) \/ 2);\n\n    if (a[mid] > value) {\n      hi = mid - 1;\n    } else if (a[mid] < value) {\n      lo = mid + 1;\n    } else {\n      return mid;\n    }\n  }\n  return null;\n}\n\n\n(() => {\n    'use strict';\n\n    const main = () => {\n\n        \/\/ findRecursive\u00a0:: a -> [a] -> Either String Int\n        const findRecursive = (x, xs) => {\n            const go = (lo, hi) => {\n                if (hi < lo) {\n                    return Left('not found');\n                } else {\n                    const\n                        mid = div(lo + hi, 2),\n                        v = xs[mid];\n                    return v > x ? (\n                        go(lo, mid - 1)\n                    ) : v < x ? (\n                        go(mid + 1, hi)\n                    ) : Right(mid);\n                }\n            };\n            return go(0, xs.length);\n        };\n\n\n        \/\/ findRecursive\u00a0:: a -> [a] -> Either String Int\n        const findIter = (x, xs) => {\n            const [m, l, h] = until(\n                ([mid, lo, hi]) => lo > hi || lo === mid,\n                ([mid, lo, hi]) => {\n                    const\n                        m = div(lo + hi, 2),\n                        v = xs[m];\n                    return v > x ? [\n                        m, lo, m - 1\n                    ] : v < x ? [\n                        m, m + 1, hi\n                    ] : [m, m, hi];\n                },\n                [div(xs.length \/ 2), 0, xs.length - 1]\n            );\n            return l > h ? (\n                Left('not found')\n            ) : Right(m);\n        };\n\n        \/\/ TESTS ------------------------------------------\n\n        const\n            \/\/ (pre-sorted AZ)\n            xs = [\"alpha\", \"beta\", \"delta\", \"epsilon\", \"eta\", \"gamma\",\n                \"iota\", \"kappa\", \"lambda\", \"mu\", \"nu\", \"theta\", \"zeta\"\n            ];\n        return JSON.stringify([\n            'Recursive',\n            map(x => either(\n                    l => \"'\" + x + \"' \" + l,\n                    r => \"'\" + x + \"' found at index \" + r,\n                    findRecursive(x, xs)\n                ),\n                knuthShuffle(['cape'].concat(xs).concat('cairo'))\n            ),\n            '',\n            'Iterative:',\n            map(x => either(\n                    l => \"'\" + x + \"' \" + l,\n                    r => \"'\" + x + \"' found at index \" + r,\n                    findIter(x, xs)\n                ),\n                knuthShuffle(['cape'].concat(xs).concat('cairo'))\n            )\n        ], null, 2);\n    };\n\n    \/\/ GENERIC FUNCTIONS ----------------------------------\n\n    \/\/ Left\u00a0:: a -> Either a b\n    const Left = x => ({\n        type: 'Either',\n        Left: x\n    });\n\n    \/\/ Right\u00a0:: b -> Either a b\n    const Right = x => ({\n        type: 'Either',\n        Right: x\n    });\n\n    \/\/ div\u00a0:: Int -> Int -> Int\n    const div = (x, y) => Math.floor(x \/ y);\n\n    \/\/ either\u00a0:: (a -> c) -> (b -> c) -> Either a b -> c\n    const either = (fl, fr, e) =>\n        'Either' === e.type ? (\n            undefined !== e.Left ? (\n                fl(e.Left)\n            ) : fr(e.Right)\n        ) : undefined;\n\n    \/\/ Abbreviation for quick testing\n\n    \/\/ enumFromTo\u00a0:: (Int, Int) -> [Int]\n    const enumFromTo = (m, n) =>\n        Array.from({\n            length: 1 + n - m\n        }, (_, i) => m + i);\n\n    \/\/ FOR TESTS\n\n    \/\/ knuthShuffle\u00a0:: [a] -> [a]\n    const knuthShuffle = xs => {\n        const swapped = (iFrom, iTo, xs) =>\n            xs.map(\n                (x, i) => iFrom !== i ? (\n                    iTo !== i ? x : xs[iFrom]\n                ) : xs[iTo]\n            );\n        return enumFromTo(0, xs.length - 1)\n            .reduceRight((a, i) => {\n                const iRand = randomRInt(0, i)();\n                return i !== iRand ? (\n                    swapped(i, iRand, a)\n                ) : a;\n            }, xs);\n    };\n\n    \/\/ map\u00a0:: (a -> b) -> [a] -> [b]\n    const map = (f, xs) =>\n        (Array.isArray(xs) ? (\n            xs\n        ) : xs.split('')).map(f);\n\n\n    \/\/ FOR TESTS\n\n    \/\/ randomRInt\u00a0:: Int -> Int -> IO () -> Int\n    const randomRInt = (low, high) => () =>\n        low + Math.floor(\n            (Math.random() * ((high - low) + 1))\n        );\n\n    \/\/ reverse\u00a0:: [a] -> [a]\n    const reverse = xs =>\n        'string' !== typeof xs ? (\n            xs.slice(0).reverse()\n        ) : xs.split('').reverse().join('');\n\n    \/\/ until\u00a0:: (a -> Bool) -> (a -> a) -> a -> a\n    const until = (p, f, x) => {\n        let v = x;\n        while (!p(v)) v = f(v);\n        return v;\n    };\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n\n","human_summarization":"The code implements a binary search algorithm that searches for a specific \"secret\" value within a sorted integer array. The search can be performed both recursively and iteratively. The algorithm divides the search range in half repeatedly until the secret value is found or the range is exhausted. The code also handles multiple values equal to the given value and indicates whether the element was found or not. It returns the index of the secret value if found, otherwise, it returns the insertion point. The code also includes variations of the binary search algorithm that return the leftmost and rightmost insertion points. Additionally, the code avoids overflow bugs during the calculation of the mid-point of the search range.","id":2898}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: Node.js\nprocess.argv.forEach((val, index) => {\n  console.log(`${index}: ${val}`);\n});\n\nWorks with: JScript\nvar objArgs = WScript.Arguments;\nfor (var i = 0; i < objArgs.length; i++)\n   WScript.Echo(objArgs.Item(i));\n\nWorks with: JScript.NET (compiled with jsc.exe)\nimport System;\nvar argv:String[] = Environment.GetCommandLineArgs();\nfor (var i in argv)\n  print(argv[i]);\n\nWorks with: Rhino\nWorks with: SpiderMonkey\nfor (var i = 0; i < arguments.length; i++)\n    print(arguments[i]);\n\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c \"alpha beta\" -h \"gamma\"'. It also includes functionalities for intelligent parsing of these arguments.","id":2899}
    {"lang_cluster":"JavaScript","source_code":"<html><head>\n  <title>Pendulum<\/title>\n<\/head><body style=\"background: gray;\">\n\n<canvas id=\"canvas\" width=\"600\" height=\"600\">\n  <p>Sorry, your browser does not support the <canvas> used to display the pendulum animation.<\/p>\n<\/canvas>\n<script>\n  function PendulumSim(length_m, gravity_mps2, initialAngle_rad, timestep_ms, callback) {\n    var velocity = 0;\n    var angle = initialAngle_rad;\n    var k = -gravity_mps2\/length_m;\n    var timestep_s = timestep_ms \/ 1000;\n    return setInterval(function () {\n      var acceleration = k * Math.sin(angle);\n      velocity += acceleration * timestep_s;\n      angle    += velocity     * timestep_s;\n      callback(angle);\n    }, timestep_ms);\n  }\n  \n  var canvas = document.getElementById('canvas');\n  var context = canvas.getContext('2d');\n  var prev=0;\n  var sim = PendulumSim(1, 9.80665, Math.PI*99\/100, 10, function (angle) {\n    var rPend = Math.min(canvas.width, canvas.height) * 0.47;\n    var rBall = Math.min(canvas.width, canvas.height) * 0.02;\n    var rBar = Math.min(canvas.width, canvas.height) * 0.005;\n    var ballX = Math.sin(angle) * rPend;\n    var ballY = Math.cos(angle) * rPend;\n\n    context.fillStyle = \"rgba(255,255,255,0.51)\";\n    context.globalCompositeOperation = \"destination-out\";\n    context.fillRect(0, 0, canvas.width, canvas.height);\n    \n    context.fillStyle = \"yellow\";\n    context.strokeStyle = \"rgba(0,0,0,\"+Math.max(0,1-Math.abs(prev-angle)*10)+\")\";\n    context.globalCompositeOperation = \"source-over\";\n\n    context.save();\n      context.translate(canvas.width\/2, canvas.height\/2);\n      context.rotate(angle);\n      \n      context.beginPath();\n      context.rect(-rBar, -rBar, rBar*2, rPend+rBar*2);\n      context.fill();\n      context.stroke();\n      \n      context.beginPath();\n      context.arc(0, rPend, rBall, 0, Math.PI*2, false);\n      context.fill();\n      context.stroke();\n    context.restore();\n    prev=angle;\n  });\n<\/script>\n\n<\/body><\/html>\n\n\n<svg height=\"100%\" width=\"100%\" viewBox=\"-2 0 4 4\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\">\n  <line id=\"string\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\" stroke=\"grey\" stroke-width=\"0.05\" \/>\n  <circle id=\"ball\" cx=\"0\" cy=\"0\" r=\"0.1\" fill=\"black\" \/>\n  <script>\n    \/*jshint esnext: true *\/\n\n    function rk4(dt, x, f) {\n      \"use strict\";\n      let from = Array.from,\n          a = from(f(from(x,  $    => $         )), $ => $*dt),\n          b = from(f(from(x, ($,i) => $ + a[i]\/2)), $ => $*dt),\n          c = from(f(from(x, ($,i) => $ + b[i]\/2)), $ => $*dt),\n          d = from(f(from(x, ($,i) => $ + c[i]  )), $ => $*dt);\n      return from(x, (_,i) => (a[i] + 2*b[i] + 2*c[i] + d[i])\/6);\n    }\n\n    function setPendulumPos($) {\n      const string = document.getElementById(\"string\"),\n            ball = document.getElementById(\"ball\");\n      let $2 = $*$,\n          x = 2*$\/(1+$2),\n          y = (1-$2)\/(1+$2);\n      string.setAttribute(\"x2\", x);\n      string.setAttribute(\"y2\", y);\n      ball.setAttribute(\"cx\", x);\n      ball.setAttribute(\"cy\", y);\n    }\n\n    var q = [1, 0];\n    var previousTimestamp;\n    (function animate(timestamp) {\n      if ( previousTimestamp !== undefined) {\n        let dq = rk4((timestamp - previousTimestamp)\/1000, q, $ => [$[1], 2*$[1]*$[1]*$[0]\/(1+$[0]*$[0]) - $[0]]);\n        q = [q[0] + dq[0], q[1] + dq[1]];\n        setPendulumPos(q[0]);\n      }\n      previousTimestamp = timestamp;\n      window.requestAnimationFrame(animate);    \n    })()\n  <\/script>\n<\/svg>\n\n","human_summarization":"simulate and animate a simple gravity pendulum using SVG. The animation is created using a stereographic projection of the circle and the Euler-Lagrange equations are integrated using the Runge-Kutta method. The problem is formulated in a dimensionless manner, assuming unit values for mass and length.","id":2900}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar data = JSON.parse('{ \"foo\": 1, \"bar\": [10, \"apples\"] }');\n\nvar sample = { \"blue\": [1,2], \"ocean\": \"water\" };\nvar json_string = JSON.stringify(sample);\n\n\n","human_summarization":"The code loads a JSON string into a data structure and creates a new data structure, serializing it into valid JSON using objects and arrays. It requires a JSON library, which is available in all major browsers. The JSON used is different from JavaScript object literal.","id":2901}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction nthRoot(num, nArg, precArg) {\n  var n = nArg || 2;\n  var prec = precArg || 12;\n  \n  var x = 1; \/\/ Initial guess.\n  for (var i=0; i<prec; i++) {\n    x = 1\/n * ((n-1)*x + (num \/ Math.pow(x, n-1)));\n  }\n  \n  return x;\n}\n\n","human_summarization":"Implement the algorithm to compute the principal nth root of a positive real number with a default precision of 12 and n defaulting to 2.","id":2902}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: JScript\nvar network = new ActiveXObject('WScript.Network');\nvar hostname = network.computerName;\nWScript.echo(hostname);\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":2903}
    {"lang_cluster":"JavaScript","source_code":"\nconst leoNum = (c, l0 = 1, l1 = 1, add = 1) =>\n    new Array(c).fill(add).reduce(\n        (p, c, i) => i > 1 ? (\n            p.push(p[i - 1] + p[i - 2] + c) && p\n        ) : p, [l0, l1]\n    );\n    \nconsole.log(leoNum(25));\nconsole.log(leoNum(25, 0, 1, 0));\n\n[1, 1, 3, 5, 9, 15, 25, 41, 67, 109, 177, 287, 465, 753, 1219, 1973, 3193, 5167, 8361, 13529, 21891, 35421, 57313, 92735, 150049]\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368]\n(() => {\n    'use strict';\n\n    \/\/ leo\u00a0:: Int -> Int -> Int -> Generator [Int]\n    function* leo(L0, L1, delta) {\n        let [x, y] = [L0, L1];\n        while (true) {\n            yield x;\n            [x, y] = [y, delta + x + y];\n        }\n    }\n\n    \/\/ ----------------------- TEST ------------------------\n    \/\/ main\u00a0:: IO ()\n    const main = () => {\n        const\n            leonardo = leo(1, 1, 1),\n            fibonacci = leo(0, 1, 0);\n\n        return unlines([\n            'First 25 Leonardo numbers:',\n            indentWrapped(take(25)(leonardo)),\n            '',\n            'First 25 Fibonacci numbers:',\n            indentWrapped(take(25)(fibonacci))\n        ]);\n    };\n\n    \/\/ -------------------- FORMATTING ---------------------\n\n    \/\/ indentWrapped\u00a0:: [Int] -> String\n    const indentWrapped = xs =>\n        unlines(\n            map(x => '\\t' + x.join(','))(\n                chunksOf(16)(\n                    map(str)(xs)\n                )\n            )\n        );\n\n    \/\/ ----------------- GENERIC FUNCTIONS -----------------\n\n    \/\/ chunksOf\u00a0:: Int -> [a] -> [[a]]\n    const chunksOf = n =>\n        xs => enumFromThenTo(0)(n)(\n            xs.length - 1\n        ).reduce(\n            (a, i) => a.concat([xs.slice(i, (n + i))]),\n            []\n        );\n\n    \/\/ enumFromThenTo\u00a0:: Int -> Int -> Int -> [Int]\n    const enumFromThenTo = x1 =>\n        x2 => y => {\n            const d = x2 - x1;\n            return Array.from({\n                length: Math.floor(y - x2) \/ d + 2\n            }, (_, i) => x1 + (d * i));\n        };\n\n    \/\/ map\u00a0:: (a -> b) -> [a] -> [b]\n    const map = f =>\n        \/\/ The list obtained by applying f\n        \/\/ to each element of xs.\n        \/\/ (The image of xs under f).\n        xs => [...xs].map(f);\n\n    \/\/ str\u00a0:: a -> String\n    const str = x =>\n        x.toString();\n\n    \/\/ take\u00a0:: Int -> [a] -> [a]\n    \/\/ take\u00a0:: Int -> String -> String\n    const take = n =>\n        \/\/ The first n elements of a list,\n        \/\/ string of characters, or stream.\n        xs => 'GeneratorFunction' !== xs\n        .constructor.constructor.name ? (\n            xs.slice(0, n)\n        ) : [].concat.apply([], Array.from({\n            length: n\n        }, () => {\n            const x = xs.next();\n            return x.done ? [] : [x.value];\n        }));\n\n    \/\/ unlines\u00a0:: [String] -> String\n    const unlines = xs => xs.join('\\n');\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n\n","human_summarization":"generates the first 25 Leonardo numbers starting from L(0), allows customization of the first two Leonardo numbers and the add number, and can also generate the Fibonacci sequence by setting 0 and 1 for L(0) and L(1), and 0 for the add number.","id":2904}
    {"lang_cluster":"JavaScript","source_code":"\nfunction twentyfour(numbers, input) {\n    var invalidChars = \/[^\\d\\+\\*\\\/\\s-\\(\\)]\/;\n\n    var validNums = function(str) {\n        \/\/ Create a duplicate of our input numbers, so that\n        \/\/ both lists will be sorted.\n        var mnums = numbers.slice();\n        mnums.sort();\n\n        \/\/ Sort after mapping to numbers, to make comparisons valid.\n        return str.replace(\/[^\\d\\s]\/g, \" \")\n            .trim()\n            .split(\/\\s+\/)\n            .map(function(n) { return parseInt(n, 10); })\n            .sort()\n            .every(function(v, i) { return v === mnums[i]; });\n    };\n\n    var validEval = function(input) {\n        try {\n            return eval(input);\n        } catch (e) {\n            return {error: e.toString()};\n        }\n    };\n\n    if (input.trim() === \"\") return \"You must enter a value.\";\n    if (input.match(invalidChars)) return \"Invalid chars used, try again. Use only:\\n + - * \/ ( )\";\n    if (!validNums(input)) return \"Wrong numbers used, try again.\";\n    var calc = validEval(input);\n    if (typeof calc !== 'number') return \"That is not a valid input; please try again.\";\n    if (calc !== 24) return \"Wrong answer: \" + String(calc) + \"; please try again.\";\n    return input + \" == 24.  Congratulations!\";\n};\n\n\/\/ I\/O below.\n\nwhile (true) {\n    var numbers = [1, 2, 3, 4].map(function() {\n        return Math.floor(Math.random() * 8 + 1);\n    });\n\n    var input = prompt(\n        \"Your numbers are:\\n\" + numbers.join(\" \") +\n        \"\\nEnter expression. (use only + - * \/ and parens).\\n\", +\"'x' to exit.\", \"\");\n\n    if (input === 'x') {\n        break;\n    }\n    alert(twentyfour(numbers, input));\n}\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":2905}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction encode(input) {\n    var encoding = [];\n    var prev, count, i;\n    for (count = 1, prev = input[0], i = 1; i < input.length; i++) {\n        if (input[i] != prev) {\n            encoding.push([count, prev]);\n            count = 1;\n            prev = input[i];\n        }\n        else \n            count ++;\n    }\n    encoding.push([count, prev]);\n    return encoding;\n}\n\nHere's an encoding method that uses a regular expression to grab the character runs (Works with: JavaScript version 1.6 for the forEach method)\nfunction encode_re(input) {\n    var encoding = [];\n    input.match(\/(.)\\1*\/g).forEach(function(substr){ encoding.push([substr.length, substr[0]]) });\n    return encoding;\n}\n\n\nfunction decode(encoded) {\n    var output = \"\";\n    encoded.forEach(function(pair){ output += new Array(1+pair[0]).join(pair[1]) })\n    return output;\n}\n\n\n(() => {\n    'use strict';\n\n    \/\/ runLengthEncode\u00a0:: String -> [(Int, Char)]\n    const runLengthEncoded = s =>\n        group(s.split('')).map(\n            cs => [cs.length, cs[0]]\n        );\n\n    \/\/ runLengthDecoded\u00a0:: [(Int, Char)] -> String\n    const runLengthDecoded = pairs =>\n        pairs.map(([n, c]) => c.repeat(n)).join('');\n\n\n    \/\/ ------------------------TEST------------------------\n    const main = () => {\n        const\n            xs = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWW' +\n            'WWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW',\n            ys = runLengthEncoded(xs);\n\n        console.log('From: ', show(xs));\n        [ys, runLengthDecoded(ys)].forEach(\n            x => console.log('  ->  ', show(x))\n        )\n    };\n\n    \/\/ ----------------------GENERIC-----------------------\n\n    \/\/ group\u00a0:: [a] -> [[a]]\n    const group = xs => {\n        \/\/ A list of lists, each containing only equal elements,\n        \/\/ such that the concatenation of these lists is xs.\n        const go = xs =>\n            0 < xs.length ? (() => {\n                const\n                    h = xs[0],\n                    i = xs.findIndex(x => h !== x);\n                return i !== -1 ? (\n                    [xs.slice(0, i)].concat(go(xs.slice(i)))\n                ) : [xs];\n            })() : [];\n        return go(xs);\n    };\n\n    \/\/ show\u00a0:: a -> String\n    const show = JSON.stringify;\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n\n","human_summarization":"implement a run-length encoding and decoding system. It compresses strings by counting the number of repeated characters and then reverses the compression. The input is a string of uppercase characters, and the output is a string representing the count and character. The code also includes a method that traverses the input string character by character for encoding, and a function for decoding. A generic group function and a .reduce() based one-liner are also defined.","id":2906}
    {"lang_cluster":"JavaScript","source_code":"\nvar s = \"hello\"\nprint(s + \" there!\")\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":2907}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar normal = 'http:\/\/foo\/bar\/';\nvar encoded = encodeURIComponent(normal);\n\n","human_summarization":"The code provides a function to convert a given string into URL encoding representation. It converts all characters except 0-9, A-Z, and a-z into a percent symbol followed by a two-digit hexadecimal code. It also handles ASCII control codes, symbols, and extended characters. The code also supports variations like lowercase escapes and different encoding standards like RFC 3986, HTML 5, and encodeURI function in Javascript. An optional feature to use an exception string is also provided.","id":2908}
    {"lang_cluster":"JavaScript","source_code":"\n(() => {\n    \"use strict\";\n\n    \/\/ --------------- COMMON SORTED LIST ----------------\n\n    \/\/ commonSorted\u00a0:: Ord a => [[a]] -> [a]\n    const commonSorted = xs =>\n        sort(nub(concat(xs)));\n\n\n    \/\/ ---------------------- TEST -----------------------\n    const main = () =>\n        commonSorted([\n            [5, 1, 3, 8, 9, 4, 8, 7],\n            [3, 5, 9, 8, 4],\n            [1, 3, 7, 9]\n        ]);\n\n\n    \/\/ --------------------- GENERIC ---------------------\n\n    \/\/ concat\u00a0:: [[a]] -> [a]\n    const concat = xs =>\n        xs.flat(1);\n\n\n    \/\/ nub\u00a0:: Eq a => [a] -> [a]\n    const nub = xs => [...new Set(xs)];\n\n\n    \/\/ sort\u00a0:: Ord a => [a] -> [a]\n    const sort = xs =>\n        \/\/ An (ascending) sorted copy of xs.\n        xs.slice().sort();\n\n    return main();\n})();\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":2909}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: Node.js\nvar fs = require('fs');\nvar words = fs.readFileSync('unixdict.txt', 'UTF-8').split('\\n');\n\nvar i, item, max = 0,\n    anagrams = {};\n \nfor (i = 0; i < words.length; i += 1) {\n  var key = words[i].split('').sort().join('');\n  if (!anagrams.hasOwnProperty(key)) {\/\/check if property exists on current obj only\n      anagrams[key] = [];\n  }\n  var count = anagrams[key].push(words[i]); \/\/push returns new array length\n  max = Math.max(count, max);\n}\n\n\/\/note, this returns all arrays that match the maximum length\nfor (item in anagrams) {\n  if (anagrams.hasOwnProperty(item)) {\/\/check if property exists on current obj only\n    if (anagrams[item].length === max) {\n        console.log(anagrams[item].join(' '));\n    }\n  }\n}\n\n\n","human_summarization":"Code summarization: The code uses JavaScript for Automation on macOS to find sets of words from a given word list that are anagrams, i.e., they share the same characters but in different orders. The code specifically identifies the sets with the most words.","id":2910}
    {"lang_cluster":"JavaScript","source_code":"\nWorks with: JavaScript version 1.6\nWorks with: Firefox version 1.5+\n\n<!DOCTYPE html PUBLIC \"-\/\/W3C\/\/DTD HTML 4.01\/\/EN\" \"http:\/\/www.w3.org\/TR\/html4\/strict.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text\/html;charset=utf-8\">\n<title>Sierpinski Carpet<\/title>\n<script type='text\/javascript'>\n\nvar black_char = \"#\";\nvar white_char = \" \";\n\nvar SierpinskiCarpet = function(size) {\n    this.carpet = [black_char];\n    for (var i = 1; i <= size; i++) {\n        this.carpet = [].concat(\n            this.carpet.map(this.sier_top),\n            this.carpet.map(this.sier_middle),\n            this.carpet.map(this.sier_top)\n        );\n    }\n}\n\nSierpinskiCarpet.prototype.sier_top = function(x) {\n    var str = new String(x);\n    return new String(str+str+str);\n}\n\nSierpinskiCarpet.prototype.sier_middle = function (x) {\n    var str = new String(x);\n    var spacer = str.replace(new RegExp(black_char, 'g'), white_char);\n    return new String(str+spacer+str);\n}\n\nSierpinskiCarpet.prototype.to_string = function() {\n    return this.carpet.join(\"\\n\")\n}\n\nSierpinskiCarpet.prototype.to_html = function(target) {\n    var table = document.createElement('table');\n    for (var i = 0; i < this.carpet.length; i++) {\n        var row = document.createElement('tr');\n        for (var j = 0; j < this.carpet[i].length; j++) {\n            var cell = document.createElement('td');\n            cell.setAttribute('class', this.carpet[i][j] == black_char ? 'black' : 'white');\n            cell.appendChild(document.createTextNode('\\u00a0'));\n            row.appendChild(cell);\n        }\n        table.appendChild(row);\n    }\n    target.appendChild(table);\n}\n\n<\/script>\n<style type='text\/css'>\n    table {border-collapse: collapse;}\n    td {width: 1em;}\n    .black {background-color: black;}\n    .white {background-color: white;}\n<\/style>\n<\/head>\n<body>\n\n<pre id='to_string' style='float:left; margin-right:0.25in'><\/pre>\n<div id='to_html'><\/div>\n    \n<script type='text\/javascript'>\n    var sc = new SierpinskiCarpet(3);\n    document.getElementById('to_string').appendChild(document.createTextNode(sc.to_string()));\n    sc.to_html(document.getElementById('to_html'));\n<\/script>\n\n<\/body>\n<\/html>\n\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation is created using a N by N array of boolean values, which are then mapped to lines of characters for output. The code also allows for the generation of a graphical representation via HTML and CSS in a browser environment. The placement of whitespace and non-whitespace characters is crucial in the representation.","id":2911}
    {"lang_cluster":"JavaScript","source_code":"Works with: SpiderMonkey for the print() function.\n\nfunction HuffmanEncoding(str) {\n    this.str = str;\n\n    var count_chars = {};\n    for (var i = 0; i < str.length; i++) \n        if (str[i] in count_chars) \n            count_chars[str[i]] ++;\n        else \n            count_chars[str[i]] = 1;\n\n    var pq = new BinaryHeap(function(x){return x[0];});\n    for (var ch in count_chars) \n        pq.push([count_chars[ch], ch]);\n\n    while (pq.size() > 1) {\n        var pair1 = pq.pop();\n        var pair2 = pq.pop();\n        pq.push([pair1[0]+pair2[0], [pair1[1], pair2[1]]]);\n    }\n\n    var tree = pq.pop();\n    this.encoding = {};\n    this._generate_encoding(tree[1], \"\");\n\n    this.encoded_string = \"\"\n    for (var i = 0; i < this.str.length; i++) {\n        this.encoded_string += this.encoding[str[i]];\n    }\n}\n\nHuffmanEncoding.prototype._generate_encoding = function(ary, prefix) {\n    if (ary instanceof Array) {\n        this._generate_encoding(ary[0], prefix + \"0\");\n        this._generate_encoding(ary[1], prefix + \"1\");\n    }\n    else {\n        this.encoding[ary] = prefix;\n    }\n}\n\nHuffmanEncoding.prototype.inspect_encoding = function() {\n    for (var ch in this.encoding) {\n        print(\"'\" + ch + \"': \" + this.encoding[ch])\n    }\n}\n\nHuffmanEncoding.prototype.decode = function(encoded) {\n    var rev_enc = {};\n    for (var ch in this.encoding) \n        rev_enc[this.encoding[ch]] = ch;\n\n    var decoded = \"\";\n    var pos = 0;\n    while (pos < encoded.length) {\n        var key = \"\"\n        while (!(key in rev_enc)) {\n            key += encoded[pos];\n            pos++;\n        }\n        decoded += rev_enc[key];\n    }\n    return decoded;\n}\n\n\nvar s = \"this is an example for huffman encoding\";\nprint(s);\n\nvar huff = new HuffmanEncoding(s);\nhuff.inspect_encoding();\n\nvar e = huff.encoded_string;\nprint(e);\n\nvar t = huff.decode(e);\nprint(t);\n\nprint(\"is decoded string same as original? \" + (s==t));\n\n\n","human_summarization":"The code implements Huffman encoding for a given string. It first calculates the frequency of each character in the string. It then uses a binary heap to create a tree of nodes, where each node represents a character and its frequency. The tree is constructed such that nodes with lower frequencies are higher up in the tree. The code then traverses the tree from root to leaves, assigning a '0' for one branch and a '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for the corresponding character. The output is a table of characters and their Huffman encodings.","id":2912}
    {"lang_cluster":"JavaScript","source_code":"\n<html>\n<head>\n    <title>Simple Window Application<\/title>\n<\/head>\n\n<body>\n    <br>            \n\n    <script type=\"text\/javascript\">\n        var box = document.createElement('input') \n        box.style.position = 'absolute';  \/\/ position it\n        box.style.left = '10px';\n        box.style.top = '60px';\n        document.body.appendChild(box).style.border=\"3px solid white\"; \n        document.body.appendChild(box).value = \"There have been no clicks yet\"; \n        document.body.appendChild(box).style['width'] = '220px';\n        var clicks = 0;\n        function count_clicks() {\n            document.body.appendChild(box).remove()\n            clicks += 1;\n            document.getElementById(\"clicks\").innerHTML = clicks;\n        };\n    <\/script>\n\n    <button type=\"button\" onclick=\"count_clicks()\"> Click me<\/button>\n    <pre><p>    Clicks: <a id=\"clicks\">0<\/a> <\/p><\/pre> \n<\/body>\n\n<\/html>\n\n\n\n","human_summarization":"create a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button is labeled \"click me\". The label updates to show the number of times the button has been clicked when the button is clicked.","id":2913}
    {"lang_cluster":"JavaScript","source_code":"\nfor (var i=10; i>=0; --i) print(i);\n\n\nfor (var i = 11; i--;) console.log(i);\n\n\nvar i = 11;\nwhile (i--) console.log(i);\n\n\nfunction range(m, n) {\n  return Array.apply(null, Array(n - m + 1)).map(\n    function (x, i) {\n      return m + i;\n    }\n  );\n}\n\nrange(0, 10).reverse().forEach(\n  function (x) {\n    console.log(x);\n  }\n);\n\n\nconsole.log(\n  range(0, 10).reverse().map(\n    function (x) {\n      return x;\n    }\n  ).join('\\n')\n);\n\n\nconsole.log(\n    range(0, 10).reverse().join('\\n')\n);\n\n","human_summarization":"utilize a for loop to perform a countdown from 10 to 0. The code may be optimized for longer reversed iterations by moving the mutation into the test and omitting the third term of the for() statement. The code can also be written in a functional idiom of JavaScript using Array.map() instead of Array.forEach() for a composable expression with a value.","id":2914}
    {"lang_cluster":"JavaScript","source_code":"\n\/\/ helpers\n\/\/ helper\nfunction ordA(a) {\n  return a.charCodeAt(0) - 65;\n}\n\n\/\/ vigenere\nfunction vigenere(text, key, decode) {\n  var i = 0, b;\n  key = key.toUpperCase().replace(\/[^A-Z]\/g, '');\n  return text.toUpperCase().replace(\/[^A-Z]\/g, '').replace(\/[A-Z]\/g, function(a) {\n    b = key[i++ % key.length];\n    return String.fromCharCode(((ordA(a) + (decode ? 26 - ordA(b) : ordA(b))) % 26 + 65));\n  });\n}\n\n\/\/ example\nvar text = \"The quick brown fox Jumped over the lazy Dog the lazy dog lazy dog dog\";\nvar key = 'alex';\nvar enc = vigenere(text,key);\nvar dec = vigenere(enc,key,true);\n\nconsole.log(enc);\nconsole.log(dec);\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":2915}
    {"lang_cluster":"JavaScript","source_code":"\nvar output = '',\n    i;\nfor (i = 2; i <= 8; i += 2) {\n   output += i + ', ';\n}\noutput += 'who do we appreciate?';\ndocument.write(output);\n\n\n\/\/ range(iMax)\n\/\/ range(iMin, iMax)\n\/\/ range(iMin, iMax, dI)\nfunction range() {\n  var lngArgs = arguments.length,\n    lngMore = lngArgs - 1;\n\n  iMin = lngMore ? arguments[0] : 1;\n  iMax = arguments[lngMore ? 1 : 0];\n  dI = lngMore > 1 ? arguments[2] : 1;\n\n  return lngArgs ? Array.apply(null, Array(\n    Math.floor((iMax - iMin) \/ dI) + 1\n  )).map(function (_, i) {\n    return iMin + (dI * i);\n  }) : [];\n}\n\nconsole.log(\n  range(2, 8, 2).join(', ') + ', who do we appreciate\u00a0?'\n);\n\n\n2, 4, 6, 8, who do we appreciate\u00a0?\n","human_summarization":"demonstrate a for-loop in JavaScript with a step-value greater than one, using a functional idiom. The computation is composed within the superordinate expressions of the program, returning a value rather than firing off side-effects. The stepped series is generated as an expression, replacing a state-changing loop with a non-mutating map or fold.","id":2916}
    {"lang_cluster":"JavaScript","source_code":"\nvar obj;\n\nfunction sum(o, lo, hi, term) {\n  var tmp = 0;\n  for (o.val = lo; o.val <= hi; o.val++)\n    tmp += term();\n  return tmp;\n}\n\nobj = {val: 0};\nalert(sum(obj, 1, 100, function() {return 1 \/ obj.val}));\n\n\n","human_summarization":"The code implements Jensen's Device, a programming technique that exploits the call by name mechanism. It calculates the 100th harmonic number using a sum procedure, which takes in four parameters: an integer, two range values, and a term passed by name. The sum procedure iteratively adds the term to a temporary variable, which is then returned as the result. The calculation depends on the re-evaluation of the passed expression in the caller's context each time the formal parameter's value is needed. The first parameter, representing the bound variable of the summation, is also passed by name to ensure changes to it are visible in the caller's context. The result is displayed as '5.187377517639621'.","id":2917}
    {"lang_cluster":"JavaScript","source_code":"function maze(x,y) {\n\tvar n=x*y-1;\n\tif (n<0) {alert(\"illegal maze dimensions\");return;}\n\tvar horiz =[]; for (var j= 0; j<x+1; j++) horiz[j]= [],\n\t    verti =[]; for (var j= 0; j<x+1; j++) verti[j]= [],\n\t    here = [Math.floor(Math.random()*x), Math.floor(Math.random()*y)],\n\t    path = [here],\n\t    unvisited = [];\n\tfor (var j = 0; j<x+2; j++) {\n\t\tunvisited[j] = [];\n\t\tfor (var k= 0; k<y+1; k++)\n\t\t\tunvisited[j].push(j>0 && j<x+1 && k>0 && (j != here[0]+1 || k != here[1]+1));\n\t}\n\twhile (0<n) {\n\t\tvar potential = [[here[0]+1, here[1]], [here[0],here[1]+1],\n\t\t    [here[0]-1, here[1]], [here[0],here[1]-1]];\n\t\tvar neighbors = [];\n\t\tfor (var j = 0; j < 4; j++)\n\t\t\tif (unvisited[potential[j][0]+1][potential[j][1]+1])\n\t\t\t\tneighbors.push(potential[j]);\n\t\tif (neighbors.length) {\n\t\t\tn = n-1;\n\t\t\tnext= neighbors[Math.floor(Math.random()*neighbors.length)];\n\t\t\tunvisited[next[0]+1][next[1]+1]= false;\n\t\t\tif (next[0] == here[0])\n\t\t\t\thoriz[next[0]][(next[1]+here[1]-1)\/2]= true;\n\t\t\telse \n\t\t\t\tverti[(next[0]+here[0]-1)\/2][next[1]]= true;\n\t\t\tpath.push(here = next);\n\t\t} else \n\t\t\there = path.pop();\n\t}\n\treturn {x: x, y: y, horiz: horiz, verti: verti};\n}\n\nfunction display(m) {\n\tvar text= [];\n\tfor (var j= 0; j<m.x*2+1; j++) {\n\t\tvar line= [];\n\t\tif (0 == j%2)\n\t\t\tfor (var k=0; k<m.y*4+1; k++)\n\t\t\t\tif (0 == k%4) \n\t\t\t\t\tline[k]= '+';\n\t\t\t\telse\n\t\t\t\t\tif (j>0 && m.verti[j\/2-1][Math.floor(k\/4)])\n\t\t\t\t\t\tline[k]= ' ';\n\t\t\t\t\telse\n\t\t\t\t\t\tline[k]= '-';\n\t\telse\n\t\t\tfor (var k=0; k<m.y*4+1; k++)\n\t\t\t\tif (0 == k%4)\n\t\t\t\t\tif (k>0 && m.horiz[(j-1)\/2][k\/4-1])\n\t\t\t\t\t\tline[k]= ' ';\n\t\t\t\t\telse\n\t\t\t\t\t\tline[k]= '|';\n\t\t\t\telse\n\t\t\t\t\tline[k]= ' ';\n\t\tif (0 == j) line[1]= line[2]= line[3]= ' ';\n\t\tif (m.x*2-1 == j) line[4*m.y]= ' ';\n\t\ttext.push(line.join('')+'\\r\\n');\n\t}\n\treturn text.join('');\n}\n\n\nx,y \u2014 dimensions of maze\nn \u2014 number of openings to be generated\nhoriz \u2014 two dimensional array of locations of horizontal openings (true means wall is open)\nverti \u2014 two dimensional array of locations of vertical openings (true means wall is open)\nhere \u2014 current location under consideration\npath \u2014 history (stack) of locations that might need to be revisited\nunvisited \u2014 two dimensional array of locations that have not been visited, padded to avoid need for boundary tests (true means location needs to be visited)\npotential \u2014 locations adjacent to here\nneighbors \u2014 unvisited locations adjacent to here\n\nm \u2014 maze to be drawn\ntext \u2014 lines of text representing maze\nline \u2014 characters of current line\n\n\nExample use:\n<html><head><title><\/title><\/head><body><pre id=\"out\"><\/pre><\/body><\/html>\n<script type=\"text\/javascript\">\n\/* ABOVE CODE GOES HERE *\/\ndocument.getElementById('out').innerHTML= display(maze(8,11)); \n<\/script>\n\n\n+   +---+---+---+---+---+---+---+---+---+---+\n|                   |                   |   |\n+---+---+   +   +---+   +   +---+---+   +   +\n|       |   |   |       |   |           |   |\n+   +   +   +---+   +---+   +---+---+   +   +\n|   |   |               |           |   |   |\n+   +---+   +---+---+---+---+---+   +   +   +\n|       |   |               |       |       |\n+---+   +---+   +---+---+   +   +---+---+   +\n|   |   |       |               |       |   |\n+   +   +   +---+---+---+---+---+   +   +   +\n|       |                   |       |   |   |\n+   +---+---+   +---+---+   +   +---+---+   +\n|   |       |   |           |       |       |\n+   +   +   +---+   +---+---+   +   +   +---+\n|       |           |           |            \n+---+---+---+---+---+---+---+---+---+---+---+\n\n\tfunction step() {\n\t\tif (0<n) {\n\n\n\t\t\tdocument.getElementById('out').innerHTML= display({x: x, y: y, horiz: horiz, verti: verti, here: here});\n\t\t\tsetTimeout(step, 100);\n\t\t}\n\t}\n\tstep();\n\n\n\t\t\t\tif (m.here && m.here[0]*2+1 == j && m.here[1]*4+2 == k) \n\t\t\t\t\tline[k]= '#'\n\t\t\t\telse if (0 == k%4) {\n\n\n\t\t\there= next;\n\t\t\tif (1 < neighbors.length) \n\t\t\t\tpath.push(here);\n\n\n\n<html><head><title>Maze maker<\/title>\n<style type=\"text\/css\">\ntable { border-collapse: collapse }\ntd { width: 1em; height: 1em; border: 1px solid }\ntd.s { border-bottom: none }\ntd.n { border-top: none }\ntd.w { border-left: none }\ntd.e { border-right: none }\ntd.v { background: skyblue}\n<\/style>\n<script type=\"application\/javascript\">\nNode.prototype.add = function(tag, cnt, txt) {\n\tfor (var i = 0; i < cnt; i++)\n\t\tthis.appendChild(ce(tag, txt));\n}\nNode.prototype.ins = function(tag) {\n\tthis.insertBefore(ce(tag), this.firstChild)\n}\nNode.prototype.kid = function(i) { return this.childNodes[i] }\nNode.prototype.cls = function(t) { this.className += ' ' + t }\n\nNodeList.prototype.map = function(g) {\n\tfor (var i = 0; i < this.length; i++) g(this[i]);\n}\n\nfunction ce(tag, txt) {\n\tvar x = document.createElement(tag);\n\tif (txt !== undefined) x.innerHTML = txt;\n\treturn x\n}\n\nfunction gid(e) { return document.getElementById(e) }\nfunction irand(x) { return Math.floor(Math.random() * x) }\n\nfunction make_maze() {\n\tvar w = parseInt(gid('rows').value || 8, 10);\n\tvar h = parseInt(gid('cols').value || 8, 10);\n\tvar tbl = gid('maze');\n\ttbl.innerHTML = '';\n\ttbl.add('tr', h);\n\ttbl.childNodes.map(function(x) {\n\t\t\tx.add('th', 1);\n\t\t\tx.add('td', w, '*');\n\t\t\tx.add('th', 1)});\n\ttbl.ins('tr');\n\ttbl.add('tr', 1);\n\ttbl.firstChild.add('th', w + 2);\n\ttbl.lastChild.add('th', w + 2);\n\tfor (var i = 1; i <= h; i++) {\n\t\tfor (var j = 1; j <= w; j++) {\n\t\t\ttbl.kid(i).kid(j).neighbors = [\n\t\t\t\ttbl.kid(i + 1).kid(j),\n\t\t\t\ttbl.kid(i).kid(j + 1),\n\t\t\t\ttbl.kid(i).kid(j - 1),\n\t\t\t\ttbl.kid(i - 1).kid(j)\n\t\t\t];\n\t\t}\n\t}\n\twalk(tbl.kid(irand(h) + 1).kid(irand(w) + 1));\n\tgid('solve').style.display='inline';\n}\n\nfunction shuffle(x) {\n\tfor (var i = 3; i > 0; i--) {\n\t\tj = irand(i + 1);\n\t\tif (j == i) continue;\n\t\tvar t = x[j]; x[j] = x[i]; x[i] = t;\n\t}\n\treturn x;\n}\n\nvar dirs = ['s', 'e', 'w', 'n'];\nfunction walk(c) {\n\tc.innerHTML = ' ';\n\tvar idx = shuffle([0, 1, 2, 3]);\n\tfor (var j = 0; j < 4; j++) {\n\t\tvar i = idx[j];\n\t\tvar x = c.neighbors[i];\n\t\tif (x.textContent != '*') continue;\n\t\tc.cls(dirs[i]), x.cls(dirs[3 - i]);\n\t\twalk(x);\n\t}\n}\n\nfunction solve(c, t) {\n\tif (c === undefined) {\n\t\tc = gid('maze').kid(1).kid(1);\n\t\tc.cls('v');\n\t}\n\tif (t === undefined)\n\t\tt = gid('maze')\t.lastChild.previousSibling\n\t\t\t\t.lastChild.previousSibling;\n\n\tif (c === t) return 1;\n\tc.vis = 1;\n\tfor (var i = 0; i < 4; i++) {\n\t\tvar x = c.neighbors[i];\n\t\tif (x.tagName.toLowerCase() == 'th') continue;\n\t\tif (x.vis || !c.className.match(dirs[i]) || !solve(x, t))\n\t\t\tcontinue;\n\n\t\tx.cls('v');\n\t\treturn 1;\n\t}\n\tc.vis = null;\n\treturn 0;\n}\n\n<\/script><\/head>\n<body><form><fieldset>\n<label>rows <\/label><input id='rows' size=\"3\"\/>\n<label>colums <\/label><input id='cols' size=\"3\"\/>\n<a href=\"javascript:make_maze()\">Generate<\/a>\n<a id='solve' style='display:none' href='javascript:solve(); void(0)'>Solve<\/a>\n<\/fieldset><\/form><table id='maze'\/><\/body><\/html>\n\n","human_summarization":"The code generates and displays a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and proceeds to its neighbors. If a neighbor hasn't been visited, the wall between the current cell and that neighbor is removed and the process is repeated for that neighbor. The code relies on JavaScript arrays' ability to be treated as infinite in size with null values appearing as needed. The progress of the maze creation can be animated by using a display function in each iteration of the main loop. The code also suggests an optimization to save processing, but it will still need to backtrack through locations with no unvisited neighbors. The maze is displayed using HTML, CSS, and table cells.","id":2918}
    {"lang_cluster":"JavaScript","source_code":"\n\nlet q = 1n, r = 180n, t = 60n, i = 2n;\nfor (;;) {\n  let y = (q*(27n*i-12n)+5n*r)\/(5n*t);\n  let u = 3n*(3n*i+1n)*(3n*i+2n);\n  r = 10n*u*(q*(5n*i-2n)+r-y*t);\n  q = 10n*q*i*(2n*i-1n);\n  t = t*u;\n  i = i+1n;\n  process.stdout.write(y.toString());\n  if (i === 3n) { process.stdout.write('.'); }\n}\n\n\n<html><head><script src='https:\/\/rawgit.com\/andyperlitch\/jsbn\/v1.1.0\/index.js'><\/script><\/head>\n<body style=\"width: 100%\"><tt id=\"pi\"><\/tt><tt>...<\/tt>\n<script async defer>\nfunction bi(n, b) { return new jsbn.BigInteger(n.toString(), b ? b : 10); };\nvar one=bi(1), two=bi(2), three=bi(3), four=bi(4), seven=bi(7), ten=bi(10);\nfunction calcPi() {\n    var q=bi(1), r=bi(0), t=bi(1), k=bi(1), n=bi(3), l=bi(3);\n    var digit=0, firstrun=1;\n    var p=document.getElementById('pi');\n    function w(s) { p.appendChild(document.createTextNode(s));}\n    function continueCalcPi(q, r, t, k, n, l) {\n        while (true) {\n            if (q.multiply(four).add(r).subtract(t).compareTo(n.multiply(t)) < 0) {\n                w(n.toString());\n                if (digit==0 && firstrun==1) { w('.'); firstrun=0; };\n                digit = (digit+1) % 256;\n                var nr = (r.subtract(n.multiply(t))).multiply(ten);\n                n  = (q.multiply(three).add(r)).multiply(ten).divide(t).subtract(n.multiply(ten));\n                q  = q.multiply(ten);\n                r  = nr;\n                if (digit%8==0) {\n                    if (digit%64==0) {\n                     p.appendChild(document.createElement('br'));\n                    }\n                    w(' ');\n                    return setTimeout(function() { continueCalcPi(q, r, t, k, n, l); }, 50);\n                };\n            } else {\n                var nr = q.shiftLeft(1).add(r).multiply(l);\n                var nn = q.multiply(k).multiply(seven).add(two).add(r.multiply(l)).divide(t.multiply(l));\n                q = q.multiply(k);\n                t = t.multiply(l);\n                l = l.add(two);\n                k = k.add(one);\n                n  = nn;\n                r  = nr;\n            }\n        }\n    }\n    continueCalcPi(q, r, t, k, n, l);\n}\ncalcPi();\n<\/script>\n<\/body><\/html>\n\n\n<html>\n <head>\n <\/head>\n <body style=\"width: 100%\">\n  <tt id=\"pi\"><\/tt>\n  <tt>...<\/tt>\n  <script async defer>\nfunction calcPi() {\n    let q=1n, r=0n, t=1n, k=1n, n=3n, l=3n, nr, nn, digit=0, firstrun=1;\n    const p=document.getElementById('pi');\n    function w(s) { p.appendChild(document.createTextNode(s));}\n\/\/  function continueCalcPi(q, r, t, k, n, l) {  \/\/ (see note)\n    function continueCalcPi() {\n        while (true) {\n            if (q*4n+r-t < n*t) {\n                w(n.toString());\n                if (digit==0 && firstrun==1) { w('.'); firstrun=0; };\n                digit = (digit+1) % 256;\n                nr = (r-n*t)*10n;\n                n  = (q*3n+r)*10n\/t-n*10n;\n                q *= 10n;\n                r  = nr;\n                if (digit%8==0) {\n                    if (digit%64==0) {\n                     p.appendChild(document.createElement('br'));\n                    }\n                    w('\\xA0');\n\/\/                  return setTimeout(function() { continueCalcPi(q, r, t, k, n, l); }, 50);\n                    return setTimeout(continueCalcPi, 50);\n                };\n            } else {\n                nr = (q*2n+r)*l;\n                nn = (q*k*7n+2n+r*l)\/(t*l);\n                q *= k;\n                t *= l;\n                l += 2n;\n                k += 1n;\n                n  = nn;\n                r  = nr;\n            }\n        }\n    }\n    continueCalcPi(q, r, t, k, n, l);\n}\ncalcPi();\n  <\/script>\n <\/body>\n<\/html>\n\n\n\nvar calcPi = function() {\n  var n = 20000;\n  var pi = 0;\n  for (var i = 0; i < n; i++) {\n    var temp = 4 \/ (i*2+1);\n    if (i\u00a0% 2 == 0) {\n      pi += temp;\n    }\n    else {\n      pi -= temp;\n    }\n  }\n  return pi;\n}\n\n","human_summarization":"The code continuously calculates and outputs the next decimal digit of Pi, starting from 3.14159265... until manually stopped by the user. It can be adapted to work in both Node.js and browser environments. It also includes a feature to load the code into a webpage without freezing the browser. The code uses BigInt and may consume significant memory. It returns an approximation of Pi, calculated one digit at a time.","id":2919}
    {"lang_cluster":"JavaScript","source_code":"\n\n(() => {\n    'use strict';\n\n    \/\/ <= is already defined for lists in JS\n\n    \/\/ compare\u00a0:: [a] -> [a] -> Bool\n    const compare = (xs, ys) => xs <= ys;\n\n\n    \/\/ TEST\n    return [\n        compare([1, 2, 1, 3, 2], [1, 2, 0, 4, 4, 0, 0, 0]),\n        compare([1, 2, 0, 4, 4, 0, 0, 0], [1, 2, 1, 3, 2])\n    ];\n\n    \/\/ --> [false, true]\n})()\n\n\n","human_summarization":"\"Function to compare and order two numerical lists based on lexicographic order, returning true if the first list should be ordered before the second, false otherwise.\"","id":2920}
    {"lang_cluster":"JavaScript","source_code":"\nfunction ack(m, n) {\n return m === 0 ? n + 1 : ack(m - 1, n === 0  ? 1 : ack(m, n - 1));\n}\n\nfunction ack(M,N) {\n  for (; M > 0; M--) {\n    N = N === 0 ? 1 : ack(M,N-1);\n  }\n  return N+1;\n}\n\nfunction stackermann(M, N) {\n  const stack = [];\n  for (;;) {\n    if (M === 0) {\n      N++;\n      if (stack.length === 0) return N;\n      const r = stack[stack.length-1];\n      if (r[1] === 1) stack.length--;\n      else r[1]--;\n      M = r[0];\n    } else if (N === 0) {\n      M--;\n      N = 1;\n    } else {\n      M--\n      stack.push([M, N]);\n      N = 1;\n    }\n  }\n}\n\n#!\/usr\/bin\/env nodejs\nfunction ack(M, N){\n\tconst next = new Float64Array(M + 1);\n\tconst goal = new Float64Array(M + 1).fill(1, 0, M);\n\tconst n = N + 1;\n\n\t\/\/ This serves as a sentinel value;\n\t\/\/ next[M] never equals goal[M] == -1,\n\t\/\/ so we don't need an extra check for\n\t\/\/ loop termination below.\n\tgoal[M] = -1;\n\n\tlet v;\n\tdo {\n\t\tv = next[0] + 1;\n\t\tlet m = 0;\n\t\twhile (next[m] === goal[m]) {\n\t\t\tgoal[m] = v;\n\t\t\tnext[m++]++;\n\t\t}\n\t\tnext[m]++;\n\t} while (next[M] !== n);\n\treturn v;\n}\nvar args = process.argv;\nconsole.log(ack(parseInt(args[2]), parseInt(args[3])));\n\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":2921}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction gamma(x) {\n    var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,\n        771.32342877765313, -176.61502916214059, 12.507343278686905,\n        -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7\n    ];\n\n    var g = 7;\n    if (x < 0.5) {\n        return Math.PI \/ (Math.sin(Math.PI * x) * gamma(1 - x));\n    }\n\n    x -= 1;\n    var a = p[0];\n    var t = x + g + 0.5;\n    for (var i = 1; i < p.length; i++) {\n        a += p[i] \/ (x + i);\n    }\n\n    return Math.sqrt(2 * Math.PI) * Math.pow(t, x + 0.5) * Math.exp(-t) * a;\n}\n\n","human_summarization":"Implement and compare the Gamma function using built-in\/library function and self-implemented algorithms. The function is defined through numerical integration, and methods include Lanczos and Stirling's approximation.","id":2922}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction queenPuzzle(rows, columns) {\n    if (rows <= 0) {\n        return [[]];\n    } else {\n        return addQueen(rows - 1, columns);\n    }\n}\n\nfunction addQueen(newRow, columns, prevSolution) {\n    var newSolutions = [];\n    var prev = queenPuzzle(newRow, columns);\n    for (var i = 0; i < prev.length; i++) {\n        var solution = prev[i];\n        for (var newColumn = 0; newColumn < columns; newColumn++) {\n            if (!hasConflict(newRow, newColumn, solution))\n                newSolutions.push(solution.concat([newColumn]))\n        }\n    }\n    return newSolutions;\n}\n\nfunction hasConflict(newRow, newColumn, solution) {\n    for (var i = 0; i < newRow; i++) {\n        if (solution[i]     == newColumn          ||\n            solution[i] + i == newColumn + newRow || \n            solution[i] - i == newColumn - newRow) {\n                return true;\n        }\n    }\n    return false;\n}\n\nconsole.log(queenPuzzle(8,8));\n\n\n(() => {\n    \"use strict\";\n\n    \/\/ ---------------- N QUEENS PROBLEM -----------------\n\n    \/\/ queenPuzzle\u00a0:: Int -> Int -> [[Int]]\n    const queenPuzzle = intCols => {\n        \/\/ All solutions for a given number\n        \/\/ of columns and rows.\n        const go = nRows =>\n            nRows <= 0 ? [\n                []\n            ] : go(nRows - 1).reduce(\n                (a, solution) => [\n                    ...a, ...(\n                        enumFromTo(0)(intCols - 1)\n                        .reduce((b, iCol) =>\n                            safe(\n                                nRows - 1, iCol, solution\n                            ) ? (\n                                [...b, [...solution, iCol]]\n                            ) : b, [])\n                    )\n                ], []\n            );\n\n\n        return go;\n    };\n\n    \/\/ safe\u00a0: Int -> Int -> [Int] -> Bool\n    const safe = (iRow, iCol, solution) =>\n        !zip(solution)(\n            enumFromTo(0)(iRow - 1)\n        )\n        .some(\n            ([sc, sr]) => (iCol === sc) || (\n                sc + sr === iCol + iRow\n            ) || (sc - sr === iCol - iRow)\n        );\n\n    \/\/ ---------------------- TEST -----------------------\n    \/\/ Ten columns of solutions to the 7*7 board\n\n    \/\/ main\u00a0:: IO ()\n    const main = () =>\n        \/\/ eslint-disable-next-line no-console\n        console.log(\n            showSolutions(10)(7)\n        );\n\n    \/\/ --------------------- DISPLAY ---------------------\n\n    \/\/ showSolutions\u00a0:: Int -> Int -> String\n    const showSolutions = nCols =>\n        \/\/ Display of solutions, in nCols columns\n        \/\/ for a board of size N * N.\n        n => chunksOf(nCols)(\n            queenPuzzle(n)(n)\n        )\n        .map(xs => transpose(\n                xs.map(\n                    rows => rows.map(\n                        r => enumFromTo(1)(rows.length)\n                        .flatMap(\n                            x => r === x ? (\n                                \"\u265b\"\n                            ) : \".\"\n                        )\n                        .join(\"\")\n                    )\n                )\n            )\n            .map(cells => cells.join(\"  \"))\n        )\n        .map(x => x.join(\"\\n\"))\n        .join(\"\\n\\n\");\n\n\n    \/\/ ---------------- GENERIC FUNCTIONS ----------------\n\n    \/\/ chunksOf\u00a0:: Int -> [a] -> [[a]]\n    const chunksOf = n => {\n        \/\/ xs split into sublists of length n.\n        \/\/ The last sublist will be short if n\n        \/\/ does not evenly divide the length of xs .\n        const go = xs => {\n            const chunk = xs.slice(0, n);\n\n            return Boolean(chunk.length) ? [\n                chunk, ...go(xs.slice(n))\n            ] : [];\n        };\n\n        return go;\n    };\n\n\n    \/\/ enumFromTo\u00a0:: Int -> Int -> [Int]\n    const enumFromTo = m =>\n        n => Array.from({\n            length: 1 + n - m\n        }, (_, i) => m + i);\n\n\n    \/\/ transpose_\u00a0:: [[a]] -> [[a]]\n    const transpose = rows =>\n        \/\/ The columns of the input transposed\n        \/\/ into new rows.\n        \/\/ Simpler version of transpose, assuming input\n        \/\/ rows of even length.\n        Boolean(rows.length) ? rows[0].map(\n            (_, i) => rows.flatMap(\n                v => v[i]\n            )\n        ) : [];\n\n\n    \/\/ zip\u00a0:: [a] -> [b] -> [(a, b)]\n    const zip = xs =>\n        \/\/ The paired members of xs and ys, up to\n        \/\/ the length of the shorter of the two lists.\n        ys => Array.from({\n            length: Math.min(xs.length, ys.length)\n        }, (_, i) => [xs[i], ys[i]]);\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n\n","human_summarization":"implement a solution to the N-queens problem using recursive backtracking. The algorithm checks for the correct position on subfields to save position checks. It also includes a function to display columns of solutions. The code is a translation of an ES5 version. It can solve the puzzle for a board of any size NxN and provides the number of solutions for small values of N.","id":2923}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar a = [1,2,3],\n    b = [4,5,6],\n    c = a.concat(b); \/\/=> [1,2,3,4,5,6]\n\n\n(function () {\n    'use strict';\n\n    \/\/ concat\u00a0:: [[a]] -> [a]\n    function concat(xs) {\n        return [].concat.apply([], xs);\n    }\n\n\n   return concat(\n      [[\"alpha\", \"beta\", \"gamma\"], \n      [\"delta\", \"epsilon\", \"zeta\"], \n      [\"eta\", \"theta\", \"iota\"]]\n  );\n\n})();\n\n\n","human_summarization":"demonstrate how to concatenate two arrays using the Array.concat() method or a generic function, as per the programming task.","id":2924}
    {"lang_cluster":"JavaScript","source_code":"\n\n\/*global portviz:false, _:false *\/\n\/*\n * 0-1 knapsack solution, recursive, memoized, approximate.\n *\n * credits:\n *\n * the Go implementation here:\n *   http:\/\/rosettacode.org\/mw\/index.php?title=Knapsack_problem\/0-1\n *\n * approximation details here:\n *   http:\/\/math.mit.edu\/~goemans\/18434S06\/knapsack-katherine.pdf\n *\/\nportviz.knapsack = {};\n(function() {\n  this.combiner = function(items, weightfn, valuefn) {\n    \/\/ approximation guarantees result >= (1-e) * optimal\n    var _epsilon = 0.01;\n    var _p = _.max(_.map(items,valuefn));\n    var _k = _epsilon * _p \/ items.length;\n \n    var _memo = (function(){\n      var _mem = {};\n      var _key = function(i, w) {\n        return i + '::' + w;\n      };\n      return {\n        get: function(i, w) {\n          return _mem[_key(i,w)];\n        },\n        put: function(i, w, r) {\n          _mem[_key(i,w)]=r;\n          return r;\n        }\n      };\n    })();\n \n    var _m = function(i, w) {\n \n      i = Math.round(i);\n      w = Math.round(w);\n \n \n      if (i < 0 || w === 0) {\n        \/\/ empty base case\n        return {items: [], totalWeight: 0, totalValue: 0};\n      }\n \n      var mm = _memo.get(i,w);\n      if (!_.isUndefined(mm)) {\n        return mm;\n      }\n \n      var item = items[i];\n      if (weightfn(item) > w) {\n        \/\/item does not fit, try the next item\n        return _memo.put(i, w, _m(i-1, w));\n      }\n      \/\/ this item could fit.\n      \/\/ are we better off excluding it?\n      var excluded = _m(i-1, w);\n      \/\/ or including it?\n      var included = _m(i-1, w - weightfn(item));\n      if (included.totalValue + Math.floor(valuefn(item)\/_k) > excluded.totalValue) {\n        \/\/ better off including it\n        \/\/ make a copy of the list\n        var i1 = included.items.slice();\n        i1.push(item);\n        return _memo.put(i, w,\n          {items: i1,\n           totalWeight: included.totalWeight + weightfn(item),\n           totalValue: included.totalValue + Math.floor(valuefn(item)\/_k)});\n      }\n      \/\/better off excluding it\n      return _memo.put(i,w, excluded);\n    };\n    return {\n      \/* one point *\/\n      one: function(maxweight) {\n        var scaled = _m(items.length - 1, maxweight);\n        return {\n          items: scaled.items,\n          totalWeight: scaled.totalWeight,\n          totalValue: scaled.totalValue * _k\n        };\n      },\n      \/* the entire EF *\/\n      ef: function(maxweight, step) {\n        return _.map(_.range(0, maxweight+1, step), function(weight) {\n          var scaled = _m(items.length - 1, weight);\n          return {\n            items: scaled.items,\n            totalWeight: scaled.totalWeight,\n            totalValue: scaled.totalValue * _k\n          };\n        });\n      }\n    };\n  };\n}).apply(portviz.knapsack);\n\n\/*global portviz:false, _:false *\/\n\/*\n * after rosettacode.org\/mw\/index.php?title=Knapsack_problem\/0-1\n *\/\nvar allwants = [\n  {name:\"map\", weight:9, value: 150},\n  {name:\"compass\", weight:13, value: 35},\n  {name:\"water\", weight:153, value: 200},\n  {name:\"sandwich\", weight: 50, value: 160},\n  {name:\"glucose\", weight:15, value: 60},\n  {name:\"tin\", weight:68, value: 45},\n  {name:\"banana\", weight:27, value: 60},\n  {name:\"apple\", weight:39, value: 40},\n  {name:\"cheese\", weight:23, value: 30},\n  {name:\"beer\", weight:52, value: 10},\n  {name:\"suntan cream\", weight:11, value: 70},\n  {name:\"camera\", weight:32, value: 30},\n  {name:\"T-shirt\", weight:24, value: 15},\n  {name:\"trousers\", weight:48, value: 10},\n  {name:\"umbrella\", weight:73, value: 40},\n  {name:\"waterproof trousers\", weight:42, value: 70},\n  {name:\"waterproof overclothes\", weight:43, value: 75},\n  {name:\"note-case\", weight:22, value: 80},\n  {name:\"sunglasses\", weight:7, value: 20},\n  {name:\"towel\", weight:18, value: 12},\n  {name:\"socks\", weight:4, value: 50},\n  {name:\"book\", weight:30, value: 10}\n];\n \nvar near = function(actual, expected, tolerance) {\n  if (expected === 0 && actual === 0) return true;\n  if (expected === 0) {\n    return Math.abs(expected - actual) \/ actual < tolerance;\n  }\n  return Math.abs(expected - actual) \/ expected < tolerance;\n};\n \ntest(\"one knapsack\", function() {\n  var combiner =\n    portviz.knapsack.combiner(allwants,\n      function(x){return x.weight;},\n      function(x){return x.value;});\n  var oneport = combiner.one(400);\n  ok(near(oneport.totalValue, 1030, 0.01), \"correct total value\");\n  ok(near(oneport.totalValue, 1030, 0.01), \"correct total value\");\n  equal(oneport.totalWeight, 396, \"correct total weight\");\n});\n \ntest(\"frontier\", function() {\n  var combiner =\n    portviz.knapsack.combiner(allwants,\n      function(x){return x.weight;},\n      function(x){return x.value;});\n  var ef = combiner.ef(400, 1);\n  equal(ef.length, 401, \"401 because it includes the endpoints\");\n  ef = combiner.ef(400, 40);\n  equal(ef.length, 11, \"11 because it includes the endpoints\");\n  var expectedTotalValue = [\n    0,\n    330,\n    445,\n    590,\n    685,\n    755,\n    810,\n    860,\n    902,\n    960,\n    1030\n  ] ;\n  _.each(ef, function(element, index) {\n    \/\/ 15% error!  bleah!\n    ok(near(element.totalValue, expectedTotalValue[index], 0.15),\n      'actual ' + element.totalValue + ' expected ' + expectedTotalValue[index]);\n  });\n  deepEqual(_.pluck(ef, 'totalWeight'), [\n    0,\n    39,\n    74,\n    118,\n    158,\n    200,\n    236,\n    266,\n    316,\n    354,\n    396\n  ]);\n  deepEqual(_.map(ef, function(x){return x.items.length;}), [\n    0,\n    4,\n    6,\n    7,\n    9,\n    10,\n    10,\n    12,\n    14,\n    11,\n    12\n   ]);\n});\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), where each item has a specific weight and value. The goal is to maximize the total value without exceeding the weight limit. The items cannot be divided or reduced.","id":2925}
    {"lang_cluster":"JavaScript","source_code":"\nfunction Person(name) {\n\n    var candidateIndex = 0;\n\n    this.name = name;\n    this.fiance = null;\n    this.candidates = [];\n\n    this.rank = function(p) {\n        for (i = 0; i < this.candidates.length; i++)\n            if (this.candidates[i] === p) return i;\n        return this.candidates.length + 1;\n    }\n\n    this.prefers = function(p) {\n        return this.rank(p) < this.rank(this.fiance);\n    }\n\n    this.nextCandidate = function() {\n        if (candidateIndex >= this.candidates.length) return null;\n        return this.candidates[candidateIndex++];\n    }\n\n    this.engageTo = function(p) {\n        if (p.fiance) p.fiance.fiance = null;\n        p.fiance = this;\n        if (this.fiance) this.fiance.fiance = null;\n        this.fiance = p;\n    }\n\n    this.swapWith = function(p) {\n        console.log(\"%s & %s swap partners\", this.name, p.name);\n        var thisFiance = this.fiance;\n        var pFiance = p.fiance;\n        this.engageTo(pFiance);\n        p.engageTo(thisFiance);\n    }\n}\n\nfunction isStable(guys, gals) {\n    for (var i = 0; i < guys.length; i++)\n        for (var j = 0; j < gals.length; j++)\n            if (guys[i].prefers(gals[j]) && gals[j].prefers(guys[i]))\n                return false;\n    return true;\n}\n\nfunction engageEveryone(guys) {\n    var done;\n    do {\n        done = true;\n        for (var i = 0; i < guys.length; i++) {\n            var guy = guys[i];\n            if (!guy.fiance) {\n                done = false;\n                var gal = guy.nextCandidate();\n                if (!gal.fiance || gal.prefers(guy))\n                    guy.engageTo(gal);\n            }\n        }\n    } while (!done);\n}\n\nfunction doMarriage() {\n\n    var abe  = new Person(\"Abe\");\n    var bob  = new Person(\"Bob\");\n    var col  = new Person(\"Col\");\n    var dan  = new Person(\"Dan\");\n    var ed   = new Person(\"Ed\");\n    var fred = new Person(\"Fred\");\n    var gav  = new Person(\"Gav\");\n    var hal  = new Person(\"Hal\");\n    var ian  = new Person(\"Ian\");\n    var jon  = new Person(\"Jon\");\n    var abi  = new Person(\"Abi\");\n    var bea  = new Person(\"Bea\");\n    var cath = new Person(\"Cath\");\n    var dee  = new Person(\"Dee\");\n    var eve  = new Person(\"Eve\");\n    var fay  = new Person(\"Fay\");\n    var gay  = new Person(\"Gay\");\n    var hope = new Person(\"Hope\");\n    var ivy  = new Person(\"Ivy\");\n    var jan  = new Person(\"Jan\");\n\n    abe.candidates  = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay];\n    bob.candidates  = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay];\n    col.candidates  = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan];\n    dan.candidates  = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi];\n    ed.candidates   = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay];\n    fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay];\n    gav.candidates  = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay];\n    hal.candidates  = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee];\n    ian.candidates  = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve];\n    jon.candidates  = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope];\n    abi.candidates  = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal];\n    bea.candidates  = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal];\n    cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon];\n    dee.candidates  = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed];\n    eve.candidates  = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob];\n    fay.candidates  = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal];\n    gay.candidates  = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian];\n    hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred];\n    ivy.candidates  = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan];\n    jan.candidates  = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan];\n\n    var guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon];\n    var gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan];\n\n    engageEveryone(guys);\n\n    for (var i = 0; i < guys.length; i++) {\n        console.log(\"%s is engaged to %s\", guys[i].name, guys[i].fiance.name);\n    }\n    console.log(\"Stable = %s\", isStable(guys, gals) ? \"Yes\" : \"No\");\n    jon.swapWith(fred);\n    console.log(\"Stable = %s\", isStable(guys, gals) ? \"Yes\" : \"No\");\n}\n\ndoMarriage();\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":2926}
    {"lang_cluster":"JavaScript","source_code":"\n\n(function () {\n    'use strict';\n\n    function a(bool) {\n        console.log('a -->', bool);\n\n        return bool;\n    }\n\n    function b(bool) {\n        console.log('b -->', bool);\n\n        return bool;\n    }\n  \n  \n    var x = a(false) && b(true),\n        y = a(true) || b(false),\n        z = true ? a(true) : b(false);\n    \n  return [x, y, z];\n})();\n\n\n\n","human_summarization":"The code defines two functions, 'a' and 'b', both of which accept and return the same boolean value and print their respective names when called. The code then calculates and assigns the values of two equations, using short-circuit evaluation to ensure that function 'b' is only called when necessary. If the programming language does not support short-circuit evaluation, nested 'if' statements are used to achieve the same result. The code demonstrates the concept of short-circuit evaluation in boolean expressions, a feature present in JavaScript since its early versions.","id":2927}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar globalAudioContext = new webkitAudioContext();\n\nfunction morsecode(text, unit, freq) {\n\t'use strict';\n\n\t\/\/ defaults\n\tunit = unit ? unit : 0.05;\n\tfreq = freq ? freq : 700;\n\tvar cont = globalAudioContext;\n\tvar time = cont.currentTime;\n\n\t\/\/ morsecode\n\tvar code = {\n\t\ta: '._',    b: '_...',  c: '_._.',  d: '_..',   e: '.',     f: '.._.',\n\t\tg: '__.',   h: '....',  i: '..',    j: '.___',  k: '_._',   l: '._..',\n\t\tm: '__',    n: '_.',    o: '___',   p: '.__.',  q: '__._',  r: '._.',\n\t\ts: '...',   t: '_',     u: '.._',   v: '..._',  w: '.__',   x: '_.._',\n\t\ty: '_.__',  z: '__..',  0: '_____', 1: '.____', 2: '..___', 3: '...__',\n\t\t4: '...._', 5: '.....', 6: '_....', 7: '__...', 8: '___..', 9: '____.'\n\t};\n\n\t\/\/ generate code for text\n\tfunction makecode(data) {\n\t\tfor (var i = 0; i <= data.length; i ++) {\n\t\t\tvar codedata = data.substr(i, 1).toLowerCase();\n\t\t\tcodedata = code[codedata];\n\t\t\t\/\/ recognised character\n\t\t\tif (codedata !== undefined) {\n\t\t\t\tmaketime(codedata);\n\t\t\t}\n\t\t\t\/\/ unrecognised character\n\t\t\telse {\n\t\t\t\ttime += unit * 7;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ generate time for code\n\tfunction maketime(data) {\n\t\tfor (var i = 0; i <= data.length; i ++) {\n\t\t\tvar timedata = data.substr(i, 1);\n\t\t\ttimedata = (timedata === '.') ? 1 : (timedata === '_') ? 3 : 0;\n\t\t\ttimedata *= unit;\n\t\t\tif (timedata > 0) {\n\t\t\t\tmaketone(timedata);\n\t\t\t\ttime += timedata;\n\t\t\t\t\/\/ tone gap\n\t\t\t\ttime += unit * 1;\n\t\t\t}\n\t\t}\n\t\t\/\/ char gap\n\t\ttime += unit * 2;\n\t}\n\n\t\/\/ generate tone for time\n\tfunction maketone(data) {\n\t\tvar start = time;\n\t\tvar stop = time + data;\n\t\t\/\/ filter: envelope the tone slightly\n\t\tgain.gain.linearRampToValueAtTime(0, start);\n\t\tgain.gain.linearRampToValueAtTime(1, start + (unit \/ 8));\n\t\tgain.gain.linearRampToValueAtTime(1, stop - (unit \/ 16));\n\t\tgain.gain.linearRampToValueAtTime(0, stop);\n\t}\n\n\t\/\/ create: oscillator, gain, destination\n\tvar osci = cont.createOscillator();\n\tosci.frequency.value = freq;\n\tvar gain = cont.createGainNode();\n\tgain.gain.value = 0;\n\tvar dest = cont.destination;\n\t\/\/ connect: oscillator -> gain -> destination\n\tosci.connect(gain);\n\tgain.connect(dest);\n\t\/\/ start oscillator\n\tosci.start(time);\n\n\t\/\/ begin encoding: text -> code -> time -> tone\n\tmakecode(text);\n\n\t\/\/ return web audio context for reuse \/ control\n\treturn cont;\n}\n\n\nmorsecode('Hello World');\n\n\n","human_summarization":"The code translates a given string into Morse code, handles unknown characters, and outputs the Morse code as audible tones through an audio device using the Web Audio API. It is divided into three modules: character to Morse code translation, Morse code timing creation, and tone generation based on the timings.","id":2928}
    {"lang_cluster":"JavaScript","source_code":"\n\nvar blocks = \"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\";\n\nfunction CheckWord(blocks, word) {\n   \/\/ Makes sure that word only contains letters.\n   if(word !== \/([a-z]*)\/i.exec(word)[1]) return false;\n   \/\/ Loops through each character to see if a block exists.\n   for(var i = 0; i < word.length; ++i)\n   {\n      \/\/ Gets the ith character.\n      var letter = word.charAt(i);\n      \/\/ Stores the length of the blocks to determine if a block was removed.\n      var length = blocks.length;\n      \/\/ The regexp gets constructed by eval to allow more browsers to use the function.\n      var reg = eval(\"\/([a-z]\"+letter+\"|\"+letter+\"[a-z])\/i\");\n      \/\/ This does the same as above, but some browsers do not support...\n      \/\/var reg = new RegExp(\"([a-z]\"+letter+\"|\"+letter+\"[a-z])\", \"i\");\n      \/\/ Removes all occurrences of the match. \n      blocks = blocks.replace(reg, \"\");\n      \/\/ If the length did not change then a block did not exist.\n      if(blocks.length === length) return false;\n   }\n   \/\/ If every character has passed then return true.\n   return true;\n};\n\nvar words = [\n   \"A\",\n   \"BARK\", \n   \"BOOK\", \n   \"TREAT\", \n   \"COMMON\", \n   \"SQUAD\", \n   \"CONFUSE\" \n];\n\nfor(var i = 0;i<words.length;++i)\n   console.log(words[i] + \": \" + CheckWord(blocks, words[i]));\n\n\nA: true\nBARK: true\nBOOK: false\nTREAT: true\nCOMMON: false\nSQUAD: true\nCONFUSE: true\n\n(function (strWords) {\n\n    var strBlocks =\n        'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM',\n        blocks = strBlocks.split(' ');\n\n    function abc(lstBlocks, strWord) {\n        var lngChars = strWord.length;\n\n        if (!lngChars) return [];\n\n        var b = lstBlocks[0],\n            c = strWord[0];\n\n        return chain(lstBlocks, function (b) {\n            return (b.indexOf(c.toUpperCase()) !== -1) ? [\n                (b + ' ').concat(\n                    abc(removed(b, lstBlocks), strWord.slice(1)))\n            ] : [];\n        })\n    }\n\n    \/\/ Monadic bind (chain) for lists\n    function chain(xs, f) {\n        return [].concat.apply([], xs.map(f));\n    }\n\n    \/\/ a -> [a] -> [a]\n    function removed(x, xs) {\n        var h = xs.length ? xs[0] : null,\n            t = h ? xs.slice(1) : [];\n\n        return h ? (\n            h === x ? t : [h].concat(removed(x, t))\n        ) : [];\n    }\n\n    function solution(strWord) {\n        var strAttempt = abc(blocks, strWord)[0].split(',')[0];\n\n        \/\/ two chars per block plus one space -> 3\n        return strWord + ((strAttempt.length === strWord.length * 3) ?\n            ' -> ' + strAttempt : ': [no solution]');\n    }\n\n    return strWords.split(' ').map(solution).join('\\n');\n\n})('A bark BooK TReAT COMMON squAD conFUSE');\n\n\n","human_summarization":"The code defines a function that determines if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive. It also includes examples of the function's usage with seven different words. The method utilizes regular expressions and the string replace function for better compatibility with older browsers.","id":2929}
    {"lang_cluster":"JavaScript","source_code":"\nfor (var n = 0; n < 1e14; n++) { \/\/ arbitrary limit that's not too big\n    document.writeln(n.toString(8)); \/\/ not sure what's the best way to output it in JavaScript\n}\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":2930}
    {"lang_cluster":"JavaScript","source_code":"\n\nfunction swap(arr) {\n  var tmp = arr[0];\n  arr[0] = arr[1];\n  arr[1] = tmp;\n}\n\n\nfunction swap(aName, bName) {\n  eval('(function(){ arguments[0] = aName; aName = bName; bName = arguments[0] })()'\n    .replace(\/aName\/g, aName)\n    .replace(\/bName\/g, bName)\n  )\n}\nvar x = 1\nvar y = 2\nswap('x', 'y')\n\n\nfunction swap(a, b) {\n  var tmp = window[a];\n  window[a] = window[b];\n  window[b] = tmp;\n}\nvar x = 1;\nvar y = 2;\nswap('x', 'y');\n\n\nconst arr = [1, 2, 3, 4, 5];\n[arr[0], arr[1]] = [arr[1], arr[0]]\n\n","human_summarization":"implement a generic swap function or operator that can exchange the values of two variables or storage places, regardless of their types. In statically typed languages, the function describes how the language provides genericity. The variables should have a mutually compatible type to avoid type violation. The function also addresses issues in programming language semantics, including difficulties in generic programming and destructive operations. In JavaScript, the function can swap values by wrapping the variables in an object or array. It also provides a metaprogramming solution using code generation and eval. The function can also swap array items using destructing assignment.","id":2931}
    {"lang_cluster":"JavaScript","source_code":"\nfunction isPalindrome(str) {\n  return str === str.split(\"\").reverse().join(\"\");\n}\n\nconsole.log(isPalindrome(\"ingirumimusnocteetconsumimurigni\"));\n\nvar isPal = str => str === str.split(\"\").reverse().join(\"\");\n\n(() => {\n\n    \/\/ isPalindrome\u00a0:: String -> Bool\n    const isPalindrome = s => {\n        const cs = filter(c => ' '\u00a0!== c, s.toLocaleLowerCase());\n        return cs.join('') === reverse(cs).join('');\n    };\n\n\n    \/\/ TEST -----------------------------------------------\n    const main = () =>\n        isPalindrome(\n            'In girum imus nocte et consumimur igni'\n        )\n\n    \/\/ GENERIC FUNCTIONS ----------------------------------\n\n    \/\/ filter\u00a0:: (a -> Bool) -> [a] -> [a]\n    const filter = (f, xs) => (\n        'string'\u00a0!== typeof xs\u00a0? (\n            xs\n        )\u00a0: xs.split('')\n    ).filter(f);\n\n    \/\/ reverse\u00a0:: [a] -> [a]\n    const reverse = xs =>\n        'string'\u00a0!== typeof xs\u00a0? (\n            xs.slice(0).reverse()\n        )\u00a0: xs.split('').reverse().join('');\n\n    \/\/ MAIN ---\n    return main();\n})();\n\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It supports Unicode characters and also detects inexact palindromes by ignoring white-space, punctuation, and case sensitivity. The function may also reverse a string and be used to test other functions.","id":2932}
    {"lang_cluster":"JavaScript","source_code":"\n\nWorks with: JScript\nvar shell = new ActiveXObject(\"WScript.Shell\");\nvar env = shell.Environment(\"PROCESS\");\nWScript.echo('SYSTEMROOT=' + env.item('SYSTEMROOT'));\n\n","human_summarization":"demonstrate how to access a process's environment variables such as PATH, HOME, or USER in a Unix system using JavaScript, relying on the host environment for access.","id":2933}
    {"lang_cluster":"JavaScript","source_code":"\n\/**\n * @param {bigint} n\n * @param {bigint} x\n * @param {bigint} y\n * @returns {bigint}\n *\/\nfunction F(n, x, y) {\n  if (n === 0) {\n    return x + y;\n  }\n\n  if (y === 0) {\n    return x;\n  }\n\n  return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y);\n}\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.","id":2934}
    {"lang_cluster":"Prolog","source_code":"\n\n% push( ELEMENT, STACK, NEW )\n% True if NEW is [ELEMENT|STACK]\npush(ELEMENT,STACK,[ELEMENT|STACK]).\n\n% pop( STACK, TOP, NEW )\n% True if TOP and NEW are head and tail, respectively, of STACK\npop([TOP|STACK],TOP,STACK).\n\n% empty( STACK )\n% True if STACK is empty\nempty([]).\n","human_summarization":"implement a stack with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy. The topmost element can be accessed without modifying the stack. The stack can be used for resource management, implementing local variables in recursive subprograms, and in various algorithms.","id":2935}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog\nWorks with: GNU Prolog\nWorks with: YAP\nfib(1, 1)\u00a0:-\u00a0!.\nfib(0, 0)\u00a0:-\u00a0!.\nfib(N, Value)\u00a0:-\n  A is N - 1, fib(A, A1),\n  B is N - 2, fib(B, B1),\n  Value is A1 + B1.\n\n?- time(fib(0,F)).\n% 2 inferences, 0.000 CPU in 0.000 seconds (88% CPU, 161943 Lips)\nF = 0.\n\n?- time(fib(10,F)).\n% 265 inferences, 0.000 CPU in 0.000 seconds (98% CPU, 1458135 Lips)\nF = 55.\n\n?- time(fib(20,F)).\n% 32,836 inferences, 0.016 CPU in 0.016 seconds (99% CPU, 2086352 Lips)\nF = 6765.\n\n?- time(fib(30,F)).\n% 4,038,805 inferences, 1.122 CPU in 1.139 seconds (98% CPU, 3599899 Lips)\nF = 832040.\n\n?- time(fib(40,F)).\n% 496,740,421 inferences, 138.705 CPU in 140.206 seconds (99% CPU, 3581264 Lips)\nF = 102334155.\n\nWorks with: SWI Prolog\nWorks with: YAP\nWorks with: GNU Prolog\n\n%:- dynamic fib\/2. \u00a0% This is ISO, but GNU doesn't like it.\n:- dynamic(fib\/2). \u00a0% Not ISO, but works in SWI, YAP and GNU unlike the ISO declaration.\nfib(1, 1)\u00a0:-\u00a0!.\nfib(0, 0)\u00a0:-\u00a0!.\nfib(N, Value)\u00a0:-\n  A is N - 1, fib(A, A1),\n  B is N - 2, fib(B, B1),\n  Value is A1 + B1,\n  asserta((fib(N, Value)\u00a0:-\u00a0!)).\n\n?- time(fib(0,F)).\n% 2 inferences, 0.000 CPU in 0.000 seconds (90% CPU, 160591 Lips)\nF = 0.\n\n?- time(fib(10,F)).\n% 37 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 552610 Lips)\nF = 55.\n\n?- time(fib(20,F)).\n% 41 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 541233 Lips)\nF = 6765.\n\n?- time(fib(30,F)).\n% 41 inferences, 0.000 CPU in 0.000 seconds (95% CPU, 722722 Lips)\nF = 832040.\n\n?- time(fib(40,F)).\n% 41 inferences, 0.000 CPU in 0.000 seconds (96% CPU, 543572 Lips)\nF = 102334155.\n\n?- listing(fib).\n:- dynamic fib\/2.\n\nfib(40, 102334155)\u00a0:-\u00a0!.\nfib(39, 63245986)\u00a0:-\u00a0!.\nfib(38, 39088169)\u00a0:-\u00a0!.\nfib(37, 24157817)\u00a0:-\u00a0!.\nfib(36, 14930352)\u00a0:-\u00a0!.\nfib(35, 9227465)\u00a0:-\u00a0!.\nfib(34, 5702887)\u00a0:-\u00a0!.\nfib(33, 3524578)\u00a0:-\u00a0!.\nfib(32, 2178309)\u00a0:-\u00a0!.\nfib(31, 1346269)\u00a0:-\u00a0!.\nfib(30, 832040)\u00a0:-\u00a0!.\nfib(29, 514229)\u00a0:-\u00a0!.\nfib(28, 317811)\u00a0:-\u00a0!.\nfib(27, 196418)\u00a0:-\u00a0!.\nfib(26, 121393)\u00a0:-\u00a0!.\nfib(25, 75025)\u00a0:-\u00a0!.\nfib(24, 46368)\u00a0:-\u00a0!.\nfib(23, 28657)\u00a0:-\u00a0!.\nfib(22, 17711)\u00a0:-\u00a0!.\nfib(21, 10946)\u00a0:-\u00a0!.\nfib(20, 6765)\u00a0:-\u00a0!.\nfib(19, 4181)\u00a0:-\u00a0!.\nfib(18, 2584)\u00a0:-\u00a0!.\nfib(17, 1597)\u00a0:-\u00a0!.\nfib(16, 987)\u00a0:-\u00a0!.\nfib(15, 610)\u00a0:-\u00a0!.\nfib(14, 377)\u00a0:-\u00a0!.\nfib(13, 233)\u00a0:-\u00a0!.\nfib(12, 144)\u00a0:-\u00a0!.\nfib(11, 89)\u00a0:-\u00a0!.\nfib(10, 55)\u00a0:-\u00a0!.\nfib(9, 34)\u00a0:-\u00a0!.\nfib(8, 21)\u00a0:-\u00a0!.\nfib(7, 13)\u00a0:-\u00a0!.\nfib(6, 8)\u00a0:-\u00a0!.\nfib(5, 5)\u00a0:-\u00a0!.\nfib(4, 3)\u00a0:-\u00a0!.\nfib(3, 2)\u00a0:-\u00a0!.\nfib(2, 1)\u00a0:-\u00a0!.\nfib(1, 1)\u00a0:-\u00a0!.\nfib(0, 0)\u00a0:-\u00a0!.\nfib(A, D)\u00a0:-\n\tB is A+ -1,\n\tfib(B, E),\n\tC is A+ -2,\n\tfib(C, F),\n\tD is E+F,\n\tasserta((fib(A, D):-!)).\n\n\n:- use_module(lambda).\nfib(N, FN)\u00a0:-\n\tcont_fib(N, _, FN, \\_^Y^_^U^(U = Y)).\n\ncont_fib(N, FN1, FN, Pred)\u00a0:-\n\t(   N < 2 ->\n\t    call(Pred, 0, 1, FN1, FN)\n\t;\n\t    N1 is N - 1,\n\t    P = \\X^Y^Y^U^(U is X + Y),\n\t    cont_fib(N1, FNA, FNB, P),\n\t    call(Pred, FNA, FNB, FN1, FN)\n\t).\n\nfib([0,1|X])\u00a0:-\n    ffib(0,1,X).\nffib(A,B,X)\u00a0:-\n    freeze(X, (C is A+B, X=[C|Y], ffib(B,C,Y)) ).\n\n?- fib(X), length(A,15), append(A,_,X), writeln(A).\n[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]\ntake( 0, Next, Z-Z, Next).\ntake( N, Next, [A|B]-Z, NZ):- N>0,\u00a0!, next( Next, A, Next1),\n  N1 is N-1,\n  take( N1, Next1, B-Z, NZ).\n\nnext( fib(A,B), A, fib(B,C)):- C is A+B.\n\n%% usage:\u00a0?- take(15, fib(0,1), _X-[], G), writeln(_X).\n%% [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]\n%% G = fib(610, 987)\n\n% Fibonacci sequence generator\nfib(C, [P,S], C, N) \u00a0:- N is P + S.\nfib(C, [P,S], Cv, V)\u00a0:- succ(C, Cn), N is P + S,\u00a0!, fib(Cn, [S,N], Cv, V).\n\nfib(0, 0).\nfib(1, 1).\nfib(C, N)\u00a0:- fib(2, [0,1], C, N).\u00a0% Generate from 3rd sequence on\n\n\u00a0?- time(fib(30,X)).\n% 86 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\nX = 832040 \n\u00a0?- time(fib(40,X)).\n% 116 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\nX = 102334155\n\u00a0?- time(fib(100,X)).\n% 296 inferences, 0.000 CPU in 0.001 seconds (0% CPU, Infinite Lips)\nX = 354224848179261915075 \n\n\n?- time(fib(X,Fib)).\n% 0 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\nX = Fib, Fib = 0\u00a0;\n% 1 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\nX = Fib, Fib = 1\u00a0;\n% 3 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\nX = 2,\nFib = 1\u00a0;\n% 5 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\nX = 3,\nFib = 2\u00a0;\n% 5 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\nX = 4,\nFib = 3\u00a0;\n% 5 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\nX = Fib, Fib = 5\u00a0;\n% 5 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\nX = 6,\nFib = 8\n...etc.\n\n\u00a0?- time(fib(100,354224848179261915075)).\n% 296 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\ntrue .\n\n?- time(fib(X,354224848179261915075)).\n% 394 inferences, 0.000 CPU in 0.000 seconds (?% CPU, Infinite Lips)\nX = 100 .\n% John Devou: 26-Nov-2021\n% Efficient program to calculate n-th Fibonacci number.\n% Works fast for n \u2264 1 000 000 000.\n\nb(0,Bs,Bs).\nb(N,Bs,Res):- N > 0, B is mod(N,2), M is div(N,2), b(M,[B|Bs],Res).\n\nf([],A,_,_,A).\nf([X|Xs],A,B,C,Res):- AA is A^2, BB is B^2, A_ is 2*BB-3*AA-C, B_ is AA+BB,\n    (X =:= 1 -> T is A_+B_, f(Xs,B_,T,-2,Res); f(Xs,A_,B_,2,Res)).\n\nfib(N,F):- b(N,[],Bs), f(Bs,0,1,2,F),\u00a0!.\n\n","human_summarization":"The code generates the nth Fibonacci number using either an iterative or recursive approach. It optionally supports negative numbers by inversely applying the Fibonacci formula. The code also implements a time\/space tradeoff to improve performance for larger values of N by storing interim N\/Value pairs for quicker future use. It also includes a generator function that can generate all Fibonacci numbers in sequence without requiring any bound input variables.","id":2936}
    {"lang_cluster":"Prolog","source_code":"\nevens(D, Es)\u00a0:- findall(E, (member(E, D), E mod 2 =:= 0), Es).\n\n?- evens([1,2,3,4,5,6,7,8,9,10],E).\nE = [2, 4, 6, 8, 10]\n\n?- use_module(library(lambda)).\ntrue.\n\n?- include((\\X^(X mod 2 =:= 0)), [1,2,3,4,5,6,7,8,9], L).\nL = [2,4,6,8].\n\n:- use_module(lambda).\n\n%% filter(Pred, LstIn, LstOut)\n%%\nfilter(_Pre, [], []).\n\nfilter(Pred, [H|T], L)\u00a0:-\n\tfilter(Pred, T, L1),\n\t(   call(Pred,H) -> L = [H|L1]; L = L1).\n\n\u00a0?- filter(\\X^(X mod 2 =:= 0), [1,2,3,4,5,6,7,8,9], L).\nL = [2,4,6,8] .\n","human_summarization":"The code selects specific elements from an array to create a new array in a generic manner. It specifically filters out all even numbers from an array. Optionally, it can also modify the original array instead of creating a new one. The code is compatible with SWI-Prolog and the lambda module by Ulrich Neumerkel.","id":2937}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog version 7\nsubstring_task(Str, N, M, Char, SubStr) :-\n    sub_string(Str, N, M, _, Span),\n    sub_string(Str, N, _, 0, ToEnd),\n    sub_string(Str, 0, _, 1, MinusLast),\n    string_from_substring_to_m(Str, Char, M, FromCharToMth),\n    string_from_substring_to_m(Str, SubStr, M, FromSubToM),\n    maplist( writeln,\n            [ 'from n to m ':Span,\n              'from n to end ': ToEnd,\n              'string minus last char ': MinusLast,\n              'form known char to m ': FromCharToMth,\n              'from known substring to m ': FromSubToM ]).\n\n\nstring_from_substring_to_m(String, Sub, M, FromSubToM) :-\n    sub_string(String, Before, _, _, Sub),\n    sub_string(String, Before, M, _, FromSubToM).\n\n\n?- substring_task(\"abcdefghijk\", 2, 4, \"d\", \"ef\").\nfrom n to m :cdef\nfrom n to end :cdefghijk\nstring minus last char :abcdefghij\nform known char to m :defg\nfrom known substring to m :efgh\ntrue\n\n","human_summarization":"The code extracts substrings from a given string in various ways: starting from a specified character index and of a certain length, starting from a specified character index to the end of the string, excluding the last character of the string, starting from a known character or substring within the string and of a specified length. The code supports any valid Unicode code point and works with logical characters, not 8-bit or 16-bit code units. It is not designed to handle all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":2938}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog\nreverse(\"abcd\", L), string_to_list(S,L).\n\n","human_summarization":"The code takes an input string and reverses its characters. It also ensures the preservation of Unicode combining characters during the reversal process. For instance, \"asdf\" is reversed to \"fdsa\" and \"as\u20dddf\u0305\" is reversed to \"f\u0305ds\u20dda\". The main functionality is encapsulated in the reverse\/2 predicate.","id":2939}
    {"lang_cluster":"Prolog","source_code":"\n\n    rpath([target|reversed_path], distance)   \n\n   - arbitrarily selects a node (Qi) neighboring origin (o), and for that node\n   - if o->Qi is the shortest known path:\n       - update path and distance\n       - traverse Qi\n   - if o->Qi is not the shortest, select the next node.\n\n\n   - We use this list to ensure that we do not loop endlessly.\n   - This path is recorded as the shortest if the distance is indeed shorter than a known path.\n   - Leaf nodes in the traversal tree are processed completely before the origin node processing \n     is completed. \n     - This implies that the first stage in our algorithm involves allocating each node\n       in the traversal tree a path and 'shortest known distance from origin' value.\n     - ...Which is arguably better than assigning an initial 'infinite distance' value.\n\n\n%___________________________________________________________________________\n\n:-dynamic\n\trpath\/2.      % A reversed path\n\nedge(a,b,7).\nedge(a,c,9).\nedge(b,c,10).\nedge(b,d,15).\nedge(c,d,11).\nedge(d,e,6).\nedge(a,f,14).\nedge(c,f,2).\nedge(e,f,9).\n\npath(From,To,Dist) :- edge(To,From,Dist).\npath(From,To,Dist) :- edge(From,To,Dist).\n\nshorterPath([H|Path], Dist) :-\t\t       % path < stored path? replace it\n\trpath([H|T], D), !, Dist < D,          % match target node [H|_]\n\tretract(rpath([H|_],_)),\n\twritef('%w is closer than %w\\n', [[H|Path], [H|T]]),\n\tassert(rpath([H|Path], Dist)).\nshorterPath(Path, Dist) :-\t\t       % Otherwise store a new path\n\twritef('New path:%w\\n', [Path]),\n\tassert(rpath(Path,Dist)).\n\ntraverse(From, Path, Dist) :-\t\t    % traverse all reachable nodes\n\tpath(From, T, D),\t\t    % For each neighbor\n\tnot(memberchk(T, Path)),\t    %\twhich is unvisited\n\tshorterPath([T,From|Path], Dist+D), %\tUpdate shortest path and distance\n\ttraverse(T,[From|Path],Dist+D).\t    %\tThen traverse the neighbor\n\ntraverse(From) :-\n\tretractall(rpath(_,_)),           % Remove solutions\n\ttraverse(From,[],0).              % Traverse from origin\ntraverse(_).\n\ngo(From, To) :-\n\ttraverse(From),                   % Find all distances\n\trpath([To|RPath], Dist)->         % If the target was reached\n\t  reverse([To|RPath], Path),      % Report the path and distance\n\t  Distance is round(Dist),\n\t  writef('Shortest path is %w with distance %w = %w\\n',\n\t       [Path, Dist, Distance]);\n\twritef('There is no route from %w to %w\\n', [From, To]).\n\n\n?- go(a,e).\nNew path:[b,a]\nNew path:[c,b,a]\nNew path:[d,c,b,a]\nNew path:[e,d,c,b,a]\nNew path:[f,e,d,c,b,a]\n[f,c,b,a] is closer than [f,e,d,c,b,a]\n[e,f,c,b,a] is closer than [e,d,c,b,a]\n[d,b,a] is closer than [d,c,b,a]\n[c,a] is closer than [c,b,a]\n[d,c,a] is closer than [d,b,a]\n[e,d,c,a] is closer than [e,f,c,b,a]\n[f,c,a] is closer than [f,c,b,a]\n[e,f,c,a] is closer than [e,d,c,a]\nShortest path is [a,c,f,e] with distance 0+9+2+9 = 20\ntrue.\n","human_summarization":"implement Dijkstra's algorithm for finding the shortest path in a graph with non-negative edge path costs. The algorithm takes a directed and weighted graph, represented by an adjacency matrix or list and a start node, as input. It outputs a set of edges depicting the shortest path to each reachable node from the start node. The code also includes functionality to interpret the output and display the shortest path from the start node to specified nodes.","id":2940}
    {"lang_cluster":"Prolog","source_code":"\nmersenne_factor(P, F) :-\n    prime(P),\n    once((\n        between(1, 100_000, K),  % Fail if we can't find a small factor\n        Q is 2*K*P + 1,\n        test_factor(Q, P, F))).\n\ntest_factor(Q, P, prime) :- Q*Q > (1 << P - 1), !.\ntest_factor(Q, P, Q) :-\n    R is Q \/\\ 7, member(R, [1, 7]),\n    prime(Q),\n    powm(2, P, Q) =:= 1.\n\n\nwheel235(L) :-\n   W = [4, 2, 4, 2, 4, 6, 2, 6 | W],\n   L = [1, 2, 2 | W].\n\nprime(N) :-\n   N >= 2,\n   wheel235(W),\n   prime(N, 2, W).\n\nprime(N, D, _) :- D*D > N, !.\nprime(N, D, [A|As]) :-\n    N mod D =\\= 0,\n    D2 is D + A, prime(N, D2, As).\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":2941}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library(lists)).\n\nset :-\n\tA = [2, 4, 1, 3],\n\tB = [5, 2, 3, 2],\n\t(   is_set(A) -> format('~w is a set~n', [A])\n\t;   format('~w is not a set~n', [A])),\n\t(   is_set(B) -> format('~w is a set~n', [B])\n\t;   format('~w is not a set~n', [B])),\n\n\t% create a set from a list\n\n\tlist_to_set(B, BS),\n\t(   is_set(BS) -> format('~nCreate a set from a list~n~w is a set~n', [BS])\n\t;   format('~w is not a set~n', [BS])),\n\n\tintersection(A, BS, I),\n\tformat('~n~w intersection ~w => ~w~n', [A, BS, I]),\n\tunion(A, BS, U),\n\tformat('~w union ~w => ~w~n', [A, BS, U]),\n\tdifference(A, BS, D),\n\tformat('~w difference ~w => ~w~n', [A, BS, D]),\n\n\tX = [1,2],\n\t(   subset(X, A) -> format('~n~w is a subset of ~w~n', [X, A])\n\t;   format('~w is not a subset of ~w~n', [X, A])),\n\tY = [1,5],\n\t(   subset(Y, A) -> format('~w is a subset of ~w~n', [Y, A])\n\t;   format('~w is not a subset of ~w~n', [Y, A])),\n\tZ = [1, 2, 3, 4],\n\t(  equal(Z, A) -> format('~n~w is equal to ~w~n', [Z, A])\n\t;   format('~w is not equal to ~w~n', [Z, A])),\n\tT = [1, 2, 3],\n\t(  equal(T, A) -> format('~w is equal to ~w~n', [T, A])\n\t;   format('~w is not equal to ~w~n', [T, A])).\n\n\n\n% compute difference of sets\ndifference(A, B, D) :-\n\texclude(member_(B), A, D).\n\nmember_(L, X) :-\n\tmember(X, L).\n\nequal([], []).\nequal([H1 | T1], B) :-\n\tselect(H1, B, B1),\n\tequal(T1, B1).\n\n\n","human_summarization":"The code demonstrates various set operations such as set creation, checking if an element belongs to a set, union, intersection, difference, subset, and equality of two sets. It also optionally shows other set operations and modifications on a mutable set. The set is implemented using an associative array, binary search tree, hash table, or binary bits. The code works with SWI-Prolog's standard library ordsets, which treats sets as ordered lists of unique elements.","id":2942}
    {"lang_cluster":"Prolog","source_code":"\n\nmain()\u00a0:-\n    christmas_days_falling_on_sunday(2011, 2121, SundayList),\n    writeln(SundayList).\n\nchristmas_days_falling_on_sunday(StartYear, EndYear, SundayList)\u00a0:-\n    numlist(StartYear, EndYear, YearRangeList),\n    include(is_christmas_day_a_sunday, YearRangeList, SundayList).\n    \nis_christmas_day_a_sunday(Year)\u00a0:-\n    Date = date(Year, 12, 25),\n    day_of_the_week(Date, DayOfTheWeek),\n    DayOfTheWeek == 7.\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday by using standard date handling libraries. It also compares the calculated dates with the outputs of other languages to identify any discrepancies due to issues like overflow in date\/time representation similar to y2k problems. The code is compatible with SWI-Prolog.","id":2943}
    {"lang_cluster":"Prolog","source_code":"\nuniq(Data,Uniques)\u00a0:- sort(Data,Uniques).\n\n?- uniq([1, 2, 3, 2, 3, 4],Xs).\nXs = [1, 2, 3, 4]\n\nmember1(X,[H|_])\u00a0:- X==H,!.\nmember1(X,[_|T])\u00a0:- member1(X,T).\n\ndistinct([],[]).\ndistinct([H|T],C)\u00a0:- member1(H,T),!, distinct(T,C).\ndistinct([H|T],[H|C])\u00a0:- distinct(T,C).\n\n?- distinct([A, A, 1, 2, 3, 2, 3, 4],Xs).\nXs = [A, 1, 2, 3, 4]\n","human_summarization":"\"Implement a function to remove duplicate elements from an array. This can be achieved through three approaches: 1) Using a hash table to eliminate duplicates with a complexity of O(n) on average and O(n2) in the worst case. 2) Sorting the elements and removing consecutive duplicates with a complexity of O(n log n). 3) Iterating through the list, checking for duplicate elements and discarding them with a complexity of O(n2).\"","id":2944}
    {"lang_cluster":"Prolog","source_code":"\nqsort( [], [] ).\nqsort( [H|U], S )\u00a0:- splitBy(H, U, L, R), qsort(L, SL), qsort(R, SR), append(SL, [H|SR], S).\n\n% splitBy( H, U, LS, RS )\n% True if LS = { L in U | L <= H }; RS = { R in U | R > H }\nsplitBy( _, [], [], []).\nsplitBy( H, [U|T], [U|LS], RS )\u00a0:- U =< H, splitBy(H, T, LS, RS).\nsplitBy( H, [U|T], LS, [U|RS] )\u00a0:- U  > H, splitBy(H, T, LS, RS).\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":2945}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog version 6\ndisplay_date :-\n    get_time(Time),\n    format_time(atom(Short), '%Y-%M-%d',      Time),\n    format_time(atom(Long),  '%A, %B %d, %Y', Time),\n    format('~w~n~w~n', [Short, Long]).\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":2946}
    {"lang_cluster":"Prolog","source_code":"\n\npowerset(X,Y)\u00a0:- bagof( S, subseq(S,X), Y).\n\nsubseq( [], []).\nsubseq( [], [_|_]).\nsubseq( [X|Xs], [X|Ys] )\u00a0:- subseq(Xs, Ys).\nsubseq( [X|Xs], [_|Ys] )\u00a0:- append(_, [X|Zs], Ys), subseq(Xs, Zs).\n\n","human_summarization":"The code implements a function that takes a set S as input and generates the power set of S. It uses either a built-in set type or a custom-defined set type with necessary operations. The power set includes all subsets of the original set, including the empty set and the set itself. The code also demonstrates the handling of edge cases, such as the power set of an empty set and the power set of a set containing only the empty set. It uses the predicate powerset(X,Y) to represent \"Y is the power set of X\" and subseq(X,Y) to check if X is a subsequence of Y. The implementation is efficient and logical.","id":2947}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog\nLibrary: clpfd\n\n:- use_module(library(clpfd)).\n\nroman\u00a0:-\n\tLA =  [    _       , 2010,    _, 1449,         _],\n\tLR =  ['MDCCLXXXIX',  _  , 'CX',    _, 'MDCLXVI'],\n\tmaplist(roman,   LA, LR),\n\tmaplist(my_print,LA, LR).\n\n\nroman(A, R)\u00a0:-\n\tA #> 0,\n\troman(A, [u, t, h, th], LR, []),\n\tlabel([A]),\n\tparse_Roman(CR, LR, []),\n\tatom_chars(R, CR).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% using DCG\n \nroman(0, []) --> [].\n\nroman(N, [H | T]) -->\n\t{N1 #= N \/ 10,\n\t N2 #= N mod 10},\n\troman(N1, T),\n\tunity(N2, H).\n\nunity(1, u) --> ['I'].\nunity(1, t) --> ['X'].\nunity(1, h) --> ['C'].\nunity(1, th)--> ['M'].\n\nunity(4, u) --> ['IV'].\nunity(4, t) --> ['XL'].\nunity(4, h) --> ['CD'].\nunity(4, th)--> ['MMMM'].\n\nunity(5, u) --> ['V'].\nunity(5, t) --> ['L'].\nunity(5, h) --> ['D'].\nunity(5, th)--> ['MMMMM'].\n\nunity(9, u) --> ['IX'].\nunity(9, t) --> ['XC'].\nunity(9, h) --> ['CM'].\nunity(9, th)--> ['MMMMMMMMM'].\n\nunity(0, _) --> [].\n\n\nunity(V, U)-->\n\t{V #> 5,\n\tV1 #= V - 5},\n\tunity(5, U),\n\tunity(V1, U).\n\nunity(V, U) -->\n\t{V #> 1, V #< 4,\n\tV1 #= V-1},\n\tunity(1, U),\n\tunity(V1, U).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Extraction of roman \"lexeme\"\nparse_Roman(['C','M'|T]) -->\n\t['CM'],\n\tparse_Roman(T).\n\nparse_Roman(['C','D'|T]) -->\n\t['CD'],\n\tparse_Roman(T).\n\nparse_Roman(['X','C'| T]) -->\n\t['XC'],\n\tparse_Roman(T).\n\n\nparse_Roman(['X','L'| T]) -->\n\t['XL'],\n\tparse_Roman(T).\n\n\nparse_Roman(['I','X'| T]) -->\n\t['IX'],\n\tparse_Roman(T).\n\n\nparse_Roman(['I','V'| T]) -->\n\t['IV'],\n\tparse_Roman(T).\n\nparse_Roman([H | T]) -->\n\t[H],\n\tparse_Roman(T).\n\n\nparse_Roman([]) -->\n\t[].\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nmy_print(A, R)\u00a0:-\n\tformat('~w in roman is ~w~n', [A, R]).\n\n","human_summarization":"The code defines a function that takes a positive integer as an input and returns its equivalent in Roman numerals. It handles each digit separately, starting from the leftmost digit and ignoring zeroes. It also ensures compatibility with both Roman to Arabic and Arabic to Roman conversions using the clpfd library.","id":2948}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog\n\nsingleassignment:-                   \n    functor(Array,array,100),\u00a0% create a term with 100 free Variables as arguments\n                             \u00a0% index of arguments start at 1\n    arg(1 ,Array,a),         \u00a0% put an a at position 1 \n    arg(12,Array,b),         \u00a0% put an b at position 12\n    arg(1 ,Array,Value1),    \u00a0% get the value at position 1\n    print(Value1),nl,        \u00a0% will print Value1 and therefore a followed by a newline \n    arg(4 ,Array,Value2),    \u00a0% get the value at position 4 which is a free Variable\n    print(Value2),nl.        \u00a0% will print that it is a free Variable followed by a newline\n\ndestructive:-                   \n    functor(Array,array,100),\u00a0% create a term with 100 free Variables as arguments\n                             \u00a0% index of arguments start at 1\n    setarg(1 ,Array,a),      \u00a0% put an a at position 1 \n    setarg(12,Array,b),      \u00a0% put an b at position 12\n    setarg(1, Array,c),      \u00a0% overwrite value at position 1 with c\n    arg(1 ,Array,Value1),    \u00a0% get the value at position 1\n    print(Value1),nl.        \u00a0% will print Value1 and therefore c followed by a newline\n\nlistvariant:-\n    length(List,100),         \u00a0% create a list of length 100\n    nth1(1 ,List,a),          \u00a0% put an a at position 1 , nth1\/3 uses indexing from 1, nth0\/3 from 0\n    nth1(12,List,b),          \u00a0% put an b at position 3\n    append(List,[d],List2),   \u00a0% append an d at the end , List2 has 101 elements\n    length(Add,10),           \u00a0% create a new list of length 10\n    append(List2,Add,List3),  \u00a0% append 10 free variables to List2 , List3 now has 111 elements\n    nth1(1 ,List3,Value),     \u00a0% get the value at position 1\n    print(Value),nl.          \u00a0% will print out a\n","human_summarization":"demonstrate the basic syntax of arrays in the given programming language. The codes create an array, assign a value to it, and retrieve an element from it. The codes also showcase the use of both fixed-length and dynamic arrays, including the process of pushing a value into the array. The codes further illustrate the use of Prolog Terms as array structures, utilizing functor\/3 for array creation and arg\/3 for nondestructive retrieval and setting of elements. Additionally, setarg\/3 is used for destructive setting of an array element, mimicking the common practice in most other programming languages. The codes also demonstrate the use of lists as arrays.","id":2949}
    {"lang_cluster":"Prolog","source_code":"\n\n% main predicate, find and print closest point\ndo_find_closest_points(Points) :-\n\tpoints_closest(Points, points(point(X1,Y1),point(X2,Y2),Dist)),\n\tformat('Point 1\u00a0: (~p, ~p)~n', [X1,Y1]),\n\tformat('Point 1\u00a0: (~p, ~p)~n', [X2,Y2]),\n\tformat('Distance: ~p~n', [Dist]).\n\n% Find the distance between two points\ndistance(point(X1,Y1), point(X2,Y2), points(point(X1,Y1),point(X2,Y2),Dist)) :-\n\tDx is X2 - X1,\n\tDy is Y2 - Y1,\n\tDist is sqrt(Dx * Dx + Dy * Dy).\n\n% find the closest point that relatest to another point\npoint_closest(Points, Point, Closest) :-\n\tselect(Point, Points, Remaining),\n\tmaplist(distance(Point), Remaining, PointList),\n\tfoldl(closest, PointList, 0, Closest).\n\n% find the closest point\/dist pair for all points\npoints_closest(Points, Closest) :-\n\tmaplist(point_closest(Points), Points, ClosestPerPoint),\n\tfoldl(closest, ClosestPerPoint, 0, Closest).\n\n% used by foldl to get the lowest point\/distance combination\nclosest(points(P1,P2,Dist), 0, points(P1,P2,Dist)).\nclosest(points(_,_,Dist), points(P1,P2,Dist2), points(P1,P2,Dist2)) :-\n\tDist2 < Dist.\nclosest(points(P1,P2,Dist), points(_,_,Dist2), points(P1,P2,Dist)) :-\n\tDist =< Dist2.\n\n\ndo_find_closest_points([\n    point(0.654682, 0.925557),\n    point(0.409382, 0.619391),\n    point(0.891663, 0.888594),\n    point(0.716629, 0.996200),\n    point(0.477721, 0.946355),\n    point(0.925092, 0.818220),\n    point(0.624291, 0.142924),\n    point(0.211332, 0.221507),\n    point(0.293786, 0.691701),\n    point(0.839186, 0.728260)\n]).\n\n\n","human_summarization":"The code provides two solutions to the closest pair of points problem in a two-dimensional plane. The first solution uses a brute-force algorithm with a time complexity of O(n^2) to find the two points with the minimum distance between them. The second solution uses a recursive divide and conquer approach with a time complexity of O(n log n) to find the closest pair of points. The points are sorted by their x and y coordinates in ascending order. The code is tested with a list of points in SWI-Prolog.","id":2950}
    {"lang_cluster":"Prolog","source_code":"\n\n% create a list\nL = [a,b,c,d],\n \n% prepend to the list\nL2 = [before_a|L],\n \n% append to the list\nappend(L2, ['Hello'], L3),\n\n% delete from list\nexclude(=(b), L3, L4).\n\nL = [a, b, c, d],\nL2 = [before_a, a, b, c, d],\nL3 = [before_a, a, b, c, d, 'Hello'],\nL4 = [before_a, a, c, d, 'Hello'].\n\n\n% create an empty dict call 'point'\nD1 = point{},\n\n% add a value\t\nD2 = D1.put(x, 20).put(y, 30).put(z, 20),\n\n% update a value\nD3 = D2.put([x=25]),\n\n% remove a value\ndel_dict(z, D3, _, D4),\n\n% access a value randomly\nformat('x = ~w, y = ~w~n', [D4.x, D4.y]).\n\nx = 25, y = 30\nD1 = point{},\nD2 = point{x:20, y:30, z:20},\nD3 = point{x:25, y:30, z:20},\nD4 = point{x:25, y:30}.\n\n","human_summarization":"create a collection and add a few values to it. The code also demonstrates how to use different types of collections in statically-typed languages. It also includes examples of using Dicts in SWI-Prolog, which can be accessed, added, and removed in an immutable way.","id":2951}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library(simplex)).\n\n% tuples (name, Explantion, Value, weights, volume).\nknapsack :-\n\tL =[(\tpanacea, 'Incredible healing properties', 3000,\t0.3,\t0.025),\n\t    (\tichor,   'Vampires blood',                1800,\t0.2,\t0.015),\n\t    (\tgold ,\t 'Shiney shiney',\t          2500,\t2.0,\t0.002)],\n\n\t gen_state(S0),\n\t length(L, N),\n\t numlist(1, N, LN),\n\n\t % to get statistics\n\t time((create_constraint_N(LN, L, S0, S1, [], LVa, [], LW, [], LVo),\n\t       constraint(LW =< 25.0, S1, S2),\n\t       constraint(LVo =< 0.25, S2, S3),\n\t       maximize(LVa, S3, S4)\n\t      )),\n\n\t% we display the results\n\tcompute_lenword(L, 0, Len),\n\tsformat(A0, '~~w~~t~~~w|', [3]),\n\tsformat(A1, '~~w~~t~~~w|', [Len]),\n\tsformat(A2, '~~t~~w~~~w|', [10]),\n\tsformat(A3, '~~t~~2f~~~w|', [10]),\n\tsformat(A4, '~~t~~3f~~~w|', [10]),\n\tsformat(A33, '~~t~~w~~~w|', [10]),\n\tsformat(A44, '~~t~~w~~~w|', [10]),\n\n\tsformat(W0, A0, ['Nb']),\n\tsformat(W1, A1, ['Items']),\n\tsformat(W2, A2, ['Value']),\n\tsformat(W3, A33, ['Weigth']),\n\tsformat(W4, A44, ['Volume']),\n\tformat('~w~w~w~w~w~n', [W0, W1,W2,W3,W4]),\n\n\tprint_results(S4, A0, A1, A2, A3, A4, L, LN, 0, 0, 0).\n\n\ncreate_constraint_N([], [], S, S, LVa, LVa, LW, LW, LVo, LVo).\n\ncreate_constraint_N([HN|TN], [(_, _,Va, W, Vo) | TL], S1, SF, LVa, LVaF, LW, LWF, LVo, LVoF) :-\n\tconstraint(integral(x(HN)), S1, S2),\n\tconstraint([x(HN)] >= 0, S2, S3),\n\tcreate_constraint_N(TN, TL, S3, SF,\n\t\t\t    [Va * x(HN) | LVa], LVaF,\n\t\t\t    [W * x(HN) | LW], LWF,\n\t\t\t    [Vo * x(HN) | LVo], LVoF).\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\ncompute_lenword([], N, N).\ncompute_lenword([(Name, _, _, _, _)|T], N, NF):-\n\tatom_length(Name, L),\n\t(   L > N -> N1 = L; N1 = N),\n\tcompute_lenword(T, N1, NF).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nprint_results(_S, A0, A1, A2, A3, A4, [], [], VaM, WM, VoM) :-\n\tsformat(W0, A0, [' ']),\n\tsformat(W1, A1, [' ']),\n\tsformat(W2, A2, [VaM]),\n\tsformat(W3, A3, [WM]),\n\tsformat(W4, A4, [VoM]),\n\tformat('~w~w~w~w~w~n', [W0, W1,W2,W3,W4]).\n\n\nprint_results(S, A0, A1, A2, A3, A4, [(Name, _, Va, W, Vo)|T], [N|TN], Va1, W1, Vo1) :-\n\tvariable_value(S, x(N), X),\n\t(   X = 0 -> Va1 = Va2, W1 = W2, Vo1 = Vo2\n\t;\n\t    sformat(S0, A0, [X]),\n\t    sformat(S1, A1, [Name]),\n\t    Vatemp is X * Va,\n\t    Wtemp is X * W,\n\t    Votemp is X * Vo,\n\t    sformat(S2, A2, [Vatemp]),\n\t    sformat(S3, A3, [Wtemp]),\n\t    sformat(S4, A4, [Votemp]),\n\t    format('~w~w~w~w~w~n', [S0,S1,S2,S3,S4]),\n\t    Va2 is Va1 + Vatemp,\n\t    W2 is W1 + Wtemp,\n\t    Vo2 is Vo1 + Votemp ),\n\tprint_results(S, A0, A1, A2, A3, A4, T, TN, Va2, W2, Vo2).\n\n\n\u00a0?- knapsack.\n% 145,319 inferences, 0.078 CPU in 0.079 seconds (99% CPU, 1860083 Lips)\nNb Items       Value    Weigth    Volume\n15 ichor       27000      3.00     0.225\n11 gold        27500     22.00     0.022\n               54500     25.00     0.247\ntrue \n","human_summarization":"determine the maximum value of items a traveler can carry in his knapsack, given the weight and volume constraints, and the value, weight, and volume of each item. The solution provides one of the four possible combinations that yield the maximum value.","id":2952}
    {"lang_cluster":"Prolog","source_code":"\nexample\u00a0:- \n  between(1,10,Val), write(Val), Val<10, write(', '), fail.\nexample.\n?- example.\n1, 2, 3, 4, 5, 6, 7, 8, 9, 10\ntrue.\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":2953}
    {"lang_cluster":"Prolog","source_code":"\n:- system:set_prolog_flag(double_quotes,codes) .\n\n:- [library(lists)] .\n\n%!  starts_with(FIRSTz,SECONDz)\n%\n% True if `SECONDz` is the beginning of `FIRSTz` .\n\nstarts_with(FIRSTz,SECONDz)\n:-\nlists:append(SECONDz,_,FIRSTz)\n.\n\n%!  contains(FIRSTz,SECONDz)\n%\n% True once if `SECONDz` is contained within `FIRSTz` at one or more positions .\n\ncontains(FIRSTz,SECONDz)\n:-\ncontains(FIRSTz,SECONDz,_) ,\n!\n.\n\n%!  contains(FIRSTz,SECONDz,NTH1)\n%\n% True if `SECONDz` is contained within `FIRSTz` at position `NTH1` .\n\ncontains(FIRSTz,SECONDz,NTH1)\n:-\nlists:append([PREFIXz,SECONDz,_SUFFIXz_],FIRSTz) ,\nprolog:length(PREFIXz,NTH0) ,\nNTH1 is NTH0 + 1\n.\n\n%!  ends_with(FIRSTz,SECONDz)\n%\n% True if `SECONDz` is the ending of `FIRSTz` .\n\nends_with(FIRSTz,SECONDz)\n:-\nlists:append(_,SECONDz,FIRSTz)\n.\n\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":2954}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library(clpfd)).\n\n% main predicate\nmy_sum(Min, Max, Top, LL):-\n    L = [A,B,C,D,E,F,G],\n    L ins Min..Max,\n    (   Top == 0\n    ->  all_distinct(L)\n    ;    true),\n    R #= A+B,\n    R #= B+C+D,\n    R #= D+E+F,\n    R #= F+G,\n    setof(L, labeling([ff], L), LL).\n\n\nmy_sum_1(Min, Max) :-\n    my_sum(Min, Max, 0, LL),\n    maplist(writeln, LL).\n\nmy_sum_2(Min, Max, Len) :-\n    my_sum(Min, Max, 1, LL),\n    length(LL, Len).\n\n\n\u00a0?- my_sum_1(1,7).\n[3,7,2,1,5,4,6]\n[4,5,3,1,6,2,7]\n[4,7,1,3,2,6,5]\n[5,6,2,3,1,7,4]\n[6,4,1,5,2,3,7]\n[6,4,5,1,2,7,3]\n[7,2,6,1,3,5,4]\n[7,3,2,5,1,4,6]\ntrue.\n\n\u00a0?- my_sum_1(3,9).\n[7,8,3,4,5,6,9]\n[8,7,3,5,4,6,9]\n[9,6,4,5,3,7,8]\n[9,6,5,4,3,8,7]\ntrue.\n\n\u00a0?- my_sum_2(0,9,N).\nN = 2860.\n\n","human_summarization":"The code solves a puzzle where seven variables (a, b, c, d, e, f, g) are replaced with decimal digits ranging from a lower limit (LOW) to an upper limit (HIGH). The goal is to find the values of these variables such that the sum of the variables in each of the four squares is equal. The code provides all unique solutions for ranges 1-7 and 3-9, and the total number of solutions (including non-unique) for the range 0-9.","id":2955}
    {"lang_cluster":"Prolog","source_code":"\nshow :-\n    Data = [100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000, 100_000_000],\n    forall(\n        member(Max, Data),\n        (count_triples(Max, Total, Prim),\n         format(\"upto ~D, there are ~D Pythagorean triples (~D primitive.)~n\", [Max, Total, Prim]))).\n\ndiv(A, B, C) :- C is A div B.\n\ncount_triples(Max, Total, Prims) :-\n    findall(S, (triple(Max, A, B, C), S is A + B + C), Ps),\n    length(Ps, Prims),\n    maplist(div(Max), Ps, Counts), sumlist(Counts, Total).\n\n% - between_by\/4\n\nbetween_by(A, B, N, K) :-\n    C is (B - A) div N,\n    between(0, C, J),\n    K is N*J + A.\n\n% - Pythagorean triple generator\n\ntriple(P, A, B, C) :-\n    Max is floor(sqrt(P\/2)) - 1,\n    between(0, Max, M),\n    Start is (M \/\\ 1) + 1, succ(Pm, M),\n    between_by(Start, Pm, 2, N),\n    gcd(M, N) =:= 1,\n    X is M*M - N*N,\n    Y is 2*M*N,\n    C is M*M + N*N,\n    order2(X, Y, A, B),\n    (A + B + C) =< P.\n\norder2(A, B, A, B) :- A < B, !.\norder2(A, B, B, A).\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":2956}
    {"lang_cluster":"Prolog","source_code":"\n\n?- new(D, window('Prolog Window')), send(D, open).\n\n","human_summarization":"Creates an empty GUI window using SWI-Prolog's graphic interface XPCE, which can respond to close requests.","id":2957}
    {"lang_cluster":"Prolog","source_code":"\n\nfrequency(File) :-\n\tread_file_to_codes(File, Code, []),\n\n\t% we only keep alphabetic codes\n\tinclude(my_code_type, Code, LstCharCode),\n\n\t% we translate char_codes into uppercase atoms.\n\tmaplist(my_upcase, LstCharCode, LstChar),\n\n\t% sort and pack the list\n\tmsort(LstChar, SortLstChar),\n\tpackList(SortLstChar, Freq),\n\tmaplist(my_write, Freq).\n\n\nmy_write([Num, Atom]) :-\n\tswritef(A, '%3r', [Num]),\n\twritef('Number of %w\u00a0:%w\\n', [Atom, A]).\n\n\nmy_code_type(Code) :-\n\tcode_type(Code, alpha).\n\nmy_upcase(CharCode, UpChar) :-\n\tchar_code(Atom, CharCode),\n\tupcase_atom(Atom, UpChar).\n\n:- use_module(library(clpfd)).\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\u00a0?- packList([a,a,a,b,c,c,c,d,d,e], L).\n%  L = [[3,a],[1,b],[3,c],[2,d],[1,e]] .\n%\n%\u00a0?- packList(R,  [[3,a],[1,b],[3,c],[2,d],[1,e]]).\n% R = [a,a,a,b,c,c,c,d,d,e] .\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\npackList([],[]).\n\npackList([X],[[1,X]]) :-\n\t!.\n\npackList([X|Rest],[XRun|Packed]):-\n\trun(X,Rest, XRun,RRest),\n\tpackList(RRest,Packed).\n\nrun(Var,[],[1,Var],[]).\n\nrun(Var,[Var|LRest],[N1, Var],RRest):-\n\tN #> 0,\n\tN1 #= N + 1,\n\trun(Var,LRest,[N, Var],RRest).\n\nrun(Var,[Other|RRest], [1,Var],[Other|RRest]):-\n\tdif(Var,Other).\n\n\n","human_summarization":"The code opens a text file and counts the frequency of each letter, only considering alphabetic codes in uppercase. It uses the packlist\/2 function for run-length encoding. It may also count all characters, including punctuation. The code is compatible with SWI-Prolog.","id":2958}
    {"lang_cluster":"Prolog","source_code":"\n\nfractal :-\n\tnew(D, window('Fractal')),\n\tsend(D, size, size(800, 600)),\n\tdrawTree(D, 400, 500, -90, 9),\n\tsend(D, open).\n\n\ndrawTree(_D, _X, _Y, _Angle, 0).\n\ndrawTree(D, X1, Y1, Angle, Depth) :-\n        X2 is X1 + cos(Angle * pi \/ 180.0) * Depth * 10.0,\n        Y2 is Y1 + sin(Angle * pi \/ 180.0) * Depth * 10.0,\n\tnew(Line, line(X1, Y1, X2, Y2, none)),\n\tsend(D, display, Line),\n\tA1 is Angle - 30,\n\tA2 is Angle + 30,\n\tDe is Depth - 1,\n        drawTree(D, X2, Y2, A1, De),\n        drawTree(D, X2, Y2, A2, De).\n\n","human_summarization":"The code generates and draws a fractal tree using SWI-Prolog's graphic interface, XPCE. It begins by drawing the trunk, then splits the end of the trunk at a certain angle to create two branches. This process is repeated at the end of each branch until a desired level of branching is achieved.","id":2959}
    {"lang_cluster":"Prolog","source_code":"\n\nbrute_force_factors( N , Fs )\u00a0:-\n  integer(N) ,\n  N > 0 ,  \n  setof( F , ( between(1,N,F) , N mod F =:= 0 ) , Fs )\n  .\n\nsmart_factors(N,Fs)\u00a0:-\n  integer(N) ,\n  N > 0 ,\n  setof( F , factor(N,F) , Fs )\n  .\n\nfactor(N,F)\u00a0:-\n  L is floor(sqrt(N)) ,\n  between(1,L,X) ,\n  0 =:= N mod X ,\n  ( F = X\u00a0; F is N \/\/ X )\n  .\n\nbetween(X,Y,Z)\u00a0:-\n  integer(X) ,\n  integer(Y) ,\n  X =< Z ,\n  between1(X,Y,Z)\n  .\n\nbetween1(X,Y,X)\u00a0:-\n  X =< Y\n  .\nbetween1(X,Y,Z)\u00a0:-\n  X < Y ,\n  X1 is X+1 ,\n  between1(X1,Y,Z)\n  .\n\n","human_summarization":"calculate the factors of a positive integer, excluding zero and negative integers. The factors are the positive integers that can divide the given number to yield a positive integer result. For prime numbers, the factors are 1 and the number itself. The code implementation uses a simple brute force method and a slightly smarter method. Some Prolog versions may require between\/3.","id":2960}
    {"lang_cluster":"Prolog","source_code":"\n\naligner :-\n\tL =\"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\",\n\n\t% read the lines and the words\n\t% compute the length of the longuest word.\n\t% LP is the list of lines, \n\t% each line is a list of words\n\tparse(L, 0, N, LP, []),\n\n\t% we need to add 1 to aligned\n\tN1 is N+1,\n\t% words will be left aligned\n\tsformat(AL, '~~w~~t~~~w|', [N1]),\n\t% words will be centered\n\tsformat(AC, '~~t~~w~~t~~~w|', [N1]),\n\t% words will be right aligned\n\tsformat(AR, '~~t~~w~~~w|', [N1]),\n\n\twrite('Left justified\u00a0:'), nl,\n\tmaplist(affiche(AL), LP), nl,\n\twrite('Centered justified\u00a0:'), nl,\n\tmaplist(affiche(AC), LP), nl,\n\twrite('Right justified\u00a0:'), nl,\n\tmaplist(affiche(AR), LP), nl.\n\naffiche(F, L) :-\n\tmaplist(my_format(F), L),\n\tnl.\n\nmy_format(_F, [13]) :-\n\tnl.\n\nmy_format(F, W) :-\n\tstring_to_atom(W,AW),\n\tsformat(AF, F, [AW]),\n\twrite(AF).\n\n\nparse([], Max, Max) --> [].\n\nparse(T, N, Max) -->\n\t{ parse_line(T, 0, N1, T1, L, []),\n\t  (   N1 > N -> N2 = N1; N2 = N)},\n\t[L],\n\tparse(T1, N2, Max).\n\nparse_line([], NF, NF, []) --> [].\n\nparse_line([H|TF], NF, NF, TF) -->\n\t{code_type(H, end_of_line), !},\n\t[].\n\n\nparse_line(T, N, NF, TF) -->\n\t{ parse_word(T, 0, N1, T1, W, []),\n\t  (   N1 > N -> N2 = N1; N2 = N)},\n\t[W],\n\tparse_line(T1, N2, NF, TF).\n\n% 36 is the code of '$'\nparse_word([36|T], N, N, T) -->\n\t{!},\n\t[].\n\nparse_word([H|T], N, N, [H|T]) -->\n\t{code_type(H, end_of_line), !},\n\t[].\n\nparse_word([], N, N, []) --> [].\n\nparse_word([H|T], N1, NF, TF) -->\n\t[H],\n\t{N2 is  N1 + 1},\n\tparse_word(T, N2, NF, TF).\n\n\n","human_summarization":"The code reads a text file where each line's fields are separated by a dollar sign. It aligns each column by ensuring at least one space between words in each column. The words in a column can be left, right, or center justified. The minimum space between columns is calculated from the text, not hard-coded. The code also handles trailing dollar characters and insignificant consecutive spaces at the end of lines. The output is displayed in a mono-spaced font on a plain text editor or terminal.","id":2961}
    {"lang_cluster":"Prolog","source_code":"\n\ncuboid(D1,D2,D3) :-\n\tW is D1 * 50,\n\tH is D2 * 50,\n\tD is D3 * 50,\n\n\tnew(C, window(cuboid)),\n\n\t% compute the size of the window\n\tWidth is W + ceiling(sqrt(H * 48)) + 50,\n\tHeight is H +  ceiling(sqrt(H * 48)) + 50,\n\tsend(C, size, new(_,size(Width,Height))),\n\n\t%compute the top-left corner of the front face of the cuboid\n\tPX is 25,\n\tPY is 25 + ceiling(sqrt(H * 48)),\n\n\t% colors of the faces\n\tnew(C1, colour(@default, 65535, 0, 0)),\n\tnew(C2, colour(@default, 0, 65535, 0)),\n\tnew(C3, colour(@default, 0, 0, 65535)),\n\n\t% the front face\n\tnew(B1, box(W, H)),\n\tsend(B1, fill_pattern, C1),\n\tsend(C, display,B1, point(PX, PY)),\n\n\t% the top face\n\tnew(B2, hpara(point(PX,PY), W, D, C2)),\n\tsend(C, display, B2),\n\n\t% the left face\n\tPX1 is PX + W,\n\tnew(B3, vpara(point(PX1,PY), H, D, C3)),\n\tsend(C, display, B3),\n\n\tsend(C, open).\n\n\n\n:- pce_begin_class(hpara, path, \"drawing of a horizontal parallelogram\").\n\ninitialise(P, Pos, Width, Height, Color) :->\n\tsend(P, send_super, initialise),\n\tsend(P, append, Pos),\n\tH is ceiling(sqrt(Height * 48)),\n\tget(Pos, x, X),\n\tget(Pos, y, Y),\n\tX1 is X + H,\n\tY1 is Y - H,\n\tsend(P, append, point(X1, Y1)),\n\tX2 is X1 + Width,\n\tsend(P, append, point(X2, Y1)),\n\tX3 is X2 - H,\n\tsend(P, append, point(X3, Pos?y)),\n\tsend(P, append, Pos),\n\tsend(P, fill_pattern, Color).\n\n:- pce_end_class.\n\n:- pce_begin_class(vpara, path, \"drawing of a vertical parallelogram\").\n\ninitialise(P, Pos, Height, Depth, Color) :->\n\tsend(P, send_super, initialise),\n\tsend(P, append, Pos),\n\tH is ceiling(sqrt(Depth * 48)),\n\tget(Pos, x, X),\n\tget(Pos, y, Y),\n\tX1 is X + H,\n\tY1 is Y - H,\n\tsend(P, append, point(X1, Y1)),\n\tY2 is Y1 + Height,\n\tsend(P, append, point(X1, Y2)),\n\tY3 is Y2 + H,\n\tsend(P, append, point(X, Y3)),\n\tsend(P, append, Pos),\n\tsend(P, fill_pattern, Color).\n\n:- pce_end_class.\n\n\n","human_summarization":"The code generates a 2x3x4 cuboid, either graphically or in ASCII art, depending on the language capabilities. It ensures three faces are visible to meet the cuboid criteria, and supports both static and rotational projection. The code is compatible with SWI-Prolog and XPCE.","id":2962}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library(ctypes)).\n\nruntime_entry(start)\u00a0:-\n\tprompt(_, ''),\n\trot13.\n\nrot13\u00a0:-\n\tget0(Ch),\n\t(   is_endfile(Ch) ->\n\t\ttrue\n\t;   rot13_char(Ch, Rot),\n\t    put(Rot),\n\t    rot13\n\t).\n\nrot13_char(Ch, Rot)\u00a0:-\n\t(   is_alpha(Ch) ->\n\t\tto_upper(Ch, Up),\n\t\tLetter is Up - 0'A,\n\t\tRot is Ch + ((Letter + 13) mod 26) - Letter\n\t;   Rot = Ch\n\t).\n\nrot13(Str, SR)\u00a0:-\n\tmaplist(rot, Str, Str1),\n\tstring_to_list(SR, Str1).\n\nrot(C, C1)\u00a0:-\n\t(   member(C, \"abcdefghijklmABCDEFGHIJKLM\") -> C1 is C+13;\n\t    (\tmember(C, \"nopqrstuvwxyzNOPQRSTUVWXYZ\") -> C1 is C-13; C1 = C)).\n\n\u00a0?- rot13(\"The Quick Brown Fox Jumped Over The Lazy Dog!\", SR).\nSR = \"Gur Dhvpx Oebja Sbk Whzcrq Bire Gur Ynml Qbt!\".\n","human_summarization":"The code implements a ROT-13 function that replaces each letter of the ASCII alphabet with the letter 13 characters away in the 26 letter alphabet, preserving case and passing non-alphabetic characters without alteration. This function can be optionally wrapped in a utility program similar to UNIX utility, performing line-by-line ROT-13 encoding of input from each file listed on its command line or acting as a filter on its standard input. The function is compatible with Quintus Prolog and SWI-Prolog.","id":2963}
    {"lang_cluster":"Prolog","source_code":"\n\nexample\u00a0:- \n    between(1,5,I), nl, between(1,I,_J),\n    write('*'), fail.\nexample.\n?- example.\n\n*\n**\n***\n****\n*****\ntrue.\n","human_summarization":"demonstrate how to use nested 'for' loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop. The pattern printed consists of an increasing number of asterisks on each line. In Prolog, the 'between' function is used as an equivalent to a 'for' loop.","id":2964}
    {"lang_cluster":"Prolog","source_code":"\n\nmymap(key1,value1).\nmymap(key2,value2).\n\n?- mymap(key1,V).\n   V = value1\n","human_summarization":"\"Create an associative array, dictionary, map, or hash using a facts table.\"","id":2965}
    {"lang_cluster":"Prolog","source_code":"\nhalve(X,Y) :- Y is X \/\/ 2.\ndouble(X,Y) :- Y is 2*X.\nis_even(X) :- 0 is X mod 2.\n\n% columns(First,Second,Left,Right) is true if integers First and Second\n% expand into the columns Left and Right, respectively\ncolumns(1,Second,[1],[Second]).\ncolumns(First,Second,[First|Left],[Second|Right]) :-\n    halve(First,Halved),\n    double(Second,Doubled),\n    columns(Halved,Doubled,Left,Right).\n\n% contribution(Left,Right,Amount) is true if integers Left and Right,\n% from their respective columns contribute Amount to the final sum.\ncontribution(Left,_Right,0) :-\n    is_even(Left).\ncontribution(Left,Right,Right) :-\n    \\+ is_even(Left).\n\nethiopian(First,Second,Product) :-\n    columns(First,Second,Left,Right),\n    maplist(contribution,Left,Right,Contributions),\n    sumlist(Contributions,Product).\n\n\n\n:- use_module(library(func)).\n\n% halve\/2, double\/2, is_even\/2 definitions go here\n\nethiopian(First,Second,Product) :-\n    ethiopian(First,Second,0,Product).\n\nethiopian(1,Second,Sum0,Sum) :-\n    Sum is Sum0 + Second.\nethiopian(First,Second,Sum0,Sum) :-\n    Sum1 is Sum0 + Second*(First mod 2),\n    ethiopian(halve $ First, double $ Second, Sum1, Sum).\n\n\n\n:- module(ethiopia, [test\/0, mul\/3]).\n\n:- use_module(library(chr)).\n\n:- chr_constraint mul\/3, halve\/2, double\/2, even\/1, add_odd\/4.\n\nmul(1, Y, S) <=>          S = Y.\nmul(X, Y, S) <=> X \\= 1 | halve(X, X1),\n                          double(Y, Y1),\n                          mul(X1, Y1, S1),\n                          add_odd(X, Y, S1, S).\n\nhalve(X, Y) <=> Y is X \/\/ 2.\n\ndouble(X, Y) <=> Y is X * 2.\n\neven(X) <=> 0 is X mod 2 | true.\neven(X) <=> 1 is X mod 2 | false.\n\nadd_odd(X, _, A, S) <=> even(X)    | S is A.\nadd_odd(X, Y, A, S) <=> \\+ even(X) | S is A + Y.\n\ntest :-\n    mul(17, 34, Z), !,\n    writeln(Z).\nNote that the task statement is what makes the halve and double constraints required.  Their use is highly artificial and a more realistic implementation would look like this:\n:- module(ethiopia, [test\/0, mul\/3]).\n\n:- use_module(library(chr)).\n\n:- chr_constraint mul\/3, even\/1, add_if_odd\/4.\n\nmul(1, Y, S) <=>          S = Y.\nmul(X, Y, S) <=> X \\= 1 | X1 is X \/\/ 2,\n                          Y1 is Y * 2,\n                          mul(X1, Y1, S1),\n                          add_if_odd(X, Y, S1, S).\n\neven(X) <=> 0 is X mod 2 | true.\neven(X) <=> 1 is X mod 2 | false.\n\nadd_if_odd(X, _, A, S) <=> even(X)    | S is A.\nadd_if_odd(X, Y, A, S) <=> \\+ even(X) | S is A + Y.\n\ntest :-\n    mul(17, 34, Z),\n    writeln(Z).\nEven this is more verbose than what a more native solution would look like.\n","human_summarization":"The code defines three functions to halve an integer, double an integer, and check if an integer is even. These functions are then used to implement the Ethiopian multiplication method, which multiplies two integers using only addition, doubling, and halving operations. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column. The solution is implemented in Prolog language.","id":2966}
    {"lang_cluster":"Prolog","source_code":"\n\nplay24(Len, Range, Goal) :-\n\tgame(Len, Range, Goal, L, S),\n\tmaplist(my_write, L),\n\tformat(': ~w~n', [S]).\n\ngame(Len, Range, Value, L, S) :-\n\tlength(L, Len),\n\tmaplist(choose(Range), L),\n\tcompute(L, Value, [], S).\n\n\nchoose(Range, V) :-\n\tV is random(Range) + 1.\n\n\nwrite_tree([M], [M]).\n\nwrite_tree([+, M, N], S) :-\n\twrite_tree(M, MS),\n\twrite_tree(N, NS),\n\tappend(MS, [+ | NS], S).\n\nwrite_tree([-, M, N], S) :-\n\twrite_tree(M, MS),\n\twrite_tree(N, NS),\n\t(   is_add(N) -> append(MS, [-, '(' | NS], Temp), append(Temp, ')', S)\n\t;   append(MS, [- | NS], S)).\n\n\nwrite_tree([Op, M, N], S) :-\n\tmember(Op, [*, \/]),\n\twrite_tree(M, MS),\n\twrite_tree(N, NS),\n\t(   is_add(M) -> append(['(' | MS], [')'], TempM)\n\t;  TempM = MS),\n\t(   is_add(N) -> append(['(' | NS], [')'], TempN)\n\t;   TempN = NS),\n\tappend(TempM, [Op | TempN], S).\n\nis_add([Op, _, _]) :-\n\tmember(Op, [+, -]).\n\ncompute([Value], Value, [[_R-S1]], S) :-\n\twrite_tree(S1, S2),\n\twith_output_to(atom(S), maplist(write, S2)).\n\ncompute(L, Value, CS, S) :-\n\tselect(M, L, L1),\n\tselect(N, L1, L2),\n\tnext_value(M, N, R, CS, Expr),\n\tcompute([R|L2], Value, Expr, S).\n\nnext_value(M, N, R, CS,[[R - [+, M1, N1]] | CS2]) :-\n\tR is M+N,\n\t(   member([M-ExprM], CS) -> select([M-ExprM], CS, CS1), M1 = ExprM\n\t;   M1 = [M], CS1 = CS\n\t),\n\t(   member([N-ExprN], CS1) -> select([N-ExprN], CS1, CS2), N1 = ExprN\n\t;   N1 = [N], CS2 = CS1\n\t).\n\nnext_value(M, N, R, CS,[[R - [-, M1, N1]] | CS2]) :-\n\tR is M-N,\n\t(   member([M-ExprM], CS) -> select([M-ExprM], CS, CS1), M1 = ExprM\n\t;   M1 = [M], CS1 = CS\n\t),\n\t(   member([N-ExprN], CS1) -> select([N-ExprN], CS1, CS2), N1 = ExprN\n\t;   N1 = [N], CS2 = CS1\n\t).\n\nnext_value(M, N, R, CS,[[R - [*, M1, N1]] | CS2]) :-\n\tR is M*N,\n\t(   member([M-ExprM], CS) -> select([M-ExprM], CS, CS1), M1 = ExprM\n\t;   M1 = [M], CS1 = CS\n\t),\n\t(   member([N-ExprN], CS1) -> select([N-ExprN], CS1, CS2), N1 = ExprN\n\t;   N1 = [N], CS2 = CS1\n\t).\n\nnext_value(M, N, R, CS,[[R - [\/, M1, N1]] | CS2]) :-\n\tN \\= 0,\n\tR is rdiv(M,N),\n\t(   member([M-ExprM], CS) -> select([M-ExprM], CS, CS1), M1 = ExprM\n\t;   M1 = [M], CS1 = CS\n\t),\n\t(   member([N-ExprN], CS1) -> select([N-ExprN], CS1, CS2), N1 = ExprN\n\t;   N1 = [N], CS2 = CS1\n\t).\n\nmy_write(V) :-\n\tformat('~w ', [V]).\n\n\n","human_summarization":"The code takes four digits as input, either from the user or randomly generated, and calculates arithmetic expressions according to the rules of the 24 game. It can also work with different goals and number ranges, not just 24 and 1-9. It uses rdiv\/2 instead of \/\/2 to solve complex cases and makes efforts to remove duplicates. Examples of solutions are also provided. Compatible with SWI-Prolog.","id":2967}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog\nfact(X, 1)\u00a0:- X<2.\nfact(X, F)\u00a0:- Y is X-1, fact(Y,Z), F is Z*X.\nfact(N, NF)\u00a0:-\n\tfact(1, N, 1, NF).\n\nfact(X, X, F, F)\u00a0:-\u00a0!.\nfact(X, N, FX, F)\u00a0:-\n\tX1 is X + 1,\n\tFX1 is FX * X1,\n\tfact(X1, N, FX1, F).\n\n% foldl(Pred, Init, List, R).\n%\nfoldl(_Pred, Val, [], Val).\nfoldl(Pred, Val, [H | T], Res)\u00a0:-\n\tcall(Pred, Val, H, Val1),\n\tfoldl(Pred, Val1, T, Res).\n\n% factorial\np(X, Y, Z)\u00a0:- Z is X * Y).\n\nfact(X, F)\u00a0:-\n\tnumlist(2, X, L),\n\tfoldl(p, 1, L, F).\n\n:- use_module(lambda).\n\n% foldl(Pred, Init, List, R).\n%\nfoldl(_Pred, Val, [], Val).\nfoldl(Pred, Val, [H | T], Res)\u00a0:-\n\tcall(Pred, Val, H, Val1),\n\tfoldl(Pred, Val1, T, Res).\n\nfact(N, F)\u00a0:-\n\tnumlist(2, N, L),\n\tfoldl(\\X^Y^Z^(Z is X * Y), 1, L, F).\n\n:- use_module(lambda).\n\nfact(N, FN)\u00a0:-\n\tcont_fact(N, FN, \\X^Y^(Y = X)).\n\ncont_fact(N, F, Pred)\u00a0:-\n\t(   N = 0 ->\n\t    call(Pred, 1, F)\n\t;   N1 is N - 1,\n\n\t    P =  \\Z^T^(T is Z * N),\n\t    cont_fact(N1, FT, P),\n\t    call(Pred, FT, F)\n\t).\n","human_summarization":"The code is a function that calculates the factorial of a given number. It can be implemented iteratively or recursively. It optionally includes error handling for negative inputs. The function utilizes the Factorial Function, which multiplies a sequence of descending integers from the input number to one. The code also has a relation to Primorial numbers and uses the foldl simulation with anonymous functions from the lambda module by Ulrich Neumerkel.","id":2968}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library(lambda)).\n:- use_module(library(clpfd)).\n\n% Parameters of the server\n\n% length of the guess\nproposition(4).\n\n% Numbers of digits\n% 0 -> 8\ndigits(8).\n\n\nbulls_and_cows_server :-\n\tproposition(LenGuess),\n\tlength(Solution, LenGuess),\n\tchoose(Solution),\n\trepeat,\n\twrite('Your guess\u00a0: '),\n\tread(Guess),\n\t(   study(Solution, Guess, Bulls, Cows)\n\t->  format('Bulls\u00a0: ~w Cows\u00a0: ~w~n', [Bulls, Cows]),\n\t    Bulls = LenGuess\n\t;   digits(Digits), Max is Digits + 1,\n\t    format('Guess must be of ~w digits between 1 and ~w~n',\n\t\t   [LenGuess, Max]),\n\t    fail).\n\nchoose(Solution) :-\n\tdigits(Digits),\n\tMax is Digits + 1,\n\trepeat,\n\tmaplist(\\X^(X is random(Max) + 1), Solution),\n\tall_distinct(Solution),\n\t!.\n\nstudy(Solution, Guess, Bulls, Cows) :-\n\tproposition(LenGuess),\n\tdigits(Digits),\n\t\n\t% compute the transformation 1234 => [1,2,3,4]\n\tatom_chars(Guess, Chars),\n\tmaplist(\\X^Y^(atom_number(X, Y)), Chars, Ms),\n\t\n\t% check that the guess is well formed\n\tlength(Ms, LenGuess),\n\tmaplist(\\X^(X > 0, X =< Digits+1), Ms),\n\n\t% compute the digit in good place\n\tfoldl(\\X^Y^V0^V1^((X = Y->V1 is V0+1; V1 = V0)),Solution, Ms, 0, Bulls),\n\t\n\t% compute the digits in bad place\n\tfoldl(\\Y1^V2^V3^(foldl(\\X2^Z2^Z3^(X2 = Y1 -> Z3 is Z2+1; Z3 = Z2), Ms, 0, TT1),\n\t\t\t V3 is V2+ TT1),\n\t      Solution, 0, TT),\n\tCows is TT - Bulls.\n\n","human_summarization":"The code generates a four-digit random number from 1 to 9 without duplication. It prompts the user for guesses, rejects malformed guesses, and prints the score for each guess. The score is calculated based on the number of 'bulls' and 'cows' in the guess, where a 'bull' is a digit that matches the corresponding digit in the random number and a 'cow' is a digit that exists in the random number but in a different position. The game ends when the guess matches the random number. The code is compatible with SWI-Prolog 6.1.8 and uses the lambda and clpfd modules.","id":2969}
    {"lang_cluster":"Prolog","source_code":"\n\ndot_product(L1, L2, N) :-\n\tmaplist(mult, L1, L2, P),\n\tsumlist(P, N).\n\nmult(A,B,C) :-\n\tC is A*B.\n\n\n\u00a0?- dot_product([1,3,-5], [4,-2,-1], N).\nN = 3.\n","human_summarization":"\"Implements a function to compute the dot product of two vectors of the same length by multiplying corresponding terms and summing the products.\"","id":2970}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: GNU Prolog\ndate_time(H).\n\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. It may also relate to the task of date formatting and retrieving system time.","id":2971}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog version 6\n\nnth(N, N_Th) :-\n    ( tween(N)      -> Th = \"th\"\n    ; 1 is N mod 10 -> Th = \"st\"\n    ; 2 is N mod 10 -> Th = \"nd\"\n    ; 3 is N mod 10 -> Th = \"rd\"\n    ; Th = \"th\" ),\n    string_concat(N, Th, N_Th).\n\ntween(N) :- Tween is N mod 100, between(11, 13, Tween).\n\ntest :-\n    forall( between(0,25, N),     (nth(N, N_Th), format('~w, ', N_Th)) ),\n    nl, nl,\n    forall( between(250,265,N),   (nth(N, N_Th), format('~w, ', N_Th)) ),\n    nl, nl,\n    forall( between(1000,1025,N), (nth(N, N_Th), format('~w, ', N_Th)) ).\n\n\n","human_summarization":"The code is a function that takes a non-negative integer as input and returns a string representation of the number followed by its ordinal suffix. It also demonstrates the output for the ranges 0-25, 250-265, and 1000-1025. The use of apostrophes in the output is optional.","id":2972}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library(lambda)).\n\nstripchars(String, Exclude, Result) :-\n\texclude(\\X^(member(X, Exclude)), String, Result1),\n\tstring_to_list(Result, Result1).\n\n\n","human_summarization":"The code defines a function that removes a specified set of characters from a given string. The function takes two arguments: the original string and a string of characters to be removed. The function then returns the original string, stripped of any characters present in the second string. This code is compatible with SWI-Prolog and the lambda.pl module by Ulrich Neumerkel.","id":2973}
    {"lang_cluster":"Prolog","source_code":"\n\nmaxNumber(105).  \nfactors([(3, \"Fizz\"), (5, \"Buzz\"), (7, \"Baxx\")]).\n\n\ngo :- maxNumber(M), factors(Fs), MLast is M+1, loop(1,MLast,Fs).\n\nloop(B,B,_).\nloop(A,B,Fs) :- \n    A < B, fizzbuzz(A,Fs,S), ( (S = \"\", Res is A) ; Res = S ), writeln(Res), \n    Next is A+1, loop(Next,B,Fs).\n\nfizzbuzz(_,[],\"\").\nfizzbuzz(N,[(F,S)|Fs],Res) :-\n    fizzbuzz(N,Fs,OldRes),\n    ( N mod F =:= 0, string_concat(S,OldRes,Res) ; Res = OldRes ).\n\n\n?- go.\n\n\nfactors([(3, \"Fizz\"), (5, \"Buzz\")]).\n\n\n","human_summarization":"The code is a generalized implementation of the FizzBuzz program. It accepts a maximum number and a list of factors with corresponding words from the user. It then prints numbers from 1 to the maximum number, replacing multiples of the factors with their corresponding words. If a number is a multiple of multiple factors, it prints all corresponding words in the order of least to greatest factor. The code can handle an arbitrary number of factors.","id":2974}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog\n\n:- op(200, xfx, user:(=+)).\n\n%% +Prepend =+ +Chars\n%\n%    Will destructively update Chars\n%    So that Chars = Prepend prefixed to Chars.\n%    eazar001 in ##prolog helped refine this approach.\n\n[X|Xs] =+ Chars :-\n  append(Xs, Chars, Rest),\n  nb_setarg(2, Chars, Rest),\n  nb_setarg(1, Chars, X).\n\n\n?- Str = `World!`, `Hello, ` =+ Str.\nStr = \"Hello, World!\".\n\n\n","human_summarization":"create a string variable and prepend it with another string literal. The code also includes idiomatic ways to perform this operation without referring to the variable twice. It also demonstrates the content of the variable. In Prolog, it uses the traditional representation of strings as lists of character codes and the non-logical predicate `setarg\/3` to destructively set the head and tail of the list, effectively mutating the variable holding the string.","id":2975}
    {"lang_cluster":"Prolog","source_code":"\n\ndragonCurve(N) :-\n\tdcg_dg(N, [left], DCL, []),\n\tSide = 4,\n\tAngle is -N * (pi\/4),\n\tdcg_computePath(Side, Angle, DCL, point(180,400), P, []),\n\tnew(D, window('Dragon Curve')),\n\tsend(D, size, size(800,600)),\n\tnew(Path, path(poly)),\n\tsend_list(Path, append, P),\n\tsend(D, display, Path),\n\tsend(D, open).\n\n\n% compute the list of points of the Dragon Curve\ndcg_computePath(Side, Angle, [left | DCT], point(X1, Y1)) -->\n\t   [point(X1, Y1)],\n\t   {\tX2 is X1 + Side * cos(Angle),\n\t\tY2 is Y1 + Side * sin(Angle),\n\t\tAngle1 is Angle + pi \/ 2\n\t   },\n\t   dcg_computePath(Side, Angle1, DCT, point(X2, Y2)).\n\ndcg_computePath(Side, Angle, [right | DCT], point(X1, Y1)) -->\n\t   [point(X1, Y1)],\n\t   {\tX2 is X1 + Side * cos(Angle),\n\t\tY2 is Y1 + Side * sin(Angle),\n\t\tAngle1 is Angle - pi \/ 2\n\t   },\n\t   dcg_computePath(Side, Angle1, DCT, point(X2, Y2)).\n\n\ndcg_computePath(_Side, _Angle, [], point(X1, Y1)) -->\n\t[ point(X1, Y1)].\n\n\n% compute the list of the \"turns\" of the Dragon Curve\ndcg_dg(1, L) --> L.\n\ndcg_dg(N, L) -->\n\t{dcg_dg(L, L1, []),\n\t  N1 is N - 1},\n\t  dcg_dg(N1, L1).\n\n% one interation of the process\ndcg_dg(L) -->\n\tL,\n\t[left],\n\tinverse(L).\n\ninverse([H | T]) -->\n\tinverse(T),\n\tinverse(H).\n\ninverse([]) --> [].\n\ninverse(left) -->\n\t[right].\n\ninverse(right) -->\n\t[left].\n\n\n1\u00a0?- dragonCurve(13).\ntrue \n","human_summarization":"The code generates a Dragon Curve fractal either for direct display or to be written to an image file. It uses recursive, successive approximation, iterative, and Lindenmayer system methods to create the fractal. The code also includes functionality to calculate absolute direction and X,Y coordinates of a point, and to test whether a given point or segment is on the curve. It is compatible with SWI-Prolog and uses DCG to compute the list of turns and points in the Dragon Curve.","id":2976}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog version 6\nmain :-\n    random_between(1, 10, N),\n    repeat,\n    prompt1('Guess the number: '),\n    read(N),\n    writeln('Well guessed!'),\n    !.\n\n\n?- main.\nGuess the number: 1.\nGuess the number: 2.\nGuess the number: 3.\nWell guessed!\ntrue.\n\n","human_summarization":"The code prompts the user to guess a number between 1 and 10. If the guess is incorrect, the user is prompted to guess again. The program continues to prompt the user until the correct number is guessed, at which point it displays a \"Well guessed!\" message and exits. A conditional loop is used to facilitate repeated guessing.","id":2977}
    {"lang_cluster":"Prolog","source_code":"\n\na_to_z(From, To, L)\u00a0:-\n\tmaplist(atom_codes, [From, To], [[C_From], [C_To]]),\n\tbagof([C], between(C_From, C_To, C), L1),\n\tmaplist(atom_codes,L, L1).\n\n\u00a0?- a_to_z(a, z, L).\nL = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z].\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from 'a' to 'z'. The sequence can be an array, list, lazy sequence, or indexable string. The code is written in a reliable style suitable for large programs and uses strong typing if available to avoid bugs. The code also demonstrates how to access a similar sequence from the standard library if it exists.","id":2978}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog\nWorks with: GNU Prolog\nbinary(X)\u00a0:- format('~2r~n', [X]).\nmain\u00a0:- maplist(binary, [5,50,9000]), halt.\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":2979}
    {"lang_cluster":"Prolog","source_code":"\n\npatient(1001,'Hopper').\npatient(4004,'Wirth').\npatient(3003,'Kemeny').\npatient(2002,'Gosling').\npatient(5005,'Kurtz').\n \nvisit(2002,'2020-09-10',6.8).\nvisit(1001,'2020-09-17',5.5).\nvisit(4004,'2020-09-24',8.4).\nvisit(2002,'2020-10-08',nan).\nvisit(1001,'',6.6).\nvisit(3003,'2020-11-12',nan).\nvisit(4004,'2020-11-05',7.0).\nvisit(1001,'2020-11-19',5.3).\n\nsummaryDates(Id, Lastname, LastDate) :- \n     aggregate(max(Ts),\n\t       Score^Date^(visit(Id, Date, Score), Date \\= '', parse_time(Date, iso_8601, Ts)),\n\t       MaxTs),\n     format_time(atom(LastDate), '%Y-%m-%d', MaxTs),\n     patient(Id,Lastname).\n\nsummaryScores(Id, Lastname, Sum, Mean) :- \n     aggregate(r(sum(Score),count), Date^(visit(Id, Date, Score), Score \\= nan), r(Sum,Count)), \n     patient(Id,Lastname),\n     Mean is Sum\/Count.\n\ntest :-\n    summaryDates(Id, Lastname, LastDate),\n    writeln(summaryDates(Id, Lastname, LastDate)),\n    fail.\n\ntest :-\n    summaryScores(Id, Lastname, ScoreSum, ScoreMean),\n    writeln(summaryScores(Id, Lastname, ScoreSum, ScoreMean)),\n    fail.\n\n\n","human_summarization":"The code merges and aggregates two datasets from .csv files into a new dataset. It loads data from 'patients.csv' and 'visits.csv', merges them based on patient id and last name, and calculates the maximum visit date, sum, and average of scores per patient. The resulting dataset is displayed on the screen or saved to a file. The code is particularly suitable for data science and data processing languages like F#, Python, R, SPSS, MATLAB etc.","id":2980}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library( http\/http_open )).\n\nhttp :-\n\thttp_open('http:\/\/www.rosettacode.org\/',In, []),\n\tcopy_stream_data(In, user_output),\n\tclose(In).\n\n","human_summarization":"The code accesses a specified URL's content and prints it to the console using the SWI-Prolog and http\/http_open library. This is specific to HTTP requests, not HTTPS.","id":2981}
    {"lang_cluster":"Prolog","source_code":"\n%repeat(Str,Num,Res).\nrepeat(Str,1,Str).\nrepeat(Str,Num,Res):-\n    Num1 is Num-1,\n    repeat(Str,Num1,Res1),\n    string_concat(Str, Res1, Res).\n\nWorks with: SWI-Prolog version 7\n:- system:set_prolog_flag(double_quotes,chars) .\n\nrepeat(SOURCEz0,COUNT0,TARGETz)\n:-\nprolog:phrase(repeat(SOURCEz0,COUNT0),TARGETz)\n.\n\n%! repeat(SOURCEz0,COUNT0)\/\/2\n\nrepeat(_SOURCEz0_,0)\n-->\n! ,\n[]\n.\n\nrepeat(SOURCEz0,COUNT0)\n-->\nSOURCEz0 ,\n{ COUNT is COUNT0 - 1 } ,\nrepeat(SOURCEz0,COUNT)\n.\n\n","human_summarization":"implement a function to repeat a given string a specified number of times. An example of this is repeating \"ha\" 5 times to get \"hahahahaha\". Additionally, the code demonstrates a more efficient way to repeat a single character, such as repeating \"*\" 5 times to get \"*****\". The implementation uses a tail-recursive DCG, which is more efficient than using lists:append.","id":2982}
    {"lang_cluster":"Prolog","source_code":"\n\nprint_expression_and_result(M, N, Operator)\u00a0:-\n    Expression =.. [Operator, M, N],\n    Result is Expression,\n    format('~w ~8|is ~d~n', [Expression, Result]).\n\narithmetic_integer\u00a0:-\n    read(M),\n    read(N),\n    maplist( print_expression_and_result(M, N), [+,-,*,\/\/,rem,^] ).\n\n?- arithmetic_integer.\n|: 5.\n|: 7.\n5+7     is 12\n5-7     is -2\n5*7     is 35\n5\/\/7    is 0\n5 rem 7 is 5\n5^7     is 78125\ntrue.\n","human_summarization":"take two integers as input from the user and calculate their sum, difference, product, integer quotient, remainder, and exponentiation. The code does not include error handling. The integer quotient rounds towards zero and the sign of the remainder matches the sign of the first operand. The code also includes an example of the integer `divmod` operator.","id":2983}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog version 7\n\ncount_substring(String, Sub, Total) :-\n    count_substring(String, Sub, 0, Total).\n\ncount_substring(String, Sub, Count, Total) :-\n    ( substring_rest(String, Sub, Rest)\n    ->\n        succ(Count, NextCount),\n        count_substring(Rest, Sub, NextCount, Total)\n    ;\n        Total = Count\n    ).\n\nsubstring_rest(String, Sub, Rest) :-\n    sub_string(String, Before, Length, Remain, Sub),\n    DropN is Before + Length,\n    sub_string(String, DropN, Remain, 0, Rest).\n\n\n?- count_substring(\"the three truths\",\"th\",X).\nX = 3.\n\n?- count_substring(\"ababababab\",\"abab\",X).\nX = 2.\n\nWorks with: SWI-Prolog version 7.6.4\n:- system:set_prolog_flag(double_quotes,chars) .\n\noccurrences(TARGETz0,SUBSTRINGz0,COUNT)\n:-\nprolog:phrase(occurrences(SUBSTRINGz0,0,COUNT),TARGETz0)\n.\n\noccurrences(\"\",_,_)\n-->\n! ,\n{ false }\n.\n\noccurrences(SUBSTRINGz0,COUNT0,COUNT)\n-->\nSUBSTRINGz0 ,\n! ,\n{ COUNT1 is COUNT0 + 1 } ,\noccurrences(SUBSTRINGz0,COUNT1,COUNT)\n.\n\noccurrences(SUBSTRINGz0,COUNT0,COUNT)\n-->\n[_] ,\n! ,\noccurrences(SUBSTRINGz0,COUNT0,COUNT)\n.\n\noccurrences(_SUBSTRINGz0_,COUNT,COUNT)\n-->\n!\n.\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments, the main string and the substring to search for, and returns an integer count. Overlapping substrings are not counted multiple times. The matching is done either from left-to-right or right-to-left to yield the maximum number of non-overlapping matches.","id":2984}
    {"lang_cluster":"Prolog","source_code":"\n\nhanoi(N)\u00a0:- move(N,left,center,right).\n\nmove(0,_,_,_)\u00a0:-\u00a0!.\nmove(N,A,B,C)\u00a0:-\n    M is N-1,\n    move(M,A,C,B),\n    inform(A,B),\n    move(M,C,B,A).\n\ninform(X,Y)\u00a0:- write([move,a,disk,from,the,X,pole,to,Y,pole]), nl.\n\nhanoi(N, Src, Aux, Dest, Moves-NMoves)\u00a0:-\n  NMoves is 2^N - 1,\n  length(Moves, NMoves),\n  phrase(move(N, Src, Aux, Dest), Moves).\n\n\nmove(1, Src, _, Dest) -->\u00a0!,\n  [Src->Dest].\n\nmove(2, Src, Aux, Dest) -->\u00a0!,\n  [Src->Aux,Src->Dest,Aux->Dest].\n\nmove(N, Src, Aux, Dest) -->\n  { succ(N0, N) },\n  move(N0, Src, Dest, Aux),\n  move(1, Src, Aux, Dest),\n  move(N0, Aux, Src, Dest).\n","human_summarization":"\"Output: The code uses recursion to solve the Towers of Hanoi problem, as per the task described in Programming in Prolog by W.F. Clocksin & C.S. Mellish. It separates core logic from IO using DCGs.\"","id":2985}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library(pce)).\n\nanimation :-\n    new(D, window('Animation')),\n    new(Label, label(hello, 'Hello world\u00a0! ')),\n    send(D, display, Label, point(1,10)),\n    new(@animation, animation(Label)),\n    send(D, recogniser,\n         new(_G, my_click_gesture(left, ''))),\n\n    send(D, done_message, and(message(@animation, free),\n                  message(@receiver, destroy))),\n    send(D, open),\n    send(@animation?mytimer, start).\n\n\n:- pce_begin_class(animation(label), object).\nvariable(label, object,  both, \"Display window\").\nvariable(delta,    object, both,  \"increment of the angle\").\nvariable(mytimer, timer, both, \"timer of the animation\").\n\ninitialise(P, W:object) :->\n        \"Creation of the object\"::\n        send(P, label, W),\n        send(P, delta, to_left),\n    send(P, mytimer, new(_, timer(0.5,message(P, anim_message)))).\n\n% method called when the object is destroyed\n% first the timer is stopped\n% then all the resources are freed\nunlink(P) :->\n    send(P?mytimer, stop),\n    send(P, send_super, unlink).\n\n\n% message processed by the timer\nanim_message(P) :->\n    get(P, label, L),\n    get(L, selection, S),\n    get(P, delta, Delta),\n    compute(Delta, S, S1),\n    new(A, name(S1)),\n    send(L, selection, A).\n\n\n:- pce_end_class.\n\n:- pce_begin_class(my_click_gesture, click_gesture,\n           \"Click in a window\").\n\nclass_variable(button, button_name, left,\n           \"By default click with left button\").\n\nterminate(G, Ev:event) :->\n    send(G, send_super, terminate, Ev),\n    get(@animation, delta, D),\n    (   D = to_left -> D1 = to_right; D1 = to_left),\n    send(@animation, delta, D1).\n\n:- pce_end_class.\n\n\n% compute next text to be dispalyed\ncompute(to_right, S, S1) :-\n    get(S, size, Len),\n    Len1 is Len - 1,\n    get(S, sub, Len1, Str),\n    get(S, delete_suffix, Str, V),\n    get(Str, append, V, S1).\n\ncompute(to_left, S, S1) :-\n    get(S, sub, 0, 1, Str),\n    get(S, delete_prefix, Str, V),\n    get(V, append, Str, S1).\n\n","human_summarization":"create a GUI animation where a \"Hello World!\" string appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text. The animation is implemented using SWI-Prolog's graphic interface XPCE.","id":2986}
    {"lang_cluster":"Prolog","source_code":"\n% initial condition\ndo(0):- write(0),nl,do(1).\n\n% control condition\ndo(V):- 0 is mod(V,6),\u00a0!, fail.\n\n% loop\ndo(V)\u00a0:-\n    write(V),nl,\n    Y is V + 1,\n    do(Y).\n\nwloop\u00a0:-\n   do(0).\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":2987}
    {"lang_cluster":"Prolog","source_code":"\n\nremove_first_last_chars :-\n    L = \"Rosetta\",\n    L = [_|L1],\n    remove_last(L, L2),\n    remove_last(L1, L3),\n    writef('Original string     \u00a0: %s\\n', [L]),\n    writef('Without first char      \u00a0: %s\\n', [L1]),\n    writef('Without last char       \u00a0: %s\\n', [L2]),\n    writef('Without first\/last chars\u00a0: %s\\n', [L3]).\n\nremove_last(L, LR) :-\n    append(LR, [_], L).\n\n\n\u00a0?- remove_first_last_chars.\nOriginal string         \u00a0: Rosetta\nWithout first char      \u00a0: osetta\nWithout last char       \u00a0: Rosett\nWithout first\/last chars\u00a0: osett\ntrue.\n\n","human_summarization":"demonstrate how to remove the first, last, or both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16 encoding, referencing logical characters not code units. It is not designed to handle all Unicode characters in other encodings like 8-bit ASCII or EUC-JP.","id":2988}
    {"lang_cluster":"Prolog","source_code":"\n:- use_module(library(clpfd)).\n \nsudoku(Rows) :-\n        length(Rows, 9), maplist(length_(9), Rows),\n        append(Rows, Vs), Vs ins 1..9,\n        maplist(all_distinct, Rows),\n        transpose(Rows, Columns), maplist(all_distinct, Columns),\n        Rows = [A,B,C,D,E,F,G,H,I],\n        blocks(A, B, C), blocks(D, E, F), blocks(G, H, I).\n \nlength_(L, Ls) :- length(Ls, L).\n \nblocks([], [], []).\nblocks([A,B,C|Bs1], [D,E,F|Bs2], [G,H,I|Bs3]) :-\n        all_distinct([A,B,C,D,E,F,G,H,I]),\n        blocks(Bs1, Bs2, Bs3).\n \nproblem(1, [[_,_,_,_,_,_,_,_,_],\n            [_,_,_,_,_,3,_,8,5],\n            [_,_,1,_,2,_,_,_,_],\n            [_,_,_,5,_,7,_,_,_],\n            [_,_,4,_,_,_,1,_,_],\n            [_,9,_,_,_,_,_,_,_],\n            [5,_,_,_,_,_,_,7,3],\n            [_,_,2,_,1,_,_,_,_],\n            [_,_,_,_,4,_,_,_,9]]).\n\nWorks with: GNU Prolog version 1.4.4\n:- initialization(main).\n\n\nsolve(Rows) :-\n    maplist(domain_1_9, Rows)\n  , different(Rows)\n  , transpose(Rows,Cols), different(Cols)\n  , blocks(Rows,Blocks) , different(Blocks)\n  , maplist(fd_labeling, Rows)\n  .\n\ndomain_1_9(Rows) :- fd_domain(Rows,1,9).\ndifferent(Rows)  :- maplist(fd_all_different, Rows).\n\nblocks(Rows,Blocks) :-\n    maplist(split3,Rows,Xs), transpose(Xs,Ys)\n  , concat(Ys,Zs), concat_map(split3,Zs,Blocks)\n  . % where\n    split3([X,Y,Z|L],[[X,Y,Z]|R]) :- split3(L,R).\n    split3([],[]).\n\n\n% utils\/list\nconcat_map(F,Xs,Ys) :- call(F,Xs,Zs), maplist(concat,Zs,Ys).\n\nconcat([],[]).\nconcat([X|Xs],Ys) :- append(X,Zs,Ys), concat(Xs,Zs).\n\ntranspose([],[]).\ntranspose([[X]|Col], [[X|Row]]) :- transpose(Col,[Row]).\ntranspose([[X|Row]], [[X]|Col]) :- transpose([Row],Col).\ntranspose([[X|Row]|Xs], [[X|Col]|Ys]) :-\n    maplist(bind_head, Row, Ys, YX)\n  , maplist(bind_head, Col, Xs, XY)\n  , transpose(XY,YX)\n  . % where\n    bind_head(H,[H|T],T).\n    bind_head([],[],[]).\n\n\n% tests\ntest([ [_,_,3,_,_,_,_,_,_]\n     , [4,_,_,_,8,_,_,3,6]\n     , [_,_,8,_,_,_,1,_,_]\n     , [_,4,_,_,6,_,_,7,3]\n     , [_,_,_,9,_,_,_,_,_]\n     , [_,_,_,_,_,2,_,_,5]\n     , [_,_,4,_,7,_,_,6,8]\n     , [6,_,_,_,_,_,_,_,_]\n     , [7,_,_,6,_,_,5,_,_]\n     ]).\n\nmain :- test(T), solve(T), maplist(show,T), halt.\nshow(X) :- write(X), nl.\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and displays the solved Sudoku in a human-readable format. The solution utilizes the Algorithmics of Sudoku and is adapted for gprolog 1.3.1, running in 0.02 time and using 68352 memory.\"","id":2989}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog\nLibrary: clpfd\n:- use_module(library(clpfd)).\n\ncaesar :-\n\tL1 = \"The five boxing wizards jump quickly\",\n\twritef(\"Original\u00a0: %s\\n\", [L1]),\n\n\t% encryption of the sentence\n\tencoding(3, L1, L2) ,\n\twritef(\"Encoding\u00a0: %s\\n\", [L2]),\n\n\t% deciphering on the encoded sentence\n\tencoding(3, L3, L2),\n\twritef(\"Decoding\u00a0: %s\\n\", [L3]).\n\n% encoding\/decoding of a sentence\nencoding(Key, L1, L2) :-\n\tmaplist(caesar_cipher(Key), L1, L2).\n\ncaesar_cipher(_, 32, 32) :- !.\n\ncaesar_cipher(Key, V1, V2) :-\n\tV #= Key + V1,\n\n\t% we verify that we are in the limits of A-Z and a-z.\n\t((V1 #=< 0'Z #\/\\ V #> 0'Z) #\\\/ (V1 #=< 0'z #\/\\ V #> 0'z)\n\t#\\\/\n\t(V1 #< 0'A #\/\\ V2 #>= 0'A)#\\\/ (V1 #< 0'a #\/\\ V2 #>= 0'a)) #==> A,\n\n\t% if we are not in these limits A is 1, otherwise 0.\n\tV2 #= V - A * 26,\n\n\t% compute values of V1 and V2\n\tlabel([A, V1, V2]).\n\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":2990}
    {"lang_cluster":"Prolog","source_code":"\n\nlcm(X, Y, Z) :-\n\tZ is abs(X * Y) \/ gcd(X,Y).\n\n\n\u00a0?- lcm(18,12, Z).\nZ = 36.\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula |m x n|\/gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":2991}
    {"lang_cluster":"Prolog","source_code":"\n\n?- foreach(member(X, [red,green,blue,black,white]), writeln(X)).\nred\ngreen\nblue\nblack\nwhite\ntrue.\n","human_summarization":"iterates through each element in a collection in order and prints it, using a \"for each\" loop or another type of loop if \"for each\" is not available.","id":2992}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog\nsplitup(Sep,[token(B)|BL]) --> splitup(Sep,B,BL).\nsplitup(Sep,[A|AL],B)      --> [A], {\\+ [A] = Sep }, splitup(Sep,AL,B).\nsplitup(Sep,[],[B|BL])     --> Sep, splitup(Sep,B,BL).\nsplitup(_Sep,[],[])        --> [].\nstart\u00a0:-\n    phrase(splitup(\",\",Tokens),\"Hello,How,Are,You,Today\"),\n    phrase(splitup(\".\",Tokens),Backtogether),\n    string_to_list(ABack,Backtogether),\n    writeln(ABack).\n\n","human_summarization":"\"Tokenizes a given string by separating it at commas into an array, then displays each word to the user, separated by a period, using the SWI Prolog string data type and accompanying predicates.\"","id":2993}
    {"lang_cluster":"Prolog","source_code":"\ngcd(X, 0, X):-\u00a0!.\ngcd(0, X, X):-\u00a0!.\ngcd(X, Y, D):- X > Y,\u00a0!, Z is X mod Y, gcd(Y, Z, D).\ngcd(X, Y, D):- Z is Y mod X, gcd(X, Z, D).\ngcd(X, 0, X):-\u00a0!.\ngcd(0, X, X):-\u00a0!.\ngcd(X, Y, D):- X =< Y,\u00a0!, Z is Y - X, gcd(X, Z, D).\ngcd(X, Y, D):- gcd(Y, X, D).\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":2994}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog version 7\n\nnumeric_string(String)\u00a0:-\n    atom_string(Atom, String),\n    atom_number(Atom, _).\n\ntest_strings(Strings)\u00a0:-\n    forall( member(String, Strings),\n            ( ( numeric_string(String)\n              ->  Result = a\n             \u00a0;   Result = 'not a' ),\n              format('~w is ~w number.~n', [String, Result])\n            )\n          ).\n\n?- test_strings([\"123\", \"0.123\", \"-123.1\", \"NotNum\", \"1.\"]).\n123 is a number.\n0.123 is a number.\n-123.1 is a number.\nNotNum is not a number.\n1. is not a number.\ntrue.\n","human_summarization":"implement a boolean function that checks if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax for numeric literals or numbers converted from strings.","id":2995}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog\nLibrary: clpfd\n\n:- use_module(library(clpfd)).\n\n% tuples (name, weights, value, nb pieces).\nknapsack :-\n\tL = [(   map, \t        9, \t150, \t1),\n\t     (   compass, \t13, \t35, \t1),\n\t     (   water, \t153, \t200, \t2),\n\t     (   sandwich, \t50, \t60, \t2),\n\t     (   glucose, \t15, \t60, \t2),\n\t     (   tin, \t68, \t45, \t3),\n\t     (   banana, \t27, \t60, \t3),\n\t     (   apple, \t39, \t40, \t3),\n\t     (   cheese, \t23, \t30, \t1),\n\t     (   beer, \t52, \t10, \t3),\n\t     (   'suntan cream', \t11, \t70, \t1),\n\t     (   camera, \t32, \t30, \t1),\n\t     (   'T-shirt', \t24, \t15, \t2),\n\t     (   trousers, \t48, \t10, \t2),\n\t     (   umbrella, \t73, \t40, \t1),\n\t     (   'waterproof trousers', \t42, \t70, \t1),\n\t     (   'waterproof overclothes', \t43, \t75, \t1),\n\t     (   'note-case', \t22, \t80, \t1),\n\t     (   sunglasses, \t7, \t20, \t1),\n\t     (   towel, \t18, \t12, \t2),\n\t     (   socks, \t4, \t50, \t1),\n\t     (   book, \t30, \t10, \t2)],\n\n\t% Takes is the list of the numbers of each items\n\t% these numbers are between 0 and the 4th value of the tuples of the items\n        maplist(collect, L, Ws, Vs, Takes),\n        scalar_product(Ws, Takes, #=<, 400),\n        scalar_product(Vs, Takes, #=, VM),\n\n\t% to have statistics on the resolution of the problem.\n\ttime(labeling([max(VM), down], Takes)),\n        scalar_product(Ws, Takes, #=, WM),\n\n\t%% displayinf of the results.\n\tcompute_lenword(L, 0, Len),\n\tsformat(A1, '~~w~~t~~~w|', [Len]),\n\tsformat(A2, '~~t~~w~~~w|', [4]),\n\tsformat(A3, '~~t~~w~~~w|', [5]),\n\tprint_results(A1,A2,A3, L, Takes, WM, VM).\n\ncollect((_, W, V, N), W, V, Take) :-\n\tTake in 0..N.\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\ncompute_lenword([], N, N).\ncompute_lenword([(Name, _, _, _)|T], N, NF):-\n\tatom_length(Name, L),\n\t(   L > N -> N1 = L; N1 = N),\n\tcompute_lenword(T, N1, NF).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nprint_results(A1,A2,A3, [], [], WM, WR) :-\n\tsformat(W0, '~w ', [' ']),\n\tsformat(W1, A1, [' ']),\n\tsformat(W2, A2, [WM]),\n\tsformat(W3, A3, [WR]),\n\tformat('~w~w~w~w~n', [W0,W1,W2,W3]).\n\n\nprint_results(A1,A2,A3, [_H|T], [0|TR], WM, VM) :-\n\t!,\n\tprint_results(A1,A2,A3, T, TR, WM, VM).\n\nprint_results(A1, A2, A3, [(Name, W, V, _)|T], [N|TR], WM, VM) :-\n\tsformat(W0, '~w ', [N]),\n\tsformat(W1, A1, [Name]),\n\tsformat(W2, A2, [W]),\n\tsformat(W3, A3, [V]),\n\tformat('~w~w~w~w~n', [W0,W1,W2,W3]),\n\tprint_results(A1, A2, A3, T, TR, WM, VM).\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist should carry in his knapsack, given a maximum weight limit of 4 kg. The selection is made based on the value and weight of each item, with the aim to maximize the total value without exceeding the weight limit. The code uses the clpfd and simplex libraries by Markus Triska for computation.","id":2996}
    {"lang_cluster":"Prolog","source_code":"\n\nincr_numerical_string(S1, S2)\u00a0:-\n\tstring_to_atom(S1, A1),\n\tatom_number(A1, N1),\n\tN2 is N1+1,\n\tatom_number(A2, N2),\n\tstring_to_atom(S2, A2).\n\n","human_summarization":"\"Increments a numerical string using SWI-Prolog.\"","id":2997}
    {"lang_cluster":"Prolog","source_code":"\n%! directory_prefix(PATHs,STOP0,PREFIX)\n\ndirectory_prefix([],_STOP0_,'')\n:-\n!\n.\n\ndirectory_prefix(PATHs0,STOP0,PREFIX)\n:-\nprolog:once(longest_prefix(PATHs0,STOP0,LONGEST_PREFIX)) ->\nprolog:atom_concat(PREFIX,STOP0,LONGEST_PREFIX) ;\nPREFIX=''\n. \n\n%! longest_prefix(PATHs,STOP0,PREFIX)\n\nlongest_prefix(PATHs0,STOP0,PREFIX)\n:-\nQUERY=(shortest_prefix(PATHs0,STOP0,SHORTEST_PREFIX)) ,\nprolog:findall(SHORTEST_PREFIX,QUERY,SHORTEST_PREFIXs) ,\nlists:reverse(SHORTEST_PREFIXs,LONGEST_PREFIXs) ,\nlists:member(PREFIX,LONGEST_PREFIXs)\n.\n\n%! shortest_prefix(PATHs,STOP0,PREFIX)\n\nshortest_prefix([],_STOP0_,_PREFIX_) .\n\nshortest_prefix([PATH0|PATHs0],STOP0,PREFIX)\n:-\nstarts_with(PATH0,PREFIX) ,\nends_with(PREFIX,STOP0) ,\nshortest_prefix(PATHs0,STOP0,PREFIX)\n.\n\n%! starts_with(TARGET,START)\n\nstarts_with(TARGET,START)\n:-\nprolog:atom_concat(START,_,TARGET)\n.\n\n%! ends_with(TARGET,END)\n\nends_with(TARGET,END)\n:-\nprolog:atom_concat(_,END,TARGET)\n.\n\n\n","human_summarization":"The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '\/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.","id":2998}
    {"lang_cluster":"Prolog","source_code":"\nmedian(L, Z) :-\n    length(L, Length),\n    I is Length div 2,\n    Rem is Length rem 2,\n    msort(L, S),\n    maplist(sumlist, [[I, Rem], [I, 1]], Mid),\n    maplist(nth1, Mid, [S, S], X),\n    sumlist(X, Y),\n    Z is Y\/2.\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.","id":2999}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog version 4.8.0\nWorks with: Ciao Prolog version 1.21.0\n\nfizzbuzz\u00a0:-\n   forall(between(1, 100, X), print_item(X)).\n\nprint_item(X)\u00a0:-\n   (  X mod 15 =:= 0\n   -> write('FizzBuzz')\n  \u00a0;  X mod 3 =:= 0\n   -> write('Fizz')\n  \u00a0;  X mod 5 =:= 0\n   -> write('Buzz')\n  \u00a0;  write(X)\n   ),\n   nl.\n\nfizzbuzz(X)\u00a0:- X mod 15 =:= 0,\u00a0!, write('FizzBuzz').\nfizzbuzz(X)\u00a0:- X mod 3 =:= 0,\u00a0!, write('Fizz').\nfizzbuzz(X)\u00a0:- X mod 5 =:= 0,\u00a0!, write('Buzz').\nfizzbuzz(X)\u00a0:- write(X).\n\ndofizzbuzz\u00a0:-between(1, 100, X), fizzbuzz(X), nl, fail.\ndofizzbuzz.\n\n%        N  \/3?  \/5?  V\nfizzbuzz(_, yes, yes, 'FizzBuzz').\nfizzbuzz(_, yes, no,  'Fizz').\nfizzbuzz(_, no,  yes, 'Buzz').\nfizzbuzz(N, no,  no,  N).\n\n% Unifies V with 'yes' if D divides evenly into N, 'no' otherwise.\ndivisible_by(N, D, yes)\u00a0:- N mod D =:= 0.\ndivisible_by(N, D, no)\u00a0:- N mod D =\\= 0.\n\n% Print 'Fizz', 'Buzz', 'FizzBuzz' or N as appropriate.\nfizz_buzz_or_n(N)\u00a0:- N > 100.\nfizz_buzz_or_n(N)\u00a0:- N =< 100,\n   divisible_by(N, 3, Fizz),\n   divisible_by(N, 5, Buzz),\n   fizzbuzz(N, Fizz, Buzz, FB),\n   write(FB), nl,\n   M is N+1, fizz_buzz_or_n(M).\n\nmain\u00a0:-\n   fizz_buzz_or_n(1).\n\nWorks with: SWI Prolog version 8.2.1 Works with: Scryer Prolog version 0.7.8\n% This implementation uses modern Prolog techniques\n% in order to be an idiomatic solution that uses logical purity, generality and determinism wherever possible:\n% - CLP(Z): constraint logic programming on integers.\n% - library(reif): efficient logical predicates based on 'Indexing dif\/2'.\n:- module(fizz_buzz, [main\/0, integer_fizzbuzz_below_100\/2, integer_fizzbuzz\/2]).\n\n:- use_module(library(reif)).\n\n% for Scryer-Prolog:\n:- use_module(library(clpz)).\n:- use_module(library(between)).\n:- use_module(library(iso_ext)).\n:- use_module(library(si)).\n\n% for SWI-Prolog:\n%\u00a0:- use_module(library(clpfd)).\n\n% Prints all solutions to `integer_fizzbuzz_below_100` each on a separate line, in order.\n% Logically-impure shell, as currently there is no logically-pure way to write to a filestream.\nmain\u00a0:-\n    forall(integer_fizzbuzz_below_100(_, FizzBuzz), write_line(FizzBuzz)).\n\nwrite_line(Value)\u00a0:-\n    write(Value),\n    nl.\n\n% Constrains FizzBuzz results to the range 1 <= X <= 100,\n% and (for the 'most general query' where neither X or FizzBuzz is concrete)\n% ensures results are traversed in order low -> high X.\n%\n%\u00a0?- integer_fizzbuzz_below_100(X, FizzBuzz)\u00a0% generate all the results in order\n%\u00a0?- integer_fizzbuzz_below_100(27, Result)\u00a0% Find out what output `27` will produce (it's 'Fizz'.)\n%\u00a0?- integer_fizzbuzz_below_100(X, 'Fizz')  \u00a0% generate all the numbers which would print 'Fizz' in order (3, 6, 9, etc).\n%\u00a0?- integer_fizzbuzz_below_100(X, Res), integer_si(Res)\u00a0% generate all the numbers which would print themselves in order (1, 2, 4, 6, 7, 8, 11, etc).\n%\u00a0?- integer_fizzbuzz_below_100(X, Res), is_of_type(integer, Res)\u00a0% SWI-Prolog version doing the same.\ninteger_fizzbuzz_below_100(X, FizzBuzz)\u00a0:-\n    between(1, 100, X),\n    integer_fizzbuzz(X, FizzBuzz).\n\n% States the relationship between a number\n% and its FizzBuzz representation.\n%\n% Because constraints are propagated lazily,\n% prompting this predicate without having constrained `Num`\n% to a particular integer value will give you its definition back.\n% Put differently: This predicate returns the whole solution space at once,\n% and external labeling techniques are required to traverse and concretize this solution space\n% in an order that we like.\ninteger_fizzbuzz(Num, FizzBuzz)\u00a0:-\n    if_(Num mod 15 #= 0, FizzBuzz = 'FizzBuzz',\n        if_(Num mod 5 #= 0, FizzBuzz = 'Buzz',\n            if_(Num mod 3 #= 0, FizzBuzz = 'Fizz',\n                Num = FizzBuzz)\n           )\n       ).\n\n% Reifiable `#=`.\n#=(X, Y, T)\u00a0:-\n    X #= X1,\n    Y #= Y1,\n    zcompare(C, X1, Y1),\n    eq_t(C, T).\n\neq_t(=, true).\neq_t(<, false).\neq_t(>, false).\n","human_summarization":"The code prints numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'. It uses different Prolog techniques for looping, including higher-order predicates, failure-driven loops, and tail recursion.","id":3000}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library(pce)).\n\nmandelbrot\u00a0:-\n    new(D, window('Mandelbrot Set')),\n    send(D, size, size(700, 650)),\n    new(Img, image(@nil, width\u00a0:= 700, height\u00a0:= 650, kind\u00a0:= pixmap)),\n\n    forall(between(0,699, I),\n           (   forall(between(0,649, J),\n              (   get_RGB(I, J, R, G, B),\n                  R1 is (R * 256) mod 65536,\n                  G1 is (G * 256) mod 65536,\n                  B1 is (B * 256) mod 65536,\n                  send(Img, pixel(I, J, colour(@default, R1, G1, B1))))))),\n    new(Bmp, bitmap(Img)),\n    send(D, display, Bmp, point(0,0)),\n    send(D, open).\n\nget_RGB(X, Y, R, G, B)\u00a0:-\n    CX is (X - 350) \/ 150,\n    CY is (Y - 325) \/ 150,\n    Iter = 570,\n    compute_RGB(CX, CY, 0, 0, Iter, It),\n    IterF is It \\\/ It << 15,\n    R is IterF >> 16,\n    Iter1 is IterF - R << 16,\n    G is Iter1 >> 8,\n    B  is Iter1 - G << 8.\n\ncompute_RGB(CX, CY, ZX, ZY, Iter, IterF)\u00a0:-\n    ZX * ZX + ZY * ZY < 4,\n    Iter > 0,\n   \u00a0!,\n    Tmp is  ZX * ZX - ZY * ZY + CX,\n    ZY1 is 2 * ZX * ZY + CY,\n    Iter1 is Iter - 1,\n    compute_RGB(CX, CY, Tmp, ZY1, Iter1, IterF).\n\ncompute_RGB(_CX, _CY, _ZX, _ZY, Iter, Iter).Example\u00a0:\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions, utilizing the graphic interface XPCE of SWI-Prolog.","id":3001}
    {"lang_cluster":"Prolog","source_code":"\nsum([],0).\nsum([H|T],X)\u00a0:- sum(T,Y), X is H + Y.\nproduct([],1).\nproduct([H|T],X)\u00a0:- product(T,Y), X is H * X.\n\n:- sum([1,2,3,4,5,6,7,8,9],X).\nX =45;\n:- product([1,2,3,4,5],X).\nX = 120;\n\n\nadd(A,B,R):-\n    R is A + B.\n\nmul(A,B,R):-\n    R is A * B.\n\n% define fold now.\nfold([], Act, Init, Init).\n\nfold(Lst, Act, Init, Res):-\n    head(Lst,Hd),\n    tail(Lst,Tl),\n    apply(Act,[Init, Hd, Ra]),\n    fold(Tl, Act, Ra, Res).\n\nsumproduct(Lst, Sum, Prod):-\n    fold(Lst,mul,1, Prod),\n    fold(Lst,add,0, Sum).\n\n?- sumproduct([1,2,3,4],Sum,Prod).\nSum = 10,\nProd = 24 .\n","human_summarization":"\"Calculates the sum and product of an array of integers using fold method.\"","id":3002}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog\nleap_year(L)\u00a0:-\n\tpartition(is_leap_year, L, LIn, LOut),\n\tformat('leap years\u00a0: ~w~n', [LIn]),\n\tformat('not leap years\u00a0: ~w~n', [LOut]).\n\nis_leap_year(Year)\u00a0:-\n\tR4 is Year mod 4,\n\tR100 is Year mod 100,\n\tR400 is Year mod 400,\n\t(   (R4 = 0, R100 \\= 0); R400 = 0).\n\n","human_summarization":"determine if a given year is a leap year in the Gregorian calendar using a built-in function.","id":3003}
    {"lang_cluster":"Prolog","source_code":"\ndept(X) :- between(1, 7, X).\n\npolice(X) :- member(X, [2, 4, 6]).\nfire(X)   :- dept(X).\nsan(X)    :- dept(X).\n\nassign(A, B, C) :-\n    police(A), fire(B), san(C),\n    A =\\= B, A =\\= C, B =\\= C,\n    12 is A + B + C.\n\nmain :-\n    write(\"P F S\"), nl,\n    forall(assign(Police, Fire, Sanitation), format(\"~w ~w ~w~n\", [Police, Fire, Sanitation])),\n    halt.\n\n?- main.\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":3004}
    {"lang_cluster":"Prolog","source_code":"\n\n?- A = \"A test string\", A = B.\nA = B, B = \"A test string\".\n","human_summarization":"distinguish between copying a string's content and creating an additional reference to an existing string in Prolog, considering that values in Prolog are immutable and a variable can't be reassigned once it has been unified with a string value.","id":3005}
    {"lang_cluster":"Prolog","source_code":"\nfemale(0,1).\nfemale(N,F) :- N>0, \n\t       N1 is N-1, \n\t       female(N1,R),\n\t       male(R, R1),\n\t       F is N-R1.\n\nmale(0,0).\nmale(N,F) :- N>0, \n\t     N1 is N-1, \n\t     male(N1,R),\n\t     female(R, R1),\n\t     F is N-R1.\n\nWorks with: GNU Prolog\nflist(S) :- for(X, 0, S), female(X, R), format('~d ', [R]), fail.\nmlist(S) :- for(X, 0, S), male(X, R), format('~d ', [R]), fail.\n\n\n|\u00a0?- flist(19).\n1 1 2 2 3 3 4 5 5 6 6 7 8 8 9 9 10 11 11 12 \n\nno\n|\u00a0?- mlist(19).\n0 0 1 2 2 3 4 4 5 6 6 7 7 8 9 9 10 11 11 12\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions handle cases where a language does not support mutual recursion by stating this limitation.","id":3006}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog version 6\n?- random_member(M, [a, b, c, d, e, f, g, h, i, j]).\nM = i.\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":3007}
    {"lang_cluster":"Prolog","source_code":"\n\nbin_search(Elt,List,Result):-\n  length(List,N), bin_search_inner(Elt,List,1,N,Result).\n  \nbin_search_inner(Elt,List,J,J,J):-\n  nth(J,List,Elt).\nbin_search_inner(Elt,List,Begin,End,Mid):-\n  Begin < End,\n  Mid is (Begin+End) div 2,\n  nth(Mid,List,Elt).\nbin_search_inner(Elt,List,Begin,End,Result):-\n  Begin < End,\n  Mid is (Begin+End) div 2,\n  nth(Mid,List,MidElt),\n  MidElt < Elt,\n  NewBegin is Mid+1,\n  bin_search_inner(Elt,List,NewBegin,End,Result).\nbin_search_inner(Elt,List,Begin,End,Result):-\n  Begin < End,\n  Mid is (Begin+End) div 2,\n  nth(Mid,List,MidElt),\n  MidElt > Elt,\n  NewEnd is Mid-1,\n  bin_search_inner(Elt,List,Begin,NewEnd,Result).\n\nOutput examples:\n\u00a0?- bin_search(4,[1,2,4,8,16,32,64,128],Result).\nResult = 3.\n\n?- bin_search(5,[1,2,4,8],Result).\nResult = -1.\n","human_summarization":"The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It includes both recursive and iterative versions of the traditional algorithm, as well as versions that return the leftmost and rightmost insertion points for the given value. The code also handles potential overflow bugs. The binary search is performed on a sorted integer array, and the index of the found number is returned, along with a message indicating whether the number was found in the array.","id":3008}
    {"lang_cluster":"Prolog","source_code":"\n\n:-\n    current_prolog_flag(os_argv, Args),\n    write(Args).\n\n\n:-\n    current_prolog_flag(argv, Args),\n    write(Args).\n\n\n","human_summarization":"\"Code retrieves and prints the list of command-line arguments given to the program. It uses os_argv or argv to access arguments not consumed by the Prolog interpreter, excluding the interpreter name, input Prolog filename, and any other arguments directed at the Prolog interpreter.\"","id":3009}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library(pce)).\n\npendulum :-\n\tnew(D, window('Pendulum')),\n\tsend(D, size, size(560, 300)),\n\tnew(Line, line(80, 50, 480, 50)),\n\tsend(D, display, Line),\n\tnew(Circle, circle(20)),\n\tsend(Circle, fill_pattern,  colour(@default, 0, 0, 0)),\n\tnew(Boule, circle(60)),\n\tsend(Boule, fill_pattern,  colour(@default, 0, 0, 0)),\n\tsend(D, display, Circle, point(270,40)),\n\tsend(Circle, handle, handle(h\/2, w\/2, in)),\n\tsend(Boule, handle, handle(h\/2, w\/2, out)),\n\tsend(Circle, connect, Boule, link(in, out, line(0,0,0,0,none))),\n\tnew(Anim, animation(D, 0.0, Boule, 200.0)),\n\tsend(D, done_message, and(message(Anim, free),\n\t\t\t\t  message(Boule, free),\n\t\t\t\t  message(Circle, free),\n\t\t\t\t  message(@receiver,destroy))),\n\tsend(Anim?mytimer, start),\n\tsend(D, open).\n\n\n\n\n:- pce_begin_class(animation(window, angle, boule, len_pendulum), object).\nvariable(window, object,  both, \"Display window\").\nvariable(boule,  object, both,  \"bowl of the pendulum\").\nvariable(len_pendulum,    object, both,  \"len of the pendulum\").\nvariable(angle,  object, both,  \"angle with the horizontal\").\nvariable(delta,    object, both,  \"increment of the angle\").\nvariable(mytimer, timer, both, \"timer of the animation\").\n\ninitialise(P, W:object, A:object, B : object, L:object) :->\n        \"Creation of the object\"::\n        send(P, window, W),\n        send(P, angle, A),\n        send(P, boule, B),\n        send(P, len_pendulum, L),\n        send(P, delta, 0.01),\n\tsend(P, mytimer, new(_, timer(0.01,message(P, anim_message)))).\n\n% method called when the object is destroyed\n% first the timer is stopped\n% then all the resources are freed\nunlink(P) :->\n\tsend(P?mytimer, stop),\n\tsend(P, send_super, unlink).\n\n\n% message processed by the timer\nanim_message(P) :->\n\tget(P, angle, A),\n\tget(P, len_pendulum, L),\n\tcalc(A, L, X, Y),\n\tget(P, window, W),\n\tget(P, boule, B),\n\tsend(W, display, B, point(X,Y)),\n\t% computation of the next position\n\tget(P, delta, D),\n\tnext_Angle(A, D, NA, ND),\n\tsend(P, angle, NA),\n\tsend(P, delta, ND).\n\n:- pce_end_class.\n\n% computation of the position of the bowl.\ncalc(Ang, Len, X, Y) :-\n\tX is Len * cos(Ang)+ 250,\n\tY is Len * sin(Ang) + 20.\n\n\n% computation of the next angle\n% if we reach 0 or pi, delta change.\nnext_Angle(A, D, NA, ND) :-\n\tNA is D + A,\n\t(((D > 0,   abs(pi-NA) < 0.01); (D < 0, abs(NA) < 0.01))->\n\t  ND = - D;\n\t  ND = D).\n\n","human_summarization":"simulate and animate a simple gravity pendulum using SWI-Prolog's graphic interface XPCE.","id":3010}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module([ library(http\/json),\n                library(func) ]).\n\ntest_json('{\"widget\": { \"debug\": \"on\", \"window\": { \"title\": \"Sample Konfabulator Widget\", \"name\": \"main_window\", \"width\": 500, \"height\": 500 }, \"image\": { \"src\": \"Images\/Sun.png\", \"name\": \"sun1\", \"hOffset\": 250, \"vOffset\": 250, \"alignment\": \"center\" }, \"text\": { \"data\": \"Click Here\", \"size\": 36, \"style\": \"bold\", \"name\": \"text1\", \"hOffset\": 250, \"vOffset\": 100, \"alignment\": \"center\", \"onMouseUp\": \"sun1.opacity = (sun1.opacity \/ 100) * 90;\" }}}').\n\nreading_JSON_term :-\n    atom_json_dict(test_json(~), Dict, []), %% This accomplishes reading in the JSON data\n    writeln( 'JSON as Prolog dict: ~w~n'\n           $ Dict),\n    writeln( 'Access field \"widget.text.data\": ~s~n'\n           $ Dict.widget.text.data),\n    writeln( 'Alter field \"widget\": ~w~n'\n           $ Dict.put(widget, \"Altered\")).\n\nsearalize_a_JSON_term :-\n    Dict = _{book:_{title:\"To Mock a Mocking Bird\",\n                    author:_{first_name:\"Ramond\",\n                             last_name:\"Smullyan\"},\n                    publisher:\"Alfred A. Knopf\",\n                    year:1985\n                   }},\n    json_write(current_output, Dict). %% This accomplishes serializing the JSON object.\n\n\n","human_summarization":"utilize SWI-Prolog 7's library(http\/json) and the new dict datatype to handle JSON objects. They load a JSON string into a data structure and create a new data structure, serializing it into JSON. The code ensures the JSON is valid and uses objects and arrays as appropriate for the language. The serialization and parsing are accomplished with two predicates.","id":3011}
    {"lang_cluster":"Prolog","source_code":"\n\niroot(_, 0, 0) :- !.\niroot(M, N, R) :-\n    M > 1,\n    (N > 0 ->\n        irootpos(M, N, R)\n    ;\n        N \/\\ 1 =:= 1,\n        NegN is -N, irootpos(M, NegN, R0), R is -R0).\n\nirootpos(N, A, R) :-\n    X0 is 1 << (msb(A) div N),  % initial guess is 2^(log2(A) \/ N)\n    newton(N, A, X0, X1),\n    iroot_loop(A, X1, N, A, R).\n\niroot_loop(X1, X2, _, _, X1) :- X1 =< X2, !.\niroot_loop(_, X1, N, A, R) :-\n    newton(N, A, X1, X2),\n    iroot_loop(X1, X2, N, A, R).\n\nnewton(2, A, X0, X1) :- X1 is (X0 + A div X0) >> 1, !.  % fast special case\nnewton(N, A, X0, X1) :- X1 is ((N - 1)*X0 + A div X0**(N - 1)) div N.\n\n\n","human_summarization":"Implement an algorithm to compute the principal nth root of a positive real number using integer math, with the ability to approximate non-integral roots to arbitrary precision.","id":3012}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: GNU Prolog\n:- initialization(main).\n\n\nanswer(24).\nplay :- round, play ; true.\n\nround :-\n    prompt(Ns), get_line(Input), Input \\= \"stop\"\n  , ( phrase(parse(Ns,[]), Input) -> Result = 'correct'\n                                   ; Result = 'wrong'\n    ), write(Result), nl, nl\n  . % where\n    prompt(Ns)  :- length(Ns,4), maplist(random(1,10), Ns)\n                 , write('Digits: '), write(Ns), nl\n                 .\n\nparse([],[X])     --> { answer(X) }.\nparse(Ns,[Y,X|S]) --> \"+\", { Z is X  +  Y }, parse(Ns,[Z|S]).\nparse(Ns,[Y,X|S]) --> \"-\", { Z is X  -  Y }, parse(Ns,[Z|S]).\nparse(Ns,[Y,X|S]) --> \"*\", { Z is X  *  Y }, parse(Ns,[Z|S]).\nparse(Ns,[Y,X|S]) --> \"\/\", { Z is X div Y }, parse(Ns,[Z|S]).\nparse(Ns,Stack)   --> \" \", parse(Ns,Stack).\nparse(Ns,Stack)   --> { select(N,Ns,Ns1), number_codes(N,[Code]) }\n                    , [Code], parse(Ns1,[N|Stack])\n                    .\n\nget_line(Xs) :- get_code(X)\n              , ( X == 10 -> Xs = [] ; Xs = [X|Ys], get_line(Ys) )\n              .\nmain :- randomize, play, halt.\n\n\nDigits: [9,4,6,9]\n46*9-9+\ncorrect\n\nDigits: [7,4,7,8]\n8 4 7 7 \/ - *\ncorrect\n\nDigits: [7,2,8,2]\n7282---\nwrong\n\nDigits: [2,6,7,1]\n4611***\nwrong\n\nDigits: [3,6,5,8]\n+\nwrong\n\nDigits: [2,1,7,7]\nstop\n","human_summarization":"The code generates four random digits from 1 to 9, prompts the player to form an arithmetic expression using those digits exactly once each, and checks if the expression evaluates to 24. The code supports addition, subtraction, multiplication, and division operations, and allows the use of brackets. It does not allow forming multiple digit numbers from the given digits. The order of the digits does not need to be preserved. The code does not generate or test the validity of the expression.","id":3013}
    {"lang_cluster":"Prolog","source_code":"\n\n% the test\nrun_length :-\n\tL = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\",\n\twritef('encode %s\\n', [L]),\n\tencode(L, R),\n\twriteln(R), nl,\n\twritef('decode %w\\n', [R]),\n\tdecode(R, L1),\n\twriteln(L1).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%  encode\n%  \n%  translation\n%  from\n%  \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\n%  to\n%  \"12W1B12W3B24W1B14W\"\n%  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nencode(In, Out) :-\n\t% Because of the special management of the \"strings\" by Prolog\n\t( is_list(In) -> I = In; string_to_list(In, I)),\n\tpackList(I, R1),\n\tdcg_packList2List(R1,R2, []),\n\tstring_to_list(Out,R2).\n\n\n\ndcg_packList2List([[N, V]|T]) -->\n\t{ number_codes(N, LN)},\n\tLN,\n\t[V],\n\tdcg_packList2List(T).\n\ndcg_packList2List([]) --> [].\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%  decode\n%  \n%  translation\n%  from\n%  \"12W1B12W3B24W1B14W\"\n%  to\n%  \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\n%  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\ndecode(In, Out) :-\n\t% Because of the special management of the \"strings\" by Prolog\n\t( is_list(In) -> I = In; string_to_list(In, I)),\n\tdcg_List2packList(I, R1, []),\n\tpackList(L1, R1),\n\tstring_to_list(Out, L1).\n\n\ndcg_List2packList([H|T]) -->\n\t{code_type(H, digit)},\n\tparse_number([H|T], 0).\n\ndcg_List2packList([]) --> [].\n\n\nparse_number([H|T], N) -->\n\t{code_type(H, digit), !,\n\tN1 is N*10 + H - 48 },\n\tparse_number(T, N1).\n\nparse_number([H|T], N) -->\n\t[[N, H]],\n\tdcg_List2packList(T).\n\n\n% use of library clpfd allows packList(?In, ?Out) to works\n% in both ways In --> Out and In <-- Out.\n\n:- use_module(library(clpfd)).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\n%\u00a0?- packList([a,a,a,b,c,c,c,d,d,e], L).\n%  L = [[3,a],[1,b],[3,c],[2,d],[1,e]] .\n%\u00a0?- packList(R,  [[3,a],[1,b],[3,c],[2,d],[1,e]]).\n% R = [a,a,a,b,c,c,c,d,d,e] .\n%  \n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\npackList([],[]).\n\npackList([X],[[1,X]]) :- !.\n\n\npackList([X|Rest],[XRun|Packed]):-\n    run(X,Rest, XRun,RRest),\n    packList(RRest,Packed).\n\n\nrun(Var,[],[1,Var],[]).\n\nrun(Var,[Var|LRest],[N1, Var],RRest):-\n    N #> 0,\n    N1 #= N + 1,\n    run(Var,LRest,[N, Var],RRest).\n\n\nrun(Var,[Other|RRest], [1,Var],[Other|RRest]):-\n    dif(Var,Other).\n\n\n\u00a0?- run_length.\nencode WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\n12W1B12W3B24W1B14W\n\ndecode 12W1B12W3B24W1B14W\nWWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\ntrue .\n\n","human_summarization":"implement a run-length encoding and decoding system. The system takes a string of uppercase characters, compresses repeated characters by storing the length of the character run, and provides a function to reverse the compression. The output can be any format that can recreate the original input.","id":3014}
    {"lang_cluster":"Prolog","source_code":"\n\n:- use_module(library(simplex)).\n% tuples (name, weights, value).\nknapsack :-\n\tL = [(   beef, \t  3.8, \t36),\n\t     (   pork, \t  5.4, \t43),\n\t     (   ham, \t  3.6, \t90),\n\t     (   greaves, 2.4, \t45),\n\t     (   flitch,  4.0, \t30),\n\t     (   brawn,   2.5, \t56),\n\t     (   welt, \t  3.7, \t67),\n\t     (   salami,  3.0, \t95),\n\t     (   sausage, 5.9, \t98)],\n\n\t gen_state(S0),\n\t length(L, N),\n\t numlist(1, N, LN),\n\t (   (  create_constraint_N(LN, L, S0, S1, [], LW, [], LV),\n\t\tconstraint(LW =< 15.0, S1, S2),\n\t\tmaximize(LV, S2, S3)\n\t      )),\n\tcompute_lenword(L, 0, Len),\n\tsformat(A1, '~~w~~t~~~w|', [Len]),\n\tsformat(A2, '~~t~~2f~~~w|', [10]),\n\tsformat(A3, '~~t~~2f~~~w|', [10]),\n\tprint_results(S3, A1,A2,A3, L, LN, 0, 0).\n\n\ncreate_constraint_N([], [], S, S, LW, LW, LV, LV).\n\ncreate_constraint_N([HN|TN], [(_, W, V) | TL], S1, SF, LW, LWF, LV, LVF) :-\n\tconstraint([x(HN)] >= 0, S1, S2),\n\tconstraint([x(HN)] =< W, S2, S3),\n\tX is V\/W,\n\tcreate_constraint_N(TN, TL, S3, SF, [x(HN) | LW], LWF, [X * x(HN) | LV], LVF).\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\ncompute_lenword([], N, N).\ncompute_lenword([(Name, _, _)|T], N, NF):-\n\tatom_length(Name, L),\n\t(   L > N -> N1 = L; N1 = N),\n\tcompute_lenword(T, N1, NF).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nprint_results(_S, A1, A2, A3, [], [], WM, VM) :-\n\tsformat(W1, A1, [' ']),\n\tsformat(W2, A2, [WM]),\n\tsformat(W3, A3, [VM]),\n\tformat('~w~w~w~n', [W1,W2,W3]).\n\n\nprint_results(S, A1, A2, A3, [(Name, W, V)|T], [N|TN], W1, V1) :-\n\tvariable_value(S, x(N), X),\n\t(   X = 0 -> W1 = W2, V1 = V2\n\t;\n\t    sformat(S1, A1, [Name]),\n\t    sformat(S2, A2, [X]),\n\t    Vtemp is X * V\/W,\n\t    sformat(S3, A3, [Vtemp]),\n\t    format('~w~w~w~n', [S1,S2,S3]),\n\t    W2 is W1 + X,\n\t    V2 is V1 + Vtemp ),\n\tprint_results(S, A1, A2, A3, T, TN, W2, V2).\n\n\n\u00a0?- knapsack.\nham          3.60     90.00\ngreaves      2.40     45.00\nbrawn        2.50     56.00\nwelt         3.50     63.38\nsalami       3.00     95.00\n            15.00    349.38\ntrue .\n","human_summarization":"determine the optimal selection of items a thief can carry in his knapsack, given a weight limit of 15 kg. The items can be cut, with their value decreasing proportionally to their weight. The goal is to maximize the total value of the items in the knapsack. The items available, their weights and values are provided. The solution uses SWI-Prolog and the simplex library.","id":3015}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog version 5.10.0\n:- use_module(library( http\/http_open )).\n\nanagrams:-\n        % we read the URL of the words\n\thttp_open('http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt',\tIn, []),\n\tread_file(In, [], Out),\n\tclose(In),\n\n        % we get a list of pairs key-value where key = a-word value = <list-of-its-codes>\n        % this list must be sorted\n\tmsort(Out, MOut),\n\n        % in order to gather values with the same keys\n\tgroup_pairs_by_key(MOut, GPL),\n\n        % we sorted this list in decreasing order of the length of values\n\tpredsort(my_compare, GPL, GPLSort),\n\n\t% we extract the first 6 items \n        GPLSort = [_H1-T1, _H2-T2, _H3-T3, _H4-T4, _H5-T5, _H6-T6 | _],\n\n        % Tnn are lists of codes (97 for 'a'), we create the strings \n\tmaplist(maplist(atom_codes), L, [T1, T2, T3, T4, T5, T6] ),\n\n\tmaplist(writeln, L).\n\n\nread_file(In, L, L1) :-\n\tread_line_to_codes(In, W),\n\t(   W == end_of_file -> \n               % the file is read\n\t       L1 = L\n\t       ; \n               % we sort the list of codes of the line\n\t       msort(W, W1),\n\n               % to create the key in alphabetic order\n\t       atom_codes(A, W1), \n\n               % and we have the pair Key-Value in the result list\n\t       read_file(In, [A-W | L], L1)).\n\n% predicate for sorting list of pairs Key-Values\n% if the lentgh of values is the same\n% we sort the keys in alhabetic order\nmy_compare(R, K1-V1, K2-V2) :-\n\tlength(V1, L1),\n\tlength(V2, L2),\n\t(   L1 < L2 -> R = >; L1 > L2 -> R = <; compare(R, K1, K2)).\n\n\n[abel,able,bale,bela,elba]\n[caret,carte,cater,crate,trace]\n[angel,angle,galen,glean,lange]\n[alger,glare,lager,large,regal]\n[elan,lane,lean,lena,neal]\n[evil,levi,live,veil,vile]\ntrue\n","human_summarization":"find the largest sets of anagrams from the word list provided at http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt.","id":3016}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog\n\nmain:-\n    write_sierpinski_carpet('sierpinski_carpet.svg', 486, 4).\n\nwrite_sierpinski_carpet(File, Size, Order):-\n    open(File, write, Stream),\n    format(Stream,\n           \"<svg xmlns='http:\/\/www.w3.org\/2000\/svg' width='~d' height='~d'>\\n\",\n           [Size, Size]),\n    write(Stream, \"<rect width='100%' height='100%' fill='white'\/>\\n\"),\n    Side is Size\/3.0,\n    sierpinski_carpet(Stream, 0, 0, Side, Order),\n    write(Stream, \"<\/svg>\\n\"),\n    close(Stream).\n\nsierpinski_carpet(Stream, X, Y, Side, 0):-\n    !,\n    X0 is X + Side,\n    Y0 is Y + Side,\n    write_square(Stream, X0, Y0, Side).\nsierpinski_carpet(Stream, X, Y, Side, Order):-\n    Order1 is Order - 1,\n    Side1 is Side \/ 3.0,\n    X0 is X + Side,\n    Y0 is Y + Side,\n    X1 is X0 + Side,\n    Y1 is Y0 + Side,\n    write_square(Stream, X0, Y0, Side),\n    sierpinski_carpet(Stream, X, Y, Side1, Order1),\n    sierpinski_carpet(Stream, X0, Y, Side1, Order1),\n    sierpinski_carpet(Stream, X1, Y, Side1, Order1),\n    sierpinski_carpet(Stream, X, Y0, Side1, Order1),\n    sierpinski_carpet(Stream, X1, Y0, Side1, Order1),\n    sierpinski_carpet(Stream, X, Y1, Side1, Order1),\n    sierpinski_carpet(Stream, X0, Y1, Side1, Order1),\n    sierpinski_carpet(Stream, X1, Y1, Side1, Order1).\n\nwrite_square(Stream, X, Y, Side):-\n    format(Stream,\n           \"<rect fill='black' x='~g' y='~g' width='~g' height='~g'\/>\\n\",\n           [X, Y, Side, Side]).\n\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, specifically the '#' character. The program also produces an SVG format image file of the Sierpinski carpet.","id":3017}
    {"lang_cluster":"Prolog","source_code":"\n\nhuffman :-\n\tL = 'this is an example for huffman encoding',\n\tatom_chars(L, LA),\n\tmsort(LA, LS),\n\tpackList(LS, PL),\n\tsort(PL, PLS),\n\tbuild_tree(PLS, A),\n\tcoding(A, [], C),\n\tsort(C, SC),\n\tformat('Symbol~t   Weight~t~30|Code~n'),\n\tmaplist(print_code, SC).\n\nbuild_tree([[V1|R1], [V2|R2]|T], AF) :- \n\tV is V1 + V2, \n\tA = [V, [V1|R1], [V2|R2]],\n\t(   T=[] -> AF=A ;  sort([A|T], NT), build_tree(NT, AF) ).\n\ncoding([_A,FG,FD], Code, CF) :-\n\t(   is_node(FG) ->  coding(FG, [0 | Code], C1)\n\t\t\t ;  leaf_coding(FG, [0 | Code], C1) ),\n\t(   is_node(FD) ->  coding(FD, [1 | Code], C2)\n\t\t\t ;  leaf_coding(FD, [1 | Code], C2) ),\n\tappend(C1, C2, CF).\n\nleaf_coding([FG,FD], Code, CF) :-\n\treverse(Code, CodeR),\n\tCF = [[FG, FD, CodeR]] .\n\nis_node([_V, _FG, _FD]).\n\nprint_code([N, Car, Code]):-\n\tformat('~w\u00a0:~t~w~t~30|', [Car, N]),\n\tforall(member(V, Code), write(V)),\n\tnl.\n\npackList([], []).\npackList([X], [[1,X]]) :- !.\npackList([X|Rest], [XRun|Packed]):-\n    run(X, Rest, XRun, RRest),\n    packList(RRest, Packed).\n\nrun(V, [], [1,V], []).\nrun(V, [V|LRest], [N1,V], RRest):-\n    run(V, LRest, [N, V], RRest),\n    N1 is N + 1.\nrun(V, [Other|RRest], [1,V], [Other|RRest]):-\n    dif(V, Other).\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a priority queue with a leaf node for each character symbol based on their frequency of occurrence. It then constructs a binary tree by removing the two nodes with the highest priority (lowest probability) from the queue and creating a new internal node with these two nodes as children. This process continues until there is only one node left in the queue, which becomes the root node. The code then traverses the binary tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute the Huffman encoding for the corresponding symbol. The result is a table of Huffman encodings for each character in the string. The code is compatible with SWI-Prolog.","id":3018}
    {"lang_cluster":"Prolog","source_code":"\n\n:- dynamic click\/1.\n\ndialog('Simple windowed application',\n       [ object        :=\n\t   Simple_windowed_application,\n\t parts         :=\n\t   [ Simple_windowed_application :=\n\t       dialog('Simple windowed application'),\n\t     Name                       :=\n\t       label(name, 'There have been no clicks yet'),\n\t     BtnClick                     :=\n\t       button(button)\n\t   ],\n\t modifications :=\n\t   [ BtnClick := [ label := 'Click me\u00a0!'\n\t\t       ]\n\t   ],\n\t layout        :=\n\t   [ area(Name,\n\t\t  area(40, 20, 200, 18)),\n\t     area(BtnClick,\n\t\t  area(90, 60, 80, 24))\n\t   ],\n\t behaviour :=\n\t [\n\t  BtnClick := [message := message(@prolog, btnclick, Name)]\n\t ]\n       ]).\n\nbtnclick(Label) :-\n\tretract(click(V)),\n\tV1 is V+1,\n\tassert(click(V1)),\n\tsformat(A, '~w click(s)', [V1]),\n\tsend(Label, selection, A).\n\nsimple_windowed :-\n\tretractall(click(_)),\n\tassert(click(0)),\n\tmake_dialog(D, 'Simple windowed application'),\n\tsend(D, open).\n\n","human_summarization":"\"Implements a simple windowed application using SWI-Prolog and XPCE. The application features a window with a label displaying the text 'There have been no clicks yet' and a button labeled 'click me'. The label updates to show the number of times the button has been clicked each time the button is pressed.\"","id":3019}
    {"lang_cluster":"Prolog","source_code":"\n\nrfor(Hi,Lo,Hi)\u00a0:- Hi >= Lo.\nrfor(Hi,Lo,Val)\u00a0:- Hi > Lo, H is Hi - 1,\u00a0!, rfor(H,Lo,Val).\n\nreverse_iter\u00a0:-\n  rfor(10,0,Val), write(Val), nl, fail.\nreverse_iter.\n?- reverse_iter.\n10\n9\n8\n7\n6\n5\n4\n3\n2\n1\n0\ntrue.\n\n","human_summarization":"implement a for loop that counts down from 10 to 0 using Prolog, which doesn't have a built-in iterator for descending values.","id":3020}
    {"lang_cluster":"Prolog","source_code":"\n\nfor(Lo,Hi,Step,Lo) \u00a0:- Step>0, Lo=<Hi.\nfor(Lo,Hi,Step,Val)\u00a0:- Step>0, plus(Lo,Step,V), V=<Hi,\u00a0!, for(V,Hi,Step,Val).\n\nexample\u00a0:- \n  for(0,10,2,Val), write(Val), write(' '), fail.\nexample.\n?- example.\n0 2 4 6 8 10 \ntrue.\n\nfor(Hi,Lo,Step,Hi) \u00a0:- Step<0, Lo=<Hi.\nfor(Hi,Lo,Step,Val)\u00a0:- Step<0, plus(Hi,Step,V), Lo=<V,\u00a0!, for(V,Lo,Step,Val).\n","human_summarization":"demonstrate a for-loop with a step-value greater than one and also include a stepping iterator that allows backward iteration.","id":3021}
    {"lang_cluster":"Prolog","source_code":"\n\nxor_pattern :-\n\tnew(D, window('XOR Pattern')),\n\tsend(D, size, size(512,512)),\n\tnew(Img, image(@nil, width := 512, height := 512 , kind := pixmap)),\n\n\tforall(between(0,511, I),\n\t       (   forall(between(0,511, J),\n\t\t\t  (   V is I xor J,\n\t\t\t      R is (V * 1024) mod 65536,\n\t\t\t      G is (65536 - V * 1024) mod 65536,\n\t\t\t      (\t  V mod 2 =:= 0\n\t\t\t      ->  B is  (V * 4096) mod 65536\n\t\t\t      ;\t   B is  (65536 - (V * 4096)) mod 65536),\n\t\t\t      send(Img, pixel(I, J, colour(@default, R, G, B))))))),\n\n\tnew(Bmp, bitmap(Img)),\n\tsend(D, display, Bmp, point(0,0)),\n\tsend(D, open).\n\n\n","human_summarization":"The code generates a graphical pattern where each pixel's color is determined by the 'x xor y' value from a color table, using SWI-Prolog and its GUI XPCE for rendering munching squares.","id":3022}
    {"lang_cluster":"Prolog","source_code":"\n\n:- dynamic cell\/2.\n\nmaze(Lig,Col) :-\n\tretractall(cell(_,_)),\n\n\tnew(D, window('Maze')),\n\n\t% creation of the grid\n\tforall(between(0,Lig, I),\n\t       (XL is  50, YL is I * 30 + 50,\n\t\tXR is Col * 30 + 50,\n\t\tnew(L, line(XL, YL, XR, YL)),\n\t\tsend(D, display, L))),\n\n\tforall(between(0,Col, I),\n\t       (XT is  50 + I * 30, YT is 50,\n\t\tYB is Lig * 30 + 50,\n\t\tnew(L, line(XT, YT, XT, YB)),\n\t\tsend(D, display, L))),\n\n\tSX is Col * 30 + 100,\n\tSY is Lig * 30 + 100,\n\tsend(D, size, new(_, size(SX, SY))),\n\n\t% choosing a first cell\n\tL0 is random(Lig),\n\tC0 is random(Col),\n\tassert(cell(L0, C0)),\n\t\\+search(D, Lig, Col, L0, C0),\n\tsend(D, open).\n\nsearch(D, Lig, Col, L, C) :-\n\tDir is random(4),\n\tnextcell(Dir, Lig, Col, L, C, L1, C1),\n\tassert(cell(L1,C1)),\n\tassert(cur(L1,C1)),\n\terase_line(D, L, C, L1, C1),\n\tsearch(D, Lig, Col, L1, C1).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nerase_line(D, L, C, L, C1) :-\n\t(   C < C1 -> C2 = C1; C2 = C),\n\tXT is C2  * 30 + 50,\n\tYT is L * 30 + 51, YR is (L+1) * 30 + 50,\n\tnew(Line, line(XT, YT, XT, YR)),\n\tsend(Line, colour, white),\n\tsend(D, display, Line).\n\nerase_line(D, L, C, L1, C) :-\n\tXT is  51 + C * 30, XR is 50 + (C + 1) * 30,\n\t(   L < L1 -> L2 is L1; L2 is L),\n\tYT is L2 * 30 + 50,\n\tnew(Line, line(XT, YT, XR, YT)),\n\tsend(Line, colour, white),\n\tsend(D, display, Line).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nnextcell(Dir, Lig, Col, L, C, L1, C1) :-\n\tnext(Dir, Lig, Col, L, C, L1, C1);\n\t(   Dir1 is (Dir+3) mod 4,\n\t    next(Dir1, Lig, Col, L, C, L1, C1));\n\t(   Dir2 is (Dir+1) mod 4,\n\t    next(Dir2, Lig, Col, L, C, L1, C1));\n\t(   Dir3 is (Dir+2) mod 4,\n\t    next(Dir3, Lig, Col, L, C, L1, C1)).\n\n% 0 => northward\nnext(0, _Lig, _Col, L, C, L1, C) :-\n\tL > 0,\n\tL1 is L - 1,\n\t\\+cell(L1, C).\n\n% 1 => rightward\nnext(1, _Lig, Col, L, C, L, C1) :-\n\tC < Col - 1,\n\tC1 is C + 1,\n\t\\+cell(L, C1).\n\n% 2 => southward\nnext(2, Lig, _Col, L, C, L1, C) :-\n\tL < Lig - 1,\n\tL1 is L + 1,\n\t\\+cell(L1, C).\n\n% 3 => leftward\nnext(2, _Lig, _Col, L, C, L, C1) :-\n\tC > 0,\n\tC1 is C - 1,\n\t\\+cell(L, C1).\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. The process begins at a random cell, marks it as visited, and retrieves a list of its neighboring cells. For each neighbor, starting with a randomly selected one, if the neighbor hasn't been visited, the wall between the current cell and the neighbor is removed, and the process is recursively repeated with the neighbor as the current cell. The codes are compatible with SWI-Prolog and XPCE.","id":3023}
    {"lang_cluster":"Prolog","source_code":"\n\npi_spigot :-\n    pi(X),\n    forall(member(Y, X), write(Y)).\n\npi(OUT) :-\n    pi(1, 180, 60, 2, OUT).\n\npi(Q, R, T, I, OUT) :-\n    freeze(OUT,\n           (   OUT = [Digit | OUT_]\n           ->  U is 3 * (3 * I + 1) * (3 * I + 2),\n               Y is (Q * (27 * I - 12) + 5 * R) \/\/ (5 * T),\n               Digit is Y,\n               Q2 is 10 * Q * I * (2 * I - 1),\n               R2 is 10 * U * (Q * (5 * I - 2) + R - Y * T),\n               T2 is T * U,\n               I2 is I + 1,\n               pi(Q2, R2, T2, I2, OUT_)\n           ;   true)).\n\n","human_summarization":"The code continually calculates and outputs the next decimal digit of Pi, starting from 3.14159265. The process continues indefinitely until interrupted by the user. The code does not use built-in Pi constants but calculates Pi from scratch. It utilizes a coroutine with freeze\/2 predicate for this task.","id":3024}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog\n:- table ack\/3.\u00a0% memoization reduces the execution time of ack(4,1,X) from several\n               \u00a0% minutes to about one second on a typical desktop computer.\nack(0, N, Ans)\u00a0:- Ans is N+1.\nack(M, 0, Ans)\u00a0:- M>0, X is M-1, ack(X, 1, Ans).\nack(M, N, Ans)\u00a0:- M>0, N>0, X is M-1, Y is N-1, ack(M, Y, Ans2), ack(X, Ans2, Ans).\n\nack(0,N,s(N)).\nack(s(M),0,P):- ack(M,s(0),P).\nack(s(M),s(N),P):- ack(s(M),N,S), ack(M,S,P).\n\n% Peano's first axiom in Prolog is that s(0) AND s(s(N)):- s(N)\n% Thanks to this we don't need explicit N > 0 checks.\n% Nor explicit arithmetic operations like X is M-1.\n% Recursion and unification naturally decrement s(N) to N.\n% But: Prolog clauses are relations and cannot be replaced by their result, like functions.\n% Because of this we do need an extra argument to hold the output of the function.\n% And we also need an additional call to the function in the last clause.\n\n% Example input\/output:\n%\u00a0?- ack(s(0),s(s(0)),P).\n% P = s(s(s(s(0))))\u00a0;\n% false.\n","human_summarization":"The code implements the Ackermann function, a non-primitive recursive function. It takes two non-negative arguments and returns their Ackermann value. The function handles large numbers but doesn't necessarily require arbitrary precision.","id":3025}
    {"lang_cluster":"Prolog","source_code":"\n\ngamma_coefficients(\n     [ 1.00000000000000000000000,  0.57721566490153286060651, -0.65587807152025388107701,\n      -0.04200263503409523552900,  0.16653861138229148950170, -0.04219773455554433674820,\n      -0.00962197152787697356211,  0.00721894324666309954239, -0.00116516759185906511211,\n      -0.00021524167411495097281,  0.00012805028238811618615, -0.00002013485478078823865,\n      -0.00000125049348214267065,  0.00000113302723198169588, -0.00000020563384169776071,\n       0.00000000611609510448141,  0.00000000500200764446922, -0.00000000118127457048702,\n       0.00000000010434267116911,  0.00000000000778226343990, -0.00000000000369680561864,\n       0.00000000000051003702874, -0.00000000000002058326053, -0.00000000000000534812253,\n       0.00000000000000122677862, -0.00000000000000011812593,  0.00000000000000000118669,\n       0.00000000000000000141238, -0.00000000000000000022987,  0.00000000000000000001714\n    ]).\n\ntolerance(1e-17).\n\ngamma(X, _) :- X =< 0.0, !, fail.\ngamma(X, Y) :-\n    X < 1.0, small_gamma(X, Y), !.\ngamma(1, 1) :- !.\ngamma(1.0, 1) :- !.\ngamma(X, Y) :-\n    X1 is X - 1,\n    gamma(X1, Y1),\n    Y is X1 * Y1.\n    \nsmall_gamma(X, Y) :-\n    gamma_coefficients(Cs),\n    recip_gamma(X, 1.0, Cs, 1.0, 0.0, Y0),\n    Y is 1 \/ Y0.\n\nrecip_gamma(_, _, [], _, Y, Y) :- !.\nrecip_gamma(_, _, [], X0, X1, Y) :- tolerance(Tol), abs(X1 - X0) < Tol, Y = X1, !. % early exit\nrecip_gamma(X, PrevPow, [C|Cs], _, X1, Y) :-\n    Power is PrevPow * X,\n    X2 is X1 + C*Power,\n    recip_gamma(X, Power, Cs, X1, X2, Y).\n\n\n","human_summarization":"implement an algorithm to compute the Gamma function in the real field, comparing the results with built-in or library functions if available. The Gamma function is computed through numerical integration, with the Lanczos approximation and Stirling's approximation suggested for better efficiency. The accuracy of the computation is checked against Wolfram Alpha.","id":3026}
    {"lang_cluster":"Prolog","source_code":"\n\nsolution([]).\n \nsolution([X\/Y|Others]) :-\n solution(Others),\n member(Y, [1,2,3,4,5,6,7,8]),\n noattack(X\/Y, Others).\n \nnoattack(_,[]).\n \nnoattack(X\/Y,[X1\/Y1|Others]) :-\n Y =\\= Y1,\n Y1 - Y =\\= X1 - X,\n Y1 - Y =\\= X - X1,\n noattack(X\/Y,Others).\n \nmember(Item,[Item|Rest]).\n \nmember(Item,[First|Rest]) :-\n member(Item,Rest).\n \ntemplate([1\/Y1,2\/Y2,3\/Y3,4\/Y4,5\/Y5,6\/Y6,7\/Y7,8\/Y8]).\n\n\nsolution(Queens)\u00a0:-\n permutation([1,2,3,4,5,6,7,8], Queens),\n safe(Queens).\n \npermutation([],[]).\n \npermutation([Head|Tail],PermList)\u00a0:-\n permutation(Tail,PermTail),\n del(Head,PermList,PermTail).\n \ndel(Item,[Item|List],List).\n \ndel(Item,[First|List],[First|List1])\u00a0:-\n del(Item,List,List1).\n \nsafe([]).\n \nsafe([Queen|Others])\u00a0:-\n safe(Others),\n noattack(Queen,Others,1).\n \nnoattack(_,[],_).\n \nnoattack(Y,[Y1|Ylist],Xdist)\u00a0:-\n Y1-Y=\\=Xdist,\n Y-Y1=\\=Xdist,\n Dist1 is Xdist + 1,\n noattack(Y,Ylist,Dist1).\n\nsolution(Ylist)\u00a0:-\n sol(Ylist,[1,2,3,4,5,6,7,8],\n    [1,2,3,4,5,6,7,8],\n    [-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7],\n    [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]).\n \nsol([],[],[],Du,Dv).\n \nsol([Y|Ylist],[X|Dx1],Dy,Du,Dv)\u00a0:-\n del(Y,Dy,Dy1),\n U is X-Y,\n del(U,Du,Du1),\n V is X+Y,\n del(V,Dv,Dv1),\n sol(Ylist,Dx1, Dy1,Du1,Dv1).\n \ndel(Item,[Item|List],List).\n \ndel(Item,[First|List],[First|List1])\u00a0:-\n del(Item,List,List1).\n\n\u00a0\u00a0?- findall(S, solution(S), LS), length(LS,N), write(N).\n\u00a0 92\n\n\n:- initialization(main).\n\n\nqueens(N,Qs)\u00a0:- bagof(X, between(1,N,X), Xs), place(Xs,[],Qs).\n\nplace(Xs,Qs,Res)\u00a0:-\n    Xs = [] -> Res = Qs\n \u00a0; select(Q,Xs,Ys), not_diag(Q,Qs,1), place(Ys,[Q|Qs],Res)\n  .\n\nnot_diag(_, []     , _).\nnot_diag(Q, [Qh|Qs], D)\u00a0:-\n     abs(Q - Qh) =\\= D, D1 is D + 1, not_diag(Q,Qs,D1).\n\n\nmain\u00a0:- findall(Qs, (queens(8,Qs), write(Qs), nl), _), halt.\n\n\nWorks with: SWI Prolog version version 6.2.6 by Jan Wielemaker, University of Amsterdam\n% 8 queens problem.\n%  q(Row) represents a queen, allocated one per row. No rows ever clash.\n%  The columns are chosen iteratively from available columns held in a\n%  list, reduced with each allocation, so we need never check verticals.\n%  For diagonals, we check prior to allocation whether each newly placed\n%  queen will clash with any of the prior placements. This prevents\n%  most invalid permutations from ever being attempted.\ncan_place(_, [])\u00a0:-\u00a0!.\t  \u00a0% success for empty board\ncan_place(q(R,C),Board)\u00a0:-\u00a0% check diagonals against allocated queens\n\tmember(q(Ra,Ca), Board), abs(Ra-R) =:= abs(Ca-C),\u00a0!, fail.\ncan_place(_,_).           \u00a0% succeed if no diagonals failed\n\nqueens([], [], Board, Board).                           \u00a0% found a solution\nqueens([q(R)|Queens], Columns, Board, Solution)\u00a0:-\n\tnth0(_,Columns,C,Free), can_place(q(R,C),Board),\u00a0% find all solutions\n\tqueens(Queens,Free,[q(R,C)|Board], Solution).   \u00a0% recursively\n\nqueens\u00a0:-\n  findall(q(N), between(0,7,N), Queens), findall(N, between(0,7,N), Columns),\n  findall(B, queens(Queens, Columns, [], B), Boards),    \u00a0% backtrack over all\n  length(Boards, Len), writef('%w solutions:\\n', [Len]), \u00a0% Output solutions\n  member(R,Boards), reverse(R,Board), writef('  - %w\\n', [Board]), fail.\nqueens.\n\n","human_summarization":"solve the N-Queens problem, extending the traditional eight queens puzzle to a board of size NxN. It uses backtracking, a highly efficient mechanism in Prolog, to find all solutions. The code utilizes non-ISO predicates between\/3 and select\/3, and the CLP(FD): Constraint Logic Programming over Finite Domain Library. The code runs in SWI-Prolog 7.2.3 and v8.0.2, providing the number of solutions for small values of N.","id":3027}
    {"lang_cluster":"Prolog","source_code":"\n?- append([1,2,3],[4,5,6],R).\nR = [1, 2, 3, 4, 5, 6].\n","human_summarization":"demonstrate how to concatenate two arrays.","id":3028}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-Prolog\nLibrary: clpfd\n:- use_module(library(clpfd)).\n\nknapsack :-\n        L = [\n             item(map,  9,      150),\n             item(compass,      13,     35),\n             item(water,        153,    200),\n             item(sandwich, 50,         160),\n             item(glucose,      15,     60),\n             item(tin,  68,     45),\n             item(banana,       27,     60),\n             item(apple,        39,     40),\n             item(cheese,       23,     30),\n             item(beer,         52,     10),\n             item('suntan cream',       11,     70),\n             item(camera,       32,     30),\n             item('t-shirt',    24,     15),\n             item(trousers, 48,         10),\n             item(umbrella, 73,         40),\n             item('waterproof trousers',        42,     70),\n             item('waterproof overclothes',     43,     75),\n             item('note-case',22,       80),\n             item(sunglasses,   7,      20),\n             item(towel,        18,     12),\n             item(socks,        4,      50),\n             item(book,         30,     10 )],\n        length(L, N),\n        length(R, N),\n        R ins 0..1,\n        maplist(arg(2), L, LW),\n        maplist(arg(3), L, LV),\n        scalar_product(LW, R, #=<, 400),\n        scalar_product(LV, R, #=, VM),\n        labeling([max(VM)], R),\n        scalar_product(LW, R, #=, WM),\n        %% affichage des r\u00e9sultats\n        compute_lenword(L, 0, Len),\n        sformat(A1, '~~w~~t~~~w|', [Len]),\n        sformat(A2, '~~t~~w~~~w|', [4]),\n        sformat(A3, '~~t~~w~~~w|', [5]),\n        print_results(A1,A2,A3, L, R, WM, VM).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% to show the results in a good way\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\ncompute_lenword([], N, N).\ncompute_lenword([item(Name, _, _)|T], N, NF):-\n        atom_length(Name, L),\n        (   L > N -> N1 = L; N1 = N),\n        compute_lenword(T, N1, NF).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%\nprint_results(A1,A2,A3, [], [], WM, WR) :-\n        sformat(W1, A1, [' ']),\n        sformat(W2, A2, [WM]),\n        sformat(W3, A3, [WR]),\n        format('~w~w~w~n', [W1,W2,W3]).\n\n\nprint_results(A1,A2,A3, [_H|T], [0|TR], WM, VM) :-\n        print_results(A1,A2,A3, T, TR, WM, VM).\n\nprint_results(A1, A2, A3, [item(Name, W, V)|T], [1|TR], WM, VM) :-\n        sformat(W1, A1, [Name]),\n        sformat(W2, A2, [W]),\n        sformat(W3, A3, [V]),\n        format('~w~w~w~n', [W1,W2,W3]),\n        print_results(A1, A2, A3, T, TR, WM, VM).\n\n\n","human_summarization":"The code determines the optimal combination of items, with a maximum weight of 4kg, that a tourist can carry in his knapsack for a trip to maximize the total value. The items, their weights, and their importance values are given in a list. The solution does not allow for fractional items. The code uses a library written by Markus Triska and solves the problem in about 3 seconds.","id":3029}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI-PrologLibrary: XPCE\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% facts\nprefere(abe,[ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]).\nprefere(  bob,[ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]).\nprefere(  col,[ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]).\nprefere(  dan,[ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]).\nprefere(   ed,[ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]).\nprefere( fred,[ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]).\nprefere(  gav,[ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]).\nprefere(  hal,[ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]).\nprefere(  ian,[ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]).\nprefere(  jon,[ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]).\n\nprefere(  abi,[ bob, fred, jon, gav, ian, abe, dan, ed, col, hal]).\nprefere(  bea,[ bob, abe, col, fred, gav, dan, ian, ed, jon, hal]).\nprefere( cath,[ fred, bob, ed, gav, hal, col, ian, abe, dan, jon]).\nprefere(  dee,[ fred, jon, col, abe, ian, hal, gav, dan, bob, ed]).\nprefere(  eve,[ jon, hal, fred, dan, abe, gav, col, ed, ian, bob]).\nprefere(  fay,[ bob, abe, ed, ian, jon, dan, fred, gav, col, hal]).\nprefere(  gay,[ jon, gav, hal, fred, bob, abe, col, ed, dan, ian]).\nprefere( hope,[ gav, jon, bob, abe, ian, dan, hal, ed, col, fred]).\nprefere(  ivy,[ ian, col, hal, gav, fred, bob, abe, ed, jon, dan]).\nprefere(  jan,[ ed, hal, gav, abe, bob, jon, col, ian, fred, dan]).\n\n\nman(abe).\nman(bob).\nman(col).\nman(dan).\nman(ed).\nman(fred).\nman(gav).\nman(hal).\nman(ian).\nman(jon).\n\nwoman(abi).\nwoman(bea).\nwoman(cath).\nwoman(dee).\nwoman(eve).\nwoman(fay).\nwoman(gay).\nwoman(hope).\nwoman(ivy).\nwoman(jan).\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% rules\n\nstable_mariage :-\n\tnew(LstMan, chain),\n\tforall(man(X),\n\t       (   prefere(X, Lst),\n\t\t   new(P, man(X, Lst)),\n\t\t   send(LstMan, append, P))),\n\n\tnew(LstWoman, chain),\n\tforall(woman(X),\n\t       (   prefere(X, Lst),\n\t\t   new(P, woman(X, Lst)),\n\t\t   send(LstWoman, append, P))),\n\tsend(LstMan, for_all, message(@arg1, init_liste, LstWoman)),\n\tsend(LstWoman, for_all, message(@arg1, init_liste, LstMan)),\n\n\tround(LstMan, LstWoman),\n\tnew(LstCouple, chain),\n\t% creation of the couple.\n\tsend(LstWoman, for_all, and(message(@prolog, create_couple, @arg1, LstCouple),\n\t\t\t\t   message(@pce, write_ln, @arg1?name, with, @arg1?elu?name))),\n\n\tnl,\n\t\n\t% test of the stability of couples\n\tstability(LstCouple),\n\tnl,\n\n\t% Perturbation of couples\n\tget(LstCouple, size, Len),\n\tget_two_random_couples(Len, V1, V2),\n\n\tget(LstCouple, nth0, V1, C1),\n\tget(LstCouple, nth0, V2, C2),\n\tnew(NC1, tuple(C1?first, C2?second)),\n\tnew(NC2, tuple(C2?first, C1?second)),\n\tsend(LstCouple, nth0, V1, NC1),\n\tsend(LstCouple, nth0, V2, NC2),\n\n\tsend(@pce, write_ln, 'perturbation of couples'),\n\tsend(@pce, write_ln, NC1?second, with, NC1?first),\n\tsend(@pce, write_ln, NC2?second, with, NC2?first),\n\tnl,\n\t\n\tstability(LstCouple).\n\nget_two_random_couples(Len, C1, C2) :-\n\tC1 is random(Len),\n\trepeat,\n\tC2 is random(Len),\n\tC1 \\= C2.\n\ncreate_couple(Woman, LstCouple ) :-\n\tsend(LstCouple, append, new(_, tuple(Woman?elu?name, Woman?name))).\n\n% iterations of the algorithm\nround(LstMan, LstWoman) :-\n\tsend(LstMan, for_some, message(@arg1, propose)),\n\tsend(LstWoman, for_some, message(@arg1, dispose)),\n\t(   \\+send(LstWoman, for_all, @arg1?status == maybe)\n\t->\n\t    round(LstMan, LstWoman)\n\t;\n\t    true\n\t).\n\n:-pce_begin_class(person, object, \"description of a person\").\nvariable(name, object, both, \"name of the person\").\nvariable(preference, chain, both, \"list of priority\").\nvariable(status, object, both, \"statut of engagement\u00a0: maybe \/ free\").\n\ninitialise(P, Name, Pref) :->\n\tsend(P, send_super, initialise),\n\tsend(P, slot, name, Name),\n\tsend(P, slot, preference, Pref),\n\tsend(P, slot, status, free).\n\n% reception of the list of partners\ninit_liste(P, Lst) :->\n\t% we replace the list of name of partners\n\t% with the list of persons partners.\n\tnew(NLP, chain),\n\tget(P, slot, preference, LP),\n\tsend(LP, for_all, message(@prolog, find_person,@arg1, Lst, NLP)),\n\tsend(P, slot, preference, NLP).\n\n:- pce_end_class(person).\n\n\n\nfind_person(Name, LstPerson, LstPref) :-\n\tget(LstPerson, find, @arg1?name == Name, Elem),\n\tsend(LstPref, append, Elem).\n\n:-pce_begin_class(man, person, \"description of a man\").\n\ninitialise(P, Name, Pref) :->\n\tsend(P, send_super, initialise, Name, Pref).\n\n% a man propose \"la botte\" to a woman\npropose(P) :->\n\tget(P, slot, status, free),\n\tget(P, slot, preference, XPref),\n\tget(XPref, delete_head, Pref),\n\tsend(P, slot, preference, XPref),\n\tsend(Pref, proposition, P).\n\nrefuse(P) :->\n\tsend(P, slot, status, free).\n\naccept(P) :->\n\tsend(P, slot, status, maybe).\n\n:- pce_end_class(man).\n\n:-pce_begin_class(woman, person, \"description of a woman\").\nvariable(elu, object, both, \"name of the elu\").\nvariable(contact, chain, both, \"men that have contact this woman\").\n\ninitialise(P, Name, Pref) :->\n\tsend(P, send_super, initialise, Name, Pref),\n\tsend(P, slot, contact, new(_, chain)),\n\tsend(P, slot, elu, @nil).\n\n% a woman decide Maybe\/No\ndispose(P) :->\n\tget(P, slot, contact, Contact),\n\tget(P, slot, elu, Elu),\n\n\t(   Elu \\= @nil\n\t->\n\t    send(Contact, append, Elu)\n\t;\n\t    true),\n\n\tnew(R, chain),\n\tsend(Contact, for_all, message(P, fetch, @arg1, R)),\n\tsend(R, sort, ?(@arg1?first, compare, @arg2?first)),\n\tget(R, delete_head, Tete),\n\tsend(Tete?second, accept),\n\tsend(P, slot, status, maybe),\n\tsend(P, slot, elu, Tete?second),\n\tsend(R, for_some, message(@arg1?second, refuse)),\n\tsend(P, slot, contact, new(_, chain)) .\n\n\n% looking for the person of the given name  Contact\n% Adding it in the chain Chain\nfetch(P, Contact, Chain) :->\n\tget(P, slot, preference, Lst),\n\tget(Lst, find, @arg1?name == Contact?name, Elem),\n\tget(Lst, index, Elem, Ind),\n\tsend(Chain, append, new(_, tuple(Ind, Contact))).\n\n% a woman receive a proposition from a man\nproposition(P, Name) :->\n\tget(P, slot, contact, C),\n\tsend(C, append, Name),\n\tsend(P, slot, contact, C).\n\n:- pce_end_class(woman).\n\n% computation of the stability od couple\nstability(LstCouple) :-\n\tchain_list(LstCouple, LstPceCouple),\n\tmaplist(transform, LstPceCouple, PrologLstCouple),\n\tstudy_couples(PrologLstCouple, [], UnstableCouple),\n\t(   UnstableCouple = []\n\t->\n\t    writeln('Couples are stable')\n\t;\n\t    sort(UnstableCouple, SortUnstableCouple),\n\t    writeln('Unstable couples are'),\n\t    maplist(print_unstable_couple, SortUnstableCouple),\n\t    nl\n\t).\n\n\nprint_unstable_couple((C1, C2)) :-\n\tformat('~w and ~w~n', [C1, C2]).\n\ntransform(PceCouple, couple(First, Second)):-\n\tget(PceCouple?first, value, First),\n\tget(PceCouple?second, value, Second).\n\nstudy_couples([], UnstableCouple, UnstableCouple).\n\nstudy_couples([H | T], CurrentUnstableCouple, UnstableCouple):-\n\tinclude(unstable_couple(H), T, Lst),\n\t(   Lst \\= []\n\t->\n\t    maplist(build_one_couple(H), Lst, Lst1),\n\t    append(CurrentUnstableCouple, Lst1,CurrentUnstableCouple1)\n\t;\n\t    CurrentUnstableCouple1 = CurrentUnstableCouple\n\t),\n\tstudy_couples(T, CurrentUnstableCouple1, UnstableCouple).\n\n\nbuild_one_couple(C1, C2, (C1, C2)).\n\nunstable_couple(couple(X1, Y1), couple(X2, Y2)) :-\n\tprefere(X1, PX1),\n\tprefere(X2, PX2),\n\tprefere(Y1, PY1),\n\tprefere(Y2, PY2),\n\n\t% index of women for X1\n\tnth0(IY12, PX1, Y2),\n\tnth0(IY11, PX1, Y1),\n\t% index of men for Y2\n\tnth0(IX21, PY2, X1),\n\tnth0(IX22, PY2, X2),\n\n\t% index of women for X2\n\tnth0(IY21, PX2, Y1),\n\tnth0(IY22, PX2, Y2),\n\t% index of men for Y1\n\tnth0(IX11, PY1, X1),\n\tnth0(IX12, PY1, X2),\n\n\t% A couple is unstable\n\t( (IY12 < IY11 , IX21 < IX22);\n\t  (IY21 < IY22 , IX12 < IX11)).\n\n\n","human_summarization":"The code uses the Gale-Shapley algorithm to solve the Stable Marriage Problem. It takes as input preferences of ten males and ten females for potential partners. It then generates a stable set of engagements where no individual prefers someone else over their current partner. The code also perturbs this stable set to create an unstable set and checks its stability.","id":3030}
    {"lang_cluster":"Prolog","source_code":"\n\nshort_circuit :-\n\t(   a_or_b(true, true) -> writeln('==> true'); writeln('==> false')) , nl,\n\t(   a_or_b(true, false)-> writeln('==>  true'); writeln('==> false')) , nl,\n\t(   a_or_b(false, true)-> writeln('==> true'); writeln('==> false')) , nl,\n\t(   a_or_b(false, false)-> writeln('==> true'); writeln('==> false')) , nl,\n\t(   a_and_b(true, true)-> writeln('==> true'); writeln('==> false')) , nl,\n\t(   a_and_b(true, false)-> writeln('==>  true'); writeln('==> false')) , nl,\n\t(   a_and_b(false, true)-> writeln('==>  true'); writeln('==> false')) , nl,\n\t(   a_and_b(false, false)-> writeln('==>  true'); writeln('==> false')) .\n\n\na_and_b(X, Y) :-\n\tformat('a(~w) and b(~w)~n', [X, Y]),\n\t(   a(X), b(Y)).\n\na_or_b(X, Y) :-\n\tformat('a(~w) or b(~w)~n', [X, Y]),\n\t(   a(X); b(Y)).\n\na(X) :-\n\tformat('a(~w)~n', [X]),\n\tX.\n\nb(X) :-\n\tformat('b(~w)~n', [X]),\n\tX.\n\n\n","human_summarization":"The code defines two functions, 'a' and 'b', which both take and return the same boolean value and print their names when called. The code then calculates the values of two equations, 'x' and 'y', using short-circuit evaluation to ensure that function 'b' is only called when necessary. In the case that the language does not support short-circuit evaluation, nested 'if' statements are used to achieve the same result. The code is tested with SWI-Prolog and should work with other dialects.","id":3031}
    {"lang_cluster":"Prolog","source_code":"\n\n% convert text to morse\n% query text2morse(Text, Morse)\n% where\n% Text is string to convert\n% Morse is Morse representation\n% There is a space between chars and double space between words\n%\ntext2morse(Text, Morse) :-\n\tstring_lower(Text, TextLower),\t\t\t% rules are in lower case\n\tstring_chars(TextLower, Chars),\t\t\t% convert string into list of chars\n\tchars2morse(Chars, MorseChars),\t\t\t% convert each char into morse\n\tstring_chars(MorsePlusSpace, MorseChars),\t% append returned string list into single string\n\tstring_concat(Morse, ' ', MorsePlusSpace).\t% Remove trailing space\n\nchars2morse([], \"\").\nchars2morse([H|CharTail], Morse) :-\n\tmorse(H, M),\n\tchars2morse(CharTail, MorseTail),\n\tstring_concat(M,' ', MorseSpace),\n\tstring_concat(MorseSpace, MorseTail, Morse).\n\n% space\nmorse(' ', \" \").\n% letters\nmorse('a', \".-\").\nmorse('b', \"-...\").\nmorse('c', \"-.-.\").\nmorse('d', \"-..\").\nmorse('e', \".\").\nmorse('f', \"..-.\").\nmorse('g', \"--.\").\nmorse('h', \"....\").\nmorse('i', \"..\").\nmorse('j', \".---\").\nmorse('k', \"-.-\").\nmorse('l', \".-..\").\nmorse('m', \"--\").\nmorse('n', \"-.\").\nmorse('o', \"---\").\nmorse('p', \".--.\").\nmorse('q', \"--.-\").\nmorse('r', \".-.\").\nmorse('s', \"...\").\nmorse('t', \"-\").\nmorse('u', \"..-\").\nmorse('v', \"...-\").\nmorse('w', \".--\").\nmorse('x', \"-..-\").\nmorse('y', \"-.--\").\nmorse('z', \"--..\").\n% numbers\nmorse('1', \".----\").\nmorse('2', \"..---\").\nmorse('3', \"...--\").\nmorse('4', \"....-\").\nmorse('5', \".....\").\nmorse('6', \"-....\").\nmorse('7', \"--...\").\nmorse('8', \"---..\").\nmorse('9', \"----.\").\nmorse('0', \"-----\").\n% common punctuation\nmorse('.', \".-.-.-\").\nmorse(',', \"--..--\").\nmorse('\/', \"-..-.\").\nmorse('?', \"..--..\").\nmorse('=', \"-...-\").\nmorse('+', \".-.-.\").\nmorse('-', \"-....-\").\nmorse('@', \".--.-.\").\n\ntext2morse(\"Hello World\", Morse).\n\n\n","human_summarization":"The code converts a given string into audible Morse code and sends it to an audio device, such as a PC speaker. It either ignores or indicates unknown characters not included in the standard Morse code, possibly through a different pitch. The code is written in SWI Prolog, Edinburgh syntax.","id":3032}
    {"lang_cluster":"Prolog","source_code":"\n\nabc_problem :-\n\tmaplist(abc_problem, ['', 'A', bark, bOOk, treAT, 'COmmon', sQuaD, 'CONFUSE']).\n\n\nabc_problem(Word) :-\n\tL = [[b,o],[x,k],[d,q],[c,p],[n,a],[g,t],[r,e],[t,g],[q,d],[f,s],\n\t     [j,w],[h,u],[v,i],[a,n],[o,b],[e,r],[f,s],[l,y],[p,c],[z,m]],\n\n\t(   abc_problem(L, Word)\n\t->  format('~w OK~n', [Word])\n\t;   format('~w KO~n', [Word])).\n\nabc_problem(L, Word) :-\n\tatom_chars(Word, C_Words),\n\tmaplist(downcase_atom, C_Words, D_Words),\n\tcan_makeword(L, D_Words).\n\ncan_makeword(_L, []).\n\ncan_makeword(L, [H | T]) :-\n\t(   select([H, _], L, L1); select([_, H], L, L1)),\n\tcan_makeword(L1, T).\n\n\n","human_summarization":"The code is a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block has two letters and can only be used once. The function is case-insensitive and tests the functionality with seven different words. The code uses the CHR library and a module for composing predicates in SWI-Prolog.","id":3033}
    {"lang_cluster":"Prolog","source_code":"\nWorks with: SWI Prolog\nmain:-\n    sort_oid_list([\"1.3.6.1.4.1.11.2.17.19.3.4.0.10\",\n    \"1.3.6.1.4.1.11.2.17.5.2.0.79\",\n    \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\",\n    \"1.3.6.1.4.1.11150.3.4.0.1\",\n    \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\",\n    \"1.3.6.1.4.1.11150.3.4.0\"], Sorted_list),\n    foreach(member(oid(_, Oid), Sorted_list), writeln(Oid)).\n\nsort_oid_list(Oid_list, Sorted_list):-\n    parse_oid_list(Oid_list, Parsed),\n    sort(1, @=<, Parsed, Sorted_list).\n\nparse_oid_list([], []):-!.\nparse_oid_list([Oid|Oid_list], [oid(Numbers, Oid)|Parsed]):-\n    parse_oid(Oid, Numbers),\n    parse_oid_list(Oid_list, Parsed).\n\nparse_oid(Oid, Numbers):-\n    split_string(Oid, \".\", \".\", Strings),\n    number_strings(Numbers, Strings).\n\nnumber_strings([], []):-!.\nnumber_strings([Number|Numbers], [String|Strings]):-\n    number_string(Number, String),\n    number_strings(Numbers, Strings).\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":3034}
    {"lang_cluster":"Prolog","source_code":"\n\nstart(Port) :- socket('AF_INET',Socket),\n               socket_connect(Socket, 'AF_INET'(localhost,Port), Input, Output),\n               write(Output, 'hello socket world'),\n               flush_output(Output),\n               close(Output),\n               close(Input).\n\n","human_summarization":"The code opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket. It is compatible with Gnu Prolog and does not handle any exceptions or errors.","id":3035}
    {"lang_cluster":"Prolog","source_code":"\n\no(O) :- member(O, [0,1,2,3,4,5,6,7]).\n\noctal([O]) :- o(O).\noctal([A|B]) :- \n\toctal(O), \n\to(T), \n\tappend(O, [T], [A|B]),\n\tdif(A, 0).\n\t\noctalize :-\n\tforall(\n\t\toctal(X),\n\t\t(maplist(write, X), nl)\n\t).\n\n","human_summarization":"generate a sequence of octal numbers, starting from zero and incrementing by one each time. The sequence continues until the program is terminated or the maximum value of the numeric type in use is reached. Each octal number is printed on a separate line. The code also includes a function to validate if a number is a valid octal number.","id":3036}
    {"lang_cluster":"Prolog","source_code":"\nswap(A,B,B,A).\n\n?- swap(1,2,X,Y).\nX = 2,\nY = 1.\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.","id":3037}
    {"lang_cluster":"Prolog","source_code":"\n\npalindrome(Word)\u00a0:- name(Word,List), reverse(List,List).\n\nWorks with: SWI Prolog\npali(Str)\u00a0:- sub_string(Str, 0, 1, _, X), string_concat(Str2, X, Str), string_concat(X, Mid, Str2), pali(Mid).\npali(Str)\u00a0:- string_length(Str, Len), Len < 2.\n\nWorks with: GNU Prolog\npali(Str)\u00a0:- sub_atom(Str, 0, 1, _, X), atom_concat(Str2, X, Str), atom_concat(X, Mid, Str2), pali(Mid).\npali(Str)\u00a0:- atom_length(Str, Len), Len < 2.\n","human_summarization":"The code includes a function to check if a given sequence of characters is a palindrome. It supports Unicode characters and has an additional function to detect inexact palindromes, ignoring white-space, punctuation and case differences. It uses string reversal and can be tested using the 'Test a function' task. The code can also run on GNU Prolog when the string is changed into an atom.","id":3038}
    {"lang_cluster":"Prolog","source_code":"\n\n\u00a0?- getenv('TEMP', Temp).\n\n","human_summarization":"demonstrate how to retrieve a specific environment variable from the process's environment in SWI-Prolog using the built-in function getenv. The variables that can be accessed may differ based on the system, but commonly include PATH, HOME, and USER on Unix systems.","id":3039}
    {"lang_cluster":"Dart","source_code":"\nint fib(int n) {\n  if (n==0 || n==1) {\n    return n;\n  }\n  var prev=1;\n  var current=1;\n  for (var i=2; i<n; i++) {\n    var next = prev + current;\n    prev = current;\n    current = next;    \n  }\n  return current;\n}\n\nint fibRec(int n) => n==0 || n==1\u00a0? n\u00a0: fibRec(n-1) + fibRec(n-2);\n\nmain() {\n  print(fib(11));\n  print(fibRec(11));\n}\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":3040}
    {"lang_cluster":"Dart","source_code":"\n\nString reverse(String s) => new String.fromCharCodes(s.runes.toList().reversed);\n\n\nimport 'package:unittest\/unittest.dart';\n\nString reverse(String s) => new String.fromCharCodes(s.runes.toList().reversed);\n\nmain() {\n  group(\"Reverse a string -\", () {\n    test(\"Strings with ASCII characters are reversed correctly.\", () {\n      expect(reverse(\"hello, world\"), equals(\"dlrow ,olleh\"));\n    });\n    test(\"Strings with non-ASCII BMP characters are reversed correctly.\", () {\n      expect(reverse(\"\\u4F60\\u4EEC\\u597D\"), equals(\"\\u597D\\u4EEC\\u4F60\"));\n    });\n    test(\"Strings with non-BMP characters are reversed correctly.\", () {\n      expect(reverse(\"hello, \\u{1F310}\"), equals(\"\\u{1F310} ,olleh\"));\n    });\n  });\n}\n\n\n","human_summarization":"are designed to reverse a given string, including handling Unicode combining characters and UTF-16 surrogate pairs. The Dart language's \"runes\" feature is utilized to convert strings into sequences of Unicode code points, which can then be easily reversed to create new strings.","id":3041}
    {"lang_cluster":"Dart","source_code":"\nvoid main(){\n  \/\/Set Creation\n  Set A = new Set.from([1,2,3]);\n  Set B = new Set.from([1,2,3,4,5]);\n  Set C = new Set.from([1,2,4,5]);\n\t\n  print('Set A = $A');\n  print('Set B = $B');\n  print('Set C = $C');\n  print('');\n  \/\/Test if element is in set\n  int m = 3;\n  print('m = 5');\n  print('m in A = ${A.contains(m)}');\n  print('m in B = ${B.contains(m)}');\n  print('m in C = ${C.contains(m)}');\n  print('');\n  \/\/Union of two sets\n  Set AC = A.union(C);\n  print('Set AC = Union of A and C = $AC');\n  print('');\n  \/\/Intersection of two sets\n  Set A_C = A.intersection(C);\n  print('Set A_C = Intersection of A and C = $A_C');\n  print('');\n  \/\/Difference of two sets\n  Set A_diff_C = A.difference(C);\n  print('Set A_diff_C = Difference between A and C = $A_diff_C');\n  print('');\n  \/\/Test if set is subset of another set\n  print('A is a subset of B = ${B.containsAll(A)}');\n  print('C is a subset of B = ${B.containsAll(C)}');\n  print('A is a subset of C = ${C.containsAll(A)}');\n  print('');\n  \/\/Test if two sets are equal\n  print('A is equal to B  = ${B.containsAll(A) && A.containsAll(B)}');\n  print('B is equal to AC = ${B.containsAll(AC) && AC.containsAll(B)}');\n}\n\n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":3042}
    {"lang_cluster":"Dart","source_code":"\nquickSort(List a) {\n  if (a.length <= 1) {\n    return a;\n  }\n  \n  var pivot = a[0];\n  var less = [];\n  var more = [];\n  var pivotList = [];\n  \n  \/\/ Partition\n  a.forEach((var i){    \n    if (i.compareTo(pivot) < 0) {\n      less.add(i);\n    } else if (i.compareTo(pivot) > 0) {\n      more.add(i);\n    } else {\n      pivotList.add(i);\n    }\n  });\n  \n  \/\/ Recursively sort sublists\n  less = quickSort(less);\n  more = quickSort(more);\n  \n  \/\/ Concatenate results\n  less.addAll(pivotList);\n  less.addAll(more);\n  return less;\n}\n\nvoid main() {\n  var arr=[1,5,2,7,3,9,4,6,8];\n  print(\"Before sort\");\n  arr.forEach((var i)=>print(\"$i\"));\n  arr = quickSort(arr);\n  print(\"After sort\");\n  arr.forEach((var i)=>print(\"$i\"));\n}\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":3043}
    {"lang_cluster":"Dart","source_code":"\nmain(){\n\t\/\/ Dart uses Lists which dynamically resize by default\n\tfinal growable = [ 1, 2, 3 ];\n\n        \/\/ Add to the list using the add method\n\tgrowable.add(4);\n\n\tprint('growable: $growable');\n\n\t\/\/ You can pass an int to the constructor to create a fixed sized List\n\tfinal fixed = List(3);\n\t\n\t\/\/ We must assign each element individually using the Subscript operator\n\t\/\/ using .add would through an error\n\tfixed[0] = 'one';\n\tfixed[1] = 'two';\n\tfixed[2] = 'three';\n\n\tprint('fixed: $fixed');\n\n\t\/\/ If we want to create a fixed list all at once we can use the of constructor\n\t\/\/ Setting growable to false is what makes it fixed\n\tfinal fixed2 = List.of( [ 1.5, 2.5, 3.5 ], growable: false);\n\n\tprint('fixed2: $fixed2');\n\t\n\t\/\/ A potential gotcha involving the subscript operator [] might surprise JavaScripters\n\t\/\/ One cannot add new elements to a List using the subscript operator\n\t\/\/ We can only assign to existing elements, even if the List is growable\n\n\tfinal gotcha = [ 1, 2 ];\t\n\t\/\/ gotcha[2] = 3 would cause an error in Dart, but not in JavaScript\n\t\/\/ We must first add the new element using .add\n\tgotcha.add(3);\n\t\/\/ Now we can modify the existing elements with the subscript\n\tgotcha[2] = 4;\n\n\tprint('gotcha: $gotcha');\n\n\n}\n\n\n","human_summarization":"demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and includes the functionality of pushing a value into the array.","id":3044}
    {"lang_cluster":"Dart","source_code":"\nString capitalize(String string) {\n  if (string.isEmpty) {\n    return string;\n  }\n  return string[0].toUpperCase() + string.substring(1);\n}\n\nvoid main() {\n  var s = 'alphaBETA';\n  print('Original string: $s');\n  print('To Lower case:   ${s.toLowerCase()}');\n  print('To Upper case:   ${s.toUpperCase()}');\n  print('To Capitalize:   ${capitalize(s)}');\n}\n\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":3045}
    {"lang_cluster":"Dart","source_code":"\nString loopPlusHalf(start, end) {\n  var result = '';\n  for(int i = start; i <= end; i++) {\n    result += '$i';\n    if(i == end) {\n      break;\n    }\n    result += ', ';\n  }\n  return result;\n}\n\nvoid main() {\n  print(loopPlusHalf(1, 10));\n}\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":3046}
    {"lang_cluster":"Dart","source_code":"\nimport 'dart:math';\n\nfactors(n)\n{\n var factorsArr = [];\n factorsArr.add(n);\n factorsArr.add(1);\n for(var test = n - 1; test >= sqrt(n).toInt(); test--)\n  if(n\u00a0% test == 0)\n  {\n   factorsArr.add(test);\n   factorsArr.add(n \/ test);\n  }\n return factorsArr;\n}\n\nvoid main() {\n  print(factors(5688));\n}\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":3047}
    {"lang_cluster":"Dart","source_code":"\nmain() {\n    for (var i = 0; i < 5; i++)\n        for (var j = 0; j < i + 1; j++)\n            print(\"*\");\n        print(\"\\n\");\n}\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":3048}
    {"lang_cluster":"Dart","source_code":"\nmain() {\n\tvar rosettaCode = { \/\/ Type is inferred to be Map<String, String>\n\t\t'task': 'Associative Array Creation'\n\t};\n\n\trosettaCode['language'] = 'Dart';\n\n\t\/\/ The update function can be used to update a key using a callback\n\trosettaCode.update( 'is fun',  \/\/ Key to update\n\t\t(value) => \"i don't know\", \/\/ New value to use if key is present\n\t\tifAbsent: () => 'yes!' \/\/ Value to use if key is absent\n\t);\n\t\n\tassert( rosettaCode.toString() == '{task: Associative Array Creation, language: Dart, is fun: yes!}');\n\t\n\t\/\/ If we type the Map with dynamic keys and values, it is like a JavaScript object\n\tMap<dynamic, dynamic> jsObject = {\n\t\t'key': 'value',\n\t\t1: 2,\n\t\t1.5: [ 'more', 'stuff' ],\n\t\t#doStuff: () => print('doing stuff!') \/\/ #doStuff is a symbol, only one instance of this exists in the program. Would be :doStuff in Ruby\n\t};\n\n\tprint( jsObject['key'] );\n\tprint( jsObject[1] );\n\t\n\tfor ( var value in jsObject[1.5] )\n\t\tprint('item: $value');\n\n\tjsObject[ #doStuff ](); \/\/ Calling the function\n\t\n\tprint('\\nKey types:');\n\tjsObject.keys.forEach( (key) => print( key.runtimeType ) );\n}\n\n\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":3049}
    {"lang_cluster":"Dart","source_code":"\nint fact(int n) {\n  if(n<0) {\n    throw new IllegalArgumentException('Argument less than 0');\n  }\n  return n==0\u00a0? 1\u00a0: n*fact(n-1);\n}\n\nmain() {\n  print(fact(10));\n  print(fact(-1));\n}\nint fact(int n) {\n  if(n<0) {\n    throw new IllegalArgumentException('Argument less than 0');\n  }\n  int res=1;\n  for(int i=1;i<=n;i++) {\n    res*=i;\n  }\n  return res;\n}\n \nmain() {\n  print(fact(10));\n  print(fact(-1));\n}\n","human_summarization":"The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.","id":3050}
    {"lang_cluster":"Dart","source_code":"\nnum dot(List<num> A, List<num> B){\n  if (A.length != B.length){\n    throw new Exception('Vectors must be of equal size');\n  }\n  num result = 0;\n  for (int i = 0; i < A.length; i++){\n    result += A[i] * B[i];\n  }\n  return result;\n}\n\nvoid main(){\n  var l = [1,3,-5];\n  var k = [4,-2,-1];\n  print(dot(l,k));\n}\n\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":3051}
    {"lang_cluster":"Dart","source_code":"import 'dart:math';\nimport 'dart:io';\n\nmain() {\n  final n = (1 + new Random().nextInt(10)).toString();\n  print(\"Guess which number I've chosen in the range 1 to 10\");\n  do { stdout.write(\" Your guess\u00a0: \"); } while (n != stdin.readLineSync());\n  print(\"\\nWell guessed!\");\n}\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":3052}
    {"lang_cluster":"Dart","source_code":"\nString binary(int n) {\n  if(n<0)\n    throw new IllegalArgumentException(\"negative numbers require 2s complement\");\n  if(n==0) return \"0\";\n  String res=\"\";\n  while(n>0) {\n    res=(n%2).toString()+res;\n    n=(n\/2).toInt();\n  }\n  return res;\n}\n\nmain() {\n  print(binary(0));\n  print(binary(1));\n  print(binary(5));\n  print(binary(10));\n  print(binary(50));\n  print(binary(9000));\n  print(binary(65535));\n  print(binary(0xaa5511ff));\n  print(binary(0x123456789abcde));\n  \/\/ fails due to precision limit\n  print(binary(0x123456789abcdef));\n}\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":3053}
    {"lang_cluster":"Dart","source_code":"import 'dart:math';\n\nclass Haversine {\n  static final R = 6372.8; \/\/ In kilometers\n\n  static double haversine(double lat1, lon1, lat2, lon2) {\n    double dLat = _toRadians(lat2 - lat1);\n    double dLon = _toRadians(lon2 - lon1);\n    lat1 = _toRadians(lat1);\n    lat2 = _toRadians(lat2);\n    double a = pow(sin(dLat \/ 2), 2) + pow(sin(dLon \/ 2), 2) * cos(lat1) * cos(lat2);\n    double c = 2 * asin(sqrt(a));\n    return R * c;\n  }\n\n  static double _toRadians(double degree) {\n    return degree * pi \/ 180;\n  }\n\n  static void main() {\n    print(haversine(36.12, -86.67, 33.94, -118.40));\n  }\n}\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":3054}
    {"lang_cluster":"Dart","source_code":"\n\nimport 'dart:io';\nvoid main(){\n  var url = 'http:\/\/rosettacode.org';\n  var client = new HttpClient();\n  client.getUrl(Uri.parse(url))\n        .then((HttpClientRequest request)   => request.close())\n        .then((HttpClientResponse response) => response.pipe(stdout));\n}\n\n","human_summarization":"\"Code accesses and prints the content of a specified URL to the console using a stand-alone VM. Note: This does not cover HTTPS requests.\"","id":3055}
    {"lang_cluster":"Dart","source_code":"\nRegExp regexp = new RegExp(r'\\w+\\!');\n\nString capitalize(Match m) => '${m[0].substring(0, m[0].length-1).toUpperCase()}';\n\nvoid main(){\n  String hello = 'hello hello! world world!';\n  String hellomodified = hello.replaceAllMapped(regexp, capitalize);\n  print(hello);\n  print(hellomodified);\n}\n\n\n","human_summarization":"\"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression.\"","id":3056}
    {"lang_cluster":"Dart","source_code":"\nmain() { \n  moveit(from,to) {\n    print(\"move ${from} ---> ${to}\");\n  }\n\n  hanoi(height,toPole,fromPole,usePole) {\n    if (height>0) {\n      hanoi(height-1,usePole,fromPole,toPole);  \n      moveit(fromPole,toPole);\n      hanoi(height-1,toPole,usePole,fromPole);\n    }\n  }\n\n  hanoi(3,3,1,2);\n}\n\n\nmain() {\n  String say(String from, String to) => \"$from ---> $to\"; \n\n  hanoi(int height, int toPole, int fromPole, int usePole) {\n    if (height > 0) {\n      hanoi(height - 1, usePole, fromPole, toPole);  \n      print(say(fromPole.toString(), toPole.toString()));\n      hanoi(height - 1, toPole, usePole, fromPole);\n    }\n  }\n\n  hanoi(3, 3, 1, 2);\n}\n\n\n","human_summarization":"implement a recursive solution to solve the Towers of Hanoi problem, adhering to the style guide provided by dartlang.org and optionally including static type annotations.","id":3057}
    {"lang_cluster":"Dart","source_code":"\nvoid main() {\n    List<int> a = shellSort([1100, 2, 56, 200, -52, 3, 99, 33, 177, -199]);\n    print('$a');\n}\n\nshellSort(List<int> array) {\n\tint n = array.length;\n \n        \/\/ Start with a big gap, then reduce the gap\n        for (int gap = n~\/2; gap > 0; gap ~\/= 2)\n        {\n            \/\/ Do a gapped insertion sort for this gap size.\n            \/\/ The first gap elements a[0..gap-1] are already\n            \/\/ in gapped order keep adding one more element\n            \/\/ until the entire array is gap sorted\n            for (int i = gap; i < n; i += 1)\n            {\n                \/\/ add a[i] to the elements that have been gap\n                \/\/ sorted save a[i] in temp and make a hole at\n                \/\/ position i\n                int temp = array[i];\n \n                \/\/ shift earlier gap-sorted elements up until\n                \/\/ the correct location for a[i] is found\n                int j;\n                for (j = i; j >= gap && array[j - gap] > temp; j -= gap)\n                    array[j] = array[j - gap];\n \n                \/\/ put temp (the original a[i]) in its correct\n                \/\/ location\n                array[j] = temp;\n            }\n        }\n  return array;\n}\n\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. The algorithm, invented by Donald Shell in 1959, uses a diminishing increment sequence for interleaved insertion sorts. The increment size reduces with each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, which is the best case scenario for insertion sort. The algorithm works with any sequence that ends in 1, but sequences with a geometric increment ratio of about 2.2 have been found to be most effective.","id":3058}
    {"lang_cluster":"Dart","source_code":"\nLibrary: Flutter\n\nimport 'package:flutter\/material.dart';\nimport 'dart:async' show Timer;\n\nvoid main() {\n  \n  var timer = const Duration( milliseconds: 75 ); \/\/ How often to update i.e. how fast the animation is\n  \n  runApp(MaterialApp (\n    home: Scaffold (\n      body: Center (\n        child: AnimatedText( timer )\n      )\n    )\n  ));\n}\n\nclass AnimatedText extends StatefulWidget {\n  \n  final Duration period; \/\/ Time period for update\n  \n  AnimatedText( this.period );\n  @override\n  _AnimatedText createState() => _AnimatedText( period );\n}\n\n\nclass _AnimatedText extends State<AnimatedText> {\n  \n  bool forward = true; \/\/ Text should go forward?\n  \n  Timer timer; \/\/ Timer Objects allow us to do things based on a period of time\n  \/\/ We want to get an array of characters, but Dart does not have a char type\n  \/\/ Below is the equivalent code\n  var _text =  'Hello World!      '.runes \/\/ .runes gives us the unicode number of each character\n    .map( (code) => String.fromCharCode(code) ) \/\/ Map all these codes to Strings containing the single character\n    .toList(); \/\/ Conver to a List\n  \n  _AnimatedText( Duration period ){\n    timer = Timer.periodic( period , (_){\n      setState((){ \/\/ Set state forces the gui elements to be redrawn\n        shiftText();\n        \n      });  \n    });\n  }\n  \n  String get text => _text.join(''); \/\/ Getter, joins the list of chars into a string\n  \n  void shiftText() {\n    if (forward) { \/\/ If we should go forward\n      var last = _text.removeLast(); \/\/ Remove the last char\n\n      _text.insert( 0, last); \/\/ Insert it at the front\n      \n    } else { \/\/ If we should go backward\n      var first = _text.removeAt(0); \/\/ Remove the first char\n      \n      _text.insert( _text.length, first ); \/\/ Insert it at the end\n    }\n    \n }\n  \n  @override\n  Widget build(BuildContext context) {\n    return GestureDetector( \/\/ GestureDetector lets us capture events\n      onTap: () => forward = !forward, \/\/ on Tap (Click in browser) invert the forward bool\n      child: Text(\n        text, \/\/ Call the text getter to get the shifted string\n        style: TextStyle( \/\/ Styling\n          fontSize: 50,\n          color: Colors.grey[600]\n        )\n      )\n    \n    );   \n  }\n    \n}\n\n\nLibrary: Html Dom\nimport 'dart:html';\nimport 'dart:async';\n\nconst frameTime = const Duration(milliseconds: 100);\n\nvoid main() {\n  String text = \"Hello World! \";\n  bool rotateRight = true;\n\n  Element writeHere =\n      querySelector('#output'); \/\/ assumes you have a pre with that ID\n  writeHere.onClick.listen((event) => rotateRight = !rotateRight);\n\n  new Timer.periodic(frameTime, (_) {\n    text = changeText(text, rotateRight);\n    writeHere.text = text;\n  });\n}\n\nString changeText(extt, rotateRight) {\n  if (rotateRight) {\n    return extt.substring(extt.length - 1) + extt.substring(0, extt.length - 1);\n  } else {\n    return extt.substring(1) + extt.substring(0, 1);\n  }\n}\n\n","human_summarization":"Creates an animated GUI window displaying the text \"Hello World!\". The text appears to rotate right by periodically shifting the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":3059}
    {"lang_cluster":"Dart","source_code":"\nvoid main() {\n  int val = 0;\n  do {\n    val++;\n    print(val);\n  } while (val % 6 != 0);\n}\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":3060}
    {"lang_cluster":"Dart","source_code":"\nvoid main() {\n  String word = \"Premier League\";\n  print(\"Without first letter: ${word.substring(1)}\u00a0!\");\n  print(\"Without last letter: ${word.substring(0, word.length - 1)}\u00a0!\");\n  print(\"Without first and last letter: ${word.substring(1, word.length - 1)}\u00a0!\");\n}\n\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":3061}
    {"lang_cluster":"Dart","source_code":"\nimport 'dart:io';\n \nvoid main() {\n  stdout.write(\"Goodbye, World!\");\n}\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":3062}
    {"lang_cluster":"Dart","source_code":"\nLibrary: Flutter\n\nimport 'package:flutter\/material.dart';\n\nmain() => runApp( OutputLabel() );\n\nclass OutputLabel extends StatefulWidget {\n  @override\n  _OutputLabelState createState() => _OutputLabelState();\n}\n\nclass _OutputLabelState extends State<OutputLabel> {\n  String output = \"output\"; \/\/ This will be displayed in an output text field\n\n  TextEditingController _stringInputController = TextEditingController(); \/\/ Allows us to get the text from a text field \n  TextEditingController _numberInputController = TextEditingController();\n\n  @override\n  Widget build( BuildContext context ) {\n    return MaterialApp(\n      debugShowCheckedModeBanner: false, \/\/ Disable debug banner in top right\n      home: Scaffold ( \/\/ Scaffold provides a layout for the app\n        body: Center ( \/\/ Everything in the center widget will be centered\n          child: Column ( \/\/ All the widgets will be in a column\n            children: <Widget> [\n              SizedBox( height: 25 ), \/\/ Space between top and text field\n\n              TextField ( \/\/ String input Text Field\n                controller: _stringInputController, \/\/ Add input controller so we can grab text\n                textAlign: TextAlign.center, \/\/ Center text\n                decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Enter a string...'), \/\/ Border and default text\n              ), \/\/ end TextField\n\n              SizedBox( height: 10 ), \/\/ Space between text fields\n\n              TextField ( \/\/ Number input Text Field\n                controller: _numberInputController, \/\/ Add input controller so we can grab text\n                textAlign: TextAlign.center, \/\/ Center text\n                decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Enter 75000'), \/\/ Border and default text\n              ), \/\/ end TextField\n\n              FlatButton ( \/\/ Submit Button\n                child: Text('Submit Data'), \/\/ Button Text\n                color: Colors.blue[400] \/\/ button color\n                onPressed: () { \/\/ On pressed Callback for button\n                  setState( () {\n                    output = ''; \/\/ Reset output\n\n                    int number; \/\/ Int to store number in\n      \n                    var stringInput = _stringInputController.text ?? ''; \/\/ Get the input from the first field, if it is null set it to an empty string\n\n                    var numberString = _numberInputController.text ?? ''; \/\/ Get the input from the second field, if it is null set it to an empty string\n\n                    if ( stringInput == '')  { \/\/ If first field is empty\n                      output = 'Please enter something in field 1\\n';\n                      return;\n                    }\n\n                    if (_numberInputController.text == '') { \/\/ If second field is empty\n                      output += 'Please enter something in field 2';\n                      return;\n                    } else { \/\/ If we got an input in the second field\n\n                      try {\n                        number = int.parse( numberString ); \/\/ Parse numberString into an int\n\n                        if ( number == 75000 )\n                          output = 'text output: $stringInput\\nnumber: $number'; \/\/ Grabs the text from the input controllers and changes the string\n                        else\n                          output = '$number is not 75000!';\n\n                      } on FormatException { \/\/ If a number is not entered in second field\n                          output = '$numberString is not a number!';\n                      }\n\n                    }\n                    \n                  });\n                }   \n              ), \/\/ End FlatButton\n\n              Text( output ) \/\/ displays output\n\n            ]\n          )\n        )\n      )\n    );\n  }\n}\n\n","human_summarization":"The code enables the input of a string and the integer 75000 via a graphical user interface. It features two text fields, a button, and an output label. The code can be viewed on Dartpad.","id":3063}
    {"lang_cluster":"Dart","source_code":"\nclass Caesar {\n  int _key;\n\n  Caesar(this._key);\n\n  int _toCharCode(String s) {\n    return s.charCodeAt(0);\n  }\n\n  String _fromCharCode(int ch) {\n    return new String.fromCharCodes([ch]);\n  }\n\n  String _process(String msg, int offset) {\n    StringBuffer sb=new StringBuffer();\n    for(int i=0;i<msg.length;i++) {\n      int ch=msg.charCodeAt(i);\n      if(ch>=_toCharCode('A')&&ch<=_toCharCode('Z')) {\n        sb.add(_fromCharCode(_toCharCode(\"A\")+(ch-_toCharCode(\"A\")+offset)%26));\n      }\n      else if(ch>=_toCharCode('a')&&ch<=_toCharCode('z')) {\n        sb.add(_fromCharCode(_toCharCode(\"a\")+(ch-_toCharCode(\"a\")+offset)%26));\n      } else {\n        sb.add(msg[i]);\n      }\n    }\n    return sb.toString();\n  }\n\n  String encrypt(String msg) {\n    return _process(msg, _key);\n  }\n\n  String decrypt(String msg) {\n    return _process(msg, 26-_key);\n   }\n}\n\nvoid trip(String msg) {\n  Caesar cipher=new Caesar(10);\n\n  String enc=cipher.encrypt(msg);\n  String dec=cipher.decrypt(enc);\n  print(\"\\\"$msg\\\" encrypts to:\");\n  print(\"\\\"$enc\\\" decrypts to:\");\n  print(\"\\\"$dec\\\"\");\n  Expect.equals(msg,dec);\n}\n\nmain() {\n  Caesar c2=new Caesar(2);\n  print(c2.encrypt(\"HI\"));\n  Caesar c20=new Caesar(20);\n  print(c20.encrypt(\"HI\"));\n\n  \/\/ try a few roundtrips\n\n  trip(\"\");\n  trip(\"A\");\n  trip(\"z\");\n  trip(\"Caesar cipher\");\n  trip(\".-:\/\\\"\\\\!\");\n  trip(\"The Quick Brown Fox Jumps Over The Lazy Dog.\");\n}\n\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":3064}
    {"lang_cluster":"Dart","source_code":"\nmain() {\n\tint x=8;\n  int y=12;\nint z= gcd(x,y);\n  var lcm=(x*y)\/z;\n  print('$lcm');\n  }\n\nint gcd(int a,int b)\n{\n  if(b==0)\n    return a;\n  if(b!=0)\n    return gcd(b,a%b);\n}\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":3065}
    {"lang_cluster":"Dart","source_code":"\nmain() {\n  for (int i = 1; i <= 100; i++) {\n    List<String> out = [];\n    if (i\u00a0% 3 == 0)\n      out.add(\"Fizz\");\n    if (i\u00a0% 5 == 0)\n      out.add(\"Buzz\");\n    print(out.length > 0\u00a0? out.join(\"\")\u00a0: i);\n  }\n}\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":3066}
    {"lang_cluster":"Dart","source_code":"\n\nclass Complex {\n  double _r,_i;\n\n  Complex(this._r,this._i);\n  double get r => _r;\n  double get i => _i;\n  String toString() => \"($r,$i)\";\n\n  Complex operator +(Complex other) => new Complex(r+other.r,i+other.i);\n  Complex operator *(Complex other) =>\n      new Complex(r*other.r-i*other.i,r*other.i+other.r*i);\n  double abs() => r*r+i*i;\n}\n\nvoid main() {\n  double start_x=-1.5;\n  double start_y=-1.0;\n  double step_x=0.03;\n  double step_y=0.1;\n\n  for(int y=0;y<20;y++) {\n    String line=\"\";\n    for(int x=0;x<70;x++) {\n      Complex c=new Complex(start_x+step_x*x,start_y+step_y*y);\n      Complex z=new Complex(0.0, 0.0);\n      for(int i=0;i<100;i++) {\n        z=z*(z)+c;\n        if(z.abs()>2) {\n          break;\n        }\n      }\n      line+=z.abs()>2 ? \" \" : \"*\";\n    }\n    print(line);\n  }\n}\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. The code is implemented in Google Dart and operates on http:\/\/try.dartlang.org\/. It utilizes an incomplete Complex class that supports operator overloading. Note that due to the novelty of the language, the code may become obsolete in the future.","id":3067}
    {"lang_cluster":"Dart","source_code":"\nclass Leap {\n  bool leapYear(num year) {\n    return (year % 400 == 0) || (( year % 100 != 0) && (year % 4 == 0));\n\n  bool isLeapYear(int year) =>\n    (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0));\n  \/\/ Source: https:\/\/api.flutter.dev\/flutter\/quiver.time\/isLeapYear.html\n  }\n}\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":3068}
    {"lang_cluster":"Dart","source_code":"\nint M(int n) => n==0?1:n-F(M(n-1));\nint F(int n) => n==0?0:n-M(F(n-1));\n\nmain() {\n  String f=\"\",m=\"\";\n  for(int i=0;i<20;i++) {\n    m+=\"${M(i)} \";\n    f+=\"${F(i)} \";\n  }\n  print(\"M: $m\");\n  print(\"F: $f\");\n}\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":3069}
    {"lang_cluster":"Dart","source_code":"import 'dart:math';\n\nvoid main() {\n  final array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];\n  int i;\n\n  for (i = 1; i < 30; i++) {\n    var intValue = Random().nextInt(i) % 10;\n    print(array[intValue]);\n  }\n}\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":3070}
    {"lang_cluster":"Dart","source_code":"\nmain(List<String> args) {\n    for(var arg in args)\n        print(arg);\n}\n\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c \"alpha beta\" -h \"gamma\"'. It also includes functionalities for intelligent parsing of these arguments.","id":3071}
    {"lang_cluster":"Dart","source_code":"\nimport 'dart:convert' show jsonDecode, jsonEncode;\n\nmain(){\n\tvar json_string = '''\n\t{\n\t\t\"rosetta_code\": {\n\t\t\t\"task\": \"json\",\n\t\t\t\"language\": \"dart\",\n\t\t\t\"descriptions\": [ \"fun!\", \"easy to learn!\", \"awesome!\" ]\n\t\t}\n\t}\n\t''';\n\t\n\t\/\/ decode string into Map<String, dynamic>\n\tvar json_object = jsonDecode(json_string);\n\t\n\tfor ( var description in json_object[\"rosetta_code\"][\"descriptions\"] )\n\t\tprint( \"dart is $description\" );\n\n\tvar dart = {\n\t\t\"compiled\": true,\n\t\t\"interpreted\": true,\n\t\t\"creator(s)\":[ \"Lars Bak\", \"Kasper Lund\"],\n\t\t\"development company\": \"Google\"\n\t};\n\n\tvar as_json_text = jsonEncode(dart);\n\n\tassert(as_json_text == '{\"compiled\":true,\"interpreted\":true,\"creator(s)\":[\"Lars Bak\",\"Kasper Lund\"],\"development company\":\"Google\"}');\n}\n\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":3072}
    {"lang_cluster":"Dart","source_code":"\nvoid main() {\n  for (var i = 10; i >= 0; --i) {\n    print(i);\n  }\n}\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":3073}
    {"lang_cluster":"Dart","source_code":"\nmain() {\n  for (int i = 1; i <= 21; i += 2) print(i);\n}\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":3074}
    {"lang_cluster":"Dart","source_code":"\n\nint A(int m, int n) => m==0 ? n+1 : n==0 ? A(m-1,1) : A(m-1,A(m,n-1));\n\nmain() {\n  print(A(0,0));\n  print(A(1,0));\n  print(A(0,1));\n  print(A(2,2));\n  print(A(2,3));\n  print(A(3,3));\n  print(A(3,4));\n  print(A(3,5));\n  print(A(4,0));\n}\n\n","human_summarization":"Implement the Ackermann function, a non-primitive recursive function that takes two non-negative arguments and returns a rapidly growing value. The function should ideally support arbitrary precision due to its fast growth rate, but it's not mandatory. The function does not utilize caching, resulting in longer execution times for larger inputs.","id":3075}
    {"lang_cluster":"Dart","source_code":"\n\/**\nReturn true if queen placement q[n] does not conflict with\nother queens q[0] through q[n-1]\n*\/\nisConsistent(List q, int n) {\n  for (int i=0; i<n; i++) {\n    if (q[i] == q[n]) {\n      return false; \/\/ Same column\n    }\n    \n    if ((q[i] - q[n]) == (n - i)) {\n      return false; \/\/ Same major diagonal\n    }\n    \n    if ((q[n] - q[i]) == (n - i)) {\n      return false; \/\/ Same minor diagonal\n    }\n  }\n  \n  return true;\n}\n\n\/**\nPrint out N-by-N placement of queens from permutation q in ASCII. \n*\/\nprintQueens(List q) {\n  int N = q.length;\n  for (int i=0; i<N; i++) {\n    StringBuffer sb = new StringBuffer();\n    for (int j=0; j<N; j++) {\n      if (q[i] == j) {\n        sb.write(\"Q \");\n      } else {\n        sb.write(\"* \");\n      }\n    }\n    print(sb.toString());\n  }\n  print(\"\");\n}\n\n\/**\nTry all permutations using backtracking\n*\/\nenumerate(int N) {\n  var a = new List(N);\n  _enumerate(a, 0);\n}\n\n_enumerate(List q, int n) {\n  if (n == q.length) {\n    printQueens(q);\n  } else {\n    for (int i = 0; i < q.length; i++) {\n      q[n] = i;\n      if (isConsistent(q, n)){\n        _enumerate(q, n+1);\n      }\n    } \n  }\n}\n\nvoid main() {\n  enumerate(4);\n}\n\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":3076}
    {"lang_cluster":"Dart","source_code":"\nList solveKnapsack(items, maxWeight) {\n  int MIN_VALUE=-100;\n  int N = items.length; \/\/ number of items \n  int W = maxWeight; \/\/ maximum weight of knapsack\n  \n  List profit = new List(N+1);\n  List weight = new List(N+1);\n  \n  \/\/ generate random instance, items 1..N\n  for(int n = 1; n<=N; n++) {\n    profit[n] = items[n-1][2];\n    weight[n] = items[n-1][1];\n    \n  }\n  \n  \/\/ opt[n][w] = max profit of packing items 1..n with weight limit w\n  \/\/ sol[n][w] = does opt solution to pack items 1..n with weight limit w include item n?\n  List<List<int>> opt = new List<List<int>>(N+1);\n  for (int i=0; i<N+1; i++) {\n    opt[i] = new List<int>(W+1);\n    for(int j=0; j<W+1; j++) {\n      opt[i][j] = MIN_VALUE;\n    }\n  }\n  \n  List<List<bool>> sol = new List<List<bool>>(N+1);\n  for (int i=0; i<N+1; i++) {\n    sol[i] = new List<bool>(W+1);\n    for(int j=0; j<W+1; j++) {\n      sol[i][j] = false;\n    }\n  }\n  \n  for(int n=1; n<=N; n++) {\n    for (int w=1; w <= W; w++) {\n      \/\/ don't take item n      \n      int option1 = opt[n-1][w];\n      \n      \/\/ take item n\n      int option2 = MIN_VALUE;\n      if (weight[n] <= w) {\n        option2 = profit[n] + opt[n-1][w - weight[n]];\n      }\n            \n      \/\/ select better of two options\n      opt[n][w] = Math.max(option1, option2);\n      sol[n][w] = (option2 > option1);\n    }\n  }\n  \n  \/\/ determine which items to take\n  List<List> packItems = new List<List>();\n  List<bool> take = new List(N+1);\n  for (int n = N, w = W; n > 0; n--) {\n    if (sol[n][w]) {\n      take[n] = true;\n      w = w - weight[n];\n      packItems.add(items[n-1]); \n    } else {\n      take[n] = false; \n    }\n  }\n    \n  return packItems;\n  \n}\n\nmain() {\n  List knapsackItems = [];\n  knapsackItems.add([\"map\", 9, 150]);\n  knapsackItems.add([\"compass\", 13, 35]);\n  knapsackItems.add([\"water\", 153, 200]);\n  knapsackItems.add([\"sandwich\", 50, 160]);\n  knapsackItems.add([\"glucose\", 15, 60]);\n  knapsackItems.add([\"tin\", 68, 45]);\n  knapsackItems.add([\"banana\", 27, 60]);\n  knapsackItems.add([\"apple\", 39, 40]);\n  knapsackItems.add([\"cheese\", 23, 30]);\n  knapsackItems.add([\"beer\", 52, 10]);\n  knapsackItems.add([\"suntan cream\", 11, 70]);\n  knapsackItems.add([\"camera\", 32, 30]);\n  knapsackItems.add([\"t-shirt\", 24, 15]);\n  knapsackItems.add([\"trousers\", 48, 10]);\n  knapsackItems.add([\"umbrella\", 73, 40]);\n  knapsackItems.add([\"waterproof trousers\", 42, 70]);\n  knapsackItems.add([\"waterproof overclothes\", 43, 75]);\n  knapsackItems.add([\"note-case\", 22, 80]);\n  knapsackItems.add([\"sunglasses\", 7, 20]);\n  knapsackItems.add([\"towel\", 18, 12]);\n  knapsackItems.add([\"socks\", 4, 50]);\n  knapsackItems.add([\"book\", 30, 10]);\n  int maxWeight = 400;\n  Stopwatch sw = new Stopwatch.start();\n  List p = solveKnapsack(knapsackItems, maxWeight);\n  sw.stop();\n  int totalWeight = 0;\n  int totalValue = 0;\n  print([\"item\",\"profit\",\"weight\"]);\n  p.forEach((var i) { print(\"${i}\"); totalWeight+=i[1]; totalValue+=i[2]; });\n  print(\"Total Value = ${totalValue}\");\n  print(\"Total Weight = ${totalWeight}\");\n  print(\"Elapsed Time = ${sw.elapsedInMs()}ms\");\n  \n}\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":3077}
    {"lang_cluster":"Dart","source_code":"\nbool isPalindrome(String s){  \n  for(int i = 0; i < s.length\/2;i++){\n    if(s[i]\u00a0!= s[(s.length-1) -i])\n      return false;        \n  }  \n  return true;  \n}\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":3078}
    {"lang_cluster":"Dart","source_code":"int F(int n, int x, int y) {\n  if (n == 0) {\n    return x + y;\n  } else if (y == 0) {\n    return x;\n  }\n\n  return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y);\n}\n\nvoid main() {\n  print('F(1,3,3) = ${F(1, 3, 3)}');\n}\n\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.","id":3079}
    {"lang_cluster":"D","source_code":"\n\nimport std.array;\n\nclass Stack(T) {\n    private T[] items;\n\n    @property bool empty() { return items.empty(); }\n\n    void push(T top) { items ~= top; }\n\n    T pop() {\n        if (this.empty)\n            throw new Exception(\"Empty Stack.\");\n        auto top = items.back;\n        items.popBack();\n        return top;\n    }\n}\n\nvoid main() {\n    auto s = new Stack!int();\n    s.push(10);\n    s.push(20);\n    assert(s.pop() == 20);\n    assert(s.pop() == 10);\n    assert(s.empty());\n}\n\n","human_summarization":"Implement a stack class supporting basic operations such as push (adding an element to the top of the stack), pop (removing and returning the topmost element), and empty (checking if the stack is empty). The stack follows a last in, first out (LIFO) access policy.","id":3080}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio, std.conv, std.algorithm, std.math;\n\nlong sgn(alias unsignedFib)(int n) { \/\/ break sign manipulation apart\n    immutable uint m = (n >= 0)\u00a0? n\u00a0: -n;\n    if (n < 0 && (n\u00a0% 2 == 0))\n        return -unsignedFib(m);\n    else\n        return unsignedFib(m);\n}\n\nlong fibD(uint m) { \/\/ Direct Calculation, correct for abs(m) <= 84\n    enum sqrt5r =  1.0L \/ sqrt(5.0L);         \/\/  1 \/ sqrt(5)\n    enum golden = (1.0L + sqrt(5.0L)) \/ 2.0L; \/\/ (1 + sqrt(5)) \/ 2\n    return roundTo!long(pow(golden, m) * sqrt5r);\n}\n\nlong fibI(in uint m) pure nothrow { \/\/ Iterative\n    long thisFib = 0;\n    long nextFib = 1;\n    foreach (i; 0 .. m) {\n        long tmp = nextFib;\n        nextFib += thisFib;\n        thisFib  = tmp;\n    }\n    return thisFib;\n}\n\nlong fibR(uint m) { \/\/ Recursive\n    return (m < 2)\u00a0? m\u00a0: fibR(m - 1) + fibR(m - 2);\n}\n\nlong fibM(uint m) { \/\/ memoized Recursive\n    static long[] fib = [0, 1];\n    while (m >= fib.length )\n        fib ~= fibM(m - 2) + fibM(m - 1);\n    return fib[m];\n}\n\nalias sgn!fibD sfibD;\nalias sgn!fibI sfibI;\nalias sgn!fibR sfibR;\nalias sgn!fibM sfibM;\n\nauto fibG(in int m) { \/\/ generator(?)\n    immutable int sign = (m < 0)\u00a0? -1\u00a0: 1;\n    long yield;\n    \n    return new class {\n        final int opApply(int delegate(ref int, ref long) dg) {\n            int idx = -sign; \/\/ prepare for pre-increment\n            foreach (f; this)\n                if (dg(idx += sign, f))\n                    break;\n            return 0;\n        }\n        \n        final int opApply(int delegate(ref long) dg) {\n            long f0, f1 = 1;\n            foreach (p; 0 .. m * sign + 1) {\n                if (sign == -1 && (p\u00a0% 2 == 0))\n                    yield = -f0;\n                else\n                    yield = f0;\n                if (dg(yield)) break;\n                auto temp = f1;\n                f1 = f0 + f1;\n                f0 = temp;\n            }\n            return 0;\n        }\n    };\n}\n\nvoid main(in string[] args) {\n    int k = args.length > 1\u00a0? to!int(args[1])\u00a0: 10;\n    writefln(\"Fib(%3d) = \", k);\n    writefln(\"D\u00a0: %20d <- %20d + %20d\",\n             sfibD(k), sfibD(k - 1), sfibD(k - 2));\n    writefln(\"I\u00a0: %20d <- %20d + %20d\",\n             sfibI(k), sfibI(k - 1), sfibI(k - 2));\n    if (abs(k) < 36 || args.length > 2)\n        \/\/ set a limit for recursive version\n        writefln(\"R\u00a0: %20d <- %20d + %20d\",\n                 sfibR(k), sfibM(k - 1), sfibM(k - 2));\n    writefln(\"O\u00a0: %20d <- %20d + %20d\",\n             sfibM(k), sfibM(k - 1), sfibM(k - 2));\n    foreach (i, f; fibG(-9))\n        writef(\"%d:%d | \", i, f);\n}\n\n","human_summarization":"The code includes four versions of functions to calculate the nth Fibonacci number, supporting both positive and negative inputs. The traditional recursive approach is optimized with static storage for intermediate results. The functions have a limit of 84 for FibD due to floating point precision, and 92 for the others due to long overflow. The code performs faster than the matrix exponentiation version for large inputs.","id":3081}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.algorithm: filter, equal;\n\n    immutable data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n    auto evens = data.filter!(x => x % 2 == 0); \/\/ Lazy.\n    assert(evens.equal([2, 4, 6, 8, 10]));\n}\n\nLibrary: Tango\nimport tango.core.Array, tango.io.Stdout;\n\nvoid main() {\n    auto array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\n\n    \/\/ removeIf places even elements at the beginnig of the array and returns number of found evens\n    auto evens = array.removeIf( ( typeof(array[0]) i ) { return (i % 2) == 1; } );\n    Stdout(\"Evens - \")( array[0 .. evens] ).newline; \/\/ The order of even elements is preserved\n    Stdout(\"Odds - \")( array[evens .. $].sort ).newline; \/\/ Unlike odd elements\n}\n\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":3082}
    {"lang_cluster":"D","source_code":"\nWorks with: D version 2\nimport std.stdio, std.string;\n\nvoid main() {\n    const s = \"the quick brown fox jumps over the lazy dog\";\n    enum n = 5, m = 3;\n\n    writeln(s[n .. n + m]);\n\n    writeln(s[n .. $]);\n\n    writeln(s[0 .. $ - 1]);\n\n    const i = s.indexOf(\"q\");\n    writeln(s[i .. i + m]);\n\n    const j = s.indexOf(\"qu\");\n    writeln(s[j .. j + m]);\n}\n\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":3083}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n\timport std.range, std.conv;\n\n\tstring s1 = \"hello\"; \/\/ UTF-8\n\tassert(s1.retro.text == \"olleh\");\n\n\twstring s2 = \"hello\"w; \/\/ UTF-16\n\tassert(s2.retro.wtext == \"olleh\"w);\n\n\tdstring s3 = \"hello\"d; \/\/ UTF-32\n\tassert(s3.retro.dtext == \"olleh\"d);\n\n\t\/\/ without using std.range:\n\tdstring s4 = \"hello\"d;\n\tassert(s4.dup.reverse == \"olleh\"d); \/\/ simple but inefficient (copies first, then reverses)\n}\n\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":3084}
    {"lang_cluster":"D","source_code":"import std.stdio, std.array, std.algorithm, std.range, std.ascii,\n       std.conv, std.string, std.regex, std.typecons;\n\nstring unique(in string s) pure nothrow @safe {\n    string result;\n    foreach (immutable char c; s)\n        if (!result.representation.canFind(c)) \/\/ Assumes ASCII string.\n            result ~= c;\n    return result;\n}\n\nstruct Playfair {\n    string from, to;\n    string[string] enc, dec;\n\n    this(in string key, in string from_ = \"J\", in string to_ = null)\n    pure \/*nothrow @safe*\/ {\n        this.from = from_;\n        if (to_.empty)\n            this.to = (from_ == \"J\") ? \"I\" : \"\";\n\n        immutable m = _canonicalize(key ~ uppercase)\n                      .unique\n                      .chunks(5)\n                      .map!text\n                      .array;\n        auto I5 = 5.iota;\n\n        foreach (immutable R; m)\n            foreach (immutable i, immutable j; cartesianProduct(I5, I5))\n                if (i != j)\n                    enc[[R[i], R[j]]] = [R[(i + 1) % 5], R[(j+1) % 5]];\n\n        foreach (immutable r; I5) {\n            immutable c = m.transversal(r).array;\n            foreach (immutable i, immutable j; cartesianProduct(I5, I5))\n                if (i != j)\n                    enc[[c[i], c[j]]] = [c[(i + 1) % 5], c[(j+1) % 5]];\n        }\n\n        foreach (i1, j1, i2, j2; cartesianProduct(I5, I5, I5, I5))\n            if (i1 != i2 && j1 != j2)\n                enc[[m[i1][j1], m[i2][j2]]] = [m[i1][j2], m[i2][j1]];\n\n        dec = enc.byKeyValue.map!(t => tuple(t.value, t.key)).assocArray;\n    }\n\n    private string _canonicalize(in string s) const pure @safe {\n        return s.toUpper.removechars(\"^A-Z\").replace(from, to);\n    }\n\n    string encode(in string s) const \/*pure @safe*\/ {\n        return _canonicalize(s)\n               .matchAll(r\"(.)(?:(?!\\1)(.))?\")\n               .map!(m => enc[m[0].leftJustify(2, 'X')])\n               .join(' ');\n    }\n\n    string decode(in string s) const pure @safe {\n        return _canonicalize(s).chunks(2).map!(p => dec[p.text]).join(' ');\n    }\n}\n\nvoid main() \/*@safe*\/ {\n    \/*immutable*\/ const pf = Playfair(\"Playfair example\");\n    immutable orig = \"Hide the gold in...the TREESTUMP!!!\";\n    writeln(\"Original: \", orig);\n    immutable enc = pf.encode(orig);\n    writeln(\" Encoded: \", enc);\n    writeln(\" Decoded: \", pf.decode(enc));\n}\n\n\n","human_summarization":"Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.","id":3085}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.typecons, std.algorithm, std.container;\n\nalias Vertex = string;\nalias Weight = int;\n\nstruct Neighbor {\n    Vertex target;\n    Weight weight;\n}\n\nalias AdjacencyMap = Neighbor[][Vertex];\n\npure dijkstraComputePaths(Vertex source, Vertex target, AdjacencyMap adjacencyMap){\n    Weight[Vertex] minDistance;\n    Vertex[Vertex] previous;\n\n    foreach(v, neighs; adjacencyMap){\n        minDistance[v] = Weight.max;\n        foreach(n; neighs) minDistance[n.target] = Weight.max;\n    }\n\n    minDistance[source] = 0;\n    auto vertexQueue = redBlackTree(tuple(minDistance[source], source));\n\n    foreach(_, u; vertexQueue){\n        if (u == target)\n            break;\n\n        \/\/ Visit each edge exiting u.\n        foreach(n; adjacencyMap.get(u, null)){\n            const v = n.target;\n            const distanceThroughU = minDistance[u] + n.weight;\n            if(distanceThroughU < minDistance[v]){\n                vertexQueue.removeKey(tuple(minDistance[v], v));\n                minDistance[v] = distanceThroughU;\n                previous[v] = u;\n                vertexQueue.insert(tuple(minDistance[v], v));\n            }\n        }\n    }\n\n    return tuple(minDistance, previous);\n}\n\npure dijkstraGetShortestPathTo(Vertex v, Vertex[Vertex] previous){\n    Vertex[] path = [v];\n\n    while (v in previous) {\n        v = previous[v];\n        if (v == path[$ - 1])\n            break;\n        path ~= v;\n    }\n\n    path.reverse();\n    return path;\n}\n\nvoid main() {\n    immutable arcs = [tuple(\"a\", \"b\", 7),\n                      tuple(\"a\", \"c\", 9),\n                      tuple(\"a\", \"f\", 14),\n                      tuple(\"b\", \"c\", 10),\n                      tuple(\"b\", \"d\", 15),\n                      tuple(\"c\", \"d\", 11),\n                      tuple(\"c\", \"f\", 2),\n                      tuple(\"d\", \"e\", 6),\n                      tuple(\"e\", \"f\", 9)];\n\n    AdjacencyMap adj;\n    foreach (immutable arc; arcs) {\n        adj[arc[0]] ~= Neighbor(arc[1], arc[2]);\n        \/\/ Add this if you want an undirected graph:\n        \/\/adj[arc[1]] ~= Neighbor(arc[0], arc[2]);\n    }\n\n    const minDist_prev = dijkstraComputePaths(\"a\", \"e\", adj);\n    const minDistance = minDist_prev[0];\n    const previous = minDist_prev[1];\n\n    writeln(`Distance from \"a\" to \"e\": `, minDistance[\"e\"]);\n    writeln(\"Path: \", dijkstraGetShortestPathTo(\"e\", previous));\n}\n\n\n","human_summarization":"Implement Dijkstra's algorithm to find the shortest path from a single source to all other vertices in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges depicting the shortest path to each reachable node from the start node. The program also interprets the output to display the shortest path from the start node to specific nodes.","id":3086}
    {"lang_cluster":"D","source_code":"import std.stdio, std.algorithm;\n\nclass AVLtree {\n    private Node* root;\n\n    private static struct Node {\n        private int key, balance;\n        private Node* left, right, parent;\n\n        this(in int k, Node* p) pure nothrow @safe @nogc {\n            key = k;\n            parent = p;\n        }\n    }\n\n    public bool insert(in int key) pure nothrow @safe {\n        if (root is null)\n            root = new Node(key, null);\n        else {\n            Node* n = root;\n            Node* parent;\n            while (true) {\n                if (n.key == key)\n                    return false;\n\n                parent = n;\n\n                bool goLeft = n.key > key;\n                n = goLeft ? n.left : n.right;\n\n                if (n is null) {\n                    if (goLeft) {\n                        parent.left = new Node(key, parent);\n                    } else {\n                        parent.right = new Node(key, parent);\n                    }\n                    rebalance(parent);\n                    break;\n                }\n            }\n        }\n        return true;\n    }\n\n    public void deleteKey(in int delKey) pure nothrow @safe @nogc {\n        if (root is null)\n            return;\n        Node* n = root;\n        Node* parent = root;\n        Node* delNode = null;\n        Node* child = root;\n\n        while (child !is null) {\n            parent = n;\n            n = child;\n            child = delKey >= n.key ? n.right : n.left;\n            if (delKey == n.key)\n                delNode = n;\n        }\n\n        if (delNode !is null) {\n            delNode.key = n.key;\n\n            child = n.left !is null ? n.left : n.right;\n\n            if (root.key == delKey) {\n                root = child;\n            } else {\n                if (parent.left is n) {\n                    parent.left = child;\n                } else {\n                    parent.right = child;\n                }\n                rebalance(parent);\n            }\n        }\n    }\n\n    private void rebalance(Node* n) pure nothrow @safe @nogc {\n        setBalance(n);\n\n        if (n.balance == -2) {\n            if (height(n.left.left) >= height(n.left.right))\n                n = rotateRight(n);\n            else\n                n = rotateLeftThenRight(n);\n\n        } else if (n.balance == 2) {\n            if (height(n.right.right) >= height(n.right.left))\n                n = rotateLeft(n);\n            else\n                n = rotateRightThenLeft(n);\n        }\n\n        if (n.parent !is null) {\n            rebalance(n.parent);\n        } else {\n            root = n;\n        }\n    }\n\n    private Node* rotateLeft(Node* a) pure nothrow @safe @nogc {\n        Node* b = a.right;\n        b.parent = a.parent;\n\n        a.right = b.left;\n\n        if (a.right !is null)\n            a.right.parent = a;\n\n        b.left = a;\n        a.parent = b;\n\n        if (b.parent !is null) {\n            if (b.parent.right is a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node* rotateRight(Node* a) pure nothrow @safe @nogc {\n        Node* b = a.left;\n        b.parent = a.parent;\n\n        a.left = b.right;\n\n        if (a.left !is null)\n            a.left.parent = a;\n\n        b.right = a;\n        a.parent = b;\n\n        if (b.parent !is null) {\n            if (b.parent.right is a) {\n                b.parent.right = b;\n            } else {\n                b.parent.left = b;\n            }\n        }\n\n        setBalance(a, b);\n\n        return b;\n    }\n\n    private Node* rotateLeftThenRight(Node* n) pure nothrow @safe @nogc {\n        n.left = rotateLeft(n.left);\n        return rotateRight(n);\n    }\n\n    private Node* rotateRightThenLeft(Node* n) pure nothrow @safe @nogc {\n        n.right = rotateRight(n.right);\n        return rotateLeft(n);\n    }\n\n    private int height(in Node* n) const pure nothrow @safe @nogc {\n        if (n is null)\n            return -1;\n        return 1 + max(height(n.left), height(n.right));\n    }\n\n    private void setBalance(Node*[] nodes...) pure nothrow @safe @nogc {\n        foreach (n; nodes)\n            n.balance = height(n.right) - height(n.left);\n    }\n\n    public void printBalance() const @safe {\n        printBalance(root);\n    }\n\n    private void printBalance(in Node* n) const @safe {\n        if (n !is null) {\n            printBalance(n.left);\n            write(n.balance, ' ');\n            printBalance(n.right);\n        }\n    }\n}\n\nvoid main() @safe {\n    auto tree = new AVLtree();\n\n    writeln(\"Inserting values 1 to 10\");\n    foreach (immutable i; 1 .. 11)\n        tree.insert(i);\n\n    write(\"Printing balance: \");\n    tree.printBalance;\n}\n\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.","id":3087}
    {"lang_cluster":"D","source_code":"import std.stdio, std.typecons, std.math;\n\nclass ValueException : Exception {\n    this(string msg_) pure { super(msg_); }\n}\n\nstruct V2 { double x, y; }\nstruct Circle { double x, y, r; }\n\n\/**Following explanation at:\nhttp:\/\/mathforum.org\/library\/drmath\/view\/53027.html\n*\/\nTuple!(Circle, Circle)\ncirclesFromTwoPointsAndRadius(in V2 p1, in V2 p2, in double r)\npure in {\n    assert(r >= 0, \"radius can't be negative\");\n} body {\n    enum nBits = 40;\n\n    if (r.abs < (1.0 \/ (2.0 ^^ nBits)))\n        throw new ValueException(\"radius of zero\");\n\n    if (feqrel(p1.x, p2.x) >= nBits &&\n        feqrel(p1.y, p2.y) >= nBits)\n        throw new ValueException(\"coincident points give\" ~\n                                 \" infinite number of Circles\");\n\n    \/\/ Delta between points.\n    immutable d = V2(p2.x - p1.x, p2.y - p1.y);\n\n    \/\/ Distance between points.\n    immutable q = sqrt(d.x ^^ 2 + d.y ^^ 2);\n    if (q > 2.0 * r)\n        throw new ValueException(\"separation of points > diameter\");\n\n    \/\/ Halfway point.\n    immutable h = V2((p1.x + p2.x) \/ 2, (p1.y + p2.y) \/ 2);\n\n    \/\/ Distance along the mirror line.\n    immutable dm = sqrt(r ^^ 2 - (q \/ 2) ^^ 2);\n\n    return typeof(return)(\n        Circle(h.x - dm * d.y \/ q, h.y + dm * d.x \/ q, r.abs),\n        Circle(h.x + dm * d.y \/ q, h.y - dm * d.x \/ q, r.abs));\n}\n\nvoid main() {\n    foreach (immutable t; [\n                 tuple(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 2.0),\n                 tuple(V2(0.0000, 2.0000), V2(0.0000, 0.0000), 1.0),\n                 tuple(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 2.0),\n                 tuple(V2(0.1234, 0.9876), V2(0.8765, 0.2345), 0.5),\n                 tuple(V2(0.1234, 0.9876), V2(0.1234, 0.9876), 0.0)]) {\n        writefln(\"Through points:\\n  %s   %s  and radius %f\\n\" ~\n                 \"You can construct the following circles:\", t[]);\n        try {\n            writefln(\"  %s\\n  %s\\n\",\n                     circlesFromTwoPointsAndRadius(t[])[]);\n        } catch (ValueException v)\n            writefln(\"  ERROR: %s\\n\", v.msg);\n    }\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":3088}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.range, std.algorithm;\n\n\/\/\/ Rotate uint left.\nuint rol(in uint x, in uint nBits) @safe pure nothrow @nogc {\n    return (x << nBits) | (x >> (32 - nBits));\n}\n\nalias Nibble = ubyte; \/\/ 4 bits used.\nalias SBox = immutable Nibble[16][8];\n\nprivate bool _validateSBox(in SBox data) @safe pure nothrow @nogc {\n    foreach (const ref row; data)\n        foreach (ub; row)\n            if (ub >= 16) \/\/ Verify it's a nibble.\n                return false;\n    return true;\n}\n\nstruct GOST(s...) if (s.length == 1 && s[0]._validateSBox) {\n    private static generate(ubyte k)() @safe pure nothrow {\n        return k87.length.iota\n               .map!(i=> (s[0][k][i >> 4] << 4) | s[0][k - 1][i & 0xF])\n               .array;\n    }\n\n    private uint[2] buffer;\n    private static immutable ubyte[256] k87 = generate!7,\n                                        k65 = generate!5,\n                                        k43 = generate!3,\n                                        k21 = generate!1;\n\n    \/\/ Endianess problems?\n    private static uint f(in uint x) pure nothrow @nogc @safe {\n        immutable uint y = (k87[(x >> 24) & 0xFF] << 24) |\n                           (k65[(x >> 16) & 0xFF] << 16) |\n                           (k43[(x >>  8) & 0xFF] <<  8) |\n                            k21[ x        & 0xFF];\n        return rol(y, 11);\n    }\n\n    \/\/ This performs only a step of the encoding.\n    public void mainStep(in uint[2] input, in uint key)\n    pure nothrow @nogc @safe {\n        buffer[0] = f(key + input[0]) ^ input[1];\n        buffer[1] = input[0];\n    }\n}\n\nvoid main() {\n    \/\/ S-boxes used by the Central Bank of Russian Federation:\n    \/\/ http:\/\/en.wikipedia.org\/wiki\/GOST_28147-89\n    \/\/ (This is a matrix of nibbles).\n    enum SBox cbrf = [\n      [ 4, 10,  9,  2, 13,  8,  0, 14,  6, 11,  1, 12,  7, 15,  5,  3],\n      [14, 11,  4, 12,  6, 13, 15, 10,  2,  3,  8,  1,  0,  7,  5,  9],\n      [ 5,  8,  1, 13, 10,  3,  4,  2, 14, 15, 12,  7,  6,  0,  9, 11],\n      [ 7, 13, 10,  1,  0,  8,  9, 15, 14,  4,  6, 12, 11,  2,  5,  3],\n      [ 6, 12,  7,  1,  5, 15, 13,  8,  4, 10,  9, 14,  0,  3, 11,  2],\n      [ 4, 11, 10,  0,  7,  2,  1, 13,  3,  6,  8,  5,  9, 12, 15, 14],\n      [13, 11,  4,  1,  3, 15,  5,  9,  0, 10, 14,  7,  6,  8,  2, 12],\n      [ 1, 15, 13,  0,  5,  7, 10,  4,  9,  2,  3, 14,  6, 11,  8, 12]];\n\n    GOST!cbrf g;\n\n    \/\/ Example from the talk page (bytes swapped for endianess):\n    immutable uint[2] input = [0x_04_3B_04_21, 0x_04_32_04_30];\n    immutable uint key = 0x_E2_C1_04_F9;\n\n    g.mainStep(input, key);\n    writefln(\"%(%08X\u00a0%)\", g.buffer);\n}\n\n\n","human_summarization":"Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.","id":3089}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.random;\n\nvoid main() {\n    while (true) {\n        int r = uniform(0, 20);\n        write(r, \" \");\n        if (r == 10)\n            break;\n        write(uniform(0, 20), \" \");\n    }\n}\n\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":3090}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.math, std.traits;\n\nulong mersenneFactor(in ulong p) pure nothrow @nogc {\n    static bool isPrime(T)(in T n) pure nothrow @nogc {\n        if (n < 2 || n % 2 == 0)\n            return n == 2;\n        for (Unqual!T i = 3; i ^^ 2 <= n; i += 2)\n            if (n % i == 0)\n                return false;\n        return true;\n    }\n\n    static ulong modPow(in ulong cb, in ulong ce,in ulong m)\n    pure nothrow @nogc {\n        ulong b = cb;\n        ulong result = 1;\n        for (ulong e = ce; e > 0; e >>= 1) {\n            if ((e & 1) == 1)\n                result = (result * b) % m;\n            b = (b ^^ 2) % m;\n        }\n        return result;\n    }\n\n    immutable ulong limit = p <= 64 ? cast(ulong)(real(2.0) ^^ p - 1).sqrt : uint.max; \/\/ prevents silent overflows\n    for (ulong k = 1; (2 * p * k + 1) < limit; k++) {\n        immutable ulong q = 2 * p * k + 1;\n        if ((q % 8 == 1 || q % 8 == 7) && isPrime(q) && \n            modPow(2, p, q) == 1)\n            return q;\n    }\n    return 1; \/\/ returns a sensible smallest factor\n}\n\nvoid main() {\n    writefln(\"Factor of M929: %d\", 929.mersenneFactor);\n}\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":3091}
    {"lang_cluster":"D","source_code":"\n\nLibrary: KXML\nimport kxml.xml;\nchar[]xmlinput =\n\"<inventory title=\\\"OmniCorp Store #45x10^3\\\">\n  <section name=\\\"health\\\">\n    <item upc=\\\"123456789\\\" stock=\\\"12\\\">\n      <name>Invisibility Cream<\/name>\n      <price>14.50<\/price>\n      <description>Makes you invisible<\/description>\n    <\/item>\n    <item upc=\\\"445322344\\\" stock=\\\"18\\\">\n      <name>Levitation Salve<\/name>\n      <price>23.99<\/price>\n      <description>Levitate yourself for up to 3 hours per application<\/description>\n    <\/item>\n  <\/section>\n  <section name=\\\"food\\\">\n    <item upc=\\\"485672034\\\" stock=\\\"653\\\">\n      <name>Blork and Freen Instameal<\/name>\n      <price>4.95<\/price>\n      <description>A tasty meal in a tablet; just add water<\/description>\n    <\/item>\n    <item upc=\\\"132957764\\\" stock=\\\"44\\\">\n      <name>Grob winglets<\/name>\n      <price>3.56<\/price>\n      <description>Tender winglets of Grob. Just add water<\/description>\n    <\/item>\n  <\/section>\n<\/inventory>\n\";\nvoid main() {\n        auto root = readDocument(xmlinput);\n        auto firstitem = root.parseXPath(\"inventory\/section\/item\")[0];\n        foreach(price;root.parseXPath(\"inventory\/section\/item\/price\")) {\n                std.stdio.writefln(\"%s\",price.getCData);\n        }\n        auto namearray = root.parseXPath(\"inventory\/section\/item\/name\");\n}\n\n","human_summarization":"The code retrieves the first \"item\" element, prints out each \"price\" element, and creates an array of all the \"name\" elements from an XML document representing an inventory of OmniCorp Store. Note that the KXML library used for this task has limited XPath support.","id":3092}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.algorithm, std.range;\n\n    \/\/ Not true sets, items can be repeated, but must be sorted.\n    auto s1 = [1, 2, 3, 4, 5, 6].assumeSorted;\n    auto s2 = [2, 5, 6, 3, 4, 8].sort(); \/\/ [2,3,4,5,6,8].\n    auto s3 = [1, 2, 5].assumeSorted;\n\n    assert(s1.canFind(4)); \/\/ Linear search.\n    assert(s1.contains(4)); \/\/ Binary search.\n    assert(s1.setUnion(s2).equal([1,2,2,3,3,4,4,5,5,6,6,8]));\n    assert(s1.setIntersection(s2).equal([2, 3, 4, 5, 6]));\n    assert(s1.setDifference(s2).equal([1]));\n    assert(s1.setSymmetricDifference(s2).equal([1, 8]));\n    assert(s3.setDifference(s1).empty); \/\/ It's a subset.\n    assert(!s1.equal(s2));\n\n    auto s4 = [[1, 4, 7, 8], [1, 7], [1, 7, 8], [4], [7]];\n    const s5 = [1, 1, 1, 4, 4, 7, 7, 7, 7, 8, 8];\n    assert(s4.nWayUnion.equal(s5));\n}\n ==D==\nmodule set;\nimport std.typecons : Tuple, tuple;\nstruct Set(V) { \/\/ Limited set of V-type elements                                        \/\/ here 'this' is named A, s is B, v V-type item\n\nprotected V[] array;\n\n\tthis(const Set s) {                                                              \/\/ construct A by copy of B\n\t\tarray = s.array.dup;\n\t}\n\n\tthis(V[] arg...){                                                                \/\/ construct A with items\n\t\tforeach(v; arg) if (v.isNotIn(array)) array ~= v;\n\t}\n\n\tenum : Set { empty = Set() }                                                     \/\/ \u2205\n\n\tref Set opAssign()(const Set s) {                                                \/\/ A = B\n\t\tarray = s.array.dup;\n\t\treturn this;\n\t}\n\n\tbool opBinaryRight(string op : \"in\")(const V v) const {                          \/\/ v \u2208 A\n\t\treturn v.isIn(array);\n\t}\n\n\tref Set opOpAssign(string op)(const V v) if (op == \"+\" || op == \"|\") {           \/\/ A += {v}          \/\/ + = \u222a = |\n\t\tif (v.isIn(array)) return this;\n\t\tarray ~= v;\n\t\treturn this;\n\t}\n\n\tref Set opOpAssign(string op)(const Set s) if (op == \"+\" || op == \"|\") {         \/\/ A += B\n\t\tforeach(x; s.array) if (x.isNotIn(array)) array ~= x;\n\t\treturn this;\n\t}\n\n\tSet opBinary(string op)(const V v) const if (op == \"+\" || op == \"|\"){            \/\/ A + {v}\n\t\tSet result = this;\n\t\tresult += v;\n\t\treturn result;\n\t}\n\n\tSet opBinaryRight(string op)(const V v) const if (op == \"+\" || op == \"|\") {      \/\/ {v} + A\n\t\tSet result = this;\n\t\tresult += v;\n\t\treturn result;\n\t}\n\n\tSet opBinary(string op)(const Set s) const if (op == \"+\" || op == \"|\") {         \/\/ A + B\n\t\tSet result = this;\n\t\tresult += s;\n\t\treturn result;\n\t}\n\n\tSet opBinary(string op : \"&\")(const Set s) const{                                \/\/ A \u2229 B               \/\/ \u2229 = &\n\t\tSet result;\n\t\tforeach(x; array) if(x.isIn(s.array)) result += x;\n\t\treturn result;\n\t}\n\n\tref Set opOpAssign(string op : \"&\")(const Set s) {                               \/\/ A \u2229= B\n\t\treturn this(this & s);\n\t}\n\n\tSet opBinary(string op : \"^\")(const Set s) const {                               \/\/ (A \u222a B) - (A \u2229 B)    \/\/  = A ^ B\n\t\tSet result;\n\t\tforeach(x; array) if (x.isNotIn(s.array)) result += x;\n\t\tforeach(x; s.array) if(x.isNotIn(array)) result += x;\n\t\treturn result;\n\t}\n\n\tref opOpAssign(string op : \"^\")(const Set s) {\n\t\treturn this = this ^ s;\n\t}\n\n\tSet opBinary(string op : \"-\")(const Set s) const {                                \/\/ A - B\n\t\tSet r;\n\t\tforeach(x; array) if(x.isNot(s.array)) r += x;\n\t\treturn r;\n\t}\n\n\tref Set opOpAssign(string op : \"-\")(const Set s) {                                \/\/ A -= B\n\t\treturn this = this - s;\n\t}\n\n\tSet!(Tuple!(V,U)) opBinary(U, string op : \"*\")(const Set!U s) const {             \/\/ A \u00d7 B = { (x, y) | \u2200x \u2208 A \u2227 \u2200y \u2208 B }\n\t\tSet!(Tuple!(V, U)) r;\n\t\tforeach(x; array) foreach(y; s.array) r += tuple(x, y);\n\t\treturn r;\n\t}\n\n\tbool isEmpty() const { return !array.length;}                                     \/\/ A \u225f \u2205\n\n\tbool opBinary(string op : \"in\")(const Set s) const {                              \/\/ A \u2282 s\n\t\tforeach(v; array) if(v.isNotIn(s.array)) return false;\n\t\treturn true;\n\t}\n\n\tbool opEquals(const Set s) const {                                                \/\/ A \u225f B\n\t\tif (array.length != s.array.length) return false;\n\t\treturn this in s;\n\t}\n\n\tT[] array() const @property { return array.dup;}\n\n}\n\nSet!(Tuple!(T, T)) sqr(T)(const Set!T s) { return s * s; }                                 \/\/ A\u00b2\n\nauto pow(T, uint n : 0)(const Set!T s) {                                                   \/\/ A ^ 0\n\treturn Set!T.empty;\n}\n\nauto pow(T, uint n : 1)(const Set!T s) {                                                   \/\/ A ^ 1 = A\n\treturn s;\n}\n\nauto pow(T, uint n : 2)(const Set!T s) {                                                   \/\/ A ^\u00a02 (=A\u00b2)\n\treturn sqr!T(s);\n}\n\nauto pow(T, uint n)(const Set!T s) if(n % 2) {                                             \/\/ if n Odd,  A^n = A * (A^(n\/2))\u00b2\t\n        return s * sqr!T(pow!(T, n\/2)(s));\n}\n\nauto pow(T, uint n)(const Set!T s) if(!(n % 2)) {                                           \/\/ if n Even, A^n = (A^(n\/2))\u00b2\n\treturn sqr!T(pow!(T, n\/2)(s));\n}\n\nsize_t Card(T)(const Set!T s) {return s.length; }                                           \/\/ Card(A)\n\nSet!(Set!T) power(T)(Set!T s) {                                                             \/\/ \u2200B \u2208 P(A) \u21d2 B \u2282 A \n\tSet!(Set!T) ret;\n\tforeach(e; s.array) {\n\t\tSet!(Set!T) rs;\n\t\tforeach(x; ret.array) {\n\t\t\tx += e;\n\t\t\trs += x;\n\t\t}\n\t\tret += rs;\n\t}\n\treturn ret;\n}\n\nbool isIn(T)(T x, T[] array){\n\tforeach(a; array) if(a == x) return true;\n\treturn false;\n}\nbool isNotIn(T)(T x, T[] array){\n\tforeachj(a; array) if(a == x) return false;\n\treturn true;\n}\n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":3093}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.range, std.algorithm, std.datetime;\n\n    writeln(\"Christmas comes on a Sunday in the years:\\n\",\n            iota(2008, 2122)\n            .filter!(y => Date(y, 12, 25).dayOfWeek == DayOfWeek.sun));\n}\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":3094}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.math, std.algorithm, std.traits,\n       std.typecons, std.numeric, std.range, std.conv;\n\ntemplate elementwiseMat(string op) {\n    T[][] elementwiseMat(T)(in T[][] A, in T B) pure nothrow {\n        if (A.empty)\n            return null;\n        auto R = new typeof(return)(A.length, A[0].length);\n        foreach (immutable r, const row; A)\n            R[r][] = mixin(\"row[] \" ~ op ~ \"B\");\n        return R;\n    }\n\n    T[][] elementwiseMat(T, U)(in T[][] A, in U[][] B)\n    pure nothrow if (is(Unqual!T == Unqual!U)) {\n        assert(A.length == B.length);\n        if (A.empty)\n            return null;\n        auto R = new typeof(return)(A.length, A[0].length);\n        foreach (immutable r, const row; A) {\n            assert(row.length == B[r].length);\n            R[r][] = mixin(\"row[] \" ~ op ~ \"B[r][]\");\n        }\n        return R;\n    }\n}\n\nalias mSum = elementwiseMat!q{ + },\n      mSub = elementwiseMat!q{ - },\n      pMul = elementwiseMat!q{ * },\n      pDiv = elementwiseMat!q{ \/ };\n\nbool isRectangular(T)(in T[][] mat) pure nothrow {\n    return mat.all!(r => r.length == mat[0].length);\n}\n\nT[][] matMul(T)(in T[][] a, in T[][] b) pure nothrow\nin {\n    assert(a.isRectangular && b.isRectangular &&\n           a[0].length == b.length);\n} body {\n    auto result = new T[][](a.length, b[0].length);\n    auto aux = new T[b.length];\n    foreach (immutable j; 0 .. b[0].length) {\n        foreach (immutable k; 0 .. b.length)\n            aux[k] = b[k][j];\n        foreach (immutable i; 0 .. a.length)\n            result[i][j] = a[i].dotProduct(aux);\n    }\n    return result;\n}\n\nUnqual!T[][] transpose(T)(in T[][] m) pure nothrow {\n    auto r = new Unqual!T[][](m[0].length, m.length);\n    foreach (immutable nr, row; m)\n        foreach (immutable nc, immutable c; row)\n            r[nc][nr] = c;\n    return r;\n}\n\nT norm(T)(in T[][] m) pure nothrow {\n    return transversal(m, 0).map!q{ a ^^ 2 }.sum.sqrt;\n}\n\nUnqual!T[][] makeUnitVector(T)(in size_t dim) pure nothrow {\n    auto result = new Unqual!T[][](dim, 1);\n    foreach (row; result)\n        row[] = 0;\n    result[0][0] = 1;\n    return result;\n}\n\n\/\/\/ Return a nxn identity matrix.\nUnqual!T[][] matId(T)(in size_t n) pure nothrow {\n    auto Id = new Unqual!T[][](n, n);\n    foreach (immutable r, row; Id) {\n        row[] = 0;\n        row[r] = 1;\n    }\n    return Id;\n}\n\nT[][] slice2D(T)(in T[][] A,\n                 in size_t ma, in size_t mb,\n                 in size_t na, in size_t nb) pure nothrow {\n    auto B = new T[][](mb - ma + 1, nb - na + 1);\n    foreach (immutable i, brow; B)\n        brow[] = A[ma + i][na .. na + brow.length];\n    return B;\n}\n\nsize_t rows(T)(in T[][] A) pure nothrow { return A.length; }\n\nsize_t cols(T)(in T[][] A) pure nothrow {\n    return A.length ? A[0].length : 0;\n}\n\nT[][] mcol(T)(in T[][] A, in size_t n) pure nothrow {\n    return slice2D(A, 0, A.rows - 1, n, n);\n}\n\nT[][] matEmbed(T)(in T[][] A, in T[][] B,\n                  in size_t row, in size_t col) pure nothrow {\n    auto C = new T[][](rows(A), cols(A));\n    foreach (immutable i, const arow; A)\n        C[i][] = arow[]; \/\/ Some wasted copies.\n    foreach (immutable i, const brow; B)\n        C[row + i][col .. col + brow.length] = brow[];\n    return C;\n}\n\n\/\/ Main routines ---------------\n\nT[][] makeHouseholder(T)(in T[][] a) {\n    immutable m = a.rows;\n    immutable T s = a[0][0].sgn;\n    immutable e = makeUnitVector!T(m);\n    immutable u = mSum(a, pMul(e, a.norm * s));\n    immutable v = pDiv(u, u[0][0]);\n    immutable beta = 2.0 \/ v.transpose.matMul(v)[0][0];\n    return mSub(matId!T(m), pMul(v.matMul(v.transpose), beta));\n}\n\nTuple!(T[][],\"Q\", T[][],\"R\") QRdecomposition(T)(T[][] A) {\n    immutable m = A.rows;\n    immutable n = A.cols;\n    auto Q = matId!T(m);\n\n    \/\/ Work on n columns of A.\n    foreach (immutable i; 0 .. (m == n ? n - 1 : n)) {\n        \/\/ Select the i-th submatrix. For i=0 this means the original\n        \/\/ matrix A.\n        immutable B = slice2D(A, i, m - 1, i, n - 1);\n\n        \/\/ Take the first column of the current submatrix B.\n        immutable x = mcol(B, 0);\n\n        \/\/ Create the Householder matrix for the column and embed it\n        \/\/ into an mxm identity.\n        immutable H = matEmbed(matId!T(m), x.makeHouseholder, i, i);\n\n        \/\/ The product of all H matrices from the right hand side is\n        \/\/ the orthogonal matrix Q.\n        Q = Q.matMul(H);\n\n        \/\/ The product of all H matrices with A from the LHS is the\n        \/\/ upper triangular matrix R.\n        A  = H.matMul(A);\n    }\n\n    \/\/ Return Q and R.\n    return typeof(return)(Q, A);\n}\n\n\/\/ Polynomial regression ---------------\n\n\/\/\/ Solve an upper triangular system by back substitution.\nT[][] solveUpperTriangular(T)(in T[][] R, in T[][] b) pure nothrow {\n    immutable n = R.cols;\n    auto x = new T[][](n, 1);\n\n    foreach_reverse (immutable k; 0 .. n) {\n        T tot = 0;\n        foreach (immutable j; k + 1 .. n)\n            tot += R[k][j] * x[j][0];\n        x[k][0] = (b[k][0] - tot) \/ R[k][k];\n    }\n\n    return x;\n}\n\n\/\/\/ Solve a linear least squares problem by QR decomposition.\nT[][] lsqr(T)(T[][] A, in T[][] b) pure nothrow {\n    const qr = A.QRdecomposition;\n    immutable n = qr.R.cols;\n    return solveUpperTriangular(\n        slice2D(qr.R, 0, n - 1, 0, n - 1),\n        slice2D(qr.Q.transpose.matMul(b), 0, n - 1, 0, 0));\n}\n\nT[][] polyFit(T)(in T[][] x, in T[][] y, in size_t n) pure nothrow {\n    immutable size_t m = x.cols;\n    auto A = new T[][](m, n + 1);\n    foreach (immutable i, row; A)\n        foreach (immutable j, ref item; row)\n            item = x[0][i] ^^ j;\n    return lsqr(A, y.transpose);\n}\n\nvoid main() {\n    \/\/ immutable (Q, R) = QRdecomposition([[12.0, -51,   4],\n    immutable qr = QRdecomposition([[12.0, -51,   4],\n                                    [ 6.0, 167, -68],\n                                    [-4.0,  24, -41]]);\n    immutable form = \"[%([%(%2.3f,\u00a0%)]%|,\\n\u00a0%)]\\n\";\n    writefln(form, qr.Q);\n    writefln(form, qr.R);\n\n    immutable x = [[0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]];\n    immutable y = [[1.0, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]];\n    polyFit(x, y, 2).writeln;\n}\n\n\n","human_summarization":"The code performs QR decomposition on a given matrix using the Householder reflections method. It decomposes the matrix into an orthogonal matrix and an upper triangular matrix. It also demonstrates the use of QR decomposition for solving linear least squares problems. The code handles cases where the matrix is not square by cutting off zero padded bottom rows. The final solution is obtained by back substitution. The code utilizes functions from Element-wise_operations, Matrix multiplication, and Matrix transposition.","id":3095}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.algorithm;\n\n    [1, 3, 2, 9, 1, 2, 3, 8, 8, 1, 0, 2]\n    .sort()\n    .uniq\n    .writeln;\n}\n\n\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) using a hash table, 2) sorting the elements and removing consecutive duplicates, and 3) iterating through the list and discarding any repeated elements. An additional method using an associative array is also implemented.","id":3096}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio : writefln, writeln;\nimport std.algorithm: filter;\nimport std.array;\n\nT[] quickSort(T)(T[] xs) => \n  xs.length == 0 ? [] :  \n    xs[1 .. $].filter!(x => x< xs[0]).array.quickSort ~  \n    xs[0 .. 1] ~  \n    xs[1 .. $].filter!(x => x>=xs[0]).array.quickSort; \n\nvoid main() =>\n  [4, 65, 2, -31, 0, 99, 2, 83, 782, 1].quickSort.writeln;\n\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by selecting a pivot element and dividing the rest of the elements into two partitions, one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The code includes two versions of the algorithm, one that creates new arrays for the partitions and another more efficient one that sorts the array in place by swapping elements. The pivot selection method is not specified.","id":3097}
    {"lang_cluster":"D","source_code":"\nWorks with: D version DMD 1.026\nLibrary: Tango\nmodule datetimedemo ;\n\nimport tango.time.Time ; \nimport tango.text.locale.Locale ;\nimport tango.time.chrono.Gregorian ;\n\nimport tango.io.Stdout ;\n\nvoid main() {\n    Gregorian g = new Gregorian ;\n    Stdout.layout = new Locale; \/\/ enable Stdout to handle date\/time format\n    Time d = g.toTime(2007, 11, 10, 0, 0, 0, 0, g.AD_ERA) ;\n    Stdout.format(\"{:yyy-MM-dd}\", d).newline ;\n    Stdout.format(\"{:dddd, MMMM d, yyy}\", d).newline ;\n    d = g.toTime(2008, 2, 1, 0, 0, 0, 0, g.AD_ERA) ;\n    Stdout.format(\"{:dddd, MMMM d, yyy}\", d).newline ;\n}\n\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":3098}
    {"lang_cluster":"D","source_code":"\n\nimport std.algorithm;\nimport std.range;\n\nauto powerSet(R)(R r)\n{\n\treturn\n\t\t(1L<<r.length)\n\t\t.iota\n\t\t.map!(i =>\n\t\t\tr.enumerate\n\t\t\t.filter!(t => (1<<t[0]) & i)\n\t\t\t.map!(t => t[1])\n\t\t);\n}\n\nunittest\n{\n\tint[] emptyArr;\n\tassert(emptyArr.powerSet.equal!equal([emptyArr]));\n\tassert(emptyArr.powerSet.powerSet.equal!(equal!equal)([[], [emptyArr]]));\n}\n\nvoid main(string[] args)\n{\n\timport std.stdio;\n\targs[1..$].powerSet.each!writeln;\n}\n\n\nimport std.range;\n\nstruct PowerSet(R)\n\tif (isRandomAccessRange!R)\n{\n\tR r;\n\tsize_t position;\n\n\tstruct PowerSetItem\n\t{\n\t\tR r;\n\t\tsize_t position;\n\n\t\tprivate void advance()\n\t\t{\n\t\t\twhile (!(position & 1))\n\t\t\t{\n\t\t\t\tr.popFront();\n\t\t\t\tposition >>= 1;\n\t\t\t}\n\t\t}\n\n\t\t@property bool empty() { return position == 0; }\n\t\t@property auto front()\n\t\t{\n\t\t\tadvance();\n\t\t\treturn r.front;\n\t\t}\n\t\tvoid popFront()\n\t\t{\n\t\t\tadvance();\n\t\t\tr.popFront();\n\t\t\tposition >>= 1;\n\t\t}\n\t}\n\n\t@property bool empty() { return position == (1 << r.length); }\n\t@property PowerSetItem front() { return PowerSetItem(r.save, position); }\n\tvoid popFront() { position++; }\n}\n\nauto powerSet(R)(R r) { return PowerSet!R(r); }\n\n\n","human_summarization":"The code takes a set S as input and generates its power set. The power set includes all possible subsets of S, including the empty set and the set itself. For a set with n elements, the power set will have 2^n elements. The code also demonstrates the ability to handle edge cases such as the power set of an empty set and the power set of a set containing only the empty set. The implementation uses a lazy enumeration approach to generate the power set.","id":3099}
    {"lang_cluster":"D","source_code":"\nstring toRoman(int n) pure nothrow\nin {\n    assert(n < 5000);\n} body {\n    static immutable weights = [1000, 900, 500, 400, 100, 90,\n                                50, 40, 10, 9, 5, 4, 1];\n    static immutable symbols = [\"M\",\"CM\",\"D\",\"CD\",\"C\",\"XC\",\"L\",\n                                \"XL\",\"X\",\"IX\",\"V\",\"IV\",\"I\"];\n\n    string roman;\n    foreach (i, w; weights) {\n        while (n >= w) {\n            roman ~= symbols[i];\n            n -= w;\n        }\n        if (n == 0)\n            break;\n    }\n    return roman;\n} unittest {\n    assert(toRoman(455)  == \"CDLV\");\n    assert(toRoman(3456) == \"MMMCDLVI\");\n    assert(toRoman(2488) == \"MMCDLXXXVIII\");\n}\n\nvoid main() {}\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":3100}
    {"lang_cluster":"D","source_code":"\n\/\/ All D arrays are capable of bounds checks.\n\nimport std.stdio, core.stdc.stdlib;\nimport std.container: Array;\n\nvoid main() {\n    \/\/ GC-managed heap allocated dynamic array:\n    auto array1 = new int[1];\n    array1[0] = 1;\n    array1 ~= 3; \/\/ append a second item\n    \/\/ array1[10] = 4; \/\/ run-time error\n    writeln(\"A) Element 0: \", array1[0]);\n    writeln(\"A) Element 1: \", array1[1]);\n\n    \/\/ Stack-allocated fixed-size array:\n    int[5] array2;\n    array2[0] = 1;\n    array2[1] = 3;\n    \/\/ array2[2] = 4; \/\/ compile-time error\n    writeln(\"B) Element 0: \", array2[0]);\n    writeln(\"B) Element 1: \", array2[1]);\n\n    \/\/ Stack-allocated dynamic fixed-sized array,\n    \/\/ length known only at run-time:\n    int n = 2;\n    int[] array3 = (cast(int*)alloca(n * int.sizeof))[0 .. n];\n    array3[0] = 1;\n    array3[1] = 3;\n    \/\/ array3[10] = 4; \/\/ run-time error\n    writeln(\"C) Element 0: \", array3[0]);\n    writeln(\"C) Element 1: \", array3[1]);\n\n    \/\/ Phobos-defined  heap allocated not GC-managed array:\n    Array!int array4;\n    array4.length = 2;\n    array4[0] = 1;\n    array4[1] = 3;\n    \/\/ array4[10] = 4; \/\/ run-time exception\n    writeln(\"D) Element 0: \", array4[0]);\n    writeln(\"D) Element 1: \", array4[1]);\n}\n\n\n","human_summarization":"demonstrate the basic syntax of creating an array, assigning a value to it, and retrieving an element in a specific programming language. It includes both fixed-length and dynamic arrays, and shows how to push a value into the array.","id":3101}
    {"lang_cluster":"D","source_code":"\nLibrary: Phobos\nWorks with: D version 2\nimport std.file: copy;\n\nvoid main() {\n    copy(\"input.txt\", \"output.txt\");\n}\n\n\nvoid main() {\nimport std.file;\nauto data = std.file.read(\"input.txt\");\nstd.file.write(\"output.txt\", data);\n}\n\n\nimport std.stdio;\n\nint main() {\n    auto from = File(\"input.txt\", \"rb\");\n    scope(exit) from.close();\n\n    auto to = File(\"output.txt\", \"wb\");\n    scope(exit) to.close();\n\n    foreach(buffer; from.byChunk(new ubyte[4096*1024])) {\n        to.rawWrite(buffer);\n    }\n\n    return 0;\n}\n\nLibrary: Tango\nWorks with: D version 1\n\nimport tango.io.device.File;\n\nvoid main()\n{\n    auto from = new File(\"input.txt\");\n    auto to = new File(\"output.txt\", File.WriteCreate);\n    to.copy(from).close;\n    from.close;\n}\n\n\nimport tango.io.device.File;\n\nvoid main()\n{\n    auto to = new File(\"output.txt\", File.WriteCreate);\n    to.copy(new File(\"input.txt\")).close;\n}\n\n","human_summarization":"demonstrate how to read content from an input file into an intermediate variable and then write this content into an output file. Exception handling is managed by Tango. The codes also include a shorter example where the output file is not explicitly closed.","id":3102}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.string;\n\n    immutable s = \"alphaBETA\";\n    s.toUpper.writeln;\n    s.toLower.writeln;\n}\n\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":3103}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.typecons, std.math, std.algorithm,\n       std.random, std.traits, std.range, std.complex;\n\nauto bruteForceClosestPair(T)(in T[] points) pure nothrow @nogc {\n\/\/  return pairwise(points.length.iota, points.length.iota)\n\/\/         .reduce!(min!((i, j) => abs(points[i] - points[j])));\n  auto minD = Unqual!(typeof(T.re)).infinity;\n  T minI, minJ;\n  foreach (immutable i, const p1; points.dropBackOne)\n    foreach (const p2; points[i + 1 .. $]) {\n      immutable dist = abs(p1 - p2);\n      if (dist < minD) {\n        minD = dist;\n        minI = p1;\n        minJ = p2;\n      }\n    }\n  return tuple(minD, minI, minJ);\n}\n\nauto closestPair(T)(T[] points) pure nothrow {\n  static Tuple!(typeof(T.re), T, T) inner(in T[] xP, \/*in*\/ T[] yP)\n  pure nothrow {\n    if (xP.length <= 3)\n      return xP.bruteForceClosestPair;\n    const Pl = xP[0 .. $ \/ 2];\n    const Pr = xP[$ \/ 2 .. $];\n    immutable xDiv = Pl.back.re;\n    auto Yr = yP.partition!(p => p.re <= xDiv);\n    immutable dl_pairl = inner(Pl, yP[0 .. yP.length - Yr.length]);\n    immutable dr_pairr = inner(Pr, Yr);\n    immutable dm_pairm = dl_pairl[0]<dr_pairr[0] ? dl_pairl : dr_pairr;\n    immutable dm = dm_pairm[0];\n    const nextY = yP.filter!(p => abs(p.re - xDiv) < dm).array;\n\n    if (nextY.length > 1) {\n      auto minD = typeof(T.re).infinity;\n      size_t minI, minJ;\n      foreach (immutable i; 0 .. nextY.length - 1)\n        foreach (immutable j; i + 1 .. min(i + 8, nextY.length)) {\n          immutable double dist = abs(nextY[i] - nextY[j]);\n          if (dist < minD) {\n            minD = dist;\n            minI = i;\n            minJ = j;\n          }\n        }\n      return dm <= minD ? dm_pairm :\n                        typeof(return)(minD, nextY[minI], nextY[minJ]);\n    } else\n      return dm_pairm;\n  }\n\n  points.sort!q{ a.re < b.re };\n  const xP = points.dup;\n  points.sort!q{ a.im < b.im };\n  return inner(xP, points);\n}\n\nvoid main() {\n  alias C = complex;\n  auto pts = [C(5,9), C(9,3), C(2), C(8,4), C(7,4), C(9,10), C(1,9),\n              C(8,2), C(0,10), C(9,6)];\n  pts.writeln;\n  writeln(\"bruteForceClosestPair: \", pts.bruteForceClosestPair);\n  writeln(\"          closestPair: \", pts.closestPair);\n\n  rndGen.seed = 1;\n  Complex!double[10_000] points;\n  foreach (ref p; points)\n    p = C(uniform(0.0, 1000.0) + uniform(0.0, 1000.0));\n  writeln(\"bruteForceClosestPair: \", points.bruteForceClosestPair);\n  writeln(\"          closestPair: \", points.closestPair);\n}\n\n\n","human_summarization":"The code provides two solutions to the Closest Pair of Points problem in a two-dimensional plane. The first function uses a brute force algorithm with a time complexity of O(n^2) to find the two points with the minimum distance between them. The second function uses a more efficient divide and conquer approach with a time complexity of O(n log n) to find the closest pair of points. The divide and conquer function sorts the points based on x and y coordinates, divides them into two halves, and recursively finds the closest pairs in each half. It then compares the closest pairs from both halves and the points lying in the strip around the dividing line to find the overall closest pair. The code also includes performance metrics for data generation and execution of both algorithms.","id":3104}
    {"lang_cluster":"D","source_code":"\n\nint[3] array;\narray[0] = 5;\n\/\/ array.length = 4; \/\/ compile-time error\n\n\nint[] array;\narray ~= 5; \/\/ append 5\narray.length = 3;\narray[3] = 17; \/\/ runtime error: out of bounds. check removed in release mode.\narray = [2, 17, 3];\nwritefln(array.sort); \/\/ 2, 3, 17\n\n\nint[int] array;\n\/\/ array ~= 5; \/\/ it doesn't work that way!\narray[5] = 17;\narray[6] = 20;\n\/\/ prints \"[5, 6]\" -> \"[17, 20]\" - although the order is not specified.\nwritefln(array.keys, \" -> \", array.values);\nassert(5 in array); \/\/ returns a pointer, by the way\nif (auto ptr = 6 in array) writefln(*ptr); \/\/ 20\n\n","human_summarization":"The code creates a collection in a statically-typed language, adds values to it, and reviews examples related to various types of collections such as arrays, associative arrays, linked lists, queues, sets, and stacks. It also includes the use of static, dynamic, and associative arrays in D programming language.","id":3105}
    {"lang_cluster":"D","source_code":"void main() @safe \/*@nogc*\/ {\n    import std.stdio, std.algorithm, std.typecons, std.conv;\n\n    static struct Bounty {\n        int value;\n        double weight, volume;\n    }\n\n    immutable Bounty panacea = {3000,  0.3, 0.025};\n    immutable Bounty ichor =   {1800,  0.2, 0.015};\n    immutable Bounty gold =    {2500,  2.0, 0.002};\n    immutable Bounty sack =    {   0, 25.0, 0.25 };\n\n    immutable maxPanacea = min(sack.weight \/ panacea.weight,\n                               sack.volume \/ panacea.volume).to!int;\n    immutable maxIchor   = min(sack.weight \/ ichor.weight,\n                               sack.volume \/ ichor.volume).to!int;\n    immutable maxGold    = min(sack.weight \/ gold.weight,\n                               sack.volume \/ gold.volume).to!int;\n\n    Bounty best = {0, 0, 0};\n    Tuple!(int, int, int) bestAmounts;\n\n    foreach (immutable nPanacea; 0 .. maxPanacea)\n        foreach (immutable nIchor; 0 .. maxIchor)\n            foreach (immutable nGold; 0 .. maxGold) {\n                immutable Bounty current = {\n                    value: nPanacea * panacea.value +\n                           nIchor * ichor.value +\n                           nGold * gold.value,\n                    weight: nPanacea * panacea.weight +\n                            nIchor * ichor.weight +\n                            nGold * gold.weight,\n                    volume: nPanacea * panacea.volume +\n                            nIchor * ichor.volume +\n                            nGold * gold.volume};\n\n                if (current.value > best.value &&\n                    current.weight <= sack.weight &&\n                    current.volume <= sack.volume) {\n                    best = Bounty(current.value, current.weight, current.volume);\n                    bestAmounts = tuple(nPanacea, nIchor, nGold);\n                }\n            }\n\n    writeln(\"Maximum value achievable is \", best.value);\n    writefln(\"This is achieved by carrying (one solution) %d\" ~\n             \" panacea, %d ichor and %d gold\", bestAmounts[]);\n    writefln(\"The weight to carry is %4.1f and the volume used is %5.3f\",\n             best.weight, best.volume);\n}\n\n\n","human_summarization":"\"Calculate the maximum value of items a traveler can carry in his knapsack from Shangri La, considering the weight and volume constraints of the knapsack and the value, weight, and volume of each item. The code provides one of the four possible solutions to maximize the value taken.\"","id":3106}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\n \nvoid main() {\n    for (int i = 1; ; i++) {\n        write(i);\n        if (i >= 10)\n            break;\n        write(\", \");\n    }\n\n    writeln();\n}\n\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":3107}
    {"lang_cluster":"D","source_code":"import std.stdio, std.string, std.algorithm, std.range;\n\nfinal class ArgumentException : Exception {\n    this(string text) pure nothrow @safe \/*@nogc*\/ {\n        super(text);\n    }\n}\n\nalias TDependencies = string[][string];\n\nstring[][] topoSort(TDependencies d) pure \/*nothrow @safe*\/ {\n    foreach (immutable k, v; d)\n        d[k] = v.sort().uniq.filter!(s => s != k).array;\n    foreach (immutable s; d.byValue.join.sort().uniq)\n        if (s !in d)\n            d[s] = [];\n\n    string[][] sorted;\n    while (true) {\n        string[] ordered;\n\n        foreach (immutable item, const dep; d)\n            if (dep.empty)\n                ordered ~= item;\n        if (!ordered.empty)\n            sorted ~= ordered.sort().release;\n        else\n            break;\n\n        TDependencies dd;\n        foreach (immutable item, const dep; d)\n            if (!ordered.canFind(item))\n                dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array;\n        d = dd;\n    }\n\n    \/\/if (!d.empty)\n    if (d.length > 0)\n        throw new ArgumentException(format(\n            \"A cyclic dependency exists amongst:\\n%s\", d));\n\n    return sorted;\n}\n\nvoid main() {\n    immutable data =\n\"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\ndw01           ieee dw01 dware gtech\ndw02           ieee dw02 dware\ndw03           std synopsys dware dw03 dw02 dw01 ieee gtech\ndw04           dw04 ieee dw01 dware gtech\ndw05           dw05 ieee dware\ndw06           dw06 ieee dware\ndw07           ieee dware\ndware          ieee dware\ngtech          ieee gtech\nramlib         std ieee\nstd_cell_lib   ieee std_cell_lib\nsynopsys\";\n\n    TDependencies deps;\n    foreach (immutable line; data.splitLines)\n        deps[line.split[0]] = line.split[1 .. $];\n\n    auto depw = deps.dup;\n    foreach (immutable idx, const subOrder; depw.topoSort)\n        writefln(\"#%d\u00a0: %s\", idx + 1,  subOrder);\n\n    writeln;\n    depw = deps.dup;\n    depw[\"dw01\"] ~= \"dw04\";\n    foreach (const subOrder; depw.topoSort) \/\/ Should throw.\n        subOrder.writeln;\n}\n\n\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":3108}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio;\n    import std.algorithm: startsWith, endsWith, find, countUntil;\n\n    \"abcd\".startsWith(\"ab\").writeln;      \/\/ true\n    \"abcd\".endsWith(\"zn\").writeln;        \/\/ false\n    \"abab\".find(\"bb\").writeln;            \/\/ empty array (no match)\n    \"abcd\".find(\"bc\").writeln;            \/\/ \"bcd\" (substring start\n                                           \/\/        at match)\n    \"abab\".countUntil(\"bb\").writeln;      \/\/ -1 (no match)\n    \"abab\".countUntil(\"ba\").writeln;      \/\/  1 (index of 1st match)\n\n    \/\/ std.algorithm.startsWith also works on arrays and ranges:\n    [1, 2, 3].countUntil(3).writeln;      \/\/  2\n    [1, 2, 3].countUntil([2, 3]).writeln; \/\/  1\n}\n\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":3109}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\n\nvoid main() {\n    fourSquare(1,7,true,true);\n    fourSquare(3,9,true,true);\n    fourSquare(0,9,false,false);\n}\n\nvoid fourSquare(int low, int high, bool unique, bool print) {\n    int count;\n\n    if (print) {\n        writeln(\"a b c d e f g\");\n    }\n    for (int a=low; a<=high; ++a) {\n        for (int b=low; b<=high; ++b) {\n            if (!valid(unique, a, b)) continue;\n\n            int fp = a+b;\n            for (int c=low; c<=high; ++c) {\n                if (!valid(unique, c, a, b)) continue;\n                for (int d=low; d<=high; ++d) {\n                    if (!valid(unique, d, a, b, c)) continue;\n                    if (fp != b+c+d) continue;\n\n                    for (int e=low; e<=high; ++e) {\n                        if (!valid(unique, e, a, b, c, d)) continue;\n                        for (int f=low; f<=high; ++f) {\n                            if (!valid(unique, f, a, b, c, d, e)) continue;\n                            if (fp != d+e+f) continue;\n\n                            for (int g=low; g<=high; ++g) {\n                                if (!valid(unique, g, a, b, c, d, e, f)) continue;\n                                if (fp != f+g) continue;\n\n                                ++count;\n                                if (print) {\n                                    writeln(a,' ',b,' ',c,' ',d,' ',e,' ',f,' ',g);\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n    }\n    if (unique) {\n        writeln(\"There are \", count, \" unique solutions in [\",low,\",\",high,\"]\");\n    } else {\n        writeln(\"There are \", count, \" non-unique solutions in [\",low,\",\",high,\"]\");\n    }\n}\n\nbool valid(bool unique, int needle, int[] haystack ...) {\n    if (unique) {\n        foreach (value; haystack) {\n            if (needle == value) {\n                return false;\n            }\n        }\n    }\n    return true;\n}\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":3110}
    {"lang_cluster":"D","source_code":"\n\nIMPORT STD.STDIO, STD.DATETIME, STD.STRING, STD.CONV,\n       STD.ALGORITHM, STD.ARRAY;\n\nVOID PRINT_CALENDAR(IN UINT YEAR, IN UINT COLS)\nIN {\n    ASSERT(COLS > 0 && COLS <= 12);\n} BODY {\n    STATIC ENUM CAMEL_CASE = (STRING[] PARTS) PURE =>\n        PARTS[0] ~ PARTS[1 .. $].MAP!CAPITALIZE.JOIN;\n\n    IMMUTABLE ROWS = 12 \/ COLS + (12\u00a0% COLS\u00a0!= 0);\n    MIXIN(\"AUTO DATE = \" ~ \"DATE(YEAR, 1, 1);\".CAPITALIZE);\n    ENUM STRING S1 = CAMEL_CASE(\"DAY OF WEEK\".SPLIT);\n    MIXIN(FORMAT(\"AUTO OFFS = CAST(INT)DATE.%S;\", S1));\n    CONST MONTHS = \"JANUARY FEBRUARY MARCH APRIL MAY JUNE\n        JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER\"\n        .SPLIT.MAP!CAPITALIZE.ARRAY;\n\n    STRING[8][12] MONS;\n    FOREACH (IMMUTABLE M; 0 .. 12) {\n        MONS[M][0] = MONTHS[M].CENTER(21);\n        MONS[M][1] = \" \" ~ \"SU MO TU WE TH FR SA\"\n                           .SPLIT.MAP!CAPITALIZE.JOIN(\" \");\n        ENUM STRING S2 = CAMEL_CASE(\"DAYS IN MONTH\".SPLIT);\n        MIXIN(FORMAT(\"IMMUTABLE DIM = DATE.%S;\", S2));\n        FOREACH (IMMUTABLE D; 1 .. 43) {\n            IMMUTABLE DAY = D > OFFS && D <= OFFS + DIM;\n            IMMUTABLE STR = DAY\u00a0? FORMAT(\" %2S\", D-OFFS)\u00a0: \"   \";\n            MONS[M][2 + (D - 1) \/ 7] ~= STR;\n        }\n        OFFS = (OFFS + DIM)\u00a0% 7;\n        DATE.ADD!\"MONTHS\"(1);\n    }\n\n    FORMAT(\"[%S %S]\", \"SNOOPY\".CAPITALIZE, \"PICTURE\".CAPITALIZE)\n    .CENTER(COLS * 24 + 4).WRITELN;\n    WRITELN(YEAR.TEXT.CENTER(COLS * 24 + 4), \"\\N\");\n    FOREACH (IMMUTABLE R; 0 .. ROWS) {\n        STRING[8] S;\n        FOREACH (IMMUTABLE C; 0 .. COLS) {\n            IF (R * COLS + C > 11)\n                BREAK;\n            FOREACH (IMMUTABLE I, LINE; MONS[R * COLS + C])\n                S[I] ~= FORMAT(\"   %S\", LINE);\n        }\n        WRITEFLN(\"%-(%S\\N%)\\N\", S);\n    }\n}\n\nSTATIC THIS() {\n    PRINT_CALENDAR(1969, 3);\n}\n\nimport std.string;mixin(import(\"CALENDAR\").toLower);void main(){}\n\n\n","human_summarization":"The code provides an algorithm for a calendar task, formatted to fill a 132-character wide page, inspired by 1969 era line printers. The entire code is in uppercase, as it was often mandatory in the 1960s due to character encoding limitations. The code does not include Snoopy generation but outputs a placeholder instead. The code is stored in a text file named \"CALENDAR\", which is then imported and mixed-in by another source code file for safety.","id":3111}
    {"lang_cluster":"D","source_code":"\n\nvoid main() @safe {\n    import std.stdio, std.range, std.algorithm, std.typecons, std.numeric;\n\n    enum triples = (in uint n) pure nothrow @safe \/*@nogc*\/ =>\n        iota(1, n + 1)\n        .map!(z => iota(1, z + 1)\n                   .map!(x => iota(x, z + 1).map!(y => tuple(x, y, z))))\n        .joiner.joiner\n        .filter!(t => t[0] ^^ 2 + t[1] ^^ 2 == t[2] ^^ 2 && t[].only.sum <= n)\n        .map!(t => tuple(t[0 .. 2].gcd == 1, t[]));\n\n    auto xs = triples(100);\n    writeln(\"Up to 100 there are \", xs.count, \" triples, \",\n            xs.filter!q{ a[0] }.count, \" are primitive.\");\n}\n\n\n","human_summarization":"The code determines the number of Pythagorean triples, which are sets of three positive integers that satisfy the condition a^2 + b^2 = c^2 and a < b < c. It also identifies the number of these triples that are primitive, meaning the three numbers are co-prime. The code calculates these triples for perimeters up to 100. For extra credit, the code is optimized to handle larger perimeters up to 1,000,000, 10,000,000, and 100,000,000. The performance of the code is measured in terms of run-time.","id":3112}
    {"lang_cluster":"D","source_code":"\nLibrary: FLTK4d\n module Window;\n \n import fltk4d.all;\n \n void main() {\n     auto window = new Window(300, 300, \"A window\");\n     window.show;\n     FLTK.run;\n }\n\nLibrary: Derelict\nLibrary: SDL\n import derelict.sdl.sdl;\n \n int main(char[][] args)\n {\n     DerelictSDL.load();\n \n     SDL_Event event;\n     auto done = false;\n \n     SDL_Init(SDL_INIT_VIDEO);\n     scope(exit) SDL_Quit();\n \n     SDL_SetVideoMode(1024, 768, 0, SDL_OPENGL);\n     SDL_WM_SetCaption(\"My first Window\", \"SDL test\");\n \t \n     while (!done)\n     {\n         if (SDL_PollEvent(&event) == 1)\n         {\n             switch (event.type)\n \t     {\n                 case SDL_QUIT:\n \t              done = true;\n \t\t          break;\n \t\t default:\n \t\t      break;\n \t     }\n \t }\t\t\n     }\n \n    return 0;\n }\n\nLibrary: QD\n\n import qd;\n \n void main() {\n   screen(640, 480);\n   while (true) events();\n }\n\n","human_summarization":"Create a GUI window using QD, a wrapper around SDL, which can handle close requests.","id":3113}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.ascii, std.algorithm, std.range;\n\n    uint[26] frequency;\n\n    foreach (const buffer; \"unixdict.txt\".File.byChunk(2 ^^ 15))\n        foreach (immutable c; buffer.filter!isAlpha)\n            frequency[c.toLower - 'a']++;\n\n    writefln(\"%(%(%s,\u00a0%),\\n%)\", frequency[].chunks(10));\n}\n\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":3114}
    {"lang_cluster":"D","source_code":"\n\nstruct SLinkedNode(T) {\n    T data;\n    typeof(this)* next;\n}\n\nvoid main() {\n    alias SLinkedNode!int N;\n    N* n = new N(10);\n}\n\n\n","human_summarization":"define a data structure for a singly-linked list element. This element holds a numeric value and a mutable link to the next element. The code also includes references to various related data structures and operations, such as arrays, collections, doubly-linked lists, queues, sets, stacks, and generic template-based node elements. Additionally, it mentions the Phobos library's singly-linked list and Tango's LinkSeq collection.","id":3115}
    {"lang_cluster":"D","source_code":"import std.stdio, std.math;\n\nenum width = 1000, height = 1000; \/\/ Image dimension.\nenum length = 400;                \/\/ Trunk size.\nenum scale = 6.0 \/ 10;            \/\/ Branch scale relative to trunk.\n\nvoid tree(in double x, in double y, in double length, in double angle) {\n    if (length < 1)\n        return;\n    immutable x2 = x + length * angle.cos;\n    immutable y2 = y + length * angle.sin;\n    writefln(\"<line x1='%f' y1='%f' x2='%f' y2='%f' \" ~\n             \"style='stroke:black;stroke-width:1'\/>\", x, y, x2, y2);\n    tree(x2, y2, length * scale, angle + PI \/ 5);\n    tree(x2, y2, length * scale, angle - PI \/ 5);\n}\n\nvoid main() {\n    \"<svg width='100%' height='100%' version='1.1'\n     xmlns='http:\/\/www.w3.org\/2000\/svg'>\".writeln;\n    tree(width \/ 2.0, height, length, 3 * PI \/ 2);\n    \"<\/svg>\".writeln;\n}\n\nimport grayscale_image, turtle;\n\nvoid tree(Color)(Image!Color img, ref Turtle t, in uint depth,\n                 in real step, in real scale, in real angle) {\n    if (depth == 0) return;\n    t.forward(img, step);\n    t.right(angle);\n    img.tree(t, depth - 1, step * scale, scale, angle);\n    t.left(2 * angle);\n    img.tree(t, depth - 1, step * scale, scale, angle);\n    t.right(angle);\n    t.forward(img, -step);\n}\n\nvoid main() {\n    auto img = new Image!Gray(330, 300);\n    auto t = Turtle(165, 270, -90);\n    img.tree(t, 10, 80, 0.7, 30);\n    img.savePGM(\"fractal_tree.pgm\");\n}\n\nimport dfl.all;\nimport std.math;\n\nclass FractalTree: Form {\n\n    private immutable DEG_TO_RAD = PI \/ 180.0;\n\n    this() {\n        width = 600;\n        height = 500;\n        text = \"Fractal Tree\";\n        backColor = Color(0xFF, 0xFF, 0xFF);\n        startPosition = FormStartPosition.CENTER_SCREEN;\n        formBorderStyle = FormBorderStyle.FIXED_DIALOG;\n        maximizeBox = false;\n    }\n\n    private void drawTree(Graphics g, Pen p, int x1, int y1, double angle, int depth) {\n        if (depth == 0) return;\n        int x2 = x1 + cast(int) (cos(angle * DEG_TO_RAD) * depth * 10.0);\n        int y2 = y1 + cast(int) (sin(angle * DEG_TO_RAD) * depth * 10.0);\n        g.drawLine(p, x1, y1, x2, y2);\n        drawTree(g, p, x2, y2, angle - 20, depth - 1);\n        drawTree(g, p, x2, y2, angle + 20, depth - 1);\n    }\n    \n    protected override void onPaint(PaintEventArgs ea){\n        super.onPaint(ea);\n        Pen p = new Pen(Color(0, 0xAA, 0));\n        drawTree(ea.graphics, p, 300, 450, -90, 9);\n    }\n}\n\nint main() {\n    int result = 0; \n    try {\n        Application.run(new FractalTree);\n    } catch(Exception e) {\n        msgBox(e.msg, \"Fatal Error\", MsgBoxButtons.OK, MsgBoxIcon.ERROR);        \n        result = 1;\n    }   \n    return result;\n}\n\n","human_summarization":"The code utilizes the turtle and grayscale image modules to generate and draw a fractal tree. It begins by drawing the trunk, then splits the end of the trunk at a certain angle to create two branches. This process is repeated until a desired level of branching is achieved. The code is written in DFL.","id":3116}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.math, std.algorithm;\n\nT[] factors(T)(in T n) pure nothrow {\n    if (n == 1)\n        return [n];\n\n    T[] res = [1, n];\n    T limit = cast(T)real(n).sqrt + 1;\n    for (T i = 2; i < limit; i++) {\n        if (n % i == 0) {\n            res ~= i;\n            immutable q = n \/ i;\n            if (q > i)\n                res ~= q;\n        }\n    }\n\n    return res.sort().release;\n}\n\nvoid main() {\n    writefln(\"%(%s\\n%)\", [45, 53, 64, 1111111].map!factors);\n}\n\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":3117}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.string, std.algorithm, std.range, std.typetuple;\n\n    immutable data =\n\"Given$a$txt$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\"\n    .split.map!(r => r.chomp(\"$\").split(\"$\")).array;\n\n    size_t[size_t] maxWidths;\n    foreach (const line; data)\n        foreach (immutable i, const word; line)\n            maxWidths[i] = max(maxWidths.get(i, 0), word.length);\n\n    foreach (immutable just; TypeTuple!(leftJustify, center, rightJustify))\n        foreach (immutable line; data)\n            writefln(\"%-(%s\u00a0%)\", line.length.iota\n                     .map!(i => just(line[i], maxWidths[i], ' ')));\n}\n\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":3118}
    {"lang_cluster":"D","source_code":"import std.stdio, std.array;\n\nvoid printCuboid(in int dx, in int dy, in int dz) {\n    static cline(in int n, in int dx, in int dy, in string cde) {\n        writef(\"%*s\", n+1, cde[0 .. 1]);\n        write(cde[1 .. 2].replicate(9*dx - 1));\n        write(cde[0]);\n        writefln(\"%*s\", dy+1, cde[2 .. $]);\n    }\n\n    cline(dy+1, dx, 0, \"+-\");\n    foreach (i; 1 .. dy+1)\n        cline(dy-i+1, dx, i-1, \"\/ |\");\n    cline(0, dx, dy, \"+-|\");\n    foreach (_; 0 .. 4*dz - dy - 2)\n        cline(0, dx, dy, \"| |\");\n    cline(0, dx, dy, \"| +\");\n    foreach_reverse (i; 0 .. dy)\n        cline(0, dx, i, \"| \/\");\n    cline(0, dx, 0, \"+-\\n\");\n}\n\nvoid main() {\n    printCuboid(2, 3, 4);\n    printCuboid(1, 1, 1);\n    printCuboid(6, 2, 1);\n}\n\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":3119}
    {"lang_cluster":"D","source_code":"\n\nimport openldap;\nimport std.stdio;\n\nvoid main() {\n  auto ldap = LDAP(\"ldap:\/\/localhost\");\n  auto r = ldap.search_s(\"dc=example,dc=com\", LDAP_SCOPE_SUBTREE, \"(uid=%s)\".format(\"test\"));\n  int b = ldap.bind_s(r[0].dn, \"password\");\n  scope(exit) ldap.unbind;\n  if (b)\n  {\n    writeln(\"error on binding\");\n    return;\n  }\n\n  \/\/ do something\n  ...\n    \n}\n\n","human_summarization":"Establish a connection to an Active Directory or Lightweight Directory Access Protocol server using dopenldap.","id":3120}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\nimport std.ascii: letters, U = uppercase, L = lowercase;\nimport std.string: makeTrans, translate;\n\nimmutable r13 = makeTrans(letters,\n                          \/\/U[13 .. $] ~ U[0 .. 13] ~\n                          U[13 .. U.length] ~ U[0 .. 13] ~\n                          L[13 .. L.length] ~ L[0 .. 13]);\n\nvoid main() {\n    writeln(\"This is the 1st test!\".translate(r13, null));\n}\n\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":3121}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.algorithm;\n\nstruct Pair { string name, value; }\n\nvoid main() {\n    Pair[] pairs = [{\"Joe\",    \"5531\"},\n                    {\"Adam\",   \"2341\"},\n                    {\"Bernie\",  \"122\"},\n                    {\"Walter\", \"1234\"},\n                    {\"David\",    \"19\"}];\n\n    pairs.schwartzSort!q{ a.name }.writeln;\n}\n\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":3122}
    {"lang_cluster":"D","source_code":"\nimport std.stdio: write, writeln;\n\nvoid main() {\n    for (int i; i < 5; i++) {\n        for (int j; j <= i; j++)\n            write(\"*\");\n        writeln();\n    }\n    writeln();\n\n    foreach (i; 0 .. 5) {\n        foreach (j; 0 .. i + 1)\n            write(\"*\");\n        writeln();\n    }\n}\n\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":3123}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    auto hash = [\"foo\":42, \"bar\":100];\n    assert(\"foo\" in hash);\n}\n\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":3124}
    {"lang_cluster":"D","source_code":"\nstruct LinearCongruentialGenerator {\n    enum uint RAND_MAX = (1U << 31) - 1;\n    uint seed = 0;\n\n    uint randBSD() pure nothrow @nogc {\n        seed = (seed * 1_103_515_245 + 12_345) & RAND_MAX;\n        return seed;\n    }\n\n    uint randMS() pure nothrow @nogc {\n        seed = (seed * 214_013 + 2_531_011) & RAND_MAX;\n        return seed >> 16;\n    }\n}\n\nvoid main() {\n    import std.stdio;\n\n    LinearCongruentialGenerator rnd;\n\n    foreach (immutable i; 0 .. 10)\n        writeln(rnd.randBSD);\n    writeln;\n\n    rnd.seed = 0;\n    foreach (immutable i; 0 .. 10)\n        writeln(rnd.randMS);\n}\n\n\n12345\n1406932606\n654583775\n1449466924\n229283573\n1109335178\n1051550459\n1293799192\n794471793\n551188310\n\n38\n7719\n21238\n2437\n8855\n11797\n8365\n32285\n10450\n30612\n","human_summarization":"\"Implement two historic random number generators: the rand() function from BSD libc, and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). Both generators use the linear congruential generator formula, but with different constants and seed values. The generators produce a sequence of integers that are not cryptographically secure but can be used for simple tasks like the Miller-Rabin primality test or FreeCell deals.\"","id":3125}
    {"lang_cluster":"D","source_code":"\nstruct SLinkedNode(T) {\n    T data;\n    typeof(this)* next;\n}\n\nvoid insertAfter(T)(SLinkedNode!T* listNode, SLinkedNode!T* newNode) {\n    newNode.next = listNode.next;\n    listNode.next = newNode;\n}\n\nvoid main() {\n    alias N = SLinkedNode!char;\n\n    auto lh = new N('A', new N('B'));\n    auto c = new N('C');\n\n    \/\/ Inserts C after A, creating the (A C B) list:\n    insertAfter(lh, c);\n\n    \/\/ The GC will collect the memory.\n}\n\n","human_summarization":"\"Defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element C into a list of elements A->B, after element A.\"","id":3126}
    {"lang_cluster":"D","source_code":"\nint ethiopian(int n1, int n2) pure nothrow @nogc\nin {\n    assert(n1 >= 0, \"Multiplier can't be negative\");\n} body {\n    static enum doubleNum = (in int n) pure nothrow @nogc => n * 2;\n    static enum halveNum = (in int n) pure nothrow @nogc => n \/ 2;\n    static enum isEven = (in int n) pure nothrow @nogc => !(n & 1);\n\n    int result;\n    while (n1 >= 1) {\n        if (!isEven(n1))\n            result += n2;\n        n1 = halveNum(n1);\n        n2 = doubleNum(n2);\n    }\n\n    return result;\n} unittest {\n    assert(ethiopian(77, 54) == 77 * 54);\n    assert(ethiopian(8, 923) == 8 * 923);\n    assert(ethiopian(64, -4) == 64 * -4);\n}\n\nvoid main() {\n    import std.stdio;\n\n    writeln(\"17 ethiopian 34 is \", ethiopian(17, 34));\n}\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":3127}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.algorithm, std.range, std.conv, std.string,\n       std.concurrency, permutations2, arithmetic_rational;\n\nstring solve(in int target, in int[] problem) {\n    static struct T { Rational r; string e; }\n\n    Generator!T computeAllOperations(in Rational[] L) {\n        return new typeof(return)({\n            if (!L.empty) {\n                immutable x = L[0];\n                if (L.length == 1) {\n                    yield(T(x, x.text));\n                } else {\n                    foreach (const o; computeAllOperations(L.dropOne)) {\n                        immutable y = o.r;\n                        auto sub = [T(x * y, \"*\"), T(x + y, \"+\"), T(x - y, \"-\")];\n                        if (y) sub ~= [T(x \/ y, \"\/\")];\n                        foreach (const e; sub)\n                            yield(T(e.r, format(\"(%s%s%s)\", x, e.e, o.e)));\n                    }\n                }\n            }\n        });\n    }\n\n    foreach (const p; problem.map!Rational.array.permutations!false)\n        foreach (const sol; computeAllOperations(p))\n            if (sol.r == target)\n                return sol.e;\n    return \"No solution\";\n}\n\nvoid main() {\n    foreach (const prob; [[6, 7, 9, 5], [3, 3, 8, 8], [1, 1, 1, 1]])\n        writeln(prob, \": \", solve(24, prob));\n}\n\n\n","human_summarization":"The code takes four digits as input or generates them randomly, then computes arithmetic expressions according to the rules of the 24 game. It also displays examples of solutions it generates. The code utilizes the Rational struct and permutations functions from two other Rosetta Code Tasks.","id":3128}
    {"lang_cluster":"D","source_code":"\nuint factorial(in uint n) pure nothrow @nogc\nin {\n    assert(n <= 12);\n} body {\n    uint result = 1;\n    foreach (immutable i; 1 .. n + 1)\n        result *= i;\n    return result;\n}\n\n\/\/ Computed and printed at compile-time.\npragma(msg, 12.factorial);\n\nvoid main() {\n    import std.stdio;\n\n    \/\/ Computed and printed at run-time.\n    12.factorial.writeln;\n}\n\n","human_summarization":"The code calculates the factorial of a given number. It can be implemented either iteratively or recursively. The function may optionally handle errors for negative input values. It is related to the task of generating primorial numbers.","id":3129}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.random, std.string, std.algorithm,\n           std.range, std.ascii;\n\n    immutable hidden = \"123456789\"d.randomCover.take(4).array;\n    while (true) {\n        \"Next guess: \".write;\n        const d = readln.strip.array.sort().release;\n        if (d.count == 4 && d.all!isDigit && d.uniq.count == 4) {\n            immutable bulls = d.zip(hidden).count!q{ a[0] == a[1] },\n                      cows = d.count!(g => hidden.canFind(g)) - bulls;\n            if (bulls == 4)\n                return \" You guessed it!\".writeln;\n            writefln(\"bulls %d, cows %d\", bulls, cows);\n        }\n        \" Bad guess! (4 unique digits, 1-9)\".writeln;\n    }\n}\n\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":3130}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.random, std.math;\n\nstruct NormalRandom {\n    double mean, stdDev;\n\n    \/\/ Necessary because it also defines an opCall.\n    this(in double mean_, in double stdDev_) pure nothrow {\n        this.mean = mean_;\n        this.stdDev = stdDev_;\n    }\n\n    double opCall() const \/*nothrow*\/ {\n        immutable r1 = uniform01, r2 = uniform01; \/\/ Not nothrow.\n        return mean + stdDev * sqrt(-2 * r1.log) * cos(2 * PI * r2);\n    }\n}\n\nvoid main() {\n    double[1000] array;\n    auto nRnd = NormalRandom(1.0, 0.5);\n    foreach (ref x; array)\n        \/\/x = nRnd;\n        x = nRnd();\n}\n\n\nLibrary: tango\nimport tango.math.random.Random;\n\nvoid main() {\n    double[1000] list;\n    auto r = new Random();\n    foreach (ref l; list) {\n        r.normalSource!(double)()(l);\n        l = 1.0 + 0.5 * l;\n    }\n}\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using libraries that generate uniformly distributed random numbers.","id":3131}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.numeric;\n\n    [1.0, 3.0, -5.0].dotProduct([4.0, -2.0, -1.0]).writeln;\n}\n\n\n","human_summarization":"\"Implements a function to compute the dot product of two vectors of the same length by multiplying corresponding terms from each vector and summing the products.\"","id":3132}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio;\n\n    immutable fileName = \"input_loop1.d\";\n\n    foreach (const line; fileName.File.byLine) {\n        pragma(msg, typeof(line)); \/\/ Prints: const(char[])\n        \/\/ line is a transient slice, so if you need to\n        \/\/ retain it for later use, you have to .dup or .idup it.\n        line.writeln; \/\/ Do something with each line.\n    }\n\n    \/\/ Keeping the line terminators:\n    foreach (const line; fileName.File.byLine(KeepTerminator.yes)) {\n        \/\/ line is a transient slice.\n        line.writeln;\n    }\n\n    foreach (const string line; fileName.File.lines) {\n        \/\/ line is a transient slice.\n        line.writeln;\n    }\n}\n\nLibrary: Tango\nimport tango.io.Console;\nimport tango.text.stream.LineIterator;\n\nvoid main (char[][] args) {\n    foreach (line; new LineIterator!(char)(Cin.input)) {\n        \/\/ do something with each line\n    }\n}\n\nLibrary: Tango\nimport tango.io.Console;\nimport tango.text.stream.SimpleIterator;\n\nvoid main (char[][] args) {\n    foreach (word; new SimpleIterator!(char)(\" \", Cin.input)) {\n        \/\/ do something with each word\n    }\n}\n\n\n","human_summarization":"read data from a text stream either word-by-word or line-by-line until there's no more data. It duplicates 'line' and 'word' variables for later use as they are transient slices.","id":3133}
    {"lang_cluster":"D","source_code":"\nWorks with: D version 2.011+\nmodule xmltest ;\n\nimport std.stdio ;\nimport std.xml ;\n\nvoid main() {\n  auto doc = new Document(\"root\") ;\n\/\/doc.prolog = q\"\/<?xml version=\"1.0\"?>\/\"\u00a0; \/\/ default\n  doc ~= new Element(\"element\", \"Some text here\") ;\n  writefln(doc) ;\n\/\/ output: <?xml version=\"1.0\"?><root><element>Some text here<\/element><\/root>\n}\n\n","human_summarization":"Create a simple DOM and serialize it into the specified XML format.","id":3134}
    {"lang_cluster":"D","source_code":"\nWorks with: Tango\n\nStdout(Clock.now.span.days \/ 365).newline;\n\n","human_summarization":"the system time in a specified unit, which can be used for debugging, network information, random number seeds, or program performance. The time-span is calculated from 1 Jan 1 A.D, with the lowest unit available being nanoseconds. The task is related to date formatting and retrieving system time.","id":3135}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.algorithm, std.string, std.numeric, std.ascii;\n\nchar checksum(in char[] sedol) pure @safe \/*@nogc*\/\nin {\n    assert(sedol.length == 6);\n    foreach (immutable c; sedol)\n        assert(c.isDigit || (c.isUpper && !\"AEIOU\".canFind(c)));\n} out (result) {\n    assert(result.isDigit);\n} body {\n    static immutable c2v = (in dchar c) => c.isDigit ? c - '0' : (c - 'A' + 10);\n    immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]);\n    return digits[10 - (d % 10)];\n}\n\nvoid main() {\n    foreach (const sedol; \"710889 B0YBKJ 406566 B0YBLH 228276\n                          B0YBKL 557910 B0YBKR 585284 B0YBKT\".split)\n        writeln(sedol, sedol.checksum);\n}\n\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the corresponding SEDOL. It also validates each input to ensure it is correctly formed according to the allowed characters in a SEDOL string.","id":3136}
    {"lang_cluster":"D","source_code":"import std.stdio, std.math, std.algorithm, std.numeric;\n\nalias V3 = double[3];\nimmutable light = normalize([30.0, 30.0, -50.0]);\n\nV3 normalize(V3 v) pure @nogc {\n    v[] \/= dotProduct(v, v) ^^ 0.5;\n    return v;\n}\n\ndouble dot(in ref V3 x, in ref V3 y) pure nothrow @nogc {\n    immutable double d = dotProduct(x, y);\n    return d < 0 ? -d : 0;\n}\n\nvoid drawSphere(in double R, in double k, in double ambient) @nogc {\n    enum shades = \".:!*oe&#%@\";\n    foreach (immutable i; cast(int)floor(-R) .. cast(int)ceil(R) + 1) {\n        immutable double x = i + 0.5;\n        foreach (immutable j; cast(int)floor(-2 * R) ..\n                              cast(int)ceil(2 * R) + 1) {\n            immutable double y = j \/ 2. + 0.5;\n            if (x ^^ 2 + y ^^ 2 <= R ^^ 2) {\n                immutable vec = [x, y, (R^^2 - x^^2 - y^^2) ^^ 0.5]\n                                .normalize;\n                immutable double b = dot(light, vec) ^^ k + ambient;\n                int intensity = cast(int)((1 - b) * (shades.length-1));\n                intensity = min(shades.length - 1, max(intensity, 0));\n                shades[intensity].putchar;\n            } else\n                ' '.putchar;\n        }\n        '\\n'.putchar;\n    }\n}\n\nvoid main() {\n    drawSphere(20, 4, 0.1);\n    drawSphere(10, 2, 0.4);\n}\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":3137}
    {"lang_cluster":"D","source_code":"import std.stdio, std.string, std.range, std.algorithm;\n\nstring nth(in uint n) pure {\n    static immutable suffix = \"th st nd rd th th th th th th\".split;\n    return \"%d'%s\".format(n, (n % 100 <= 10 || n % 100 > 20) ?\n                             suffix[n % 10] : \"th\");\n}\n\nvoid main() {\n    foreach (r; [iota(26), iota(250, 266), iota(1000, 1026)])\n        writefln(\"%-(%s\u00a0%)\", r.map!nth);\n}\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":3138}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio;\n\nstring stripchars(string s, string chars) {\n    import std.algorithm;\n    import std.conv;\n    return s.filter!(c => !chars.count(c)).to!string;\n}\n\nstring stripchars2(string s, string chars) {\n    import std.regex;\n    return replaceAll(s, regex(\"[\" ~ chars ~ \"]\"), \"\");\n}\n\nvoid main() {\n    string s = \"She was a soul stripper. She took my heart!\";\n    string chars = \"aei\";\n\n    writeln(stripchars(s, chars));\n    writeln(stripchars2(s, chars));\n}\n\n\n","human_summarization":"The function 'stripchars' takes two strings as input, removes all occurrences of characters in the second string from the first string, and returns the modified string.","id":3139}
    {"lang_cluster":"D","source_code":"\nimport core.stdc.stdlib;\nimport std.stdio;\n\nvoid main() {\n    int limit;\n    write(\"Max number (>0): \");\n    readf!\"%d\\n\"(limit);\n    if (limit <= 0) {\n        writeln(\"The max number to consider must be greater than zero.\");\n        exit(1);\n    }\n\n    int terms;\n    write(\"Terms (>0): \");\n    readf!\"%d\\n\"(terms);\n    if (terms <= 0) {\n        writeln(\"The number of terms to consider must be greater than zero.\");\n        exit(1);\n    }\n\n    int[] factors = new int[terms];\n    string[] words = new string[terms];\n\n    for (int i=0; i<terms; ++i) {\n        write(\"Factor \", i+1, \" and word: \");\n        readf!\"%d %s\\n\"(factors[i], words[i]);\n        if (factors[i] <= 0) {\n            writeln(\"The factor to consider must be greater than zero.\");\n            exit(1);\n        }\n    }\n\n    foreach(n; 1..limit+1) {\n        bool print = true;\n\n        for (int i=0; i<terms; ++i) {\n            if (n % factors[i] == 0) {\n                write(words[i]);\n                print = false;\n            }\n        }\n\n        if (print) {\n            writeln(n);\n        } else {\n            writeln();\n        }\n    }\n}\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":3140}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\n\nvoid main() {\n    string s = \"world!\";\n    s = \"Hello \" ~ s; \n    writeln(s);\n}\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":3141}
    {"lang_cluster":"D","source_code":"\n\nvariables\u00a0: X Y F\nconstants\u00a0: + \u2212\nstart \u00a0: FX\nrules \u00a0: (X \u2192 X+YF+),(Y \u2192 -FX-Y)\nangle \u00a0: 90\u00b0\nimport std.stdio, std.string;\n\nstruct Board {\n    enum char spc = ' ';\n    char[][] b = [[' ']]; \/\/ Set at least 1x1 board.\n    int shiftx, shifty;\n\n    void clear() pure nothrow {\n        shiftx = shifty = 0;\n        b = [['\\0']];\n    }\n\n    void check(in int x, in int y) pure nothrow {\n        while (y + shifty < 0) {\n            auto newr = new char[b[0].length];\n            newr[] = spc;\n            b = newr ~ b;\n            shifty++;\n        }\n\n        while (y + shifty >= b.length) {\n            auto newr = new char[b[0].length];\n            newr[] = spc;\n            b ~= newr;\n        }\n\n        while (x + shiftx < 0) {\n            foreach (ref c; b)\n                c = [spc] ~ c;\n            shiftx++;\n        }\n\n        while (x + shiftx >= b[0].length)\n            foreach (ref c; b)\n                c ~= [spc];\n    }\n\n    char opIndexAssign(in char value, in int x, in int y)\n    pure nothrow {\n        check(x, y);\n        b[y + shifty][x + shiftx] = value;\n        return value;\n    }\n\n    string toString() const pure {\n        return format(\"%-(%s\\n%)\", b);\n    }\n}\n\nstruct Turtle {\n    static struct TState {\n        int[2] xy;\n        int heading;\n    }\n\n    enum int[2][] dirs = [[1, 0],  [1,   1], [0,  1], [-1,  1],\n                          [-1, 0], [-1, -1], [0, -1],  [1, -1]];\n    enum string trace = r\"-\\|\/-\\|\/\";\n    TState t;\n\n    void reset() pure nothrow {\n        t = typeof(t).init;\n    }\n\n    void turn(in int dir) pure nothrow {\n        t.heading = (t.heading + 8 + dir) % 8;\n    }\n\n    void forward(ref Board b) pure nothrow {\n        with (t) {\n            xy[] += dirs[heading][];\n            b[xy[0], xy[1]] = trace[heading];\n            xy[] += dirs[heading][];\n            b[xy[0], xy[1]] = b.spc;\n        }\n    }\n}\n\nvoid dragonX(in int n, ref Turtle t, ref Board b) pure nothrow {\n    if (n >= 0) { \/\/ X -> X+YF+\n        dragonX(n - 1, t, b);\n        t.turn(2);\n        dragonY(n - 1, t, b);\n        t.forward(b);\n        t.turn(2);\n    }\n}\n\nvoid dragonY(in int n, ref Turtle t, ref Board b) pure nothrow {\n    if (n >= 0) { \/\/ Y -> -FX-Y\n        t.turn(-2);\n        t.forward(b);\n        dragonX(n - 1, t, b);\n        t.turn(-2);\n        dragonY(n - 1, t, b);\n    }\n}\n\nvoid main() {\n    Turtle t;\n    Board b;\n                      \/\/ Seed\u00a0: FX\n    t.forward(b);     \/\/ <- F\n    dragonX(7, t, b); \/\/ <- X\n    writeln(b);\n}\n\n\n","human_summarization":"The code generates a Dragon Curve fractal either directly or by writing it to an image file. It uses different algorithms including recursive, successive approximation, iterative, and Lindenmayer system of expansions. The recursive algorithm involves right and left curling dragons, while the successive approximation rewrites each straight line as two new segments at a right angle. The iterative method uses bit manipulation to determine the direction of the turn. The Lindenmayer system uses two symbols for straight lines. Additionally, the code includes a textual version of the Dragon Curve and uses modules from the Bresenham's line algorithm and Grayscale Image tasks. The code also allows for the calculation of absolute X,Y coordinates of a point and a predicate test to check if a given X,Y point or segment is on the curve.","id":3142}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    immutable num = uniform(1, 10).text;\n\n    do write(\"What's next guess (1 - 9)? \");\n    while (readln.strip != num);\n\n    writeln(\"Yep, you guessed my \", num);\n}\n\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":3143}
    {"lang_cluster":"D","source_code":"\n\nimport std.ascii: lowercase;\n\nvoid main() {}\n\n\nvoid main() {\n    char['z' - 'a' + 1] arr;\n\n    foreach (immutable i, ref c; arr)\n        c = 'a' + i;\n}\n\n\nvoid main() {\n    import std.range, std.algorithm, std.array;\n\n    char[26] arr = 26.iota.map!(i => cast(char)('a' + i)).array;\n}\n\n\nvoid main() {\n    char[] arr;\n\n    foreach (immutable char c; 'a' .. 'z' + 1)\n        arr ~= c;\n\n    assert(arr == \"abcdefghijklmnopqrstuvwxyz\");\n}\n\n","human_summarization":"generate an array, list, or string of all lower case ASCII characters from 'a' to 'z'. The code also demonstrates how to access a similar sequence if it exists in the standard library. The coding style used is reliable and suitable for large programs, with strong typing utilized if available. The code avoids manually enumerating all lowercase characters to prevent bugs.","id":3144}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio;\n\n    foreach (immutable i; 0 .. 16)\n        writefln(\"%b\", i);\n}\n\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":3145}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.string, std.conv, std.regex, std.getopt;\n\nenum VarName(alias var) = var.stringof;\n\nvoid setOpt(alias Var)(in string line) {\n    auto m = match(line, regex(`^(?i)` ~ VarName!Var ~ `(?-i)(\\s*=?\\s+(.*))?`));\n\n    if (!m.empty) {\n        static if (is(typeof(Var) == string[]))\n            Var = m.captures.length > 2 ? m.captures[2].split(regex(`\\s*,\\s*`)) : [\"\"];\n        static if (is(typeof(Var) == string))\n            Var = m.captures.length > 2 ? m.captures[2] : \"\";\n        static if (is(typeof(Var) == bool))\n            Var = true;\n        static if (is(typeof(Var) == int))\n            Var = m.captures.length > 2 ? to!int(m.captures[2]) : 0;\n    }\n}\n\nvoid main(in string[] args) {\n    string fullName, favouriteFruit;\n    string[] otherFamily;\n    bool needsPeeling, seedsRemoved; \/\/ Default false.\n\n    auto f = \"readcfg.conf\".File;\n\n    foreach (line; f.byLine) {\n        auto opt = line.strip.idup;\n\n        setOpt!fullName(opt);\n        setOpt!favouriteFruit(opt);\n        setOpt!needsPeeling(opt);\n        setOpt!seedsRemoved(opt);\n        setOpt!otherFamily(opt);\n    }\n\n    writefln(\"%s = %s\", VarName!fullName, fullName);\n    writefln(\"%s = %s\", VarName!favouriteFruit, favouriteFruit);\n    writefln(\"%s = %s\", VarName!needsPeeling, needsPeeling);\n    writefln(\"%s = %s\", VarName!seedsRemoved, seedsRemoved);\n    writefln(\"%s = %s\", VarName!otherFamily, otherFamily);\n}\n\n\n","human_summarization":"The code reads a standard configuration file, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration parameters. It handles an optional equals sign separating configuration parameter data from the option name. It also supports multiple parameters for a configuration option, storing them in an array. The output includes four variables: fullname, favouritefruit, needspeeling, and seedsremoved, and an array otherfamily with multiple parameters.","id":3146}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.math;\n\nreal haversineDistance(in real dth1, in real dph1,\n                       in real dth2, in real dph2)\npure nothrow @nogc {\n    enum real R = 6371;\n    enum real TO_RAD = PI \/ 180;\n\n    alias imr = immutable real;\n    imr ph1d = dph1 - dph2;\n    imr ph1 = ph1d * TO_RAD;\n    imr th1 = dth1 * TO_RAD;\n    imr th2 = dth2 * TO_RAD;\n\n    imr dz = th1.sin - th2.sin;\n    imr dx = ph1.cos * th1.cos - th2.cos;\n    imr dy = ph1.sin * th1.cos;\n    return asin(sqrt(dx ^^ 2 + dy ^^ 2 + dz ^^ 2) \/ 2) * 2 * R;\n}\n\nvoid main() {\n    writefln(\"Haversine distance:\u00a0%.1f km\",\n             haversineDistance(36.12, -86.67, 33.94, -118.4));\n}\n\n\n","human_summarization":"implement the Haversine formula to calculate the great-circle distance between Nashville International Airport (BNA) and Los Angeles International Airport (LAX) using their respective longitudes and latitudes. The earth's radius is considered as 6372.8 km or 6371 km based on the user's preference. The formula is used in navigation and spherical trigonometry.","id":3147}
    {"lang_cluster":"D","source_code":"\nLibrary: phobos\nvoid main() {\n  import std.stdio, std.net.curl;\n  writeln(get(\"http:\/\/google.com\"));\n}\n\nLibrary: tango\nimport tango.io.Console;\nimport tango.net.http.HttpGet;\n\nvoid main() {\n  Cout.stream.copy( (new HttpGet(\"http:\/\/google.com\")).open );\n}\n\n\nimport tango.io.Console;\nimport tango.net.InternetAddress;\nimport tango.net.device.Socket;\n\nvoid main() {\n  auto site = new Socket;\n  site.connect (new InternetAddress(\"google.com\",80)).write (\"GET \/ HTTP\/1.0\\n\\n\");\n\n  Cout.stream.copy (site);\n}\n\n","human_summarization":"\"Prints the content of a specified URL to the console using HTTP request.\"","id":3148}
    {"lang_cluster":"D","source_code":"import std.algorithm, std.range, std.string;\n\nenum luhnTest = (in string n) pure \/*nothrow*\/ @safe \/*@nogc*\/ =>\n    retro(n)\n    .zip(only(1, 2).cycle)\n    .map!(p => (p[0] - '0') * p[1])\n    .map!(d => d \/ 10 + d % 10)\n    .sum % 10 == 0;\n\nvoid main() {\n    assert(\"49927398716 49927398717 1234567812345678 1234567812345670\"\n           .split.map!luhnTest.equal([true, false, false, true]));\n}\nimport std.algorithm;\n\nbool luhnTest(in string num) @safe pure nothrow @nogc {\n    uint sum;\n    foreach_reverse (immutable i, immutable n; num) {\n        immutable uint ord = n - '\\u0030';\n        sum += ((num.length - i) & 1) ? ord : ord \/ 5 + (2 * ord) % 10;\n    }\n    return sum % 10 == 0;\n}\n\nvoid main() {\n    immutable data = [\"49927398716\",\n                      \"49927398717\",\n                      \"1234567812345678\",\n                      \"1234567812345670\"];\n    assert(data.map!luhnTest.equal([true, false, false, true]));\n}\n\nimport std.stdio;\n\nstruct Interval(T) {\n    immutable T a, b;\n\n    this(in T a_, in T b_) pure nothrow @nogc {\n        this.a = a_;\n        this.b = b_;\n    }\n\n    bool opBinaryRight(string op=\"in\")(in T x)\n    const pure nothrow @nogc {\n        return x >= a && x <= b;\n    }\n\n    pure nothrow @safe @nogc const invariant {\n        assert(a <= b);\n    }\n}\n\nInterval!T interval(T)(in T a, in T b) pure nothrow @nogc {\n    return Interval!T(a, b);\n}\n\n\nbool luhnTest(in string num) pure nothrow @nogc\nin {\n    assert(num.length <= 20);\n} body {\n    int sum = 0;\n    bool od = true;\n    bool ok = true;\n    immutable int numLen = num.length;\n\n    foreach_reverse (immutable p; 0 .. numLen) {\n        immutable int i = num[p] - '0';\n        if (i !in interval(0, 9)) {\n            ok = false;\n            break;\n        }\n\n        immutable int x = ((i * 2) % 10) + (i \/ 5);\n        assert((numLen - p) in interval(0, 19));\n        assert(sum in interval(0, (numLen - p) * 10));\n        assert(i in interval(0, 9));\n        assert(x in interval(0, 9));\n        sum += od ? i : x;\n        od = !od;\n    }\n\n    return ok && (sum % 10) == 0;\n}\n\n\nvoid main() {\n    foreach (immutable n; [\"49927398716\", \"49927398717\",\n                           \"1234567812345678\", \"1234567812345670\",\n                           \"123456781234567D\"])\n        writefln(\"%s is %svalid\", n, luhnTest(n) ? \"\" : \"not \");\n}\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It first reverses the order of the digits, then sums the odd digits to form a partial sum (s1). It also multiplies the even digits by two, sums the digits if the result is greater than nine, and forms another partial sum (s2). If the sum of s1 and s2 ends in zero, the number is a valid credit card number. The function is used to validate a list of given numbers.","id":3149}
    {"lang_cluster":"D","source_code":"import std.stdio, std.algorithm, std.array, std.string, std.range;\n\nT pop(T)(ref T[] items, in size_t i) pure \/*nothrow*\/ @safe \/*@nogc*\/ {\n    auto aux = items[i];\n    items = items.remove(i);\n    return aux;\n}\n\nstring josephus(in int n, in int k) pure \/*nothrow*\/ @safe {\n    auto p = n.iota.array;\n    int i;\n    immutable(int)[] seq;\n    while (!p.empty) {\n        i = (i + k - 1) % p.length;\n        seq ~= p.pop(i);\n    }\n\n    return format(\"Prisoner killing order:\\n%(%(%d\u00a0%)\\n%).\" ~\n                  \"\\nSurvivor: %d\",\n                  seq[0 .. $ - 1].chunks(20), seq[$ - 1]);\n}\n\nvoid main() \/*@safe*\/ {\n    josephus(5, 2).writeln;\n    writeln;\n    josephus(41, 3).writeln;\n}\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":3150}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio, std.array;\n\nvoid main() {\n    writeln(\"ha\".replicate(5));\n}\n\n\nimport std.stdio;\n\nvoid main() {\n    char[] chars;     \/\/ create the dynamic array\n    chars.length = 5; \/\/ set the length\n    chars[] = '*';    \/\/ set all characters in the string to '*'\n    writeln(chars);\n}\n\n","human_summarization":"implement a function to repeat a string a certain number of times, and another function to repeat a single character a specified number of times.","id":3151}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.regex;\n\n    immutable s = \"I am a string\";\n\n    \/\/ Test.\n    if (s.match(\"string$\"))\n        \"Ends with 'string'.\".writeln;\n\n    \/\/ Substitute.\n    s.replace(\" a \".regex, \" another \").writeln;\n}\n\n\n","human_summarization":"utilize std.string functions to efficiently match and substitute parts of a string using regular expressions.","id":3152}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.string, std.conv;\n\nvoid main() {\n    int a = 10, b = 20;\n    try {\n        a = readln().strip().to!int();\n        b = readln().strip().to!int();\n    } catch (StdioException e) {}\n    writeln(\"a = \", a, \", b = \", b);\n\n    writeln(\"a + b = \", a + b);\n    writeln(\"a - b = \", a - b);\n    writeln(\"a * b = \", a * b);\n    writeln(\"a \/ b = \", a \/ b);\n    writeln(\"a\u00a0% b = \", a % b);\n    writeln(\"a ^^ b = \", a ^^ b);\n}\n\n\n","human_summarization":"The code takes two integers as input from the user and calculates their sum, difference, product, integer quotient, remainder, and exponentiation. It also indicates the rounding method for quotient and the sign matching for the remainder. It does not include error handling. A bonus feature is the inclusion of the 'divmod' operator example. The division and modulus are defined as in C99.","id":3153}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.algorithm;\n\n    \"the three truths\".count(\"th\").writeln;\n    \"ababababab\".count(\"abab\").writeln;\n}\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":3154}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\n\nvoid hanoi(in int n, in char from, in char to, in char via) {\n    if (n > 0) {\n        hanoi(n - 1, from, via, to);\n        writefln(\"Move disk %d from %s to %s\", n, from, to);\n        hanoi(n - 1, via, to, from);\n    }\n}\n\nvoid main() {\n    hanoi(3, 'L', 'M', 'R');\n}\n\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem, based on the shortest and 'mysterious' TH algorithm.\"","id":3155}
    {"lang_cluster":"D","source_code":"\nT binomial(T)(in T n, T k) pure nothrow {\n    if (k > (n \/ 2))\n        k = n - k;\n    T bc = 1;\n    foreach (T i; T(2) .. k + 1)\n        bc = (bc * (n - k + i)) \/ i;\n    return bc;\n}\n\nvoid main() {\n    import std.stdio, std.bigint;\n\n    foreach (const d; [[5, 3], [100, 2], [100, 98]])\n        writefln(\"(%3d %3d) = %s\", d[0], d[1], binomial(d[0], d[1]));\n    writeln(\"(100  50) = \", binomial(100.BigInt, 50.BigInt));\n}\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is capable of outputting the binomial coefficient of (5,3) which equals 10. The code also includes tasks for generating combinations and permutations, both with and without replacement. Additionally, it can handle large coefficients, as demonstrated by the correct calculation of 100C50.","id":3156}
    {"lang_cluster":"D","source_code":"\nimport std.stdio: writeln;\n\nvoid shellSort(T)(T[] seq) pure nothrow {\n    int inc = seq.length \/ 2;\n    while (inc) {\n        foreach (ref i, el; seq) {\n            while (i >= inc && seq[i - inc] > el) {\n                seq[i] = seq[i - inc];\n                i -= inc;\n            }\n            seq[i] = el;\n        }\n        inc = (inc == 2) ? 1 : cast(int)(inc * 5.0 \/ 11);\n    }\n}\n\nvoid main() {\n    auto data = [22, 7, 2, -5, 8, 4];\n    shellSort(data);\n    writeln(data);\n}\n\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":3157}
    {"lang_cluster":"D","source_code":"\n\nmodule grayscale_image;\n\nimport core.stdc.stdio, std.array, std.algorithm, std.string, std.ascii;\npublic import bitmap;\n\nstruct Gray {\n    ubyte c;\n    enum black = typeof(this)(0);\n    enum white = typeof(this)(255);\n    alias c this;\n}\n\n\nImage!Color loadPGM(Color)(Image!Color img, in string fileName) {\n    static int readNum(FILE* f) nothrow @nogc {\n        int n;\n        while (!fscanf(f, \"%d \", &n)) {\n            if ((n = fgetc(f)) == '#') {\n                while ((n = fgetc(f)) != '\\n')\n                    if (n == EOF)\n                        return 0;\n            } else\n                return 0;\n        }\n        return n;\n    }\n\n    if (img is null)\n        img = new Image!Color();\n\n    auto fin = fopen(fileName.toStringz(), \"rb\");\n    scope(exit) if (fin) fclose(fin);\n    if (!fin)\n        throw new Exception(\"Can't open input file.\");\n\n    if (fgetc(fin) != 'P' ||\n        fgetc(fin) != '5' ||\n        !isWhite(fgetc(fin)))\n        throw new Exception(\"Not a PGM (PPM P5) image.\");\n\n    immutable int nc = readNum(fin);\n    immutable int nr = readNum(fin);\n    immutable int maxVal = readNum(fin);\n    if (nc <= 0 || nr <= 0 || maxVal <= 0)\n        throw new Exception(\"Wrong input image sizes.\");\n    img.allocate(nc, nr);\n    auto pix = new ubyte[img.image.length];\n\n    immutable count = fread(pix.ptr, 1, nc * nr, fin);\n    if (count != nc * nr)\n        throw new Exception(\"Wrong number of items read.\");\n\n    pix.copy(img.image);\n    return img;\n}\n\n\nvoid savePGM(Color)(in Image!Color img, in string fileName)\nin {\n    assert(img !is null);\n    assert(!fileName.empty);\n    assert(img.nx > 0 && img.ny > 0 &&\n           img.image.length == img.nx * img.ny,\n           \"Wrong image.\");\n} body {\n    auto fout = fopen(fileName.toStringz(), \"wb\");\n    if (fout == null)\n        throw new Exception(\"File can't be opened.\");\n    fprintf(fout, \"P5\\n%d %d\\n255\\n\", img.nx, img.ny);\n    auto pix = new ubyte[img.image.length];\n    foreach (i, ref p; pix)\n        p = cast(typeof(pix[0]))img.image[i];\n    immutable count = fwrite(pix.ptr, ubyte.sizeof,\n                             img.nx * img.ny, fout);\n    if (count != img.nx * img.ny)\n        new Exception(\"Wrong number of items written.\");\n    fclose(fout);\n}\n\n\nGray lumCIE(in RGB c) pure nothrow @nogc {\n    return Gray(cast(ubyte)(0.2126 * c.r +\n                            0.7152 * c.g +\n                            0.0722 * c.b + 0.5));\n}\n\nGray lumAVG(in RGB c) pure nothrow @nogc {\n    return Gray(cast(ubyte)(0.3333 * c.r +\n                            0.3333 * c.g +\n                            0.3333 * c.b + 0.5));\n}\n\nImage!Gray rgb2grayImage(alias Conv=lumCIE)(in Image!RGB im) nothrow {\n    auto result = new typeof(return)(im.nx, im.ny);\n    foreach (immutable i, immutable rgb; im.image)\n        result.image[i] = Conv(rgb);\n    return result;\n}\n\nImage!RGB gray2rgbImage(in Image!Gray im) nothrow {\n    auto result = new typeof(return)(im.nx, im.ny);\n    foreach (immutable i, immutable gr; im.image)\n        result.image[i] = RGB(gr, gr, gr);\n    return result;\n}\n\nversion (grayscale_image_main) {\n    void main() {\n        auto im1 = new Image!Gray;\n        im1.loadPGM(\"lena.pgm\");\n        gray2rgbImage(im1).savePPM6(\"lena_rgb.ppm\");\n\n        auto img2 = new Image!RGB;\n        img2.loadPPM6(\"quantum_frog.ppm\");\n        img2.rgb2grayImage.savePGM(\"quantum_frog_grey.pgm\");\n    }\n}\n\n","human_summarization":"extend the data storage type to support grayscale images. They define two operations: one for converting a color image to a grayscale image and another for the reverse conversion. The luminance of a color is calculated using the CIE recommended formula. The codes also ensure that rounding errors in floating-point arithmetic do not cause run-time problems or distorted results when the calculated luminance is stored as an unsigned integer. The bitmap module from the Bitmap Task page is utilized in these codes.","id":3158}
    {"lang_cluster":"D","source_code":"\nLibrary: QD\nuses Library: SDL\nLibrary: SDL_ttf\nLibrary: tools\nmodule test26;\n\nimport qd, SDL_ttf, tools.time;\n\nvoid main() {\n  screen(320, 200);\n  auto last = sec();\n  string text = \"Hello World! \";\n  auto speed = 0.2;\n  int dir = true;\n  while (true) {\n    cls;\n    print(10, 10, Bottom|Right, text);\n    if (sec() - last > speed) {\n      last = sec();\n      if (dir == 0) text = text[$-1] ~ text[0 .. $-1];\n      else text = text[1 .. $] ~ text[0];\n    }\n    flip; events;\n    if (mouse.clicked\n      && mouse.pos in display.select(10, 10, 100, 20)\n    ) dir = !dir;\n  }\n}\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":3159}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\n\nvoid main() {\n    int val;\n    do {\n        val++;\n        write(val, \" \");\n    } while (val % 6 != 0);\n}\n\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":3160}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\n\nvoid showByteLen(T)(T[] str) {\n    writefln(\"Byte length: %2d -\u00a0%(%02x%)\",\n             str.length * T.sizeof, cast(ubyte[])str);\n}\n\nvoid main() {\n    string s1a = \"m\u00f8\u00f8se\"; \/\/ UTF-8\n    showByteLen(s1a);\n    wstring s1b = \"m\u00f8\u00f8se\"; \/\/ UTF-16\n    showByteLen(s1b);\n    dstring s1c = \"m\u00f8\u00f8se\"; \/\/ UTF-32\n    showByteLen(s1c);\n    writeln();\n\n    string s2a = \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\";\n    showByteLen(s2a);\n    wstring s2b = \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\";\n    showByteLen(s2b);\n    dstring s2c = \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\";\n    showByteLen(s2c);\n    writeln();\n\n    string s3a = \"J\u0332o\u0332s\u0332\u00e9\u0332\";\n    showByteLen(s3a);\n    wstring s3b = \"J\u0332o\u0332s\u0332\u00e9\u0332\";\n    showByteLen(s3b);\n    dstring s3c = \"J\u0332o\u0332s\u0332\u00e9\u0332\";\n    showByteLen(s3c);\n}\n\n\n","human_summarization":"calculate the character and byte length of a string, considering UTF-8 and UTF-16 encodings. They handle non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. The codes also have the ability to provide the string length in graphemes if the language supports it.","id":3161}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio;\nimport std.random;\n\nvoid main()\n{\n  Mt19937 gen;\n  gen.seed(unpredictableSeed);\n  auto n = gen.front;\n  writeln(n);\n}\n\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using a system's built-in mechanism, not just a software algorithm, similar to the \/dev\/urandom devices in Unix. It also includes an example of using the MersenneTwisterEngine to generate uniformly-distributed 32-bit numbers with a period of 2^19937.","id":3162}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio;\n\nvoid main() {\n    \/\/ strip first character\n    writeln(\"knight\"[1 .. $]);\n\n    \/\/ strip last character\n    writeln(\"socks\"[0 .. $ - 1]);\n\n    \/\/ strip both first and last characters\n    writeln(\"brooms\"[1 .. $ - 1]);\n}\n\n\n","human_summarization":"The code demonstrates the removal of the first and last characters from a string. It shows how to obtain a string with the first character removed, a string with the last character removed, and a string with both the first and last characters removed. It works with any valid Unicode code point in UTF-8 or UTF-16, focusing on logical characters (code points) rather than 8-bit or 16-bit code units. Handling all Unicode characters for other encodings like 8-bit ASCII or EUC-JP is not required.","id":3163}
    {"lang_cluster":"D","source_code":"\n\nThere is no need to worry about possible collisions with existing files in the filesystem.\nThere is no socket file to be removed upon program termination.\nWe do not need to create a file for the socket at all. This obviates target directory existence, permissions checks, and reduces filesystem clutter. Also, it works in chrooted environments.\n\nbool is_unique_instance()\n{\n    import std.socket;\n    auto socket = new Socket(AddressFamily.UNIX, SocketType.STREAM);\n    auto addr = new UnixAddress(\"\\0\/tmp\/myapp.uniqueness.sock\");\n    try\n    {\n        socket.bind(addr);\n        return true;\n    }\n    catch (SocketOSException e)\n    {\n        import core.stdc.errno : EADDRINUSE;\n\n        if (e.errorCode == EADDRINUSE)\n            return false;\n        else\n            throw e;\n    }\n}\n\n","human_summarization":"The code checks if there is only one instance of the application running by using Unix domain sockets in the abstract namespace. If another instance is found, it displays a message and exits. It generates a unique name for the program and uses it as the address when binding the socket.","id":3164}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.range, std.string, std.algorithm, std.array,\n       std.ascii, std.typecons;\n\nstruct Digit {\n    immutable char d;\n\n    this(in char d_) pure nothrow @safe @nogc\n    in { assert(d_ >= '0' && d_ <= '9'); }\n    body { this.d = d_; }\n\n    this(in int d_) pure nothrow @safe @nogc\n    in { assert(d_ >= '0' && d_ <= '9'); }\n    body { this.d = cast(char)d_; } \/\/ Required cast.\n\n    alias d this;\n}\n\nenum size_t sudokuUnitSide = 3;\nenum size_t sudokuSide = sudokuUnitSide ^^ 2; \/\/ Sudoku grid side.\nalias SudokuTable = Digit[sudokuSide ^^ 2];\n\n\nNullable!SudokuTable sudokuSolver(in ref SudokuTable problem)\npure nothrow {\n    alias Tgrid = uint;\n    Tgrid[SudokuTable.length] grid = void;\n    problem[].map!(c => c - '0').copy(grid[]);\n\n    \/\/ DMD doesn't inline this function. Performance loss.\n    Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc {\n        return grid[y * sudokuSide + x];\n    }\n\n    \/\/ DMD doesn't inline this function. If you want to retain\n    \/\/ the same performance as the C++ entry and you use the DMD\n    \/\/ compiler then this function must be manually inlined.\n    bool checkValidity(in Tgrid val, in size_t x, in size_t y)\n    pure nothrow @safe @nogc {\n        \/*static*\/ foreach (immutable i; staticIota!(0, sudokuSide))\n            if (access(i, y) == val || access(x, i) == val)\n                return false;\n\n        immutable startX = (x \/ sudokuUnitSide) * sudokuUnitSide;\n        immutable startY = (y \/ sudokuUnitSide) * sudokuUnitSide;\n\n        \/*static*\/ foreach (immutable i; staticIota!(0, sudokuUnitSide))\n            \/*static*\/ foreach (immutable j; staticIota!(0, sudokuUnitSide))\n                if (access(startX + j, startY + i) == val)\n                    return false;\n\n        return true;\n    }\n\n    bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc {\n        if (pos == SudokuTable.length)\n            return true;\n        if (grid[pos] > 0)\n            return canPlaceNumbers(pos + 1);\n\n        foreach (immutable n; 1 .. sudokuSide + 1)\n            if (checkValidity(n, pos % sudokuSide, pos \/ sudokuSide)) {\n                grid[pos] = n;\n                if (canPlaceNumbers(pos + 1))\n                    return true;\n                grid[pos] = 0;\n            }\n\n        return false;\n    }\n\n    if (canPlaceNumbers) {\n        \/\/return typeof(return)(grid[]\n        \/\/                      .map!(c => Digit(c + '0'))\n        \/\/                      .array);\n        immutable SudokuTable result = grid[]\n                                       .map!(c => Digit(c + '0'))\n                                       .array;\n        return typeof(return)(result);\n    } else\n        return typeof(return)();\n}\n\nstring representSudoku(in ref SudokuTable sudo)\npure nothrow @safe out(result) {\n    assert(result.countchars(\"1-9\") == sudo[].count!q{a != '0'});\n    assert(result.countchars(\".\") == sudo[].count!q{a == '0'});\n} body {\n    static assert(sudo.length == 81,\n        \"representSudoku works only with a 9x9 Sudoku.\");\n    string result;\n\n    foreach (immutable i; 0 .. sudokuSide) {\n        foreach (immutable j; 0 .. sudokuSide) {\n            result ~= sudo[i * sudokuSide + j];\n            result ~= ' ';\n            if (j == 2 || j == 5)\n                result ~= \"| \";\n        }\n        result ~= \"\\n\";\n        if (i == 2 || i == 5)\n            result ~= \"------+-------+------\\n\";\n    }\n\n    return result.replace(\"0\", \".\");\n}\n\nvoid main() {\n    enum ValidateCells(string s) = s.map!Digit.array;\n\n    immutable SudokuTable problem = ValidateCells!(\"\n        850002400\n        720000009\n        004000000\n        000107002\n        305000900\n        040000000\n        000080070\n        017000000\n        000036040\".removechars(whitespace));\n    problem.representSudoku.writeln;\n\n    immutable solution = problem.sudokuSolver;\n    if (solution.isNull)\n        writeln(\"Unsolvable!\");\n    else\n        solution.get.representSudoku.writeln;\n}\n\n\n","human_summarization":"The code solves a given partially filled 9x9 Sudoku grid and displays the result in a user-friendly format. It utilizes strong static typing and idioms to avoid memory allocations on the heap, making it efficient for larger programs. The solution is inspired by the Algorithmics of Sudoku and a Python Sudoku Solver video from Computerphile.","id":3165}
    {"lang_cluster":"D","source_code":"\n\nvoid main() {\n    import std.stdio, std.random;\n\n    auto a = [1, 2, 3, 4, 5, 6, 7, 8, 9];\n    a.randomShuffle;\n    a.writeln;\n}\n\n\n","human_summarization":"Implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The algorithm can be adjusted to return a new array instead if in-place modification is not suitable. It can also be modified to iterate from left to right for convenience. Test cases are provided for verification.","id":3166}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.datetime, std.traits;\n\nvoid lastFridays(in uint year) {\n    auto date = Date(year, 1, 1);\n    foreach (_; [EnumMembers!Month]) {\n        date.day(date.daysInMonth);\n        date.roll!\"days\"(-(date.dayOfWeek + 2) % 7);\n        writeln(date);\n        date.add!\"months\"(1, AllowDayOverflow.no);\n    }\n}\n\nvoid main() {\n    lastFridays(2012);\n}\n\n2012-Jan-27\n2012-Feb-24\n2012-Mar-30\n2012-Apr-27\n2012-May-25\n2012-Jun-29\n2012-Jul-27\n2012-Aug-31\n2012-Sep-28\n2012-Oct-26\n2012-Nov-30\n2012-Dec-28\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":3167}
    {"lang_cluster":"D","source_code":"\nWorks with: D version 2.0\nimport std.stdio;\n\nvoid main() {\n    write(\"Goodbye, World!\");\n}\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":3168}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.traits;\n\nS rot(S)(in S s, in int key) pure nothrow @safe\nif (isSomeString!S) {\n    auto res = s.dup;\n\n    foreach (immutable i, ref c; res) {\n        if ('a' <= c && c <= 'z')\n            c = ((c - 'a' + key) % 26 + 'a');\n        else if ('A' <= c && c <= 'Z')\n            c = ((c - 'A' + key) % 26 + 'A');\n    }\n    return res;\n}\n\nvoid main() @safe {\n    enum key = 3;\n    immutable txt = \"The five boxing wizards jump quickly\";\n    writeln(\"Original:  \", txt);\n    writeln(\"Encrypted: \", txt.rot(key));\n    writeln(\"Decrypted: \", txt.rot(key).rot(26 - key));\n}\n\n\n","human_summarization":"implement both encoding and decoding functionalities of a Caesar cipher. The cipher rotates the letters of the alphabet based on a key ranging from 1 to 25. It replaces each letter with the next 1st to 25th letter in the alphabet, wrapping Z back to A. The codes also consider the fact that Caesar cipher is identical to Vigen\u00e8re cipher with a key of length 1 and Rot-13 is identical to Caesar cipher with key 13. Despite its simplicity, this cipher provides almost no security.","id":3169}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.bigint, std.math;\n\nT gcd(T)(T a, T b) pure nothrow {\n    while (b) {\n        immutable t = b;\n        b = a % b;\n        a = t;\n    }\n    return a;\n}\n\nT lcm(T)(T m, T n) pure nothrow {\n    if (m == 0) return m;\n    if (n == 0) return n;\n    return abs((m * n) \/ gcd(m, n));\n}\n\nvoid main() {\n    lcm(12, 18).writeln;\n    lcm(\"2562047788015215500854906332309589561\".BigInt,\n        \"6795454494268282920431565661684282819\".BigInt).writeln;\n}\n\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":3170}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\n\nvoid main(string[] args) {\n    writeln(\"CUSIP       Verdict\");\n    foreach(arg; args[1..$]) {\n        writefln(\"%9s\u00a0: %s\", arg, isValidCusip(arg) ? \"Valid\" : \"Invalid\");\n    }\n}\n\nclass IllegalCharacterException : Exception {\n    this(string msg) {\n        super(msg);\n    }\n}\n\nbool isValidCusip(string cusip) in {\n    assert(cusip.length == 9, \"Incorrect cusip length\");\n} body {\n    try {\n        auto check = cusipCheckDigit(cusip);\n        return cusip[8] == ('0' + check);\n    } catch (IllegalCharacterException e) {\n        return false;\n    }\n}\n\nunittest {\n    \/\/ Oracle Corporation\n    assertEquals(isValidCusip(\"68389X105\"), true);\n\n    \/\/ Oracle Corporation (invalid)\n    assertEquals(isValidCusip(\"68389X106\"), false);\n}\n\nint cusipCheckDigit(string cusip) in {\n    assert(cusip.length == 9, \"Incorrect cusip length\");\n} body {\n    int sum;\n    for (int i=0; i<8; ++i) {\n        char c = cusip[i];\n        int v;\n\n        switch(c) {\n            case '0': .. case '9':\n                v = c - '0';\n                break;\n            case 'A': .. case 'Z':\n                v = c - 'A' + 10;\n                break;\n            case '*':\n                v = 36;\n                break;\n            case '@':\n                v = 37;\n                break;\n            case '#':\n                v = 38;\n                break;\n            default:\n                throw new IllegalCharacterException(\"Saw character: \" ~ c);\n        }\n        if (i%2 == 1) {\n            v = 2 * v;\n        }\n\n        sum = sum + (v \/ 10) + (v % 10);\n    }\n\n   return (10 - (sum % 10)) % 10;\n}\n\nunittest {\n    \/\/ Apple Incorporated\n    assertEquals(cusipCheckDigit(\"037833100\"), 0);\n\n    \/\/ Cisco Systems\n    assertEquals(cusipCheckDigit(\"17275R102\"), 2);\n\n    \/\/ Google Incorporated\n    assertEquals(cusipCheckDigit(\"38259P508\"), 8);\n\n    \/\/ Microsoft Corporation\n    assertEquals(cusipCheckDigit(\"594918104\"), 4);\n\n    \/\/ Oracle Corporation\n    assertEquals(cusipCheckDigit(\"68389X105\"), 5);\n}\n\nversion(unittest) {\n    void assertEquals(T)(T actual, T expected) {\n        import core.exception;\n        import std.conv;\n        if (actual != expected) {\n            throw new AssertError(\"Actual [\" ~ to!string(actual) ~ \"]; Expected [\" ~ to!string(expected) ~ \"]\");\n        }\n    }\n}\n\n\/\/\/ Invoke with `cusip 037833100 17275R102 38259P508 594918104 68389X106 68389X105`\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":3171}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n  import std.stdio, std.system;\n\n  writeln(\"Word size = \", size_t.sizeof * 8, \" bits.\");\n  writeln(endian == Endian.littleEndian ? \"Little\" : \"Big\", \" endian.\");\n}\n\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":3172}
    {"lang_cluster":"D","source_code":"\n\nvoid main() {\n    import std.stdio, std.algorithm, std.conv, std.array, std.regex,\n           std.typecons, std.net.curl;\n\n    immutable r1 = `\"title\":\"Category:([^\"]+)\"`;\n    const languages = get(\"www.rosettacode.org\/w\/api.php?action=query\"~\n                          \"&list=categorymembers&cmtitle=Category:Pro\"~\n                          \"gramming_Languages&cmlimit=500&format=json\")\n                      .matchAll(r1).map!q{ a[1].dup }.array;\n\n    auto pairs = get(\"www.rosettacode.org\/w\/index.php?\" ~\n                      \"title=Special:Categories&limit=5000\")\n                  .matchAll(`title=\"Category:([^\"]+)\">[^<]+` ~\n                            `<\/a>[^(]+\\((\\d+) members\\)`)\n                  .filter!(m => languages.canFind(m[1]))\n                  .map!(m => tuple(m[2].to!uint, m[1].dup));\n\n    foreach (i, res; pairs.array.sort!q{a > b}.release)\n        writefln(\"%3d. %3d - %s\", i + 1, res[]);\n}\n\n\nSample output (top twenty as of 2013-01-24):\n  1. 717 - Tcl\n  2. 663 - Python\n  3. 643 - C\n  4. 626 - PicoLisp\n  5. 622 - J\n  6. 587 - Go\n  7. 587 - Ruby\n  8. 585 - D\n  9. 568 - Perl 6\n 10. 564 - Ada\n 11. 554 - Mathematica\n 12. 535 - Perl\n 13. 532 - Haskell\n 14. 514 - BBC BASIC\n 15. 505 - REXX\n 16. 491 - Java\n 17. 478 - OCaml\n 18. 469 - PureBasic\n 19. 462 - Unicon\n 20. 430 - AutoHotkey\n","human_summarization":"The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It accesses data either through web scraping or using the API method. The code also has the option to filter out incorrect results. The final output is a complete ranked list of all programming languages. The code needs to be compiled with dmd using specific parameters.","id":3173}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio: writeln;\n\nvoid main() {\n    auto collection1 = \"ABC\";\n    foreach (element; collection1) \n        writeln(element);\n\n    auto collection2 = [1, 2, 3];\n    foreach (element; collection1) \n        writeln(element);\n\n    auto collection3 = [1:10, 2:20, 3:30];\n    foreach (element; collection3) \n        writeln(element);\n\n    foreach (key, value; collection3)\n        writeln(key, \" \", value);        \n}\n\n\n","human_summarization":"iterate through each element in a collection in order and print them. This is applicable to collections such as strings, arrays, associative arrays, or those that implement an opApply function or have basic Range methods. The \"for each\" loop is used if available, otherwise another loop is used for iteration.","id":3174}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.string;\n\n    \"Hello,How,Are,You,Today\".split(',').join('.').writeln;\n}\n\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":3175}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.numeric;\n\nlong myGCD(in long x, in long y) pure nothrow @nogc {\n    if (y == 0)\n        return x;\n    return myGCD(y, x % y);\n}\n\nvoid main() {\n    gcd(15, 10).writeln; \/\/ From Phobos.\n    myGCD(15, 10).writeln;\n}\n\n\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":3176}
    {"lang_cluster":"D","source_code":"\n\nimport std.array, std.socket;\n\nvoid main() {\n    auto listener = new TcpSocket;\n    assert(listener.isAlive);\n    listener.bind(new InternetAddress(12321));\n    listener.listen(10);\n\n    Socket currSock;\n    uint bytesRead;\n    ubyte[1] buff;\n\n    while (true) {\n        currSock = listener.accept();\n        while ((bytesRead = currSock.receive(buff)) > 0)\n            currSock.send(buff);\n        currSock.close();\n        buff.clear();\n    }\n}\n\n\nimport std.stdio, std.socket, std.array;\n\nvoid main() {\n    enum ushort port = 7;\n    enum int backlog = 10;\n    enum int max_connections = 60;\n    enum BUFFER_SIZE = 16;\n\n    auto listener = new TcpSocket;\n    assert(listener.isAlive);\n    listener.bind(new InternetAddress(port));\n    listener.listen(backlog);\n    debug writeln(\"Listening on port \", port);\n\n    \/\/ Room for listener.\n    auto sset = new SocketSet(max_connections + 1);\n\n    Socket[] sockets;\n    char[BUFFER_SIZE] buf;\n\n    for (;; sset.reset()) {\n        sset.add(listener);\n        foreach (each; sockets)\n            sset.add(each);\n\n        \/\/ Update socket set with only those sockets that have data\n        \/\/ avaliable for reading. Options are for read, write,\n        \/\/ and error.\n        Socket.select(sset, null, null);\n\n        \/\/ Read the data from each socket remaining, and handle\n        \/\/ the request.\n        for (int i = 0; ; i++) {\nNEXT:\n            if (i == sockets.length)\n                break;\n            if (sset.isSet(sockets[i])) {\n                int read = sockets[i].receive(buf);\n                if (Socket.ERROR == read) {\n                    debug writeln(\"Connection error.\");\n                    goto SOCK_DOWN;\n                } else if (read == 0) {\n                    debug {\n                        try {\n                            \/\/ If the connection closed due to an\n                            \/\/ error, remoteAddress() could fail.\n                            writefln(\"Connection from %s closed.\",\n                                     sockets[i].remoteAddress()\n                                     .toString());\n                        } catch (SocketException) {\n                            writeln(\"Connection closed.\");\n                        }\n                    }\nSOCK_DOWN:\n                    sockets[i].close(); \/\/Release socket resources now.\n\n                    \/\/ Remove from socket from sockets, and id from\n                    \/\/ threads.\n                    if (i != sockets.length - 1)\n                        sockets[i] = sockets.back;\n                    sockets.length--;\n                    debug writeln(\"\\tTotal connections: \",\n                                  sockets.length);\n                    goto NEXT; \/\/ -i- is still the NEXT index.\n                } else {\n                    debug\n                        writefln(\"Received %d bytes from %s:\"\n                                 ~ \"\\n-----\\n%s\\n-----\",\n                                 read,\n                                 sockets[i].remoteAddress().toString(),\n                                 buf[0 .. read]);\n\n                    \/\/ Echo what was sent.\n                    sockets[i].send(buf[0 .. read]);\n                }\n            }\n        }\n\n        \/\/ Connection request.\n        if (sset.isSet(listener)) {\n            Socket sn;\n            try {\n                if (sockets.length < max_connections) {\n                    sn = listener.accept();\n                    debug writefln(\"Connection from %s established.\",\n                                   sn.remoteAddress().toString());\n                    assert(sn.isAlive);\n                    assert(listener.isAlive);\n                    sockets ~= sn;\n                    debug writefln(\"\\tTotal connections: %d\",\n                                   sockets.length);\n                } else {\n                    sn = listener.accept();\n                    debug writefln(\"Rejected connection from %s;\"\n                                   ~ \" too many connections.\",\n                                   sn.remoteAddress().toString());\n                    assert(sn.isAlive);\n                    sn.close();\n                    assert(!sn.isAlive);\n                    assert(listener.isAlive);\n                }\n            } catch (Exception e) {\n                debug writefln(\"Error accepting: %s\", e.toString());\n                if (sn)\n                    sn.close();\n            }\n        }\n    }\n}\n\n","human_summarization":"The code implements an echo server that listens on TCP port 12321, accepts connections, and echoes back complete lines to clients. It supports simultaneous connections from multiple clients, handling each connection in a multi-threaded or multi-process manner. The server continues to respond to other clients even if one client sends a partial line or stops reading responses. Connection information is logged to standard output. The server is designed to prevent denial-of-service attacks by multiplexing clients. However, it processes buffers one character at a time and only supports connections from localhost for testing purposes.","id":3177}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio, std.string, std.array;\n\nvoid main() {\n    foreach (const s; [\"12\", \" 12\\t\", \"hello12\", \"-12\", \"02\",\n                 \"0-12\", \"+12\", \"1.5\", \"1,000\", \"1_000\",\n                 \"0x10\", \"0b10101111_11110000_11110000_00110011\",\n                 \"-0b10101\", \"0x10.5\"])\n        writefln(`isNumeric(\"%s\"): %s`, s, s.strip().isNumeric(true));\n}\n\n\n","human_summarization":"\"Implement a boolean function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, using the Phobos function standard. The function does not recognize binary and hex literals.\"","id":3178}
    {"lang_cluster":"D","source_code":"\n\nauto data = get(\"https:\/\/sourceforge.net\");\nwriteln(data);\n\n","human_summarization":"send a GET request to \"https:\/\/www.w3.org\/\" without authentication, validate the host certificate, and print the response to the console. It also contrasts with the HTTP Request task and HTTPS request with authentication task. The task is implemented using curl.","id":3179}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.array, std.range, std.typecons, std.algorithm;\n\nstruct Vec2 { \/\/ To be replaced with Phobos code.\n    double x, y;\n\n    Vec2 opBinary(string op=\"-\")(in Vec2 other)\n    const pure nothrow @safe @nogc {\n        return Vec2(this.x - other.x, this.y - other.y);\n    }\n\n    typeof(x) cross(in Vec2 other) const pure nothrow @safe @nogc {\n        return this.x * other.y - this.y * other.x;\n    }\n}\n\nimmutable(Vec2)[] clip(in Vec2[] subjectPolygon, in Vec2[] clipPolygon)\npure \/*nothrow*\/ @safe in {\n    assert(subjectPolygon.length > 1);\n    assert(clipPolygon.length > 1);\n    \/\/ Probably clipPolygon needs to be convex and probably\n    \/\/ its vertices need to be listed in a direction.\n} out(result) {\n    assert(result.length > 1);\n} body {\n    alias Edge = Tuple!(Vec2,\"p\", Vec2,\"q\");\n\n    static enum isInside = (in Vec2 p, in Edge cle)\n    pure nothrow @safe @nogc =>\n        (cle.q.x - cle.p.x) * (p.y - cle.p.y) >\n        (cle.q.y - cle.p.y) * (p.x - cle.p.x);\n\n    static Vec2 intersection(in Edge se, in Edge cle)\n    pure nothrow @safe @nogc {\n        immutable dc = cle.p - cle.q;\n        immutable dp = se.p - se.q;\n        immutable n1 = cle.p.cross(cle.q);\n        immutable n2 = se.p.cross(se.q);\n        immutable n3 = 1.0 \/ dc.cross(dp);\n        return Vec2((n1 * dp.x - n2 * dc.x) * n3,\n                    (n1 * dp.y - n2 * dc.y) * n3);\n    }\n\n    \/\/ How much slower is this compared to lower-level code?\n    static enum edges = (in Vec2[] poly) pure nothrow @safe @nogc =>\n        \/\/ poly[$ - 1 .. $].chain(poly).zip!Edge(poly);\n        poly[$ - 1 .. $].chain(poly).zip(poly).map!Edge;\n\n    immutable(Vec2)[] result = subjectPolygon.idup; \/\/ Not nothrow.\n\n    foreach (immutable clipEdge; edges(clipPolygon)) {\n        immutable inputList = result;\n        result.destroy;\n        foreach (immutable inEdge; edges(inputList)) {\n            if (isInside(inEdge.q, clipEdge)) {\n                if (!isInside(inEdge.p, clipEdge))\n                    result ~= intersection(inEdge, clipEdge);\n                result ~= inEdge.q;\n            } else if (isInside(inEdge.p, clipEdge))\n                result ~= intersection(inEdge, clipEdge);\n        }\n    }\n\n    return result;\n}\n\n\/\/ Code adapted from the C version.\nvoid saveEPSImage(in string fileName, in Vec2[] subjPoly,\n                  in Vec2[] clipPoly, in Vec2[] clipped)\nin {\n    assert(!fileName.empty);\n    assert(subjPoly.length > 1);\n    assert(clipPoly.length > 1);\n    assert(clipped.length > 1);\n} body {\n    auto eps = File(fileName, \"w\");\n\n    \/\/ The image bounding box is hard-coded, not computed.\n    eps.writeln(\n\"%%!PS-Adobe-3.0\n%%%%BoundingBox: 40 40 360 360\n\/l {lineto} def\n\/m {moveto} def\n\/s {setrgbcolor} def\n\/c {closepath} def\n\/gs {fill grestore stroke} def\n\");\n\n    eps.writef(\"0 setlinewidth %g %g m \", clipPoly[0].tupleof);\n    foreach (immutable cl; clipPoly[1 .. $])\n        eps.writef(\"%g %g l \", cl.tupleof);\n    eps.writefln(\"c 0.5 0 0 s gsave 1 0.7 0.7 s gs\");\n\n    eps.writef(\"%g %g m \", subjPoly[0].tupleof);\n    foreach (immutable s; subjPoly[1 .. $])\n        eps.writef(\"%g %g l \", s.tupleof);\n    eps.writefln(\"c 0 0.2 0.5 s gsave 0.4 0.7 1 s gs\");\n\n    eps.writef(\"2 setlinewidth [10 8] 0 setdash %g %g m \",\n               clipped[0].tupleof);\n    foreach (immutable c; clipped[1 .. $])\n        eps.writef(\"%g %g l \", c.tupleof);\n    eps.writefln(\"c 0.5 0 0.5 s gsave 0.7 0.3 0.8 s gs\");\n\n    eps.writefln(\"%%%%EOF\");\n    eps.close;\n    writeln(fileName, \" written.\");\n}\n\nvoid main() {\n    alias V = Vec2;\n    immutable subjectPolygon = [V(50, 150), V(200, 50), V(350, 150),\n                                V(350, 300), V(250, 300), V(200, 250),\n                                V(150, 350), V(100, 250), V(100, 200)];\n    immutable clippingPolygon = [V(100, 100), V(300, 100),\n                                 V(300, 300), V(100, 300)];\n    immutable clipped = subjectPolygon.clip(clippingPolygon);\n    writefln(\"%(%s\\n%)\", clipped);\n    saveEPSImage(\"sutherland_hodgman_clipping_out.eps\",\n                 subjectPolygon, clippingPolygon, clipped);\n}\n\n\n","human_summarization":"Implement the Sutherland-Hodgman polygon clipping algorithm to find the intersection of a given arbitrary polygon and a convex polygon. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle and prints the sequence of points defining the resulting clipped polygon. It also provides an option to display all three polygons on a graphical surface, each in a different color, and generates an EPS file as output.","id":3180}
    {"lang_cluster":"D","source_code":"\nimport std.algorithm;\nimport std.stdio;\n\nvoid main() {\n    immutable scores = [\n        \"Solomon\": 44,\n        \"Jason\": 42,\n        \"Errol\": 42,\n        \"Garry\": 41,\n        \"Bernard\": 41,\n        \"Barry\": 41,\n        \"Stephen\": 39\n    ];\n\n    scores.standardRank;\n    scores.modifiedRank;\n    scores.denseRank;\n    scores.ordinalRank;\n    scores.fractionalRank;\n}\n\n\/*\nStandard ranking\n1 44 Solomon\n2 42 Jason\n2 42 Errol\n4 41 Garry\n4 41 Bernard\n4 41 Barry\n7 39 Stephen\n*\/\nvoid standardRank(const int[string] data) {\n    writeln(\"Standard Rank\");\n\n    int rank = 1;\n    foreach (value; data.values.dup.sort!\"a>b\".uniq) {\n        int temp = rank;\n        foreach(k,v; data) {\n            if (v==value) {\n                writeln(temp, \" \", v, \" \", k);\n                rank++;\n            }\n        }\n    }\n\n    writeln;\n}\n\n\/*\nModified ranking\n1 44 Solomon\n3 42 Jason\n3 42 Errol\n6 41 Garry\n6 41 Bernard\n6 41 Barry\n7 39 Stephen\n*\/\nvoid modifiedRank(const int[string] data) {\n    writeln(\"Modified Rank\");\n\n    int rank = 0;\n    foreach (value; data.values.dup.sort!\"a>b\".uniq) {\n        foreach(k,v; data) {\n            if (v==value) {\n                rank++;\n            }\n        }\n        foreach(k,v; data) {\n            if (v==value) {\n                writeln(rank, \" \", v, \" \", k);\n            }\n        }\n    }\n\n    writeln;\n}\n\n\/*\nDense ranking\n1 44 Solomon\n2 42 Jason\n2 42 Errol\n3 41 Garry\n3 41 Bernard\n3 41 Barry\n4 39 Stephen\n*\/\nvoid denseRank(const int[string] data) {\n    writeln(\"Dense Rank\");\n\n    int rank = 1;\n    foreach (value; data.values.dup.sort!\"a>b\".uniq) {\n        foreach(k,v; data) {\n            if (v==value) {\n                writeln(rank, \" \", v, \" \", k);\n            }\n        }\n        rank++;\n    }\n\n    writeln;\n}\n\n\/*\nOrdinal ranking\n1 44 Solomon\n2 42 Jason\n3 42 Errol\n4 41 Garry\n5 41 Bernard\n6 41 Barry\n7 39 Stephen\n*\/\nvoid ordinalRank(const int[string] data) {\n    writeln(\"Ordinal Rank\");\n\n    int rank = 1;\n    foreach (value; data.values.dup.sort!\"a>b\".uniq) {\n        foreach(k,v; data) {\n            if (v==value) {\n                writeln(rank, \" \", v, \" \", k);\n                rank++;\n            }\n        }\n    }\n\n    writeln;\n}\n\n\/*\nFractional ranking\n1,0 44 Solomon\n2,5 42 Jason\n2,5 42 Errol\n5,0 41 Garry\n5,0 41 Bernard\n5,0 41 Barry\n7,0 39 Stephen\n*\/\nvoid fractionalRank(const int[string] data) {\n    writeln(\"Fractional Rank\");\n\n    int rank = 0;\n    foreach (value; data.values.dup.sort!\"a>b\".uniq) {\n        real avg = 0;\n        int cnt;\n\n        foreach(k,v; data) {\n            if (v==value) {\n                rank++;\n                cnt++;\n                avg+=rank;\n            }\n        }\n        avg \/= cnt;\n\n        foreach(k,v; data) {\n            if (v==value) {\n                writef(\"%0.1f \", avg);\n                writeln(v, \" \", k);\n            }\n        }\n    }\n\n    writeln;\n}\n\n\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":3181}
    {"lang_cluster":"D","source_code":"void main() {\n    import std.stdio, std.math;\n\n    enum degrees = 45.0L;\n    enum t0 = degrees * PI \/ 180.0L;\n    writeln(\"Reference:  0.7071067811865475244008\");\n    writefln(\"Sine:      \u00a0%.20f \u00a0%.20f\", PI_4.sin, t0.sin);\n    writefln(\"Cosine:    \u00a0%.20f \u00a0%.20f\", PI_4.cos, t0.cos);\n    writefln(\"Tangent:   \u00a0%.20f \u00a0%.20f\", PI_4.tan, t0.tan);\n\n    writeln;\n    writeln(\"Reference:  0.7853981633974483096156\");\n    immutable real t1 = PI_4.sin.asin;\n    writefln(\"Arcsine:   \u00a0%.20f\u00a0%.20f\", t1, t1 * 180.0L \/ PI);\n\n    immutable real t2 = PI_4.cos.acos;\n    writefln(\"Arccosine: \u00a0%.20f\u00a0%.20f\", t2, t2 * 180.0L \/ PI);\n\n    immutable real t3 = PI_4.tan.atan;\n    writefln(\"Arctangent:\u00a0%.20f\u00a0%.20f\", t3, t3 * 180.0L \/ PI);\n}\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":3182}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.typecons, std.functional;\n\nimmutable struct Item {\n    string name;\n    int weight, value, quantity;\n}\n\nimmutable Item[] items = [\n    {\"map\",           9, 150, 1}, {\"compass\",      13,  35, 1},\n    {\"water\",       153, 200, 3}, {\"sandwich\",     50,  60, 2},\n    {\"glucose\",      15,  60, 2}, {\"tin\",          68,  45, 3},\n    {\"banana\",       27,  60, 3}, {\"apple\",        39,  40, 3},\n    {\"cheese\",       23,  30, 1}, {\"beer\",         52,  10, 3},\n    {\"suntan cream\", 11,  70, 1}, {\"camera\",       32,  30, 1},\n    {\"t-shirt\",      24,  15, 2}, {\"trousers\",     48,  10, 2},\n    {\"umbrella\",     73,  40, 1}, {\"w-trousers\",   42,  70, 1},\n    {\"w-overcoat\",   43,  75, 1}, {\"note-case\",    22,  80, 1},\n    {\"sunglasses\",    7,  20, 1}, {\"towel\",        18,  12, 2},\n    {\"socks\",         4,  50, 1}, {\"book\",         30,  10, 2}];\n\nTuple!(int, const(int)[]) chooseItem(in int iWeight, in int idx) nothrow @safe {\n    alias memoChooseItem = memoize!chooseItem;\n    if (idx < 0)\n        return typeof(return)();\n\n    int bestV;\n    const(int)[] bestList;\n    with (items[idx])\n        foreach (immutable i; 0 .. quantity + 1) {\n            immutable wlim = iWeight - i * weight;\n            if (wlim < 0)\n                break;\n\n            \/\/const (val, taken) = memoChooseItem(wlim, idx - 1);\n            const val_taken = memoChooseItem(wlim, idx - 1);\n            if (val_taken[0] + i * value > bestV) {\n                bestV = val_taken[0] + i * value;\n                bestList = val_taken[1] ~ i;\n            }\n        }\n\n    return tuple(bestV, bestList);\n}\n\nvoid main() {\n    \/\/ const (v, lst) = chooseItem(400, items.length - 1);\n    const v_lst = chooseItem(400, items.length - 1);\n\n    int w;\n    foreach (immutable i, const cnt; v_lst[1])\n        if (cnt > 0) {\n            writeln(cnt, \" \", items[i].name);\n            w += items[i].weight * cnt;\n        }\n\n    writeln(\"Total weight: \", w, \" Value: \", v_lst[0]);\n}\n\n\n","human_summarization":"The code implements a solution to the bounded knapsack problem using memoization. It helps a tourist to decide which items to carry on a trip to maximize the total value without exceeding the weight limit of 4 kg. The items, their weights, values, and available quantities are given in a list, and the tourist can only take whole units of any item.","id":3183}
    {"lang_cluster":"D","source_code":"import core.stdc.signal;\nimport core.thread;\nimport std.concurrency;\nimport std.datetime.stopwatch;\nimport std.stdio;\n\n__gshared int gotint = 0;\nextern(C) void handleSigint(int sig) nothrow @nogc @system {\n    \/*\n     * Signal safety: It is not safe to call clock(), printf(),\n     * or exit() inside a signal handler. Instead, we set a flag.\n     *\/\n    gotint = 1;\n}\n\nvoid main() {\n    auto sw = StopWatch(AutoStart.yes);\n    signal(SIGINT, &handleSigint);\n    for (int i=0; !gotint;) {\n        Thread.sleep(500_000.usecs);\n        if (gotint) {\n            break;\n        }\n        writeln(++i);\n    }\n    sw.stop();\n    auto td = sw.peek();\n    writeln(\"Program has run for \", td);\n}\n\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.","id":3184}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.string;\n\n    immutable s = \"12349\".succ;\n    assert(s == \"12350\");\n}\n\n","human_summarization":"\"Increments a given numerical string.\"","id":3185}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio, std.string, std.algorithm, std.path, std.array;\n\nstring commonDirPath(in string[] paths, in string sep = \"\/\") pure {\n    if (paths.empty)\n        return null;\n    return paths.map!(p => p.split(sep)).reduce!commonPrefix.join(sep);\n}\n\nvoid main() {\n    immutable paths = [\"\/home\/user1\/tmp\/coverage\/test\",\n                       \"\/home\/user1\/tmp\/covert\/operator\",\n                       \"\/home\/user1\/tmp\/coven\/members\"];\n    writeln(`The common path is: \"`, paths.commonDirPath, '\"');\n}\n\n\n","human_summarization":"\"Create a function that identifies and returns the common directory path from a set of given directory paths, using a specified directory separator. The function also includes a test case using '\/' as the directory separator and three specific strings as input paths. The code utilizes the 'std.algorithm.commonPrefix' function to find the common prefix of two ranges.\"","id":3186}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\n\nvoid main() {\n    auto items = [0,1,2,3,4,5];\n    sattoloCycle(items);\n    items.writeln;\n}\n\n\/\/\/ The Sattolo cycle is an algorithm for randomly shuffling an array in such a way that each element ends up in a new position.\nvoid sattoloCycle(R)(R items) {\n    import std.algorithm : swapAt;\n    import std.random : uniform;\n\n    for (int i=items.length; i-- > 1;) {\n        int j = uniform(0, i);\n        items.swapAt(i, j);\n    }\n}\n\nunittest {\n    import std.range : lockstep;\n    auto o = ['a', 'b', 'c', 'd', 'e'];\n\n    auto s = o.dup;\n    sattoloCycle(s);\n    foreach (a, b; lockstep(o, s)) {\n        assert(a != b, \"An element stayed in place unexpectedly.\");\n    }\n}\n\n\n","human_summarization":"Implement the Sattolo cycle algorithm to randomly shuffle an array ensuring each element ends up in a new position. The algorithm modifies the input array in-place, but can be amended to return a new array. The algorithm can also be amended to iterate from left to right. The difference between this and the Knuth shuffle is the range from which j is chosen. Test cases are provided for validation.","id":3187}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.algorithm;\n\nT median(T)(T[] nums) pure nothrow {\n    nums.sort();\n    if (nums.length & 1)\n        return nums[$ \/ 2];\n    else\n        return (nums[$ \/ 2 - 1] + nums[$ \/ 2]) \/ 2.0;\n}\n\nvoid main() {\n    auto a1 = [5.1, 2.6, 6.2, 8.8, 4.6, 4.1];\n    writeln(\"Even median: \", a1.median);\n\n    auto a2 = [5.1, 2.6, 8.8, 4.6, 4.1];\n    writeln(\"Odd median:  \", a2.median);\n}\n\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.","id":3188}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.algorithm, std.conv;\n\n\/\/\/ With if-else.\nvoid fizzBuzz(in uint n) {\n    foreach (immutable i; 1 .. n + 1)\n        if (!(i\u00a0% 15))\n            \"FizzBuzz\".writeln;\n        else if (!(i\u00a0% 3))\n            \"Fizz\".writeln;\n        else if (!(i\u00a0% 5))\n            \"Buzz\".writeln;\n        else\n            i.writeln;\n}\n\n\/\/\/ With switch case.\nvoid fizzBuzzSwitch(in uint n) {\n    foreach (immutable i; 1 .. n + 1)\n        switch (i\u00a0% 15) {\n            case 0:\n                \"FizzBuzz\".writeln;\n                break;\n            case 3, 6, 9, 12:\n                \"Fizz\".writeln;\n                break;\n            case 5, 10:\n                \"Buzz\".writeln;\n                break;\n            default:\n                i.writeln;\n        }\n}\n\nvoid fizzBuzzSwitch2(in uint n) {\n    foreach (immutable i; 1 .. n + 1)\n        (i\u00a0% 15).predSwitch(\n        0,       \"FizzBuzz\",\n        3,       \"Fizz\",\n        5,       \"Buzz\",\n        6,       \"Fizz\",\n        9,       \"Fizz\",\n        10,      \"Buzz\",\n        12,      \"Fizz\",\n        \/*else*\/ i.text).writeln;\n}\n\nvoid main() {\n    100.fizzBuzz;\n    writeln;\n    100.fizzBuzzSwitch;\n    writeln;\n    100.fizzBuzzSwitch2;\n}\n\nimport std;\n\nvoid main()\n{\n    auto fizzbuzz(in uint i)\n    {\n        string r;\n        if (i\u00a0% 3 == 0) r ~= \"fizz\";\n        if (i\u00a0% 5 == 0) r ~= \"buzz\";\n        if (r.length == 0) r ~= i.to!string;\n        return r;\n    }\n    \n    enum r = 1.iota(101).map!fizzbuzz;\n\n    r.each!writeln;\n}\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":3189}
    {"lang_cluster":"D","source_code":"\n\nvoid main() {\n    import std.stdio, std.complex;\n\n    for (real y = -1.2; y < 1.2; y += 0.05) {\n        for (real x = -2.05; x < 0.55; x += 0.03) {\n            auto z = 0.complex;\n            foreach (_; 0 .. 100)\n                z = z ^^ 2 + complex(x, y);\n            write(z.abs < 2 ? '#' : '.');\n        }\n        writeln;\n    }\n}\n\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. It utilizes std.complex as D built-in complex numbers are deprecated. The output produced is similar to the original.","id":3190}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\n\nvoid main() {\n    immutable array = [1, 2, 3, 4, 5];\n\n    int sum = 0;\n    int prod = 1;\n\n    foreach (x; array) {\n        sum += x;\n        prod *= x;\n    }\n\n    writeln(\"Sum: \", sum);\n    writeln(\"Product: \", prod);\n}\n\n\n","human_summarization":"\"Calculates the sum and product of all integers in an array in a single pass.\"","id":3191}
    {"lang_cluster":"D","source_code":"\nimport std.algorithm;\n\nbool leapYear(in uint y) pure nothrow {\n    return (y % 4) == 0 && (y % 100 || (y % 400) == 0);\n}\n\nvoid main() {\n    auto good = [1600, 1660, 1724, 1788, 1848, 1912, 1972, 2032,\n                 2092, 2156, 2220, 2280, 2344, 2348];\n    auto bad =  [1698, 1699, 1700, 1750, 1800, 1810, 1900, 1901,\n                 1973, 2100, 2107, 2200, 2203, 2289];\n    assert(filter!leapYear(bad ~ good).equal(good));\n}\n\n\nimport std.datetime;\n\nvoid main() {\n    assert(yearIsLeapYear(1724));\n    assert(!yearIsLeapYear(1973));\n    assert(!Date(1900, 1, 1).isLeapYear);\n    assert(DateTime(2000, 1, 1).isLeapYear);\n}\n\n","human_summarization":"\"Determines if a given year is a leap year in the Gregorian calendar using the datetime library.\"","id":3192}
    {"lang_cluster":"D","source_code":"\n\nimport std.bitmanip, core.stdc.string, std.conv, std.math, std.array,\n       std.string;\n\nversion (D_InlineAsm_X86) {} else {\n    static assert(false, \"For X86 machine only.\");\n}\n\n\/\/ CTFE construction of transform expressions.\nuint S(in uint n) pure nothrow @safe @nogc {\n    static immutable aux = [7u, 12, 17, 22, 5, 9, 14, 20, 4, 11,\n                            16, 23, 6, 10, 15, 21];\n    return aux[(n \/ 16) * 4 + (n % 4)];\n}\n\nuint K(in uint n) pure nothrow @safe @nogc {\n    uint r = 0;\n    if (n <= 15)\n        r = n;\n    else if (n <= 31)\n        r = 5 * n + 1;\n    else if (n <= 47)\n        r = 3 * n + 5;\n    else\n        r = 7 * n;\n    return r % 16;\n}\n\nuint T(in uint n) pure nothrow @nogc {\n    return cast(uint)(abs(sin(n + 1.0L)) * (2UL ^^ 32));\n}\n\nstring[] ABCD(in int n) pure nothrow {\n    enum abcd = [\"EAX\", \"EBX\", \"ECX\", \"EDX\"];\n    return abcd[(64 - n) % 4 .. 4] ~ abcd[0 .. (64 - n) % 4];\n}\n\nstring SUB(in int n, in string s) pure nothrow {\n    return s\n           .replace(\"ax\", n.ABCD[0])\n           .replace(\"bx\", n.ABCD[1])\n           .replace(\"cx\", n.ABCD[2])\n           .replace(\"dx\", n.ABCD[3]);\n}\n\n\/\/ FF, GG, HH & II expressions part 1 (F, G, H, I).\nstring fghi1(in int n) pure nothrow @nogc {\n    switch (n \/ 16) {\n        case 0:\n            \/\/ (bb & cc) | (~bb & dd)\n            return q{\n                        mov ESI, bx;\n                        mov EDI, bx;\n                        not ESI;\n                        and EDI, cx;\n                        and ESI, dx;\n                        or EDI, ESI;\n                        add ax, EDI;\n                    };\n        case 1:\n            \/\/ (dd & bb) | (~dd & cc)\n            return q{\n                        mov ESI, dx;\n                        mov EDI, dx;\n                        not ESI;\n                        and EDI, bx;\n                        and ESI, cx;\n                        or EDI, ESI;\n                        add ax, EDI;\n                    };\n        case 2: \/\/ (bb ^ cc ^ dd)\n            return q{\n                        mov EDI, bx;\n                        xor EDI, cx;\n                        xor EDI, dx;\n                        add ax, EDI;\n                    };\n        case 3: \/\/ (cc ^ (bb | ~dd))\n            return q{\n                       mov EDI, dx;\n                       not EDI;\n                       or EDI, bx;\n                       xor EDI, cx;\n                       add ax, EDI;\n                    };\n        default:\n            assert(false);\n    }\n}\n\n\/\/ FF, GG, HH & II expressions part 2.\nstring fghi2(in int n) pure nothrow {\n    return q{\n                add ax, [EBP + 4 * KK];\n                add ax, TT;\n            } ~ n.fghi1;\n}\n\n\/\/ FF, GG, HH & II expressions prepended with previous parts\n\/\/ & subsitute ABCD.\nstring FGHI(in int n) pure nothrow {\n    \/\/ aa = ((aa << SS)|( aa >>> (32 - SS))) + bb = ROL(aa, SS) + bb\n    return SUB(n, n.fghi2 ~ q{\n                                rol ax, SS;\n                                add ax, bx;\n                             });\n}\n\nstring genExpr(uint n) pure nothrow {\n    return FGHI(n)\n           .replace(\"SS\", n.S.text)\n           .replace(\"KK\", n.K.text)\n           .replace(\"TT\", \"0x\" ~ to!string(n.T, 16));\n}\n\nstring genTransformCode(int n) pure nothrow {\n    return (n < 63) ? n.genExpr ~ genTransformCode(n + 1) : n.genExpr;\n}\n\nenum string coreZMD5 = 0.genTransformCode;\n\nstruct ZMD5 {\n    uint[4] state = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476];\n    ulong count;\n    ubyte[64] buffer;\n\n    ubyte[64] padding = [\n      0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n      0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n      0, 0];\n\n    private void transform(ubyte* block) pure nothrow @nogc {\n        uint[16] x = void;\n\n        version (BigEndian) {\n            foreach (immutable i; 0 .. 16)\n                x[i] = littleEndianToNative!uint(*cast(ubyte[4]*)&block[i * 4]);\n        } else {\n            (cast(ubyte*)x.ptr)[0 .. 64] = block[0 .. 64];\n        }\n\n        auto pState = state.ptr;\n        auto pBuffer = x.ptr;\n\n        asm pure nothrow @nogc {\n            mov  ESI, pState[EBP];\n            mov  EDX, [ESI + 3 * 4];\n            mov  ECX, [ESI + 2 * 4];\n            mov  EBX, [ESI + 1 * 4];\n            mov  EAX, [ESI + 0 * 4];\n            push EBP;\n            push ESI;\n\n            mov  EBP, pBuffer[EBP];\n        }\n\n        mixin(\"asm pure nothrow @nogc { \" ~ coreZMD5 ~ \"}\");\n\n        asm pure nothrow @nogc {\n            pop ESI;\n            pop EBP;\n            add [ESI + 0 * 4], EAX;\n            add [ESI + 1 * 4], EBX;\n            add [ESI + 2 * 4], ECX;\n            add [ESI + 3 * 4], EDX;\n        }\n        x[] = 0;\n    }\n\n    void update(in void[] input) pure nothrow @nogc {\n        auto inputLen = input.length;\n        uint index = (count >> 3) & 0b11_1111U;\n        count += inputLen * 8;\n        immutable uint partLen = 64 - index;\n\n        uint i;\n        if (inputLen >= partLen) {\n            memcpy(&buffer[index], input.ptr, partLen);\n            transform(buffer.ptr);\n            for (i = partLen; i + 63 < inputLen; i += 64)\n                transform((cast(ubyte[])input)[i .. i + 64].ptr);\n            index = 0;\n        } else\n            i = 0;\n\n        if (inputLen - i)\n            memcpy(&buffer[index], &input[i], inputLen - i);\n    }\n\n    void finish(ref ubyte[16] digest) pure nothrow @nogc {\n        ubyte[8] bits = void;\n        bits[0 .. 8] = nativeToLittleEndian(count)[];\n\n        immutable uint index = (count >> 3) & 0b11_1111U;\n        immutable uint padLen = (index < 56) ?\n                                (56 - index) : (120 - index);\n        update(padding[0 .. padLen]);\n        update(bits);\n\n        digest[0 .. 4]   = nativeToLittleEndian(state[0])[];\n        digest[4 .. 8]   = nativeToLittleEndian(state[1])[];\n        digest[8 .. 12]  = nativeToLittleEndian(state[2])[];\n        digest[12 .. 16] = nativeToLittleEndian(state[3])[];\n\n        \/\/ Zeroize sensitive information.\n        memset(&this, 0, ZMD5.sizeof);\n    }\n}\n\nstring getDigestString(in void[][] data...) pure {\n    ZMD5 ctx;\n    foreach (datum; data)\n        ctx.update(datum);\n    ubyte[16] digest;\n    ctx.finish(digest);\n    return format(\"%-(%02X%)\", digest);\n}\n\n\nvoid main() { \/\/ Benchmark code --------------\n    import std.stdio, std.datetime, std.digest.md;\n\n    writefln(`md5  digest(\"\")  =\u00a0%-(%02X%)`, \"\".md5Of);\n    writefln(`zmd5 digest(\"\")  = %s`, \"\".getDigestString);\n\n    enum megaBytes = 512;\n    writefln(\"\\nTest performance \/ message size %dMBytes:\", megaBytes);\n    auto data = new float[megaBytes * 0x40000 + 13];\n\n    StopWatch sw;\n    sw.start;\n    immutable d1 = data.md5Of;\n    sw.stop;\n    immutable time1 = sw.peek.msecs \/ 1000.0;\n    writefln(\"digest(data) =\u00a0%-(%02X%)\", d1);\n    writefln(\"std.md5: %8.2f M\/sec  ( %8.2f secs)\",\n             megaBytes \/ time1, time1);\n\n    sw.reset;\n    sw.start;\n    immutable d2 = data.getDigestString;\n    sw.stop;\n    immutable time2 = sw.peek.msecs \/ 1000.0;\n    writefln(\"digest(data) = %s\", d2);\n    writefln(\"zmd5  \u00a0: %8.2f M\/sec  ( %8.2f secs)\",\n             megaBytes \/ time2, time2);\n}\n\n\nOutput (dmd compiler):\nmd5  digest(\"\")  = D41D8CD98F00B204E9800998ECF8427E\nzmd5 digest(\"\")  = D41D8CD98F00B204E9800998ECF8427E\n\nTest performance \/ message size 512MBytes:\ndigest(data) = A36190ECA92203A477EFC4DAB966CE6F\nstd.md5:    45.85 M\/sec  (    11.17 secs)\ndigest(data) = A36190ECA92203A477EFC4DAB966CE6F\nzmd5  \u00a0:   244.86 M\/sec  (     2.09 secs)\n\nOutput (ldc2 compiler):\nmd5  digest(\"\")  = D41D8CD98F00B204E9800998ECF8427E\nzmd5 digest(\"\")  = D41D8CD98F00B204E9800998ECF8427E\n\nTest performance \/ message size 512MBytes:\ndigest(data) = A36190ECA92203A477EFC4DAB966CE6F\nstd.md5:   310.12 M\/sec  (     1.65 secs)\ndigest(data) = A36190ECA92203A477EFC4DAB966CE6F\nzmd5  \u00a0:   277.06 M\/sec  (     1.85 secs)\n\n","human_summarization":"The code is an implementation of the MD5 Message Digest Algorithm, developed directly from the algorithm's specifications without using built-in or external hashing libraries. It generates a correct message digest for an input string and demonstrates bit manipulation, working with little-endian data, and attention to boundary conditions. The code also includes challenges and implementation choices made during the development process. However, it does not mimic all calling modes and does not use built-in MD5 functions or library routines. The code has been validated with verification strings and hashes from RFC 1321.","id":3193}
    {"lang_cluster":"D","source_code":"import std.stdio, std.range;\n\nvoid main() {\n    int sol = 1;\n    writeln(\"\\t\\tFIRE\\t\\tPOLICE\\t\\tSANITATION\");\n    foreach( f; iota(1,8) ) {\n        foreach( p; iota(1,8) ) {\n            foreach( s; iota(1,8) ) {\n                if( f != p && f != s && p != s && !( p & 1 ) && ( f + s + p == 12 ) ) {\n                    writefln(\"SOLUTION #%2d:\\t%2d\\t\\t%3d\\t\\t%6d\", sol++, f, p, s);\n                }\n            }\n        }\n    }\n}\n\n\n\t\tFIRE\t\tPOLICE\t\tSANITATION\nSOLUTION # 1:\t 1\t\t  4\t\t     7\nSOLUTION # 2:\t 1\t\t  6\t\t     5\nSOLUTION # 3:\t 2\t\t  4\t\t     6\nSOLUTION # 4:\t 2\t\t  6\t\t     4\nSOLUTION # 5:\t 3\t\t  2\t\t     7\nSOLUTION # 6:\t 3\t\t  4\t\t     5\nSOLUTION # 7:\t 4\t\t  2\t\t     6\nSOLUTION # 8:\t 4\t\t  6\t\t     2\nSOLUTION # 9:\t 5\t\t  4\t\t     3\nSOLUTION #10:\t 5\t\t  6\t\t     1\nSOLUTION #11:\t 6\t\t  2\t\t     4\nSOLUTION #12:\t 6\t\t  4\t\t     2\nSOLUTION #13:\t 7\t\t  2\t\t     3\nSOLUTION #14:\t 7\t\t  4\t\t     1  \n\n","human_summarization":"generate all unique combinations of numbers between 1 and 7 for the police, sanitation, and fire departments such that the sum of the numbers is 12 and the police department number is even.","id":3194}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    string src = \"This is a string\";\n\n    \/\/ copy contents:\n    auto dest1 = src.idup;\n\n    \/\/ copy contents to mutable char array\n    auto dest2 = src.dup;\n\n    \/\/ copy just the fat reference of the string\n    auto dest3 = src;\n}\n\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":3195}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.algorithm, std.range;\n\nint male(in int n) pure nothrow {\n    return n ? n - male(n - 1).female : 0;\n}\n\nint female(in int n) pure nothrow {\n    return n ? n - female(n - 1).male : 1;\n}\n\nvoid main() {\n    20.iota.map!female.writeln;\n    20.iota.map!male.writeln;\n}\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":3196}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.random;\n\nvoid main() {\n    const items = [\"foo\", \"bar\", \"baz\"];\n    items[uniform(0, $)].writeln;\n}\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":3197}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.uri;\n\nvoid main() {\n    writeln(decodeComponent(\"http%3A%2F%2Ffoo%20bar%2F\"));\n}\n\nhttp:\/\/foo bar\/\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":3198}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.array, std.range, std.traits;\n\n\/\/\/ Recursive.\nbool binarySearch(R, T)(\/*in*\/ R data, in T x) pure nothrow @nogc\nif (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) {\n    if (data.empty)\n        return false;\n    immutable i = data.length \/ 2;\n    immutable mid = data[i];\n    if (mid > x)\n        return data[0 .. i].binarySearch(x);\n    if (mid < x)\n        return data[i + 1 .. $].binarySearch(x);\n    return true;\n}\n\n\/\/\/ Iterative.\nbool binarySearchIt(R, T)(\/*in*\/ R data, in T x) pure nothrow @nogc\nif (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) {\n    while (!data.empty) {\n        immutable i = data.length \/ 2;\n        immutable mid = data[i];\n        if (mid > x)\n            data = data[0 .. i];\n        else if (mid < x)\n            data = data[i + 1 .. $];\n        else\n            return true;\n    }\n    return false;\n}\n\nvoid main() {\n    \/*const*\/ auto items = [2, 4, 6, 8, 9].assumeSorted;\n    foreach (const x; [1, 8, 10, 9, 5, 2])\n        writefln(\"%2d %5s %5s %5s\", x,\n                 items.binarySearch(x),\n                 items.binarySearchIt(x),\n                 \/\/ Standard Binary Search:\n                 !items.equalRange(x).empty);\n}\n\n\n","human_summarization":"The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It takes a sorted integer array, a starting point, an ending point, and a \"secret value\" as inputs. The algorithm can be either recursive or iterative and returns whether the number was in the array and its index if found. The code also includes variations of the binary search algorithm that return the leftmost or rightmost insertion point for the given value. It also handles potential overflow bugs.","id":3199}
    {"lang_cluster":"D","source_code":"\nvoid main(in string[] args) {\n    import std.stdio;\n\n    foreach (immutable i, arg; args[1 .. $])\n        writefln(\"#%2d\u00a0: %s\", i + 1, arg);\n}\n\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c \"alpha beta\" -h \"gamma\"'. It also includes functionalities for intelligent parsing of these arguments.","id":3200}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.json;\n    \nvoid main() {\n    auto j = parseJSON(`{ \"foo\": 1, \"bar\": [10, \"apples\"] }`);\n    writeln(toJSON(&j)); \n}\n\n{\"foo\":1,\"bar\":[10,\"apples\"]}\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":3201}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.math;\n\nreal nthroot(in int n, in real A, in real p=0.001) pure nothrow {\n    real[2] x = [A, A \/ n];\n    while (abs(x[1] - x[0]) > p)\n        x = [x[1], ((n - 1) * x[1] + A \/ (x[1] ^^ (n-1))) \/ n];\n    return x[1];\n}\n\nvoid main() {\n    writeln(nthroot(10, 7131.5 ^^ 10));\n    writeln(nthroot(6, 64));\n}\n\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":3202}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.socket;\n\nvoid main() {\n    writeln(Socket.hostName());\n}\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":3203}
    {"lang_cluster":"D","source_code":"import std.stdio;\n\nvoid main() {\n    write(\"Leonardo Numbers: \");\n    leonardoNumbers( 25 );\n\n    write(\"Fibonacci Numbers: \");\n    leonardoNumbers( 25, 0, 1, 0 );\n}\n\nvoid leonardoNumbers(int count, int l0=1, int l1=1, int add=1) {\n    int t;\n    for (int i=0; i<count; ++i) {\n        write(l0, \" \");\n        t = l0 + l1 + add;\n        l0 = l1;\n        l1 = t;\n    }\n    writeln();\n}\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":3204}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.random, std.math, std.algorithm, std.range,\n       std.typetuple;\n\nvoid main() {\n    void op(char c)() {\n        if (stack.length < 2)\n            throw new Exception(\"Wrong expression.\");\n        stack[$ - 2] = mixin(\"stack[$ - 2]\" ~ c ~ \"stack[$ - 1]\");\n        stack.popBack();\n    }\n\n    const problem = iota(4).map!(_ => uniform(1, 10))().array();\n    writeln(\"Make 24 with the digits: \", problem);\n\n    double[] stack;\n    int[] digits;\n    foreach (const char c; readln())\n        switch (c) {\n            case ' ', '\\t', '\\n': break;\n            case '1': .. case '9':\n                stack ~= c - '0';\n                digits ~= c - '0';\n                break;\n            foreach (o; TypeTuple!('+', '-', '*', '\/')) {\n                case o: op!o(); break;\n            }\n            break;\n            default: throw new Exception(\"Wrong char: \" ~ c);\n        }\n\n    if (!digits.sort().equal(problem.dup.sort()))\n        throw new Exception(\"Not using the given digits.\");\n    if (stack.length != 1)\n        throw new Exception(\"Wrong expression.\");\n    writeln(\"Result: \", stack[0]);\n    writeln(abs(stack[0] - 24) < 0.001 ? \"Good job!\" : \"Try again.\");\n}\n\n\nMake 24 with the digits: [1, 8, 9, 8]\n8 1 - 9 + 8 +\nResult: 24\nGood job!\n","human_summarization":"The code generates four random digits from 1 to 9 and prompts the user to input an arithmetic expression using these digits. It then evaluates the expression to check if it equals 24. The code allows the use of multiplication, division, addition, subtraction operators, and brackets. It does not allow the formation of multiple-digit numbers from the given digits.","id":3205}
    {"lang_cluster":"D","source_code":"\nimport std.algorithm, std.array;\n\nalias encode = group;\n\nauto decode(Group!(\"a == b\", string) enc) {\n    return enc.map!(t => [t[0]].replicate(t[1])).join;\n}\n\nvoid main() {\n    immutable s = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWW\" ~\n                  \"WWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\";\n    assert(s.encode.decode.equal(s));\n}\n\nimport std.stdio, std.array, std.conv;\n\n\/\/ Similar to the 'look and say' function.\nstring encode(in string input) pure nothrow @safe {\n    if (input.empty)\n        return input;\n    char last = input[$ - 1];\n    string output;\n    int count;\n\n    foreach_reverse (immutable c; input) {\n        if (c == last) {\n            count++;\n        } else {\n            output = count.text ~ last ~ output;\n            count = 1;\n            last = c;\n        }\n    }\n\n    return count.text ~ last ~ output;\n}\n\nstring decode(in string input) pure \/*@safe*\/ {\n    string i, result;\n\n    foreach (immutable c; input)\n        switch (c) {\n            case '0': .. case '9':\n                i ~= c;\n                break;\n            case 'A': .. case 'Z':\n                if (i.empty)\n                    throw new Exception(\"Can not repeat a letter \" ~\n                        \"without a number of repetitions\");\n                result ~= [c].replicate(i.to!int);\n                i.length = 0;\n                break;\n            default:\n                throw new Exception(\"'\" ~ c ~ \"' is not alphanumeric\");\n        }\n\n    return result;\n}\n\nvoid main() {\n    immutable txt = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWW\" ~\n                    \"WWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\";\n    writeln(\"Input: \", txt);\n    immutable encoded = txt.encode;\n    writeln(\"Encoded: \", encoded);\n    assert(txt == encoded.decode);\n}\n\n\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated sequences of the same character by storing the length of the sequence. It also provides a function to reverse the compression. The system can handle UTF-encoded strings and uses a Variable-length Quantity module. It also handles digits by escaping them with a '#'.","id":3206}
    {"lang_cluster":"D","source_code":"\nimport std.stdio;\n \nvoid main() {\n    string s = \"hello\";\n    writeln(s ~ \" world\");\n    auto s2 = s ~ \" world\";\n    writeln(s2);\n}\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":3207}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.uri;\n\nvoid main() {\n    writeln(encodeComponent(\"http:\/\/foo bar\/\"));\n}\n\nhttp%3A%2F%2Ffoo%20bar%2F\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":3208}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.algorithm, std.string;\n\nstruct Item {\n    string name;\n    real amount, value;\n\n    @property real valuePerKG() @safe const pure nothrow @nogc {\n        return value \/ amount;\n    }\n\n    string toString() const pure \/*nothrow*\/ @safe {\n        return format(\"%10s %7.2f %7.2f %7.2f\",\n                      name, amount, value, valuePerKG);\n    }\n}\n\nreal sumBy(string field)(in Item[] items) @safe pure nothrow @nogc {\n    return reduce!(\"a + b.\" ~ field)(0.0L, items);\n}\n\nvoid main() \/*@safe*\/ {\n    const items = [Item(\"beef\",    3.8, 36.0),\n                   Item(\"pork\",    5.4, 43.0),\n                   Item(\"ham\",     3.6, 90.0),\n                   Item(\"greaves\", 2.4, 45.0),\n                   Item(\"flitch\",  4.0, 30.0),\n                   Item(\"brawn\",   2.5, 56.0),\n                   Item(\"welt\",    3.7, 67.0),\n                   Item(\"salami\",  3.0, 95.0),\n                   Item(\"sausage\", 5.9, 98.0)]\n                  .schwartzSort!(it => -it.valuePerKG)\n                  .release;\n\n    immutable(Item)[] chosen;\n    real space = 15.0;\n    foreach (const item; items)\n        if (item.amount < space) {\n            chosen ~= item;\n            space -= item.amount;\n        } else {\n            chosen ~= Item(item.name, space, item.valuePerKG * space);\n            break;\n        }\n\n    writefln(\"%10s %7s %7s %7s\", \"ITEM\", \"AMOUNT\", \"VALUE\", \"$\/unit\");\n    writefln(\"%(%s\\n%)\", chosen);\n    Item(\"TOTAL\", chosen.sumBy!\"amount\", chosen.sumBy!\"value\").writeln;\n}\n\n\n","human_summarization":"determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.","id":3209}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.algorithm, std.string, std.exception, std.file;\n\nvoid main() {\n    string[][ubyte[]] an;\n    foreach (w; \"unixdict.txt\".readText.splitLines)\n        an[w.dup.representation.sort().release.assumeUnique] ~= w;\n    immutable m = an.byValue.map!q{ a.length }.reduce!max;\n    writefln(\"%(%s\\n%)\", an.byValue.filter!(ws => ws.length == m));\n}\n\n\n","human_summarization":"find the sets of words from the provided URL that are anagrams of each other, with a focus on the sets that contain the most words. The code has two versions with different runtimes, 0.07 and 0.06 seconds, both producing the same output.","id":3210}
    {"lang_cluster":"D","source_code":"import std.stdio, std.string, std.algorithm, std.array;\n\nauto sierpinskiCarpet(in int n) pure nothrow @safe {\n    auto r = [\"#\"];\n    foreach (immutable _; 0 .. n) {\n        const p = r.map!q{a ~ a ~ a}.array;\n        r = p ~ r.map!q{a ~ a.replace(\"#\", \" \") ~ a}.array ~ p;\n    }\n    return r.join('\\n');\n}\n\nvoid main() {\n    3.sierpinskiCarpet.writeln;\n}\n\n\nimport std.stdio, std.algorithm, std.range, std.functional;\n\nauto nextCarpet(in string[] c) pure nothrow {\n    \/*immutable*\/ const b = c.map!q{a ~ a ~ a}.array;\n    return b ~ c.map!q{a ~ a.replace(\"#\", \" \") ~ a}.array ~ b;\n}\n\nvoid main() {\n    [\"#\"]\n    .recurrence!((a, n) => a[n - 1].nextCarpet)\n    .dropExactly(3)\n    .front\n    .binaryReverseArgs!writefln(\"%-(%s\\n%)\");\n}\n\n\nimport std.stdio, std.array;\n\nchar[][] sierpinskiCarpet(in size_t n) pure nothrow @safe {\n    auto mat = uninitializedArray!(typeof(return))(3 ^^ n, 3 ^^ n);\n\n    foreach (immutable r, row; mat) {\n        row[] = '#';\n        foreach (immutable c, ref cell; row) {\n            size_t r2 = r, c2 = c;\n            while (r2 && c2) {\n                if (r2 % 3 == 1 && c2 % 3 == 1) {\n                    cell = ' ';\n                    break;\n                }\n                r2 \/= 3;\n                c2 \/= 3;\n            }\n        }\n    }\n\n    return mat;\n}\n\nvoid main() {\n    writefln(\"%-(%s\\n%)\", 3.sierpinskiCarpet);\n    7.sierpinskiCarpet.length.writeln;\n}\n\n","human_summarization":"generate an ASCII-art or graphical representation of a Sierpinski carpet of a given order, N. The representation uses specific placement of whitespace and non-whitespace characters.","id":3211}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.algorithm, std.typecons, std.container, std.array;\n\nauto encode(alias eq, R)(Group!(eq, R) sf) \/*pure nothrow @safe*\/ {\n    auto heap = sf.map!(s => tuple(s[1], [tuple(s[0], \"\")]))\n                .array.heapify!q{b < a};\n\n    while (heap.length > 1) {\n        auto lo = heap.front; heap.removeFront;\n        auto hi = heap.front; heap.removeFront;\n        lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]);\n        hi[1].each!((ref pair) => pair[1] = '1' ~ pair[1]);\n        heap.insert(tuple(lo[0] + hi[0], lo[1] ~ hi[1]));\n    }\n    return heap.front[1].schwartzSort!q{ tuple(a[1].length, a[0]) };\n}\n\nvoid main() \/*@safe*\/ {\n    immutable s = \"this is an example for huffman encoding\"d;\n    foreach (const p; s.dup.sort().group.encode)\n        writefln(\"'%s'  %s\", p[]);\n}\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":3212}
    {"lang_cluster":"D","source_code":"\nWorks with: D version 1\nLibrary: DFL\nmodule winapp ;\nimport dfl.all ;\nimport std.string ;\n\nclass MainForm: Form {\n  Label label ;\n  Button button ;\n  this() {\n    width = 240 ;\n    with(label = new Label) {\n      text = \"There have been no clicks yet\" ;\n      dock = DockStyle.TOP ;\n      parent = this ;     \n    }\n    with(button = new Button) {\n      dock = DockStyle.BOTTOM ;\n      text = \"Click Me\" ;\n      parent = this ;\n      click ~= &onClickButton ;\n    }\n    height = label.height + button.height + 36 ;\n  }\n  private void onClickButton(Object sender, EventArgs ea) {\n    static int count = 0 ;\n    label.text = \"You had been clicked me \" ~ std.string.toString(++count) ~ \" times.\" ;\n  }\n}\n\nvoid main() {\n    Application.run(new MainForm);  \n}\n\nWorks with: D version 1\nLibrary: Hybrid\n\nimport \"themes\/default.cfg\"\n\nnew FramedTopLevelWindow main {\n\tframe.text = \"Simple Window\";\n\n\tnew Label label {\n\t\ttext = \"There have been no clicks yet\";\n\t}\n\n\tnew Button button {\n\t\ttext = \"Click me\";\n\t\tsize = 201 20;\n\t}\n}\n\n\nmodule SimpleWindow;\nimport tango.text.convert.Integer;\nimport tango.core.Thread; \/\/ For Thread.yield\n\nimport xf.hybrid.Hybrid; \/\/For widgets and general API\nimport xf.hybrid.backend.GL; \/\/ For OpenGL Renderer\n\nvoid main() {\n\t\/\/load config file\n\tscope cfg = loadHybridConfig(`.\/SimpleWindow.cfg`);\n\tscope renderer = new Renderer;\n\tauto counter = 0;\n\n\tbool programRunning = true;\n\twhile (programRunning) {\n\t\t\/\/ Tell Hybrid what config to use\n\t\tgui.begin(cfg);\n\t\t\/\/ Exit program if user clicks the Close button\n\t\tif (gui().getProperty!(bool)(\"main.frame.closeClicked\")) {\n\t\t\tprogramRunning = false;\n\t\t}\n\t\t\/\/ Update text on the label\n\t\tif (counter != 0)\n\t\t\tLabel(\"main.label\").text = toString(counter);\n\t\t\/\/ Increment counter if the button has been clicked\n\t\tif (Button(\"main.button\").clicked) {\n\t\t\tcounter++;\n\t\t}\n\t\t\/\/ Finalize. Prepare to render\n\t\tgui.end();\n\t\t\/\/ Render window using OpenGL Renderer\n\t\tgui.render(renderer);\n\n\t\tThread.yield();\n\t}\n}\n\n","human_summarization":"The code creates a simple windowed application with a label and a button. Initially, the label displays \"There have been no clicks yet\". When the button labeled \"click me\" is clicked, the label updates to show the number of times the button has been clicked. The GUI layout is described using Hybrid's config files, SimpleWindow.cfg and SimpleWindow.d.","id":3213}
    {"lang_cluster":"D","source_code":"\nimport std.stdio: writeln;\n\nvoid main() {\n    for (int i = 10; i >= 0; --i)\n        writeln(i);\n    writeln();\n\n    foreach_reverse (i ; 0 .. 10 + 1)\n        writeln(i);\n}\n\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":3214}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.string;\n\nstring encrypt(in string txt, in string key) pure @safe\nin {\n    assert(key.removechars(\"^A-Z\") == key);\n} body {\n    string res;\n    foreach (immutable i, immutable c; txt.toUpper.removechars(\"^A-Z\"))\n        res ~= (c + key[i % $] - 2 * 'A') % 26 + 'A';\n    return res;\n}\n\nstring decrypt(in string txt, in string key) pure @safe\nin {\n    assert(key.removechars(\"^A-Z\") == key);\n} body {\n    string res;\n    foreach (immutable i, immutable c; txt.toUpper.removechars(\"^A-Z\"))\n       res ~= (c - key[i % $] + 26) % 26 + 'A';\n    return res;\n}\n\nvoid main() {\n    immutable key = \"VIGENERECIPHER\";\n    immutable original = \"Beware the Jabberwock, my son!\" ~\n                         \" The jaws that bite, the claws that catch!\";\n    immutable encoded = original.encrypt(key);\n    writeln(encoded, \"\\n\", encoded.decrypt(key));\n}\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The code handles keys and text of unequal length, capitalizes all characters, and discards non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":3215}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.range;\n\nvoid main() {\n    \/\/ Print odd numbers up to 9.\n    for (int i = 1; i < 10; i += 2)\n        writeln(i);\n\n    \/\/ Alternative way.\n    foreach (i; iota(1, 10, 2))\n        writeln(i);\n}\n\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":3216}
    {"lang_cluster":"D","source_code":"\n\ndouble sum(ref int i, in int lo, in int hi, lazy double term)\npure @safe \/*nothrow @nogc*\/ {\n    double result = 0.0;\n    for (i = lo; i <= hi; i++)\n        result += term();\n    return result;\n}\n\nvoid main() {\n    import std.stdio;\n\n    int i;\n    sum(i, 1, 100, 1.0\/i).writeln;\n}\n\n\n","human_summarization":"The code is an implementation of Jensen's Device, a programming technique devised by J\u00f8rn Jensen. It uses call by name to compute the 100th harmonic number. The technique relies on the re-evaluation of an expression passed as an actual parameter in the caller's context whenever the corresponding formal parameter's value is required. The first parameter to the sum function, representing the \"bound\" variable of the summation, must also be passed by name or by reference to ensure changes to it are visible in the caller's context. The global variable doesn't need to use the same identifier as the formal parameter.","id":3217}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio;\n\n    enum width = 512, height = 512;\n\n    auto f = File(\"xor_pattern.ppm\", \"wb\");\n    f.writefln(\"P6\\n%d %d\\n255\", width, height);\n    foreach (immutable y; 0 .. height)\n        foreach (immutable x; 0 .. width) {\n            immutable c = (x ^ y) & ubyte.max;\n            immutable ubyte[3] u3 = [255 - c, c \/ 2, c];\n            f.rawWrite(u3);\n        }\n}\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":3218}
    {"lang_cluster":"D","source_code":"\nvoid main() @safe {\n    import std.stdio, std.algorithm, std.range, std.random;\n\n    enum uint w = 14, h = 10;\n    auto vis = new bool[][](h, w),\n         hor = iota(h + 1).map!(_ => [\"+---\"].replicate(w)).array,\n         ver = h.iota.map!(_ => [\"|   \"].replicate(w) ~ \"|\").array;\n\n    void walk(in uint x, in uint y) \/*nothrow*\/ @safe \/*@nogc*\/ {\n        vis[y][x] = true;\n        \/\/foreach (immutable p; [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover) {\n        foreach (const p; [[x-1, y], [x, y+1], [x+1, y], [x, y-1]].randomCover) {\n            if (p[0] >= w || p[1] >= h || vis[p[1]][p[0]]) continue;\n            if (p[0] == x) hor[max(y, p[1])][x] = \"+   \";\n            if (p[1] == y) ver[y][max(x, p[0])] = \"    \";\n            walk(p[0], p[1]);\n        }\n    }\n    walk(uniform(0, w), uniform(0, h));\n    foreach (const a, const b; hor.zip(ver ~ []))\n        join(a ~ \"+\\n\" ~ b).writeln;\n}\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":3219}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio, std.conv, std.string;\n\nstruct PiDigits {\n    immutable uint nDigits;\n\n    int opApply(int delegate(ref string \/*chunk of pi digit*\/) dg){\n        \/\/ Maximum width for correct output, for type ulong.\n        enum size_t width = 9;\n\n        enum ulong scale = 10UL ^^ width;\n        enum ulong initDigit = 2UL * 10UL ^^ (width - 1);\n        enum string formatString = \"%0\" ~ text(width) ~ \"d\";\n\n        immutable size_t len = 10 * nDigits \/ 3;\n        auto arr = new ulong[len];\n        arr[] = initDigit;\n        ulong carry;\n\n        foreach (i; 0 .. nDigits \/ width) {\n            ulong sum;\n            foreach_reverse (j; 0 .. len) {\n                auto quo = sum * (j + 1) + scale * arr[j];\n                arr[j] = quo % (j*2 + 1);\n                sum = quo \/ (j*2 + 1);\n            }\n            auto yield = format(formatString, carry + sum\/scale);\n            if (dg(yield))\n                break;\n            carry = sum % scale;\n        }\n        return 0;\n    }\n}\n\nvoid main() {\n    foreach (d; PiDigits(100))\n        writeln(d);\n}\n\n\n","human_summarization":"continuously calculate and print the next decimal digit of Pi, starting from 3.14159265. The process continues indefinitely until manually stopped by the user. The calculation is based on a modified Spigot algorithm, which has a limitation in terms of memory usage as it increases with the number of digits to be printed.","id":3220}
    {"lang_cluster":"D","source_code":"\n\nvoid main() {\n    assert([1,2,1,3,2] >= [1,2,0,4,4,0,0,0]);\n}\n\n","human_summarization":"\"Function to compare two numerical lists lexicographically and return true if the first list should be ordered before the second, false otherwise.\"","id":3221}
    {"lang_cluster":"D","source_code":"\nulong ackermann(in ulong m, in ulong n) pure nothrow @nogc {\n    if (m == 0)\n        return n + 1;\n    if (n == 0)\n        return ackermann(m - 1, 1);\n    return ackermann(m - 1, ackermann(m, n - 1));\n}\n\nvoid main() {\n    assert(ackermann(2, 4) == 11);\n}\nimport std.stdio, std.bigint, std.conv;\n\nBigInt ipow(BigInt base, BigInt exp) pure nothrow {\n    auto result = 1.BigInt;\n    while (exp) {\n        if (exp & 1)\n            result *= base;\n        exp >>= 1;\n        base *= base;\n    }\n\n    return result;\n}\n\nBigInt ackermann(in uint m, in uint n) pure nothrow\nout(result) {\n    assert(result >= 0);\n} body {\n    static BigInt ack(in uint m, in BigInt n) pure nothrow {\n        switch (m) {\n            case 0: return n + 1;\n            case 1: return n + 2;\n            case 2: return 3 + 2 * n;\n            \/\/case 3: return 5 + 8 * (2 ^^ n - 1);\n            case 3: return 5 + 8 * (ipow(2.BigInt, n) - 1);\n            default: return (n == 0) ?\n                        ack(m - 1, 1.BigInt) :\n                        ack(m - 1, ack(m, n - 1));\n        }\n    }\n\n    return ack(m, n.BigInt);\n}\n\nvoid main() {\n    foreach (immutable m; 1 .. 4)\n        foreach (immutable n; 1 .. 9)\n            writefln(\"ackermann(%d, %d): %s\", m, n, ackermann(m, n));\n    writefln(\"ackermann(4, 1): %s\", ackermann(4, 1));\n\n    immutable a = ackermann(4, 2).text;\n    writefln(\"ackermann(4, 2)) (%d digits):\\n%s...\\n%s\",\n             a.length, a[0 .. 94], a[$ - 96 .. $]);\n}\n\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":3222}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.math, std.mathspecial;\n\nreal taylorGamma(in real x) pure nothrow @safe @nogc {\n    static immutable real[30] table = [\n     0x1p+0,                    0x1.2788cfc6fb618f4cp-1,\n    -0x1.4fcf4026afa2dcecp-1,  -0x1.5815e8fa27047c8cp-5,\n     0x1.5512320b43fbe5dep-3,  -0x1.59af103c340927bep-5,\n    -0x1.3b4af28483e214e4p-7,   0x1.d919c527f60b195ap-8,\n    -0x1.317112ce3a2a7bd2p-10, -0x1.c364fe6f1563ce9cp-13,\n     0x1.0c8a78cd9f9d1a78p-13, -0x1.51ce8af47eabdfdcp-16,\n    -0x1.4fad41fc34fbb2p-20,    0x1.302509dbc0de2c82p-20,\n    -0x1.b9986666c225d1d4p-23,  0x1.a44b7ba22d628acap-28,\n     0x1.57bc3fc384333fb2p-28, -0x1.44b4cedca388f7c6p-30,\n     0x1.cae7675c18606c6p-34,   0x1.11d065bfaf06745ap-37,\n    -0x1.0423bac8ca3faaa4p-38,  0x1.1f20151323cd0392p-41,\n    -0x1.72cb88ea5ae6e778p-46, -0x1.815f72a05f16f348p-48,\n     0x1.6198491a83bccbep-50,  -0x1.10613dde57a88bd6p-53,\n     0x1.5e3fee81de0e9c84p-60,  0x1.a0dc770fb8a499b6p-60,\n    -0x1.0f635344a29e9f8ep-62,  0x1.43d79a4b90ce8044p-66];\n\n    immutable real y = x - 1.0L;\n    real sm = table[$ - 1];\n    foreach_reverse (immutable an; table[0 .. $ - 1])\n        sm = sm * y + an;\n    return 1.0L \/ sm;\n}\n\nreal lanczosGamma(real z) pure nothrow @safe @nogc {\n    \/\/ Coefficients used by the GNU Scientific Library.\n    \/\/ http:\/\/en.wikipedia.org\/wiki\/Lanczos_approximation\n    enum g = 7;\n    static immutable real[9] table =\n        [    0.99999_99999_99809_93,\n           676.52036_81218_851,\n         -1259.13921_67224_028,\n           771.32342_87776_5313,\n          -176.61502_91621_4059,\n            12.50734_32786_86905,\n            -0.13857_10952_65720_12,\n             9.98436_95780_19571_6e-6,\n             1.50563_27351_49311_6e-7];\n\n    \/\/ Reflection formula.\n    if (z < 0.5L) {\n        return PI \/ (sin(PI * z) * lanczosGamma(1 - z));\n    } else {\n        z -= 1;\n        real x = table[0];\n        foreach (immutable i; 1 .. g + 2)\n            x += table[i] \/ (z + i);\n        immutable real t = z + g + 0.5L;\n        return sqrt(2 * PI) * t ^^ (z + 0.5L) * exp(-t) * x;\n    }\n}\n\nvoid main() {\n    foreach (immutable i; 1 .. 11) {\n        immutable real x = i \/ 3.0L;\n        writefln(\"%f: %20.19e %20.19e %20.19e\", x,\n                 x.taylorGamma, x.lanczosGamma, x.gamma);\n    }\n}\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":3223}
    {"lang_cluster":"D","source_code":"\n\nvoid main() {\n    import std.stdio, std.algorithm, std.range, permutations2;\n\n    enum n = 8;\n    n.iota.array.permutations.filter!(p =>\n        n.iota.map!(i => p[i] + i).array.sort().uniq.count == n &&\n        n.iota.map!(i => p[i] - i).array.sort().uniq.count == n)\n    .count.writeln;\n}\n\n\n","human_summarization":"The code solves the N-queens puzzle, which can be extended to a board of size NxN. It uses the second solution of the Permutations task to display all possible solutions. The code's runtime for a board size of 17 is approximately 49.5 seconds when compiled with ldc2.","id":3224}
    {"lang_cluster":"D","source_code":"\nimport std.stdio: writeln;\n \nvoid main() {\n    int[] a = [1, 2];\n    int[] b = [4, 5, 6];\n \n    writeln(a, \" ~ \", b, \" = \", a ~ b);\n}\n\n\n","human_summarization":"demonstrate how to concatenate two arrays.","id":3225}
    {"lang_cluster":"D","source_code":"import std.stdio, std.algorithm, std.typecons, std.array, std.range;\n\nstruct Item { string name; int weight, value; }\n\nItem[] knapsack01DinamicProgramming(immutable Item[] items, in int limit)\npure nothrow @safe {\n    auto tab = new int[][](items.length + 1, limit + 1);\n\n    foreach (immutable i, immutable it; items)\n        foreach (immutable w; 1 .. limit + 1)\n            tab[i + 1][w] = (it.weight > w) ? tab[i][w] :\n                max(tab[i][w], tab[i][w - it.weight] + it.value);\n\n    typeof(return) result;\n    int w = limit;\n    foreach_reverse (immutable i, immutable it; items)\n        if (tab[i + 1][w] != tab[i][w]) {\n            w -= it.weight;\n            result ~= it;\n        }\n\n    return result;\n}\n\nvoid main() @safe {\n    enum int limit = 400;\n    immutable Item[] items = [\n        {\"apple\",      39,  40}, {\"banana\",        27,  60},\n        {\"beer\",       52,  10}, {\"book\",          30,  10},\n        {\"camera\",     32,  30}, {\"cheese\",        23,  30},\n        {\"compass\",    13,  35}, {\"glucose\",       15,  60},\n        {\"map\",         9, 150}, {\"note-case\",     22,  80},\n        {\"sandwich\",   50, 160}, {\"socks\",          4,  50},\n        {\"sunglasses\",  7,  20}, {\"suntan cream\",  11,  70},\n        {\"t-shirt\",    24,  15}, {\"tin\",           68,  45},\n        {\"towel\",      18,  12}, {\"trousers\",      48,  10},\n        {\"umbrella\",   73,  40}, {\"water\",        153, 200},\n        {\"waterproof overclothes\", 43, 75},\n        {\"waterproof trousers\",    42, 70}];\n\n    immutable bag = knapsack01DinamicProgramming(items, limit);\n    writefln(\"Items:\\n%-(  %s\\n%)\", bag.map!q{ a.name }.retro);\n    const t = reduce!q{ a[] += [b.weight, b.value] }([0, 0], bag);\n    writeln(\"\\nTotal weight and value: \", t[0] <= limit ? t : [0, 0]);\n}\n\n\n","human_summarization":"The code determines the optimal combination of items, with individual weights not exceeding 4kg in total, that a tourist can carry in his knapsack to maximize the total value. The items are selected from a predefined list, with each item having a specific weight and value. Only one of each item is available and items cannot be divided. The solution is obtained in approximately 0.04 to 0.09 seconds.","id":3226}
    {"lang_cluster":"D","source_code":"\n\nimport std.stdio, std.array, std.algorithm, std.string;\n\n\nstring[string] matchmaker(string[][string] guyPrefers,\n                          string[][string] girlPrefers) \/*@safe*\/ {\n    string[string] engagedTo;\n    string[] freeGuys = guyPrefers.keys;\n\n    while (freeGuys.length) {\n        const string thisGuy = freeGuys[0];\n        freeGuys.popFront();\n        const auto thisGuyPrefers = guyPrefers[thisGuy];\n        foreach (girl; thisGuyPrefers) {\n            if (girl !in engagedTo) { \/\/ girl is free\n                engagedTo[girl] = thisGuy;\n                break;\n            } else {\n                string otherGuy = engagedTo[girl];\n                string[] thisGirlPrefers = girlPrefers[girl];\n                if (thisGirlPrefers.countUntil(thisGuy) <\n                    thisGirlPrefers.countUntil(otherGuy)) {\n                    \/\/ this girl prefers this guy to\n                    \/\/ the guy she's engagedTo to.\n                    engagedTo[girl] = thisGuy;\n                    freeGuys ~= otherGuy;\n                    break;\n                }\n                \/\/ else no change, keep looking for this guy\n            }\n        }\n    }\n\n    return engagedTo;\n}\n\n\nbool check(bool doPrint=false)(string[string] engagedTo,\n                               string[][string] guyPrefers,\n                               string[][string] galPrefers) @safe {\n    enum MSG = \"%s likes %s better than %s and %s \" ~\n               \"likes %s better than their current partner\";\n    string[string] inverseEngaged;\n    foreach (k, v; engagedTo)\n        inverseEngaged[v] = k;\n\n    foreach (she, he; engagedTo) {\n        auto sheLikes = galPrefers[she];\n        auto sheLikesBetter = sheLikes[0 .. sheLikes.countUntil(he)];\n        auto heLikes = guyPrefers[he];\n        auto heLikesBetter = heLikes[0 .. heLikes.countUntil(she)];\n        foreach (guy; sheLikesBetter) {\n            auto guysGirl = inverseEngaged[guy];\n            auto guyLikes = guyPrefers[guy];\n\n            if (guyLikes.countUntil(guysGirl) >\n                guyLikes.countUntil(she)) {\n                static if (doPrint)\n                    writefln(MSG, she, guy, he, guy, she);\n                return false;\n            }\n        }\n\n        foreach (gal; heLikesBetter) {\n            auto girlsGuy = engagedTo[gal];\n            auto galLikes = galPrefers[gal];\n\n            if (galLikes.countUntil(girlsGuy) >\n                galLikes.countUntil(he)) {\n                static if (doPrint)\n                    writefln(MSG, he, gal, she, gal, he);\n                return false;\n            }\n        }\n    }\n\n    return true;\n}\n\n\nvoid main() \/*@safe*\/ {\n    auto guyData = \"abe  abi eve cath ivy jan dee fay bea hope gay\n                    bob  cath hope abi dee eve fay bea jan ivy gay\n                    col  hope eve abi dee bea fay ivy gay cath jan\n                    dan  ivy fay dee gay hope eve jan bea cath abi\n                    ed   jan dee bea cath fay eve abi ivy hope gay\n                    fred bea abi dee gay eve ivy cath jan hope fay\n                    gav  gay eve ivy bea cath abi dee hope jan fay\n                    hal  abi eve hope fay ivy cath jan bea gay dee\n                    ian  hope cath dee gay bea abi fay ivy jan eve\n                    jon  abi fay jan gay eve bea dee cath ivy hope\";\n\n    auto galData = \"abi  bob fred jon gav ian abe dan ed col hal\n                    bea  bob abe col fred gav dan ian ed jon hal\n                    cath fred bob ed gav hal col ian abe dan jon\n                    dee  fred jon col abe ian hal gav dan bob ed\n                    eve  jon hal fred dan abe gav col ed ian bob\n                    fay  bob abe ed ian jon dan fred gav col hal\n                    gay  jon gav hal fred bob abe col ed dan ian\n                    hope gav jon bob abe ian dan hal ed col fred\n                    ivy  ian col hal gav fred bob abe ed jon dan\n                    jan  ed hal gav abe bob jon col ian fred dan\";\n\n    string[][string] guyPrefers, galPrefers;\n    foreach (line; guyData.splitLines())\n        guyPrefers[split(line)[0]] = split(line)[1..$];\n    foreach (line; galData.splitLines())\n        galPrefers[split(line)[0]] = split(line)[1..$];\n\n    writeln(\"Engagements:\");\n    auto engagedTo = matchmaker(guyPrefers, galPrefers);\n\n    writeln(\"\\nCouples:\");\n    string[] parts;\n    foreach (k; engagedTo.keys.sort())\n        writefln(\"%s is engagedTo to %s\", k, engagedTo[k]);\n    writeln();\n\n    bool c = check!(true)(engagedTo, guyPrefers, galPrefers);\n    writeln(\"Marriages are \", c ? \"stable\" : \"unstable\");\n\n    writeln(\"\\n\\nSwapping two fiances to introduce an error\");\n    auto gals = galPrefers.keys.sort();\n    swap(engagedTo[gals[0]], engagedTo[gals[1]]);\n    foreach (gal; gals[0 .. 2])\n        writefln(\"  %s is now engagedTo to %s\", gal, engagedTo[gal]);\n    writeln();\n\n    c = check!(true)(engagedTo, guyPrefers, galPrefers);\n    writeln(\"Marriages are \", c ? \"stable\" : \"unstable\");\n}\n\n\n","human_summarization":"The code implements the Gale\/Shapley algorithm to solve the Stable Marriage Problem. It takes as input a list of ten males and ten females along with their ranked preferences for potential partners. The code finds a stable set of engagements where no individual prefers someone else over their current partner. It then perturbs this set to create an unstable set of engagements and checks this new set for stability.","id":3227}
    {"lang_cluster":"D","source_code":"import std.stdio, std.algorithm;\n\nT a(T)(T answer) {\n    writefln(\"  # Called function a(%s) -> %s\", answer, answer);\n    return answer;\n}\n\nT b(T)(T answer) {\n    writefln(\"  # Called function b(%s) -> %s\", answer, answer);\n    return answer;\n}\n\nvoid main() {\n    foreach (immutable x, immutable y;\n             [false, true].cartesianProduct([false, true])) {\n        writeln(\"\\nCalculating: r1 = a(x) && b(y)\");\n        immutable r1 = a(x) && b(y);\n        writeln(\"Calculating: r2 = a(x) || b(y)\");\n        immutable r2 = a(x) || b(y);\n    }\n}\n\n\n","human_summarization":"create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.","id":3228}
    {"lang_cluster":"D","source_code":"\nimport std.conv;\nimport std.stdio;\n\nimmutable string[char] morsecode;\n\nstatic this() {\n    morsecode = [\n        'a': \".-\",\n        'b': \"-...\",\n        'c': \"-.-.\",\n        'd': \"-..\",\n        'e': \".\",\n        'f': \"..-.\",\n        'g': \"--.\",\n        'h': \"....\",\n        'i': \"..\",\n        'j': \".---\",\n        'k': \"-.-\",\n        'l': \".-..\",\n        'm': \"--\",\n        'n': \"-.\",\n        'o': \"---\",\n        'p': \".--.\",\n        'q': \"--.-\",\n        'r': \".-.\",\n        's': \"...\",\n        't': \"-\",\n        'u': \"..-\",\n        'v': \"...-\",\n        'w': \".--\",\n        'x': \"-..-\",\n        'y': \"-.--\",\n        'z': \"--..\",\n        '0': \"-----\",\n        '1': \".----\",\n        '2': \"..---\",\n        '3': \"...--\",\n        '4': \"....-\",\n        '5': \".....\",\n        '6': \"-....\",\n        '7': \"--...\",\n        '8': \"---..\",\n        '9': \"----.\"\n    ];\n}\n\nvoid main(string[] args) {\n    foreach (arg; args[1..$]) {\n        writeln(arg);\n        foreach (ch; arg) {\n            if (ch in morsecode) {\n                write(morsecode[ch]);\n            }\n            write(' ');\n        }\n        writeln();\n    }\n}\n\n","human_summarization":"<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":3229}
    {"lang_cluster":"D","source_code":"\nimport std.stdio, std.algorithm, std.string;\n\nbool canMakeWord(in string word, in string[] blocks) pure \/*nothrow*\/ @safe {\n    auto bs = blocks.dup;\n    outer: foreach (immutable ch; word.toUpper) {\n        foreach (immutable block; bs)\n            if (block.canFind(ch)) {\n                bs = bs.remove(bs.countUntil(block));\n                continue outer;\n            }\n        return false;\n    }\n    return true;\n}\n\nvoid main() @safe {\n    immutable blocks = \"BO XK DQ CP NA GT RE TG QD FS JW HU VI\n                        AN OB ER FS LY PC ZM\".split;\n\n    foreach (word; \"\" ~ \"A BARK BoOK TrEAT COmMoN SQUAD conFUsE\".split)\n        writefln(`\"%s\" %s`, word, canMakeWord(word, blocks));\n}\n\n\n","human_summarization":"The code implements a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive. It uses a simple greedy algorithm and avoids heap allocations for efficiency. It can handle ASCII inputs and doesn't shuffle the input blocks. It also includes test cases for seven different words.","id":3230}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio, std.digest.md;\n\n    auto txt = \"The quick brown fox jumped over the lazy dog's back\";\n    writefln(\"%-(%02x%)\", txt.md5Of);\n}\n\n\n","human_summarization":"encode a string using the MD5 algorithm, validate the implementation using test values from IETF RFC (1321), and provide a warning about the known weaknesses of MD5. If a library solution is used, refer to MD5\/Implementation for a scratch implementation.","id":3231}
    {"lang_cluster":"D","source_code":"\nmodule socket ;\nimport std.stdio ;\nimport std.socket ;\nversion(Win32) {\n  \/\/ For Win32 systems, need to link with ws2_32.lib. \n  pragma(lib, \"ws2_32.lib\") ; \n}\nvoid main() {\n  long res;\n  auto socket = new Socket(AddressFamily.INET, SocketType.STREAM) ;\n  socket.connect(new InternetAddress(\"localhost\",256)) ;\n  res = socket.send(cast(void[])\"hello socket world\") ;\n  writefln(\"Socket %d bytes sent.\", res) ;\n  socket.close() ;\n}\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":3232}
    {"lang_cluster":"D","source_code":"\n\nvoid main() {\n    import std.net.curl;\n\n    auto s = SMTP(\"smtps:\/\/smtp.gmail.com\");\n    s.setAuthentication(\"someuser@gmail.com\", \"somepassword\");\n    s.mailTo = [\"<friend@example.com>\"];\n    s.mailFrom = \"<someuser@gmail.com>\";\n    s.message = \"Subject:test\\n\\nExample Message\";\n    s.perform;\n}\n\n","human_summarization":"The code is a function for sending an email, allowing parameters to set From, To, Cc addresses, Subject, and message text, with optional fields for server name and login details. It uses the libcurl library and provides notifications for any issues or success. The code is designed to be portable across different operating systems. Sensitive data used in examples is obfuscated.","id":3233}
    {"lang_cluster":"D","source_code":"\nvoid main() {\n    import std.stdio;\n\n    ubyte i;\n    do writefln(\"%o\", i++);\n    while(i);\n}\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":3234}
    {"lang_cluster":"D","source_code":"\nimport std.algorithm: swap; \/\/ from Phobos standard library\n\n\/\/ The D solution uses templates and it's similar to the C++ one:\nvoid mySwap(T)(ref T left, ref T right) {\n    auto temp = left;\n    left = right;\n    right = temp;\n}\n\nvoid main() {\n    import std.stdio;\n\n    int[] a = [10, 20];\n    writeln(a);\n\n    \/\/ The std.algorithm standard library module\n    \/\/ contains a generic swap:\n    swap(a[0], a[1]);\n    writeln(a);\n\n    \/\/ Using mySwap:\n    mySwap(a[0], a[1]);\n    writeln(a);\n}\n\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.","id":3235}
    {"lang_cluster":"D","source_code":"\nimport std.traits, std.algorithm;\n\nbool isPalindrome1(C)(in C[] s) pure \/*nothrow*\/\nif (isSomeChar!C) {\n    auto s2 = s.dup;\n    s2.reverse(); \/\/ works on Unicode too, not nothrow.\n    return s == s2;\n}\n\nvoid main() {\n    alias pali = isPalindrome1;\n    assert(pali(\"\"));\n    assert(pali(\"z\"));\n    assert(pali(\"aha\"));\n    assert(pali(\"sees\"));\n    assert(!pali(\"oofoe\"));\n    assert(pali(\"deified\"));\n    assert(!pali(\"Deified\"));\n    assert(pali(\"amanaplanacanalpanama\"));\n    assert(pali(\"ingirumimusnocteetconsumimurigni\"));\n    assert(pali(\"sal\u00c3\u00a0las\"));\n}\n\nimport std.traits;\n\nbool isPalindrome2(C)(in C[] s) pure if (isSomeChar!C) {\n    dchar[] dstr;\n    foreach (dchar c; s) \/\/ not nothrow\n        dstr ~= c;\n\n    for (int i; i < dstr.length \/ 2; i++)\n        if (dstr[i] != dstr[$ - i - 1])\n            return false;\n    return true;\n}\n\nvoid main() {\n    alias isPalindrome2 pali;\n    assert(pali(\"\"));\n    assert(pali(\"z\"));\n    assert(pali(\"aha\"));\n    assert(pali(\"sees\"));\n    assert(!pali(\"oofoe\"));\n    assert(pali(\"deified\"));\n    assert(!pali(\"Deified\"));\n    assert(pali(\"amanaplanacanalpanama\"));\n    assert(pali(\"ingirumimusnocteetconsumimurigni\"));\n    assert(pali(\"sal\u00c3\u00a0las\"));\n}\n\nimport std.stdio, core.exception, std.traits;\n\n\/\/ assume alloca() to be pure for this program\nextern(C) pure nothrow void* alloca(in size_t size);\n\nbool isPalindrome3(C)(in C[] s) pure if (isSomeChar!C) {\n    auto p = cast(dchar*)alloca(s.length * 4);\n    if (p == null)\n        \/\/ no fallback heap allocation used\n        throw new OutOfMemoryError();\n    dchar[] dstr = p[0 .. s.length];\n\n    \/\/ use std.utf.stride for an even lower level version\n    int i = 0;\n    foreach (dchar c; s) { \/\/ not nothrow\n        dstr[i] = c;\n        i++;\n    }\n    dstr = dstr[0 .. i];\n\n    foreach (j; 0 .. dstr.length \/ 2)\n        if (dstr[j] != dstr[$ - j - 1])\n            return false;\n    return true;\n}\n\nvoid main() {\n    alias isPalindrome3 pali;\n    assert(pali(\"\"));\n    assert(pali(\"z\"));\n    assert(pali(\"aha\"));\n    assert(pali(\"sees\"));\n    assert(!pali(\"oofoe\"));\n    assert(pali(\"deified\"));\n    assert(!pali(\"Deified\"));\n    assert(pali(\"amanaplanacanalpanama\"));\n    assert(pali(\"ingirumimusnocteetconsumimurigni\"));\n    assert(pali(\"sal\u00c3\u00a0las\"));\n}\n\nbool isPalindrome4(in string str) pure nothrow {\n    if (str.length == 0) return true;\n    immutable(char)* s = str.ptr;\n    immutable(char)* t = &(str[$ - 1]);\n    while (s < t)\n        if (*s++ != *t--) \/\/ ugly\n            return false;\n    return true;\n}\n\nvoid main() {\n    alias isPalindrome4 pali;\n    assert(pali(\"\"));\n    assert(pali(\"z\"));\n    assert(pali(\"aha\"));\n    assert(pali(\"sees\"));\n    assert(!pali(\"oofoe\"));\n    assert(pali(\"deified\"));\n    assert(!pali(\"Deified\"));\n    assert(pali(\"amanaplanacanalpanama\"));\n    assert(pali(\"ingirumimusnocteetconsumimurigni\"));\n    \/\/assert(pali(\"sal\u00c3\u00a0las\"));\n}\n\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":3236}
    {"lang_cluster":"D","source_code":"\nLibrary: phobos\nimport std.stdio, std.process;\n\nvoid main() {\n    auto home = getenv(\"HOME\");\n}\n\nLibrary: tango\nimport tango.sys.Environment;\n\nvoid main() {\n    auto home = Environment(\"HOME\");\n}\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":3237}
    {"lang_cluster":"C#","source_code":"\n\/\/ Non-Generic Stack\nSystem.Collections.Stack stack = new System.Collections.Stack();\nstack.Push( obj );\nbool isEmpty = stack.Count == 0;\nobject top = stack.Peek(); \/\/ Peek without Popping.\ntop = stack.Pop();\n\n\/\/ Generic Stack\nSystem.Collections.Generic.Stack<Foo> stack = new System.Collections.Generic.Stack<Foo>();\nstack.Push(new Foo());\nbool isEmpty = stack.Count == 0;\nFoo top = stack.Peek(); \/\/ Peek without Popping.\ntop = stack.Pop();\n\n","human_summarization":"implement a stack data structure with basic operations such as push (to add elements), pop (to remove and return the last added element), and empty (to check if the stack is empty). This stack follows a Last-In-First-Out (LIFO) access policy.","id":3238}
    {"lang_cluster":"C#","source_code":"\npublic static ulong Fib(uint n) {\n    return (n < 2)? n : Fib(n - 1) + Fib(n - 2);\n}\n\nTail-public static ulong Fib(uint n) {\n    return Fib(0, 1, n);\n}\n\nprivate static ulong Fib(ulong a, ulong b, uint n) {\n    return (n < 1)? a :(n == 1)?  b : Fib(b, a + b, n - 1);\n}\n\npublic static ulong Fib(uint x) {\n    if (x == 0) return 0;\n\n    ulong prev = 0;\n    ulong next = 1;\n    for (int i = 1; i < x; i++)\n    {\n        ulong sum = prev + next;\n        prev = next;\n        next = sum;\n    }\n    return next;\n}\n\nusing System; using System.Text; \/\/ FIBRUS.cs Russia\nnamespace Fibrus { class Program { static void Main() \n{ long fi1=1; long fi2=1; long fi3=1; int da; int i; int d; \nfor (da=1; da<=78; da++) \/\/ rextester.com\/MNGUV70257\n    { d = 20-Convert.ToInt32((Convert.ToString(fi3)).Length);\n    for (i=1; i<d; i++) Console.Write(\".\");\nConsole.Write(fi3); Console.Write(\" \"); Console.WriteLine(da);\n    fi3 = fi2 + fi1;\n    fi1 = fi2;\n    fi2 = fi3;\n}}}}\n\n\n","human_summarization":"The code defines a function to generate the nth Fibonacci number, either iteratively or recursively. It optionally supports negative numbers by using the inverse of the positive definition. The function is accurate up to the 71st Fibonacci number due to custom rounding. It uses System.Windows.Media.Matrix or a similar Matrix class for calculations, and can efficiently calculate large Fibonacci numbers. Additionally, it includes a routine to return an array of Fibonacci numbers.","id":3239}
    {"lang_cluster":"C#","source_code":"\nWorks with: .NET version 1.1\nArrayList array = new ArrayList( new int[] { 1, 2, 3, 4, 5 } );\nArrayList evens = new ArrayList();\nforeach( int i in array )\n{\n        if( (i%2) == 0 )\n                evens.Add( i );\n}\nforeach( int i in evens )\n       System.Console.WriteLine( i.ToString() );\n\nWorks with: .NET version 2.0\nList<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } );\nList<int> evens = array.FindAll( delegate( int i ) { return (i%2)==0; } );\nforeach( int i in evens )\n       System.Console.WriteLine( i.ToString() );\n\nWorks with: .NET version 3.5\nIEnumerable<int> array = new List<int>( new int[] { 1, 2, 3, 4, 5 } );\nIEnumerable<int> evens = array.Where( delegate( int i ) { return (i%2)==0; } );\nforeach( int i in evens )\n       System.Console.WriteLine( i.ToString() );\n\n\nint[] array = { 1, 2, 3, 4, 5 };\nint[] evens = array.Where(i => (i % 2) == 0).ToArray();\n\nforeach (int i in evens)\n    Console.WriteLine(i);\n\n","human_summarization":"select specific elements from an array into a new array, specifically even numbers. Optionally, it also provides a destructive filtering method that modifies the original array instead of creating a new one. The code also demonstrates the replacement of a delegate with a lambda expression for conciseness.","id":3240}
    {"lang_cluster":"C#","source_code":"\nusing System;\nnamespace SubString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string s = \"0123456789\";\n            const int n = 3;\n            const int m = 2;\n            const char c = '3';\n            const string z = \"345\";\n\n            \/\/ A: starting from n characters in and of m length;\n            Console.WriteLine(s.Substring(n, m));\n            \/\/ B: starting from n characters in, up to the end of the string;\n            Console.WriteLine(s.Substring(n, s.Length - n));\n            \/\/ C: whole string minus the last character;\n            Console.WriteLine(s.Substring(0, s.Length - 1));\n            \/\/ D: starting from a known character within the string and of m length;\n            Console.WriteLine(s.Substring(s.IndexOf(c), m));\n            \/\/ E: starting from a known substring within the string and of m length.\n            Console.WriteLine(s.Substring(s.IndexOf(z), m));\n        }\n    }\n}\n\n\n\/\/ B: starting from n characters in, up to the end of the string;\nConsole.WriteLine(s[n..]);\n\/\/ C: whole string minus the last character;\nConsole.WriteLine(s[..^1]);\n\n","human_summarization":"- Display a substring from a specific position and of a certain length.\n- Display a substring from a specific position to the end of the string.\n- Display the entire string except the last character.\n- Display a substring starting from a known character within the string and of a certain length.\n- Display a substring starting from a known substring within the string and of a certain length.\n- The program supports any valid Unicode code point in UTF-8 or UTF-16.\n- The program references logical characters, not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- The program does not necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.\n- Utilizes the Range syntax in C# 8 for more succinct code in certain cases.","id":3241}
    {"lang_cluster":"C#","source_code":"\n\nstatic string ReverseString(string input)\n{\n    char[] inputChars = input.ToCharArray();\n    Array.Reverse(inputChars);\n    return new string(inputChars);\n}\n\n\nusing System.Linq;\n\n\/\/ ...\n\nreturn new string(input.Reverse().ToArray());\n\n\/\/ ...\n\n\npublic string ReverseElements(string s)\n{\n    \/\/ In .NET, a text element is series of code units that is displayed as one character, and so reversing the text\n    \/\/ elements of the string correctly handles combining character sequences and surrogate pairs.\n    var elements = System.Globalization.StringInfo.GetTextElementEnumerator(s);\n    return string.Concat(AsEnumerable(elements).OfType<string>().Reverse());\n}\n\n\/\/ Wraps an IEnumerator, allowing it to be used as an IEnumerable.\npublic IEnumerable AsEnumerable(IEnumerator enumerator)\n{\n    while (enumerator.MoveNext())\n        yield return enumerator.Current;\n}\n\n","human_summarization":"implement a function to reverse a string, preserving Unicode combining characters. The function converts the string to a character array, reverses it, and returns a new string from the reversed array. It uses .Net 3.5 LINQ-to-objects Reverse() extension method and ToArray extension method. It also supports combining characters by separating a string into individual graphemes using System.Globalization.StringInfo.","id":3242}
    {"lang_cluster":"C#","source_code":"\nWorks with: C sharp version 7\nusing static System.Linq.Enumerable;\nusing static System.String;\nusing static System.Console;\nusing System.Collections.Generic;\nusing System;\nusing EdgeList = System.Collections.Generic.List<(int node, double weight)>;\n\npublic static class Dijkstra\n{\n    public static void Main() {\n        Graph graph = new Graph(6);\n        Func<char, int> id = c => c - 'a';\n        Func<int , char> name = i => (char)(i + 'a');\n        foreach (var (start, end, cost) in new [] {\n            ('a', 'b', 7),\n            ('a', 'c', 9),\n            ('a', 'f', 14),\n            ('b', 'c', 10),\n            ('b', 'd', 15),\n            ('c', 'd', 11),\n            ('c', 'f', 2),\n            ('d', 'e', 6),\n            ('e', 'f', 9),\n        }) {\n            graph.AddEdge(id(start), id(end), cost);\n        }\n\n        var path = graph.FindPath(id('a'));\n        for (int d = id('b'); d <= id('f'); d++) {\n            WriteLine(Join(\" -> \", Path(id('a'), d).Select(p => $\"{name(p.node)}({p.distance})\").Reverse()));\n        }\n        \n        IEnumerable<(double distance, int node)> Path(int start, int destination) {\n            yield return (path[destination].distance, destination);\n            for (int i = destination; i != start; i = path[i].prev) {\n                yield return (path[path[i].prev].distance, path[i].prev);\n            }\n        }\n    }\n\n}\n\nsealed class Graph\n{\n    private readonly List<EdgeList> adjacency;\n\n    public Graph(int vertexCount) => adjacency = Range(0, vertexCount).Select(v => new EdgeList()).ToList();\n\n    public int Count => adjacency.Count;\n    public bool HasEdge(int s, int e) => adjacency[s].Any(p => p.node == e);\n    public bool RemoveEdge(int s, int e) => adjacency[s].RemoveAll(p => p.node == e) > 0;\n\n    public bool AddEdge(int s, int e, double weight) {\n        if (HasEdge(s, e)) return false;\n        adjacency[s].Add((e, weight));\n        return true;\n    }\n\n    public (double distance, int prev)[] FindPath(int start) {\n        var info = Range(0, adjacency.Count).Select(i => (distance: double.PositiveInfinity, prev: i)).ToArray();\n        info[start].distance = 0;\n        var visited = new System.Collections.BitArray(adjacency.Count);\n\n        var heap = new Heap<(int node, double distance)>((a, b) => a.distance.CompareTo(b.distance));\n        heap.Push((start, 0));\n        while (heap.Count > 0) {\n            var current = heap.Pop();\n            if (visited[current.node]) continue;\n            var edges = adjacency[current.node];\n            for (int n = 0; n < edges.Count; n++) {\n                int v = edges[n].node;\n                if (visited[v]) continue;\n                double alt = info[current.node].distance + edges[n].weight;\n                if (alt < info[v].distance) {\n                    info[v] = (alt, current.node);\n                    heap.Push((v, alt));\n                }\n            }\n            visited[current.node] = true;\n        }\n        return info;\n    }\n\n}\n\nsealed class Heap<T>\n{\n    private readonly IComparer<T> comparer;\n    private readonly List<T> list = new List<T> { default };\n\n    public Heap() : this(default(IComparer<T>)) { }\n\n    public Heap(IComparer<T> comparer) {\n        this.comparer = comparer ?? Comparer<T>.Default;\n    }\n\n    public Heap(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }\n\n    public int Count => list.Count - 1;\n\n    public void Push(T element) {\n        list.Add(element);\n        SiftUp(list.Count - 1);\n    }\n\n    public T Pop() {\n        T result = list[1];\n        list[1] = list[list.Count - 1];\n        list.RemoveAt(list.Count - 1);\n        SiftDown(1);\n        return result;\n    }\n\n    private static int Parent(int i) => i \/ 2;\n    private static int Left(int i) => i * 2;\n    private static int Right(int i) => i * 2 + 1;\n\n    private void SiftUp(int i) {\n        while (i > 1) {\n            int parent = Parent(i);\n            if (comparer.Compare(list[i], list[parent]) > 0) return;\n            (list[parent], list[i]) = (list[i], list[parent]);\n            i = parent;\n        }\n    }\n\n    private void SiftDown(int i) {\n        for (int left = Left(i); left < list.Count; left = Left(i)) {\n            int smallest = comparer.Compare(list[left], list[i]) <= 0 ? left : i;\n            int right = Right(i);\n            if (right < list.Count && comparer.Compare(list[right], list[smallest]) <= 0) smallest = right;\n            if (smallest == i) return;\n            (list[i], list[smallest]) = (list[smallest], list[i]);\n            i = smallest;\n        }\n    }\n\n}\n\n\n","human_summarization":"Implement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges representing the shortest path to each reachable node. The program also interprets the output to display the shortest path from the source node to specific nodes.","id":3243}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Collections.Generic;\n\npublic enum Direction { FromLeft, FromRight };\n\npublic enum State { Header, LeftHigh, Balanced, RightHigh };\n\npublic enum SetOperation\n{\n    Union,\n    Intersection,\n    SymmetricDifference,\n    Difference,\n    Equality,\n    Inequality,\n    Subset,\n    Superset\n}\n\npublic class Node\n{\n    public Node Left;\n    public Node Right;\n    public Node Parent;\n    public State Balance;\n\n    public Node()\n    {\n        Left = this;\n        Right = this;\n        Parent = null;\n        Balance = State.Header;\n    }\n\n    public Node(Node p)\n    {\n        Left = null;\n        Right = null;\n        Parent = p;\n        Balance = State.Balanced;\n    }\n    \n    public bool IsHeader\n    { get { return Balance == State.Header; } }\n}\n\npublic class SetNode<T> : Node\n{\n    public T Data;\n\n    public SetNode() { }\n    \n    public SetNode(T dataType, Node Parent) : base(Parent)\n    {\n        Data = dataType;\n    }\n\n    public override int GetHashCode()\n    {\n        return Data.GetHashCode();\n    }\n}\n\nclass Utility \/\/ Nongeneric Tree Balancing\n{\n    static void RotateLeft(ref Node Root)\n    {\n        Node Parent = Root.Parent;\n        Node x = Root.Right;\n\n        Root.Parent = x;\n        x.Parent = Parent;\n        if (x.Left != null) x.Left.Parent = Root;\n\n        Root.Right = x.Left;\n        x.Left = Root;\n        Root = x;\n    }\n\n    static void RotateRight(ref Node Root)\n    {\n        Node Parent = Root.Parent;\n        Node x = Root.Left;\n\n        Root.Parent = x;\n        x.Parent = Parent;\n        if (x.Right != null) x.Right.Parent = Root;\n\n        Root.Left = x.Right;\n        x.Right = Root;\n        Root = x;\n    }\n\n    static void BalanceLeft(ref Node Root)\n    {\n        Node Left = Root.Left;\n\n        switch (Left.Balance)\n        {\n            case State.LeftHigh:\n                Root.Balance = State.Balanced;\n                Left.Balance = State.Balanced;\n                RotateRight(ref Root);\n                break;\n\n            case State.RightHigh:\n                {\n                    Node subRight = Left.Right;\n                    switch (subRight.Balance)\n                    {\n                        case State.Balanced:\n                            Root.Balance = State.Balanced;\n                            Left.Balance = State.Balanced;\n                            break;\n\n                        case State.RightHigh:\n                            Root.Balance = State.Balanced;\n                            Left.Balance = State.LeftHigh;\n                            break;\n\n                        case State.LeftHigh:\n                            Root.Balance = State.RightHigh;\n                            Left.Balance = State.Balanced;\n                            break;\n                    }\n                    subRight.Balance = State.Balanced;\n                    RotateLeft(ref Left);\n                    Root.Left = Left;\n                    RotateRight(ref Root);\n                }\n                break;\n\n            case State.Balanced:\n                Root.Balance = State.LeftHigh;\n                Left.Balance = State.RightHigh;\n                RotateRight(ref Root);\n                break;\n        }\n    }\n\n    static void BalanceRight(ref Node Root)\n    {\n        Node Right = Root.Right;\n\n        switch (Right.Balance)\n        {\n            case State.RightHigh:\n                Root.Balance = State.Balanced;\n                Right.Balance = State.Balanced;\n                RotateLeft(ref Root);\n                break;\n\n            case State.LeftHigh:\n                {\n                    Node subLeft = Right.Left; \/\/ Left Subtree of Right\n                    switch (subLeft.Balance)\n                    {\n                        case State.Balanced:\n                            Root.Balance = State.Balanced;\n                            Right.Balance = State.Balanced;\n                            break;\n\n                        case State.LeftHigh:\n                            Root.Balance = State.Balanced;\n                            Right.Balance = State.RightHigh;\n                            break;\n\n                        case State.RightHigh:\n                            Root.Balance = State.LeftHigh;\n                            Right.Balance = State.Balanced;\n                            break;\n                    }\n                    subLeft.Balance = State.Balanced;\n                    RotateRight(ref Right);\n                    Root.Right = Right;\n                    RotateLeft(ref Root);\n                }\n                break;\n\n            case State.Balanced:\n                Root.Balance = State.RightHigh;\n                Right.Balance = State.LeftHigh;\n                RotateLeft(ref Root);\n                break;\n        }\n    }\n\n    public static void BalanceSet(Node Root, Direction From)\n    {\n        bool Taller = true;\n\n        while (Taller)\n        {\n            Node Parent = Root.Parent;\n            Direction NextFrom = (Parent.Left == Root) ? Direction.FromLeft : Direction.FromRight;\n\n            if (From == Direction.FromLeft)\n            {\n                switch (Root.Balance)\n                {\n                    case State.LeftHigh:\n                        if (Parent.IsHeader)\n                            BalanceLeft(ref Parent.Parent);\n                        else if (Parent.Left == Root)\n                            BalanceLeft(ref Parent.Left);\n                        else\n                            BalanceLeft(ref Parent.Right);\n                        Taller = false;\n                        break;\n\n                    case State.Balanced:\n                        Root.Balance = State.LeftHigh;\n                        Taller = true;\n                        break;\n\n                    case State.RightHigh:\n                        Root.Balance = State.Balanced;\n                        Taller = false;\n                        break;\n                }\n            }\n            else\n            {\n                switch (Root.Balance)\n                {\n                    case State.LeftHigh:\n                        Root.Balance = State.Balanced;\n                        Taller = false;\n                        break;\n\n                    case State.Balanced:\n                        Root.Balance = State.RightHigh;\n                        Taller = true;\n                        break;\n\n                    case State.RightHigh:\n                        if (Parent.IsHeader)\n                            BalanceRight(ref Parent.Parent);\n                        else if (Parent.Left == Root)\n                            BalanceRight(ref Parent.Left);\n                        else\n                            BalanceRight(ref Parent.Right);\n                        Taller = false;\n                        break;\n                }\n            }\n\n            if (Taller) \/\/ skip up a level\n            {\n                if (Parent.IsHeader)\n                    Taller = false;\n                else\n                {\n                    Root = Parent;\n                    From = NextFrom;\n                }\n            }\n        }\n    }\n\n    public static void BalanceSetRemove(Node Root, Direction From)\n    {\n        if (Root.IsHeader) return;\n\n        bool Shorter = true;\n\n        while (Shorter)\n        {\n            Node Parent = Root.Parent;\n            Direction NextFrom = (Parent.Left == Root) ? Direction.FromLeft : Direction.FromRight;\n\n            if (From == Direction.FromLeft)\n            {\n                switch (Root.Balance)\n                {\n                    case State.LeftHigh:\n                        Root.Balance = State.Balanced;\n                        Shorter = true;\n                        break;\n\n                    case State.Balanced:\n                        Root.Balance = State.RightHigh;\n                        Shorter = false;\n                        break;\n\n                    case State.RightHigh:\n                        if (Root.Right.Balance == State.Balanced)\n                            Shorter = false;\n                        else\n                            Shorter = true;\n                        if (Parent.IsHeader)\n                            BalanceRight(ref Parent.Parent);\n                        else if (Parent.Left == Root)\n                            BalanceRight(ref Parent.Left);\n                        else\n                            BalanceRight(ref Parent.Right);\n                        break;\n                }\n            }\n            else\n            {\n                switch (Root.Balance)\n                {\n                    case State.RightHigh:\n                        Root.Balance = State.Balanced;\n                        Shorter = true;\n                        break;\n\n                    case State.Balanced:\n                        Root.Balance = State.LeftHigh;\n                        Shorter = false;\n                        break;\n\n                    case State.LeftHigh:\n                        if (Root.Left.Balance == State.Balanced)\n                            Shorter = false;\n                        else\n                            Shorter = true;\n                        if (Parent.IsHeader)\n                            BalanceLeft(ref Parent.Parent);\n                        else if (Parent.Left == Root)\n                            BalanceLeft(ref Parent.Left);\n                        else\n                            BalanceLeft(ref Parent.Right);\n                        break;\n                }\n            }\n\n            if (Shorter)\n            {\n                if (Parent.IsHeader)\n                    Shorter = false;\n                else\n                {\n                    From = NextFrom;\n                    Root = Parent;\n                }\n            }\n        }\n    }\n\n    public static Node PreviousItem(Node Node)\n    {\n        if (Node.IsHeader) { return Node.Right; }\n\n        if (Node.Left != null)\n        {\n            Node = Node.Left;\n            while (Node.Right != null) Node = Node.Right;\n        }\n        else\n        {\n            Node y = Node.Parent;\n            if (y.IsHeader) return y;\n            while (Node == y.Left) { Node = y; y = y.Parent; }\n            Node = y;\n        }\n        return Node;\n    }\n\n    public static Node NextItem(Node Node)\n    {\n        if (Node.IsHeader) return Node.Left;\n\n        if (Node.Right != null)\n        {\n            Node = Node.Right;\n            while (Node.Left != null) Node = Node.Left;\n        }\n        else\n        {\n            Node y = Node.Parent;\n            if (y.IsHeader) return y;\n            while (Node == y.Right) { Node = y; y = y.Parent; }\n            Node = y;\n        }\n        return Node;\n    }\n\n    public static ulong Depth(Node Root)\n    {\n        if (Root != null)\n        {\n            ulong Left = Root.Left != null ? Depth(Root.Left) : 0;\n            ulong Right = Root.Right != null ? Depth(Root.Right) : 0;\n            return Left < Right ? Right + 1 : Left + 1;\n        }\n        else\n            return 0;\n    }\n\n    static void SwapNodeReference(ref Node First,\n                                  ref Node Second)\n    { Node Temporary = First; First = Second; Second = Temporary; }\n\n    public static void SwapNodes(Node A, Node B)\n    {\n        if (B == A.Left)\n        {\n            if (B.Left != null) B.Left.Parent = A;\n            if (B.Right != null) B.Right.Parent = A;\n\n            if (A.Right != null) A.Right.Parent = B;\n\n            if (!A.Parent.IsHeader)\n            {\n                if (A.Parent.Left == A)\n                    A.Parent.Left = B;\n                else\n                    A.Parent.Right = B;\n            }\n            else A.Parent.Parent = B;\n\n            B.Parent = A.Parent;\n            A.Parent = B;\n\n            A.Left = B.Left;\n            B.Left = A;\n\n            SwapNodeReference(ref A.Right, ref B.Right);\n        }\n        else if (B == A.Right)\n        {\n            if (B.Right != null) B.Right.Parent = A;\n            if (B.Left != null) B.Left.Parent = A;\n\n            if (A.Left != null) A.Left.Parent = B;\n\n            if (!A.Parent.IsHeader)\n            {\n                if (A.Parent.Left == A)\n                    A.Parent.Left = B;\n                else\n                    A.Parent.Right = B;\n            }\n            else A.Parent.Parent = B;\n\n            B.Parent = A.Parent;\n            A.Parent = B;\n\n            A.Right = B.Right;\n            B.Right = A;\n\n            SwapNodeReference(ref A.Left, ref B.Left);\n        }\n        else if (A == B.Left)\n        {\n            if (A.Left != null) A.Left.Parent = B;\n            if (A.Right != null) A.Right.Parent = B;\n\n            if (B.Right != null) B.Right.Parent = A;\n\n            if (!B.Parent.IsHeader)\n            {\n                if (B.Parent.Left == B)\n                    B.Parent.Left = A;\n                else\n                    B.Parent.Right = A;\n            }\n            else B.Parent.Parent = A;\n\n            A.Parent = B.Parent;\n            B.Parent = A;\n\n            B.Left = A.Left;\n            A.Left = B;\n\n            SwapNodeReference(ref A.Right, ref B.Right);\n        }\n        else if (A == B.Right)\n        {\n            if (A.Right != null) A.Right.Parent = B;\n            if (A.Left != null) A.Left.Parent = B;\n\n            if (B.Left != null) B.Left.Parent = A;\n\n            if (!B.Parent.IsHeader)\n            {\n                if (B.Parent.Left == B)\n                    B.Parent.Left = A;\n                else\n                    B.Parent.Right = A;\n            }\n            else B.Parent.Parent = A;\n\n            A.Parent = B.Parent;\n            B.Parent = A;\n\n            B.Right = A.Right;\n            A.Right = B;\n\n            SwapNodeReference(ref A.Left, ref B.Left);\n        }\n        else\n        {\n            if (A.Parent == B.Parent)\n                SwapNodeReference(ref A.Parent.Left, ref A.Parent.Right);\n            else\n            {\n                if (!A.Parent.IsHeader)\n                {\n                    if (A.Parent.Left == A)\n                        A.Parent.Left = B;\n                    else\n                        A.Parent.Right = B;\n                }\n                else A.Parent.Parent = B;\n\n                if (!B.Parent.IsHeader)\n                {\n                    if (B.Parent.Left == B)\n                        B.Parent.Left = A;\n                    else\n                        B.Parent.Right = A;\n                }\n                else B.Parent.Parent = A;\n            }\n\n            if (B.Left != null) B.Left.Parent = A;\n            if (B.Right != null) B.Right.Parent = A;\n\n            if (A.Left != null) A.Left.Parent = B;\n            if (A.Right != null) A.Right.Parent = B;\n\n            SwapNodeReference(ref A.Left, ref B.Left);\n            SwapNodeReference(ref A.Right, ref B.Right);\n            SwapNodeReference(ref A.Parent, ref B.Parent);\n        }\n\n        State Balance = A.Balance;\n        A.Balance = B.Balance;\n        B.Balance = Balance;\n    }\n}\n\npublic struct SetEntry<T> : IEnumerator<T>\n{\n    public SetEntry(Node N) { _Node = N; }\n\n    public T Value\n    {\n        get\n        {\n            return ((SetNode<T>)_Node).Data;\n        }\n    }\n\n    public bool IsEnd { get { return _Node.IsHeader; } }\n\n    public bool MoveNext()\n    {\n        _Node = Utility.NextItem(_Node);\n        return _Node.IsHeader ? false : true;\n    }\n\n    public bool MovePrevious()\n    {\n        _Node = Utility.PreviousItem(_Node);\n        return _Node.IsHeader ? false : true;\n    }\n\n    public static SetEntry<T> operator ++(SetEntry<T> entry)\n    {\n        entry._Node = Utility.NextItem(entry._Node);\n        return entry;\n    }\n\n    public static SetEntry<T> operator --(SetEntry<T> entry)\n    {\n        entry._Node = Utility.PreviousItem(entry._Node);\n        return entry;\n    }\n\n    public void Reset()\n    {\n        while (!MoveNext()) ;\n    }\n\n    object System.Collections.IEnumerator.Current\n    { get { return ((SetNode<T>)_Node).Data; } }\n\n    T IEnumerator<T>.Current\n    { get { return ((SetNode<T>)_Node).Data; } }\n\n    public static bool operator ==(SetEntry<T> x, SetEntry<T> y) { return x._Node == y._Node; }\n    public static bool operator !=(SetEntry<T> x, SetEntry<T> y) { return x._Node != y._Node; }\n\n    public override bool Equals(object o) { return _Node == ((SetEntry<T>)o)._Node; }\n\n    public override int GetHashCode() { return _Node.GetHashCode(); }\n\n    public static SetEntry<T> operator +(SetEntry<T> C, ulong Increment)\n    {\n        SetEntry<T> Result = new SetEntry<T>(C._Node);\n        for (ulong i = 0; i < Increment; i++) ++Result;\n        return Result;\n    }\n\n    public static SetEntry<T> operator +(ulong Increment, SetEntry<T> C)\n    {\n        SetEntry<T> Result = new SetEntry<T>(C._Node);\n        for (ulong i = 0; i < Increment; i++) ++Result;\n        return Result;\n    }\n\n    public static SetEntry<T> operator -(SetEntry<T> C, ulong Decrement)\n    {\n        SetEntry<T> Result = new SetEntry<T>(C._Node);\n        for (ulong i = 0; i < Decrement; i++) --Result;\n        return Result;\n    }\n\n    public override string ToString()\n    {\n        return Value.ToString();\n    }\n\n    public void Dispose() { }\n\n    public Node _Node;\n}\n\nclass Set<T> : IEnumerable<T>\n{\n    IComparer<T> Comparer;\n    Node Header;\n    ulong Nodes;\n\n    \/\/*** Constructors ***\n\n    public Set()\n    {\n        Comparer = Comparer<T>.Default;\n        Header = new Node();\n        Nodes = 0;\n    }\n\n    public Set(IComparer<T> c)\n    {\n        Comparer = c;\n        Header = new Node();\n        Nodes = 0;\n    }\n\n    \/\/*** Properties ***\n\n    SetNode<T> Root\n    {\n        get { return (SetNode<T>)Header.Parent; }\n        set { Header.Parent = value; }\n    }\n\n    Node LeftMost\n    {\n        get { return Header.Left; }\n        set { Header.Left = value; }\n    }\n\n    Node RightMost\n    {\n        get { return Header.Right; }\n        set { Header.Right = value; }\n    }\n\n    public SetEntry<T> Begin\n    { get { return new SetEntry<T>(Header.Left); } }\n\n    public SetEntry<T> End\n    { get { return new SetEntry<T>(Header); } }\n\n    public ulong Length { get { return Nodes; } }\n\n    public ulong Depth { get { return Utility.Depth(Root); } }\n\n    \/\/*** Operators ***\n\n    public bool this[T key] { get { return Search(key); } }\n\n    public static Set<T> operator +(Set<T> set, T t)\n    {\n        set.Add(t); return set;\n    }\n\n    public static Set<T> operator -(Set<T> set, T t)\n    {\n        set.Remove(t); return set;\n    }\n\n    public static Set<T> operator |(Set<T> A, Set<T> B)\n    {\n        Set<T> U = new Set<T>(A.Comparer);\n        CombineSets(A, B, U, SetOperation.Union);\n        return U;\n    }\n\n    public static Set<T> operator &(Set<T> A, Set<T> B)\n    {\n        Set<T> I = new Set<T>(A.Comparer);\n        CombineSets(A, B, I, SetOperation.Intersection);\n        return I;\n    }\n\n    public static Set<T> operator ^(Set<T> A, Set<T> B)\n    {\n        Set<T> S = new Set<T>(A.Comparer);\n        CombineSets(A, B, S, SetOperation.SymmetricDifference);\n        return S;\n    }\n\n    public static Set<T> operator -(Set<T> A, Set<T> B)\n    {\n        Set<T> S = new Set<T>(A.Comparer);\n        CombineSets(A, B, S, SetOperation.Difference);\n        return S;\n    }\n\n    public static bool operator ==(Set<T> A, Set<T> B)\n    {\n        return CheckSets(A, B, SetOperation.Equality);\n    }\n\n    public static bool operator !=(Set<T> A, Set<T> B)\n    {\n        return CheckSets(A, B, SetOperation.Inequality);\n    }\n\n    public override bool Equals(object o)\n    {\n        return CheckSets(this, (Set<T>)o, SetOperation.Equality);\n    }\n\n\n    \/\/*** Methods ***\n\n    public void Add(T key)\n    {\n        if (Root == null)\n        {\n            Root = new SetNode<T>(key, Header);\n            LeftMost = RightMost = Root;\n        }\n        else\n        {\n            SetNode<T> Search = Root;\n            for (; ; )\n            {\n                int Compare = Comparer.Compare(key, Search.Data);\n\n                if (Compare == 0) \/\/ Item Exists\n                    throw new EntryAlreadyExistsException();\n\n                else if (Compare < 0)\n                {\n                    if (Search.Left != null)\n                        Search = (SetNode<T>)Search.Left;\n                    else\n                    {\n                        Search.Left = new SetNode<T>(key, Search);\n                        if (LeftMost == Search) LeftMost = (SetNode<T>)Search.Left;\n                        Utility.BalanceSet(Search, Direction.FromLeft);\n                        Nodes++;\n                        break;\n                    }\n                }\n\n                else\n                {\n                    if (Search.Right != null)\n                        Search = (SetNode<T>)Search.Right;\n                    else\n                    {\n                        Search.Right = new SetNode<T>(key, Search);\n                        if (RightMost == Search) RightMost = (SetNode<T>)Search.Right;\n                        Utility.BalanceSet(Search, Direction.FromRight);\n                        Nodes++;\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n    { return new SetEntry<T>(Header); }\n\n    IEnumerator<T> IEnumerable<T>.GetEnumerator()\n    { return new SetEntry<T>(Header); }\n\n    public override int GetHashCode()\n    {\n        return GetHashCode((SetNode<T>)Header.Parent);\n    }\n\n    int GetHashCode(SetNode<T> Root)\n    {\n        if (Root != null)\n        {\n            int HashCode = Root.GetHashCode();\n\n            if (Root.Left != null)\n                HashCode += GetHashCode((SetNode<T>)Root.Left);\n\n            if (Root.Right != null)\n                HashCode += GetHashCode((SetNode<T>)Root.Right);\n\n            return HashCode;\n        }\n\n        return 0;\n    }\n\n\n    public void Remove(T key)\n    {\n        SetNode<T> root = Root;\n\n        for (; ; )\n        {\n            if (root == null)\n                throw new EntryNotFoundException();\n\n            int Compare = Comparer.Compare(key, root.Data);\n\n            if (Compare < 0)\n                root = (SetNode<T>)root.Left;\n\n            else if (Compare > 0)\n                root = (SetNode<T>)root.Right;\n\n            else \/\/ Item is found\n            {\n                if (root.Left != null && root.Right != null)\n                {\n                    SetNode<T> replace = (SetNode<T>)root.Left;\n                    while (replace.Right != null) replace = (SetNode<T>)replace.Right;\n                    Utility.SwapNodes(root, replace);\n                }\n\n                SetNode<T> Parent = (SetNode<T>)root.Parent;\n\n                Direction From = (Parent.Left == root) ? Direction.FromLeft : Direction.FromRight;\n\n                if (LeftMost == root)\n                {\n                    SetEntry<T> e = new SetEntry<T>(root); e.MoveNext();\n\n                    if (e._Node.IsHeader)\n                    { LeftMost = Header; RightMost = Header; }\n                    else\n                        LeftMost = e._Node;\n                }\n                else if (RightMost == root)\n                {\n                    SetEntry<T> e = new SetEntry<T>(root); e.MovePrevious();\n\n                    if (e._Node.IsHeader)\n                    { LeftMost = Header; RightMost = Header; }\n                    else\n                        RightMost = e._Node;\n                }\n\n                if (root.Left == null)\n                {\n                    if (Parent == Header)\n                        Header.Parent = root.Right;\n                    else if (Parent.Left == root)\n                        Parent.Left = root.Right;\n                    else\n                        Parent.Right = root.Right;\n\n                    if (root.Right != null) root.Right.Parent = Parent;\n                }\n                else\n                {\n                    if (Parent == Header)\n                        Header.Parent = root.Left;\n                    else if (Parent.Left == root)\n                        Parent.Left = root.Left;\n                    else\n                        Parent.Right = root.Left;\n\n                    if (root.Left != null) root.Left.Parent = Parent;\n                }\n\n                Utility.BalanceSetRemove(Parent, From);\n                Nodes--;\n                break;\n            }\n        }\n    }\n\n    public bool Search(T key)\n    {\n        if (Root == null)\n            return false;\n        else\n        {\n            SetNode<T> Search = Root;\n\n            do\n            {\n                int Result = Comparer.Compare(key, Search.Data);\n\n                if (Result < 0) Search = (SetNode<T>)Search.Left;\n\n                else if (Result > 0) Search = (SetNode<T>)Search.Right;\n\n                else break;\n\n            } while (Search != null);\n\n            if (Search == null)\n                return false;\n            else\n                return true;\n        }\n    }\n\n    public override string ToString()\n    {\n        string StringOut = \"{\";\n\n        SetEntry<T> start = Begin;\n        SetEntry<T> end = End;\n        SetEntry<T> last = End - 1;\n\n        while (start != end)\n        {\n            string new_StringOut = start.Value.ToString();\n            if (start != last) new_StringOut = new_StringOut + \",\";\n            StringOut = StringOut + new_StringOut;\n            ++start;\n        }\n\n        StringOut = StringOut + \"}\";\n        return StringOut;\n    }\n\n    public void Validate()\n    {\n        if (Nodes == 0 || Root == null)\n        {\n            if (Nodes != 0) { throw new InvalidEmptyTreeException(); }\n            if (Root != null) { throw new InvalidEmptyTreeException(); }\n            if (LeftMost != Header) { throw new InvalidEndItemException(); }\n            if (RightMost != Header) { throw new InvalidEndItemException(); }\n        }\n\n        Validate(Root);\n\n        if (Root != null)\n        {\n            SetNode<T> x = Root;\n            while (x.Left != null) x = (SetNode<T>)x.Left;\n\n            if (LeftMost != x) throw new InvalidEndItemException();\n\n            SetNode<T> y = Root;\n            while (y.Right != null) y = (SetNode<T>)y.Right;\n\n            if (RightMost != y) throw new InvalidEndItemException();\n        }\n    }\n\n    void Validate(SetNode<T> root)\n    {\n        if (root == null) return;\n\n        if (root.Left != null)\n        {\n            SetNode<T> Left = (SetNode<T>)root.Left;\n\n            if (Comparer.Compare(Left.Data, root.Data) >= 0)\n                throw new OutOfKeyOrderException();\n\n            if (Left.Parent != root)\n                throw new TreeInvalidParentException();\n\n            Validate((SetNode<T>)root.Left);\n        }\n\n        if (root.Right != null)\n        {\n            SetNode<T> Right = (SetNode<T>)root.Right;\n\n            if (Comparer.Compare(Right.Data, root.Data) <= 0)\n                throw new OutOfKeyOrderException();\n\n            if (Right.Parent != root)\n                throw new TreeInvalidParentException();\n\n            Validate((SetNode<T>)root.Right);\n        }\n\n        ulong depth_Left = root.Left != null ? Utility.Depth(root.Left) : 0;\n        ulong depth_Right = root.Right != null ? Utility.Depth(root.Right) : 0;\n\n        if (depth_Left > depth_Right && depth_Left - depth_Right > 2)\n            throw new TreeOutOfBalanceException();\n\n        if (depth_Left < depth_Right && depth_Right - depth_Left > 2)\n            throw new TreeOutOfBalanceException();\n    }\n\n    public static void CombineSets(Set<T> A,\n                                   Set<T> B,\n                                   Set<T> R,\n                                   SetOperation operation)\n    {\n        IComparer<T> TComparer = R.Comparer;\n        SetEntry<T> First1 = A.Begin;\n        SetEntry<T> Last1 = A.End;\n        SetEntry<T> First2 = B.Begin;\n        SetEntry<T> Last2 = B.End;\n\n        switch (operation)\n        {\n            case SetOperation.Union:\n                while (First1 != Last1 && First2 != Last2)\n                {\n                    int Order = TComparer.Compare(First1.Value, First2.Value);\n\n                    if (Order < 0)\n                    {\n                        R.Add(First1.Value);\n                        First1.MoveNext();\n                    }\n\n                    else if (Order > 0)\n                    {\n                        R.Add(First2.Value);\n                        First2.MoveNext();\n                    }\n\n                    else\n                    {\n                        R.Add(First1.Value);\n                        First1.MoveNext();\n                        First2.MoveNext();\n                    }\n                }\n                while (First1 != Last1)\n                {\n                    R.Add(First1.Value);\n                    First1.MoveNext();\n                }\n                while (First2 != Last2)\n                {\n                    R.Add(First2.Value);\n                    First2.MoveNext();\n                }\n                return;\n\n            case SetOperation.Intersection:\n                while (First1 != Last1 && First2 != Last2)\n                {\n                    int Order = TComparer.Compare(First1.Value, First2.Value);\n\n                    if (Order < 0)\n                        First1.MoveNext();\n\n                    else if (Order > 0)\n                        First2.MoveNext();\n\n                    else\n                    {\n                        R.Add(First1.Value);\n                        First1.MoveNext();\n                        First2.MoveNext();\n                    }\n                }\n                return;\n\n            case SetOperation.SymmetricDifference:\n                while (First1 != Last1 && First2 != Last2)\n                {\n                    int Order = TComparer.Compare(First1.Value, First2.Value);\n\n                    if (Order < 0)\n                    {\n                        R.Add(First1.Value);\n                        First1.MoveNext();\n                    }\n\n                    else if (Order > 0)\n                    {\n                        R.Add(First2.Value);\n                        First2.MoveNext();\n                    }\n\n                    else\n                    { First1.MoveNext(); First2.MoveNext(); }\n                }\n\n                while (First1 != Last1)\n                {\n                    R.Add(First1.Value);\n                    First1.MoveNext();\n                }\n\n                while (First2 != Last2)\n                {\n                    R.Add(First2.Value);\n                    First2.MoveNext();\n                }\n                return;\n\n            case SetOperation.Difference:\n                while (First1 != Last1 && First2 != Last2)\n                {\n                    int Order = TComparer.Compare(First1.Value, First2.Value);\n\n                    if (Order < 0)\n                    {\n                        R.Add(First1.Value);\n                        First1.MoveNext();\n                    }\n\n                    else if (Order > 0)\n                    {\n                        R.Add(First1.Value);\n                        First1.MoveNext();\n                        First2.MoveNext();\n                    }\n\n                    else\n                    { First1.MoveNext(); First2.MoveNext(); }\n                }\n\n                while (First1 != Last1)\n                {\n                    R.Add(First1.Value);\n                    First1.MoveNext();\n                }\n                return;\n        }\n\n        throw new InvalidSetOperationException();\n    }\n\n    public static bool CheckSets(Set<T> A,\n                                 Set<T> B,\n                                 SetOperation operation)\n    {\n        IComparer<T> TComparer = A.Comparer;\n        SetEntry<T> First1 = A.Begin;\n        SetEntry<T> Last1 = A.End;\n        SetEntry<T> First2 = B.Begin;\n        SetEntry<T> Last2 = B.End;\n\n        switch (operation)\n        {\n            case SetOperation.Equality:\n            case SetOperation.Inequality:\n                {\n                    bool Equals = true;\n\n                    while (First1 != Last1 && First2 != Last2)\n                    {\n                        if (TComparer.Compare(First1.Value, First2.Value) == 0)\n                        { First1.MoveNext(); First2.MoveNext(); }\n                        else\n                        { Equals = false; break; }\n                    }\n\n                    if (Equals)\n                    {\n                        if (First1 != Last1) Equals = false;\n                        if (First2 != Last2) Equals = false;\n                    }\n\n                    if (operation == SetOperation.Equality)\n                        return Equals;\n                    else\n                        return !Equals;\n                }\n\n            case SetOperation.Subset:\n            case SetOperation.Superset:\n                {\n                    bool Subset = true;\n\n                    while (First1 != Last1 && First2 != Last2)\n                    {\n                        int Order = TComparer.Compare(First1.Value, First2.Value);\n\n                        if (Order < 0)\n                        { Subset = false; break; }\n\n                        else if (Order > 0)\n                            First2.MoveNext();\n\n                        else\n                        { First1.MoveNext(); First2.MoveNext(); }\n                    }\n\n                    if (Subset)\n                        if (First1 != Last1) Subset = false;\n\n                    if (operation == SetOperation.Subset)\n                        return Subset;\n                    else\n                        return !Subset;\n                }\n        }\n\n        throw new InvalidSetOperationException();\n    }\n}\n\npublic class EntryNotFoundException : Exception\n{\n    static String message = \"The requested entry could not be located in the specified collection.\";\n\n    public EntryNotFoundException() : base(message) { }\n}\n\npublic class EntryAlreadyExistsException : Exception\n{\n    static String message = \"The requested entry already resides in the collection.\";\n\n    public EntryAlreadyExistsException() : base(message) { }\n}\n\npublic class InvalidEndItemException : Exception\n{\n    static String message = \"The validation routines detected that the end item of a tree is invalid.\";\n\n    public InvalidEndItemException() : base(message) { }\n}\n\npublic class InvalidEmptyTreeException : Exception\n{\n    static String message = \"The validation routines detected that an empty tree is invalid.\";\n\n    public InvalidEmptyTreeException() : base(message) { }\n}\n\npublic class OutOfKeyOrderException : Exception\n{\n    static String message = \"A trees was found to be out of key order.\";\n\n    public OutOfKeyOrderException() : base(message) { }\n}\n\npublic class TreeInvalidParentException : Exception\n{\n    static String message = \"The validation routines detected that the Parent structure of a tree is invalid.\";\n\n    public TreeInvalidParentException() : base(message) { }\n}\n\npublic class TreeOutOfBalanceException : Exception\n{\n    static String message = \"The validation routines detected that the tree is out of State.\";\n\n    public TreeOutOfBalanceException() : base(message) { }\n}\n\npublic class InvalidSetOperationException : Exception\n{\n    static String message = \"An invalid set operation was requested.\";\n\n    public InvalidSetOperationException() : base(message) { }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        Set<string> s = new Set<string>() {\"S0\",\"S1\",\"S2\",\"S3\",\"S4\",\n                                           \"S5\",\"S6\",\"S7\",\"S8\",\"S9\"};\n\n        Console.WriteLine(\"Depth = {0}\", s.Depth);\n\n        s.Validate();\n\n        for (int i = 0; i < 10; i += 2)\n            s.Remove(\"S\" + i.ToString());\n\n        Console.WriteLine(\"Depth = {0}\", s.Depth);\n\n        s.Validate();\n\n        Console.WriteLine(\"{0}\", s);\n\n        Set<int> A = new Set<int>() { 1, 3, 5, 7 };\n        Set<int> B = new Set<int>() { 2, 4, 6, 8 };\n\n        Set<int> U = A | B;\n\n        Console.WriteLine(\"{0} | {1} == {2}\", A, B, U);\n    }\n}\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures that lookup, insertion, and deletion operations take O(log n) time in both average and worst cases. The tree is rebalanced after insertions and deletions through one or more tree rotations. Duplicate node keys are not allowed. The AVL tree is compared with red-black trees in terms of operations and time complexity.","id":3244}
    {"lang_cluster":"C#","source_code":"\nWorks with: C sharp version 6\nusing System;\npublic class CirclesOfGivenRadiusThroughTwoPoints\n{\n    public static void Main()\n    {\n        double[][] values = new double[][] {\n            new [] { 0.1234, 0.9876, 0.8765, 0.2345,   2 },\n            new [] { 0.0,       2.0,    0.0,    0.0,   1 },\n            new [] { 0.1234, 0.9876, 0.1234, 0.9876,   2 },\n            new [] { 0.1234, 0.9876, 0.8765, 0.2345, 0.5 },\n            new [] { 0.1234, 0.9876, 0.1234, 0.9876,   0 }\n        };\n\t\t\n        foreach (var a in values) {\n            var p = new Point(a[0], a[1]);\n            var q = new Point(a[2], a[3]);\n            Console.WriteLine($\"Points {p} and {q} with radius {a[4]}:\");\n            try {\n                var centers = FindCircles(p, q, a[4]);\n                Console.WriteLine(\"\\t\" + string.Join(\" and \", centers));\n            } catch (Exception ex) {\n                Console.WriteLine(\"\\t\" + ex.Message);\n            }\n        }\n    }\n\t\n    static Point[] FindCircles(Point p, Point q, double radius) {\n        if(radius < 0) throw new ArgumentException(\"Negative radius.\");\n        if(radius == 0) {\n            if(p == q) return new [] { p };\n            else throw new InvalidOperationException(\"No circles.\");\n        }\n        if (p == q) throw new InvalidOperationException(\"Infinite number of circles.\");\n\t\t\n        double sqDistance = Point.SquaredDistance(p, q);\n        double sqDiameter = 4 * radius * radius;\n        if (sqDistance > sqDiameter) throw new InvalidOperationException(\"Points are too far apart.\");\n\t\t\n        Point midPoint = new Point((p.X + q.X) \/ 2, (p.Y + q.Y) \/ 2);\n        if (sqDistance == sqDiameter) return new [] { midPoint };\n\t\t\n        double d = Math.Sqrt(radius * radius - sqDistance \/ 4);\n        double distance = Math.Sqrt(sqDistance);\n        double ox = d * (q.X - p.X) \/ distance, oy = d * (q.Y - p.Y) \/ distance;\n        return new [] {\n            new Point(midPoint.X - oy, midPoint.Y + ox),\n            new Point(midPoint.X + oy, midPoint.Y - ox)\n        };\n    }\n\t\n    public struct Point\n    {\n        public Point(double x, double y) : this() {\n            X = x;\n            Y = y;\n        }\n\t\n        public double X { get; }\n        public double Y { get; }\n\t\n        public static bool operator ==(Point p, Point q) => p.X == q.X && p.Y == q.Y;\n        public static bool operator !=(Point p, Point q) => p.X != q.X || p.Y != q.Y;\n\t\n        public static double SquaredDistance(Point p, Point q) {\n            double dx = q.X - p.X, dy = q.Y - p.Y;\n            return dx * dx + dy * dy;\n        }\n\t\t\n        public override string ToString() => $\"({X}, {Y})\";\n\t\t\n    }\t\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":3245}
    {"lang_cluster":"C#","source_code":"\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Random random = new Random();\n        while (true)\n        {\n            int a = random.Next(20);\n            Console.WriteLine(a);\n            if (a == 10)\n                break;\n            int b = random.Next(20)\n            Console.WriteLine(b);\n        }\n           \n        Console.ReadLine();\n    }       \n}\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":3246}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace prog\n{\n\tclass MainClass\n\t{\n\t\tpublic static void Main (string[] args)\n\t\t{\n\t\t\tint q = 929;\n\t\t\tif ( !isPrime(q) ) return;\n\t\t\tint r = q;\n\t\t\twhile( r > 0 ) \n\t\t\t\tr <<= 1;\n\t\t\tint d = 2 * q + 1;\n\t\t\tdo\n\t\t\t{\n\t\t\t\tint i = 1;\n\t\t\t\tfor( int p=r; p!=0; p<<=1 )\n\t\t\t\t{\n\t\t\t\t\ti = (i*i) % d;\n\t\t\t\t\tif (p < 0) i *= 2;\n\t\t\t\t\tif (i > d) i -= d;\n\t\t\t\t}\n\t\t\t\tif (i != 1) d += 2 * q; else break;\t\t\t\t\n\t\t\t}\n\t\t\twhile(true);\n\t\t\t\n\t\t\tConsole.WriteLine(\"2^\"+q+\"-1 = 0 (mod \"+d+\")\"); \n\t\t}\n\t\t\n\t\tstatic bool isPrime(int n)\n\t\t{\n\t\t\tif ( n % 2 == 0 ) return n == 2;\n\t\t\tif ( n % 3 == 0 ) return n == 3;\n\t\t\tint d = 5;\n\t\t\twhile( d*d <= n )\n\t\t\t{\n\t\t\t\tif ( n % d == 0 ) return false;\n\t\t\t\td += 2;\n\t\t\t\tif ( n % d == 0 ) return false;\n\t\t\t\td += 4;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}\n}\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":3247}
    {"lang_cluster":"C#","source_code":"\nXmlReader XReader;\n \n\/\/ Either read the xml from a string ...\nXReader = XmlReader.Create(new StringReader(\"<inventory title=... <\/inventory>\"));\n \n\/\/ ... or read it from the file system.\nXReader = XmlReader.Create(\"xmlfile.xml\");\n \n\/\/ Create a XPathDocument object (which implements the IXPathNavigable interface)\n\/\/ which is optimized for XPath operation. (very fast).\nIXPathNavigable XDocument = new XPathDocument(XReader);\n \n\/\/ Create a Navigator to navigate through the document.\nXPathNavigator Nav = XDocument.CreateNavigator();\nNav = Nav.SelectSingleNode(\"\/\/item\");\n \n\/\/ Move to the first element of the selection. (if available).\nif(Nav.MoveToFirst())\n{\n  Console.WriteLine(Nav.OuterXml); \/\/ The outer xml of the first item element.\n}\n \n\/\/ Get an iterator to loop over multiple selected nodes.\nXPathNodeIterator Iterator = XDocument.CreateNavigator().Select(\"\/\/price\");\n \nwhile (Iterator.MoveNext())\n{\n  Console.WriteLine(Iterator.Current.Value);\n}\n \nIterator = XDocument.CreateNavigator().Select(\"\/\/name\");\n \n\/\/ Use a generic list.\nList<string> NodesValues = new List<string>();\n \nwhile (Iterator.MoveNext())\n{\n  NodesValues.Add(Iterator.Current.Value);\n}\n \n\/\/ Convert the generic list to an array and output the count of items.\nConsole.WriteLine(NodesValues.ToArray().Length);\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":3248}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nclass Program\n{\n    static void PrintCollection(IEnumerable<int> x)\n    {\n        Console.WriteLine(string.Join(\" \", x));\n    }\n    static void Main(string[] args)\n    {\n        Console.OutputEncoding = Encoding.UTF8;\n        Console.WriteLine(\"Set creation\");\n        var A = new HashSet<int> { 4, 12, 14, 17, 18, 19, 20 };\n        var B = new HashSet<int> { 2, 5, 8, 11, 12, 13, 17, 18, 20 };\n\n        PrintCollection(A);\n        PrintCollection(B);\n\n        Console.WriteLine(\"Test m \u2208 S -- \\\"m is an element in set S\\\"\");\n        Console.WriteLine(\"14 is an element in set A: {0}\", A.Contains(14));\n        Console.WriteLine(\"15 is an element in set A: {0}\", A.Contains(15));\n\n        Console.WriteLine(\"A \u222a B -- union; a set of all elements either in set A or in set B.\");\n        var aUb = A.Union(B);\n        PrintCollection(aUb);\n\n        Console.WriteLine(\"A \u2216 B -- difference; a set of all elements in set A, except those in set B.\");\n        var aDb = A.Except(B);\n        PrintCollection(aDb);\n\n        Console.WriteLine(\"A \u2286 B -- subset; true if every element in set A is also in set B.\");\n        Console.WriteLine(A.IsSubsetOf(B));\n        var C = new HashSet<int> { 14, 17, 18 };\n        Console.WriteLine(C.IsSubsetOf(A));\n\n        Console.WriteLine(\"A = B -- equality; true if every element of set A is in set B and vice versa.\");\n        Console.WriteLine(A.SetEquals(B));\n        var D = new HashSet<int> { 4, 12, 14, 17, 18, 19, 20 };\n        Console.WriteLine(A.SetEquals(D));\n\n        Console.WriteLine(\"If A \u2286 B, but A \u2260 B, then A is called a true or proper subset of B, written A \u2282 B or A \u228a B\");\n        Console.WriteLine(A.IsProperSubsetOf(B));\n        Console.WriteLine(C.IsProperSubsetOf(A));\n\n        Console.WriteLine(\"Modify a mutable set.  (Add 10 to A; remove 12 from B).\");\n        A.Add(10);\n        B.Remove(12);\n        PrintCollection(A);\n        PrintCollection(B);\n\n        Console.ReadKey();\n    }\n}\n\n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":3249}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        for (int i = 2008; i <= 2121; i++)\n        {\n            DateTime date = new DateTime(i, 12, 25);\n            if (date.DayOfWeek == DayOfWeek.Sunday)\n            {\n                Console.WriteLine(date.ToString(\"dd MMM yyyy\"));\n            }\n        }\n    }\n}\n\n\nusing System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        string[] days = Enumerable.Range(2008, 2121 - 2007)\n            .Select(year => new DateTime(year, 12, 25))\n            .Where(day => day.DayOfWeek == DayOfWeek.Sunday)\n            .Select(day => day.ToString(\"dd MMM yyyy\")).ToArray();\n\n        foreach (string day in days) Console.WriteLine(day);\n    }\n}\nLambda expressions FTW:\nusing System;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        Enumerable.Range(2008, 113).ToList()\n        .ConvertAll(ent => new DateTime(ent, 12, 25))\n        .Where(ent => ent.DayOfWeek.Equals(DayOfWeek.Sunday)).ToList()\n        .ForEach(ent => Console.WriteLine(ent.ToString(\"dd MMM yyyy\")));\n    }\n}\n\n\n","human_summarization":"The code calculates the years between 2008 and 2121 when Christmas (25th December) falls on a Sunday using standard date handling libraries. It also compares the results with outputs from other programming languages to identify any anomalies in date\/time representation, possibly due to issues similar to the Y2K problem. The code uses LINQ for this task.","id":3250}
    {"lang_cluster":"C#","source_code":"\nLibrary: Math.Net\nusing System;\nusing MathNet.Numerics.LinearAlgebra;\nusing MathNet.Numerics.LinearAlgebra.Double;\n\n\nclass Program\n{\n\n    static void Main(string[] args)\n    {\n        Matrix<double> A = DenseMatrix.OfArray(new double[,]\n        {\n                {  12,  -51,    4 },\n                {   6,  167,  -68 },\n                {  -4,   24,  -41 }\n        });\n        Console.WriteLine(\"A:\");\n        Console.WriteLine(A);\n        var qr = A.QR();\n        Console.WriteLine();\n        Console.WriteLine(\"Q:\");\n        Console.WriteLine(qr.Q);\n        Console.WriteLine();\n        Console.WriteLine(\"R:\");\n        Console.WriteLine(qr.R);\n    }\n}\n\n\n","human_summarization":"The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.","id":3251}
    {"lang_cluster":"C#","source_code":"\nWorks with: C# version 2+\nint[] nums = { 1, 1, 2, 3, 4, 4 };\nList<int> unique = new List<int>();\nforeach (int n in nums)\n    if (!unique.Contains(n))\n        unique.Add(n);\n\nWorks with: C# version 3+\nint[] nums = {1, 1, 2, 3, 4, 4};\nint[] unique = nums.Distinct().ToArray();\n\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":3252}
    {"lang_cluster":"C#","source_code":"\n\/\/\n\/\/ The Tripartite conditional enables Bentley-McIlroy 3-way Partitioning.\n\/\/ This performs additional compares to isolate islands of keys equal to\n\/\/ the pivot value.  Use unless key-equivalent classes are of small size.\n\/\/\n#define Tripartite\n\nnamespace RosettaCode {\n  using System;\n  using System.Diagnostics;\n\n  public class QuickSort<T> where T : IComparable {\n    #region Constants\n    public const UInt32 INSERTION_LIMIT_DEFAULT = 12;\n    private const Int32 SAMPLES_MAX = 19;\n    #endregion\n\n    #region Properties\n    public UInt32 InsertionLimit { get; }\n    private T[] Samples { get; }\n    private Int32 Left { get; set; }\n    private Int32 Right { get; set; }\n    private Int32 LeftMedian { get; set; }\n    private Int32 RightMedian { get; set; }\n    #endregion\n\n    #region Constructors\n    public QuickSort(UInt32 insertionLimit = INSERTION_LIMIT_DEFAULT) {\n      this.InsertionLimit = insertionLimit;\n      this.Samples = new T[SAMPLES_MAX];\n    }\n    #endregion\n\n    #region Sort Methods\n    public void Sort(T[] entries) {\n      Sort(entries, 0, entries.Length - 1);\n    }\n\n    public void Sort(T[] entries, Int32 first, Int32 last) {\n      var length = last + 1 - first;\n      while (length > 1) {\n        if (length < InsertionLimit) {\n          InsertionSort<T>.Sort(entries, first, last);\n          return;\n        }\n\n        Left = first;\n        Right = last;\n        var median = pivot(entries);\n        partition(median, entries);\n        \/\/[Note]Right < Left\n\n        var leftLength = Right + 1 - first;\n        var rightLength = last + 1 - Left;\n\n        \/\/\n        \/\/ First recurse over shorter partition, then loop\n        \/\/ on the longer partition to elide tail recursion.\n        \/\/\n        if (leftLength < rightLength) {\n          Sort(entries, first, Right);\n          first = Left;\n          length = rightLength;\n        }\n        else {\n          Sort(entries, Left, last);\n          last = Right;\n          length = leftLength;\n        }\n      }\n    }\n\n    \/\/\/ <summary>Return an odd sample size proportional to the log of a large interval size.<\/summary>\n    private static Int32 sampleSize(Int32 length, Int32 max = SAMPLES_MAX) {\n      var logLen = (Int32)Math.Log10(length);\n      var samples = Math.Min(2 * logLen + 1, max);\n      return Math.Min(samples, length);\n    }\n\n    \/\/\/ <summary>Estimate the median value of entries[Left:Right]<\/summary>\n    \/\/\/ <remarks>A sample median is used as an estimate the true median.<\/remarks>\n    private T pivot(T[] entries) {\n      var length = Right + 1 - Left;\n      var samples = sampleSize(length);\n      \/\/ Sample Linearly:\n      for (var sample = 0; sample < samples; sample++) {\n        \/\/ Guard against Arithmetic Overflow:\n        var index = (Int64)length * sample \/ samples + Left;\n        Samples[sample] = entries[index];\n      }\n\n      InsertionSort<T>.Sort(Samples, 0, samples - 1);\n      return Samples[samples \/ 2];\n    }\n\n    private void partition(T median, T[] entries) {\n      var first = Left;\n      var last = Right;\n#if Tripartite\n      LeftMedian = first;\n      RightMedian = last;\n#endif\n      while (true) {\n        \/\/[Assert]There exists some index >= Left where entries[index] >= median\n        \/\/[Assert]There exists some index <= Right where entries[index] <= median\n        \/\/ So, there is no need for Left or Right bound checks\n        while (median.CompareTo(entries[Left]) > 0) Left++;\n        while (median.CompareTo(entries[Right]) < 0) Right--;\n\n        \/\/[Assert]entries[Right] <= median <= entries[Left]\n        if (Right <= Left) break;\n\n        Swap(entries, Left, Right);\n        swapOut(median, entries);\n        Left++;\n        Right--;\n        \/\/[Assert]entries[first:Left - 1] <= median <= entries[Right + 1:last]\n      }\n\n      if (Left == Right) {\n        Left++;\n        Right--;\n      }\n      \/\/[Assert]Right < Left\n      swapIn(entries, first, last);\n\n      \/\/[Assert]entries[first:Right] <= median <= entries[Left:last]\n      \/\/[Assert]entries[Right + 1:Left - 1] == median when non-empty\n    }\n    #endregion\n\n    #region Swap Methods\n    [Conditional(\"Tripartite\")]\n    private void swapOut(T median, T[] entries) {\n      if (median.CompareTo(entries[Left]) == 0) Swap(entries, LeftMedian++, Left);\n      if (median.CompareTo(entries[Right]) == 0) Swap(entries, Right, RightMedian--);\n    }\n\n    [Conditional(\"Tripartite\")]\n    private void swapIn(T[] entries, Int32 first, Int32 last) {\n      \/\/ Restore Median entries\n      while (first < LeftMedian) Swap(entries, first++, Right--);\n      while (RightMedian < last) Swap(entries, Left++, last--);\n    }\n\n    \/\/\/ <summary>Swap entries at the left and right indicies.<\/summary>\n    public void Swap(T[] entries, Int32 left, Int32 right) {\n      Swap(ref entries[left], ref entries[right]);\n    }\n\n    \/\/\/ <summary>Swap two entities of type T.<\/summary>\n    public static void Swap(ref T e1, ref T e2) {\n      var e = e1;\n      e1 = e2;\n      e2 = e;\n    }\n    #endregion\n  }\n\n  #region Insertion Sort\n  static class InsertionSort<T> where T : IComparable {\n    public static void Sort(T[] entries, Int32 first, Int32 last) {\n      for (var next = first + 1; next <= last; next++)\n        insert(entries, first, next);\n    }\n\n    \/\/\/ <summary>Bubble next entry up to its sorted location, assuming entries[first:next - 1] are already sorted.<\/summary>\n    private static void insert(T[] entries, Int32 first, Int32 next) {\n      var entry = entries[next];\n      while (next > first && entries[next - 1].CompareTo(entry) > 0)\n        entries[next] = entries[--next];\n      entries[next] = entry;\n    }\n  }\n  #endregion\n}\n\n\n  using Sort;\n  using System;\n\n  class Program {\n    static void Main(String[] args) {\n      var entries = new Int32[] { 1, 3, 5, 7, 9, 8, 6, 4, 2 };\n      var sorter = new QuickSort<Int32>();\n      sorter.Sort(entries);\n      Console.WriteLine(String.Join(\" \", entries));\n    }\n  }\n\n\n","human_summarization":"The code implements the quicksort algorithm to sort an array or list of elements. It selects a pivot element and divides the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions. The code also includes an optimized version of quicksort that works in place by swapping elements within the array to avoid additional memory allocation. The pivot selection method is not specified and can vary. The code also compares quicksort with merge sort, highlighting their differences and use cases.","id":3253}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace RosettaCode.DateFormat\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            DateTime today = DateTime.Now.Date;\n            Console.WriteLine(today.ToString(\"yyyy-MM-dd\"));\n            Console.WriteLine(today.ToString(\"dddd, MMMMM d, yyyy\"));\n        }\n    }\n}\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":3254}
    {"lang_cluster":"C#","source_code":"\npublic IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)\n{\n    return from m in Enumerable.Range(0, 1 << list.Count)\n                  select\n                      from i in Enumerable.Range(0, list.Count)\n                      where (m & (1 << i)) != 0\n                      select list[i];\n}\n\npublic void PowerSetofColors()\n{\n    var colors = new List<KnownColor> { KnownColor.Red, KnownColor.Green, \n        KnownColor.Blue, KnownColor.Yellow };\n    \n    var result = GetPowerSet(colors);\n    \n    Console.Write( string.Join( Environment.NewLine, \n        result.Select(subset => \n            string.Join(\",\", subset.Select(clr => clr.ToString()).ToArray())).ToArray()));\n}\n\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all possible subsets of the input set, including the empty set and the set itself. The function also demonstrates the ability to handle edge cases such as the power set of an empty set and the power set of a set containing only the empty set. The function can be implemented either recursively or non-recursively.","id":3255}
    {"lang_cluster":"C#","source_code":"\nusing System;\nclass Program\n{\n    static uint[] nums = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };\n    static string[] rum = { \"M\", \"CM\", \"D\", \"CD\", \"C\", \"XC\", \"L\", \"XL\", \"X\", \"IX\", \"V\", \"IV\", \"I\" };\n\n    static string ToRoman(uint number)\n    {\n        string value = \"\";\n        for (int i = 0; i < nums.Length && number != 0; i++)\n        {\n            while (number >= nums[i])\n            {\n                number -= nums[i];\n                value += rum[i];\n            }\n        }\n        return value;\n    }\n\n    static void Main()\n    {\n        for (uint number = 1; number <= 1 << 10; number *= 2)\n        {\n            Console.WriteLine(\"{0} = {1}\", number, ToRoman(number));\n        }\n    }\n}\n\n\nFunc<int, string> toRoman = (number) =>\n  new Dictionary<int, string>\n  {\n    {1000, \"M\"},\n    {900, \"CM\"},\n    {500, \"D\"},\n    {400, \"CD\"},\n    {100, \"C\"},\n    {90, \"XC\"},\n    {50, \"L\"},\n    {40, \"XL\"},\n    {10, \"X\"},\n    {9, \"IX\"},\n    {5, \"V\"},\n    {4, \"IV\"},\n    {1, \"I\"}\n  }.Aggregate(new string('I', number), (m, _) => m.Replace(new string('I', _.Key), _.Value));\n\n\n","human_summarization":"implement a function that converts a positive integer into its equivalent Roman numeral representation.","id":3256}
    {"lang_cluster":"C#","source_code":"\n\n int[] numbers = new int[10];\n\n\n string[] words = { \"these\", \"are\", \"arrays\" };\n\n\n  int[] more_numbers = new int[3]{ 21, 14 ,63 };\n\n\n  int[,] number_matrix = new int[3,2];\n\n\n  string[,] string_matrix = { {\"I\",\"swam\"}, {\"in\",\"the\"}, {\"freezing\",\"water\"} };\n\n\n string[,] funny_matrix = new string[2,2]{ {\"clowns\", \"are\"} , {\"not\", \"funny\"} };\n\nint[] array = new int[10];\n\narray[0] = 1;\narray[1] = 3;\n\nConsole.WriteLine(array[0]);\n\n\nusing System;\nusing System.Collections.Generic;\n\nList<int> list = new List<int>();\n\nlist.Add(1);\nlist.Add(3);\n\nlist[0] = 2;\n\nConsole.WriteLine(list[0]);\n\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. The codes include creation of both fixed-length and dynamic arrays, assigning values to them, and retrieving an element from them. It also shows the creation of a multi-dimensional array, specifically a 3x2 int matrix, and its initialization. The codes also cover examples of arrays of 10 int types and 3 string types.","id":3257}
    {"lang_cluster":"C#","source_code":"\n\nusing System.IO;\n\nusing (var reader = new StreamReader(\"input.txt\"))\nusing (var writer = new StreamWriter(\"output.txt\"))\n{\n    var text = reader.ReadToEnd();\n    writer.Write(text);\n}\n\n\nusing System.IO;\n\nvar text = File.ReadAllText(\"input.txt\");\nFile.WriteAllText(\"output.txt\", text);\n\n","human_summarization":"demonstrate how to read the contents of \"input.txt\" file into a variable and then write these contents into a new file called \"output.txt\".","id":3258}
    {"lang_cluster":"C#","source_code":"\nclass Program\n{\n    static void Main(string[] args)\n    {\n        string input;\n        Console.Write(\"Enter a series of letters: \");\n        input = Console.ReadLine();\n        stringCase(input);\n    }\n\n    private static void stringCase(string str)\n    {\n        char[] chars = str.ToCharArray();\n        string newStr = \"\";\n\n        foreach (char i in chars)\n            if (char.IsLower(i))\n                newStr += char.ToUpper(i);\n            else\n                newStr += char.ToLower(i);\n        Console.WriteLine(\"Converted: {0}\", newStr);\n    }\n}\n\n\nSystem.Console.WriteLine(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(\"exAmpLe sTrinG\"));\n\n","human_summarization":"demonstrate the conversion of the string 'alphaBETA' to upper-case and lower-case using the default encoding or ASCII. It also showcases additional case conversion functions available in the language library, such as swapping case or capitalizing the first letter. The code also handles title case conversion differently.","id":3259}
    {"lang_cluster":"C#","source_code":"\n\nclass Segment\n{\n    public Segment(PointF p1, PointF p2)\n    {\n        P1 = p1;\n        P2 = p2;\n    }\n\n    public readonly PointF P1;\n    public readonly PointF P2;\n\n    public float Length()\n    {\n        return (float)Math.Sqrt(LengthSquared());\n    }\n\n    public float LengthSquared()\n    {\n        return (P1.X - P2.X) * (P1.X - P2.X)\n            + (P1.Y - P2.Y) * (P1.Y - P2.Y);\n    }\n}\n\n\nSegment Closest_BruteForce(List<PointF> points)\n{\n    int n = points.Count;\n    var result = Enumerable.Range( 0, n-1)\n        .SelectMany( i => Enumerable.Range( i+1, n-(i+1) )\n            .Select( j => new Segment( points[i], points[j] )))\n            .OrderBy( seg => seg.LengthSquared())\n            .First();\n\n    return result;\n}\n\n\npublic static Segment MyClosestDivide(List<PointF> points)\n{\n   return MyClosestRec(points.OrderBy(p => p.X).ToList());\n}\n\nprivate static Segment MyClosestRec(List<PointF> pointsByX)\n{\n   int count = pointsByX.Count;\n   if (count <= 4)\n      return Closest_BruteForce(pointsByX);\n\n   \/\/ left and right lists sorted by X, as order retained from full list\n   var leftByX = pointsByX.Take(count\/2).ToList();\n   var leftResult = MyClosestRec(leftByX);\n\n   var rightByX = pointsByX.Skip(count\/2).ToList();\n   var rightResult = MyClosestRec(rightByX);\n\n   var result = rightResult.Length() < leftResult.Length() ? rightResult : leftResult;\n\n   \/\/ There may be a shorter distance that crosses the divider\n   \/\/ Thus, extract all the points within result.Length either side\n   var midX = leftByX.Last().X;\n   var bandWidth = result.Length();\n   var inBandByX = pointsByX.Where(p => Math.Abs(midX - p.X) <= bandWidth);\n\n   \/\/ Sort by Y, so we can efficiently check for closer pairs\n   var inBandByY = inBandByX.OrderBy(p => p.Y).ToArray();\n\n   int iLast = inBandByY.Length - 1;\n   for (int i = 0; i < iLast; i++ )\n   {\n      var pLower = inBandByY[i];\n\n      for (int j = i + 1; j <= iLast; j++)\n      {\n         var pUpper = inBandByY[j];\n\n         \/\/ Comparing each point to successivly increasing Y values\n         \/\/ Thus, can terminate as soon as deltaY is greater than best result\n         if ((pUpper.Y - pLower.Y) >= result.Length())\n            break;\n\n         if (Segment.Length(pLower, pUpper) < result.Length())\n            result = new Segment(pLower, pUpper);\n      }\n   }\n\n   return result;\n}\n\n\nvar randomizer = new Random(10);\nvar points = Enumerable.Range( 0, 10000).Select( i => new PointF( (float)randomizer.NextDouble(), (float)randomizer.NextDouble())).ToList();\nStopwatch sw = Stopwatch.StartNew();\nvar r1 = Closest_BruteForce(points);\nsw.Stop();\nDebugger.Log(1, \"\", string.Format(\"Time used (Brute force) (float): {0} ms\", sw.Elapsed.TotalMilliseconds));\nStopwatch sw2 = Stopwatch.StartNew();\nvar result2 = Closest_Recursive(points);\nsw2.Stop();\nDebugger.Log(1, \"\", string.Format(\"Time used (Divide & Conquer): {0} ms\",sw2.Elapsed.TotalMilliseconds));\nAssert.Equal(r1.Length(), result2.Length());\n\n\n","human_summarization":"The code provides a solution for the Closest Pair of Points problem in two dimensions. It includes two algorithms: a brute-force method with a time complexity of O(n^2) and a more efficient divide-and-conquer approach with a time complexity of O(n log n). The code also includes a helper class for distance comparisons and an optimized targeted search method.","id":3260}
    {"lang_cluster":"C#","source_code":"\n\/\/ Creates and initializes a new integer Array\nint[] intArray = new int[5] { 1, 2, 3, 4, 5 };\n\/\/same as\nint[] intArray = new int[]{ 1, 2, 3, 4, 5 };\n\/\/same as\nint[] intArray = { 1, 2, 3, 4, 5 };\n\n\/\/Arrays are zero-based\nstring[] stringArr = new string[5];\nstringArr[0] = \"string\";\n\n\n\/\/Create and initialize ArrayList\nArrayList myAl = new ArrayList { \"Hello\", \"World\", \"!\" };\n\n\/\/Create ArrayList and add some values\nArrayList myAL = new ArrayList();\n      myAL.Add(\"Hello\");\n      myAL.Add(\"World\");\n      myAL.Add(\"!\");\n\n\n\/\/Create and initialize List\nList<string> myList = new List<string> { \"Hello\", \"World\", \"!\" };\n\n\/\/Create List and add some values\nList<string> myList2 = new List<string>();\n            myList2.Add(\"Hello\");\n            myList2.Add(\"World\");\n            myList2.Add(\"!\");\n\n\n\/\/Create an initialize Hashtable\nHashtable myHt = new Hashtable() { { \"Hello\", \"World\" }, { \"Key\", \"Value\" } };\n\n\/\/Create Hashtable and add some Key-Value pairs.\nHashtable myHt2 = new Hashtable();\n\tmyHt2.Add(\"Hello\", \"World\");\n\tmyHt2.Add(\"Key\", \"Value\");\n\n\n\/\/Create an initialize Dictionary\nDictionary<string, string> dict = new Dictionary<string, string>() { { \"Hello\", \"World\" }, { \"Key\", \"Value\" } };\n\/\/Create Dictionary and add some Key-Value pairs.\nDictionary<string, string> dict2 = new Dictionary<string, string>();\n\tdict2.Add(\"Hello\", \"World\");\n\tdict2.Add(\"Key\", \"Value\");\n\n","human_summarization":"The code creates a collection and adds values to it. It utilizes various data structures like ArrayList, List, Hashtables, and Dictionary. The ArrayList dynamically increases in size as required and is zero-based. The List class is a strongly typed list of objects accessible by index. Hashtables and Dictionary classes represent collections of unique key\/value pairs.","id":3261}
    {"lang_cluster":"C#","source_code":"\n\/*    Items  Value  Weight  Volume\n          a     30       3      25\n          b     18       2      15\n          c     25      20       2\n\n                     <=250   <=250      *\/\nusing System;\nclass Program\n{\n    static void Main()\n    {\n        uint[] r = items1();\n        Console.WriteLine(r[0] + \" v  \" + r[1] + \" a  \" + r[2] + \" b\");  \/\/ 0 15 11\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) items1();\n        Console.Write(sw.Elapsed); Console.Read();\n    }\n\n    static uint[] items0()  \/\/ 1.2 \u00b5s\n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n                for (c = 0; a * 25 + b * 15 + c * 2 <= 250 && a * 3 + b * 2 + c * 20 <= 250; c++)\n                    if (v0 < (v = a * 30 + b * 18 + c * 25))\n                    {\n                        v0 = v; a0 = a; b0 = b; c0 = c;\n                        \/\/Console.WriteLine(\"{0,5} {1,5} {2,5} {3,5}\", v, a, b, c);\n                    }\n        return new uint[] { a0, b0, c0 };\n    }\n\n    static uint[] items1()  \/\/ 0,22 \u00b5s \n    {\n        uint v, v0 = 0, a, b, c, a0 = 0, b0 = 0, c0 = 0, c1 = 0;\n        for (a = 0; a <= 10; a++)\n            for (b = 0; a * 5 + b * 3 <= 50; b++)\n            {\n                c = (250 - a * 25 - b * 15) \/ 2;\n                if ((c1 = (250 - a * 3 - b * 2) \/ 20) < c) c = c1;\n                if (v0 < (v = a * 30 + b * 18 + c * 25))\n                { v0 = v; a0 = a; b0 = b; c0 = c; }\n            }\n        return new uint[] { a0, b0, c0 };\n    }\n}\n\n","human_summarization":"determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.","id":3262}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        for (int i = 1; ; i++)\n        {\n            Console.Write(i);\n            if (i == 10) break;\n            Console.Write(\", \");\n        }\n        Console.WriteLine();\n    }\n}\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":3263}
    {"lang_cluster":"C#","source_code":"\nnamespace Algorithms\n{\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    public class TopologicalSorter<ValueType>\n    {\n        private class Relations\n        {\n            public int Dependencies = 0;\n            public HashSet<ValueType> Dependents = new HashSet<ValueType>();\n        }\n\n        private Dictionary<ValueType, Relations> _map = new Dictionary<ValueType, Relations>();\n\n        public void Add(ValueType obj)\n        {\n            if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations());\n        }\n\n        public void Add(ValueType obj, ValueType dependency)\n        {\n            if (dependency.Equals(obj)) return;\n\n            if (!_map.ContainsKey(dependency)) _map.Add(dependency, new Relations());\n\n            var dependents = _map[dependency].Dependents;\n\n            if (!dependents.Contains(obj))\n            {\n                dependents.Add(obj);\n\n                if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations());\n\n                ++_map[obj].Dependencies;\n            }\n        }\n\n        public void Add(ValueType obj, IEnumerable<ValueType> dependencies)\n        {\n            foreach (var dependency in dependencies) Add(obj, dependency);\n        }\n\n        public void Add(ValueType obj, params ValueType[] dependencies)\n        {\n            Add(obj, dependencies as IEnumerable<ValueType>);\n        }\n\n        public Tuple<IEnumerable<ValueType>, IEnumerable<ValueType>> Sort()\n        {\n            List<ValueType> sorted = new List<ValueType>(), cycled = new List<ValueType>();\n            var map = _map.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);\n\n            sorted.AddRange(map.Where(kvp => kvp.Value.Dependencies == 0).Select(kvp => kvp.Key));\n\n            for (int idx = 0; idx < sorted.Count; ++idx) sorted.AddRange(map[sorted[idx]].Dependents.Where(k => --map[k].Dependencies == 0));\n\n            cycled.AddRange(map.Where(kvp => kvp.Value.Dependencies != 0).Select(kvp => kvp.Key));\n\n            return new Tuple<IEnumerable<ValueType>, IEnumerable<ValueType>>(sorted, cycled);\n        }\n\n        public void Clear()\n        {\n            _map.Clear();\n        }\n    }\n\n}\n\n\/*\n\tExample usage with Task object\n*\/\n\nnamespace ExampleApplication\n{\n    using Algorithms;\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n\n    public class Task\n    {\n        public string Message;\n    }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            List<Task> tasks = new List<Task>\n            {\n                new Task{ Message = \"A - depends on B and C\" },    \/\/0\n                new Task{ Message = \"B - depends on none\" },       \/\/1\n                new Task{ Message = \"C - depends on D and E\" },    \/\/2\n                new Task{ Message = \"D - depends on none\" },       \/\/3\n                new Task{ Message = \"E - depends on F, G and H\" }, \/\/4\n                new Task{ Message = \"F - depends on I\" },          \/\/5\n                new Task{ Message = \"G - depends on none\" },       \/\/6\n                new Task{ Message = \"H - depends on none\" },       \/\/7\n                new Task{ Message = \"I - depends on none\" },       \/\/8\n            };\n\n            TopologicalSorter<Task> resolver = new TopologicalSorter<Task>();\n\n            \/\/ now setting relations between them as described above\n            resolver.Add(tasks[0], new[] { tasks[1], tasks[2] });\n            \/\/resolver.Add(tasks[1]); \/\/ no need for this since the task was already mentioned as a dependency\n            resolver.Add(tasks[2], new[] { tasks[3], tasks[4] });\n            \/\/resolver.Add(tasks[3]); \/\/ no need for this since the task was already mentioned as a dependency\n            resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]);\n            resolver.Add(tasks[5], tasks[8]);\n            \/\/resolver.Add(tasks[6]); \/\/ no need for this since the task was already mentioned as a dependency\n            \/\/resolver.Add(tasks[7]); \/\/ no need for this since the task was already mentioned as a dependency\n\n            \/\/resolver.Add(tasks[3], tasks[0]); \/\/ uncomment this line to test cycled dependency\n\n            var result = resolver.Sort();\n            var sorted = result.Item1;\n            var cycled = result.Item2;\n\n            if (!cycled.Any())\n            {\n                foreach (var d in sorted) Console.WriteLine(d.Message);\n            }\n            else\n            {\n                Console.Write(\"Cycled dependencies detected: \");\n\n                foreach (var d in cycled) Console.Write($\"{d.Message[0]} \");\n\n                Console.WriteLine();\n            }\n\n            Console.WriteLine(\"exiting...\");\n        }\n    }\n}\n\n\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":3264}
    {"lang_cluster":"C#","source_code":"\nWorks with: Mono version 2.6\nclass Program\n{\n\tpublic static void Main (string[] args)\n\t{\n\t\tvar value = \"abcd\".StartsWith(\"ab\");\n\t\tvalue = \"abcd\".EndsWith(\"zn\"); \/\/returns false\n\t\tvalue = \"abab\".Contains(\"bb\"); \/\/returns false\n\t\tvalue = \"abab\".Contains(\"ab\"); \/\/returns true\n\t\tint loc = \"abab\".IndexOf(\"bb\"); \/\/returns -1\n\t\tloc = \"abab\".IndexOf(\"ab\"); \/\/returns 0\n\t\tloc = \"abab\".IndexOf(\"ab\",loc+1); \/\/returns 2\n\t}\n}\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":3265}
    {"lang_cluster":"C#","source_code":"using System;\nusing System.Linq;\n\nnamespace Four_Squares_Puzzle {\n    class Program {\n        static void Main(string[] args) {\n            fourSquare(1, 7, true, true);\n            fourSquare(3, 9, true, true);\n            fourSquare(0, 9, false, false);\n        }\n\n        private static void fourSquare(int low, int high, bool unique, bool print) {\n            int count = 0;\n\n            if (print) {\n                Console.WriteLine(\"a b c d e f g\");\n            }\n            for (int a = low; a <= high; ++a) {\n                for (int b = low; b <= high; ++b) {\n                    if (notValid(unique, b, a)) continue;\n\n                    int fp = a + b;\n                    for (int c = low; c <= high; ++c) {\n                        if (notValid(unique, c, b, a)) continue;\n                        for (int d = low; d <= high; ++d) {\n                            if (notValid(unique, d, c, b, a)) continue;\n                            if (fp != b + c + d) continue;\n\n                            for (int e = low; e <= high; ++e) {\n                                if (notValid(unique, e, d, c, b, a)) continue;\n                                for (int f = low; f <= high; ++f) {\n                                    if (notValid(unique, f, e, d, c, b, a)) continue;\n                                    if (fp != d + e + f) continue;\n\n                                    for (int g = low; g <= high; ++g) {\n                                        if (notValid(unique, g, f, e, d, c, b, a)) continue;\n                                        if (fp != f + g) continue;\n\n                                        ++count;\n                                        if (print) {\n                                            Console.WriteLine(\"{0} {1} {2} {3} {4} {5} {6}\", a, b, c, d, e, f, g);\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n            if (unique) {\n                Console.WriteLine(\"There are {0} unique solutions in [{1}, {2}]\", count, low, high);\n            }\n            else {\n                Console.WriteLine(\"There are {0} non-unique solutions in [{1}, {2}]\", count, low, high);\n            }\n        }\n\n        private static bool notValid(bool unique, int needle, params int[] haystack) {\n            return unique && haystack.Any(p => p == needle);\n        }\n    }\n}\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":3266}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class Clock : Form\n{\n    static readonly float degrees06 = (float)Math.PI \/ 30;\n    static readonly float degrees30 = degrees06 * 5;\n    static readonly float degrees90 = degrees30 * 3;\n\n    readonly int margin = 20;\n\n    private Point p0;\n\n    public Clock()\n    {\n        Size = new Size(500, 500);\n        StartPosition = FormStartPosition.CenterScreen;\n        Resize += (sender, args) => ResetSize();\n        ResetSize();\n        var timer = new Timer() { Interval = 1000, Enabled = true };\n        timer.Tick += (sender, e) => Refresh();\n        DoubleBuffered = true;\n    }\n\n    private void ResetSize()\n    {\n        p0 = new Point(ClientRectangle.Width \/ 2, ClientRectangle.Height \/ 2);\n        Refresh();\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        drawFace(e.Graphics);\n\n        var time = DateTime.Now;\n        int second = time.Second;\n        int minute = time.Minute;\n        int hour = time.Hour;\n\n        float angle = degrees90 - (degrees06 * second);\n        DrawHand(e.Graphics, Pens.Red, angle, 0.95);\n\n        float minsecs = (minute + second \/ 60.0F);\n        angle = degrees90 - (degrees06 * minsecs);\n        DrawHand(e.Graphics, Pens.Black, angle, 0.9);\n\n        float hourmins = (hour + minsecs \/ 60.0F);\n        angle = degrees90 - (degrees30 * hourmins);\n        DrawHand(e.Graphics, Pens.Black, angle, 0.6);\n    }\n\n    private void drawFace(Graphics g)\n    {\n        int radius = Math.Min(p0.X, p0.Y) - margin;\n        g.FillEllipse(Brushes.White, p0.X - radius, p0.Y - radius, radius * 2, radius * 2);\n\n        for (int h = 0; h < 12; h++)\n            DrawHand(g, Pens.LightGray, h * degrees30, -0.05);\n\n        for (int m = 0; m < 60; m++)\n            DrawHand(g, Pens.LightGray, m * degrees06, -0.025);\n    }\n\n    private void DrawHand(Graphics g, Pen pen, float angle, double size)\n    {\n        int radius = Math.Min(p0.X, p0.Y) - margin;\n\n        int x0 = p0.X + (size > 0 ? 0 : Convert.ToInt32(radius * (1 + size) * Math.Cos(angle)));\n        int y0 = p0.Y + (size > 0 ? 0 : Convert.ToInt32(radius * (1 + size) * Math.Sin(-angle)));\n\n        int x1 = p0.X + Convert.ToInt32(radius * (size > 0 ? size : 1) * Math.Cos(angle));\n        int y1 = p0.Y + Convert.ToInt32(radius * (size > 0 ? size : 1) * Math.Sin(-angle));\n\n        g.DrawLine(pen, x0, y0, x1, y1);\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new Clock());\n    }\n}\n\n","human_summarization":"illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.","id":3267}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\n\nnamespace RosettaCode.CSharp\n{\n    class Program\n    {\n        static void Count_New_Triangle(ulong A, ulong B, ulong C, ulong Max_Perimeter, ref ulong Total_Cnt, ref ulong Primitive_Cnt)\n        {\n            ulong Perimeter = A + B + C;\n\n            if (Perimeter <= Max_Perimeter)\n            {\n                Primitive_Cnt = Primitive_Cnt + 1;\n                Total_Cnt = Total_Cnt + Max_Perimeter \/ Perimeter;\n                Count_New_Triangle(A + 2 * C - 2 * B, 2 * A + 2 * C - B, 2 * A + 3 * C - 2 * B, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt);\n                Count_New_Triangle(A + 2 * B + 2 * C, 2 * A + B + 2 * C, 2 * A + 2 * B + 3 * C, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt);\n                Count_New_Triangle(2 * B + 2 * C - A, B + 2 * C - 2 * A, 2 * B + 3 * C - 2 * A, Max_Perimeter, ref Total_Cnt, ref Primitive_Cnt);\n            }\n        }\n\n        static void Count_Pythagorean_Triples()\n        {\n            ulong T_Cnt, P_Cnt;\n\n            for (int I = 1; I <= 8; I++)\n            {\n                T_Cnt = 0;\n                P_Cnt = 0;\n                ulong ExponentNumberValue = (ulong)Math.Pow(10, I);\n                Count_New_Triangle(3, 4, 5, ExponentNumberValue, ref T_Cnt, ref P_Cnt);\n                Console.WriteLine(\"Perimeter up to 10E\" + I + \"\u00a0: \" + T_Cnt + \" Triples, \" + P_Cnt + \" Primitives\");\n            }\n        }\n\n        static void Main(string[] args)\n        {\n            Count_Pythagorean_Triples();\n        }\n    }\n}\n\nPerimeter up to 10E1\u00a0: 0 Triples, 0 Primitives\nPerimeter up to 10E2\u00a0: 17 Triples, 7 Primitives\nPerimeter up to 10E3\u00a0: 325 Triples, 70 Primitives\nPerimeter up to 10E4\u00a0: 4858 Triples, 703 Primitives\nPerimeter up to 10E5\u00a0: 64741 Triples, 7026 Primitives\nPerimeter up to 10E6\u00a0: 808950 Triples, 70229 Primitives\nPerimeter up to 10E7\u00a0: 9706567 Triples, 702309 Primitives\nPerimeter up to 10E8\u00a0: 113236940 Triples, 7023027 Primitives\n","human_summarization":"The code determines the number of Pythagorean triples with a perimeter not exceeding 100 and counts how many of these are primitive. It also handles larger values up to a maximum perimeter of 100,000,000. The code is based on an efficient method translated from C, as seen in the Ada example.","id":3268}
    {"lang_cluster":"C#","source_code":"\nLibrary: Windows Forms\nUses: .NET Framework (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses library\" (as page type) with input value \"library\/.NET Framework\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\nusing System;\nusing System.Windows.Forms;\n\npublic class Window {\n    [STAThread]\n    static void Main() {\n        Form form = new Form();\n        \n        form.Text = \"Window\";\n        form.Disposed += delegate { Application.Exit(); };\n\n        form.Show();\n        Application.Run();\n    }\n}\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":3269}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\nclass Program\n{\n    static SortedDictionary<TItem, int> GetFrequencies<TItem>(IEnumerable<TItem> items)\n    {\n        var dictionary = new SortedDictionary<TItem, int>();\n        foreach (var item in items)\n        {\n            if (dictionary.ContainsKey(item))\n            {\n                dictionary[item]++;\n            }\n            else\n            {\n                dictionary[item] = 1;\n            }\n        }\n        return dictionary;\n    }\n\n    static void Main(string[] arguments)\n    {\n        var file = arguments.FirstOrDefault();\n        if (File.Exists(file))\n        {\n            var text = File.ReadAllText(file);\n            foreach (var entry in GetFrequencies(text))\n            {\n                Console.WriteLine(\"{0}: {1}\", entry.Key, entry.Value);\n            }\n        }\n    }\n}\n\n\n","human_summarization":"\"Opens a text file and counts the frequency of each letter, with some versions also counting all characters including punctuation.\"","id":3270}
    {"lang_cluster":"C#","source_code":"\nclass LinkedListNode\n{\n    public int Value { get; set; }\n    public LinkedListNode Next { get; set; }\n\n    \/\/ A constructor is not necessary, but could be useful.\n    public Link(int value, LinkedListNode next = null)\n    {\n        Item = value;\n        Next = next;\n    }\n}\n\n\nclass LinkedListNode<T>\n{\n    public T Value { get; set; }\n    public LinkedListNode Next { get; set; }\n\n    public Link(T value, LinkedListNode next = null)\n    {\n        Item = value;\n        Next = next;\n    }\n}\n\n\nunsafe struct link {\n    public link* next;\n    public int data;\n};\n\n","human_summarization":"Defines a data structure for a singly-linked list element. This element contains a numeric data member and a mutable link to the next element. The code is written in a C-like style.","id":3271}
    {"lang_cluster":"C#","source_code":"\nstatic void Main (string[] args) {\n    do {\n        Console.WriteLine (\"Number:\");\n        Int64 p = 0;\n        do {\n            try {\n                p = Convert.ToInt64 (Console.ReadLine ());\n                break;\n            } catch (Exception) { }\n\n        } while (true);\n\n        Console.WriteLine (\"For 1 through \" + ((int) Math.Sqrt (p)).ToString () + \"\");\n        for (int x = 1; x <= (int) Math.Sqrt (p); x++) {\n            if (p % x == 0)\n                Console.WriteLine (\"Found: \" + x.ToString () + \". \" + p.ToString () + \" \/ \" + x.ToString () + \" = \" + (p \/ x).ToString ());\n        }\n\n        Console.WriteLine (\"Done.\");\n    } while (true);\n}\n\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":3272}
    {"lang_cluster":"C#","source_code":"\n\nWorks with: C# version 2+\nusing System;\nclass ColumnAlignerProgram\n{\n    delegate string Justification(string s, int width);\n\n    static string[] AlignColumns(string[] lines, Justification justification)\n    {\n        const char Separator = '$';\n        \/\/ build input table and calculate columns count\n        string[][] table = new string[lines.Length][];\n        int columns = 0;\n        for (int i = 0; i < lines.Length; i++)\n        {\n            string[] row = lines[i].TrimEnd(Separator).Split(Separator);\n            if (columns < row.Length) columns = row.Length;\n            table[i] = row;\n        }\n        \/\/ create formatted table\n        string[][] formattedTable = new string[table.Length][];\n        for (int i = 0; i < formattedTable.Length; i++)\n        {\n            formattedTable[i] = new string[columns];\n        }\n        for (int j = 0; j < columns; j++)\n        {\n            \/\/ get max column width\n            int columnWidth = 0;\n            for (int i = 0; i < table.Length; i++)\n            {\n                if (j < table[i].Length && columnWidth < table[i][j].Length)\n                    columnWidth = table[i][j].Length;\n            }\n            \/\/ justify column cells\n            for (int i = 0; i < formattedTable.Length; i++)\n            {\n                if (j < table[i].Length)\n                    formattedTable[i][j] = justification(table[i][j], columnWidth);\n                else \n                    formattedTable[i][j] = new String(' ', columnWidth);\n            }\n        }\n        \/\/ create result\n        string[] result = new string[formattedTable.Length];\n        for (int i = 0; i < result.Length; i++)\n        {\n            result[i] = String.Join(\" \", formattedTable[i]);\n        }\n        return result;\n    }\n\n    static string JustifyLeft(string s, int width) { return s.PadRight(width); }\n    static string JustifyRight(string s, int width) { return s.PadLeft(width); }\n    static string JustifyCenter(string s, int width) \n    { \n        return s.PadLeft((width + s.Length) \/ 2).PadRight(width); \n    }\n\n    static void Main()\n    {\n        string[] input = {    \n            \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\",\n            \"are$delineated$by$a$single$'dollar'$character,$write$a$program\",\n            \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\",\n            \"column$are$separated$by$at$least$one$space.\",\n            \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\",\n            \"justified,$right$justified,$or$center$justified$within$its$column.\",\n        };\n\n        foreach (string line in AlignColumns(input, JustifyCenter))\n        {\n            Console.WriteLine(line);\n        }\n    }\n}\n\n\nWorks with: C# version 8+\nusing System;\nusing System.Linq;\n\nenum Justification { Left, Center, Right }\n\npublic class Program\n{\n    static void Main()\n    {\n        string text =\n@\"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\";\n\n        AlignColumns(text, Justification.Left);\n        Console.WriteLine();\n        AlignColumns(text, Justification.Center);\n        Console.WriteLine();\n        AlignColumns(text, Justification.Right);\n    }\n\n    public static void AlignColumns(string text, Justification justification) =>\n        AlignColumns(text.Split(Environment.NewLine), justification);\n\n    public static void AlignColumns(string[] lines, Justification justification) =>\n        AlignColumns(lines.Select(line => line.Split('$')).ToArray(), justification);\n\n    public static void AlignColumns(string[][] table, Justification justification)\n    {\n        Console.WriteLine(justification + \":\");\n        int columns = table.Max(line => line.Length);\n        var columnWidths =\n            Enumerable.Range(0, columns)\n            .Select(i => table.Max(line => i < line.Length ? line[i].Length : 0)\n            ).ToArray();\n        \n        foreach (var line in table) {\n            Console.WriteLine(string.Join(\" \",\n                Enumerable.Range(0, line.Length)\n                .Select(i => justification switch {\n                    Justification.Left => line[i].PadRight(columnWidths[i]),\n                    Justification.Right => line[i].PadLeft(columnWidths[i]),\n                    _ => line[i].PadLeft(columnWidths[i] \/ 2).PadRight(columnWidths[i])\n                })\n            ));\n        }\n    }    \n\n}\n\n\n","human_summarization":"The code reads a text file where fields within a line are separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It allows for each word in a column to be left justified, right justified, or center justified. The code uses C# 2's delegate feature to define the justification and newer features like LINQ, lambdas, and switch expressions. The minimum space between columns is computed from the text and not hard-coded.","id":3273}
    {"lang_cluster":"C#","source_code":"using System;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\nnamespace Cuboid\n{\n    public partial class Form1 : Form\n    {\n        double[][] nodes = {\n            new double[] {-1, -1, -1}, new double[] {-1, -1, 1}, new double[] {-1, 1, -1},\n            new double[] {-1, 1, 1}, new double[] {1, -1, -1}, new double[] {1, -1, 1},\n            new double[] {1, 1, -1}, new double[] {1, 1, 1} };\n\n        int[][] edges = {\n            new int[] {0, 1}, new int[] {1, 3}, new int[] {3, 2}, new int[] {2, 0}, new int[] {4, 5},\n            new int[] {5, 7}, new int[] {7, 6}, new int[] {6, 4}, new int[] {0, 4}, new int[] {1, 5},\n            new int[] {2, 6}, new int[] {3, 7}};\n\n        private int mouseX;\n        private int prevMouseX;\n        private int prevMouseY;\n        private int mouseY;\n\n        public Form1()\n        {\n            Width = Height = 640;\n            StartPosition = FormStartPosition.CenterScreen;\n            SetStyle(\n                ControlStyles.AllPaintingInWmPaint |\n                ControlStyles.UserPaint |\n                ControlStyles.DoubleBuffer,\n                true);\n\n            MouseMove += (s, e) =>\n            {\n                prevMouseX = mouseX;\n                prevMouseY = mouseY;\n                mouseX = e.X;\n                mouseY = e.Y;\n\n                double incrX = (mouseX - prevMouseX) * 0.01;\n                double incrY = (mouseY - prevMouseY) * 0.01;\n\n                RotateCuboid(incrX, incrY);\n                Refresh();\n            };\n\n            MouseDown += (s, e) =>\n            {\n                mouseX = e.X;\n                mouseY = e.Y;\n            };\n\n            Scale(80, 120, 160);\n            RotateCuboid(Math.PI \/ 5, Math.PI \/ 9);\n        }\n\n        private void RotateCuboid(double angleX, double angleY)\n        {\n            double sinX = Math.Sin(angleX);\n            double cosX = Math.Cos(angleX);\n\n            double sinY = Math.Sin(angleY);\n            double cosY = Math.Cos(angleY);\n\n            foreach (var node in nodes)\n            {\n                double x = node[0];\n                double y = node[1];\n                double z = node[2];\n\n                node[0] = x * cosX - z * sinX;\n                node[2] = z * cosX + x * sinX;\n\n                z = node[2];\n\n                node[1] = y * cosY - z * sinY;\n                node[2] = z * cosY + y * sinY;\n            }\n        }\n\n        private void Scale(int v1, int v2, int v3)\n        {\n            foreach (var item in nodes)\n            {\n                item[0] *= v1;\n                item[1] *= v2;\n                item[2] *= v3;\n            }\n        }\n\n        protected override void OnPaint(PaintEventArgs args)\n        {\n            var g = args.Graphics;\n            g.SmoothingMode = SmoothingMode.HighQuality;\n            g.Clear(Color.White);\n\n            g.TranslateTransform(Width \/ 2, Height \/ 2);\n\n            foreach (var edge in edges)\n            {\n                double[] xy1 = nodes[edge[0]];\n                double[] xy2 = nodes[edge[1]];\n                g.DrawLine(Pens.Black, (int)Math.Round(xy1[0]), (int)Math.Round(xy1[1]),\n                        (int)Math.Round(xy2[0]), (int)Math.Round(xy2[1]));\n            }\n\n            foreach (var node in nodes)\n            {\n                g.FillEllipse(Brushes.Black, (int)Math.Round(node[0]) - 4,\n                    (int)Math.Round(node[1]) - 4, 8, 8);\n            }\n        }\n    }\n}\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":3274}
    {"lang_cluster":"C#","source_code":"\n\/\/ Requires adding a reference to System.DirectoryServices \nvar objDE = new System.DirectoryServices.DirectoryEntry(\"LDAP:\/\/DC=onecity,DC=corp,DC=fabrikam,DC=com\");\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server.","id":3275}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Text;\n\n\nclass Program {\n    private static char shift(char c) {\n\t\treturn c.ToString().ToLower().First() switch {\n\t\t\t>= 'a' and <= 'm' => (char)(c + 13),\n\t\t\t>= 'n' and <= 'z' => (char)(c - 13),\n\t\t\tvar _ => c\n\t\t};\n    }\n\n    static string Rot13(string s)\n    \t=> new string(message.Select(c => shift(c)).ToArray());\n\n\n    static void Main(string[] args) {\n        foreach (var file in args.Where(file => File.Exists(file))) {\n            Console.WriteLine(Rot13(File.ReadAllText(file)));\n        }\n        if (!args.Any()) {\n            Console.WriteLine(Rot13(Console.In.ReadToEnd()));\n        }\n    }\n}\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":3276}
    {"lang_cluster":"C#","source_code":"\nWorks with: C# version 3+\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{        \n    struct Entry\n    {\n        public Entry(string name, double value) { Name = name; Value = value; }\n        public string Name;\n        public double Value;\n    }\n\n    static void Main(string[] args)\n    {\n        var Elements = new List<Entry>\n        {\n            new Entry(\"Krypton\", 83.798), new Entry(\"Beryllium\", 9.012182), new Entry(\"Silicon\", 28.0855),\n            new Entry(\"Cobalt\", 58.933195), new Entry(\"Selenium\", 78.96), new Entry(\"Germanium\", 72.64)\n        };\n\n        var sortedElements = Elements.OrderBy(e => e.Name);\n\n        foreach (Entry e in sortedElements)\n            Console.WriteLine(\"{0,-11}{1}\", e.Name, e.Value);\n    }\n}\n\n\nBeryllium  9.012182\nCobalt     58.933195\nGermanium  72.64\nKrypton    83.798\nSelenium   78.96\nSilicon    28.0855\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":3277}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program {\n    static void Main(string[] args)\n    {\n        for (int i = 0; i < 5; i++)\n        {\n            for (int j = 0; j <= i; j++)\n            {\n                Console.Write(\"*\");\n            }\n            Console.WriteLine();\n        }\n    }\n}\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":3278}
    {"lang_cluster":"C#","source_code":"\n\nSystem.Collections.HashTable map = new System.Collections.HashTable();\nmap[\"key1\"] = \"foo\";\n\n\nDictionary<string, string> map = new Dictionary<string,string>();\nmap[ \"key1\" ] = \"foo\";\n\nWorks with: C# version 3.0+\nvar map = new Dictionary<string, string> {{\"key1\", \"foo\"}};\n\n","human_summarization":"create an associative array (dictionary, map, or hash) in .NET 1.x and .NET 2.0 platforms.","id":3279}
    {"lang_cluster":"C#","source_code":"\nWorks with: C# version 6+\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\n\nnamespace LinearCongruentialGenerator\n{\n    static class LinearCongruentialGenerator\n    {\n        static int _seed = (int)DateTime.Now.Ticks; \/\/ from bad random gens might as well have bad seed!\n        static int _bsdCurrent = _seed;\n        static int _msvcrtCurrent = _seed;\n\n        static int Next(int seed, int a, int b) => (a * seed + b) & int.MaxValue;\n\n        static int BsdRand() => _bsdCurrent = Next(_bsdCurrent, 1103515245, 12345); \n\n        static int MscvrtRand() => _msvcrtCurrent = Next (_msvcrtCurrent << 16,214013,2531011) >> 16;\n\n        static void PrintRandom(int count, bool isBsd)\n        {\n            var name = isBsd ? \"BSD\" : \"MS\";\n            WriteLine($\"{name} next {count} Random\");\n            var gen = isBsd ? (Func<int>)(BsdRand) : MscvrtRand;\n            foreach (var r in Enumerable.Repeat(gen, count))\n                WriteLine(r.Invoke());\n        }\n\n        static void Main(string[] args)\n        {\n            PrintRandom(10, true);\n            PrintRandom(10, false);\n            Read();\n        }\n    }\n}\n\n\nBSD next 10 Random\n1587930915\n19022880\n1025044953\n1143293854\n1642451583\n1110934092\n773706389\n1830436778\n1527715739\n2072016696\nMS next 10 Random\n24368\n8854\n28772\n16122\n11064\n24190\n23724\n6690\n14784\n21222\n\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace FreeCellDeals\n{\n    public class LCG\n    {\n        private int _state;\n        public bool Microsoft { get; set;}\n        public bool BSD\n        {\n            get\n            {\n                return !Microsoft;\n            }\n            set\n            {\n                Microsoft = !value;\n            }\n        }\n\n        public LCG(bool microsoft = true)\n        {\n            _state = (int)DateTime.Now.Ticks;\n            Microsoft = microsoft;\n        }\n\n        public LCG(int n, bool microsoft = true)\n        {\n            _state = n;\n            Microsoft = microsoft;\n        }\n\n        public int Next()\n        {\n            if (BSD)\n            {\n                return _state = (1103515245 * _state + 12345) & int.MaxValue;\n            }\n            return ((_state = 214013 * _state + 2531011) & int.MaxValue) >> 16;\n        }\n\n        public IEnumerable<int> Seq()\n        {\n            while (true)\n            {\n                yield return Next();\n            }\n        }\n    }\n\n    class Program\n    {\n        static void Main()\n        {\n            LCG ms = new LCG(0, true);\n            LCG bsd = new LCG(0,false);\n            Console.WriteLine(\"Microsoft\");\n            ms.Seq().Take(10).ToList().ForEach(Console.WriteLine);\n            Console.WriteLine(\"\\nBSD\");\n            bsd.Seq().Take(10).ToList().ForEach(Console.WriteLine);\n            Console.ReadKey();\n        }\n    }\n}\n\n\nMicrosoft\n38\n7719\n21238\n2437\n8855\n11797\n8365\n32285\n10450\n30612\n\nBSD\n12345\n1406932606\n654583775\n1449466924\n229283573\n1109335178\n1051550459\n1293799192\n794471793\n551188310\n\n","human_summarization":"The code replicates two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). The code uses the Linear Congruential Generator (LCG) formula to generate a sequence of random numbers. The generated sequence is identical to the original generator when starting from the same seed. The BSD and Microsoft formulas are used with specific constants. The code is not cryptographically secure but is sufficient for simple tasks like the Miller-Rabin primality test or FreeCell deals.","id":3280}
    {"lang_cluster":"C#","source_code":"\n\nstatic void InsertAfter<T>(LinkedListNode<T> prev, T value)\n{\n    prev.Next = new Link() { Value = value, Next = prev.Next };\n}\n\nstatic void Main()\n{\n    \/\/Create A(5)->B(7)\n    var A = new LinkedListNode<int>() { Value = 5 };\n    InsertAfter(A, 7);\n    \/\/Insert C between A and B\n    InsertAfter(A, 15);\n}\n\n","human_summarization":"The code defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element 'C' into a list containing elements 'A' and 'B', placing 'C' after 'A'. It utilizes a generic version of the node type and creates nodes from the passed data.","id":3281}
    {"lang_cluster":"C#","source_code":"\nWorks with: C# version 3+\nLibrary: System.Linq\nusing System;\nusing System.Linq;\n\nnamespace RosettaCode.Tasks\n{\n\tpublic static class EthiopianMultiplication_Task\n\t{\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Ethiopian Multiplication\" );\n\t\t\tint A = 17, B = 34;\n\t\t\tConsole.WriteLine ( \"Recursion: {0}*{1}={2}\", A, B, EM_Recursion ( A, B ) );\n\t\t\tConsole.WriteLine ( \"Linq: {0}*{1}={2}\", A, B, EM_Linq ( A, B ) );\n\t\t\tConsole.WriteLine ( \"Loop: {0}*{1}={2}\", A, B, EM_Loop ( A, B ) );\n\t\t\tConsole.WriteLine ( );\n\t\t}\n\n\t\tpublic static int Halve ( this int p_Number )\n\t\t{\n\t\t\treturn p_Number >> 1;\n\t\t}\n\t\tpublic static int Double ( this int p_Number )\n\t\t{\n\t\t\treturn p_Number << 1;\n\t\t}\n\t\tpublic static bool IsEven ( this int p_Number )\n\t\t{\n\t\t\treturn ( p_Number % 2 ) == 0;\n\t\t}\n\n\t\tpublic static int EM_Recursion ( int p_NumberA, int p_NumberB )\n\t\t{\n\t\t\t\/\/     Anchor Point,                Recurse to find the next row                                 Sum it with the second number according to the rules\n\t\t\treturn p_NumberA == 1 ? p_NumberB : EM_Recursion ( p_NumberA.Halve ( ), p_NumberB.Double ( ) ) + ( p_NumberA.IsEven ( ) ? 0 : p_NumberB );\n\t\t}\n\t\tpublic static int EM_Linq ( int p_NumberA, int p_NumberB )\n\t\t{\n\t\t\t\/\/ Creating a range from 1 to x where x the number of times p_NumberA can be halved.\n\t\t\t\/\/ This will be 2^x where 2^x <= p_NumberA. Basically, ln(p_NumberA)\/ln(2).\n\t\t\treturn Enumerable.Range ( 1, Convert.ToInt32 ( Math.Log ( p_NumberA, Math.E ) \/ Math.Log ( 2, Math.E ) ) + 1 )\n\t\t\t\t\/\/ For every item (Y) in that range, create a new list, comprising the pair (p_NumberA,p_NumberB) Y times.\n\t\t\t\t.Select ( ( item ) => Enumerable.Repeat ( new { Col1 = p_NumberA, Col2 = p_NumberB }, item )\n\t\t\t\t\t\/\/ The aggregate method iterates over every value in the target list, passing the accumulated value and the current item's value.\n\t\t\t\t\t.Aggregate ( ( agg_pair, orig_pair ) => new { Col1 = agg_pair.Col1.Halve ( ), Col2 = agg_pair.Col2.Double ( ) } ) )\n\t\t\t\t\/\/ Remove all even items\n\t\t\t\t.Where ( pair => !pair.Col1.IsEven ( ) )\n\t\t\t\t\/\/ And sum!\n\t\t\t\t.Sum ( pair => pair.Col2 );\n\t\t}\n\t\tpublic static int EM_Loop ( int p_NumberA, int p_NumberB )\n\t\t{\n\t\t\tint RetVal = 0;\n\t\t\twhile ( p_NumberA >= 1 )\n\t\t\t{\n\t\t\t\tRetVal += p_NumberA.IsEven ( ) ? 0 : p_NumberB;\n\t\t\t\tp_NumberA = p_NumberA.Halve ( );\n\t\t\t\tp_NumberB = p_NumberB.Double ( );\n\t\t\t}\n\t\t\treturn RetVal;\n\t\t}\n\t}\n}\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":3282}
    {"lang_cluster":"C#","source_code":"\n\nWorks with: C sharp version 8\nusing System;\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\n\npublic static class Solve24Game\n{\n    public static void Main2() {\n        var testCases = new [] {\n            new [] { 1,1,2,7 },\n            new [] { 1,2,3,4 },\n            new [] { 1,2,4,5 },\n            new [] { 1,2,7,7 },\n            new [] { 1,4,5,6 },\n            new [] { 3,3,8,8 },\n            new [] { 4,4,5,9 },\n            new [] { 5,5,5,5 },\n            new [] { 5,6,7,8 },\n            new [] { 6,6,6,6 },\n            new [] { 6,7,8,9 },\n        };\n        foreach (var t in testCases) Test(24, t);\n        Test(100, 9,9,9,9,9,9);\n\n        static void Test(int target, params int[] numbers) {\n            foreach (var eq in GenerateEquations(target, numbers)) Console.WriteLine(eq);\n            Console.WriteLine();\n        }\n    }\n\n    static readonly char[] ops = { '*', '\/', '+', '-' };\n    public static IEnumerable<string> GenerateEquations(int target, params int[] numbers) {\n        var operators = Repeat(ops, numbers.Length - 1).CartesianProduct().Select(e => e.ToArray()).ToList();\n        return (\n            from pattern in Patterns(numbers.Length)\n            let expression = CreateExpression(pattern)\n            from ops in operators\n            where expression.WithOperators(ops).HasPreferredTree()\n            from permutation in Permutations(numbers)\n            let expr = expression.WithValues(permutation)\n            where expr.Value == target && expr.HasPreferredValues()\n            select $\"{expr.ToString()} = {target}\")\n            .Distinct()\n            .DefaultIfEmpty($\"Cannot make {target} with {string.Join(\", \", numbers)}\");\n    }\n\n    \/\/\/<summary>Generates postfix expression trees where 1's represent operators and 0's represent numbers.<\/summary>\n    static IEnumerable<int> Patterns(int length) {\n        if (length == 1) yield return 0; \/\/0\n        if (length == 2) yield return 1; \/\/001\n        if (length < 3) yield break;\n        \/\/Of each tree, the first 2 bits must always be 0 and the last bit must be 1. Generate the bits in between.\n        length -= 2;\n        int len = length * 2 + 3;\n        foreach (int permutation in BinaryPatterns(length, length * 2)) {\n            (int p, int l) = ((permutation << 1) + 1, len);\n            if (IsValidPattern(ref p, ref l)) yield return (permutation << 1) + 1;\n        }\n    }\n\n    \/\/\/<summary>Generates all numbers with the given number of 1's and total length.<\/summary>\n    static IEnumerable<int> BinaryPatterns(int ones, int length) {\n        int initial = (1 << ones) - 1;\n        int blockMask = (1 << length) - 1;\n        for (int v = initial; v >= initial; ) {\n            yield return v;\n            int w = (v | (v - 1)) + 1;\n            w |= (((w & -w) \/ (v & -v)) >> 1) - 1;\n            v = w & blockMask;\n        }\n    }\n\n    static bool IsValidPattern(ref int pattern, ref int len) {\n        bool isNumber = (pattern & 1) == 0;\n        pattern >>= 1;\n        len--;\n        if (isNumber) return true;\n        IsValidPattern(ref pattern, ref len);\n        IsValidPattern(ref pattern, ref len);\n        return len == 0;\n    }\n\n    static Expr CreateExpression(int pattern) {\n        return Create();\n\n        Expr Create() {\n            bool isNumber = (pattern & 1) == 0;\n            pattern >>= 1;\n            if (isNumber) return new Const(0);\n            Expr right = Create();\n            Expr left = Create();\n            return new Binary('*', left, right);\n        }\n    }\n\n    static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences) {\n        IEnumerable<IEnumerable<T>> emptyProduct = new[] { Empty<T>() };\n        return sequences.Aggregate(\n            emptyProduct,\n            (accumulator, sequence) =>\n                from acc in accumulator\n                from item in sequence\n                select acc.Concat(new [] { item }));\n    }\n\n    private static List<int> helper = new List<int>();\n    public static IEnumerable<T[]> Permutations<T>(params T[] input) {\n        if (input == null || input.Length == 0) yield break;\n        helper.Clear();\n        for (int i = 0; i < input.Length; i++) helper.Add(i);\n        while (true) {\n            yield return input;\n            int cursor = helper.Count - 2;\n            while (cursor >= 0 && helper[cursor] > helper[cursor + 1]) cursor--;\n            if (cursor < 0) break;\n            int i = helper.Count - 1;\n            while (i > cursor && helper[i] < helper[cursor]) i--;\n            (helper[cursor], helper[i]) = (helper[i], helper[cursor]);\n            (input[cursor], input[i]) = (input[i], input[cursor]);\n            int firstIndex = cursor + 1;\n            for (int lastIndex = helper.Count - 1; lastIndex > firstIndex; ++firstIndex, --lastIndex) {\n                (helper[firstIndex], helper[lastIndex]) = (helper[lastIndex], helper[firstIndex]);\n                (input[firstIndex], input[lastIndex]) = (input[lastIndex], input[firstIndex]);\n            }\n        }\n    }\n\n    static Expr WithOperators(this Expr expr, char[] operators) {\n        int i = 0;\n        SetOperators(expr, operators, ref i);\n        return expr;\n\n        static void SetOperators(Expr expr, char[] operators, ref int i) {\n            if (expr is Binary b) {\n                b.Symbol = operators[i++];\n                SetOperators(b.Right, operators, ref i);\n                SetOperators(b.Left, operators, ref i);\n            }\n        }\n    }\n\n    static Expr WithValues(this Expr expr, int[] values) {\n        int i = 0;\n        SetValues(expr, values, ref i);\n        return expr;\n\n        static void SetValues(Expr expr, int[] values, ref int i) {\n            if (expr is Binary b) {\n                SetValues(b.Left, values, ref i);\n                SetValues(b.Right, values, ref i);\n            } else {\n                expr.Value = values[i++];\n            }\n        }\n    }\n\n    static bool HasPreferredTree(this Expr expr) => expr switch {\n        Const _ => true,\n    \n        \/\/ a \/ b * c => a * c \/ b\n        ((_, '\/' ,_), '*', _) => false,\n        \/\/ c + a * b => a * b + c\n        (var l, '+', (_, '*' ,_) r) when l.Depth < r.Depth => false,\n        \/\/ c + a \/ b => a \/ b + c\n        (var l, '+', (_, '\/' ,_) r) when l.Depth < r.Depth => false,\n        \/\/ a * (b + c) => (b + c) * a\n        (var l, '*', (_, '+' ,_) r) when l.Depth < r.Depth => false,\n        \/\/ a * (b - c) => (b - c) * a\n        (var l, '*', (_, '-' ,_) r) when l.Depth < r.Depth => false,\n        \/\/ (a +- b) + (c *\/ d) => ((c *\/ d) + a) +- b\n        ((_, var p, _), '+', (_, var q, _)) when \"+-\".Contains(p) && \"*\/\".Contains(q) => false,\n        \/\/ a + (b + c) => (a + b) + c\n        (var l, '+', (_, '+' ,_) r) => false,\n        \/\/ a + (b - c) => (a + b) - c\n        (var l, '+', (_, '-' ,_) r) => false,\n        \/\/ a - (b + c) => (a - b) + c\n        (_, '-', (_, '+', _)) => false,\n        \/\/ a * (b * c) => (a * b) * c\n        (var l, '*', (_, '*' ,_) r) => false,\n        \/\/ a * (b \/ c) => (a * b) \/ c\n        (var l, '*', (_, '\/' ,_) r) => false,\n        \/\/ a \/ (b \/ c) => (a * c) \/ b\n        (var l, '\/', (_, '\/' ,_) r) => false,\n        \/\/ a - (b - c) * d => (c - b) * d + a\n        (_, '-', ((_, '-' ,_), '*', _)) => false,\n        \/\/ a - (b - c) \/ d => (c - b) \/ d + a\n        (_, '-', ((_, '-' ,_), '\/', _)) => false,\n        \/\/ a - (b - c) => a + c - b\n        (_, '-', (_, '-', _)) => false,\n        \/\/ (a - b) + c => (a + c) - b\n        ((_, '-', var b), '+', var c) => false,\n\n        (var l, _, var r) => l.HasPreferredTree() && r.HasPreferredTree()\n    };\n\n    static bool HasPreferredValues(this Expr expr) => expr switch {\n        Const _ => true,\n\n        \/\/ -a + b => b - a\n        (var l, '+', var r) when l.Value < 0 && r.Value >= 0 => false,\n        \/\/ b * a => a * b\n        (var l, '*', var r) when l.Depth == r.Depth && l.Value > r.Value => false,\n        \/\/ b + a => a + b\n        (var l, '+', var r) when l.Depth == r.Depth && l.Value > r.Value => false,\n        \/\/ (b o c) * (a o d) => (a o d) * (b o c)\n        ((var a, _, _) l, '*', (var c, _, _) r) when l.Value == r.Value && l.Depth == r.Depth && a.Value < c.Value => false,\n        \/\/ (b o c) + (a o d) => (a o d) + (b o c)\n        ((var a, var p, _) l, '+', (var c, var q, _) r) when l.Value == r.Value && l.Depth == r.Depth && a.Value < c.Value => false,\n        \/\/ (a * c) * b => (a * b) * c\n        ((_, '*', var c), '*', var b) when b.Value < c.Value => false,\n        \/\/ (a + c) + b => (a + b) + c\n        ((_, '+', var c), '+', var b) when b.Value < c.Value => false,\n        \/\/ (a - b) - c => (a - c) - b\n        ((_, '-', var b), '-', var c) when b.Value < c.Value => false,\n        \/\/ a \/ 1 => a * 1\n        (_, '\/', var b) when b.Value == 1 => false,\n        \/\/ a * b \/ b => a + b - b\n        ((_, '*', var b), '\/', var c) when b.Value == c.Value => false,\n        \/\/ a * 1 * 1 => a + 1 - 1\n        ((_, '*', var b), '*', var c) when b.Value == 1 && c.Value == 1 => false,\n\n        (var l, _, var r) => l.HasPreferredValues() && r.HasPreferredValues()\n    };\n\n    private struct Fraction : IEquatable<Fraction>, IComparable<Fraction>\n    {\n        public readonly int Numerator, Denominator;\n\n        public Fraction(int numerator, int denominator)\n            => (Numerator, Denominator) = (numerator, denominator) switch\n        {\n            (_, 0) => (Math.Sign(numerator), 0),\n            (0, _) => (0, 1),\n            (_, var d) when d < 0 => (-numerator, -denominator),\n            _ => (numerator, denominator)\n        };\n\n        public static implicit operator Fraction(int i) => new Fraction(i, 1);\n        public static Fraction operator +(Fraction a, Fraction b) =>\n            new Fraction(a.Numerator * b.Denominator + a.Denominator * b.Numerator, a.Denominator * b.Denominator);\n        public static Fraction operator -(Fraction a, Fraction b) =>\n            new Fraction(a.Numerator * b.Denominator + a.Denominator * -b.Numerator, a.Denominator * b.Denominator);\n        public static Fraction operator *(Fraction a, Fraction b) =>\n            new Fraction(a.Numerator * b.Numerator, a.Denominator * b.Denominator);\n        public static Fraction operator \/(Fraction a, Fraction b) =>\n            new Fraction(a.Numerator * b.Denominator, a.Denominator * b.Numerator);\n\n        public static bool operator ==(Fraction a, Fraction b) => a.CompareTo(b) == 0;\n        public static bool operator !=(Fraction a, Fraction b) => a.CompareTo(b) != 0;\n        public static bool operator  <(Fraction a, Fraction b) => a.CompareTo(b)  < 0;\n        public static bool operator  >(Fraction a, Fraction b) => a.CompareTo(b)  > 0;\n        public static bool operator <=(Fraction a, Fraction b) => a.CompareTo(b) <= 0;\n        public static bool operator >=(Fraction a, Fraction b) => a.CompareTo(b) >= 0;\n\n        public bool Equals(Fraction other) => Numerator == other.Numerator && Denominator == other.Denominator;\n        public override string ToString() => Denominator == 1 ? Numerator.ToString() : $\"[{Numerator}\/{Denominator}]\";\n\n        public int CompareTo(Fraction other) => (Numerator, Denominator, other.Numerator, other.Denominator) switch {\n            var (    n1, d1,     n2, d2) when n1 == n2 && d1 == d2 => 0,\n                (     0,  0,      _,  _) => (-1),\n                (     _,  _,      0,  0) => 1,\n            var (    n1, d1,     n2, d2) when d1 == d2 => n1.CompareTo(n2),\n                (var n1,  0,      _,  _) => Math.Sign(n1),\n                (     _,  _, var n2,  0) => Math.Sign(n2),\n            var (    n1, d1,     n2, d2) => (n1 * d2).CompareTo(n2 * d1)\n        };\n    }\n\n    private abstract class Expr\n    {\n        protected Expr(char symbol) => Symbol = symbol;\n        public char Symbol { get; set; }\n        public abstract Fraction Value { get; set; }\n        public abstract int Depth { get; }\n        public abstract void Deconstruct(out Expr left, out char symbol, out Expr right);\n    }\n\n    private sealed class Const : Expr\n    {\n        public Const(Fraction value) : base('c') => Value = value;\n        public override Fraction Value { get; set; }\n        public override int Depth => 0;\n        public override void Deconstruct(out Expr left, out char symbol, out Expr right) => (left, symbol, right) = (this, Symbol, this);\n        public override string ToString() => Value.ToString();\n    }\n\n    private sealed class Binary : Expr\n    {\n        public Binary(char symbol, Expr left, Expr right) : base(symbol) => (Left, Right) = (left, right);\n        public Expr Left { get; }\n        public Expr Right { get; }\n        public override int Depth => Math.Max(Left.Depth, Right.Depth) + 1;\n        public override void Deconstruct(out Expr left, out char symbol, out Expr right) => (left, symbol, right) = (Left, Symbol, Right);\n\n        public override Fraction Value {\n            get => Symbol switch {\n                '*' => Left.Value * Right.Value,\n                '\/' => Left.Value \/ Right.Value,\n                '+' => Left.Value + Right.Value,\n                '-' => Left.Value - Right.Value,\n                _ => throw new InvalidOperationException() };\n            set {}\n        }\n\n        public override string ToString() => Symbol switch {\n            '*' => ToString(\"+-\".Contains(Left.Symbol), \"+-\".Contains(Right.Symbol)),\n            '\/' => ToString(\"+-\".Contains(Left.Symbol), \"*\/+-\".Contains(Right.Symbol)),\n            '+' => ToString(false, false),\n            '-' => ToString(false, \"+-\".Contains(Right.Symbol)),\n            _ => $\"[{Value}]\"\n        };\n\n        private string ToString(bool wrapLeft, bool wrapRight) =>\n            $\"{(wrapLeft\u00a0? $\"({Left})\"\u00a0: $\"{Left}\")} {Symbol} {(wrapRight\u00a0? $\"({Right})\"\u00a0: $\"{Right}\")}\";\n    }\n}\n\n\n","human_summarization":"The code takes four digits as input, either provided by the user or generated randomly, and computes arithmetic expressions based on the rules of the 24 game. It generates binary trees, creates permutations, forms expressions, and evaluates them. The code also filters out redundant expressions. It can work with other targets and more numbers, but the performance may slow down.","id":3283}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program\n{\n    static int Factorial(int number)\n    {\n        if(number < 0) \n            throw new ArgumentOutOfRangeException(nameof(number), number, \"Must be zero or a positive number.\");\n\n        var accumulator = 1;\n        for (var factor = 1; factor <= number; factor++)\n        {\n            accumulator *= factor;\n        }\n        return accumulator;\n    }\n\n    static void Main()\n    {\n        Console.WriteLine(Factorial(10));\n    }\n}\n\nusing System;\n\nclass Program\n{\n    static int Factorial(int number)\n    {\n        if(number < 0) \n            throw new ArgumentOutOfRangeException(nameof(number), number, \"Must be zero or a positive number.\");\n\n        return number == 0 ? 1 : number * Factorial(number - 1);\n    }\n\n    static void Main()\n    {\n        Console.WriteLine(Factorial(10));\n    }\n}\n\nTail using System;\n\nclass Program\n{\n    static int Factorial(int number)\n    {\n        if(number < 0) \n            throw new ArgumentOutOfRangeException(nameof(number), number, \"Must be zero or a positive number.\");\n\n        return Factorial(number, 1);\n    }\n\n    static int Factorial(int number, int accumulator)\n    {\n        if(number < 0) \n            throw new ArgumentOutOfRangeException(nameof(number), number, \"Must be zero or a positive number.\");\n        if(accumulator < 1) \n            throw new ArgumentOutOfRangeException(nameof(accumulator), accumulator, \"Must be a positive number.\");\n\n        return number == 0 ? accumulator : Factorial(number - 1, number * accumulator);\n    }\n\n    static void Main()\n    {\n        Console.WriteLine(Factorial(10));\n    }\n}\n\nusing System;\nusing System.Linq;\n\nclass Program\n{\n    static int Factorial(int number)\n    {\n        return Enumerable.Range(1, number).Aggregate((accumulator, factor) => accumulator * factor);\n    }\n\n    static void Main()\n    {\n        Console.WriteLine(Factorial(10));\n    }\n}\n\nLibrary: System.Numerics\n\nusing System;\nusing System.Numerics;\nusing System.Linq; \nclass Program\n{\n    static BigInteger factorial(int n) \/\/ iterative\n    {\n        BigInteger acc = 1; for (int i = 1; i <= n; i++) acc *= i; return acc;\n    }\n\n    static public BigInteger Factorial(int number) \/\/ functional\n    {\n        return Enumerable.Range(1, number).Aggregate(new BigInteger(1), (acc, num) => acc * num);\n    }\n\n    static public BI FactorialQ(int number) \/\/ functional quick, uses prodtree method\n    {\n        var s = Enumerable.Range(1, number).Select(num => new BI(num)).ToArray();\n        int top = s.Length, nt, i, j;\n        while (top > 1) {\n            for (i = 0, j = top, nt = top >> 1; i < nt; i++) s[i] *= s[--j];\n            top = nt + ((top & 1) == 1 ? 1 : 0);\n        }\n        return s[0];\n    }\n\n    static void Main(string[] args)\n    {\n        Console.WriteLine(Factorial(250));\n    }\n}\n\n\n","human_summarization":"The code implements a function to calculate the factorial of a given number. The factorial function multiplies a sequence of descending positive integers from the given number down to 1. The function can handle both iterative and recursive solutions, and optionally supports error handling for negative inputs. The code also includes a comparison between the plain method and the product tree method for calculating factorials, demonstrating that the product tree method is more efficient for large inputs.","id":3284}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace BullsnCows\n{\n    class Program\n    {\n        \n        static void Main(string[] args)\n        {\n            int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };\n            KnuthShuffle<int>(ref nums);\n            int[] chosenNum = new int[4];\n            Array.Copy(nums, chosenNum, 4);\n\n            Console.WriteLine(\"Your Guess\u00a0?\");\n            while (!game(Console.ReadLine(), chosenNum))\n            {\n                Console.WriteLine(\"Your next Guess\u00a0?\");\n            }\n            \n            Console.ReadKey();\n        }\n\n        public static void KnuthShuffle<T>(ref T[] array)\n        {\n            System.Random random = new System.Random();\n            for (int i = 0; i < array.Length; i++)\n            {\n                int j = random.Next(array.Length);\n                T temp = array[i]; array[i] = array[j]; array[j] = temp;\n            }\n        }\n\n        public static bool game(string guess, int[] num)\n        {\n            char[] guessed = guess.ToCharArray();\n            int bullsCount = 0, cowsCount = 0;\n\n            if (guessed.Length != 4)\n            {\n                Console.WriteLine(\"Not a valid guess.\");\n                return false;\n            }\n\n            for (int i = 0; i < 4; i++)\n            {\n                int curguess = (int) char.GetNumericValue(guessed[i]);\n                if (curguess < 1 || curguess > 9)\n                {\n                    Console.WriteLine(\"Digit must be ge greater 0 and lower 10.\");\n                    return false;\n                }\n                if (curguess == num[i])\n                {\n                    bullsCount++;\n                }\n                else\n                {\n                    for (int j = 0; j < 4; j++)\n                    {\n                        if (curguess == num[j])\n                            cowsCount++;\n                    }\n                }\n            }\n\n            if (bullsCount == 4)\n            {\n                Console.WriteLine(\"Congratulations! You have won!\");\n                return true;\n            }\n            else\n            {\n                Console.WriteLine(\"Your Score is {0} bulls and {1} cows\", bullsCount, cowsCount);\n                return false;\n            }\n        }\n    }\n}\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":3285}
    {"lang_cluster":"C#","source_code":"private static double randomNormal()\n{\n\treturn Math.Cos(2 * Math.PI * tRand.NextDouble()) * Math.Sqrt(-2 * Math.Log(tRand.NextDouble()));\n}\n\n\nstatic Random tRand = new Random();\n\nstatic void Main(string[] args)\n{\n\tdouble[] a = new double[1000];\n\n\tdouble tAvg = 0;\n\tfor (int x = 0; x < a.Length; x++)\n\t{\n\t\ta[x] = randomNormal() \/ 2 + 1;\n\t\ttAvg += a[x];\n\t}\n\n\ttAvg \/= a.Length;\n\tConsole.WriteLine(\"Average: \" + tAvg.ToString());\n\n\tdouble s = 0;\n\tfor (int x = 0; x < a.Length; x++)\n\t{\n\t\ts += Math.Pow((a[x] - tAvg), 2);\n\t}\n\ts = Math.Sqrt(s \/ 1000);\n\n\tConsole.WriteLine(\"Standard Deviation: \" + s.ToString());\n\n\tConsole.ReadLine();\n}\n\n\nAverage: 1,00510073053613\nStandard Deviation: 0,502540443430955\n\n","human_summarization":"generates a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5. If the library only supports uniformly distributed random numbers, it applies a specific algorithm to achieve the normal distribution. It also calculates the average and standard deviation of the generated numbers.","id":3286}
    {"lang_cluster":"C#","source_code":"\nstatic void Main(string[] args)\n{\n\tConsole.WriteLine(DotProduct(new decimal[] { 1, 3, -5 }, new decimal[] { 4, -2, -1 }));\n\tConsole.Read();\n}\n\nprivate static decimal DotProduct(decimal[] vec1, decimal[] vec2) \n{\n\tif (vec1 == null)\n\t\treturn 0;\n\n\tif (vec2 == null)\n\t\treturn 0;\n\n\tif (vec1.Length != vec2.Length)\n\t\treturn 0;\n\n\tdecimal tVal = 0;\n\tfor (int x = 0; x < vec1.Length; x++)\n\t{\n\t\ttVal += vec1[x] * vec2[x];\n\t}\n\n\treturn tVal;\n}\n\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":3287}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.IO;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        \/\/ For stdin, you could use\n        \/\/ new StreamReader(Console.OpenStandardInput(), Console.InputEncoding)\n\n        using (var b = new StreamReader(\"file.txt\"))\n        {\n            string line;\n            while ((line = b.ReadLine()) != null)\n                Console.WriteLine(line);\n        }\n    }\n}\n\n","human_summarization":"\"Continuously read words or lines from a text stream until there is no more data available.\"","id":3288}
    {"lang_cluster":"C#","source_code":"\n\nusing System.Xml;\nusing System.Xml.Serialization;\n[XmlRoot(\"root\")]\npublic class ExampleXML\n{\n    [XmlElement(\"element\")]\n    public string element = \"Some text here\";\n    static void Main(string[] args)\n    {\n        var xmlnamespace = new XmlSerializerNamespaces();\n        xmlnamespace.Add(\"\", \"\"); \/\/used to stop default namespaces from printing\n        var writer = XmlWriter.Create(\"output.xml\");\n        new XmlSerializer(typeof(ExampleXML)).Serialize(writer, new ExampleXML(), xmlnamespace);\n    }\n    \/\/","human_summarization":"The code creates a simple DOM and serializes it into XML format using the System.Xml.Serialization library of .Net. The resulting XML contains a root element with a nested element that contains some text.","id":3289}
    {"lang_cluster":"C#","source_code":"\nConsole.WriteLine(DateTime.Now);\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":3290}
    {"lang_cluster":"C#","source_code":"\nstatic int[] sedol_weights = { 1, 3, 1, 7, 3, 9 };\nstatic int sedolChecksum(string sedol)\n{\n    int len = sedol.Length;\n    int sum = 0;\n\n    if (len == 7) \/\/SEDOL code already checksummed?\n        return (int)sedol[6];\n\n    if ((len > 7) || (len < 6) || System.Text.RegularExpressions.Regex.IsMatch(sedol, \"[AEIOUaeiou]+\")) \/\/invalid SEDOL\n        return -1;\n\n    for (int i = 0; i < 6; i++)\n    {\n        if (Char.IsDigit(sedol[i]))\n            sum += (((int)sedol[i] - 48) * sedol_weights[i]);\n\n        else if (Char.IsLetter(sedol[i]))\n            sum += (((int)Char.ToUpper(sedol[i]) - 55) * sedol_weights[i]);\n\n        else\n            return -1;\n\n    }\n\n    return (10 - (sum % 10)) % 10;\n}\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":3291}
    {"lang_cluster":"C#","source_code":"using System;\n\nnamespace Sphere {\n    internal class Program {\n        private const string Shades = \".:!*oe%&#@\";\n        private static readonly double[] Light = {30, 30, -50};\n\n        private static void Normalize(double[] v) {\n            double len = Math.Sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n            v[0] \/= len;\n            v[1] \/= len;\n            v[2] \/= len;\n        }\n\n        private static double Dot(double[] x, double[] y) {\n            double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n            return d < 0 ? -d : 0;\n        }\n\n        public static void DrawSphere(double r, double k, double ambient) {\n            var vec = new double[3];\n            for(var i = (int)Math.Floor(-r); i <= (int)Math.Ceiling(r); i++) {\n                double x = i + .5;\n                for(var j = (int)Math.Floor(-2*r); j <= (int)Math.Ceiling(2*r); j++) {\n                    double y = j\/2.0 + .5;\n                    if(x*x + y*y <= r*r) {\n                        vec[0] = x;\n                        vec[1] = y;\n                        vec[2] = Math.Sqrt(r*r - x*x - y*y);\n                        Normalize(vec);\n                        double b = Math.Pow(Dot(Light, vec), k) + ambient;\n                        int intensity = (b <= 0)\n                                            ? Shades.Length - 2\n                                            : (int)Math.Max((1 - b)*(Shades.Length - 1), 0);\n                        Console.Write(Shades[intensity]);\n                    }\n                    else\n                        Console.Write(' ');\n                }\n                Console.WriteLine();\n            }\n        }\n\n        private static void Main() {\n            Normalize(Light);\n            DrawSphere(6, 4, .1);\n            DrawSphere(10, 2, .4);\n            Console.ReadKey();\n        }\n    }\n}\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":3292}
    {"lang_cluster":"C#","source_code":"using System;\nusing System.Linq;\n\nclass Program\n{\n    private static string Ordinalize(int i)\n    {\n        i = Math.Abs(i);\n\n        if (new[] {11, 12, 13}.Contains(i%100))\n            return i + \"th\";\n\n        switch (i%10)\n        {\n            case 1:\n                return i + \"st\";\n            case 2:\n                return i + \"nd\";\n            case 3:\n                return i + \"rd\";\n            default:\n                return i + \"th\";\n        }\n    }\n\n    static void Main()\n    {\n        Console.WriteLine(string.Join(\" \", Enumerable.Range(0, 26).Select(Ordinalize)));\n        Console.WriteLine(string.Join(\" \", Enumerable.Range(250, 16).Select(Ordinalize)));\n        Console.WriteLine(string.Join(\" \", Enumerable.Range(1000, 26).Select(Ordinalize)));\n    }\n}\n\n\nusing System;\n\nstatic string Ordinalize(int i)\n{\n    return i + (\n        i % 100 is >= 11 and <= 13 ? \"th\" :\n        i % 10 == 1 ? \"st\" :\n        i % 10 == 2 ? \"nd\" :\n        i % 10 == 3 ? \"rd\" :\n        \"th\");\n}\n\nstatic void PrintRange(int begin, int end)\n{\n    for(var i = begin; i <= end; i++)\n        Console.Write(Ordinalize(i) + (i == end ? \"\" : \" \"));\n    Console.WriteLine();\n}\n\nPrintRange(0, 25);\nPrintRange(250, 265);\nPrintRange(1000, 1025);\n\n\n","human_summarization":"The code defines a function that takes an integer greater than or equal to zero as input and returns a string representation of the number appended with its ordinal suffix. The function is used to generate and display the ordinal representation of numbers in the ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional. The implementation does not use LINQ and is compatible with Dotnet 5.","id":3293}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\npublic static string RemoveCharactersFromString(string testString, string removeChars)\n{\n    char[] charAry = removeChars.ToCharArray();\n    string returnString = testString;\n    foreach (char c in charAry)\n    {\n        while (returnString.IndexOf(c) > -1)\n        {\n            returnString = returnString.Remove(returnString.IndexOf(c), 1);\n        }\n    }\n    return returnString;\n}\n\n\nusing System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        string testString = \"She was a soul stripper. She took my heart!\";\n        string removeChars = \"aei\";\n        Console.WriteLine(RemoveCharactersFromString(testString, removeChars));\n    }\n}\n\n","human_summarization":"The code defines a function that removes a specific set of characters from a given string. The function takes two arguments: the original string and a string of characters to be removed. The function returns the original string with all instances of the characters in the second string removed.","id":3294}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\n\npublic class GeneralFizzBuzz\n{\n    public static void Main() \n    {\n        int i;\n        int j;\n        int k;\n        \n        int limit;\n        \n        string iString;\n        string jString;\n        string kString;\n\n        Console.WriteLine(\"First integer:\");\n        i = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"First string:\");\n        iString = Console.ReadLine();\n\n        Console.WriteLine(\"Second integer:\");\n        j = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Second string:\");\n        jString = Console.ReadLine();\n\n        Console.WriteLine(\"Third integer:\");\n        k = Convert.ToInt32(Console.ReadLine());\n        Console.WriteLine(\"Third string:\");\n        kString = Console.ReadLine();\n\n        Console.WriteLine(\"Limit (inclusive):\");\n        limit = Convert.ToInt32(Console.ReadLine());\n\n        for(int n = 1; n<= limit; n++)\n        {\n            bool flag = true;\n            if(n%i == 0)\n            {\n                Console.Write(iString);\n                flag = false;\n            }\n\n            if(n%j == 0)\n            {\n                Console.Write(jString);\n                flag = false;\n            }\n\n            if(n%k == 0)\n            {\n                Console.Write(kString);\n                flag = false;\n            }\n            if(flag)\n                Console.Write(n);\n            Console.WriteLine();\n        }\n    }\n}\n\n","human_summarization":"The code takes a maximum number and a list of factors with corresponding words as input from the user. It then prints numbers from 1 to the maximum number, replacing multiples of the given factors with the corresponding words. If a number is a multiple of multiple factors, it prints all corresponding words in the order of the factors.","id":3295}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace PrependString\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            string str = \"World\";\n            str = \"Hello \" + str;\n            Console.WriteLine(str);\n            Console.ReadKey();\n        }\n    }\n}\n\nHello World\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":3296}
    {"lang_cluster":"C#","source_code":"using System;\nusing System.Collections.Generic;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\npublic class DragonCurve : Form\n{\n    private List<int> turns;\n    private double startingAngle, side;\n\n    public DragonCurve(int iter)\n    {\n        Size = new Size(800, 600);\n        StartPosition = FormStartPosition.CenterScreen;\n        DoubleBuffered = true;\n        BackColor = Color.White;\n\n        startingAngle = -iter * (Math.PI \/ 4);\n        side = 400 \/ Math.Pow(2, iter \/ 2.0);\n\n        turns = getSequence(iter);\n    }\n\n    private List<int> getSequence(int iter)\n    {\n        var turnSequence = new List<int>();\n        for (int i = 0; i < iter; i++)\n        {\n            var copy = new List<int>(turnSequence);\n            copy.Reverse();\n            turnSequence.Add(1);\n            foreach (int turn in copy)\n            {\n                turnSequence.Add(-turn);\n            }\n        }\n        return turnSequence;\n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        base.OnPaint(e);\n        e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;\n\n        double angle = startingAngle;\n        int x1 = 230, y1 = 350;\n        int x2 = x1 + (int)(Math.Cos(angle) * side);\n        int y2 = y1 + (int)(Math.Sin(angle) * side);\n        e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n        x1 = x2;\n        y1 = y2;\n        foreach (int turn in turns)\n        {\n            angle += turn * (Math.PI \/ 2);\n            x2 = x1 + (int)(Math.Cos(angle) * side);\n            y2 = y1 + (int)(Math.Sin(angle) * side);\n            e.Graphics.DrawLine(Pens.Black, x1, y1, x2, y2);\n            x1 = x2;\n            y1 = y2;\n        }\n    }\n\n    [STAThread]\n    static void Main()\n    {\n        Application.Run(new DragonCurve(14));\n    }\n}\n\n","human_summarization":"generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.","id":3297}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass GuessTheNumberGame\n{\n    static void Main()\n    {\n        int randomNumber = new Random().Next(1, 11);\n        \n        Console.WriteLine(\"I'm thinking of a number between 1 and 10. Can you guess it?\");\n        while(true)\n        {\n            Console.Write(\"Guess: \");\n            if (int.Parse(Console.ReadLine()) == randomNumber)\n                break;\n            Console.WriteLine(\"That's not it. Guess again.\");\n        }\n        Console.WriteLine(\"Congrats!! You guessed right!\");\n    }\n};\n\n\n\nusing System; using System.Text; \/\/daMilliard.cs \nnamespace DANILIN\n\n{ class Program\n    { static void Main(string[] args)\n    { Random rand = new Random();int t=0;\nint h2=100000000; int h1=0; int f=0; \nint comp = rand.Next(h2); \nint human = rand.Next(h2); \n\nwhile (f<1)\n{ Console.WriteLine();Console.Write(t);\nConsole.Write(\" \");Console.Write(comp); \nConsole.Write(\" \");Console.Write(human);\n\nif(comp < human)\n{ Console.Write(\" MORE\");\nint a=comp; comp=(comp+h2)\/2; h1=a; }\n\nelse if(comp > human)\n{ Console.Write(\" less\");\nint a=comp; comp=(h1+comp)\/2; h2=a;}\n\nelse {Console.Write(\" win by \");\nConsole.Write(t); Console.Write(\" steps\");f=1;}\nt++; }}}}\n\n\n","human_summarization":"The code generates a random number between 1 and 10, then repeatedly prompts the user to guess the number. If the guess is incorrect, the user is prompted again. Once the correct number is guessed, the program displays a \"Well guessed!\" message and terminates.","id":3298}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\nusing System.Linq;\n\ninternal class Program\n{\n    private static void Main()\n    {\n        Console.WriteLine(String.Concat(Enumerable.Range('a', 26).Select(c => (char)c)));\n    }\n}\n\n","human_summarization":"generate an array, list, or string of all lowercase ASCII characters, from a to z, using a reliable and strongly typed coding style. This is done to avoid bugs associated with manually enumerating the characters in the code. The solution includes both a simple Linq 1 liner solution and an old style property and enumerable based solution.","id":3299}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var number in new[] { 5, 50, 9000 })\n        {\n            Console.WriteLine(Convert.ToString(number, 2));\n        }\n    }\n}\n\nAnother version using dotnet 5using System;\nusing System.Text;\n\nstatic string ToBinary(uint x) {\n    if(x == 0) return \"0\";\n    var bin = new StringBuilder();\n    for(uint mask = (uint)1 << (sizeof(uint)*8 - 1);mask > 0;mask = mask >> 1)\n        bin.Append((mask & x) > 0\u00a0? \"1\"\u00a0: \"0\");\n    return bin.ToString().TrimStart('0');\n}\n\nConsole.WriteLine(ToBinary(5));\nConsole.WriteLine(ToBinary(50));\nConsole.WriteLine(ToBinary(9000));\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":3300}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing System.Runtime.Serialization;\n\npublic static class MergeAndAggregateDatasets\n{\n    public static void Main()\n    {\n        string patientsCsv = @\"\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\";\n\n        string visitsCsv = @\"\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\";\n\n        string format = \"yyyy-MM-dd\";\n        var formatProvider = new DateTimeFormat(format).FormatProvider;\n\n        var patients = ParseCsv(\n            patientsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (PatientId: int.Parse(line[0]), LastName: line[1]));\n\n        var visits = ParseCsv(\n            visitsCsv.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries),\n            line => (\n                PatientId: int.Parse(line[0]),\n                VisitDate: DateTime.TryParse(line[1], formatProvider, DateTimeStyles.None, out var date) ? date : default(DateTime?),\n                Score: double.TryParse(line[2], out double score) ? score : default(double?)\n            )\n        );\n\n        var results =\n            patients.GroupJoin(visits,\n                p => p.PatientId,\n                v => v.PatientId,\n                (p, vs) => (\n                    p.PatientId,\n                    p.LastName,\n                    LastVisit: vs.Max(v => v.VisitDate),\n                    ScoreSum: vs.Sum(v => v.Score),\n                    ScoreAvg: vs.Average(v => v.Score)\n                )\n            ).OrderBy(r => r.PatientId);\n\n        Console.WriteLine(\"| PATIENT_ID | LASTNAME | LAST_VISIT | SCORE_SUM | SCORE_AVG |\");\n        foreach (var r in results) {\n            Console.WriteLine($\"| {r.PatientId,-10} | {r.LastName,-8} | {r.LastVisit?.ToString(format)\u00a0?? \"\",-10} | {r.ScoreSum,9} | {r.ScoreAvg,9} |\");\n        }\n    }\n\n    private static IEnumerable<T> ParseCsv<T>(string[] contents, Func<string[], T> constructor)\n    {\n        for (int i = 1; i < contents.Length; i++) {\n            var line = contents[i].Split(',');\n            yield return constructor(line);\n        }\n    }\n\n}\n\n\n","human_summarization":"\"Merge and aggregate two provided .csv datasets into a new dataset, grouping by patient id and last name, calculating the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on screen, stored in memory, or written to a file.\"","id":3301}
    {"lang_cluster":"C#","source_code":"public static class Haversine {\n  public static double calculate(double lat1, double lon1, double lat2, double lon2) {\n    var R = 6372.8; \/\/ In kilometers\n    var dLat = toRadians(lat2 - lat1);\n    var dLon = toRadians(lon2 - lon1);\n    lat1 = toRadians(lat1);\n    lat2 = toRadians(lat2);\n   \n    var a = Math.Sin(dLat \/ 2) * Math.Sin(dLat \/ 2) + Math.Sin(dLon \/ 2) * Math.Sin(dLon \/ 2) * Math.Cos(lat1) * Math.Cos(lat2);\n    var c = 2 * Math.Asin(Math.Sqrt(a));\n    return R * 2 * Math.Asin(Math.Sqrt(a));\n  }\n  \n  public static double toRadians(double angle) {\n    return Math.PI * angle \/ 180.0;\n  }\n}\n\nvoid Main() {\n  Console.WriteLine(String.Format(\"The distance between coordinates {0},{1} and {2},{3} is: {4}\", 36.12, -86.67, 33.94, -118.40, Haversine.calculate(36.12, -86.67, 33.94, -118.40)));\n}\n\n\/\/ Returns: The distance between coordinates 36.12,-86.67 and 33.94,-118.4 is: 2887.25995060711\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":3302}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Text;\nusing System.Net;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        WebClient wc = new WebClient();\n        string content = wc.DownloadString(\"http:\/\/www.google.com\");\n        Console.WriteLine(content);\n    }\n}\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":3303}
    {"lang_cluster":"C#","source_code":"\n\n    public static class Luhn\n    {\n        public static bool LuhnCheck(this string cardNumber)\n        {\n            return LuhnCheck(cardNumber.Select(c => c - '0').ToArray());\n        }\n\n        private static bool LuhnCheck(this int[] digits)\n        {\n            return GetCheckValue(digits) == 0;\n        }\n\n        private static int GetCheckValue(int[] digits)\n        {\n            return digits.Select((d, i) => i % 2 == digits.Length % 2 ? ((2 * d) % 10) + d \/ 5 : d).Sum() % 10;\n        }\n    }\n\n    public static class TestProgram\n    {\n        public static void Main()\n        {\n            long[] testNumbers = {49927398716, 49927398717, 1234567812345678, 1234567812345670};\n            foreach (var testNumber in testNumbers)\n                Console.WriteLine(\"{0} is {1}valid\", testNumber, testNumber.ToString().LuhnCheck() ? \"\" : \"not \");\n        }\n    }\n\n49927398716 is valid\n49927398717 is not valid\n1234567812345678 is not valid\n1234567812345670 is valid\n\n\nusing System;\nusing System.Linq;\n\nnamespace Luhn\n{\n    class Program\n    {\n        public static bool luhn(long n)\n        {\n            long nextdigit, sum = 0;            \n            bool alt = false;            \n            while (n != 0)\n            {                \n                nextdigit = n % 10;\n                if (alt)\n                {\n                    nextdigit *= 2;\n                    nextdigit -= (nextdigit > 9) ? 9 : 0;\n                }\n                sum += nextdigit;\n                alt = !alt;\n                n \/= 10;\n            }\n            return (sum % 10 == 0);\n        }\n\n        public static bool luhnLinq(long n)\n        {\n            string s = n.ToString();\n            return s.Select((c, i) => (c - '0') << ((s.Length - i - 1) & 1)).Sum(n => n > 9 ? n - 9 : n) % 10 == 0;\n        }\n\n        static void Main(string[] args)\n        {            \n            long[] given = new long[] {49927398716, 49927398717, 1234567812345678, 1234567812345670};\n            foreach (long num in given)\n            {\n                string valid = (luhn(num)) ? \" is valid\" : \" is not valid\";\n                Console.WriteLine(num + valid);\n            }\n            \n        }\n    }\n}\n\n49927398716 is valid\n49927398717 is not valid\n1234567812345678 is not valid\n1234567812345670 is valid\n\n\nusing System;\nnamespace Luhn_Test\n{\n\tpublic static class Extensions \n\t{\n\t\tpublic static string Reverse(this string s )\n\t\t{\n\t\t    char[] charArray = s.ToCharArray();\n\t\t    Array.Reverse( charArray );\n\t\t    return new string( charArray );\n\t\t}\n\t}\n\tclass Program\n\t{\n\t\tpublic static bool Luhn(long x)\n\t\t{\n\t\t\tlong s1=0;\n\t\t\tlong s2=0;\n\t\t\tbool STATE=x%10!=0; \/\/ If it ends with zero, we want the order to be the other way around\n\t\t\tx=long.Parse(x.ToString().Reverse());\n\t\t\twhile (x!=0)\n\t\t\t{\n\t\t\t\ts1+=STATE?x%10:0;\n\t\t\t\ts2+=STATE?0:((x%10)*2>9)?(((x%10)*2\/10)+((x%10)*2)%10):((x%10)*2); \n\t\t\t\tSTATE=!STATE; \/\/Switch state\n\t\t\t\tx\/=10; \/\/Cut the last digit and continue\n\t\t\t}\n\t\t\treturn ((s1+s2)%10==0); \/\/Check if it ends with zero, if so, return true, otherwise,false.\n\t\t}\n\t\tpublic static void Main(string[] args)\n\t\t{\n\t\t\tlong[] ks = {1234567812345670, 49927398717, 1234567812345678 ,1234567812345670 };\n\t\t\tforeach (long k in ks)\n\t\t\t{\n\t\t\tConsole.WriteLine(\"{0} is {1} Valid.\",k,Luhn(k)?\"\":\"Not\");\t\n\t\t\t}\n\t\tStart:\n\t\t\ttry { \n\t\t\tConsole.WriteLine(\"Enter your credit:\");\n\t\t\tlong x=long.Parse(Console.ReadLine());\n\t\t\tConsole.WriteLine(\"{0} Valid.\",Luhn(x)?\"\":\"Not\");\n\t\t\tgoto Start;\n\t\t\t}\n\t\t\tcatch (FormatException)\n\t\t\t{\n\t\t\t\tgoto Start;\n\t\t\t}\t\t\t\n\t\t}\n\t}\n}\n\n1234567812345670 is Valid.\n49927398717 is Not Valid.\n1234567812345678 is Not Valid.\n49927398716 is Valid.\n\n\nusing System;\nusing System.Linq;\n\npublic class CreditCardLogic\n{\n    static Func<char, int> charToInt = c => c - '0';\n\n    static Func<int, int> doubleDigit = n => (n * 2).ToString().Select(charToInt).Sum();\n\n    static Func<int, bool> isOddIndex = index => index % 2 == 0;\n\n    public static bool LuhnCheck(string creditCardNumber)\n    {\n        var checkSum = creditCardNumber\n            .Select(charToInt)\n            .Reverse()\n            .Select((digit, index) => isOddIndex(index) ? digit : doubleDigit(digit))\n            .Sum();\n\n        return checkSum % 10 == 0;\n    }\n}\n\n\nusing System;\nusing EuropaRTL.Utilities;\n\npublic static partial class Algoritmhs\n{\n    public static bool CheckLuhn(long n)\n    {\n        int s1 = n.Shatter(true).Subset(2).Arithmetic('+');\n        int s2 = n.Shatter(true).Subset(1, -1, 2).ArithmeticRA('*', 2).ShatterAndSum().Arithmetic('+');\n        return (s1 + s2) % 10 == 0 ? true : false;\n    }\n}\nclass Program\n{\n    static void Main(string[] args)\n    {\n        long[] ll = {\n                49927398716,\n                49927398717,\n                1234567812345678,\n                1234567812345670\n            };\n        foreach (var item in ll)\n        {\n            item.ToString().WriteLine();\n            Algoritmhs.CheckLuhn(item).ToString().WriteLine();\n        }\n        Console.ReadKey();\n    }\n}\n\n49927398716\nTrue\n49927398717\nFalse\n1234567812345678\nFalse\n1234567812345670\nFalse\n\n","human_summarization":"The code validates credit card numbers using the Luhn algorithm. It first reverses the digits of the number, then calculates two partial sums, s1 and s2. S1 is the sum of the odd digits in the reversed number, while s2 is calculated by doubling each even digit, summing the digits of the result if it's greater than nine, and then summing these values. If the total of s1 and s2 ends in zero, the number is validated as a legitimate credit card number. The code also includes a method for validating an array of integers.","id":3304}
    {"lang_cluster":"C#","source_code":"\nnamespace Josephus\n{\n    using System;\n    using System.Collections;\n    using System.Collections.Generic;\n\n    public class Program\n    {\n        public static int[] JosephusProblem(int n, int m)\n        {\n            var circle = new List<int>();\n            var order = new int[n];\n\n            for (var i = 0; i < n; ++i)\n            {\n                circle.Add(i);\n            }\n\n            var l = 0;\n            var j = 0;\n            var k = 0;\n\n            while (circle.Count != 0)\n            {\n                j++;\n                if (j == m)\n                {\n                    order[k] = circle[l];\n                    circle.RemoveAt(l);\n\n                    k++;\n                    l--;\n                    j = 0;\n                }\n\n                if (k == n - 1)\n                {\n                    order[k] = circle[0];\n                    circle.RemoveAt(0);\n                }\n\n                if (l == circle.Count - 1)\n                {\n                    l = 0;\n                }\n                else\n                {\n                    l++;\n                }\n            }\n\n            return order;\n        }\n\n        static void Main(string[] args)\n        {\n            try\n            {\n                var n = 7;\n                var m = 2;\n\n                var result = JosephusProblem(n, m);\n\n               for (var i = 0; i < result.Length; i++)\n               {\n                   Console.WriteLine(result[i]);\/\/1 3 5 0 4 2 6\n               }\n            }\n            catch (Exception e)\n            {\n                Console.WriteLine(e);\n            }\n            finally\n            {\n                Console.ReadLine();\n            }\n        }\n\n    }\n}\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":3305}
    {"lang_cluster":"C#","source_code":"\nstring s = \"\".PadLeft(5, 'X').Replace(\"X\", \"ha\");\n\n\nstring s = new String('X', 5).Replace(\"X\", \"ha\");\n\n\nstring s = String.Join(\"ha\", new string[5 + 1]);\n\n\nstring s = String.Concat(Enumerable.Repeat(\"ha\", 5));\n\n\nstring s = \"\".PadLeft(5, '*');\n\n\nstring s = new String('*', 5);\n\n","human_summarization":"The code takes a string or a single character and repeats it a specified number of times. For example, repeating \"ha\" 5 times results in \"hahahahaha\", and repeating \"*\" 5 times results in \"*****\". It is designed to work with .NET 2+ and .NET 4+.","id":3306}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Text.RegularExpressions;\n\nclass Program {\n    static void Main(string[] args) {\n        string str = \"I am a string\";\n\n        if (new Regex(\"string$\").IsMatch(str)) {\n            Console.WriteLine(\"Ends with string.\");\n        }\n\n        str = new Regex(\" a \").Replace(str, \" another \");\n        Console.WriteLine(str);\n    }\n}\n\n","human_summarization":"\"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression.\"","id":3307}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int a = Convert.ToInt32(args[0]);\n        int b = Convert.ToInt32(args[1]);\n\n        Console.WriteLine(\"{0} + {1} = {2}\", a, b, a + b);\n        Console.WriteLine(\"{0} - {1} = {2}\", a, b, a - b);\n        Console.WriteLine(\"{0} * {1} = {2}\", a, b, a * b);\n        Console.WriteLine(\"{0} \/ {1} = {2}\", a, b, a \/ b); \/\/ truncates towards 0\n        Console.WriteLine(\"{0}\u00a0% {1} = {2}\", a, b, a % b); \/\/ matches sign of first operand\n        Console.WriteLine(\"{0} to the power of {1} = {2}\", a, b, Math.Pow(a, b));\n    }\n}\n\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":3308}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass SubStringTestClass\n{\n   public static int CountSubStrings(this string testString, string testSubstring)\n   {\n        int count = 0;\n            \n        if (testString.Contains(testSubstring))\n        {\n            for (int i = 0; i < testString.Length; i++)\n            {\n                if (testString.Substring(i).Length >= testSubstring.Length)\n                {\n                    bool equals = testString.Substring(i, testSubstring.Length).Equals(testSubstring);\n                    if (equals)\n                    {\n                        count++;\n                        i += testSubstring.Length - 1;  \/\/ Fix: Don't count overlapping matches\n                    }\n                }\n            }\n        }\n        return count;\n   }\n}\n\nusing System;\nclass SubStringTestClass\n{\n   public static int CountSubStrings(this string testString, string testSubstring) =>\n       testString?.Split(new [] { testSubstring }, StringSplitOptions.None)?.Length - 1\u00a0?? 0;\n}\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer count of non-overlapping matches, prioritizing the highest number of such matches. The function does not count overlapping substrings. It uses features from C# 6.0 including expression-bodied member, null-conditional operator, and coalesce operator.","id":3309}
    {"lang_cluster":"C#","source_code":"\npublic  void move(int n, int from, int to, int via) {\n   if (n == 1) {\n     System.Console.WriteLine(\"Move disk from pole \" + from + \" to pole \" + to);\n   } else {\n     move(n - 1, from, via, to);\n     move(1, from, to, via);\n     move(n - 1, via, to, from);\n   }\n }\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":3310}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace BinomialCoefficients\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ulong n = 1000000, k = 3;\n            ulong result = biCoefficient(n, k);\n            Console.WriteLine(\"The Binomial Coefficient of {0}, and {1}, is equal to: {2}\", n, k, result);\n            Console.ReadLine();\n        }\n\n        static int fact(int n)\n        {\n            if (n == 0) return 1;\n            else return n * fact(n - 1);\n        }\n\n        static ulong biCoefficient(ulong n, ulong k)\n        {\n            if (k > n - k)\n            {\n                k = n - k;\n            }\n\n            ulong c = 1;\n            for (uint i = 0; i < k; i++)\n            {\n                c = c * (n - i);\n                c = c \/ (i + 1);\n            }\n            return c;\n        }\n    }\n}\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":3311}
    {"lang_cluster":"C#","source_code":"\npublic static class ShellSorter\n{\n    public static void Sort<T>(IList<T> list) where T\u00a0: IComparable\n    {\n        int n = list.Count;\n        int h = 1;\n\n        while (h < (n >> 1))\n        {   \n            h = (h << 1) + 1;\n        }\n\n        while (h >= 1)\n        {\n            for (int i = h; i < n; i++)\n            {\n                int k = i - h;\n                for (int j = i; j >= h && list[j].CompareTo(list[k]) < 0; k -= h)\n                {\n                    T temp = list[j];\n                    list[j] = list[k];\n                    list[k] = temp;\n                    j = k;\n                }\n            }\n            h >>= 1;\n        }\n    }\n}\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":3312}
    {"lang_cluster":"C#","source_code":"\n\nBitmap tImage = new Bitmap(\"spectrum.bmp\");\n\nfor (int x = 0; x < tImage.Width; x++)\n{\n\tfor (int y = 0; y < tImage.Height; y++)\n\t{\n\t\tColor tCol = tImage.GetPixel(x, y);\n\n\t\t\/\/ L = 0.2126\u00b7R + 0.7152\u00b7G + 0.0722\u00b7B \n\t\tdouble L = 0.2126 * tCol.R + 0.7152 * tCol.G + 0.0722 * tCol.B;\n\t\ttImage.SetPixel(x, y, Color.FromArgb(Convert.ToInt32(L), Convert.ToInt32(L), Convert.ToInt32(L)));\n\t}\n}\n\n\/\/ Save\ntImage.Save(\"spectrum2.bmp\");\n\n","human_summarization":"extend the data storage type to support grayscale images, convert a color image to a grayscale image and vice versa using the CIE recommended formula for luminance. It also ensures rounding errors in floating-point arithmetic do not cause run-time problems or distorted results.","id":3313}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BasicAnimation\n{\n  class BasicAnimationForm : Form\n  {\n    bool isReverseDirection;\n    Label textLabel;\n    Timer timer;\n\n    internal BasicAnimationForm()\n    {\n      this.Size = new Size(150, 75);\n      this.Text = \"Basic Animation\";\n\n      textLabel = new Label();\n      textLabel.Text = \"Hello World! \";\n      textLabel.Location = new Point(3,3);\n      textLabel.AutoSize = true;\n      textLabel.Click += new EventHandler(textLabel_OnClick);\n      this.Controls.Add(textLabel);\n\n      timer = new Timer();\n      timer.Interval = 500;\n      timer.Tick += new EventHandler(timer_OnTick);\n      timer.Enabled = true;\n\n      isReverseDirection = false;\n    }\n\n    private void timer_OnTick(object sender, EventArgs e)\n    {\n      string oldText = textLabel.Text, newText;\n      if(isReverseDirection)\n        newText = oldText.Substring(1, oldText.Length - 1) + oldText.Substring(0, 1);\n      else\n        newText = oldText.Substring(oldText.Length - 1, 1) + oldText.Substring(0, oldText.Length - 1);\n      textLabel.Text = newText;\n    }\n\n    private void textLabel_OnClick(object sender, EventArgs e)\n    {\n      isReverseDirection = !isReverseDirection;\n    }\n  }\n\n   class Program\n   {\n      static void Main()\n      {\n\tApplication.Run(new BasicAnimationForm());\n      }\n   }\n}\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":3314}
    {"lang_cluster":"C#","source_code":"\nint a = 0;\n\ndo\n{\n    a += 1;\n    Console.WriteLine(a);\n} while (a % 6 != 0);\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":3315}
    {"lang_cluster":"C#","source_code":"\n\nWorks with: C # version 1.0+\nstring s = \"Hello, world!\";\nint characterLength = s.Length;\n\n\nusing System.Text;\n\nstring s = \"Hello, world!\";\nint byteLength = Encoding.Unicode.GetByteCount(s);\n\n\nint utf8ByteLength = Encoding.UTF8.GetByteCount(s);\n\n","human_summarization":"determine the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. It also handles non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. It also provides the string length in graphemes if the language supports it. The codes also handle string length calculation for .NET platform considering its Unicode storage.","id":3316}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Security.Cryptography;\n\nprivate static int GetRandomInt()\n{\n  int result = 0;\n  var rng = new RNGCryptoServiceProvider();\n  var buffer = new byte[4];\n\n  rng.GetBytes(buffer);\n  result = BitConverter.ToInt32(buffer, 0);\n\n  return result;\n}\n\n\nconst long m = 2147483647L;\nconst long a = 48271L;\nconst long q = 44488L;\nconst long r = 3399L;\nstatic long r_seed = 12345678L;\n\npublic static byte gen()\n{\n   long hi = r_seed \/ q;\n   long lo = r_seed - q * hi;\n   long t = a * lo - r * hi;\n       if (t > 0)\n           r_seed = t;\n       else\n           r_seed = t + m;\n       return (byte)r_seed;\n}\n\npublic static void ParkMiller(byte[] arr)\n{\n   byte[] arr = new byte[10900000];\n    for (int i = 0; i < arr.Length; i++)\n                {                       \n                       arr[i] = gen();\n                }\n}\n\n","human_summarization":"demonstrate how to generate a 32-bit random number using a system's built-in mechanism, not just a software algorithm like \/dev\/urandom devices in Unix.","id":3317}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        string testString = \"test\";\n        Console.WriteLine(testString.Substring(1));\n        Console.WriteLine(testString.Substring(0, testString.Length - 1));\n        Console.WriteLine(testString.Substring(1, testString.Length - 2));\n    }\n}\n\nest\ntes\nes\n","human_summarization":"demonstrate the removal of the first and last characters from a string, including handling of any valid Unicode code point in UTF-8 or UTF-16 encoding. The program operates on logical characters, not 8-bit or 16-bit code units.","id":3318}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Net;\nusing System.Net.Sockets;\n\nclass Program {        \n    static void Main(string[] args) {        \n        try {\n            TcpListener server = new TcpListener(IPAddress.Any, 12345);\n            server.Start();\n        } \n       \n        catch (SocketException e) {\n            if (e.SocketErrorCode == SocketError.AddressAlreadyInUse) {\n                Console.Error.WriteLine(\"Already running.\");\n            }\n        }\n    }\n}\n\n\/\/ Use this class in your process to guard against multiple instances\n\/\/\n\/\/ This is valid for C# running on Windows, but not for C# with Linux.\n\/\/\nusing System;\nusing System.Threading;\n\n\/\/\/ <summary>\n\/\/\/ RunOnce should be instantiated in the calling processes main clause\n\/\/\/ (preferably using a \"using\" clause) and then calling process\n\/\/\/ should then check AlreadyRunning and do whatever is appropriate\n\/\/\/ <\/summary>\npublic class RunOnce : IDisposable\n{\n\tpublic RunOnce( string name )\n\t{\n\t\tm_name = name;\n\t\tAlreadyRunning = false;\n\n\t\tbool created_new = false;\n\n\t\tm_mutex = new Mutex( false, m_name, out created_new );\n\n\t\tAlreadyRunning = !created_new;\n\t}\n\n\t~RunOnce()\n\t{\n\t\tDisposeImpl( false );\n\t}\n\n\tpublic bool AlreadyRunning\n\t{\n\t\tget { return m_already_running; }\n\t\tprivate set { m_already_running = value; }\n\t}\n\n\tprivate void DisposeImpl( bool is_disposing )\n\t{\n\t\tGC.SuppressFinalize( this );\n\n\t\tif( is_disposing )\n\t\t{\n\t\t\tm_mutex.Close();\n\t\t}\n\t}\n\n\t#region IDisposable Members\n\n\tpublic void Dispose()\n\t{\n\t\tDisposeImpl( true );\n\t}\n\n\t#endregion\n\n\tprivate string m_name;\n\tprivate bool m_already_running;\n\tprivate Mutex m_mutex;\n}\n\nclass Program\n{\n    \/\/ Example code to use this\n    static void Main( string[] args )\n    {\n        using ( RunOnce ro = new RunOnce( \"App Name\" ) )\n        {\n            if ( ro.AlreadyRunning )\n            {\n                Console.WriteLine( \"Already running\" );\n                return;\n            }\n\n            \/\/ Program logic\n        }\n    }\n}\n\n","human_summarization":"\"Check if an application instance is already running, display a message if so, and terminate the program.\"","id":3319}
    {"lang_cluster":"C#","source_code":"\nWorks with: .NET Framework version 4.7.2 (simple enough that it should probably work on every Framework version--.NET Core 3.0 will support Windows Forms on Windows only)\n\nLibrary: GDI+ (managed interface) [System.Drawing]\nLibrary: Windows Forms [System.Windows.Forms]\n\nusing System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nstatic class Program\n{\n    static void Main()\n    {\n        Rectangle bounds = Screen.PrimaryScreen.Bounds;\n        Console.WriteLine($\"Primary screen bounds:  {bounds.Width}x{bounds.Height}\");\n\n        Rectangle workingArea = Screen.PrimaryScreen.WorkingArea;\n        Console.WriteLine($\"Primary screen working area:  {workingArea.Width}x{workingArea.Height}\");\n    }\n}\n\n\n","human_summarization":"The code calculates the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations and menubars. It also accounts for multiple monitors and tiling window managers, determining the maximum size a window can be created without scrolling. The code uses Roslyn C# and references the screen's dimensions and working area, or alternatively, the dimensions of a borderless form maximized to fit the screen.","id":3320}
    {"lang_cluster":"C#","source_code":"using System;\n\nclass SudokuSolver\n{\n    private int[] grid;\n\n    public SudokuSolver(String s)\n    {\n        grid = new int[81];\n        for (int i = 0; i < s.Length; i++)\n        {\n            grid[i] = int.Parse(s[i].ToString());\n        }\n    }\n\n    public void solve()\n    {\n        try\n        {\n            placeNumber(0);\n            Console.WriteLine(\"Unsolvable!\");\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex.Message);\n            Console.WriteLine(this);\n        }\n    }\n\n    public void placeNumber(int pos)\n    {\n        if (pos == 81)\n        {\n            throw new Exception(\"Finished!\");\n        }\n        if (grid[pos] > 0)\n        {\n            placeNumber(pos + 1);\n            return;\n        }\n        for (int n = 1; n <= 9; n++)\n        {\n            if (checkValidity(n, pos % 9, pos \/ 9))\n            {\n                grid[pos] = n;\n                placeNumber(pos + 1);\n                grid[pos] = 0;\n            }\n        }\n    }\n\n    public bool checkValidity(int val, int x, int y)\n    {\n        for (int i = 0; i < 9; i++)\n        {\n            if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)\n                return false;\n        }\n        int startX = (x \/ 3) * 3;\n        int startY = (y \/ 3) * 3;\n        for (int i = startY; i < startY + 3; i++)\n        {\n            for (int j = startX; j < startX + 3; j++)\n            {\n                if (grid[i * 9 + j] == val)\n                    return false;\n            }\n        }\n        return true;\n    }\n\n    public override string ToString()\n    {\n        string sb = \"\";\n        for (int i = 0; i < 9; i++)\n        {\n            for (int j = 0; j < 9; j++)\n            {\n                sb += (grid[i * 9 + j] + \" \");\n                if (j == 2 || j == 5)\n                    sb += (\"| \");\n            }\n            sb += ('\\n');\n            if (i == 2 || i == 5)\n                sb += (\"------+-------+------\\n\");\n        }\n        return sb;\n    }\n\n    public static void Main(String[] args)\n    {\n        new SudokuSolver(\"850002400\" +\n                         \"720000009\" +\n                         \"004000000\" +\n                         \"000107002\" +\n                         \"305000900\" +\n                         \"040000000\" +\n                         \"000080070\" +\n                         \"017000000\" +\n                         \"000036040\").solve();\n        Console.Read();\n    }\n}\n\nusing System.Linq;\nusing static System.Linq.Enumerable;\nusing System.Collections.Generic;\nusing System;\nusing System.Runtime.CompilerServices;\n\nnamespace SodukoFastMemoBFS {\n    internal readonly record struct Square (int Row, int Col);\n    internal record Constraints (IEnumerable<int> ConstrainedRange, Square Square);\n    internal class Cache : Dictionary<Square, Constraints> { };\n    internal record CacheGrid (int[][] Grid, Cache Cache);\n\n    internal static class SudokuFastMemoBFS {\n        internal static U Fwd<T, U>(this T data, Func<T, U> f) => f(data);\n\n        [MethodImpl(MethodImplOptions.AggressiveInlining)]\n        private static int RowCol(int rc) => rc <= 2 ? 0 : rc <= 5 ? 3 : 6;\n\n        private static bool Solve(this CacheGrid cg, Constraints constraints, int finished) {            \n            var (row, col) = constraints.Square;\n            foreach (var i in constraints.ConstrainedRange) {\n                cg.Grid[row][col] = i;\n                if (cg.Cache.Count == finished || cg.Solve(cg.Next(constraints.Square), finished))\n                    return true;                    \n            }\n            cg.Grid[row][col] = 0;\n            return false;\n        }\n\n        private static readonly int[] domain = Range(0, 9).ToArray();\n        private static readonly int[] range = Range(1, 9).ToArray();\n\n        private static bool Valid(this int[][] grid, int row, int col, int val) {\n            for (var i = 0; i < 9; i++)\n                if (grid[row][i] == val || grid[i][col] == val)\n                    return false;\n            for (var r = RowCol(row); r < RowCol(row) + 3; r++)\n                for (var c = RowCol(col); c < RowCol(col) + 3; c++)\n                    if (grid[r][c] == val)\n                        return false;\n            return true;\n        }\n\n        private static IEnumerable<int> Constraints(this int[][] grid, int row, int col) =>\n            range.Where(val => grid.Valid(row, col, val));\n\n        private static Constraints Next(this CacheGrid cg, Square square) => \n            cg.Cache.ContainsKey(square)\n            ? cg.Cache[square]\n            : cg.Cache[square]=cg.Grid.SortedCells();\n\n        private static Constraints SortedCells(this int[][] grid) =>\n            (from row in domain\n            from col in domain\n            where grid[row][col] == 0\n            let cell = new Constraints(grid.Constraints(row, col), new Square(row, col))\n            orderby cell.ConstrainedRange.Count() ascending\n            select cell).First();\n\n        private static CacheGrid Parse(string input) =>\n            input\n            .Select((c, i) => (index: i, val: int.Parse(c.ToString())))\n            .GroupBy(id => id.index \/ 9)\n            .Select(grp => grp.Select(id => id.val).ToArray())\n            .ToArray()\n            .Fwd(grid => new CacheGrid(grid, new Cache()));\n            \n        public static string AsString(this int[][] grid) =>\n            string.Join('\\n', grid.Select(row => string.Concat(row)));\n\n        public static int[][] Run(string input) {\n            var cg = Parse(input);\n            var marked = cg.Grid.SelectMany(row => row.Where(c => c > 0)).Count();\n            return cg.Solve(cg.Grid.SortedCells(), 80 - marked) ? cg.Grid : new int[][] { Array.Empty<int>() };\n        }\n    }\n}\n\n\nusing System.Linq;\nusing static System.Linq.Enumerable;\nusing static System.Console;\nusing System.IO;\n\nnamespace SodukoFastMemoBFS {\n    static class Program {\n\n        static void Main(string[] args) {            \n            var num = int.Parse(args[0]);\n            var puzzles = File.ReadLines(@\"sudoku17.txt\").Take(num);\n            var single = puzzles.First();\n\n            var watch = new System.Diagnostics.Stopwatch();\n            watch.Start();\n            WriteLine(SudokuFastMemoBFS.Run(single).AsString());\n            watch.Stop();\n            WriteLine($\"{single}: {watch.ElapsedMilliseconds} ms\");\n\n            WriteLine($\"Doing {num} puzzles\");\n            var total = 0.0;\n            watch.Start();\n            foreach (var puzzle in puzzles) {\n                watch.Reset();\n                watch.Start();\n                SudokuFastMemoBFS.Run(puzzle);\n                watch.Stop();\n                total += watch.ElapsedMilliseconds;\n                Write(\".\");\n            }\n            watch.Stop();\n            WriteLine($\"\\nPuzzles:{num}, Total:{total} ms, Average:{total \/ num:0.00} ms\");\n            ReadKey();\n        }\n    }\n}\n\n\n693784512\n487512936\n125963874\n932651487\n568247391\n741398625\n319475268\n856129743\n274836159\n000000010400000000020000000000050407008000300001090000300400200050100000000806000: 336 ms\nDoing 100 puzzles\n....................................................................................................\nPuzzles:100, Total:5316 ms, Average:53.16 ms\nLibrary: Microsoft Solver Foundation\nusing Microsoft.SolverFoundation.Solvers;\n\nnamespace Sudoku\n{\n    class Program\n    {\n        private static int[,] B = new int[,] {{9,7,0, 3,0,0, 0,6,0},\n                                              {0,6,0, 7,5,0, 0,0,0},\n                                              {0,0,0, 0,0,8, 0,5,0},\n\n                                              {0,0,0, 0,0,0, 6,7,0},\n                                              {0,0,0, 0,3,0, 0,0,0},\n                                              {0,5,3, 9,0,0, 2,0,0},\n\n                                              {7,0,0, 0,2,5, 0,0,0},\n                                              {0,0,2, 0,1,0, 0,0,8},\n                                              {0,4,0, 0,0,7, 3,0,0}};\n\n        private static CspTerm[] GetSlice(CspTerm[][] sudoku, int Ra, int Rb, int Ca, int Cb)\n        {\n            CspTerm[] slice = new CspTerm[9];\n            int i = 0;\n            for (int row = Ra; row < Rb + 1; row++)\n                for (int col = Ca; col < Cb + 1; col++)\n                {\n                    {\n                        slice[i++] = sudoku[row][col];\n                    }\n                }\n            return slice;\n        }\n\n        static void Main(string[] args)\n        {\n            ConstraintSystem S = ConstraintSystem.CreateSolver();\n            CspDomain Z = S.CreateIntegerInterval(1, 9);\n            CspTerm[][] sudoku = S.CreateVariableArray(Z, \"cell\", 9, 9);\n            for (int row = 0; row < 9; row++)\n            {\n                for (int col = 0; col < 9; col++)\n                {\n                    if (B[row, col] > 0)\n                    {\n                        S.AddConstraints(S.Equal(B[row, col], sudoku[row][col]));\n                    }\n                }\n                S.AddConstraints(S.Unequal(GetSlice(sudoku, row, row, 0, 8)));\n            }\n            for (int col = 0; col < 9; col++)\n            {\n                S.AddConstraints(S.Unequal(GetSlice(sudoku, 0, 8, col, col)));\n            }\n            for (int a = 0; a < 3; a++)\n            {\n                for (int b = 0; b < 3; b++)\n                {\n                    S.AddConstraints(S.Unequal(GetSlice(sudoku, a * 3, a * 3 + 2, b * 3, b * 3 + 2)));\n                }\n            }\n            ConstraintSolverSolution soln = S.Solve();\n            object[] h = new object[9];\n            for (int row = 0; row < 9; row++)\n            {\n                if ((row % 3) == 0) System.Console.WriteLine();\n                for (int col = 0; col < 9; col++)\n                {\n                    soln.TryGetValue(sudoku[row][col], out h [col]);\n                }\n                System.Console.WriteLine(\"{0}{1}{2} {3}{4}{5} {6}{7}{8}\", h[0],h[1],h[2],h[3],h[4],h[5],h[6],h[7],h[8]);\n            }\n        }\n    }\n}\n\n\n975 342 861\n861 759 432\n324 168 957\n\n219 584 673\n487 236 519\n653 971 284\n\n738 425 196\n592 613 748\n146 897 325\n\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\nusing static System.Linq.Enumerable;\n\npublic class Sudoku\n{\n    public static void Main2() {\n        string puzzle = \"....7.94.....9...53....5.7...74..1..463...........7.8.8........7......28.5.26....\";\n        string solution = new Sudoku().Solutions(puzzle).FirstOrDefault() ?? puzzle;\n        Print(puzzle, solution);\n    }\n\n    private DLX dlx;\n\n    public void Build() {\n        const int rows = 9 * 9 * 9, columns = 4 * 9 * 9;\n        dlx = new DLX(rows, columns);\n        for (int i = 0; i < columns; i++) dlx.AddHeader();\n\n        for (int cell = 0, row = 0; row < 9; row++) {\n            for (int column = 0; column < 9; column++) {\n                int box = row \/ 3 * 3 + column \/ 3;\n                for (int digit = 0; digit < 9; digit++) {\n                    dlx.AddRow(cell, 81 + row * 9 + digit, 2 * 81 + column * 9 + digit, 3 * 81 + box * 9 + digit);\n                }\n                cell++;\n            }\n        }\n    }\n\n    public IEnumerable<string> Solutions(string puzzle) {\n        if (puzzle == null) throw new ArgumentNullException(nameof(puzzle));\n        if (puzzle.Length != 81) throw new ArgumentException(\"The input is not of the correct length.\");\n        if (dlx == null) Build();\n\n        for (int i = 0; i < puzzle.Length; i++) {\n            if (puzzle[i] == '0' || puzzle[i] == '.') continue;\n            if (puzzle[i] < '1' && puzzle[i] > '9') throw new ArgumentException($\"Input contains an invalid character: ({puzzle[i]})\");\n            int digit = puzzle[i] - '0' - 1;\n            dlx.Give(i * 9 + digit);\n        }\n        return Iterator();\n\n        IEnumerable<string> Iterator() {\n            var sb = new StringBuilder(new string('.', 81));\n            foreach (int[] rows in dlx.Solutions()) {\n                foreach (int r in rows) {\n                    sb[r \/ 81 * 9 + r \/ 9 % 9] = (char)(r % 9 + '1');\n                }\n                yield return sb.ToString();\n            }\n        }\n    }\n\n    static void Print(string left, string right) {\n        foreach (string line in GetPrintLines(left).Zip(GetPrintLines(right), (l, r) => l + \"\\t\" + r)) {\n            Console.WriteLine(line);\n        }\n\n        IEnumerable<string> GetPrintLines(string s) {\n            int r = 0;\n            foreach (string row in s.Cut(9)) {\n                yield return r == 0\n                    ? \"\u2554\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2564\u2550\u2550\u2550\u2557\"\n                    : r % 3 == 0\n                    ? \"\u2560\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u256a\u2550\u2550\u2550\u2563\"\n                    : \"\u255f\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u256b\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u253c\u2500\u2500\u2500\u2562\";\n                yield return \"\u2551 \" + row.Cut(3).Select(segment => segment.DelimitWith(\" \u2502 \")).DelimitWith(\" \u2551 \") + \" \u2551\";\n                r++;\n            }\n            yield return \"\u255a\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u2567\u2550\u2550\u2550\u255d\";\n        }\n    }\n\n}\n\npublic class DLX \/\/Some functionality elided\n{\n    private readonly Header root = new Header(null, null) { Size = int.MaxValue };\n    private readonly List<Header> columns;\n    private readonly List<Node> rows;\n    private readonly Stack<Node> solutionNodes = new Stack<Node>();\n    private int initial = 0;\n\n    public DLX(int rowCapacity, int columnCapacity) {\n        columns = new List<Header>(columnCapacity);\n        rows = new List<Node>(rowCapacity);\n    }\n\n    public void AddHeader() {\n        Header h = new Header(root.Left, root);\n        h.AttachLeftRight();\n        columns.Add(h);\n    }\n\n    public void AddRow(params int[] newRow) {\n        Node first = null;\n        if (newRow != null) {\n            for (int i = 0; i < newRow.Length; i++) {\n                if (newRow[i] < 0) continue;\n                if (first == null) first = AddNode(rows.Count, newRow[i]);\n                else AddNode(first, newRow[i]);\n            }\n        }\n        rows.Add(first);\n    }\n\n    private Node AddNode(int row, int column) {\n        Node n = new Node(null, null, columns[column].Up, columns[column], columns[column], row);\n        n.AttachUpDown();\n        n.Head.Size++;\n        return n;\n    }\n\n    private void AddNode(Node firstNode, int column) {\n        Node n = new Node(firstNode.Left, firstNode, columns[column].Up, columns[column], columns[column], firstNode.Row);\n        n.AttachLeftRight();\n        n.AttachUpDown();\n        n.Head.Size++;\n    }\n\n    public void Give(int row) {\n        solutionNodes.Push(rows[row]);\n        CoverMatrix(rows[row]);\n        initial++;\n    }\n\n    public IEnumerable<int[]> Solutions() {\n        try {\n            Node node = ChooseSmallestColumn().Down;\n            do {\n                if (node == node.Head) {\n                    if (node == root) {\n                        yield return solutionNodes.Select(n => n.Row).ToArray();\n                    }\n                    if (solutionNodes.Count > initial) {\n                        node = solutionNodes.Pop();\n                        UncoverMatrix(node);\n                        node = node.Down;\n                    }\n                } else {\n                    solutionNodes.Push(node);\n                    CoverMatrix(node);\n                    node = ChooseSmallestColumn().Down;\n                }\n            } while(solutionNodes.Count > initial || node != node.Head);\n        } finally {\n            Restore();\n        }\n    }\n\n    private void Restore() {\n        while (solutionNodes.Count > 0) UncoverMatrix(solutionNodes.Pop());\n        initial = 0;\n    }\n\n    private Header ChooseSmallestColumn() {\n        Header traveller = root, choice = root;\n        do {\n            traveller = (Header)traveller.Right;\n            if (traveller.Size < choice.Size) choice = traveller;\n        } while (traveller != root && choice.Size > 0);\n        return choice;\n    }\n\n    private void CoverRow(Node row) {\n        Node traveller = row.Right;\n        while (traveller != row) {\n            traveller.DetachUpDown();\n            traveller.Head.Size--;\n            traveller = traveller.Right;\n        }\n    }\n\n    private void UncoverRow(Node row) {\n        Node traveller = row.Left;\n        while (traveller != row) {\n            traveller.AttachUpDown();\n            traveller.Head.Size++;\n            traveller = traveller.Left;\n        }\n    }\n\n    private void CoverColumn(Header column) {\n        column.DetachLeftRight();\n        Node traveller = column.Down;\n        while (traveller != column) {\n            CoverRow(traveller);\n            traveller = traveller.Down;\n        }\n    }\n\n    private void UncoverColumn(Header column) {\n        Node traveller = column.Up;\n        while (traveller != column) {\n            UncoverRow(traveller);\n            traveller = traveller.Up;\n        }\n        column.AttachLeftRight();\n    }\n\n    private void CoverMatrix(Node node) {\n        Node traveller = node;\n        do {\n            CoverColumn(traveller.Head);\n            traveller = traveller.Right;\n        } while (traveller != node);\n    }\n\n    private void UncoverMatrix(Node node) {\n        Node traveller = node;\n        do {\n            traveller = traveller.Left;\n            UncoverColumn(traveller.Head);\n        } while (traveller != node);\n    }\n\n    private class Node\n    {\n        public Node(Node left, Node right, Node up, Node down, Header head, int row) {\n            Left = left ?? this;\n            Right = right ?? this;\n            Up = up ?? this;\n            Down = down ?? this;\n            Head = head ?? this as Header;\n            Row = row;\n        }\n\n        public Node Left   { get; set; }\n        public Node Right  { get; set; }\n        public Node Up     { get; set; }\n        public Node Down   { get; set; }\n        public Header Head { get; }\n        public int Row     { get; }\n\n        public void AttachLeftRight() {\n            this.Left.Right = this;\n            this.Right.Left = this;\n        }\n\n        public void AttachUpDown() {\n            this.Up.Down = this;\n            this.Down.Up = this;\n        }\n\n        public void DetachLeftRight() {\n            this.Left.Right = this.Right;\n            this.Right.Left = this.Left;\n        }\n\n        public void DetachUpDown() {\n            this.Up.Down = this.Down;\n            this.Down.Up = this.Up;\n        }\n\n    }\n\n    private class Header : Node\n    {\n        public Header(Node left, Node right) : base(left, right, null, null, null, -1) { }\n        \n        public int Size { get; set; }\n    }\n\n}\n\nstatic class Extensions\n{\n    public static IEnumerable<string> Cut(this string input, int length)\n    {\n        for (int cursor = 0; cursor < input.Length; cursor += length) {\n            if (cursor + length > input.Length) yield return input.Substring(cursor);\n            else yield return input.Substring(cursor, length);\n        }\n    }\n\n    public static string DelimitWith<T>(this IEnumerable<T> source, string separator) => string.Join(separator, source);\n}\n\n\n","human_summarization":"\"Solves a partially filled 9x9 Sudoku grid and displays the result in a human-readable format.\"","id":3321}
    {"lang_cluster":"C#","source_code":"\npublic static void KnuthShuffle<T>(T[] array)\n{\n    System.Random random = new System.Random();\n    for (int i = 0; i < array.Length; i++)\n    {\n        int j = random.Next(i, array.Length); \/\/ Don't select from the entire array on subsequent loops\n        T temp = array[i]; array[i] = array[j]; array[j] = temp;\n    }\n}\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":3322}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\n\nnamespace RosettaCode.LastFridaysOfYear\n{\n    internal static class Program\n    {\n        private static IEnumerable<DateTime> LastFridaysOfYear(int year)\n        {\n            for (var month = 1; month <= 12; month++)\n            {\n                var date = new DateTime(year, month, 1).AddMonths(1).AddDays(-1);\n                while (date.DayOfWeek != DayOfWeek.Friday)\n                {\n                    date = date.AddDays(-1);\n                }\n                yield return date;\n            }\n        }\n\n        private static void Main(string[] arguments)\n        {\n            int year;\n            var argument = arguments.FirstOrDefault();\n            if (string.IsNullOrEmpty(argument) || !int.TryParse(argument, out year))\n            {\n                year = DateTime.Today.Year;\n            }\n\n            foreach (var date in LastFridaysOfYear(year))\n            {\n                Console.WriteLine(date.ToString(\"d\", CultureInfo.InvariantCulture));\n            }\n        }\n    }\n}\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":3323}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        \/\/Using Console.WriteLine() will append a newline\n        Console.WriteLine(\"Goodbye, World!\");\n\n        \/\/Using Console.Write() will not append a newline\n        Console.Write(\"Goodbye, World!\");\n    }\n}\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":3324}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Linq;\n\nnamespace CaesarCypher\n{\n    class Program\n    {\n        static char Encrypt(char ch, int code)\n        {\n            if (!char.IsLetter(ch)) return ch;\n\n            char offset = char.IsUpper(ch) ? 'A' : 'a';\n            return (char)((ch + code - offset) % 26 + offset);\n        }\n\n        static string Encrypt(string input, int code)\n        {\n            return new string(input.Select(ch => Encrypt(ch, code)).ToArray());\n        }\n\n        static string Decrypt(string input, int code)\n        {\n            return Encrypt(input, 26 - code);\n        }\n\n        const string TestCase = \"Pack my box with five dozen liquor jugs.\";\n\n        static void Main()\n        {\n            string str = TestCase;\n\n            Console.WriteLine(str);\n            str = Encrypt(str, 5);\n            Console.WriteLine(\"Encrypted: \" + str);\n            str = Decrypt(str, 5);\n            Console.WriteLine(\"Decrypted: \" + str);\n            Console.ReadKey();\n        }\n    }\n}\n\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":3325}
    {"lang_cluster":"C#","source_code":"\nUsing System;\nclass Program\n{\n    static int gcd(int m, int n)\n    {\n        return n == 0 ? Math.Abs(m) : gcd(n, n % m);\n    }\n    static int lcm(int m, int n)\n    {\n        return Math.Abs(m * n) \/ gcd(m, n);\n    }\n    static void Main()\n    {\n        Console.WriteLine(\"lcm(12,18)=\" + lcm(12,18));\n    }\n}\n\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":3326}
    {"lang_cluster":"C#","source_code":"using System;\nusing System.Collections.Generic;\n\nnamespace CUSIP {\n    class Program {\n        static bool IsCusip(string s) {\n            if (s.Length != 9) return false;\n            int sum = 0;\n            for (int i = 0; i <= 7; i++) {\n                char c = s[i];\n\n                int v;\n                if (c >= '0' && c <= '9') {\n                    v = c - 48;\n                }\n                else if (c >= 'A' && c <= 'Z') {\n                    v = c - 55;  \/\/ lower case letters apparently invalid\n                }\n                else if (c == '*') {\n                    v = 36;\n                }\n                else if (c == '#') {\n                    v = 38;\n                }\n                else {\n                    return false;\n                }\n                if (i % 2 == 1) v *= 2;  \/\/ check if odd as using 0-based indexing\n                sum += v \/ 10 + v % 10;\n            }\n            return s[8] - 48 == (10 - (sum % 10)) % 10;\n        }\n\n        static void Main(string[] args) {\n            List<string> candidates = new List<string>() {\n                \"037833100\",\n                \"17275R102\",\n                \"38259P508\",\n                \"594918104\",\n                \"68389X106\",\n                \"68389X105\"\n            };\n            foreach (var candidate in candidates) {\n                Console.WriteLine(\"{0} -> {1}\", candidate, IsCusip(candidate) ? \"correct\" : \"incorrect\");\n            }\n        }\n    }\n}\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":3327}
    {"lang_cluster":"C#","source_code":"\nstatic void Main()\n{\n  Console.WriteLine(\"Word size = {0} bytes,\",sizeof(int));\n\n  if (BitConverter.IsLittleEndian)\n    Console.WriteLine(\"Little-endian.\");\n  else\n    Console.WriteLine(\"Big-endian.\");\n}\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":3328}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        string get1 = new WebClient().DownloadString(\"http:\/\/www.rosettacode.org\/w\/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json\");\n        string get2 = new WebClient().DownloadString(\"http:\/\/www.rosettacode.org\/w\/index.php?title=Special:Categories&limit=5000\");\n\n        ArrayList langs = new ArrayList();\n        Dictionary<string, int> qtdmbr = new Dictionary<string, int>();\n\n        MatchCollection match1 = new Regex(\"\\\"title\\\":\\\"Category:(.+?)\\\"\").Matches(get1);\n        MatchCollection match2 = new Regex(\"title=\\\"Category:(.+?)\\\">.+?<\/a>[^(]*\\\\((\\\\d+) members\\\\)\").Matches(get2);\n\n        foreach (Match lang in match1) langs.Add(lang.Groups[1].Value);\n\n        foreach (Match match in match2)\n        {\n            if (langs.Contains(match.Groups[1].Value))\n            {\n                qtdmbr.Add(match.Groups[1].Value, Int32.Parse(match.Groups[2].Value));\n            }\n        }\n\n        string[] test = qtdmbr.OrderByDescending(x => x.Value).Select(x => String.Format(\"{0,3} - {1}\", x.Value, x.Key)).ToArray();\n\n        int count = 1;\n\n        foreach (string i in test)\n        {\n            Console.WriteLine(\"{0,3}. {1}\", count, i);\n            count++;\n        }\n    }\n}\n\n\nOutput (as of May 30, 2010):\n 1. 397 - Tcl\n 2. 368 - Python\n 3. 350 - Ruby\n 4. 333 - J\n 5. 332 - C\n 6. 322 - Haskell\n 7. 322 - OCaml\n 8. 302 - Perl\n 9. 290 - Common Lisp\n10. 289 - AutoHotkey\n    . . .\n\nusing System;\nusing System.Net;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Collections.Generic;\n\nclass Category {\n    private string _title;\n    private int _members;\n\n    public Category(string title, int members) {\n        _title = title;\n        _members = members;\n    }\n\n    public string Title {\n        get {\n            return _title;\n        }\n    }\n\n    public int Members {\n        get {\n            return _members;\n        }\n    }\n}\n\nclass Program {\n    static void Main(string[] args) {\n        string get1 = new WebClient().DownloadString(\"http:\/\/www.rosettacode.org\/w\/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=500&format=json\");\n        string get2 = new WebClient().DownloadString(\"http:\/\/www.rosettacode.org\/w\/index.php?title=Special:Categories&limit=5000\");\n\n        MatchCollection match1 = new Regex(\"\\\"title\\\":\\\"Category:(.+?)\\\"\").Matches(get1);\n        MatchCollection match2 = new Regex(\"title=\\\"Category:(.+?)\\\">.+?<\/a>[^(]*\\\\((\\\\d+) members\\\\)\").Matches(get2);\n\n        string[] valids = match1.Cast<Match>().Select(x => x.Groups[1].Value).ToArray();\n        List<Category> langs = new List<Category>();\n\n        foreach (Match match in match2) {\n            string category = match.Groups[1].Value;\n            int members = Int32.Parse(match.Groups[2].Value);\n\n            if (valids.Contains(category)) langs.Add(new Category(category, members));\n        }\n\n        langs = langs.OrderByDescending(x => x.Members).ToList();\n        int count = 1;\n\n        foreach (Category i in langs) {\n            Console.WriteLine(\"{0,3}. {1,3} - {2}\", count, i.Members, i.Title);\n            count++;\n        }\n    }\n}\n\n","human_summarization":"sort and rank the most popular computer programming languages based on the number of members in their respective Rosetta Code categories. The ranking can be achieved by either web scraping or using the API method. The code also has the option to filter incorrect results, and if using the API, it can cross-check the results against a complete list of all programming languages. The final output is a complete ranked list of all programming languages.","id":3329}
    {"lang_cluster":"C#","source_code":"\nstring[] things = {\"Apple\", \"Banana\", \"Coconut\"};\n\nforeach (string thing in things)\n{\n    Console.WriteLine(thing);\n}\n\n","human_summarization":"Iterates through each element in a collection in order and prints it, using a \"for each\" loop or another loop if \"for each\" is not available in the language.","id":3330}
    {"lang_cluster":"C#","source_code":"\nstring str = \"Hello,How,Are,You,Today\"; \n\/\/ or Regex.Split ( \"Hello,How,Are,You,Today\", \",\" );\n\/\/ (Regex is in System.Text.RegularExpressions namespace)\nstring[] strings = str.Split(',');\nConsole.WriteLine(String.Join(\".\", strings));\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":3331}
    {"lang_cluster":"C#","source_code":"\nstatic void Main()\n{\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 1, 1, gcd(1, 1));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 1, 10, gcd(1, 10));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 10, 100, gcd(10, 100));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 5, 50, gcd(5, 50));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 8, 24, gcd(8, 24));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 36, 17, gcd(36, 17));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 36, 18, gcd(36, 18));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 36, 19, gcd(36, 19));\n\tfor (int x = 1; x < 36; x++)\n\t{\n\t\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 36, x, gcd(36, x));\n\t}\n\tConsole.Read();\n}\n \n\/\/\/ <summary>\n\/\/\/ Greatest Common Denominator using Euclidian Algorithm\n\/\/\/ <\/summary>\nstatic int gcd(int a, int b)\n{\n    while (b != 0) b = a % (a = b);\n    return a;\n}\n\n\nGCD of 1 and 1 is 1\nGCD of 1 and 10 is 1\nGCD of 10 and 100 is 10\nGCD of 5 and 50 is 5\nGCD of 8 and 24 is 8\nGCD of 36 and 1 is 1\nGCD of 36 and 2 is 2\n..\nGCD of 36 and 16 is 4\nGCD of 36 and 17 is 1\nGCD of 36 and 18 is 18\n..\n..\nGCD of 36 and 33 is 3\nGCD of 36 and 34 is 2\nGCD of 36 and 35 is 1\n\nstatic void Main(string[] args)\n{\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 1, 1, gcd(1, 1));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 1, 10, gcd(1, 10));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 10, 100, gcd(10, 100));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 5, 50, gcd(5, 50));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 8, 24, gcd(8, 24));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 36, 17, gcd(36, 17));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 36, 18, gcd(36, 18));\n\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 36, 19, gcd(36, 19));\n\tfor (int x = 1; x < 36; x++)\n\t{\n\t\tConsole.WriteLine(\"GCD of {0} and {1} is {2}\", 36, x, gcd(36, x));\n\t}\n\tConsole.Read();\n}\n \n\/\/ Greatest Common Denominator using Euclidian Algorithm\n\/\/ Gist: https:\/\/gist.github.com\/SecretDeveloper\/6c426f8993873f1a05f7\nstatic int gcd(int a, int b)\n{\t\n\treturn b==0 ? a : gcd(b, a % b);\n}\n\n\nGCD of 1 and 1 is 1\nGCD of 1 and 10 is 1\nGCD of 10 and 100 is 10\nGCD of 5 and 50 is 5\nGCD of 8 and 24 is 8\nGCD of 36 and 1 is 1\nGCD of 36 and 2 is 2\n..\nGCD of 36 and 16 is 4\nGCD of 36 and 17 is 1\nGCD of 36 and 18 is 18\n..\n..\nGCD of 36 and 33 is 3\nGCD of 36 and 34 is 2\nGCD of 36 and 35 is 1\n\n","human_summarization":"find the greatest common divisor (GCD), also known as greatest common factor (gcf) or greatest common measure, of two integers.","id":3332}
    {"lang_cluster":"C#","source_code":"\nusing System.Net.Sockets;\nusing System.Threading;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static TcpListener listen;\n        static Thread serverthread;\n\n        static void Main(string[] args)\n        {\n            listen = new TcpListener(System.Net.IPAddress.Parse(\"127.0.0.1\"), 12321);\n            serverthread = new Thread(new ThreadStart(DoListen));\n            serverthread.Start();\n        }\n\n        private static void DoListen()\n        {\n            \/\/ Listen\n            listen.Start();\n            Console.WriteLine(\"Server: Started server\");\n\n            while (true)\n            {\n                Console.WriteLine(\"Server: Waiting...\");\n                TcpClient client = listen.AcceptTcpClient();\n                Console.WriteLine(\"Server: Waited\");\n\n                \/\/ New thread with client\n                Thread clientThread = new Thread(new ParameterizedThreadStart(DoClient));\n                clientThread.Start(client);\n            }\n        }\n\n        private static void DoClient(object client)\n        {\n            \/\/ Read data\n            TcpClient tClient = (TcpClient)client;\n\n            Console.WriteLine(\"Client (Thread: {0}): Connected!\", Thread.CurrentThread.ManagedThreadId);\n            do\n            {\n                if (!tClient.Connected)\n                { \n                    tClient.Close();\n                    Thread.CurrentThread.Abort();       \/\/ Kill thread.\n                }\n\n                if (tClient.Available > 0)\n                {\n                    \/\/ Resend\n                    byte pByte = (byte)tClient.GetStream().ReadByte();\n                    Console.WriteLine(\"Client (Thread: {0}): Data {1}\", Thread.CurrentThread.ManagedThreadId, pByte);\n                    tClient.GetStream().WriteByte(pByte);\n                }\n\n                \/\/ Pause\n                Thread.Sleep(100);\n            } while (true);\n        }\n    }\n}\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":3333}
    {"lang_cluster":"C#","source_code":"\n\npublic static bool IsNumeric(string s)\n{\n    double Result;\n    return double.TryParse(s, out Result);  \/\/ TryParse routines were added in Framework version 2.0.\n}        \n\nstring value = \"123\";\nif (IsNumeric(value)) \n{\n  \/\/ do something\n}\n\n\npublic static bool IsNumeric(string s)\n{\n  try\n  {\n    Double.Parse(s);\n    return true;\n  }\n  catch\n  {\n    return false;\n  }\n}\n\n","human_summarization":"The code implements a boolean function in .NET framework that checks if a given string can be interpreted as a numeric value, including floating point and negative numbers.","id":3334}
    {"lang_cluster":"C#","source_code":"\nWorks with: C sharp version 3.0\nusing System;\nusing System.Net;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var client = new WebClient();\n        var data = client.DownloadString(\"https:\/\/www.google.com\");\n\n        Console.WriteLine(data);\n    }\n}\n\n\n","human_summarization":"send a GET request to the URL \"https:\/\/www.w3.org\/\", print the obtained resource to the console, check the host certificate for validity, and do not perform authentication. It does not support URLs requiring a secure (SSL) connection.","id":3335}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows;\n\nnamespace Sutherland\n{\n    public static class SutherlandHodgman\n    {\n        #region Class: Edge\n\n        \/\/\/ <summary>\n        \/\/\/ This represents a line segment\n        \/\/\/ <\/summary>\n        private class Edge\n        {\n            public Edge(Point from, Point to)\n            {\n                this.From = from;\n                this.To = to;\n            }\n\n            public readonly Point From;\n            public readonly Point To;\n        }\n\n        #endregion\n\n        \/\/\/ <summary>\n        \/\/\/ This clips the subject polygon against the clip polygon (gets the intersection of the two polygons)\n        \/\/\/ <\/summary>\n        \/\/\/ <remarks>\n        \/\/\/ Based on the psuedocode from:\n        \/\/\/ http:\/\/en.wikipedia.org\/wiki\/Sutherland%E2%80%93Hodgman\n        \/\/\/ <\/remarks>\n        \/\/\/ <param name=\"subjectPoly\">Can be concave or convex<\/param>\n        \/\/\/ <param name=\"clipPoly\">Must be convex<\/param>\n        \/\/\/ <returns>The intersection of the two polygons (or null)<\/returns>\n        public static Point[] GetIntersectedPolygon(Point[] subjectPoly, Point[] clipPoly)\n        {\n            if (subjectPoly.Length < 3 || clipPoly.Length < 3)\n            {\n                throw new ArgumentException(string.Format(\"The polygons passed in must have at least 3 points: subject={0}, clip={1}\", subjectPoly.Length.ToString(), clipPoly.Length.ToString()));\n            }\n\n            List<Point> outputList = subjectPoly.ToList();\n\n            \/\/\tMake sure it's clockwise\n            if (!IsClockwise(subjectPoly))\n            {\n                outputList.Reverse();\n            }\n\n            \/\/\tWalk around the clip polygon clockwise\n            foreach (Edge clipEdge in IterateEdgesClockwise(clipPoly))\n            {\n                List<Point> inputList = outputList.ToList();\t\t\/\/\tclone it\n                outputList.Clear();\n\n                if (inputList.Count == 0)\n                {\n                    \/\/\tSometimes when the polygons don't intersect, this list goes to zero.  Jump out to avoid an index out of range exception\n                    break;\n                }\n\n                Point S = inputList[inputList.Count - 1];\n\n                foreach (Point E in inputList)\n                {\n                    if (IsInside(clipEdge, E))\n                    {\n                        if (!IsInside(clipEdge, S))\n                        {\n                            Point? point = GetIntersect(S, E, clipEdge.From, clipEdge.To);\n                            if (point == null)\n                            {\n                                throw new ApplicationException(\"Line segments don't intersect\");\t\t\/\/\tmay be colinear, or may be a bug\n                            }\n                            else\n                            {\n                                outputList.Add(point.Value);\n                            }\n                        }\n\n                        outputList.Add(E);\n                    }\n                    else if (IsInside(clipEdge, S))\n                    {\n                        Point? point = GetIntersect(S, E, clipEdge.From, clipEdge.To);\n                        if (point == null)\n                        {\n                            throw new ApplicationException(\"Line segments don't intersect\");\t\t\/\/\tmay be colinear, or may be a bug\n                        }\n                        else\n                        {\n                            outputList.Add(point.Value);\n                        }\n                    }\n\n                    S = E;\n                }\n            }\n\n            \/\/\tExit Function\n            return outputList.ToArray();\n        }\n\n        #region Private Methods\n\n        \/\/\/ <summary>\n        \/\/\/ This iterates through the edges of the polygon, always clockwise\n        \/\/\/ <\/summary>\n        private static IEnumerable<Edge> IterateEdgesClockwise(Point[] polygon)\n        {\n            if (IsClockwise(polygon))\n            {\n                #region Already clockwise\n\n                for (int cntr = 0; cntr < polygon.Length - 1; cntr++)\n                {\n                    yield return new Edge(polygon[cntr], polygon[cntr + 1]);\n                }\n\n                yield return new Edge(polygon[polygon.Length - 1], polygon[0]);\n\n                #endregion\n            }\n            else\n            {\n                #region Reverse\n\n                for (int cntr = polygon.Length - 1; cntr > 0; cntr--)\n                {\n                    yield return new Edge(polygon[cntr], polygon[cntr - 1]);\n                }\n\n                yield return new Edge(polygon[0], polygon[polygon.Length - 1]);\n\n                #endregion\n            }\n        }\n\n        \/\/\/ <summary>\n        \/\/\/ Returns the intersection of the two lines (line segments are passed in, but they are treated like infinite lines)\n        \/\/\/ <\/summary>\n        \/\/\/ <remarks>\n        \/\/\/ Got this here:\n        \/\/\/ http:\/\/stackoverflow.com\/questions\/14480124\/how-do-i-detect-triangle-and-rectangle-intersection\n        \/\/\/ <\/remarks>\n        private static Point? GetIntersect(Point line1From, Point line1To, Point line2From, Point line2To)\n        {\n            Vector direction1 = line1To - line1From;\n            Vector direction2 = line2To - line2From;\n            double dotPerp = (direction1.X * direction2.Y) - (direction1.Y * direction2.X);\n\n            \/\/ If it's 0, it means the lines are parallel so have infinite intersection points\n            if (IsNearZero(dotPerp))\n            {\n                return null;\n            }\n\n            Vector c = line2From - line1From;\n            double t = (c.X * direction2.Y - c.Y * direction2.X) \/ dotPerp;\n            \/\/if (t < 0 || t > 1)\n            \/\/{\n            \/\/    return null;\t\t\/\/\tlies outside the line segment\n            \/\/}\n\n            \/\/double u = (c.X * direction1.Y - c.Y * direction1.X) \/ dotPerp;\n            \/\/if (u < 0 || u > 1)\n            \/\/{\n            \/\/    return null;\t\t\/\/\tlies outside the line segment\n            \/\/}\n\n            \/\/\tReturn the intersection point\n            return line1From + (t * direction1);\n        }\n\n        private static bool IsInside(Edge edge, Point test)\n        {\n            bool? isLeft = IsLeftOf(edge, test);\n            if (isLeft == null)\n            {\n                \/\/\tColinear points should be considered inside\n                return true;\n            }\n\n            return !isLeft.Value;\n        }\n        private static bool IsClockwise(Point[] polygon)\n        {\n            for (int cntr = 2; cntr < polygon.Length; cntr++)\n            {\n                bool? isLeft = IsLeftOf(new Edge(polygon[0], polygon[1]), polygon[cntr]);\n                if (isLeft\u00a0!= null)\t\t\/\/\tsome of the points may be colinear.  That's ok as long as the overall is a polygon\n                {\n                    return !isLeft.Value;\n                }\n            }\n\n            throw new ArgumentException(\"All the points in the polygon are colinear\");\n        }\n\n        \/\/\/ <summary>\n        \/\/\/ Tells if the test point lies on the left side of the edge line\n        \/\/\/ <\/summary>\n        private static bool? IsLeftOf(Edge edge, Point test)\n        {\n            Vector tmp1 = edge.To - edge.From;\n            Vector tmp2 = test - edge.To;\n\n            double x = (tmp1.X * tmp2.Y) - (tmp1.Y * tmp2.X);\t\t\/\/\tdot product of perpendicular?\n\n            if (x < 0)\n            {\n                return false;\n            }\n            else if (x > 0)\n            {\n                return true;\n            }\n            else\n            {\n                \/\/\tColinear points;\n                return null;\n            }\n        }\n\n        private static bool IsNearZero(double testValue)\n        {\n            return Math.Abs(testValue) <= .000000001d;\n        }\n\n        #endregion\n    }\n}\n\n<Window x:Class=\"Sutherland.MainWindow\"\n        xmlns=\"http:\/\/schemas.microsoft.com\/winfx\/2006\/xaml\/presentation\"\n        xmlns:x=\"http:\/\/schemas.microsoft.com\/winfx\/2006\/xaml\"\n        Title=\"Sutherland Hodgman\" Background=\"#B0B0B0\" ResizeMode=\"CanResizeWithGrip\" Width=\"525\" Height=\"450\">\n    <Grid Margin=\"4\">\n        <Grid.RowDefinitions>\n            <RowDefinition Height=\"1*\"\/>\n            <RowDefinition Height=\"auto\"\/>\n        <\/Grid.RowDefinitions>\n\n        <Border Grid.Row=\"0\" CornerRadius=\"4\" BorderBrush=\"#707070\" Background=\"#FFFFFF\" BorderThickness=\"2\">\n            <Canvas Name=\"canvas\"\/>\n        <\/Border>\n\n        <UniformGrid Grid.Row=\"1\" Rows=\"1\" Margin=\"0,4,0,0\">\n            <Button Name=\"btnTriRect\" Content=\"Triangle - Rectangle\" Margin=\"4,0\" Click=\"btnTriRect_Click\"\/>\n            <Button Name=\"btnConvex\" Content=\"Concave - Convex\" Click=\"btnConvex_Click\"\/>\n        <\/UniformGrid>\n    <\/Grid>\n<\/Window>\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\nusing System.Windows.Navigation;\nusing System.Windows.Shapes;\n\nnamespace Sutherland\n{\n    public partial class MainWindow\u00a0: Window\n    {\n        #region Declaration Section\n\n        private Random _rand = new Random();\n\n        private Brush _subjectBack = new SolidColorBrush(ColorFromHex(\"30427FCF\"));\n        private Brush _subjectBorder = new SolidColorBrush(ColorFromHex(\"427FCF\"));\n        private Brush _clipBack = new SolidColorBrush(ColorFromHex(\"30D65151\"));\n        private Brush _clipBorder = new SolidColorBrush(ColorFromHex(\"D65151\"));\n        private Brush _intersectBack = new SolidColorBrush(ColorFromHex(\"609F18CC\"));\n        private Brush _intersectBorder = new SolidColorBrush(ColorFromHex(\"9F18CC\"));\n\n        #endregion\n\n        #region Constructor\n\n        public MainWindow()\n        {\n            InitializeComponent();\n        }\n\n        #endregion\n\n        #region Event Listeners\n\n        private void btnTriRect_Click(object sender, RoutedEventArgs e)\n        {\n            try\n            {\n                double width = canvas.ActualWidth;\n                double height = canvas.ActualHeight;\n\n                Point[] poly1 = new Point[] {\n\t\t\t\t    new Point(_rand.NextDouble() * width, _rand.NextDouble() * height),\n\t\t\t\t    new Point(_rand.NextDouble() * width, _rand.NextDouble() * height),\n\t\t\t\t    new Point(_rand.NextDouble() * width, _rand.NextDouble() * height) };\n\n                Point rectPoint = new Point(_rand.NextDouble() * (width * .75d), _rand.NextDouble() * (height * .75d));\t\t\/\/\tdon't let it start all the way at the bottom right\n                Rect rect = new Rect(\n                    rectPoint,\n                    new Size(_rand.NextDouble() * (width - rectPoint.X), _rand.NextDouble() * (height - rectPoint.Y)));\n\n                Point[] poly2 = new Point[] { rect.TopLeft, rect.TopRight, rect.BottomRight, rect.BottomLeft };\n\n                Point[] intersect = SutherlandHodgman.GetIntersectedPolygon(poly1, poly2);\n\n                canvas.Children.Clear();\n                ShowPolygon(poly1, _subjectBack, _subjectBorder, 1d);\n                ShowPolygon(poly2, _clipBack, _clipBorder, 1d);\n                ShowPolygon(intersect, _intersectBack, _intersectBorder, 3d);\n            }\n            catch (Exception ex)\n            {\n                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);\n            }\n        }\n        private void btnConvex_Click(object sender, RoutedEventArgs e)\n        {\n            try\n            {\n                Point[] poly1 = new Point[] { new Point(50, 150), new Point(200, 50), new Point(350, 150), new Point(350, 300), new Point(250, 300), new Point(200, 250), new Point(150, 350), new Point(100, 250), new Point(100, 200) };\n                Point[] poly2 = new Point[] { new Point(100, 100), new Point(300, 100), new Point(300, 300), new Point(100, 300) };\n\n                Point[] intersect = SutherlandHodgman.GetIntersectedPolygon(poly1, poly2);\n\n                canvas.Children.Clear();\n                ShowPolygon(poly1, _subjectBack, _subjectBorder, 1d);\n                ShowPolygon(poly2, _clipBack, _clipBorder, 1d);\n                ShowPolygon(intersect, _intersectBack, _intersectBorder, 3d);\n            }\n            catch (Exception ex)\n            {\n                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);\n            }\n        }\n\n        #endregion\n\n        #region Private Methods\n\n        private void ShowPolygon(Point[] points, Brush background, Brush border, double thickness)\n        {\n            if (points == null || points.Length == 0)\n            {\n                return;\n            }\n\n            Polygon polygon = new Polygon();\n            polygon.Fill = background;\n            polygon.Stroke = border;\n            polygon.StrokeThickness = thickness;\n\n            foreach (Point point in points)\n            {\n                polygon.Points.Add(point);\n            }\n\n            canvas.Children.Add(polygon);\n        }\n\n        \/\/\/ <summary>\n        \/\/\/ This is just a wrapper to the color converter (why can't they have a method off the color class with all\n        \/\/\/ the others?)\n        \/\/\/ <\/summary>\n        private static Color ColorFromHex(string hexValue)\n        {\n            if (hexValue.StartsWith(\"#\"))\n            {\n                return (Color)ColorConverter.ConvertFromString(hexValue);\n            }\n            else\n            {\n                return (Color)ColorConverter.ConvertFromString(\"#\" + hexValue);\n            }\n        }\n\n        #endregion\n    }\n}\n\n","human_summarization":"implement the Sutherland-Hodgman clipping algorithm to find the intersection between a subject polygon and a clip polygon. The subject polygon is defined by a sequence of points and is clipped by a rectangle. The program then prints the sequence of points that define the resulting clipped polygon. Additionally, for extra credit, the program displays all three polygons on a graphical surface, each in a different color, and fills the resulting polygon. The origin for display can be either north-west or south-west. The implementation is done in .net 4.0 using wpf.","id":3336}
    {"lang_cluster":"C#","source_code":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace RankingMethods {\n    class Program {\n        static void Main(string[] args) {\n            Dictionary<string, int> scores = new Dictionary<string, int> {\n                [\"Solomon\"] = 44,\n                [\"Jason\"] = 42,\n                [\"Errol\"] = 42,\n                [\"Gary\"] = 41,\n                [\"Bernard\"] = 41,\n                [\"Barry\"] = 41,\n                [\"Stephen\"] = 39,\n            };\n\n            StandardRank(scores);\n            ModifiedRank(scores);\n            DenseRank(scores);\n            OrdinalRank(scores);\n            FractionalRank(scores);\n        }\n\n        static void StandardRank(Dictionary<string, int> data) {\n            Console.WriteLine(\"Standard Rank\");\n\n            var list = data.Values.Distinct().ToList();\n            list.Sort((a, b) => b.CompareTo(a));\n\n            int rank = 1;\n            foreach (var value in list) {\n                int temp = rank;\n                foreach (var k in data.Keys) {\n                    if (data[k] == value) {\n                        Console.WriteLine(\"{0} {1} {2}\", temp, value, k);\n                        rank++;\n                    }\n                }\n            }\n\n            Console.WriteLine();\n        }\n\n        static void ModifiedRank(Dictionary<string, int> data) {\n            Console.WriteLine(\"Modified Rank\");\n\n            var list = data.Values.Distinct().ToList();\n            list.Sort((a, b) => b.CompareTo(a));\n\n            int rank = 0;\n            foreach (var value in list) {\n                foreach (var k in data.Keys) {\n                    if (data[k] == value) {\n                        rank++;\n                    }\n                }\n\n                foreach (var k in data.Keys) {\n                    if (data[k] == value) {\n                        Console.WriteLine(\"{0} {1} {2}\", rank, data[k], k);\n                    }\n                }\n            }\n\n            Console.WriteLine();\n        }\n\n        static void DenseRank(Dictionary<string, int> data) {\n            Console.WriteLine(\"Dense Rank\");\n\n            var list = data.Values.Distinct().ToList();\n            list.Sort((a, b) => b.CompareTo(a));\n\n            int rank = 1;\n            foreach (var value in list) {\n                foreach (var k in data.Keys) {\n                    if (data[k] == value) {\n                        Console.WriteLine(\"{0} {1} {2}\", rank, data[k], k);\n                    }\n                }\n                rank++;\n            }\n\n            Console.WriteLine();\n        }\n\n        static void OrdinalRank(Dictionary<string, int> data) {\n            Console.WriteLine(\"Ordinal Rank\");\n\n            var list = data.Values.Distinct().ToList();\n            list.Sort((a, b) => b.CompareTo(a));\n\n            int rank = 1;\n            foreach (var value in list) {\n                foreach (var k in data.Keys) {\n                    if (data[k] == value) {\n                        Console.WriteLine(\"{0} {1} {2}\", rank, data[k], k);\n                        rank++;\n                    }\n                }\n            }\n\n            Console.WriteLine();\n        }\n\n        static void FractionalRank(Dictionary<string, int> data) {\n            Console.WriteLine(\"Fractional Rank\");\n\n            var list = data.Values.Distinct().ToList();\n            list.Sort((a, b) => b.CompareTo(a));\n\n            int rank = 0;\n            foreach (var value in list) {\n                double avg = 0;\n                int cnt = 0;\n\n                foreach (var k in data.Keys) {\n                    if (data[k] == value) {\n                        rank++;\n                        cnt++;\n                        avg += rank;\n                    }\n                }\n                avg \/= cnt;\n\n                foreach (var k in data.Keys) {\n                    if (data[k] == value) {\n                        Console.WriteLine(\"{0:F1} {1} {2}\", avg, data[k], k);\n                    }\n                }\n            }\n\n            Console.WriteLine();\n        }\n    }\n}\n\n\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":3337}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            Console.WriteLine(\"=== radians ===\");\n            Console.WriteLine(\"sin (pi\/3) = {0}\", Math.Sin(Math.PI \/ 3));\n            Console.WriteLine(\"cos (pi\/3) = {0}\", Math.Cos(Math.PI \/ 3));\n            Console.WriteLine(\"tan (pi\/3) = {0}\", Math.Tan(Math.PI \/ 3));\n            Console.WriteLine(\"arcsin (1\/2) = {0}\", Math.Asin(0.5));\n            Console.WriteLine(\"arccos (1\/2) = {0}\", Math.Acos(0.5));\n            Console.WriteLine(\"arctan (1\/2) = {0}\", Math.Atan(0.5));\n            Console.WriteLine(\"\");\n            Console.WriteLine(\"=== degrees ===\");\n            Console.WriteLine(\"sin (60) = {0}\", Math.Sin(60 * Math.PI \/ 180));\n            Console.WriteLine(\"cos (60) = {0}\", Math.Cos(60 * Math.PI \/ 180));\n            Console.WriteLine(\"tan (60) = {0}\", Math.Tan(60 * Math.PI \/ 180));\n            Console.WriteLine(\"arcsin (1\/2) = {0}\", Math.Asin(0.5) * 180\/ Math.PI);\n            Console.WriteLine(\"arccos (1\/2) = {0}\", Math.Acos(0.5) * 180 \/ Math.PI);\n            Console.WriteLine(\"arctan (1\/2) = {0}\", Math.Atan(0.5) * 180 \/ Math.PI);\n\n            Console.ReadLine();\n        }\n    }\n}\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":3338}
    {"lang_cluster":"C#","source_code":"\n\nusing System;  \/\/ 4790@3.6\nclass program\n{\n    static void Main()\n    {\n        knapSack(40);\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        Console.Write(knapSack(400) + \"\\n\" + sw.Elapsed);  \/\/ 51 \u00b5s\n        Console.Read();\n    }\n\n    static string knapSack(uint w1)\n    {\n        init(); change();\n        uint n = (uint)w.Length; var K = new uint[n + 1, w1 + 1];\n        for (uint vi, wi, w0, x, i = 0; i < n; i++)\n            for (vi = v[i], wi = w[i], w0 = 1; w0 <= w1; w0++)\n            {\n                x = K[i, w0];\n                if (wi <= w0) x = max(vi + K[i, w0 - wi], x);\n                K[i + 1, w0] = x;\n            }\n        string str = \"\";\n        for (uint v1 = K[n, w1]; v1 > 0; n--)\n            if (v1 != K[n - 1, w1])\n            {\n                v1 -= v[n - 1]; w1 -= w[n - 1]; str += items[n - 1] + \"\\n\";\n            }\n        return str;\n    }\n\n    static uint max(uint a, uint b) { return a > b ? a : b; }\n\n    static byte[] w, v; static string[] items;\n\n    static byte[] p = { 1, 1, 2, 2, 2, 3, 3, 3, 1, 3, 1, 1, 2, 2, 1, 1, 1, 1, 1, 2, 1, 2 };\n\n    static void init()\n    {\n        w = new byte[] { 9, 13, 153, 50, 15, 68, 27, 39, 23, 52, 11,\n                          32, 24, 48, 73, 42, 43, 22, 7, 18, 4, 30 };\n\n        v = new byte[] { 150, 35, 200, 60, 60, 45, 60, 40, 30, 10, 70,\n                          30, 15, 10, 40, 70, 75, 80, 20, 12, 50, 10 };\n\n        items = new string[] {\"map\",\"compass\",\"water\",\"sandwich\",\"glucose\",\"tin\",\n                              \"banana\",\"apple\",\"cheese\",\"beer\",\"suntan cream\",\n                              \"camera\",\"T-shirt\",\"trousers\",\"umbrella\",\n                              \"waterproof trousers\",\"waterproof overclothes\",\n                              \"note-case\",\"sunglasses\",\"towel\",\"socks\",\"book\"};\n    }\n\n    static void change()\n    {\n        int n = w.Length, s = 0, i, j, k; byte xi;\n        for (i = 0; i < n; i++) s += p[i];\n        {\n            byte[] x = new byte[s];\n            for (k = i = 0; i < n; i++)\n                for (xi = w[i], j = p[i]; j > 0; j--) x[k++] = xi;\n            w = x;\n        }\n        {\n            byte[] x = new byte[s];\n            for (k = i = 0; i < n; i++)\n                for (xi = v[i], j = p[i]; j > 0; j--) x[k++] = xi;\n            v = x;\n        }\n        string[] pItems = new string[s]; string itemI;\n        for (k = i = 0; i < n; i++)\n            for (itemI = items[i], j = p[i]; j > 0; j--) pItems[k++] = itemI;\n        items = pItems;\n    }\n}\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, without exceeding a weight limit of 4 kg, to maximize the total value. The items, their weights, values, and quantities are given in a list. The solution does not allow for fractional items. This is a variant of the Bounded Knapsack problem.","id":3339}
    {"lang_cluster":"C#","source_code":"\n\nusing System; \/\/DateTime, Console, Environment classes\nclass Program\n{\n    static DateTime start;\n    static void Main(string[] args)\n    {\n        start = DateTime.Now;\n        \/\/Add event handler for Ctrl+C command\n        Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);\n        int counter = 0;\n        while (true)\n        {\n            Console.WriteLine(++counter);\n            System.Threading.Thread.Sleep(500);\n        }\n    }\n    static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)\n    {\n        var end = DateTime.Now;\n        Console.WriteLine(\"This program ran for {0:000.000} seconds.\", (end - start).TotalMilliseconds \/ 1000);\n        Environment.Exit(0);\n    }\n}\n\n","human_summarization":"The code outputs an integer every half second. It also handles SIGINT or SIGQUIT signals, often generated by user's ctrl-C or ctrl-\\ inputs. On receiving these signals, the code stops outputting integers, displays the total runtime in seconds, and then terminates. This signal handling is achieved through event handler functions, referred to as 'events' in C#.","id":3340}
    {"lang_cluster":"C#","source_code":"\nstring s = \"12345\";\ns = (int.Parse(s) + 1).ToString();\n\/\/ The above functions properly for strings >= Int32.MinValue and\n\/\/  < Int32.MaxValue. ( -2147483648 to 2147483646 )\n\n\/\/ The following will work for any arbitrary-length integer string.\n\/\/  (Assuming that the string fits in memory, leaving enough space\n\/\/  for the temporary BigInteger created, plus the resulting string):\nusing System.Numerics;\nstring bis = \"123456789012345678999999999\";\nbis = (BigInteger.Parse(bis) + 1).ToString();\n\/\/ Note that extremely long strings will take a long time to parse\n\/\/  and convert from a BigInteger back into a string.\n\n","human_summarization":"\"Increments a given numerical string.\"","id":3341}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace RosettaCodeTasks\n{\n\n\tclass Program\n\t{\n\t\tstatic void Main ( string[ ] args )\n\t\t{\n\t\t\tFindCommonDirectoryPath.Test ( );\n\t\t}\n\n\t}\n\n\tclass FindCommonDirectoryPath\n\t{\n\t\tpublic static void Test ( )\n\t\t{\n\t\t\tConsole.WriteLine ( \"Find Common Directory Path\" );\n\t\t\tConsole.WriteLine ( );\n\t\t\tList<string> PathSet1 = new List<string> ( );\n\t\t\tPathSet1.Add ( \"\/home\/user1\/tmp\/coverage\/test\" );\n\t\t\tPathSet1.Add ( \"\/home\/user1\/tmp\/covert\/operator\" );\n\t\t\tPathSet1.Add ( \"\/home\/user1\/tmp\/coven\/members\" );\n\t\t\tConsole.WriteLine(\"Path Set 1 (All Absolute Paths):\");\n\t\t\tforeach ( string path in PathSet1 )\n\t\t\t{\n\t\t\t\tConsole.WriteLine ( path );\n\t\t\t}\n\t\t\tConsole.WriteLine ( \"Path Set 1 Common Path: {0}\", FindCommonPath ( \"\/\", PathSet1 ) );\n\t\t}\n\t\tpublic static string FindCommonPath ( string Separator, List<string> Paths )\n\t\t{\n\t\t\tstring CommonPath = String.Empty;\n\t\t\tList<string> SeparatedPath = Paths\n\t\t\t\t.First ( str => str.Length == Paths.Max ( st2 => st2.Length ) )\n\t\t\t\t.Split ( new string[ ] { Separator }, StringSplitOptions.RemoveEmptyEntries )\n\t\t\t\t.ToList ( );\n\n\t\t\tforeach ( string PathSegment in SeparatedPath.AsEnumerable ( ) )\n\t\t\t{\n\t\t\t\tif ( CommonPath.Length == 0 && Paths.All ( str => str.StartsWith ( PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath = PathSegment;\n\t\t\t\t}\n\t\t\t\telse if ( Paths.All ( str => str.StartsWith ( CommonPath + Separator + PathSegment ) ) )\n\t\t\t\t{\n\t\t\t\t\tCommonPath += Separator + PathSegment;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn CommonPath;\n\t\t}\n\t}\n}\n\n","human_summarization":"The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '\/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.","id":3342}
    {"lang_cluster":"C#","source_code":"\nprivate static readonly Random Rand = new Random();\n\nvoid sattoloCycle<T>(IList<T> items) {\n    for (var i = items.Count; i-- > 1;) {\n        int j = Rand.Next(i);\n        var tmp = items[i];\n        items[i] = items[j];\n        items[j] = tmp;\n    }\n}\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":3343}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Linq;\n\nnamespace Test\n{\n    class Program\n    {\n        static void Main()\n        {\n            double[] myArr = new double[] { 1, 5, 3, 6, 4, 2 };\n\n            myArr = myArr.OrderBy(i => i).ToArray();\n            \/\/ or Array.Sort(myArr) for in-place sort\n\n            int mid = myArr.Length \/ 2;\n            double median;\n\n            if (myArr.Length % 2 == 0)\n            {\n                \/\/we know its even\n                median = (myArr[mid] + myArr[mid - 1]) \/ 2.0;\n            }\n            else\n            {\n                \/\/we know its odd\n                median = myArr[mid];\n            }\n\n            Console.WriteLine(median);\n            Console.ReadLine();\n        }\n    }\n}\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.","id":3344}
    {"lang_cluster":"C#","source_code":"\nclass Program\n{\n    public void FizzBuzzGo()\n    {\n        Boolean Fizz = false;\n        Boolean Buzz = false;\n        for (int count = 1; count <= 100; count ++)\n        {\n            Fizz = count % 3 == 0;\n            Buzz = count % 5 == 0;\n            if (Fizz && Buzz)\n            {\n                Console.WriteLine(\"Fizz Buzz\");\n                listBox1.Items.Add(\"Fizz Buzz\");\n            }\n            else if (Fizz)\n            {\n                Console.WriteLine(\"Fizz\");\n                listBox1.Items.Add(\"Fizz\");\n            }\n            else if (Buzz)\n            {\n                Console.WriteLine(\"Buzz\");\n                listBox1.Items.Add(\"Buzz\");\n            }\n            else\n            {\n                Console.WriteLine(count);\n                listBox1.Items.Add(count);\n            }\n        }\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        for (uint i = 1; i <= 100; i++)\n        {\n            string s = null;\n \n            if (i % 3 == 0)\n                s = \"Fizz\";\n \n            if (i % 5 == 0)\n                s += \"Buzz\";\n \n            System.Console.WriteLine(s ?? i.ToString());\n        }\n    }\n}\n\nusing System;\nusing System.Linq;\n\nnamespace FizzBuzz\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Enumerable.Range(1, 100)\n                .Select(a => String.Format(\"{0}{1}\", a % 3 == 0 ? \"Fizz\" : string.Empty, a % 5 == 0 ? \"Buzz\" : string.Empty))\n                .Select((b, i) => String.IsNullOrEmpty(b) ? (i + 1).ToString() : b)\n                .ToList()\n                .ForEach(Console.WriteLine);\n        }\n    }\n}\n\nusing System;\nusing System.Globalization;\nusing System.Linq;\n\nnamespace FizzBuzz\n{\n    class Program\n    {\n        static void Main()\n        {\n            Enumerable.Range(1, 100)\n                .GroupBy(e => e % 15 == 0 ? \"FizzBuzz\" : e % 5 == 0 ? \"Buzz\" : e % 3 == 0 ? \"Fizz\" : string.Empty)\n                .SelectMany(item => item.Select(x => new { \n                    Value = x, \n                    Display = String.IsNullOrEmpty(item.Key) ? x.ToString(CultureInfo.InvariantCulture) : item.Key \n                }))\n                .OrderBy(x => x.Value)\n                .Select(x => x.Display)\n                .ToList()\n                .ForEach(Console.WriteLine);\n        }\n    }\n}\n\nusing System;\nnamespace FizzBuzz\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            for (int i = 1; i <= 100; i++)\n            {\n                if (i % 15 == 0)\n                {\n                    Console.WriteLine(\"FizzBuzz\");\n                }\n                else if (i % 3 == 0)\n                {\n                    Console.WriteLine(\"Fizz\");\n                }\n                else if (i % 5 == 0)\n                {\n                    Console.WriteLine(\"Buzz\");\n                }\n                else\n                {\n                    Console.WriteLine(i);\n                }\n            }\n        }\n    }\n}\n\nusing System;\nusing System.Globalization;\n\nnamespace Rosettacode\n{\n    class Program\n    {\n        static void Main()\n        {\n            for (var number = 0; number < 100; number++)\n            {\n                if ((number % 3) == 0 & (number % 5) == 0)\n                {\n                    \/\/For numbers which are multiples of both three and five print \"FizzBuzz\".\n                    Console.WriteLine(\"FizzBuzz\");\n                    continue;\n                }\n\n                if ((number % 3) == 0) Console.WriteLine(\"Fizz\");\n                if ((number % 5) == 0) Console.WriteLine(\"Buzz\");\n                if ((number % 3) != 0 && (number % 5) != 0) Console.WriteLine(number.ToString(CultureInfo.InvariantCulture));\n\n                if (number % 5 == 0)\n                {\n                    Console.WriteLine(Environment.NewLine);\n                }\n            }\n        }\n    }\n}\n\nusing System;\nusing System.Linq;\n \nnamespace FizzBuzz\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Enumerable.Range(1, 100).ToList().ForEach(i => Console.WriteLine(i % 5 == 0 ? string.Format(i % 3 == 0 ? \"Fizz{0}\" : \"{0}\", \"Buzz\") : string.Format(i%3 == 0 ? \"Fizz\" : i.ToString())));\n        }\n    }\n}\n\nclass Program\n{\n    public static string FizzBuzzIt(int n) =>\n        (n % 3, n % 5) switch\n        {\n            (0, 0) => \"FizzBuzz\",\n            (0, _) => \"Fizz\",\n            (_, 0) => \"Buzz\",\n            (_, _) => $\"{n}\"\n        };\n\n    static void Main(string[] args)\n    { \n        foreach (var n in Enumerable.Range(1, 100))\n        {\n            Console.WriteLine(FizzBuzzIt(n));\n        }\n    }\n}\n\nusing System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Linq;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace FizzBuzz\n{\n    [TestClass]\n    public class FizzBuzzTest\n    {\n        private FizzBuzz fizzBuzzer;\n\n        [TestInitialize]\n        public void Initialize()\n        {\n            fizzBuzzer = new FizzBuzz();\n        }\n\n        [TestMethod]\n        public void Give4WillReturn4()\n        {\n            Assert.AreEqual(\"4\", fizzBuzzer.FizzBuzzer(4));\n        }\n\n        [TestMethod]\n        public void Give9WillReturnFizz()\n        {\n            Assert.AreEqual(\"Fizz\", fizzBuzzer.FizzBuzzer(9));\n        }\n\n        [TestMethod]\n        public void Give25WillReturnBuzz()\n        {\n            Assert.AreEqual(\"Buzz\", fizzBuzzer.FizzBuzzer(25));\n        }\n\n        [TestMethod]\n        public void Give30WillReturnFizzBuzz()\n        {\n            Assert.AreEqual(\"FizzBuzz\", fizzBuzzer.FizzBuzzer(30));\n        }\n\n        [TestMethod]\n        public void First15()\n        {\n            ICollection expected = new ArrayList\n                {\"1\", \"2\", \"Fizz\", \"4\", \"Buzz\", \"Fizz\", \"7\", \"8\", \"Fizz\", \"Buzz\", \"11\", \"Fizz\", \"13\", \"14\", \"FizzBuzz\"};\n\n            var actual = Enumerable.Range(1, 15).Select(x => fizzBuzzer.FizzBuzzer(x)).ToList();\n\n            CollectionAssert.AreEqual(expected, actual);\n        }\n\n        [TestMethod]\n        public void From1To100_ToShowHowToGet100()\n        {\n            const int expected = 100;\n            var actual = Enumerable.Range(1, 100).Select(x => fizzBuzzer.FizzBuzzer(x)).ToList();\n\n            Assert.AreEqual(expected, actual.Count);\n        }\n    }\n\n    public class FizzBuzz\n    {\n        private delegate string Xzzer(int value);\n        private readonly IList<Xzzer> _functions = new List<Xzzer>();\n\n        public FizzBuzz()\n        {\n            _functions.Add(x => x % 3 == 0 ? \"Fizz\" : \"\");\n            _functions.Add(x => x % 5 == 0 ? \"Buzz\" : \"\");\n        }\n\n        public string FizzBuzzer(int value)\n        {\n            var result = _functions.Aggregate(String.Empty, (current, function) => current + function.Invoke(value));\n            return String.IsNullOrEmpty(result) ? value.ToString(CultureInfo.InvariantCulture) : result;\n        }\n    }\n}\n\nusing System;\nint max = 100;\nfor(int i=0;\n    ++i<=max; \n    Console.WriteLine(\"{0}{1}{2}\", i%3==0 ? \"Fizz\" : \"\", i%5==0 ? \"Buzz\" : \"\", i%3!=0 && i%5!=0  ? i.ToString() : \"\")\n){}\n\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":3345}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Threading;\nusing System.Windows.Forms;\n\n\/\/\/ <summary>\n\/\/\/ Generates bitmap of Mandelbrot Set and display it on the form.\n\/\/\/ <\/summary>\npublic class MandelbrotSetForm : Form\n{\n    const double MaxValueExtent = 2.0;\n    Thread thread;\n\n    static double CalcMandelbrotSetColor(ComplexNumber c)\n    {\n        \/\/ from http:\/\/en.wikipedia.org\/w\/index.php?title=Mandelbrot_set\n        const int MaxIterations = 1000;\n        const double MaxNorm = MaxValueExtent * MaxValueExtent;\n\n        int iteration = 0;\n        ComplexNumber z = new ComplexNumber();\n        do\n        {\n            z = z * z + c;\n            iteration++;\n        } while (z.Norm() < MaxNorm && iteration < MaxIterations);\n        if (iteration < MaxIterations)\n            return (double)iteration \/ MaxIterations;\n        else\n            return 0; \/\/ black\n    }\n\n    static void GenerateBitmap(Bitmap bitmap)\n    {\n        double scale = 2 * MaxValueExtent \/ Math.Min(bitmap.Width, bitmap.Height);\n        for (int i = 0; i < bitmap.Height; i++)\n        {\n            double y = (bitmap.Height \/ 2 - i) * scale;\n            for (int j = 0; j < bitmap.Width; j++)\n            {\n                double x = (j - bitmap.Width \/ 2) * scale;\n                double color = CalcMandelbrotSetColor(new ComplexNumber(x, y));\n                bitmap.SetPixel(j, i, GetColor(color));\n            }\n        }\n    }\n\n    static Color GetColor(double value)\n    {\n        const double MaxColor = 256;\n        const double ContrastValue = 0.2;\n        return Color.FromArgb(0, 0,\n            (int)(MaxColor * Math.Pow(value, ContrastValue)));\n    }\n    \n    public MandelbrotSetForm()\n    {\n        \/\/ form creation\n        this.Text = \"Mandelbrot Set Drawing\";\n        this.BackColor = System.Drawing.Color.Black;\n        this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;\n        this.MaximizeBox = false;\n        this.StartPosition = FormStartPosition.CenterScreen;\n        this.FormBorderStyle = FormBorderStyle.FixedDialog;\n        this.ClientSize = new Size(640, 640);\n        this.Load += new System.EventHandler(this.MainForm_Load);\n    }\n\n    void MainForm_Load(object sender, EventArgs e)\n    {\n        thread = new Thread(thread_Proc);\n        thread.IsBackground = true;\n        thread.Start(this.ClientSize);\n    }\n\n    void thread_Proc(object args)\n    {\n        \/\/ start from small image to provide instant display for user\n        Size size = (Size)args;\n        int width = 16;\n        while (width * 2 < size.Width)\n        {\n            int height = width * size.Height \/ size.Width;\n            Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);\n            GenerateBitmap(bitmap);\n            this.BeginInvoke(new SetNewBitmapDelegate(SetNewBitmap), bitmap);\n            width *= 2;\n            Thread.Sleep(200);\n        }\n        \/\/ then generate final image\n        Bitmap finalBitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb);\n        GenerateBitmap(finalBitmap);\n        this.BeginInvoke(new SetNewBitmapDelegate(SetNewBitmap), finalBitmap);\n    }\n\n    void SetNewBitmap(Bitmap image)\n    {\n        if (this.BackgroundImage != null)\n            this.BackgroundImage.Dispose();\n        this.BackgroundImage = image;\n    }\n\n    delegate void SetNewBitmapDelegate(Bitmap image);\n\n    static void Main()\n    {\n        Application.Run(new MandelbrotSetForm());\n    }\n}\n\nstruct ComplexNumber\n{\n    public double Re;\n    public double Im;\n\n    public ComplexNumber(double re, double im)\n    {\n        this.Re = re;\n        this.Im = im;\n    }\n\n    public static ComplexNumber operator +(ComplexNumber x, ComplexNumber y)\n    {\n        return new ComplexNumber(x.Re + y.Re, x.Im + y.Im);\n    }\n\n    public static ComplexNumber operator *(ComplexNumber x, ComplexNumber y)\n    {\n        return new ComplexNumber(x.Re * y.Re - x.Im * y.Im,\n            x.Re * y.Im + x.Im * y.Re);\n    }\n\n    public double Norm()\n    {\n        return Re * Re + Im * Im;\n    }\n}\n\n","human_summarization":"generate and draw the Mandelbrot set using various available algorithms and functions.","id":3346}
    {"lang_cluster":"C#","source_code":"\nint sum = 0, prod = 1;\nint[] arg = { 1, 2, 3, 4, 5 };\nforeach (int value in arg) {\n  sum += value;\n  prod *= value;\n}\n\nWorks with: C# version 3\nint[] arg = { 1, 2, 3, 4, 5 };\nint sum = arg.Sum();\nint prod = arg.Aggregate((runningProduct, nextFactor) => runningProduct * nextFactor);\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":3347}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program\n{\n    static void Main()\n    {\n        foreach (var year in new[] { 1900, 1994, 1996, DateTime.Now.Year })\n        {\n            Console.WriteLine(\"{0} is {1}a leap year.\",\n                              year,\n                              DateTime.IsLeapYear(year) ? string.Empty : \"not \");\n        }\n    }\n}\n\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":3348}
    {"lang_cluster":"C#","source_code":"\n\n\t\/\/\/ Represent digest with ABCD\n\tsealed public class Digest\n\t{\n\t\tpublic uint A;\n\t\tpublic uint B;\n\t\tpublic uint C;\n\t\tpublic uint D;\n\n\t\tpublic Digest()\n\t\t{\n\t\t\tA=(uint)MD5InitializerConstant.A;\n\t\t\tB=(uint)MD5InitializerConstant.B;\n\t\t\tC=(uint)MD5InitializerConstant.C;\n\t\t\tD=(uint)MD5InitializerConstant.D;\n       \t        }\n\n\t\tpublic override string ToString()\n\t\t{\n\t\t\tstring st ;\n\t\t\tst= MD5Helper.ReverseByte(A).ToString(\"X8\")+\n\t\t\t    MD5Helper.ReverseByte(B).ToString(\"X8\")+\n                            MD5Helper.ReverseByte(C).ToString(\"X8\")+\n\t\t\t    MD5Helper.ReverseByte(D).ToString(\"X8\");\n\t\t\treturn st;\n\t\t\t\n\t\t}\n\t}\n\n\tpublic class MD5\n\t{\n\t\t\/***********************VARIABLES************************************\/\n\n\n\t\t\/***********************Statics**************************************\/\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ lookup table 4294967296*sin(i)\n\t\t\/\/\/ <\/summary>\n\t\tprotected readonly static uint []  T =new uint[64] \n\t\t\t{\t0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,\n\t\t\t\t0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,\n                0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,\n                0x6b901122,0xfd987193,0xa679438e,0x49b40821,\n\t\t\t\t0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,\n                0xd62f105d,0x2441453,0xd8a1e681,0xe7d3fbc8,\n                0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,\n\t\t\t\t0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,\n                0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,\n                0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,\n                0x289b7ec6,0xeaa127fa,0xd4ef3085,0x4881d05,\n\t\t\t\t0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,\n                0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,\n                0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,\n                0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,\n\t\t\t\t0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391};\n\t\t\n\t\t\/*****instance variables**************\/\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ X used to proces data in \n\t\t\/\/\/\t512 bits chunks as 16 32 bit word\n\t\t\/\/\/ <\/summary>\n\t\tprotected  uint [] X = new uint [16];\t\n\t\t\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ the finger print obtained. \n\t\t\/\/\/ <\/summary>\n\t\tprotected Digest dgFingerPrint;\t\t\t\n\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ the input bytes\n\t\t\/\/\/ <\/summary>\n\t\tprotected\tbyte [] m_byteInput;\t\t\n\t\t\n\t\n\t\t\n\t\t\/**********************EVENTS AND DELEGATES*******************************************\/\n\n\t\tpublic delegate void ValueChanging (object sender,MD5ChangingEventArgs Changing);\n\t\tpublic delegate void ValueChanged (object sender,MD5ChangedEventArgs Changed);\n\n\n\t\tpublic event ValueChanging OnValueChanging;\n\t\tpublic event ValueChanged  OnValueChanged;\n\n\n\t\t\n\t\t\/********************************************************************\/\n\t\t\/***********************PROPERTIES ***********************\/\n\t\t\/\/\/ <summary>\n\t\t\/\/\/gets or sets as string\n\t\t\/\/\/ <\/summary>\n\t\tpublic string Value\n\t\t{\n\t\t\tget\n\t\t\t{ \n\t\t\t\tstring st ;\n\t\t\t\tchar [] tempCharArray= new Char[m_byteInput.Length];\n\t\t\t\t\n\t\t\t\tfor(int i =0; i<m_byteInput.Length;i++)\n\t\t\t\t\ttempCharArray[i]=(char)m_byteInput[i];\n\n\t\t\t\tst= new String(tempCharArray);\n\t\t\t\treturn st;\n\t\t\t}\n\t\t\tset\n\t\t\t{\n\t\t\t\t\/\/\/ raise the event to notify the changing \n\t\t\t\tif (this.OnValueChanging !=null)\n\t\t\t\t\tthis.OnValueChanging(this,new MD5ChangingEventArgs(value));\n\n\n\t\t\t\tm_byteInput=new byte[value.Length];\n\t\t\t\tfor (int i =0; i<value.Length;i++)\n\t\t\t\t\tm_byteInput[i]=(byte)value[i];\n\t\t\t\tdgFingerPrint=CalculateMD5Value();\t\t\t\t\n\n\t\t\t\t\/\/\/ raise the event to notify the change\n\t\t\t\tif (this.OnValueChanged !=null)\n\t\t\t\t\tthis.OnValueChanged(this,new MD5ChangedEventArgs(value,dgFingerPrint.ToString()));\n\t\t\t\t \n\t\t\t}\n\t\t}\t\t\n\t\t\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ get\/sets as  byte array \n\t\t\/\/\/ <\/summary>\n\t\tpublic byte [] ValueAsByte\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\tbyte [] bt = new byte[m_byteInput.Length];\n\t\t\t\tfor (int i =0; i<m_byteInput.Length;i++)\n\t\t\t\t\tbt[i]=m_byteInput[i];\n\t\t\t\treturn bt;\n          }\n\t\t\tset\n\t\t\t{\n\t\t\t\t\/\/\/ raise the event to notify the changing\n\t\t\t\tif (this.OnValueChanging !=null)\n\t\t\t\t\tthis.OnValueChanging(this,new MD5ChangingEventArgs(value));\n\n\t\t\t\tm_byteInput=new byte[value.Length];\n\t\t\t\tfor (int i =0; i<value.Length;i++)\n\t\t\t\t\tm_byteInput[i]=value[i];\n\t\t\t\tdgFingerPrint=CalculateMD5Value();\n\n\t\n\t\t\t\t\/\/\/ notify the changed  value\n\t\t\t\tif (this.OnValueChanged !=null)\n\t\t\t\t\tthis.OnValueChanged(this,new MD5ChangedEventArgs(value,dgFingerPrint.ToString()));\n\t\t\t}\n\t\t}\n\n\t\t\/\/gets the signature\/figner print as string\n\t\tpublic  string FingerPrint\n\t\t{\n\t\t\tget\n\t\t\t{\n\t\t\t\treturn dgFingerPrint.ToString();\n\t\t\t}\n\t\t}\n\n\n\t\t\/*************************************************************************\/\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ Constructor\n\t\t\/\/\/ <\/summary>\n\t\tpublic MD5()\n\t\t{\t\t\t\n\t\t\tValue=\"\";\n\t\t}\n\t\t\n\t\t\n\t\t\/******************************************************************************\/\n\t\t\/*********************METHODS**************************\/\n\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ calculat md5 signature of the string in Input\n\t\t\/\/\/ <\/summary>\n\t\t\/\/\/ <returns> Digest: the finger print of msg<\/returns>\n\t\tprotected Digest CalculateMD5Value()\n\t\t{\n\t\t\t\/***********vairable declaration**************\/\n\t\t\tbyte [] bMsg;\t\/\/buffer to hold bits\n\t\t\tuint N;\t\t\t\/\/N is the size of msg as  word (32 bit) \n\t\t\tDigest dg =new Digest();\t\t\t\/\/  the value to be returned\n\n\t\t\t\/\/ create a buffer with bits padded and length is alos padded\n\t\t\tbMsg=CreatePaddedBuffer();\n\n\t\t\tN=(uint)(bMsg.Length*8)\/32;\t\t\/\/no of 32 bit blocks\n\t\t\t\n\t\t\tfor (uint  i=0; i<N\/16;i++)\n\t\t\t{\n\t\t\t\tCopyBlock(bMsg,i);\n\t\t\t\tPerformTransformation(ref dg.A,ref dg.B,ref dg.C,ref dg.D);\n\t\t\t}\n\t\t\treturn dg;\n\t\t}\n\t\n\t\t\/********************************************************\n\t\t * TRANSFORMATIONS\u00a0:  FF , GG , HH , II  acc to RFC 1321\n\t\t * where each Each letter represnets the aux function used\n\t\t *********************************************************\/\n\n\n\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ perform transformatio using f(((b&c) | (~(b)&d))\n\t\t\/\/\/ <\/summary>\n\t\tprotected void TransF(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i )\n\t\t{\n\t\t\ta = b + MD5Helper.RotateLeft((a + ((b&c) | (~(b)&d)) + X[k] + T[i-1]), s);\n\t\t}\n\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ perform transformatio using g((b&d) | (c & ~d) )\n\t\t\/\/\/ <\/summary>\n\t\tprotected void TransG(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i )\n\t\t{\n\t\t\ta = b + MD5Helper.RotateLeft((a + ((b&d) | (c & ~d) ) + X[k] + T[i-1]), s);\n\t\t}\n\t\t\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ perform transformatio using h(b^c^d)\n\t\t\/\/\/ <\/summary>\n\t\tprotected void TransH(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i )\n\t\t{\n\t\t\ta = b + MD5Helper.RotateLeft((a + (b^c^d) + X[k] + T[i-1]), s);\n\t\t}\n\t\t\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ perform transformatio using i (c^(b|~d))\n\t\t\/\/\/ <\/summary>\n\t\tprotected void TransI(ref uint a, uint b, uint c, uint d,uint k,ushort s, uint i )\n\t\t{\n\t\t\ta = b + MD5Helper.RotateLeft((a + (c^(b|~d))+ X[k] + T[i-1]), s);\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ Perform All the transformation on the data\n\t\t\/\/\/ <\/summary>\n\t\t\/\/\/ <param name=\"A\">A<\/param>\n\t\t\/\/\/ <param name=\"B\">B <\/param>\n\t\t\/\/\/ <param name=\"C\">C<\/param>\n\t\t\/\/\/ <param name=\"D\">D<\/param>\n\t\tprotected void PerformTransformation(ref uint A,ref uint B,ref uint C, ref uint D)\n\t\t{\n\t\t\t\/\/\/\/ saving  ABCD  to be used in end of loop\n\t\t\t\n\t\t\tuint AA,BB,CC,DD;\n\n\t\t\tAA=A;\t\n\t\t\tBB=B;\n\t\t\tCC=C;\n\t\t\tDD=D;\n\n\t\t\t\/* Round 1 \n\t\t\t\t* [ABCD  0  7  1]  [DABC  1 12  2]  [CDAB  2 17  3]  [BCDA  3 22  4]\n\t\t\t\t* [ABCD  4  7  5]  [DABC  5 12  6]  [CDAB  6 17  7]  [BCDA  7 22  8]\n\t\t\t\t* [ABCD  8  7  9]  [DABC  9 12 10]  [CDAB 10 17 11]  [BCDA 11 22 12]\n\t\t\t\t* [ABCD 12  7 13]  [DABC 13 12 14]  [CDAB 14 17 15]  [BCDA 15 22 16]\n\t\t\t\t*  * *\/\n\t\t\tTransF(ref A,B,C,D,0,7,1);TransF(ref D,A,B,C,1,12,2);TransF(ref C,D,A,B,2,17,3);TransF(ref B,C,D,A,3,22,4);\n\t\t\tTransF(ref A,B,C,D,4,7,5);TransF(ref D,A,B,C,5,12,6);TransF(ref C,D,A,B,6,17,7);TransF(ref B,C,D,A,7,22,8);\n\t\t\tTransF(ref A,B,C,D,8,7,9);TransF(ref D,A,B,C,9,12,10);TransF(ref C,D,A,B,10,17,11);TransF(ref B,C,D,A,11,22,12);\n\t\t\tTransF(ref A,B,C,D,12,7,13);TransF(ref D,A,B,C,13,12,14);TransF(ref C,D,A,B,14,17,15);TransF(ref B,C,D,A,15,22,16);\n\t\t\t\/** rOUND 2\n\t\t\t\t**[ABCD  1  5 17]  [DABC  6  9 18]  [CDAB 11 14 19]  [BCDA  0 20 20]\n\t\t\t\t*[ABCD  5  5 21]  [DABC 10  9 22]  [CDAB 15 14 23]  [BCDA  4 20 24]\n\t\t\t\t*[ABCD  9  5 25]  [DABC 14  9 26]  [CDAB  3 14 27]  [BCDA  8 20 28]\n\t\t\t\t*[ABCD 13  5 29]  [DABC  2  9 30]  [CDAB  7 14 31]  [BCDA 12 20 32]\n\t\t\t*\/\n\t\t\tTransG(ref A,B,C,D,1,5,17);TransG(ref D,A,B,C,6,9,18);TransG(ref C,D,A,B,11,14,19);TransG(ref B,C,D,A,0,20,20);\n\t\t\tTransG(ref A,B,C,D,5,5,21);TransG(ref D,A,B,C,10,9,22);TransG(ref C,D,A,B,15,14,23);TransG(ref B,C,D,A,4,20,24);\n\t\t\tTransG(ref A,B,C,D,9,5,25);TransG(ref D,A,B,C,14,9,26);TransG(ref C,D,A,B,3,14,27);TransG(ref B,C,D,A,8,20,28);\n\t\t\tTransG(ref A,B,C,D,13,5,29);TransG(ref D,A,B,C,2,9,30);TransG(ref C,D,A,B,7,14,31);TransG(ref B,C,D,A,12,20,32);\n\t\t\t\/*  rOUND 3\n\t\t\t\t* [ABCD  5  4 33]  [DABC  8 11 34]  [CDAB 11 16 35]  [BCDA 14 23 36]\n\t\t\t\t* [ABCD  1  4 37]  [DABC  4 11 38]  [CDAB  7 16 39]  [BCDA 10 23 40]\n\t\t\t\t* [ABCD 13  4 41]  [DABC  0 11 42]  [CDAB  3 16 43]  [BCDA  6 23 44]\n\t\t\t\t* [ABCD  9  4 45]  [DABC 12 11 46]  [CDAB 15 16 47]  [BCDA  2 23 48]\n\t\t\t * *\/\n\t\t\tTransH(ref A,B,C,D,5,4,33);TransH(ref D,A,B,C,8,11,34);TransH(ref C,D,A,B,11,16,35);TransH(ref B,C,D,A,14,23,36);\n\t\t\tTransH(ref A,B,C,D,1,4,37);TransH(ref D,A,B,C,4,11,38);TransH(ref C,D,A,B,7,16,39);TransH(ref B,C,D,A,10,23,40);\n\t\t\tTransH(ref A,B,C,D,13,4,41);TransH(ref D,A,B,C,0,11,42);TransH(ref C,D,A,B,3,16,43);TransH(ref B,C,D,A,6,23,44);\n\t\t\tTransH(ref A,B,C,D,9,4,45);TransH(ref D,A,B,C,12,11,46);TransH(ref C,D,A,B,15,16,47);TransH(ref B,C,D,A,2,23,48);\n\t\t\t\/*ORUNF  4\n\t\t\t\t*[ABCD  0  6 49]  [DABC  7 10 50]  [CDAB 14 15 51]  [BCDA  5 21 52]\n\t\t\t\t*[ABCD 12  6 53]  [DABC  3 10 54]  [CDAB 10 15 55]  [BCDA  1 21 56]\n\t\t\t\t*[ABCD  8  6 57]  [DABC 15 10 58]  [CDAB  6 15 59]  [BCDA 13 21 60]\n\t\t\t\t*[ABCD  4  6 61]  [DABC 11 10 62]  [CDAB  2 15 63]  [BCDA  9 21 64]\n\t\t\t\t\t\t * *\/\n\t\t\tTransI(ref A,B,C,D,0,6,49);TransI(ref D,A,B,C,7,10,50);TransI(ref C,D,A,B,14,15,51);TransI(ref B,C,D,A,5,21,52);\n\t\t\tTransI(ref A,B,C,D,12,6,53);TransI(ref D,A,B,C,3,10,54);TransI(ref C,D,A,B,10,15,55);TransI(ref B,C,D,A,1,21,56);\n\t\t\tTransI(ref A,B,C,D,8,6,57);TransI(ref D,A,B,C,15,10,58);TransI(ref C,D,A,B,6,15,59);TransI(ref B,C,D,A,13,21,60);\n\t\t\tTransI(ref A,B,C,D,4,6,61);TransI(ref D,A,B,C,11,10,62);TransI(ref C,D,A,B,2,15,63);TransI(ref B,C,D,A,9,21,64);\n\n\n\t\t\tA=A+AA;\n\t\t\tB=B+BB;\n\t\t\tC=C+CC;\n\t\t\tD=D+DD;\n\n\n\t\t}\n\n\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ Create Padded buffer for processing , buffer is padded with 0 along \n\t\t\/\/\/ with the size in the end\n\t\t\/\/\/ <\/summary>\n\t\t\/\/\/ <returns>the padded buffer as byte array<\/returns>\n\t\tprotected byte[] CreatePaddedBuffer()\n\t\t{\n\t\t\tuint pad;\t\t\/\/no of padding bits for 448 mod 512 \n\t\t\tbyte [] bMsg;\t\/\/buffer to hold bits\n\t\t\tulong sizeMsg;\t\t\/\/64 bit size pad\n\t\t\tuint sizeMsgBuff;\t\/\/buffer size in multiple of bytes\n\t\t\tint temp=(448-((m_byteInput.Length*8)%512)); \/\/temporary \n\n\n\t\t\tpad = (uint )((temp+512)%512);\t\t\/\/getting no of bits to  be pad\n\t\t\tif (pad==0)\t\t\t\t\/\/\/pad is in bits\n\t\t\t\tpad=512;\t\t\t\/\/at least 1 or max 512 can be added\n\n\t\t\tsizeMsgBuff= (uint) ((m_byteInput.Length)+ (pad\/8)+8);\n\t\t\tsizeMsg=(ulong)m_byteInput.Length*8;\n\t\t\tbMsg=new byte[sizeMsgBuff];\t\/\/\/no need to pad with 0 coz new bytes \n\t\t\t\/\/ are already initialize to 0\u00a0:)\n\n\n\n\n\t\t\t\/\/\/\/copying string to buffer \n\t\t\tfor (int i =0; i<m_byteInput.Length;i++)\n\t\t\t\tbMsg[i]=m_byteInput[i];\n\n\t\t\tbMsg[m_byteInput.Length]|=0x80;\t\t\/\/\/making first bit of padding 1,\n\t\t\t\n\t\t\t\/\/wrting the size value\n\t\t\tfor (int i =8; i >0;i--)\n\t\t\t\tbMsg[sizeMsgBuff-i]=(byte) (sizeMsg>>((8-i)*8) & 0x00000000000000ff);\n\n\t\t\treturn bMsg;\n\t\t}\n\n\n\t\t\/\/\/ <summary>\n\t\t\/\/\/ Copies a 512 bit block into X as 16 32 bit words\n\t\t\/\/\/ <\/summary>\n\t\t\/\/\/ <param name=\"bMsg\"> source buffer<\/param>\n\t\t\/\/\/ <param name=\"block\">no of block to copy starting from 0<\/param>\n\t\tprotected void CopyBlock(byte[] bMsg,uint block)\n\t\t{\n\n\t\t\tblock=block<<6;\n\t\t\tfor (uint j=0; j<61;j+=4)\n\t\t\t{\n\t\t\t\tX[j>>2]=(((uint) bMsg[block+(j+3)]) <<24 ) |\n\t\t\t\t\t\t(((uint) bMsg[block+(j+2)]) <<16 ) |\n\t\t\t\t\t\t(((uint) bMsg[block+(j+1)]) <<8 ) |\n\t\t\t\t\t\t(((uint) bMsg[block+(j)]) ) ;\n\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\n\nSystem.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();\nbyte[] bs = System.Text.Encoding.UTF8.GetBytes(password);\nbs = x.ComputeHash(bs); \/\/this function is not in the above classdefinition\nSystem.Text.StringBuilder s = new System.Text.StringBuilder();\nforeach (byte b in bs)\n{\n   s.Append(b.ToString(\"x2\").ToLower());\n} \npassword = s.ToString();\n\n","human_summarization":"Implement and validate the MD5 Message Digest Algorithm directly without using built-in or external hashing libraries. The implementation should produce a correct message digest for an input string. It should also note any challenges, implementation choices, or limitations. The code should not mimic all calling modes but should provide practical illustrations of bit manipulation, unsigned integers, and working with little-endian data. The implementation should be tested against verification strings and hashes from RFC 1321.","id":3349}
    {"lang_cluster":"C#","source_code":"\nusing System;\npublic class Program\n{\n    public static void Main() {\n        for (int p = 2; p <= 7; p+=2) {\n            for (int s = 1; s <= 7; s++) {\n                int f = 12 - p - s;\n                if (s >= f) break;\n                if (f > 7) continue;\n                if (s == p || f == p) continue; \/\/not even necessary\n                Console.WriteLine($\"Police:{p}, Sanitation:{s}, Fire:{f}\");\n                Console.WriteLine($\"Police:{p}, Sanitation:{f}, Fire:{s}\");\n            }\n        }\n    }\n}\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":3350}
    {"lang_cluster":"C#","source_code":"\nstring src = \"Hello\";\nstring dst = src;\n\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":3351}
    {"lang_cluster":"C#","source_code":"\nnamespace RosettaCode {\n    class Hofstadter {\n        static public int F(int n) {\n            int result = 1;\n            if (n > 0) {\n                result = n - M(F(n-1));\n            }\n\n            return result;\n        }\n\n        static public int M(int n) {\n            int result = 0;\n            if (n > 0) {\n                result = n - F(M(n - 1));\n            }\n\n            return result;\n        }\n    }\n}\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":3352}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Collections.Generic;\n\nclass RandomElementPicker {\n  static void Main() {\n    var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});\n    var rng = new Random();\n    var randomElement = list[rng.Next(list.Count)];\n    Console.WriteLine(\"I picked element {0}\", randomElement);\n  }\n}\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":3353}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace URLEncode\n{\n    internal class Program\n    {\n        private static void Main(string[] args)\n        {\n            Console.WriteLine(Decode(\"http%3A%2F%2Ffoo%20bar%2F\"));\n        }\n\n        private static string Decode(string uri)\n        {\n            return Uri.UnescapeDataString(uri);\n        }\n    }\n}\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":3354}
    {"lang_cluster":"C#","source_code":"\n\nnamespace Search {\n  using System;\n\n  public static partial class Extensions {\n    \/\/\/ <summary>Use Binary Search to find index of GLB for value<\/summary>\n    \/\/\/ <typeparam name=\"T\">type of entries and value<\/typeparam>\n    \/\/\/ <param name=\"entries\">array of entries<\/param>\n    \/\/\/ <param name=\"value\">search value<\/param>\n    \/\/\/ <remarks>entries must be in ascending order<\/remarks>\n    \/\/\/ <returns>index into entries of GLB for value<\/returns>\n    public static int RecursiveBinarySearchForGLB<T>(this T[] entries, T value)\n      where T : IComparable {\n      return entries.RecursiveBinarySearchForGLB(value, 0, entries.Length - 1);\n    }\n\n    \/\/\/ <summary>Use Binary Search to find index of GLB for value<\/summary>\n    \/\/\/ <typeparam name=\"T\">type of entries and value<\/typeparam>\n    \/\/\/ <param name=\"entries\">array of entries<\/param>\n    \/\/\/ <param name=\"value\">search value<\/param>\n    \/\/\/ <param name=\"left\">leftmost index to search<\/param>\n    \/\/\/ <param name=\"right\">rightmost index to search<\/param>\n    \/\/\/ <remarks>entries must be in ascending order<\/remarks>\n    \/\/\/ <returns>index into entries of GLB for value<\/returns>\n    public static int RecursiveBinarySearchForGLB<T>(this T[] entries, T value, int left, int right)\n      where T : IComparable {\n      if (left <= right) {\n        var middle = left + (right - left) \/ 2;\n        return entries[middle].CompareTo(value) < 0 ?\n          entries.RecursiveBinarySearchForGLB(value, middle + 1, right) :\n          entries.RecursiveBinarySearchForGLB(value, left, middle - 1);\n      }\n\n      \/\/[Assert]left == right + 1\n      \/\/ GLB: entries[right] < value && value <= entries[right + 1]\n      return right;\n    }\n\n    \/\/\/ <summary>Use Binary Search to find index of LUB for value<\/summary>\n    \/\/\/ <typeparam name=\"T\">type of entries and value<\/typeparam>\n    \/\/\/ <param name=\"entries\">array of entries<\/param>\n    \/\/\/ <param name=\"value\">search value<\/param>\n    \/\/\/ <remarks>entries must be in ascending order<\/remarks>\n    \/\/\/ <returns>index into entries of LUB for value<\/returns>\n    public static int RecursiveBinarySearchForLUB<T>(this T[] entries, T value)\n      where T : IComparable {\n      return entries.RecursiveBinarySearchForLUB(value, 0, entries.Length - 1);\n    }\n\n    \/\/\/ <summary>Use Binary Search to find index of LUB for value<\/summary>\n    \/\/\/ <typeparam name=\"T\">type of entries and value<\/typeparam>\n    \/\/\/ <param name=\"entries\">array of entries<\/param>\n    \/\/\/ <param name=\"value\">search value<\/param>\n    \/\/\/ <param name=\"left\">leftmost index to search<\/param>\n    \/\/\/ <param name=\"right\">rightmost index to search<\/param>\n    \/\/\/ <remarks>entries must be in ascending order<\/remarks>\n    \/\/\/ <returns>index into entries of LUB for value<\/returns>\n    public static int RecursiveBinarySearchForLUB<T>(this T[] entries, T value, int left, int right)\n      where T : IComparable {\n      if (left <= right) {\n        var middle = left + (right - left) \/ 2;\n        return entries[middle].CompareTo(value) <= 0 ?\n          entries.RecursiveBinarySearchForLUB(value, middle + 1, right) :\n          entries.RecursiveBinarySearchForLUB(value, left, middle - 1);\n      }\n\n      \/\/[Assert]left == right + 1\n      \/\/ LUB: entries[left] > value && value >= entries[left - 1]\n      return left;\n    }\n  }\n}\n\n\nnamespace Search {\n  using System;\n\n  public static partial class Extensions {\n    \/\/\/ <summary>Use Binary Search to find index of GLB for value<\/summary>\n    \/\/\/ <typeparam name=\"T\">type of entries and value<\/typeparam>\n    \/\/\/ <param name=\"entries\">array of entries<\/param>\n    \/\/\/ <param name=\"value\">search value<\/param>\n    \/\/\/ <remarks>entries must be in ascending order<\/remarks>\n    \/\/\/ <returns>index into entries of GLB for value<\/returns>\n    public static int BinarySearchForGLB<T>(this T[] entries, T value)\n      where T : IComparable {\n      return entries.BinarySearchForGLB(value, 0, entries.Length - 1);\n    }\n\n    \/\/\/ <summary>Use Binary Search to find index of GLB for value<\/summary>\n    \/\/\/ <typeparam name=\"T\">type of entries and value<\/typeparam>\n    \/\/\/ <param name=\"entries\">array of entries<\/param>\n    \/\/\/ <param name=\"value\">search value<\/param>\n    \/\/\/ <param name=\"left\">leftmost index to search<\/param>\n    \/\/\/ <param name=\"right\">rightmost index to search<\/param>\n    \/\/\/ <remarks>entries must be in ascending order<\/remarks>\n    \/\/\/ <returns>index into entries of GLB for value<\/returns>\n    public static int BinarySearchForGLB<T>(this T[] entries, T value, int left, int right)\n      where T : IComparable {\n      while (left <= right) {\n        var middle = left + (right - left) \/ 2;\n        if (entries[middle].CompareTo(value) < 0)\n          left = middle + 1;\n        else\n          right = middle - 1;\n      }\n\n      \/\/[Assert]left == right + 1\n      \/\/ GLB: entries[right] < value && value <= entries[right + 1]\n      return right;\n    }\n\n    \/\/\/ <summary>Use Binary Search to find index of LUB for value<\/summary>\n    \/\/\/ <typeparam name=\"T\">type of entries and value<\/typeparam>\n    \/\/\/ <param name=\"entries\">array of entries<\/param>\n    \/\/\/ <param name=\"value\">search value<\/param>\n    \/\/\/ <remarks>entries must be in ascending order<\/remarks>\n    \/\/\/ <returns>index into entries of LUB for value<\/returns>\n    public static int BinarySearchForLUB<T>(this T[] entries, T value)\n      where T : IComparable {\n      return entries.BinarySearchForLUB(value, 0, entries.Length - 1);\n    }\n\n    \/\/\/ <summary>Use Binary Search to find index of LUB for value<\/summary>\n    \/\/\/ <typeparam name=\"T\">type of entries and value<\/typeparam>\n    \/\/\/ <param name=\"entries\">array of entries<\/param>\n    \/\/\/ <param name=\"value\">search value<\/param>\n    \/\/\/ <param name=\"left\">leftmost index to search<\/param>\n    \/\/\/ <param name=\"right\">rightmost index to search<\/param>\n    \/\/\/ <remarks>entries must be in ascending order<\/remarks>\n    \/\/\/ <returns>index into entries of LUB for value<\/returns>\n    public static int BinarySearchForLUB<T>(this T[] entries, T value, int left, int right)\n      where T : IComparable {\n      while (left <= right) {\n        var middle = left + (right - left) \/ 2;\n        if (entries[middle].CompareTo(value) <= 0)\n          left = middle + 1;\n        else\n          right = middle - 1;\n      }\n\n      \/\/[Assert]left == right + 1\n      \/\/ LUB: entries[left] > value && value >= entries[left - 1]\n      return left;\n    }\n  }\n}\n\n\n\/\/#define UseRecursiveSearch\n\nusing System;\nusing Search;\n\nclass Program {\n  static readonly int[][] tests = {\n    new int[] { },\n    new int[] { 2 },\n    new int[] { 2, 2 },\n    new int[] { 2, 2, 2, 2 },\n    new int[] { 3, 3, 4, 4 },\n    new int[] { 0, 1, 3, 3, 4, 4 },\n    new int[] { 0, 1, 2, 2, 2, 3, 3, 4, 4},\n    new int[] { 0, 1, 1, 2, 2, 2, 3, 3, 4, 4 },\n    new int[] { 0, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4 },\n    new int[] { 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4 },\n    new int[] { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4 },\n  };\n\n  static void Main(string[] args) {\n    var index = 0;\n    foreach (var test in tests) {\n      var join = String.Join(\" \", test);\n      Console.WriteLine($\"test[{index}]: {join}\");\n#if UseRecursiveSearch\n      var glb = test.RecursiveBinarySearchForGLB(2);\n      var lub = test.RecursiveBinarySearchForLUB(2);\n#else\n      var glb = test.BinarySearchForGLB(2);\n      var lub = test.BinarySearchForLUB(2);\n#endif\n      Console.WriteLine($\"glb = {glb}\");\n      Console.WriteLine($\"lub = {lub}\");\n\n      index++;\n    }\n#if DEBUG\n    Console.Write(\"Press Enter\");\n    Console.ReadLine();\n#endif\n  }\n}\n\n\ntest[0]:\nglb = -1\nlub = 0\ntest[1]: 2\nglb = -1\nlub = 1\ntest[2]: 2 2\nglb = -1\nlub = 2\ntest[3]: 2 2 2 2\nglb = -1\nlub = 4\ntest[4]: 3 3 4 4\nglb = -1\nlub = 0\ntest[5]: 0 1 3 3 4 4\nglb = 1\nlub = 2\ntest[6]: 0 1 2 2 2 3 3 4 4\nglb = 1\nlub = 5\ntest[7]: 0 1 1 2 2 2 3 3 4 4\nglb = 2\nlub = 6\ntest[8]: 0 1 1 1 1 2 2 3 3 4 4\nglb = 4\nlub = 7\ntest[9]: 0 1 1 1 1 2 2 2 2 2 2 2 3 3 4 4\nglb = 4\nlub = 12\ntest[10]: 0 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 3 3 4 4\nglb = 13\nlub = 21\n","human_summarization":"The code implements a binary search algorithm to find a \"secret value\" within a sorted integer array. It includes both recursive and iterative versions of the algorithm, as well as variations that return the leftmost and rightmost insertion points. The code also ensures no overflow bugs occur during the calculation of the midpoint. If the \"secret value\" is found, the index is returned, otherwise, it indicates where the value would be inserted to maintain the sorted order.","id":3355}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main(string[] args) {\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n\n\nusing System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main() {\n            string[] args = Environment.GetCommandLineArgs();\n            for (int i = 0; i < args.Length; i++)\n                Console.WriteLine(String.Format(\"Argument {0} is '{1}'\", i, args[i]));\n        }\n    }\n}\n\n","human_summarization":"The code retrieves the list of command-line arguments given to the program. It uses two methods to access these arguments: one accesses the string array passed to the Main function, only retrieving the arguments, not the path to the executable; the other calls the Environment.GetCommandLineArgs function, which returns both the path to the executable and the actual command-line arguments.","id":3356}
    {"lang_cluster":"C#","source_code":"\nLibrary: Windows Forms\nLibrary: GDI (System.Drawing)\nusing System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nclass CSharpPendulum\n{\n    Form _form;\n    Timer _timer;\n    \n    double _angle = Math.PI \/ 2, \n           _angleAccel, \n           _angleVelocity = 0, \n           _dt = 0.1;\n    \n    int _length = 50;\n\n    [STAThread]\n    static void Main()\n    {\n        var p = new CSharpPendulum();\n    }\n\n    public CSharpPendulum()\n    {\n        _form = new Form() { Text = \"Pendulum\", Width = 200, Height = 200 };\n        _timer = new Timer() { Interval = 30 };\n\n        _timer.Tick += delegate(object sender, EventArgs e)\n        {\n            int anchorX = (_form.Width \/ 2) - 12,\n                anchorY = _form.Height \/ 4,\n                ballX = anchorX + (int)(Math.Sin(_angle) * _length),\n                ballY = anchorY + (int)(Math.Cos(_angle) * _length);\n\n            _angleAccel = -9.81 \/ _length * Math.Sin(_angle);\n            _angleVelocity += _angleAccel * _dt;\n            _angle += _angleVelocity * _dt;\n          \n            Bitmap dblBuffer = new Bitmap(_form.Width, _form.Height);\n            Graphics g = Graphics.FromImage(dblBuffer);\n            Graphics f = Graphics.FromHwnd(_form.Handle);\n\n            g.DrawLine(Pens.Black, new Point(anchorX, anchorY), new Point(ballX, ballY));\n            g.FillEllipse(Brushes.Black, anchorX - 3, anchorY - 4, 7, 7);\n            g.FillEllipse(Brushes.DarkGoldenrod, ballX - 7, ballY - 7, 14, 14);\n            \n            f.Clear(Color.White);\n            f.DrawImage(dblBuffer, new Point(0, 0));    \n        };\n\n        _timer.Start();\n        Application.Run(_form);\n    }     \n}\n\n","human_summarization":"create and animate a simple physical model of a gravity pendulum.","id":3357}
    {"lang_cluster":"C#","source_code":"\nWorks with: C sharp version 3.0\n\nusing System;\nusing System.Collections.Generic;\nusing System.Web.Script.Serialization;\n\nclass Program\n{\n    static void Main()\n    {\n        var people = new Dictionary<string, object> {{\"1\", \"John\"}, {\"2\", \"Susan\"}};\n        var serializer = new JavaScriptSerializer();\n        \n        var json = serializer.Serialize(people);\n        Console.WriteLine(json);\n\n        var deserialized = serializer.Deserialize<Dictionary<string, object>>(json);\n        Console.WriteLine(deserialized[\"2\"]);\n\n        var jsonObject = serializer.DeserializeObject(@\"{ \"\"foo\"\": 1, \"\"bar\"\": [10, \"\"apples\"\"] }\");\n        var data = jsonObject as Dictionary<string, object>;\n        var array = data[\"bar\"] as object[];\n        Console.WriteLine(array[1]);\n    }\n}\n\n","human_summarization":"\"Loads a JSON string into a data structure, creates a new data structure and serializes it into JSON using JavaScriptSerializer class from .NET 3.5, ensuring the JSON is valid.\"","id":3358}
    {"lang_cluster":"C#","source_code":"\n\nstatic void Main(string[] args)\n{\n\tConsole.WriteLine(NthRoot(81,2,.001));\n        Console.WriteLine(NthRoot(1000,3,.001));\n        Console.ReadLine();\n}\n\npublic static double NthRoot(double A,int n,  double p)\n{\n\tdouble _n= (double) n;\n\tdouble[] x = new double[2];\t\t\n\tx[0] = A;\n\tx[1] = A\/_n;\n\twhile(Math.Abs(x[0] -x[1] ) > p)\n\t{\n\t\tx[1] = x[0];\n\t\tx[0] = (1\/_n)*(((_n-1)*x[1]) + (A\/Math.Pow(x[1],_n-1)));\n\t\t\t\n\t}\n\treturn x[0];\n}\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":3359}
    {"lang_cluster":"C#","source_code":"\nSystem.Net.Dns.GetHostName();\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":3360}
    {"lang_cluster":"C#","source_code":"\nWorks with: C sharp version 7\nusing System;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main() {\n        Console.WriteLine(string.Join(\" \", Leonardo().Take(25)));\n        Console.WriteLine(string.Join(\" \", Leonardo(L0: 0, L1: 1, add: 0).Take(25)));\n    }\n\n    public static IEnumerable<int> Leonardo(int L0 = 1, int L1 = 1, int add = 1) {\n        while (true) {\n            yield return L0;\n            (L0, L1) = (L1, L0 + L1 + add);\n        }\n    }\n}\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":3361}
    {"lang_cluster":"C#","source_code":"public class MathParser : I24MathParser {\n\t\/\/used to translate brackets to implied multiplication - i.e. \"3(4)5(6)\" will be interpreted as \"3*(4)*5*(6)\"\n\tprivate const string bracketsPattern = @\"(?<=[0-9)])(?<rightSide>\\()|(?<=\\))(?<rightSide>[0-9])\";\n\t\t\n\t\/\/finds multiplication or division sub expression - i.e. \"4*8-4*2)\" yields {\"4*8\", \"4*2\"}\n\tprivate const string multiplyDividePattern = @\"[0-9]+[\/*][0-9]+\";\n\t\t\n\t\/\/finds bracketed expressions - i.e. \"(4+30)(10-1)\" yields {\"4+30\", \"10-1\"}\n\tprivate const string subExpressionPattern = @\"\\(([0-9\/*\\-+]*)\\)\";\n\t\t\n\t\/\/splits expression into it elements - i.e. \"4+-30-4.123\" yields {\"4\", \"+\", \"-30\" ,\"-\", \"4.123\"}\n\tprivate const string tokenPattern = @\"(?:(?<=[\/*\\-+]|^)[+-]?)?(?:[0-9]+(?:\\.[0-9]*)?)|[\/*\\-+]\";\n\n\tRegex brackets;\n\tRegex multiplyDivide;\n\tRegex subExpression;\n\tRegex token;\n\n\n\tpublic MathParser() {\n\t\t\/\/initialize reusable regular expressions\n\t\tbrackets = new Regex(bracketsPattern, RegexOptions.Compiled);\n\t\tsubExpression = new Regex(subExpressionPattern, RegexOptions.Compiled);\n\t\ttoken = new Regex(tokenPattern, RegexOptions.Compiled);\n\t\tmultiplyDivide = new Regex(multiplyDividePattern, RegexOptions.Compiled);\n\t}\n\n\tpublic float Evaluate(string input) {\n\t\t\/\/brackets with no operator implies multiplication\n\t\tstring equation = brackets.Replace(input, \"*${rightSide}\");\n\t\tfloat answer = Solve(equation);\n\t\t\t\n\t\treturn answer;\n\t}\n\n\tfloat Solve(string equation) {\n\t\t\/\/carry out order of operations\n\t\t\/\/\tbracketed subexpressions - for any operator\n\t\tequation = SolveSubExpressions(subExpression, equation);\n\n\t\t\/\/\tmultiplication and division\n\t\tequation = SolveSubExpressions(multiplyDivide, equation);\n\n\t\t\/\/\taddition and subtraction\n\t\tfloat answer = ParseEquation(equation);\n\n\t\treturn answer;\n\t}\n\t\t\n\tstring SolveSubExpressions(Regex subExpression, string equation) {\n\t\tfloat subResult;\n\t\tMatch match = subExpression.Match(equation);\n\n\t\twhile (match.Success) {\n\t\t\tif (match.Groups[1].Length > 0) {\n\t\t\t\t\/\/recursively solve for subexpressions -- match group 1 excludes outer brackets\n\t\t\t\tsubResult = Solve(match.Groups[1].Value);\n\t\t\t}\n\t\t\telse {\n\t\t\t\t\/\/no more nested expressions - get final result for this subExpression\n\t\t\t\tsubResult = ParseEquation(match.Value);\n\t\t\t}\n\n\n\t\t\t\/\/replace subexpression with resolved answer\n\t\t\tequation = equation.Replace(match.Value, subResult.ToString());\n\n\t\t\t\/\/retest updated equation string\n\t\t\tmatch = subExpression.Match(equation);\n\t\t}\n\n\t\treturn equation;\n\t}\n\n\n\tfloat ParseEquation(string equation) {\n\t\tMatch match = token.Match(equation);\n\t\tfloat leftSide = leftSide = float.Parse(match.Value);\n\t\tstring symbol;\n\t\tfloat rightSide;\n\t\tmatch = match.NextMatch();\n\n\t\twhile (match.Success) {\n\t\t\tsymbol = match.Value;\n\t\t\tmatch = match.NextMatch();\n\n\t\t\tif (match.Success)\n\t\t\t{\n\t\t\t\trightSide = float.Parse(match.Value);\n\t\t\t\tleftSide = Calculate(leftSide, symbol, rightSide);\n\t\t\t\tmatch = match.NextMatch();\n\t\t\t}\n\t\t} \n\n\t\treturn leftSide;\n\t}\n\n\n\tfloat Calculate(float leftSide, string symbol, float rightSide) {\n\t\tfloat answer;\n\n\t\tswitch (symbol) {\n\t\t\tcase \"\/\":\n\t\t\t\tanswer = leftSide \/ rightSide;\n\t\t\t\tbreak;\n\n\t\t\tcase \"*\":\n\t\t\t\tanswer = leftSide * rightSide;\n\t\t\t\tbreak;\n\n\t\t\tcase \"-\":\n\t\t\t\tanswer = leftSide - rightSide;\n\t\t\t\tbreak;\n\n\t\t\tcase \"+\":\n\t\t\t\tanswer = leftSide + rightSide;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tthrow new ArgumentException();\n\t\t}\n\n\t\treturn answer;\n\t}\n}\n\nclass TwentyFourGame {\n\t\/\/puzzle parameters\n\tprivate const int listSize = 4;\n\tprivate const int minValue = 1;\n\tprivate const int maxValue = 9;\n\n\t\/\/signals end of game\n\tprivate const string quitToken = \"Q\";\n\n\t\/\/the only valid puzzle solution\n\tprivate const float targetValue = 24;\n\n\t\/\/Regular Expressions for evaluating math input\n\tprivate const string dictionaryBlacklistPattern = @\"[^1-9\/*\\-+()]\";\n\tprivate const string inputDigitsPattern = @\"(?:(?<=[+-]|^)[+-]?)?(?:[0-9]+(?:\\.[0-9]*)?)\";\n\tRegex dictionaryBlackList;\n\tRegex inputDigits;\n\tI24MathParser mathParser;\n\tpublic TwentyFourGame() {\n\t\t\/\/initialize reusable regular expressions\n\t\tdictionaryBlackList = new Regex(dictionaryBlacklistPattern, RegexOptions.Compiled);\n\t\tinputDigits = new Regex(inputDigitsPattern, RegexOptions.Compiled);\n\n\t\t\/\/define instance of math evaluator provider\n\t\t\/\/custom parser\n\t\t\/\/mathParser = new MathParser();\n\n\t\t\/\/xpath parser\n\t\tmathParser = new XPathEval();\n\t}\n\n\tstatic void Main(string[] args)\t{\n\t\tTwentyFourGame game = new TwentyFourGame();\n\t\tgame.PrintInstructions();\n\t\tgame.PlayGame();\n\t}\n\n\tvoid PlayGame()\t{\n\t\tstring input;\n\t\tbool endGame = false;\n\t\t\t\n\n\t\t\/\/repeat play cycle until user signals the end\n\t\tdo {\n\t\t\tstring puzzle = GetPuzzle();\n\t\t\tbool isValid = false;\n\n\t\t\t\/\/continue prompting user until valid input is received\n\t\t\tdo {\n\t\t\t\tfloat answer;\n\t\t\t\tstring message = String.Empty;\n\n\t\t\t\ttry {\n\t\t\t\t\t\/\/show user puzzle and get read their solution\n\t\t\t\t\tinput = GetInput(puzzle);\n\n\t\t\t\t\tif (input.Length == 0) {\n\t\t\t\t\t\t\/\/skip current puzzle - perhaps there is no solution\n\t\t\t\t\t\tisValid = true;\n\t\t\t\t\t\tmessage = \"Skipping this puzzle\";\n\t\t\t\t\t}\n\t\t\t\t\telse if (String.Compare(input, quitToken, true) == 0) {\n\t\t\t\t\t\t\/\/user wishes to quit\n\t\t\t\t\t\tisValid = true;\n\t\t\t\t\t\tmessage = \"End Game\";\n\t\t\t\t\t}\n\t\t\t\t\telse if (ValidateInput(input, puzzle)) {\n\t\t\t\t\t\t\/\/interpret user input and calculate answer\n\t\t\t\t\t\tanswer = mathParser.Evaluate(input);\n\n\t\t\t\t\t\tif (answer == targetValue) {\n\t\t\t\t\t\t\tisValid = true;\n\t\t\t\t\t\t\tmessage = String.Format(\"Good work.  {0} = {1}.\", input, answer);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tisValid = false;\n\t\t\t\t\t\t\tmessage = String.Format(\"Incorrect.  {0} = {1}.  Try again.\", input, answer);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tisValid = false;\n\t\t\t\t\t\tmessage = \"Invalid input.  Try again.\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch {\n\t\t\t\t\tmessage = \"An error occurred.  Check your input and try again.\";\n\t\t\t\t\tisValid = false;\n\t\t\t\t}\n\t\t\t\tfinally {\n\t\t\t\t\tPrintMessage(message);\n\t\t\t\t\tPrintMessage(String.Empty);\n\t\t\t\t\tPrintMessage(String.Empty);\n\t\t\t\t}\n\t\t\t} while (!isValid);\n\t\t} while (!endGame);\n\n\t\t\/\/pause\n\t\tGetInput(String.Empty);\n\t}\n\tbool ValidateInput(string input, string puzzle) {\n\t\tbool isValid;\n\n\t\tif (dictionaryBlackList.IsMatch(input)) {\n\t\t\t\/\/illegal characters used\n\t\t\tisValid = false;\n\t\t}\n\t\telse {\n\t\t\t\/\/get inputted digits and compare to those in puzzle\n\t\t\tstring inputNumbers = String.Join(\" \", from Match m in inputDigits.Matches(input) orderby float.Parse(m.Value) select m.Value);\n\n\t\t\tisValid = inputNumbers.CompareTo(puzzle) == 0;\n\t\t}\n\n\t\treturn isValid;\n\t}\n\tstring GetPuzzle() {\n\t\tint[] digits = new int[listSize];\n\n\t\t\/\/randomly choose 4 digits (from 1 to 9)\n\t\tRandom rand = new Random();\n\n\t\tfor (int i = 0; i < digits.Length; i++) {\n\t\t\tdigits[i] = rand.Next(minValue, maxValue);\n\t\t}\n\n\t\t\/\/format for display\n\t\tArray.Sort(digits);\n\t\tstring puzzle = String.Join(\" \", digits);\n\t\treturn puzzle;\n\t}\n\tstring GetInput(string prompt) {\n\t\tConsole.Write(String.Concat(prompt, \":  \"));\n\t\treturn Console.ReadLine();\n\t}\n\tvoid PrintMessage(string message) {\n\t\tConsole.WriteLine(message);\n\t}\n\tvoid PrintInstructions() {\n\t\tPrintMessage(\"--------------------------------- 24 Game ---------------------------------\");\n\t\tPrintMessage(String.Empty);\n\t\tPrintMessage(\"------------------------------- Instructions ------------------------------\");\n\t\tPrintMessage(\"Four digits will be displayed.\");\n\t\tPrintMessage(\"Enter an equation using all of those four digits that evaluates to 24\");\n\t\tPrintMessage(\"Only * \/ + - operators and () are allowed\");\n\t\tPrintMessage(\"Digits can only be used once, but in any order you need.\");\n\t\tPrintMessage(\"Digits cannot be combined - i.e.: 12 + 12 when given 1,2,2,1 is not allowed\");\n\t\tPrintMessage(\"Submit a blank line to skip the current puzzle.\");\n\t\tPrintMessage(\"Type 'Q' to quit\");\n\t\tPrintMessage(String.Empty);\n\t\tPrintMessage(\"Example: given 2 3 8 2, answer should resemble 8*3-(2-2)\");\n\t\tPrintMessage(\"---------------------------------------------------------------------------\");\n\t\tPrintMessage(String.Empty);\n\t\tPrintMessage(String.Empty);\n\t}\n}\n","human_summarization":"The code randomly selects and displays four digits from 1 to 9, prompts the player to form an arithmetic expression using these digits exactly once, and checks if the expression evaluates to 24. It supports addition, subtraction, multiplication, and division operations, and allows the use of brackets. The code does not allow forming multiple-digit numbers from the given digits. The order of the digits does not need to be preserved. The type of expression evaluator used is not specified. The code does not generate or test the feasibility of the expression.","id":3362}
    {"lang_cluster":"C#","source_code":"\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\nusing static System.Linq.Enumerable;\n\nnamespace RunLengthEncoding\n{\n    static class Program\n    {\n          public static string Encode(string input) => input.Length ==0 ? \"\" : input.Skip(1)\n            .Aggregate((t:input[0].ToString(),o:Empty<string>()),\n               (a,c)=>a.t[0]==c ? (a.t+c,a.o) : (c.ToString(),a.o.Append(a.t)),\n               a=>a.o.Append(a.t).Select(p => (key: p.Length, chr: p[0])))\n            .Select(p=> $\"{p.key}{p.chr}\")\n            .StringConcat();\n\n        public static string Decode(string input) => input\n            .Aggregate((t: \"\", o: Empty<string>()), (a, c) => !char.IsDigit(c) ? (\"\", a.o.Append(a.t+c)) : (a.t + c,a.o)).o \n            .Select(p => new string(p.Last(), int.Parse(string.Concat(p.Where(char.IsDigit)))))\n            .StringConcat();\n\n        private static string StringConcat(this IEnumerable<string> seq) => string.Concat(seq);\n        \n        public static void Main(string[] args)\n        {\n            const string  raw = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\";\n            const string encoded = \"12W1B12W3B24W1B14W\";\n\n            WriteLine($\"raw = {raw}\");\n            WriteLine($\"encoded = {encoded}\");\n            WriteLine($\"Encode(raw) = encoded = {Encode(raw)}\");\n            WriteLine($\"Decode(encode) = {Decode(encoded)}\");\n            WriteLine($\"Decode(Encode(raw)) = {Decode(Encode(raw)) == raw}\");\n            ReadLine();\n        }\n    }\n}\n\n\nraw = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nencoded = 12W1B12W3B24W1B14W\nEncode(raw) = encoded = 12W1B12W3B24W1B14W\nDecode(encode) = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nDecode(Encode(raw)) = True\n\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\nnamespace RunLengthEncoding\n{\n    static class Program\n    {\n         public static string Encode(string input) => input.Length ==0 ? \"\" : input.Skip(1)\n            .Aggregate((t:input[0].ToString(),o:Empty<string>()),\n               (a,c)=>a.t[0]==c ? (a.t+c,a.o) : (c.ToString(),a.o.Append(a.t)),\n               a=>a.o.Append(a.t).Select(p => (key: p.Length, chr: p[0])));\n\n        public static string Decode(IEnumerable<(int i , char c)> input) =>\n            string.Concat(input.Select(t => new string(t.c, t.i)));\n\n        public static void Main(string[] args)\n        {\n            const string  raw = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\";\n            var encoded = new[] { (12, 'W'), (1, 'B'), (12, 'W'), (3, 'B'), (24, 'W'), (1, 'B'), (14, 'W') };\n\n            WriteLine($\"raw = {raw}\");\n            WriteLine($\"Encode(raw) = encoded = {Encode(raw).TupleListToString()}\");\n            WriteLine($\"Decode(encoded) = {Decode(encoded)}\");\n            WriteLine($\"Decode(Encode(raw)) = {Decode(Encode(raw)) == raw}\");\n            ReadLine();\n        }\n        private static string TupleListToString(this IEnumerable<(int i, char c)> list) =>\n            string.Join(\",\", list.Select(t => $\"[{t.i},{t.c}]\"));\n    }\n}\n\n\nraw = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nEncode(raw) = encoded = [12,W],[1,B],[12,W],[3,B],[24,W],[1,B],[14,W]\nDecode(encoded) = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nDecode(Encode(raw)) = True\n\n\nusing System.Collections.Generic;\nusing System.Linq;\nusing static System.Console;\nusing static System.Text;\n\nnamespace RunLengthEncoding\n{\n    static class Program\n    {\n         public static string Encode(string input) => input.Length == 0 ? \"\" : input.Skip(1)\n          .Aggregate((len: 1, chr: input[0], sb: new StringBuilder()),\n             (a, c) => a.chr == c ? (a.len + 1, a.chr, a.sb) \n                                  : (1, c, a.sb.Append(a.len).Append(a.chr))),\n             a => a.sb.Append(a.len).Append(a.chr)))\n          .ToString();\n\n         public static string Decode(string input) => input\n           .Aggregate((t: \"\", sb: new StringBuilder()),\n             (a, c) => !char.IsDigit(c) ? (\"\", a.sb.Append(new string(c, int.Parse(a.t)))) \n                                        : (a.t + c, a.sb))\n           .sb.ToString();\n        \n        public static void Main(string[] args)\n        {\n            const string  raw = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\";\n            const string encoded = \"12W1B12W3B24W1B14W\";\n\n            WriteLine($\"raw = {raw}\");\n            WriteLine($\"encoded = {encoded}\");\n            WriteLine($\"Encode(raw) = encoded = {Encode(raw)}\");\n            WriteLine($\"Decode(encode) = {Decode(encoded)}\");\n            WriteLine($\"Decode(Encode(raw)) = {Decode(Encode(raw)) == raw}\");\n            ReadLine();\n        }\n    }\n}\n\n\nraw = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nencoded = 12W1B12W3B24W1B14W\nEncode(raw) = encoded = 12W1B12W3B24W1B14W\nDecode(encode) = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nDecode(Encode(raw)) = True\n\n\n       public static void Main(string[] args)\n       {\n           string input = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\";\n           Console.WriteLine(Encode(input));\/\/Outputs: 12W1B12W3B24W1B14W\n           Console.WriteLine(Decode(Encode(input)));\/\/Outputs: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\n           Console.ReadLine();\n       }\n       public static string Encode(string s)\n       {\n           StringBuilder sb = new StringBuilder();\n           int count = 1;\n           char current =s[0];\n           for(int i = 1; i < s.Length;i++)\n           {\n               if (current == s[i])\n               {\n                   count++;\n               }\n               else\n               {\n                   sb.AppendFormat(\"{0}{1}\", count, current);\n                   count = 1;\n                   current = s[i];\n               }\n           }\n           sb.AppendFormat(\"{0}{1}\", count, current);\n           return sb.ToString();\n       }\n       public static string Decode(string s)\n       {\n           string a = \"\";\n           int count = 0;\n           StringBuilder sb = new StringBuilder();\n           char current = char.MinValue;\n           for(int i = 0; i < s.Length; i++)\n           {\n               current = s[i];\n               if (char.IsDigit(current))\n                   a += current;\n               else\n               {\n                   count = int.Parse(a);\n                   a = \"\";\n                   for (int j = 0; j < count; j++)\n                       sb.Append(current);\n               }\n           }\n           return sb.ToString();\n       }\n\n\nusing System;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n    private delegate void fOk(bool ok, string message);\n\n    public static int Main(string[] args)\n    {\n        const string raw = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\";\n        const string code = \"12W1B12W3B24W1B14W\";\n\n        fOk Ok = delegate(bool ok, string message)\n        {\n            Console.WriteLine(\"{0}: {1}\", ok ? \"ok\" : \"not ok\", message);\n        };\n        Ok(code.Equals(Encode(raw)), \"Encode\");\n        Ok(raw.Equals(Decode(code)), \"Decode\");\n        return 0;\n    }\n\n    public static string Encode(string input)\n    {\n        return Regex.Replace(input, @\"(.)\\1*\", delegate(Match m)\n        {\n            return string.Concat(m.Value.Length, m.Groups[1].Value);\n        });\n    }\n\n    public static string Decode(string input)\n    {\n        return Regex.Replace(input, @\"(\\d+)(\\D)\", delegate(Match m)\n        {\n            return new string(m.Groups[2].Value[0], int.Parse(m.Groups[1].Value));\n        });\n    }\n}\n\n","human_summarization":"The code provides a function to perform run-length encoding on a given string of uppercase characters. It compresses repeated characters by storing the length of the run. It also provides a function to reverse this compression. The output format can vary as long as the original input can be recreated. The code also handles different scenarios such as outputting a list of tuples, using a stringbuilder for performance, and dealing with strings that contain no digits.","id":3363}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program {\n    static void Main(string[] args) {\n        var s = \"hello\";\n        Console.Write(s);\n        Console.WriteLine(\" literal\");\n        var s2 = s + \" literal\";\n        Console.WriteLine(s2);\n    }\n}\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":3364}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace URLEncode\n{\n    internal class Program\n    {\n        private static void Main(string[] args)\n        {\n            Console.WriteLine(Encode(\"http:\/\/foo bar\/\"));\n        }\n\n        private static string Encode(string uri)\n        {\n            return Uri.EscapeDataString(uri);\n        }\n    }\n}\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":3365}
    {"lang_cluster":"C#","source_code":"\nusing System;  \/\/4790@3.6\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(knapSack(15) + \"\\n\");\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) knapSack(15);\n        Console.Write(sw.Elapsed); Console.Read();    \/\/ 0.60 \u00b5s\n    }\n\n    static string knapSack(double w1)\n    {\n        int k = w.Length; var q = new double[k];\n        for (int i = 0; i < k; ) q[i] = v[i] \/ w[i++];\n        var c = new double[k];\n        Array.Copy(q, c, k); Array.Sort(c, w);\n        Array.Copy(q, c, k); Array.Sort(c, v);\n        Array.Sort(q, items);\n        string str = \"\";\n        for (k--; k >= 0; k--)\n            if (w1 - w[k] > 0) { w1 -= w[k]; str += items[k] + \"\\n\"; }\n            else break;\n        return w1 > 0 && k >= 0 ? str + items[k] : str;\n    }\n\n    static double[] w = { 3.8, 5.4, 3.6, 2.4, 4.0, 2.5, 3.7, 3.0, 5.9 },\n\n                    v = { 36, 43, 90, 45, 30, 56, 67, 95, 98 };\n\n    static string[] items = {\"beef\",\"pork\",\"ham\",\"greaves\",\"flitch\",\n                             \"brawn\",\"welt\",\"salami\",\"sausage\"};\n}\n\n\nusing System;\nclass Program\n{\n    static void Main()\n    {\n        Console.WriteLine(knapSack(15) + \"\\n\");\n        var sw = System.Diagnostics.Stopwatch.StartNew();\n        for (int i = 1000; i > 0; i--) knapSack(15);\n        Console.Write(sw.Elapsed); Console.Read();    \/\/ 0.37 \u00b5s\n    }\n\n    static string knapSack(double w1)\n    {\n        int i = 0, k = w.Length; var idx = new int[k];\n        {\n            var q = new double[k];\n            while (i < k) q[i] = v[i] \/ w[idx[i] = i++];\n            Array.Sort(q, idx);\n        }\n        string str = \"\";\n        for (k--; k >= 0; k--)\n            if (w1 > w[i = idx[k]]) { w1 -= w[i]; str += items[i] + \"\\n\"; }\n            else break;\n        return w1 > 0 && k >= 0 ? str + items[idx[k]] : str;\n    }\n\n    static double[] w = { 3.8, 5.4, 3.6, 2.4, 4.0, 2.5, 3.7, 3.0, 5.9 },\n\n                    v = { 36, 43, 90, 45, 30, 56, 67, 95, 98 };\n\n    static string[] items = {\"beef\",\"pork\",\"ham\",\"greaves\",\"flitch\",\n                             \"brawn\",\"welt\",\"salami\",\"sausage\"};\n}\n\n","human_summarization":"\"Output: The code calculates the maximum profit a thief can get by selecting and possibly cutting items from a butcher's shop, given a knapsack with a maximum capacity of 15 kg. The items' worth is proportional to their weight. The code sorts the items based on their value-to-weight ratio to optimize the selection process.\"","id":3366}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Text.RegularExpressions;\n\nnamespace Anagram\n{\n    class Program\n    {\n        const string DICO_URL = \"http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt\";\n\n        static void Main( string[] args )\n        {\n            WebRequest request = WebRequest.Create(DICO_URL);\n            string[] words;\n            using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream(), true)) {\n                words = Regex.Split(sr.ReadToEnd(), @\"\\r?\\n\");\n            }\n            var groups = from string w in words\n                         group w by string.Concat(w.OrderBy(x => x)) into c\n                         group c by c.Count() into d\n                         orderby d.Key descending\n                         select d;\n            foreach (var c in groups.First()) {\n                Console.WriteLine(string.Join(\" \", c));\n            }\n        }\n    }\n}\n\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":3367}
    {"lang_cluster":"C#","source_code":"Works with: C# version 3.0+\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static List<string> NextCarpet(List<string> carpet)\n    {\n        return carpet.Select(x => x + x + x)\n                     .Concat(carpet.Select(x => x + x.Replace('#', ' ') + x))\n                     .Concat(carpet.Select(x => x + x + x)).ToList();\n    }\n\n    static List<string> SierpinskiCarpet(int n)\n    {\n        return Enumerable.Range(1, n).Aggregate(new List<string> { \"#\" }, (carpet, _) => NextCarpet(carpet));\n    }\n\n    static void Main(string[] args)\n    {\n        foreach (string s in SierpinskiCarpet(3))\n            Console.WriteLine(s);\n    }\n}\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":3368}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Collections.Generic;\n\nnamespace Huffman_Encoding\n{\n    public class PriorityQueue<T> where T : IComparable\n    {\n        protected List<T> LstHeap = new List<T>();\n\n        public virtual int Count\n        {\n            get { return LstHeap.Count; }\n        }\n\n        public virtual void Add(T val)\n        {\n            LstHeap.Add(val);\n            SetAt(LstHeap.Count - 1, val);\n            UpHeap(LstHeap.Count - 1);\n        }\n\n        public virtual T Peek()\n        {\n            if (LstHeap.Count == 0)\n            {\n                throw new IndexOutOfRangeException(\"Peeking at an empty priority queue\");\n            }\n\n            return LstHeap[0];\n        }\n\n        public virtual T Pop()\n        {\n            if (LstHeap.Count == 0)\n            {\n                throw new IndexOutOfRangeException(\"Popping an empty priority queue\");\n            }\n\n            T valRet = LstHeap[0];\n\n            SetAt(0, LstHeap[LstHeap.Count - 1]);\n            LstHeap.RemoveAt(LstHeap.Count - 1);\n            DownHeap(0);\n            return valRet;\n        }\n\n        protected virtual void SetAt(int i, T val)\n        {\n            LstHeap[i] = val;\n        }\n\n        protected bool RightSonExists(int i)\n        {\n            return RightChildIndex(i) < LstHeap.Count;\n        }\n\n        protected bool LeftSonExists(int i)\n        {\n            return LeftChildIndex(i) < LstHeap.Count;\n        }\n\n        protected int ParentIndex(int i)\n        {\n            return (i - 1) \/ 2;\n        }\n\n        protected int LeftChildIndex(int i)\n        {\n            return 2 * i + 1;\n        }\n\n        protected int RightChildIndex(int i)\n        {\n            return 2 * (i + 1);\n        }\n\n        protected T ArrayVal(int i)\n        {\n            return LstHeap[i];\n        }\n\n        protected T Parent(int i)\n        {\n            return LstHeap[ParentIndex(i)];\n        }\n\n        protected T Left(int i)\n        {\n            return LstHeap[LeftChildIndex(i)];\n        }\n\n        protected T Right(int i)\n        {\n            return LstHeap[RightChildIndex(i)];\n        }\n\n        protected void Swap(int i, int j)\n        {\n            T valHold = ArrayVal(i);\n            SetAt(i, LstHeap[j]);\n            SetAt(j, valHold);\n        }\n\n        protected void UpHeap(int i)\n        {\n            while (i > 0 && ArrayVal(i).CompareTo(Parent(i)) > 0)\n            {\n                Swap(i, ParentIndex(i));\n                i = ParentIndex(i);\n            }\n        }\n\n        protected void DownHeap(int i)\n        {\n            while (i >= 0)\n            {\n                int iContinue = -1;\n\n                if (RightSonExists(i) && Right(i).CompareTo(ArrayVal(i)) > 0)\n                {\n                    iContinue = Left(i).CompareTo(Right(i)) < 0 ? RightChildIndex(i) : LeftChildIndex(i);\n                }\n                else if (LeftSonExists(i) && Left(i).CompareTo(ArrayVal(i)) > 0)\n                {\n                    iContinue = LeftChildIndex(i);\n                }\n\n                if (iContinue >= 0 && iContinue < LstHeap.Count)\n                {\n                    Swap(i, iContinue);\n                }\n\n                i = iContinue;\n            }\n        }\n    }\n\n    internal class HuffmanNode<T> : IComparable\n    {\n        internal HuffmanNode(double probability, T value)\n        {\n            Probability = probability;\n            LeftSon = RightSon = Parent = null;\n            Value = value;\n            IsLeaf = true;\n        }\n\n        internal HuffmanNode(HuffmanNode<T> leftSon, HuffmanNode<T> rightSon)\n        {\n            LeftSon = leftSon;\n            RightSon = rightSon;\n            Probability = leftSon.Probability + rightSon.Probability;\n            leftSon.IsZero = true;\n            rightSon.IsZero = false;\n            leftSon.Parent = rightSon.Parent = this;\n            IsLeaf = false;\n        }\n\n        internal HuffmanNode<T> LeftSon { get; set; }\n        internal HuffmanNode<T> RightSon { get; set; }\n        internal HuffmanNode<T> Parent { get; set; }\n        internal T Value { get; set; }\n        internal bool IsLeaf { get; set; }\n\n        internal bool IsZero { get; set; }\n\n        internal int Bit\n        {\n            get { return IsZero ? 0 : 1; }\n        }\n\n        internal bool IsRoot\n        {\n            get { return Parent == null; }\n        }\n\n        internal double Probability { get; set; }\n\n        public int CompareTo(object obj)\n        {\n            return -Probability.CompareTo(((HuffmanNode<T>) obj).Probability);\n        }\n    }\n\n    public class Huffman<T> where T : IComparable\n    {\n        private readonly Dictionary<T, HuffmanNode<T>> _leafDictionary = new Dictionary<T, HuffmanNode<T>>();\n        private readonly HuffmanNode<T> _root;\n\n        public Huffman(IEnumerable<T> values)\n        {\n            var counts = new Dictionary<T, int>();\n            var priorityQueue = new PriorityQueue<HuffmanNode<T>>();\n            int valueCount = 0;\n\n            foreach (T value in values)\n            {\n                if (!counts.ContainsKey(value))\n                {\n                    counts[value] = 0;\n                }\n                counts[value]++;\n                valueCount++;\n            }\n\n            foreach (T value in counts.Keys)\n            {\n                var node = new HuffmanNode<T>((double) counts[value] \/ valueCount, value);\n                priorityQueue.Add(node);\n                _leafDictionary[value] = node;\n            }\n\n            while (priorityQueue.Count > 1)\n            {\n                HuffmanNode<T> leftSon = priorityQueue.Pop();\n                HuffmanNode<T> rightSon = priorityQueue.Pop();\n                var parent = new HuffmanNode<T>(leftSon, rightSon);\n                priorityQueue.Add(parent);\n            }\n\n            _root = priorityQueue.Pop();\n            _root.IsZero = false;\n        }\n\n        public List<int> Encode(T value)\n        {\n            var returnValue = new List<int>();\n            Encode(value, returnValue);\n            return returnValue;\n        }\n\n        public void Encode(T value, List<int> encoding)\n        {\n            if (!_leafDictionary.ContainsKey(value))\n            {\n                throw new ArgumentException(\"Invalid value in Encode\");\n            }\n            HuffmanNode<T> nodeCur = _leafDictionary[value];\n            var reverseEncoding = new List<int>();\n            while (!nodeCur.IsRoot)\n            {\n                reverseEncoding.Add(nodeCur.Bit);\n                nodeCur = nodeCur.Parent;\n            }\n\n            reverseEncoding.Reverse();\n            encoding.AddRange(reverseEncoding);\n        }\n\n        public List<int> Encode(IEnumerable<T> values)\n        {\n            var returnValue = new List<int>();\n\n            foreach (T value in values)\n            {\n                Encode(value, returnValue);\n            }\n            return returnValue;\n        }\n\n        public T Decode(List<int> bitString, ref int position)\n        {\n            HuffmanNode<T> nodeCur = _root;\n            while (!nodeCur.IsLeaf)\n            {\n                if (position > bitString.Count)\n                {\n                    throw new ArgumentException(\"Invalid bitstring in Decode\");\n                }\n                nodeCur = bitString[position++] == 0 ? nodeCur.LeftSon : nodeCur.RightSon;\n            }\n            return nodeCur.Value;\n        }\n\n        public List<T> Decode(List<int> bitString)\n        {\n            int position = 0;\n            var returnValue = new List<T>();\n\n            while (position != bitString.Count)\n            {\n                returnValue.Add(Decode(bitString, ref position));\n            }\n            return returnValue;\n        }\n    }\n\n    internal class Program\n    {\n        private const string Example = \"this is an example for huffman encoding\";\n\n        private static void Main()\n        {\n            var huffman = new Huffman<char>(Example);\n            List<int> encoding = huffman.Encode(Example);\n            List<char> decoding = huffman.Decode(encoding);\n            var outString = new string(decoding.ToArray());\n            Console.WriteLine(outString == Example ? \"Encoding\/decoding worked\" : \"Encoding\/Decoding failed\");\n\n            var chars = new HashSet<char>(Example);\n            foreach (char c in chars)\n            {\n                encoding = huffman.Encode(c);\n                Console.Write(\"{0}:  \", c);\n                foreach (int bit in encoding)\n                {\n                    Console.Write(\"{0}\", bit);\n                }\n                Console.WriteLine();\n            }\n            Console.ReadKey();\n        }\n    }\n}\n\n\n","human_summarization":"The code takes a string input, calculates the frequency of each character, and generates a Huffman encoding for each character. It constructs a binary tree where each leaf node represents a character and its frequency of occurrence, and each internal node represents the sum of the frequencies of its child nodes. The code ensures that no smaller Huffman code can be a prefix of a larger one. The output is a table displaying each character and its corresponding Huffman encoding.","id":3369}
    {"lang_cluster":"C#","source_code":"\nusing System.Windows.Forms;\n\nclass RosettaForm : Form\n{\n    RosettaForm()\n    {\n        var clickCount = 0;\n\n        var label = new Label();\n        label.Text = \"There have been no clicks yet.\";\n        label.Dock = DockStyle.Top;\n        Controls.Add(label);\n\n        var button = new Button();\n        button.Text = \"Click Me\";\n        button.Dock = DockStyle.Bottom;\n        button.Click += delegate\n                        {\n                            clickCount++;\n                            label.Text = \"Number of clicks: \" + clickCount + \".\";\n                        };\n        Controls.Add(button);\n    }\n\n    static void Main()\n    {\n        Application.Run(new RosettaForm());\n    }\n}\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":3370}
    {"lang_cluster":"C#","source_code":"\nfor (int i = 10; i >= 0; i--)\n{\n   Console.WriteLine(i);\n}\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":3371}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace VigenereCipher\n{\n    class VCipher\n    {\n        public string encrypt(string txt, string pw, int d)\n        {\n            int pwi = 0, tmp;\n            string ns = \"\";\n            txt = txt.ToUpper();\n            pw = pw.ToUpper();\n            foreach (char t in txt)\n            {\n                if (t < 65) continue;\n                tmp = t - 65 + d * (pw[pwi] - 65);\n                if (tmp < 0) tmp += 26;\n                ns += Convert.ToChar(65 + ( tmp % 26) );\n                if (++pwi == pw.Length) pwi = 0;\n            }\n\n            return ns;\n        }\n    };\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            VCipher v = new VCipher();\n\n            string s0 = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\",\n                   pw = \"VIGENERECIPHER\";\n\n            Console.WriteLine(s0 + \"\\n\" + pw + \"\\n\");\n            string s1 = v.encrypt(s0, pw, 1);\n            Console.WriteLine(\"Encrypted: \" + s1);\n            s1 = v.encrypt(s1, \"VIGENERECIPHER\", -1);\n            Console.WriteLine(\"Decrypted: \" + s1);\n            Console.WriteLine(\"\\nPress any key to continue...\");\n            Console.ReadKey();\n        }\n    }\n}\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":3372}
    {"lang_cluster":"C#","source_code":"\nusing System;\n \nclass Program {\n    static void Main(string[] args) {    \n        for (int i = 2; i <= 8; i+= 2) {        \n            Console.Write(\"{0}, \", i);\n        }\n\n        Console.WriteLine(\"who do we appreciate?\");\n    }\n}\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":3373}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\n\nclass JensensDevice\n{    \n    public static double Sum(ref int i, int lo, int hi, Func<double> term)\n    {\n        double temp = 0.0;\n        for (i = lo; i <= hi; i++)\n        {\n            temp += term();\n        }\n        return temp;\n    }\n\n    static void Main()\n    {\n        int i = 0;\n        Console.WriteLine(Sum(ref i, 1, 100, () => 1.0 \/ i));\n    }\n}\n\n","human_summarization":"The code utilizes Jensen's Device, a programming technique, to calculate the 100th harmonic number. It uses call by name method for parameters in a procedure, allowing re-evaluation of expressions in the caller's context. The first parameter represents the \"bound\" variable of the summation and must be passed by name or reference. The code also demonstrates that a global variable doesn't need to use the same identifier as the formal parameter. This technique can be simulated using lambda expressions.","id":3374}
    {"lang_cluster":"C#","source_code":"\nusing System.Drawing;\nusing System.Drawing.Imaging;\nusing System.Linq;\n\nclass XORPattern\n{\n    static void Main()\n    {\n        var size = 0x100;\n        var black = Color.Black.ToArgb();\n        var palette = Enumerable.Range(black, size).Select(Color.FromArgb).ToArray();\n        using (var image = new Bitmap(size, size))\n        {\n            for (var x = 0; x < size; x++)\n            {\n                for (var y = 0; y < size; y++)\n                {\n                    image.SetPixel(x, y, palette[x ^ y]);\n                }\n            }\n            image.Save(\"XORPatternCSharp.png\", ImageFormat.Png);\n        }\n    }\n}\n\n\n","human_summarization":"generate a graphical pattern by coloring each pixel based on the value of 'x xor y' from a given color table, implementing the Munching Squares algorithm.","id":3375}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Linq;\nusing System.Text;\nusing System.Drawing;\n\nnamespace MazeGeneration\n{\n    public static class Extensions\n    {\n        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng)\n        {\n            var e = source.ToArray();\n            for (var i = e.Length - 1; i >= 0; i--)\n            {\n                var swapIndex = rng.Next(i + 1);\n                yield return e[swapIndex];\n                e[swapIndex] = e[i];\n            }\n        }\n\n        public static CellState OppositeWall(this CellState orig)\n        {\n            return (CellState)(((int) orig >> 2) | ((int) orig << 2)) & CellState.Initial;\n        }\n\n        public static bool HasFlag(this CellState cs,CellState flag)\n        {\n            return ((int)cs & (int)flag) != 0;\n        }\n    }\n\n    [Flags]\n    public enum CellState\n    {\n        Top = 1,\n        Right = 2,\n        Bottom = 4,\n        Left = 8,\n        Visited = 128,\n        Initial = Top | Right | Bottom | Left,\n    }\n\n    public struct RemoveWallAction\n    {\n        public Point Neighbour;\n        public CellState Wall;\n    }\n\n    public class Maze\n    {\n        private readonly CellState[,] _cells;\n        private readonly int _width;\n        private readonly int _height;\n        private readonly Random _rng;\n\n        public Maze(int width, int height)\n        {\n            _width = width;\n            _height = height;\n            _cells = new CellState[width, height];\n            for(var x=0; x<width; x++)\n                for(var y=0; y<height; y++)\n                    _cells[x, y] = CellState.Initial;\n            _rng = new Random();\n            VisitCell(_rng.Next(width), _rng.Next(height));\n        }\n\n        public CellState this[int x, int y]\n        {\n            get { return _cells[x,y]; }\n            set { _cells[x,y] = value; }\n        }\n\n        public IEnumerable<RemoveWallAction> GetNeighbours(Point p)\n        {\n            if (p.X > 0) yield return new RemoveWallAction {Neighbour = new Point(p.X - 1, p.Y), Wall = CellState.Left};\n            if (p.Y > 0) yield return new RemoveWallAction {Neighbour = new Point(p.X, p.Y - 1), Wall = CellState.Top};\n            if (p.X < _width-1) yield return new RemoveWallAction {Neighbour = new Point(p.X + 1, p.Y), Wall = CellState.Right};\n            if (p.Y < _height-1) yield return new RemoveWallAction {Neighbour = new Point(p.X, p.Y + 1), Wall = CellState.Bottom};\n        }\n\n        public void VisitCell(int x, int y)\n        {\n            this[x,y] |= CellState.Visited;\n            foreach (var p in GetNeighbours(new Point(x, y)).Shuffle(_rng).Where(z => !(this[z.Neighbour.X, z.Neighbour.Y].HasFlag(CellState.Visited))))\n            {\n                this[x, y] -= p.Wall;\n                this[p.Neighbour.X, p.Neighbour.Y] -= p.Wall.OppositeWall();\n                VisitCell(p.Neighbour.X, p.Neighbour.Y);\n            }\n        }\n\n        public void Display()\n        {\n            var firstLine = string.Empty;\n            for (var y = 0; y < _height; y++)\n            {\n                var sbTop = new StringBuilder();\n                var sbMid = new StringBuilder();\n                for (var x = 0; x < _width; x++)\n                {\n                    sbTop.Append(this[x, y].HasFlag(CellState.Top) ? \"+---\" : \"+   \");\n                    sbMid.Append(this[x, y].HasFlag(CellState.Left) ? \"|   \" : \"    \");\n                }\n                if (firstLine == string.Empty)\n                    firstLine = \"   \" + sbTop.ToString();\n                Debug.WriteLine(\"   \" + sbTop + \"+\");\n                Debug.WriteLine(\"   \" + sbMid + \"|\");\n            }\n            Debug.WriteLine(firstLine);\n        }\n    }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var maze = new Maze(20, 20);\n            maze.Display();\n        }\n    }\n}\n\n\n   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+\n   |           |                   |                       |                       |\n   +   +---+   +---+---+   +---+   +   +---+---+   +---+   +---+---+   +---+---+   +\n   |   |       |           |   |   |       |       |       |           |       |   |\n   +   +   +---+   +---+---+   +   +---+---+   +---+---+   +   +---+---+   +   +   +\n   |   |           |   |       |   |           |       |       |           |   |   |\n   +   +   +---+---+   +   +   +   +   +---+---+   +   +---+---+   +---+---+   +   +\n   |   |   |       |   |   |       |               |           |   |           |   |\n   +   +---+   +   +   +   +---+---+   +---+---+---+---+---+   +   +   +---+---+   +\n   |           |   |   |           |                   |   |       |   |   |       |\n   +---+---+---+   +   +---+---+   +---+---+---+---+   +   +---+---+   +   +   +---+\n   |           |   |           |               |           |           |       |   |\n   +   +---+---+---+   +   +---+---+---+---+   +   +---+---+   +---+---+   +---+   +\n   |       |           |           |       |   |   |           |       |   |       |\n   +   +   +   +---+---+---+---+   +   +   +   +   +   +---+---+   +   +   +---+   +\n   |   |       |                   |   |       |   |       |       |               |\n   +   +---+---+   +---+   +---+---+   +---+---+   +---+   +---+---+   +---+---+---+\n   |       |       |   |   |           |       |   |   |   |       |       |       |\n   +---+---+   +---+   +   +   +---+---+   +---+   +   +   +   +   +---+---+   +   +\n   |           |           |       |   |           |   |       |               |   |\n   +   +---+---+   +---+---+---+   +   +   +---+---+   +---+---+---+---+---+---+   +\n   |       |       |           |   |   |       |                               |   |\n   +   +   +   +---+   +---+   +   +   +---+   +---+---+   +---+---+---+---+---+   +\n   |   |   |   |       |   |       |       |   |           |                       |\n   +   +   +---+   +---+   +---+---+   +   +   +   +---+---+   +---+---+---+---+   +\n   |   |           |                   |   |       |       |   |               |   |\n   +   +---+---+---+---+---+   +---+---+   +   +---+   +   +   +   +   +---+---+   +\n   |   |       |           |   |       |   |   |       |       |   |   |       |   |\n   +   +   +   +---+   +   +   +   +---+   +   +   +---+---+---+   +---+   +   +   +\n   |       |       |   |       |   |       |   |           |   |           |       |\n   +---+---+---+   +   +---+---+   +   +---+   +---+---+   +   +   +---+---+---+---+\n   |           |   |       |           |       |   |       |       |       |       |\n   +   +---+   +   +   +   +   +---+---+   +---+   +   +---+   +---+   +---+   +   +\n   |   |   |       |   |   |           |   |       |   |   |   |       |       |   |\n   +   +   +---+---+---+   +---+---+---+   +   +---+   +   +   +   +   +   +---+   +\n   |       |           |               |       |       |   |   |   |           |   |\n   +---+   +---+   +   +---+---+---+   +---+   +   +---+   +   +---+---+---+---+   +\n   |   |           |   |           |           |   |   |       |                   |\n   +   +---+---+---+   +   +---+   +---+---+---+   +   +   +---+   +---+---+---+   +\n   |                       |                       |               |               |\n   +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts at a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, then recurses with the neighbor as the new current cell.","id":3376}
    {"lang_cluster":"C#","source_code":"\nLibrary: System.Numericsusing System;\nusing System.Numerics;\n\nnamespace PiCalc {\n    internal class Program {\n        private readonly BigInteger FOUR = new BigInteger(4);\n        private readonly BigInteger SEVEN = new BigInteger(7);\n        private readonly BigInteger TEN = new BigInteger(10);\n        private readonly BigInteger THREE = new BigInteger(3);\n        private readonly BigInteger TWO = new BigInteger(2);\n\n        private BigInteger k = BigInteger.One;\n        private BigInteger l = new BigInteger(3);\n        private BigInteger n = new BigInteger(3);\n        private BigInteger q = BigInteger.One;\n        private BigInteger r = BigInteger.Zero;\n        private BigInteger t = BigInteger.One;\n\n        public void CalcPiDigits() {\n            BigInteger nn, nr;\n            bool first = true;\n            while (true) {\n                if ((FOUR*q + r - t).CompareTo(n*t) == -1) {\n                    Console.Write(n);\n                    if (first) {\n                        Console.Write(\".\");\n                        first = false;\n                    }\n                    nr = TEN*(r - (n*t));\n                    n = TEN*(THREE*q + r)\/t - (TEN*n);\n                    q *= TEN;\n                    r = nr;\n                } else {\n                    nr = (TWO*q + r)*l;\n                    nn = (q*(SEVEN*k) + TWO + r*l)\/(t*l);\n                    q *= k;\n                    t *= l;\n                    l += TWO;\n                    k += BigInteger.One;\n                    n = nn;\n                    r = nr;\n                }\n            }\n        }\n\n        private static void Main(string[] args) {\n            new Program().CalcPiDigits();\n        }\n    }\n}\n\n\nLibrary: System.Numerics\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Numerics;\n\nnamespace EnumeratePi {\n  class Program {\n    private const int N = 60;\n    private const string ZS = \" +-\";\n    static void Main() {\n      Console.WriteLine(\"Digits of PI\");\n      Console.WriteLine(new string('=', N + 13));\n\n      Console.WriteLine(\"Decimal   \u00a0: {0}\", string.Concat(PiDigits(10).Take(N).Select(_ => _.ToString(\"d\"))));\n      Console.WriteLine(\"Binary    \u00a0: {0}\", string.Concat(PiDigits(2).Take(N).Select(_ => _.ToString(\"d\"))));\n      Console.WriteLine(\"Quaternary\u00a0: {0}\", string.Concat(PiDigits(4).Take(N).Select(_ => _.ToString(\"d\"))));\n      Console.WriteLine(\"Octal     \u00a0: {0}\", string.Concat(PiDigits(8).Take(N).Select(_ => _.ToString(\"d\"))));\n      Console.WriteLine(\"Hexadecimal: {0}\", string.Concat(PiDigits(16).Take(N).Select(_ => _.ToString(\"x\"))));\n      Console.WriteLine(\"Alphabetic\u00a0: {0}\", string.Concat(PiDigits(26).Take(N).Select(_ => (char) ('A' + _))));\n      Console.WriteLine(\"Fun       \u00a0: {0}\", string.Concat(PiDigits(ZS.Length).Take(N).Select(_ => ZS[(int)_])));\n\n      Console.WriteLine(\"Nibbles   \u00a0: {0}\", string.Concat(PiDigits(0x10).Take(N\/2).Select(_ => string.Format(\"{0:x1} \", _))));\n      Console.WriteLine(\"Bytes     \u00a0: {0}\", string.Concat(PiDigits(0x100).Take(N\/3).Select(_ => string.Format(\"{0:x2} \", _))));\n      Console.WriteLine(\"Words     \u00a0: {0}\", string.Concat(PiDigits(0x10000).Take(N\/5).Select(_ => string.Format(\"{0:x4} \", _))));\n      Console.WriteLine(\"Dwords    \u00a0: {0}\", string.Concat(PiDigits(0x100000000).Take(N\/9).Select(_ => string.Format(\"{0:x8} \", _))));\n\n      Console.WriteLine(new string('=', N + 13));\n      Console.WriteLine(\"* press any key to exit *\");\n      Console.ReadKey();\n    }\n\n    \/\/\/ <summary>Enumerates the digits of PI.<\/summary>\n    \/\/\/ <param name=\"b\">Base of the Numeral System to use for the resulting digits (default = Base.Decimal (10)).<\/param>\n    \/\/\/ <returns>The digits of PI.<\/returns>\n    static IEnumerable<long> PiDigits(long b = 10) {\n      BigInteger\n        k = 1,\n        l = 3,\n        n = 3,\n        q = 1,\n        r = 0,\n        t = 1\n        ;\n\n      \/\/ skip integer part\n      var nr = b * (r - t * n);\n      n = b * (3 * q + r) \/ t - b * n;\n      q *= b;\n      r = nr;\n\n      for (; ; ) {\n        var tn = t * n;\n        if (4 * q + r - t < tn) {\n          yield return (long)n;\n          nr = b * (r - tn);\n          n = b * (3 * q + r) \/ t - b * n;\n          q *= b;\n        } else {\n          t *= l;\n          nr = (2 * q + r) * l;\n          var nn = (q * (7 * k) + 2 + r * l) \/ t;\n          q *= k;\n          l += 2;\n          ++k;\n          n = nn;\n        }\n        r = nr;\n      }\n    }\n  }\n}\n\n\n","human_summarization":"continuously calculate and display the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The codes also relate to the task of calculating Pi using arithmetic-geometric mean.","id":3377}
    {"lang_cluster":"C#","source_code":"\nnamespace RosettaCode.OrderTwoNumericalLists\n{\n    using System;\n    using System.Collections.Generic;\n\n    internal static class Program\n    {\n        private static bool IsLessThan(this IEnumerable<int> enumerable,\n            IEnumerable<int> otherEnumerable)\n        {\n            using (\n                IEnumerator<int> enumerator = enumerable.GetEnumerator(),\n                    otherEnumerator = otherEnumerable.GetEnumerator())\n            {\n                while (true)\n                {\n                    if (!otherEnumerator.MoveNext())\n                    {\n                        return false;\n                    }\n\n                    if (!enumerator.MoveNext())\n                    {\n                        return true;\n                    }\n\n                    if (enumerator.Current == otherEnumerator.Current)\n                    {\n                        continue;\n                    }\n\n                    return enumerator.Current < otherEnumerator.Current;\n                }\n            }\n        }\n\n        private static void Main()\n        {\n            Console.WriteLine(\n                new[] {1, 2, 1, 3, 2}.IsLessThan(new[] {1, 2, 0, 4, 4, 0, 0, 0}));\n        }\n    }\n}\n\n\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise.\"","id":3378}
    {"lang_cluster":"C#","source_code":"\nusing System;\nclass Program\n{\n    public static long Ackermann(long m, long n)\n    {\n        if(m > 0)\n        {\n            if (n > 0)\n                return Ackermann(m - 1, Ackermann(m, n - 1));\n            else if (n == 0)\n                return Ackermann(m - 1, 1);\n        }\n        else if(m == 0)\n        {\n            if(n >= 0) \n                return n + 1;\n        }\n\n        throw new System.ArgumentOutOfRangeException();\n    }\n    \n    static void Main()\n    {\n        for (long m = 0; m <= 3; ++m)\n        {\n            for (long n = 0; n <= 4; ++n)\n            {\n                Console.WriteLine(\"Ackermann({0}, {1}) = {2}\", m, n, Ackermann(m, n));\n            }\n        }\n    }\n}\n\n\n","human_summarization":"implement the Ackermann function, a non-primitive recursive function that takes two non-negative arguments and returns a value based on the provided conditions. The function is designed to handle large values due to the rapid growth of the function. The implementation is optimized for efficiency, particularly in C#, and can handle the computation of Ack(4,2) when executed in Visual Studio. It also includes a reference to System.Numerics for arbitrary precision.","id":3379}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\nusing System.Numerics;\n\nstatic int g = 7;\nstatic double[] p = {0.99999999999980993, 676.5203681218851, -1259.1392167224028,\n\t     771.32342877765313, -176.61502916214059, 12.507343278686905,\n\t     -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7};\n\t\t \nComplex Gamma(Complex z)\n{\n    \/\/ Reflection formula\n    if (z.Real < 0.5)\n\t{\n        return Math.PI \/ (Complex.Sin( Math.PI * z) * Gamma(1 - z));\n\t}\n    else\n\t{\n        z -= 1;\n        Complex x = p[0];\n        for (var i = 1; i < g + 2; i++)\n\t\t{\n            x += p[i]\/(z+i);\n\t\t}\n        Complex t = z + g + 0.5;\n        return Complex.Sqrt(2 * Math.PI) * (Complex.Pow(t, z + 0.5)) * Complex.Exp(-t) * x;\n\t}\n}\n\n","human_summarization":"implement an algorithm to compute the Gamma function using numerical integration, Lanczos approximation, and Stirling's approximation. The results are then compared with the built-in\/library function if available. The codes also work with complex numbers as well as reals.","id":3380}
    {"lang_cluster":"C#","source_code":"\nWorks with: C# version 7\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\nusing static System.Console;\nusing static System.Math;\n\nnamespace N_Queens\n{\n    static class Program\n    {\n        static void Main(string[] args)\n        {\n            var n = 8;\n            var cols = Range(0, n);\n            var combs = cols.Combinations(2).Select(pairs=> pairs.ToArray());\n            var solved = from v in cols.Permutations().Select(p => p.ToArray())\n                         where combs.All(c => Abs(v[c[0]] - v[c[1]]) != Abs(c[0] - c[1]))\n                         select v;\n            \n            WriteLine($\"{n}-queens has {solved.Count()} solutions\");\n            WriteLine(\"Position is row, value is column:-\");\n            var first = string.Join(\" \", solved.First());\n            WriteLine($\"First Solution: {first}\");\n            Read();\n        }\n\n        \/\/Helpers \n        public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n        {\n            if (values.Count() == 1)\n                return values.ToSingleton();\n\n            return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())), (v, p) => p.Prepend(v));\n        }\n\n        public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq) =>\n            seq.Aggregate(Empty<T>().ToSingleton(), (a, b) => a.Concat(a.Select(x => x.Append(b))));\n\n        public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> seq, int numItems) =>\n            seq.Combinations().Where(s => s.Count() == numItems);\n\n        public static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; }\n    }\n}\n\n\n8-queens has 92 solutions\nPosition is row, value is column:-\nFirst Solution: 0 4 7 5 2 6 1 3\n\n\nusing System.Collections.Generic;\nusing static System.Linq.Enumerable;\nusing static System.Console;\nusing static System.Math;\n\nnamespace N_Queens\n{\n    static class Program\n    {\n        static void Main(string[] args)\n        {\n            var n = 8;\n            var cols = Range(0, n);\n            var solved = from v in cols.Permutations().Select(p => p.ToArray())\n                         where n == (from i in cols select v[i]+i).Distinct().Count()\n                         where n == (from i in cols select v[i]-i).Distinct().Count()\n                         select v;\n\n            WriteLine($\"{n}-queens has {solved.Count()} solutions\");\n            WriteLine(\"Position is row, value is column:-\");\n            var first = string.Join(\" \", solved.First());\n            WriteLine($\"First Solution: {first}\");\n            Read();\n        }\n\n        \/\/Helpers from https:\/\/gist.github.com\/martinfreedman\/139dd0ec7df4737651482241e48b062f\n\n        public static IEnumerable<IEnumerable<T>> Permutations<T>(this IEnumerable<T> values)\n        {\n            if (values.Count() == 1)\n                return values.ToSingleton();\n\n            return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())), (v, p) => p.Prepend(v));\n        }\n\n        public static IEnumerable<T> ToSingleton<T>(this T item) { yield return item; }\n    }\n}\n\n\nWorks with: C# version 7.1\nusing static System.Linq.Enumerable;\nusing static System.Console;\n\nnamespace N_Queens\n{\n    static class Program\n    {\n        static void Main(string[] args)\n        {\n            var n = 8;\n            var domain = Range(0, n).ToArray();\n\n            var amb = new Amb.Amb();\n            var queens = domain.Select(_ => amb.Choose(domain)).ToArray();\n            amb.Require(() => n == queens.Select(q=> q.Value).Distinct().Count());\n            amb.Require(() => n == domain.Select(i=> i + queens[i].Value).Distinct().Count());\n            amb.Require(() => n == domain.Select(i=> i - queens[i].Value).Distinct().Count());\n\n            if (amb.Disambiguate())\n            {\n                WriteLine(\"Position is row, value is column:-\");\n                WriteLine(string.Join(\" \", queens.AsEnumerable()));\n            }\n            else\n                WriteLine(\"amb is angry\");\n            Read();\n        }\n    }\n}\n\n","human_summarization":"\"Implement a solution for the N-queens problem, which extends the eight queens puzzle to a board of size NxN. The solution involves generating permutations of column indices to represent queen placements, and then eliminating those that place two queens on the same diagonal. The code uses a backtracking algorithm with lambdas and the Amb C# class for this purpose. However, due to the specification of the Amb challenge, it only produces one solution, not 92.\"","id":3381}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace RosettaCode\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] a = { 1, 2, 3 };\n            int[] b = { 4, 5, 6 };\n\n            int[] c = new int[a.Length + b.Length];\n            a.CopyTo(c, 0);\n            b.CopyTo(c, a.Length);\n\n            foreach(int n in c)\n            {\n                Console.WriteLine(n.ToString());\n            }\n        }\n    }\n}\n\n\nWorks with: C# version 3\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        int[] a = { 1, 2, 3 };\n        int[] b = { 4, 5, 6 };\n\n        int[] c = a.Concat(b).ToArray();\n    }\n}\n\n","human_summarization":"demonstrate how to concatenate two arrays either directly or using LINQ extension methods.","id":3382}
    {"lang_cluster":"C#","source_code":"\nLibrary: System\nLibrary: System.Collections.Generic\nusing System;\nusing System.Collections.Generic;\n\nnamespace Tests_With_Framework_4\n{\n\nclass Bag : IEnumerable<Bag.Item>\n        {\n            List<Item> items;\n            const int MaxWeightAllowed = 400;\n\n            public Bag()\n            {\n                items = new List<Item>();\n            }\n\n            void AddItem(Item i)\n            {\n                if ((TotalWeight + i.Weight) <= MaxWeightAllowed)\n                    items.Add(i);\n            }\n\n            public void Calculate(List<Item> items)\n            {\n                foreach (Item i in Sorte(items))\n                {\n                    AddItem(i);\n                }\n            }\n\n            List<Item> Sorte(List<Item> inputItems)\n            {\n                List<Item> choosenItems = new List<Item>();\n                for (int i = 0; i < inputItems.Count; i++)\n                {\n                    int j = -1;\n                    if (i == 0)\n                    {\n                        choosenItems.Add(inputItems[i]);\n                    }\n                    if (i > 0)\n                    {\n                        if (!RecursiveF(inputItems, choosenItems, i, choosenItems.Count - 1, false, ref j))\n                        {\n                            choosenItems.Add(inputItems[i]);\n                        }\n                    }\n                }\n                return choosenItems;\n            }\n\n            bool RecursiveF(List<Item> knapsackItems, List<Item> choosenItems, int i, int lastBound, bool dec, ref int indxToAdd)\n            {\n                if (!(lastBound < 0))\n                {\n                    if ( knapsackItems[i].ResultWV < choosenItems[lastBound].ResultWV )\n                    {\n                        indxToAdd = lastBound;\n                    }\n                    return RecursiveF(knapsackItems, choosenItems, i, lastBound - 1, true, ref indxToAdd);\n                }\n                if (indxToAdd > -1)\n                {\n                    choosenItems.Insert(indxToAdd, knapsackItems[i]);\n                    return true;\n                }\n                return false;\n            }\n\n            #region IEnumerable<Item> Members\n            IEnumerator<Item> IEnumerable<Item>.GetEnumerator()\n            {\n                foreach (Item i in items)\n                    yield return i;\n            }\n            #endregion\n\n            #region IEnumerable Members\n            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n            {\n                return items.GetEnumerator();\n            }\n            #endregion\n\n            public int TotalWeight\n            {\n                get\n                {\n                    var sum = 0;\n                    foreach (Item i in this)\n                    {\n                        sum += i.Weight;\n                    }\n                    return sum;\n                }\n            }\n\n            public class Item\n            {\n                public string Name { get; set; } public int Weight { get; set; } public int Value { get; set; } public int ResultWV { get { return  Weight-Value; } }\n                public override string ToString()\n                {\n                    return \"Name\u00a0: \" + Name + \"        Wieght\u00a0: \" + Weight + \"       Value\u00a0: \" + Value + \"     ResultWV\u00a0: \" + ResultWV;\n                }\n            }\n        }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {List<Bag.Item> knapsackItems = new List<Bag.Item>();\n            knapsackItems.Add(new Bag.Item() { Name = \"Map\", Weight = 9, Value = 150 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Water\", Weight = 153, Value = 200 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Compass\", Weight = 13, Value = 35 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sandwitch\", Weight = 50, Value = 160 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Glucose\", Weight = 15, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Tin\", Weight = 68, Value = 45 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Banana\", Weight = 27, Value = 60 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Apple\", Weight = 39, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Cheese\", Weight = 23, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Beer\", Weight = 52, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Suntan Cream\", Weight = 11, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Camera\", Weight = 32, Value = 30 });\n            knapsackItems.Add(new Bag.Item() { Name = \"T-shirt\", Weight = 24, Value = 15 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Trousers\", Weight = 48, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Umbrella\", Weight = 73, Value = 40 });\n            knapsackItems.Add(new Bag.Item() { Name = \"WaterProof Trousers\", Weight = 42, Value = 70 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Note-Case\", Weight = 22, Value = 80 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Sunglasses\", Weight = 7, Value = 20 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Towel\", Weight = 18, Value = 12 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Socks\", Weight = 4, Value = 50 });\n            knapsackItems.Add(new Bag.Item() { Name = \"Book\", Weight = 30, Value = 10 });\n            knapsackItems.Add(new Bag.Item() { Name = \"waterproof overclothes \", Weight = 43, Value = 75 });\n\n            Bag b = new Bag();\n            b.Calculate(knapsackItems);\n            b.All(x => { Console.WriteLine(x); return true; });\n            Console.WriteLine(b.Sum(x => x.Weight));\n            Console.ReadKey();\n        }\n    }\n}\n\n\n\nusing System;\t\t\/\/ Knapsack C# binary DANILIN\nusing System.Text;\t\/\/ rextester.com\/YRFA61366\nnamespace Knapsack \n{ \nclass Knapsack  \n    { \n    static void Main()\n        { \n            int n = 7; \n            int Inside = 5; \n            int all=Convert.ToInt32(Math.Pow(2,(n+1))); \n            int[] mass = new int[n]; \n            int[] cost = new int[n]; \n            int[] jack = new int[n]; \n            int[] quality = new int[all]; \n            int[] amount = new int[all];   \n            int i; \t\t\t\/\/ circle\n            int k; \t\t\t\/\/ circle\n            int dec;  \n            string[] bin = new string[all]; \n            int list; \n            int max;\n            int max_num;\n            Random rand = new Random();\n\n            for (i=0; i<n; i++)\n            {\n                mass[i]=1+rand.Next(3);\n                cost[i]=10+rand.Next(9);\n                Console.WriteLine(\"{0} {1} {2}\", i+1, mass[i], cost[i]); \n            } \n            Console.WriteLine();\n\n            for (list = all-1; list>(all-1)\/2; list--) \n            { \n                dec=list; \n                while (dec > 0)\n                { \n                    bin[list] = dec % 2 + bin[list]; \/\/ from 10 to 2 \n                    dec\/=2; \n                }\n                if (bin[list] == \"\") \n                {\n                    bin[list] = \"0\";\n                }\n                bin[list]=bin[list].Substring(1,bin[list].Length-1); \n                for (k=0; k<n; k++) \/\/ inside 01\n                {\n                    jack[k]=Convert.ToInt32(bin[list].Substring(k,1));\n                    quality[list]=quality[list]+mass[k]*jack[k]*cost[k]; \t\/\/ integral of costs\n                    amount[list]=amount[list]+mass[k]*jack[k]; \t\/\/ integral of mass\n                }        \n                if (amount[list]<= Inside)\t\t\/\/ current mass < Knapsack\n                { \n                    Console.WriteLine(\"{0} {1} {2} {3}\", Inside, amount[list], quality[list], bin[list]); \n                } \n            } \n            Console.WriteLine();\n\n            max=0; \n            max_num=1;\n            for (i=0; i < all; i++)\n            { \n                if (amount[i]<=Inside && quality[i]>max)\n                { \n                    max = quality[i]; max_num =i ;\n                }\n            }\n            Console.WriteLine(\"{0} {1} {2}\",amount[max_num],quality[max_num],bin[max_num]);\n        }\n    }\n}\n\n\n","human_summarization":"implement a solution for the 0-1 Knapsack problem to determine the maximum value of items a tourist can carry in his knapsack without exceeding a weight limit of 4kg. The solution also incorporates a Russian Binary cipher to optimize the number of comparisons from N! to 2^N. The items' weights and values are represented in a table, and only whole units of any item can be taken.","id":3383}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\nusing System.Collections.Generic;\n\nnamespace StableMarriage\n{\n    class Person\n    {\n        private int _candidateIndex;\n        public string Name { get; set; }\n        public List<Person> Prefs { get; set; }\n        public Person Fiance { get; set; }\n        \n        public Person(string name) {\n            Name = name;\n            Prefs = null;\n            Fiance = null;\n            _candidateIndex = 0;\n        }\n        public bool Prefers(Person p) {\n            return Prefs.FindIndex(o => o == p) < Prefs.FindIndex(o => o == Fiance);\n        }\n        public Person NextCandidateNotYetProposedTo() {\n            if (_candidateIndex >= Prefs.Count) return null;\n            return Prefs[_candidateIndex++];\n        }\n        public void EngageTo(Person p) {\n            if (p.Fiance != null) p.Fiance.Fiance = null;\n            p.Fiance = this;\n            if (Fiance != null) Fiance.Fiance = null;\n            Fiance = p;\n        }\n    }\n    \n    static class MainClass\n    {\n        static public bool IsStable(List<Person> men) {\n            List<Person> women = men[0].Prefs;\n            foreach (Person guy in men) {\n                foreach (Person gal in women) {\n                    if (guy.Prefers(gal) && gal.Prefers(guy))\n                        return false;\n                }\n            }\n            return true;\n        }\n        \n        static void DoMarriage() {\n            Person abe  = new Person(\"abe\");\n            Person bob  = new Person(\"bob\");\n            Person col  = new Person(\"col\");\n            Person dan  = new Person(\"dan\");\n            Person ed   = new Person(\"ed\");\n            Person fred = new Person(\"fred\");\n            Person gav  = new Person(\"gav\");\n            Person hal  = new Person(\"hal\");\n            Person ian  = new Person(\"ian\");\n            Person jon  = new Person(\"jon\");\n            Person abi  = new Person(\"abi\");\n            Person bea  = new Person(\"bea\");\n            Person cath = new Person(\"cath\");\n            Person dee  = new Person(\"dee\");\n            Person eve  = new Person(\"eve\");\n            Person fay  = new Person(\"fay\");\n            Person gay  = new Person(\"gay\");\n            Person hope = new Person(\"hope\");\n            Person ivy  = new Person(\"ivy\");\n            Person jan  = new Person(\"jan\");\n            \n            abe.Prefs  = new List<Person>() {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay};\n            bob.Prefs  = new List<Person>() {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay};\n            col.Prefs  = new List<Person>() {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan};\n            dan.Prefs  = new List<Person>() {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi};\n            ed.Prefs   = new List<Person>() {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay};\n            fred.Prefs = new List<Person>() {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay};\n            gav.Prefs  = new List<Person>() {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay};\n            hal.Prefs  = new List<Person>() {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee};\n            ian.Prefs  = new List<Person>() {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve};\n            jon.Prefs  = new List<Person>() {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope};\n            abi.Prefs  = new List<Person>() {bob, fred, jon, gav, ian, abe, dan, ed, col, hal};\n            bea.Prefs  = new List<Person>() {bob, abe, col, fred, gav, dan, ian, ed, jon, hal};\n            cath.Prefs = new List<Person>() {fred, bob, ed, gav, hal, col, ian, abe, dan, jon};\n            dee.Prefs  = new List<Person>() {fred, jon, col, abe, ian, hal, gav, dan, bob, ed};\n            eve.Prefs  = new List<Person>() {jon, hal, fred, dan, abe, gav, col, ed, ian, bob};\n            fay.Prefs  = new List<Person>() {bob, abe, ed, ian, jon, dan, fred, gav, col, hal};\n            gay.Prefs  = new List<Person>() {jon, gav, hal, fred, bob, abe, col, ed, dan, ian};\n            hope.Prefs = new List<Person>() {gav, jon, bob, abe, ian, dan, hal, ed, col, fred};\n            ivy.Prefs  = new List<Person>() {ian, col, hal, gav, fred, bob, abe, ed, jon, dan};\n            jan.Prefs  = new List<Person>() {ed, hal, gav, abe, bob, jon, col, ian, fred, dan};\n            \n            List<Person> men = new List<Person>(abi.Prefs);\n            \n            int freeMenCount = men.Count;\n            while (freeMenCount > 0) {\n                foreach (Person guy in men) {\n                    if (guy.Fiance == null) {\n                        Person gal = guy.NextCandidateNotYetProposedTo();\n                        if (gal.Fiance == null) {\n                            guy.EngageTo(gal);\n                            freeMenCount--;\n                        } else if (gal.Prefers(guy)) {\n                            guy.EngageTo(gal);\n                        }\n                    }\n                }\n            }\n            \n            foreach (Person guy in men) {\n                Console.WriteLine(\"{0} is engaged to {1}\", guy.Name, guy.Fiance.Name);\n            }\n            Console.WriteLine(\"Stable = {0}\", IsStable(men));\n            \n            Console.WriteLine(\"\\nSwitching fred & jon's partners\");\n            Person jonsFiance = jon.Fiance;\n            Person fredsFiance = fred.Fiance;\n            fred.EngageTo(jonsFiance);\n            jon.EngageTo(fredsFiance);\n            Console.WriteLine(\"Stable = {0}\", IsStable(men));\n        }\n        \n        public static void Main(string[] args)\n        {\n            DoMarriage();\n        }\n    }\n}\n\n\n","human_summarization":"The code implements the Gale-Shapley algorithm to solve the Stable Marriage problem. It takes as input ten males and ten females along with their ranked preferences for each other. The algorithm then generates a stable set of engagements where no individual prefers someone else over their current partner. The code also includes a functionality to perturb this stable set to create an unstable set and check its stability.","id":3384}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program\n{\n    static bool a(bool value)\n    {\n        Console.WriteLine(\"a\");\n        return value;\n    }\n\n    static bool b(bool value)\n    {\n        Console.WriteLine(\"b\");\n        return value;\n    }\n\n    static void Main()\n    {\n        foreach (var i in new[] { false, true })\n        {\n            foreach (var j in new[] { false, true })\n            {\n                Console.WriteLine(\"{0} and {1} = {2}\", i, j, a(i) && b(j));\n                Console.WriteLine();\n                Console.WriteLine(\"{0} or {1} = {2}\", i, j, a(i) || b(j));\n                Console.WriteLine();\n            }\n        }\n    }\n}\n\n\n","human_summarization":"create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.","id":3385}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Collections.Generic;\n\nnamespace Morse\n{\n    class Morse\n    {\n        static void Main(string[] args)\n        {\n            string word = \"sos\";\n            Dictionary<string, string> Codes = new Dictionary<string, string>\n            {\n                {\"a\", \".-   \"}, {\"b\", \"-... \"}, {\"c\", \"-.-. \"}, {\"d\", \"-..  \"}, \n                {\"e\", \".    \"}, {\"f\", \"..-. \"}, {\"g\", \"--.  \"}, {\"h\", \".... \"},\n                {\"i\", \"..   \"}, {\"j\", \".--- \"}, {\"k\", \"-.-  \"}, {\"l\", \".-.. \"},\n                {\"m\", \"--   \"}, {\"n\", \"-.   \"}, {\"o\", \"---  \"}, {\"p\", \".--. \"}, \n                {\"q\", \"--.- \"}, {\"r\", \".-.  \"}, {\"s\", \"...  \"}, {\"t\", \"-    \"}, \n                {\"u\", \"..-  \"}, {\"v\", \"...- \"}, {\"w\", \".--  \"}, {\"x\", \"-..- \"}, \n                {\"y\", \"-.-- \"}, {\"z\", \"--.. \"}, {\"0\", \"-----\"}, {\"1\", \".----\"}, \n                {\"2\", \"..---\"}, {\"3\", \"...--\"}, {\"4\", \"....-\"}, {\"5\", \".....\"}, \n                {\"6\", \"-....\"}, {\"7\", \"--...\"}, {\"8\", \"---..\"}, {\"9\", \"----.\"}    \n            };\n\n            foreach (char c in word.ToCharArray())\n            {\n                string rslt = Codes[c.ToString()].Trim();\n                foreach (char c2 in rslt.ToCharArray())\n                {\n                    if (c2 == '.')\n                        Console.Beep(1000, 250);\n                    else\n                        Console.Beep(1000, 750);\n                }\n                System.Threading.Thread.Sleep(50);\n            }\n        }\n    }\n}\n\n","human_summarization":"<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":3386}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\nusing System.IO;\n\/\/ Needed for the method.\nusing System.Text.RegularExpressions;\nusing System.Collections.Generic;\n\nvoid Main()\n{\n   string blocks = \"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\";\n   List<string> words = new List<string>() {\n      \"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"CONFUSE\"\n   };\n\n   foreach(var word in words)\n   {\n      Console.WriteLine(\"{0}: {1}\", word, CheckWord(blocks, word));\n   }\n}\n\nbool CheckWord(string blocks, string word)\n{\n   for(int i = 0; i < word.Length; ++i)\n   {\n      int length = blocks.Length;\n      Regex rgx = new Regex(\"([a-z]\"+word[i]+\"|\"+word[i]+\"[a-z])\", RegexOptions.IgnoreCase);\n      blocks = rgx.Replace(blocks, \"\", 1);\n      if(blocks.Length == length) return false;\n   }\n   return true;\n}\n\n\n","human_summarization":"The code defines a function that checks if a given word can be spelled using a collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive. It uses regular expressions to perform the check and its time complexity is approximately m*(n - (m-1)\/2), where n is the length of the blocks string and m is the length of the word string. The function is unoptimized.","id":3387}
    {"lang_cluster":"C#","source_code":"\nusing System.Text;\nusing System.Security.Cryptography;\n\nbyte[] data = Encoding.ASCII.GetBytes(\"The quick brown fox jumped over the lazy dog's back\");\nbyte[] hash = MD5.Create().ComputeHash(data);\nConsole.WriteLine(BitConverter.ToString(hash).Replace(\"-\", \"\").ToLower());\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":3388}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.Linq;\nusing System.Collections.Generic;\n\npublic class Program\n{\n    public static void Main() {\n        var oids = new [] {\n            \"1.3.6.1.4.1.11.2.17.19.3.4.0.10\",\n            \"1.3.6.1.4.1.11.2.17.5.2.0.79\",\n            \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\",\n            \"1.3.6.1.4.1.11150.3.4.0.1\",\n            \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\",\n            \"1.3.6.1.4.1.11150.3.4.0\"\n        };\n\n        var comparer = Comparer<string>.Create((a, b) => {\n            int c = a.Split('.').Select(int.Parse)\n\t        .Zip(b.Split('.').Select(int.Parse),\n                    (i, j) => i.CompareTo(j)).FirstOrDefault(x => x != 0);\n            return c != 0 ? c : a.Length.CompareTo(b.Length);\n        });\n\n        Array.Sort(oids, comparer);\n\n        Console.WriteLine(string.Join(Environment.NewLine, oids));\n    }\n}\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":3389}
    {"lang_cluster":"C#","source_code":"\nusing System;\nusing System.IO;\nusing System.Net.Sockets;\n\nclass Program {\n    static void Main(string[] args) {\n        TcpClient tcp = new TcpClient(\"localhost\", 256);\n        StreamWriter writer = new StreamWriter(tcp.GetStream());\n\n        writer.Write(\"hello socket world\");\n        writer.Flush();\n\n        tcp.Close();\n    }\n}\n\n\nusing System.Text;\nusing System.Net.Sockets;\n\nnamespace SocketClient\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n            sock.Connect(\"127.0.0.1\", 1000);\n            sock.Send(Encoding.ASCII.GetBytes(\"Hell, world!\"));\n            sock.Close();\n        }\n    }\n}\n\n","human_summarization":"\"Opens a socket to localhost on port 256, sends the message 'hello socket world', and then closes the socket without exception handling.\"","id":3390}
    {"lang_cluster":"C#","source_code":"\nWorks with: Mono version 1.2\nWorks with: Visual C# version 2003\nstatic void Main(string[] args)\n{\n    \/\/First of all construct the SMTP client\n\n    SmtpClient SMTP = new SmtpClient(\"smtp.gmail.com\", 587); \/\/I have provided the URI and port for GMail, replace with your providers SMTP details\n    SMTP.EnableSsl = true; \/\/Required for gmail, may not for your provider, if your provider does not require it then use false.\n    SMTP.DeliveryMethod = SmtpDeliveryMethod.Network;\n    SMTP.Credentials = new NetworkCredential(\"YourUserName\", \"YourPassword\");\n    MailMessage Mail = new MailMessage(\"yourEmail@address.com\", \"theirEmail@address.com\");\n\n\n    \/\/Then we construct the message\n\n    Mail.Subject = \"Important Message\";\n    Mail.Body = \"Hello over there\"; \/\/The body contains the string for your email\n    \/\/using \"Mail.IsBodyHtml = true;\" you can put an HTML page in your message body\n\n    \/\/Then we use the SMTP client to send the message\n\n    SMTP.Send(Mail);\n\n    Console.WriteLine(\"Message Sent\");\n}\n\n","human_summarization":"Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.","id":3391}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nclass Program\n{\n    static void Main()\n    {\n        var number = 0;\n        do\n        {\n            Console.WriteLine(Convert.ToString(number, 8));\n        } while (++number > 0);\n    }\n}\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":3392}
    {"lang_cluster":"C#","source_code":"\nWorks with: C# version 2.0+\n\nstatic void Swap<T>(ref T a, ref T b)\n{\n    T temp = a;\n    a = b;\n    b = temp;\n}\n\n\nint a = 1;\nint b = 2;\nSwap(ref a, ref b); \/\/ Type parameter is inferred.\n\nWorks with: C# version 7.0+\n\nint a = 1;\nint b = 2;\n(a, b) = (b, a);\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of any two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain constraints for type compatibility. The implementation utilizes the concept of generics introduced in C# 2.0 and the support for tuples in C# 7.0.","id":3393}
    {"lang_cluster":"C#","source_code":"\n\nusing System;\n\nclass Program\n{\n    static string Reverse(string value)\n    {\n        char[] chars = value.ToCharArray();\n        Array.Reverse(chars);\n        return new string(chars);\n    }\n\n    static bool IsPalindrome(string value)\n    {\n        return value == Reverse(value);\n    }\n\n    static void Main(string[] args)\n    {\n        Console.WriteLine(IsPalindrome(\"ingirumimusnocteetconsumimurigni\"));\n    }\n}\n\n\nusing System;\nusing System.Linq;\n\nclass Program\n{\n\tstatic bool IsPalindrome(string text)\n\t{\n\t\treturn text == new String(text.Reverse().ToArray());\n\t}\n\n\tstatic void Main(string[] args)\n\t{\n\t\tConsole.WriteLine(IsPalindrome(\"ingirumimusnocteetconsumimurigni\"));\n\t}\n}\n\n\nusing System;\n\nstatic class Program\n{\n    \/\/As an extension method (must be declared in a static class)\n    static bool IsPalindrome(this string sentence)\n    {\n        for (int l = 0, r = sentence.Length - 1; l < r; l++, r--)\n            if (sentence[l] != sentence[r]) return false;\n        return true;\n    }\n\n    static void Main(string[] args)\n    {\n        Console.WriteLine(\"ingirumimusnocteetconsumimurigni\".IsPalindrome());\n    }\n}\n\n","human_summarization":"The code checks if a given sequence of characters (or bytes) is a palindrome, supporting Unicode characters. It also includes a function to detect inexact palindromes, ignoring white-space, punctuation, and case. The code avoids string reversal for efficiency, instead comparing characters directly.","id":3394}
    {"lang_cluster":"C#","source_code":"\nusing System;\n\nnamespace RosettaCode {\n    class Program {\n        static void Main() {\n            string temp = Environment.GetEnvironmentVariable(\"TEMP\");\n            Console.WriteLine(\"TEMP is \" + temp);\n        }\n    }\n}\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":3395}
    {"lang_cluster":"C#","source_code":"\/\/Aamrun, 11th July 2022\n\nusing System;\n\nnamespace Sudan\n{\n  class Sudan\n  {\n  \tstatic int F(int n,int x,int y) {\n  \t\tif (n == 0) {\n    \t\treturn x + y;\n  \t\t}\n \n  \t\telse if (y == 0) {\n    \t\treturn x;\n  \t\t}\n \n  \t\treturn F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y);\n\t}\n    \n    static void Main(string[] args)\n    {\n      Console.WriteLine(\"F(1,3,3) = \" + F(1,3,3));    \n    }\n  }\n}\n\n\nF(1,3,3) = 35\n\n","human_summarization":"implement the Sudan function, a non-primitive recursive function. It takes two inputs x and y, and returns their sum if the function is at the base case. If not at the base case, it recursively calls itself based on specific conditions.","id":3396}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n\n\/* to read expanded code, run through cpp | indent -st *\/\n#define DECL_STACK_TYPE(type, name)\t\t\t\t\t\\\ntypedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;\t\\\nstk_##name stk_##name##_create(size_t init_size) {\t\t\t\\\n\tstk_##name s; if (!init_size) init_size = 4;\t\t\t\\\n\ts = malloc(sizeof(struct stk_##name##_t));\t\t\t\\\n\tif (!s) return 0;\t\t\t\t\t\t\\\n\ts->buf = malloc(sizeof(type) * init_size);\t\t\t\\\n\tif (!s->buf) { free(s); return 0; }\t\t\t\t\\\n\ts->len = 0, s->alloc = init_size;\t\t\t\t\\\n\treturn s; }\t\t\t\t\t\t\t\\\nint stk_##name##_push(stk_##name s, type item) {\t\t\t\\\n\ttype *tmp;\t\t\t\t\t\t\t\\\n\tif (s->len >= s->alloc) {\t\t\t\t\t\\\n\t\ttmp = realloc(s->buf, s->alloc*2*sizeof(type));\t\t\\\n\t\tif (!tmp) return -1; s->buf = tmp;\t\t\t\\\n\t\ts->alloc *= 2; }\t\t\t\t\t\\\n\ts->buf[s->len++] = item;\t\t\t\t\t\\\n\treturn s->len; }\t\t\t\t\t\t\\\ntype stk_##name##_pop(stk_##name s) {\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\t\t\\\n\tif (!s->len) abort();\t\t\t\t\t\t\\\n\ttmp = s->buf[--s->len];\t\t\t\t\t\t\\\n\tif (s->len * 2 <= s->alloc && s->alloc >= 8) {\t\t\t\\\n\t\ts->alloc \/= 2;\t\t\t\t\t\t\\\n\t\ts->buf = realloc(s->buf, s->alloc * sizeof(type));}\t\\\n\treturn tmp; }\t\t\t\t\t\t\t\\\nvoid stk_##name##_delete(stk_##name s) {\t\t\t\t\\\n\tfree(s->buf); free(s); }\n\n#define stk_empty(s) (!(s)->len)\n#define stk_size(s) ((s)->len)\n\nDECL_STACK_TYPE(int, int)\n\nint main(void)\n{\n\tint i;\n\tstk_int stk = stk_int_create(0);\n\n\tprintf(\"pushing: \");\n\tfor (i = 'a'; i <= 'z'; i++) {\n\t\tprintf(\" %c\", i);\n\t\tstk_int_push(stk, i);\n\t}\n\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\tprintf(\"\\npoppoing:\");\n\twhile (stk_size(stk))\n\t\tprintf(\" %c\", stk_int_pop(stk));\n\tprintf(\"\\nsize now: %d\", stk_size(stk));\n\tprintf(\"\\nstack is%s empty\\n\", stk_empty(stk) ? \"\" : \" not\");\n\n\t\/* stk_int_pop(stk); <-- will abort() *\/\n\tstk_int_delete(stk);\n\treturn 0;\n}\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stddef.h>\n#include <stdbool.h>\n\n#define check_pointer(p) if (!p) {puts(\"Out of memory.\"); exit(EXIT_FAILURE);}\n\n#define MINIMUM_SIZE 1\n \/* Minimal stack size (expressed in number of elements) for which\n space is allocated. It should be at least 1. *\/\n#define GROWTH_FACTOR 2\n \/* How much more memory is allocated each time a stack grows\n out of its allocated segment. *\/\ntypedef int T;\n \/\/ The type of the stack elements.\n\ntypedef struct\n {T *bottom;\n  T *top;\n  T *allocated_top;} stack;\n\nstack * new(void)\n\/* Creates a new stack. *\/\n {stack *s = malloc(sizeof(stack));\n  check_pointer(s);\n  s->bottom = malloc(MINIMUM_SIZE * sizeof(T));\n  check_pointer(s->bottom);\n  s->top = s->bottom - 1;\n  s->allocated_top = s->bottom + MINIMUM_SIZE - 1;\n  return s;}\n\nvoid destroy(stack *s)\n\/* Frees all the memory used for a stack. *\/\n {free(s->bottom);\n  free(s);}\n\nbool empty(stack *s)\n\/* Returns true iff there are no elements on the stack. This\nis different from the stack not having enough memory reserved\nfor even one element, which case is never allowed to arise. *\/\n {return s->top < s->bottom ? true : false;}\n\nvoid push(stack *s, T x)\n\/* Puts a new element on the stack, enlarging the latter's\nmemory allowance if necessary. *\/\n {if (s->top == s->allocated_top)\n     {ptrdiff_t qtty = s->top - s->bottom + 1;\n      ptrdiff_t new_qtty = GROWTH_FACTOR * qtty;\n      s->bottom = realloc(s->bottom, new_qtty * sizeof(T));\n      check_pointer(s->bottom);\n      s->top = s->bottom + qtty - 1;\n      s->allocated_top = s->bottom + new_qtty - 1;}\n  *(++s->top) = x;}\n\nT pop(stack *s)\n\/* Removes and returns the topmost element. The result of popping\nan empty stack is undefined. *\/\n {return *(s->top--);}\n\nvoid compress(stack *s)\n\/* Frees any memory the stack isn't actually using. The\nallocated portion still isn't allowed to shrink smaller than\nMINIMUM_SIZE. If all the stack's memory is in use, nothing\nhappens. *\/\n {if (s->top == s->allocated_top) return;\n  ptrdiff_t qtty = s->top - s->bottom + 1;\n  if (qtty < MINIMUM_SIZE) qtty = MINIMUM_SIZE;\n  size_t new_size = qtty * sizeof(T);\n  s->bottom = realloc(s->bottom, new_size);\n  check_pointer(s->bottom);\n  s->allocated_top = s->bottom + qtty - 1;}\n\n","human_summarization":"implement a stack data structure with basic operations such as push (adding an element to the top of the stack), pop (removing the topmost element from the stack and returning it), and empty (checking if the stack is empty). The stack follows a Last In, First Out (LIFO) access policy.","id":3397}
    {"lang_cluster":"C","source_code":"\nlong long fibb(long long a, long long b, int n) {\n    return (--n>0)?(fibb(b, a+b, n)):(a);\n}\n\nlong long int fibb(int n) {\n\tint fnow = 0, fnext = 1, tempf;\n\twhile(--n>0){\n\t\ttempf = fnow + fnext;\n\t\tfnow = fnext;\n\t\tfnext = tempf;\n\t\t}\n\t\treturn fnext;\t\n}\n\n#include <tgmath.h>\n#define PHI ((1 + sqrt(5))\/2)\n\nlong long unsigned fib(unsigned n) {\n    return floor( (pow(PHI, n) - pow(1 - PHI, n))\/sqrt(5) );\n}\nWorks with: gcc version version 4.1.2 20080704 (Red Hat 4.1.2-44)\n#include <stdio.h>\ntypedef enum{false=0, true=!0} bool;\ntypedef void iterator;\n\n#include <setjmp.h>\n\/* declare label otherwise it is not visible in sub-scope *\/\n#define LABEL(label) jmp_buf label; if(setjmp(label))goto label;\n#define GOTO(label) longjmp(label, true)\n\n\/* the following line is the only time I have ever required \"auto\" *\/\n#define FOR(i, iterator) { auto bool lambda(i); yield_init = (void *)λ iterator; bool lambda(i)\n#define DO {\n#define     YIELD(x) if(!yield(x))return\n#define     BREAK    return false\n#define     CONTINUE return true\n#define OD CONTINUE; } }\n\nstatic volatile void *yield_init; \/* not thread safe *\/\n#define YIELDS(type) bool (*yield)(type) = yield_init\n\niterator fibonacci(int stop){\n    YIELDS(int);\n    int f[] = {0, 1};\n    int i;\n    for(i=0; i<stop; i++){\n        YIELD(f[i%2]);\n        f[i%2]=f[0]+f[1];\n    }\n}\n\nmain(){\n  printf(\"fibonacci: \");\n  FOR(int i, fibonacci(16)) DO\n    printf(\"%d, \",i);\n  OD;\n  printf(\"...\\n\");\n}\n\n\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":3398}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n\nint even_sel(int x) { return !(x & 1); }\nint tri_sel(int x) { return x % 3; }\n\n\/* using a predicate function sel() to select elements *\/\nint* grep(int *in, int len, int *outlen, int (*sel)(int), int inplace)\n{\n\tint i, j, *out;\n\n\tif (inplace)\tout = in;\n\telse\t\tout = malloc(sizeof(int) * len);\n\n\tfor (i = j = 0; i < len; i++)\n\t\tif (sel(in[i]))\n\t\t\tout[j++] = in[i];\n\n\tif (!inplace && j < len)\n\t\tout = realloc(out, sizeof(int) * j);\n\n\t*outlen = j;\n\treturn out;\n}\n\nint main()\n{\n\tint in[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n\tint i, len;\n\n\tint *even = grep(in, 10, &len, even_sel, 0);\n\tprintf(\"Filtered even:\");\n\tfor (i = 0; i < len; i++) printf(\" %d\", even[i]);\n\tprintf(\"\\n\");\n\n\tgrep(in, 8, &len, tri_sel, 1);\n\tprintf(\"In-place filtered not multiple of 3:\");\n\tfor (i = 0; i < len; i++) printf(\" %d\", in[i]);\n\n\tprintf(\"\\n\");\n\n\treturn 0;\n}\n\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":3399}
    {"lang_cluster":"C","source_code":"\n\/*\n * RosettaCode: Substring, C89\n *\n * In this task display a substring: starting from n characters in and of m\n * length; starting from n characters in, up to the end of the string; whole\n * string minus last character; starting from a known character within the\n * string and of m length; starting from a known substring within the string\n * and of m length.\n *\n * This example program DOES NOT make substrings. The program simply displays\n * certain parts of the input string.\n * \n *\/\n#define _CRT_SECURE_NO_WARNINGS \/* MSVS compilers need this *\/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\/*\n * Put no more than m characters from string to standard output.\n *\n * It is worth noting that printf(\"%*s\",width,string) does not limit the number\n * of characters to be printed.\n *\n * @param string null terminated string\n * @param m      number of characters to display\n *\/\nvoid putm(char* string, size_t m)\n{\n    while(*string && m--)\n        putchar(*string++);\n}\n\nint main(void)\n{\n\n    char string[] = \n        \"Programs for other encodings (such as 8-bit ASCII, or EUC-JP).\"\n\n    int n = 3;\n    int m = 4;\n    char knownCharacter = '(';\n    char knownSubstring[] = \"encodings\";\n\n    putm(string+n-1, m );                       putchar('\\n');\n    puts(string+n+1);                           putchar('\\n');\n    putm(string, strlen(string)-1);             putchar('\\n');\n    putm(strchr(string, knownCharacter), m );   putchar('\\n');\n    putm(strstr(string, knownSubstring), m );   putchar('\\n');\n\n    return EXIT_SUCCESS;\n}\n\n\/*\n * RosettaCode: Substring, C89, Unicode\n *\n * In this task display a substring: starting from n characters in and of m\n * length; starting from n characters in, up to the end of the string; whole\n * string minus last character; starting from a known character within the\n * string and of m length; starting from a known substring within the string\n * and of m length.\n *\n * This example program DOES NOT make substrings. The program simply displays\n * certain parts of the input string.\n * \n *\/\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\/*\n * Put all characters from string to standard output AND write newline.\n * BTW, _putws may not be avaliable.\n *\/\nvoid put(wchar_t* string)\n{\n    while(*string)\n        putwchar(*string++);\n    putwchar(L'\\n');\n}\n\n\/*\n * Put no more than m characters from string to standard output AND newline.\n *\/\nvoid putm(wchar_t* string, size_t m)\n{\n    while(*string && m--)\n        putwchar(*string++);\n    putwchar(L'\\n');\n}\n\nint main(void)\n{\n    wchar_t string[] = \n        L\"Programs for other encodings (such as 8-bit ASCII).\";\n\n    int n = 3;\n    int m = 4;\n    wchar_t knownCharacter = L'(';\n    wchar_t knownSubstring[] = L\"encodings\";\n\n    putm(string+n-1,m);                        \n    put (string+n+1);                         \n    putm(string, wcslen(string)-1);           \n    putm(wcschr(string, knownCharacter), m ); \n    putm(wcsstr(string, knownSubstring), m ); \n\n    return EXIT_SUCCESS;\n}\n\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nchar *substring(const char *s, size_t n, ptrdiff_t m)\n{\n  char *result;\n  \/* check for null s *\/\n  if (NULL == s)\n    return NULL;\n  \/* negative m to mean 'up to the mth char from right' *\/\n  if (m < 0) \n    m = strlen(s) + m - n + 1;\n\n  \/* n < 0 or m < 0 is invalid *\/\n  if (n < 0 || m < 0)\n    return NULL;\n\n  \/* make sure string does not end before n \n   * and advance the \"s\" pointer to beginning of substring *\/\n  for ( ; n > 0; s++, n--)\n    if (*s == '\\0')\n      \/* string ends before n: invalid *\/\n      return NULL;\n\n  result = malloc(m+1);\n  if (NULL == result)\n    \/* memory allocation failed *\/\n    return NULL;\n  result[0]=0;\n  strncat(result, s, m); \/* strncat() will automatically add null terminator\n                          * if string ends early or after reading m characters *\/\n  return result;\n}\n\nchar *str_wholeless1(const char *s)\n{\n  return substring(s, 0, strlen(s) - 1);\n}\n\nchar *str_fromch(const char *s, int ch, ptrdiff_t m)\n{\n  return substring(s, strchr(s, ch) - s, m);\n}\n\nchar *str_fromstr(const char *s, char *in, ptrdiff_t m)\n{\n  return substring(s, strstr(s, in) - s , m);\n}\n\n\n#define TEST(A) do {\t\t\\\n    char *r = (A);\t\t\\\n    if (NULL == r)\t\t\\\n      puts(\"--error--\");\t\\\n    else {\t\t\t\\\n      puts(r);\t\t\t\\\n      free(r);\t\t\t\\\n    }\t\t\t\t\\\n  } while(0)\n\nint main()\n{\n  const char *s = \"hello world shortest program\";\n\n  TEST( substring(s, 12, 5) );\t\t\/\/ get \"short\"\n  TEST( substring(s, 6, -1) );\t\t\/\/ get \"world shortest program\"\n  TEST( str_wholeless1(s) );\t\t\/\/ \"... progra\"\n  TEST( str_fromch(s, 'w', 5) );\t\/\/ \"world\"\n  TEST( str_fromstr(s, \"ro\", 3) );\t\/\/ \"rog\"\n\n  return 0;\n}\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":3400}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n#include <wchar.h>\n\nconst char *sa = \"abcdef\";\nconst char *su = \"as\u20dddf\u0305\"; \/* Should be in your native locale encoding. Mine is UTF-8 *\/\n\nint is_comb(wchar_t c)\n{\n\tif (c >= 0x300 && c <= 0x36f) return 1;\n\tif (c >= 0x1dc0 && c <= 0x1dff) return 1;\n\tif (c >= 0x20d0 && c <= 0x20ff) return 1;\n\tif (c >= 0xfe20 && c <= 0xfe2f) return 1;\n\treturn 0;\n}\n\nwchar_t* mb_to_wchar(const char *s)\n{\n\twchar_t *u;\n\tsize_t len = mbstowcs(0, s, 0) + 1;\n\tif (!len) return 0;\n\n\tu = malloc(sizeof(wchar_t) * len);\n\tmbstowcs(u, s, len);\n\treturn u;\n}\n\nwchar_t* ws_reverse(const wchar_t* u)\n{\n\tsize_t len, i, j;\n\twchar_t *out;\n\tfor (len = 0; u[len]; len++);\n\tout = malloc(sizeof(wchar_t) * (len + 1));\n\tout[len] = 0;\n\tj = 0;\n\twhile (len) {\n\t\tfor (i = len - 1; i && is_comb(u[i]); i--);\n\t\twcsncpy(out + j, u + i, len - i);\n\t\tj += len - i;\n\t\tlen = i;\n\t}\n\treturn out;\n}\n\nchar *mb_reverse(const char *in)\n{\n\tsize_t len;\n\tchar *out;\n\twchar_t *u = mb_to_wchar(in);\n\twchar_t *r = ws_reverse(u);\n\tlen = wcstombs(0, r, 0) + 1;\n\tout = malloc(len);\n\twcstombs(out, r, len);\n\tfree(u);\n\tfree(r);\n\treturn out;\n}\n\nint main(void)\n{\n\tsetlocale(LC_CTYPE, \"\");\n\n\tprintf(\"%s => %s\\n\", sa, mb_reverse(sa));\n\tprintf(\"%s => %s\\n\", su, mb_reverse(su));\n\treturn 0;\n}\n\n\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":3401}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <limits.h>\n\ntypedef struct {\n    int vertex;\n    int weight;\n} edge_t;\n\ntypedef struct {\n    edge_t **edges;\n    int edges_len;\n    int edges_size;\n    int dist;\n    int prev;\n    int visited;\n} vertex_t;\n\ntypedef struct {\n    vertex_t **vertices;\n    int vertices_len;\n    int vertices_size;\n} graph_t;\n\ntypedef struct {\n    int *data;\n    int *prio;\n    int *index;\n    int len;\n    int size;\n} heap_t;\n\nvoid add_vertex (graph_t *g, int i) {\n    if (g->vertices_size < i + 1) {\n        int size = g->vertices_size * 2 > i\u00a0? g->vertices_size * 2\u00a0: i + 4;\n        g->vertices = realloc(g->vertices, size * sizeof (vertex_t *));\n        for (int j = g->vertices_size; j < size; j++)\n            g->vertices[j] = NULL;\n        g->vertices_size = size;\n    }\n    if (!g->vertices[i]) {\n        g->vertices[i] = calloc(1, sizeof (vertex_t));\n        g->vertices_len++;\n    }\n}\n\nvoid add_edge (graph_t *g, int a, int b, int w) {\n    a = a - 'a';\n    b = b - 'a';\n    add_vertex(g, a);\n    add_vertex(g, b);\n    vertex_t *v = g->vertices[a];\n    if (v->edges_len >= v->edges_size) {\n        v->edges_size = v->edges_size\u00a0? v->edges_size * 2\u00a0: 4;\n        v->edges = realloc(v->edges, v->edges_size * sizeof (edge_t *));\n    }\n    edge_t *e = calloc(1, sizeof (edge_t));\n    e->vertex = b;\n    e->weight = w;\n    v->edges[v->edges_len++] = e;\n}\n\nheap_t *create_heap (int n) {\n    heap_t *h = calloc(1, sizeof (heap_t));\n    h->data = calloc(n + 1, sizeof (int));\n    h->prio = calloc(n + 1, sizeof (int));\n    h->index = calloc(n, sizeof (int));\n    return h;\n}\n\nvoid push_heap (heap_t *h, int v, int p) {\n    int i = h->index[v] == 0\u00a0? ++h->len\u00a0: h->index[v];\n    int j = i \/ 2;\n    while (i > 1) {\n        if (h->prio[j] < p)\n            break;\n        h->data[i] = h->data[j];\n        h->prio[i] = h->prio[j];\n        h->index[h->data[i]] = i;\n        i = j;\n        j = j \/ 2;\n    }\n    h->data[i] = v;\n    h->prio[i] = p;\n    h->index[v] = i;\n}\n\nint min (heap_t *h, int i, int j, int k) {\n    int m = i;\n    if (j <= h->len && h->prio[j] < h->prio[m])\n        m = j;\n    if (k <= h->len && h->prio[k] < h->prio[m])\n        m = k;\n    return m;\n}\n\nint pop_heap (heap_t *h) {\n    int v = h->data[1];\n    int i = 1;\n    while (1) {\n        int j = min(h, h->len, 2 * i, 2 * i + 1);\n        if (j == h->len)\n            break;\n        h->data[i] = h->data[j];\n        h->prio[i] = h->prio[j];\n        h->index[h->data[i]] = i;\n        i = j;\n    }\n    h->data[i] = h->data[h->len];\n    h->prio[i] = h->prio[h->len];\n    h->index[h->data[i]] = i;\n    h->len--;\n    return v;\n}\n\nvoid dijkstra (graph_t *g, int a, int b) {\n    int i, j;\n    a = a - 'a';\n    b = b - 'a';\n    for (i = 0; i < g->vertices_len; i++) {\n        vertex_t *v = g->vertices[i];\n        v->dist = INT_MAX;\n        v->prev = 0;\n        v->visited = 0;\n    }\n    vertex_t *v = g->vertices[a];\n    v->dist = 0;\n    heap_t *h = create_heap(g->vertices_len);\n    push_heap(h, a, v->dist);\n    while (h->len) {\n        i = pop_heap(h);\n        if (i == b)\n            break;\n        v = g->vertices[i];\n        v->visited = 1;\n        for (j = 0; j < v->edges_len; j++) {\n            edge_t *e = v->edges[j];\n            vertex_t *u = g->vertices[e->vertex];\n            if (!u->visited && v->dist + e->weight <= u->dist) {\n                u->prev = i;\n                u->dist = v->dist + e->weight;\n                push_heap(h, e->vertex, u->dist);\n            }\n        }\n    }\n}\n\nvoid print_path (graph_t *g, int i) {\n    int n, j;\n    vertex_t *v, *u;\n    i = i - 'a';\n    v = g->vertices[i];\n    if (v->dist == INT_MAX) {\n        printf(\"no path\\n\");\n        return;\n    }\n    for (n = 1, u = v; u->dist; u = g->vertices[u->prev], n++)\n       \u00a0;\n    char *path = malloc(n);\n    path[n - 1] = 'a' + i;\n    for (j = 0, u = v; u->dist; u = g->vertices[u->prev], j++)\n        path[n - j - 2] = 'a' + u->prev;\n    printf(\"%d\u00a0%.*s\\n\", v->dist, n, path);\n}\n\nint main () {\n    graph_t *g = calloc(1, sizeof (graph_t));\n    add_edge(g, 'a', 'b', 7);\n    add_edge(g, 'a', 'c', 9);\n    add_edge(g, 'a', 'f', 14);\n    add_edge(g, 'b', 'c', 10);\n    add_edge(g, 'b', 'd', 15);\n    add_edge(g, 'c', 'd', 11);\n    add_edge(g, 'c', 'f', 2);\n    add_edge(g, 'd', 'e', 6);\n    add_edge(g, 'e', 'f', 9);\n    dijkstra(g, 'a', 'e');\n    print_path(g, 'e');\n    return 0;\n}\n\n","human_summarization":"Implement Dijkstra's algorithm to determine the shortest path from a given source node to all other nodes in a directed, weighted graph. The algorithm outputs a set of edges representing the shortest path to each reachable node. It also includes functionality to interpret the output and display the shortest path from the source node to specific nodes. The graph's vertices and edges are represented using either numbers or names. The priority queue used in the algorithm is implemented as a binary heap.","id":3402}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\nstruct node {\n\tint payload;\n\tint height;\n\tstruct node * kid[2];\n} dummy = { 0, 0, {&dummy, &dummy} }, *nnil = &dummy;\n\/\/ internally, nnil is the new nul\n\nstruct node *new_node(int value)\n{\n\tstruct node *n = calloc(1, sizeof *n);\n\t*n = (struct node) { value, 1, {nnil, nnil} };\n\treturn n;\n}\n\nint max(int a, int b) { return a > b ? a : b; }\ninline void set_height(struct node *n) {\n\tn->height = 1 + max(n->kid[0]->height, n->kid[1]->height);\n}\n\ninline int ballance(struct node *n) {\n\treturn n->kid[0]->height - n->kid[1]->height;\n}\n\n\/\/ rotate a subtree according to dir; if new root is nil, old root is freed\nstruct node * rotate(struct node **rootp, int dir)\n{\n\tstruct node *old_r = *rootp, *new_r = old_r->kid[dir];\n\n\tif (nnil == (*rootp = new_r))\n\t\tfree(old_r);\n\telse {\n\t\told_r->kid[dir] = new_r->kid[!dir];\n\t\tset_height(old_r);\n\t\tnew_r->kid[!dir] = old_r;\n\t}\n\treturn new_r;\n}\n\nvoid adjust_balance(struct node **rootp)\n{\n\tstruct node *root = *rootp;\n\tint b = ballance(root)\/2;\n\tif (b) {\n\t\tint dir = (1 - b)\/2;\n\t\tif (ballance(root->kid[dir]) == -b)\n\t\t\trotate(&root->kid[dir], !dir);\n\t\troot = rotate(rootp, dir);\n\t}\n\tif (root != nnil) set_height(root);\n}\n\n\/\/ find the node that contains value as payload; or returns 0\nstruct node *query(struct node *root, int value)\n{\n\treturn root == nnil\n\t\t? 0\n\t\t: root->payload == value\n\t\t\t? root\n\t\t\t: query(root->kid[value > root->payload], value);\n}\n\nvoid insert(struct node **rootp, int value)\n{\n\tstruct node *root = *rootp;\n\n\tif (root == nnil)\n\t\t*rootp = new_node(value);\n\telse if (value != root->payload) { \/\/ don't allow dup keys\n\t\tinsert(&root->kid[value > root->payload], value);\n\t\tadjust_balance(rootp);\n\t}\n}\n\nvoid delete(struct node **rootp, int value)\n{\n\tstruct node *root = *rootp;\n\tif (root == nnil) return; \/\/ not found\n\n\t\/\/ if this is the node we want, rotate until off the tree\n\tif (root->payload == value)\n\t\tif (nnil == (root = rotate(rootp, ballance(root) < 0)))\n\t\t\treturn;\n\n\tdelete(&root->kid[value > root->payload], value);\n\tadjust_balance(rootp);\n}\n\n\/\/ aux display and verification routines, helpful but not essential\nstruct trunk {\n\tstruct trunk *prev;\n\tchar * str;\n};\n\nvoid show_trunks(struct trunk *p)\n{\n\tif (!p) return;\n\tshow_trunks(p->prev);\n\tprintf(\"%s\", p->str);\n}\n\n\/\/ this is very haphazzard\nvoid show_tree(struct node *root, struct trunk *prev, int is_left)\n{\n\tif (root == nnil) return;\n\n\tstruct trunk this_disp = { prev, \"    \" };\n\tchar *prev_str = this_disp.str;\n\tshow_tree(root->kid[0], &this_disp, 1);\n\n\tif (!prev)\n\t\tthis_disp.str = \"---\";\n\telse if (is_left) {\n\t\tthis_disp.str = \".--\";\n\t\tprev_str = \"   |\";\n\t} else {\n\t\tthis_disp.str = \"`--\";\n\t\tprev->str = prev_str;\n\t}\n\n\tshow_trunks(&this_disp);\n\tprintf(\"%d\n\", root->payload);\n\n\tif (prev) prev->str = prev_str;\n\tthis_disp.str = \"   |\";\n\n\tshow_tree(root->kid[1], &this_disp, 0);\n\tif (!prev) puts(\"\");\n}\n\nint verify(struct node *p)\n{\n\tif (p == nnil) return 1;\n\n\tint h0 = p->kid[0]->height, h1 = p->kid[1]->height;\n\tint b = h0 - h1;\n\n\tif (p->height != 1 + max(h0, h1) || b < -1 || b > 1) {\n\t\tprintf(\"node %d bad, balance %d\n\", p->payload, b);\n\t\tshow_tree(p, 0, 0);\n\t\tabort();\n\t}\n\treturn verify(p->kid[0]) && verify(p->kid[1]);\n}\n\n#define MAX_VAL 32\nint main(void)\n{\n\tint x;\n\tstruct node *root = nnil;\n\n\tsrand(time(0));\n\n\tfor (x = 0; x < 10 * MAX_VAL; x++) {\n\t\t\/\/ random insertion and deletion\n\t\tif (rand()&1)\tinsert(&root, rand()%MAX_VAL);\n\t\telse\t\tdelete(&root, rand()%MAX_VAL);\n\n\t\tverify(root);\n\t}\n\n\tputs(\"Tree is:\");\n\tshow_tree(root, 0, 0);\n\n\tputs(\"\nQuerying values:\");\n\tfor (x = 0; x < MAX_VAL; x++) {\n\t\tstruct node *p = query(root, x);\n\t\tif (p)\tprintf(\"%2d found: %p %d\n\", x, p, p->payload);\n\t}\n\n\tfor (x = 0; x < MAX_VAL; x++) {\n\t\tdelete(&root, x);\n\t\tverify(root);\n\t}\n\n\tputs(\"\nAfter deleting all values, tree is:\");\n\tshow_tree(root, 0, 0);\n\n\treturn 0;\n}","human_summarization":"Implement an AVL tree, a self-balancing binary search tree where the heights of two child subtrees of any node differ by at most one. The code includes operations for lookup, insertion, and deletion, all of which take O(log n) time. The tree is rebalanced as needed through tree rotations. Duplicate node keys are not allowed. The code also provides comparison with red-black trees.","id":3403}
    {"lang_cluster":"C","source_code":"\n#include<stdio.h>\n#include<math.h>\n\ntypedef struct{\n\tdouble x,y;\n\t}point;\n\t\ndouble distance(point p1,point p2)\n{\n\treturn sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));\n}\n\t\nvoid findCircles(point p1,point p2,double radius)\n{\n\tdouble separation = distance(p1,p2),mirrorDistance;\n\t\n\tif(separation == 0.0)\n\t{\n\t\tradius == 0.0 ? printf(\"\\nNo circles can be drawn through (%.4f,%.4f)\",p1.x,p1.y):\n\t\t\t\t\t\t\t printf(\"\\nInfinitely many circles can be drawn through (%.4f,%.4f)\",p1.x,p1.y);\n\t}\n\t\n\telse if(separation == 2*radius)\n\t{\n\t\tprintf(\"\\nGiven points are opposite ends of a diameter of the circle with center (%.4f,%.4f) and radius\u00a0%.4f\",(p1.x+p2.x)\/2,(p1.y+p2.y)\/2,radius); \n\t}\n\t\n\telse if(separation > 2*radius)\n\t{\n\t\tprintf(\"\\nGiven points are farther away from each other than a diameter of a circle with radius\u00a0%.4f\",radius);\n\t}   \n\t\n\telse\n\t{\n\t\tmirrorDistance =sqrt(pow(radius,2) - pow(separation\/2,2));\n\t\t\n\t\tprintf(\"\\nTwo circles are possible.\");\n\t\tprintf(\"\\nCircle C1 with center (%.4f,%.4f), radius\u00a0%.4f and Circle C2 with center (%.4f,%.4f), radius\u00a0%.4f\",(p1.x+p2.x)\/2 + mirrorDistance*(p1.y-p2.y)\/separation,(p1.y+p2.y)\/2 + mirrorDistance*(p2.x-p1.x)\/separation,radius,(p1.x+p2.x)\/2 - mirrorDistance*(p1.y-p2.y)\/separation,(p1.y+p2.y)\/2 - mirrorDistance*(p2.x-p1.x)\/separation,radius);\n\t}\n}\n\nint main()\n{\n    int i;\n\n    point cases[] = \t\n    {\t{0.1234, 0.9876},    {0.8765, 0.2345},  \n\t{0.0000, 2.0000},    {0.0000, 0.0000},   \n\t{0.1234, 0.9876},    {0.1234, 0.9876},   \n\t{0.1234, 0.9876},    {0.8765, 0.2345},    \n\t{0.1234, 0.9876},    {0.1234, 0.9876}\n    };\n\n    double radii[] = {2.0,1.0,2.0,0.5,0.0};\n\n    for(i=0;i<5;i++)\n    {\t\n\tprintf(\"\\nCase %d)\",i+1);\n\tfindCircles(cases[2*i],cases[2*i+1],radii[i]);\n    }\n\n    return 0;\n}\n\n\ntest run:\nCase 1)\nTwo circles are possible.\nCircle C1 with center (1.8631,1.9742), radius 2.0000 and Circle C2 with center (-0.8632,-0.7521), radius 2.0000\nCase 2)\nGiven points are opposite ends of a diameter of the circle with center (0.0000,1.0000) and radius 1.0000\nCase 3)\nInfinitely many circles can be drawn through (0.1234,0.9876)\nCase 4)\nGiven points are farther away from each other than a diameter of a circle with radius 0.5000\nCase 5)\nNo circles can be drawn through (0.1234,0.9876)\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":3404}
    {"lang_cluster":"C","source_code":"\n\nstatic unsigned char const k8[16] = {\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 }; \nstatic unsigned char const k7[16] = {\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 };\nstatic unsigned char const k6[16] = {\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 };\nstatic unsigned char const k5[16] = {\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 };\nstatic unsigned char const k4[16] = {\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 };\nstatic unsigned char const k3[16] = {\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 };\nstatic unsigned char const k2[16] = {\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 };\nstatic unsigned char const k1[16] = {\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 };\n\nstatic unsigned char k87[256];\nstatic unsigned char k65[256];\nstatic unsigned char k43[256];\nstatic unsigned char k21[256];\n\nvoid\nkboxinit(void)\n{\n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15];\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15];\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15];\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15];\n\t}\n}\n\nstatic word32\nf(word32 x)\n{\n\tx = k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t    k43[x>> 8 & 255] <<  8 | k21[x & 255];\n\treturn x<<11 | x>>(32-11);\n}\n\n","human_summarization":"implement the main step of the GOST 28147-89 encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using the replacement table, and returning an encrypted block. The version includes a packed replacement table.","id":3405}
    {"lang_cluster":"C","source_code":"\nint main(){\n\ttime_t t;\n\tint a, b;\n\tsrand((unsigned)time(&t));\n\tfor(;;){\n\t\ta = rand() % 20;\n\t\tprintf(\"%d\\n\", a);\n\t\tif(a == 10)\n\t\t\tbreak;\n\t\tb = rand() % 20;\n\t\tprintf(\"%d\\n\", b);\n\t}\n\treturn 0;\n}\n\n\n12\n18\n2\n8\n10\n18\n9\n9\n4\n10\n\n","human_summarization":"generates and prints random numbers from 0 to 19. If the generated number is 10, it stops the loop. If not, it generates and prints a second random number before restarting the loop. The loop runs indefinitely if 10 is never generated as the first number.","id":3406}
    {"lang_cluster":"C","source_code":"\nint isPrime(int n){\n\tif (n%2==0) return n==2;\n\tif (n%3==0) return n==3;\n\tint d=5;\n\twhile(d*d<=n){\n\t\tif(n%d==0) return 0;\n\t\td+=2;\n\t\tif(n%d==0) return 0;\n\t\td+=4;}\n\treturn 1;}\n\nmain() {int i,d,p,r,q=929;\n\tif (!isPrime(q)) return 1; \n\tr=q;\n\twhile(r>0) r<<=1;\n\td=2*q+1;\n\tdo { \tfor(p=r, i= 1; p; p<<= 1){\n\t\t\ti=((long long)i * i) % d;\n\t\t\tif (p < 0) i *= 2;\n\t\t\tif (i > d) i -= d;}\n\t\tif (i != 1) d += 2*q;\n\t\telse break;\n\t} while(1);\n\tprintf(\"2^%d - 1 = 0 (mod %d)\\n\", q, d);}\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":3407}
    {"lang_cluster":"C","source_code":"\nLibrary: LibXML\n\n#include <libxml\/parser.h>\n#include <libxml\/xpath.h>\n\nxmlDocPtr getdoc (char *docname) {\n\txmlDocPtr doc;\n\tdoc = xmlParseFile(docname);\n\n\treturn doc;\n}\n\nxmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){\n\t\n\txmlXPathContextPtr context;\n\txmlXPathObjectPtr result;\n\n\tcontext = xmlXPathNewContext(doc);\n\n\tresult = xmlXPathEvalExpression(xpath, context);\n\txmlXPathFreeContext(context);\n\n\treturn result;\n}\n\nint main(int argc, char **argv) {\n\n\tif (argc <= 2) {\n\t\tprintf(\"Usage: %s <XML Document Name> <XPath expression>\\n\", argv[0]);\n\t\treturn 0;\n\t}\n\t\n\tchar *docname;\n\txmlDocPtr doc;\n\txmlChar *xpath = (xmlChar*) argv[2];\n\txmlNodeSetPtr nodeset;\n\txmlXPathObjectPtr result;\n\tint i;\n\txmlChar *keyword;\n\n\tdocname = argv[1];\n\tdoc = getdoc(docname);\n\tresult = getnodeset (doc, xpath);\n\tif (result) {\n\t\tnodeset = result->nodesetval;\n\t\tfor (i=0; i < nodeset->nodeNr; i++) {\n\t\txmlNodePtr titleNode = nodeset->nodeTab[i];\n\t\tkeyword = xmlNodeListGetString(doc, titleNode->xmlChildrenNode, 1);\n\t\tprintf(\"Value %d: %s\\n\",i+1, keyword);\n\t\txmlFree(keyword);\n\t\t}\n\t\txmlXPathFreeObject (result);\n\t}\n\txmlFreeDoc(doc);\n\txmlCleanupParser();\n\treturn 0;\n}\n\n\nC:\\rosettaCode>xPather.exe testXML.xml \/\/price\nValue 1: 14.50\nValue 2: 23.99\nValue 3: 4.95\nValue 4: 3.56\n\nC:\\rosettaCode>xPather.exe testXML.xml \/\/name\nValue 1: Invisibility Cream\nValue 2: Levitation Salve\nValue 3: Blork and Freen Instameal\nValue 4: Grob winglets\n\n","human_summarization":"The code takes an XML document and XPath expressions as inputs, and performs three specific queries: retrieving the first \"item\" element, printing out each \"price\" element, and generating an array of all \"name\" elements. It also includes error handling for incorrect invocations. The XML document used for testing is stored in testXML.xml.","id":3408}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n\ntypedef unsigned int set_t; \/* probably 32 bits; change according to need *\/\n\nvoid show_set(set_t x, const char *name)\n{\n\tint i;\n\tprintf(\"%s is:\", name);\n\tfor (i = 0; (1U << i) <= x; i++)\n\t\tif (x & (1U << i))\n\t\t\tprintf(\" %d\", i);\n\tputchar('\\n');\n}\n\nint main(void)\n{\n\tint i;\n\tset_t a, b, c;\n\t\n\ta = 0; \/* empty set *\/\n\tfor (i = 0; i < 10; i += 3) \/* add 0 3 6 9 to set a *\/\n\t\ta |= (1U << i);\n\tshow_set(a, \"a\");\n\n\tfor (i = 0; i < 5; i++)\n\t\tprintf(\"\\t%d%s in set a\\n\", i, (a & (1U << i)) ? \"\":\" not\");\n\n\tb = a;\n\tb |= (1U << 5); b |= (1U << 10); \/* b is a plus 5, 10 *\/\n\tb &= ~(1U << 0);\t\/* sans 0 *\/\n\tshow_set(b, \"b\");\n\n\tshow_set(a | b, \"union(a, b)\");\n\tshow_set(c = a & b, \"c = common(a, b)\");\n\tshow_set(a & ~b, \"a - b\"); \/* diff, not arithmetic minus *\/\n\tshow_set(b & ~a, \"b - a\");\n\tprintf(\"b is%s a subset of a\\n\", !(b & ~a) ? \"\" : \" not\");\n\tprintf(\"c is%s a subset of a\\n\", !(c & ~a) ? \"\" : \" not\");\n\n\tprintf(\"union(a, b) - common(a, b) %s union(a - b, b - a)\\n\",\n\t\t((a | b) & ~(a & b)) == ((a & ~b) | (b & ~a))\n\t\t\t? \"equals\" : \"does not equal\");\n\n\treturn 0;\n}\n\n","human_summarization":"demonstrate various set operations such as set creation, checking if an element is in a set, union, intersection, difference, subset, and equality of two sets. The code also optionally shows other set operations and modifications to a mutable set. The implementation of the set can be done using an associative array, binary search tree, hash table, or binary bits. The code also considers the efficiency of the basic test operation. The type of set implementation depends on the datatype and use case. For small, non-negative integers, a bit field implementation is shown.","id":3409}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n\n\/* Calculate day of week in proleptic Gregorian calendar. Sunday == 0. *\/\nint wday(int year, int month, int day)\n{\n\tint adjustment, mm, yy;\n\n\tadjustment = (14 - month) \/ 12;\n\tmm = month + 12 * adjustment - 2;\n\tyy = year - adjustment;\n\treturn (day + (13 * mm - 1) \/ 5 +\n\t\tyy + yy \/ 4 - yy \/ 100 + yy \/ 400) % 7;\n}\n\nint main()\n{\n\tint y;\n\n\tfor (y = 2008; y <= 2121; y++) {\n\t\tif (wday(y, 12, 25) == 0) printf(\"%04d-12-25\\n\", y);\n\t}\n\n\treturn 0;\n}\n\n","human_summarization":"\"Determines the years between 2008 and 2121 where Christmas falls on a Sunday using standard date handling libraries. The program also checks for any discrepancies in date handling across different programming languages, potentially caused by issues like y2k-like overflow. Zeller's Rule is used to calculate the day of the week due to known issues with C libraries.\"","id":3410}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct {\n\tint m, n;\n\tdouble ** v;\n} mat_t, *mat;\n\nmat matrix_new(int m, int n)\n{\n\tmat x = malloc(sizeof(mat_t));\n\tx->v = malloc(sizeof(double*) * m);\n\tx->v[0] = calloc(sizeof(double), m * n);\n\tfor (int i = 0; i < m; i++)\n\t\tx->v[i] = x->v[0] + n * i;\n\tx->m = m;\n\tx->n = n;\n\treturn x;\n}\n\nvoid matrix_delete(mat m)\n{\n\tfree(m->v[0]);\n\tfree(m->v);\n\tfree(m);\n}\n\nvoid matrix_transpose(mat m)\n{\n\tfor (int i = 0; i < m->m; i++) {\n\t\tfor (int j = 0; j < i; j++) {\n\t\t\tdouble t = m->v[i][j];\n\t\t\tm->v[i][j] = m->v[j][i];\n\t\t\tm->v[j][i] = t;\n\t\t}\n\t}\n}\n\nmat matrix_copy(int n, double a[][n], int m)\n{\n\tmat x = matrix_new(m, n);\n\tfor (int i = 0; i < m; i++)\n\t\tfor (int j = 0; j < n; j++)\n\t\t\tx->v[i][j] = a[i][j];\n\treturn x;\n}\n\nmat matrix_mul(mat x, mat y)\n{\n\tif (x->n != y->m) return 0;\n\tmat r = matrix_new(x->m, y->n);\n\tfor (int i = 0; i < x->m; i++)\n\t\tfor (int j = 0; j < y->n; j++)\n\t\t\tfor (int k = 0; k < x->n; k++)\n\t\t\t\tr->v[i][j] += x->v[i][k] * y->v[k][j];\n\treturn r;\n}\n\nmat matrix_minor(mat x, int d)\n{\n\tmat m = matrix_new(x->m, x->n);\n\tfor (int i = 0; i < d; i++)\n\t\tm->v[i][i] = 1;\n\tfor (int i = d; i < x->m; i++)\n\t\tfor (int j = d; j < x->n; j++)\n\t\t\tm->v[i][j] = x->v[i][j];\n\treturn m;\n}\n\n\/* c = a + b * s *\/\ndouble *vmadd(double a[], double b[], double s, double c[], int n)\n{\n\tfor (int i = 0; i < n; i++)\n\t\tc[i] = a[i] + s * b[i];\n\treturn c;\n}\n\n\/* m = I - v v^T *\/\nmat vmul(double v[], int n)\n{\n\tmat x = matrix_new(n, n);\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < n; j++)\n\t\t\tx->v[i][j] = -2 *  v[i] * v[j];\n\tfor (int i = 0; i < n; i++)\n\t\tx->v[i][i] += 1;\n\n\treturn x;\n}\n\n\/* ||x|| *\/\ndouble vnorm(double x[], int n)\n{\n\tdouble sum = 0;\n\tfor (int i = 0; i < n; i++) sum += x[i] * x[i];\n\treturn sqrt(sum);\n}\n\n\/* y = x \/ d *\/\ndouble* vdiv(double x[], double d, double y[], int n)\n{\n\tfor (int i = 0; i < n; i++) y[i] = x[i] \/ d;\n\treturn y;\n}\n\n\/* take c-th column of m, put in v *\/\ndouble* mcol(mat m, double *v, int c)\n{\n\tfor (int i = 0; i < m->m; i++)\n\t\tv[i] = m->v[i][c];\n\treturn v;\n}\n\nvoid matrix_show(mat m)\n{\n\tfor(int i = 0; i < m->m; i++) {\n\t\tfor (int j = 0; j < m->n; j++) {\n\t\t\tprintf(\" %8.3f\", m->v[i][j]);\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\tprintf(\"\\n\");\n}\n\nvoid householder(mat m, mat *R, mat *Q)\n{\n\tmat q[m->m];\n\tmat z = m, z1;\n\tfor (int k = 0; k < m->n && k < m->m - 1; k++) {\n\t\tdouble e[m->m], x[m->m], a;\n\t\tz1 = matrix_minor(z, k);\n\t\tif (z != m) matrix_delete(z);\n\t\tz = z1;\n\n\t\tmcol(z, x, k);\n\t\ta = vnorm(x, m->m);\n\t\tif (m->v[k][k] > 0) a = -a;\n\n\t\tfor (int i = 0; i < m->m; i++)\n\t\t\te[i] = (i == k) ? 1 : 0;\n\n\t\tvmadd(x, e, a, e, m->m);\n\t\tvdiv(e, vnorm(e, m->m), e, m->m);\n\t\tq[k] = vmul(e, m->m);\n\t\tz1 = matrix_mul(q[k], z);\n\t\tif (z != m) matrix_delete(z);\n\t\tz = z1;\n\t}\n\tmatrix_delete(z);\n\t*Q = q[0];\n\t*R = matrix_mul(q[0], m);\n\tfor (int i = 1; i < m->n && i < m->m - 1; i++) {\n\t\tz1 = matrix_mul(q[i], *Q);\n\t\tif (i > 1) matrix_delete(*Q);\n\t\t*Q = z1;\n\t\tmatrix_delete(q[i]);\n\t}\n\tmatrix_delete(q[0]);\n\tz = matrix_mul(*Q, m);\n\tmatrix_delete(*R);\n\t*R = z;\n\tmatrix_transpose(*Q);\n}\n\ndouble in[][3] = {\n\t{ 12, -51,   4},\n\t{  6, 167, -68},\n\t{ -4,  24, -41},\n\t{ -1, 1, 0},\n\t{ 2, 0, 3},\n};\n\nint main()\n{\n\tmat R, Q;\n\tmat x = matrix_copy(3, in, 5);\n\thouseholder(x, &R, &Q);\n\n\tputs(\"Q\"); matrix_show(Q);\n\tputs(\"R\"); matrix_show(R);\n\n\t\/\/ to show their product is the input matrix\n\tmat m = matrix_mul(Q, R);\n\tputs(\"Q * R\"); matrix_show(m);\n\n\tmatrix_delete(x);\n\tmatrix_delete(R);\n\tmatrix_delete(Q);\n\tmatrix_delete(m);\n\treturn 0;\n}\n\n\n","human_summarization":"The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.","id":3411}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct list_node {int x; struct list_node *next;};\ntypedef struct list_node node;\n\nnode * uniq(int *a, unsigned alen)\n {if (alen == 0) return NULL;\n  node *start = malloc(sizeof(node));\n  if (start == NULL) exit(EXIT_FAILURE);\n  start->x = a[0];\n  start->next = NULL;\n\n  for (int i = 1 ; i < alen ; ++i)\n     {node *n = start;\n      for (;; n = n->next)\n         {if (a[i] == n->x) break;\n          if (n->next == NULL)\n             {n->next = malloc(sizeof(node));\n              n = n->next;\n              if (n == NULL) exit(EXIT_FAILURE);\n              n->x = a[i];\n              n->next = NULL;\n              break;}}}\n\n  return start;}\n\nint main(void)\n   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};\n    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)\n        printf(\"%d \", n->x);\n    puts(\"\");\n    return 0;}\n\n\n","human_summarization":"\"Implements a function to remove duplicate elements from an array using three different approaches: 1) Utilizing a hash table, 2) Sorting elements and removing consecutive duplicates, 3) Checking each element against the rest of the list. The function returns the result as a linked list due to unknown size of the new data structure.\"","id":3412}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nvoid quicksort(int *A, int len);\n\nint main (void) {\n  int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n  int n = sizeof a \/ sizeof a[0];\n\n  int i;\n  for (i = 0; i < n; i++) {\n    printf(\"%d \", a[i]);\n  }\n  printf(\"\\n\");\n\n  quicksort(a, n);\n\n  for (i = 0; i < n; i++) {\n    printf(\"%d \", a[i]);\n  }\n  printf(\"\\n\");\n\n  return 0;\n}\n\nvoid quicksort(int *A, int len) {\n  if (len < 2) return;\n\n  int pivot = A[len \/ 2];\n\n  int i, j;\n  for (i = 0, j = len - 1; ; i++, j--) {\n    while (A[i] < pivot) i++;\n    while (A[j] > pivot) j--;\n\n    if (i >= j) break;\n\n    int temp = A[i];\n    A[i]     = A[j];\n    A[j]     = temp;\n  }\n\n  quicksort(A, i);\n  quicksort(A + i, len - i);\n}\n\n\n","human_summarization":"implement the quicksort algorithm to sort an array or list. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them together with the pivot. The algorithm can work in place by swapping elements within the array, avoiding additional memory allocation. The pivot selection method is not specified and can vary. The code also includes a variant of quicksort that works with randomized sort and separated components.","id":3413}
    {"lang_cluster":"C","source_code":"\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n#define MAX_BUF 50\n\nint main(void)\n{\n  char buf[MAX_BUF];\n  time_t seconds = time(NULL);\n  struct tm *now = localtime(&seconds);\n  const char *months[] = {\"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n                          \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"};\n\n  const char *days[] = {\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\",\"Thursday\",\"Friday\",\"Saturday\"};\n\n  (void) printf(\"%d-%d-%d\\n\", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);\n  (void) printf(\"%s, %s %d, %d\\n\",days[now->tm_wday], months[now->tm_mon],\n               now->tm_mday, now->tm_year + 1900);\n  \/* using the strftime (the result depends on the locale) *\/\n  (void) strftime(buf, MAX_BUF, \"%A, %B %e, %Y\", now);\n  (void) printf(\"%s\\n\", buf);\n  return EXIT_SUCCESS;\n}\n\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":3414}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nstruct node {\n\tchar *s;\n\tstruct node* prev;\n};\n\nvoid powerset(char **v, int n, struct node *up)\n{\n\tstruct node me;\n\n\tif (!n) {\n\t\tputchar('[');\n\t\twhile (up) {\n\t\t\tprintf(\" %s\", up->s);\n\t\t\tup = up->prev;\n\t\t}\n\t\tputs(\" ]\");\n\t} else {\n\t\tme.s = *v;\n\t\tme.prev = up;\n\t\tpowerset(v + 1, n - 1, up);\n\t\tpowerset(v + 1, n - 1, &me);\n\t}\n}\n\nint main(int argc, char **argv)\n{\n\tpowerset(argv + 1, argc - 1, 0);\n\treturn 0;\n}\n\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":3415}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n\n\nint main() {\n    int arabic[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};\n\n    \/\/ There is a bug: \"XL\\0\" is translated into sequence 58 4C 00 00, i.e. it is 4-bytes long...\n    \/\/ Should be \"XL\" without \\0 etc.\n    \/\/\n    char roman[13][3] = {\"M\\0\", \"CM\\0\", \"D\\0\", \"CD\\0\", \"C\\0\", \"XC\\0\", \"L\\0\", \"XL\\0\", \"X\\0\", \"IX\\0\", \"V\\0\", \"IV\\0\", \"I\\0\"};\n    int N;\n\n    printf(\"Enter arabic number:\\n\");\n    scanf(\"%d\", &N);\n    printf(\"\\nRoman number:\\n\");\n\n    for (int i = 0; i < 13; i++) {\n        while (N >= arabic[i]) {\n            printf(\"%s\", roman[i]);\n            N -= arabic[i];\n        }\n    }\n    return 0;\n}\n\n\n","human_summarization":"The code takes a positive integer as input and returns its equivalent in Roman numerals as a string. It handles each digit separately, starting from the leftmost and ignoring zeros. For example, it converts 1990 to MCMXC, 2008 to MMVIII, and 1666 to MDCLXVI.","id":3416}
    {"lang_cluster":"C","source_code":"\n\nint myArray2[10] = { 1, 2, 0 }; \/* the rest of elements get the value 0 *\/\nfloat myFloats[] ={1.2, 2.5, 3.333, 4.92, 11.2, 22.0 }; \/* automatically sizes *\/\n\n\n#define MYFLOAT_SIZE (sizeof(myFloats)\/sizeof(myFloats[0]))\n\n\nlong a2D_Array[3][5];    \/* 3 rows, 5 columns. *\/\nfloat my2Dfloats[][3] = { \n   1.0, 2.0, 0.0,\n   5.0, 1.0, 3.0 };\n#define FLOAT_ROWS (sizeof(my2Dfloats)\/sizeof(my2dFloats[0]))\n\n\nint numElements = 10;\nint *myArray = malloc(sizeof(int) * numElements);  \/* array of 10 integers *\/\nif ( myArray != NULL )   \/* check to ensure allocation succeeded. *\/\n{\n  \/* allocation succeeded *\/\n  \/* at the end, we need to free the allocated memory *\/\n  free(myArray);\n}\n                    \/* calloc() additionally pre-initializes to all zeros *\/\nshort *myShorts = calloc( numElements, sizeof(short)); \/* array of 10 *\/ \nif (myShorts != NULL)....\n\n\nmyArray[0] = 1;\nmyArray[1] = 3;\n\n\nprintf(\"%d\\n\", myArray[1]);\n\n\n*(array + index) = 1;\nprintf(\"%d\\n\", *(array + index));\n3[array] = 5;\n\n\n#define XSIZE 20\ndouble *kernel = malloc(sizeof(double)*2*XSIZE+1);\nif (kernel) {\n   kernel += XSIZE;\n   for (ix=-XSIZE; ix<=XSIZE; ix++) {\n       kernel[ix] = f(ix);\n   ....\n   free(kernel-XSIZE);\n   }\n}\n\n\nint *array = malloc (sizeof(int) * 20);\n....\narray = realloc(array, sizeof(int) * 40);\n\n\n#include <stdlib.h>\n#include <stdio.h>\ntypedef struct node{\n  char value;\n  struct node* next;\n} node;\ntypedef struct charList{\n  node* first;\n  int size;\n} charList;\n\ncharList createList(){\n  charList foo = {.first = NULL, .size = 0};\n  return foo;\n}\nint addEl(charList* list, char c){\n  if(list != NULL){\n    node* foo = (node*)malloc(sizeof(node));\n    if(foo == NULL) return -1;\n    foo->value = c; foo->next = NULL;\n    if(list->first == NULL){\n      list->first = foo;\n    }else{\n      node* it= list->first;\n      while(it->next != NULL)it = it->next;\n      it->next = foo;\n    }\n    list->size = list->size+1;\n    return 0;\n  }else return -1;\n}\nint removeEl(charList* list, int index){\n    if(list != NULL && list->size > index){\n      node* it = list->first;\n      for(int i = 0; i < index-1; i++) it = it->next;\n      node* el = it->next;\n      it->next = el->next;\n      free(el);\n      list->size--;\n      return 0;\n    }else return -1;\n}\nchar getEl(charList* list, int index){\n    if(list != NULL && list->size > index){\n        node* it = list->first;\n        for(int i = 0; i < index; i++) it = it->next;\n        return it->value;\n    }else return '\\0';\n}\nstatic void cleanHelp(node* el){\n  if(el != NULL){\n    if(el->next != NULL) cleanHelp(el->next);\n    free(el);\n  }\n}\nvoid clean(charList* list){\n  cleanHelp(list->first);\n  list->size = 0;\n}\n\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. The codes create both fixed-length and dynamic arrays, assign values to them, and retrieve an element from them. It also includes the initialization of a static array of integers, handling of autosized multidimensional arrays, and dynamic allocation of arrays when size is not known at compile time. The codes also showcase the usage of malloc(), calloc() and free() functions, array indexing, and absence of bounds check on the indexes. The codes also depict how to implement negative indexing and declare arrays with runtime known size. Lastly, it demonstrates the implementation of a linked list for characters.","id":3417}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nint main(int argc, char **argv) {\n  FILE *in, *out;\n  int c;\n\n  in = fopen(\"input.txt\", \"r\");\n  if (!in) {\n    fprintf(stderr, \"Error opening input.txt for reading.\\n\");\n    return 1;\n  }\n\n  out = fopen(\"output.txt\", \"w\");\n  if (!out) {\n    fprintf(stderr, \"Error opening output.txt for writing.\\n\");\n    fclose(in);\n    return 1;\n  }\n\n  while ((c = fgetc(in)) != EOF) {\n    fputc(c, out);\n  }\n\n  fclose(out);\n  fclose(in);\n  return 0;\n}\n\n\nWorks with: POSIX\n#include <unistd.h>\n#include <fcntl.h>\n#include <sys\/types.h>\n#include <sys\/stat.h>\n\n\/* we just return a yes\/no status; caller can check errno *\/\nint copy_file(const char *in, const char *out)\n{\n\tint ret = 0;\n\tint fin, fout;\n\tssize_t len;\n\tchar *buf[4096]; \/* buffer size, some multiple of block size preferred *\/\n\tstruct stat st;\n\n\tif ((fin  = open(in,  O_RDONLY)) == -1) return 0;\n\tif (fstat(fin, &st)) goto bail;\n\n\t\/* open output with same permission *\/\n\tfout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777);\n\tif (fout == -1) goto bail;\n\n\twhile ((len = read(fin, buf, 4096)) > 0)\n\t\twrite(fout, buf, len);\n\n\tret = len ? 0 : 1; \/* last read should be 0 *\/\n\nbail:\tif (fin != -1)  close(fin);\n\tif (fout != -1) close(fout);\n\treturn ret;\n}\n\nint main()\n{\n\tcopy_file(\"infile\", \"outfile\");\n\treturn 0;\n}\n\nIf it's certain that mapping the whole input file into memory poses no problem (there can be all kinds of problems), this may be the most efficient:int copy_file(const char *in, const char *out)\n{\n\tint ret = 0;\n\tint fin, fout;\n\tchar *bi;\n\tstruct stat st;\n\n\tif ((fin  = open(in,  O_RDONLY)) == -1) return 0;\n\tif (fstat(fin, &st)) goto bail;\n\n\tfout = open(out, O_WRONLY|O_CREAT|O_TRUNC, st.st_mode & 0777);\n\tif (fout == -1) goto bail;\n\n\tbi = mmap(0, st.st_size, PROT_READ, MAP_PRIVATE, fin,  0);\n\n\tret = (bi == (void*)-1)\n\t\t? 0 : (write(fout, bi, st.st_size) == st.st_size);\n\nbail:\tif (fin != -1)  close(fin);\n\tif (fout != -1) close(fout);\n\tif (bi != (void*)-1) munmap(bi, st.st_size);\n\treturn ret;\n}\n\n","human_summarization":"demonstrate how to read the contents of \"input.txt\" file into an intermediate variable and then write those contents into a new file called \"output.txt\". The codes also show how to handle file operations efficiently by copying larger blocks of data instead of one character at a time, using POSIX functions like open(), read(), write() and close().","id":3418}
    {"lang_cluster":"C","source_code":"\n\n\/* Demonstrate toupper and tolower for \n   standard C strings.\n   This does not work for multibyte character sets. *\/\n#include <ctype.h>\n#include <stdio.h>\n\n\/* upper-cases s in place *\/\nvoid str_toupper(char *s)\n{\n    while(*s)\n    {\n        *s=toupper(*s);\n        s++;\n    }\n}\n\n\n\/* lower-cases s in place *\/\nvoid str_tolower(char *s)\n{\n    while(*s)\n    {\n        *s=tolower(*s);\n        s++;\n    }\n}\n\nint main(int argc, char *argv[])\n{\n    char t[255]=\"alphaBETA\";\n    str_toupper(t);\n    printf(\"uppercase: %s\\n\", t);\n    str_tolower(t);\n    printf(\"lowercase: %s\\n\", t);\n    return 0;\n}\n\n","human_summarization":"The code takes a string \"alphaBETA\" and converts it to both upper-case and lower-case using the default encoding. It also demonstrates additional case conversion functions that may be included in the language's library, such as swapping case and capitalizing the first letter. The code uses locale-aware tolower and toupper functions.","id":3419}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <values.h>\n#include <math.h>\n#include <string.h>\n\ntypedef struct { double x, y; } point_t, *point;\n\ninline double dist(point a, point b)\n{\n        double dx = a->x - b->x, dy = a->y - b->y;\n        return dx * dx + dy * dy;\n}\n\ninline int cmp_dbl(double a, double b)\n{\n        return a < b ? -1 : a > b ? 1 : 0;\n}\n\nint cmp_x(const void *a, const void *b) {\n        return cmp_dbl( (*(const point*)a)->x, (*(const point*)b)->x );\n}\n\nint cmp_y(const void *a, const void *b) {\n        return cmp_dbl( (*(const point*)a)->y, (*(const point*)b)->y );\n}\n\ndouble brute_force(point* pts, int max_n, point *a, point *b)\n{\n        int i, j;\n        double d, min_d = MAXDOUBLE;\n\n        for (i = 0; i < max_n; i++) {\n                for (j = i + 1; j < max_n; j++) {\n                        d = dist(pts[i], pts[j]);\n                        if (d >= min_d ) continue;\n                        *a = pts[i];\n                        *b = pts[j];\n                        min_d = d;\n                }\n        }\n        return min_d;\n}\n\ndouble closest(point* sx, int nx, point* sy, int ny, point *a, point *b)\n{\n        int left, right, i;\n        double d, min_d, x0, x1, mid, x;\n        point a1, b1;\n        point *s_yy;\n\n        if (nx <= 8) return brute_force(sx, nx, a, b);\n\n        s_yy  = malloc(sizeof(point) * ny);\n        mid = sx[nx\/2]->x;\n\n        \/* adding points to the y-sorted list; if a point's x is less than mid,\n           add to the begining; if more, add to the end backwards, hence the\n           need to reverse it *\/\n        left = -1; right = ny;\n        for (i = 0; i < ny; i++)\n                if (sy[i]->x < mid) s_yy[++left] = sy[i];\n                else                s_yy[--right]= sy[i];\n\n        \/* reverse the higher part of the list *\/\n        for (i = ny - 1; right < i; right ++, i--) {\n                a1 = s_yy[right]; s_yy[right] = s_yy[i]; s_yy[i] = a1;\n        }\n\n        min_d = closest(sx, nx\/2, s_yy, left + 1, a, b);\n        d = closest(sx + nx\/2, nx - nx\/2, s_yy + left + 1, ny - left - 1, &a1, &b1);\n\n        if (d < min_d) { min_d = d; *a = a1; *b = b1; }\n        d = sqrt(min_d);\n\n        \/* get all the points within distance d of the center line *\/\n        left = -1; right = ny;\n        for (i = 0; i < ny; i++) {\n                x = sy[i]->x - mid;\n                if (x <= -d || x >= d) continue;\n\n                if (x < 0) s_yy[++left]  = sy[i];\n                else       s_yy[--right] = sy[i];\n        }\n\n        \/* compare each left point to right point *\/\n        while (left >= 0) {\n                x0 = s_yy[left]->y + d;\n\n                while (right < ny && s_yy[right]->y > x0) right ++;\n                if (right >= ny) break;\n\n                x1 = s_yy[left]->y - d;\n                for (i = right; i < ny && s_yy[i]->y > x1; i++)\n                        if ((x = dist(s_yy[left], s_yy[i])) < min_d) {\n                                min_d = x;\n                                d = sqrt(min_d);\n                                *a = s_yy[left];\n                                *b = s_yy[i];\n                        }\n\n                left --;\n        }\n\n        free(s_yy);\n        return min_d;\n}\n\n#define NP 1000000\nint main()\n{\n        int i;\n        point a, b;\n\n        point pts  = malloc(sizeof(point_t) * NP);\n        point* s_x = malloc(sizeof(point) * NP);\n        point* s_y = malloc(sizeof(point) * NP);\n\n        for(i = 0; i < NP; i++) {\n                s_x[i] = pts + i;\n                pts[i].x = 100 * (double) rand()\/RAND_MAX;\n                pts[i].y = 100 * (double) rand()\/RAND_MAX;\n        }\n\n\/*      printf(\"brute force: %g, \", sqrt(brute_force(s_x, NP, &a, &b)));\n        printf(\"between (%f,%f) and (%f,%f)\n\", a->x, a->y, b->x, b->y);        *\/\n\n        memcpy(s_y, s_x, sizeof(point) * NP);\n        qsort(s_x, NP, sizeof(point), cmp_x);\n        qsort(s_y, NP, sizeof(point), cmp_y);\n\n        printf(\"min: %g; \", sqrt(closest(s_x, NP, s_y, NP, &a, &b)));\n        printf(\"point (%f,%f) and (%f,%f)\n\", a->x, a->y, b->x, b->y);\n\n        \/* not freeing the memory, let OS deal with it.  Habit. *\/\n        return 0;\n}\n","human_summarization":"The code provides two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute-force approach, iterating through each pair of points to find the pair with the minimum distance. The second function uses a recursive divide and conquer approach, sorting the points by x and y coordinates, and recursively finding the closest pair in the divided sets. The code returns the minimum distance and the pair of points.","id":3420}
    {"lang_cluster":"C","source_code":"\n\n#define cSize( a )  ( sizeof(a)\/sizeof(a[0]) ) \/* a.size() *\/\nint ar[10];               \/* Collection<Integer> ar = new ArrayList<Integer>(10); *\/\nar[0] = 1;                \/* ar.set(0, 1); *\/\nar[1] = 2;\n\nint* p;                   \/* Iterator<Integer> p; Integer pValue; *\/\nfor (p=ar;                \/* for( p = ar.itereator(), pValue=p.next(); *\/\n       p<(ar+cSize(ar));  \/*        p.hasNext(); *\/\n       p++) {             \/*        pValue=p.next() ) { *\/\n  printf(\"%d\\n\",*p);      \/*   System.out.println(pValue); *\/\n}                         \/* } *\/\n\n\nint* ar;                  \/* Collection<Integer> ar; *\/\nint arSize;\narSize = (rand() % 6) + 1; \nar = calloc(arSize, sizeof(int) ); \/* ar = new ArrayList<Integer>(arSize); *\/\nar[0] = 1;                \/* ar.set(0, 1); *\/\n\nint* p;                   \/* Iterator<Integer> p; Integer pValue; *\/\nfor (p=ar;                \/* p=ar.itereator(); for( pValue=p.next(); *\/\n       p<(ar+arSize);     \/*                         p.hasNext(); *\/\n       p++) {             \/*                         pValue=p.next() ) { *\/\n  printf(\"%d\\n\",*p);      \/*   System.out.println(pValue); *\/\n}                         \/* }    *\/\n\n\n","human_summarization":"The code creates a collection and adds a few values to it. It utilizes various collection types such as arrays, malloced arrays, and strings. The code also demonstrates the use of pointer arithmetic in C language, and the creation of complex data structures using struct and pointers. The code also includes the usage of various data structures like linked lists, doubly-linked lists, queues, sets, stacks, and associative arrays.","id":3421}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    double value;\n    double weight;\n    double volume;\n} item_t;\n\nitem_t items[] = {\n    {\"panacea\", 3000.0, 0.3, 0.025},\n    {\"ichor\",   1800.0, 0.2, 0.015},\n    {\"gold\",    2500.0, 2.0, 0.002},\n};\n\nint n = sizeof (items) \/ sizeof (item_t);\nint *count;\nint *best;\ndouble best_value;\n\nvoid knapsack (int i, double value, double weight, double volume) {\n    int j, m1, m2, m;\n    if (i == n) {\n        if (value > best_value) {\n            best_value = value;\n            for (j = 0; j < n; j++) {\n                best[j] = count[j];\n            }\n        }\n        return;\n    }\n    m1 = weight \/ items[i].weight;\n    m2 = volume \/ items[i].volume;\n    m = m1 < m2 ? m1 : m2;\n    for (count[i] = m; count[i] >= 0; count[i]--) {\n        knapsack(\n            i + 1,\n            value + count[i] * items[i].value,\n            weight - count[i] * items[i].weight,\n            volume - count[i] * items[i].volume\n        );\n    }\n}\n\nint main () {\n    count = malloc(n * sizeof (int));\n    best = malloc(n * sizeof (int));\n    best_value = 0;\n    knapsack(0, 0.0, 25.0, 0.25);\n    int i;\n    for (i = 0; i < n; i++) {\n        printf(\"%d %s\\n\", best[i], items[i].name);\n    }\n    printf(\"best value:\u00a0%.0f\\n\", best_value);\n    free(count); free(best);\n    return 0;\n}\n\n\n","human_summarization":"\"Output: The code implements a solution to the unbounded Knapsack problem, where a traveler in Shangri La needs to maximize the value of items he can carry in his knapsack, given the weight and volume constraints. The code determines the optimal quantity of each item (panacea, ichor, gold) to take, considering their respective values, weights, and volumes. It provides one of the four possible solutions that maximize the total value.\"","id":3422}
    {"lang_cluster":"C","source_code":"#include <stdio.h>\n\nint main()\n{\n  int i;\n  for (i = 1; i <= 10; i++) {\n    printf(\"%d\", i);\n    printf(i == 10 ? \"\\n\" : \", \");\n  }\n  return 0;\n}\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":3423}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\nchar input[] =\n\t\"des_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\\n\"\n\t\"dw01             ieee dw01 dware gtech\\n\"\n\t\"dw02             ieee dw02 dware\\n\"\n\t\"dw03             std synopsys dware dw03 dw02 dw01 ieee gtech\\n\"\n\t\"dw04             dw04 ieee dw01 dware gtech\\n\"\n\t\"dw05             dw05 ieee dware\\n\"\n\t\"dw06             dw06 ieee dware\\n\"\n\t\"dw07             ieee dware\\n\"\n\t\"dware            ieee dware\\n\"\n\t\"gtech            ieee gtech\\n\"\n\t\"ramlib           std ieee\\n\"\n\t\"std_cell_lib     ieee std_cell_lib\\n\"\n\t\"synopsys\\n\"\n\t\"cycle_11\t  cycle_12\\n\"\n\t\"cycle_12\t  cycle_11\\n\"\n\t\"cycle_21\t  dw01 cycle_22 dw02 dw03\\n\"\n\t\"cycle_22\t  cycle_21 dw01 dw04\";\n\ntypedef struct item_t item_t, *item;\nstruct item_t { const char *name; int *deps, n_deps, idx, depth; };\n\nint get_item(item *list, int *len, const char *name)\n{\n\tint i;\n\titem lst = *list;\n\n\tfor (i = 0; i < *len; i++)\n\t\tif (!strcmp(lst[i].name, name)) return i;\n\n\tlst = *list = realloc(lst, ++*len * sizeof(item_t));\n\ti = *len - 1;\n\tmemset(lst + i, 0, sizeof(item_t));\n\tlst[i].idx = i;\n\tlst[i].name = name;\n\treturn i;\n}\n\nvoid add_dep(item it, int i)\n{\n\tif (it->idx == i) return;\n\tit->deps = realloc(it->deps, (it->n_deps + 1) * sizeof(int));\n\tit->deps[it->n_deps++] = i;\n}\n\nint parse_input(item *ret)\n{\n\tint n_items = 0;\n\tint i, parent, idx;\n\titem list = 0;\n\n\tchar *s, *e, *word, *we;\n\tfor (s = input; ; s = 0) {\n\t\tif (!(s = strtok_r(s, \"\\n\", &e))) break;\n\n\t\tfor (i = 0, word = s; ; i++, word = 0) {\n\t\t\tif (!(word = strtok_r(word, \" \\t\", &we))) break;\n\t\t\tidx = get_item(&list, &n_items, word);\n\n\t\t\tif (!i) parent = idx;\n\t\t\telse    add_dep(list + parent, idx);\n\t\t}\n\t}\n\n\t*ret = list;\n\treturn n_items;\n}\n\n\/* recursively resolve compile order; negative means loop *\/\nint get_depth(item list, int idx, int bad)\n{\n\tint max, i, t;\n\n\tif (!list[idx].deps)\n\t\treturn list[idx].depth = 1;\n\n\tif ((t = list[idx].depth) < 0) return t;\n\n\tlist[idx].depth = bad;\n\tfor (max = i = 0; i < list[idx].n_deps; i++) {\n\t\tif ((t = get_depth(list, list[idx].deps[i], bad)) < 0) {\n\t\t\tmax = t;\n\t\t\tbreak;\n\t\t}\n\t\tif (max < t + 1) max = t + 1;\n\t}\n\treturn list[idx].depth = max;\n}\n\nint main()\n{\n\tint i, j, n, bad = -1, max, min;\n\titem items;\n\tn = parse_input(&items);\n\n\tfor (i = 0; i < n; i++)\n\t\tif (!items[i].depth && get_depth(items, i, bad) < 0) bad--;\n\n\tfor (i = 0, max = min = 0; i < n; i++) {\n\t\tif (items[i].depth > max) max = items[i].depth;\n\t\tif (items[i].depth < min) min = items[i].depth;\n\t}\n\n\tprintf(\"Compile order:\\n\");\n\tfor (i = min; i <= max; i++) {\n\t\tif (!i) continue;\n\n\t\tif (i < 0) printf(\"   [unorderable]\");\n\t\telse\t   printf(\"%d:\", i);\n\n\t\tfor (j = 0; j < n || !putchar('\\n'); j++)\n\t\t\tif (items[j].depth == i)\n\t\t\t\tprintf(\" %s\", items[j].name);\n\t}\n\n\treturn 0;\n}\n\n\n","human_summarization":"\"Implement a function to return a valid compile order of VHDL libraries based on their dependencies. The function should handle self dependencies, un-orderable dependencies, and libraries with no dependents. It uses topological sorting, specifically Kahn's 1962 topological sort or depth-first search, to determine the order. The function also parses a multiline string to show the compile order.\"","id":3424}
    {"lang_cluster":"C","source_code":"\n\n#include <string.h>\n#include <stdio.h>\n\nint startsWith(const char* container, const char* target)\n{\n  size_t clen = strlen(container), tlen = strlen(target);\n  if (clen < tlen)\n    return 0;\n  return strncmp(container, target, tlen) == 0;\n}\n\nint endsWith(const char* container, const char* target)\n{\n  size_t clen = strlen(container), tlen = strlen(target);\n  if (clen < tlen)\n    return 0;\n  return strncmp(container + clen - tlen, target, tlen) == 0;\n}\n\nint doesContain(const char* container, const char* target)\n{\n  return strstr(container, target) != 0;\n}\n\nint main(void)\n{\n  printf(\"Starts with Test ( Hello,Hell )\u00a0: %d\\n\", startsWith(\"Hello\",\"Hell\"));\n  printf(\"Ends with Test ( Code,ode )\u00a0: %d\\n\", endsWith(\"Code\",\"ode\"));\n  printf(\"Contains Test ( Google,msn )\u00a0: %d\\n\", doesContain(\"Google\",\"msn\"));\n\n  return 0;\n}\n\n\n","human_summarization":"The code performs three types of string matching operations: checking if the first string starts with the second string, if the first string contains the second string at any location, and if the first string ends with the second string. It also optionally prints the location of the match and handles multiple occurrences of a string. The matching is case sensitive and is implemented without using the string library, demonstrating that char strings are just pointers.","id":3425}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\n#define TRUE 1\n#define FALSE 0\n\nint a,b,c,d,e,f,g;\nint lo,hi,unique,show;\nint solutions;\n\nvoid\nbf()\n{\n    for (f = lo;f <= hi; f++)\n        if ((!unique) ||\n           ((f != a) && (f != c) && (f != d) && (f != g) && (f != e)))\n            {\n            b = e + f - c;\n            if ((b >= lo) && (b <= hi) &&\n                   ((!unique) || ((b != a) && (b != c) &&\n                   (b != d) && (b != g) && (b != e) && (b != f))))\n                {\n                solutions++;\n                if (show)\n                    printf(\"%d %d %d %d %d %d %d\\n\",a,b,c,d,e,f,g);\n                }\n            }\n}\n\n\nvoid\nge()\n{\n    for (e = lo;e <= hi; e++)\n        if ((!unique) || ((e != a) && (e != c) && (e != d)))\n            {\n            g = d + e;\n            if ((g >= lo) && (g <= hi) &&\n                   ((!unique) || ((g != a) && (g != c) &&\n                   (g != d) && (g != e))))\n                bf();\n            }\n}\n\nvoid\nacd()\n{\n    for (c = lo;c <= hi; c++)\n        for (d = lo;d <= hi; d++)\n            if ((!unique) || (c != d))\n                {\n                a = c + d;\n                if ((a >= lo) && (a <= hi) &&\n                   ((!unique) || ((c != 0) && (d != 0))))\n                    ge();\n                }\n}\n\n\nvoid\nfoursquares(int plo,int phi, int punique,int pshow)\n{\n    lo = plo;\n    hi = phi;\n    unique = punique;\n    show = pshow;\n    solutions = 0;\n\n    printf(\"\\n\");\n\n    acd();\n\n    if (unique)\n        printf(\"\\n%d unique solutions in %d to %d\\n\",solutions,lo,hi);\n    else\n        printf(\"\\n%d non-unique solutions in %d to %d\\n\",solutions,lo,hi);\n}\n\nmain()\n{\n    foursquares(1,7,TRUE,TRUE);\n    foursquares(3,9,TRUE,TRUE);\n    foursquares(0,9,FALSE,FALSE);\n}\n\n\n\n\n4 7 1 3 2 6 5\n6 4 1 5 2 3 7\n3 7 2 1 5 4 6\n5 6 2 3 1 7 4\n7 3 2 5 1 4 6\n4 5 3 1 6 2 7\n6 4 5 1 2 7 3\n7 2 6 1 3 5 4\n\n8 unique solutions in 1 to 7\n\n7 8 3 4 5 6 9\n8 7 3 5 4 6 9\n9 6 4 5 3 7 8\n9 6 5 4 3 8 7\n\n4 unique solutions in 3 to 9\n\n\n2860 non-unique solutions in 0 to 9\n\n","human_summarization":"The code finds all possible solutions for a puzzle where seven variables (a, b, c, d, e, f, g) are replaced with unique decimal digits ranging from a given low to high value. The sum of the variables in each of the four squares must be equal. It provides solutions for the ranges 1-7 and 3-9. Additionally, it calculates the number of solutions when the variables can have non-unique values in the range 0-9.","id":3426}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <time.h>\n#include <sys\/time.h>\n \n#define PI 3.14159265\nconst char * shades = \" .:-*ca&#%@\";\n \n\/* distance of (x, y) from line segment (0, 0)->(x0, y0) *\/\ndouble dist(double x, double y, double x0, double y0) {\n\tdouble l = (x * x0 + y * y0) \/ (x0 * x0 + y0 * y0);\n \n\tif (l > 1) {\n\t\tx -= x0;\n\t\ty -= y0;\n\t} else if (l >= 0) {\n\t\tx -= l * x0;\n\t\ty -= l * y0;\n\t}\n\treturn sqrt(x * x + y * y);\n}\n \nenum { sec = 0, min, hur }; \/\/ for subscripts\n \nvoid draw(int size)\n{\n#\tdefine for_i for(int i = 0; i < size; i++)\n#\tdefine for_j for(int j = 0; j < size * 2; j++)\n \n\tdouble angle, cx = size \/ 2.;\n\tdouble sx[3], sy[3], sw[3];\n\tdouble fade[] = { 1, .35, .35 }; \/* opacity of each arm *\/\n\tstruct timeval tv;\n\tstruct tm *t;\n \n\t\/* set width of each arm *\/\n\tsw[sec] = size * .02;\n\tsw[min] = size * .03;\n\tsw[hur] = size * .05;\n \nevery_second:\n\tgettimeofday(&tv, 0);\n\tt = localtime(&tv.tv_sec);\n \n\tangle = t->tm_sec * PI \/ 30;\n\tsy[sec] = -cx * cos(angle);\n\tsx[sec] =  cx * sin(angle);\n \n\tangle = (t->tm_min + t->tm_sec \/ 60.) \/ 30 * PI;\n\tsy[min] = -cx * cos(angle) * .8;\n\tsx[min] =  cx * sin(angle) * .8;\n \n\tangle = (t->tm_hour + t->tm_min \/ 60.) \/ 6 * PI;\n\tsy[hur] = -cx * cos(angle) * .6;\n\tsx[hur] =  cx * sin(angle) * .6;\n \n\tprintf(\"\\033[s\"); \/* save cursor position *\/\n\tfor_i {\n\t\tprintf(\"\\033[%d;0H\", i);  \/* goto row i, col 0 *\/\n\t\tdouble y = i - cx;\n\t\tfor_j {\n\t\t\tdouble x = (j - 2 * cx) \/ 2;\n \n\t\t\tint pix = 0;\n\t\t\t\/* calcs how far the \"pixel\" is from each arm and set\n\t\t\t * shade, with some anti-aliasing.  It's ghetto, but much\n\t\t\t * easier than a real scanline conversion.\n\t\t\t *\/\n\t\t\tfor (int k = hur; k >= sec; k--) {\n\t\t\t\tdouble d = dist(x, y, sx[k], sy[k]);\n\t\t\t\tif (d < sw[k] - .5)\n\t\t\t\t\tpix = 10 * fade[k];\n\t\t\t\telse if (d < sw[k] + .5)\n\t\t\t\t\tpix = (5 + (sw[k] - d) * 10) * fade[k];\n\t\t\t}\n\t\t\tputchar(shades[pix]);\n\t\t}\n\t}\n\tprintf(\"\\033[u\"); \/* restore cursor pos so you can bg the job -- value unclear *\/\n \n\tfflush(stdout);\n\tsleep(1); \/* sleep 1 can at times miss a second, but will catch up next update *\/\n\tgoto every_second;\n}\n \nint main(int argc, char *argv[])\n{\n\tint s;\n\tif (argc <= 1 || (s = atoi(argv[1])) <= 0) s = 20;\n\tdraw(s);\n\treturn 0;\n}\n\n\/\/ clockrosetta.c - https:\/\/rosettacode.org\/wiki\/Draw_a_clock\n\n\/\/ # Makefile\n\/\/ CFLAGS = -O3 -Wall -Wfatal-errors -Wpedantic -Werror\n\/\/ LDLIBS = -lX11 -lXext -lm\n\/\/ all:  clockrosetta\n\n#define SIZE 500\n\n#include <X11\/Xlib.h>\n#include <X11\/Xutil.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <sys\/select.h>\n#include <time.h>\n#include <X11\/extensions\/Xdbe.h>\n#include <math.h>\n\nstatic XdbeBackBuffer dbewindow = 0;\nstatic Display *display;\nstatic Window window;\nstatic int needseg = 1;\nstatic double d2r;\nstatic XSegment seg[61];\nstatic GC gc;\nstatic int mw = SIZE \/ 2;\nstatic int mh = SIZE \/ 2;\n\nstatic void\ndraw(void)\n  {\n  struct tm *ptm;\n  int i;\n  double angle;\n  double delta;\n  int radius = (mw < mh ? mw : mh) - 2;\n  XPoint pt[3];\n  double onetwenty = 3.1415926 * 2 \/ 3;\n  XdbeSwapInfo swapi;\n   time_t newtime;\n\n  if(dbewindow == 0)\n    {\n    dbewindow = XdbeAllocateBackBufferName(display, window, XdbeBackground);\n    XClearWindow(display, window);\n    }\n\n  time(&newtime);\n  ptm = localtime(&newtime);\n\n  if(needseg)\n    {\n    d2r = atan2(1.0, 0.0) \/ 90.0;\n    for(i = 0; i < 60; i++)\n      {\n      angle = (double)i * 6.0 * d2r;\n      delta = i % 5 ? 0.97 : 0.9;\n      seg[i].x1 = mw + radius * delta * sin(angle);\n      seg[i].y1 = mh - radius * delta * cos(angle);\n      seg[i].x2 = mw + radius * sin(angle);\n      seg[i].y2 = mh - radius * cos(angle);\n      }\n    needseg = 0;\n    }\n\n  angle = (double)(ptm->tm_sec) * 6.0 * d2r;\n  seg[60].x1 = mw;\n  seg[60].y1 = mh;\n  seg[60].x2 = mw + radius * 0.9 * sin(angle);\n  seg[60].y2 = mh - radius * 0.9 * cos(angle);\n  XDrawSegments(display, dbewindow, gc, seg, 61);\n\n  angle = (double)ptm->tm_min * 6.0 * d2r;\n  pt[0].x = mw + radius * 3 \/ 4 * sin(angle);\n  pt[0].y = mh - radius * 3 \/ 4 * cos(angle);\n  pt[1].x = mw + 6 * sin(angle + onetwenty);\n  pt[1].y = mh - 6 * cos(angle + onetwenty);\n  pt[2].x = mw + 6 * sin(angle - onetwenty);\n  pt[2].y = mh - 6 * cos(angle - onetwenty);\n  XFillPolygon(display, dbewindow, gc, pt, 3, Nonconvex, CoordModeOrigin);\n\n  angle = (double)(ptm->tm_hour * 60 + ptm->tm_min) \/ 2.0 * d2r;\n  pt[0].x = mw + radius \/ 2 * sin(angle);\n  pt[0].y = mh - radius \/ 2 * cos(angle);\n  pt[1].x = mw + 6 * sin(angle + onetwenty);\n  pt[1].y = mh - 6 * cos(angle + onetwenty);\n  pt[2].x = mw + 6 * sin(angle - onetwenty);\n  pt[2].y = mh - 6 * cos(angle - onetwenty);\n  XFillPolygon(display, dbewindow, gc, pt, 3, Nonconvex, CoordModeOrigin);\n\n  swapi.swap_window = window;\n  swapi.swap_action = XdbeBackground;\n  XdbeSwapBuffers(display, &swapi, 1);\n  }\n\nint\nmain(int argc, char *argv[])\n  {\n  Atom wm_both_protocols[1];\n  Atom wm_delete;\n  Atom wm_protocols;\n  Window root;\n  XEvent event;\n  XSetWindowAttributes attr;\n  fd_set fd;\n  int exposed = 0;\n  int more = 1;\n  struct timeval tv;\n\n  display = XOpenDisplay(NULL);\n\n  if(display == NULL)\n    {\n    fprintf(stderr,\"Error: The display cannot be opened\\n\");\n    exit(1);\n    }\n\n  root = DefaultRootWindow(display);\n  wm_delete = XInternAtom(display, \"WM_DELETE_WINDOW\", False);\n  wm_protocols = XInternAtom(display, \"WM_PROTOCOLS\", False);\n\n  attr.background_pixel = 0x000000;\n  attr.event_mask = KeyPress | KeyRelease |\n    ButtonPressMask | ButtonReleaseMask | ExposureMask;\n\n  window = XCreateWindow(display, root,\n    0, 0, SIZE, SIZE, 0,\n    CopyFromParent, InputOutput, CopyFromParent,\n    CWBackPixel | CWEventMask,\n    &attr\n    );\n\n  XStoreName(display, window, \"Clock for RosettaCode\");\n\n  wm_both_protocols[0] = wm_delete;\n  XSetWMProtocols(display, window, wm_both_protocols, 1);\n\n  gc = XCreateGC(display, window, 0, NULL);\n  XSetForeground(display, gc, 0xFFFF80);\n\n  XMapWindow(display, window);\n\n  while(more)\n    {\n    if(QLength(display) > 0)\n      {\n      XNextEvent(display, &event);\n      }\n    else\n      {\n      int maxfd = ConnectionNumber(display);\n\n      XFlush(display);\n      FD_ZERO(&fd);\n      FD_SET(ConnectionNumber(display), &fd);\n\n      event.type = LASTEvent;\n      tv.tv_sec = 0;\n      tv.tv_usec = 250000;\n      if(select(maxfd + 1, &fd, NULL, NULL, &tv) > 0)\n        {\n        if(FD_ISSET(ConnectionNumber(display), &fd))\n          {\n          XNextEvent(display, &event);\n          }\n        }\n      }\n\n    switch(event.type)\n      {\n    case Expose:\n      exposed = 1;\n      draw();\n      break;\n\n    case ButtonRelease:\n    case KeyRelease:\n      more = 0;\n    case ButtonPress:  \/\/ ignore\n    case KeyPress:     \/\/ ignore\n      break;\n\n    case LASTEvent:  \/\/ the timeout comes here\n      if(exposed) draw();\n      break;\n\n    case ConfigureNotify:\n      mw = event.xconfigure.width \/ 2;\n      mh = event.xconfigure.height \/ 2;\n      needseg = 1;\n      break;\n\n\n    case ClientMessage: \/\/ for close request from WM\n      if(event.xclient.window == window &&\n        event.xclient.message_type == wm_protocols &&\n        event.xclient.format == 32 &&\n        event.xclient.data.l[0] == wm_delete)\n        {\n        more = 0;\n        }\n      break;\n\n\/\/    default:\n\/\/      printf(\"unexpected event.type %d\\n\", event.type);;\n      }\n    }\n\n  XCloseDisplay(display);\n  exit(0);\n  }\n\n\/\/ END\n\n","human_summarization":"draw a simple, time-keeping device that updates every second. It does not need to be hyper-accurate but should be in sync with the system clock. The code avoids unnecessary system resource usage and maintains simplicity and clarity. It can be a text-based or graphical representation, but not a string of numbers. The code is written in C99 and compiled with gcc -std=c99.","id":3427}
    {"lang_cluster":"C","source_code":"\n\ntcc -DSTRUCT=struct -DCONST=const -DINT=int -DCHAR=char -DVOID=void -DMAIN=main -DIF=if -DELSE=else -DWHILE=while -DFOR=for -DDO=do -DBREAK=break -DRETURN=return -DPUTCHAR=putchar UCCALENDAR.c\n\n\/* UPPER CASE ONLY VERSION OF THE ORIGINAL CALENDAR.C, CHANGES MOSTLY TO AVOID NEEDING #INCLUDES *\/\n\/* ERROR MESSAGES GO TO STDOUT TO SLIGHTLY SIMPLIFY THE I\/O HANDLING                             *\/\n\/* WHEN COMPILING THIS, THE COMMAND LINE SHOULD SPECIFY -D OPTIONS FOR THE FOLLOWING WORDS:      *\/\n\/*    STRUCT, VOID, INT, CHAR, CONST, MAIN, IF, ELSE, WHILE, FOR, DO, BREAK, RETURN, PUTCHAR     *\/\n\/* THE VALUE OF EACH MACRO SHOULD BE THE WORD IN LOWER-CASE                                      *\/\n\nINT PUTCHAR(INT);\n\nINT WIDTH = 80, YEAR = 1969;\nINT COLS, LEAD, GAP;\n \nCONST CHAR *WDAYS[] = { \"SU\", \"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\" };\nSTRUCT MONTHS {\n    CONST CHAR *NAME;\n    INT DAYS, START_WDAY, AT;\n} MONTHS[12] = {\n    { \"JANUARY\",    31, 0, 0 },\n    { \"FEBRUARY\",    28, 0, 0 },\n    { \"MARCH\",    31, 0, 0 },\n    { \"APRIL\",    30, 0, 0 },\n    { \"MAY\",    31, 0, 0 },\n    { \"JUNE\",    30, 0, 0 },\n    { \"JULY\",    31, 0, 0 },\n    { \"AUGUST\",    31, 0, 0 },\n    { \"SEPTEMBER\",    30, 0, 0 },\n    { \"OCTOBER\",    31, 0, 0 },\n    { \"NOVEMBER\",    30, 0, 0 },\n    { \"DECEMBER\",    31, 0, 0 }\n};\n \nVOID SPACE(INT N) { WHILE (N-- > 0) PUTCHAR(' '); }\nVOID PRINT(CONST CHAR * S){ WHILE (*S != '\\0') { PUTCHAR(*S++); } }\nINT  STRLEN(CONST CHAR * S)\n{\n   INT L = 0;\n   WHILE (*S++ != '\\0') { L ++; };\nRETURN L;\n}\nINT ATOI(CONST CHAR * S)\n{\n    INT I = 0;\n    INT SIGN = 1;\n    CHAR C;\n    WHILE ((C = *S++) != '\\0') {\n        IF (C == '-')\n            SIGN *= -1;\n        ELSE {\n            I *= 10;\n            I += (C - '0');\n        }\n    }\nRETURN I * SIGN;\n}\n\nVOID INIT_MONTHS(VOID)\n{\n    INT I;\n \n    IF ((!(YEAR % 4) && (YEAR % 100)) || !(YEAR % 400))\n        MONTHS[1].DAYS = 29;\n \n    YEAR--;\n    MONTHS[0].START_WDAY\n        = (YEAR * 365 + YEAR\/4 - YEAR\/100 + YEAR\/400 + 1) % 7;\n \n    FOR (I = 1; I < 12; I++)\n        MONTHS[I].START_WDAY =\n            (MONTHS[I-1].START_WDAY + MONTHS[I-1].DAYS) % 7;\n \n    COLS = (WIDTH + 2) \/ 22;\n    WHILE (12 % COLS) COLS--;\n    GAP = COLS - 1 ? (WIDTH - 20 * COLS) \/ (COLS - 1) : 0;\n    IF (GAP > 4) GAP = 4;\n    LEAD = (WIDTH - (20 + GAP) * COLS + GAP + 1) \/ 2;\n        YEAR++;\n}\n \nVOID PRINT_ROW(INT ROW)\n{\n    INT C, I, FROM = ROW * COLS, TO = FROM + COLS;\n    SPACE(LEAD);\n    FOR (C = FROM; C < TO; C++) {\n        I = STRLEN(MONTHS[C].NAME);\n        SPACE((20 - I)\/2);\n        PRINT(MONTHS[C].NAME);\n        SPACE(20 - I - (20 - I)\/2 + ((C == TO - 1) ? 0 : GAP));\n    }\n    PUTCHAR('\\012');\n \n    SPACE(LEAD);\n    FOR (C = FROM; C < TO; C++) {\n        FOR (I = 0; I < 7; I++) {\n            PRINT(WDAYS[I]);\n            PRINT(I == 6 ? \"\" : \" \");\n        }\n        IF (C < TO - 1) SPACE(GAP);\n        ELSE PUTCHAR('\\012');\n    }\n \n    WHILE (1) {\n        FOR (C = FROM; C < TO; C++)\n            IF (MONTHS[C].AT < MONTHS[C].DAYS) BREAK;\n        IF (C == TO) BREAK;\n \n        SPACE(LEAD);\n        FOR (C = FROM; C < TO; C++) {\n            FOR (I = 0; I < MONTHS[C].START_WDAY; I++) SPACE(3);\n            WHILE(I++ < 7 && MONTHS[C].AT < MONTHS[C].DAYS) {\n                INT MM = ++MONTHS[C].AT;\n                PUTCHAR((MM < 10) ? ' ' : '0' + (MM \/10));\n                PUTCHAR('0' + (MM %10));\n                IF (I < 7 || C < TO - 1) PUTCHAR(' ');\n            }\n            WHILE (I++ <= 7 && C < TO - 1) SPACE(3);\n            IF (C < TO - 1) SPACE(GAP - 1);\n            MONTHS[C].START_WDAY = 0;\n        }\n        PUTCHAR('\\012');\n    }\n    PUTCHAR('\\012');\n}\n \nVOID PRINT_YEAR(VOID)\n{\n    INT Y = YEAR;\n    INT ROW;\n    CHAR BUF[32];\n    CHAR * B = &(BUF[31]);\n    *B-- = '\\0';\n    DO {\n        *B-- = '0' + (Y % 10);\n        Y \/= 10;\n    } WHILE (Y > 0);\n    B++;\n    SPACE((WIDTH - STRLEN(B)) \/ 2);\n    PRINT(B);PUTCHAR('\\012');PUTCHAR('\\012');\n    FOR (ROW = 0; ROW * COLS < 12; ROW++)\n        PRINT_ROW(ROW);\n}\n \nINT MAIN(INT C, CHAR **V)\n{\n    INT I, YEAR_SET = 0, RESULT = 0;\n    FOR (I = 1; I < C && RESULT == 0; I++) {\n        IF (V[I][0] == '-' && V[I][1] == 'W' && V[I][2] == '\\0') {\n            IF (++I == C || (WIDTH = ATOI(V[I])) < 20)\n                RESULT = 1;\n        } ELSE IF (!YEAR_SET) {\n            YEAR = ATOI(V[I]);\n            IF (YEAR <= 0)\n                YEAR = 1969;\n            YEAR_SET = 1;\n        } ELSE\n            RESULT = 1;\n    }\n \n    IF (RESULT == 0) {\n        INIT_MONTHS();\n        PRINT_YEAR();\n    } ELSE {\n        PRINT(\"BAD ARGS\\012USAGE: \");\n        PRINT(V[0]);\n        PRINT(\" YEAR [-W WIDTH (>= 20)]\\012\");\n    }\nRETURN RESULT;\n}\n\n","human_summarization":"The code provides an algorithm for a calendar task, formatted to fit a 132-character wide page, inspired by 1969 era line printers. The entire code is written in uppercase, as per the requirements of some 1960s computer systems. The code does not include Snoopy generation but outputs a placeholder instead. The code is designed to be compatible with UNIX systems connected to upper-case only terminals, and can be compiled with most C compilers.","id":3428}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n \ntypedef unsigned long long xint;\ntypedef unsigned long ulong;\n\ninline ulong gcd(ulong m, ulong n)\n{\n    ulong t;\n    while (n) { t = n; n = m % n; m = t; }\n    return m;\n}\n \nint main()\n{\n    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;\n    xint aa, bb, cc;\n\n    for (a = 1; a <= max_p \/ 3; a++) {\n        aa = (xint)a * a;\n        printf(\"a = %lu\\r\", a); \/* show that we are working *\/\n        fflush(stdout);\n\n        \/*  max_p\/2: valid limit, because one side of triangle\n         *  must be less than the sum of the other two\n         *\/\n        for (b = a + 1; b < max_p\/2; b++) {\n            bb = (xint)b * b;\n            for (c = b + 1; c < max_p\/2; c++) {\n                cc = (xint)c * c;\n                if (aa + bb < cc) break;\n                if (a + b + c > max_p) break;\n\n                if (aa + bb == cc) {\n                    pytha++;\n                    if (gcd(a, b) == 1) prim++;\n                }\n            }\n        }\n    }\n \n    printf(\"Up to %lu, there are %lu triples, of which %lu are primitive\\n\",\n        max_p, pytha, prim);\n\n    return 0;\n}\noutput:Up to 100, there are 17 triples, of which 7 are primitive\n\nEfficient method, generating primitive triples only as described in the same WP article:#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n\/* should be 64-bit integers if going over 1 billion *\/\ntypedef unsigned long xint;\n#define FMT \"%lu\"\n\nxint total, prim, max_peri;\nxint U[][9] =  {{ 1, -2, 2,  2, -1, 2,  2, -2, 3},\n        { 1,  2, 2,  2,  1, 2,  2,  2, 3},\n        {-1,  2, 2, -2,  1, 2, -2,  2, 3}};\n\nvoid new_tri(xint in[])\n{\n    int i;\n    xint t[3], p = in[0] + in[1] + in[2];\n\n    if (p > max_peri) return;\n\n    prim ++;\n\n    \/* for every primitive triangle, its multiples would be right-angled too;\n     * count them up to the max perimeter *\/\n    total += max_peri \/ p;\n\n    \/* recursively produce next tier by multiplying the matrices *\/\n    for (i = 0; i < 3; i++) {\n        t[0] = U[i][0] * in[0] + U[i][1] * in[1] + U[i][2] * in[2];\n        t[1] = U[i][3] * in[0] + U[i][4] * in[1] + U[i][5] * in[2];\n        t[2] = U[i][6] * in[0] + U[i][7] * in[1] + U[i][8] * in[2];\n        new_tri(t);\n    }\n}\n\nint main()\n{\n    xint seed[3] = {3, 4, 5};\n\n    for (max_peri = 10; max_peri <= 100000000; max_peri *= 10) {\n        total = prim = 0;\n        new_tri(seed);\n\n        printf( \"Up to \"FMT\": \"FMT\" triples, \"FMT\" primitives.\\n\",\n            max_peri, total, prim);\n    }\n    return 0;\n}\nOutputUp to 10: 0 triples, 0 primitives.\nUp to 100: 17 triples, 7 primitives.\nUp to 1000: 325 triples, 70 primitives.\nUp to 10000: 4858 triples, 703 primitives.\nUp to 100000: 64741 triples, 7026 primitives.\nUp to 1000000: 808950 triples, 70229 primitives.\nUp to 10000000: 9706567 triples, 702309 primitives.\nUp to 100000000: 113236940 triples, 7023027 primitives.\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n\/* should be 64-bit integers if going over 1 billion *\/\ntypedef unsigned long xint;\n#define FMT \"%lu\"\n\nxint total, prim, max_peri;\n\nvoid new_tri(xint in[])\n{\n    int i;\n    xint t[3], p;\n    xint x = in[0], y = in[1], z = in[2];\n\nrecur:  p = x + y + z;\n    if (p > max_peri) return;\n\n    prim ++;\n    total += max_peri \/ p;\n\n    t[0] = x - 2 * y + 2 * z;\n    t[1] = 2 * x - y + 2 * z;\n    t[2] = t[1] - y + z;\n    new_tri(t);\n\n    t[0] += 4 * y;\n    t[1] += 2 * y;\n    t[2] += 4 * y;\n    new_tri(t);\n\n    z = t[2] - 4 * x;\n    y = t[1] - 4 * x;\n    x = t[0] - 2 * x;\n    goto recur;\n}\n\nint main()\n{\n    xint seed[3] = {3, 4, 5};\n\n    for (max_peri = 10; max_peri <= 100000000; max_peri *= 10) {\n        total = prim = 0;\n        new_tri(seed);\n\n        printf( \"Up to \"FMT\": \"FMT\" triples, \"FMT\" primitives.\\n\",\n            max_peri, total, prim);\n    }\n    return 0;\n}\n\n","human_summarization":"The code calculates the number of Pythagorean triples (sets of three positive integers a, b, c where a^2 + b^2 = c^2 and a < b < c) with a perimeter no larger than 100, and also determines how many of these triples are primitive (where a, b, and c are co-prime). The code is also designed to handle larger perimeters up to 100,000,000.","id":3429}
    {"lang_cluster":"C","source_code":"\nWorks with: ANSI C version C89\nLibrary: SDL\nUses: SDL (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses library\" (as page type) with input value \"library\/SDL\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\nUses: ANSI C (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses library\" (as page type) with input value \"library\/ANSI C\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\n\n\/*\n *   Opens an 800x600 16bit color window. \n *   Done here with ANSI C.\n *\/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include \"SDL.h\"\n\nint main()\n{\n  SDL_Surface *screen;\n  \n  if (SDL_Init(SDL_INIT_VIDEO) != 0) {\n    fprintf(stderr, \"Unable to initialize SDL: %s\\n\", SDL_GetError());\n    return 1;\n  }\n  atexit(SDL_Quit);\n  screen = SDL_SetVideoMode( 800, 600, 16, SDL_SWSURFACE | SDL_HWPALETTE );\n  \n  return 0;\n}\n\nLibrary: GTK\nUses: GTK (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses library\" (as page type) with input value \"library\/GTK\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\n\n#include <gtk\/gtk.h>\n\nint\nmain(int argc, char *argv[]) \n{\n  GtkWidget *window;\n\n  gtk_init(&argc, &argv);\n  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_signal_connect(GTK_OBJECT(window), \"destroy\",\n    GTK_SIGNAL_FUNC(gtk_main_quit), NULL);\n  gtk_widget_show(window);\n  gtk_main();\n\n  return 0;\n}\n\nLibrary: Gtk2\nUses: Gtk2 (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses library\" (as page type) with input value \"library\/Gtk2\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\n\n#include <gtk\/gtk.h>\n\nint\nmain(int argc, char *argv[])\n{\n  GtkWidget *window;\n\n  gtk_init(&argc, &argv);\n  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  g_signal_connect (window, \"destroy\", G_CALLBACK(gtk_main_quit), NULL);\n  gtk_widget_show(window);\n  gtk_main();\n\n  return 0;\n}\n\nLibrary: GLUT\nUses: GLUT (Components:{{#foreach: component$n$|{{{component$n$}}}Property \"Uses library\" (as page type) with input value \"library\/GLUT\/{{{component$n$}}}\" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process., }})\n\n\/\/ A C+GLUT implementation of the Creating a Window task at Rosetta Code\n\/\/ http:\/\/rosettacode.org\/wiki\/Creating_a_Window\n#include <stdlib.h>\n#include <GL\/glut.h>\n\n\/\/ This function is not strictly necessary to meet the requirements of the task.\nvoid onKeyPress(unsigned char key, int x, int y)\n{\n\t\/\/ If you have any cleanup or such, you need to use C's\n\t\/\/ onexit routine for registering cleanup callbacks.\n\texit(0);\n\n}\n\nint main(int argc, char **argv)\n{\n\t\/\/ Pulls out any command-line arguments that are specific to GLUT,\n\t\/\/ And leaves a command-line argument set without any of those arguments\n\t\/\/ when it returns.\n\t\/\/ (If you want a copy, take a copy first.)\n\tglutInit(&argc, argv);\n\n\t\/\/ Tell GLUT we want to create a window.\n\t\/\/ It won't *actually* be created until we call glutMainLoop below.\n\tglutCreateWindow(\"Goodbye, World!\");\n\n\t\/\/ Register a callback to handle key press events (so we can quit on\n\t\/\/ when someone hits a key)  This part is not necessary to meet the\n\t\/\/ requirements of the task.\n\tglutKeyboardFunc(&onKeyPress);\n\n\t\/\/ Put the execution of the app in glut's hands. Most GUI environments\n\t\/\/ involve a message loop that communicate window events. GLUT handles\n\t\/\/ most of these with defaults, except for any we register callbacks\n\t\/\/ for. (Like the onKeyPress above.)\n\tglutMainLoop();\n\n\treturn 0;\n\n}\n\n","human_summarization":"The code creates a GUI window that responds to close requests. It doesn't contain any content or drawing callbacks, resulting in a blank appearance. A keypress callback is registered for closing the program. The code is compiled using different commands for SDL, GTK, and GLUT libraries.","id":3430}
    {"lang_cluster":"C","source_code":"\n\/* declare array *\/\nint frequency[26];\nint ch;\nFILE* txt_file = fopen (\"a_text_file.txt\", \"rt\");\n\n\/* init the freq table: *\/\nfor (ch = 0; ch < 26; ch++)\n    frequency[ch] = 0;\n\nwhile (1) {\n    ch = fgetc(txt_file);\n    if (ch == EOF) break; \/* end of file or read error.  EOF is typically -1 *\/\n\n    \/* assuming ASCII; \"letters\" means \"a to z\" *\/\n    if ('a' <= ch && ch <= 'z')      \/* lower case *\/\n        frequency[ch-'a']++;\n    else if ('A' <= ch && ch <= 'Z') \/* upper case *\/\n        frequency[ch-'A']++;\n}\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":3431}
    {"lang_cluster":"C","source_code":"\nstruct link {\n  struct link *next;\n  int data;\n};\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":3432}
    {"lang_cluster":"C","source_code":"\nLibrary: SDL\nLibrary: SGE or Library: cairo\n#include <SDL\/SDL.h>\n#ifdef WITH_CAIRO\n#include <cairo.h>\n#else\n#include <SDL\/sge.h>\n#endif\n#include <cairo.h>\n#include <stdlib.h>\n#include <time.h>\n#include <math.h>\n\n#ifdef WITH_CAIRO\n#define PI 3.1415926535\n#endif\n \n#define SIZE           800   \/\/ determines size of window\n#define SCALE          5     \/\/ determines how quickly branches shrink (higher value means faster shrinking)\n#define BRANCHES       14    \/\/ number of branches\n#define ROTATION_SCALE 0.75  \/\/ determines how slowly the angle between branches shrinks (higher value means slower shrinking)\n#define INITIAL_LENGTH 50    \/\/ length of first branch\n \ndouble rand_fl(){\n  return (double)rand() \/ (double)RAND_MAX;\n}\n \nvoid draw_tree(SDL_Surface * surface, double offsetx, double offsety,\n               double directionx, double directiony, double size,\n               double rotation, int depth) {\n#ifdef WITH_CAIRO\n  cairo_surface_t *surf = cairo_image_surface_create_for_data( surface->pixels,\n                                                               CAIRO_FORMAT_RGB24,\n\t\t\t\t\t\t\t       surface->w, surface->h,\n\t\t\t\t\t\t\t       surface->pitch );\n  cairo_t *ct = cairo_create(surf);\n\n  cairo_set_line_width(ct, 1);\n  cairo_set_source_rgba(ct, 0,0,0,1);\n  cairo_move_to(ct, (int)offsetx, (int)offsety);\n  cairo_line_to(ct, (int)(offsetx + directionx * size), (int)(offsety + directiony * size));\n  cairo_stroke(ct);\n#else\n  sge_AALine(surface,\n      (int)offsetx, (int)offsety,\n      (int)(offsetx + directionx * size), (int)(offsety + directiony * size),\n      SDL_MapRGB(surface->format, 0, 0, 0));\n#endif\n  if (depth > 0){\n    \/\/ draw left branch\n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(rotation) + directiony * sin(rotation),\n        directionx * -sin(rotation) + directiony * cos(rotation),\n        size * rand_fl() \/ SCALE + size * (SCALE - 1) \/ SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n \n    \/\/ draw right branch\n    draw_tree(surface,\n        offsetx + directionx * size,\n        offsety + directiony * size,\n        directionx * cos(-rotation) + directiony * sin(-rotation),\n        directionx * -sin(-rotation) + directiony * cos(-rotation),\n        size * rand_fl() \/ SCALE + size * (SCALE - 1) \/ SCALE,\n        rotation * ROTATION_SCALE,\n        depth - 1);\n  }\n}\n \nvoid render(SDL_Surface * surface){\n  SDL_FillRect(surface, NULL, SDL_MapRGB(surface->format, 255, 255, 255));\n  draw_tree(surface,\n      surface->w \/ 2.0,\n      surface->h - 10.0,\n      0.0, -1.0,\n      INITIAL_LENGTH,\n      PI \/ 8,\n      BRANCHES);\n  SDL_UpdateRect(surface, 0, 0, 0, 0);\n}\n \nint main(){\n  SDL_Surface * screen;\n  SDL_Event evt;\n \n  SDL_Init(SDL_INIT_VIDEO);\n \n  srand((unsigned)time(NULL));\n \n  screen = SDL_SetVideoMode(SIZE, SIZE, 32, SDL_HWSURFACE);\n \n  render(screen);\n  while(1){\n    if (SDL_PollEvent(&evt)){\n      if(evt.type == SDL_QUIT) break;\n    }\n    SDL_Delay(1);\n  }\n  SDL_Quit();\n  return 0;\n}\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":3433}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    int *list;\n    short count; \n} Factors;\n\nvoid xferFactors( Factors *fctrs, int *flist, int flix ) \n{\n    int ix, ij;\n    int newSize = fctrs->count + flix;\n    if (newSize > flix)  {\n        fctrs->list = realloc( fctrs->list, newSize * sizeof(int));\n    }\n    else {\n        fctrs->list = malloc(  newSize * sizeof(int));\n    }\n    for (ij=0,ix=fctrs->count; ix<newSize; ij++,ix++) {\n        fctrs->list[ix] = flist[ij];\n    }\n    fctrs->count = newSize;\n}\n\nFactors *factor( int num, Factors *fctrs)\n{\n    int flist[301], flix;\n    int dvsr;\n    flix = 0;\n    fctrs->count = 0;\n    free(fctrs->list);\n    fctrs->list = NULL;\n    for (dvsr=1; dvsr*dvsr < num; dvsr++) {\n        if (num % dvsr != 0) continue;\n        if ( flix == 300) {\n            xferFactors( fctrs, flist, flix );\n            flix = 0;\n        }\n        flist[flix++] = dvsr;\n        flist[flix++] = num\/dvsr;\n    }\n    if (dvsr*dvsr == num) \n        flist[flix++] = dvsr;\n    if (flix > 0)\n        xferFactors( fctrs, flist, flix );\n\n    return fctrs;\n}\n        \nint main(int argc, char*argv[])\n{\n    int nums2factor[] = { 2059, 223092870, 3135, 45 };\n    Factors ftors = { NULL, 0};\n    char sep;\n    int i,j;\n\n    for (i=0; i<4; i++) {\n        factor( nums2factor[i], &ftors );\n        printf(\"\\nfactors of %d are:\\n  \", nums2factor[i]);\n        sep = ' ';\n        for (j=0; j<ftors.count; j++) {\n            printf(\"%c %d\", sep, ftors.list[j]);\n            sep = ',';\n        }\n        printf(\"\\n\");\n    }\n    return 0;\n}\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n\/* 65536 = 2^16, so we can factor all 32 bit ints *\/\nchar bits[65536];\n\ntypedef unsigned long ulong;\nulong primes[7000], n_primes;\n\ntypedef struct { ulong p, e; } prime_factor; \/* prime, exponent *\/\n\nvoid sieve()\n{\n\tint i, j;\n\tmemset(bits, 1, 65536);\n\tbits[0] = bits[1] = 0;\n\tfor (i = 0; i < 256; i++)\n\t\tif (bits[i])\n\t\t\tfor (j = i * i; j < 65536; j += i)\n\t\t\t\tbits[j] = 0;\n\n\t\/* collect primes into a list. slightly faster this way if dealing with large numbers *\/\n\tfor (i = j = 0; i < 65536; i++)\n\t\tif (bits[i]) primes[j++] = i;\n\n\tn_primes = j;\n}\n\nint get_prime_factors(ulong n, prime_factor *lst)\n{\n\tulong i, e, p;\n\tint len = 0;\n\n\tfor (i = 0; i < n_primes; i++) {\n\t\tp = primes[i];\n\t\tif (p * p > n) break;\n\t\tfor (e = 0; !(n % p); n \/= p, e++);\n\t\tif (e) {\n\t\t\tlst[len].p = p;\n\t\t\tlst[len++].e = e;\n\t\t}\n\t}\n\n\treturn n == 1 ? len : (lst[len].p = n, lst[len].e = 1, ++len);\n}\n\nint ulong_cmp(const void *a, const void *b)\n{\n\treturn *(const ulong*)a < *(const ulong*)b ? -1 : *(const ulong*)a > *(const ulong*)b;\n}\n\nint get_factors(ulong n, ulong *lst)\n{\n\tint n_f, len, len2, i, j, k, p;\n\tprime_factor f[100];\n\n\tn_f = get_prime_factors(n, f);\n\n\tlen2 = len = lst[0] = 1;\n\t\/* L = (1); L = (L, L * p**(1 .. e)) forall((p, e)) *\/\n\tfor (i = 0; i < n_f; i++, len2 = len)\n\t\tfor (j = 0, p = f[i].p; j < f[i].e; j++, p *= f[i].p)\n\t\t\tfor (k = 0; k < len2; k++)\n\t\t\t\tlst[len++] = lst[k] * p;\n\n\tqsort(lst, len, sizeof(ulong), ulong_cmp);\n\treturn len;\n}\n\nint main()\n{\n\tulong fac[10000];\n\tint len, i, j;\n\tulong nums[] = {3, 120, 1024, 2UL*2*2*2*3*3*3*5*5*7*11*13*17*19 };\n\n\tsieve();\n\n\tfor (i = 0; i < 4; i++) {\n\t\tlen = get_factors(nums[i], fac);\n\t\tprintf(\"%lu:\", nums[i]);\n\t\tfor (j = 0; j < len; j++)\n\t\t\tprintf(\" %lu\", fac[j]);\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":3434}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nconst char *str = \n\t\"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n\"\n\t\"are$delineated$by$a$single$'dollar'$character,$write$a$program\n\"\n\t\"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n\"\n\t\"column$are$separated$by$at$least$one$space.\n\"\n\t\"Further,$allow$for$each$word$in$a$column$to$be$either$left$\n\"\n\t\"justified,$right$justified,$or$center$justified$within$its$column.\";\n\nvoid align(const char *in, char alignment)\n{\n\tint col, i, l, r;\n\tint w[1024] = {0};\n\tconst char *s;\n\n\tfor (s = in, i = col = 0; s[i]; s += i + 1) {\n\t\tfor (i = 0; s[i] && s[i] != '$' && s[i] != '\n'; i++);\n\n\t\tif (i > w[col]) w[col] = i;\n\n\t\tif (col++ >= 1024) abort(); \/* artificial limit *\/\n\n\t\tif (s[i] == '\n') col = 0;\n\t\tif (!s[i]) break;\n\t}\n\n\tfor (s = in, i = col = 0; s[i]; s += i + 1) {\n\t\tfor (i = 0; s[i] && s[i] != '$' && s[i] != '\n'; i++);\n\n\t\tswitch(alignment) {\n\t\tcase 'l':\tr = w[col] - i; break;\n\t\tcase 'c':\tr = (w[col] - i)\/2; break;\n\t\tcase 'r':\tr = 0; break;\n\t\t}\n\t\tl = w[col++] - i - r + 1;\n\n\t\twhile (l--) putchar(' ');\n\t\tprintf(\"%.*s\", i, s);\n\t\twhile (r--) putchar(' ');\n\n\t\tif (s[i] != '$') {\n\t\t\tputchar('\n');\n\t\t\tcol = 0;\n\t\t}\n\t\tif (!s[i]) break;\n\t}\n}\n\nint main(void)\n{\n\tputs(\"\n----  right ----\"); align(str, 'r');\n\tputs(\"\n----  left  ----\"); align(str, 'l');\n\tputs(\"\n---- center ----\"); align(str, 'c');\n\treturn 0;\n}\n","human_summarization":"The code reads a text file where each line's fields are separated by a dollar character. It then aligns each column by ensuring at least one space between words in each column. The code also allows for words in a column to be left, right, or center justified. The minimum space between columns is computed from the text and not hard-coded. The output is viewed in a mono-spaced font on a plain text editor or basic terminal.","id":3435}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n \nconst char *shades = \".:!*oe&#%@\";\n \nvoid vsub(double *v1, double *v2, double *s) {\n\ts[0] = v1[0] - v2[0];\n\ts[1] = v1[1] - v2[1];\n\ts[2] = v1[2] - v2[2];\n}\n\ndouble normalize(double * v) {\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] \/= len; v[1] \/= len; v[2] \/= len;\n\treturn len;\n}\n \ndouble dot(double *x, double *y) {\n        return x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n}\n\ndouble * cross(double x[3], double y[3], double s[3]) {\n\ts[0] = x[1] * y[2] - x[2] * y[1];\n\ts[1] = x[2] * y[0] - x[0] * y[2];\n\ts[2] = x[0] * y[1] - x[1] * y[0];\n\treturn s;\n}\n\ndouble* madd(double *x, double *y, double d, double *r) {\n\tr[0] = x[0] + y[0] * d;\n\tr[1] = x[1] + y[1] * d;\n\tr[2] = x[2] + y[2] * d;\n\treturn r;\n}\n\ndouble v000[] = { -4, -3, -2 };\ndouble v100[] = {  4, -3, -2 };\ndouble v010[] = { -4,  3, -2 };\ndouble v110[] = {  4,  3, -2 };\ndouble v001[] = { -4, -3,  2 };\ndouble v101[] = {  4, -3,  2 };\ndouble v011[] = { -4,  3,  2 };\ndouble v111[] = {  4,  3,  2 };\n\ntypedef struct {\n\tdouble * v[4];\n\tdouble norm[3];\n} face_t;\n\nface_t f[] = {\n\t{ { v000, v010, v110, v100 }, {  0,  0, -1 } },\n\t{ { v001, v011, v111, v101 }, {  0,  0,  1 } },\n\t{ { v000, v010, v011, v001 }, { -1,  0,  0 } },\n\t{ { v100, v110, v111, v101 }, {  1,  0,  0 } },\n\t{ { v000, v100, v101, v001 }, {  0, -1,  0 } },\n\t{ { v010, v110, v111, v011 }, {  0,  1,  0 } },\n};\n\nint in_range(double x, double x0, double x1) {\n\treturn (x - x0) * (x - x1) <= 0;\n}\n\nint face_hit(face_t *face, double src[3], double dir[3], double hit[3], double *d)\n{\n\tint i;\n\tdouble dist;\n\tfor (i = 0; i < 3; i++)\n\t\tif (face->norm[i])\n\t\t\tdist = (face->v[0][i] - src[i]) \/ dir[i];\n\n\tmadd(src, dir, dist, hit);\n\t*d = fabs(dot(dir, face->norm) * dist);\n\n\tif (face->norm[0]) {\n\t\treturn  in_range(hit[1], face->v[0][1], face->v[2][1]) &&\n\t\t\tin_range(hit[2], face->v[0][2], face->v[2][2]);\n\t}\n\telse if (face->norm[1]) {\n\t\treturn  in_range(hit[0], face->v[0][0], face->v[2][0]) &&\n\t\t\tin_range(hit[2], face->v[0][2], face->v[2][2]);\n\t}\n\telse if (face->norm[2]) {\n\t\treturn  in_range(hit[0], face->v[0][0], face->v[2][0]) &&\n\t\t\tin_range(hit[1], face->v[0][1], face->v[2][1]);\n\t}\n\treturn 0;\n}\n\nint main()\n{\n\tint i, j, k;\n\tdouble eye[3] = { 7, 7, 6 };\n\tdouble dir[3] = { -1, -1, -1 }, orig[3] = {0, 0, 0};\n\tdouble hit[3], dx[3], dy[3] = {0, 0, 1}, proj[3];\n\tdouble d, *norm, dbest, b;\n\tdouble light[3] = { 6, 8, 6 }, ldist[3], decay, strength = 10;\n\n \tnormalize(cross(eye, dy, dx));\n\tnormalize(cross(eye, dx, dy));\n\n\tfor (i = -10; i <= 17; i++) {\n\t\tfor (j = -35; j < 35; j++) {\n\t\t\tvsub(orig, orig, proj);\n\t\t\tmadd(madd(proj, dx, j \/ 6., proj), dy, i\/3., proj);\n\t\t\tvsub(proj, eye, dir);\n\t\t\tdbest = 1e100;\n\t\t\tnorm = 0;\n\t\t \tfor (k = 0; k < 6; k++) {\n\t\t\t\tif (!face_hit(f + k, eye, dir, hit, &d)) continue;\n\t\t\t\tif (dbest > d) {\n\t\t\t\t\tdbest = d;\n\t\t\t\t\tnorm = f[k].norm;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!norm) {\n\t\t\t\tputchar(' ');\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tvsub(light, hit, ldist);\n\t\t\tdecay = normalize(ldist);\n\t\t\tb = dot(norm, ldist) \/ decay * strength;\n\t\t\tif (b < 0) b = 0;\n\t\t\telse if (b > 1) b = 1;\n\t\t\tb += .2;\n\t\t\tif (b > 1) b = 0;\n\t\t\telse b = 1 - b;\n\t\t\tputchar(shades[(int)(b * (sizeof(shades) - 2))]);\n\t\t}\n\t\tputchar('\\n');\n\t}\n\n        return 0;\n}\n\n\n                                \n                                .\n                        ................\n                ...............................\n         .............................................\n     ........................................................\n     ...............................................................\n      ..............................................................::\n      ...........................................................::::\n       .......................................................:::::::\n       .....................................................::::::::\n        .................................................::::::::::\n       \u00a0:..............................................::::::::::::\n        \u00a0:............................................::::::::::::\n        \u00a0::..........................................:::::::::::::\n          \u00a0:........................................:::::::::::::\n             ......................................::::::::::::::\n               ....................................:::::::::::::\n                 .................................::::::::::::\n                    ............................::::::::::::\n                      .........................:::::::::::\n                        ......................::::::::::\n                          ...................:::::::::\n                             ..............:::::::::\n                               ...........:::::::::\n                                 .........:::::::\n                                   .......:::::\n                                     .....:::\n                                        .::\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, displaying three visible faces. The cuboid can be either static or rotationally projected. The code correctly executes, but only the characters '.' and ':' appear on the cuboid.","id":3436}
    {"lang_cluster":"C","source_code":"\n\n#include <ldap.h>\n...\nchar *name, *password;\n...\nLDAP *ld = ldap_init(\"ldap.somewhere.com\", 389);\nldap_simple_bind_s(ld, name, password);\n... after done with it...\nldap_unbind(ld);\n\n","human_summarization":"Establishes a connection to an Active Directory or Lightweight Directory Access Protocol server using OpenLDAP.","id":3437}
    {"lang_cluster":"C","source_code":"\n\n#include <ctype.h>\n#include <limits.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nstatic char rot13_table[UCHAR_MAX + 1];\n\nstatic void init_rot13_table(void) {\n\tstatic const unsigned char upper[] = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\tstatic const unsigned char lower[] = \"abcdefghijklmnopqrstuvwxyz\";\n\n\tfor (int ch = '\\0'; ch <= UCHAR_MAX; ch++) {\n\t\trot13_table[ch] = ch;\n\t}\n\tfor (const unsigned char *p = upper; p[13] != '\\0'; p++) {\n\t\trot13_table[p[0]] = p[13];\n\t\trot13_table[p[13]] = p[0];\n\t}\n\tfor (const unsigned char *p = lower; p[13] != '\\0'; p++) {\n\t\trot13_table[p[0]] = p[13];\n\t\trot13_table[p[13]] = p[0];\n\t}\n}\n\nstatic void rot13_file(FILE *fp)\n{\n\tint ch;\n\twhile ((ch = fgetc(fp)) != EOF) {\n\t\tfputc(rot13_table[ch], stdout);                \n\t}\n}\n\nint main(int argc, char *argv[])\n{\n\tinit_rot13_table();\n\n\tif (argc > 1) {\n\t\tfor (int i = 1; i < argc; i++) {\n\t\t\tFILE *fp = fopen(argv[i], \"r\");\n\t\t\tif (fp == NULL) {\n\t\t\t\tperror(argv[i]);\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t\trot13_file(fp);\n\t\t\tfclose(fp);\n\t\t}\n\t} else {\n\t\trot13_file(stdin);\n\t}\n\treturn EXIT_SUCCESS;\n}\n\n","human_summarization":"implement a rot-13 encoding function that can be optionally wrapped in a utility program. The function replaces every letter of the ASCII alphabet with the letter 13 characters away, preserving case and passing non-alphabetic characters without alteration. It can handle all character sets, even if the letters are not in a contiguous range.","id":3438}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <ctype.h>\n\ntypedef struct twoStringsStruct {\n    char * key, *value;\n} sTwoStrings;\n \nint ord( char v )\n{\n    static char *dgts = \"012345679\";\n    char *cp;\n    for (cp=dgts; v != *cp; cp++);\n    return (cp-dgts);\n}\n\nint cmprStrgs(const sTwoStrings *s1,const sTwoStrings *s2)\n{\n    char *p1 = s1->key; \n    char *p2 = s2->key;\n    char *mrk1, *mrk2;\n    while ((tolower(*p1) == tolower(*p2)) && *p1) { p1++; p2++;}\n    if (isdigit(*p1) && isdigit(*p2)) {\n        long v1, v2;\n        if ((*p1 == '0') ||(*p2 == '0')) {\n            while (p1 > s1->key) {\n                p1--; p2--;\n                if (*p1 != '0') break;\n            }\n            if (!isdigit(*p1)) {\n                p1++; p2++;\n            }\n        }\n        mrk1 = p1; mrk2 = p2;\n        v1 = 0;\n        while(isdigit(*p1)) {\n            v1 = 10*v1+ord(*p1);\n            p1++;\n        }\n        v2 = 0;\n        while(isdigit(*p2)) {\n            v2 = 10*v2+ord(*p2);\n            p2++;\n        }\n        if (v1 == v2) \n           return(p2-mrk2)-(p1-mrk1);\n        return v1 - v2;\n    }\n    if (tolower(*p1) != tolower(*p2))\n       return (tolower(*p1) - tolower(*p2));\n    for(p1=s1->key, p2=s2->key; (*p1 == *p2) && *p1; p1++, p2++);\n    return (*p1 -*p2);\n}\n\nint maxstrlen( char *a, char *b)\n{\n\tint la = strlen(a);\n\tint lb = strlen(b);\n\treturn (la>lb)? la : lb;\n}\n\nint main()\n{\n    sTwoStrings toBsorted[] = {\n        { \"Beta11a\", \"many\" },\n        { \"alpha1\", \"This\" },\n        { \"Betamax\", \"sorted.\" },\n        { \"beta3\", \"order\" },\n        { \"beta11a\", \"strings\" },\n        { \"beta001\", \"is\" },\n        { \"beta11\", \"which\" },\n        { \"beta041\", \"be\" },\n        { \"beta05\", \"in\" },\n        { \"beta1\", \"the\" },\n        { \"beta40\", \"should\" },\n    };\n#define ASIZE (sizeof(toBsorted)\/sizeof(sTwoStrings))\n    int k, maxlens[ASIZE];\n    char format[12];\n    sTwoStrings *cp;\n\n    qsort( (void*)toBsorted, ASIZE, sizeof(sTwoStrings),cmprStrgs); \n\n    for (k=0,cp=toBsorted; k < ASIZE; k++,cp++) {\n        maxlens[k] = maxstrlen(cp->key, cp->value);   \n        sprintf(format,\"\u00a0%%-%ds\", maxlens[k]);\n        printf(format, toBsorted[k].value);\n\t}\n    printf(\"\\n\");\n    for (k=0; k < ASIZE; k++) {\n        sprintf(format,\"\u00a0%%-%ds\", maxlens[k]);\n        printf(format, toBsorted[k].key);\n\t}\n    printf(\"\\n\");\n\n  return 0;\n}\n\n\n   This      is   the order     in  which    many strings should      be sorted.\n alpha1 beta001 beta1 beta3 beta05 beta11 Beta11a beta11a beta40 beta041 Betamax\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator and the qsort function from the standard library.","id":3439}
    {"lang_cluster":"C","source_code":"\nint i, j;\nfor (i = 1; i <= 5; i++) {\n  for (j = 1; j <= i; j++)\n    putchar('*');\n  puts(\"\");\n}\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":3440}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    int size;\n    void **keys;\n    void **values;\n} hash_t;\n\nhash_t *hash_new (int size) {\n    hash_t *h = calloc(1, sizeof (hash_t));\n    h->keys = calloc(size, sizeof (void *));\n    h->values = calloc(size, sizeof (void *));\n    h->size = size;\n    return h;\n}\n\nint hash_index (hash_t *h, void *key) {\n    int i = (int) key % h->size;\n    while (h->keys[i] && h->keys[i] != key)\n        i = (i + 1) % h->size;\n    return i;\n}\n\nvoid hash_insert (hash_t *h, void *key, void *value) {\n    int i = hash_index(h, key);\n    h->keys[i] = key;\n    h->values[i] = value;\n}\n\nvoid *hash_lookup (hash_t *h, void *key) {\n    int i = hash_index(h, key);\n    return h->values[i];\n}\n\nint main () {\n    hash_t *h = hash_new(15);\n    hash_insert(h, \"hello\", \"world\");\n    hash_insert(h, \"a\", \"b\");\n    printf(\"hello => %s\n\", hash_lookup(h, \"hello\"));\n    printf(\"herp => %s\n\", hash_lookup(h, \"herp\"));\n    printf(\"a => %s\n\", hash_lookup(h, \"a\"));\n    return 0;\n}\n","human_summarization":"create an associative array, also referred to as a dictionary, map, or hash.","id":3441}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n\n\/* always assuming int is at least 32 bits *\/\nint rand();\nint rseed = 0;\n\ninline void srand(int x)\n{\n\trseed = x;\n}\n\n#ifndef MS_RAND\n#define RAND_MAX ((1U << 31) - 1)\n\ninline int rand()\n{\n\treturn rseed = (rseed * 1103515245 + 12345) & RAND_MAX;\n}\n\n#else \/* MS rand *\/\n\n#define RAND_MAX_32 ((1U << 31) - 1)\n#define RAND_MAX ((1U << 15) - 1)\n\ninline int rand()\n{\n\treturn (rseed = (rseed * 214013 + 2531011) & RAND_MAX_32) >> 16;\n}\n\n#endif\/* MS_RAND *\/\n\nint main()\n{\n\tint i;\n\tprintf(\"rand max is %d\\n\", RAND_MAX);\n\n\tfor (i = 0; i < 100; i++)\n\t\tprintf(\"%d\\n\", rand());\n\n\treturn 0;\n}\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). The generators use the linear congruential generator formula, with different constants for each version. The code ensures that each generator produces the same sequence of integers as the original when given the same seed. The BSD version generates numbers in the range of 0 to 2147483647, while the Microsoft version generates numbers in the range of 0 to 32767. The code also allows for easy reproduction of a sequence of numbers from the same seed.","id":3442}
    {"lang_cluster":"C","source_code":"\n\nvoid insert_append (struct link *anchor, struct link *newlink) {\n  newlink->next = anchor->next;\n  anchor->next = newlink;\n}\n\n\nstruct link *a, *b, *c;\na = malloc(sizeof(link));\nb = malloc(sizeof(link));\nc = malloc(sizeof(link));\na->data = 1;\nb->data = 2;\nc->data = 3;\n\n\n insert_append (a, b);\n\n\n insert_append (a, c);\n\n\n free (a);\n free (b);\n free (c);\n\n","human_summarization":"The code defines a method to insert an element into a singly-linked list after a given element. It specifically inserts element C after element A in a list with elements A and B. The code also includes checks for valid values and memory management after the operation is completed.","id":3443}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdbool.h>\n\nvoid halve(int *x) { *x >>= 1; }\nvoid doublit(int *x)  { *x <<= 1; }\nbool iseven(const int x) { return (x & 1) ==  0; }\n\nint ethiopian(int plier,\n\t      int plicand, const bool tutor)\n{\n  int result=0;\n\n  if (tutor)\n    printf(\"ethiopian multiplication of %d by %d\\n\", plier, plicand);\n  \n  while(plier >= 1) {\n    if ( iseven(plier) ) {\n      if (tutor) printf(\"%4d %6d struck\\n\", plier, plicand);\n    } else {\n      if (tutor) printf(\"%4d %6d kept\\n\", plier, plicand);\n      result += plicand;\n    }\n    halve(&plier); doublit(&plicand);\n  }\n  return result;\n}\n\nint main()\n{\n  printf(\"%d\\n\", ethiopian(17, 34, true));\n  return 0;\n}\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":3444}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n\ntypedef struct {int val, op, left, right;} Node;\n\nNode nodes[10000];\nint iNodes;\n\nint b;\nfloat eval(Node x){\n    if (x.op != -1){\n        float l = eval(nodes[x.left]), r = eval(nodes[x.right]);\n        switch(x.op){\n            case 0: return l+r;\n            case 1: return l-r;\n            case 2: return r-l;\n            case 3: return l*r;\n            case 4: return r?l\/r:(b=1,0);\n            case 5: return l?r\/l:(b=1,0);\n        }\n    }\n    else return x.val*1.;\n}\n\nvoid show(Node x){\n    if (x.op != -1){\n        printf(\"(\");\n        switch(x.op){\n            case 0: show(nodes[x.left]); printf(\" + \"); show(nodes[x.right]); break;\n            case 1: show(nodes[x.left]); printf(\" - \"); show(nodes[x.right]); break;\n            case 2: show(nodes[x.right]); printf(\" - \"); show(nodes[x.left]); break;\n            case 3: show(nodes[x.left]); printf(\" * \"); show(nodes[x.right]); break;\n            case 4: show(nodes[x.left]); printf(\" \/ \"); show(nodes[x.right]); break;\n            case 5: show(nodes[x.right]); printf(\" \/ \"); show(nodes[x.left]); break;\n        }\n        printf(\")\");\n    }\n    else printf(\"%d\", x.val);\n}\n\nint float_fix(float x){ return x < 0.00001 && x > -0.00001; }\n\nvoid solutions(int a[], int n, float t, int s){\n    if (s == n){\n        b = 0;\n        float e = eval(nodes[0]);        \n        \n        if (!b && float_fix(e-t)){\n            show(nodes[0]);\n            printf(\"\\n\");\n        }\n    }\n    else{\n        nodes[iNodes++] = (typeof(Node)){a[s],-1,-1,-1};\n        \n        for (int op = 0; op < 6; op++){    \n            int k = iNodes-1;\n            for (int i = 0; i < k; i++){\n                nodes[iNodes++] = nodes[i];\n                nodes[i] = (typeof(Node)){-1,op,iNodes-1,iNodes-2};\n                solutions(a, n, t, s+1);\n                nodes[i] = nodes[--iNodes];\n            }\n        }\n        \n        iNodes--;\n    }\n};\n\nint main(){\n    \/\/ define problem\n\n    int a[4] = {8, 3, 8, 3};\n    float t = 24;\n\n    \/\/ print all solutions\n\n    nodes[0] = (typeof(Node)){a[0],-1,-1,-1};\n    iNodes = 1;\n\n    solutions(a, sizeof(a)\/sizeof(int), t, 1);\n\n    return 0;\n}\n\n","human_summarization":"The code takes four digits as input, either from the user or generated randomly, and calculates arithmetic expressions based on the rules of the 24 game. It displays examples of solutions produced. The code uses a brute-force approach with a specific time complexity and recursion depth. It can be adjusted to work with more than four numbers, different goals, and additional operations. If no solutions are found, it prints nothing.","id":3445}
    {"lang_cluster":"C","source_code":"\nint factorial(int n) {\n    int result = 1;\n    for (int i = 1; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\n\nint factorialSafe(int n) {\n    int result = 1;\n    if(n<0)\n        return -1;\n    for (int i = 1; i <= n; ++i)\n        result *= i;\n    return result;\n}\n\nint factorial(int n) {\n    return n == 0 ? 1 : n * factorial(n - 1);\n}\n\n\nint factorialSafe(int n) {\n    return n<0 ? -1 : n == 0 ? 1 : n * factorialSafe(n - 1);\n}\n\nTail \nint fac_aux(int n, int acc) {\n    return n < 1 ? acc : fac_aux(n - 1, acc * n);\n}\n\nint fac_auxSafe(int n, int acc) {\n    return n<0 ? -1 : n < 1 ? acc : fac_aux(n - 1, acc * n);\n}\n\nint factorial(int n) {\n    return fac_aux(n, 1);\n}\n\n\n#include <stdio.h>\n\n#define l11l 0xFFFF\n#define ll1 for\n#define ll111 if\n#define l1l1 unsigned\n#define l111 struct\n#define lll11 short\n#define ll11l long\n#define ll1ll putchar\n#define l1l1l(l) l=malloc(sizeof(l111 llll1));l->lll1l=1-1;l->ll1l1=1-1;\n#define l1ll1 *lllll++=l1ll%10000;l1ll\/=10000;\n#define l1lll ll111(!l1->lll1l){l1l1l(l1->lll1l);l1->lll1l->ll1l1=l1;}\\\nlllll=(l1=l1->lll1l)->lll;ll=1-1;\n#define llll 1000\n\n\n\n\n                                                     l111 llll1 {\n                                                     l111 llll1 *\n      lll1l,*ll1l1        ;l1l1                      lll11 lll [\n      llll];};main      (){l111 llll1                *ll11,*l1l,*\n      l1, *ll1l, *    malloc ( ) ; l1l1              ll11l l1ll ;\n      ll11l l11,ll  ,l;l1l1 lll11 *lll1,*            lllll; ll1(l\n      =1-1 ;l< 14; ll1ll(\"\\t\\\"8)>l\\\"9!.)>vl\"         [l]^'L'),++l\n      );scanf(\"%d\",&l);l1l1l(l1l) l1l1l(ll11         ) (l1=l1l)->\n      lll[l1l->lll[1-1]     =1]=l11l;ll1(l11         =1+1;l11<=l;\n      ++l11){l1=ll11;         lll1 = (ll1l=(         ll11=l1l))->\n      lll; lllll =(            l1l=l1)->lll;         ll=(l1ll=1-1\n      );ll1(;ll1l->             lll1l||l11l!=        *lll1;){l1ll\n      +=l11**lll1++             ;l1ll1 ll111         (++ll>llll){\n      l1lll lll1=(              ll1l =ll1l->         lll1l)->lll;\n      }}ll1(;l1ll;              ){l1ll1 ll111        (++ll>=llll)\n      { l1lll} } *              lllll=l11l;}\n      ll1(l=(ll=1-              1);(l<llll)&&\n      (l1->lll[ l]              !=l11l);++l);        ll1 (;l1;l1=\n      l1->ll1l1,l=              llll){ll1(--l        ;l>=1-1;--l,\n      ++ll)printf(              (ll)?((ll%19)        ?\"%04d\":(ll=\n      19,\"\\n%04d\")              ):\"%4d\",l1->         lll[l] ) ; }\n                                                     ll1ll(10); }\n\n","human_summarization":"The code implements a function to calculate the factorial of a given number. The function can be either iterative or recursive. It optionally handles negative input values by returning -1. The maximum factorial it can calculate is 429539.","id":3446}
    {"lang_cluster":"C","source_code":"\nLibrary: ncurses\n#include <stdio.h>\n#include <stdarg.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <curses.h>\n#include <string.h>\n\n#define MAX_NUM_TRIES 72\n#define LINE_BEGIN 7\n#define LAST_LINE 18\n\nint yp=LINE_BEGIN, xp=0;\n\nchar number[5];\nchar guess[5];\n\n#define MAX_STR 256\nvoid mvaddstrf(int y, int x, const char *fmt, ...)\n{\n  va_list args;\n  char buf[MAX_STR];\n  \n  va_start(args, fmt);\n  vsprintf(buf, fmt, args);\n  move(y, x);\n  clrtoeol();\n  addstr(buf);\n  va_end(args);\n}\n\nvoid ask_for_a_number()\n{\n  int i=0;\n  char symbols[] = \"123456789\";\n\n  move(5,0); clrtoeol();\n  addstr(\"Enter four digits: \");\n  while(i<4) {\n    int c = getch();\n    if ( (c >= '1') && (c <= '9') && (symbols[c-'1']!=0) ) {\n      addch(c);\n      symbols[c-'1'] = 0;\n      guess[i++] = c;\n    }\n  }\n}\n\nvoid choose_the_number()\n{\n  int i=0, j;\n  char symbols[] = \"123456789\";\n\n  while(i<4) {\n    j = rand() % 9;\n    if ( symbols[j] != 0 ) {\n      number[i++] = symbols[j];\n      symbols[j] = 0;\n    }\n  }\n}\n\n\nbool take_it_or_not()\n{\n  int i;\n  int cows=0, bulls=0;\n\n  for(i=0; i < 4; i++) {\n    if ( number[i] == guess[i] ) {\n      bulls++;\n    } else if ( strchr(number, guess[i]) != NULL ) {\n      cows++;\n    }\n  }\n  move(yp, xp);\n  addstr(guess); addch(' ');\n  if ( bulls == 4 ) { yp++; return true; }\n  if ( (cows==0) && (bulls==0) ) addch('-');\n  while( cows-- > 0 ) addstr(\"O\");\n  while( bulls-- > 0 ) addstr(\"X\");\n  yp++;\n  if ( yp > LAST_LINE ) {\n    yp = LINE_BEGIN;\n    xp += 10;\n  }\n  return false;\n}\n\nbool ask_play_again()\n{\n  int i;\n\n  while(yp-- >= LINE_BEGIN) {\n    move(yp, 0); clrtoeol();\n  }\n  yp = LINE_BEGIN; xp = 0;\n\n  move(21,0); clrtoeol();\n  addstr(\"Do you want to play again? [y\/n]\");\n  while(true) {\n    int a = getch();\n    switch(a) {\n    case 'y':\n    case 'Y':\n      return true;\n    case 'n':\n    case 'N':\n      return false;\n    }\n  }\n}\n\n\nint main()\n{\n  bool bingo, again;\n  int tries = 0;\n\n  initscr(); cbreak(); noecho();\n  clear();\n\n  number[4] = guess[4] = 0;\n\n  mvaddstr(0,0, \"I choose a number made of 4 digits (from 1 to 9) without repetitions\\n\"\n                \"You enter a number of 4 digits, and I say you how many of them are\\n\"\n                \"in my secret number but in wrong position (cows or O), and how many\\n\"\n                \"are in the right position (bulls or X)\");\n  do {\n    move(20,0); clrtoeol(); move(21, 0); clrtoeol();\n    srand(time(NULL));\n    choose_the_number();\n    do {\n      ask_for_a_number();\n      bingo = take_it_or_not();\n      tries++;\n    } while(!bingo && (tries < MAX_NUM_TRIES));\n    if ( bingo ) \n      mvaddstrf(20, 0, \"You guessed %s correctly in %d attempts!\", number, tries);\n    else\n      mvaddstrf(20,0, \"Sorry, you had only %d tries...; the number was %s\", \n\t\tMAX_NUM_TRIES, number);\n    again = ask_play_again();\n    tries = 0; \n  } while(again);\n  nocbreak(); echo(); endwin();\n  return EXIT_SUCCESS;\n}\n\n","human_summarization":"The code generates a random four-digit number with unique digits from 1 to 9. It then prompts the user to guess this number, rejecting any malformed guesses. The code calculates and prints a score for each guess, with \"bulls\" representing correct digits in the correct position and \"cows\" representing correct digits in the wrong position. The game ends when the user correctly guesses the number.","id":3447}
    {"lang_cluster":"C","source_code":"\n#include <stdlib.h>\n#include <math.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\ndouble drand()   \/* uniform distribution, (0..1] *\/\n{\n  return (rand()+1.0)\/(RAND_MAX+1.0);\n}\ndouble random_normal()  \/* normal distribution, centered on 0, std dev 1 *\/\n{\n  return sqrt(-2*log(drand())) * cos(2*M_PI*drand());\n}\nint main()\n{\n  int i;\n  double rands[1000];\n  for (i=0; i<1000; i++)\n    rands[i] = 1.0 + 0.5*random_normal();\n  return 0;\n}\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":3448}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n\nint dot_product(int *, int *, size_t);\n\nint\nmain(void)\n{\n        int a[3] = {1, 3, -5};\n        int b[3] = {4, -2, -1};\n\n        printf(\"%d\\n\", dot_product(a, b, sizeof(a) \/ sizeof(a[0])));\n\n        return EXIT_SUCCESS;\n}\n\nint\ndot_product(int *a, int *b, size_t n)\n{\n        int sum = 0;\n        size_t i;\n\n        for (i = 0; i < n; i++) {\n                sum += a[i] * b[i];\n        }\n\n        return sum;\n}\n\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":3449}
    {"lang_cluster":"C","source_code":"\n\n#include <stdlib.h>\n#include <stdio.h>\n\nchar *get_line(FILE* fp)\n{\n\tint len = 0, got = 0, c;\n\tchar *buf = 0;\n\n\twhile ((c = fgetc(fp)) != EOF) {\n\t\tif (got + 1 >= len) {\n\t\t\tlen *= 2;\n\t\t\tif (len < 4) len = 4;\n\t\t\tbuf = realloc(buf, len);\n\t\t}\n\t\tbuf[got++] = c;\n\t\tif (c == '\\n') break;\n\t}\n\tif (c == EOF && !got) return 0;\n\n\tbuf[got++] = '\\0';\n\treturn buf;\n}\n\nint main()\n{\n\tchar *s;\n\twhile ((s = get_line(stdin))) {\n\t\tprintf(\"%s\",s);\n\t\tfree(s);\n\t}\n\treturn 0;\n}\n\n","human_summarization":"read data from a text stream either word-by-word or line-by-line until no more data is available. It reads an arbitrarily long line each time and returns a null-terminated string. The caller is responsible for freeing the string.","id":3450}
    {"lang_cluster":"C","source_code":"\n#include <libxml\/parser.h>\n#include <libxml\/tree.h>\n  \nint main()\n{\n  xmlDoc *doc = xmlNewDoc(\"1.0\");\n  xmlNode *root = xmlNewNode(NULL, BAD_CAST \"root\");\n  xmlDocSetRootElement(doc, root);\n\n  xmlNode *node = xmlNewNode(NULL, BAD_CAST \"element\");\n  xmlAddChild(node, xmlNewText(BAD_CAST \"some text here\"));\n  xmlAddChild(root, node);\n\n  xmlSaveFile(\"myfile.xml\", doc);\n \n  xmlFreeDoc(doc);\n  xmlCleanupParser();\n}\n\n\n#include <gadget\/gadget.h>\n\nLIB_GADGET_START\n\nMain\n   String XML, body;\n   Stack{\n       Store ( XML, Parser( \"element\", \"\",\"Some text here\", NORMAL_TAG) );\n       Store ( XML, Parser( \"root\", \"\",XML, NORMAL_TAG) );\n   } Stack_off;\n   \n   body = Multi_copy( body,\"<?xml version=\\\"1.0\\\"\u00a0?>\", XML, NULL);\n   Print \"%s\\n\", body;\n   \n   Free secure XML, body;\nEnd\n\n\n#include <gadget\/gadget.h>\n\nLIB_GADGET_START\n\nMain\n   String XML, body;\n   \n   Get_fn_let( XML, Parser( \"element\", \"\",\"Some text here\", NORMAL_TAG) );\n   Get_fn_let( XML, Parser( \"root\", \"\",XML, NORMAL_TAG) );\n   \n   body = Multi_copy( body,\"<?xml version=\\\"1.0\\\"\u00a0?>\", XML, NULL);\n   Print \"%s\\n\", body;\n   \n   Free secure XML, body;\nEnd\n\n\n#include <gadget\/gadget.h>\n\nLIB_GADGET_START\n\nMain\n   String XML, body;\n   Stack{\n       Store ( XML, Parser( \"root\", \"\", \n                    Parser( \"element\", \"\",\"Some text here\", NORMAL_TAG), \n                    NORMAL_TAG) );\n   } Stack_off;\n   \n   body = Multi_copy( body,\"<?xml version=\\\"1.0\\\"\u00a0?>\", XML, NULL);\n   Print \"%s\\n\", body;\n   \n   Free secure XML, body;\nEnd\n\n\n#include <gadget\/gadget.h>\n\nLIB_GADGET_START\n\nMain\n   String body;\n   Stack{\n       Store ( body, Multi_copy( body,\"<?xml version=\\\"1.0\\\"\u00a0?>\", \n                                 Parser( \"root\", \"\", Parser( \"element\", \"\",\"Some text here\", \n                                 NORMAL_TAG), NORMAL_TAG), \n                                 NULL) );\n   }\n\n   Print \"%s\\n\", body;\n   \n   Free secure body;\nEnd\n\n\n","human_summarization":"Create a simple DOM and serialize it to XML format. The XML output includes a root element containing a single element with some text. The code also includes different versions with varying memory allocations.","id":3451}
    {"lang_cluster":"C","source_code":"\n\nIt shows system time as \"Www Mmm dd hh:mm:ss yyyy\", where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year.#include<time.h>\n#include<stdio.h>\n#include<stdlib.h>\nint main(){\n  time_t my_time = time(NULL);\n  printf(\"%s\", ctime(&my_time));\n  return 0;\n}\n\n","human_summarization":"the system time, which can be used for debugging, network information, random number seeds, or program performance. The time can be outputted using a system command or a built-in language function. The time units are also specified.","id":3452}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <ctype.h>\n#include <string.h>\n\nint sedol_weights[] = {1, 3, 1, 7, 3, 9}; \nconst char *reject = \"AEIOUaeiou\";\n\nint sedol_checksum(const char *sedol6)\n{\n  int len = strlen(sedol6);\n  int sum = 0, i;\n\n  if ( len == 7 ) {\n    fprintf(stderr, \"SEDOL code already checksummed? (%s)\\n\", sedol6);\n    return sedol6[6] & 0x7f;\n  }\n  if ( (len > 7) || (len < 6) || ( strcspn(sedol6, reject) != 6 )) {\n    fprintf(stderr, \"not a SEDOL code? (%s)\\n\", sedol6);\n    return -1;\n  }\n  for(i=0; i < 6; i++) {\n    if ( isdigit(sedol6[i]) ) {\n      sum += (sedol6[i]-'0')*sedol_weights[i];\n    } else if ( isalpha(sedol6[i]) ) {\n      sum += ((toupper(sedol6[i])-'A') + 10)*sedol_weights[i];\n    } else {\n      fprintf(stderr, \"SEDOL with not alphanumeric digit\\n\");\n      return -1;\n    }\n  }\n  return (10 - (sum%10))%10 + '0'; \n}\n\n\n#define MAXLINELEN 10\nint main()\n{\n  char line[MAXLINELEN];\n  int sr, len;\n  while( fgets(line, MAXLINELEN, stdin) != NULL ) {\n    len = strlen(line);\n    if ( line[len-1] == '\\n' ) line[len-1]='\\0';\n    sr = sedol_checksum(line);\n    if ( sr > 0 )\n      printf(\"%s%c\\n\", line, sr);\n  }\n  return 0;\n}\n\n\n7108899\nB0YBKJ7\n4065663\nB0YBLH2\n2282765\nB0YBKL9\n5579107\nB0YBKR5\n5852842\nB0YBKT7\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the respective SEDOL. It also validates the input to ensure it is correctly formed according to the SEDOL string rules. The SEDOLs are read from standard input, one per line, and must meet specific encoding specifications. The code then outputs the original SEDOLs with the appended checksum digit.","id":3453}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <math.h>\n\nconst char *shades = \".:!*oe&#%@\";\n\ndouble light[3] = { 30, 30, -50 };\nvoid normalize(double * v)\n{\n        double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n        v[0] \/= len; v[1] \/= len; v[2] \/= len;\n}\n\ndouble dot(double *x, double *y)\n{\n        double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n        return d < 0 ? -d : 0;\n}\n\nvoid draw_sphere(double R, double k, double ambient)\n{\n        int i, j, intensity;\n        double b;\n        double vec[3], x, y;\n        for (i = floor(-R); i <= ceil(R); i++) {\n                x = i + .5;\n                for (j = floor(-2 * R); j <= ceil(2 * R); j++) {\n                        y = j \/ 2. + .5;\n                        if (x * x + y * y <= R * R) {\n                                vec[0] = x;\n                                vec[1] = y;\n                                vec[2] = sqrt(R * R - x * x - y * y);\n                                normalize(vec);\n                                b = pow(dot(light, vec), k) + ambient;\n                                intensity = (1 - b) * (sizeof(shades) - 1);\n                                if (intensity < 0) intensity = 0;\n                                if (intensity >= sizeof(shades) - 1)\n                                        intensity = sizeof(shades) - 2;\n                                putchar(shades[intensity]);\n                        } else\n                                putchar(' ');\n                }\n                putchar('\\n');\n        }\n}\n\n\nint main()\n{\n        normalize(light);\n        draw_sphere(20, 4, .1);\n        draw_sphere(10, 2, .4);\n\n        return 0;\n}\n\n\n","human_summarization":"represent a sphere either graphically or in ASCII art, with the option for static or rotational projection. The lighting calculation used for shading is basic.","id":3454}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n \nchar* addSuffix(int num, char* buf, size_t len)\n{\n    char *suffixes[4] = { \"th\", \"st\", \"nd\", \"rd\" };\n    int i;\n\n    switch (num % 10)\n    {\n        case 1 : i = (num % 100 == 11) ? 0 : 1;\n\t         break;\n        case 2 : i = (num % 100 == 12) ? 0 : 2;\n                 break;\n        case 3 : i = (num % 100 == 13) ? 0 : 3;\n                 break;\n        default: i = 0;\n    };\n \n    snprintf(buf, len, \"%d%s\", num, suffixes[i]);\n    return buf;\n}\n\nint main(void)\n{\n    int i;\n\n    printf(\"Set [0,25]:\\n\");\n    for (i = 0; i < 26; i++)\n    {\n        char s[5];\n        printf(\"%s \", addSuffix(i, s, 5));\n    }\n    putchar('\\n'); \n\n    printf(\"Set [250,265]:\\n\");\n    for (i = 250; i < 266; i++)\n    {\n        char s[6];\n        printf(\"%s \", addSuffix(i, s, 6));\n    }\n    putchar('\\n'); \n\n    printf(\"Set [1000,1025]:\\n\");\n    for (i = 1000; i < 1026; i++)\n    {\n        char s[7];\n        printf(\"%s \", addSuffix(i, s, 7));\n    }\n    putchar('\\n');\n\n    return 0;\n}\n\n\n#include <stdlib.h>\n#include <stdio.h>\n\nstatic int digits(const int x) {\n    if (x \/ 10 == 0) return 1;\n    return 1 + digits(x \/ 10);\n}\n\nstatic char * get_ordinal(const int i) {\n    const int string_size = digits(i) + 3;\n    char * o_number = malloc(string_size);\n    char * ordinal;\n    if(i % 100 >= 11 && i % 100 <= 13) ordinal = \"th\";\n    else ordinal = i\/10==1?\"th\":i%10==1?\"st\":i%10==2?\"nd\":i%10==3?\"rd\":\"th\";\n    sprintf_s(o_number, string_size, \"%d%s\", i, ordinal);\n    return o_number;\n}\n\nstatic void print_range(const int begin, const int end) {\n    printf(\"Set [%d,%d]:\\n\", begin, end);\n    for (int i = begin; i <= end; i++) {\n        char * o_number = get_ordinal(i);\n        printf(\"%s \", o_number);\n        free(o_number);\n    }\n    printf(\"\\n\");\n}\n\nint main(void) {\n    print_range(0, 25);\n    print_range(250, 265);\n    print_range(1000, 1025);\n}\n\n\n","human_summarization":"The code implements a function that accepts a non-negative integer as input and returns a string representation of the number with its ordinal suffix. The function is tested with integer ranges 0..25, 250..265, and 1000..1025. The use of apostrophes in the output is optional.","id":3455}
    {"lang_cluster":"C","source_code":"\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n  \/* removes all chars from string *\/\nchar *strip_chars(const char *string, const char *chars)\n{\n  char * newstr = malloc(strlen(string) + 1);\n  int counter = 0;\n\n  for ( ; *string; string++) {\n    if (!strchr(chars, *string)) {\n      newstr[ counter ] = *string;\n      ++ counter;\n    }\n  }\n\n  newstr[counter] = 0;\n  return newstr;\n}\n\nint main(void)\n{\n  char *new = strip_chars(\"She was a soul stripper. She took my heart!\", \"aei\");\n  printf(\"%s\\n\", new);\n\n  free(new);\n  return 0;\n}\n\n\nResult:\nSh ws  soul strppr. Sh took my hrt!\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nchar *strip(const char * str, const char *pat)\n{\n\t\/*  char replacement is typically done with lookup tables if\n\t *  the replacement set can be large: it turns O(m n) into\n\t *  O(m + n).\n\t *  If same replacement pattern is going to be applied to many\n\t *  strings, it's better to build a table beforehand and reuse it.\n\t *  If charset is big like unicode, table needs to be implemented\n\t *  more efficiently, say using bit field or hash table -- it\n\t *  all depends on the application.\n\t *\/\n\tint i = 0, tbl[128] = {0};\n\twhile (*pat != '\\0') tbl[(int)*(pat++)] = 1;\n\n\tchar *ret = malloc(strlen(str) + 1);\n\tdo {\n\t\tif (!tbl[(int)*str])\n\t\t\tret[i++] = *str;\n\t} while (*(str++) != '\\0');\n\n\t\/*  assuming realloc is efficient and succeeds; if not, we could\n\t *  do a two-pass, count first, alloc and strip second\n\t *\/\n\treturn realloc(ret, i);\n}\n\nint main()\n{\n\tchar * x = strip(\"She was a soul stripper. She took my heart!\", \"aei\");\n\tprintf(x);\n\tfree(x);\n\n\treturn 0;\n}\nOutput same as above.\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":3456}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct replace_info {\n    int n;\n    char *text;\n};\n\nint compare(const void *a, const void *b)\n{\n    struct replace_info *x = (struct replace_info *) a;\n    struct replace_info *y = (struct replace_info *) b;\n    return x->n - y->n;\n}\n\nvoid generic_fizz_buzz(int max, struct replace_info *info, int info_length)\n{\n    int i, it;\n    int found_word;\n\n    for (i = 1; i < max; ++i) {\n        found_word = 0;\n\n        \/* Assume sorted order of values in the info array *\/\n        for (it = 0; it < info_length; ++it) {\n            if (0 == i % info[it].n) {\n                printf(\"%s\", info[it].text);\n                found_word = 1;\n            }\n        }\n\n        if (0 == found_word)\n            printf(\"%d\", i);\n\n        printf(\"\\n\");\n    }\n}\n\nint main(void)\n{\n    struct replace_info info[3] = {\n        {5, \"Buzz\"},\n        {7, \"Baxx\"},\n        {3, \"Fizz\"}\n    };\n\n    \/* Sort information array *\/\n    qsort(info, 3, sizeof(struct replace_info), compare);\n\n    \/* Print output for generic FizzBuzz *\/\n    generic_fizz_buzz(20, info, 3);\n    return 0;\n}\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":3457}
    {"lang_cluster":"C","source_code":"\n#include<stdio.h>\n#include<string.h>\n#include<stdlib.h>\n\nint main()\n{\n    char str[100]=\"my String\";\n    char *cstr=\"Changed \";\n    char *dup;\n    sprintf(str,\"%s%s\",cstr,(dup=strdup(str)));\n    free(dup);\n    printf(\"%s\\n\",str);\n    return 0;\n}\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":3458}
    {"lang_cluster":"C","source_code":"\n\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n\n\/* x, y: coordinates of current point; dx, dy: direction of movement.\n * Think turtle graphics.  They are divided by scale, so as to keep\n * very small coords\/increments without losing precission. clen is\n * the path length travelled, which should equal to scale at the end\n * of the curve.\n *\/\nlong long x, y, dx, dy, scale, clen;\ntypedef struct { double r, g, b; } rgb;\nrgb ** pix;\n\n\/* for every depth increase, rotate 45 degrees and scale up by sqrt(2)\n * Note how coords can still be represented by integers.\n *\/\nvoid sc_up()\n{\n\tlong long tmp = dx - dy; dy = dx + dy; dx = tmp;\n\tscale *= 2; x *= 2; y *= 2;\n}\n\n\/* Hue changes from 0 to 360 degrees over entire length of path; Value\n * oscillates along the path to give some contrast between segments\n * close to each other spatially.  RGB derived from HSV gets *added*\n * to each pixel reached; they'll be dealt with later.\n *\/\nvoid h_rgb(long long x, long long y)\n{\n\trgb *p = &pix[y][x];\n\n#\tdefine SAT 1\n\tdouble h = 6.0 * clen \/ scale;\n\tdouble VAL = 1 - (cos(3.141592653579 * 64 * clen \/ scale) - 1) \/ 4;\n\tdouble c = SAT * VAL;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n\n\tswitch((int)h) {\n\tcase 0: p->r += c; p->g += X; return;\n\tcase 1:\tp->r += X; p->g += c; return;\n\tcase 2: p->g += c; p->b += X; return;\n\tcase 3: p->g += X; p->b += c; return;\n\tcase 4: p->r += X; p->b += c; return;\n\tdefault:\n\t\tp->r += c; p->b += X;\n\t}\n}\n\n\/* string rewriting.  No need to keep the string itself, just execute\n * its instruction recursively.\n *\/\nvoid iter_string(const char * str, int d)\n{\n\tlong tmp;\n#\tdefine LEFT  tmp = -dy; dy = dx; dx = tmp\n#\tdefine RIGHT tmp = dy; dy = -dx; dx = tmp\n\twhile (*str != '\\0') {\n\t\tswitch(*(str++)) {\n\t\tcase 'X':\tif (d) iter_string(\"X+YF+\", d - 1); continue;\n\t\tcase 'Y':\tif (d) iter_string(\"-FX-Y\", d - 1); continue;\n\t\tcase '+':\tRIGHT; continue;\n\t\tcase '-':\tLEFT;  continue;\n\t\tcase 'F':\n                        \/* draw: increment path length; add color; move. Here\n                         * is why the code does not allow user to choose arbitrary\n                         * image size: if it's not a power of two, aliasing will\n                         * occur and grid-like bright or dark lines will result\n                         * when normalized later.  It can be gotten rid of, but that\n                         * involves computing multiplicative order and would be a huge\n                         * bore.\n                         *\/\n\t\t\t\tclen ++;\n\t\t\t\th_rgb(x\/scale, y\/scale);\n\t\t\t\tx += dx; y += dy;\n\t\t\t\tcontinue;\n\t\t}\n\t}\n}\n\nvoid dragon(long leng, int depth)\n{\n\tlong i, d = leng \/ 3 + 1;\n\tlong h = leng + 3, w = leng + d * 3 \/ 2 + 2;\n\n\t\/* allocate pixel buffer *\/\n\trgb *buf = malloc(sizeof(rgb) * w * h);\n\tpix = malloc(sizeof(rgb *) * h);\n\tfor (i = 0; i < h; i++)\n\t\tpix[i] = buf + w * i;\n\tmemset(buf, 0, sizeof(rgb) * w * h);\n\n        \/* init coords; scale up to desired; exec string *\/\n\tx = y = d; dx = leng; dy = 0; scale = 1; clen = 0;\n\tfor (i = 0; i < depth; i++) sc_up();\n\titer_string(\"FX\", depth);\n\n\t\/* write color PNM file *\/\n\tunsigned char *fpix = malloc(w * h * 3);\n\tdouble maxv = 0, *dbuf = (double*)buf;\n\n        \/* find highest value among pixels; normalize image according\n         * to it.  Highest value would be at points most travelled, so\n         * this ends up giving curve edge a nice fade -- it's more apparaent\n         * if we increase iteration depth by one or two.\n         *\/\n\tfor (i = 3 * w * h - 1; i >= 0; i--)\n\t\tif (dbuf[i] > maxv) maxv = dbuf[i];\n\tfor (i = 3 * h * w - 1; i >= 0; i--)\n\t\tfpix[i] = 255 * dbuf[i] \/ maxv;\n\n\tprintf(\"P6\\n%ld %ld\\n255\\n\", w, h);\n\tfflush(stdout); \/* printf and fwrite may treat buffer differently *\/\n\tfwrite(fpix, h * w * 3, 1, stdout);\n}\n\nint main(int c, char ** v)\n{\n\tint size, depth;\n\n\tdepth  = (c > 1) ? atoi(v[1]) : 10;\n\tsize = 1 << depth;\n\n\tfprintf(stderr, \"size: %d depth: %d\\n\", size, depth);\n\tdragon(size, depth * 2);\n\n\treturn 0;\n}\n\n","human_summarization":"The code generates a dragon curve fractal, a mathematical shape that is self-replicating. It uses various algorithms to create the fractal, such as recursive methods, successive approximation, and iterative methods. The code also allows for the curve to be displayed directly or written to an image file. It can calculate absolute direction and coordinates for each point, and can also test if a given point or segment is on the curve. Additionally, the code can be run with a specified depth to control the complexity of the fractal.","id":3459}
    {"lang_cluster":"C","source_code":"\n#include <stdlib.h>\n#include <stdio.h>\n#include <time.h>\n\nint main(void)\n{\n    int n;\n    int g;\n    char c;\n\n    srand(time(NULL));\n    n = 1 + (rand() % 10);\n\n    puts(\"I'm thinking of a number between 1 and 10.\");\n    puts(\"Try to guess it:\");\n\n    while (1) {\n        if (scanf(\"%d\", &g) != 1) {\n\t\t\/* ignore one char, in case user gave a non-number *\/\n\t\tscanf(\"%c\", &c);\n\t\tcontinue;\n\t}\n\n        if (g == n) {\n\t    puts(\"Correct!\");\n\t    return 0;\n\t}\n        puts(\"That's not my number. Try another guess:\");\n    }\n}\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":3460}
    {"lang_cluster":"C","source_code":"\n#include <stdlib.h>\n\n#define N 26\n\nint main() {\n    unsigned char lower[N];\n\n    for (size_t i = 0; i < N; i++) {\n        lower[i] = i + 'a';\n    }\n\n    return EXIT_SUCCESS;\n}\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":3461}
    {"lang_cluster":"C","source_code":"\n#define _CRT_SECURE_NO_WARNINGS    \/\/ turn off panic warnings\n#define _CRT_NONSTDC_NO_DEPRECATE   \/\/ enable old-gold POSIX names in MSVS\n\n#include <stdio.h>\n#include <stdlib.h>\n\n\nchar* bin2str(unsigned value, char* buffer)\n{\n    \/\/ This algorithm is not the fastest one, but is relativelly simple.\n    \/\/\n    \/\/ A faster algorithm would be conversion octets to strings by a lookup table.\n    \/\/ There is only 2**8 == 256 octets, therefore we would need only 2048 bytes\n    \/\/ for the lookup table. Conversion of a 64-bit integers would need 8 lookups\n    \/\/ instead 64 and\/or\/shifts of bits etc. Even more... lookups may be implemented\n    \/\/ with XLAT or similar CPU instruction... and AVX\/SSE gives chance for SIMD.\n\n    const unsigned N_DIGITS = sizeof(unsigned) * 8;\n    unsigned mask = 1 << (N_DIGITS - 1);\n    char* ptr = buffer;\n\n    for (int i = 0; i < N_DIGITS; i++)\n    {\n        *ptr++ = '0' + !!(value & mask);\n        mask >>= 1;\n    }\n    *ptr = '\\0';\n\n    \/\/ Remove leading zeros.\n    \/\/\n    for (ptr = buffer; *ptr == '0'; ptr++)\n        ;\n\n    return ptr;\n}\n\n\nchar* bin2strNaive(unsigned value, char* buffer)\n{\n    \/\/ This variation of the solution doesn't use bits shifting etc.\n\n    unsigned n, m, p;\n\n    n = 0;\n    p = 1;  \/\/ p = 2 ** n\n    while (p <= value \/ 2)\n    {\n        n = n + 1;\n        p = p * 2;\n    }\n\n    m = 0;\n    while (n > 0)\n    {\n        buffer[m] = '0' + value \/ p;\n        value = value % p;\n        m = m + 1;\n        n = n - 1;\n        p = p \/ 2;\n    }\n\n    buffer[m + 1] = '\\0';\n    return buffer;\n}\n\n\nint main(int argc, char* argv[])\n{\n    const unsigned NUMBERS[] = { 5, 50, 9000 };\n\n    const int RADIX = 2;\n    char buffer[(sizeof(unsigned)*8 + 1)];\n\n    \/\/ Function itoa is an POSIX function, but it is not in C standard library.\n    \/\/ There is no big surprise that Microsoft deprecate itoa because POSIX is\n    \/\/ \"Portable Operating System Interface for UNIX\". Thus it is not a good\n    \/\/ idea to use _itoa instead itoa: we lost compatibility with POSIX;\n    \/\/ we gain nothing in MS Windows (itoa-without-underscore is not better\n    \/\/ than _itoa-with-underscore). The same holds for kbhit() and _kbhit() etc.\n    \/\/\n    for (int i = 0; i < sizeof(NUMBERS) \/ sizeof(unsigned); i++)\n    {\n        unsigned value = NUMBERS[i];\n        itoa(value, buffer, RADIX);\n        printf(\"itoa:          %u decimal = %s binary\\n\", value, buffer);\n    }\n\n    \/\/ Yeep, we can use a homemade bin2str function. Notice that C is very very\n    \/\/ efficient (as \"hi level assembler\") when bit manipulation is needed.\n    \/\/\n    for (int i = 0; i < sizeof(NUMBERS) \/ sizeof(unsigned); i++)\n    {\n        unsigned value = NUMBERS[i];\n        printf(\"bin2str:       %u decimal = %s binary\\n\", value, bin2str(value, buffer));\n    }\n\n    \/\/ Another implementation - see above.\n    \/\/\n    for (int i = 0; i < sizeof(NUMBERS) \/ sizeof(unsigned); i++)\n    {\n        unsigned value = NUMBERS[i];\n        printf(\"bin2strNaive:  %u decimal = %s binary\\n\", value, bin2strNaive(value, buffer));\n    }\n\n    return EXIT_SUCCESS;\n}\n\n\n","human_summarization":"\"Generates and displays a sequence of binary digits for a given non-negative integer. The output is a string of binary digits, without any leading zeros, whitespace, radix, or sign markers. The conversion can be achieved using built-in radix functions or a user-defined function.\"","id":3462}
    {"lang_cluster":"C","source_code":"\n\n#include<graphics.h>\n\nint main()\n{\n\tinitwindow(320,240,\"Red Pixel\");\n\t\n\tputpixel(100,100,RED);\n\t\n\tgetch();\n\t\n\treturn 0;\n}\n\n","human_summarization":"Creates a 320x240 window using the WinBGIm library and draws a red pixel at position (100, 100).","id":3463}
    {"lang_cluster":"C","source_code":"\nLibrary: libconfini\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <confini.h>\n\n#define rosetta_uint8_t unsigned char\n\n#define FALSE 0\n#define TRUE 1\n\n#define CONFIGS_TO_READ 5\n#define INI_ARRAY_DELIMITER ','\n\n\/* Assume that the config file represent a struct containing all the parameters to load *\/\nstruct configs {\n\tchar *fullname;\n\tchar *favouritefruit;\n\trosetta_uint8_t needspeeling;\n\trosetta_uint8_t seedsremoved;\n\tchar **otherfamily;\n\tsize_t otherfamily_len;\n\tsize_t _configs_left_;\n};\n\nstatic char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) {\n \n\t\/* Allocate a new array of strings and populate it from the stringified source *\/\n\t*arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format);\n\tchar ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL;\n\tif (!dest) { return NULL; }\n\tmemcpy(dest + *arrlen, src, buffsize);\n\tchar * iter = (char *) (dest + *arrlen);\n\tfor (size_t idx = 0; idx < *arrlen; idx++) {\n\t\tdest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format);\n\t\tini_string_parse(dest[idx], ini_format);\n\t}\n\treturn dest;\n\n}\n\nstatic int configs_member_handler (IniDispatch *this, void *v_confs) {\n\n\tstruct configs *confs = (struct configs *) v_confs;\n\n\tif (this->type != INI_KEY) {\n\n\t\treturn 0;\n\n\t}\n\n\tif (ini_string_match_si(\"FULLNAME\", this->data, this->format)) {\n\n\t\tif (confs->fullname) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \/* Remove all quotes, if any *\/\n\t\tconfs->fullname = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"FAVOURITEFRUIT\", this->data, this->format)) {\n\n\t\tif (confs->favouritefruit) { return 0; }\n\t\tthis->v_len = ini_string_parse(this->value, this->format); \/* Remove all quotes, if any *\/\n\t\tconfs->favouritefruit = strndup(this->value, this->v_len);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"NEEDSPEELING\", this->data, this->format)) {\n\n\t\tif (~confs->needspeeling & 0x80) { return 0; }\n\t\tconfs->needspeeling = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (ini_string_match_si(\"SEEDSREMOVED\", this->data, this->format)) {\n\n\t\tif (~confs->seedsremoved & 0x80) { return 0; }\n\t\tconfs->seedsremoved = ini_get_bool(this->value, TRUE);\n\t\tconfs->_configs_left_--;\n\n\t} else if (!confs->otherfamily && ini_string_match_si(\"OTHERFAMILY\", this->data, this->format)) {\n\n\t\tif (confs->otherfamily) { return 0; }\n\t\tthis->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); \/* Save memory (not strictly needed) *\/\n\t\tconfs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format);\n\t\tconfs->_configs_left_--;\n\n\t}\n\n\t\/* Optimization: stop reading the INI file when we have all we need *\/\n\treturn !confs->_configs_left_;\n\n}\n\nstatic int populate_configs (struct configs * confs) {\n\n\t\/* Define the format of the configuration file *\/\n\tIniFormat config_format = {\n\t\t.delimiter_symbol = INI_ANY_SPACE,\n\t\t.case_sensitive = FALSE,\n\t\t.semicolon_marker = INI_IGNORE,\n\t\t.hash_marker = INI_IGNORE,\n\t\t.multiline_nodes = INI_NO_MULTILINE,\n\t\t.section_paths = INI_NO_SECTIONS,\n\t\t.no_single_quotes = FALSE,\n\t\t.no_double_quotes = FALSE,\n\t\t.no_spaces_in_names = TRUE,\n\t\t.implicit_is_not_empty = TRUE,\n\t\t.do_not_collapse_values = FALSE,\n\t\t.preserve_empty_quotes = FALSE,\n\t\t.disabled_after_space = TRUE,\n\t\t.disabled_can_be_implicit = FALSE\n\t};\n\n\t*confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ };\n\n\tif (load_ini_path(\"rosetta.conf\", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) {\n\n\t\tfprintf(stderr, \"Sorry, something went wrong\u00a0:-(\\n\");\n\t\treturn 1;\n\n\t}\n\n\tconfs->needspeeling &= 0x7F;\n\tconfs->seedsremoved &= 0x7F;\n\n\treturn 0;\n\n}\n\nint main () {\n\n\tstruct configs confs;\n\n\tini_global_set_implicit_value(\"YES\", 0);\n\n\tif (populate_configs(&confs)) {\n\n\t\treturn 1;\n\n\t}\n\n\t\/* Print the configurations parsed *\/\n\n\tprintf(\n\n\t\t\"Full name: %s\\n\"\n\t\t\"Favorite fruit: %s\\n\"\n\t\t\"Need spelling: %s\\n\"\n\t\t\"Seeds removed: %s\\n\",\n\n\t\tconfs.fullname,\n\t\tconfs.favouritefruit,\n\t\tconfs.needspeeling ? \"True\" : \"False\",\n\t\tconfs.seedsremoved ? \"True\" : \"False\"\n\n\t);\n\n\tfor (size_t idx = 0; idx < confs.otherfamily_len; idx++) {\n\n\t\tprintf(\"Other family[%d]: %s\\n\", idx, confs.otherfamily[idx]);\n\n\t}\n\n\t\/* Free the allocated memory *\/\n\n\t#define FREE_NON_NULL(PTR) if (PTR) { free(PTR); }\n\n\tFREE_NON_NULL(confs.fullname);\n\tFREE_NON_NULL(confs.favouritefruit);\n\tFREE_NON_NULL(confs.otherfamily);\n\n\treturn 0;\n\n}\n\n\n","human_summarization":"The code reads a standard configuration file, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration entries: 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved'. It also handles multiple parameters for a configuration option, storing them in an array under 'otherfamily'. The configuration option names are not case sensitive, but the data is case sensitive. An optional equals sign can be used to separate data from the option name.","id":3464}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\n#define R 6371\n#define TO_RAD (3.1415926536 \/ 180)\ndouble dist(double th1, double ph1, double th2, double ph2)\n{\n\tdouble dx, dy, dz;\n\tph1 -= ph2;\n\tph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD;\n\n\tdz = sin(th1) - sin(th2);\n\tdx = cos(ph1) * cos(th1) - cos(th2);\n\tdy = sin(ph1) * cos(th1);\n\treturn asin(sqrt(dx * dx + dy * dy + dz * dz) \/ 2) * 2 * R;\n}\n\nint main()\n{\n\tdouble d = dist(36.12, -86.67, 33.94, -118.4);\n\t\/* Americans don't know kilometers *\/\n\tprintf(\"dist:\u00a0%.1f km (%.1f mi.)\\n\", d, d \/ 1.609344);\n\n\treturn 0;\n}\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":3465}
    {"lang_cluster":"C","source_code":"\nLibrary: libcurl\n#include <stdio.h>\n#include <stdlib.h>\n#include <curl\/curl.h>\n\nint\nmain(void)\n{\n        CURL *curl;\n        char buffer[CURL_ERROR_SIZE];\n\n        if ((curl = curl_easy_init()) != NULL) {\n                curl_easy_setopt(curl, CURLOPT_URL, \"http:\/\/www.rosettacode.org\/\");\n                curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);\n                curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);\n                if (curl_easy_perform(curl) != CURLE_OK) {\n                        fprintf(stderr, \"%s\\n\", buffer);\n                        return EXIT_FAILURE;\n                }\n                curl_easy_cleanup(curl);\n        }\n        return EXIT_SUCCESS;\n}\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":3466}
    {"lang_cluster":"C","source_code":"\n#include <string.h>\n#include <stdio.h>\n\nint luhn(const char* cc)\n{\n\tconst int m[] = {0,2,4,6,8,1,3,5,7,9}; \/\/ mapping for rule 3\n\tint i, odd = 1, sum = 0;\n\n\tfor (i = strlen(cc); i--; odd = !odd) {\n\t\tint digit = cc[i] - '0';\n\t\tsum += odd ? digit : m[digit];\n\t}\n\n\treturn sum % 10 == 0;\n}\n\nint main()\n{\n\tconst char* cc[] = {\n\t\t\"49927398716\",\n\t\t\"49927398717\",\n\t\t\"1234567812345678\",\n\t\t\"1234567812345670\",\n\t\t0\n\t};\n\tint i;\n\n\tfor (i = 0; cc[i]; i++)\n\t\tprintf(\"%16s\\t%s\\n\", cc[i], luhn(cc[i]) ? \"ok\" : \"not ok\");\n\n\treturn 0;\n}\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":3467}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\n\/\/ m-th on the reversed kill list; m = 0 is final survivor\nint jos(int n, int k, int m) {\n\tint a;\n\tfor (a = m + 1; a <= n; a++)\n\t\tm = (m + k) % a;\n\treturn m;\n}\n\ntypedef unsigned long long xint;\n\n\/\/ same as jos(), useful if n is large and k is not\nxint jos_large(xint n, xint k, xint m) {\n\tif (k <= 1) return n - m - 1;\n\n\txint a = m;\n\twhile (a < n) {\n\t\txint q = (a - m + k - 2) \/ (k - 1);\n\n\t\tif (a + q > n)\tq = n - a;\n\t\telse if (!q)\tq = 1;\n\n\t\tm = (m + q * k) % (a += q);\n\t}\n\n\treturn m;\n}\n\nint main(void) {\n\txint n, k, i;\n\n\tn = 41;\n\tk = 3;\n\tprintf(\"n = %llu, k = %llu, final survivor: %d\\n\", n, k, jos(n, k, 0));\n\n\tn = 9876543210987654321ULL;\n\tk = 12031;\n\tprintf(\"n = %llu, k = %llu, three survivors:\", n, k);\n\n\tfor (i = 3; i--; )\n\t\tprintf(\" %llu\", jos_large(n, k, i));\n\tputchar('\\n');\n\n\treturn 0;\n}\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":3468}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nchar * string_repeat( int n, const char * s ) {\n  size_t slen = strlen(s);\n  char * dest = malloc(n*slen+1);\n\n  int i; char * p;\n  for ( i=0, p = dest; i < n; ++i, p += slen ) {\n    memcpy(p, s, slen);\n  }\n  *p = '\\0';\n  return dest;\n}\n\nint main() {\n  char * result = string_repeat(5, \"ha\");\n  puts(result);\n  free(result);\n  return 0;\n}\n\n\n...\nchar *string_repeat(const char *str, int n)\n{\n   char *pa, *pb;\n   size_t slen = strlen(str);\n   char *dest = malloc(n*slen+1);\n\n   pa = dest + (n-1)*slen;\n   strcpy(pa, str);\n   pb = --pa + slen; \n   while (pa>=dest) *pa-- = *pb--;\n   return dest;\n}\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nchar * char_repeat( int n, char c ) {\n  char * dest = malloc(n+1);\n  memset(dest, c, n);\n  dest[n] = '\\0';\n  return dest;\n}\n\nint main() {\n  char * result = char_repeat(5, '*');\n  puts(result);\n  free(result);\n  return 0;\n}\n\n\n","human_summarization":"\"Code functionality: Repeats a given string or character a specified number of times. For example, repeating 'ha' 5 times results in 'hahahahaha'. If using GLib, the function g_strnfill can be used to repeat a single character efficiently.\"","id":3469}
    {"lang_cluster":"C","source_code":"\nWorks with: POSIX\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <sys\/types.h>\n#include <regex.h>\n#include <string.h>\n\nint main()\n{\n   regex_t preg;\n   regmatch_t substmatch[1];\n   const char *tp = \"string$\";\n   const char *t1 = \"this is a matching string\";\n   const char *t2 = \"this is not a matching string!\";\n   const char *ss = \"istyfied\";\n   \n   regcomp(&preg, \"string$\", REG_EXTENDED);\n   printf(\"'%s' %smatched with '%s'\\n\", t1,\n                                        (regexec(&preg, t1, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   printf(\"'%s' %smatched with '%s'\\n\", t2,\n                                        (regexec(&preg, t2, 0, NULL, 0)==0) ? \"\" : \"did not \", tp);\n   regfree(&preg);\n   \/* change \"a[a-z]+\" into \"istifyed\"?*\/\n   regcomp(&preg, \"a[a-z]+\", REG_EXTENDED);\n   if ( regexec(&preg, t1, 1, substmatch, 0) == 0 )\n   {\n      \/\/fprintf(stderr, \"%d, %d\\n\", substmatch[0].rm_so, substmatch[0].rm_eo);\n      char *ns = malloc(substmatch[0].rm_so + 1 + strlen(ss) +\n                        (strlen(t1) - substmatch[0].rm_eo) + 2);\n      memcpy(ns, t1, substmatch[0].rm_so+1);\n      memcpy(&ns[substmatch[0].rm_so], ss, strlen(ss));\n      memcpy(&ns[substmatch[0].rm_so+strlen(ss)], &t1[substmatch[0].rm_eo],\n                strlen(&t1[substmatch[0].rm_eo]));\n      ns[ substmatch[0].rm_so + strlen(ss) +\n          strlen(&t1[substmatch[0].rm_eo]) ] = 0;\n      printf(\"mod string: '%s'\\n\", ns);\n      free(ns); \n   } else {\n      printf(\"the string '%s' is the same: no matching!\\n\", t1);\n   }\n   regfree(&preg);\n   \n   return 0;\n}\n\n\nLibrary: GLib\n#include <stdio.h>\n#include <glib.h>\n\nvoid print_regex_match(const GRegex* regex, const char* string) {\n    GMatchInfo* match_info;\n    gboolean match = g_regex_match(regex, string, 0, &match_info);\n    printf(\"  string = '%s': %s\\n\", string, match ? \"yes\" : \"no\");\n    g_match_info_free(match_info);\n}\n\nvoid regex_match_demo() {\n    const char* pattern = \"^[a-z]+$\";\n    GError* error = NULL;\n    GRegex* regex = g_regex_new(pattern, 0, 0, &error);\n    if (regex == NULL) {\n        fprintf(stderr, \"%s\\n\", error->message);\n        g_error_free(error);\n        return;\n    }\n    printf(\"Does the string match the pattern '%s'?\\n\", pattern);\n    print_regex_match(regex, \"test\");\n    print_regex_match(regex, \"Test\");\n    g_regex_unref(regex);\n}\n\nvoid regex_replace_demo() {\n    const char* pattern = \"[0-9]\";\n    const char* input = \"Test2\";\n    const char* replace = \"X\";\n    GError* error = NULL;\n    GRegex* regex = g_regex_new(pattern, 0, 0, &error);\n    if (regex == NULL) {\n        fprintf(stderr, \"%s\\n\", error->message);\n        g_error_free(error);\n        return;\n    }\n    char* result = g_regex_replace_literal(regex, input, -1,\n                                           0, replace, 0, &error);\n    if (result == NULL) {\n        fprintf(stderr, \"%s\\n\", error->message);\n        g_error_free(error);\n    } else {\n        printf(\"Replace pattern '%s' in string '%s' by '%s': '%s'\\n\",\n               pattern, input, replace, result);\n        g_free(result);\n    }\n    g_regex_unref(regex);\n}\n\nint main() {\n    regex_match_demo();\n    regex_replace_demo();\n    return 0;\n}\n\n\n","human_summarization":"implement the functionality to match a string against a regular expression and substitute part of a string using a regular expression. The POSIX defined function is used for regex matching and the substitution is manually coded. The code complexity is reduced by converting it into a function. GLib's Perl-compatible regular expression functionality is also utilized to simplify the task.","id":3470}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[])\n{\n  int a, b;\n  if (argc < 3) exit(1);\n  b = atoi(argv[--argc]);\n  if (b == 0) exit(2);\n  a = atoi(argv[--argc]);\n  printf(\"a+b = %d\\n\", a+b);\n  printf(\"a-b = %d\\n\", a-b);\n  printf(\"a*b = %d\\n\", a*b);\n  printf(\"a\/b = %d\\n\", a\/b); \/* truncates towards 0 (in C99) *\/\n  printf(\"a%%b = %d\\n\", a%b); \/* same sign as first operand (in C99) *\/\n  return 0;\n}\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":3471}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <string.h>\n\nint match(const char *s, const char *p, int overlap)\n{\n        int c = 0, l = strlen(p);\n\n        while (*s != '\\0') {\n                if (strncmp(s++, p, l)) continue;\n                if (!overlap) s += l - 1;\n                c++;\n        }\n        return c;\n}\n\nint main()\n{\n        printf(\"%d\\n\", match(\"the three truths\", \"th\", 0));\n        printf(\"overlap:%d\\n\", match(\"abababababa\", \"aba\", 1));\n        printf(\"not:    %d\\n\", match(\"abababababa\", \"aba\", 0));\n        return 0;\n}\n\n\n#include <stdio.h>\n#include <string.h>\n\n\/\/ returns count of non-overlapping occurrences of 'sub' in 'str'\nint countSubstring(const char *str, const char *sub)\n{\n    int length = strlen(sub);\n    if (length == 0) return 0;\n    int count = 0;\n    for (str = strstr(str, sub); str; str = strstr(str + length, sub))\n        ++count;\n    return count;\n}\n\nint main()\n{\n    printf(\"%d\\n\", countSubstring(\"the three truths\", \"th\"));\n    printf(\"%d\\n\", countSubstring(\"ababababab\", \"abab\"));\n    printf(\"%d\\n\", countSubstring(\"abaabba*bbaba*bbab\", \"a*b\"));\n\n    return 0;\n}\n\n\n","human_summarization":"\"Output: The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments - the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.\"","id":3472}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nvoid move(int n, int from, int via, int to)\n{\n  if (n > 1) {\n    move(n - 1, from, to, via);\n    printf(\"Move disk from pole %d to pole %d\\n\", from, to);\n    move(n - 1, via, from, to);\n  } else {\n    printf(\"Move disk from pole %d to pole %d\\n\", from, to);\n  }\n}\nint main()\n{\n  move(4, 1,2,3);\n  return 0;\n}\n\nAnimate it for fun:#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\ntypedef struct { int *x, n; } tower;\ntower *new_tower(int cap)\n{\n\ttower *t = calloc(1, sizeof(tower) + sizeof(int) * cap);\n\tt->x = (int*)(t + 1);\n\treturn t;\n}\n\ntower *t[3];\nint height;\n\nvoid text(int y, int i, int d, const char *s)\n{\n\tprintf(\"\\033[%d;%dH\", height - y + 1, (height + 1) * (2 * i + 1) - d);\n\twhile (d--) printf(\"%s\", s);\n}\n\nvoid add_disk(int i, int d)\n{\n\tt[i]->x[t[i]->n++] = d;\n\ttext(t[i]->n, i, d, \"==\");\n\n\tusleep(100000);\n\tfflush(stdout);\n}\n\nint remove_disk(int i)\n{\n\tint d = t[i]->x[--t[i]->n];\n\ttext(t[i]->n + 1, i, d, \"  \");\n\treturn d;\n}\n\nvoid move(int n, int from, int to, int via)\n{\n\tif (!n) return;\n\n\tmove(n - 1, from, via, to);\n\tadd_disk(to, remove_disk(from));\n\tmove(n - 1, via, to, from);\n}\n\nint main(int c, char *v[])\n{\n\tputs(\"\\033[H\\033[J\");\n\n\tif (c <= 1 || (height = atoi(v[1])) <= 0)\n\t\theight = 8;\n\tfor (c = 0; c < 3; c++)\t t[c] = new_tower(height);\n\tfor (c = height; c; c--) add_disk(0, c);\n\n\tmove(height, 0, 2, 1);\n\n\ttext(1, 0, 1, \"\\n\");\n\treturn 0;\n}\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":3473}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <limits.h>\n\n\/* We go to some effort to handle overflow situations *\/\n\nstatic unsigned long gcd_ui(unsigned long x, unsigned long y) {\n  unsigned long t;\n  if (y < x) { t = x; x = y; y = t; }\n  while (y > 0) {\n    t = y;  y = x % y;  x = t;  \/* y1 <- x0\u00a0% y0\u00a0; x1 <- y0 *\/\n  }\n  return x;\n}\n\nunsigned long binomial(unsigned long n, unsigned long k) {\n  unsigned long d, g, r = 1;\n  if (k == 0) return 1;\n  if (k == 1) return n;\n  if (k >= n) return (k == n);\n  if (k > n\/2) k = n-k;\n  for (d = 1; d <= k; d++) {\n    if (r >= ULONG_MAX\/n) {  \/* Possible overflow *\/\n      unsigned long nr, dr;  \/* reduced numerator \/ denominator *\/\n      g = gcd_ui(n, d);  nr = n\/g;  dr = d\/g;\n      g = gcd_ui(r, dr);  r = r\/g;  dr = dr\/g;\n      if (r >= ULONG_MAX\/nr) return 0;  \/* Unavoidable overflow *\/\n      r *= nr;\n      r \/= dr;\n      n--;\n    } else {\n      r *= n--;\n      r \/= d;\n    }\n  }\n  return r;\n}\n\nint main() {\n    printf(\"%lu\\n\", binomial(5, 3));\n    printf(\"%lu\\n\", binomial(40, 19));\n    printf(\"%lu\\n\", binomial(67, 31));\n    return 0;\n}\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":3474}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nvoid shell_sort (int *a, int n) {\n    int h, i, j, t;\n    for (h = n; h \/= 2;) {\n        for (i = h; i < n; i++) {\n            t = a[i];\n            for (j = i; j >= h && t < a[j - h]; j -= h) {\n                a[j] = a[j - h];\n            }\n            a[j] = t;\n        }\n    }\n}\n\nint main (int ac, char **av) {\n    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};\n    int n = sizeof a \/ sizeof a[0];\n    int i;\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    shell_sort(a, n);\n    for (i = 0; i < n; i++)\n        printf(\"%d%s\", a[i], i == n - 1 ? \"\\n\" : \" \");\n    return 0;\n}\n\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":3475}
    {"lang_cluster":"C","source_code":"\n\ntypedef unsigned char luminance;\ntypedef luminance pixel1[1];\ntypedef struct {\n   unsigned int width;\n   unsigned int height;\n   luminance *buf;\n} grayimage_t;\ntypedef grayimage_t *grayimage;\n\ngrayimage alloc_grayimg(unsigned int, unsigned int);\ngrayimage tograyscale(image);\nimage tocolor(grayimage);\n\n\ngrayimage alloc_grayimg(unsigned int width, unsigned int height)\n{\n     grayimage img;\n     img = malloc(sizeof(grayimage_t));\n     img->buf = malloc(width*height*sizeof(pixel1));\n     img->width = width;\n     img->height = height;\n     return img;\n}\n\n\ngrayimage tograyscale(image img)\n{\n   unsigned int x, y;\n   grayimage timg;\n   double rc, gc, bc, l;\n   unsigned int ofs;\n\n   timg = alloc_grayimg(img->width, img->height);\n   \n   for(x=0; x < img->width; x++)\n   {\n      for(y=0; y < img->height; y++)\n      {\n        ofs = (y * img->width) + x;\n        rc = (double) img->buf[ofs][0];\n        gc = (double) img->buf[ofs][1];\n        bc = (double) img->buf[ofs][2];\n        l = 0.2126*rc + 0.7152*gc + 0.0722*bc;\n        timg->buf[ofs][0] = (luminance) (l+0.5);\n      }\n   }\n   return timg;\n}\n\n\nimage tocolor(grayimage img)\n{\n   unsigned int x, y;\n   image timg;\n   luminance l;\n   unsigned int ofs;\n\n   timg = alloc_img(img->width, img->height);\n   \n   for(x=0; x < img->width; x++)\n   {\n      for(y=0; y < img->height; y++)\n      {\n        ofs = (y * img->width) + x;\n        l = img->buf[ofs][0];\n        timg->buf[ofs][0] = l;\n        timg->buf[ofs][1] = l;\n        timg->buf[ofs][2] = l;\n      }\n   }\n   return timg;\n}\n\n\ntocolor and tograyscale do not free the previous image, so it must be freed normally calling free_img. With a cast we can use the same function also for grayscale images, or we can define something like\n#define free_grayimg(IMG) free_img((image)(IMG))\n\nLuminance is rounded. Since the C implementation is based on unsigned char (256 possible values per components), L can be at most 255.0 and rounding gives 255, as we expect. Changing the color_component type would only change 256, 255.0 and 255 values here written in something else, the code would work the same.\n","human_summarization":"- Defines a data storage type for grayscale images.\n- Implements two operations for converting a color image to a grayscale image and vice versa.\n- Uses the CIE recommended formula for calculating luminance of a color.\n- Ensures that rounding errors in floating-point arithmetic do not cause run-time problems or distort results when storing calculated luminance as an unsigned integer.\n- Provides a definition\/interface for a grayscale image similar to alloc_img.\n- Converts a color image to a grayscale image and back.","id":3476}
    {"lang_cluster":"C","source_code":"\nLibrary: GTK\n\n#include <stdlib.h>\n#include <string.h>\n#include <gtk\/gtk.h>\n\nconst gchar *hello = \"Hello World! \";\ngint direction = -1;\ngint cx=0;\ngint slen=0;\n\nGtkLabel *label;\n\nvoid change_dir(GtkLayout *o, gpointer d)\n{\n  direction = -direction;\n}\n\ngchar *rotateby(const gchar *t, gint q, gint l)\n{\n  gint i, cl = l, j;\n  gchar *r = malloc(l+1);\n  for(i=q, j=0; cl > 0; cl--, i = (i + 1)%l, j++)\n    r[j] = t[i];\n  r[l] = 0;\n  return r;\n}\n\ngboolean scroll_it(gpointer data)\n{\n  if ( direction > 0 )\n    cx = (cx + 1) % slen;\n  else\n    cx = (cx + slen - 1 ) % slen;\n  gchar *scrolled = rotateby(hello, cx, slen);\n  gtk_label_set_text(label, scrolled);\n  free(scrolled);\n  return TRUE;\n}\n\n\nint main(int argc, char **argv)\n{\n  GtkWidget *win;\n  GtkButton *button;\n  PangoFontDescription *pd;\n\n  gtk_init(&argc, &argv);\n  win = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(GTK_WINDOW(win), \"Basic Animation\");\n  g_signal_connect(G_OBJECT(win), \"delete-event\", gtk_main_quit, NULL);\n\n  label = (GtkLabel *)gtk_label_new(hello);\n\n  \/\/ since we shift a whole character per time, it's better to use\n  \/\/ a monospace font, so that the shifting seems done at the same pace\n  pd = pango_font_description_new();\n  pango_font_description_set_family(pd, \"monospace\");\n  gtk_widget_modify_font(GTK_WIDGET(label), pd);\n\n  button = (GtkButton *)gtk_button_new();\n  gtk_container_add(GTK_CONTAINER(button), GTK_WIDGET(label));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(button));\n  g_signal_connect(G_OBJECT(button), \"clicked\", G_CALLBACK(change_dir), NULL);\n\n  slen = strlen(hello);\n\n  g_timeout_add(125, scroll_it, NULL);\n  \n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n  return 0;\n}\n\n","human_summarization":"The code creates a GUI window displaying the string \"Hello World!\" and implements an animation effect that gives the illusion of the text rotating to the right by periodically moving the last letter to the beginning of the string. The direction of rotation reverses when the user clicks on the text. The code utilizes the GTK and Pango libraries.","id":3477}
    {"lang_cluster":"C","source_code":"\nint val = 0;\ndo{\n   val++;\n   printf(\"%d\\n\",val);\n}while(val % 6 != 0);\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":3478}
    {"lang_cluster":"C","source_code":"\nWorks with: ANSI C\nWorks with: GCC version 3.3.3\n#include <string.h>\n\nint main(void) \n{\n  const char *string = \"Hello, world!\";\n  size_t length = strlen(string);\n         \n  return 0;\n}\n\n\nint main(void) \n{\n  const char *string = \"Hello, world!\";\n  size_t length = 0;\n  \n  const char *p = string;\n  while (*p++ != '\\0') length++;                                         \n  \n  return 0;\n}\n\n\n#include <stdlib.h>\n\nint main(void)\n{\n  char s[] = \"Hello, world!\";\n  size_t length = sizeof s - 1;\n  \n  return 0;\n}\n\n\n#include <stdio.h>\n#include <wchar.h>\n\nint main(void) \n{\n   wchar_t *s = L\"\\x304A\\x306F\\x3088\\x3046\"; \/* Japanese hiragana ohayou *\/\n   size_t length;\n\n   length = wcslen(s);\n   printf(\"Length in characters = %d\\n\", length);\n   printf(\"Length in bytes      = %d\\n\", sizeof(s) * sizeof(wchar_t));\n   \n   return 0;\n}\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <locale.h>\n\nint main()\n{\n\tsetlocale(LC_CTYPE, \"\");\n\tchar moose[] = \"m\u00f8\u00f8se\";\n\tprintf(\"bytes: %d\\n\", sizeof(moose) - 1);\n\tprintf(\"chars: %d\\n\", (int)mbstowcs(0, moose, 0));\n\n\treturn 0;\n}\noutputbytes: 7\nchars: 5\n","human_summarization":"determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. The character count is based on individual Unicode code points, not user-visible graphemes or code units. The code also handles non-BMP code points correctly. If possible, the code also provides the string length in graphemes. The example strings used include \"m\u00f8\u00f8se\" and \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\". The code assumes the environment locale is UTF-8.","id":3479}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#define RANDOM_PATH \"\/dev\/urandom\"\n\nint main(void)\n{\n        unsigned char buf[4];\n        unsigned long v;\n        FILE *fin;\n\n        if ((fin = fopen(RANDOM_PATH, \"r\")) == NULL) {\n                fprintf(stderr, \"%s: unable to open file\\n\", RANDOM_PATH);\n                return EXIT_FAILURE;\n        }\n        if (fread(buf, 1, sizeof buf, fin) != sizeof buf) {\n                fprintf(stderr, \"%s: not enough bytes (expected %u)\\n\",\n                        RANDOM_PATH, (unsigned) sizeof buf);\n                return EXIT_FAILURE;\n        }\n        fclose(fin);\n        v = buf[0] | buf[1] << 8UL | buf[2] << 16UL | buf[3] << 24UL;\n        printf(\"%lu\\n\", v);\n        return 0;\n}\n\n\n#include <inttypes.h> \/* PRIu32 *\/\n#include <stdlib.h> \/* arc4random *\/\n#include <stdio.h>  \/* printf *\/\n\nint\nmain()\n{\n  printf(\"%\" PRIu32 \"\\n\", arc4random());\n  return 0;\n}\n\n\n#include <inttypes.h>\n#include <stdio.h>\n\n#include <openssl\/err.h>\n#include <openssl\/rand.h>\n\nint\nmain()\n{\n  uint32_t v;\n\n  if (RAND_bytes((unsigned char *)&v, sizeof v) == 0) {\n    ERR_print_errors_fp(stderr);\n    return 1;\n  }\n  printf(\"%\" PRIu32 \"\\n\", v);\n  return 0;\n}\n\nWorks with: MinGW\n#include <stdio.h>  \/* printf *\/\n#include <windows.h>\n#include <wincrypt.h> \/* CryptAcquireContext, CryptGenRandom *\/\n\nint\nmain()\n{\n  HCRYPTPROV p;\n  ULONG i;\n\n  if (CryptAcquireContext(&p, NULL, NULL,\n      PROV_RSA_FULL, CRYPT_VERIFYCONTEXT) == FALSE) {\n    fputs(\"CryptAcquireContext failed.\\n\", stderr);\n    return 1;\n  }\n  if (CryptGenRandom(p, sizeof i, (BYTE *)&i) == FALSE) {\n    fputs(\"CryptGenRandom failed.\\n\", stderr);\n    return 1;\n  }\n  printf(\"%lu\\n\", i);\n  CryptReleaseContext(p, 0);\n  return 0;\n}\n\nWorks with: GCC\n#include <stdio.h> \n#include <stdlib.h>\n\n\/*\n   (C) 2020 J.G.A. Debaere, all rights reserved 2020\/10\/29\n\n    Put into Public Domain for individuals only \n         \n    Tested with NIST, Diehard, Diehard 3.31\n    \n    gcc -lm .\/jpsrand_f.c -o .\/jpsrand_f.o\n\n    dieharder -a -f \/tmp\/tmp.bin\n\n\tI consider it TRNG, \n\t\n\tusing Time, Hardddisk and Memory as the hardware component\n\n\tNo warranty of any kind, \"AS IS\"\n\t \n\tLast time I tested  ( 2021\/07\/07 ) with dieharder:\n\t \n\trgb_bitdist\t\t|   8|    100000|     100|0.99716738|   WEAK \t\n\trgb_lagged_sum\t|   3|   1000000|     100|0.99661184|   WEAK \n\t \n\tOut of 114 tests, rest PASSED\n\n        Obviously, it changes per run\u00a0:)\n\t\n*\/\n\nunsigned int  jps_rand()\n{\n    \/* (C) 2020 J.G.A. Debaere, all rights reserved *\/\n    \n    #include   <dirent.h>\n\n    #include <sys\/time.h>\n\n    struct timeval current_time ;\n    \n    DIR *folder ;\n    \n    struct dirent *en ;    \n    \n    folder = opendir ( \".\" ) ;\n\n    while ( ( folder ) && ( en = readdir ( folder ) ) != NULL )\n\n        asm ( \"nop\" ) ;\n        \n    closedir ( folder ) ;\n   \n    gettimeofday( ¤t_time, NULL ) ;\n        \n    unsigned int t = ( current_time.tv_sec * current_time.tv_usec \/ 17.17 ) ; \n    \n    return t ;\n}\n\nint main() \n{ \n    FILE * f1;\n\n    f1 = fopen(\"\/tmp\/tmp.bin\", \"wb\");\n\n\n    unsigned int t = ( unsigned int ) jps_rand() ;\n    \n    for ( unsigned int k = 0;  k < 40000000 ; k++ )\n    {\n        t = jps_rand () ;\n\n        fwrite ( &t, sizeof( unsigned int ),  1, f1 ) ;\n    }\n    \n    fflush(f1);\n    \n    fclose(f1);\n    \n    return 0; \n}\n\n\n   Random\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using system's built-in mechanisms such as \/dev\/urandom in Unix, arc4random() in BSD systems, or OpenSSL's default generator. The code is compatible with systems that have \/dev\/urandom like GNU\/Linux, and uses entropy from a kernel device or the Entropy Gathering Daemon.","id":3480}
    {"lang_cluster":"C","source_code":"\n#include <string.h>\n#include <stdlib.h>\n#include <stdio.h>\n\nint main( int argc, char ** argv ){\n  const char * str_a = \"knight\";\n  const char * str_b = \"socks\";\n  const char * str_c = \"brooms\";\n\n  char * new_a = malloc( strlen( str_a ) - 1 );\n  char * new_b = malloc( strlen( str_b ) - 1 );\n  char * new_c = malloc( strlen( str_c ) - 2 );\n\n  strcpy( new_a, str_a + 1 );\n  strncpy( new_b, str_b, strlen( str_b ) - 1 );\n  strncpy( new_c, str_c + 1, strlen( str_c ) - 2 );\n\n  printf( \"%s\\n%s\\n%s\\n\", new_a, new_b, new_c );\n\n  free( new_a );\n  free( new_b );\n  free( new_c );\n\n  return 0;\n}\n\n\nnight\nsock\nroom\n\n","human_summarization":"The code demonstrates how to remove the first and last characters from a string. It shows how to get a string with the first character removed, a string with the last character removed, and a string with both the first and last characters removed. The code works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not 8-bit or 16-bit code units. It doesn't support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP. The code uses only ANSI C for text manipulation.","id":3481}
    {"lang_cluster":"C","source_code":"\n\nLibrary: POSIX\n#include <fcntl.h>\t\/* fcntl, open *\/\n#include <stdlib.h>\t\/* atexit, getenv, malloc *\/\n#include <stdio.h>\t\/* fputs, printf, puts, snprintf *\/\n#include <string.h>\t\/* memcpy *\/\n#include <unistd.h>\t\/* sleep, unlink *\/\n\n\/* Filename for only_one_instance() lock. *\/\n#define INSTANCE_LOCK \"rosetta-code-lock\"\n\nvoid\nfail(const char *message)\n{\n\tperror(message);\n\texit(1);\n}\n\n\/* Path to only_one_instance() lock. *\/\nstatic char *ooi_path;\n\nvoid\nooi_unlink(void)\n{\n\tunlink(ooi_path);\n}\n\n\/* Exit if another instance of this program is running. *\/\nvoid\nonly_one_instance(void)\n{\n\tstruct flock fl;\n\tsize_t dirlen;\n\tint fd;\n\tchar *dir;\n\n\t\/*\n\t * Place the lock in the home directory of this user;\n\t * therefore we only check for other instances by the same\n\t * user (and the user can trick us by changing HOME).\n\t *\/\n\tdir = getenv(\"HOME\");\n\tif (dir == NULL || dir[0] != '\/') {\n\t\tfputs(\"Bad home directory.\\n\", stderr);\n\t\texit(1);\n\t}\n\tdirlen = strlen(dir);\n\n\tooi_path = malloc(dirlen + sizeof(\"\/\" INSTANCE_LOCK));\n\tif (ooi_path == NULL)\n\t\tfail(\"malloc\");\n\tmemcpy(ooi_path, dir, dirlen);\n\tmemcpy(ooi_path + dirlen, \"\/\" INSTANCE_LOCK,\n\t    sizeof(\"\/\" INSTANCE_LOCK));  \/* copies '\\0' *\/\n\n\tfd = open(ooi_path, O_RDWR | O_CREAT, 0600);\n\tif (fd < 0)\n\t\tfail(ooi_path);\n\n\tfl.l_start = 0;\n\tfl.l_len = 0;\n\tfl.l_type = F_WRLCK;\n\tfl.l_whence = SEEK_SET;\n\tif (fcntl(fd, F_SETLK, &fl) < 0) {\n\t\tfputs(\"Another instance of this program is running.\\n\",\n\t\t    stderr);\n\t\texit(1);\n\t}\n\n\t\/*\n\t * Run unlink(ooi_path) when the program exits. The program\n\t * always releases locks when it exits.\n\t *\/\n\tatexit(ooi_unlink);\n}\n\n\/*\n * Demo for Rosetta Code.\n * http:\/\/rosettacode.org\/wiki\/Determine_if_only_one_instance_is_running\n *\/\nint\nmain()\n{\n\tint i;\n\n\tonly_one_instance();\n\n\t\/* Play for 10 seconds. *\/\n\tfor(i = 10; i > 0; i--) {\n\t\tprintf(\"%d...%s\", i, i % 5 == 1 ? \"\\n\" : \" \");\n\t\tfflush(stdout);\n\t\tsleep(1);\n\t}\n\tputs(\"Fin!\");\n\treturn 0;\n}\n\n\nLibrary: POSIX\n#include <fcntl.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\/* unistd for sleep *\/\n\nvoid sigint_handler(int sig)\n{\n   fprintf(stderr, \"Caught signal %d.\\n\", sig);\n   unlink(\"\/tmp\/MyUniqueName\");\n   \/* exit() is not safe in a signal handler, use _exit() *\/\n   _exit(1);\n}\n\nint main()\n{\n   struct sigaction act;\n   int myfd;\n   \n   myfd = open(\"\/tmp\/MyUniqueName\", O_CREAT|O_EXCL);\n   if ( myfd < 0 )\n   {\n      fprintf(stderr, \"I am already running!\\n\");\n      exit(1);\n   }\n   act.sa_handler = sigint_handler;\n   sigemptyset(&act.sa_mask);\n   act.sa_flags = 0;\n   sigaction(SIGINT, &act, NULL);\n   \/* here the real code of the app*\/\n   sleep(20);\n   \/* end of the app *\/\n   unlink(\"\/tmp\/MyUniqueName\"); close(myfd);\n   return 0;\n}\n\n","human_summarization":"The code checks if only one instance of an application is running. It uses a write lock on the ~\/rosetta-code-lock file to ensure only one instance can set the lock. If the lock setting fails, it assumes another instance is running and exits. The lock is cleared upon program termination. If the program is terminated via an interrupt or signal, the lock file persists but the lock is cleared. The code also handles scenarios where the file system doesn't support file locking. It also creates a file with O_CREAT|O_EXCL and if the file exists, it assumes another instance is running. The code makes sure to unlink the file upon termination. It also handles signal interruptions and ensures the file is deleted unless the program is terminated with SIGKILL. The code uses a regular file with open() and unlink(), and an older version used a semaphore with sem_open() and sem_unlink().","id":3482}
    {"lang_cluster":"C","source_code":"\n\n#include<windows.h>\n#include<stdio.h>\n\nint main()\n{\n\tprintf(\"Dimensions of the screen are (w x h)\u00a0: %d x %d pixels\",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN));\n\treturn 0;\n}\n\n\nDimensions of the screen are (w x h)\u00a0: 1536 x 864 pixels\n\n","human_summarization":"calculate the maximum height and width of a window that can fit within the physical display area of the screen without scrolling, considering window decorations and menubars. The code also accounts for multiple monitors and tiling window managers. Tested on Windows 8.1.","id":3483}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n\nvoid show(int *x)\n{\n\tint i, j;\n\tfor (i = 0; i < 9; i++) {\n\t\tif (!(i % 3)) putchar('\\n');\n\t\tfor (j = 0; j < 9; j++)\n\t\t\tprintf(j % 3 ? \"%2d\" : \"%3d\", *x++);\n\t\tputchar('\\n');\n\t}\n}\n\nint trycell(int *x, int pos)\n{\n\tint row = pos \/ 9;\n\tint col = pos % 9;\n\tint i, j, used = 0;\n\n\tif (pos == 81) return 1;\n\tif (x[pos]) return trycell(x, pos + 1);\n\n\tfor (i = 0; i < 9; i++)\n\t\tused |= 1 << (x[i * 9 + col] - 1);\n\n\tfor (j = 0; j < 9; j++)\n\t\tused |= 1 << (x[row * 9 + j] - 1);\n\n\trow = row \/ 3 * 3;\n\tcol = col \/ 3 * 3;\n\tfor (i = row; i < row + 3; i++)\n\t\tfor (j = col; j < col + 3; j++)\n\t\t\tused |= 1 << (x[i * 9 + j] - 1);\n\n\tfor (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)\n\t\tif (!(used & 1) && trycell(x, pos + 1)) return 1;\n\n\tx[pos] = 0;\n\treturn 0;\n}\n\nvoid solve(const char *s)\n{\n\tint i, x[81];\n\tfor (i = 0; i < 81; i++)\n\t\tx[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;\n\n\tif (trycell(x, 0))\n\t\tshow(x);\n\telse\n\t\tputs(\"no solution\");\n}\n\nint main(void)\n{\n\tsolve(\t\"5x..7....\"\n\t\t\"6..195...\"\n\t\t\".98....6.\"\n\t\t\"8...6...3\"\n\t\t\"4..8.3..1\"\n\t\t\"7...2...6\"\n\t\t\".6....28.\"\n\t\t\"...419..5\"\n\t\t\"....8..79\"\t);\n\n\treturn 0;\n}\n\n","human_summarization":"are designed to solve a partially filled 9x9 Sudoku grid and display the results in a human-readable format. The solution is based on the Algorithmics of Sudoku and is suitable for size 3 puzzles. For larger puzzles, a more complex version of the code is required.","id":3484}
    {"lang_cluster":"C","source_code":"\n\n#include <stdlib.h>\n#include <string.h>\n\nint rrand(int m)\n{\n  return (int)((double)m * ( rand() \/ (RAND_MAX+1.0) ));\n}\n\n#define BYTE(X) ((unsigned char *)(X)) \nvoid shuffle(void *obj, size_t nmemb, size_t size)\n{\n  void *temp = malloc(size);\n  size_t n = nmemb;\n  while ( n > 1 ) {\n    size_t k = rrand(n--);\n    memcpy(temp, BYTE(obj) + n*size, size);\n    memcpy(BYTE(obj) + n*size, BYTE(obj) + k*size, size);\n    memcpy(BYTE(obj) + k*size, temp, size);\n  }\n  free(temp);\n}\n\n\n#include <stdio.h>\n#include <stdlib.h>\n\n\/* define a shuffle function. e.g. decl_shuffle(double).\n * advantage: compiler is free to optimize the swap operation without\n *            indirection with pointers, which could be much faster.\n * disadvantage: each datatype needs a separate instance of the function.\n *            for a small funciton like this, it's not very big a deal.\n *\/\n#define decl_shuffle(type)\t\t\t\t\\\nvoid shuffle_##type(type *list, size_t len) {\t\t\\\n\tint j;\t\t\t\t\t\t\\\n\ttype tmp;\t\t\t\t\t\\\n\twhile(len) {\t\t\t\t\t\\\n\t\tj = irand(len);\t\t\t\t\\\n\t\tif (j\u00a0!= len - 1) {\t\t\t\\\n\t\t\ttmp = list[j];\t\t\t\\\n\t\t\tlist[j] = list[len - 1];\t\\\n\t\t\tlist[len - 1] = tmp;\t\t\\\n\t\t}\t\t\t\t\t\\\n\t\tlen--;\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\\\n}\t\t\t\t\t\t\t\\\n\n\/* random integer from 0 to n-1 *\/\nint irand(int n)\n{\n\tint r, rand_max = RAND_MAX - (RAND_MAX % n);\n\t\/* reroll until r falls in a range that can be evenly\n\t * distributed in n bins.  Unless n is comparable to\n\t * to RAND_MAX, it's not *that* important really. *\/\n\twhile ((r = rand()) >= rand_max);\n\treturn r \/ (rand_max \/ n);\n}\n\n\/* declare and define int type shuffle function from macro *\/\ndecl_shuffle(int);\n\nint main()\n{\n\tint i, x[20];\n\n\tfor (i = 0; i < 20; i++) x[i] = i;\n\tfor (printf(\"before:\"), i = 0; i < 20 || !printf(\"\\n\"); i++)\n\t\tprintf(\" %d\", x[i]);\n\n\tshuffle_int(x, 20);\n\n\tfor (printf(\"after: \"), i = 0; i < 20 || !printf(\"\\n\"); i++)\n\t\tprintf(\" %d\", x[i]);\n\treturn 0;\n}\n\n","human_summarization":"Implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm which randomly shuffles the elements of an array. The algorithm modifies the input array in-place, but can be adjusted to return a new array if necessary. It can also be adjusted to iterate from left to right. The function handles integer arrays and potentially arrays of any type. Test cases are provided for validation.","id":3485}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n\nint main(int c, char *v[])\n{\n\tint days[] = {31,29,31,30,31,30,31,31,30,31,30,31};\n\tint m, y, w;\n\n\tif (c < 2 || (y = atoi(v[1])) <= 1700) return 1;\n \tdays[1] -= (y % 4) || (!(y % 100) && (y % 400));\n\tw = y * 365 + (y - 1) \/ 4 - (y - 1) \/ 100 + (y - 1) \/ 400 + 6;\n\n\tfor(m = 0; m < 12; m++) {\n\t\tw = (w + days[m]) % 7;\n\t\tprintf(\"%d-%02d-%d\\n\", y, m + 1,\n\t\t\tdays[m] + (w < 5 ? -2 : 5) - w);\n\t}\n\n\treturn 0;\n}\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Fridays of each month for that given year. It doesn't support the Julian calendar.","id":3486}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n\nint main(int argc, char *argv[]) {\n  (void) printf(\"Goodbye, World!\");    \/* No automatic newline *\/\n  return EXIT_SUCCESS;\n}\n\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without a trailing newline in C language, considering that the language doesn't automatically insert a newline unless embedded and the last line of a text stream may or may not require a new-line based on the implementation.\"","id":3487}
    {"lang_cluster":"C","source_code":"\nLibrary: GTK\n#include <gtk\/gtk.h>\n\nvoid ok_hit(GtkButton *o, GtkWidget **w)\n{\n  GtkMessageDialog *msg;\n\n  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);\n  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);\n\n  msg = (GtkMessageDialog *)\n    gtk_message_dialog_new(NULL,\n\t\t\t   GTK_DIALOG_MODAL,\n\t\t\t   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,\n\t\t\t   GTK_BUTTONS_OK,\n\t\t\t   \"You wrote '%s' and selected the number %d%s\",\n\t\t\t   c, (gint)v,\n\t\t\t   (v==75000) ? \"\" : \" which is wrong (75000 expected)!\");\n  gtk_widget_show_all(GTK_WIDGET(msg));\n  (void)gtk_dialog_run(GTK_DIALOG(msg));\n  gtk_widget_destroy(GTK_WIDGET(msg));\n  if ( v==75000 ) gtk_main_quit();\n}\n\nint main(int argc, char **argv)\n{\n  GtkWindow *win;\n  GtkEntry *entry;\n  GtkSpinButton *spin;\n  GtkButton *okbutton;\n  GtkLabel *entry_l, *spin_l;\n  GtkHBox *hbox[2];\n  GtkVBox *vbox;\n  GtkWidget *widgs[2];\n\n  gtk_init(&argc, &argv);\n  \n  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);\n  gtk_window_set_title(win, \"Insert values\");\n  \n  entry_l = (GtkLabel *)gtk_label_new(\"Insert a string\");\n  spin_l =  (GtkLabel *)gtk_label_new(\"Insert 75000\");\n\n  entry = (GtkEntry *)gtk_entry_new();\n  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);\n\n  widgs[0] = GTK_WIDGET(entry);\n  widgs[1] = GTK_WIDGET(spin);\n\n  okbutton = (GtkButton *)gtk_button_new_with_label(\"Ok\");\n  \n  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);\n\n  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);\n\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));\n  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));\n  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));\n\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));\n  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));\n\n  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));\n\n  g_signal_connect(G_OBJECT(win), \"delete-event\", (GCallback)gtk_main_quit, NULL);\n  g_signal_connect(G_OBJECT(okbutton), \"clicked\", (GCallback)ok_hit, widgs);\n\n  gtk_widget_show_all(GTK_WIDGET(win));\n  gtk_main();\n\n  return 0;\n}\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":3488}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\n#define caesar(x) rot(13, x)\n#define decaesar(x) rot(13, x)\n#define decrypt_rot(x, y) rot((26-x), y)\n\nvoid rot(int c, char *str)\n{\n\tint l = strlen(str);\n        \n        const char*  alpha_low  = \"abcdefghijklmnopqrstuvwxyz\"; \n\n        const char*  alpha_high = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n   \n       \n       char subst;  \/* substitution character *\/\n       int idx;    \/* index *\/\n\n         int i; \/* loop var *\/\n\n\tfor (i = 0; i < l; i++)  \/* for each letter in string *\/\n\t{\n\t\tif( 0 == isalpha(str[i]) )  continue; \/* not alphabet character *\/\n\n                idx = (int) (tolower(str[i]) - 'a') + c) % 26; \/* compute index *\/\n\n\t\tif( isupper(str[i]) )\n                    subst = alpha_high[idx]; \n                else\n                    subst = alpha_low[idx]; \n\n               str[i] = subst;\n\n\t}\n}\n\n\nint main(int argc, char** argv)\n{\n\tchar str[] = \"This is a top secret text message!\";\n\t\n\tprintf(\"Original: %s\\n\", str);\n\tcaesar(str);\n\tprintf(\"Encrypted: %s\\n\", str);\n\tdecaesar(str);\n\tprintf(\"Decrypted: %s\\n\", str);\n\t\n\treturn 0;\n}\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":3489}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nint gcd(int m, int n)\n{\n        int tmp;\n        while(m) { tmp = m; m = n % m; n = tmp; }       \n        return n;\n}\n\nint lcm(int m, int n)\n{\n        return m \/ gcd(m, n) * n;\n}\n\nint main()\n{\n        printf(\"lcm(35, 21) = %d\\n\", lcm(21,35));\n        return 0;\n}\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":3490}
    {"lang_cluster":"C","source_code":"\n\n#include<stdlib.h>\n#include<stdio.h>\n\nint cusipCheck(char str[10]){\n\tint sum=0,i,v;\n\t\n\tfor(i=0;i<8;i++){\n\t\tif(str[i]>='0'&&str[i]<='9')\n\t\t\tv = str[i]-'0';\n\t\telse if(str[i]>='A'&&str[i]<='Z')\n\t\t\tv = (str[i] - 'A' + 10);\n\t\telse if(str[i]=='*')\n\t\t\tv = 36;\n\t\telse if(str[i]=='@')\n\t\t\tv = 37;\n\t\telse if(str[i]=='#')\n\t\t\tv = 38;\n\t\tif(i%2!=0)\n\t\t\tv*=2;\n\t\t\n\t\tsum += ((int)(v\/10) + v%10);\n\t}\n\treturn ((10 - (sum%10))%10);\n}\n\nint main(int argC,char* argV[])\n{\n\tchar cusipStr[10];\n\t\n\tint i,numLines;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage\u00a0: %s <full path of CUSIP Data file>\",argV[0]);\n\t\n\telse{\n\t\tFILE* fp = fopen(argV[1],\"r\");\n\t\n\t\tfscanf(fp,\"%d\",&numLines);\n\t\t\n\t\tprintf(\"CUSIP       Verdict\\n\");\n\t\tprintf(\"-------------------\");\n\t\t\n\t\tfor(i=0;i<numLines;i++){\n\t\t\n\t\t\tfscanf(fp,\"%s\",cusipStr);\n\t\t\n\t\t\tprintf(\"\\n%s\u00a0: %s\",cusipStr,(cusipCheck(cusipStr)==(cusipStr[8]-'0'))?\"Valid\":\"Invalid\");\n\t\t}\n\t\n\t\tfclose(fp);\n\t}\n\treturn 0;\n}\n\n\n6\n037833100\n17275R102\n38259P508\n594918104\n68389X106\n68389X105\n\n\nC:\\rosettaCode>cusipCheck.exe cusipData.txt\nCUSIP       Verdict\n-------------------\n037833100\u00a0: Valid\n17275R102\u00a0: Valid\n38259P508\u00a0: Valid\n594918104\u00a0: Valid\n68389X106\u00a0: Invalid\n68389X105\u00a0: Valid\n\n","human_summarization":"The code reads CUSIP strings from a file, verifies the correctness of the last digit (check digit) of each CUSIP code, and prints the results to the console. The CUSIP code is a nine-character alphanumeric code that identifies a North American financial security. The verification process involves a specific algorithm that takes into account the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. If invoked incorrectly, usage instructions are printed.","id":3491}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stddef.h> \/* for size_t *\/\n#include <limits.h> \/* for CHAR_BIT *\/\n\nint main() {\n    int one = 1;\n\n    \/*\n     * Best bet: size_t typically is exactly one word.\n     *\/\n    printf(\"word size = %d bits\\n\", (int)(CHAR_BIT * sizeof(size_t)));\n\n    \/*\n     * Check if the least significant bit is located\n     * in the lowest-address byte.\n     *\/\n    if (*(char *)&one)\n        printf(\"little endian\\n\");\n    else\n        printf(\"big endian\\n\");\n    return 0;\n}\n\n\n#include <stdio.h>\n#include <arpa\/inet.h>\n\nint main()\n{\n  if (htonl(1) == 1)\n    printf(\"big endian\\n\");\n  else\n    printf(\"little endian\\n\");\n}\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine, and tests the endianness on POSIX-compatible systems using network order.\"","id":3492}
    {"lang_cluster":"C","source_code":"\n\n\nThis example is incorrect.  Please fix the code and remove this message.Details: Compiles without error but \"Segmentation fault\" when run. Tested on Cygwin, SuSE Linux and Arch Linux (Manjaro)\n\n\n\n\nThis example is in need of improvement:\nThis solution uses an external program wget for networking, but it could use Library: libcurl (see Web scraping#C) for example. Also this solution scrapes Special:Categories &limit 5000 which will break if the HTML style changes or the number of languages exceeds 5000. It could use the MediWiki API to get the language names and pages in a single call, in blocks of 500 until complete with no upper limit. See the Awk example. If you make an API-based version please retain the web-scrapping version in its own sub-section (following the lead of TCL on this page). \n\nGhetto parser#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nconst char * lang_url = \"http:\/\/www.rosettacode.org\/w\/api.php?action=query&\"\n\t\t\"list=categorymembers&cmtitle=Category:Programming_Languages&\"\n\t\t\"cmlimit=500&format=json\";\nconst char * cat_url = \"http:\/\/www.rosettacode.org\/w\/index.php?title=Special:Categories&limit=5000\";\n\n#define BLOCK 1024\nchar *get_page(const char *url)\n{\n\tchar cmd[1024];\n\tchar *ptr, *buf;\n\tint bytes_read = 1, len = 0;\n\tsprintf(cmd, \"wget -q \\\"%s\\\" -O -\", url);\n\tFILE *fp = popen(cmd, \"r\");\n\tif (!fp) return 0;\n\tfor (ptr = buf = 0; bytes_read > 0; ) {\n\t\tbuf = realloc(buf, 1 + (len += BLOCK));\n\t\tif (!ptr) ptr = buf;\n\t\tbytes_read = fread(ptr, 1, BLOCK, fp);\n\t\tif (bytes_read <= 0) break;\n\t\tptr += bytes_read;\n\t}\n\t*++ptr = '\\0';\n\treturn buf;\n}\n\nchar ** get_langs(char *buf, int *l)\n{\n\tchar **arr = 0;\n\tfor (*l = 0; (buf = strstr(buf, \"Category:\")) && (buf += 9); ++*l)\n\t\tfor (\t(*l)[arr = realloc(arr, sizeof(char*)*(1 + *l))] = buf;\n\t\t\t*buf != '\"' || (*buf++ = 0);\n\t\t\tbuf++);\n\n\treturn arr;\n}\n\ntypedef struct { const char *name; int count; } cnt_t;\ncnt_t * get_cats(char *buf, char ** langs, int len, int *ret_len)\n{\n\tchar str[1024], *found;\n\tcnt_t *list = 0;\n\tint i, llen = 0;\n\tfor (i = 0; i < len; i++) {\n\t\tsprintf(str, \"\/wiki\/Category:%s\", langs[i]);\n\t\tif (!(found = strstr(buf, str))) continue;\n\t\tbuf = found + strlen(str);\n\n\t\tif (!(found = strstr(buf, \"<\/a> (\"))) continue;\n\t\tlist = realloc(list, sizeof(cnt_t) * ++llen);\n\t\tlist[llen - 1].name = langs[i];\n\t\tlist[llen - 1].count = strtol(found + 6, 0, 10);\n\t}\n\t*ret_len = llen;\n\treturn list;\n}\n\nint _scmp(const void *a, const void *b)\n{\n\tint x = ((const cnt_t*)a)->count, y = ((const cnt_t*)b)->count;\n\treturn x < y ? -1 : x > y;\n}\n\nint main()\n{\n\tint len, clen;\n\tchar ** langs = get_langs(get_page(lang_url), &len);\n\tcnt_t *cats = get_cats(get_page(cat_url), langs, len, &clen);\n\tqsort(cats, clen, sizeof(cnt_t), _scmp);\n\twhile (--clen >= 0)\n\t\tprintf(\"%4d %s\\n\", cats[clen].count, cats[clen].name);\n\n\treturn 0;\n}\n\n\n","human_summarization":"The code ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It scrapes data from the web or uses the API method to access the data. The code can filter incorrect results and cross-check against the MostLinkedCategories or a complete list of programming languages. It compiles using cJSON and gcc, and outputs the top 'n' languages, with a default of 10.","id":3493}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n...\n\nconst char *list[] = {\"Red\",\"Green\",\"Blue\",\"Black\",\"White\"};\n#define LIST_SIZE (sizeof(list)\/sizeof(list[0]))\n\nint ix;\nfor(ix=0; ix<LIST_SIZE; ix++) {\n   printf(\"%s\\n\", list[ix]);\n}\n\n\n#include <stdio.h>\n#include <stdlib.h>\n\/* foreach macro for using a string as a collection of char *\/\n#define foreach( ptrvar , strvar ) char* ptrvar; for( ptrvar=strvar\u00a0; (*ptrvar)\u00a0!= '\\0'\u00a0; *ptrvar++)\n\nint main(int argc,char* argv[]){\nchar* s1=\"abcdefg\";\nchar* s2=\"123456789\";\nforeach( p1 , s1 ) {\n printf(\"loop 1 %c\\n\",*p1);\n}\nforeach( p2 , s2 ){\n printf(\"loop 2 %c\\n\",*p2);\n}\nexit(0);\nreturn(0);\n}\n\n\n#include <stdio.h>\n#include <stdlib.h>\nint main(int argc,char* argv[]){\n\/* foreach macro viewing an array of int values as a collection of int values *\/\n#define foreach( intpvar , intary ) int* intpvar; for( intpvar=intary; intpvar < (intary+(sizeof(intary)\/sizeof(intary[0])))\u00a0; intpvar++)\nint a1[]={ 1 , 1 , 2 , 3 , 5 , 8 };\nint a2[]={ 3 , 1 , 4 , 1, 5, 9 };\nforeach( p1 , a1 ) {\n printf(\"loop 1 %d\\n\",*p1);\n}\nforeach( p2 , a2 ){\n printf(\"loop 2 %d\\n\",*p2);\n}\nexit(0);\nreturn(0);\n}\n\n\nNote: idxtype can be removed and typeof(col[0]) can be used in it's place with GCC\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\nint main(int argc,char* argv[]){\n#define foreach( idxtype , idxpvar , col , colsiz ) idxtype* idxpvar; for( idxpvar=col\u00a0; idxpvar < (col+(colsiz))\u00a0; idxpvar++)\n#define arraylen( ary ) ( sizeof(ary)\/sizeof(ary[0]) )\nchar* c1=\"collection\";\nint c2[]={ 3 , 1 , 4 , 1, 5, 9 };\ndouble* c3;\nint c3len=4;\nc3=(double*)calloc(c3len,sizeof(double)); \nc3[0]=1.2;c3[1]=3.4;c3[2]=5.6;c3[3]=7.8;  \nforeach( char,p1   , c1, strlen(c1) ) {\n printf(\"loop 1\u00a0: %c\\n\",*p1);\n}\nforeach( int,p2    , c2, arraylen(c2) ){\n printf(\"loop 2\u00a0: %d\\n\",*p2);\n}\nforeach( double,p3 , c3, c3len ){\n printf(\"loop 3\u00a0: %3.1lf\\n\",*p3);\n}\nexit(0);\nreturn(0);\n}\n\n","human_summarization":"demonstrate how to iterate through a collection in C using a loop, as it doesn't have a native 'for each' statement or 'container' type. The codes show how to print each element of a C string (collection of char), an int array (collection of int), and a general string or array (collection size known at run-time).","id":3494}
    {"lang_cluster":"C","source_code":"\nWorks with: ANSI C\nLibrary: POSIX\n\n#include<string.h>\n#include<stdio.h>\n#include<stdlib.h>\n\nint main(void)\n{\n\tchar *a[5];\n\tconst char *s=\"Hello,How,Are,You,Today\";\n\tint n=0, nn;\n\n\tchar *ds=strdup(s);\n\n\ta[n]=strtok(ds, \",\");\n\twhile(a[n] && n<4) a[++n]=strtok(NULL, \",\");\n\n\tfor(nn=0; nn<=n; ++nn) printf(\"%s.\", a[nn]);\n\tputchar('\\n');\n\n\tfree(ds);\n\n\treturn 0;\n}\n\n\n#include<stdio.h>\n\ntypedef void (*callbackfunc)(const char *);\n\nvoid doprint(const char *s) {\n\tprintf(\"%s.\", s);\n}\n\nvoid tokenize(char *s, char delim, callbackfunc cb) {\n\tchar *olds = s;\n\tchar olddelim = delim;\n\twhile(olddelim && *s) {\n\t\twhile(*s && (delim != *s)) s++;\n\t\t*s ^= olddelim = *s; \/\/ olddelim = *s; *s = 0;\n\t\tcb(olds);\n\t\t*s++ ^= olddelim; \/\/ *s = olddelim; s++;\n\t\tolds = s;\n\t}\n}\n\nint main(void)\n{\n        char array[] = \"Hello,How,Are,You,Today\";\n\ttokenize(array, ',', doprint);\n\treturn 0;\n}\n\n","human_summarization":"\"Tokenizes a string by separating it into an array based on comma delimiters, then displays the words to the user separated by periods. The strtok() function is used for tokenization, which modifies the original string, hence a copy of the string is made using strdup(). Alternatively, the task can be accomplished by temporarily modifying the separator character without using additional memory, but this requires the input string to be writable.\"","id":3495}
    {"lang_cluster":"C","source_code":"\nint\ngcd_iter(int u, int v) {\n  if (u < 0) u = -u;\n  if (v < 0) v = -v;\n  if (v) while ((u %= v) && (v %= u));\n  return (u + v);\n}\n\nint gcd(int u, int v) {\nreturn (v != 0)?gcd(v, u%v):u;\n}\n\nint gcd_bin(int u, int v) {\n  int t, k;\n\n  u = u < 0 ? -u : u; \/* abs(u) *\/\n  v = v < 0 ? -v : v; \n  if (u < v) {\n    t = u;\n    u = v;\n    v = t;\n  }\n  if (v == 0)\n    return u;\n\n  k = 1;\n  while ((u & 1) == 0 && (v & 1) == 0) { \/* u, v - even *\/\n    u >>= 1; v >>= 1;\n    k <<= 1;\n  }\n\n  t = (u & 1) ? -v : u;\n  while (t) {\n    while ((t & 1) == 0) \n      t >>= 1;\n\n    if (t > 0)\n      u = t;\n    else\n      v = -t;\n\n    t = u - v;\n  }\n  return u * k;        \n}\n\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":3496}
    {"lang_cluster":"C","source_code":"\nWorks with: POSIX\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <errno.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netdb.h>\n#include <unistd.h>\n#include <sys\/wait.h>\n#include <signal.h>\n\n#define MAX_ENQUEUED 20\n#define BUF_LEN 256\n#define PORT_STR \"12321\"\n\n\/* ------------------------------------------------------------ *\/\n\/* How to clean up after dead child processes                   *\/\n\/* ------------------------------------------------------------ *\/\n\nvoid wait_for_zombie(int s)\n{\n    while(waitpid(-1, NULL, WNOHANG) > 0) ;\n}\n\n\/* ------------------------------------------------------------ *\/\n\/* Core of implementation of a child process                    *\/\n\/* ------------------------------------------------------------ *\/\n\nvoid echo_lines(int csock)\n{\n    char buf[BUF_LEN];\n    int r;\n\n    while( (r = read(csock, buf, BUF_LEN)) > 0 ) {\n        (void)write(csock, buf, r);\n    }\n    exit(EXIT_SUCCESS);\n}\n\n\/* ------------------------------------------------------------ *\/\n\/* Core of implementation of the parent process                 *\/\n\/* ------------------------------------------------------------ *\/\n\nvoid take_connections_forever(int ssock)\n{\n    for(;;) {\n        struct sockaddr addr;\n        socklen_t addr_size = sizeof(addr);\n        int csock;\n\n        \/* Block until we take one connection to the server socket *\/\n        csock = accept(ssock, &addr, &addr_size);\n\n        \/* If it was a successful connection, spawn a worker process to service it *\/\n        if ( csock == -1 ) {\n            perror(\"accept\");\n        } else if ( fork() == 0 ) {\n            close(ssock);\n            echo_lines(csock);\n        } else {\n            close(csock);\n        }\n    }\n}\n\n\/* ------------------------------------------------------------ *\/\n\/* The server process's one-off setup code                      *\/\n\/* ------------------------------------------------------------ *\/\n\nint main()\n{\n    struct addrinfo hints, *res;\n    struct sigaction sa;\n    int sock;\n\n    \/* Look up the address to bind to *\/\n    memset(&hints, 0, sizeof(struct addrinfo));\n    hints.ai_family = AF_UNSPEC;\n    hints.ai_socktype = SOCK_STREAM;\n    hints.ai_flags = AI_PASSIVE;\n    if ( getaddrinfo(NULL, PORT_STR, &hints, &res) != 0 ) {\n        perror(\"getaddrinfo\");\n        exit(EXIT_FAILURE);\n    }\n\n    \/* Make a socket *\/\n    if ( (sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol)) == -1 ) {\n        perror(\"socket\");\n        exit(EXIT_FAILURE);\n    }\n\n    \/* Arrange to clean up child processes (the workers) *\/\n    sa.sa_handler = wait_for_zombie;\n    sigemptyset(&sa.sa_mask);\n    sa.sa_flags = SA_RESTART;\n    if ( sigaction(SIGCHLD, &sa, NULL) == -1 ) {\n        perror(\"sigaction\");\n        exit(EXIT_FAILURE);\n    }\n\n    \/* Associate the socket with its address *\/\n    if ( bind(sock, res->ai_addr, res->ai_addrlen) != 0 ) {\n        perror(\"bind\");\n        exit(EXIT_FAILURE);\n    }\n\n    freeaddrinfo(res);\n\n    \/* State that we've opened a server socket and are listening for connections *\/\n    if ( listen(sock, MAX_ENQUEUED) != 0 ) {\n        perror(\"listen\");\n        exit(EXIT_FAILURE);\n    }\n\n    \/* Serve the listening socket until killed *\/\n    take_connections_forever(sock);\n    return EXIT_SUCCESS;\n}\n\n","human_summarization":"The code implements an echo server that listens on TCP port 12321. It accepts and handles multiple simultaneous connections from localhost, echoing back complete lines received from clients. The server continues to respond to other clients even if one client sends a partial line or stops reading responses. Connection information is logged to standard output. The implementation uses POSIX read and write functions and may be multi-threaded or multi-process.","id":3497}
    {"lang_cluster":"C","source_code":"\n\n#include <ctype.h>\n#include <stdlib.h>\nint isNumeric (const char * s)\n{\n    if (s == NULL || *s == '\\0' || isspace(*s))\n      return 0;\n    char * p;\n    strtod (s, &p);\n    return *p == '\\0';\n}\n\n","human_summarization":"The function checks if the input string is a numeric value, including floating point and negative numbers, and returns true if it is, otherwise it returns false.","id":3498}
    {"lang_cluster":"C","source_code":"\nLibrary: libcurl\n#include <stdio.h>\n#include <stdlib.h>\n#include <curl\/curl.h>\nCURL *curl;\nchar buffer[CURL_ERROR_SIZE];\nint main(void) {\n    if ((curl = curl_easy_init()) != NULL) {\n        curl_easy_setopt(curl, CURLOPT_URL, \"https:\/\/sourceforge.net\/\");\n        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);\n        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, buffer);\n        if (curl_easy_perform(curl) != CURLE_OK) {\n            fprintf(stderr, \"%s\\n\", buffer);\n            return EXIT_FAILURE;\n        }\n        curl_easy_cleanup(curl);\n    }\n    return EXIT_SUCCESS;\n}\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":3499}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\ntypedef struct { double x, y; } vec_t, *vec;\n\ninline double dot(vec a, vec b)\n{\n\treturn a->x * b->x + a->y * b->y;\n}\n\ninline double cross(vec a, vec b)\n{\n\treturn a->x * b->y - a->y * b->x;\n}\n\ninline vec vsub(vec a, vec b, vec res)\n{\n\tres->x = a->x - b->x;\n\tres->y = a->y - b->y;\n\treturn res;\n}\n\n\/* tells if vec c lies on the left side of directed edge a->b\n * 1 if left, -1 if right, 0 if colinear\n *\/\nint left_of(vec a, vec b, vec c)\n{\n\tvec_t tmp1, tmp2;\n\tdouble x;\n\tvsub(b, a, &tmp1);\n\tvsub(c, b, &tmp2);\n\tx = cross(&tmp1, &tmp2);\n\treturn x < 0 ? -1 : x > 0;\n}\n\nint line_sect(vec x0, vec x1, vec y0, vec y1, vec res)\n{\n\tvec_t dx, dy, d;\n\tvsub(x1, x0, &dx);\n\tvsub(y1, y0, &dy);\n\tvsub(x0, y0, &d);\n\t\/* x0 + a dx = y0 + b dy ->\n\t   x0 X dx = y0 X dx + b dy X dx ->\n\t   b = (x0 - y0) X dx \/ (dy X dx) *\/\n\tdouble dyx = cross(&dy, &dx);\n\tif (!dyx) return 0;\n\tdyx = cross(&d, &dx) \/ dyx;\n\tif (dyx <= 0 || dyx >= 1) return 0;\n\n\tres->x = y0->x + dyx * dy.x;\n\tres->y = y0->y + dyx * dy.y;\n\treturn 1;\n}\n\n\/* === polygon stuff === *\/\ntypedef struct { int len, alloc; vec v; } poly_t, *poly;\n\npoly poly_new()\n{\n\treturn (poly)calloc(1, sizeof(poly_t));\n}\n\nvoid poly_free(poly p)\n{\n\tfree(p->v);\n\tfree(p);\n}\n\nvoid poly_append(poly p, vec v)\n{\n\tif (p->len >= p->alloc) {\n\t\tp->alloc *= 2;\n\t\tif (!p->alloc) p->alloc = 4;\n\t\tp->v = (vec)realloc(p->v, sizeof(vec_t) * p->alloc);\n\t}\n\tp->v[p->len++] = *v;\n}\n\n\/* this works only if all of the following are true:\n *   1. poly has no colinear edges;\n *   2. poly has no duplicate vertices;\n *   3. poly has at least three vertices;\n *   4. poly is convex (implying 3).\n*\/\nint poly_winding(poly p)\n{\n\treturn left_of(p->v, p->v + 1, p->v + 2);\n}\n\nvoid poly_edge_clip(poly sub, vec x0, vec x1, int left, poly res)\n{\n\tint i, side0, side1;\n\tvec_t tmp;\n\tvec v0 = sub->v + sub->len - 1, v1;\n\tres->len = 0;\n\n\tside0 = left_of(x0, x1, v0);\n\tif (side0 != -left) poly_append(res, v0);\n\n\tfor (i = 0; i < sub->len; i++) {\n\t\tv1 = sub->v + i;\n\t\tside1 = left_of(x0, x1, v1);\n\t\tif (side0 + side1 == 0 && side0)\n\t\t\t\/* last point and current straddle the edge *\/\n\t\t\tif (line_sect(x0, x1, v0, v1, &tmp))\n\t\t\t\tpoly_append(res, &tmp);\n\t\tif (i == sub->len - 1) break;\n\t\tif (side1 != -left) poly_append(res, v1);\n\t\tv0 = v1;\n\t\tside0 = side1;\n\t}\n}\n\npoly poly_clip(poly sub, poly clip)\n{\n\tint i;\n\tpoly p1 = poly_new(), p2 = poly_new(), tmp;\n\n\tint dir = poly_winding(clip);\n\tpoly_edge_clip(sub, clip->v + clip->len - 1, clip->v, dir, p2);\n\tfor (i = 0; i < clip->len - 1; i++) {\n\t\ttmp = p2; p2 = p1; p1 = tmp;\n\t\tif(p1->len == 0) {\n\t\t\tp2->len = 0;\n\t\t\tbreak;\n\t\t}\n\t\tpoly_edge_clip(p1, clip->v + i, clip->v + i + 1, dir, p2);\n\t}\n\n\tpoly_free(p1);\n\treturn p2;\n}\n\nint main()\n{\n\tint i;\n\tvec_t c[] = {{100,100}, {300,100}, {300,300}, {100,300}};\n\t\/\/vec_t c[] = {{100,300}, {300,300}, {300,100}, {100,100}};\n\tvec_t s[] = {\t{50,150}, {200,50}, {350,150},\n\t\t\t{350,300},{250,300},{200,250},\n\t\t\t{150,350},{100,250},{100,200}};\n#define clen (sizeof(c)\/sizeof(vec_t))\n#define slen (sizeof(s)\/sizeof(vec_t))\n\tpoly_t clipper = {clen, 0, c};\n\tpoly_t subject = {slen, 0, s};\n\n\tpoly res = poly_clip(&subject, &clipper);\n\n\tfor (i = 0; i < res->len; i++)\n\t\tprintf(\"%g %g\\n\", res->v[i].x, res->v[i].y);\n\n\t\/* long and arduous EPS printout *\/\n\tFILE * eps = fopen(\"test.eps\", \"w\");\n\tfprintf(eps, \"%%!PS-Adobe-3.0\\n%%%%BoundingBox: 40 40 360 360\\n\"\n\t\t\"\/l {lineto} def \/m{moveto} def \/s{setrgbcolor} def\"\n\t\t\"\/c {closepath} def \/gs {fill grestore stroke} def\\n\");\n\tfprintf(eps, \"0 setlinewidth %g %g m \", c[0].x, c[0].y);\n\tfor (i = 1; i < clen; i++)\n\t\tfprintf(eps, \"%g %g l \", c[i].x, c[i].y);\n\tfprintf(eps, \"c .5 0 0 s gsave 1 .7 .7 s gs\\n\");\n\n\tfprintf(eps, \"%g %g m \", s[0].x, s[0].y);\n\tfor (i = 1; i < slen; i++)\n\t\tfprintf(eps, \"%g %g l \", s[i].x, s[i].y);\n\tfprintf(eps, \"c 0 .2 .5 s gsave .4 .7 1 s gs\\n\");\n\n\tfprintf(eps, \"2 setlinewidth [10 8] 0 setdash %g %g m \",\n\t\tres->v[0].x, res->v[0].y);\n\tfor (i = 1; i < res->len; i++)\n\t\tfprintf(eps, \"%g %g l \", res->v[i].x, res->v[i].y);\n\tfprintf(eps, \"c .5 0 .5 s gsave .7 .3 .8 s gs\\n\");\n\n\tfprintf(eps, \"%%%%EOF\");\n\tfclose(eps);\n\tprintf(\"test.eps written\\n\");\n\n\treturn 0;\n}\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as input, clips the polygon by the rectangle, and outputs the sequence of points defining the resulting clipped polygon. Additionally, it provides an option to visually display all three polygons on a graphical surface, with each polygon in a different color. The code also includes utility routines for storage and writes the test results to a 'test.eps' file in the current directory.","id":3500}
    {"lang_cluster":"C","source_code":"\n\n#include<stdlib.h>\n#include<stdio.h>\n\ntypedef struct{\n\tint score;\n\tchar name[100];\n}entry;\n\nvoid ordinalRanking(entry* list,int len){\n\t\n\tint i;\n\t\n\tprintf(\"\\n\\nOrdinal Ranking\\n---------------\");\n\t\n\tfor(i=0;i<len;i++)\n\t\tprintf(\"\\n%d\\t%d\\t%s\",i+1,list[i].score,list[i].name);\n}\n\nvoid standardRanking(entry* list,int len){\n\t\n\tint i,j=1;\n\t\n\tprintf(\"\\n\\nStandard Ranking\\n----------------\");\n\t\n\tfor(i=0;i<len;i++){\n\t\tprintf(\"\\n%d\\t%d\\t%s\",j,list[i].score,list[i].name);\n\t\tif(list[i+1].score<list[i].score)\n\t\t\tj = i+2;\n\t}\n}\n\nvoid denseRanking(entry* list,int len){\n\t\n\tint i,j=1;\n\t\n\tprintf(\"\\n\\nDense Ranking\\n-------------\");\n\t\n\tfor(i=0;i<len;i++){\n\t\tprintf(\"\\n%d\\t%d\\t%s\",j,list[i].score,list[i].name);\n\t\tif(list[i+1].score<list[i].score)\n\t\t\tj++;\n\t}\n}\n\nvoid modifiedRanking(entry* list,int len){\n\t\n\tint i,j,count;\n\t\n\tprintf(\"\\n\\nModified Ranking\\n----------------\");\n\t\n\tfor(i=0;i<len-1;i++){\n\t\tif(list[i].score!=list[i+1].score){\n\t\t\tprintf(\"\\n%d\\t%d\\t%s\",i+1,list[i].score,list[i].name);\n\t\t\tcount = 1;\n\t\t\tfor(j=i+1;list[j].score==list[j+1].score && j<len-1;j++)\n\t\t\t\tcount ++;\n\t\t\tfor(j=0;j<count-1;j++)\n\t\t\t\tprintf(\"\\n%d\\t%d\\t%s\",i+count+1,list[i+j+1].score,list[i+j+1].name);\n\t\t\ti += (count-1);\n\t\t}\n\t}\n\tprintf(\"\\n%d\\t%d\\t%s\",len,list[len-1].score,list[len-1].name);\n}\n\nvoid fractionalRanking(entry* list,int len){\n\t\n\tint i,j,count;\n\tfloat sum = 0;\n\t\n\tprintf(\"\\n\\nFractional Ranking\\n------------------\");\n\t\n\tfor(i=0;i<len;i++){\n\t\tif(i==len-1 || list[i].score!=list[i+1].score)\n\t\t\tprintf(\"\\n%.1f\\t%d\\t%s\",(float)(i+1),list[i].score,list[i].name);\n\t\telse if(list[i].score==list[i+1].score){\n\t\t\tsum = i;\n\t\t\tcount = 1;\n\t\t\tfor(j=i;list[j].score==list[j+1].score;j++){\n\t\t\t\tsum += (j+1);\n\t\t\t\tcount ++;\n\t\t\t}\n\t\t\tfor(j=0;j<count;j++)\n\t\t\t\tprintf(\"\\n%.1f\\t%d\\t%s\",sum\/count + 1,list[i+j].score,list[i+j].name);\n\t\t\ti += (count-1);\n\t\t}\n\t}\n}\n\nvoid processFile(char* fileName){\n\tFILE* fp = fopen(fileName,\"r\");\n\tentry* list;\n\tint i,num;\n\t\n\tfscanf(fp,\"%d\",&num);\n\t\n\tlist = (entry*)malloc(num*sizeof(entry));\n\t\n\tfor(i=0;i<num;i++)\n\t\tfscanf(fp,\"%d%s\",&list[i].score,list[i].name);\n\t\n\tfclose(fp);\n\t\n\tordinalRanking(list,num);\n\tstandardRanking(list,num);\n\tdenseRanking(list,num);\n\tmodifiedRanking(list,num);\n\tfractionalRanking(list,num);\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=2)\n\t\tprintf(\"Usage %s <score list file>\");\n\telse\n\t\tprocessFile(argV[1]);\n\treturn 0;\n}\n\n\n7\n44 Solomon\n42 Jason\n42 Errol\n41 Garry\n41 Bernard\n41 Barry\n39 Stephen\n\n\nC:\\rosettaCode>ranking.exe rankData.txt\n\n\nOrdinal Ranking\n---------------\n1       44      Solomon\n2       42      Jason\n3       42      Errol\n4       41      Garry\n5       41      Bernard\n6       41      Barry\n7       39      Stephen\n\nStandard Ranking\n----------------\n1       44      Solomon\n2       42      Jason\n2       42      Errol\n4       41      Garry\n4       41      Bernard\n4       41      Barry\n7       39      Stephen\n\nDense Ranking\n-------------\n1       44      Solomon\n2       42      Jason\n2       42      Errol\n3       41      Garry\n3       41      Bernard\n3       41      Barry\n4       39      Stephen\n\nModified Ranking\n----------------\n1       44      Solomon\n3       42      Jason\n3       42      Errol\n6       41      Garry\n6       41      Bernard\n6       41      Barry\n7       39      Stephen\n\nFractional Ranking\n------------------\n1.0     44      Solomon\n2.5     42      Jason\n2.5     42      Errol\n5.0     41      Garry\n5.0     41      Bernard\n5.0     41      Barry\n7.0     39      Stephen\n\n","human_summarization":"\"Code implements various ranking methods (Standard, Modified, Dense, Ordinal, Fractional) for competitors in a competition. It takes competition scores from an input file, assigns ranks based on each method, and outputs the rankings. It also handles incorrect invocation by displaying usage instructions.\"","id":3501}
    {"lang_cluster":"C","source_code":"\n#include <math.h>\n#include <stdio.h>\n\nint main() {\n  double pi = 4 * atan(1);\n  \/*Pi \/ 4 is 45 degrees. All answers should be the same.*\/\n  double radians = pi \/ 4;\n  double degrees = 45.0;\n  double temp;\n  \/*sine*\/\n  printf(\"%f %f\\n\", sin(radians), sin(degrees * pi \/ 180));\n  \/*cosine*\/\n  printf(\"%f %f\\n\", cos(radians), cos(degrees * pi \/ 180));\n  \/*tangent*\/\n  printf(\"%f %f\\n\", tan(radians), tan(degrees * pi \/ 180));\n  \/*arcsine*\/\n  temp = asin(sin(radians));\n  printf(\"%f %f\\n\", temp, temp * 180 \/ pi);\n  \/*arccosine*\/\n  temp = acos(cos(radians));\n  printf(\"%f %f\\n\", temp, temp * 180 \/ pi);\n  \/*arctangent*\/\n  temp = atan(tan(radians));\n  printf(\"%f %f\\n\", temp, temp * 180 \/ pi);\n\n  return 0;\n}\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":3502}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n    int count;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150,   1},\n    {\"compass\",                 13,    35,   1},\n    {\"water\",                  153,   200,   2},\n    {\"sandwich\",                50,    60,   2},\n    {\"glucose\",                 15,    60,   2},\n    {\"tin\",                     68,    45,   3},\n    {\"banana\",                  27,    60,   3},\n    {\"apple\",                   39,    40,   3},\n    {\"cheese\",                  23,    30,   1},\n    {\"beer\",                    52,    10,   3},\n    {\"suntan cream\",            11,    70,   1},\n    {\"camera\",                  32,    30,   1},\n    {\"T-shirt\",                 24,    15,   2},\n    {\"trousers\",                48,    10,   2},\n    {\"umbrella\",                73,    40,   1},\n    {\"waterproof trousers\",     42,    70,   1},\n    {\"waterproof overclothes\",  43,    75,   1},\n    {\"note-case\",               22,    80,   1},\n    {\"sunglasses\",               7,    20,   1},\n    {\"towel\",                   18,    12,   2},\n    {\"socks\",                    4,    50,   1},\n    {\"book\",                    30,    10,   2},\n};\n\nint n = sizeof (items) \/ sizeof (item_t);\n\nint *knapsack (int w) {\n    int i, j, k, v, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            m[i][j] = m[i - 1][j];\n            for (k = 1; k <= items[i - 1].count; k++) {\n                if (k * items[i - 1].weight > j) {\n                    break;\n                }\n                v = m[i - 1][j - k * items[i - 1].weight] + k * items[i - 1].value;\n                if (v > m[i][j]) {\n                    m[i][j] = v;\n                }\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        int v = m[i][j];\n        for (k = 0; v != m[i - 1][j] + k * items[i - 1].value; k++) {\n            s[i - 1]++;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, tc = 0, tw = 0, tv = 0, *s;\n    s = knapsack(400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d %5d\\n\", items[i].name, s[i], s[i] * items[i].weight, s[i] * items[i].value);\n            tc += s[i];\n            tw += s[i] * items[i].weight;\n            tv += s[i] * items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d %5d\\n\", \"count, weight, value:\", tc, tw, tv);\n    return 0;\n}\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. It selects items based on their importance value and weight, ensuring the total weight does not exceed the limit and the total value is maximized. The code considers the quantity available of each item and only allows whole units to be selected.","id":3503}
    {"lang_cluster":"C","source_code":"\nLibrary: POSIX\n\n#include <stdio.h>\n#include <stdlib.h>\t\/\/ for exit()\n#include <signal.h>\n#include <time.h>\t\/\/ for clock()\n#include <unistd.h>\t\/\/ for POSIX usleep()\n\nvolatile sig_atomic_t gotint = 0;\n\nvoid handleSigint() {\n    \/*\n     * Signal safety: It is not safe to call clock(), printf(),\n     * or exit() inside a signal handler. Instead, we set a flag.\n     *\/\n    gotint = 1;\n}\n \nint main() {\n    clock_t startTime = clock();\n    signal(SIGINT, handleSigint);\n    int i=0;\n    for (;;) {\n        if (gotint)\n            break;\n        usleep(500000);\n        if (gotint)\n            break;\n\tprintf(\"%d\\n\", ++i);\n    }\n    clock_t endTime = clock();\n    double td = (endTime - startTime) \/ (double)CLOCKS_PER_SEC;\n    printf(\"Program has run for %5.3f seconds\\n\", td);\n    return 0;\n}\n\n\n","human_summarization":"The code outputs an integer every half second. When a SIGINT or SIGQUIT signal is received, typically from the user typing ctrl-C or ctrl-\\, the program stops outputting integers, displays the total runtime in seconds, and then terminates. To achieve the half-second delay, the POSIX usleep() function is used instead of the standard C's sleep() function. Signal handlers are implemented to ensure the program behaves predictably upon receiving a signal.","id":3504}
    {"lang_cluster":"C","source_code":"\nHandling strings of arbitrary sizes:#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n\/*  Constraints: input is in the form of (\\+|-)?[0-9]+\n *  and without leading zero (0 itself can be as \"0\" or \"+0\", but not \"-0\");\n *  input pointer is realloc'able and may change;\n *  if input has leading + sign, return may or may not keep it.\n *  The constranits conform to sprintf(\"%+d\") and this function's own output.\n *\/\nchar * incr(char *s)\n{\n\tint i, begin, tail, len;\n\tint neg = (*s == '-');\n\tchar tgt = neg ? '0' : '9';\n\n\t\/* special case: \"-1\" *\/\n\tif (!strcmp(s, \"-1\")) {\n\t\ts[0] = '0', s[1] = '\\0';\n\t\treturn s;\n\t}\n\n\tlen = strlen(s);\n\tbegin = (*s == '-' || *s == '+') ? 1 : 0;\n\n\t\/* find out how many digits need to be changed *\/\n\tfor (tail = len - 1; tail >= begin && s[tail] == tgt; tail--);\n\n\tif (tail < begin && !neg) {\n\t\t\/* special case: all 9s, string will grow *\/\n\t\tif (!begin) s = realloc(s, len + 2);\n\t\ts[0] = '1';\n\t\tfor (i = 1; i <= len - begin; i++) s[i] = '0';\n\t\ts[len + 1] = '\\0';\n\t} else if (tail == begin && neg && s[1] == '1') {\n\t\t\/* special case: -1000..., so string will shrink *\/\n\t\tfor (i = 1; i < len - begin; i++) s[i] = '9';\n\t\ts[len - 1] = '\\0';\n\t} else { \/* normal case; change tail to all 0 or 9, change prev digit by 1*\/\n\t\tfor (i = len - 1; i > tail; i--)\n\t\t\ts[i] = neg ? '9' : '0';\n\t\ts[tail] += neg ? -1 : 1;\n\t}\n\n\treturn s;\n}\n\nvoid string_test(const char *s)\n{\n\tchar *ret = malloc(strlen(s));\n\tstrcpy(ret, s);\n\n\tprintf(\"text: %s\\n\", ret);\n\tprintf(\"  ->: %s\\n\", ret = incr(ret));\n\tfree(ret);\n}\n\nint main()\n{\n\tstring_test(\"+0\");\n\tstring_test(\"-1\");\n\tstring_test(\"-41\");\n\tstring_test(\"+41\");\n\tstring_test(\"999\");\n\tstring_test(\"+999\");\n\tstring_test(\"109999999999999999999999999999999999999999\");\n\tstring_test(\"-100000000000000000000000000000000000000000000\");\n\n\treturn 0;\n}\n\n\n","human_summarization":"\"Increments a given numerical string.\"","id":3505}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nint common_len(const char *const *names, int n, char sep)\n{\n\tint i, pos;\n\tfor (pos = 0; ; pos++) {\n\t\tfor (i = 0; i < n; i++) {\n\t\t\tif (names[i][pos] != '\\0' &&\n\t\t\t\t\tnames[i][pos] == names[0][pos])\n\t\t\t\tcontinue;\n\n\t\t\t\/* backtrack *\/\n\t\t\twhile (pos > 0 && names[0][--pos] != sep);\n\t\t\treturn pos;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nint main()\n{\n\tconst char *names[] = {\n\t\t\"\/home\/user1\/tmp\/coverage\/test\",\n\t\t\"\/home\/user1\/tmp\/covert\/operator\",\n\t\t\"\/home\/user1\/tmp\/coven\/members\",\n\t};\n\tint len = common_len(names, sizeof(names) \/ sizeof(const char*), '\/');\n\n\tif (!len) printf(\"No common path\\n\");\n\telse      printf(\"Common path:\u00a0%.*s\\n\", len, names[0]);\n\n\treturn 0;\n}\noutput:Common path: \/home\/user1\/tmp\n\n","human_summarization":"The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '\/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.","id":3506}
    {"lang_cluster":"C","source_code":"\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\nvoid sattoloCycle(void** arr,int count){\n\tint i,j;\n\tvoid* temp;\n\t\n\tif(count<2)\n\t\treturn;\n\tfor(i=count-1;i>=1;i--){\n\t\tj = rand()%i;\n\t\ttemp = arr[j];\n\t\tarr[j] = arr[i];\n\t\tarr[i] = temp;\n\t}\n}\n\nint main(int argC,char* argV[])\n{\n\tint i;\n\t\n\tif(argC==1)\n\t\tprintf(\"Usage\u00a0: %s <array elements separated by a space each>\",argV[0]);\n\telse{\n                srand((unsigned)time(NULL));\n\t\tsattoloCycle((void*)(argV + 1),argC-1);\n\t\t\n\t\tfor(i=1;i<argC;i++)\n\t\t\tprintf(\"%s \",argV[i]);\n\t}\n\treturn 0;\n}\n\n\nC:\\rosettaCode>sattoloCycle.exe \"\"\n\nC:\\rosettaCode>sattoloCycle.exe 10\n10\nC:\\rosettaCode>sattoloCycle.exe 10 20\n20 10\nC:\\rosettaCode>sattoloCycle.exe 10 20 30\n30 10 20\nC:\\rosettaCode>sattoloCycle.exe 11 12 13 14 15 16 17 18 19 20 21 22\n16 17 11 12 13 20 22 14 15 21 18 19\nC:\\rosettaCode>sattoloCycle.exe s a t t o l o C y c l e\nl o s a t c e t o l C y\nC:\\rosettaCode>sattoloCycle.exe 1 2.3 4.2 1 3 e r q t 2 1 oo 2.1 eds\n1 2.1 2.3 q r eds 1 e 3 t 1 2 oo 4.2\nC:\\rosettaCode>sattoloCycle.exe totally mixed up random string ( 1 2.3 2 ) which will get even more { a 2 q.1 } mixed up.\nmixed q.1 a 1 up ) 2 even { will ( } 2 more totally random get which string up. 2.3 mixed\n\n\n#include<stdlib.h>\n#include<stdio.h>\n#include<time.h>\n\nvoid sattoloCycle(void** arr,int count){\n\tint i,j;\n\tvoid* temp;\n\t\n\tif(count<2)\n\t\treturn;\n\tfor(i=count-1;i>=1;i--){\n\t\tj = rand()%i;\n\t\ttemp = arr[j];\n\t\tarr[j] = arr[i];\n\t\tarr[i] = temp;\n\t}\n}\n\nint main()\n{\n\tint i;\n\t\n\tint a[] = {};\n\tint b[] = {10};\n\tint c[] = {10, 20};\n\tint d[] = {10, 20, 30};\n\tint e[] = {11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22};\n\n\tsrand((unsigned)time(NULL));\n\tsattoloCycle((void*)a,0);\n\t\t\n\tprintf(\"\\nShuffled a = \");\n\tfor(i=0;i<0;i++)\n\t\tprintf(\"%d \",a[i]);\n\t\t\n\tsattoloCycle((void*)b,1);\n\t\t\n\tprintf(\"\\nShuffled b = \");\n\tfor(i=0;i<1;i++)\n\t\tprintf(\"%d \",b[i]);\n\t\t\t\n\tsattoloCycle((void*)c,2);\n\t\t\n\tprintf(\"\\nShuffled c = \");\n\tfor(i=0;i<2;i++)\n\t\tprintf(\"%d \",c[i]);\n\t\n\tsattoloCycle((void*)d,3);\n\t\t\n\tprintf(\"\\nShuffled d = \");\n\tfor(i=0;i<3;i++)\n\t\tprintf(\"%d \",d[i]);\n\t\t\n\tsattoloCycle((void*)e,12);\n\t\t\n\tprintf(\"\\nShuffled e = \");\n\tfor(i=0;i<12;i++)\n\t\tprintf(\"%d \",e[i]);\n\n\treturn 0;\n}\n\n\nShuffled a =\nShuffled b = 10\nShuffled c = 20 10\nShuffled d = 20 30 10\nShuffled e = 13 18 14 20 17 15 21 19 16 12 22 11\n\n","human_summarization":"implement the Sattolo cycle algorithm that shuffles an array ensuring each element ends up in a new position. The algorithm modifies the input array in-place or returns a new array based on the programming language's convenience. The function can handle any type of array.","id":3507}
    {"lang_cluster":"C","source_code":"\n\nLibrary: libcurl\n#include <curl\/curl.h>\n#include <string.h>\n#include <stdio.h>\n\nsize_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fwrite(ptr,size,nmeb,stream);\n}\n\nsize_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){\n    return fread(ptr,size,nmeb,stream);\n}\n\nvoid callSOAP(char* URL, char * inFile, char * outFile) {\n\n    FILE * rfp = fopen(inFile, \"r\");\n    if(!rfp) \n        perror(\"Read File Open:\");\n\n    FILE * wfp = fopen(outFile, \"w+\");\n    if(!wfp)\n        perror(\"Write File Open:\");\n\n    struct curl_slist *header = NULL;\n\t\theader = curl_slist_append (header, \"Content-Type:text\/xml\");\n\t\theader = curl_slist_append (header, \"SOAPAction: rsc\");\n\t\theader = curl_slist_append (header, \"Transfer-Encoding: chunked\");\n\t\theader = curl_slist_append (header, \"Expect:\");\n    CURL *curl;\n\n    curl = curl_easy_init();\n    if(curl) {\n        curl_easy_setopt(curl, CURLOPT_URL, URL);\n        curl_easy_setopt(curl, CURLOPT_POST, 1L);\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data);\n        curl_easy_setopt(curl, CURLOPT_READDATA, rfp); \n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp);\n        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1);\n        curl_easy_setopt(curl, CURLOPT_VERBOSE,1L);            \n        curl_easy_perform(curl);\n\n        curl_easy_cleanup(curl);\n    }\n}\n\nint main(int argC,char* argV[])\n{\n\tif(argC!=4)\n\t\tprintf(\"Usage\u00a0: %s <URL of WSDL> <Input file path> <Output File Path>\",argV[0]);\n\telse\n\t\tcallSOAP(argV[1],argV[2],argV[3]);\n\treturn 0;\n}\n\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" \nxmlns:xsd=\"http:\/\/www.w3.org\/2001\/XMLSchema\" \nxmlns:soapenv=\"http:\/\/schemas.xmlsoap.org\/soap\/envelope\/\" \nxmlns:dom=\"http:\/\/example.com\/soap\/wsdl\">\n   <soapenv:Header\/>\n   <soapenv:Body>\n      <dom:soapFunc soapenv:encodingStyle=\"http:\/\/schemas.xmlsoap.org\/soap\/encoding\/\"\/>\n   <\/soapenv:Body>\n<\/soapenv:Envelope>\n\n\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" \nxmlns:xsd=\"http:\/\/www.w3.org\/2001\/XMLSchema\" \nxmlns:soapenv=\"http:\/\/schemas.xmlsoap.org\/soap\/envelope\/\" \nxmlns:dom=\"http:\/\/example.com\/soap\/wsdl\">\n   <soapenv:Header\/>\n   <soapenv:Body>\n      <dom:anotherSoapFunc soapenv:encodingStyle=\"http:\/\/schemas.xmlsoap.org\/soap\/encoding\/\"\/>\n   <\/soapenv:Body>\n<\/soapenv:Envelope>\n\n","human_summarization":"The code creates a SOAP client that accesses and calls the functions soapFunc() and anotherSoapFunc() defined at http:\/\/example.com\/soap\/wsdl. It requires the construction of input XML files for these functions and may need libraries like xerces if written in C. Note that the code may be flagged incorrect due to pending task clarification.","id":3508}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct floatList {\n    float *list;\n    int   size;\n} *FloatList;\n\nint floatcmp( const void *a, const void *b) {\n    if (*(const float *)a < *(const float *)b) return -1;\n    else return *(const float *)a > *(const float *)b;\n}\n\nfloat median( FloatList fl )\n{\n    qsort( fl->list, fl->size, sizeof(float), floatcmp);\n    return 0.5 * ( fl->list[fl->size\/2] + fl->list[(fl->size-1)\/2]);\n}\n\nint main()\n{\n    static float floats1[] = { 5.1, 2.6, 6.2, 8.8, 4.6, 4.1 };\n    static struct floatList flist1 = { floats1, sizeof(floats1)\/sizeof(float) };\n\n    static float floats2[] = { 5.1, 2.6, 8.8, 4.6, 4.1 };\n    static struct floatList flist2 = { floats2, sizeof(floats2)\/sizeof(float) };\n\n    printf(\"flist1 median is %7.2f\\n\", median(&flist1)); \/* 4.85 *\/\n    printf(\"flist2 median is %7.2f\\n\", median(&flist2)); \/* 4.60 *\/\n    return 0;\n}\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n \n#define MAX_ELEMENTS 1000000\n \n\/* Return the k-th smallest item in array x of length len *\/\ndouble quick_select(int k, double *x, int len)\n{\n   inline void swap(int a, int b)\n   {\n      double t = x[a];\n      x[a] = x[b], x[b] = t;\n   }\n \n   int left = 0, right = len - 1;\n   int pos, i;\n   double pivot;\n \n   while (left < right)\n   {\n      pivot = x[k];\n      swap(k, right);\n      for (i = pos = left; i < right; i++)\n      {\n         if (x[i] < pivot)\n         {\n            swap(i, pos);\n            pos++;\n         }\n      }\n      swap(right, pos);\n      if (pos == k) break;\n      if (pos < k) left = pos + 1;\n      else right = pos - 1;\n   }\n   return x[k];\n}\n \nint main(void)\n{\n   int i, length;\n   double *x, median;\n \n   \/* Initialize random length double array with random doubles *\/\n   srandom(time(0));\n   length = random() % MAX_ELEMENTS;\n   x = malloc(sizeof(double) * length);\n   for (i = 0; i < length; i++)\n   {\n      \/\/ shifted by RAND_MAX for negative values\n      \/\/ divide by a random number for floating point\n      x[i] = (double)(random() - RAND_MAX \/ 2) \/ (random() + 1); \/\/ + 1 to not divide by 0\n   }\n \n\n   if (length % 2 == 0) \/\/ Even number of elements, median is average of middle two\n   {\n      median = (quick_select(length \/ 2, x, length) + quick_select(length \/ 2 - 1, x, length \/ 2)) \/ 2;\n   } \n   else \/\/ select middle element\n   {\n      median = quick_select(length \/ 2, x, length);\n   }\n \n\n   \/* Sanity testing of median *\/\n   int less = 0, more = 0, eq = 0;\n   for (i = 0; i < length; i++)\n   {\n      if (x[i] < median) less ++;\n      else if (x[i] > median) more ++;\n      else eq ++;\n   }\n   printf(\"length: %d\\nmedian: %lf\\n<: %d\\n>: %d\\n=: %d\\n\", length, median, less, more, eq);\n\n   free(x);\n   return 0;\n}\n\n\nlength: 992021\nmedian: 0.000473\n<: 496010\n>: 496010\n=: 1\n\n","human_summarization":"find the median value of a vector of floating-point numbers. It handles the case of an even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time efficiency. The code also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation.","id":3509}
    {"lang_cluster":"C","source_code":"\n\n  int i = 0 ;  char B[88] ;\n  while ( i++ < 100 )\n    !sprintf( B, \"%s%s\", i%3 ? \"\":\"Fizz\", i%5 ? \"\":\"Buzz\" )\n    ? sprintf( B, \"%d\", i ):0, printf( \", %s\", B );\n\n\n  int i = 0 ;  char B[88] ;\n  while ( i++ < 100 )\n    !sprintf( B, \"%s%s%s%s\", \n       i%3 ? \"\":\"Fiz\", i%5 ? \"\":\"Buz\", i%7 ? \"\":\"Goz\", i%11 ? \"\":\"Kaz\" )\n    ? sprintf( B, \"%d\", i ):0, printf( \", %s\", B );\n\n","human_summarization":"The code prints integers from 1 to 100. It replaces multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'. This is a solution to the FizzBuzz problem, demonstrating basic programming comprehension. The code is optimized for low signal-to-noise and is presented in various forms including one-line, pretty printing, and obfuscated versions.","id":3510}
    {"lang_cluster":"C","source_code":"\n\n \/* \n c program:\n --------------------------------\n  1. draws Mandelbrot set for Fc(z)=z*z +c\n  using Mandelbrot algorithm ( boolean escape time )\n -------------------------------         \n 2. technique of creating ppm file is  based on the code of Claudio Rocchini\n http:\/\/en.wikipedia.org\/wiki\/Image:Color_complex_plot.jpg\n create 24 bit color graphic file ,  portable pixmap file = PPM \n see http:\/\/en.wikipedia.org\/wiki\/Portable_pixmap\n to see the file use external application ( graphic viewer)\n  *\/\n #include <stdio.h>\n #include <math.h>\n int main()\n {\n          \/* screen ( integer) coordinate *\/\n        int iX,iY;\n        const int iXmax = 800; \n        const int iYmax = 800;\n        \/* world ( double) coordinate = parameter plane*\/\n        double Cx,Cy;\n        const double CxMin=-2.5;\n        const double CxMax=1.5;\n        const double CyMin=-2.0;\n        const double CyMax=2.0;\n        \/* *\/\n        double PixelWidth=(CxMax-CxMin)\/iXmax;\n        double PixelHeight=(CyMax-CyMin)\/iYmax;\n        \/* color component ( R or G or B) is coded from 0 to 255 *\/\n        \/* it is 24 bit color RGB file *\/\n        const int MaxColorComponentValue=255; \n        FILE * fp;\n        char *filename=\"new1.ppm\";\n        char *comment=\"# \";\/* comment should start with # *\/\n        static unsigned char color[3];\n        \/* Z=Zx+Zy*i \u00a0;   Z0 = 0 *\/\n        double Zx, Zy;\n        double Zx2, Zy2; \/* Zx2=Zx*Zx;  Zy2=Zy*Zy  *\/\n        \/*  *\/\n        int Iteration;\n        const int IterationMax=200;\n        \/* bail-out value , radius of circle\u00a0;  *\/\n        const double EscapeRadius=2;\n        double ER2=EscapeRadius*EscapeRadius;\n        \/*create new file,give it a name and open it in binary mode  *\/\n        fp= fopen(filename,\"wb\"); \/* b -  binary mode *\/\n        \/*write ASCII header to the file*\/\n        fprintf(fp,\"P6\\n %s\\n %d\\n %d\\n %d\\n\",comment,iXmax,iYmax,MaxColorComponentValue);\n        \/* compute and write image data bytes to the file*\/\n        for(iY=0;iY<iYmax;iY++)\n        {\n             Cy=CyMin + iY*PixelHeight;\n             if (fabs(Cy)< PixelHeight\/2) Cy=0.0; \/* Main antenna *\/\n             for(iX=0;iX<iXmax;iX++)\n             {         \n                        Cx=CxMin + iX*PixelWidth;\n                        \/* initial value of orbit = critical point Z= 0 *\/\n                        Zx=0.0;\n                        Zy=0.0;\n                        Zx2=Zx*Zx;\n                        Zy2=Zy*Zy;\n                        \/* *\/\n                        for (Iteration=0;Iteration<IterationMax && ((Zx2+Zy2)<ER2);Iteration++)\n                        {\n                            Zy=2*Zx*Zy + Cy;\n                            Zx=Zx2-Zy2 +Cx;\n                            Zx2=Zx*Zx;\n                            Zy2=Zy*Zy;\n                        };\n                        \/* compute  pixel color (24 bit = 3 bytes) *\/\n                        if (Iteration==IterationMax)\n                        { \/*  interior of Mandelbrot set = black *\/\n                           color[0]=0;\n                           color[1]=0;\n                           color[2]=0;                           \n                        }\n                     else \n                        { \/* exterior of Mandelbrot set = white *\/\n                             color[0]=255; \/* Red*\/\n                             color[1]=255;  \/* Green *\/ \n                             color[2]=255;\/* Blue *\/\n                        };\n                        \/*write color to the file*\/\n                        fwrite(color,1,3,fp);\n                }\n        }\n        fclose(fp);\n        return 0;\n }\n\n\n\nOpenBSD users, install freeglut package, and compile with make mandelbrot CPPFLAGS='-I\/usr\/local\/include `pkg-config glu --cflags`' LDLIBS='-L\/usr\/local\/lib -lglut `pkg-config glu --libs` -lm'\nLibrary: GLUT\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <GL\/glut.h>\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n \nvoid set_texture();\n \ntypedef struct {unsigned char r, g, b;} rgb_t;\nrgb_t **tex = 0;\nint gwin;\nGLuint texture;\nint width, height;\nint tex_w, tex_h;\ndouble scale = 1.\/256;\ndouble cx = -.6, cy = 0;\nint color_rotate = 0;\nint saturation = 1;\nint invert = 0;\nint max_iter = 256;\n \nvoid render()\n{\n\tdouble\tx = (double)width \/tex_w,\n\t\ty = (double)height\/tex_h;\n \n\tglClear(GL_COLOR_BUFFER_BIT);\n\tglTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);\n \n\tglBindTexture(GL_TEXTURE_2D, texture);\n \n\tglBegin(GL_QUADS);\n \n\tglTexCoord2f(0, 0); glVertex2i(0, 0);\n\tglTexCoord2f(x, 0); glVertex2i(width, 0);\n\tglTexCoord2f(x, y); glVertex2i(width, height);\n\tglTexCoord2f(0, y); glVertex2i(0, height);\n \n\tglEnd();\n \n\tglFlush();\n\tglFinish();\n}\n \nint dump = 1;\nvoid screen_dump()\n{\n\tchar fn[100];\n\tint i;\n\tsprintf(fn, \"screen%03d.ppm\", dump++);\n\tFILE *fp = fopen(fn, \"w\");\n\tfprintf(fp, \"P6\\n%d %d\\n255\\n\", width, height);\n\tfor (i = height - 1; i >= 0; i--)\n\t\tfwrite(tex[i], 1, width * 3, fp);\n\tfclose(fp);\n\tprintf(\"%s written\\n\", fn);\n}\n \nvoid keypress(unsigned char key, int x, int y)\n{\n\tswitch(key) {\n\tcase 'q':\tglFinish();\n\t\t\tglutDestroyWindow(gwin);\n\t\t\treturn;\n\tcase 27:\tscale = 1.\/256; cx = -.6; cy = 0; break;\n \n\tcase 'r':\tcolor_rotate = (color_rotate + 1) % 6;\n\t\t\tbreak;\n \n\tcase '>': case '.':\n\t\t\tmax_iter += 128;\n\t\t\tif (max_iter > 1 << 15) max_iter = 1 << 15;\n\t\t\tprintf(\"max iter: %d\\n\", max_iter);\n\t\t\tbreak;\n \n\tcase '<': case ',':\n\t\t\tmax_iter -= 128;\n\t\t\tif (max_iter < 128) max_iter = 128;\n\t\t\tprintf(\"max iter: %d\\n\", max_iter);\n\t\t\tbreak;\n \n\tcase 'c':\tsaturation = 1 - saturation;\n\t\t\tbreak;\n \n\tcase 's':\tscreen_dump(); return;\n\tcase 'z':\tmax_iter = 4096; break;\n\tcase 'x':\tmax_iter = 128; break;\n\tcase ' ':\tinvert = !invert;\n\t}\n\tset_texture();\n}\n \nvoid hsv_to_rgb(int hue, int min, int max, rgb_t *p)\n{\n\tif (min == max) max = min + 1;\n\tif (invert) hue = max - (hue - min);\n\tif (!saturation) {\n\t\tp->r = p->g = p->b = 255 * (max - hue) \/ (max - min);\n\t\treturn;\n\t}\n\tdouble h = fmod(color_rotate + 1e-4 + 4.0 * (hue - min) \/ (max - min), 6);\n#\tdefine VAL 255\n\tdouble c = VAL * saturation;\n\tdouble X = c * (1 - fabs(fmod(h, 2) - 1));\n \n\tp->r = p->g = p->b = 0;\n \n\tswitch((int)h) {\n\tcase 0: p->r = c; p->g = X; return;\n\tcase 1:\tp->r = X; p->g = c; return;\n\tcase 2: p->g = c; p->b = X; return;\n\tcase 3: p->g = X; p->b = c; return;\n\tcase 4: p->r = X; p->b = c; return;\n\tdefault:p->r = c; p->b = X;\n\t}\n}\n \nvoid calc_mandel()\n{\n\tint i, j, iter, min, max;\n\trgb_t *px;\n\tdouble x, y, zx, zy, zx2, zy2;\n\tmin = max_iter; max = 0;\n\tfor (i = 0; i < height; i++) {\n\t\tpx = tex[i];\n\t\ty = (i - height\/2) * scale + cy;\n\t\tfor (j = 0; j  < width; j++, px++) {\n\t\t\tx = (j - width\/2) * scale + cx;\n\t\t\titer = 0;\n \n\t\t\tzx = hypot(x - .25, y);\n\t\t\tif (x < zx - 2 * zx * zx + .25) iter = max_iter;\n\t\t\tif ((x + 1)*(x + 1) + y * y < 1\/16) iter = max_iter;\n \n\t\t\tzx = zy = zx2 = zy2 = 0;\n\t\t\tfor (; iter < max_iter && zx2 + zy2 < 4; iter++) {\n\t\t\t\tzy = 2 * zx * zy + y;\n\t\t\t\tzx = zx2 - zy2 + x;\n\t\t\t\tzx2 = zx * zx;\n\t\t\t\tzy2 = zy * zy;\n\t\t\t}\n\t\t\tif (iter < min) min = iter;\n\t\t\tif (iter > max) max = iter;\n\t\t\t*(unsigned short *)px = iter;\n\t\t}\n\t}\n \n\tfor (i = 0; i < height; i++)\n\t\tfor (j = 0, px = tex[i]; j  < width; j++, px++)\n\t\t\thsv_to_rgb(*(unsigned short*)px, min, max, px);\n}\n \nvoid alloc_tex()\n{\n\tint i, ow = tex_w, oh = tex_h;\n \n\tfor (tex_w = 1; tex_w < width;  tex_w <<= 1);\n\tfor (tex_h = 1; tex_h < height; tex_h <<= 1);\n \n\tif (tex_h != oh || tex_w != ow)\n\t\ttex = realloc(tex, tex_h * tex_w * 3 + tex_h * sizeof(rgb_t*));\n \n\tfor (tex[0] = (rgb_t *)(tex + tex_h), i = 1; i < tex_h; i++)\n\t\ttex[i] = tex[i - 1] + tex_w;\n}\n \nvoid set_texture()\n{\n\talloc_tex();\n\tcalc_mandel();\n \n\tglEnable(GL_TEXTURE_2D);\n\tglBindTexture(GL_TEXTURE_2D, texture);\n\tglTexImage2D(GL_TEXTURE_2D, 0, 3, tex_w, tex_h,\n\t\t0, GL_RGB, GL_UNSIGNED_BYTE, tex[0]);\n \n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\trender();\n}\n \nvoid mouseclick(int button, int state, int x, int y)\n{\n\tif (state != GLUT_UP) return;\n \n\tcx += (x - width \/ 2) * scale;\n\tcy -= (y - height\/ 2) * scale;\n \n\tswitch(button) {\n\tcase GLUT_LEFT_BUTTON: \/* zoom in *\/\n\t\tif (scale > fabs(x) * 1e-16 && scale > fabs(y) * 1e-16)\n\t\t\tscale \/= 2;\n\t\tbreak;\n\tcase GLUT_RIGHT_BUTTON: \/* zoom out *\/\n\t\tscale *= 2;\n\t\tbreak;\n\t\/* any other button recenters *\/\n\t}\n\tset_texture();\n}\n \n \nvoid resize(int w, int h)\n{\n\tprintf(\"resize %d %d\\n\", w, h);\n\twidth = w;\n\theight = h;\n \n\tglViewport(0, 0, w, h);\n\tglOrtho(0, w, 0, h, -1, 1);\n \n\tset_texture();\n}\n \nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 480);\n\t\n\tgwin = glutCreateWindow(\"Mandelbrot\");\n\tglutDisplayFunc(render);\n \n\tglutKeyboardFunc(keypress);\n\tglutMouseFunc(mouseclick);\n\tglutReshapeFunc(resize);\n\tglGenTextures(1, &texture);\n\tset_texture();\n}\n \nint main(int c, char **v)\n{\n\tinit_gfx(&c, v);\n\tprintf(\"keys:\\n\\tr: color rotation\\n\\tc: monochrome\\n\\ts: screen dump\\n\\t\"\n\t\t\"<, >: decrease\/increase max iteration\\n\\tq: quit\\n\\tmouse buttons to zoom\\n\");\n \n\tglutMainLoop();\n\treturn 0;\n}\n\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <math.h>\n#include <GL\/glut.h>\n#include <GL\/gl.h>\n#include <GL\/glu.h>\n\nvoid set_texture();\n\nunsigned char *tex;\nint gwin;\nGLuint texture;\nint width, height;\nint old_width, old_height;\ndouble scale = 1. \/ 256;\ndouble cx = -.6, cy = 0;\nint color_rotate = 0;\nint saturation = 1;\nint invert = 0;\nint max_iter = 256;\n\nvoid render()\n{\n    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);\n\n    glBindTexture(GL_TEXTURE_2D, texture);\n\n    glBegin(GL_QUADS);\n\n    glTexCoord2d(0, 0);\n    glVertex2i(0, 0);\n    glTexCoord2d(1, 0);\n    glVertex2i(width, 0);\n    glTexCoord2d(1, 1);\n    glVertex2i(width, height);\n    glTexCoord2d(0, 1);\n    glVertex2i(0, height);\n\n    glEnd();\n\n    glFlush();\n    glFinish();\n}\n\nint dump = 1;\nvoid screen_dump()\n{\n    char fn[100];\n    sprintf(fn, \"screen%03d.ppm\", dump++);\n    FILE *fp = fopen(fn, \"w\");\n    fprintf(fp, \"P6\\n%d %d\\n255\\n\", width, height);\n    for (int i = height - 1; i >= 0; i -= 1) {\n        for (int j = 0; j < width; j += 1) {\n            fwrite(&tex[((i * width) + j) * 4], 1, 3, fp);\n        }\n    }\n    fclose(fp);\n    printf(\"%s written\\n\", fn);\n}\n\nvoid keypress(unsigned char key,[[maybe_unused]]\n              int x,[[maybe_unused]]\n              int y)\n{\n    switch (key) {\n    case 'q':\n        glFinish();\n        glutDestroyWindow(gwin);\n        break;\n\n    case 27:\n        scale = 1. \/ 256;\n        cx = -.6;\n        cy = 0;\n        set_texture();\n        break;\n\n    case 'r':\n        color_rotate = (color_rotate + 1) % 6;\n        set_texture();\n        break;\n\n    case '>':\n    case '.':\n        max_iter += 128;\n        if (max_iter > 1 << 15)\n            max_iter = 1 << 15;\n        printf(\"max iter: %d\\n\", max_iter);\n        set_texture();\n        break;\n\n    case '<':\n    case ',':\n        max_iter -= 128;\n        if (max_iter < 128)\n            max_iter = 128;\n        printf(\"max iter: %d\\n\", max_iter);\n        set_texture();\n        break;\n\n    case 'c':\n        saturation = 1 - saturation;\n        set_texture();\n        break;\n\n    case 's':\n        screen_dump();\n        break;\n\n    case 'z':\n        max_iter = 4096;\n        set_texture();\n        break;\n\n    case 'x':\n        max_iter = 128;\n        set_texture();\n        break;\n\n    case ' ':\n        invert = !invert;\n        set_texture();\n        break;\n\n    default:\n        set_texture();\n        break;\n    }\n}\n\n#define VAL 255\n\nvoid hsv_to_rgba(int hue, int min, int max, unsigned char *px)\n{\n    unsigned char r;\n    unsigned char g;\n    unsigned char b;\n\n    if (min == max)\n        max = min + 1;\n    if (invert)\n        hue = max - (hue - min);\n    if (!saturation) {\n        r = 255 * (max - hue) \/ (max - min);\n        g = r;\n        b = r;\n    } else {\n        double h =\n            fmod(color_rotate + 1e-4 + 4.0 * (hue - min) \/ (max - min), 6);\n        double c = VAL * saturation;\n        double X = c * (1 - fabs(fmod(h, 2) - 1));\n\n        r = 0;\n        g = 0;\n        b = 0;\n\n        switch ((int) h) {\n        case 0:\n            r = c;\n            g = X;\n            break;\n        case 1:\n            r = X;\n            g = c;\n            break;\n        case 2:\n            g = c;\n            b = X;\n            break;\n        case 3:\n            g = X;\n            b = c;\n            break;\n        case 4:\n            r = X;\n            b = c;\n            break;\n        default:\n            r = c;\n            b = X;\n            break;\n        }\n    }\n\n    \/* Using an alpha channel neatly solves the problem of aligning\n     * rows on 4-byte boundaries (at the expense of memory, of\n     * course). *\/\n    px[0] = r;\n    px[1] = g;\n    px[2] = b;\n    px[3] = 255;                \/* Alpha channel. *\/\n}\n\nvoid calc_mandel()\n{\n    int i, j, iter, min, max;\n    double x, y, zx, zy, zx2, zy2;\n    unsigned short *hsv = malloc(width * height * sizeof(unsigned short));\n\n    min = max_iter;\n    max = 0;\n    for (i = 0; i < height; i++) {\n        y = (i - height \/ 2) * scale + cy;\n        for (j = 0; j < width; j++) {\n            x = (j - width \/ 2) * scale + cx;\n            iter = 0;\n\n            zx = hypot(x - .25, y);\n            if (x < zx - 2 * zx * zx + .25)\n                iter = max_iter;\n            if ((x + 1) * (x + 1) + y * y < 1 \/ 16)\n                iter = max_iter;\n\n            zx = 0;\n            zy = 0;\n            zx2 = 0;\n            zy2 = 0;\n            while (iter < max_iter && zx2 + zy2 < 4) {\n                zy = 2 * zx * zy + y;\n                zx = zx2 - zy2 + x;\n                zx2 = zx * zx;\n                zy2 = zy * zy;\n                iter += 1;\n            }\n            if (iter < min)\n                min = iter;\n            if (iter > max)\n                max = iter;\n            hsv[(i * width) + j] = iter;\n        }\n    }\n\n    for (i = 0; i < height; i += 1) {\n        for (j = 0; j < width; j += 1) {\n            unsigned char *px = tex + (((i * width) + j) * 4);\n            hsv_to_rgba(hsv[(i * width) + j], min, max, px);\n        }\n    }\n\n    free(hsv);\n}\n\nvoid alloc_tex()\n{\n    if (tex == NULL || width != old_width || height != old_height) {\n        free(tex);\n        tex = malloc(height * width * 4 * sizeof(unsigned char));\n        memset(tex, 0, height * width * 4 * sizeof(unsigned char));\n        old_width = width;\n        old_height = height;\n    }\n}\n\nvoid set_texture()\n{\n    alloc_tex();\n    calc_mandel();\n\n    glEnable(GL_TEXTURE_2D);\n    glBindTexture(GL_TEXTURE_2D, texture);\n    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height,\n                 0, GL_RGBA, GL_UNSIGNED_BYTE, tex);\n\n    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n\n    render();\n}\n\nvoid mouseclick(int button, int state, int x, int y)\n{\n    if (state != GLUT_UP)\n        return;\n\n    cx += (x - width \/ 2) * scale;\n    cy -= (y - height \/ 2) * scale;\n\n    switch (button) {\n    case GLUT_LEFT_BUTTON:     \/* zoom in *\/\n        if (scale > fabs((double) x) * 1e-16\n            && scale > fabs((double) y) * 1e-16)\n            scale \/= 2;\n        break;\n    case GLUT_RIGHT_BUTTON:    \/* zoom out *\/\n        scale *= 2;\n        break;\n        \/* any other button recenters *\/\n    }\n    set_texture();\n}\n\n\nvoid resize(int w, int h)\n{\n    printf(\"resize %d %d\\n\", w, h);\n\n    width = w;\n    height = h;\n\n    glViewport(0, 0, w, h);\n    glOrtho(0, w, 0, h, -1, 1);\n\n    set_texture();\n}\n\nvoid init_gfx(int *c, char **v)\n{\n    glutInit(c, v);\n    glutInitDisplayMode(GLUT_RGBA);\n    glutInitWindowSize(640, 480);\n\n    gwin = glutCreateWindow(\"Mandelbrot\");\n    glutDisplayFunc(render);\n\n    glutKeyboardFunc(keypress);\n    glutMouseFunc(mouseclick);\n    glutReshapeFunc(resize);\n    glGenTextures(1, &texture);\n    set_texture();\n}\n\nint main(int c, char **v)\n{\n    tex = NULL;\n\n    init_gfx(&c, v);\n    printf\n        (\"keys:\\n\\tr: color rotation\\n\\tc: monochrome\\n\\ts: screen dump\\n\\t\"\n         \"<, >: decrease\/increase max iteration\\n\\tq: quit\\n\\tmouse buttons to zoom\\n\");\n\n    glutMainLoop();\n    return 0;\n}\n\n\/\/ local variables:\n\/\/ mode: C\n\/\/ c-file-style: \"k&r\"\n\/\/ c-basic-offset: 4\n\/\/ end:\n\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. The program creates a ppm file directly and features an infinitely zoomable OpenGL program with adjustable colors, max iteration, black and white, screen dump, etc. It is compatible with architectures that allow unaligned pointers and has been tested on x86-64. Despite potential compile warnings, the output will still be produced.","id":3511}
    {"lang_cluster":"C","source_code":"\n\/* using pointer arithmetic (because we can, I guess) *\/\nint arg[] = { 1,2,3,4,5 };\nint arg_length = sizeof(arg)\/sizeof(arg[0]);\nint *end = arg+arg_length;\nint sum = 0, prod = 1;\nint *p;\n\nfor (p = arg; p!=end; ++p) {\n   sum += *p;\n   prod *= *p;\n}\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":3512}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nint is_leap_year(unsigned year)\n{\n    return !(year & (year % 100 ? 3 : 15));\n}\n\nint main(void)\n{\n    const unsigned test_case[] = {\n        1900, 1994, 1996, 1997, 2000, 2024, 2025, 2026, 2100\n    };\n    const unsigned n = sizeof test_case \/ sizeof test_case[0];\n\n    for (unsigned i = 0; i != n; ++i) {\n        unsigned year = test_case[i];\n        printf(\"%u is %sa leap year.\\n\", year, is_leap_year(year) ? \"\" : \"not \");\n    }\n    return 0;\n}\n\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":3513}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl\/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \/\/ output\n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\n\");\n\n  return EXIT_SUCCESS;\n}\n","human_summarization":"implement the MD5 Message Digest Algorithm directly without using any built-in or external hashing libraries. The key functionality is to produce a correct message digest for an input string. The implementation also handles bit manipulation, unsigned integers, and works with little-endian data. The code includes verification strings and hashes from RFC 1321 for testing purposes. Note that MD5 has been broken and should not be used in applications requiring security.","id":3514}
    {"lang_cluster":"C","source_code":"\n\n#include<stdio.h>\n\nint main()\n{\n\tint police,sanitation,fire;\n\t\n\tprintf(\"Police     Sanitation         Fire\\n\");\n\tprintf(\"----------------------------------\");\n\t\n\tfor(police=2;police<=6;police+=2){\n\t\tfor(sanitation=1;sanitation<=7;sanitation++){\n\t\t\tfor(fire=1;fire<=7;fire++){\n\t\t\t\tif(police!=sanitation && sanitation!=fire && fire!=police && police+fire+sanitation==12){\n\t\t\t\t\tprintf(\"\\n%d\\t\\t%d\\t\\t%d\",police,sanitation,fire);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn 0;\n}\n\n\nPolice     Sanitation         Fire\n----------------------------------\n2               3               7\n2               4               6\n2               6               4\n2               7               3\n4               1               7\n4               2               6\n4               3               5\n4               5               3\n4               6               2\n4               7               1\n6               1               5\n6               2               4\n6               4               2\n6               5               1\n\n","human_summarization":"\"Generate all valid combinations of unique numbers between 1 and 7 (inclusive) for three departments - police, sanitation, and fire, such that the sum of these numbers is 12 and the police department number is even.\"","id":3515}
    {"lang_cluster":"C","source_code":"\n#include <stdlib.h>\t\/* exit(), free() *\/\n#include <stdio.h>\t\/* fputs(), perror(), printf() *\/\n#include <string.h>\n\nint\nmain()\n{\n\tsize_t len;\n\tchar src[] = \"Hello\";\n\tchar dst1[80], dst2[80];\n\tchar *dst3, *ref;\n\n\t\/*\n\t * Option 1. Use strcpy() from <string.h>.\n\t *\n\t * DANGER! strcpy() can overflow the destination buffer.\n\t * strcpy() is only safe if the source string is shorter than\n\t * the destination buffer. We know that \"Hello\" (6 characters\n\t * with the final '\\0') easily fits in dst1 (80 characters).\n\t *\/\n\tstrcpy(dst1, src);\n\n\t\/*\n\t * Option 2. Use strlen() and memcpy() from <string.h>, to copy\n\t * strlen(src) + 1 bytes including the final '\\0'.\n\t *\/\n\tlen = strlen(src);\n\tif (len >= sizeof dst2) {\n\t\tfputs(\"The buffer is too small!\\n\", stderr);\n\t\texit(1);\n\t}\n\tmemcpy(dst2, src, len + 1);\n\n\t\/*\n\t * Option 3. Use strdup() from <string.h>, to allocate a copy.\n\t *\/\n\tdst3 = strdup(src);\n\tif (dst3 == NULL) {\n\t\t\/* Failed to allocate memory! *\/\n\t\tperror(\"strdup\");\n\t\texit(1);\n\t}\n\n\t\/* Create another reference to the source string. *\/\n\tref = src;\n\n\t\/* Modify the source string, not its copies. *\/\n\tmemset(src, '-', 5);\n\n\tprintf(\" src: %s\\n\", src);   \/*  src: ----- *\/\n\tprintf(\"dst1: %s\\n\", dst1);  \/* dst1: Hello *\/\n\tprintf(\"dst2: %s\\n\", dst2);  \/* dst2: Hello *\/\n\tprintf(\"dst3: %s\\n\", dst3);  \/* dst3: Hello *\/\n\tprintf(\" ref: %s\\n\", ref);   \/*  ref: ----- *\/\n\n\t\/* Free memory from strdup(). *\/\n\tfree(dst3);\n\n\treturn 0;\n}\n\n#include <stdlib.h>\t\/* exit() *\/\n#include <stdio.h>\t\/* fputs(), printf() *\/\n#include <string.h>\n\nint\nmain()\n{\n\tchar src[] = \"Hello\";\n\tchar dst[80];\n\n\t\/* Use strlcpy() from <string.h>. *\/\n\tif (strlcpy(dst, src, sizeof dst) >= sizeof dst) {\n\t\tfputs(\"The buffer is too small!\\n\", stderr);\n\t\texit(1);\n\t}\n\n\tmemset(src, '-', 5);\n\tprintf(\"src: %s\\n\", src);  \/* src: ----- *\/\n\tprintf(\"dst: %s\\n\", dst);  \/* dst: Hello *\/\n\n\treturn 0;\n}\n\n\n#include <gadget\/gadget.h>\n\nLIB_GADGET_START\n\nMain\n   String v, w = \"this message is a message\";\n   \n   Let( v, \"Hello world!\");\n   Print \"v = %s\\nw = %s\\n\\n\", v,w;\n   \n   Get_fn_let( v, Upper(w) );\n   \n   Print \"v = %s\\nw = %s\\n\\n\", v,w;\n\n   Stack{\n       Store ( v, Str_tran_last( Upper(w), \"MESSAGE\", \"PROOF\" ) );\n   }Stack_off;\n   \n   Print \"v = %s\\nw = %s\\n\\n\", v,w;\n   \n   Free secure v, w;\n\nEnd\n\n\n","human_summarization":"\"Implements a function to copy a string's content, differentiating between copying the content and creating an additional reference to the string, using the Gadget library.\"","id":3516}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n\n\/* let us declare our functions; indeed here we need\n   really only M declaration, so that F can \"see\" it\n   and the compiler won't complain with a warning *\/\nint F(const int n);\nint M(const int n);\n\nint F(const int n)\n{\n  return (n == 0) ? 1 : n - M(F(n - 1));\n}\n\nint M(const int n)\n{\n  return (n == 0) ? 0 : n - F(M(n - 1));\n}\n\nint main(void)\n{\n  int i;\n  for (i = 0; i < 20; i++)\n    printf(\"%2d \", F(i));\n  printf(\"\\n\");\n  for (i = 0; i < 20; i++)\n    printf(\"%2d \", M(i));\n  printf(\"\\n\");\n  return EXIT_SUCCESS;\n}\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions are defined such that F(0) = 1, M(0) = 0, F(n) = n - M(F(n-1)) for n > 0, and M(n) = n - F(M(n-1)) for n > 0. The functions are declared explicitly to ensure proper usage.","id":3517}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n \nint main(){\n   char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };\n   int i;\n   time_t t;\n   srand((unsigned)time(&t));\n   \n   for(i=0;i<30;i++){\n\t\tprintf(\"%c\\n\", array[rand()%10]);\n   }\n   \n   return 0;\n}\n\n\na\ne\nf\nh\nb\nd\ng\na\nb\nf\na\ni\nb\nd\nd\ng\nj\na\nf\ne\na\ne\ng\ne\ni\nd\nj\na\nf\ne\na\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":3518}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <string.h>\n\ninline int ishex(int x)\n{\n\treturn\t(x >= '0' && x <= '9')\t||\n\t\t(x >= 'a' && x <= 'f')\t||\n\t\t(x >= 'A' && x <= 'F');\n}\n\nint decode(const char *s, char *dec)\n{\n\tchar *o;\n\tconst char *end = s + strlen(s);\n\tint c;\n\n\tfor (o = dec; s <= end; o++) {\n\t\tc = *s++;\n\t\tif (c == '+') c = ' ';\n\t\telse if (c == '%' && (\t!ishex(*s++)\t||\n\t\t\t\t\t!ishex(*s++)\t||\n\t\t\t\t\t!sscanf(s - 2, \"%2x\", &c)))\n\t\t\treturn -1;\n\n\t\tif (dec) *o = c;\n\t}\n\n\treturn o - dec;\n}\n\nint main()\n{\n\tconst char *url = \"http%3A%2F%2ffoo+bar%2fabcd\";\n\tchar out[strlen(url) + 1];\n\n\tprintf(\"length: %d\\n\", decode(url, 0));\n\tputs(decode(url, out) < 0 ? \"bad string\" : out);\n\n\treturn 0;\n}\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":3519}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nint bsearch (int *a, int n, int x) {\n    int i = 0, j = n - 1;\n    while (i <= j) {\n        int k = i + ((j - i) \/ 2);\n        if (a[k] == x) {\n            return k;\n        }\n        else if (a[k] < x) {\n            i = k + 1;\n        }\n        else {\n            j = k - 1;\n        }\n    }\n    return -1;\n}\n\nint bsearch_r (int *a, int x, int i, int j) {\n    if (j < i) {\n        return -1;\n    }\n    int k = i + ((j - i) \/ 2);\n    if (a[k] == x) {\n        return k;\n    }\n    else if (a[k] < x) {\n        return bsearch_r(a, x, k + 1, j);\n    }\n    else {\n        return bsearch_r(a, x, i, k - 1);\n    }\n}\n\nint main () {\n    int a[] = {-31, 0, 1, 2, 2, 4, 65, 83, 99, 782};\n    int n = sizeof a \/ sizeof a[0];\n    int x = 2;\n    int i = bsearch(a, n, x);\n    if (i >= 0)  \n      printf(\"%d is at index %d.\\n\", x, i);\n    else\n      printf(\"%d is not found.\\n\", x);\n    x = 5;\n    i = bsearch_r(a, x, 0, n - 1);\n    if (i >= 0)  \n      printf(\"%d is at index %d.\\n\", x, i);\n    else\n      printf(\"%d is not found.\\n\", x);\n    return 0;\n}\n\n\n","human_summarization":"The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It takes a sorted integer array, a starting point, an ending point, and a \"secret value\" as inputs. The algorithm can be either recursive or iterative and returns whether the number was in the array and its index if found. The code also includes variations of the binary search algorithm that return the leftmost or rightmost insertion point for the given value. It also handles potential overflow bugs.","id":3520}
    {"lang_cluster":"C","source_code":"\n\n#include <stdlib.h>\n#include <stdio.h>\n\nint main(int argc, char* argv[])\n{\n  int i;\n  (void) printf(\"This program is named %s.\\n\", argv[0]);\n  for (i = 1; i < argc; ++i)\n    (void) printf(\"the argument #%d is %s\\n\", i, argv[i]);\n  return EXIT_SUCCESS;\n}\n\n","human_summarization":"The code retrieves the list of command-line arguments provided to the program and prints them. It also takes into account the program name as an argument. The argument count and argument strings are conventionally named as argc and argv respectively. The code is also capable of handling systems that use Unicode or other multibyte character sets by using a type of _wchar* and multi-byte-character-set-aware versions of printf.","id":3521}
    {"lang_cluster":"C","source_code":"\nLibrary: GLUT\n#include <stdlib.h>\n#include <math.h>\n#include <GL\/glut.h>\n#include <GL\/gl.h>\n#include <sys\/time.h>\n\n#define length 5\n#define g 9.8\ndouble alpha, accl, omega = 0, E;\nstruct timeval tv;\n\ndouble elappsed() {\n\tstruct timeval now;\n\tgettimeofday(&now, 0);\n\tint ret = (now.tv_sec - tv.tv_sec) * 1000000\n\t\t+ now.tv_usec - tv.tv_usec;\n\ttv = now;\n\treturn ret \/ 1.e6;\n}\n\nvoid resize(int w, int h)\n{\n\tglViewport(0, 0, w, h);\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n\tglOrtho(0, w, h, 0, -1, 1);\n}\n\nvoid render()\n{\n\tdouble x = 320 + 300 * sin(alpha), y = 300 * cos(alpha);\n\tresize(640, 320);\n \tglClear(GL_COLOR_BUFFER_BIT);\n\n\tglBegin(GL_LINES);\n\tglVertex2d(320, 0);\n\tglVertex2d(x, y);\n\tglEnd();\n\tglFlush();\n\n\tdouble us = elappsed();\n\talpha += (omega + us * accl \/ 2) * us;\n\tomega += accl * us;\n\n\t\/* don't let precision error go out of hand *\/\n\tif (length * g * (1 - cos(alpha)) >= E) {\n\t\talpha = (alpha < 0 ? -1 : 1) * acos(1 - E \/ length \/ g);\n\t\tomega = 0;\n\t}\n\taccl = -g \/ length * sin(alpha);\n}\n\nvoid init_gfx(int *c, char **v)\n{\n\tglutInit(c, v);\n\tglutInitDisplayMode(GLUT_RGB);\n\tglutInitWindowSize(640, 320);\n\tglutIdleFunc(render);\n\tglutCreateWindow(\"Pendulum\");\n}\n\nint main(int c, char **v)\n{\n\talpha = 4 * atan2(1, 1) \/ 2.1;\n\tE = length * g * (1 - cos(alpha));\n\n\taccl = -g \/ length * sin(alpha);\n\tomega = 0;\n\n\tgettimeofday(&tv, 0);\n\tinit_gfx(&c, v);\n\tglutMainLoop();\n\treturn 0;\n}\n\n","human_summarization":"create and animate a simple physical model of a gravity pendulum.","id":3522}
    {"lang_cluster":"C","source_code":"\nLibrary: YAJL\nWorks with: YAJL version 2\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <yajl\/yajl_tree.h>\n#include <yajl\/yajl_gen.h>\n\nstatic void print_callback (void *ctx, const char *str, size_t len)\n{\n  FILE *f = (FILE *) ctx;\n  fwrite (str, 1, len, f);\n}\n\nstatic void check_status (yajl_gen_status status)\n{\n  if (status != yajl_gen_status_ok)\n    {\n      fprintf (stderr, \"yajl_gen_status was %d\\n\", (int) status);\n      exit (EXIT_FAILURE);\n    }\n}\n\nstatic void serialize_value (yajl_gen gen, yajl_val val, int parse_numbers)\n{\n  size_t i;\n\n  switch (val->type)\n    {\n    case yajl_t_string:\n      check_status (yajl_gen_string (gen,\n                                     (const unsigned char *) val->u.string,\n                                     strlen (val->u.string)));\n      break;\n    case yajl_t_number:\n      if (parse_numbers  &&  YAJL_IS_INTEGER (val))\n        check_status (yajl_gen_integer (gen, YAJL_GET_INTEGER (val)));\n      else if (parse_numbers  &&  YAJL_IS_DOUBLE (val))\n        check_status (yajl_gen_double (gen, YAJL_GET_DOUBLE (val)));\n      else\n        check_status (yajl_gen_number (gen, YAJL_GET_NUMBER (val),\n                                       strlen (YAJL_GET_NUMBER (val))));\n      break;\n    case yajl_t_object:\n      check_status (yajl_gen_map_open (gen));\n      for (i = 0  ;  i < val->u.object.len  ;  i++)\n        {\n          check_status (yajl_gen_string (gen,\n                                         (const unsigned char *) val->u.object.keys[i],\n                                         strlen (val->u.object.keys[i])));\n          serialize_value (gen, val->u.object.values[i], parse_numbers);\n        }\n      check_status (yajl_gen_map_close (gen));\n      break;\n    case yajl_t_array:\n      check_status (yajl_gen_array_open (gen));\n      for (i = 0  ;  i < val->u.array.len  ;  i++)\n        serialize_value (gen, val->u.array.values[i], parse_numbers);\n      check_status (yajl_gen_array_close (gen));\n      break;\n    case yajl_t_true:\n      check_status (yajl_gen_bool (gen, 1));\n      break;\n    case yajl_t_false:\n      check_status (yajl_gen_bool (gen, 0));\n      break;\n    case yajl_t_null:\n      check_status (yajl_gen_null (gen));\n      break;\n    default:\n      fprintf (stderr, \"unexpectedly got type %d\\n\", (int) val->type);\n      exit (EXIT_FAILURE);\n    }\n}\n\nstatic void print_tree (FILE *f, yajl_val tree, int parse_numbers)\n{\n  yajl_gen gen;\n\n  gen = yajl_gen_alloc (NULL);\n  if (! gen)\n    {\n      fprintf (stderr, \"yajl_gen_alloc failed\\n\");\n      exit (EXIT_FAILURE);\n    }\n\n  if (0 == yajl_gen_config (gen, yajl_gen_beautify, 1)  ||\n      0 == yajl_gen_config (gen, yajl_gen_validate_utf8, 1)  ||\n      0 == yajl_gen_config (gen, yajl_gen_print_callback, print_callback, f))\n    {\n      fprintf (stderr, \"yajl_gen_config failed\\n\");\n      exit (EXIT_FAILURE);\n    }\n\n  serialize_value (gen, tree, parse_numbers);\n  yajl_gen_free (gen);\n}\n\nint main (int argc, char **argv)\n{\n  char err_buf[200];\n  const char *json =\n    \"{\\\"pi\\\": 3.14, \\\"large number\\\": 123456789123456789123456789, \"\n    \"\\\"an array\\\": [-1, true, false, null, \\\"foo\\\"]}\";\n  yajl_val tree;\n\n  tree = yajl_tree_parse (json, err_buf, sizeof (err_buf));\n  if (! tree)\n    {\n      fprintf (stderr, \"parsing failed because: %s\\n\", err_buf);\n      return EXIT_FAILURE;\n    }\n\n  printf (\"Treating numbers as strings...\\n\");\n  print_tree (stdout, tree, 0);\n  printf (\"Parsing numbers to long long or double...\\n\");\n  print_tree (stdout, tree, 1);\n\n  yajl_tree_free (tree);\n\n  return EXIT_SUCCESS;\n}\n\n\n","human_summarization":"\"Code loads a JSON string into a data structure, creates a new data structure and serializes it into JSON using objects and arrays. It also reads a JSON snippet into YAJL's tree format, walks the tree and prints it back out, handling numbers in both unparsed string form and converted to long long or double.\"","id":3523}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <float.h>\n\ndouble pow_ (double x, int e) {\n    int i;\n    double r = 1;\n    for (i = 0; i < e; i++) {\n        r *= x;\n    }\n    return r;\n}\n\ndouble root (int n, double x) {\n    double d, r = 1;\n    if (!x) {\n        return 0;\n    }\n    if (n < 1 || (x < 0 && !(n&1))) {\n        return 0.0 \/ 0.0; \/* NaN *\/\n    }\n    do {\n        d = (x \/ pow_(r, n - 1) - r) \/ n;\n        r += d;\n    }\n    while (d >= DBL_EPSILON * 10 || d <= -DBL_EPSILON * 10);\n    return r;\n}\n\nint main () {\n    int n = 15;\n    double x = pow_(-3.14159, 15);\n    printf(\"root(%d, %g) = %g\\n\", n, x, root(n, x));\n    return 0;\n}\n\n","human_summarization":"implement the principal nth root of a positive real number A without using the math library.","id":3524}
    {"lang_cluster":"C","source_code":"\n\n#include<stdio.h>\n\nvoid leonardo(int a,int b,int step,int num){\n\t\n\tint i,temp;\n\t\n\tprintf(\"First 25 Leonardo numbers\u00a0: \\n\");\n\t\n\tfor(i=1;i<=num;i++){\n\t\tif(i==1)\n\t\t\tprintf(\" %d\",a);\n\t\telse if(i==2)\n\t\t\tprintf(\" %d\",b);\n\t\telse{\n\t\t\tprintf(\" %d\",a+b+step);\n\t\t\ttemp = a;\n\t\t\ta = b;\n\t\t\tb = temp+b+step;\n\t\t}\n\t}\n}\n\nint main()\n{\n\tint a,b,step;\n\t\n\tprintf(\"Enter first two Leonardo numbers and increment step\u00a0: \");\n\t\n\tscanf(\"%d%d%d\",&a,&b,&step);\n\t\n\tleonardo(a,b,step,25);\n\t\n\treturn 0;\n}\n\n\nEnter first two Leonardo numbers and increment step\u00a0: 1 1 1\nFirst 25 Leonardo numbers\u00a0:\n 1 1 3 5 9 15 25 41 67 109 177 287 465 753 1219 1973 3193 5167 8361 13529 21891 35421 57313 92735 150049\n\n\nEnter first two Leonardo numbers and increment step\u00a0: 0 1 0\nFirst 25 Leonardo numbers\u00a0:\n 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368\n\n","human_summarization":"generate the first 25 Leonardo numbers starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. It also provides an option to generate the Fibonacci series by setting 0 and 1 for L(0) and L(1), and 0 for the add number. The implementation adheres to the task requirements of specifying the first two terms and the step increment.","id":3525}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <ctype.h>\n#include <stdlib.h>\n#include <setjmp.h>\n#include <time.h>\n \njmp_buf ctx;\nconst char *msg;\n \nenum { OP_NONE = 0, OP_NUM, OP_ADD, OP_SUB, OP_MUL, OP_DIV };\n \ntypedef struct expr_t *expr, expr_t;\nstruct expr_t {\n\tint op, val, used;\n\texpr left, right;\n};\n \n#define N_DIGITS 4\nexpr_t digits[N_DIGITS];\n \nvoid gen_digits()\n{\n\tint i;\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].val = 1 + rand() % 9;\n}\n \n#define MAX_INPUT 64\nchar str[MAX_INPUT];\nint pos;\n \n#define POOL_SIZE 8\nexpr_t pool[POOL_SIZE];\nint pool_ptr;\n \nvoid reset()\n{\n\tint i;\n\tmsg = 0;\n\tpool_ptr = pos = 0;\n\tfor (i = 0; i < POOL_SIZE; i++) {\n\t\tpool[i].op = OP_NONE;\n\t\tpool[i].left = pool[i].right = 0;\n\t}\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tdigits[i].used = 0;\n}\n \n\/* longish jumpish back to input cycle *\/\nvoid bail(const char *s)\n{\n\tmsg = s;\n\tlongjmp(ctx, 1);\n}\n \nexpr new_expr()\n{\n\tif (pool_ptr < POOL_SIZE)\n\t\treturn pool + pool_ptr++;\n\treturn 0;\n}\n \n\/* check next input char *\/\nint next_tok()\n{\n\twhile (isspace(str[pos])) pos++;\n\treturn str[pos];\n}\n \n\/* move input pointer forward *\/\nint take()\n{\n\tif (str[pos] != '\\0') return ++pos;\n\treturn 0;\n}\n \n\/* BNF(ish)\nexpr = term { (\"+\")|(\"-\") term }\nterm = fact { (\"*\")|(\"\/\") expr }\nfact =\tnumber\n\t| '(' expr ')'\n*\/\n \nexpr get_fact();\nexpr get_term();\nexpr get_expr();\n \nexpr get_expr()\n{\n\tint c;\n\texpr l, r, ret;\n\tif (!(ret = get_term())) bail(\"Expected term\");\n\twhile ((c = next_tok()) == '+' || c == '-') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n\t\tif (!(r = get_term())) bail(\"Expected term\");\n \n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '+') ? OP_ADD : OP_SUB;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_term()\n{\n\tint c;\n\texpr l, r, ret;\n\tret = get_fact();\n\twhile((c = next_tok()) == '*' || c == '\/') {\n\t\tif (!take()) bail(\"Unexpected end of input\");\n \n\t\tr = get_fact();\n\t\tl = ret;\n\t\tret = new_expr();\n\t\tret->op = (c == '*') ? OP_MUL : OP_DIV;\n\t\tret->left = l;\n\t\tret->right = r;\n\t}\n\treturn ret;\n}\n \nexpr get_digit()\n{\n\tint i, c = next_tok();\n\texpr ret;\n\tif (c >= '0' && c <= '9') {\n\t\ttake();\n\t\tret = new_expr();\n\t\tret->op = OP_NUM;\n\t\tret->val = c - '0';\n\t\tfor (i = 0; i < N_DIGITS; i++)\n\t\t\tif (digits[i].val == ret->val && !digits[i].used) {\n\t\t\t\tdigits[i].used = 1;\n\t\t\t\treturn ret;\n\t\t\t}\n\t\tbail(\"Invalid digit\");\n\t}\n\treturn 0;\n}\n \nexpr get_fact()\n{\n\tint c;\n\texpr l = get_digit();\n\tif (l) return l;\n\tif ((c = next_tok()) == '(') {\n\t\ttake();\n\t\tl = get_expr();\n\t\tif (next_tok() != ')') bail(\"Unbalanced parens\");\n\t\ttake();\n\t\treturn l;\n\t}\n\treturn 0;\n}\n \nexpr parse()\n{\n\tint i;\n\texpr ret = get_expr();\n\tif (next_tok() != '\\0')\n\t\tbail(\"Trailing garbage\");\n\tfor (i = 0; i < N_DIGITS; i++)\n\t\tif (!digits[i].used)\n\t\t\tbail(\"Not all digits are used\");\n\treturn ret;\n}\n \ntypedef struct frac_t frac_t, *frac;\nstruct frac_t { int denom, num; };\n \nint gcd(int m, int n)\n{\n\tint t;\n\twhile (m) {\n\t\tt = m; m = n % m; n = t;\n\t}\n\treturn n;\n}\n \n\/* evaluate expression tree.  result in fraction form *\/\nvoid eval_tree(expr e, frac res)\n{\n\tfrac_t l, r;\n\tint t;\n\tif (e->op == OP_NUM) {\n\t\tres->num = e->val;\n\t\tres->denom = 1;\n\t\treturn;\n\t}\n \n\teval_tree(e->left, &l);\n\teval_tree(e->right, &r);\n \n\tswitch(e->op) {\n\tcase OP_ADD:\n\t\tres->num = l.num * r.denom + l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_SUB:\n\t\tres->num = l.num * r.denom - l.denom * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_MUL:\n\t\tres->num = l.num * r.num;\n\t\tres->denom = l.denom * r.denom;\n\t\tbreak;\n\tcase OP_DIV:\n\t\tres->num = l.num * r.denom;\n\t\tres->denom = l.denom * r.num;\n\t\tbreak;\n\t}\n\tif ((t = gcd(res->denom, res->num))) {\n\t\tres->denom \/= t;\n\t\tres->num \/= t;\n\t}\n}\n \nvoid get_input()\n{\n\tint i;\nreinput:\n\treset();\n\tprintf(\"\\nAvailable digits are:\");\n\tfor (i = 0; i < N_DIGITS; i++) \n\t\tprintf(\" %d\", digits[i].val);\n\tprintf(\". Type an expression and I'll check it for you, or make new numbers.\\n\"\n\t\t\"Your choice? [Expr\/n\/q] \");\n \n\twhile (1) {\n\t\tfor (i = 0; i < MAX_INPUT; i++) str[i] = '\\n';\n\t\tfgets(str, MAX_INPUT, stdin);\n\t\tif (*str == '\\0') goto reinput;\n\t\tif (str[MAX_INPUT - 1] != '\\n')\n\t\t\tbail(\"string too long\");\n \n\t\tfor (i = 0; i < MAX_INPUT; i++)\n\t\t\tif (str[i] == '\\n') str[i] = '\\0';\n\t\tif (str[0] == 'q') {\n\t\t\tprintf(\"Bye\\n\");\n\t\t\texit(0);\n\t\t}\n\t\tif (str[0] == 'n') {\n\t\t\tgen_digits();\n\t\t\tgoto reinput;\n\t\t}\n\t\treturn;\n\t}\n}\n \nint main()\n{\n\tfrac_t f;\n\tsrand(time(0));\n \n\tgen_digits();\n\twhile(1) {\n\t\tget_input();\n\t\tsetjmp(ctx); \/* if parse error, jump back here with err msg set *\/\n\t\tif (msg) {\n\t\t\t\/* after error jump; announce, reset, redo *\/\n\t\t\tprintf(\"%s at '%.*s'\\n\", msg, pos, str);\n\t\t\tcontinue;\n\t\t}\n \n\t\teval_tree(parse(), &f);\n \n\t\tif (f.denom == 0) bail(\"Divide by zero\");\n\t\tif (f.denom == 1 && f.num == 24)\n\t\t\tprintf(\"You got 24.  Very good.\\n\");\n\t\telse {\n\t\t\tif (f.denom == 1)\n\t\t\t\tprintf(\"Eval to: %d, \", f.num);\n\t\t\telse\n\t\t\t\tprintf(\"Eval to: %d\/%d, \", f.num, f.denom);\n\t\t\tprintf(\"no good.  Try again.\\n\");\n\t\t}\n\t}\n\treturn 0;\n}\n\n\n","human_summarization":"The code is a game program that randomly selects and displays four digits (1-9). It prompts the player to create an arithmetic expression using these digits exactly once. The expression should evaluate to 24 using addition, subtraction, multiplication, and division. The code checks and evaluates the player's input expression. It uses either floating point or rational arithmetic for division to maintain remainders. It allows brackets in infix expressions but does not allow forming multi-digit numbers from the given digits. The code does not generate the expression or check its feasibility. It may use any type of expression evaluator, including an RPN evaluator.","id":3526}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct stream_t stream_t, *stream;\nstruct stream_t {\n\t\/* get function is supposed to return a byte value (0-255),\n\t\tor -1 to signify end of input *\/\n\tint (*get)(stream);\n\t\/* put function does output, one byte at a time *\/\n\tint (*put)(stream, int);\n};\n\n\/* next two structs inherit from stream_t *\/\ntypedef struct {\n\tint (*get)(stream);\n\tint (*put)(stream, int);\n\tchar *string;\n\tint pos;\n} string_stream;\n\ntypedef struct {\n\tint (*get)(stream);\n\tint (*put)(stream, int);\n\tFILE *fp;\n} file_stream;\n\n\/* methods for above streams *\/\nint sget(stream in)\n{\n\tint c;\n\tstring_stream* s = (string_stream*) in;\n\tc = (unsigned char)(s->string[s->pos]);\n\tif (c == '\\0') return -1;\n\ts->pos++;\n\treturn c;\n}\n\nint sput(stream out, int c)\n{\n\tstring_stream* s = (string_stream*) out;\n\ts->string[s->pos++] = (c == -1) ? '\\0' : c;\n\tif (c == -1) s->pos = 0;\n\treturn 0;\n}\n\nint file_put(stream out, int c)\n{\n\tfile_stream *f = (file_stream*) out;\n\treturn fputc(c, f->fp);\n}\n\n\/* helper function *\/\nvoid output(stream out, unsigned char* buf, int len)\n{\n\tint i;\n\tout->put(out, 128 + len);\n\tfor (i = 0; i < len; i++)\n\t\tout->put(out, buf[i]);\n}\n\n\/* Specification: encoded stream are unsigned bytes consisting of sequences.\n * First byte of each sequence is the length, followed by a number of bytes.\n * If length <=128, the next byte is to be repeated length times;\n * If length > 128, the next (length - 128) bytes are not repeated.\n * this is to improve efficiency for long non-repeating sequences.\n * This scheme can encode arbitrary byte values efficiently.\n * c.f. Adobe PDF spec RLE stream encoding (not exactly the same)\n *\/\nvoid encode(stream in, stream out)\n{\n\tunsigned char buf[256];\n\tint len = 0, repeat = 0, end = 0, c;\n\tint (*get)(stream) = in->get;\n\tint (*put)(stream, int) = out->put;\n\n\twhile (!end) {\n\t\tend = ((c = get(in)) == -1);\n\t\tif (!end) {\n\t\t\tbuf[len++] = c;\n\t\t\tif (len <= 1) continue;\n\t\t}\n\n\t\tif (repeat) {\n\t\t\tif (buf[len - 1] != buf[len - 2])\n\t\t\t\trepeat = 0;\n\t\t\tif (!repeat || len == 129 || end) {\n\t\t\t\t\/* write out repeating bytes *\/\n\t\t\t\tput(out, end ? len : len - 1);\n\t\t\t\tput(out, buf[0]);\n\t\t\t\tbuf[0] = buf[len - 1];\n\t\t\t\tlen = 1;\n\t\t\t}\n\t\t} else {\n\t\t\tif (buf[len - 1] == buf[len - 2]) {\n\t\t\t\trepeat = 1;\n\t\t\t\tif (len > 2) {\n\t\t\t\t\toutput(out, buf, len - 2);\n\t\t\t\t\tbuf[0] = buf[1] = buf[len - 1];\n\t\t\t\t\tlen = 2;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (len == 128 || end) {\n\t\t\t\toutput(out, buf, len);\n\t\t\t\tlen = 0;\n\t\t\t\trepeat = 0;\n\t\t\t}\n\t\t}\n\t}\n\tput(out, -1);\n}\n\nvoid decode(stream in, stream out)\n{\n\tint c, i, cnt;\n\twhile (1) {\n\t\tc = in->get(in);\n\t\tif (c == -1) return;\n\t\tif (c > 128) {\n\t\t\tcnt = c - 128;\n\t\t\tfor (i = 0; i < cnt; i++)\n\t\t\t\tout->put(out, in->get(in));\n\t\t} else {\n\t\t\tcnt = c;\n\t\t\tc = in->get(in);\n\t\t\tfor (i = 0; i < cnt; i++)\n\t\t\t\tout->put(out, c);\n\t\t}\n\t}\n}\n\nint main()\n{\n\tchar buf[256];\n\tstring_stream str_in = { sget, 0,\n\t\t\"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\", 0};\n\tstring_stream str_out = { sget, sput, buf, 0 };\n\tfile_stream file = { 0, file_put, stdout };\n\n\t\/* encode from str_in to str_out *\/\n\tencode((stream)&str_in, (stream)&str_out);\n\n\t\/* decode from str_out to file (stdout) *\/\n\tdecode((stream)&str_out, (stream)&file);\n\n\treturn 0;\n}\n\n\n","human_summarization":"implement a run-length encoding and decoding system. It compresses strings of uppercase characters by storing the length of consecutive identical characters. The system can recreate the original string from the compressed version. It also includes an encoder for handling byte streams of any length and value with efficiency, demonstrating object-oriented programming and polymorphism with structs.","id":3527}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nchar *sconcat(const char *s1, const char *s2)\n{\n  char *s0 = malloc(strlen(s1)+strlen(s2)+1);\n  strcpy(s0, s1);\n  strcat(s0, s2);\n  return s0;\n}\n\nint main()\n{\n   const char *s = \"hello\";\n   char *s2;\n   \n   printf(\"%s literal\\n\", s);\n   \/* or *\/\n   printf(\"%s%s\\n\", s, \" literal\");\n   \n   s2 = sconcat(s, \" literal\");\n   puts(s2);\n   free(s2);\n}\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":3528}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <ctype.h>\n \nchar rfc3986[256] = {0};\nchar html5[256] = {0};\n\n\/* caller responsible for memory *\/\nvoid encode(const char *s, char *enc, char *tb)\n{\n\tfor (; *s; s++) {\n\t\tif (tb[*s]) sprintf(enc, \"%c\", tb[*s]);\n\t\telse        sprintf(enc, \"%%%02X\", *s);\n\t\twhile (*++enc);\n\t}\n}\n \nint main()\n{\n\tconst char url[] = \"http:\/\/foo bar\/\";\n\tchar enc[(strlen(url) * 3) + 1];\n \n\tint i;\n\tfor (i = 0; i < 256; i++) {\n\t\trfc3986[i] = isalnum(i)||i == '~'||i == '-'||i == '.'||i == '_'\n\t\t\t? i : 0;\n\t\thtml5[i] = isalnum(i)||i == '*'||i == '-'||i == '.'||i == '_'\n\t\t\t? i : (i == ' ') ? '+' : 0;\n\t}\n \n\tencode(url, enc, rfc3986);\n\tputs(enc);\n \n\treturn 0;\n}\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":3529}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define COUNTOF(a) (sizeof(a)\/sizeof(a[0]))\n\nvoid fatal(const char* message) {\n    fprintf(stderr, \"%s\\n\", message);\n    exit(1);\n}\n\nvoid* xmalloc(size_t n) {\n    void* ptr = malloc(n);\n    if (ptr == NULL)\n        fatal(\"Out of memory\");\n    return ptr;\n}\n\nint icompare(const void* p1, const void* p2) {\n    const int* ip1 = p1;\n    const int* ip2 = p2;\n    return (*ip1 < *ip2) ? -1 : ((*ip1 > *ip2) ? 1 : 0);\n}\n\nsize_t unique(int* array, size_t len) {\n    size_t out_index = 0;\n    int prev;\n    for (size_t i = 0; i < len; ++i) {\n        if (i == 0 || prev != array[i])\n            array[out_index++] = array[i];\n        prev = array[i];\n    }\n    return out_index;\n}\n\nint* common_sorted_list(const int** arrays, const size_t* lengths, size_t count, size_t* size) {\n    size_t len = 0;\n    for (size_t i = 0; i < count; ++i)\n        len += lengths[i];\n    int* array = xmalloc(len * sizeof(int));\n    for (size_t i = 0, offset = 0; i < count; ++i) {\n        memcpy(array + offset, arrays[i], lengths[i] * sizeof(int));\n        offset += lengths[i];\n    }\n    qsort(array, len, sizeof(int), icompare);\n    *size = unique(array, len);\n    return array;\n}\n\nvoid print(const int* array, size_t len) {\n    printf(\"[\");\n    for (size_t i = 0; i < len; ++i) {\n        if (i > 0)\n            printf(\", \");\n        printf(\"%d\", array[i]);\n    }\n    printf(\"]\\n\");\n}\n\nint main() {\n    const int a[] = {5, 1, 3, 8, 9, 4, 8, 7};\n    const int b[] = {3, 5, 9, 8, 4};\n    const int c[] = {1, 3, 7, 9};\n    size_t len = 0;\n    const int* arrays[] = {a, b, c};\n    size_t lengths[] = {COUNTOF(a), COUNTOF(b), COUNTOF(c)};\n    int* sorted = common_sorted_list(arrays, lengths, COUNTOF(arrays), &len);\n    print(sorted, len);\n    free(sorted);\n    return 0;\n}\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":3530}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n\nstruct item { double w, v; const char *name; } items[] = {\n\t{ 3.8, 36, \"beef\" },\n\t{ 5.4, 43, \"pork\" },\n\t{ 3.6, 90, \"ham\" },\n\t{ 2.4, 45, \"greaves\" },\n\t{ 4.0, 30, \"flitch\" },\n\t{ 2.5, 56, \"brawn\" },\n\t{ 3.7, 67, \"welt\" },\n\t{ 3.0, 95, \"salami\" },\n\t{ 5.9, 98, \"sausage\" },\n};\n\nint item_cmp(const void *aa, const void *bb)\n{\n\tconst struct item *a = aa, *b = bb;\n\tdouble ua = a->v \/ a->w, ub = b->v \/ b->w;\n\treturn ua < ub ? -1 : ua > ub;\n}\n\nint main()\n{\n\tstruct item *it;\n\tdouble space = 15;\n\n\tqsort(items, 9, sizeof(struct item), item_cmp);\n\tfor (it = items + 9; it---items && space > 0; space -= it->w)\n\t\tif (space >= it->w)\n\t\t\tprintf(\"take all %s\\n\", it->name);\n\t\telse\n\t\t\tprintf(\"take %gkg of %g kg of %s\\n\",\n\t\t\t\tspace, it->w, it->name);\n\n\treturn 0;\n}\noutputtake all salami\ntake all ham\ntake all brawn\ntake all greaves\ntake 3.5kg of 3.7 kg of welt\n\n","human_summarization":"determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.","id":3531}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <time.h>\n\nchar *sortedWord(const char *word, char *wbuf)\n{\n    char *p1, *p2, *endwrd;\n    char t;\n    int swaps;\n\n    strcpy(wbuf, word);\n    endwrd = wbuf+strlen(wbuf);\n    do {\n       swaps = 0;\n       p1 = wbuf; p2 = endwrd-1;\n       while (p1<p2) {\n          if (*p2 > *p1) {\n             t = *p2; *p2 = *p1; *p1 = t;\n             swaps = 1;\n          }\n          p1++; p2--;\n       }\n       p1 = wbuf; p2 = p1+1;\n       while(p2 < endwrd) {\n           if (*p2 > *p1) {\n             t = *p2; *p2 = *p1; *p1 = t;\n             swaps = 1;\n           }\n           p1++; p2++;\n       }\n    } while (swaps);\n    return wbuf;\n}\n\nstatic\nshort cxmap[] = {\n    0x06, 0x1f, 0x4d, 0x0c, 0x5c, 0x28, 0x5d, 0x0e, 0x09, 0x33, 0x31, 0x56,\n    0x52, 0x19, 0x29, 0x53, 0x32, 0x48, 0x35, 0x55, 0x5e, 0x14, 0x27, 0x24,\n    0x02, 0x3e, 0x18, 0x4a, 0x3f, 0x4c, 0x45, 0x30, 0x08, 0x2c, 0x1a, 0x03,\n    0x0b, 0x0d, 0x4f, 0x07, 0x20, 0x1d, 0x51, 0x3b, 0x11, 0x58, 0x00, 0x49,\n    0x15, 0x2d, 0x41, 0x17, 0x5f, 0x39, 0x16, 0x42, 0x37, 0x22, 0x1c, 0x0f,\n    0x43, 0x5b, 0x46, 0x4b, 0x0a, 0x26, 0x2e, 0x40, 0x12, 0x21, 0x3c, 0x36,\n    0x38, 0x1e, 0x01, 0x1b, 0x05, 0x4e, 0x44, 0x3d, 0x04, 0x10, 0x5a, 0x2a,\n    0x23, 0x34, 0x25, 0x2f, 0x2b, 0x50, 0x3a, 0x54, 0x47, 0x59, 0x13, 0x57,\n   };\n#define CXMAP_SIZE (sizeof(cxmap)\/sizeof(short))\n\n\nint Str_Hash( const char *key, int ix_max )\n{\n   const char *cp;\n   short mash;\n   int  hash = 33501551;\n   for (cp = key; *cp; cp++) {\n      mash = cxmap[*cp % CXMAP_SIZE];\n      hash = (hash >>4) ^ 0x5C5CF5C ^ ((hash<<1) + (mash<<5));\n      hash &= 0x3FFFFFFF;\n      }\n   return  hash % ix_max;\n}\n\ntypedef struct sDictWord  *DictWord;\nstruct sDictWord {\n    const char *word;\n    DictWord next;\n};\n\ntypedef struct sHashEntry *HashEntry;\nstruct sHashEntry {\n    const char *key;\n    HashEntry next;\n    DictWord  words;\n    HashEntry link;\n    short wordCount;\n};\n\n#define HT_SIZE 8192\n\nHashEntry hashTable[HT_SIZE];\n\nHashEntry mostPerms = NULL;\n\nint buildAnagrams( FILE *fin )\n{\n    char buffer[40];\n    char bufr2[40];\n    char *hkey;\n    int hix;\n    HashEntry he, *hep;\n    DictWord  we;\n    int  maxPC = 2;\n    int numWords = 0;\n    \n    while ( fgets(buffer, 40, fin)) {\n        for(hkey = buffer; *hkey && (*hkey!='\\n'); hkey++);\n        *hkey = 0;\n        hkey = sortedWord(buffer, bufr2);\n        hix = Str_Hash(hkey, HT_SIZE);\n        he = hashTable[hix]; hep = &hashTable[hix];\n        while( he && strcmp(he->key , hkey) ) {\n            hep = &he->next;\n            he = he->next;\n        }\n        if ( ! he ) {\n            he = malloc(sizeof(struct sHashEntry));\n            he->next = NULL;\n            he->key = strdup(hkey);\n            he->wordCount = 0;\n            he->words = NULL;\n            he->link = NULL;\n            *hep = he;\n        }\n        we = malloc(sizeof(struct sDictWord));\n        we->word = strdup(buffer);\n        we->next = he->words;\n        he->words = we;\n        he->wordCount++;\n        if ( maxPC < he->wordCount) {\n            maxPC = he->wordCount;\n            mostPerms = he;\n            he->link = NULL;\n        }\n        else if (maxPC == he->wordCount) {\n            he->link = mostPerms;\n            mostPerms = he;\n        }\n         \n        numWords++;\n    }\n    printf(\"%d words in dictionary max ana=%d\\n\", numWords, maxPC);\n    return maxPC;\n}\n\n\nint main( ) \n{\n    HashEntry he;\n    DictWord  we;\n    FILE *f1;\n    \n    f1 = fopen(\"unixdict.txt\",\"r\");\n    buildAnagrams(f1);\n    fclose(f1);\n    \n    f1 = fopen(\"anaout.txt\",\"w\");\n\/\/    f1 = stdout;\n\n    for (he = mostPerms; he; he = he->link) {\n        fprintf(f1,\"%d:\", he->wordCount);\n        for(we = he->words; we; we = we->next) {\n            fprintf(f1,\"%s, \", we->word);\n        }\n        fprintf(f1, \"\\n\");\n    }\n\n    fclose(f1);\n    return 0;\n}\n\n\n","human_summarization":"Find the largest sets of anagrams using the word list from a given URL.","id":3532}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n\nint main()\n{\n\tint i, j, dim, d;\n\tint depth = 3;\n\n\tfor (i = 0, dim = 1; i < depth; i++, dim *= 3);\n\n\tfor (i = 0; i < dim; i++) {\n\t\tfor (j = 0; j < dim; j++) {\n\t\t\tfor (d = dim \/ 3; d; d \/= 3)\n\t\t\t\tif ((i % (d * 3)) \/ d == 1 && (j % (d * 3)) \/ d == 1)\n\t\t\t\t\tbreak;\n\t\t\tprintf(d ? \"  \" : \"##\");\n\t\t}\n\t\tprintf(\"\\n\");\n\t}\n\n\treturn 0;\n}\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct sCarpet {\n    int dim;      \/\/ dimension\n    char *data;   \/\/ character data\n    char **rows;  \/\/ pointers to data rows\n} *Carpet;\n\n\/* Clones a tile into larger carpet, or blank if center *\/\nvoid TileCarpet( Carpet d, int r, int c, Carpet tile )\n{\n    int y0 = tile->dim*r;\n    int x0 = tile->dim*c;\n    int k,m;\n\n    if ((r==1) && (c==1)) {\n        for(k=0; k < tile->dim; k++) {\n           for (m=0; m < tile->dim; m++) {\n               d->rows[y0+k][x0+m] = ' ';\n           }\n        }\n    }\n    else {\n        for(k=0; k < tile->dim; k++) {\n           for (m=0; m < tile->dim; m++) {\n               d->rows[y0+k][x0+m] = tile->rows[k][m];\n           }\n        }\n    }\n}\n\n\/* define a 1x1 starting carpet *\/\nstatic char s1[]= \"#\";\nstatic char *r1[] = {s1};\nstatic struct sCarpet single = { 1, s1, r1};\n\nCarpet Sierpinski( int n )\n{\n   Carpet carpet;\n   Carpet subCarpet;\n   int row,col, rb;\n   int spc_rqrd;\n\n   subCarpet = (n > 1) ? Sierpinski(n-1) : &single;\n\n   carpet = malloc(sizeof(struct sCarpet));\n   carpet->dim = 3*subCarpet->dim;\n   spc_rqrd = (2*subCarpet->dim) * (carpet->dim);\n   carpet->data = malloc(spc_rqrd*sizeof(char));\n   carpet->rows = malloc( carpet->dim*sizeof(char *));\n   for (row=0; row<subCarpet->dim; row++) {\n       carpet->rows[row] = carpet->data + row*carpet->dim;\n       rb = row+subCarpet->dim;\n       carpet->rows[rb] = carpet->data + rb*carpet->dim;\n       rb = row+2*subCarpet->dim;\n       carpet->rows[rb] = carpet->data + row*carpet->dim;\n   }\n \n    for (col=0; col < 3; col++) {\n      \/* 2 rows of tiles to copy - third group points to same data a first *\/\n      for (row=0; row < 2; row++)\n         TileCarpet( carpet, row, col, subCarpet );\n    }\n    if (subCarpet != &single ) {\n       free(subCarpet->rows);\n       free(subCarpet->data);\n       free(subCarpet);\n    }\n\n    return carpet;\n}\n\nvoid CarpetPrint( FILE *fout, Carpet carp)\n{\n    char obuf[730];\n    int row;\n    for (row=0; row < carp->dim; row++) {\n       strncpy(obuf, carp->rows[row], carp->dim);\n       fprintf(fout, \"%s\\n\", obuf);\n    }\n    fprintf(fout,\"\\n\");\n}\n\nint main(int argc, char *argv[])\n{\n\/\/    FILE *f = fopen(\"sierp.txt\",\"w\");\n    CarpetPrint(stdout, Sierpinski(3));\n\/\/    fclose(f);\n    return 0;\n}\n\n\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct _PartialGrid{\n        char** base;\n        int xbegin, xend, ybegin, yend; \/\/ yend strictly not used\n} PartialGrid;\n\nvoid sierpinski_hollow(PartialGrid G){\n        int len = G.xend - G.xbegin+1;\n        int unit = len\/3;\n        for(int i = G.xbegin+unit; i <G.xbegin+2*unit;i++){\n        for(int j = G.ybegin+unit; j <G.ybegin+2*unit;j++){\n                G.base[j][i] = ' ';\n        }}  \n}\n\nvoid sierpinski(PartialGrid G, int iterations){\n        if(iterations==0)\n                return;\n        if((iterations)==1){\n                sierpinski_hollow(G);\n                sierpinski(G,0);\n        }   \n        sierpinski_hollow(G);\n        for(int i=0;i<3;i++){\n                for(int j=0;j<3;j++){\n                        int length = G.xend-G.xbegin+1;\n                        int unit = length\/3;\n                        PartialGrid q = {G.base, G.xbegin + i*unit, G.xbegin+(i+1)*unit-1, \n                                G.ybegin+j*unit, G.ybegin+(j+1)*unit-1};\n                        sierpinski(q, iterations-1);\n                }   \n        }   \n}\n\nint intpow(int base, int expo){\n        if(expo==0){\n                return 1;\n        }   \n        return base*intpow(base,expo-1);\n}\n\nint allocate_grid(char*** g, int n, const char sep){\n        int size = intpow(3,n+1);\n        *g = (char**)calloc(size, sizeof(char*));\n        if(*g==NULL)\n                return -1;\n\n        for(int i = 0; i < size; ++i){\n                (*g)[i] = (char*)calloc(size, sizeof(char));\n                if((*g)[i] == NULL)\n                        return -1; \n                for(int j = 0; j < size; j++){\n                        (*g)[i][j] = sep;\n                }\n        }\n\n        return size;\n}\n\nvoid print_grid(char** b, int size){\n        for(int i = 0; i < size; i++){\n                printf(\"%s\\n\",b[i]);\n        }\n}\n\nint main(){\n        int n = 3;\n\n        char** basegrid;\n        int size = allocate_grid(&basegrid, n, '#');\n        if(size == -1)\n                return 1; \/\/bad alloc\n        PartialGrid b = {basegrid, 0, size-1, 0, size-1};\n        sierpinski(b, n);\n        print_grid(basegrid, size);\n        free(basegrid);\n\n        return 0;\n}\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order. The carpet is constructed based on the placement of whitespace and non-whitespace characters. The pixel is blank if any matching pair of digits in base 3 coordinates of a point are (1, 1). The code also includes a recursive version of the task.","id":3533}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BYTES 256\n\nstruct huffcode {\n  int nbits;\n  int code;\n};\ntypedef struct huffcode huffcode_t;\n\nstruct huffheap {\n  int *h;\n  int n, s, cs;\n  long *f;\n};\ntypedef struct huffheap heap_t;\n\n\/* heap handling funcs *\/\nstatic heap_t *_heap_create(int s, long *f)\n{\n  heap_t *h;\n  h = malloc(sizeof(heap_t));\n  h->h = malloc(sizeof(int)*s);\n  h->s = h->cs = s;\n  h->n = 0;\n  h->f = f;\n  return h;\n}\n\nstatic void _heap_destroy(heap_t *heap)\n{\n  free(heap->h);\n  free(heap);\n}\n\n#define swap_(I,J) do { int t_; t_ = a[(I)];\t\\\n      a[(I)] = a[(J)]; a[(J)] = t_; } while(0)\nstatic void _heap_sort(heap_t *heap)\n{\n  int i=1, j=2; \/* gnome sort *\/\n  int *a = heap->h;\n\n  while(i < heap->n) { \/* smaller values are kept at the end *\/\n    if ( heap->f[a[i-1]] >= heap->f[a[i]] ) {\n      i = j; j++;\n    } else {\n      swap_(i-1, i);\n      i--;\n      i = (i==0) ? j++ : i;\n    }\n  }\n}\n#undef swap_\n\nstatic void _heap_add(heap_t *heap, int c)\n{\n  if ( (heap->n + 1) > heap->s ) {\n    heap->h = realloc(heap->h, heap->s + heap->cs);\n    heap->s += heap->cs;\n  }\n  heap->h[heap->n] = c;\n  heap->n++;\n  _heap_sort(heap);\n}\n\nstatic int _heap_remove(heap_t *heap)\n{\n  if ( heap->n > 0 ) {\n    heap->n--;\n    return heap->h[heap->n];\n  }\n  return -1;\n}\n\n\/* huffmann code generator *\/\nhuffcode_t **create_huffman_codes(long *freqs)\n{\n  huffcode_t **codes;\n  heap_t *heap;\n  long efreqs[BYTES*2];\n  int preds[BYTES*2];\n  int i, extf=BYTES;\n  int r1, r2;\n\n  memcpy(efreqs, freqs, sizeof(long)*BYTES);\n  memset(&efreqs[BYTES], 0, sizeof(long)*BYTES);\n\n  heap = _heap_create(BYTES*2, efreqs);\n  if ( heap == NULL ) return NULL;\n\n  for(i=0; i < BYTES; i++) if ( efreqs[i] > 0 ) _heap_add(heap, i);\n\n  while( heap->n > 1 )\n  {\n    r1 = _heap_remove(heap);\n    r2 = _heap_remove(heap);\n    efreqs[extf] = efreqs[r1] + efreqs[r2];\n    _heap_add(heap, extf);\n    preds[r1] = extf;\n    preds[r2] = -extf;\n    extf++;\n  }\n  r1 = _heap_remove(heap);\n  preds[r1] = r1;\n  _heap_destroy(heap);\n\n  codes = malloc(sizeof(huffcode_t *)*BYTES);\n\n  int bc, bn, ix;\n  for(i=0; i < BYTES; i++) {\n    bc=0; bn=0;\n    if ( efreqs[i] == 0 ) { codes[i] = NULL; continue; }\n    ix = i;\n    while( abs(preds[ix]) != ix ) {\n      bc |= ((preds[ix] >= 0) ? 1 : 0 ) << bn;\n      ix = abs(preds[ix]);\n      bn++;\n    }\n    codes[i] = malloc(sizeof(huffcode_t));\n    codes[i]->nbits = bn;\n    codes[i]->code = bc;\n  }\n  return codes;\n}\n\nvoid free_huffman_codes(huffcode_t **c)\n{\n  int i;\n\n  for(i=0; i < BYTES; i++) free(c[i]);\n  free(c);\n}\n\n#define MAXBITSPERCODE 100\n\nvoid inttobits(int c, int n, char *s)\n{\n  s[n] = 0;\n  while(n > 0) {\n    s[n-1] = (c%2) + '0';\n    c >>= 1; n--;\n  }\n}\n\nconst char *test = \"this is an example for huffman encoding\";\n\nint main()\n{\n  huffcode_t **r;\n  int i;\n  char strbit[MAXBITSPERCODE];\n  const char *p;\n  long freqs[BYTES];\n\n  memset(freqs, 0, sizeof freqs);\n\n  p = test;\n  while(*p != '\\0') freqs[*p++]++;\n\n  r = create_huffman_codes(freqs);\n\n  for(i=0; i < BYTES; i++) {\n    if ( r[i] != NULL ) {\n      inttobits(r[i]->code, r[i]->nbits, strbit);\n      printf(\"%c (%d) %s\\n\", i, r[i]->code, strbit);\n    }\n  }\n\n  free_huffman_codes(r);\n\n  return 0;\n}\n\n\n#include <stdio.h>\n#include <string.h>\n\ntypedef struct node_t {\n\tstruct node_t *left, *right;\n\tint freq;\n\tchar c;\n} *node;\n\nstruct node_t pool[256] = {{0}};\nnode qqq[255], *q = qqq - 1;\nint n_nodes = 0, qend = 1;\nchar *code[128] = {0}, buf[1024];\n\nnode new_node(int freq, char c, node a, node b)\n{\n\tnode n = pool + n_nodes++;\n\tif (freq) n->c = c, n->freq = freq;\n\telse {\n\t\tn->left = a, n->right = b;\n\t\tn->freq = a->freq + b->freq;\n\t}\n\treturn n;\n}\n\n\/* priority queue *\/\nvoid qinsert(node n)\n{\n\tint j, i = qend++;\n\twhile ((j = i \/ 2)) {\n\t\tif (q[j]->freq <= n->freq) break;\n\t\tq[i] = q[j], i = j;\n\t}\n\tq[i] = n;\n}\n\nnode qremove()\n{\n\tint i, l;\n\tnode n = q[i = 1];\n\n\tif (qend < 2) return 0;\n\tqend--;\n\twhile ((l = i * 2) < qend) {\n\t\tif (l + 1 < qend && q[l + 1]->freq < q[l]->freq) l++;\n\t\tq[i] = q[l], i = l;\n\t}\n\tq[i] = q[qend];\n\treturn n;\n}\n\n\/* walk the tree and put 0s and 1s *\/\nvoid build_code(node n, char *s, int len)\n{\n\tstatic char *out = buf;\n\tif (n->c) {\n\t\ts[len] = 0;\n\t\tstrcpy(out, s);\n\t\tcode[n->c] = out;\n\t\tout += len + 1;\n\t\treturn;\n\t}\n\n\ts[len] = '0'; build_code(n->left,  s, len + 1);\n\ts[len] = '1'; build_code(n->right, s, len + 1);\n}\n\nvoid init(const char *s)\n{\n\tint i, freq[128] = {0};\n\tchar c[16];\n\n\twhile (*s) freq[(int)*s++]++;\n\n\tfor (i = 0; i < 128; i++)\n\t\tif (freq[i]) qinsert(new_node(freq[i], i, 0, 0));\n\n\twhile (qend > 2) \n\t\tqinsert(new_node(0, 0, qremove(), qremove()));\n\n\tbuild_code(q[1], c, 0);\n}\n\nvoid encode(const char *s, char *out)\n{\n\twhile (*s) {\n\t\tstrcpy(out, code[*s]);\n\t\tout += strlen(code[*s++]);\n\t}\n}\n\nvoid decode(const char *s, node t)\n{\n\tnode n = t;\n\twhile (*s) {\n\t\tif (*s++ == '0') n = n->left;\n\t\telse n = n->right;\n\n\t\tif (n->c) putchar(n->c), n = t;\n\t}\n\n\tputchar('\\n');\n\tif (t != n) printf(\"garbage input\\n\");\n}\n\nint main(void)\n{\n\tint i;\n\tconst char *str = \"this is an example for huffman encoding\";\n        char buf[1024];\n\n\tinit(str);\n\tfor (i = 0; i < 128; i++)\n\t\tif (code[i]) printf(\"'%c': %s\\n\", i, code[i]);\n\n\tencode(str, buf);\n\tprintf(\"encoded: %s\\n\", buf);\n\n\tprintf(\"decoded: \");\n\tdecode(buf, q[1]);\n\n\treturn 0;\n}\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in a given string. It first creates a tree of nodes based on the frequency of each character, with more frequent characters having fewer bits in their encoding. It uses a heap-based priority queue to manage the nodes and constructs the binary tree by removing the nodes with the highest priority (lowest probability). The code then traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf form the Huffman encoding for the corresponding character. The code outputs a table of Huffman encodings for each character.","id":3534}
    {"lang_cluster":"C","source_code":"\nLibrary: GTK\n#include <stdio.h>\n#include <gtk\/gtk.h>\n\nconst gchar *clickme = \"Click Me\";\nguint counter = 0;\n\n#define MAXLEN 64\nvoid clickedme(GtkButton *o, gpointer d)\n{\n    GtkLabel *l = GTK_LABEL(d);\n    char nt[MAXLEN];\n    \n    counter++;\n    snprintf(nt, MAXLEN, \"You clicked me %d times\", counter);\n    gtk_label_set_text(l, nt);\n}\n\nint main(int argc, char **argv)\n{\n    GtkWindow *win;\n    GtkButton *button;\n    GtkLabel *label;\n    GtkVBox *vbox;\n\n    gtk_init(&argc, &argv);\n    win = (GtkWindow*)gtk_window_new(GTK_WINDOW_TOPLEVEL);\n    gtk_window_set_title(win, clickme);\n    button = (GtkButton*)gtk_button_new_with_label(clickme);\n    label = (GtkLabel*)gtk_label_new(\"There have been no clicks yet\");\n    gtk_label_set_single_line_mode(label, TRUE);\n    vbox = (GtkVBox*)gtk_vbox_new(TRUE, 1);\n    gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(label));\n    gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(button));\n    gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));\n    g_signal_connect(G_OBJECT(win), \"delete-event\", (GCallback)gtk_main_quit, NULL);\n    g_signal_connect(G_OBJECT(button), \"clicked\", (GCallback)clickedme, label);\n    gtk_widget_show_all(GTK_WIDGET(win));\n    gtk_main();\n    return 0;\n}\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":3535}
    {"lang_cluster":"C","source_code":"\nLibrary: SQLite\n#include <stdio.h>\n#include <stdlib.h>\n#include <sqlite3.h>\n\nconst char *code = \n\"CREATE TABLE address (\\n\"\n\"       addrID\t\tINTEGER PRIMARY KEY AUTOINCREMENT,\\n\"\n\"\taddrStreet\tTEXT NOT NULL,\\n\"\n\"\taddrCity\tTEXT NOT NULL,\\n\"\n\"\taddrState\tTEXT NOT NULL,\\n\"\n\"\taddrZIP\t\tTEXT NOT NULL)\\n\" ;\n\nint main()\n{\n  sqlite3 *db = NULL;\n  char *errmsg;\n  \n  if ( sqlite3_open(\"address.db\", &db) == SQLITE_OK ) {\n    if ( sqlite3_exec(db, code, NULL, NULL,  &errmsg) != SQLITE_OK ) {\n      fprintf(stderr, errmsg);\n      sqlite3_free(errmsg);\n      sqlite3_close(db);\n      exit(EXIT_FAILURE);\n    }\n    sqlite3_close(db);\n  } else {\n    fprintf(stderr, \"cannot open db...\\n\");\n    sqlite3_close(db);\n    exit(EXIT_FAILURE);\n  }\n  return EXIT_SUCCESS;\n}\n\n","human_summarization":"create a table in a database to store US postal addresses, including fields for a unique identifier, street address, city, state code, and zipcode. The codes also demonstrate how to establish a database connection in non-database languages.","id":3536}
    {"lang_cluster":"C","source_code":"\nint i;\nfor(i = 10; i >= 0; --i)\n  printf(\"%d\\n\",i);\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":3537}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n#include <ctype.h>\n#include <getopt.h>\n\n#define NUMLETTERS 26\n#define BUFSIZE 4096\n\nchar *get_input(void);\n\nint main(int argc, char *argv[])\n{\n    char const usage[] = \"Usage: vinigere [-d] key\";\n    char sign = 1; \n    char const plainmsg[] = \"Plain text:  \";\n    char const cryptmsg[] = \"Cipher text: \";\n    bool encrypt = true;\n    int opt;\n\n    while ((opt = getopt(argc, argv, \"d\")) != -1) {\n        switch (opt) {\n        case 'd': \n            sign = -1;\n            encrypt = false;\n            break;\n        default: \n            fprintf(stderr, \"Unrecogized command line argument:'-%i'\\n\", opt);\n            fprintf(stderr, \"\\n%s\\n\", usage);\n            return 1;\n        }\n    }\n\n    if (argc - optind != 1) {\n        fprintf(stderr, \"%s requires one argument and one only\\n\", argv[0]);\n        fprintf(stderr, \"\\n%s\\n\", usage);\n        return 1;\n    }\n\n\n    \/\/ Convert argument into array of shifts\n    char const *const restrict key = argv[optind];\n    size_t const keylen = strlen(key);\n    char shifts[keylen];\n\n    char const *restrict plaintext = NULL; \n    for (size_t i = 0; i < keylen; i++) {\n        if (!(isalpha(key[i]))) {\n            fprintf(stderr, \"Invalid key\\n\");\n            return 2;\n        }\n        char const charcase = (isupper(key[i])) ? 'A' : 'a';\n        \/\/ If decrypting, shifts will be negative.\n        \/\/ This line would turn \"bacon\" into {1, 0, 2, 14, 13}\n        shifts[i] = (key[i] - charcase) * sign;\n    }\n\n    do {\n        fflush(stdout);\n        \/\/ Print \"Plain text: \" if encrypting and \"Cipher text:  \" if\n        \/\/ decrypting\n        printf(\"%s\", (encrypt) ? plainmsg : cryptmsg);\n        plaintext = get_input();\n        if (plaintext == NULL) {\n            fprintf(stderr, \"Error getting input\\n\");\n            return 4;\n        }\n    } while (strcmp(plaintext, \"\") == 0); \/\/ Reprompt if entry is empty\n\n    size_t const plainlen = strlen(plaintext);\n\n    char* const restrict ciphertext = calloc(plainlen + 1, sizeof *ciphertext);\n    if (ciphertext == NULL) {\n        fprintf(stderr, \"Memory error\\n\");\n        return 5;\n    }\n\n    for (size_t i = 0, j = 0; i < plainlen; i++) {\n        \/\/ Skip non-alphabetical characters\n        if (!(isalpha(plaintext[i]))) {\n            ciphertext[i] = plaintext[i];\n            continue;\n        }\n        \/\/ Check case\n        char const charcase = (isupper(plaintext[i])) ? 'A' : 'a';\n        \/\/ Wrapping conversion algorithm\n        ciphertext[i] = ((plaintext[i] + shifts[j] - charcase + NUMLETTERS) % NUMLETTERS) + charcase;\n        j = (j+1) % keylen;\n    }\n    ciphertext[plainlen] = '\\0';\n    printf(\"%s%s\\n\", (encrypt) ? cryptmsg : plainmsg, ciphertext);\n\n    free(ciphertext);\n    \/\/ Silence warnings about const not being maintained in cast to void*\n    free((char*) plaintext);\n    return 0;\n}\nchar *get_input(void) {\n\n    char *const restrict buf = malloc(BUFSIZE * sizeof (char));\n    if (buf == NULL) {\n        return NULL;\n    }\n\n    fgets(buf, BUFSIZE, stdin);\n\n    \/\/ Get rid of newline\n    size_t const len = strlen(buf);\n    if (buf[len - 1] == '\\n') buf[len - 1] = '\\0';\n\n    return buf;\n}\n\n\n","human_summarization":"implement a Vigen\u00e8re cipher for both encryption and decryption. It handles keys and text of unequal length, capitalizes all characters, and discards non-alphabetic characters. It also includes an option to decrypt the message with the -d command line flag, while preserving the case and skipping non-alphabetical characters.","id":3538}
    {"lang_cluster":"C","source_code":"\n\nint i;\nfor(i = 1; i < 10; i += 2)\n  printf(\"%d\\n\", i);\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one, printing all odd digits.","id":3539}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nint i;\ndouble sum(int *i, int lo, int hi, double (*term)()) {\n    double temp = 0;\n    for (*i = lo; *i <= hi; (*i)++)\n        temp += term();\n    return temp;\n}\n\ndouble term_func() { return 1.0 \/ i; }\n\nint main () {\n    printf(\"%f\\n\", sum(&i, 1, 100, term_func));\n    return 0;\n}\n\n\nWorks with: gcc\n\n#include <stdio.h>\n \nint i;\n\n#define sum(i, lo_byname, hi_byname, term)      \\\n  ({                                            \\\n  int lo = lo_byname;                           \\\n  int hi = hi_byname;                           \\\n                                                \\\n  double temp = 0;                              \\\n  for (i = lo; i <= hi; ++i)                    \\\n    temp += term;                               \\\n  temp;                                         \\\n  })\n\nint main () {\n    printf(\"%f\\n\", sum(i, 1, 100, 1.0 \/ i));\n    return 0;\n}\n\n\n","human_summarization":"The code is an implementation of Jensen's Device, a programming technique that exploits call by name. It calculates the 100th harmonic number using a sum procedure, which takes in four parameters: an integer, a lower limit, an upper limit, and a term. The term and integer are passed by name, allowing their values to be re-evaluated in the caller's context every time they are required. This results in the correct harmonic number calculation. The code also demonstrates the importance of passing the first parameter by name or reference to ensure changes are visible in the caller's context. The output of the code is 5.18738.","id":3540}
    {"lang_cluster":"C","source_code":"\n#include <stdlib.h>\n#include <stdio.h>\n#include <math.h>\n#include <string.h>\n\nvoid hue_to_rgb(double hue, double sat, unsigned char *p)\n{\n\tdouble x;\n\tint c = 255 * sat;\n\thue \/= 60;\n\tx = (1 - fabs(fmod(hue, 2) - 1)) * 255;\n\n\tswitch((int)hue) {\n\tcase 0:\tp[0] = c; p[1] = x; p[2] = 0; return;\n\tcase 1:\tp[0] = x; p[1] = c; p[2] = 0; return;\n\tcase 2:\tp[0] = 0; p[1] = c; p[2] = x; return;\n\tcase 3:\tp[0] = 0; p[1] = x; p[2] = c; return;\n\tcase 4:\tp[0] = x; p[1] = 0; p[2] = c; return;\n\tcase 5:\tp[0] = c; p[1] = 0; p[2] = x; return;\n\t}\n}\n\nint main(void)\n{\n\tconst int size = 512;\n\tint i, j;\n\tunsigned char *colors = malloc(size * 3);\n\tunsigned char *pix = malloc(size * size * 3), *p;\n\tFILE *fp;\n\n\tfor (i = 0; i < size; i++)\n\t\thue_to_rgb(i * 240. \/ size, i * 1. \/ size, colors + 3 * i);\n\n\tfor (i = 0, p = pix; i < size; i++)\n\t\tfor (j = 0; j < size; j++, p += 3)\n\t\t\tmemcpy(p, colors + (i ^ j) * 3, 3);\n\n\tfp = fopen(\"xor.ppm\", \"wb\");\n\tfprintf(fp, \"P6\\n%d %d\\n255\\n\", size, size);\n\tfwrite(pix, size * size * 3, 1, fp);\n\tfclose(fp);\n\n\treturn 0;\n}\n\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":3541}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <locale.h>\n\n#define DOUBLE_SPACE 1\n\n#if DOUBLE_SPACE\n#\tdefine SPC \"\u3000\"\n#else\n#\tdefine SPC \" \"\n#endif\n\nwchar_t glyph[] = L\"\"SPC\"\u2502\u2502\u2502\u2500\u2518\u2510\u2524\u2500\u2514\u250c\u251c\u2500\u2534\u252c\u253c\"SPC\"\u2506\u2506\u2506\u2504\u256f\u256e \u2504\u2570\u256d \u2504\";\n\ntypedef unsigned char byte;\nenum { N = 1, S = 2, W = 4, E = 8, V = 16 };\n\nbyte **cell;\nint w, h, avail;\n#define each(i, x, y) for (i = x; i <= y; i++)\n\nint irand(int n)\n{\n\tint r, rmax = n * (RAND_MAX \/ n);\n\twhile ((r = rand()) >= rmax);\n\treturn r \/ (RAND_MAX\/n);\n}\n\nvoid show()\n{\n\tint i, j, c;\n\teach(i, 0, 2 * h) {\n\t\teach(j, 0, 2 * w) {\n\t\t\tc = cell[i][j];\n\t\t\tif (c > V) printf(\"\\033[31m\");\n\t\t\tprintf(\"%lc\", glyph[c]);\n\t\t\tif (c > V) printf(\"\\033[m\");\n\t\t}\n\t\tputchar('\\n');\n\t}\n}\n\ninline int max(int a, int b) { return a >= b ? a : b; }\ninline int min(int a, int b) { return b >= a ? a : b; }\n\nstatic int dirs[4][2] = {{-2, 0}, {0, 2}, {2, 0}, {0, -2}};\nvoid walk(int x, int y)\n{\n\tint i, t, x1, y1, d[4] = { 0, 1, 2, 3 };\n\n\tcell[y][x] |= V;\n\tavail--;\n\n\tfor (x1 = 3; x1; x1--)\n\t\tif (x1 != (y1 = irand(x1 + 1)))\n\t\t\ti = d[x1], d[x1] = d[y1], d[y1] = i;\n\n\tfor (i = 0; avail && i < 4; i++) {\n\t\tx1 = x + dirs[ d[i] ][0], y1 = y + dirs[ d[i] ][1];\n\n\t\tif (cell[y1][x1] & V) continue;\n\n\t\t\/* break walls *\/\n\t\tif (x1 == x) {\n\t\t\tt = (y + y1) \/ 2;\n\t\t\tcell[t][x+1] &= ~W, cell[t][x] &= ~(E|W), cell[t][x-1] &= ~E;\n\t\t} else if (y1 == y) {\n\t\t\tt = (x + x1)\/2;\n\t\t\tcell[y-1][t] &= ~S, cell[y][t] &= ~(N|S), cell[y+1][t] &= ~N;\n\t\t}\n\t\twalk(x1, y1);\n\t}\n}\n\nint solve(int x, int y, int tox, int toy)\n{\n\tint i, t, x1, y1;\n\n\tcell[y][x] |= V;\n\tif (x == tox && y == toy) return 1;\n\n\teach(i, 0, 3) {\n\t\tx1 = x + dirs[i][0], y1 = y + dirs[i][1];\n\t\tif (cell[y1][x1]) continue;\n\n\t\t\/* mark path *\/\n\t\tif (x1 == x) {\n\t\t\tt = (y + y1)\/2;\n\t\t\tif (cell[t][x] || !solve(x1, y1, tox, toy)) continue;\n\n\t\t\tcell[t-1][x] |= S, cell[t][x] |= V|N|S, cell[t+1][x] |= N;\n\t\t} else if (y1 == y) {\n\t\t\tt = (x + x1)\/2;\n\t\t\tif (cell[y][t] || !solve(x1, y1, tox, toy)) continue;\n\n\t\t\tcell[y][t-1] |= E, cell[y][t] |= V|E|W, cell[y][t+1] |= W;\n\t\t}\n\t\treturn 1;\n\t}\n\n\t\/* backtrack *\/\n\tcell[y][x] &= ~V;\n\treturn 0;\n}\n\nvoid make_maze()\n{\n\tint i, j;\n\tint h2 = 2 * h + 2, w2 = 2 * w + 2;\n\tbyte **p;\n\n\tp = calloc(sizeof(byte*) * (h2 + 2) + w2 * h2 + 1, 1);\n\n\tp[1] = (byte*)(p + h2 + 2) + 1;\n\teach(i, 2, h2) p[i] = p[i-1] + w2;\n\tp[0] = p[h2];\n\tcell = &p[1];\n\n\teach(i, -1, 2 * h + 1) cell[i][-1] = cell[i][w2 - 1] = V;\n\teach(j, 0, 2 * w) cell[-1][j] = cell[h2 - 1][j] = V;\n\teach(i, 0, h) each(j, 0, 2 * w) cell[2*i][j] |= E|W;\n\teach(i, 0, 2 * h) each(j, 0, w) cell[i][2*j] |= N|S;\n\teach(j, 0, 2 * w) cell[0][j] &= ~N, cell[2*h][j] &= ~S;\n\teach(i, 0, 2 * h) cell[i][0] &= ~W, cell[i][2*w] &= ~E;\n\n\tavail = w * h;\n\twalk(irand(2) * 2 + 1, irand(h) * 2 + 1);\n\n\t\/* reset visited marker (it's also used by path finder) *\/\n\teach(i, 0, 2 * h) each(j, 0, 2 * w) cell[i][j] &= ~V;\n\tsolve(1, 1, 2 * w - 1, 2 * h - 1);\n\n\tshow();\n}\n\nint main(int c, char **v)\n{\n\tsetlocale(LC_ALL, \"\");\n\tif (c < 2 || (w = atoi(v[1])) <= 0) w = 16;\n\tif (c < 3 || (h = atoi(v[2])) <= 0) h = 8;\n\n\tmake_maze();\n\n\treturn 0;\n}\n\n\nSample output:\n\u250c\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u252c\u2500\u2500\u2500\u2510\n\u2502\u2504\u2504\u256e\u2502\u256d\u2504\u2504\u2504\u256e\u2502\u3000\u3000\u256d\u2504\u2504\u2504\u2504\u2504\u256e\u2502\u3000\u3000\u256d\u2504\u2504\u2504\u256e\u2502\u256d\u2504\u256e\u2502\n\u2502\u3000\u2502\u2506\u2502\u2506\u2500\u2500\u2510\u2506\u2502\u3000\u2502\u2506\u2500\u2500\u252c\u2500\u2510\u2506\u2514\u2500\u2500\u2506\u250c\u2500\u2510\u2506\u2502\u2506\u2502\u2506\u2502\n\u2502\u3000\u2502\u2506\u2502\u2570\u2504\u256e\u2502\u2506\u2502\u3000\u2502\u2570\u2504\u256e\u2502\u3000\u2502\u2570\u2504\u2504\u2504\u256f\u2502\u3000\u2502\u2570\u2504\u256f\u2502\u2506\u2502\n\u2502\u3000\u2502\u2506\u2514\u2500\u2500\u2506\u2502\u2506\u2514\u2500\u253c\u2500\u2500\u2506\u2502\u3000\u2514\u2500\u2500\u2500\u2500\u2500\u2524\u3000\u2514\u2500\u252c\u2500\u2518\u2506\u2502\n\u2502\u3000\u2502\u2570\u2504\u2504\u2504\u256f\u2502\u2570\u2504\u256e\u2502\u256d\u2504\u256f\u2502\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u2502\u3000\u3000\u3000\u2502\u256d\u2504\u256f\u2502\n\u2502\u3000\u2514\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2510\u2506\u2502\u2506\u250c\u2500\u2534\u2500\u2500\u2500\u2510\u3000\u2502\u3000\u2502\u3000\u2502\u3000\u2502\u2506\u2500\u2500\u2524\n\u2502\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u2502\u2506\u2502\u2506\u2502\u256d\u2504\u2504\u2504\u256e\u2502\u3000\u2502\u3000\u3000\u3000\u2502\u3000\u2502\u2570\u2504\u256e\u2502\n\u2502\u3000\u2500\u2500\u2500\u2500\u2500\u2500\u2510\u3000\u2502\u2506\u2502\u2506\u2502\u2506\u2500\u2500\u2510\u2506\u2514\u2500\u2524\u3000\u250c\u2500\u2518\u3000\u2514\u2500\u2510\u2506\u2502\n\u2502\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u2502\u3000\u2502\u2506\u2502\u2570\u2504\u256f\u3000\u3000\u2502\u2570\u2504\u256e\u2502\u3000\u2502\u3000\u3000\u3000\u3000\u3000\u2502\u2506\u2502\n\u2502\u3000\u250c\u2500\u2500\u2500\u2500\u2500\u2518\u3000\u2502\u2506\u251c\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2510\u2506\u2502\u3000\u2502\u3000\u2500\u2500\u252c\u2500\u2518\u2506\u2502\n\u2502\u3000\u2502\u3000\u3000\u3000\u3000\u3000\u3000\u3000\u2502\u2506\u2502\u256d\u2504\u2504\u2504\u2504\u2504\u256e\u2502\u2506\u2502\u3000\u2502\u3000\u3000\u3000\u2502\u256d\u2504\u256f\u2502\n\u251c\u2500\u2524\u3000\u2500\u2500\u252c\u2500\u252c\u2500\u2518\u2506\u2502\u2506\u250c\u2500\u252c\u2500\u2500\u2506\u2502\u2506\u2514\u2500\u2534\u2500\u2510\u3000\u2502\u2506\u250c\u2500\u2524\n\u2502\u3000\u2502\u3000\u3000\u3000\u2502\u3000\u2502\u256d\u2504\u256f\u2502\u2506\u2502\u3000\u2502\u256d\u2504\u256f\u2502\u2570\u2504\u2504\u2504\u256e\u2502\u3000\u2502\u2506\u2502\u3000\u2502\n\u2502\u3000\u2514\u2500\u2500\u3000\u2502\u3000\u2502\u2506\u2500\u2500\u2518\u2506\u2502\u3000\u2502\u2506\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2506\u2502\u3000\u2502\u2506\u2502\u3000\u2502\n\u2502\u3000\u3000\u3000\u3000\u3000\u2502\u3000\u3000\u2570\u2504\u2504\u2504\u256f\u2502\u3000\u3000\u2570\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u256f\u2502\u3000\u3000\u2570\u2504\u2504\u2502\n\u2514\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2534\u2500\u2500\u2500\u2500\u2500\u2518\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts at a random cell, marks it as visited, and processes its neighbors. If a neighbor has not been visited, it removes the wall between the current cell and the neighbor, then recursively repeats the process with the neighbor as the current cell. The code requires a UTF8 locale and a unicode capable console. If the console font line-drawing characters are single width, it sets DOUBLE_SPACE to 0.","id":3542}
    {"lang_cluster":"C","source_code":"\n\n\n\nDigits\n\nSpigot 1\n\nSpigot 2\n\nMachin 1\n\nMachin 2\n\nAGM\n\nChudnovsky\n\n\n1,000\n\n0.008\n\n0.009\n\n0.001\n\n0.001\n\n0.000\n\n0.000\n\n\n10,000\n\n0.402\n\n0.589\n\n0.020\n\n0.016\n\n0.003\n\n0.002\n\n\n100,000\n\n39.400\n\n85.600\n\n1.740\n\n1.480\n\n0.084\n\n0.002\n\n\n1,000,000\n\n\n\n\n\n177.900\n\n156.800\n\n1.474\n\n0.333\n\n\n10,000,000\n\n\n\n\n\n\n\n\n\n25.420\n\n5.715\n\nSpigot 1: plain C (no GMP), modified Winter\/Flammenkamp, correct to 1+M digits\nSpigot 2: C+GMP, as used in Computer Language Benchmarks Game\nMachin 1: C+GMP, shown below\nMachin 2: C+GMP, as below but using Chien-Lih 1997 formula\nAGM: C+GMP, essentially from the Arithmetic-geometric mean\/Calculate Pi task.  This has performance only slightly slower than MPFR.\nChudnovsky: Hanhong Xue's code from GMP web site.\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <gmp.h>\n\nmpz_t tmp1, tmp2, t5, t239, pows;\nvoid actan(mpz_t res, unsigned long base, mpz_t pows)\n{\n\tint i, neg = 1;\n\tmpz_tdiv_q_ui(res, pows, base);\n\tmpz_set(tmp1, res);\n\tfor (i = 3; ; i += 2) {\n\t\tmpz_tdiv_q_ui(tmp1, tmp1, base * base);\n\t\tmpz_tdiv_q_ui(tmp2, tmp1, i);\n\t\tif (mpz_cmp_ui(tmp2, 0) == 0) break;\n\t\tif (neg) mpz_sub(res, res, tmp2);\n\t\telse\t  mpz_add(res, res, tmp2);\n\t\tneg = !neg;\n\t}\n}\n\nchar * get_digits(int n, size_t* len)\n{\n\tmpz_ui_pow_ui(pows, 10, n + 20);\n\n\tactan(t5, 5, pows);\n\tmpz_mul_ui(t5, t5, 16);\n\n\tactan(t239, 239, pows);\n\tmpz_mul_ui(t239, t239, 4);\n\n\tmpz_sub(t5, t5, t239);\n\tmpz_ui_pow_ui(pows, 10, 20);\n\tmpz_tdiv_q(t5, t5, pows);\n\n\t*len = mpz_sizeinbase(t5, 10);\n\treturn mpz_get_str(0, 0, t5);\n}\n\nint main(int c, char **v)\n{\n\tunsigned long accu = 16384, done = 0;\n\tsize_t got;\n\tchar *s;\n\n\tmpz_init(tmp1);\n\tmpz_init(tmp2);\n\tmpz_init(t5);\n\tmpz_init(t239);\n\tmpz_init(pows);\n\n\twhile (1) {\n\t\ts = get_digits(accu, &got);\n\n\t\t\/* write out digits up to the last one not preceding a 0 or 9*\/\n\t\tgot -= 2; \/* -2: length estimate may be longer than actual *\/\n\t\twhile (s[got] == '0' || s[got] == '9') got--;\n\n\t\tprintf(\"%.*s\", (int)(got - done), s + done);\n\t\tfree(s);\n\n\t\tdone = got;\n\n\t\t\/* double the desired digits; slows down at least cubically *\/\n\t\taccu *= 2;\n\t}\n\n\treturn 0;\n}\n\n","human_summarization":"The code continually calculates and outputs the next decimal digit of Pi, starting from 3.14159265 and continuing indefinitely until the user aborts the program. It uses Machin's formula for the calculation and is designed to handle a preset number of digits, recalculating Pi with increasing length and removing already displayed leading digits. The performance is faster than the unbounded Spigot method, especially for the first 100k digits.","id":3543}
    {"lang_cluster":"C","source_code":"\nint list_cmp(int *a, int la, int *b, int lb)\n{\n\tint i, l = la;\n\tif (l > lb) l = lb;\n\tfor (i = 0; i < l; i++) {\n\t\tif (a[i] == b[i]) continue;\n\t\treturn (a[i] > b[i]) ? 1 : -1;\n\t}\n\tif (la == lb) return 0;\n\treturn la > lb ? 1 : -1;\n}\n\nThis funciton returns one of three states, not a boolean.  One can define boolean comparisons, such as list_less_or_eq, based on it:#define list_less_or_eq(a,b,c,d) (list_cmp(a,b,c,d)\u00a0!= 1)\n\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise.\"","id":3544}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n\nint ackermann(int m, int n)\n{\n        if (!m) return n + 1;\n        if (!n) return ackermann(m - 1, 1);\n        return ackermann(m - 1, ackermann(m, n - 1));\n}\n\nint main()\n{\n        int m, n;\n        for (m = 0; m <= 4; m++)\n                for (n = 0; n < 6 - m; n++)\n                        printf(\"A(%d, %d) = %d\\n\", m, n, ackermann(m, n));\n\n        return 0;\n}\n\n\n","human_summarization":"Implement the Ackermann function, a non-primitive recursive function. The function takes two non-negative arguments and returns a value based on the conditions defined in the Ackermann function. The function is expected to terminate and return a value, with a preference for arbitrary precision due to the rapid growth of the function. The implementation also includes simple caching to handle the large number of recursive calls. However, for large m values, the function may result in a stack overflow due to the depth of recursion. Alternative iterative techniques and further optimizations may be possible.","id":3545}
    {"lang_cluster":"C","source_code":"\nLibrary: GNU Scientific Library\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n#include <gsl\/gsl_sf_gamma.h>\n#ifndef M_PI\n#define M_PI 3.14159265358979323846\n#endif\n\n\/* very simple approximation *\/\ndouble st_gamma(double x)\n{\n  return sqrt(2.0*M_PI\/x)*pow(x\/M_E, x);\n}\n\n#define A 12\ndouble sp_gamma(double z)\n{\n  const int a = A;\n  static double c_space[A];\n  static double *c = NULL;\n  int k;\n  double accm;\n \n  if ( c == NULL ) {\n    double k1_factrl = 1.0; \/* (k - 1)!*(-1)^k with 0!==1*\/\n    c = c_space;\n    c[0] = sqrt(2.0*M_PI);\n    for(k=1; k < a; k++) {\n      c[k] = exp(a-k) * pow(a-k, k-0.5) \/ k1_factrl;\n\t  k1_factrl *= -k;\n    }\n  }\n  accm = c[0];\n  for(k=1; k < a; k++) {\n    accm += c[k] \/ ( z + k );\n  }\n  accm *= exp(-(z+a)) * pow(z+a, z+0.5); \/* Gamma(z+1) *\/\n  return accm\/z;\n}\n\nint main()\n{\n  double x;\n\n\n  printf(\"%15s%15s%15s%15s\\n\", \"Stirling\", \"Spouge\", \"GSL\", \"libm\");\n  for(x=1.0; x <= 10.0; x+=1.0) {\n    printf(\"%15.8lf%15.8lf%15.8lf%15.8lf\\n\", st_gamma(x\/3.0), sp_gamma(x\/3.0), \n\t   gsl_sf_gamma(x\/3.0), tgamma(x\/3.0));\n  }\n  return 0;\n}\n\n\n","human_summarization":"implement the Gamma function using numerical integration, Lanczos approximation, and Stirling's approximation. It also compares the results of the custom implementation with the built-in\/library function if available.","id":3546}
    {"lang_cluster":"C","source_code":"\nC99, compiled with gcc -std=c99 -Wall.  Take one commandline argument: size of board, or default to 8. Shows the board layout for each solution.#include <stdio.h>\n#include <stdlib.h>\n\nint count = 0;\nvoid solve(int n, int col, int *hist)\n{\n\tif (col == n) {\n\t\tprintf(\"\\nNo. %d\\n-----\\n\", ++count);\n\t\tfor (int i = 0; i < n; i++, putchar('\\n'))\n\t\t\tfor (int j = 0; j < n; j++)\n\t\t\t\tputchar(j == hist[i] ? 'Q' : ((i + j) & 1) ? ' ' : '.');\n\n\t\treturn;\n\t}\n\n#\tdefine attack(i, j) (hist[j] == i || abs(hist[j] - i) == col - j)\n\tfor (int i = 0, j = 0; i < n; i++) {\n\t\tfor (j = 0; j < col && !attack(i, j); j++);\n\t\tif (j < col) continue;\n\n\t\thist[col] = i;\n\t\tsolve(n, col + 1, hist);\n\t}\n}\n\nint main(int n, char **argv)\n{\n\tif (n <= 1 || (n = atoi(argv[1])) <= 0) n = 8;\n\tint hist[n];\n\tsolve(n, 0, hist);\n}\n\nSimiliar to above, but using bits to save board configurations and quite a bit faster:#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\ntypedef uint32_t uint;\nuint full, *qs, count = 0, nn;\n\nvoid solve(uint d, uint c, uint l, uint r)\n{\n\tuint b, a, *s;\n\tif (!d) {\n\t\tcount++;\n#if 0\n\t\tprintf(\"\\nNo. %d\\n===========\\n\", count);\n\t\tfor (a = 0; a < nn; a++, putchar('\\n'))\n\t\t\tfor (b = 0; b < nn; b++, putchar(' '))\n\t\t\t\tputchar(\" -QQ\"[((b == qs[a])<<1)|((a + b)&1)]);\n#endif\n\t\treturn;\n\t}\n\n\ta = (c | (l <<= 1) | (r >>= 1)) & full;\n\tif (a != full)\n\t\tfor (*(s = qs + --d) = 0, b = 1; b <= full; (*s)++, b <<= 1)\n\t\t\tif (!(b & a)) solve(d, b|c, b|l, b|r);\n}\n\nint main(int n, char **argv)\n{\n\tif (n <= 1 || (nn = atoi(argv[1])) <= 0) nn = 8;\n\n\tqs = calloc(nn, sizeof(int));\n\tfull = (1U << nn) - 1;\n\n\tsolve(nn, 0, 0, 0);\n\tprintf(\"\\nSolutions: %d\\n\", count);\n\treturn 0;\n}\n\n\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef unsigned int uint;\nuint count = 0;\n\n#define ulen sizeof(uint) * 8\n\n\/* could have defined as int solve(...), but void may have less\n   chance to confuse poor optimizer *\/\nvoid solve(int n)\n{\n\tint cnt = 0;\n\tconst uint full = -(int)(1 << (ulen - n));\n\tregister uint bits, pos, *m, d, e;\n\n\tuint b0, b1, l[32], r[32], c[32], mm[33] = {0};\n\tn -= 3;\n\t\/* require second queen to be left of the first queen, so\n\t   we ever only test half of the possible solutions. This\n\t   is why we can't handle n=1 here *\/\n\tfor (b0 = 1U << (ulen - n - 3); b0; b0 <<= 1) {\n\t\tfor (b1 = b0 << 2; b1; b1 <<= 1) {\n\t\t\td = n;\n\t\t\t\/* c: columns occupied by previous queens.\n\t\t\t   l: columns attacked by left diagonals\n\t\t\t   r: by right diagnoals *\/\n\t\t\tc[n] = b0 | b1;\n\t\t\tl[n] = (b0 << 2) | (b1 << 1);\n\t\t\tr[n] = (b0 >> 2) | (b1 >> 1);\n\n\t\t\t\/* availabe columns on current row. m is stack *\/\n\t\t\tbits = *(m = mm + 1) = full & ~(l[n] | r[n] | c[n]);\n\n\t\t\twhile (bits) {\n\t\t\t\t\/* d: depth, aka row. counting backwards\n\t\t\t\t   because !d is often faster than d\u00a0!= n *\/\n\t\t\t\twhile (d) {\n\t\t\t\t\t\/* pos is right most nonzero bit *\/\n\t\t\t\t\tpos = -(int)bits & bits;\n\n\t\t\t\t\t\/* mark bit used. only put current bits\n\t\t\t\t\t   on stack if not zero, so backtracking\n\t\t\t\t\t   will skip exhausted rows (because reading\n\t\t\t\t\t   stack variable is sloooow compared to\n\t\t\t\t\t   registers) *\/\n\t\t\t\t\tif ((bits &= ~pos))\n\t\t\t\t\t\t*m++ = bits | d;\n\n\t\t\t\t\t\/* faster than l[d+1] = l[d]... *\/\n\t\t\t\t\te = d--;\n\t\t\t\t\tl[d] = (l[e] | pos) << 1;\n\t\t\t\t\tr[d] = (r[e] | pos) >> 1;\n\t\t\t\t\tc[d] =  c[e] | pos;\n\n\t\t\t\t\tbits = full & ~(l[d] | r[d] | c[d]);\n\n\t\t\t\t\tif (!bits) break;\n\t\t\t\t\tif (!d) { cnt++; break; }\n\t\t\t\t}\n\t\t\t\t\/* Bottom of stack m is a zero'd field acting\n\t\t\t\t   as sentinel.  When saving to stack, left\n\t\t\t\t   27 bits are the available columns, while\n\t\t\t\t   right 5 bits is the depth. Hence solution\n\t\t\t\t   is limited to size 27 board -- not that it\n\t\t\t\t   matters in foreseeable future. *\/\n\t\t\t\td = (bits = *--m) & 31U;\n\t\t\t\tbits &= ~31U;\n\t\t\t}\n\t\t}\n\t}\n\tcount = cnt * 2;\n}\n\nint main(int c, char **v)\n{\n\tint nn;\n\tif (c <= 1 || (nn = atoi(v[1])) <= 0) nn = 8;\n\n\tif (nn > 27) {\n\t\tfprintf(stderr, \"Value too large, abort\\n\");\n\t\texit(1);\n\t}\n\n\t\/* Can't solve size 1 board; might as well skip 2 and 3 *\/\n\tif (nn < 4) count = nn == 1;\n\telse\t    solve(nn);\n\n\tprintf(\"\\nSolutions: %d\\n\", count);\n\treturn 0;\n}\n\n\n#include <stdio.h>\n#define MAXN 31\n\nint nqueens(int n)\n{\n  int q0,q1;\n  int cols[MAXN], diagl[MAXN], diagr[MAXN], posibs[MAXN]; \/\/ Our backtracking 'stack' \n  int num=0;\n  \/\/\n  \/\/ The top level is two fors, to save one bit of symmetry in the enumeration by forcing second queen to\n  \/\/ be AFTER the first queen.\n  \/\/\n  for (q0=0; q0<n-2; q0++) {\n    for (q1=q0+2; q1<n; q1++){\n      int bit0 = 1<<q0;\n      int bit1 = 1<<q1;\n      int d=0; \/\/ d is our depth in the backtrack stack \n      cols[0] = bit0 | bit1 | (-1<<n); \/\/ The -1 here is used to fill all 'coloumn' bits after n ...\n      diagl[0]= (bit0<<1 | bit1)<<1;\n      diagr[0]= (bit0>>1 | bit1)>>1;\n\n      \/\/  The variable posib contains the bitmask of possibilities we still have to try in a given row ...\n      int posib = ~(cols[0] | diagl[0] | diagr[0]);\n\n      while (d >= 0) {\n        while(posib) {\n          int bit = posib & -posib; \/\/ The standard trick for getting the rightmost bit in the mask\n          int ncols= cols[d] | bit;\n          int ndiagl = (diagl[d] | bit) << 1;\n          int ndiagr = (diagr[d] | bit) >> 1;\n          int nposib = ~(ncols | ndiagl | ndiagr);\n          posib^=bit; \/\/ Eliminate the tried possibility.\n\n          \/\/ The following is the main additional trick here, as recognizing solution can not be done using stack level (d),\n          \/\/ since we save the depth+backtrack time at the end of the enumeration loop. However by noticing all coloumns are\n          \/\/ filled (comparison to -1) we know a solution was reached ...\n          \/\/ Notice also that avoiding an if on the ncols==-1 comparison is more efficient!\n          num += ncols==-1; \n\n          if (nposib) {\n            if (posib) { \/\/ This if saves stack depth + backtrack operations when we passed the last possibility in a row.\n              posibs[d++] = posib; \/\/ Go lower in stack ..\n            }\n            cols[d] = ncols;\n            diagl[d] = ndiagl;\n            diagr[d] = ndiagr;\n            posib = nposib;\n          }\n        }\n        posib = posibs[--d]; \/\/ backtrack ...\n      }\n    }\n  }\n  return num*2;\n}\n\n\nmain(int ac , char **av) \n{\n  if(ac != 2) {\n    printf(\"usage: nq n\\n\");\n    return 1;\n  }\n  int n = atoi(av[1]);\n  if(n<1 || n > MAXN) {\n    printf(\"n must be between 2 and 31!\\n\");\n  }\n  printf(\"Number of solution for %d is %d\\n\",n,nqueens(n));\n}\n\n","human_summarization":"\"Implement a highly optimized solution to solve the N-queens problem, with a focus on speed and efficiency. The code also includes a version with redundant optimizations removed, resulting in a 15% performance improvement on modern compilers.\"","id":3547}
    {"lang_cluster":"C","source_code":"\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \\\n  (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));\n\nvoid *array_concat(const void *a, size_t an,\n                   const void *b, size_t bn, size_t s)\n{\n  char *p = malloc(s * (an + bn));\n  memcpy(p, a, an*s);\n  memcpy(p + an*s, b, bn*s);\n  return p;\n}\n\n\/\/ testing\nconst int a[] = { 1, 2, 3, 4, 5 };\nconst int b[] = { 6, 7, 8, 9, 0 };\n\nint main(void)\n{\n  unsigned int i;\n\n  int *c = ARRAY_CONCAT(int, a, 5, b, 5);\n\n  for(i = 0; i < 10; i++)\n    printf(\"%d\\n\", c[i]);\n\n  free(c);\n  return EXIT_SUCCCESS;\n}\n\n","human_summarization":"demonstrate how to concatenate two arrays in C language when their size is known.","id":3548}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n#include <stdlib.h>\n\ntypedef struct {\n    char *name;\n    int weight;\n    int value;\n} item_t;\n\nitem_t items[] = {\n    {\"map\",                      9,   150},\n    {\"compass\",                 13,    35},\n    {\"water\",                  153,   200},\n    {\"sandwich\",                50,   160},\n    {\"glucose\",                 15,    60},\n    {\"tin\",                     68,    45},\n    {\"banana\",                  27,    60},\n    {\"apple\",                   39,    40},\n    {\"cheese\",                  23,    30},\n    {\"beer\",                    52,    10},\n    {\"suntan cream\",            11,    70},\n    {\"camera\",                  32,    30},\n    {\"T-shirt\",                 24,    15},\n    {\"trousers\",                48,    10},\n    {\"umbrella\",                73,    40},\n    {\"waterproof trousers\",     42,    70},\n    {\"waterproof overclothes\",  43,    75},\n    {\"note-case\",               22,    80},\n    {\"sunglasses\",               7,    20},\n    {\"towel\",                   18,    12},\n    {\"socks\",                    4,    50},\n    {\"book\",                    30,    10},\n};\n\nint *knapsack (item_t *items, int n, int w) {\n    int i, j, a, b, *mm, **m, *s;\n    mm = calloc((n + 1) * (w + 1), sizeof (int));\n    m = malloc((n + 1) * sizeof (int *));\n    m[0] = mm;\n    for (i = 1; i <= n; i++) {\n        m[i] = &mm[i * (w + 1)];\n        for (j = 0; j <= w; j++) {\n            if (items[i - 1].weight > j) {\n                m[i][j] = m[i - 1][j];\n            }\n            else {\n                a = m[i - 1][j];\n                b = m[i - 1][j - items[i - 1].weight] + items[i - 1].value;\n                m[i][j] = a > b ? a : b;\n            }\n        }\n    }\n    s = calloc(n, sizeof (int));\n    for (i = n, j = w; i > 0; i--) {\n        if (m[i][j] > m[i - 1][j]) {\n            s[i - 1] = 1;\n            j -= items[i - 1].weight;\n        }\n    }\n    free(mm);\n    free(m);\n    return s;\n}\n\nint main () {\n    int i, n, tw = 0, tv = 0, *s;\n    n = sizeof (items) \/ sizeof (item_t);\n    s = knapsack(items, n, 400);\n    for (i = 0; i < n; i++) {\n        if (s[i]) {\n            printf(\"%-22s %5d %5d\\n\", items[i].name, items[i].weight, items[i].value);\n            tw += items[i].weight;\n            tv += items[i].value;\n        }\n    }\n    printf(\"%-22s %5d %5d\\n\", \"totals:\", tw, tv);\n    return 0;\n}\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":3549}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n\nint verbose = 0;\nenum {\n\tclown = -1,\n\tabe, bob, col, dan, ed, fred, gav, hal, ian, jon,\n\tabi, bea, cath, dee, eve, fay, gay, hope, ivy, jan,\n};\nconst char *name[] = {\n\t\"Abe\", \"Bob\", \"Col\",  \"Dan\", \"Ed\",  \"Fred\", \"Gav\", \"Hal\",  \"Ian\", \"Jon\",\n\t\"Abi\", \"Bea\", \"Cath\", \"Dee\", \"Eve\", \"Fay\",  \"Gay\", \"Hope\", \"Ivy\", \"Jan\"\n};\nint pref[jan + 1][jon + 1] = {\n\t{ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay },\n\t{ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay },\n\t{ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan },\n\t{ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi },\n\t{ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay },\n\t{ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay },\n\t{ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay },\n\t{ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee },\n\t{ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve },\n\t{ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope },\n\n\t{ bob, fred, jon, gav, ian, abe, dan, ed, col, hal   },\n\t{ bob, abe, col, fred, gav, dan, ian, ed, jon, hal   },\n\t{ fred, bob, ed, gav, hal, col, ian, abe, dan, jon   },\n\t{ fred, jon, col, abe, ian, hal, gav, dan, bob, ed   },\n\t{ jon, hal, fred, dan, abe, gav, col, ed, ian, bob   },\n\t{ bob, abe, ed, ian, jon, dan, fred, gav, col, hal   },\n\t{ jon, gav, hal, fred, bob, abe, col, ed, dan, ian   },\n\t{ gav, jon, bob, abe, ian, dan, hal, ed, col, fred   },\n\t{ ian, col, hal, gav, fred, bob, abe, ed, jon, dan   },\n\t{ ed, hal, gav, abe, bob, jon, col, ian, fred, dan   },\n};\nint pairs[jan + 1], proposed[jan + 1];\n\nvoid engage(int man, int woman)\n{\n\tpairs[man] = woman;\n\tpairs[woman] = man;\n\tif (verbose) printf(\"%4s is engaged to %4s\\n\", name[man], name[woman]);\n}\n\nvoid dump(int woman, int man)\n{\n\tpairs[man] = pairs[woman] = clown;\n\tif (verbose) printf(\"%4s dumps %4s\\n\", name[woman], name[man]);\n}\n\n\/* how high this person ranks that: lower is more preferred *\/\nint rank(int this, int that)\n{\n\tint i;\n\tfor (i = abe; i <= jon && pref[this][i] != that; i++);\n\treturn i;\n}\n\nvoid propose(int man, int woman)\n{\n\tint fiance = pairs[woman];\n\tif (verbose) printf(\"%4s proposes to %4s\\n\", name[man], name[woman]);\n\n\tif (fiance == clown) {\n\t\tengage(man, woman);\n\t} else if (rank(woman, man) < rank(woman, fiance)) {\n\t\tdump(woman, fiance);\n\t\tengage(man, woman);\n\t}\n}\n\nint covet(int man1, int wife2)\n{\n\tif (rank(man1, wife2) < rank(man1, pairs[man1]) &&\n\t\t\trank(wife2, man1) < rank(wife2, pairs[wife2])) {\n\t\tprintf( \"    %4s (w\/ %4s) and %4s (w\/ %4s) prefer each other\"\n\t\t\t\" over current pairing.\\n\",\n\t\t\tname[man1], name[pairs[man1]], name[wife2], name[pairs[wife2]]\n\t\t);\n\t\treturn 1;\n\t}\n\treturn 0;\n}\n\nint thy_neighbors_wife(int man1, int man2)\n{\t\/* +: force checking all pairs; \"||\" would shortcircuit *\/\n\treturn covet(man1, pairs[man2]) + covet(man2, pairs[man1]);\n}\n\nint unstable()\n{\n\tint i, j, bad = 0;\n\tfor (i = abe; i < jon; i++) {\n\t\tfor (j = i + 1; j <= jon; j++)\n\t\t\tif (thy_neighbors_wife(i, j)) bad = 1;\n\t}\n\treturn bad;\n}\n\nint main()\n{\n\tint i, unengaged;\n\t\/* init: everyone marries the clown *\/\n\tfor (i = abe; i <= jan; i++)\n\t\tpairs[i] = proposed[i] = clown;\n\n\t\/* rounds *\/\n\tdo {\n\t\tunengaged = 0;\n\t\tfor (i = abe; i <= jon; i++) {\n\t\t\/\/for (i = abi; i <= jan; i++) { \/* could let women propose *\/\n\t\t\tif (pairs[i] != clown) continue;\n\t\t\tunengaged = 1;\n\t\t\tpropose(i, pref[i][++proposed[i]]);\n\t\t}\n\t} while (unengaged);\n\n\tprintf(\"Pairing:\\n\");\n\tfor (i = abe; i <= jon; i++)\n\t\tprintf(\"  %4s - %s\\n\", name[i],\n\t\t\tpairs[i] == clown ? \"clown\" : name[pairs[i]]);\n\n\tprintf(unstable()\n\t\t? \"Marriages not stable\\n\" \/* draw sad face here *\/\n\t\t: \"Stable matchup\\n\");\n\n\tprintf(\"\\nBut if Bob and Fred were to swap:\\n\");\n\ti = pairs[bob];\n\tengage(bob, pairs[fred]);\n\tengage(fred, i);\n\tprintf(unstable() ? \"Marriages not stable\\n\" : \"Stable matchup\\n\");\n\n\treturn 0;\n}\n\n\n","human_summarization":"The code implements the Gale\/Shapley algorithm to solve the Stable Marriage Problem. It takes as input the preferences of ten men and ten women for potential partners. The algorithm finds a stable set of engagements where no man prefers a woman over his current partner and vice versa. The code then perturbs this stable set to create an unstable set of engagements and checks the stability of this new set.","id":3550}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdbool.h>\n\nbool a(bool in)\n{\n  printf(\"I am a\\n\");\n  return in;\n}\n\nbool b(bool in)\n{\n  printf(\"I am b\\n\");\n  return in;\n}\n\n#define TEST(X,Y,O)\t\t\t\t\t\t\\\n  do {\t\t\t\t\t\t\t\t\\\n    x = a(X) O b(Y);\t\t\t\t\t\t\\\n    printf(#X \" \" #O \" \" #Y \" = %s\\n\\n\", x\u00a0? \"true\"\u00a0: \"false\");\t\\\n  } while(false);\n\nint main()\n{\n  bool x;\n\n  TEST(false, true, &&); \/\/ b is not evaluated\n  TEST(true, false, ||); \/\/ b is not evaluated\n  TEST(true, false, &&); \/\/ b is evaluated\n  TEST(false, false, ||); \/\/ b is evaluated \n\n  return 0;\n}\n\n","human_summarization":"The code defines two functions, 'a' and 'b', which accept and return the same boolean value and print their names when called. It then calculates and assigns the values of two equations, 'x' and 'y', using short-circuit evaluation to ensure function 'b' is only called when necessary. If the programming language doesn't support short-circuit evaluation, nested 'if' statements are used instead. The boolean operators used are && and ||.","id":3551}
    {"lang_cluster":"C","source_code":"\n\n\/*\n\n  David Lambert, 2010-Dec-09\n\n  filter producing morse beep commands.\n\n  build:\n    make morse\n\n  use:\n    $ echo tie a. | .\/morse\n    beep -n -f 440 -l 300 -D 100 -n -D 200 -n -f 440 -l 100 -D 100 -n -f 440 -l 100 -D 100 -n -D 200 -n -f 440 -l 100 -D 100 -n -D 200 -n -D 400 -n -f 440 -l 100 -D 100 -n -f 440 -l 300 -D 100 -n -D 200 -n -f 440 -l 100 -D 100 -n -f 440 -l 300 -D 100 -n -f 440 -l 100 -D 100 -n -f 440 -l 300 -D 100 -n -f 440 -l 100 -D 100 -n -f 440 -l 300 -D 100 -n -D 200 -n -D 400 -n -D 400\n\n  bugs:\n    What is the space between letter and punctuation?\n    Demo truncates input lines at 71 characters or so.\n\n *\/\n\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L))\n\/*\n  BIND(-1,0,9) is 0\n  BIND( 7,0,9) is 7\n  BIND(77,0,9) is 9\n*\/\n\nchar\n  \/* beep args for *\/\n  \/* dit  dah     extra space *\/\n  dih[50],dah[50],medium[30],word[30],\n  *dd[2] = {dih,dah};\nconst char\n  *ascii = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,?'!\/()&:;=+-_\\\"$@\",\n  *itu[] = {\n     \"13\",\"3111\",\"3131\",\"311\",\"1\",\"1131\",\"331\",\"1111\",\"11\",\"1333\",\"313\",\"1311\",\"33\",\"31\",\"333\",\"1331\",\"3313\",\"131\",\"111\",\"3\",\"113\",\"1113\",\"133\",\"3113\",\"3133\",\"3311\",\"33333\",\"13333\",\"11333\",\"11133\",\"11113\",\"11111\",\"31111\",\"33111\",\"33311\",\"33331\",\"131313\",\"331133\",\"113311\",\"133331\",\"313133\",\"31131\",\"31331\",\"313313\",\"13111\",\"333111\",\"313131\",\"31113\",\"13131\",\"311113\",\"113313\",\"131131\",\"1113113\",\"133131\"\n  };\n\nvoid append(char*s,const char*morse) {\n  for (; *morse; ++morse)\n    strcat(s,dd['3'==*morse]);\n  strcat(s,medium);\n}\n\nchar*translate(const char*i,char*o) {\n  const char*pc;\n  sprintf(o,\"beep\");\n  for (; *i; ++i)\n    if (NULL == (pc = strchr(ascii,toupper(*i))))\n      strcat(o,word);\n    else\n      append(o,itu[pc-ascii]);\n  strcat(o,word);\n  return o;\n}\n\nint main(int ac,char*av[]) {\n  char\n    sin[73],sout[100000];\n  int\n    dit = 100;\n  if (1 < ac) {\n    if (strlen(av[1]) != strspn(av[1],\"0123456789\"))\n      return 0*fprintf(stderr,\"use: %s [duration]   dit in ms, default %d\\n\",*av,dit);\n    dit = BIND(atoi(av[1]),1,1000);\n  }\n  sprintf(dah,\" -n -f 440 -l %d -D %d\",3*dit,dit);\n  sprintf(dih,\" -n -f 440 -l %d -D %d\",dit,dit);\n  sprintf(medium,\" -n -D %d\",(3-1)*dit);\n  sprintf(word,\" -n -D %d\",(7-(3-1)-1)*dit);\n  while (NULL != fgets(sin,72,stdin))\n    puts(translate(sin,sout));\n  return 0;\n}\n\n","human_summarization":"The code converts a given string into audible Morse code and sends it to an audio device, such as the PC speaker. It handles unknown characters by either ignoring them or indicating them with a different pitch. The program can be substituted with the Ubuntu beep command.","id":3552}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <ctype.h>\n\nint can_make_words(char **b, char *word)\n{\n\tint i, ret = 0, c = toupper(*word);\n\n#define SWAP(a, b) if (a\u00a0!= b) { char * tmp = a; a = b; b = tmp; }\n\n\tif (!c) return 1;\n\tif (!b[0]) return 0;\n\n\tfor (i = 0; b[i] && !ret; i++) {\n\t\tif (b[i][0] != c && b[i][1] != c) continue;\n\t\tSWAP(b[i], b[0]);\n\t\tret = can_make_words(b + 1, word + 1);\n\t\tSWAP(b[i], b[0]);\n\t}\n\n\treturn ret;\n}\n\nint main(void)\n{\n\tchar* blocks[] = {\n\t\t\"BO\", \"XK\", \"DQ\", \"CP\", \"NA\", \n\t\t\"GT\", \"RE\", \"TG\", \"QD\", \"FS\", \n\t\t\"JW\", \"HU\", \"VI\", \"AN\", \"OB\", \n\t\t\"ER\", \"FS\", \"LY\", \"PC\", \"ZM\",\n\t\t0 };\n\n\tchar *words[] = {\n\t\t\"\", \"A\", \"BARK\", \"BOOK\", \"TREAT\", \"COMMON\", \"SQUAD\", \"Confuse\", 0\n\t};\n\n\tchar **w;\n\tfor (w = words; *w; w++)\n\t\tprintf(\"%s\\t%d\\n\", *w, can_make_words(blocks, *w));\n\n\treturn 0;\n}\n\n\n","human_summarization":"The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive. It tests the function with 7 example words and returns the results. An empty string input returns true.","id":3553}
    {"lang_cluster":"C","source_code":"\nLibrary: OpenSSL\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <openssl\/md5.h>\n\nconst char *string = \"The quick brown fox jumped over the lazy dog's back\";\n\nint main()\n{\n  int i;\n  unsigned char result[MD5_DIGEST_LENGTH];\n\n  MD5(string, strlen(string), result);\n\n  \/\/ output\n  for(i = 0; i < MD5_DIGEST_LENGTH; i++)\n    printf(\"%02x\", result[i]);\n  printf(\"\\n\");\n\n  return EXIT_SUCCESS;\n}\n\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <math.h>\n\ntypedef union uwb {\n    unsigned w;\n    unsigned char b[4];\n} WBunion;\n\ntypedef unsigned Digest[4];\n\nunsigned f0( unsigned abcd[] ){\n    return ( abcd[1] & abcd[2]) | (~abcd[1] & abcd[3]);}\n\nunsigned f1( unsigned abcd[] ){\n    return ( abcd[3] & abcd[1]) | (~abcd[3] & abcd[2]);}\n\nunsigned f2( unsigned abcd[] ){\n    return  abcd[1] ^ abcd[2] ^ abcd[3];}\n\nunsigned f3( unsigned abcd[] ){\n    return abcd[2] ^ (abcd[1] |~ abcd[3]);}\n\ntypedef unsigned (*DgstFctn)(unsigned a[]);\n\nunsigned *calcKs( unsigned *k)\n{\n    double s, pwr;\n    int i;\n\n    pwr = pow( 2, 32);\n    for (i=0; i<64; i++) {\n        s = fabs(sin(1+i));\n        k[i] = (unsigned)( s * pwr );\n    }\n    return k;\n}\n\n\/\/ ROtate v Left by amt bits\nunsigned rol( unsigned v, short amt )\n{\n    unsigned  msk1 = (1<<amt) -1;\n    return ((v>>(32-amt)) & msk1) | ((v<<amt) & ~msk1);\n}\n\nunsigned *md5( const char *msg, int mlen) \n{\n    static Digest h0 = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476 };\n\/\/    static Digest h0 = { 0x01234567, 0x89ABCDEF, 0xFEDCBA98, 0x76543210 };\n    static DgstFctn ff[] = { &f0, &f1, &f2, &f3 };\n    static short M[] = { 1, 5, 3, 7 };\n    static short O[] = { 0, 1, 5, 0 };\n    static short rot0[] = { 7,12,17,22};\n    static short rot1[] = { 5, 9,14,20};\n    static short rot2[] = { 4,11,16,23};\n    static short rot3[] = { 6,10,15,21};\n    static short *rots[] = {rot0, rot1, rot2, rot3 };\n    static unsigned kspace[64];\n    static unsigned *k;\n\n    static Digest h;\n    Digest abcd;\n    DgstFctn fctn;\n    short m, o, g;\n    unsigned f;\n    short *rotn;\n    union {\n        unsigned w[16];\n        char     b[64];\n    }mm;\n    int os = 0;\n    int grp, grps, q, p;\n    unsigned char *msg2;\n\n    if (k==NULL) k= calcKs(kspace);\n\n    for (q=0; q<4; q++) h[q] = h0[q];   \/\/ initialize\n\n    {\n        grps  = 1 + (mlen+8)\/64;\n        msg2 = malloc( 64*grps);\n        memcpy( msg2, msg, mlen);\n        msg2[mlen] = (unsigned char)0x80;  \n        q = mlen + 1;\n        while (q < 64*grps){ msg2[q] = 0; q++ ; }\n        {\n\/\/            unsigned char t;\n            WBunion u;\n            u.w = 8*mlen;\n\/\/            t = u.b[0]; u.b[0] = u.b[3]; u.b[3] = t;\n\/\/            t = u.b[1]; u.b[1] = u.b[2]; u.b[2] = t;\n            q -= 8;\n            memcpy(msg2+q, &u.w, 4 );\n        }\n    }\n\n    for (grp=0; grp<grps; grp++)\n    {\n        memcpy( mm.b, msg2+os, 64);\n        for(q=0;q<4;q++) abcd[q] = h[q];\n        for (p = 0; p<4; p++) {\n            fctn = ff[p];\n            rotn = rots[p];\n            m = M[p]; o= O[p];\n            for (q=0; q<16; q++) {\n                g = (m*q + o) % 16;\n                f = abcd[1] + rol( abcd[0]+ fctn(abcd) + k[q+16*p] + mm.w[g], rotn[q%4]);\n\n                abcd[0] = abcd[3];\n                abcd[3] = abcd[2];\n                abcd[2] = abcd[1];\n                abcd[1] = f;\n            }\n        }\n        for (p=0; p<4; p++)\n            h[p] += abcd[p];\n        os += 64;\n    }\n\n    if( msg2 )\n        free( msg2 );\n\n    return h;\n}    \n\nint main( int argc, char *argv[] )\n{\n    int j,k;\n    const char *msg = \"The quick brown fox jumps over the lazy dog.\";\n    unsigned *d = md5(msg, strlen(msg));\n    WBunion u;\n\n    printf(\"= 0x\");\n    for (j=0;j<4; j++){\n        u.w = d[j];\n        for (k=0;k<4;k++) printf(\"%02x\",u.b[k]);\n    }\n    printf(\"\\n\");\n\n    return 0;\n}\n\n","human_summarization":"implement the MD5 algorithm to encode a string. They also optionally validate the implementation using test values from IETF RFC 1321. The codes also consider the known weaknesses of MD5 and suggest using stronger alternatives for production-grade cryptography. The solution might be a library solution, and differences may be observed for the last 8 characters when compared with the openssl implementation.","id":3554}
    {"lang_cluster":"C","source_code":"\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\ntypedef struct oid_tag {\n    char* str_;\n    int* numbers_;\n    int length_;\n} oid;\n\n\/\/ free memory, no-op if p is null\nvoid oid_destroy(oid* p) {\n    if (p != 0) {\n        free(p->str_);\n        free(p->numbers_);\n        free(p);\n    }\n}\n\nint char_count(const char* str, char ch) {\n    int count = 0;\n    for (const char* p = str; *p; ++p) {\n        if (*p == ch)\n            ++count;\n    }\n    return count;\n}\n\n\/\/ construct an OID from a string\n\/\/ returns 0 on memory allocation failure or parse error\noid* oid_create(const char* str) {\n    oid* ptr = calloc(1, sizeof(oid));\n    if (ptr == 0)\n        return 0;\n    ptr->str_ = strdup(str);\n    if (ptr->str_ == 0) {\n        oid_destroy(ptr);\n        return 0;\n    }\n    int dots = char_count(str, '.');\n    ptr->numbers_ = malloc(sizeof(int) * (dots + 1));\n    if (ptr->numbers_ == 0) {\n        oid_destroy(ptr);\n        return 0;\n    }\n    ptr->length_ = dots + 1;\n    const char* p = str;\n    for (int i = 0; i <= dots && *p;) {\n        char* eptr = 0;\n        int num = strtol(p, &eptr, 10);\n        if (*eptr != 0 && *eptr != '.') {\n            \/\/ TODO: check for overflow\/underflow\n            oid_destroy(ptr);\n            return 0;\n        }\n        ptr->numbers_[i++] = num;\n        p = eptr;\n        if (*p)\n            ++p;\n    }\n    return ptr;\n}\n\n\/\/ compare two OIDs\nint oid_compare(const void* p1, const void* p2) {\n    const oid* o1 = *(oid* const*)p1;\n    const oid* o2 = *(oid* const*)p2;\n    int i1 = 0, i2 = 0;\n    for (; i1 < o1->length_ && i2 < o2->length_; ++i1, ++i2) {\n        if (o1->numbers_[i1] < o2->numbers_[i2])\n            return -1;\n        if (o1->numbers_[i1] > o2->numbers_[i2])\n            return 1;\n    }\n    if (o1->length_ < o2->length_)\n        return -1;\n    if (o1->length_ > o2->length_)\n        return 1;\n    return 0;\n}\n\nint main() {\n    const char* input[] = {\n        \"1.3.6.1.4.1.11.2.17.19.3.4.0.10\",\n        \"1.3.6.1.4.1.11.2.17.5.2.0.79\",\n        \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\",\n        \"1.3.6.1.4.1.11150.3.4.0.1\",\n        \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\",\n        \"1.3.6.1.4.1.11150.3.4.0\"\n    };\n    const int len = sizeof(input)\/sizeof(input[0]);\n    oid* oids[len];\n    memset(oids, 0, sizeof(oids));\n    int i;\n    for (i = 0; i < len; ++i) {\n        oids[i] = oid_create(input[i]);\n        if (oids[i] == 0)\n        {\n            fprintf(stderr, \"Out of memory\\n\");\n            goto cleanup;\n        }\n    }\n    qsort(oids, len, sizeof(oid*), oid_compare);\n    for (i = 0; i < len; ++i)\n        puts(oids[i]->str_);\ncleanup:\n    for (i = 0; i < len; ++i)\n        oid_destroy(oids[i]);\n    return 0;\n}\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs). OIDs are strings consisting of one or more non-negative integers separated by dots. The sorting is done lexicographically based on the dot-separated fields using numeric comparison. A C99 or later compiler is required for this task.","id":3555}
    {"lang_cluster":"C","source_code":"\nWorks with: POSIX version .1-2001\nWorks with: gcc version 4.2.2\n\n#include <stdio.h>\n#include <string.h>\n#include <sys\/types.h>\n#include <sys\/socket.h>\n#include <netdb.h>\n\nconst char *msg = \"hello socket world\";\n\nint main()\n{\n   int i, sock, len, slen;\n\n   struct addrinfo hints, *addrs;  \n   memset(&hints, 0, sizeof(struct addrinfo));\n   hints.ai_family = AF_UNSPEC;\n   hints.ai_socktype = SOCK_STREAM;\n   \n   if (0 == getaddrinfo(\"localhost\", \"256\", &hints, &addrs))\n   {\n       sock = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol);\n       if ( sock >= 0 )\n       {\n           if ( connect(sock, addrs->ai_addr, addrs->ai_addrlen) >= 0 )\n           {\n               const char *pm = msg;\n               do\n               {\n                  len = strlen(pm);\n                  slen = send(sock, pm, len, 0);\n                  pm += slen;\n               } while ((0 <= slen) && (slen < len));\n           }\n           close(sock);\n       }\n       freeaddrinfo(addrs);\n   }\n}\n\n","human_summarization":"Open a socket to localhost on port 256, send the message \"hello socket world\", and then close the socket. The code may also be adaptable for MS Windows.","id":3556}
    {"lang_cluster":"C","source_code":"\n\nLibrary: libcurl\n#include <curl\/curl.h>\n#include <string.h>\n#include <stdio.h>\n\n#define from    \"<sender@duniya.com>\"\n#define to      \"<addressee@gmail.com>\"\n#define cc      \"<info@example.org>\"\n \nstatic const char *payload_text[] = {\n  \"Date: Mon, 13 Jun 2018 11:30:00 +0100\\r\\n\",\n  \"To: \" to \"\\r\\n\",\n  \"From: \" from \" (Example User)\\r\\n\",\n  \"Cc: \" cc \" (Another example User)\\r\\n\",\n  \"Message-ID: <ecd7db36-10ab-437a-9g3a-e652b9458efd@\"\n  \"rfcpedant.example.org>\\r\\n\",\n  \"Subject: Sanding mail via C\\r\\n\",\n  \"\\r\\n\",\n  \"This mail is being sent by a C program.\\r\\n\",\n  \"\\r\\n\",\n  \"It connects to the GMail SMTP server, by far, the most popular mail program of all.\\r\\n\",\n  \"Which is also probably written in C.\\r\\n\",\n  \"To C or not to C..............\\r\\n\",\n  \"That is the question.\\r\\n\",\n  NULL\n};\n \nstruct upload_status {\n  int lines_read;\n};\n \nstatic size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp)\n{\n  struct upload_status *upload_ctx = (struct upload_status *)userp;\n  const char *data;\n \n  if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) {\n    return 0;\n  }\n \n  data = payload_text[upload_ctx->lines_read];\n \n  if(data) {\n    size_t len = strlen(data);\n    memcpy(ptr, data, len);\n    upload_ctx->lines_read++;\n \n    return len;\n  }\n \n  return 0;\n}\n \nint main(void)\n{\n  CURL *curl;\n  CURLcode res = CURLE_OK;\n  struct curl_slist *recipients = NULL;\n  struct upload_status upload_ctx;\n \n  upload_ctx.lines_read = 0;\n \n  curl = curl_easy_init();\n  if(curl) {\n\n    curl_easy_setopt(curl, CURLOPT_USERNAME, \"user\");\n    curl_easy_setopt(curl, CURLOPT_PASSWORD, \"secret\");\n\n    curl_easy_setopt(curl, CURLOPT_URL, \"smtp:\/\/smtp.gmail.com:465\");\n\n    curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL);\n \n    curl_easy_setopt(curl, CURLOPT_CAINFO, \"\/path\/to\/certificate.pem\");\n\n    curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from);\n\n    recipients = curl_slist_append(recipients, to);\n    recipients = curl_slist_append(recipients, cc);\n    curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients);\n\n    curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source);\n    curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx);\n    curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);\n\n    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);\n\n    res = curl_easy_perform(curl);\n\n    if(res != CURLE_OK)\n      fprintf(stderr, \"curl_easy_perform() failed: %s\\n\",curl_easy_strerror(res));\n\n    curl_slist_free_all(recipients);\n\n    curl_easy_cleanup(curl);\n  }\n \n  return (int)res;\n}\n\n","human_summarization":"The code sends an email using a function that takes parameters for From, To, Cc addresses, Subject, message text, and optionally server name and login details. It uses the GMail SMTP server and requires libcurl library. The code also handles notifications for problems\/success and is portable across different operating systems. Sensitive data used in examples is obfuscated.","id":3557}
    {"lang_cluster":"C","source_code":"\n#include <stdio.h>\n\nint main()\n{\n        unsigned int i = 0;\n        do { printf(\"%o\\n\", i++); } while(i);\n        return 0;\n}\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":3558}
    {"lang_cluster":"C","source_code":"\n\nvoid swap(void *va, void *vb, size_t s)\n{\n  char t, *a = (char*)va, *b = (char*)vb;\n  while(s--)\n    t = a[s], a[s] = b[s], b[s] = t;\n}\n\nWorks with: gcc\n\nCaution: __typeof__ is a gcc extension, not part of standard C. __typeof__ does not conflict with C89 because the standard allows compilers to add keywords with underscores like __typeof__.\n#define Swap(X,Y)  do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0)\n\n\n#include <stdio.h>\n\n#define Swap(X,Y)  do{ __typeof__ (X) _T = X; X = Y; Y = _T; }while(0)\n\nstruct test\n{\n  int a, b, c;\n};\n\n\nint main()\n{\n  struct test t = { 1, 2, 3 };\n  struct test h = { 4, 5, 6 };\n  double alfa = 0.45, omega = 9.98;\n  \n  struct test *pt = &t;\n  struct test *th = &h;\n  \n  printf(\"%d %d %d\\n\", t.a, t.b, t.c );\n  Swap(t, h);\n  printf(\"%d %d %d\\n\", t.a, t.b, t.c );\n  printf(\"%d %d %d\\n\", h.a, h.b, h.c );\n  \n  printf(\"%lf\\n\", alfa);\n  Swap(alfa, omega);\n  printf(\"%lf\\n\", alfa);\n  \n  printf(\"%d\\n\", pt->a);\n  Swap(pt, th);\n  printf(\"%d\\n\", pt->a);\n}\n\n\n","human_summarization":"implement a generic swap function that exchanges the values of two variables of any type. The function ensures type compatibility between variables to prevent type violation. It handles issues related to programming language semantics, including challenges in dynamically typed languages and static languages with limited support for parametric polymorphism. The function also includes a restriction for variables to be of the same size and demonstrates usage with GCC using the -std=c89 option.","id":3559}
    {"lang_cluster":"C","source_code":"\n\n#include <string.h>\n\nint palindrome(const char *s)\n{\n   int i,l;\n   l = strlen(s);\n   for(i=0; i<l\/2; i++)\n   {\n     if ( s[i] != s[l-i-1] ) return 0; \n   }\n   return 1;\n}\n\n\nint palindrome(const char *s)\n{\n   const char *t; \/* t is a pointer that traverses backwards from the end *\/\n   for (t = s; *t != '\\0'; t++) ; t--; \/* set t to point to last character *\/\n   while (s < t)\n   {\n     if ( *s++ != *t-- ) return 0; \n   }\n   return 1;\n}\n\n\nint palindrome_r(const char *s, int b, int e)\n{\n   if ( (e - 1) <= b ) return 1;\n   if ( s[b] != s[e-1] ) return 0;\n   return palindrome_r(s, b+1, e-1);\n}\n\n\n#include <stdio.h>\n#include <string.h>\n\/* testing *\/\nint main()\n{\n   const char *t = \"ingirumimusnocteetconsumimurigni\";\n   const char *template = \"sequence \\\"%s\\\" is%s palindrome\\n\";\n   int l = strlen(t);\n   \n   printf(template,\n          t, palindrome(t) ? \"\" : \"n't\");\n   printf(template,\n          t, palindrome_r(t, 0, l) ? \"\" : \"n't\");\n   return 0;\n}\n\n","human_summarization":"The code includes a function that checks if a given sequence of characters is a palindrome. It supports Unicode characters and can detect inexact palindromes by ignoring white-space, punctuation, and case. The function compares each character from the start and end of the sequence until the middle. If all pairs are equal, it returns true; otherwise, it returns false. The code also includes a recursive version of the function that checks if the first and last characters are the same and if the remaining string is a palindrome.","id":3560}
    {"lang_cluster":"C","source_code":"\n#include <stdlib.h>\n#include <stdio.h>\n \nint main() {\n  puts(getenv(\"HOME\"));\n  puts(getenv(\"PATH\"));\n  puts(getenv(\"USER\"));\n  return 0;\n}\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":3561}
    {"lang_cluster":"C","source_code":"\/\/Aamrun, 11th July 2022\n\n#include <stdio.h>\n\nint F(int n,int x,int y) {\n  if (n == 0) {\n    return x + y;\n  }\n \n  else if (y == 0) {\n    return x;\n  }\n \n  return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y);\n}\n\nint main() {\n  printf(\"F1(3,3) = %d\",F(1,3,3));\n  return 0;\n}\n\n\nF1(3,3) = 35\n\n","human_summarization":"implement the Sudan function, a non-primitive recursive function. The function takes two parameters, x and y, and returns their sum if the recursion depth is zero. If the recursion depth is greater than zero and y is zero, it returns x. Otherwise, it recursively calls itself with updated parameters.","id":3562}
    {"lang_cluster":"X86_Assembly","source_code":"\n; x86_64 linux nasm\n\nstruc Stack\n  maxSize: resb 8\n  currentSize: resb 8\n  contents:\nendStruc\n\nsection .data\n\nsoError: db \"Stack Overflow Exception\", 10\nseError: db \"Stack Empty Error\", 10\n\n\nsection .text\n\ncreateStack:\n; IN: max number of elements (rdi)\n; OUT: pointer to new stack (rax)\n  push rdi\n  xor rdx, rdx\n  mov rbx, 8\n  mul rbx\n  mov rcx, rax\n  mov rax, 12\n  mov rdi, 0\n  syscall\n  push rax\n  mov rdi, rax\n  add rdi, rcx\n  mov rax, 12\n  syscall\n  pop rax\n  pop rbx\n  mov qword [rax + maxSize], rbx\n  mov qword [rax + currentSize], 0\n  ret\n\n\npush:\n; IN: stack to operate on (stack argument), element to push (rdi)\n; OUT: void\n  mov rax, qword [rsp + 8]\n  mov rbx, qword [rax + currentSize]\n  cmp rbx, qword [rax + maxSize]\n  je stackOverflow\n  lea rsi, [rax + contents + 8*rbx]\n  mov qword [rsi], rdi\n  add qword [rax + currentSize], 1\n  ret\n\n\npop:\n; pop\n; IN: stack to operate on (stack argument)\n; OUT: element from stack top\n  mov rax, qword [rsp + 8]\n  mov rbx, qword [rax + currentSize]\n  cmp rbx, 0\n  je stackEmpty\n  sub rbx, 1\n  lea rsi, [rax + contents + 8*rbx]\n  mov qword [rax + currentSize], rbx\n  mov rax, qword [rsi]\n  ret\n\n\n; stack operation exceptions\nstackOverflow:\n  mov rsi, soError\n  mov rdx, 25\n  jmp errExit\nstackEmpty:\n  mov rsi, seError\n  mov rdx, 18\nerrExit:\n  mov rax, 1\n  mov rdi, 1\n  syscall\n  mov rax, 60\n  mov rdi, 1\n  syscall\n","human_summarization":"implement a stack data structure with basic operations such as push (to add elements), pop (to remove and return the last added element), and empty (to check if the stack is empty). This stack follows a Last-In-First-Out (LIFO) access policy.","id":3563}
    {"lang_cluster":"X86_Assembly","source_code":"\n\nEAX - the youngest part of the transformed block (N1);\nEDX - leading part transformed block (N2);\nESI - address of the first element of the key;\nEBX - table address changes;\nECX - the number of major steps.\n\nEDX = N1, EAX = N2 for cycles 32-\u0417, 32-\u0420;\nEAX = N1, EDX = N2 for cycle 16-\u0417.\n\nAt the end of the run the registers as follows:\nEBX (pointer to table of changes) - the same as that in the early\nESI (pointer to key) - points to the first byte of the key - it's N * 4 larger than the initial values for the SI cycle reps N (for encryption cycles N = 32 => 4 * N = 128, for authentication code generation cycle N = 16 => 4 * N = 64), larger than the initial values for the authentication code generation cycle.\nECX = 0\nThe contents of the segment registers unchanged.\n        .386\n        .model  flat\n        .code\n_gost32 proc    near32\n        public  _gost32\n; The inner loop of a subroutine\n; 1. Beginning of the cycle, and preservation of the old N1\niloop:  mov     EBP,EAX\n; 2. Adding to the S key modulo 2^32\n        add     EAX,[ESI] ; add the key\n        add     ESI,4   ; the next element of the key.\n; 3. Block-replace in the rotation of S by 8 bits to the left\nREPT    3\n        xlat            ; recoding byte\n        ror     EAX,8   ; AL <- next byte\n        add     EBX,100h; next node changes\nENDM\n        xlat            ; recoding byte\n        sub     EBX,300h; BX -> 1st node changes\n; 4. Complete rotation of the S at 3 bits to the left\n        rol     EAX,3\n; 5. The calculation of the new values of N1,N2\n        xor     EAX,EDX\n        mov     EDX,EBP\n; The completion of the inner loop\n        loop    iloop\n        ret\n_gost32 endp\n        end\n\n","human_summarization":"implement the main step of the GOST 28147-89 encryption algorithm. This involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table (8x16 matrix of 4-bit values), and returning an encrypted block. The code does not use the EDI register.","id":3564}
    {"lang_cluster":"X86_Assembly","source_code":"\nsection .text\n\tglobal _start\n\t\n\t_print:\n\t\tmov ebx, 1\n\t\tmov eax, 4\n\t\tint 0x80\n\t\tret\n\t\t\n\t_start:\n\t\t;print out our byte array. ergo, String.\n\t\tmov edx, sLen\n\t\tmov ecx, sArray\n\t\tcall _print\n\t\tmov edx, f_len\n\t\tmov ecx, f_msg\n\t\tcall _print\n\t\tmov edx, 6\t\t\t;our array members length.\n\t\txor ecx, ecx\n\t\tmov ecx, 4\n\t\t;turnicate through the array and print all it's members.\n\t\t;At an offset of *4, each array member is referenced\n\t\t;at 1,2,3 and so on. \n\t\t_out_loops:\n\t\t\tpush ecx\n\t\t\tmov ecx, [fArray+esi*4]\n\t\t\tcall _print\n\t\t\tinc esi\n\t\t\tpop ecx\n\t\tloop _out_loops\n\t\tmov edx, u_len\n\t\tmov ecx, u_msg\n\t\tcall _print\n\t\t;Let's populate 'uArray' with something from sArray.\n\t\t;mov edi, uArray\n\t\tmov ecx, 4\n\t\txor esi, esi\n\t\t_read_loops:\t\n\t\t\tpush dword [fArray+esi*4]\n\t\t\tpop dword [uArray+esi*4]\n\t\t\tinc esi\n\t\tloop _read_loops\n\t\tmov ecx, 4\n\t\txor esi, esi\n\t\t_out_loops2:\n\t\t\tpush ecx\n\t\t\tmov ecx, [uArray+esi*4]\n\t\t\tcall _print\n\t\t\tinc esi\n\t\t\tpop ecx\n\t\tloop _out_loops2\n\t\tpush 0x1\n\t\tmov eax, 1\n\t\tpush eax\n\t\tint 0x80\n\t\t\nsection .data\nsArray\tdb 'a','r','r','a','y','s',' ','a','r','e',' ','f','u','n',0xa\nsLen\t\tequ $-sArray\n\ncrap1\t\tdb \"crap1\",0xa\ncrap2\t\tdb \"crap2\",0xa\ncrap3\t\tdb \"crap3\",0xa\ncrap4\t\tdb \"crap4\",0xa\n\nfArray\tdd crap1,crap2\n\tdd crap3,crap4\n\nf_msg\t\tdb \"fArray contents\",0xa,\"----------------------\",0xa\nf_len\t\tequ $-f_msg\nu_msg\t\tdb \"uArray now holds fArray contents.. dumping..\",0xa,\"----------------------\",0xa\nu_len\t\tequ $-u_msg\n\nsection .bss\nuArray\tresd 1\n        resd 1\n\tresd 1\n\tresd 1\n\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. They include the creation of an array, assigning a value to it, and retrieving an element from it. The codes also showcase the use of both fixed-length and dynamic arrays, and the process of pushing a value into the array. The codes do not support multidimensional arrays in assembly, instead, they use a specific format to reference one. The functionality of the codes is discussed in the Village Pump: Arrays. The codes also integrate elements from obsolete tasks such as creating an array, assigning values to an array, and retrieving an element of an array.","id":3565}
    {"lang_cluster":"X86_Assembly","source_code":"\n%define TRUE 1\n%define FALSE 0\n\nglobal main,foursquares,acd,ge,bf,print_output\nextern printf\n\nsegment .data\n\na dq 0\nb dq 0\nc dq 0\nd dq 0\ne dq 0\nf dq 0\ng dq 0\n\nlo dq 0\nhi dq 0\nunique dq 0\nshow dq 0\nsolutions dq 0\n\noutput_fmt db `%ld %ld %ld %ld %ld %ld %ld\n`,0\n\nsegment .text\n\nmain:                            \n    push rbp                     \n    mov rbp,rsp                 \n\n    mov rdi,1\n    mov rsi,7\n    mov rdx,TRUE\n    mov rcx,TRUE\n    call foursquares\n\n    mov rdi,3\n    mov rsi,9\n    mov rdx,TRUE\n    mov rcx,TRUE\n    call foursquares\n\n    mov rdi,0\n    mov rsi,9\n    mov rdx,FALSE\n    mov rcx,FALSE\n    call foursquares\n\n    xor rax,rax                  \n    leave                       \n    ret   \n    \nsegment .data\n\nnewlinefmt db `\n`,0\nuniquefmt db `\n%ld unique solutions in %ld to %ld\n`,0\nnonuniquefmt db `\n%ld non-unique solutions in %ld to %ld\n`,0\n\nsegment .text\n\nfoursquares:                             \n    push rbp                     \n    mov rbp,rsp\n    \n    mov qword [lo],rdi\n    mov qword [hi],rsi\n    mov qword [unique],rdx\n    mov qword [show],rcx\n    mov qword [solutions],0\n    \n    lea rdi,[newlinefmt]\n    xor rax,rax\n    call printf\n    \n    call acd\n    \n    mov rax,qword [unique]\n    mov rbx,TRUE\n    cmp rax,rbx\n    je .isunique\n    \n    lea rdi,[nonuniquefmt]\n    mov rsi,qword [solutions]\n    mov rdx,qword [lo]\n    mov rcx,qword [hi]\n    xor rax,rax\n    call printf\n    jmp .done\n    \n.isunique:\n    lea rdi,[uniquefmt]\n    mov rsi,qword [solutions]\n    mov rdx,qword [lo]\n    mov rcx,qword [hi]\n    xor rax,rax\n    call printf\n    \n.done:\n    xor rax,rax                  \n    leave                        \n    ret  \n    \nsegment .text\n\nacd:                             \n    push rbp                     \n    mov rbp,rsp\n    \n    mov rax,qword [lo] ; c = lo\n    mov qword [c],rax \n\n.nextouterfor:\n    mov rax,qword [c]  ; c <= hi\n    mov rcx,qword [hi] \n    cmp rax,rcx\n    jg .doneouterfor\n    \n    mov rax,qword [lo] ; d = lo\n    mov qword [d],rax \n    \n.nextinnerfor:\n    mov rax,qword [d]  ; d <= hi\n    mov rcx,qword [hi] \n    cmp rax,rcx\n    jg .doneinnerfor\n    \n    mov rax,qword [unique]\n    mov rcx,FALSE\n    cmp rax,rcx\n    je .inif\n    \n    mov rax,qword [c]\n    mov rcx,qword [d]\n    cmp rax,rcx\n    jne .inif\n    jmp .iffails\n    \n.inif: \n    mov rax,qword [c]\n    mov rcx,qword [d]\n    add rax,rcx\n    mov qword [a],rax\n    \n; ((a >= lo) && \n;  (a <= hi) &&\n;  ((!unique) || \n;   ((c != 0) && \n;    (d != 0)\n;   )\n;  )\n; )\n    mov rax,qword [a]  ;(a >= lo)\n    mov rcx,qword [lo]\n    cmp rax,rcx\n    jl .iffails\n    \n    mov rax,qword [a]  ;(a <= hi)\n    mov rcx,qword [hi]\n    cmp rax,rcx\n    jg .iffails\n    \n    mov rax,qword [unique] ;(!unique)\n    mov rcx,FALSE\n    cmp rax,rcx\n    je .ifsucceeds\n\n    mov rax,qword [c]  ;(c != 0)\n    mov rcx,0\n    cmp rax,rcx\n    je .iffails\n    \n    mov rax,qword [d]  ;(d != 0)\n    mov rcx,0\n    cmp rax,rcx\n    je .iffails\n\n.ifsucceeds:\n\n    call ge\n    \n.iffails:\n    mov rax,qword [d] ; d++\n    inc rax\n    mov qword [d],rax\n    jmp .nextinnerfor\n\n.doneinnerfor:\n    mov rax,qword [c] ; c++\n    inc rax\n    mov qword [c],rax\n    jmp .nextouterfor\n   \n.doneouterfor:\n    xor rax,rax                  \n    leave                        \n    ret    \n    \nge:                              \n    push rbp                     \n    mov rbp,rsp\n    \n    mov rax,qword [lo] ; e = lo\n    mov qword [e],rax \n\n.nextfor:\n    mov rax,qword [e]  ; e <= hi\n    mov rcx,qword [hi] \n    cmp rax,rcx\n    jg .donefor\n    \n    mov rax,qword [unique]\n    mov rcx,FALSE\n    cmp rax,rcx\n    je .inif\n \n; ((e != a) && (e != c) && (e != d))\n\n    mov rax,qword [e]\n    \n    mov rcx,qword [a] ; (e != a)\n    cmp rax,rcx\n    je .skipif\n    \n    mov rcx,qword [c] ; (e != c)\n    cmp rax,rcx\n    je .skipif\n    \n    mov rcx,qword [d] ; (e != d)\n    cmp rax,rcx\n    je .skipif\n    \n.inif: \n    mov rax,qword [d] ; g = d + e\n    mov rcx,qword [e]\n    add rax,rcx\n    mov qword [g],rax\n\n; ((g >= lo) &&\n;  (g <= hi) &&\n;  ((!unique) || \n;   ((g != a) && \n;    (g != c) &&\n;    (g != d) && \n;    (g != e)\n;   )\n;  )\n; )    \n\n    mov rax,qword [g]  ;(g >= lo)\n    mov rcx,qword [lo]\n    cmp rax,rcx\n    jl .skipif\n    \n    mov rax,qword [g]  ;(g <= hi)\n    mov rcx,qword [hi]\n    cmp rax,rcx\n    jg .skipif\n    \n    mov rax,qword [unique] ;(!unique)\n    mov rcx,FALSE\n    cmp rax,rcx\n    je .innerifsucceeds\n\n    mov rax,qword [g]  ;(g != a)\n    mov rcx,qword [a]\n    cmp rax,rcx\n    je .skipif\n\n    mov rcx,qword [c]  ;(g != c)\n    cmp rax,rcx\n    je .skipif\n\n    mov rcx,qword [d]  ;(g != d)\n    cmp rax,rcx\n    je .skipif\n\n    mov rcx,qword [e]  ;(g != e)\n    cmp rax,rcx\n    je .skipif\n\n.innerifsucceeds:\n    call bf\n    \n.skipif:\n    mov rax,qword [e] ; e++\n    inc rax\n    mov qword [e],rax\n    jmp .nextfor\n   \n.donefor:\n    xor rax,rax                  \n    leave                        \n    ret   \n    \nsegment .text\n    \nbf:                              \n    push rbp                     \n    mov rbp,rsp\n    \n    mov rax,qword [lo] ; f = lo\n    mov qword [f],rax \n\n.nextfor:\n    mov rax,qword [f]  ; f <= hi\n    mov rcx,qword [hi] \n    cmp rax,rcx\n    jg .donefor\n    \n    mov rax,qword [unique]\n    mov rcx,FALSE\n    cmp rax,rcx\n    je .inif\n \n; ((f != a) && (f != c) && (f != d) && (f != g) && (f != e))\n\n    mov rax,qword [f]\n    \n    mov rcx,qword [a] ; (f != a)\n    cmp rax,rcx\n    je .skipif\n    \n    mov rcx,qword [c] ; (f != c)\n    cmp rax,rcx\n    je .skipif\n    \n    mov rcx,qword [d] ; (f != d)\n    cmp rax,rcx\n    je .skipif\n    \n    mov rcx,qword [g] ; (f != g)\n    cmp rax,rcx\n    je .skipif\n    \n    mov rcx,qword [e] ; (f != e)\n    cmp rax,rcx\n    je .skipif\n    \n.inif: \n    mov rax,qword [e] ; b = e + f - c;\n    mov rcx,qword [f]\n    add rax,rcx\n    mov rcx,qword [c]\n    sub rax,rcx\n    mov qword [b],rax\n\n; ((b >= lo) &&\n;  (b <= hi) &&\n;  ((!unique) || \n;   ((b != a) && \n;    (b != c) &&\n;    (b != d) && \n;    (b != g) && \n;    (b != e) && \n;    (b != f)\n;   )\n;  )\n; ) \n\n    mov rax,qword [b]  ;(b >= lo)\n    mov rcx,qword [lo]\n    cmp rax,rcx\n    jl .skipif\n    \n    mov rax,qword [b]  ;(b <= hi)\n    mov rcx,qword [hi]\n    cmp rax,rcx\n    jg .skipif\n    \n    mov rax,qword [unique] ;(!unique)\n    mov rcx,FALSE\n    cmp rax,rcx\n    je .innerifsucceeds\n\n    mov rax,qword [b]  ;(b != a)\n    mov rcx,qword [a]\n    cmp rax,rcx\n    je .skipif\n\n    mov rcx,qword [c]  ;(b != c)\n    cmp rax,rcx\n    je .skipif\n\n    mov rcx,qword [d]  ;(b != d)\n    cmp rax,rcx\n    je .skipif\n\n    mov rcx,qword [g]  ;(b != g)\n    cmp rax,rcx\n    je .skipif\n\n    mov rcx,qword [e]  ;(b != e)\n    cmp rax,rcx\n    je .skipif\n\n    mov rcx,qword [f]  ;(b != f)\n    cmp rax,rcx\n    je .skipif\n\n.innerifsucceeds:\n    mov rax,qword [solutions] ; solutions++\n    inc rax\n    mov qword [solutions],rax\n    \n    mov rax,qword [show]\n    cmp rax,TRUE\n    jne .skipif\n   \n    call print_output\n    \n.skipif:\n    mov rax,qword [f] ; f++\n    inc rax\n    mov qword [f],rax\n    jmp .nextfor\n   \n.donefor:\n    xor rax,rax                  \n    leave                        \n    ret   \n    \nprint_output:                            \n    push rbp                     \n    mov rbp,rsp\n        \n\n; printf(\"%d %d %d %d %d %d %d\n\",a,b,c,d,e,f,g);\n    \n    lea rdi,[output_fmt]\n    mov rsi,qword [a]\n    mov rdx,qword [b]\n    mov rcx,qword [c]\n    mov r8,qword [d]\n    mov r9,qword [e]\n    mov rax,qword [g]\n    push rax\n    mov rax,qword [f]\n    push rax\n    xor rax,rax\n    call printf\n    \n    xor rax,rax                  \n    leave                        \n    ret\n","human_summarization":"The code replaces the variables a, b, c, d, e, f, and g with decimal digits from a given range (LOW to HIGH) to make the sum of variables in each of the four large squares equal. It generates all unique solutions for ranges 1-7 and 3-9, and counts the number of solutions (including non-unique) for the range 0-9. It also includes a solution for a related no connection puzzle.","id":3566}
    {"lang_cluster":"X86_Assembly","source_code":"\n\n        .MODEL  TINY\n        .CODE\n        .486\n        ORG     100H            ;.COM FILES START HERE\nYEAR    EQU     1969            ;DISPLAY CALENDAR FOR SPECIFIED YEAR\nSTART:  MOV     CX, 61          ;SPACE(61);  TEXT(0, \"[SNOOPY]\");  CRLF(0)\n        CALL    SPACE\n        MOV     DX, OFFSET SNOOPY\n        CALL    TEXT\n        MOV     CL, 63          ;SPACE(63);  INTOUT(0, YEAR);  CRLF(0);  CRLF(0)\n        CALL    SPACE\n        MOV     AX, YEAR\n        CALL    INTOUT\n        CALL    CRLF\n        CALL    CRLF\n\n        MOV     DI, 1           ;FOR MONTH:= 1 TO 12 DO         DI=MONTH\nL22:    XOR     SI, SI          ; FOR COL:= 0 TO 6-1 DO         SI=COL\nL23:    MOV     CL, 5           ;  SPACE(5)\n        CALL    SPACE\n        MOV     DX, DI          ;  TEXT(0, MONAME(MONTH+COL-1));  SPACE(7);\n        DEC     DX              ;  DX:= (MONTH+COL-1)*10+MONAME\n        ADD     DX, SI\n        IMUL    DX, 10\n        ADD     DX, OFFSET MONAME\n        CALL    TEXT\n        MOV     CL, 7\n        CALL    SPACE\n        CMP     SI, 5           ;  IF COL<5 THEN SPACE(1);\n        JGE     L24\n         MOV    CL, 1\n         CALL   SPACE\n         INC    SI\n         JMP    L23\nL24:    CALL    CRLF\n\n        MOV     SI, 6           ; FOR COL:= 0 TO 6-1 DO\nL25:    MOV     DX, OFFSET SUMO ;  TEXT(0, \"SU MO TU WE TH FR SA\");\n        CALL    TEXT\n        DEC     SI              ;   IF COL<5 THEN SPACE(2);\n        JE      L27\n         MOV    CL, 2\n         CALL   SPACE\n         JMP    L25\nL27:    CALL    CRLF\n\n        XOR     SI, SI          ;FOR COL:= 0 TO 6-1 DO\nL28:    MOV     BX, DI          ;DAY OF FIRST SUNDAY OF MONTH (CAN BE NEGATIVE)\n        ADD     BX, SI          ;DAY(COL):= 1 - WEEKDAY(YEAR, MONTH+COL, 1);\n        MOV     BP, YEAR\n\n;DAY OF WEEK FOR FIRST DAY OF THE MONTH (0=SUN 1=MON..6=SAT)\n        CMP     BL, 2           ;IF MONTH<=2 THEN\n        JG      L3\n         ADD    BL, 12          ; MONTH:= MONTH+12;\n         DEC    BP              ; YEAR:= YEAR-1;\nL3:\n;REM((1-1 + (MONTH+1)*26\/10 + YEAR + YEAR\/4 + YEAR\/100*6 + YEAR\/400)\/7)\n        INC     BX              ;MONTH\n        IMUL    AX, BX, 26\n        MOV     CL, 10\n        CWD\n        IDIV    CX\n        MOV     BX, AX\n        MOV     AX, BP          ;YEAR\n        ADD     BX, AX\n        SHR     AX, 2\n        ADD     BX, AX\n        MOV     CL, 25\n        CWD\n        IDIV    CX\n        IMUL    DX, AX, 6       ;YEAR\/100*6\n        ADD     BX, DX\n        SHR     AX, 2           ;YEAR\/400\n        ADD     AX, BX\n        MOV     CL, 7\n        CWD\n        IDIV    CX\n        NEG     DX\n        INC     DX\n        MOV     [SI+DAY], DL    ;COL+DAY\n        INC     SI\n        CMP     SI, 5\n        JLE     L28\n\n        MOV     BP, 6           ;FOR LINE:= 0 TO 6-1 DO         BP=LINE\nL29:    XOR     SI, SI          ; FOR COL:= 0 TO 6-1 DO         SI=COL\nL30:    MOV     BX, DI          ;  DAYMAX:= DAYS(MONTH+COL);\n        MOV     BL, [BX+SI+DAYS]\n\n;IF MONTH+COL=2 & (REM(YEAR\/4)=0 & REM(YEAR\/100)#0\u00a0! REM(YEAR\/400)=0) THEN\n        MOV     AX, DI          ;MONTH\n        ADD     AX, SI\n        CMP     AL, 2\n        JNE     L32\n        MOV     AX, YEAR\n        TEST    AL, 03H\n        JNE     L32\n        MOV     CL,100\n        CWD\n        IDIV    CX\n        TEST    DX, DX\n        JNE     L31\n        TEST    AL, 03H\n        JNE     L32\nL31:     INC    BX              ;IF FEBRUARY AND LEAP YEAR THEN ADD A DAY\nL32:\n        MOV     DX, 7           ;FOR WEEKDAY:= 0 TO 7-1 DO\nL33:    MOVZX   AX, [SI+DAY]    ; IF DAY(COL)>=1 & DAY(COL)<=DAYMAX THEN\n        CMP     AL, 1\n        JL      L34\n        CMP     AL, BL\n        JG      L34\n        CALL    INTOUT          ; INTOUT(0, DAY(COL));\n        CMP     AL, 10          ; IF DAY(COL)<10 THEN SPACE(1); LEFT JUSTIFY\n        JGE     L36\n         MOV    CL, 1\n         CALL   SPACE\n        JMP     L36\nL34:    MOV     CL, 2           ; ELSE SPACE(2);\n        CALL    SPACE           ; SUPPRESS OUT OF RANGE DAYS\nL36:    MOV     CL, 1           ; SPACE(1);\n        CALL    SPACE\n        INC     BYTE PTR [SI+DAY] ; DAY(COL):= DAY(COL)+1;\n        DEC     DX              ;NEXT WEEKDAY\n        JNE     L33\n\n        CMP     SI, 5           ;IF COL<5 THEN SPACE(1);\n        JGE     L37\n         MOV    CL, 1\n         CALL   SPACE\n         INC    SI\n         JMP    L30\nL37:    CALL    CRLF\n\n        DEC     BP              ;NEXT LINE DOWN\n        JNE     L29\n        CALL    CRLF\n\n        ADD     DI, 6           ;NEXT 6 MONTHS\n        CMP     DI, 12\n        JLE     L22\n        RET\n\n;DISPLAY POSITIVE INTEGER IN AX\nINTOUT: PUSHA\n        MOV     BX, 10\n        XOR     CX, CX\nNO10:   CWD\n        IDIV    BX\n        PUSH    DX\n        INC     CX\n        TEST    AX, AX\n        JNE     NO10\nNO20:   MOV     AH, 02H\n        POP     DX\n        ADD     DL, '0'\n        INT     21H\n        LOOP    NO20\n        POPA\n        RET\n\n;DISPLAY CX SPACE CHARACTERS\nSPACE:  PUSHA\nSP10:   MOV     AH, 02H\n        MOV     DL, 20H\n        INT     21H\n        LOOP    SP10\n        POPA\n        RET\n\n;START A NEW LINE\nCRLF:   MOV     DX, OFFSET LCRLF\n\n;DISPLAY STRING AT DX\nTEXT:   MOV     AH, 09H\n        INT     21H\n        RET\n\nSNOOPY  DB      \"[SNOOPY]\"\nLCRLF   DB      0DH, 0AH, '$'\nMONAME  DB      \" JANUARY $ FEBRUARY$  MARCH  $  APRIL  $   MAY   $   JUNE  $\"\n        DB      \"   JULY  $  AUGUST $SEPTEMBER$  OCTOBER$ NOVEMBER$ DECEMBER$\"\nSUMO    DB      \"SU MO TU WE TH FR SA$\"\nDAYS    DB      0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31\nDAY     DB      ?, ?, ?, ?, ?, ?\n        END     START\n\n\n","human_summarization":"The code provides an algorithm for a calendar task, formatted to fit a 132-character wide page, mimicking the style of 1969 era line printers. The entire code is written in uppercase, inspired by the practices of real programmers in the 1960s. It does not include Snoopy generation, instead, it outputs a placeholder. The code is assembled with TASM CALENDAR and TLINK \/t CALENDAR.","id":3567}
    {"lang_cluster":"X86_Assembly","source_code":"\nLibrary: GTK\nWorks with: NASM\n;GTK imports and defines etc.\n%define GTK_WINDOW_TOPLEVEL 0\n\nextern gtk_init\nextern gtk_window_new\nextern gtk_widget_show\nextern gtk_signal_connect\nextern gtk_main\nextern g_print\nextern gtk_main_quit\n\nbits 32\n\nsection .text\n\tglobal _main\n\t\n        ;exit signal\n\tsig_main_exit:\n\t\tpush exit_sig_msg\n\t\tcall g_print\n\t\tadd esp, 4\n\t\tcall gtk_main_quit\n\t\tret\n\t\t\n\t_main:\n\t\tmov ebp, esp\t\n\t\tsub esp, 8\n\t\tpush argv\n\t\tpush argc\n\t\tcall gtk_init\n\t\tadd esp, 8\t\t\t\t;stack alignment.\n\t\tpush GTK_WINDOW_TOPLEVEL\n\t\tcall gtk_window_new\n\t\tadd esp, 4\n\t\tmov [ebp-4], eax\t\t;ebp-4 now holds our GTKWindow pointer.\n\t\tpush 0\n\t\tpush sig_main_exit\n\t\tpush gtk_delete_event\n\t\tpush dword [ebp-4]\n\t\tcall gtk_signal_connect\n\t\tadd esp, 16\n\t\tpush dword [ebp-4]\n\t\tcall gtk_widget_show\n\t\tadd esp, 4\n\t\tcall gtk_main\t\n\t\t\nsection .data\n;sudo argv \nargc                dd 1\nargv                dd args\nargs                dd title   \n\t\t\t\t\t\t  dd 0\n                  \ntitle               db \"GTK Window\",0\ngtk_delete_event   db 'delete_event',0\nexit_sig_msg      db \"-> Rage quitting..\",10,0\n\nWorks with: MASM\n.586\n.model flat, stdcall\noption casemap:none\n\ninclude \/masm32\/include\/windows.inc\ninclude \/masm32\/include\/kernel32.inc\ninclude \/masm32\/include\/user32.inc\n\nincludelib \/masm32\/lib\/kernel32.lib\nincludelib \/masm32\/lib\/user32.lib\n\nWinMain proto :dword,:dword,:dword,:dword\n\n.data\n   ClassName db \"WndClass\",0\n   AppName   db \"Window!\",0\n.data? \n   hInstance   dd\u00a0?\n   CommandLine dd\u00a0?\n\n.code\nstart:\n   invoke GetModuleHandle, NULL\n   mov hInstance, eax\n   invoke GetCommandLine\n   mov CommandLine, eax\n   invoke WinMain, hInstance, NULL, CommandLine, SW_SHOWDEFAULT\n\n   WinMain proc hInst:dword, hPervInst:dword, CmdLine:dword, CmdShow:dword\n   LOCAL wc:WNDCLASSEX\n   LOCAL msg:MSG\n   LOCAL hwnd:HWND\n\n   wc.cbSize, sizeof WNDCLASSEX\n   wc.style, CS_HREDRAW or CS_VREDRAW\n   wc.lpfnWndPRoc, offset WndProc\n   wc.cbClsExtra,NULL\n   wc.cbWndExtra, NULL\n   push hInstance\n   pop wc.hInstance\n   mov wc.hbrBackground, COLOR_BTNFACE+1\n   mov wc.lpszMenuName NULL\n   mov wc.lpszClassName, offset ClassName\n   invoke LoadIcon, NULL, IDI_APPLICATION\n   mov wc.hIcon, eax\n   mov wc.hIconSm, eax\n   invoke LoadCursor, NULL, IDC_ARROW\n   mov wc.hCursor, eax\n   invoke RegisterClassEx, addr wc\n   invoke CreateWindowEx, NULL, addr ClassName, addr AppName, WS_OVERLAPPEDWINDOW, CS_USEDEFAULT, CW_USEDEFAUT,\\\n   CW_USEDEFAUT, CW_USEDEFAUT, NULL, NULL, hInst, NULL\n   mov hwnd, eax\n   invoke ShowWindow, hwnd, SW_SHOWNORMAL\n   invoke UpdateWindow, hwnd\n   .while TRUE\n      invoke GetMessage, addr msg, NULL, 0,0\n      .break .if (!eax)\n      invoke TranslateMessage, addr msg\n      invoke DispatchMessage, addr msg\n   .endw\n   mov eax, msg.wParam\n   ret\n   WinMain endp\n\n   WndProc proc hWnd:dword, uMsg:dword, wParam:dword, lParam:dword\n   mov eax, uMsg\n   .if eax==WM_DESTROY\n      invoke PostQuitMessage, NULL\n   .else\n      invoke DefWindowProc, hWnd, uMsg, wParam, lParam\n   .endif\n   xor eax, eax\n   ret\n   WndProc endp\nend start\n\n","human_summarization":"Create an empty GUI window that can respond to close requests.","id":3568}
    {"lang_cluster":"X86_Assembly","source_code":"\n\n\n; x86_64 Linux NASM\n; Linked_List_Definition.asm\n\n%ifndef LinkedListDefinition\n%define LinkedListDefinition\n\nstruc link\n  value: resd 1\n  next: resq 1\n  linkSize:\nendstruc\n\n%endif\n\nWorks with: NASM\nstruct link\n.next: resd 1\n.data: resd 1\nendstruc\n\n\nlink resb 16\n\n\nWorks with: MASM\nlink struct\nnext dd ?\ndata dd ?\nlink ends\n\nWorks with: FASM\nstruc link next,data\n{\n    .next dd next\n    .data dd data\n}\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a numeric data member and a mutable link to the next element. The code is part of the implementations for singly-linked list operations. The structure is thought of in terms of 16 bytes (2 dwords) due to the lack of native structures in ASM.","id":3569}
    {"lang_cluster":"X86_Assembly","source_code":"\nWorks with: nasm\nsection .bss \n    factorArr resd 250 ;big buffer against seg fault\n    \nsection .text\nglobal _main\n_main:\n    mov ebp, esp; for correct debugging\n    mov eax, 0x7ffffffe ;number of which we want to know the factors, max num this program works with\n    mov ebx, eax ;save eax\n    mov ecx, 1 ;n, factor we test for\n    mov [factorArr], dword 0\n    looping:\n        mov eax, ebx ;restore eax\n        xor edx, edx ;clear edx\n        div ecx\n        cmp edx, 0 ;test if our number\u00a0% n == 0\n        jne next\n        mov edx, [factorArr] ;if yes, we increment the size of the array and append n\n        inc edx\n        mov [factorArr+edx*4], ecx ;appending n\n        mov [factorArr], edx ;storing the new size\n    next:\n        mov eax, ecx\n        cmp eax, ebx ;is n bigger then our number\u00a0?\n        jg end ;if yes we end\n        inc ecx\n        jmp looping\n    end:\n        mov ecx, factorArr ;pass arr address by ecx  \n        xor eax, eax ;clear eax\n        mov esp, ebp ;garbage collecting\n        ret\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":3570}
    {"lang_cluster":"X86_Assembly","source_code":"\n\n      1                                  ;Assemble with: tasm, tlink \/t\n      2     0000                                 .model  tiny\n      3     0000                                 .code\n      4                                          .386\n      5                                          org     100h\n      6                                  ;assume: ax=0000h, bx=0000h, cx=00ff, and\n      7                                  ; direction bit is clear (so di increments)\n      8                                                                  ;                  ____\n      9           =0050                  X0      equ     80              ;                 \/   \/|\n     10           =0050                  Y0      equ     80              ;                \/   \/ |\n     11           =0050                  wide    equ     2*40            ;         X0,Y0 +---+  |\n     12           =0064                  tall    equ     3*40*200\/240    ;               |   |  |\n     13           =0035                  deep    equ     4*40\/3          ;               |   | \/\n     14                                                                  ;               |___|\/\n     15\n     16     0100  B0 13                  start:  mov     al, 13h         ;set 320x200x8 graphic screen\n     17     0102  CD 10                          int     10h\n     18     0104  68 A000                        push    0A000h          ;point es to graphic memory segment\n     19     0107  07                             pop     es\n     20\n     21                                  ;Draw front of cuboid using horizontal lines\n     22     0108  B3 64                          mov     bl, tall\n     23     010A  BF E150                        mov     di, X0+(Y0+tall)*320 ;set pen at lower-left corner\n     24     010D  B0 04                          mov     al, 4           ;use red ink\n     25     010F  B1 50                  dc10:   mov     cl, wide        ;draw horizontal line\n     26     0111  F3> AA                         rep     stosb           ;es:[di++], al; cx--\n     27     0113  81 EF 0190                     sub     di, wide+320    ;move up to start of next line\n     28     0117  4B                             dec     bx              ;at top of face?\n     29     0118  75 F5                          jne     dc10            ;loop if not\n     30\n     31     011A  B3 35                          mov     bl, deep\n     32                                  ;Draw top using horizontal lines\n     33     011C  B0 02                  dc20:   mov     al, 2           ;use green ink\n     34     011E  B1 50                          mov     cl, wide        ;draw horizontal line\n     35     0120  F3> AA                         rep     stosb           ;es:[di++], al; cx--\n     36\n     37                                  ;Draw side using vertical lines\n     38     0122  B0 01                          mov     al, 1           ;use blue ink\n     39     0124  B1 64                          mov     cl, tall        ;draw vertical line\n     40     0126  AA                     dc30:   stosb                   ;es:[di++], al\n     41     0127  81 C7 013F                     add     di, 320-1       ;move down a pixel\n     42     012B  E2 F9                          loop    dc30\n     43\n     44     012D  81 EF 7E8F                     sub     di, wide+(tall+1)*320-1 ;move to start of next top line\n     45     0131  4B                             dec     bx              ;at deep limit?\n     46     0132  75 E8                          jne     dc20            ;loop if not\n     47\n     48     0134  CD 16                          int     16h             ;wait for keystroke (ah=0)\n     49     0136  B8 0003                        mov     ax, 0003h       ;restore normal text-mode screen\n     50     0139  CD 10                          int     10h\n     51     013B  C3                             ret                     ;return to DOS\n     52\n     53                                          end     start\n\n\n","human_summarization":"draw a cuboid with dimensions 2x3x4, representing it graphically or in ASCII art based on language capabilities, showing three visible faces, and allowing either static or rotational projection. The code is optimized to be within sixty bytes.","id":3571}
    {"lang_cluster":"X86_Assembly","source_code":"\n\nformat \tELF \texecutable 3\nentry \tstart\n\t\nsegment\treadable writeable\nbuf\trb\t1\n\t\nsegment\treadable executable\nstart:\tmov\teax, 3\t\t; syscall \"read\"\n\tmov\tebx, 0\t\t; stdin\n\tmov\tecx, buf\t; buffer for read byte\n\tmov\tedx, 1\t\t; len (read one byte)\n\tint\t80h\n\n\tcmp\teax, 0\t\t; EOF?\n\tjz\texit\n\n\txor \teax, eax\t; load read char to eax\n\tmov\tal, [buf]\n\tcmp\teax, \"A\"\t; see if it is in ascii a-z or A-Z\n\tjl\tprint\n\tcmp\teax, \"z\"\n\tjg\tprint\n\tcmp\teax, \"Z\"\n\tjle\trotup\n\tcmp\teax, \"a\"\n\tjge\trotlow\n\tjmp\tprint\n\nrotup:\tsub\teax, \"A\"-13\t; do rot 13 for A-Z\n\tcdq\n\tmov\tebx, 26\n\tdiv\tebx\n\tadd\tedx, \"A\"\n\tjmp\trotend\n\t\nrotlow:\tsub\teax, \"a\"-13\t; do rot 13 for a-z\n\tcdq\n\tmov\tebx, 26\n\tdiv\tebx\n\tadd\tedx, \"a\"\n\nrotend:\tmov\t[buf], dl\n\t\nprint: \tmov\teax, 4\t\t; syscall write\n\tmov\tebx, 1\t\t; stdout\n\tmov\tecx, buf\t; *char\n\tmov\tedx, 1\t\t; string length\n\tint\t80h\n\n\tjmp\tstart\n\nexit: \tmov     eax,1\t\t; syscall exit\n\txor     ebx,ebx\t\t; exit code\n\tint     80h\n","human_summarization":"implement a rot-13 function that can be optionally wrapped in a utility program. This function replaces every ASCII alphabet letter with the letter that is 13 characters away from it in the 26 letter alphabet, wrapping from z to a as necessary. It works on both upper and lower case letters, preserves case, and passes all non-alphabetic characters without alteration. This function is used for obfuscating text to prevent casual reading of spoilers or offensive material. It is implemented in a Linux\/FASM environment.","id":3572}
    {"lang_cluster":"X86_Assembly","source_code":"\n\n;x86-64 assembly code for Microsoft Windows\n;Tested in windows 7 Enterprise Service Pack 1 64 bit\n;With the AMD FX(tm)-6300 processor\n;Assembled with NASM version 2.11.06 \n;Linked to C library with gcc version 4.9.2 (x86_64-win32-seh-rev1, Built by MinGW-W64 project)\n\n;Assembled and linked with the following commands:\n;nasm -f win64 <filename>.asm -o <filename>.obj\n;gcc <filename>.obj -o <filename>\n\n;Takes number of iterations to run RNG loop as command line parameter.\n\nextern printf,puts,atoi,exit,time,malloc\n\nsection .data\nalign 64\nerrmsg_argnumber: db \"There should be no more than one argument.\",0\nalign 64\nerrmsg_noarg: db \"Number of iterations was not specified.\",0\nalign 64\nerrmsg_zeroiterations: db \"Zero iterations of RNG loop specified.\",0\n\nalign 64\nerrmsg_timefail: db \"Unable to retrieve calender time.\",0\nalign 64\nerrmsg_mallocfail: db \"Unable to allocate memory for array of random numbers.\",0\n\nalign 64\nfmt_random: db \"The %u number generated is %d\",0xa,0xd,0\n\nsection .bss\n\nsection .text\nglobal main\n\nmain:\n\n;check for argument\ncmp rcx,1\njle err_noarg\n\n;ensure that only one argument was entered\ncmp rcx,2\njg err_argnumber\n\n\n;get number of times to iterate get_random\nmov rcx,[rdx + 8]\ncall atoi\n\n\n;ensure that number of iterations is greater than 0\ncmp rax,0\njle err_zeroiterations\nmov rcx,rax\n\n\n;calculate space needed for an array containing the random numbers\nshl rcx,2\n\n;move size of array into r14\nmov r14,rcx\n\n;reserve memory for array of random numbers with malloc\ncall malloc\n\ncmp rax,0\njz err_mallocfail\n\n;pointer to array in r15\nmov r15,rax\n\n\n;seed the RNG using time()\nxor rcx,rcx\ncall time\n\n;ensure that time returns valid output\ncmp rax,-1\njz err_timefail\n\n;calculate address of end of array in r14\nadd r14,r15\n\n\n;pointer to array of random numbers in r15\n;address of end of array in r14\n;current address in array in rdi\n;multiplier in rbx\n;seed in rax\n;current random number in rcx\n\n\n;prepare random number generator\n\nmov rdi,r15\n\nmov rbx,214013\n\n\nget_random:\n\n;multiply by 214013 and add 2561011 to get next state\nmul ebx\nadd eax,2531011\n\n;shr by 16 and AND with 0x7FFF to get current random number\nmov ecx,eax\nshr ecx,16\nand ecx,0x7fff\n\n;store random number in array\nmov [rdi],ecx\n\nadd rdi,4\ncmp rdi,r14\njl get_random\n\n\n;pointer to array of random numbers in r15\n;address of end of array in r14\n;current address in array in rdi\n;array index in rsi\n\n\nxor rsi,rsi\nmov rdi,r15\n\nprint_random:\n\nmov rcx,fmt_random\nmov rdx,rsi\nmov r8d,[rdi]\ncall printf\n\nadd rsi,1\nadd rdi,4\ncmp rdi,r14\njl print_random\n\nxor rcx,rcx\ncall exit\n\n\n;;;;;;;;;;ERROR MESSAGES;;;;;;;;;;;;;;;;\n\nerr_argnumber:\n\nmov rcx,errmsg_argnumber\ncall puts\n\njmp exit_one\n\n\nerr_noarg:\n\nmov rcx,errmsg_noarg\ncall puts\n\njmp exit_one\n\n\nerr_zeroiterations:\n\nmov rcx,errmsg_zeroiterations\ncall puts\n\njmp exit_one\n\n\nerr_timefail:\n\nmov rcx,errmsg_timefail\ncall puts\n\njmp exit_one\n\n\nerr_mallocfail:\n\nmov rcx,errmsg_mallocfail\ncall puts\n\n\nexit_one:\n\nmov rcx,1\ncall exit\n\n\n\n\nThis example is incorrect.  Please fix the code and remove this message.Details: It will not produce output identical to that of the Microsoft rand() function.\n\n;x86-64 assembly code for Microsoft Windows\n;Tested in windows 7 Enterprise Service Pack 1 64 bit\n;With the AMD FX(tm)-6300 processor\n;Assembled with NASM version 2.11.06 \n;Linked to C library with gcc version 4.9.2 (x86_64-win32-seh-rev1, Built by MinGW-W64 project)\n\n;Assembled and linked with the following commands:\n;nasm -f win64 <filename>.asm -o <filename>.obj\n;gcc <filename>.obj -o <filename>\n\n;Takes number of iterations to run RNG loop as command line parameter.\n\nextern printf,puts,atoi,exit,time,_aligned_malloc\n\nsection .data\nalign 64\nerrmsg_argnumber: db \"There should be no more than one argument.\",0\nalign 64\nerrmsg_noarg: db \"Number of iterations was not specified.\",0\nalign 64\nerrmsg_zeroiterations: db \"Zero iterations of RNG loop specified.\",0\n\nalign 64\nerrmsg_timefail: db \"Unable to retrieve calender time.\",0\nalign 64\nerrmsg_mallocfail: db \"Unable to allocate memory for array of random numbers.\",0\n\nalign 64\nfmt_random: db \"The %u number generated is %d\",0xa,0xd,0\n\nalign 16\nmultiplier: dd 214013,17405,214013,69069\nalign 16\naddend: dd 2531011, 10395331, 13737667, 1\nalign 16\nmask: dd  0xffffffff,0,0xffffffff,0 \nalign 16\nmasklo: dd 0x7fff,0x7fff,0x7fff,0x7fff\n\nsection .bss\n\nsection .text\nglobal main\n\nmain:\n\n;check for argument\ncmp rcx,1\njle err_noarg\n\n;ensure that only one argument was entered\ncmp rcx,2\njg err_argnumber\n\n\n;get number of times to iterate get_random\nmov rcx,[rdx + 8]\ncall atoi\n\n\n;ensure that number of iterations is greater than 0\ncmp rax,0\njle err_zeroiterations\nmov rcx,rax\n\n\n;calculate space needed for an array containing the random numbers\nshl rcx,4\n\n;move size of array into r14\nmov r14,rcx\n\n;16 byte alignment boundary\nmov rdx,16\n\n;reserve memory aligned to 16 byte boundary for array with _aligned_malloc\ncall _aligned_malloc\n\ncmp rax,0\njz err_mallocfail\n\n;pointer to array in r15\nmov r15,rax\n\n\n;seed the RNG using time()\nxor rcx,rcx\ncall time\n\n;ensure that time returns valid output\ncmp rax,-1\njz err_timefail\n\n\n;pointer to array of random numbers in r15\n;address of end of array at in r14\n;states stored in xmm0\n\n;calculate address of end of array in r14\nadd r14,r15\n\n;load seed,seed+1,seed,seed+1 into xmm0\nlea rbx,[rax - 1]\nshl rax,32\nor rax,rbx\n\nmovq xmm0,rax\nvpslldq xmm1,xmm0,8\nvpor xmm0,xmm0,xmm1\n\n\n;pointer to array of random numbers in r15\n;address of end of array in r14\n;current address in array in rdi\n;current states in xmm0\n;multiplier in xmm1\n;addened in xmm2\n;mask in xmm3\n;masklo in xmm4\n;split seed in xmm5\n;current set of random numbers in xmm6\n\n;prepare random number generator\n\nmov rdi,r15\n\nvmovdqa xmm1,[multiplier]\nvmovdqa xmm2,[addend]\nvmovdqa xmm3,[mask]\nvmovdqa xmm4,[masklo]\n\n\nget_random:\n\n;arrange order of current states to 2,3,0,1 and store in split seed\nvpshufd xmm5,xmm0,10110001b\n\n;multiply current states by multiplier\nvpmulld xmm0,xmm0,xmm1\n\n;set order of multiplier to 2,3,0,1\nvpshufd xmm1,xmm1,10110001b\n\n;multiply split seed by multiplier\nvpmulld xmm5,xmm5,xmm1\n\n;and current states with mask\nvpand xmm0,xmm0,xmm3\n\n;and current split seed with mask\nvpand xmm5,xmm5,xmm3\n\n;set order of split seed to 2,3,0,1\nvpshufd xmm5,xmm5,10110001b\n\n;or current states with split seed\nvpor xmm0,xmm0,xmm5\n\n;add adder to current states\nvpaddd xmm0,xmm0,xmm2\n\n\n;shift vector right by two bytes\nvpsrldq xmm6,xmm0,2\n\n;and each state with 0x7fff\nvpand xmm6,xmm6,xmm4\n\nvmovdqa [rdi],xmm6\n\nadd rdi,16\ncmp rdi,r14\njl get_random\n\n\n;pointer to array of random numbers in r15\n;address of end of array in r14\n;current address in array in rdi\n;array index in rsi\n\n\nxor rsi,rsi\nmov rdi,r15\n\nprint_random:\n\nmov rcx,fmt_random\nmov rdx,rsi\nmov r8d,[rdi]\ncall printf\n\nadd rsi,1\nadd rdi,4\ncmp rdi,r14\njl print_random\n\nxor rcx,rcx\ncall exit\n\n\n;;;;;;;;;;ERROR MESSAGES;;;;;;;;;;;;;;;;\n\nerr_argnumber:\n\nmov rcx,errmsg_argnumber\ncall puts\n\njmp exit_one\n\n\nerr_noarg:\n\nmov rcx,errmsg_noarg\ncall puts\n\njmp exit_one\n\n\nerr_zeroiterations:\n\nmov rcx,errmsg_zeroiterations\ncall puts\n\njmp exit_one\n\n\nerr_timefail:\n\nmov rcx,errmsg_timefail\ncall puts\n\njmp exit_one\n\n\nerr_mallocfail:\n\nmov rcx,errmsg_mallocfail\ncall puts\n\n\nexit_one:\n\nmov rcx,1\ncall exit\n\n\nSample:\n\nF:\\>lcgint.exe 20\nThe 0 number generated is 20272\nThe 1 number generated is 4467\nThe 2 number generated is 8618\nThe 3 number generated is 1587\nThe 4 number generated is 2687\nThe 5 number generated is 21398\nThe 6 number generated is 29522\nThe 7 number generated is 27724\nThe 8 number generated is 23875\nThe 9 number generated is 2399\nThe 10 number generated is 4086\nThe 11 number generated is 923\nThe 12 number generated is 23002\nThe 13 number generated is 11586\nThe 14 number generated is 13200\nThe 15 number generated is 22090\nThe 16 number generated is 26528\nThe 17 number generated is 14271\nThe 18 number generated is 10476\nThe 19 number generated is 9981\n\nF:\\>\n\nF:\\>lcgavx.exe 5\nThe 0 number generated is 20370\nThe 1 number generated is 45\nThe 2 number generated is 20541\nThe 3 number generated is 15699\nThe 4 number generated is 23637\nThe 5 number generated is 30131\nThe 6 number generated is 26151\nThe 7 number generated is 27319\nThe 8 number generated is 26933\nThe 9 number generated is 28417\nThe 10 number generated is 16647\nThe 11 number generated is 14840\nThe 12 number generated is 29228\nThe 13 number generated is 16968\nThe 14 number generated is 1027\nThe 15 number generated is 12099\nThe 16 number generated is 17170\nThe 17 number generated is 23893\nThe 18 number generated is 18556\nThe 19 number generated is 16434\n\nF:\\>\n","human_summarization":"The code replicates two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). The generators use the linear congruential generator formula with specific constants and seeds. The BSD version generates random numbers in the range 0 to 2147483647, while the Microsoft version generates numbers in the range 0 to 32767. The sequence of generated numbers can be reproduced given the same seed.","id":3573}
    {"lang_cluster":"X86_Assembly","source_code":"\n; x86_64 Linux NASM\n; Linked_List_Insert.asm\n\n%ifndef INSERT\n%define INSERT\n\n%include \"Linked_List_Definition.asm\"\u00a0; see LL def task\n%include \"Heap_Alloc.asm\"\u00a0; see memory allocation task\n\nsection .text\n\n; rdi - link to insert after\n; rsi - value that the new link will hold\nInsert_After:\n  push rdi\n  push rsi\n  mov rdi, linkSize\n  call alloc\n  cmp rax, 0\n  je Memory_Allocation_Failure_Exception\n  pop rdi\n  mov dword [rax + value], edi\n  pop rdi\n  mov rsi, qword [rdi + next]\n  mov qword [rax + next], rsi\n  mov qword [rdi + next], rax\n  ret\n\n%endif\n","human_summarization":"\"Defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element C into a list of elements A->B, after element A.\"","id":3574}
    {"lang_cluster":"X86_Assembly","source_code":"\n\nformat PE64 console\nentry start\n\n    include 'win64a.inc'\n\nsection '.text' code readable executable\n\n    start:\n        stdcall dotProduct, vA, vB\n        invoke printf, msg_num, rax\n        \n        stdcall dotProduct, vA, vC\n        invoke printf, msg_num, rax\n        \n        invoke ExitProcess, 0\n        \n    proc dotProduct vectorA, vectorB\n        mov rax, [rcx]\n        cmp rax, [rdx]\n        je .calculate\n        \n        invoke printf, msg_sizeMismatch\n        mov rax, 0\n        ret\n        \n        .calculate:\n        mov r8, rcx\n        add r8, 8\n        mov r9, rdx\n        add r9, 8\n        mov rcx, rax\n        mov rax, 0\n        mov rdx, 0\n        \n        .next:\n            mov rbx, [r9]\n            imul rbx, [r8]\n            add rax, rbx\n            add r8, 8\n            add r9, 8\n            loop .next\n        \n        ret\n    endp\n\nsection '.data' data readable\n\n    msg_num db \"%d\", 0x0D, 0x0A, 0\n    msg_sizeMismatch db \"Size mismatch; can't calculate.\", 0x0D, 0x0A, 0\n    \n    struc Vector [symbols] {\n        common\n        .length dq (.end - .symbols) \/ 8\n        .symbols dq symbols\n        .end:\n    }\n    \n    vA Vector 1, 3, -5\n    vB Vector 4, -2, -1\n    vC Vector 7, 2, 9, 0\n    \nsection '.idata' import data readable writeable\n\n    library kernel32, 'KERNEL32.DLL',\\\n            msvcrt, 'MSVCRT.DLL'\n\n    include 'api\/kernel32.inc'\n\n    import  msvcrt,\\\n            printf, 'printf'\n\n","human_summarization":"The code calculates the dot product of two vectors of arbitrary length. It ensures both vectors are of the same length, multiplies corresponding terms from each vector, and sums the products to produce the final result. Implemented using FASM and targets x64 Microsoft Windows.","id":3575}
    {"lang_cluster":"X86_Assembly","source_code":"\n\n\n        .model  tiny\n        .code\n        .486\n        org     100h            ;assume ax=0, bx=0, sp=-2\nstart:  mov     al, 13h         ;(ah=0) set 320x200 video graphics mode\n        int     10h\n        push    0A000h\n        pop     es\n        mov     si, 8000h       ;color\n\n        mov     cx, 75*256+100  ;coordinates of initial horizontal line segment\n        mov     dx, 75*256+164  ;use power of 2 for length\n\n        call    dragon\n        mov     ah, 0           ;wait for keystroke\n        int     16h\n        mov     ax, 0003h       ;restore normal text mode\n        int     10h\n        ret\n\ndragon: cmp     sp, -100        ;at maximum recursion depth?\n        jne     drag30          ;skip if not\n        mov     bl, dh          ;draw at max depth to get solid image\n        imul    di, bx, 320     ;(bh=0) plot point at X=dl, Y=dh\n        mov     bl, dl\n        add     di, bx\n        mov     ax, si          ;color\n        shr     ax, 13\n        or      al, 8           ;use bright colors 8..F\n        stosb                   ;es:[di++]:= al\n        inc     si\n        ret\ndrag30:\n        push    cx              ;preserve points P and Q\n        push    dx\n\n        xchg    ax, dx          ;DX:= Q(0)-P(0);\n        sub     al, cl\n        sub     ah, ch          ;DY:= Q(1)-P(1);\n\n        mov     dx, ax          ;new point\n        sub     dl, ah          ;R(0):= P(0) + (DX-DY)\/2\n        jns     drag40\n         inc    dl\ndrag40: sar     dl, 1           ;dl:= (al-ah)\/2 + cl\n        add     dl, cl\n\n        add     dh, al          ;R(1):= P(1) + (DX+DY)\/2;\n        jns     drag45\n         inc    dh\ndrag45: sar     dh, 1           ;dh:= (al+ah)\/2 + ch\n        add     dh, ch\n\n        call    dragon          ;Dragon(P, R);\n        pop     cx              ;get Q\n        push    cx\n        call    dragon          ;Dragon(Q, R);\n\n        pop     dx              ;restore points\n        pop     cx\n        ret\n        end     start\n\n","human_summarization":"The code generates a Dragon Curve fractal, either displaying it directly or writing it to an image file. It utilizes various algorithms to create the fractal, including recursive, successive approximation, iterative, and Lindenmayer system methods. The code also includes functionality to calculate the absolute direction and X,Y coordinates of a point, and to test whether a given point or segment is on the curve. The curve can be limited to a specific number of points or a subsection. The code is translated from XPL0 and assembled with tasm, tlink \/t.","id":3576}
    {"lang_cluster":"X86_Assembly","source_code":"\nWorks with: NASM version Linux\n segment .data\n\n      random  dd  0  \u00a0; Where the random number will be stored\n      guess   dd  0  \u00a0; Where the user input will be stored\n \n     instructions    db  10, \"Welcome user! The game is simple: Guess a random number (1-10)!\", 10, 10\n     len1 equ $ - instructions  \u00a0; 1 \\n before and 2 \\n after instructions for better appearance\n\n     wrong           db  \"Not the number\u00a0:(\", 10\n     len2 equ $ - wrong\n\n     correct         db  \"You guessed right, congratulations :D\", 10\n     len3 equ $ - correct\n\n segment .bss\n\n segment .text\n     global  main\n\n main:\n     push    rbp\n     mov     rbp, rsp\n    \u00a0; ********** CODE STARTS HERE **********\n\n    \u00a0;;;;; Random number generator\u00a0;;;;;\n\n     mov     eax, 13\n     mov     ebx, random\n     int     80h\n     mov     eax, [ebx]\n     mov     ebx, 10\n     xor     edx, edx\n     div     ebx\n     inc     edx\n     mov     [random], edx\n\n    \u00a0;;;;; Print the instructions\u00a0;;;;;\n\n     mov     eax, 4\n     mov     ebx, 1\n     mov     ecx, instructions\n     mov     edx, len1\n     int     80h\n\n userInput:\n\n    \u00a0;;;;; Ask user for input\u00a0;;;;;\n\n     mov     eax, 3\n     xor     ebx, ebx\n     mov     ecx, instructions\n     mov     edx, 1\n     int     80h\n     mov     al, [ecx]\n     cmp     al, 48\n     jl      valCheck\n     cmp     al, 57\n     jg      valCheck\n\n    \u00a0;;;;; If number\u00a0;;;;;\n\n     sub     al, 48\n     xchg    eax, [guess]\n     mov     ebx, 10\n     mul     ebx\n     add     [guess], eax\n     jmp     userInput\n\n valCheck:\n\n    \u00a0;;;;; Else check number\u00a0;;;;;\n\n     mov     eax, 4\n     inc     ebx\n     mov     ecx, [guess]\n     cmp     ecx, [random]\n     je      correctResult\n\n    \u00a0;;;;; If not equal, \"not the number\u00a0:(\"\u00a0;;;;;\n\n     mov     ecx, wrong\n     mov     edx, len2\n     mov     DWORD [guess], 0\n     int     80h\n     jmp     userInput\n\n correctResult:\n\n    \u00a0;;;;; If equal, \"congratulations :D\"\u00a0;;;;;\n\n     mov     ecx, correct\n     mov     edx, len3\n     int     80h\n\n    \u00a0;;;;; EXIT\u00a0;;;;;\n\n     mov     rax, 0\n     mov     rsp, rbp\n     pop     rbp\n     ret\n\n; \"Guess my number\" program by Randomboi (8\/8\/2021)\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":3577}
    {"lang_cluster":"X86_Assembly","source_code":"\n\n        .model  tiny\n        .code\n        .486\n        org     100h\nstart:  mov     ax, 5\n        call    binout\n        call    crlf\n        mov     ax, 50\n        call    binout\n        call    crlf\n        mov     ax, 9000\n        call    binout\n\ncrlf:   mov     al, 0Dh         ;new line\n        int     29h\n        mov     al, 0Ah\n        int     29h\n        ret\n\nbinout: push    ax\n        shr     ax, 1\n        je      bo10\n         call   binout\nbo10:   pop     ax\n        and     al, 01h\n        or      al, '0'\n        int     29h             ;display character\n        ret\n        end     start\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output is strictly binary digits with no whitespace, radix, sign markers, or leading zeros. The binary sequence is followed by a newline. The conversion from decimal to binary can be achieved using built-in radix functions or a user-defined function.","id":3578}
    {"lang_cluster":"X86_Assembly","source_code":"\n\n        .model  tiny\n        .code\n        org     100h\n\nstart:  mov     ax, 0013h       ;set 320x200x8 graphic screen\n        int     10h\n        push    0A000h          ;point to graphic memory segment\n        pop     es\n        mov     byte ptr es:[320*100+100], 28h  ;draw bright red pixel\n\n        mov     ah, 0           ;wait for keystroke\n        int     16h\n        mov     ax, 0003h       ;restore normal text mode screen\n        int     10h\n        ret                     ;return to OS\n        end     start\n","human_summarization":"The code creates a 320x240 window and draws a red pixel at the position (x=100, y=100). It also includes a feature to wait for a keystroke before returning to the operating system, allowing the pixel to be visible. The executable program is 32 bytes long, created using Borland's tasm and tlink \/t.","id":3579}
    {"lang_cluster":"X86_Assembly","source_code":"\n\n0000                                 .model  tiny\n0000                                 .code\n                                     .486\n                                     org     100h           \u00a0;.com files start here\n0100  9B DB E3               start:  finit                   ;initialize floating-point unit (FPU)\n                             ;Great circle distance =\n                            \u00a0; 2.0*Radius * ASin( sqrt( Haversine(Lat2-Lat1) +\n                            \u00a0;                          Haversine(Lon2-Lon1)*Cos(Lat1)*Cos(Lat2) ) )\n0103  D9 06 0191r                    fld     Lat2            ;push real onto FPU stack\n0107  D8 26 018Dr                    fsub    Lat1            ;subtract real from top of stack (st(0) = st)\n010B  E8 0070                        call    Haversine      \u00a0;(1.0-cos(st)) \/ 2.0\n010E  D9 06 0199r                    fld     Lon2            ;repeat for longitudes\n0112  D8 26 0195r                    fsub    Lon1\n0116  E8 0065                        call    Haversine       ;st(1)=Lats; st=Lons\n0119  D9 06 018Dr                    fld     Lat1\n011D  D9 FF                          fcos                    ;replace st with its cosine\n011F  D9 06 0191r                    fld     Lat2\n0123  D9 FF                          fcos            ;st=cos(Lat2); st(1)=cos(Lat1); st(2)=Lats; st(3)=Lons\n0125  DE C9                          fmul            ;st=cos(Lat2)*cos(Lat1); st(1)=Lats; st(2)=Lons\n0127  DE C9                          fmul            ;st=cos(Lat2)*cos(Lat1)*Lats; st(1)=Lons\n0129  DE C1                          fadd            ;st=cos(Lat2)*cos(Lat1)*Lats + Lons\n012B  D9 FA                          fsqrt                   ;replace st with its square root\n                             ;asin(x) = atan(x\/sqrt(1-x^2))\n012D  D9 C0                          fld     st              ;duplicate tos\n012F  D8 C8                          fmul    st, st          ;x^2\n0131  D9 E8                          fld1                    ;get 1.0\n0133  DE E1                          fsubr                   ;1 - x^2\n0135  D9 FA                          fsqrt                   ;sqrt(1-x^2)\n0137  D9 F3                          fpatan                  ;take atan(st(1)\/st)\n0139  D8 0E 019Dr                    fmul    Radius2        \u00a0;*2.0*Radius\n\n                             ;Display value in FPU's top of stack (st)\n      =0004                  before  equ     4               ;places before\n      =0002                  after   equ     2              \u00a0; and after decimal point\n      =0001                  scaler  =       1              \u00a0;\"=\" allows scaler to be redefined, unlike equ\n                                     rept    after           ;repeat block \"after\" times\n                             scaler  =       scaler*10\n                                     endm                    ;scaler now = 10^after\n\n013D  66| 6A 64                      push    dword ptr scaler;use stack for convenient memory location\n0140  67| DA 0C 24                   fimul   dword ptr [esp] ;st:= st*scaler\n0144  67| DB 1C 24                   fistp   dword ptr [esp] ;round st to nearest integer\n0148  66| 58                         pop     eax            \u00a0; and put it into eax\n\n014A  66| BB 0000000A                mov     ebx, 10         ;set up for idiv instruction\n0150  B9 0006                        mov     cx, before+after;set up loop counter\n0153  66| 99                 ro10:   cdq                     ;convert double to quad; i.e: edx:= 0\n0155  66| F7 FB                      idiv    ebx             ;eax:= edx:eax\/ebx; remainder in edx\n0158  52                             push    dx              ;save least significant digit on stack\n0159  E2 F8                          loop    ro10            ;cx--; loop back if not zero\n\n015B  B1 06                          mov     cl, before+after;(ch=0)\n015D  B3 00                          mov     bl, 0           ;used to suppress leading zeros\n015F  58                     ro20:   pop     ax              ;get digit\n0160  0A D8                          or      bl, al          ;turn off suppression if not a zero\n0162  80 F9 03                       cmp     cl, after+1     ;is digit immediately to left of decimal point?\n0165  75 01                          jne     ro30            ;skip if not\n0167  43                              inc    bx              ;turn off leading zero suppression\n0168  04 30                  ro30:   add     al, '0'         ;if leading zero then ' ' else add 0\n016A  84 DB                          test    bl, bl\n016C  75 02                          jne     ro40\n016E  B0 20                           mov    al, ' '\n0170  CD 29                  ro40:   int     29h             ;display character in al register\n0172  80 F9 03                       cmp     cl, after+1     ;is digit immediately to left of decimal point?\n0175  75 04                          jne     ro50            ;skip if not\n0177  B0 2E                           mov    al, '.'         ;display decimal point\n0179  CD 29                           int    29h\n017B  E2 E2                  ro50:   loop    ro20            ;loop until all digits displayed\n017D  C3                             ret                     ;return to OS\n\n017E                         Haversine:                      ;return (1.0-Cos(Ang)) \/ 2.0 in st\n017E  D9 FF                          fcos\n0180  D9 E8                          fld1\n0182  DE E1                          fsubr\n0184  D8 36 0189r                    fdiv    N2\n0188  C3                             ret\n\n0189  40000000               N2      dd       2.0\n018D  3F21628D               Lat1    dd       0.63041        ;36.12*pi\/180\n0191  3F17A4E8               Lat2    dd       0.59236        ;33.94*pi\/180\n0195  BFC19F80               Lon1    dd      -1.51268       \u00a0;-86.67*pi\/180\n0199  C004410B               Lon2    dd      -2.06647       \u00a0;-118.40*pi\/180\n019D  46472666               Radius2 dd      12745.6         ;6372.8 average radius of Earth (km) times 2\n                            \u00a0;(TASM isn't smart enough to do floating point constant calculations)\n                                     end     start\n\n","human_summarization":"The code implements the Haversine formula to calculate the great-circle distance between two points on a sphere using their longitudes and latitudes. The points used in this case are the Nashville International Airport (BNA) and the Los Angeles International Airport (LAX). The code also considers the earth's radius, with two possible values (6371.0 km and 6372.8 km) leading to slightly different distance results. The recommended radius value for practical precision is 6372.8 km, although for real applications, the mean earth radius of 6371 km is suggested.","id":3580}
    {"lang_cluster":"X86_Assembly","source_code":"\nWorks with: nasm\nWorks with: windows\nextern _printf\n\nsection .data\n    output db 0,0\n    \nsection .text\nglobal _main\n_main:\n    mov bl, 0\n    looping:\n        add bl, 0x31 ;0x30 to 0x39 is 0 to 9 in ASCII\n        mov [output], bl\n        sub bl, 0x30\n        push output\n        call _printf\n        add esp, 4\n        xor eax, eax\n        xor edx, edx\n        mov al, bl\n        mov ecx, 6\n        div ecx\u00a0; remainder is saved in edx\n        cmp edx, 0\n        jne looping\u00a0; if n & 6\u00a0!= 0 do looping again\n    xor eax, eax\n    ret\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":3581}
    {"lang_cluster":"X86_Assembly","source_code":"\n\nL: rdrand eax\njnc L\n\n","human_summarization":"generates a random 32-bit number using the system's hardware random number generator, specifically utilizing the RDRAND feature supported by the processor. The code includes a loop to handle potential retrieval failures from RDRAND, indicated by the carry flag.","id":3582}
    {"lang_cluster":"X86_Assembly","source_code":"Works with: GCC version 7.3.0 - Ubuntu 18.04 64-bit\n                                        # Author: Ettore Forigo - Hexwell\n\n.intel_syntax noprefix\n\n.text\n.globl main\nmain:\n.PROLOGUE:\n    push    rbp\n    mov rbp, rsp\n    sub rsp, 32\n    mov QWORD PTR [rbp-32], rsi         # argv\n    \n.BODY:\n    mov BYTE PTR [rbp-1], 0             # shift = 0\n\n    .I_LOOP_INIT:\n        mov BYTE PTR [rbp-2], 0         # i = 0\n        jmp .I_LOOP_CONDITION           # I_LOOP_CONDITION\n    .I_LOOP_BODY:\n        movzx edx, BYTE PTR[rbp-1]      # shift\n        mov eax, edx                    # shift\n        sal eax, 2                      # shift << 2 == i * 4\n        add eax, edx                    # shift * 4 + shift = shift * 5\n        add eax, eax                    # shift * 5 + shift * 5 = shift * 10\n        mov ecx, eax                    # shift * 10\n        mov rax, QWORD PTR [rbp-32]     # argv\n        add rax, 8                      # argv + 1\n        mov rdx, QWORD PTR [rax]        # argv[1]\n        movzx eax, BYTE PTR [rbp-2]     # i\n        add rax, rdx                    # argv[1] + i\n        movzx eax, BYTE PTR [rax]       # argv[1][i]\n        add eax, ecx                    # shift * 10 + argv[1][i]\n        sub eax, 48                     # shift * 10 + argv[1][i] - '0'\n        mov BYTE PTR [rbp-1], al        # shift = shift * 10 + argv[1][i] - '0'\n    .I_LOOP_INCREMENT:\n        movzx eax, BYTE PTR [rbp-2]     # i\n        add eax, 1                      # i + 1\n        mov BYTE PTR [rbp-2], al        # i++\n    .I_LOOP_CONDITION:\n        mov rax, QWORD PTR [rbp-32]     # argv\n        add rax, 8                      # argv + 1\n        mov rax, QWORD PTR [rax]        # argv[1]\n        movzx edx, BYTE PTR [rbp-2]     # i\n        add rax, rdx                    # argv[1] + i\n        movzx rax, BYTE PTR [rax]       # argv[1][i]\n        test al, al                     # argv[1][i]?\n        jne .I_LOOP_BODY                # I_LOOP_BODY\n\n    .CAESAR_LOOP_INIT:\n        mov BYTE PTR [rbp-2], 0         # i = 0\n        jmp .CAESAR_LOOP_CONDITION      # CAESAR_LOOP_CONDITION\n    .CAESAR_LOOP_BODY:\n        mov rax, QWORD PTR [rbp-32]     # argv\n        add rax, 16                     # argv + 2\n        mov rdx, QWORD PTR [rax]        # argv[2]\n        movzx eax, BYTE PTR [rbp-2]     # i\n        add rax, rdx                    # argv[2] + i\n        mov rbx, rax                    # argv[2] + i\n        movzx eax, BYTE PTR [rax]       # argv[2][i]\n        cmp al, 32                      # argv[2][i] == ' '\n        je .CAESAR_LOOP_INCREMENT       # CAESAR_LOOP_INCREMENT\n        movzx edx, BYTE PTR [rbx]       # argv[2][i]\n        mov ecx, edx                    # argv[2][i]\n        movzx edx, BYTE PTR [rbp-1]     # shift\n        add edx, ecx                    # argv[2][i] + shift\n        sub edx, 97                     # argv[2][i] + shift - 'a'\n        mov BYTE PTR [rbx], dl          # argv[2][i] = argv[2][i] + shift - 'a'\n        movzx eax, BYTE PTR [rbx]       # argv[2][i]\n        cmp al, 25                      # argv[2][i] <=> 25\n        jle .CAESAR_RESTORE_ASCII       # <= CAESAR_RESTORE_ASCII\n        movzx edx, BYTE PTR [rbx]       # argv[2][i]\n        sub edx, 26                     # argv[2][i] - 26\n        mov BYTE PTR [rbx], dl          # argv[2][i] = argv[2][i] - 26\n    .CAESAR_RESTORE_ASCII:\n        movzx edx, BYTE PTR [rbx]       # argv[2][i]\n        add edx, 97                     # argv[2][i] + 'a'\n        mov BYTE PTR [rbx], dl          # argv[2][i] = argv[2][i] + 'a'\n    .CAESAR_LOOP_INCREMENT:\n        movzx eax, BYTE PTR [rbp-2]     # i\n        add eax, 1                      # i + 1\n        mov BYTE PTR [rbp-2], al        # i++\n    .CAESAR_LOOP_CONDITION:\n        mov rax, QWORD PTR [rbp-32]     # argv\n        add rax, 16                     # argv + 2\n        mov rdx, QWORD PTR [rax]        # argv[2]\n        movzx eax, BYTE PTR [rbp-2]     # i\n        add rax, rdx                    # argv[2] + i\n        movzx eax, BYTE PTR [rax]       # argv[2][i]\n        test al, al                     # argv[2][i]?\n        jne .CAESAR_LOOP_BODY           # CAESAR_LOOP_BODY\n\n    mov rax, QWORD PTR [rbp-32]         # argv\n    add rax, 16                         # argv + 2\n    mov rax, QWORD PTR [rax]            # argv[2]\n    mov rdi, rax                        # argv[2]\n    call    puts                        # puts(argv[2])\n\n.RETURN:\n    mov eax, 0                          # 0\n    leave\n    ret                                 # return 0\n\n$ gcc caesar.S -o caesar\n$ .\/caesar 10 abc\nklm\n$ .\/caesar 16 klm\nabc\n","human_summarization":"implement both encoding and decoding functionalities of a Caesar cipher. The cipher uses a key ranging from 1 to 25 to rotate the alphabet letters either left or right. It replaces each letter with the 1st to 25th next letter in the alphabet, wrapping Z back to A. The codes also highlight the cipher's lack of security due to its vulnerability to frequency analysis or brute force attacks. The Caesar cipher is identical to the Vigen\u00e8re cipher with a key of length 1 and the Rot-13 cipher with a key of 13.","id":3583}
    {"lang_cluster":"X86_Assembly","source_code":"\n; x86_64 Linux NASM\n\nglobal _start\n\n%define af_inet 2\n%define sock_stream 1\n%define default_proto 0\n%define sol_sock 1\n%define reuse_addr 2\n%define reuse_port 15\n%define server_port 9001\n%define addr_any 0\n%define family_offset 0\n%define port_offset 2\n%define addr_offset 4\n%define unused_offset 8\n%define addr_len 16\n%define buffer_len 64\n%define max_connections 3\n\n\nsection .text\n\n; rdi - 16 bit value to be byte swapped\n; return - byte swapped value\nhtn_swap16:\n\n  xor rax, rax\n  mov rdx, 0x000000ff\n\n  mov rsi, rdi\n  and rsi, rdx\n  shl rsi, 8\n  or rax, rsi\n  shl rdx, 8\n\n  mov rsi, rdi\n  and rsi, rdx\n  shr rsi, 8\n  or rax, rsi\n  ret\n\n; return - server socket\ncreate_server_socket:\n\n  mov rax, 41\n  mov rdi, af_inet\n  mov rsi, sock_stream\n  mov rdx, default_proto\n  syscall\n  push rax\n\n  mov rax, 54\n  mov rdi, qword [rsp]\n  mov rsi, sol_sock\n  mov rdx, reuse_addr\n  mov qword [rsp - 16], 1\n  lea r10, [rsp - 16]\n  mov r8, 4\n  syscall\n\n  mov rax, 54\n  mov rdi, qword [rsp]\n  mov rsi, sol_sock\n  mov rdx, reuse_port\n  mov qword [rsp - 16], 1\n  lea r10, [rsp - 16]\n  mov r8, 4\n  syscall\n\n\n  pop rax\n  ret\n\n; rdi - socket\n; rsi - port\n; rdx - connections\n; return - void\nbind_and_listen:\n\n  push rdi\n  push rdx\n\n  mov rdi, rsi\n  call htn_swap16\n\n  lea rsi, [rsp - 16]\n  mov word [rsi + family_offset], af_inet\n  mov word [rsi + port_offset], ax\n  mov dword [rsi + addr_offset], addr_any\n  mov qword [rsi + unused_offset], 0\n\n  mov rax, 49\n  mov rdi, qword [rsp + 8]\n  mov rdx, addr_len\n  syscall\n\n  mov rax, 50\n  pop rsi\n  pop rdi\n  syscall\n  ret\n\n; rdi - server socket\n; return - client socket\naccept:\n\n  mov rax, 43\n  lea rsi, [rsp - 16]\n  lea rdx, [rsp - 24]\n  syscall\n  ret\n\n; rdi - client socket\n; return - void\necho:\n\n  push rdi\n  mov rax, 0\n  lea rsi, [rsp - 104]\n  mov rdx, buffer_len\n  syscall\n\n  pop rdi\n  mov rdx, rax \n  lea rsi, [rsp - 112]\n  mov rax, 1\n  syscall\n  ret\n\n\n_start:\n\n  call create_server_socket\n  mov r14, rax\n\n  mov rdi, rax\n  mov rsi, server_port\n  mov rdx, max_connections\n  call bind_and_listen\n\naccept_connection:\n\n  mov rdi, r14\n  call accept\n\n  mov r15, rax\n  mov rax, 57\n  syscall\n\n  test rax, rax\n  jz handle_connection\n\n \u00a0; close client socket\n  mov rax, 3\n  mov rdi, r15\n  syscall\n  jmp accept_connection\n    \nhandle_connection:\n\n  mov rdi, r15\n  call echo\n\n  close_client:\n    mov rax, 3\n    mov rdi, r15\n    syscall\n\n  close_server:\n    mov rax, 3\n    mov rdi, r14\n    syscall\n\n  exit:\n    mov rax, 60\n    xor rdi, rdi\n    syscall\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":3584}
    {"lang_cluster":"X86_Assembly","source_code":"\nWorks with: NASM version Linux\n\n%define sys_signal \t48\n%define SIGINT\t\t\t2\n%define sys_time\t13\n\nextern usleep\nextern printf\n\nsection .text\n\tglobal _start\n\t\n\t_sig_handler:\n\t\tmov ebx, end_time\n\t\tmov eax, sys_time\n\t\tint 0x80\n\t\tmov eax, dword [start_time]\n\t\tmov ebx, dword [end_time]\n\t\tsub ebx, eax\n\t\tmov ax, 100\n\t\tdiv ebx\n\t\tpush ebx\n\t\tpush p_time\n\t\tcall printf\n\t\tpush 0x1\n\t\tmov eax, 1\n\t\tpush eax\n\t\tint 0x80\n\t\tret\n\t\t\n\t_start:\n\t\tmov ebx, start_time\n\t\tmov eax, sys_time\n\t\tint 0x80\n\t\tmov ecx, _sig_handler\n\t\tmov ebx, SIGINT\n\t\tmov eax, sys_signal\n\t\tint 0x80\n\t\txor edi, edi\n\t\t.looper:\n\t\t\tpush 500000\n\t\t\tcall usleep\n\t\t\tpush edi\n\t\t\tpush p_cnt\n\t\t\tcall printf\n\t\t\tinc edi\n\t\tjmp .looper\n\t\t\nsection .data\np_time\tdb \"The program has run for %d seconds.\",13,10,0\np_cnt\t\tdb \"%d\",13,10,0\n\nsection .bss\nstart_time\tresd 1\nend_time\t\tresd 1\n\n","human_summarization":"The code outputs an integer every half second. It handles SIGINT and SIGQUIT signals, typically generated by the user. On receiving these signals, the program stops outputting integers, displays the total runtime in seconds, and then terminates. The functionality is achieved through system calls and signal handlers, avoiding the use of C libraries.","id":3585}
    {"lang_cluster":"X86_Assembly","source_code":"\n; x86_64 linux nasm\n\nsection .bss\nnumber resb 4\n\nsection .data\nfizz: db \"Fizz\"\nbuzz: db \"Buzz\"\nnewLine: db 10\n\nsection .text\nglobal _start\n\n_start:\n\n  mov rax, 1     \u00a0; initialize counter\n\n  loop:\n    push rax\n    call fizzBuzz\n    pop rax\n    inc rax\n    cmp rax, 100\n    jle loop\n\n  mov rax, 60\n  mov rdi, 0\n  syscall\n\nfizzBuzz:\n  mov r10, rax\n  mov r15, 0      \u00a0; boolean fizz or buzz\n  checkFizz:\n    xor rdx, rdx  \u00a0; clear rdx for division\n    mov rbx, 3\n    div rbx\n    cmp rdx, 0    \u00a0; modulo result here\n    jne checkBuzz\n    mov r15, 1\n    mov rsi, fizz\n    mov rdx, 4\n    mov rax, 1\n    mov rdi, 1\n    syscall\n  checkBuzz:\n    mov rax, r10\n    xor rdx, rdx\n    mov rbx, 5\n    div rbx\n    cmp rdx, 0\n    jne finishLine\n    mov r15, 1\n    mov rsi, buzz\n    mov rdx, 4\n    mov rax, 1\n    mov rdi, 1\n    syscall\n  finishLine:     \u00a0; print number if no fizz or buzz\n    cmp r15, 1\n    je nextLine\n    mov rax, r10\n    call printNum\n    ret\n    nextLine:\n      mov rsi, newLine\n      mov rdx, 1\n      mov rax, 1\n      mov rdi, 1\n      syscall\n      ret\n\nprintNum:         \u00a0; write proper digits into number buffer\n  cmp rax, 100\n  jl lessThanHundred\n  mov byte [number], 49\n  mov byte [number + 1], 48\n  mov byte [number + 2], 48\n  mov rdx, 3\n  jmp print\n\n  lessThanHundred:\u00a0; get digits to write through division \n    xor rdx, rdx\n    mov rbx, 10\n    div rbx\n    add rdx, 48\n    cmp rax, 0\n    je lessThanTen\n    add rax, 48\n    mov byte [number], al\n    mov byte [number + 1], dl\n    mov rdx, 2\n    jmp print\n\n  lessThanTen:\n    mov byte [number], dl\n    mov rdx, 1\n  print:\n    mov byte [number + rdx], 10  \u00a0; add newline\n    inc rdx\n    mov rax, 1\n    mov rdi, 1\n    mov rsi, number\n    syscall\n  ret\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":3586}
    {"lang_cluster":"X86_Assembly","source_code":"\n\n    align 16\n; Input year as signed dword in EAX    \nIsLeapYear:\n    test eax,11b\n    jz .4\n    retn\u00a0; 75%\u00a0: ZF=0, not a leap year\n.4:\n    mov ecx,100\n    cdq\n    idiv ecx\n    test edx,edx\n    jz .100\n    cmp edx,edx\n    retn\u00a0; 24%\u00a0: ZF=1, leap year\n.100:\n    test eax,11b\n    retn\u00a0; 1%\u00a0: ZF=?, leap year if EAX%400=0\n","human_summarization":"determine if a given year is a leap year in the Gregorian calendar using FASM syntax. The code incorporates a leaf function into the program.","id":3587}
    {"lang_cluster":"X86_Assembly","source_code":"\nWorks with: nasm\n\nsection .data\n    string db \"Hello World\", 0\n\nsection .bss\n    string2 resb 12\n    \nsection .text\nglobal _main\n_main:\n    mov ecx, 0\n    looping:\n        mov al, [string + ecx]\n        mov [string2 + ecx], al\n        inc ecx\n        cmp al, 0 ;copy until we find the terminating 0\n        je end\n        jmp looping\n    end:\n        xor eax, eax\n        ret\n\nsection .data\n    string db 11,\"Hello World\"\n\nsection .bss\n    string2 resb 12\n    \nsection .text\nglobal _main\n_main:\n    xor ecx, ecx ;clear ecx\n    mov cl, [string]\n    mov [string2], cl ;copy byte signaling length\n    mov edx, 1\n    looping: ;copy each single byte\n        mov al, [string + edx]\n        mov [string2 + edx], al\n        inc edx\n        dec ecx\n        cmp ecx, 0\n        jg looping\n    xor eax, eax\n    ret\n","human_summarization":"\"Implements functionality to copy a string, differentiating between copying the string content and creating an additional reference to the existing string. It also includes creating a second string with the same content, terminated by 0, and another where the first byte indicates the string length.\"","id":3588}
    {"lang_cluster":"X86_Assembly","source_code":"\n\n;x86-64 assembly code for Microsoft Windows\n;Tested in windows 7 Enterprise Service Pack 1 64 bit\n;With the AMD FX(tm)-6300 processor\n;Assembled with NASM version 2.11.06 \n;Linked to C library with gcc version 4.9.2 (x86_64-win32-seh-rev1, Built by MinGW-W64 project)\n\n;Assembled and linked with the following commands:\n;nasm -f win64 <filename>.asm -o <filename>.obj\n;gcc <filename>.obj -o <filename>\n\n;Takes magnitude of Sierpinski Carpet as command line argument.\n\nextern atoi,puts,putchar,exit\n\nsection .data\nerrmsg_noarg: db \"Magnitude of Sierpinski Carpet was not specified.\",0\nerrmsg_argnumber: db \"There should be no more than one argument.\",0\n\nsection .bss\n\nsection .text\nglobal main\n\nmain:\n\n;check for argument\ncmp rcx,1\njle err_noarg\n\n;ensure that only one argument was entered\ncmp rcx,2\njg err_argnumber\n\n;column in rsi\n;row in rdi\n;x in r8\n;y in r9\n;width in r13\n;magic number in r14\n\nmov r14,2863311531\n\n;get magnitude in rbx from first arg\nmov rcx,[rdx + 8]\ncall atoi\nmov rbx,rax\n\ncmp rbx,0\njz magnitude_zero \n\n\n;determine dimensions of square\nmov rax,1\n\nfind_width:\n\nlea rax,[rax * 3]\n\ndec rbx\njg find_width\n\nsub rax,1\n\nmov r13,rax\nmov rdi,rax\n\n\nnext_row:\n\nmov rsi,r13\n\nfill_row:\n\n;x in r8, y in r9\nmov r8,rsi\nmov r9,rdi\n\nis_filled:\n\n;if(x%3==1 && y%3==1)\n;x%3 in rbx\nmov rax,r8\nmov rbx,r8\nmul r14\nshr rax,33\nmov r8,rax\nlea rax,[rax * 3]\nsub rbx,rax\n\n;y%3 in rcx\nmov rax,r9\nmov rcx,r9\nmul r14\nshr rax,33\nmov r9,rax\nlea rax,[rax * 3]\nsub rcx,rax\n\n;x%3==1 && y%3==1\nxor rbx,1\nxor rcx,1\nor rbx,rcx\nmov rcx,' '\ncmp rbx,0\njz dont_fill\n\n;x>0 || y>0\nmov rax,r8\nor rax,r9\ncmp rax,0\njg is_filled\n\nmov rcx,'#'\ndont_fill:\n\ncall putchar\n\ndec rsi\njge fill_row\n\n;put newline at the end of each row\nmov rcx,0xa\ncall putchar\n\ndec rdi\njge next_row\n\nxor rcx,rcx\ncall exit\n\nmagnitude_zero:\n\nmov rcx,'#'\ncall putchar\n\nmov rcx,0xa\ncall putchar\n\nxor rcx,rcx\ncall exit\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;error message\n\nerr_noarg:\n\nmov rcx,errmsg_noarg\ncall puts\n\nmov rcx,1\ncall exit\n\n\nerr_argnumber:\n\nmov rcx,errmsg_argnumber\ncall puts\n\nmov rcx,1\ncall exit\n\nSample:\nF:\\>asciisierpinski.exe\nMagnitude of Sierpinski Carpet was not specified.\n\nF:\\>asciisierpinski.exe 1 1 1\nThere should be no more than one arguement.\n\nF:\\>asciisierpinski.exe 0\n#\n\nF:\\>asciisierpinski.exe 1\n###\n# #\n###\n\nF:\\>asciisierpinski.exe 2\n#########\n# ## ## #\n#########\n###   ###\n# #   # #\n###   ###\n#########\n# ## ## #\n#########\n\nF:\\>asciisierpinski.exe 3\n###########################\n# ## ## ## ## ## ## ## ## #\n###########################\n###   ######   ######   ###\n# #   # ## #   # ## #   # #\n###   ######   ######   ###\n###########################\n# ## ## ## ## ## ## ## ## #\n###########################\n#########         #########\n# ## ## #         # ## ## #\n#########         #########\n###   ###         ###   ###\n# #   # #         # #   # #\n###   ###         ###   ###\n#########         #########\n# ## ## #         # ## ## #\n#########         #########\n###########################\n# ## ## ## ## ## ## ## ## #\n###########################\n###   ######   ######   ###\n# #   # ## #   # ## #   # #\n###   ######   ######   ###\n###########################\n# ## ## ## ## ## ## ## ## #\n###########################\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N, where the placement of whitespace and non-whitespace characters is crucial. The ASCII art does not necessarily have to use the '#' character. The program uses magic number division to avoid repeated use of the div instruction in a loop. It also relates to the task of creating a Sierpinski triangle.","id":3589}
    {"lang_cluster":"X86_Assembly","source_code":"\nWorks with: nasm\nWorks with: windows\nsection .text\n\nglobal _main\n_main:\n    mov eax, 3 ;m\n    mov ebx, 4 ;n\n    call ack ;returns number in ebx\n    ret\n    \nack:\n    cmp eax, 0\n    je M0 ;if M == 0\n    cmp ebx, 0\n    je N0 ;if N == 0\n    dec ebx ;else N-1\n    push eax ;save M\n    call ack1 ;ack(m,n) -> returned in ebx so no further instructions needed\n    pop eax ;restore M\n    dec eax ;M - 1\n    call ack1 ;return ack(m-1,ack(m,n-1))\n    ret\n    M0:\n        inc ebx ;return n + 1\n        ret\n    N0:\n        dec eax\n        inc ebx ;ebx always 0: inc -> ebx = 1\n        call ack1 ;return ack(M-1,1)\n        ret\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":3590}
    {"lang_cluster":"X86_Assembly","source_code":"\nWorks with: nasm version Linux\n;using sockets on linux with the 0x80 inturrprets.\n;\n;assemble\n;  nasm -o socket.o -f elf32 -g socket.asm\n;link\n;  ld -o socket socket.o\n;\n;\n;Just some assigns for better readability\n\n%assign SOCK_STREAM         1\n%assign AF_INET             2\n%assign SYS_socketcall      102\n%assign SYS_SOCKET          1\n%assign SYS_CONNECT         3\n%assign SYS_SEND            9\n%assign SYS_RECV            10\n\nsection .text\n  global _start\n  \n;--------------------------------------------------\n;Functions to make things easier.\u00a0:]\n;--------------------------------------------------\n_socket:\n  mov [cArray+0], dword AF_INET\n  mov [cArray+4], dword SOCK_STREAM\n  mov [cArray+8], dword 0\n  mov eax, SYS_socketcall\n  mov ebx, SYS_SOCKET\n  mov ecx, cArray\n  int 0x80\n  ret\n\n_connect:\n  call _socket\n  mov dword [sock], eax\n  mov dx, si\n  mov byte [edi+3], dl\n  mov byte [edi+2], dh\n  mov [cArray+0], eax     ;sock;\n  mov [cArray+4], edi     ;&sockaddr_in;\n  mov edx, 16\n  mov [cArray+8], edx   ;sizeof(sockaddr_in);\n  mov eax, SYS_socketcall\n  mov ebx, SYS_CONNECT\n  mov ecx, cArray\n  int 0x80\n  ret\n\n_send:\n  mov edx, [sock]\n  mov [sArray+0],edx\n  mov [sArray+4],eax\n  mov [sArray+8],ecx\n  mov [sArray+12], dword 0\n  mov eax, SYS_socketcall\n  mov ebx, SYS_SEND\n  mov ecx, sArray\n  int 0x80\n  ret\n\n_exit:\n  push 0x1\n  mov eax, 1\n  push eax\n  int 0x80\n  \n_print:\n  mov ebx, 1\n  mov eax, 4  \n  int 0x80   \n  ret         \n;--------------------------------------------------\n;Main code body\n;--------------------------------------------------\n \n_start:\n  mov esi, szIp    \n  mov edi, sockaddr_in\n  xor eax,eax\n  xor ecx,ecx\n  xor edx,edx\n  .cc:\n    xor   ebx,ebx\n  .c:\n    lodsb\n    inc   edx\n    sub   al,'0'\n    jb   .next\n    imul ebx,byte 10\n    add   ebx,eax\n    jmp   short .c\n  .next:\n    mov   [edi+ecx+4],bl\n    inc   ecx\n    cmp   ecx,byte 4\n    jne   .cc\n\n  mov word [edi], AF_INET \n  mov esi, szPort \n  xor eax,eax\n  xor ebx,ebx\n  .nextstr1:   \n    lodsb      \n    test al,al\n    jz .ret1\n    sub   al,'0'\n    imul ebx,10\n    add   ebx,eax   \n    jmp   .nextstr1\n  .ret1:\n    xchg ebx,eax   \n    mov [sport], eax\n  \n  mov si, [sport]  \n  call _connect\n  cmp eax, 0\n  jnz short _fail\n  mov eax, msg\n  mov ecx, msglen\n  call _send\n  call _exit\n\n_fail:\n  mov edx, cerrlen\n  mov ecx, cerrmsg\n  call _print\n  call _exit\n\n\n_recverr: \n  call _exit\n_dced: \n  call _exit\n\nsection .data\ncerrmsg      db 'failed to connect :(',0xa\ncerrlen      equ $-cerrmsg\nmsg          db 'Hello socket world!',0xa\nmsglen       equ $-msg\n\nszIp         db '127.0.0.1',0\nszPort       db '256',0\n\nsection .bss\nsock         resd 1\n;general 'array' for syscall_socketcall argument arg.\ncArray       resd 1\n             resd 1\n\t     resd 1\n             resd 1\n\t     \n;send 'array'.\nsArray      resd 1\n            resd 1\n            resd 1\n            resd 1\n;duh?\nsockaddr_in resb 16\n;..\nsport       resb 2\nbuff        resb 1024\n\nWorks with: MASM\n\n.586\n.model flat,stdcall\noption casemap:none\n\ninclude \/masm32\/include\/windows.inc\ninclude \/masm32\/include\/user32.inc\ninclude \/masm32\/include\/kernel32.inc\ninclude \/masm32\/include\/ws2_32.inc\n   \nincludelib \/masm32\/lib\/user32.lib\nincludelib \/masm32\/lib\/kernel32.lib\nincludelib \/masm32\/lib\/ws2_32.lib\n\nWinMain proto :DWORD,:DWORD,:DWORD,:DWORD\n\n\n.data\n   \tClassName \tdb \"MainWinClass\",0\n   \tAppName  \tdb \"Async Sockets\",0\n   \tszSockStr\tdb \"Hello socket world!\",13,10,0\n   \tszIp\t\tdb \"127.0.0.1\",0\n   \tport\t\tdd 256\n   \t\n   \twsa\t\t\tWSADATA <>\n   \tsa\t\t\tsockaddr_in <>\n   \t\n.data?\n   \thInstance \tdd ?\n   \tCommandLine dd ?\n   \tsock\t\tdd ?\n   \t\n.const\nWM_SOCK\t\t\tequ WM_USER+100\n\n.code\nstart:\n\tinvoke WSAStartup, 200h, addr wsa\n\t.if eax!=NULL\n\t\tinvoke ExitProcess, eax \n\t.else\n\t\tinvoke GetModuleHandle, NULL\n\t\tmov    hInstance,eax\n\t\tinvoke GetCommandLine\n\t\tmov    CommandLine,eax\n\t\tinvoke WinMain, hInstance,NULL,CommandLine, SW_SHOWDEFAULT\n\t\tinvoke ExitProcess,eax\n\t.endif\n\nWinMain proc hInst:HINSTANCE,hPrevInst:HINSTANCE,CmdLine:LPSTR,CmdShow:DWORD\n\tLOCAL wc:WNDCLASSEX\n\tLOCAL msg:MSG\n\tLOCAL hwnd:HWND\n\t\n\tmov   wc.cbSize,SIZEOF WNDCLASSEX\n\tmov   wc.style, CS_HREDRAW or CS_VREDRAW\n\tmov   wc.lpfnWndProc, OFFSET WndProc\n\tmov   wc.cbClsExtra,NULL\n\tmov   wc.cbWndExtra,NULL\n\tpush  hInstance\n\tpop   wc.hInstance\n\tmov   wc.hbrBackground,COLOR_BTNFACE+1\n\tmov   wc.lpszMenuName,NULL\n\tmov   wc.lpszClassName,OFFSET ClassName\n\t\n\tinvoke LoadIcon,NULL,IDI_APPLICATION\n\tmov   wc.hIcon,eax\n\tmov   wc.hIconSm,eax\n\t\n\tinvoke LoadCursor,NULL,IDC_ARROW\n\tmov   wc.hCursor,eax\n\t\n\tinvoke RegisterClassEx, addr wc\n\tINVOKE CreateWindowEx,NULL,ADDR ClassName,ADDR AppName,\\\n           WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,\\\n           CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,\\\n           hInst,NULL\n\tmov   hwnd,eax\n\t\n\tinvoke ShowWindow, hwnd,SW_SHOWNORMAL\n\tinvoke UpdateWindow, hwnd\n\t\n\t.WHILE TRUE\n\t\tinvoke GetMessage, ADDR msg,NULL,0,0\n\t\t.BREAK .IF (!eax)\n\t\tinvoke TranslateMessage, ADDR msg\n\t\tinvoke DispatchMessage, ADDR msg\n\t.ENDW\n\t\n\tmov     eax,msg.wParam\n\tret\nWinMain endp\n\nWndProc proc hWnd:HWND, uMsg:UINT, wParam:WPARAM, lParam:LPARAM\n\t\n\t.IF uMsg==WM_DESTROY\n\t\tinvoke PostQuitMessage,NULL\n\t.ELSEIF uMsg==WM_CREATE\n\t\tinvoke socket, AF_INET,SOCK_STREAM, 0\n\t\t.if eax==INVALID_SOCKET\n\t\t\t;error\n\t\t.endif\n\t\tmov sock, eax\n\t\tinvoke WSAAsyncSelect, sock, hWnd, WM_SOCK, FD_CONNECT or FD_CLOSE\n\t\t.if eax==INVALID_SOCKET\n\t\t\t;error!\n\t\t.endif\n\t\tmov sa.sin_family, AF_INET\n\t\tinvoke inet_addr, addr szIp\n\t\tmov sa.sin_addr, eax\n\t\tinvoke htons, port\n\t\tmov sa.sin_port, ax\n\t\tinvoke connect, sock, addr sa, sizeof sa\n\t\t.if eax==SOCKET_ERROR\n\t\t\tinvoke WSAGetLastError\n\t\t\t.if eax!=WSAEWOULDBLOCK\n\t\t\t\t;real error.\n\t\t\t.endif\n\t\t.endif\n\t.elseif uMsg==WM_SOCK\n\t\tmov edx, lParam\n\t\t.if dx==FD_CONNECT\n\t\t\tshr edx, 16\n\t\t\t.if dx==NULL\n\t\t\t\tinvoke lstrlen, addr szSockStr\n\t\t\t\tinvoke send, sock, addr szSockStr, eax, 0\n\t\t\t.else\n\t\t\t\t;error\n\t\t\t.endif\n\t\t.elseif dx==FD_CLOSE\n\t\t\tshr edx, 16\n\t\t\t.if dx==NULL\n\t\t\t\tinvoke SendMessage, hWnd, WM_DESTROY, 0, 0\n\t\t\t.endif\n\t\t.endif\n\t.ELSE\n\t\tinvoke DefWindowProc,hWnd,uMsg,wParam,lParam\t\t\n\t\tret\n\t.ENDIF\n\t\n\txor eax,eax\n\tret\nWndProc endp\n\n\nend start\n\nWorks with: MASM\n\n.586\n.model flat,stdcall\noption casemap:none\n\ninclude \/masm32\/include\/windows.inc\ninclude \/masm32\/include\/user32.inc\ninclude \/masm32\/include\/kernel32.inc\ninclude \/masm32\/include\/ws2_32.inc\n   \nincludelib \/masm32\/lib\/user32.lib\nincludelib \/masm32\/lib\/kernel32.lib\nincludelib \/masm32\/lib\/ws2_32.lib\n\nWinMain proto :DWORD,:DWORD,:DWORD,:DWORD\n\n\n.data\n   \tClassName \tdb \"MainWinClass\",0\n   \tAppName  \tdb \"Blocking Sockets\",0\n   \tszSockStr\tdb \"Hello socket world!\",13,10,0\n   \tszIp\t\tdb \"127.0.0.1\",0\n   \tport\t\tdd 256\n   \t\n   \twsa\t\t\tWSADATA <>\n   \tsa\t\t\tsockaddr_in <>\n   \t\n.data?\n   \thInstance \tdd ?\n   \tCommandLine dd ?\n   \tsock\t\tdd ?\n\n.code\nstart:\n\tinvoke WSAStartup, 200h, addr wsa\n\t.if eax!=NULL\n\t\tinvoke ExitProcess, eax \n\t.else\n\t\tinvoke GetModuleHandle, NULL\n\t\tmov    hInstance,eax\n\t\tinvoke GetCommandLine\n\t\tmov    CommandLine,eax\n\t\tinvoke WinMain, hInstance,NULL,CommandLine, SW_SHOWDEFAULT\n\t\tinvoke ExitProcess,eax\n\t.endif\n\nWinMain proc hInst:HINSTANCE,hPrevInst:HINSTANCE,CmdLine:LPSTR,CmdShow:DWORD\n\tLOCAL wc:WNDCLASSEX\n\tLOCAL msg:MSG\n\tLOCAL hwnd:HWND\n\t\n\tmov   wc.cbSize,SIZEOF WNDCLASSEX\n\tmov   wc.style, CS_HREDRAW or CS_VREDRAW\n\tmov   wc.lpfnWndProc, OFFSET WndProc\n\tmov   wc.cbClsExtra,NULL\n\tmov   wc.cbWndExtra,NULL\n\tpush  hInstance\n\tpop   wc.hInstance\n\tmov   wc.hbrBackground,COLOR_BTNFACE+1\n\tmov   wc.lpszMenuName,NULL\n\tmov   wc.lpszClassName,OFFSET ClassName\n\t\n\tinvoke LoadIcon,NULL,IDI_APPLICATION\n\tmov   wc.hIcon,eax\n\tmov   wc.hIconSm,eax\n\t\n\tinvoke LoadCursor,NULL,IDC_ARROW\n\tmov   wc.hCursor,eax\n\t\n\tinvoke RegisterClassEx, addr wc\n\tINVOKE CreateWindowEx,NULL,ADDR ClassName,ADDR AppName,\\\n           WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,\\\n           CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,\\\n           hInst,NULL\n\tmov   hwnd,eax\n\t\n\tinvoke ShowWindow, hwnd,SW_SHOWNORMAL\n\tinvoke UpdateWindow, hwnd\n\t\n\t.WHILE TRUE\n\t\tinvoke GetMessage, ADDR msg,NULL,0,0\n\t\t.BREAK .IF (!eax)\n\t\tinvoke TranslateMessage, ADDR msg\n\t\tinvoke DispatchMessage, ADDR msg\n\t.ENDW\n\t\n\tmov     eax,msg.wParam\n\tret\nWinMain endp\n\nWndProc proc hWnd:HWND, uMsg:UINT, wParam:WPARAM, lParam:LPARAM\n\t\n\t.IF uMsg==WM_DESTROY\n\t\tinvoke PostQuitMessage,NULL\n\t.ELSEIF uMsg==WM_CREATE\n\t\tinvoke socket, AF_INET,SOCK_STREAM, 0\n\t\t.if eax==INVALID_SOCKET\n\t\t\t;error\n\t\t.endif\n\t\tmov sock, eax\n\t\tmov sa.sin_family, AF_INET\n\t\tinvoke inet_addr, addr szIp\n\t\tmov sa.sin_addr, eax\n\t\tinvoke htons, port\n\t\tmov sa.sin_port, ax\n\t\tinvoke connect, sock, addr sa, sizeof sa\n\t\tinvoke lstrlen, addr szSockStr\n\t\tinvoke send, sock, addr szSockStr, eax, 0\n\t.ELSE\n\t\tinvoke DefWindowProc,hWnd,uMsg,wParam,lParam\t\t\n\t\tret\n\t.ENDIF\n\t\n\txor eax,eax\n\tret\nWndProc endp\n\n\nend start\n\n","human_summarization":"Open a socket to localhost on port 256, send the message \"hello socket world\", and then close the socket. The code operates in non-blocking mode.","id":3591}
    {"lang_cluster":"X86_Assembly","source_code":"\n; x86_84 Linux nasm\nsection .text\n\nisPalindrome:\n  mov rsi, rax\n  mov rdi, rax\n\n  get_end:\n    cmp byte [rsi], 0\n    je get_result\n    inc rsi\n    jmp get_end\n\n  get_result:\n    mov rax, 0\n    dec rsi\n\n    compare:\n      mov cl, byte [rdi]\n      cmp byte [rsi], cl\n      jne not_palindrome\n      cmp rsi, rdi\n      je palindrome\n      inc rdi\n      cmp rdi, rsi\n      je palindrome\n      dec rsi\n      jmp compare\n\n  not_palindrome:\n    mov rax, 0\n    ret\n  palindrome:\n    mov rax, 1\n    ret\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":3592}
    {"lang_cluster":"Perl","source_code":"\n\nsub empty{ not @_ }\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy. The stack is accessed from its top and can be used for resource management, particularly memory.","id":3593}
    {"lang_cluster":"Perl","source_code":"\nsub fib_iter {\n  my $n = shift;\n  use bigint try => \"GMP,Pari\";\n  my ($v2,$v1) = (-1,1);\n  ($v2,$v1) = ($v1,$v2+$v1) for 0..$n;\n  $v1;\n}\nsub fibRec {\n    my $n = shift;\n    $n < 2\u00a0? $n\u00a0: fibRec($n - 1) + fibRec($n - 2);\n}\n\n# Uses GMP method so very fast\nuse Math::AnyNum qw\/fibonacci\/;\nsay fibonacci(10000);\n\n# Uses GMP method, so also very fast\nuse Math::GMP;\nsay Math::GMP::fibonacci(10000);\n\n# Binary ladder, GMP if available, Pure Perl otherwise\nuse ntheory qw\/lucasu\/;\nsay lucasu(1, -1, 10000);\n\n# All Perl\nuse Math::NumSeq::Fibonacci;\nmy $seq = Math::NumSeq::Fibonacci->new;\nsay $seq->ith(10000);\n\n# All Perl\nuse Math::Big qw\/fibonacci\/;\nsay 0+fibonacci(10000);  # Force scalar context\n\n# Perl, gives floating point *approximation*\nuse Math::Fibonacci qw\/term\/;\nsay term(10000);\n\n\nsub fibonacci {\n    my $n = shift;    \n    \n    return 0 if $n <  1;\n    return 1 if $n == 1;\n        \n    my @numbers = (0, 1);\n\n    push @numbers, $numbers[-1] + $numbers[-2] foreach 2 .. $n;\n    \n    return $numbers[-1];\n}\n\nprint \"Fibonacci($_) -> \", (fibonacci $_), \"\\n\"\n    foreach (0 .. 20, 50, 93, 94, 100, 200, 1000, 1476, 1477);\n\n","human_summarization":"The code generates the nth Fibonacci number using either an iterative or recursive approach. It optionally supports negative n values by inversely applying the Fibonacci sequence formula. The code stores all Fibonacci numbers up to n in an array and returns the nth Fibonacci number. It works best for positive integers and may switch to scientific notation for n>93 or treat numbers as infinite for n>1476. Performance is not typically an issue until 100k. The code can be optimized for large values using GMP.","id":3594}
    {"lang_cluster":"Perl","source_code":"\nmy @a = (1, 2, 3, 4, 5, 6);\nmy @even = grep { $_%2 == 0 } @a;\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":3595}
    {"lang_cluster":"Perl","source_code":"\nmy $str = 'abcdefgh';\nprint substr($str, 2, 3), \"\\n\"; # Returns 'cde'\nprint substr($str, 2), \"\\n\"; # Returns 'cdefgh'\nprint substr($str, 0, -1), \"\\n\"; #Returns 'abcdefg'\nprint substr($str, index($str, 'd'), 3), \"\\n\"; # Returns 'def'\nprint substr($str, index($str, 'de'), 3), \"\\n\"; # Returns 'def'\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":3596}
    {"lang_cluster":"Perl","source_code":"\n\nuse utf8;\nbinmode STDOUT, \":utf8\";\n\n# to reverse characters (code points):\nprint scalar reverse('visor'), \"\\n\";\n\n# to reverse graphemes:\nprint join(\"\", reverse \"Jos\u00e9\" =~ \/\\X\/g), \"\\n\";\n\n$string = '\u2135\u0391\u03a9 \u99f1\u99dd\u9053 \ud83e\udd14 \ud83c\uddf8\ud83c\udde7 \ud83c\uddfa\ud83c\uddf8 \ud83c\uddec\ud83c\udde7\u200d \ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc66\ud83c\udd97\ud83d\uddfa';\nprint join(\"\", reverse $string =~ \/\\X\/g), \"\\n\";\n\n","human_summarization":"\"Reverses a given string while preserving the order of Unicode combining characters. For instance, it transforms \"asdf\" into \"fdsa\" and \"as\u20dddf\u0305\" into \"f\u0305ds\u20dda\". Note: the reverse() function is applicable to Lists or scalars, not strings.\"","id":3597}
    {"lang_cluster":"Perl","source_code":"use Math::Cartesian::Product;\n\n# Pregenerate all forward and reverse translations\nsub playfair {\n    our($key,$from) = @_;\n    $from \/\/= 'J';\n    our $to = $from eq 'J' ? 'I' : '';\n    my(%ENC,%DEC,%seen,@m);\n\n    sub canon {\n        my($str) = @_;\n        $str =~ s\/[^[:alpha:]]\/\/g;\n        $str =~ s\/$from\/$to\/gi;\n        uc $str;\n    }\n\n    my @uniq = grep { ! $seen{$_}++ } split '', canon($key . join '', 'A'..'Z');\n    while (@uniq) { push @m, [splice @uniq, 0, 5] }\n\n    # Map pairs in same row.\n    for my $r (@m)  {\n        for my $x (cartesian {@_} [0..4], [0..4]) {\n        my($i,$j) = @$x;\n        next if $i == $j;\n        $ENC{ @$r[$i] . @$r[$j] } =  @$r[($i+1)%5] . @$r[($j+1)%5];\n        }\n    }\n\n    # Map pairs in same column.\n    for my $c (0..4) {\n        my @c = map { @$_[$c] } @m;\n        for my $x (cartesian {@_} [0..4], [0..4]) {\n        my($i,$j) = @$x;\n        next if $i == $j;\n        $ENC{ $c[$i] . $c[$j] } = $c[($i+1)%5] . $c[($j+1)%5];\n        }\n    }\n\n    # Map pairs with cross-connections.\n    for my $x (cartesian {@_} [0..4], [0..4], [0..4], [0..4]) {\n        my($i1,$j1,$i2,$j2) = @$x;\n        next if $i1 == $i2 or $j1 == $j2;\n        $ENC{ $m[$i1][$j1] . $m[$i2][$j2] } = $m[$i1][$j2] . $m[$i2][$j1];\n    }\n\n    # Generate reverse translations.\n     while (my ($k, $v) = each %ENC) { $DEC{$v} = $k }\n\n    # Return code-refs for encoding\/decoding routines\n    return\n    sub { my($red) = @_; # encode\n        my $str = canon($red);\n\n        my @list;\n        while ($str =~ \/(.)(?(?=\\1)|(.?))\/g) {\n            push @list, substr($str,$-[0], $-[2] ? 2 : 1);\n        }\n        join ' ', map { length($_)==1 ? $ENC{$_.'X'} : $ENC{$_} } @list;\n    },\n    sub { my($black) = @_; # decode\n        join ' ', map { $DEC{$_} } canon($black) =~ \/..\/g;\n    }\n}\n\nmy($encode,$decode) = playfair('Playfair example');\n\nmy $orig  = \"Hide the gold in...the TREESTUMP!!!\";\nmy $black = &$encode($orig);\nmy $red   = &$decode($black);\nprint \" orig:\\t$orig\\n\";\nprint \"black:\\t$black\\n\";\nprint \"  red:\\t$red\\n\";\n\n\n","human_summarization":"Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.","id":3598}
    {"lang_cluster":"Perl","source_code":"\nuse strict;\nuse warnings;\nuse constant True => 1;\n\nsub add_edge {\n    my ($g, $a, $b, $weight) = @_;\n    $g->{$a} ||= {name => $a};\n    $g->{$b} ||= {name => $b};\n    push @{$g->{$a}{edges}}, {weight => $weight, vertex => $g->{$b}};\n}\n\nsub push_priority {\n    my ($a, $v) = @_;\n    my $i = 0;\n    my $j = $#{$a};\n    while ($i <= $j) {\n        my $k = int(($i + $j) \/ 2);\n        if ($a->[$k]{dist} >= $v->{dist}) { $j = $k - 1 }\n        else                              { $i = $k + 1 }\n    }\n    splice @$a, $i, 0, $v;\n}\n\nsub dijkstra {\n    my ($g, $a, $b) = @_;\n    for my $v (values %$g) {\n        $v->{dist} = 10e7; # arbitrary large value\n        delete @$v{'prev', 'visited'}\n     }\n    $g->{$a}{dist} = 0;\n    my $h = [];\n    push_priority($h, $g->{$a});\n    while () {\n        my $v = shift @$h;\n        last if !$v or $v->{name} eq $b;\n        $v->{visited} = True;\n        for my $e (@{$v->{edges}}) {\n            my $u = $e->{vertex};\n            if (!$u->{visited} && $v->{dist} + $e->{weight} <= $u->{dist}) {\n                $u->{prev} = $v;\n                $u->{dist} = $v->{dist} + $e->{weight};\n                push_priority($h, $u);\n            }\n        }\n    }\n}\n\nmy $g = {};\nadd_edge($g, @$_) for\n (['a', 'b',  7], ['a', 'c',  9], ['a', 'f', 14],\n  ['b', 'c', 10], ['b', 'd', 15], ['c', 'd', 11],\n  ['c', 'f',  2], ['d', 'e',  6], ['e', 'f',  9]);\n\ndijkstra($g, 'a', 'e');\n\nmy $v = $g->{e};\nmy @a;\nwhile ($v) {\n    push @a, $v->{name};\n    $v = $v->{prev};\n}\nmy $path = join '', reverse @a;\nprint \"$g->{e}{dist} $path\\n\";\n\n\n","human_summarization":"Implement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges representing the shortest path to each reachable node. The program also interprets the output to display the shortest path from the source node to specific nodes.","id":3599}
    {"lang_cluster":"Perl","source_code":"use strict;\n\nsub circles {\n    my ($x1, $y1, $x2, $y2, $r) = @_;\n\n    return \"Radius is zero\" if $r == 0;\n    return \"Coincident points gives infinite number of circles\" if $x1 == $x2 and $y1 == $y2;\n\n    # delta x, delta y between points\n    my ($dx, $dy) = ($x2 - $x1, $y2 - $y1);\n    my $q = sqrt($dx**2 + $dy**2);\n    return \"Separation of points greater than diameter\" if $q > 2*$r;\n\n    # halfway point\n    my ($x3, $y3) = (($x1 + $x2) \/ 2, ($y1 + $y2) \/ 2);\n    # distance along the mirror line\n    my $d = sqrt($r**2-($q\/2)**2);\n\n    # pair of solutions\n    sprintf '(%.4f,\u00a0%.4f) and (%.4f,\u00a0%.4f)',\n        $x3 - $d*$dy\/$q, $y3 + $d*$dx\/$q,\n        $x3 + $d*$dy\/$q, $y3 - $d*$dx\/$q;\n}\n\nmy @arr = (\n    [0.1234, 0.9876, 0.8765, 0.2345, 2.0],\n    [0.0000, 2.0000, 0.0000, 0.0000, 1.0],\n    [0.1234, 0.9876, 0.1234, 0.9876, 2.0],\n    [0.1234, 0.9876, 0.8765, 0.2345, 0.5],\n    [0.1234, 0.9876, 0.1234, 0.9876, 0.0]\n);\n\nprintf \"(%.4f,\u00a0%.4f) and (%.4f,\u00a0%.4f) with radius\u00a0%.1f: %s\\n\", @$_[0..4], circles @$_ for @arr;\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":3600}
    {"lang_cluster":"Perl","source_code":"Library: ntheory\nuse strict;\nuse warnings;\nuse ntheory 'fromdigits';\n\n# sboxes from http:\/\/en.wikipedia.org\/wiki\/GOST_(block_cipher)\nmy @sbox = (\n    [4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3],\n    [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9],\n    [5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11],\n    [7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3],\n    [6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2],\n    [4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14],\n    [13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12],\n    [1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12]\n);\n\nsub rol32 {\n    my($y, $n) = @_;\n    ($y << $n) % 2**32 | ($y >> (32 - $n))\n}\n\nsub GOST_round {\n    my($R, $K) = @_;\n    my $a = ($R + $K) % 2**32;\n    my $b = fromdigits([map { $sbox[$_][($a >> (4*$_))%16] } reverse 0..7],16);\n    rol32($b,11);\n}\n\nsub feistel_step {\n    my($F, $L, $R, $K) = @_;\n    $R, $L ^ &$F($R, $K)\n}\n\nmy @input = (0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04);\nmy @key   = (0xF9, 0x04, 0xC1, 0xE2);\n\nmy $R = fromdigits([reverse @input[0..3]], 256); # 1st half\nmy $L = fromdigits([reverse @input[4..7]], 256); # 2nd half\nmy $K = fromdigits([reverse @key        ], 256);\n\n($L,$R) = feistel_step(\\&GOST_round, $L, $R, $K);\n\nprintf '%02X ', (($L << 32) + $R >> (8*$_))%256 for 0..7;\nprint \"\\n\";\n\n\n","human_summarization":"Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.","id":3601}
    {"lang_cluster":"Perl","source_code":"\nwhile (1) {\n    my $a = int(rand(20));\n    print \"$a\\n\";\n    if ($a == 10) {\n        last;\n    }\n    my $b = int(rand(20));\n    print \"$b\\n\";\n}\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":3602}
    {"lang_cluster":"Perl","source_code":"\nuse strict;\nuse utf8;\n\nsub factors {\n\tmy $n = shift;\n\tmy $p = 2;\n\tmy @out;\n \n\twhile ($n >= $p * $p) {\n\t\twhile ($n % $p == 0) {\n\t\t\tpush @out, $p;\n\t\t\t$n \/= $p;\n\t\t}\n\t\t$p = next_prime($p);\n\t}\n\tpush @out, $n if $n > 1 || !@out;\n\t@out;\n}\n \nsub next_prime {\n\tmy $p = shift;\n\tdo { $p = $p == 2 ? 3 : $p + 2 } until is_prime($p);\n\t$p;\n}\n \nmy %pcache;\nsub is_prime { \n\tmy $x = shift;\n\t$pcache{$x} \/\/=\t(factors($x) == 1)\n}\n\nsub mtest {\n\tmy @bits = split \"\", sprintf(\"%b\", shift);\n\tmy $p = shift;\n\tmy $sq = 1;\n\twhile (@bits) {\n\t\t$sq = $sq * $sq;\n\t\t$sq *= 2 if shift @bits;\n\t\t$sq %= $p;\n\t}\n\t$sq == 1;\n}\n\nfor my $m (2 .. 60, 929) {\n\tnext unless is_prime($m);\n\tuse bigint;\n\n\tmy ($f, $k, $x) = (0, 0, 2**$m - 1);\n\n\tmy $q;\n\twhile (++$k) {\n\t\t$q = 2 * $k * $m + 1;\n\t\tnext if (($q & 7) != 1 && ($q & 7) != 7);\n\t\tnext unless is_prime($q);\n\t\tlast if $q * $q > $x;\n\t\tlast if $f = mtest($m, $q);\n\t}\n\n\tprint $f? \"M$m = $x = $q \u00d7 @{[$x \/ $q]}\\n\"\n\t\t: \"M$m = $x is prime\\n\";\n}\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number, specifically 2^929-1. The method uses the modPow operation, binary conversion of the exponent, and a Lucas-Lehmer test to efficiently determine if a number is a factor of the Mersenne number. The code also utilizes GMP's modular exponentiation and a simple probable prime test for small numbers. It stops when 2kP+1 > sqrt(N). The method is optimized for Mersenne numbers where P is prime.","id":3603}
    {"lang_cluster":"Perl","source_code":"\nLibrary: XML::XPathXPath\nuse XML::XPath qw();\n\nmy $x = XML::XPath->new('<inventory ... <\/inventory>');\n\n[$x->findnodes('\/\/item[1]')->get_nodelist]->[0];\nprint $x->findnodes_as_string('\/\/price');\n$x->findnodes('\/\/name')->get_nodelist;\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":3604}
    {"lang_cluster":"Perl","source_code":"\n\nuse strict;\n\npackage Set; # likely will conflict with stuff on CPAN\nuse overload\n\t'\"\"'\t=> \\&str,\n\t'bool'\t=> \\&count,\n\t'+='\t=> \\&add,\n\t'-='\t=> \\&del,\n\t'-'\t=> \\&diff,\n\t'=='\t=> \\&eq,\n\t'&'\t=> \\&intersection,\n\t'|'\t=> \\&union,\n\t'^'\t=> \\&xdiff;\n\nsub str {\n\tmy $set = shift;\n\t# This has drawbacks: stringification is used as set key\n\t# if the set is added to another set as an element, which\n\t# may cause inconsistencies if the element set is modified\n\t# later.  In general, a hash key loses its object identity\n\t# anyway, so it's not unique to us.\n\t\"Set{ \".  join(\", \" => sort map(\"$_\", values %$set)) . \" }\"\n}\n\nsub new {\n\tmy $pkg = shift;\n\tmy $h = bless {};\n\t$h->add($_) for @_;\n\t$h\n}\n\nsub add {\n\tmy ($set, $elem) = @_;\n\t$set->{$elem} = $elem;\n\t$set\n}\n\nsub del {\n\tmy ($set, $elem) = @_;\n\tdelete $set->{$elem};\n\t$set\n}\n\nsub has { # set has element\n\tmy ($set, $elem) = @_;\n\texists $set->{$elem}\n}\n\nsub union {\n\tmy ($this, $that) = @_;\n\tbless { %$this, %$that }\n}\n\nsub intersection {\n\tmy ($this, $that) = @_;\n\tmy $s = new Set;\n\tfor (keys %$this) {\n\t\t$s->{$_} = $this->{$_} if exists $that->{$_}\n\t}\n\t$s\n}\n\nsub diff {\n\tmy ($this, $that) = @_;\n\tmy $s = Set->new;\n\tfor (keys %$this) {\n\t\t$s += $this->{$_} unless exists $that->{$_}\n\t}\n\t$s\n}\n\nsub xdiff { # xor, symmetric diff\n\tmy ($this, $that) = @_;\n\tmy $s = new Set;\n\tbless { %{ ($this - $that) | ($that - $this) } }\n}\n\nsub count { scalar(keys %{+shift}) }\n\nsub eq {\n\tmy ($this, $that) = @_;\n\t!($this - $that) && !($that - $this);\n}\n\nsub contains { # this is a superset of that\n\tmy ($this, $that) = @_;\n\tfor (keys %$that) {\n\t\treturn 0 unless $this->has($_)\n\t}\n\treturn 1\n}\n\npackage main;\nmy ($x, $y, $z, $w);\n\n$x = Set->new(1, 2, 3);\n$x += $_ for (5 .. 7);\n$y = Set->new(1, 2, 4, $x); # not the brightest idea\n\nprint \"set x is: $x\\nset y is: $y\\n\";\nfor (1 .. 4, $x) {\n\tprint \"$_ is\", $y->has($_) ? \"\" : \" not\", \" in y\\n\";\n}\n\nprint \"union: \", $x | $y, \"\\n\";\nprint \"intersect: \", $x & $y, \"\\n\";\nprint \"z = x - y = \", $z = $x - $y, \"\\n\";\nprint \"y is \", $x->contains($y) ? \"\" : \"not \", \"a subset of x\\n\";\nprint \"z is \", $x->contains($z) ? \"\" : \"not \", \"a subset of x\\n\";\nprint \"z = (x | y) - (x & y) = \", $z = ($x | $y) - ($x & $y), \"\\n\";\nprint \"w = x ^ y = \", $w = ($x ^ $y), \"\\n\";\nprint \"w is \", ($w == $z) ? \"\" : \"not \", \"equal to z\\n\";\nprint \"w is \", ($w == $x) ? \"\" : \"not \", \"equal to x\\n\";\n\n","human_summarization":"demonstrate various set operations including set creation, testing for an element in a set, performing union, intersection, and difference operations between two sets, checking if a set is a subset or equal to another set. Optional operations such as modifying a mutable set and additional set operations may also be included. The set could be implemented using an associative array, a binary search tree, a hash table, or an ordered array of binary bits. The code also includes the time complexity of the basic test operation with different data structures. It also references Set::Object from CPAN for a more robust implementation.","id":3605}
    {"lang_cluster":"Perl","source_code":"\n#! \/usr\/bin\/perl -w\n\nuse Time::Local;\nuse strict;\n\nforeach my $i (2008 .. 2121)\n{\n  my $time = timelocal(0,0,0,25,11,$i);\n  my ($s,$m,$h,$md,$mon,$y,$wd,$yd,$is) = localtime($time);\n  if ( $wd == 0 )\n  {\n    print \"25 Dec $i is Sunday\\n\";\n  }\n}\n\nexit 0;\n\n","human_summarization":"\"Determines the years between 2008 and 2121 when Christmas falls on a Sunday by using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date handling, such as overflow in types used to represent dates\/times.\"","id":3606}
    {"lang_cluster":"Perl","source_code":"\n\nuse strict;\nuse warnings;\n\nuse PDL;\nuse PDL::LinearAlgebra qw(mqr);\n\nmy $a = pdl(\n      [12, -51,   4],\n      [ 6, 167, -68],\n      [-4,  24, -41],\n      [-1,   1,   0],\n      [ 2,   0,   3]\n);\n\nmy ($q, $r) = mqr($a);\nprint $q, $r, $q x $r;\n\n\n","human_summarization":"The code performs QR decomposition of a given matrix using the method of Householder reflections. It demonstrates this by decomposing a sample matrix from a Wikipedia article. The code also applies the QR decomposition to solve linear least squares problems from Polynomial regression. It handles cases where the matrix is not square by cutting off zero padded bottom rows. The decomposition process involves reflecting a given vector about a plane, transforming the matrix to remove all subdiagonal elements, and producing an orthogonal matrix. The code also solves the square upper triangular system by back substitution.","id":3607}
    {"lang_cluster":"Perl","source_code":"\nLibrary: List::MoreUtilsMoreUtils\n\nuse List::MoreUtils qw(uniq);\n\nmy @uniq = uniq qw(1 2 3 a b c 2 3 4 b c d);\n\nmy %seen;\nmy @uniq = grep {!$seen{$_}++} qw(1 2 3 a b c 2 3 4 b c d);\n\nmy %hash = map { $_ => 1 } qw(1 2 3 a b c 2 3 4 b c d);\nmy @uniq = keys %hash;\n\nmy %seen;\n@seen{qw(1 2 3 a b c 2 3 4 b c d)} = ();\nmy @uniq = keys %seen;\n","human_summarization":"implement three methods to remove duplicate elements from an array. The first method uses a hash table to eliminate duplicates, the second method sorts the elements and removes consecutive duplicates, and the third method iterates through the list, checking and discarding any repeated elements. The order of first appearance of each element is preserved. Note that the solutions may convert elements to strings in the result, hence losing the ability to be dereferenced.","id":3608}
    {"lang_cluster":"Perl","source_code":"\nsub quick_sort {\n    return @_ if @_ < 2;\n    my $p = splice @_, int rand @_, 1;\n    quick_sort(grep $_ < $p, @_), $p, quick_sort(grep $_ >= $p, @_);\n}\n\nmy @a = (4, 65, 2, -31, 0, 99, 83, 782, 1);\n@a = quick_sort @a;\nprint \"@a\\n\";\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":3609}
    {"lang_cluster":"Perl","source_code":"\nLibrary: POSIX\nuse POSIX;\n\nprint strftime('%Y-%m-%d', 0, 0, 0, 10, 10, 107), \"\\n\";\nprint strftime('%A, %B %d, %Y', 0, 0, 0, 10, 10, 107), \"\\n\";\n\n\n","human_summarization":"display the current date in the formats \"2007-11-23\" and \"Friday, November 23, 2007\".","id":3610}
    {"lang_cluster":"Perl","source_code":"\n\n\nuse Algorithm::Combinatorics \"subsets\";\nmy @S = (\"a\",\"b\",\"c\");\nmy @PS;\nmy $iter = subsets(\\@S);\nwhile (my $p = $iter->next) {\n  push @PS, \"[@$p]\"\n}\nsay join(\"  \",@PS);\n\n\n","human_summarization":"The code defines a function that takes a set as input and generates its power set. It handles edge cases such as an empty set and a set containing only the empty set. The code also demonstrates the ability to handle large sets with minimal memory usage. It uses either a built-in set type or a custom-defined set type with necessary operations. The code also provides solutions using recursion and list folding. It uses an iterator to process each subset immediately, reducing memory usage. It also demonstrates the use of Perl's List::Util core module and the CPAN module Set::Object for set implementation.","id":3611}
    {"lang_cluster":"Perl","source_code":"\n\nmy @symbols = ( [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']  );\n\nsub roman {\n  my($n, $r) = (shift, '');\n  ($r, $n) = ('-', -$n) if $n < 0;  # Optional handling of negative input\n  foreach my $s (@symbols) {\n    my($arabic, $roman) = @$s;\n    ($r, $n) = ($r .= $roman x int($n\/$arabic),  $n\u00a0% $arabic)\n       if $n >= $arabic;\n  }\n  $r;\n}\n\nsay roman($_) for 1..2012;\nuse Math::Roman qw\/roman\/;\nsay roman($_) for 1..2012'\nuse List::MoreUtils qw( natatime );\n\nmy %symbols = (\n    1 => \"I\", 5 => \"V\", 10 => \"X\", 50 => \"L\", 100 => \"C\",\n    500 => \"D\", 1_000 => \"M\"\n);\n\nmy @subtractors = (\n        1_000, 100,  500, 100,  100, 10,  50, 10,  10, 1,  5, 1,  1, 0\n);\n\nsub roman {\n    return '' if 0 == (my $n = shift);\n    my $iter = natatime 2, @subtractors;\n    while( my ($cut, $minus) = $iter->() ) {\n        $n >= $cut\n            and return $symbols{$cut} . roman($n - $cut);\n        $n >= $cut - $minus\n            and return $symbols{$minus} . roman($n + $minus);\n    }\n};\n\nprint roman($_) . \"\\n\" for 1..2012;\n","human_summarization":"The code is a function that takes a positive integer as input and returns its equivalent in Roman numerals. It processes each digit separately, from left to right, skipping zeros. The function is simple, efficient, and doesn't require any experimental modules. It produces the same output as the Math::Roman module and the Raku example.","id":3612}
    {"lang_cluster":"Perl","source_code":"\n\n my @empty;\n my @empty_too = ();\n \n my @populated   = ('This', 'That', 'And', 'The', 'Other');\n print $populated[2];  # And\n \n my $aref = ['This', 'That', 'And', 'The', 'Other'];\n print $aref->[2];  # And\n\nmy @arr;\n\npush @arr, 1;\npush @arr, 3;\n\n$arr[0] = 2;\n\nprint $arr[0];\n\n my @multi_dimensional = (\n     [0, 1, 2, 3],\n     [qw(a b c d e f g)],\n     [qw(! $\u00a0% & *)],\n );\n","human_summarization":"demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning values, and retrieving elements. It also showcases the use of both fixed-length and dynamic arrays, as well as the process of pushing a value into the array. The code also includes examples of in-line, dynamic, and two-dimensional arrays.","id":3613}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.8.8\n#!\/usr\/bin\/perl\n\nopen my $fh_in, '<', 'input.txt' or die \"could not open <input.txt> for reading: $!\";\nopen my $fh_out, '>', 'output.txt' or die \"could not open <output.txt> for writing: $!\";\n# '>' overwrites file, '>>' appends to file, just like in the shell\n\nbinmode $fh_out; # marks filehandle for binary content on systems where that matters\n\nprint $fh_out $_ while <$fh_in>;\n# prints current line to file associated with $fh_out filehandle\n\n# the same, less concise\n#while (<$fh_in>) {\n#  print $fh_out $_;\n#};\n\nclose $fh_in;\nclose $fh_out;\n\n","human_summarization":"demonstrate how to create a file named \"output.txt\" and write into it the contents of \"input.txt\" file using an intermediate variable. The program also showcases reading from a file into a variable and writing a variable's contents into a file. It also highlights the use of Perl's IO disciplines for automatic application of chainable transformations on the input and output.","id":3614}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.x\nmy $string = \"alphaBETA\";\nprint uc($string), \"\\n\"; # => \"ALPHABETA\"\nprint lc($string), \"\\n\"; # => \"alphabeta\"\n$string =~ tr\/[a-z][A-Z]\/[A-Z][a-z]\/; print \"$string\\n\"; # => ALPHAbeta \n\nprint ucfirst($string), \"\\n\"; # => \"AlphaBETA\"\nprint lcfirst(\"FOObar\"), \"\\n\"; # => \"fOObar\"\n\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to both upper-case and lower-case using the default encoding or ASCII. The code also showcases additional case conversion functions available in the language library, such as swapping case or capitalizing the first letter. The code is compatible with Perl 4 if \"my\" is removed.","id":3615}
    {"lang_cluster":"Perl","source_code":"\n\nuse strict;\nuse warnings;\nuse POSIX qw(ceil);\n\nsub dist {\n   my ($a, $b) = @_;\n   return sqrt(($a->[0] - $b->[0])**2 +\n               ($a->[1] - $b->[1])**2)\n}\n\nsub closest_pair_simple {\n    my @points = @{ shift @_ };\n    my ($a, $b, $d) = ( $points[0], $points[1], dist($points[0], $points[1]) );\n    while( @points ) {\n        my $p = pop @points;\n        for my $l (@points) {\n            my $t = dist($p, $l);\n            ($a, $b, $d) = ($p, $l, $t) if $t < $d;\n        }\n    }\n    $a, $b, $d\n}\n\nsub closest_pair {\n   my @r = @{ shift @_ };\n   closest_pair_real( [sort { $a->[0] <=> $b->[0] } @r], [sort { $a->[1] <=> $b->[1] } @r] )\n}\n\nsub closest_pair_real {\n    my ($rx, $ry) = @_;\n    return closest_pair_simple($rx) if scalar(@$rx) <= 3;\n\n    my(@yR, @yL, @yS);\n    my $N = @$rx;\n    my $midx = ceil($N\/2)-1;\n    my @PL = @$rx[      0 .. $midx];\n    my @PR = @$rx[$midx+1 .. $N-1];\n    my $xm = $$rx[$midx]->[0];\n    $_->[0] <= $xm ? push @yR, $_ : push @yL, $_ for @$ry;\n    my ($al, $bl, $dL) = closest_pair_real(\\@PL, \\@yR);\n    my ($ar, $br, $dR) = closest_pair_real(\\@PR, \\@yL);\n    my ($w1, $w2, $closest) = $dR > $dL ? ($al, $bl, $dL) : ($ar, $br, $dR);\n    abs($xm - $_->[0]) < $closest and push @yS, $_ for @$ry;\n\n    for my $i (0 .. @yS-1) {\n        my $k = $i + 1;\n        while ( $k <= $#yS and ($yS[$k]->[1] - $yS[$i]->[1]) < $closest ) {\n            my $d = dist($yS[$k], $yS[$i]);\n            ($w1, $w2, $closest) = ($yS[$k], $yS[$i], $d) if $d < $closest;\n            $k++;\n        }\n    }\n    $w1, $w2, $closest\n}\n\nmy @points;\npush @points, [rand(20)-10, rand(20)-10] for 1..5000;\nprintf \"%.8f between (%.5f,\u00a0%.5f), (%.5f,\u00a0%.5f)\\n\", $_->[2], @{$$_[0]}, @{$$_[1]}\n    for [closest_pair_simple(\\@points)], [closest_pair(\\@points)];\n\n\n","human_summarization":"The code provides two functions to solve the Closest Pair of Points problem in a two-dimensional space. The first function uses a brute-force algorithm with a time complexity of O(n^2) to find the closest pair of points among a given set. The second function uses a more efficient divide and conquer approach with a time complexity of O(n log n) to solve the same problem. The divide and conquer function is significantly faster than the brute-force function.","id":3616}
    {"lang_cluster":"Perl","source_code":"\n\nuse strict;\nmy @c = (); # create an empty \"array\" collection\n\n# fill it\npush @c, 10, 11, 12;\npush @c, 65;\n# print it\nprint join(\" \",@c) . \"\\n\";\n\n# create an empty hash\nmy %h = ();\n# add some pair\n$h{'one'} = 1;\n$h{'two'} = 2;\n# print it\nforeach my $i ( keys %h ) {\n    print $i . \" -> \" . $h{$i} . \"\\n\";\n}\n","human_summarization":"The code creates a collection and adds several values to it, using the concept of collections in statically-typed languages where values are typically of a common data type. The code may involve usage of arrays, associative arrays, compound data types, linked lists, queues, sets, stacks, and Perl's array and hashes.","id":3617}
    {"lang_cluster":"Perl","source_code":"\n\nmy (@names, @val, @weight, @vol, $max_vol, $max_weight, $vsc, $wsc);\n\nif (1) { # change 1 to 0 for different data set\n        @names  = qw(panacea    icor    gold);\n        @val    = qw(3000       1800    2500);\n        @weight = qw(3          2       20  );\n        @vol    = qw(25         15      2   );\n        $max_weight = 250;\n        $max_vol = 250;\n        $vsc = 1000;\n        $wsc = 10;\n} else { # with these numbers cache would have been useful\n        @names  = qw(panacea    icor    gold    banana  monkey  );\n        @val    = qw(17         11      5       3       34      );\n        @weight = qw(14         3       2       2       10      );\n        @vol    = qw(3          4       2       1       12      );\n        $max_weight = 150;\n        $max_vol = 100;\n        $vsc = $wsc = 1;\n}\n\nmy @cache;\nmy ($hits, $misses) = (0, 0);\nsub solu {\n        my ($i, $w, $v) = @_;\n        return [0, []] if $i < 0;\n\n        if ($cache[$i][$w][$v]) {\n                $hits ++;\n                return $cache[$i][$w][$v]\n        }\n        $misses ++;\n\n        my $x = solu($i - 1, $w, $v);\n\n        my ($w1, $v1);\n        for (my $t = 1; ; $t++) {\n                last if ($w1 = $w - $t * $weight[$i]) < 0;\n                last if ($v1 = $v - $t * $vol[$i]) < 0;\n\n                my $y = solu($i - 1, $w1, $v1);\n\n                if ( (my $tmp = $y->[0] + $val[$i] * $t) > $x->[0] ) {\n                        $x = [ $tmp, [ @{$y->[1]}, [$i, $t] ] ];\n                }\n        }\n\n        $cache[$i][$w][$v] = $x\n}\n\nmy $x = solu($#names, $max_weight, $max_vol);\nprint   \"Max value $x->[0], with:\\n\",\n        \"    Item\\tQty\\tWeight   Vol    Value\\n\", '-'x 50, \"\\n\";\n\nmy ($wtot, $vtot) = (0, 0);\nfor (@{$x->[1]}) {\n        my $i = $_->[0];\n        printf  \"    $names[$i]:\\t% 3d \u00a0% 8d% 8g% 8d\\n\",\n                $_->[1],\n                $weight[$i] * $_->[1] \/ $wsc,\n                $vol[$i] * $_->[1] \/ $vsc,\n                $val[$i] * $_->[1];\n\n        $wtot += $weight[$i] * $_->[1];\n        $vtot += $vol[$i] * $_->[1];\n}\nprint   \"-\" x 50, \"\\n\";\nprintf  \"    Total:\\t    \u00a0% 8d% 8g% 8d\\n\",\n        $wtot\/$wsc, $vtot\/$vsc, $x->[0];\n\nprint \"\\nCache hit: $hits\\tmiss: $misses\\n\";\n\n","human_summarization":"\"Output: The code calculates the maximum value of items a traveler can carry in his knapsack, given the weight and volume constraints, from a selection of items with varying values, weights, and volumes. It uses a dynamic programming approach to solve the unbounded knapsack problem and only needs to provide one of the four possible solutions.\"","id":3618}
    {"lang_cluster":"Perl","source_code":"\nfor my $i(1..10) {\n    print $i;\n    last if $i == 10;\n    print ', ';\n}\nprint \"\\n\";\n\nprint join(', ', 1..10), \"\\n\";\n","human_summarization":"generates a comma-separated list from 1 to 10 using a loop, with separate output statements for the number and the comma. In the last iteration, only the number is outputted, not the comma. This task is typically solved in Perl using join.","id":3619}
    {"lang_cluster":"Perl","source_code":"\n\nsub print_topo_sort {\n    my %deps = @_;\n\n    my %ba;\n    while ( my ( $before, $afters_aref ) = each %deps ) {\n        for my $after ( @{ $afters_aref } ) {\n            $ba{$before}{$after} = 1 if $before ne $after;\n            $ba{$after} ||= {};\n        }\n    }\n\n    while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) {\n        print \"@afters\\n\";\n        delete @ba{@afters};\n        delete @{$_}{@afters} for values %ba;\n    }\n\n    print !!%ba ? \"Cycle found! \". join( ' ', sort keys %ba ). \"\\n\" : \"---\\n\";\n}\n\nmy %deps = (\n    des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02\n                                                        dw01 ramlib ieee )],\n    dw01           => [qw( ieee dw01 dware gtech                         )],\n    dw02           => [qw( ieee dw02 dware                               )],\n    dw03           => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech  )],\n    dw04           => [qw( dw04 ieee dw01 dware gtech                    )],\n    dw05           => [qw( dw05 ieee dware                               )],\n    dw06           => [qw( dw06 ieee dware                               )],\n    dw07           => [qw( ieee dware                                    )],\n    dware          => [qw( ieee dware                                    )],\n    gtech          => [qw( ieee gtech                                    )],\n    ramlib         => [qw( std ieee                                      )],\n    std_cell_lib   => [qw( ieee std_cell_lib                             )],\n    synopsys       => [qw(                                               )],\n);\nprint_topo_sort(%deps);\npush @{ $deps{'dw01'} }, 'dw04'; # Add unresolvable dependency\nprint_topo_sort(%deps);\n\n","human_summarization":"implement a function to perform a topological sort on VHDL libraries based on their dependencies. The function returns a valid compile order, flags un-orderable dependencies, and ignores self-dependencies. It also allows for parallel building of independent libraries. The function uses either Kahn's 1962 topological sort or depth-first search algorithm.","id":3620}
    {"lang_cluster":"Perl","source_code":"\n\n$str1 =~ \/^\\Q$str2\\E\/  # true if $str1 starts with $str2\n$str1 =~ \/\\Q$str2\\E\/   # true if $str1 contains $str2\n$str1 =~ \/\\Q$str2\\E$\/  # true if $str1 ends with $str2\n\n\nindex($str1, $str2) == 0                               # true if $str1 starts with $str2\nindex($str1, $str2) != -1                              # true if $str1 contains $str2\nrindex($str1, $str2) == length($str1) - length($str2)  # true if $str1 ends with $str2\n\n\nsubstr($str1, 0, length($str2)) eq $str2  # true if $str1 starts with $str2\nsubstr($str1, - length($str2)) eq $str2   # true if $str1 ends with $str2\n\n\nprint $-[0], \"\\n\" while $str1 =~ \/\\Q$str2\\E\/g;  # using a regex\n\nmy $i = -1; print $i, \"\\n\" while ($i = index $str1, $str2, $i + 1) != -1;  # using index\n\n","human_summarization":"- Checks if the first string starts with the second string\n- Checks if the first string contains the second string anywhere within it\n- Checks if the first string ends with the second string\n- Optionally, prints the location of the second string within the first string\n- Optionally, handles multiple occurrences of the second string within the first string\n- Implements these functionalities using regexes, index, and substr methods\n- As a bonus task, prints all positions where the second string appears in the first string.","id":3621}
    {"lang_cluster":"Perl","source_code":"\n\nLibrary: ntheory\nuse ntheory qw\/forperm\/;\nuse Set::CrossProduct;\n\nsub four_sq_permute {\n    my($list) = @_;\n    my @solutions;\n    forperm {\n       @c = @$list[@_];\n       push @solutions, [@c] if check(@c);\n    } @$list;\n    print +@solutions . \" unique solutions found using: \" . join(', ', @$list) . \"\\n\";\n    return @solutions;\n}\n\nsub four_sq_cartesian {\n    my(@list) = @_;\n    my @solutions;\n    my $iterator = Set::CrossProduct->new( [(@list) x 7] );\n    while( my $c = $iterator->get ) {\n       push @solutions, [@$c] if check(@$c);\n    }\n    print +@solutions . \" non-unique solutions found using: \" . join(', ', @{@list[0]}) . \"\\n\";\n    return @solutions;\n}\n\nsub check {\n    my(@c) = @_;\n    $a = $c[0] + $c[1];\n    $b = $c[1] + $c[2] + $c[3];\n    $c = $c[3] + $c[4] + $c[5];\n    $d = $c[5] + $c[6];\n    $a == $b and $a == $c and $a == $d;\n}\n\nsub display {\n    my(@solutions) = @_;\n    my $fmt = \"%2s \" x 7 . \"\\n\";\n    printf $fmt, ('a'..'g');\n    printf $fmt, @$_ for @solutions;\n    print \"\\n\";\n}\n\ndisplay four_sq_permute( [1..7] );\ndisplay four_sq_permute( [3..9] );\ndisplay four_sq_permute( [8, 9, 11, 12, 17, 18, 20, 21] );\nfour_sq_cartesian( [0..9] );\n\n\n","human_summarization":"The code generates all possible solutions for a 4-squares puzzle where the sum of the values in each square is equal. It finds solutions for unique values ranging from 1 to 7, and from 3 to 9. It also calculates the number of solutions for non-unique values ranging from 0 to 9. The solutions are generated using the ntheory and Set::CrossProduct modules.","id":3622}
    {"lang_cluster":"Perl","source_code":"use utf8;                # interpret source code as UTF8\nbinmode STDOUT, ':utf8'; # allow printing wide chars without warning\n$|++;                    # disable output buffering\n\nmy ($rows, $cols) = split \/\\s+\/, `stty size`;\nmy $x = int($rows \/ 2 - 1);\nmy $y = int($cols \/ 2 - 16);\n\nmy @chars = map {[ \/(...)\/g ]}\n            (\"\u250c\u2500\u2510  \u2577\u2576\u2500\u2510\u2576\u2500\u2510\u2577 \u2577\u250c\u2500\u2574\u250c\u2500\u2574\u2576\u2500\u2510\u250c\u2500\u2510\u250c\u2500\u2510   \",\n             \"\u2502 \u2502  \u2502\u250c\u2500\u2518\u2576\u2500\u2524\u2514\u2500\u2524\u2514\u2500\u2510\u251c\u2500\u2510  \u2502\u251c\u2500\u2524\u2514\u2500\u2524\u00a0: \",\n             \"\u2514\u2500\u2518  \u2575\u2514\u2500\u2574\u2576\u2500\u2518  \u2575\u2576\u2500\u2518\u2514\u2500\u2518  \u2575\u2514\u2500\u2518\u2576\u2500\u2518   \");\n\nwhile (1) {\n    my @indices = map { ord($_) - ord('0') } split \/\/,\n                  sprintf(\"%02d:%02d:%02d\", (localtime(time))[2,1,0]);\n    \n    clear();\n    for (0 .. $#chars) {\n      position($x + $_, $y);\n      print \"@{$chars[$_]}[@indices]\";\n    }\n    position(1, 1);\n    \n    sleep 1;\n}\n\nsub clear { print \"\\e[H\\e[J\" }\nsub position { printf \"\\e[%d;%dH\", shift, shift }\n\n\n","human_summarization":"illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.","id":3623}
    {"lang_cluster":"Perl","source_code":"\n\n$PROGRAM = '\\'\n\nMY @START_DOW = (3, 6, 6, 2, 4, 0, \n                 2, 5, 1, 3, 6, 1);\nMY @DAYS = (31, 28, 31, 30, 31, 30,\n            31, 31, 30, 31, 30, 31);\n\nMY @MONTHS;\nFOREACH MY $M (0 .. 11) {\n    FOREACH MY $R (0 .. 5) {\n        $MONTHS[$M][$R] = JOIN \" \",\n            MAP { $_ < 1 || $_ > $DAYS[$M]\u00a0? \"  \"\u00a0: SPRINTF \"%2D\", $_ }\n            MAP { $_ - $START_DOW[$M] + 1 }\n            $R * 7 .. $R * 7 + 6;\n    }\n}\n\nSUB P { WARN $_[0], \"\\\\N\" }\nP UC \"                                                       [INSERT SNOOPY HERE]\";\nP \"                                                               1969\";\nP \"\";\nFOREACH (UC(\"      JANUARY               FEBRUARY               MARCH                 APRIL                  MAY                   JUNE\"),\n         UC(\"        JULY                 AUGUST              SEPTEMBER              OCTOBER               NOVEMBER              DECEMBER\")) {\n    P $_;\n    MY @MS = SPLICE @MONTHS, 0, 6;\n    P JOIN \"  \", ((UC \"SU MO TU WE TH FR SA\") X 6);\n    P JOIN \"  \", MAP { SHIFT @$_ } @MS FOREACH 0 .. 5;\n}\n\n\\'';\n\n# LOWERCASE LETTERS\n$E = '%' | '@';\n$C = '#' | '@';\n$H = '(' | '@';\n$O = '\/' | '@';\n$T = '4' | '@';\n$R = '2' | '@';\n$A = '!' | '@';\n$Z = ':' | '@';\n$P = '0' | '@';\n$L = ',' | '@';\n\n`${E}${C}${H}${O} $PROGRAM | ${T}${R} A-Z ${A}-${Z} | ${P}${E}${R}${L}`;\n\nAlthough, if we are abusing the backticks and other innocent programs, why not just: $_=$ARGV[0]\/\/1969;`\\143\\141\\154 $_ >&2`\n\n","human_summarization":"The code provides an algorithm for a calendar task, formatted to fit a 132-character wide page, similar to 1969 era line printers. The entire code is written in uppercase, inspired by the preference of real programmers and the constraints of 1960s computer architecture. The code does not include Snoopy generation but outputs a placeholder instead. Due to restrictions on using certain keywords, the calendar is printed to standard error instead of standard output.","id":3624}
    {"lang_cluster":"Perl","source_code":"\nsub gcd {\n    my ($n, $m) = @_;\n    while($n){\n        my $t = $n;\n        $n = $m % $n;\n        $m = $t;\n    }\n    return $m;\n}\n\nsub tripel {\n    my $pmax  = shift;\n    my $prim  = 0;\n    my $count = 0;\n    my $nmax = sqrt($pmax)\/2;\n    for( my $n=1; $n<=$nmax; $n++ ) {\n        for( my $m=$n+1; (my $p = 2*$m*($m+$n)) <= $pmax; $m+=2 ) {\n            next unless 1==gcd($m,$n);\n            $prim++;\n            $count += int $pmax\/$p;\n        }\n    }\n    printf \"Max. perimeter: %d, Total: %d, Primitive: %d\\n\", $pmax, $count, $prim;\n}\n\ntripel 10**$_ for 1..8;\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":3625}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.8.8\n  use Tk;\n  \n  MainWindow->new();\n  MainLoop;\n\n  use SDL::App;\n  use SDL::Event;\n  \n  $app = SDL::App->new;\n  $app->loop({\n    SDL_QUIT() => sub { exit 0; },\n  });\n\n  use Gtk3 '-init';\n  \n  $window = Gtk3::Window->new;\n  $window->signal_connect(\n    destroy => sub { Gtk3->main_quit; }\n  );\n  $window->show_all;\n  Gtk3->main;\n\nuse strict;\nuse warnings;\nuse QtGui4;\n\nmy $app = Qt::Application(\\@ARGV);\nmy $window = Qt::MainWindow;\n$window->show;\nexit $app->exec;\n\n  use Wx;\n  \n  $window = Wx::Frame->new(undef, -1, 'title');\n  $window->Show;\n  Wx::SimpleApp->new->MainLoop;\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":3626}
    {"lang_cluster":"Perl","source_code":"\n\nwhile (<>) { $cnt{lc chop}++ while length }\nprint \"$_: \", $cnt{$_}\/\/0, \"\\n\" for 'a' .. 'z';\n\n","human_summarization":"\"Opens a text file, counts the frequency of each letter in a case-insensitive manner, and includes both command line and piped input. It may count all characters or only letters A to Z.\"","id":3627}
    {"lang_cluster":"Perl","source_code":"\n\nmy %node = (\n    data => 'say what',\n    next => \\%foo_node,\n);\n$node{next} = \\%bar_node;  # mutable\n\n","human_summarization":"define a data structure for a singly-linked list element, which includes a numeric data member and a mutable link to the next element.","id":3628}
    {"lang_cluster":"Perl","source_code":"\n\nuse GD::Simple;\n\nmy ($width, $height) = (1000,1000); # image dimension\nmy $scale = 6\/10; # branch scale relative to trunk\nmy $length = 400; # trunk size\n\nmy $img = GD::Simple->new($width,$height);\n$img->fgcolor('black');\n$img->penSize(1,1);\n\ntree($width\/2, $height, $length, 270);\n\nprint $img->png;\n\n\nsub tree\n{\n        my ($x, $y, $len, $angle) = @_;\n\n        return if $len < 1;\n\n        $img->moveTo($x,$y);\n        $img->angle($angle);\n        $img->line($len);\n\n        ($x, $y) = $img->curPos();\n\n        tree($x, $y, $len*$scale, $angle+35);\n        tree($x, $y, $len*$scale, $angle-35);\n}\n\n","human_summarization":"The code uses the GD::Simple module to generate and draw a fractal tree. It starts by drawing the trunk, then splits the end of the trunk at a certain angle to create two branches. This process is repeated at the end of each branch until a desired level of branching is achieved.","id":3629}
    {"lang_cluster":"Perl","source_code":"\nsub factors\n{\n        my($n) = @_;\n        return grep { $n\u00a0% $_ == 0 }(1 .. $n);\n}\nprint join ' ',factors(64), \"\\n\";\n\nsub factors {\n  my $n = shift;\n  $n = -$n if $n < 0;\n  my @divisors;\n  for (1 .. int(sqrt($n))) {  # faster and less memory than map\/grep\n    push @divisors, $_ unless $n\u00a0% $_;\n  }\n  # Return divisors including top half, without duplicating a square\n  @divisors, map { $_*$_ == $n\u00a0? ()\u00a0: int($n\/$_) } reverse @divisors;\n}\nprint join \" \", factors(64), \"\\n\";\n\nLibrary: ntheory\nuse ntheory qw\/divisors\/;\nprint join \" \", divisors(12345678), \"\\n\";\n# Alternately something like:  fordivisors { say } 12345678;\n","human_summarization":"calculate the factors of a given positive integer, excluding zero and negative integers. It also notes that every prime number has two factors: 1 and itself.","id":3630}
    {"lang_cluster":"Perl","source_code":"\n#\/usr\/bin\/perl -w\nuse strict ;\n\ndie \"Call\u00a0: perl columnaligner.pl <inputfile> <printorientation>!\\n\" unless\n   @ARGV == 2 ; #$ARGV[ 0 ] contains example file , $ARGV[1] any of 'left' , 'right' or 'center'\ndie \"last argument must be one of center, left or right!\\n\" unless\n   $ARGV[ 1 ] =~ \/center|left|right\/ ;\nsub printLines( $$$ )\u00a0;\nopen INFILE , \"<\" , \"$ARGV[ 0 ]\" or die \"Can't open $ARGV[ 0 ]!\\n\"\u00a0;\nmy @lines = <INFILE>\u00a0;\nclose INFILE\u00a0;\nchomp @lines\u00a0;\nmy @fieldwidths = map length, split \/\\$\/ , $lines[ 0 ]\u00a0;\nforeach my $i ( 1..$#lines ) {\n   my @words = split \/\\$\/ , $lines[ $i ] ;\n   foreach my $j ( 0..$#words ) {\n      if ( $j <= $#fieldwidths ) {\n         if ( length $words[ $j ] > $fieldwidths[ $j ] ) {\n               $fieldwidths[ $j ] = length $words[ $j ] ;\n         }\n      }\n      else {\n         push @fieldwidths, length $words[ $j ] ;\n      }\n   }\n}\nprintLine( $_ , $ARGV[ 1 ] , \\@fieldwidths ) foreach @lines ;\n##################################################################    ####\nsub printLine {\n   my $line = shift ;\n   my $orientation = shift ;\n   my $widthref = shift ;\n   my @words = split \/\\$\/, $line ;\n   foreach my $k ( 0..$#words ) {\n      my $printwidth = $widthref->[ $k ] + 1 ;\n      if ( $orientation eq 'center' ) {\n         $printwidth++ ;\n      }\n      if ( $orientation eq 'left' ) {\n         print $words[ $k ] ;\n         print \" \" x ( $printwidth - length $words[ $k ] ) ;\n      }\n      elsif ( $orientation eq 'right' ) {\n         print \" \" x ( $printwidth - length $words[ $k ] ) ;\n         print $words[ $k ] ;\n      }\n      elsif ( $orientation eq 'center' ) {\n         my $left = int( ( $printwidth - length $words[ $k ] )     \/ 2 ) ;\n         my $right = $printwidth - length( $words[ $k ] ) - $left      ;\n         print \" \" x $left ;\n         print $words[ $k ] ;\n         print \" \" x $right ;\n      }\n   }\n   print \"\\n\" ;\n}\n\n\nuse List::Util qw(max);\n\nsub columns {\n    my @lines = map [split \/\\$\/] => split \/\\n\/ => shift;\n    my $pos = {qw\/left 0 center 1 right 2\/}->{+shift};\n    for my $col (0 .. max map {$#$_} @lines) {\n        my $max = max my @widths = map {length $_->[$col]} @lines;\n        for my $row (0 .. $#lines) {\n            my @pad = map {' ' x $_, ' ' x ($_ + 0.5)} ($max - $widths[$row]) \/ 2;\n            for ($lines[$row][$col])\n                {$_ = join '' => @pad[0 .. $pos-1], $_, @pad[$pos .. $#pad]}\n        }\n    }\n    join '' => map {\"@$_\\n\"} @lines\n}\n\nprint columns <<'END', $_ for qw(left right center);\nGiven$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\nEND\n\n","human_summarization":"The code reads a text file where each line's fields are separated by a dollar sign. It aligns each column by ensuring there is at least one space between words in each column. The code also allows for words in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. The output is viewed in a mono-spaced font on a plain text editor or basic terminal.","id":3631}
    {"lang_cluster":"Perl","source_code":"sub cubLine ($$$$) {\n    my ($n, $dx, $dy, $cde) = @_;\n\n    printf '%*s', $n + 1, substr($cde, 0, 1);\n\n    for (my $d = 9 * $dx - 1 ; $d > 0 ; --$d) {\n        print substr($cde, 1, 1);\n    }\n\n    print substr($cde, 0, 1);\n    printf \"%*s\\n\", $dy + 1, substr($cde, 2, 1);\n}\n\nsub cuboid ($$$) {\n    my ($dx, $dy, $dz) = @_;\n\n    printf \"cuboid %d %d %d:\\n\", $dx, $dy, $dz;\n    cubLine $dy + 1, $dx, 0, '+-';\n\n    for (my $i = 1 ; $i <= $dy ; ++$i) {\n        cubLine $dy - $i + 1, $dx, $i - 1, '\/ |';\n    }\n    cubLine 0, $dx, $dy, '+-|';\n\n    for (my $i = 4 * $dz - $dy - 2 ; $i > 0 ; --$i) {\n        cubLine 0, $dx, $dy, '| |';\n    }\n    cubLine 0, $dx, $dy, '| +';\n\n    for (my $i = 1 ; $i <= $dy ; ++$i) {\n        cubLine 0, $dx, $dy - $i, '| \/';\n    }\n    cubLine 0, $dx, 0, \"+-\\n\";\n}\n\ncuboid 2, 3, 4;\ncuboid 1, 1, 1;\ncuboid 6, 2, 1;\n\n\n","human_summarization":"represent a cuboid with dimensions 2x3x4, drawn either graphically or in ASCII art, with three visible faces, and can be either static or rotational.","id":3632}
    {"lang_cluster":"Perl","source_code":"\n\nuse Net::LDAP;\n\nmy $ldap = Net::LDAP->new('ldap:\/\/ldap.example.com') or die $@;\nmy $mesg = $ldap->bind( $bind_dn, password => $bind_pass );\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol (LDAP) server using LDAP modules.","id":3633}
    {"lang_cluster":"Perl","source_code":"\nsub rot13 {\n  shift =~ tr\/A-Za-z\/N-ZA-Mn-za-m\/r;\n}\n \nprint rot13($_) while (<>);\n\nNOWHERE Abjurer\n\n\nABJURER Nowhere\n\n\nperl -pe 'tr\/A-Za-z\/N-ZA-Mn-za-m\/'\n","human_summarization":"implement a rot-13 function that encodes every line of input from a file or standard input. The function replaces every ASCII letter with the letter that is 13 characters away in the alphabet, wrapping from z to a as needed. It should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. This function can be optionally wrapped in a utility program.","id":3634}
    {"lang_cluster":"Perl","source_code":"\n\n@people = (['joe', 120], ['foo', 31], ['bar', 51]);\n@people = sort { $a->[0] cmp $b->[0] } @people;\n\n\n@people = (['joe', 120], ['foo', 31], ['bar', 51]);\n@people = sort { $a->[1] <=> $b->[1] } @people;\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key 'name' using a custom comparator.","id":3635}
    {"lang_cluster":"Perl","source_code":"\nfor(my $x = 1; $x <= 5; $x++) {\n  for(my $y = 1; $y <= $x; $y++) {\n    print \"*\";\n  } \n  print \"\\n\";\n}\nforeach (1..5) {\n  foreach (1..$_) {\n    print '*';\n  }\n  print \"\\n\";\n}\n\nprint ('*' x $_ . \"\\n\") for 1..5;\n\nmap {print '*' x $_ . \"\\n\"} 1..5;\n","human_summarization":"demonstrate how to use nested \"for\" loops to print a specific pattern. The number of iterations of the inner loop is controlled by the outer loop. If the constraint of using two loops is removed, the code becomes simpler.","id":3636}
    {"lang_cluster":"Perl","source_code":"\n\n# using => key does not need to be quoted unless it contains special chars\nmy %hash = (\n  key1 => 'val1',\n  'key-2' => 2,\n  three => -238.83,\n  4 => 'val3',\n);\n\n# using , both key and value need to be quoted if containing something non-numeric in nature\nmy %hash = (\n  'key1', 'val1',\n  'key-2', 2,\n  'three', -238.83,\n  4, 'val3',\n);\n\nprint $hash{key1};\n\n$hash{key1} = 'val1';\n\n@hash{'key1', 'three'} = ('val1', -238.83);\n\nmy $hashref = {\n key1 => 'val1',\n  'key-2' => 2,\n  three => -238.83,\n  4 => 'val3',\n}\n\nprint $hashref->{key1};\n\n$hashref->{key1} = 'val1';\n\n@{$hashref}{('key1', 'three')} = ('val1', -238.83);\n\n","human_summarization":"create an associative array, also known as a dictionary, map, or hash. The keys are primarily strings, but integers can also be used. Special care is needed for floating point keys to avoid round-off errors. Modules like Tie::RefHash can be used to create keys of other types.","id":3637}
    {"lang_cluster":"Perl","source_code":"\nCreates a magic scalar whose value is next in the LCG sequence when read.use strict;\npackage LCG;\n\nuse overload '0+'  => \\&get;\n\nuse integer;\nsub gen_bsd { (1103515245 * shift() + 12345) % (1 << 31) }\n\nsub gen_ms  {\n\tmy $s = (214013 * shift() + 2531011) % (1 << 31);\n\t$s, $s \/ (1 << 16)\n}\n\nsub set { $_[0]->{seed} = $_[1] } # srand\nsub get {\n\tmy $o = shift;\n\t($o->{seed}, my $r) = $o->{meth}->($o->{seed});\n\t$r \/\/= $o->{seed}\n}\n\nsub new {\n\tmy $cls = shift;\n\tmy %opts = @_;\n\tbless {\n\t\tseed => $opts{seed},\n\t\tmeth => $opts{meth} eq 'MS' ? \\&gen_ms : \\&gen_bsd,\n\t}, ref $cls || $cls;\n}\n\npackage main;\n\nmy $rand = LCG->new;\n\nprint \"BSD:\\n\";\nprint \"$rand\\n\" for 1 .. 10;\n\n$rand = LCG->new(meth => 'MS');\n\nprint \"\\nMS:\\n\";\nprint \"$rand\\n\" for 1 .. 10;\noutputBSD:\n12345\n1406932606\n654583775\n1449466924\n229283573\n1109335178\n1051550459\n1293799192\n794471793\n551188310\n\nMS:\n38\n7719\n21238\n2437\n8855\n11797\n8365\n32285\n10450\n30612\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":3638}
    {"lang_cluster":"Perl","source_code":"\n\nmy @l  = ($A, $B);\npush @l, $C, splice @l, 1;\n\n\nsub insert_after {\n  # first argument: node to insert after\n  # second argument: node to insert\n  $_[1]{next} = $_[0]{next};\n  $_[0]{next} = $_[1];\n}\n\nmy %B = (\n    data => 3,\n    next => undef, # not a circular list\n);\nmy %A = (\n    data => 1,\n    next => \\%B,\n);\nmy %C = (\n    data => 2,\n);\ninsert_after \\%A, \\%C;\n\n\n insert_after \\%A, { data => 2 };\n\n\nsub insert_after {\n  my $node = $_[0];\n  my $next = $node->{next};\n  shift;\n  while (defined $_[0]) {\n    $node->{next} = $_[0];\n    $node = $node->{next};\n    shift;\n  }\n  $node->{next} = $next;\n}\n\n\nmy %list = ( data => 'A' );\ninsert_after \\%list, { data => 'B' }, { data => 'C' };\n\n\nmy $list2;\n\n# create a new list ('A'. 'B', 'C') and store it in $list2\ninsert_after $list2 = { data => 'A' }, { data => 'B' }, { data => 'C' };\n\n# append two new nodes ('D', 'E') after the first element\ninsert_after $list2, { data => 'A2' }, { data => 'A3' };\n\n# append new nodes ('A2a', 'A2b') after the second element (which now is 'A2')\ninsert_after $list2->{next}, { data => 'A2a' }, { data => 'A2b' };\n\n","human_summarization":"define a method for inserting an element into a singly-linked list after a specified element. The method is used to insert element C into a list consisting of elements A and B, after element A. The code also includes notes on the use of arrays versus linked lists, the use of references for translation, and the simplification of list handling through the use of variables containing references.","id":3639}
    {"lang_cluster":"Perl","source_code":"\nuse strict;\n\nsub halve { int((shift) \/ 2); }\nsub double { (shift) * 2; }\nsub iseven { ((shift) & 1) == 0; }\n\nsub ethiopicmult\n{\n    my ($plier, $plicand, $tutor) = @_;\n    print \"ethiopic multiplication of $plier and $plicand\\n\" if $tutor;\n    my $r = 0;\n    while ($plier >= 1)\n    {\n\t$r += $plicand unless iseven($plier);\n\tif ($tutor) {\n\t    print \"$plier, $plicand \", (iseven($plier) ? \" struck\" : \" kept\"), \"\\n\";\n\t}\n\t$plier = halve($plier);\n\t$plicand = double($plicand);\n    }\n    return $r;\n}\n\nprint ethiopicmult(17,34, 1), \"\\n\";\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":3640}
    {"lang_cluster":"Perl","source_code":"\n\n# Fischer-Krause ordered permutation generator\n# http:\/\/faq.perl.org\/perlfaq4.html#How_do_I_permute_N_e\nsub permute :prototype(&@) {\n\t\tmy $code = shift;\n\t\tmy @idx = 0..$#_;\n\t\twhile ( $code->(@_[@idx]) ) {\n\t\t\tmy $p = $#idx;\n\t\t\t--$p while $idx[$p-1] > $idx[$p];\n\t\t\tmy $q = $p or return;\n\t\t\tpush @idx, reverse splice @idx, $p;\n\t\t\t++$q while $idx[$p-1] > $idx[$q];\n\t\t\t@idx[$p-1,$q]=@idx[$q,$p-1];\n\t\t}\n\t}\n\n@formats = (\n\t'((%d %s %d) %s %d) %s %d',\n\t'(%d %s (%d %s %d)) %s %d',\n\t'(%d %s %d) %s (%d %s %d)',\n\t'%d %s ((%d %s %d) %s %d)',\n\t'%d %s (%d %s (%d %s %d))',\n\t);\n\n# generate all possible combinations of operators\n@op = qw( + - * \/ );\n@operators = map{ $a=$_; map{ $b=$_; map{ \"$a $b $_\" }@op }@op }@op;\n\nwhile(1)\n{\n\tprint \"Enter four integers or 'q' to exit: \";\n\tchomp($ent = <>);\n\tlast if $ent eq 'q';\n\n\t\n\tif($ent !~ \/^[1-9] [1-9] [1-9] [1-9]$\/){ print \"invalid input\\n\"; next }\n\n\t@n = split \/ \/,$ent;\n\tpermute { push @numbers,join ' ',@_ }@n;\n\n\tfor $format (@formats)\n\t{\n\t\tfor(@numbers)\n\t\t{\n\t\t\t@n = split;\n\t\t\tfor(@operators)\n\t\t\t{\n\t\t\t\t@o = split;\n\t\t\t\t$str = sprintf $format,$n[0],$o[0],$n[1],$o[1],$n[2],$o[2],$n[3];\n\t\t\t\t$r = eval($str);\n\t\t\t\tprint \"$str\\n\" if $r == 24;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\n","human_summarization":"The code takes four digits as input, either from the user or generated randomly, and computes all possible arithmetic expressions based on the rules of the 24 game. It also displays examples of the solutions it generates. The permute function used in the code is sourced from an external link.","id":3641}
    {"lang_cluster":"Perl","source_code":"\nsub factorial\n{\n  my $n = shift;\n  my $result = 1;\n  for (my $i = 1; $i <= $n; ++$i)\n  {\n    $result *= $i;\n  };\n  $result;\n}\n\n# using a .. range\nsub factorial {\n    my $r = 1;\n    $r *= $_ for 1..shift;\n    $r;\n}\nsub factorial\n{\n  my $n = shift;\n  ($n == 0)? 1\u00a0: $n*factorial($n-1);\n}\nuse List::Util qw(reduce);\nsub factorial\n{\n  my $n = shift;\n  reduce { $a * $b } 1, 1 .. $n\n}\n\nLibrary: ntheory\nuse ntheory qw\/factorial\/;\n# factorial returns a UV (native unsigned int) or Math::BigInt depending on size\nsay length(  factorial(10000)  );\nuse bigint;\nsay length(  10000->bfac  );\nuse Math::GMP;\nsay length(  Math::GMP->new(10000)->bfac  );\nuse Math::Pari qw\/ifact\/;\nsay length(  ifact(10000)  );\n","human_summarization":"\"Implements a function to calculate the factorial of a given number, either iteratively or recursively. The function may optionally handle errors for negative input values. The output is the product of the sequence from the input number down to 1.\"","id":3642}
    {"lang_cluster":"Perl","source_code":"\nuse Data::Random qw(rand_set);\nuse List::MoreUtils qw(uniq);\n\nmy $size = 4;\nmy $chosen = join \"\", rand_set set => [\"1\"..\"9\"], size => $size;\n\nprint \"I've chosen a number from $size unique digits from 1 to 9; you need\nto input $size unique digits to guess my number\\n\";\n\nfor ( my $guesses = 1; ; $guesses++ ) {\n    my $guess;\n    while (1) {\n        print \"\\nNext guess [$guesses]: \";\n        $guess = <STDIN>;\n        chomp $guess;\n        checkguess($guess) and last;\n        print \"$size digits, no repetition, no 0... retry\\n\";\n    }\n    if ( $guess eq $chosen ) {\n        print \"You did it in $guesses attempts!\\n\";\n        last;\n    }\n    my $bulls = 0;\n    my $cows = 0;\n    for my $i (0 .. $size-1) {\n        if ( substr($guess, $i, 1) eq substr($chosen, $i, 1) ) {\n            $bulls++;\n        } elsif ( index($chosen, substr($guess, $i, 1)) >= 0 ) {\n            $cows++;\n        }\n    }\n    print \"$cows cows, $bulls bulls\\n\";\n}\n\nsub checkguess\n{\n    my $g = shift;\n    return uniq(split \/\/, $g) == $size && $g =~ \/^[1-9]{$size}$\/;\n}\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":3643}
    {"lang_cluster":"Perl","source_code":"\nmy $PI = 2 * atan2 1, 0;\n\nmy @nums = map {\n    1 + 0.5 * sqrt(-2 * log rand) * cos(2 * $PI * rand)\n} 1..1000;\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":3644}
    {"lang_cluster":"Perl","source_code":"\nsub dotprod\n{\n        my($vec_a, $vec_b) = @_;\n        die \"they must have the same size\\n\" unless @$vec_a == @$vec_b;\n        my $sum = 0;\n        $sum += $vec_a->[$_] * $vec_b->[$_] for 0..$#$vec_a;\n        return $sum;\n}\n\nmy @vec_a = (1,3,-5);\nmy @vec_b = (4,-2,-1);\n\nprint dotprod(\\@vec_a,\\@vec_b), \"\\n\"; # 3\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":3645}
    {"lang_cluster":"Perl","source_code":"\n\nopen FH, \"< $filename\" or die \"can't open file: $!\";\nwhile (my $line = <FH>) {\n    chomp $line; # removes trailing newline\n    # process $line\n}\nclose FH or die \"can't close file: $!\";\n\n\n@lines = <FH>;\n\n\nwhile (<>) {\n    # $_ contains a line\n}\n\n\n$ seq 5 | perl -pe '$_ = \"Hello $_\"'\nHello 1\nHello 2\nHello 3\nHello 4\nHello 5\n$ seq 5 | perl -ne 'print \"Hello $_\"'\nHello 1\nHello 2\nHello 3\nHello 4\nHello 5\n","human_summarization":"The code reads data from a text stream either word-by-word or line-by-line until there is no more data. It uses the angle brackets operator to read a line at a time or all lines at once, depending on the context. It can also handle files entered as command line arguments or standard input. If invoked with the -p or -n option, it executes the loop once per input line, storing the line in $_. The -p option also prints $_ at the end of each iteration.","id":3646}
    {"lang_cluster":"Perl","source_code":"\nLibrary: XML::SimpleSimple\nuse XML::Simple;\nprint XMLout( { root => { element => \"Some text here\" } }, NoAttr => 1, RootName => \"\" );\n\n\n<root>\n  <element>Some text here<\/element>\n<\/root>\n\nLibrary: XML::DOM::BagOfTricksDOM::BagOfTricks\nuse XML::DOM::BagOfTricks qw(createDocument createTextElement);\n\nmy ($doc, $root) = createDocument('root');\n$root->appendChild(\n    createTextElement($doc, 'element', 'Some text here')\n);\nprint $doc->toString;\n\n\n<root><element>Some text here<\/element><\/root>\n\nLibrary: LibXML\nuse XML::LibXML;\n\n$xml = XML::LibXML::Document->new('1.0');\n$node = $xml->createElement('root');\n$xml->setDocumentElement($node);\n$node2 = $xml->createElement('element');\n$text = $xml->createTextNode('Some text here');\n$node2->addChild($text);\n$node->appendWellBalancedChunk('text');\n$node->addChild($node2);\n\nprint $xml->toString;\n\n\n<?xml version=\"1.0\"?>\n<root>text<element>Some text here<\/element><\/root>\n\n","human_summarization":"create a simple DOM and serialize it into a specific XML format.","id":3647}
    {"lang_cluster":"Perl","source_code":"\nSimple localtime use in scalar context.print scalar localtime, \"\\n\";\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":3648}
    {"lang_cluster":"Perl","source_code":"\n\nuse List::Util qw(sum);\nuse POSIX qw(strtol);\n\nsub zip :prototype(&\\@\\@) {\n  my $f = shift;\n  my @a = @{shift()};\n  my @b = @{shift()};\n  my @result;\n  push(@result, $f->(shift @a, shift @b)) while @a && @b;\n  return @result;\n}\n\nmy @weights = (1, 3, 1, 7, 3, 9);\nsub sedan :prototype($) {\n  my $s = shift;\n  $s =~ \/[AEIOU]\/ and die \"No vowels\";\n  my @vs = map {(strtol $_, 36)[0]} split \/\/, $s;\n  my $checksum = sum (zip {$_[0] * $_[1]} @vs, @weights);\n  my $check_digit = (10 - $checksum % 10) % 10;\n  return $s . $check_digit;\n}\n\nwhile (<>) {\n    chomp;\n    print sedol($_), \"\\n\";\n}\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates and appends the checksum digit to each SEDOL, and outputs the new SEDOLs. It also validates the input to ensure it contains only valid characters for a SEDOL string. The code reads from standard input.","id":3649}
    {"lang_cluster":"Perl","source_code":"\nuse strict;\nuse warnings;\n\nmy $x = my $y = 255;\n$x |= 1; # must be odd\nmy $depth = 255;\n\nmy $light = Vector->new(rand, rand, rand)->normalized;\n\nprint \"P2\\n$x $y\\n$depth\\n\";\n\nmy ($r, $ambient) = (($x - 1)\/2, 0);\nmy ($r2) = $r ** 2;\n{\n    for my $x (-$r .. $r) {\n\tmy $x2 = $x**2;\n\tfor my $y (-$r .. $r) {\n\t    my $y2 = $y**2;\n\t    my $pixel = 0;\n\t    if ($x2 + $y2 < $r2) {\n\t\tmy $v = Vector->new($x, $y, sqrt($r2 - $x2 - $y2))->normalized;\n\t\tmy $I = $light . $v + $ambient;\n\t\t$I = $I < 0 ? 0 : $I > 1 ? 1 : $I;\n\t\t$pixel = int($I * $depth);\n\t    }\n\t    print $pixel;\n\t    print $y == $r ? \"\\n\" : \" \";\n\t}\n    }\n}\n\npackage Vector {\n    sub new {\n\tmy $class = shift;\n\tbless ref($_[0]) eq 'Array' ? $_[0] : [ @_ ], $class;\n    }\n    sub normalized {\n\tmy $this = shift;\n\tmy $norm = sqrt($this . $this);\n\tref($this)->new( map $_\/$norm, @$this );\n    }\n    use overload q{.} => sub {\n\tmy ($a, $b) = @_;\n\tmy $sum = 0;\n\tfor (0 .. @$a - 1) {\n\t    $sum += $a->[$_] * $b->[$_]\n\t}\n\treturn $sum;\n    },\n    q{\"\"} => sub { sprintf \"Vector:[%s]\", join ' ', @{shift()} };\n}\n\n","human_summarization":"generate a graphical or ASCII art representation of a sphere, with either static or rotational projection. The output is a PGM image similar to the Raku solution.","id":3650}
    {"lang_cluster":"Perl","source_code":"\nuse 5.10.0;\nmy %irregulars = ( 1 => 'st',\n                   2 => 'nd',\n                   3 => 'rd',\n                  11 => 'th',\n                  12 => 'th',\n                  13 => 'th');\nsub nth\n{\n    my $n = shift;\n    $n . # q(') . # Uncomment this to add apostrophes to output\n    ($irregulars{$n % 100} \/\/ $irregulars{$n % 10} \/\/ 'th');\n}\n\nsub range { join ' ', map { nth($_) } @{$_[0]} }\nprint range($_), \"\\n\" for ([0..25], [250..265], [1000..1025]);\n\n\n","human_summarization":"The code is a function that takes an integer input (greater than or equal to zero) and returns a string of the number followed by an apostrophe and its corresponding ordinal suffix. The function is demonstrated with integer ranges 0..25, 250..265, and 1000..1025. It requires Perl 5.10 or newer for the Defined OR operator, or alternatively, a library can be used.","id":3651}
    {"lang_cluster":"Perl","source_code":"\n\nsub stripchars {\n    my ($s, $chars) = @_;\n    $s =~ s\/[$chars]\/\/g;\n    return $s;\n}\n\nprint stripchars(\"She was a soul stripper. She took my heart!\", \"aei\"), \"\\n\";\n\n\n","human_summarization":"\"Function to strip specified characters from a given string. The function takes two arguments - the original string and a string of characters to be stripped. The function returns the original string with all instances of the specified characters removed. Special characters may need to be escaped. The function uses the tr\/\/\/ operator for efficiency when the set of characters to strip is known at compile time.\"","id":3652}
    {"lang_cluster":"Perl","source_code":"\n#!bin\/usr\/perl\nuse 5.020;\nuse strict;\nuse warnings;\n\n#Get a max number from the user\nsay(\"Please enter the maximum possible multiple. \");\nmy $max = <STDIN>;\n\n#Get the factors from the user\nmy @factors = ();\nmy $buffer;\nsay(\"Now enter the first factor and its associated word. Ex: 3 Fizz \");\nchomp($buffer = <STDIN>);\npush @factors, $buffer;\nsay(\"Now enter the second factor and its associated word. Ex: 5 Buzz \");\nchomp($buffer = <STDIN>);\npush @factors, $buffer;\nsay(\"Now enter the third factor and its associated word. Ex: 7 Baxx \");\nchomp($buffer = <STDIN>);\npush @factors, $buffer;\n\n#Counting from 1 to max\nfor(my $i = 1; $i <= $max; $i++)\n{\n    #Create a secondary buffer as well as set the original buffer to the current index\n    my $oBuffer;\n    $buffer = $i;\n    #Run through each element in our array\n    foreach my $element (@factors)\n    {\n        #Look for white space\n        $element =~ \/\\s\/;\n        #If the int is a factor of max, append it to oBuffer as a string to be printed\n        if($i % substr($element, 0, @-) == 0)\n        {\n            $oBuffer = $oBuffer . substr($element, @+ + 1, length($element));\n            #This is essentially setting a flag saying that at least one element is a factor\n            $buffer = \"\";\n        }\n    }\n    #If there are any factors for that number, print their words. If not, print the number.\n    if(length($buffer) > 0)\n    {\n        print($buffer . \"\\n\");\n    }\n    else\n    {\n        print($oBuffer . \"\\n\");\n    }\n}\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":3653}
    {"lang_cluster":"Perl","source_code":"\nuse strict;\nuse warnings;\nuse feature ':all';\n\n# explicit concatentation\n$_ = 'bar';\n$_ = 'Foo' . $_;\nsay;\n\n\n# lvalue substr\n$_ = 'bar';\nsubstr $_, 0, 0, 'Foo';\nsay;\n\n\n# interpolation as concatenation\n# (NOT safe if concatenate sigils)\n$_ = 'bar';\n$_ = \"Foo$_\";\nsay;\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":3654}
    {"lang_cluster":"Perl","source_code":"\n\nuse SVG;\nuse List::Util qw(max min);\n\nuse constant pi => 2 * atan2(1, 0);\n\n# Compute the curve with a Lindemayer-system\nmy %rules = (\n    X => 'X+YF+',\n    Y => '-FX-Y'\n);\nmy $dragon = 'FX';\n$dragon =~ s\/([XY])\/$rules{$1}\/eg for 1..10;\n\n# Draw the curve in SVG\n($x, $y) = (0, 0);\n$theta   = 0;\n$r       = 6;\n\nfor (split \/\/, $dragon) {\n    if (\/F\/) {\n        push @X, sprintf \"%.0f\", $x;\n        push @Y, sprintf \"%.0f\", $y;\n        $x += $r * cos($theta);\n        $y += $r * sin($theta);\n    }\n    elsif (\/\\+\/) { $theta += pi\/2; }\n    elsif (\/\\-\/) { $theta -= pi\/2; }\n}\n\n$xrng =  max(@X) - min(@X);\n$yrng =  max(@Y) - min(@Y);\n$xt   = -min(@X)+10;\n$yt   = -min(@Y)+10;\n$svg = SVG->new(width=>$xrng+20, height=>$yrng+20);\n$points = $svg->get_path(x=>\\@X, y=>\\@Y, -type=>'polyline');\n$svg->rect(width=>\"100%\", height=>\"100%\", style=>{'fill'=>'black'});\n$svg->polyline(%$points, style=>{'stroke'=>'orange', 'stroke-width'=>1}, transform=>\"translate($xt,$yt)\");\n\nopen  $fh, '>', 'dragon_curve.svg';\nprint $fh  $svg->xmlify(-namespace=>'svg');\nclose $fh;\n\n\n","human_summarization":"The code generates a dragon curve fractal, either displaying it directly or writing it to an image file. It uses various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system to create the fractal. The code also includes functionality to calculate absolute direction, X,Y coordinates, and to test whether a given point or segment is on the curve. It also allows for variations and can draw other curves defined by L-systems. The output can be limited to a desired length or sub-section.","id":3655}
    {"lang_cluster":"Perl","source_code":"\nmy $number = 1 + int rand 10;\ndo { print \"Guess a number between 1 and 10: \" } until <> == $number;\nprint \"You got it!\\n\";\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":3656}
    {"lang_cluster":"Perl","source_code":"\nprint 'a'..'z'\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":3657}
    {"lang_cluster":"Perl","source_code":"\nfor (5, 50, 9000) {\n  printf \"%b\\n\", $_;\n}\n101\n110010\n10001100101000\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":3658}
    {"lang_cluster":"Perl","source_code":"\n\n#!\/usr\/bin\/perl\nmy $fmt = '|\u00a0%-11s' x 5 . \"|\\n\";\nprintf $fmt, qw( PATIENT_ID LASTNAME LAST_VISIT SCORE_SUM SCORE_AVG);\nmy ($names, $visits) = do { local $\/; split \/^\\n\/m, <DATA> };\nmy %score;\nfor ( $visits =~ \/^\\d.*\/gm )\n  {\n  my ($id, undef, $score) = split \/,\/;\n  $score{$id} \/\/= ['', ''];\n  $score and $score{$id}[0]++, $score{$id}[1] += $score;\n  }\nfor ( sort $names =~ \/^\\d.*\/gm )\n  {\n  my ($id, $name) = split \/,\/;\n  printf $fmt, $id, $name, ( sort $visits =~ \/^$id,(.*?),\/gm, '' )[-1],\n    $score{$id}[0]\n      ? ( $score{$id}[1], $score{$id}[1] \/ $score{$id}[0])\n      : ('', '');\n  }\n\n__DATA__\nPATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\n\nPATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\n\n\n","human_summarization":"\"Merge and aggregate two .csv datasets, grouping by patient id and last name. The output dataset should include the maximum visit date, and the sum and average of the scores per patient. The data can be loaded from the .csv files or hard-coded, and the resulting dataset can be stored in-memory or outputted to the screen or file.\"","id":3659}
    {"lang_cluster":"Perl","source_code":"\nLibrary: Gtk3\nuse Gtk3 '-init';\n\nmy $window = Gtk3::Window->new();\n$window->set_default_size(320, 240);\n$window->set_border_width(10);\n$window->set_title(\"Draw a Pixel\");\n$window->set_app_paintable(TRUE);\n\nmy $da = Gtk3::DrawingArea->new();\n$da->signal_connect('draw' => \\&draw_in_drawingarea);\n$window->add($da);\n$window->show_all();\n\nGtk3->main;\n\nsub draw_in_drawingarea\n{\n  my ($widget, $cr, $data) = @_;\n  $cr->set_source_rgb(1, 0, 0);\n  $cr->set_line_width(1);\n  $cr->rectangle( 100, 100, 1, 1);\n  $cr->stroke;\n}\n\n","human_summarization":"\"Creates a 320x240 window and draws a single red pixel at position (100, 100).\"","id":3660}
    {"lang_cluster":"Perl","source_code":"\n\nmy $fullname;\nmy $favouritefruit;\nmy $needspeeling;\nmy $seedsremoved;\nmy @otherfamily;\n\n# configuration file definition.  See read_conf_file below for explanation.\nmy $conf_definition = {\n    'fullname'          => [ 'string', \\$fullname ],\n    'favouritefruit'    => [ 'string', \\$favouritefruit ],\n    'needspeeling'      => [ 'boolean', \\$needspeeling ],\n    'seedsremoved'      => [ 'boolean', \\$seedsremoved ],\n    'otherfamily'       => [ 'array', \\@otherfamily ],\n};\n\nmy $arg = shift;               # take the configuration file name from the command line\n                               # (or first subroutine argument if this were in a sub)\nmy $file;                      # this is going to be a file handle reference\nopen $file, $arg or die \"Can't open configuration file '$arg': $!\";\n\nread_conf_file($file, $conf_definition); \n\nprint \"fullname = $fullname\\n\";\nprint \"favouritefruit = $favouritefruit\\n\";\nprint \"needspeeling = \", ($needspeeling ? 'true' : 'false'), \"\\n\";\nprint \"seedsremoved = \", ($seedsremoved ? 'true' : 'false'), \"\\n\";\nfor (my $i = 0; $i < @otherfamily; ++$i) {\n    print \"otherfamily(\", $i + 1, \") = \", $otherfamily[$i], \"\\n\";\n}\n\n# read_conf_file:  Given a file handle opened for reading and a configuration definition,\n# read the file.\n# If the configuration file doesn't match the definition, raise an exception with \"die\".\n# The configuration definition is (a reference to) an associative array\n# where the keys are the configuration variable names in all lower case\n# and the values are references to arrays.\n# The first element of each of these arrays is the expected type:  'boolean', 'string', or 'array';\n# the second element is a reference to the variable that should be assigned the data.\nsub read_conf_file {\n    my ($fh, $def) = @_;        # copy parameters\n\n    local $_;                   # avoid interfering with use of $_ in main program\n    while (<$fh>) {             # read a line from $fh into $_ until end of file\n        next if \/^#\/;           # skip \"#\" comments\n        next if \/^;\/;           # skip \";\" comments\n        next if \/^$\/;           # skip blank lines\n        chomp;                  # strip final newline\n\n        $_ =~ \/^\\s*(\\w+)\\s*(.*)$\/i or die \"Syntax error\";\n        my $key = $1;\n        my $rest = $2;\n        $key =~ tr\/[A-Z]\/[a-z]\/; # convert keyword to lower case\n\n        if (!exists $def->{$key}) {\n            die \"Unknown keyword: '$key'\";\n        }\n\n        if ($def->{$key}[0] eq 'boolean') {\n            if ($rest) {\n                die \"Syntax error:  extra data following boolean '$key'\";\n            }\n            ${$def->{$key}[1]} = 1;\n            next;                # done with this line, go back to \"while\"\n        }\n\n        $rest =~ s\/\\s*$\/\/;       # drop trailing whitespace\n        $rest =~ s\/^=\\s*\/\/;      # drop equals sign if present\n\n        if ($def->{$key}[0] eq 'string') {\n            ${$def->{$key}[1]} = $rest;\n        } elsif ($def->{$key}[0] eq 'array') {\n            @{$def->{$key}[1]} = split \/\\s*,\\s*\/, $rest;\n        } else {\n            die \"Internal error (unknown type in configuration definition)\";\n        }\n    }\n}\n\n","human_summarization":"The code reads a configuration file in standard format, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration entries, including fullname, favouritefruit, needspeeling, and seedsremoved. It also handles options with multiple parameters, storing them in an array. The code checks the configuration file syntax and contents, raising exceptions if there are errors.","id":3661}
    {"lang_cluster":"Perl","source_code":"\nLibrary: ntheory\nuse ntheory qw\/Pi\/;\n\nsub asin { my $x = shift; atan2($x, sqrt(1-$x*$x)); }\n\nsub surfacedist {\n  my($lat1, $lon1, $lat2, $lon2) = @_;\n  my $radius = 6372.8;\n  my $radians = Pi() \/ 180;;\n  my $dlat = ($lat2 - $lat1) * $radians;\n  my $dlon = ($lon2 - $lon1) * $radians;\n  $lat1 *= $radians;\n  $lat2 *= $radians;\n  my $a = sin($dlat\/2)**2 + cos($lat1) * cos($lat2) * sin($dlon\/2)**2;\n  my $c = 2 * asin(sqrt($a));\n  return $radius * $c;\n}\nmy @BNA = (36.12, -86.67);\nmy @LAX = (33.94, -118.4);\nprintf \"Distance:\u00a0%.3f km\\n\", surfacedist(@BNA, @LAX);\n\n\n","human_summarization":"implement the Haversine formula to calculate the great-circle distance between two points on a sphere using their longitudes and latitudes. The points in this case are Nashville International Airport (BNA) and Los Angeles International Airport (LAX). The code uses either the authalic radius (6371.0 km) or the average great-circle radius (6372.8 km) for calculations, with the latter being recommended. The code also takes into account the recommendations from the International Union of Geodesy and Geophysics for real applications. The Perl core distribution's Math::Trig is used for the great circle distance calculation.","id":3662}
    {"lang_cluster":"Perl","source_code":"\nLibrary: HTTP\/Tiny\nWorks with: Perl version 5.14\nWorks with: Perl\/HTTP\/Tiny\n\nuse strict; use warnings;\nrequire 5.014; # check HTTP::Tiny part of core\nuse HTTP::Tiny;\n\nprint( HTTP::Tiny->new()->get( 'http:\/\/rosettacode.org')->{content} );\n\nWorks with: Perl\/LWP\n\nuse LWP::Simple qw\/get $ua\/;\n$ua->agent(undef) ; # cloudflare blocks default LWP agent\nprint( get(\"http:\/\/www.rosettacode.org\") );\n\n\nuse strict;\nuse LWP::UserAgent;\n\nmy $url = 'http:\/\/www.rosettacode.org';\nmy $response = LWP::UserAgent->new->get( $url );\n\n$response->is_success or die \"Failed to GET '$url': \", $response->status_line;\n\nprint $response->as_string\n\n","human_summarization":"Accesses and prints the content of a URL using HTTP::Tiny, a library added to the core libraries in Perl\/5.14, similar to the LWP sample but with additional error-checking. This does not handle HTTPS requests.","id":3663}
    {"lang_cluster":"Perl","source_code":"\nsub luhn_test\n{\n        my @rev = reverse split \/\/,$_[0];\n        my ($sum1,$sum2,$i) = (0,0,0);\n\n        for(my $i=0;$i<@rev;$i+=2)\n        {\n                $sum1 += $rev[$i];\n                last if $i == $#rev;\n                $sum2 += 2*$rev[$i+1]%10 + int(2*$rev[$i+1]\/10);\n        }\n        return ($sum1+$sum2) % 10 == 0;\n}\nprint luhn_test('49927398716');\nprint luhn_test('49927398717');\nprint luhn_test('1234567812345678');\nprint luhn_test('1234567812345670');\n\n\nsub luhn {\n    my (@n,$i,$sum) = split \/\/, reverse $_[0];\n    my @a = map {int(2*$_ \/ 10) + (2*$_ % 10)} (0..9);\n    map {$sum += $i++ % 2 ? $a[$_] : $_} @n;\n    return ($sum % 10) ? 0 : 1;\n}\n\n# Test and display\nmap {print luhn($_), \": $_\\n\"}\n    qw(49927398716 49927398717 1234567812345678 1234567812345670);\n\n\n","human_summarization":"The code implements the Luhn test for validating credit card numbers. It first reverses the order of the digits in the number. Then, it calculates two partial sums, s1 and s2. S1 is the sum of the odd digits in the reversed number. S2 is calculated by doubling each even digit, summing the digits if the result is greater than nine, and then summing these results. If the sum of s1 and s2 ends in zero, the number is a valid credit card number. The code validates the numbers 49927398716, 49927398717, 1234567812345678, and 1234567812345670 using this method.","id":3664}
    {"lang_cluster":"Perl","source_code":"my @prisoner = 0 .. 40;\nmy $k = 3;\nuntil (@prisoner == 1) {\n    push @prisoner, shift @prisoner for 1 .. $k-1;\n    shift @prisoner;\n}\n\nprint \"Prisoner @prisoner survived.\\n\"\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":3665}
    {"lang_cluster":"Perl","source_code":"\n\"ha\" x 5\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":3666}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.8.8\n\n$string = \"I am a string\";\nif ($string =~ \/string$\/) {\n   print \"Ends with 'string'\\n\";\n}\n\nif ($string !~ \/^You\/) {\n   print \"Does not start with 'You'\\n\";\n}\n\n\n$string = \"I am a string\";\n$string =~ s\/ a \/ another \/; # makes \"I am a string\" into \"I am another string\"\nprint $string;\n\n\n$string = \"I am a string\";\n$string2 = $string =~ s\/ a \/ another \/r; # $string2 == \"I am another string\", $string is unaltered\nprint $string2;\n\n\n$string = \"I am a string\";\nif ($string =~ s\/\\bam\\b\/was\/) { # \\b is a word border\n   print \"I was able to find and replace 'am' with 'was'\\n\";\n}\n\n\n# add the following just after the last \/ for additional control\n# g = globally (match as many as possible)\n# i = case-insensitive\n# s = treat all of $string as a single line (in case you have line breaks in the content)\n# m = multi-line (the expression is run on each line individually)\n\n$string =~ s\/i\/u\/ig; # would change \"I am a string\" into \"u am a strung\"\n\n\n$_ = \"I like banana milkshake.\";\nif (\/banana\/) {          # The regular expression binding operator is omitted\n  print \"Match found\\n\";\n}\n\n","human_summarization":"The code matches a string against a regular expression and substitutes part of the string using the regular expression. It returns a new substituted string without altering the original string in Perl 5.14+. The code also omits the regular expression binding operators when matches are made against the topic variable.","id":3667}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.x\nmy $a = <>;\nmy $b = <>;\n\nprint\n    \"sum:              \", $a + $b, \"\\n\",\n    \"difference:       \", $a - $b, \"\\n\",\n    \"product:          \", $a * $b, \"\\n\",\n    \"integer quotient: \", int($a \/ $b), \"\\n\",\n    \"remainder:        \", $a % $b, \"\\n\",\n    \"exponent:         \", $a ** $b, \"\\n\"\n    ;\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":3668}
    {"lang_cluster":"Perl","source_code":"\nsub countSubstring {\n  my $str = shift;\n  my $sub = quotemeta(shift);\n  my $count = () = $str =~ \/$sub\/g;\n  return $count;\n#  or return scalar( () = $str =~ \/$sub\/g );\n}\n  \nprint countSubstring(\"the three truths\",\"th\"), \"\\n\"; # prints \"3\"\nprint countSubstring(\"ababababab\",\"abab\"), \"\\n\"; # prints \"2\"\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":3669}
    {"lang_cluster":"Perl","source_code":"\nsub hanoi {\n    my ($n, $from, $to, $via) = (@_, 1, 2, 3);\n\n    if ($n == 1) {\n        print \"Move disk from pole $from to pole $to.\\n\";\n    } else {\n        hanoi($n - 1, $from, $via, $to);\n        hanoi(1, $from, $to, $via);\n        hanoi($n - 1, $via, $to, $from);\n    };\n};\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":3670}
    {"lang_cluster":"Perl","source_code":"\nsub binomial {\n    use bigint;\n    my ($r, $n, $k) = (1, @_);\n    for (1 .. $k) { $r *= $n--; $r \/= $_ }\n    $r;\n}\n \nprint binomial(5, 3);\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations with and without replacement. The code uses the bigint module's binomial method for better performance, especially with large inputs, and the Math::Pari module, which requires large amounts of added stack space for large arguments.","id":3671}
    {"lang_cluster":"Perl","source_code":"\nsub shell_sort {\n    my (@a, $h, $i, $j, $k) = @_;\n    for ($h = @a; $h = int $h \/ 2;) {\n        for $i ($h .. $#a) {\n            $k = $a[$i];\n            for ($j = $i; $j >= $h && $k < $a[$j - $h]; $j -= $h) {\n                $a[$j] = $a[$j - $h];\n            }\n            $a[$j] = $k;\n        }\n    }\n    @a;\n}\n\nmy @a = map int rand 100, 1 .. $ARGV[0] || 10;\nsay \"@a\";\n@a = shell_sort @a;\nsay \"@a\";\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":3672}
    {"lang_cluster":"Perl","source_code":"\nLibrary: Imlib2\n\n#! \/usr\/bin\/perl\n\nuse strict;\nuse Image::Imlib2;\n\nsub tograyscale\n{\n    my $img = shift;\n    my $gimg = Image::Imlib2->new($img->width, $img->height);\n    for ( my $x = 0; $x < $gimg->width; $x++ ) {\n\tfor ( my $y = 0; $y < $gimg->height; $y++ ) {\n\t    my ( $r, $g, $b, $a ) = $img->query_pixel($x, $y);\n\t    my $gray = int(0.2126 * $r + 0.7152 * $g + 0.0722 * $b);\n\t    # discard alpha info...\n\t    $gimg->set_color($gray, $gray, $gray, 255);\n\t    $gimg->draw_point($x, $y);\n\t}\n    }\n    return $gimg;\n}\n\nmy $animage = Image::Imlib2->load(\"Lenna100.jpg\");\nmy $gscale = tograyscale($animage);\n$gscale->set_quality(80);\n$gscale->save(\"Lennagray.jpg\");\n\nexit 0;\n\n","human_summarization":"extend the data storage type to support grayscale images. They define two operations to convert a color image to grayscale and vice versa using the CIE recommended formula for luminance. The codes ensure that rounding errors in floating-point arithmetic do not cause run-time issues or distort results when storing calculated luminance as an unsigned integer. The codes use Imlib2 to convert RGB images to grayscale-like images.","id":3673}
    {"lang_cluster":"Perl","source_code":"\nuse Tk;\nuse Time::HiRes qw(sleep);\n\nmy $msg    = 'Hello World! ';\nmy $first  = '.+';\nmy $second = '.';\n\nmy $mw = Tk::MainWindow->new(-title => 'Animated side-scroller',-bg=>\"white\");\n$mw->geometry (\"400x150+0+0\");\n\n$mw->optionAdd('*Label.font', 'Courier 24 bold' );\n\nmy $scroller = $mw->Label(-text => \"$msg\")->grid(-row=>0,-column=>0);\n$mw->bind('all'=> '<Key-Escape>' => sub {exit;});\n$mw->bind(\"<Button>\" => sub { ($second,$first) = ($first,$second) });\n\n$scroller->after(1, \\&display );\nMainLoop;\n\nsub display {\n    while () {\n        sleep 0.25;\n        $msg =~ s\/($first)($second)\/$2$1\/;\n        $scroller->configure(-text=>\"$msg\");\n        $mw->update();\n    }\n}\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":3674}
    {"lang_cluster":"Perl","source_code":"\nmy $val = 0;\ndo {\n   $val++;\n   print \"$val\\n\";\n} while ($val\u00a0% 6);\n\nmy $val = 0;\ndo {\n   $val++;\n   print \"$val\\n\";\n} until ($val\u00a0% 6 == 0);\n","human_summarization":"Initializes a value at 0, then enters a loop that increments the value by 1 and prints it each iteration. The loop continues until the value modulo 6 equals 0. The loop is guaranteed to execute at least once.","id":3675}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.8\n\nuse utf8; # so we can use literal characters like \u263a in source\nuse Encode qw(encode);\n\nprint length encode 'UTF-8', \"Hello, world! \u263a\";\n# 17. The last character takes 3 bytes, the others 1 byte each.\n\nprint length encode 'UTF-16', \"Hello, world! \u263a\";\n# 32. 2 bytes for the BOM, then 15 byte pairs for each character.\nWorks with: Perl version 5.X\nmy $length = length \"Hello, world!\";\n\nWorks with: Perl version 5.12\nuse v5.12;\nmy $string = \"\\x{1112}\\x{1161}\\x{11ab}\\x{1100}\\x{1173}\\x{11af}\";  # \ud55c\uae00\nmy $len;\n$len++ while ($string =~ \/\\X\/g);\nprintf \"Grapheme length: %d\\n\", $len;\n\n","human_summarization":"The code calculates the character and byte length of a string, considering UTF-8 and UTF-16 encodings. It correctly handles non-BMP code points and provides actual character counts in code points, not in code unit counts. It also provides the string length in graphemes if the language supports it. For Perl strings, it measures the byte length by converting to a binary representation. It also matches an extended grapheme cluster in Perl 5.12 and above.","id":3676}
    {"lang_cluster":"Perl","source_code":"\n\nuse Crypt::Random::Seed;\nmy $source = Crypt::Random::Seed->new( NonBlocking => 1 ); # Allow non-blocking sources like \/dev\/urandom\nprint \"$_\\n\" for $source->random_values(10);               # A method returning an array of 32-bit values\n\n\nuse Crypt::Random::Source qw\/get_weak\/;    # Alternately get_strong\nprint unpack('L*',get_weak(4)), \"\\n\" for 1..10;\n\n\nsub read_random {\n        my $device = '\/dev\/urandom';\n        open my $in, \"<:raw\", $device   # :raw because it's not unicode string\n                or die \"Can't open $device: $!\";\n\n        sysread $in, my $rand, 4 * shift;\n        unpack('L*', $rand);\n}\n\nprint \"$_\\n\" for read_random(10);\n\n\n","human_summarization":"generates a random 32-bit number using the system's random number generator device. It utilizes modules like Crypt::Random::Seed for compatibility across UNIX, Win32, and other operating systems. The code can also directly read values from \/dev\/urandom if necessary. The suitability of \/dev\/urandom for cryptographic work is considered in the code.","id":3677}
    {"lang_cluster":"Perl","source_code":"\nprint substr(\"knight\",1), \"\\n\";        # strip first character\nprint substr(\"socks\", 0, -1), \"\\n\";    # strip last character\nprint substr(\"brooms\", 1, -1), \"\\n\";   # strip both first and last characters\n\n\n$string = 'ouch';\n$bits = chop($string);       # The last letter is returned by the chop function\nprint $bits;        # h\nprint $string;      # ouc    # See we really did chop the last letter off\n\n","human_summarization":"demonstrate how to remove the first, last, and both the first and last characters from a string, taking into account any valid Unicode code point in UTF-8 or UTF-16 encoding. The Perl version uses the chop function to remove the last character.","id":3678}
    {"lang_cluster":"Perl","source_code":"\n\nuse Fcntl ':flock';\n\nINIT\n{\n\tdie \"Not able to open $0\\n\" unless (open ME, $0);\n\tdie \"I'm already running\u00a0!!\\n\" unless(flock ME, LOCK_EX|LOCK_NB);\n}\n\nsleep 60; # then your code goes here\n\n","human_summarization":"check if only one instance of an application is running. If another instance is detected, a message is displayed and the program exits. This is done by attempting to lock the file from which the script was called, during the INIT block before the Perl runtime begins execution.","id":3679}
    {"lang_cluster":"Perl","source_code":"\nuse strict;\nuse warnings;\nuse Tk;\n\nsub get_size {\n\tmy $mw = MainWindow->new();\n\treturn ($mw->maxsize);\n}\n\n\n","human_summarization":"\"Determines the maximum height and width of a window that can fit within the physical display area of the screen without scrolling, considering window decorations, menubars, multiple monitors, and tiling window managers.\"","id":3680}
    {"lang_cluster":"Perl","source_code":"\n#!\/usr\/bin\/perl\nuse integer;\nuse strict;\n\nmy @A = qw(\n    5 3 0  0 2 4  7 0 0 \n    0 0 2  0 0 0  8 0 0 \n    1 0 0  7 0 3  9 0 2 \n\n    0 0 8  0 7 2  0 4 9 \n    0 2 0  9 8 0  0 7 0 \n    7 9 0  0 0 0  0 8 0 \n\n    0 0 0  0 3 0  5 0 6 \n    9 6 0  0 1 0  3 0 0 \n    0 5 0  6 9 0  0 1 0\n);\n\nsub solve {\n    my $i;\n    foreach $i ( 0 .. 80 ) {\n\tnext if $A[$i];\n\tmy %t = map {\n\t\t$_ \/ 9 == $i \/ 9 ||\n\t\t$_ % 9 == $i % 9 ||\n\t\t$_ \/ 27 == $i \/ 27 && $_ % 9 \/ 3 == $i\u00a0% 9 \/ 3\n\t\t? $A[$_] : 0,\n\t\t1;\n\t    } 0 .. 80;\n\tsolve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9;\n\treturn $A[$i] = 0;\n    }\n    $i = 0;\n    foreach (@A) {\n\tprint \"-----+-----+-----\\n\" if !($i%27) && $i;\n\tprint !($i%9) ? '': $i%3 ? ' ' : '|', $_;\n\tprint \"\\n\" unless ++$i%9;\n    }\n}\nsolve();\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":3681}
    {"lang_cluster":"Perl","source_code":"\nsub shuffle {\n  my @a = @_;\n  foreach my $n (1 .. $#a) {\n    my $k = int rand $n + 1;\n    $k == $n or @a[$k, $n] = @a[$n, $k];\n  }\n  return @a;\n}\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":3682}
    {"lang_cluster":"Perl","source_code":"\n#!\/usr\/bin\/perl -w\nuse strict ;\nuse DateTime ;\nuse feature qw( say ) ;\n\nforeach my $month ( 1..12 ) {\n   my $dt = DateTime->last_day_of_month( year => $ARGV[ 0 ] , month => $month ) ;\n   while ( $dt->day_of_week != 5 ) {\n      $dt->subtract( days => 1 ) ;\n   }\n   say $dt->ymd ;\n}\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":3683}
    {"lang_cluster":"Perl","source_code":"\nprint \"Goodbye, World!\";    # A newline does not occur automatically\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":3684}
    {"lang_cluster":"Perl","source_code":"\nuse Wx;\n\npackage MyApp;\nuse base 'Wx::App';\nuse Wx qw(wxHORIZONTAL wxVERTICAL wxALL wxALIGN_CENTER);\nuse Wx::Event 'EVT_BUTTON';\n\nour ($frame, $text_input, $integer_input);\n\nsub OnInit\n   {$frame = new Wx::Frame\n       (undef, -1, 'Input window', [-1, -1], [250, 150]);\n\n    my $panel = new Wx::Panel($frame, -1);\n    $text_input = new Wx::TextCtrl($panel, -1, '');\n    $integer_input = new Wx::SpinCtrl\n       ($panel, -1, '', [-1, -1], [-1, -1],\n        0, 0, 100_000);\n\n    my $okay_button = new Wx::Button($panel, -1, 'OK');\n    EVT_BUTTON($frame, $okay_button, \\&OnQuit);\n\n    my $sizer = new Wx::BoxSizer(wxVERTICAL);\n    $sizer->Add($_, 0, wxALL | wxALIGN_CENTER, 5)\n        foreach $text_input, $integer_input, $okay_button;\n    $panel->SetSizer($sizer);\n\n    $frame->Show(1);}\n\nsub OnQuit\n   {print 'String: ', $text_input->GetValue, \"\\n\";\n    print 'Integer: ', $integer_input->GetValue, \"\\n\";\n    $frame->Close;}\n\n# ---------------------------------------------------------------\n\npackage main;\n\nMyApp->new->MainLoop;\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":3685}
    {"lang_cluster":"Perl","source_code":"\nsub caesar {\n        my ($message, $key, $decode) = @_;\n        $key = 26 - $key if $decode;\n        $message =~ s\/([A-Z])\/chr(((ord(uc $1) - 65 + $key)\u00a0% 26) + 65)\/geir;\n}\n \nmy $msg = 'THE FIVE BOXING WIZARDS JUMP QUICKLY';\nmy $enc = caesar($msg, 10);\nmy $dec = caesar($enc, 10, 'decode');\n \nprint \"msg: $msg\\nenc: $enc\\ndec: $dec\\n\";\n\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":3686}
    {"lang_cluster":"Perl","source_code":"\n\nsub gcd {\n\tmy ($x, $y) = @_;\n\twhile ($x) { ($x, $y) = ($y % $x, $x) }\n\t$y\n}\n\nsub lcm {\n\tmy ($x, $y) = @_;\n\t($x && $y) and $x \/ gcd($x, $y) * $y or 0\n}\n\nprint lcm(1001, 221);\n\nOr by repeatedly increasing the smaller of the two until LCM is reached:sub lcm {\n\tuse integer;\n\tmy ($x, $y) = @_;\n\tmy ($f, $s) = @_;\n\twhile ($f != $s) {\n\t\t($f, $s, $x, $y) = ($s, $f, $y, $x) if $f > $s;\n\t\t$f = $s \/ $x * $x;\n\t\t$f += $x if $f < $s;\n\t}\n\t$f\n}\n\nprint lcm(1001, 221);\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers, m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":3687}
    {"lang_cluster":"Perl","source_code":"\n$cv{$_} = $i++ for '0'..'9', 'A'..'Z', '*', '@', '#';\n\nsub cusip_check_digit {\n    my @cusip = split m{}xms, shift;\n    my $sum = 0;\n\n    for $i (0..7) {\n        return 'Invalid character found' unless $cusip[$i] =~ m{\\A [[:digit:][:upper:]*@#] \\z}xms;\n        $v  = $cv{ $cusip[$i] };\n        $v *= 2 if $i%2;\n        $sum += int($v\/10) + $v%10;\n    }\n\n    $check_digit = (10 - ($sum%10)) % 10;\n    $check_digit == $cusip[8] ? '' : ' (incorrect)';\n}\n\nmy %test_data = (\n    '037833100' => 'Apple Incorporated',\n    '17275R102' => 'Cisco Systems',\n    '38259P508' => 'Google Incorporated',\n    '594918104' => 'Microsoft Corporation',\n    '68389X106' => 'Oracle Corporation',\n    '68389X105' => 'Oracle Corporation',\n);\n\nprint \"$_ $test_data{$_}\" . cusip_check_digit($_) . \"\\n\" for sort keys %test_data;\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":3688}
    {"lang_cluster":"Perl","source_code":"\n\nuse Config;\nprint \"UV size: $Config{uvsize}, byte order: $Config{byteorder}\\n\";\n\n\n","human_summarization":"prints the word size and endianness of the host machine.","id":3689}
    {"lang_cluster":"Perl","source_code":"\nuse 5.010;\nuse MediaWiki::API;\n\nmy $api =\n  MediaWiki::API->new( { api_url => 'http:\/\/rosettacode.org\/w\/api.php' } );\n\nmy @languages;\nmy $gcmcontinue;\nwhile (1) {\n    my $apih = $api->api(\n        {\n            action      => 'query',\n            generator   => 'categorymembers',\n            gcmtitle    => 'Category:Programming Languages',\n            gcmlimit    => 250,\n            prop        => 'categoryinfo',\n            gcmcontinue => $gcmcontinue\n        }\n    );\n    push @languages, values %{ $apih->{'query'}{'pages'} };\n\n    last if not $gcmcontinue = $apih->{'continue'}{'gcmcontinue'};\n}\n\nfor (@languages) {\n    $_->{'title'} =~ s\/Category:\/\/;\n    $_->{'categoryinfo'}{'size'} \/\/= 0;\n}\n\nmy @sorted_languages =\n  reverse sort { $a->{'categoryinfo'}{'size'} <=> $b->{'categoryinfo'}{'size'} }\n  @languages;\n\nbinmode STDOUT, ':encoding(utf8)';\nmy $n = 1;\nfor (@sorted_languages) {\n    printf \"%3d. %20s - %3d\\n\", $n++, $_->{'title'},\n      $_->{'categoryinfo'}{'size'};\n}\n\n\n","human_summarization":"sort the most popular computer programming languages based on the number of members in Rosetta Code categories. It fetches data either through web scraping or using the API method. The code also has the functionality to filter incorrect results. The final output is a ranked list of all programming languages.","id":3690}
    {"lang_cluster":"Perl","source_code":"\nforeach my $i (@collection) {\n   print \"$i\\n\";\n}\n\nprint \"$_\\n\"  foreach @collection\n\nforeach $l ( \"apples\", \"bananas\", \"cherries\" ) {\n  print \"I like $l\\n\";\n}\n","human_summarization":"Iterates through each element in a collection in a sequential order using a \"for each\" loop or an alternative loop. In Perl, an explicit list can be looped without defining a container. The keyword \"for\" can replace \"foreach\", and if a loop variable isn't specified, \"$_\" is used. A compact notation can be achieved with a Perl statement modifier.","id":3691}
    {"lang_cluster":"Perl","source_code":"\nprint join('.', split \/,\/, 'Hello,How,Are,You,Today'), \"\\n\";\n\n\necho \"Hello,How,Are,You,Today\" | perl -aplF\/,\/ -e '$\" = \".\"; $_ = \"@F\";'\n\n\nBEGIN { $\/ = \"\\n\"; $\\ = \"\\n\"; }\nLINE: while (defined($_ = <ARGV>)) {\n    chomp $_;\n    our(@F) = split(\/,\/, $_, 0);\n    $\" = '.';\n    $_ = \"@F\";\n}\ncontinue {\n    die \"-p destination: $!\\n\" unless print $_;\n}\n\n","human_summarization":"\"Tokenizes a string by separating it into an array based on commas, and displays each word to the user separated by a period. A trailing period may also be displayed for simplicity.\"","id":3692}
    {"lang_cluster":"Perl","source_code":"\nsub gcd_iter($$) {\n  my ($u, $v) = @_;\n  while ($v) {\n    ($u, $v) = ($v, $u\u00a0% $v);\n  }\n  return abs($u);\n}\nsub gcd($$) {\n  my ($u, $v) = @_;\n  if ($v) {\n    return gcd($v, $u\u00a0% $v);\n  } else {\n    return abs($u);\n  }\n}\nsub gcd_bin($$) {\n  my ($u, $v) = @_;\n  $u = abs($u);\n  $v = abs($v);\n  if ($u < $v) {\n    ($u, $v) = ($v, $u);\n  }\n  if ($v == 0) {\n    return $u;\n  }\n  my $k = 1;\n  while ($u & 1 == 0 && $v & 1 == 0) {\n    $u >>= 1;\n    $v >>= 1;\n    $k <<= 1;\n  }\n  my $t = ($u & 1)\u00a0? -$v\u00a0: $u;\n  while ($t) {\n    while ($t & 1 == 0) {\n      $t >>= 1;\n    }\n    if ($t > 0) {\n      $u = $t;\n    } else {\n      $v = -$t;\n    }\n    $t = $u - $v;\n  }\n  return $u * $k;\n}\n\n# Fastest, takes multiple inputs\nuse Math::Prime::Util \"gcd\";\n$gcd = gcd(49865, 69811);\n\n# In CORE.  Slowest, takes multiple inputs, result is a Math::BigInt unless converted\nuse Math::BigInt;\n$gcd = Math::BigInt::bgcd(49865, 69811)->numify;\n\n# Result is a Math::Pari object unless converted\nuse Math::Pari \"gcd\";\n$gcd = gcd(49865, 69811)->pari2iv\nuse Benchmark qw(cmpthese);\nuse Math::BigInt;\nuse Math::Pari;\nuse Math::Prime::Util;\n\nmy $u = 40902;\nmy $v = 24140;\ncmpthese(-5, {\n  'gcd_rec' => sub { gcd($u, $v); },\n  'gcd_iter' => sub { gcd_iter($u, $v); },\n  'gcd_bin' => sub { gcd_bin($u, $v); },\n  'gcd_bigint' => sub { Math::BigInt::bgcd($u,$v)->numify(); },\n  'gcd_pari' => sub { Math::Pari::gcd($u,$v)->pari2iv(); },\n  'gcd_mpu' => sub { Math::Prime::Util::gcd($u,$v); },\n});\n\n                Rate gcd_bigint   gcd_bin   gcd_rec  gcd_iter gcd_pari   gcd_mpu\ngcd_bigint   39939\/s         --      -83%      -94%      -95%     -98%      -99%\ngcd_bin     234790\/s       488%        --      -62%      -70%     -88%      -97%\ngcd_rec     614750\/s      1439%      162%        --      -23%     -68%      -91%\ngcd_iter    793422\/s      1887%      238%       29%        --     -58%      -89%\ngcd_pari   1896544\/s      4649%      708%      209%      139%       --      -73%\ngcd_mpu    7114798\/s     17714%     2930%     1057%      797%     275%        --\n\n","human_summarization":"find the greatest common divisor (GCD), also known as greatest common factor (GCF) or greatest common measure, of two large integers. The code uses modules like Math::Cephes euclid, Math::GMPz gcd and gcd_ui for this task. It also relates to the task of finding the least common multiple.","id":3693}
    {"lang_cluster":"Perl","source_code":"\n\nuse IO::Socket;\nmy $use_fork = 1;\n\nmy $sock = new IO::Socket::INET (\n                                 LocalHost => '127.0.0.1',\n                                 LocalPort => '12321',\n                                 Proto => 'tcp',\n                                 Listen => 1,   # maximum queued connections\n                                 Reuse => 1,\n                                )\n\t\tor die \"socket: $!\";\t# no newline, so perl appends stuff\n\n$SIG{CHLD} = 'IGNORE' if $use_fork;\t# let perl deal with zombies\n\nprint \"listening...\\n\";\nwhile (1) {\n\t# declare $con 'my' so it's closed by parent every loop\n        my $con = $sock->accept()\n\t\tor die \"accept: $!\";\n\tfork and next if $use_fork;\t# following are for child only\n\n\tprint \"incoming..\\n\";\n\tprint $con $_ while(<$con>);\t# read each line and write back\n\tprint \"done\\n\";\n\n\tlast\tif $use_fork;\t# if not forking, loop\n}\n\n# child will reach here and close its copy of $sock before exit\n\n\npackage Echo;\nuse base 'Net::Server::Fork';\nsub process_request {\n    print while <STDIN>;\n}\nEcho->run(port => 12321, log_level => 3);\n\n\npackage Echo;\nuse base 'Net::Server::PreFork';\nsub process_request {\n    print while <STDIN>;\n}\nEcho->run(port => 12321, log_level => 3);\n\n\n","human_summarization":"implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost only, and echoes back complete lines sent by clients. It also logs connection details and ensures continuous response to all clients even if one sends a partial line or stops reading responses. The server uses either multi-threading or multi-processing and supports echoing of more than one line per connection. The server also forks a new process for each client connection.","id":3694}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.8\nuse Scalar::Util qw(looks_like_number);\nprint looks_like_number($str) ? \"numeric\" : \"not numeric\\n\";\n\nWorks with: Perl version 5.8\n\nif (\/\\D\/)            { print \"has nondigits\\n\" }\nif (\/^\\d+\\z\/)         { print \"is a whole number\\n\" }\nif (\/^-?\\d+\\z\/)       { print \"is an integer\\n\" }\nif (\/^[+-]?\\d+\\z\/)    { print \"is a +\/- integer\\n\" }\nif (\/^-?\\d+\\.?\\d*\\z\/) { print \"is a real number\\n\" }\nif (\/^-?(?:\\d+(?:\\.\\d*)?&\\.\\d+)\\z\/) { print \"is a decimal number\\n\" }\nif (\/^([+-]?)(?=\\d&\\.\\d)\\d*(\\.\\d*)?([Ee]([+-]?\\d+))?\\z\/)\n                     { print \"a C float\\n\" }\n\n\nsub getnum {\n    use POSIX;\n    my $str = shift;\n    $str =~ s\/^\\s+\/\/;\n    $str =~ s\/\\s+$\/\/;\n    $! = 0;\n    my($num, $unparsed) = strtod($str);\n    if (($str eq '') && ($unparsed != 0) && $!) {\n        return undef;\n    } else {\n        return $num;\n    }\n}\n\nsub is_numeric { defined getnum($_[0]) }\n\n\n","human_summarization":"The code is a boolean function that checks if a given string is numeric, including floating point and negative numbers. It uses Perl's internal function \"looks_like_number\", Data::Types functions, and regular expressions from \"Regexp::Common\". It also uses the \"POSIX::strtod\" function for POSIX systems and the String::Scanf module. The function returns the number found in the string, or \"undef\" if the input is not a C float.","id":3695}
    {"lang_cluster":"Perl","source_code":"\nLibrary: LWP\nuse strict;\nuse LWP::UserAgent;\n\nmy $url = 'https:\/\/www.rosettacode.org';\nmy $response = LWP::UserAgent->new->get( $url );\n\n$response->is_success or die \"Failed to GET '$url': \", $response->status_line;\n\nprint $response->as_string;\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":3696}
    {"lang_cluster":"Perl","source_code":"use strict;\nuse warnings;\n\nsub intersection {\n    my($L11, $L12, $L21, $L22) = @_;\n    my ($d1x, $d1y) = ($$L11[0] - $$L12[0], $$L11[1] - $$L12[1]);\n    my ($d2x, $d2y) = ($$L21[0] - $$L22[0], $$L21[1] - $$L22[1]);\n    my $n1 = $$L11[0] * $$L12[1] - $$L11[1] * $$L12[0];\n    my $n2 = $$L21[0] * $$L22[1] - $$L21[1] * $$L22[0];\n    my $n3 = 1 \/ ($d1x * $d2y - $d2x * $d1y);\n    [($n1 * $d2x - $n2 * $d1x) * $n3, ($n1 * $d2y - $n2 * $d1y) * $n3]\n}\n\nsub is_inside {\n    my($p1, $p2, $p3) = @_;\n    ($$p2[0] - $$p1[0]) * ($$p3[1] - $$p1[1]) > ($$p2[1] - $$p1[1]) * ($$p3[0] - $$p1[0])\n}\n\nsub sutherland_hodgman {\n    my($polygon, $clip) = @_;\n    my @output = @$polygon;\n    my $clip_point1 = $$clip[-1];\n    for my $clip_point2 (@$clip) {\n        my @input = @output;\n        @output = ();\n        my $start = $input[-1];\n        for my $end (@input) {\n            if (is_inside($clip_point1, $clip_point2, $end)) {\n                push @output, intersection($clip_point1, $clip_point2, $start, $end)\n                  unless is_inside($clip_point1, $clip_point2, $start);\n                push @output, $end;\n            } elsif (is_inside($clip_point1, $clip_point2, $start)) {\n                push @output, intersection($clip_point1, $clip_point2, $start, $end);\n            }\n            $start = $end;\n        }\n        $clip_point1 = $clip_point2;\n    }\n    @output\n}\n\nmy @polygon = ([50,  150], [200, 50],  [350, 150], [350, 300], [250, 300],\n              [200, 250], [150, 350], [100, 250], [100, 200]);\n\nmy @clip    = ([100, 100], [300, 100], [300, 300], [100, 300]);\n\nmy @clipped = sutherland_hodgman(\\@polygon, \\@clip);\n\nprint \"Clipped polygon:\\n\";\nprint '(' . join(' ', @$_) . ') ' for @clipped;\n\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":3697}
    {"lang_cluster":"Perl","source_code":"my %scores = (\n    'Solomon' => 44,\n    'Jason'   => 42,\n    'Errol'   => 42,\n    'Garry'   => 41,\n    'Bernard' => 41,\n    'Barry'   => 41,\n    'Stephen' => 39\n);\n\nsub tiers {\n    my(%s) = @_; my(%h);\n    push @{$h{$s{$_}}}, $_ for keys %s;\n    @{\\%h}{reverse sort keys %h};\n}\n\nsub standard {\n    my(%s) = @_; my($result);\n    my $rank = 1;\n    for my $players (tiers %s) {\n        $result .= \"$rank \" . join(', ', sort @$players) . \"\\n\";\n        $rank += @$players;\n    }\n    return $result;\n}\n\nsub modified {\n    my(%s) = @_; my($result);\n    my $rank = 0;\n    for my $players (tiers %s) {\n        $rank += @$players;\n        $result .= \"$rank \" . join(', ', sort @$players) . \"\\n\";\n    }\n    return $result;\n}\n\nsub dense {\n    my(%s) = @_; my($n,$result);\n    $result .= sprintf \"%d %s\\n\", ++$n, join(', ', sort @$_) for tiers %s;\n    return $result;\n}\n\nsub ordinal {\n    my(%s) = @_; my($n,$result);\n    for my $players (tiers %s) {\n        $result .= sprintf \"%d %s\\n\", ++$n, $_ for sort @$players;\n    }\n    return $result;\n}\n\nsub fractional {\n    my(%s) = @_; my($result);\n    my $rank = 1;\n    for my $players (tiers %s) {\n        my $beg = $rank;\n        my $end = $rank += @$players;\n        my $avg = 0;\n        $avg += $_\/@$players for $beg .. $end-1;\n        $result .= sprintf \"%3.1f %s\\n\", $avg, join ', ', sort @$players;\n    }\n    return $result;\n}\n\nprint \"Standard:\\n\"    .   standard(%scores) . \"\\n\";\nprint \"Modified:\\n\"    .   modified(%scores) . \"\\n\";\nprint \"Dense:\\n\"       .      dense(%scores) . \"\\n\";\nprint \"Ordinal:\\n\"     .    ordinal(%scores) . \"\\n\";\nprint \"Fractional:\\n\"  . fractional(%scores) . \"\\n\";\n\n\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":3698}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.8.8\nuse Math::Trig;\n\nmy $angle_degrees = 45;\nmy $angle_radians = pi \/ 4;\n\nprint sin($angle_radians), ' ', sin(deg2rad($angle_degrees)), \"\\n\";\nprint cos($angle_radians), ' ', cos(deg2rad($angle_degrees)), \"\\n\";\nprint tan($angle_radians), ' ', tan(deg2rad($angle_degrees)), \"\\n\";\nprint cot($angle_radians), ' ', cot(deg2rad($angle_degrees)), \"\\n\";\nmy $asin = asin(sin($angle_radians));\nprint $asin, ' ', rad2deg($asin), \"\\n\";\nmy $acos = acos(cos($angle_radians));\nprint $acos, ' ', rad2deg($acos), \"\\n\";\nmy $atan = atan(tan($angle_radians));\nprint $atan, ' ', rad2deg($atan), \"\\n\";\nmy $acot = acot(cot($angle_radians));\nprint $acot, ' ', rad2deg($acot), \"\\n\";\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":3699}
    {"lang_cluster":"Perl","source_code":"\n\n#!\/usr\/bin\/perl\n\nuse strict;\n\nmy $raw = <<'TABLE';\nmap     \t9       150     1\ncompass \t13      35      1\nwater   \t153     200     2\nsandwich        50      60      2\nglucose \t15      60      2\ntin     \t68      45      3\nbanana  \t27      60      3\napple  \t\t39      40      3\ncheese  \t23      30      1\nbeer    \t52      10      1\nsuntancream     11      70      1\ncamera  \t32      30      1\nT-shirt \t24      15      2\ntrousers        48      10      2\numbrella        73      40      1\nw_trousers     \t42      70      1\nw_overcoat  \t43      75      1\nnote-case       22      80      1\nsunglasses      7       20      1\ntowel   \t18      12      2\nsocks   \t4       50      1\nbook    \t30      10      2\nTABLE\n \nmy @items;\nfor (split \"\\n\", $raw) {\n        my @x = split \/\\s+\/;\n\tpush @items, {\n\t\tname\t=> $x[0],\n\t\tweight\t=> $x[1],\n\t\tvalue\t=> $x[2],\n\t\tquant\t=> $x[3],\n\t}\n}\n\nmy $max_weight = 400;\n\nmy %cache;\nsub pick {\n\tmy ($weight, $pos) = @_;\n\tif ($pos < 0 or $weight <= 0) {\n\t\treturn 0, 0, []\n\t}\n\n\t@{ $cache{$weight, $pos} \/\/= [do{\t# odd construct: for caching\n\t\tmy $item = $items[$pos];\n\t\tmy ($bv, $bi, $bw, $bp) = (0, 0, 0, []);\n\n\t\tfor my $i (0 .. $item->{quant}) {\n\t\t\tlast if $i * $item->{weight} > $weight;\n\t\t\tmy ($v, $w, $p) = pick($weight - $i * $item->{weight}, $pos - 1);\n\t\t\tnext if ($v += $i * $item->{value}) <= $bv;\n\n\t\t\t($bv, $bi, $bw, $bp) = ($v, $i, $w, $p);\n\t\t}\n\n\t\tmy @picked = ( @$bp, $bi );\n\t\t$bv, $bw + $bi * $item->{weight}, \\@picked\n\t}]}\n}\n\nmy ($v, $w, $p) = pick($max_weight, $#items);\nfor (0 .. $#$p) {\n\tif ($p->[$_] > 0) {\n\t\tprint \"$p->[$_] of $items[$_]{name}\\n\";\n\t}\n}\nprint \"Value: $v; Weight: $w\\n\";\n\n\n","human_summarization":"The code implements a solution to the bounded knapsack problem. It helps a tourist to determine the optimal combination of items to carry on a trip, with a weight limit of 4 kg, to maximize the total value. The items, their weights, values, and quantities are given. The solution uses recursion and caching for efficiency.","id":3700}
    {"lang_cluster":"Perl","source_code":"\n\nmy $start = time;  # seconds since epohc\nmy $arlm=5;  # every 5 seconds show how we're doing\nmy $i;\n\n$SIG{QUIT} = sub\n   {print \" Ran for \", time - $start, \" seconds.\\n\"; die; };\n$SIG{INT} = sub\n   {print \" Running for \", time - $start, \" seconds.\\n\"; };\n$SIG{ALRM} = sub\n   {print \" After $arlm  seconds i= $i. Executing for \",  time - $start, \" seconds.\\n\";  alarm $arlm };\n\n\nalarm $arlm;  # trigger ALaRM after we've run  for a while\n\nprint \" ^C to inerrupt, ^\\\\ to quit, takes a break at $arlm seconds \\n\";\n\nwhile ( 1 ) {\n   for ( $w=11935000; $w--; $w>0 ){}; # spinning is bad, but hey it's only a demo\n\n    print (  ++$i,\" \\n\");\n            }\n\n^C to inerrupt, ^\\ to quit, takes a break at 5 seconds\n\n\nAfter 5  seconds i= 10. Executing for 5 seconds.\n\n\nAfter 5  seconds i= 20. Executing for 10 seconds.\n\n\nuse 5.010;\nuse AnyEvent;\nmy $start = AE::time;\nmy $exit = AE::cv;\nmy $int = AE::signal 'INT', $exit;\nmy $n;\nmy $num = AE::timer 0, 0.5, sub { say $n++ };\n$exit->recv;\nsay \" interrupted after \", AE::time - $start, \" seconds\";\n\n\n","human_summarization":"The code outputs an integer every half second. When it receives a SIGINT signal (usually triggered by user typing ctrl-C) or a SIGQUIT signal (triggered by ctrl-\\), it stops outputting integers, displays the total runtime in seconds, and then terminates.","id":3701}
    {"lang_cluster":"Perl","source_code":"\nmy $s = \"12345\";\n$s++;\n","human_summarization":"\"Increments a given numerical string.\"","id":3702}
    {"lang_cluster":"Perl","source_code":"\n\nsub common_prefix {\n    my $sep = shift;\n    my $paths = join \"\\0\", map { $_.$sep } @_;\n    $paths =~ \/^ ( [^\\0]* ) $sep [^\\0]* (?: \\0 \\1 $sep [^\\0]* )* $\/x;\n    return $1;\n}\n\n\nuse List::Util qw(first);\n\nsub common_prefix {\n    my ($sep, @paths) = @_;\n    my %prefixes;\n    \n    for (@paths) {\n        do { ++$prefixes{$_} } while s\/$sep [^$sep]* $\/\/x\n    }\n    \n    return first { $prefixes{$_} == @paths } reverse sort keys %prefixes;\n}\n\n\nmy @paths = qw(\/home\/user1\/tmp\/coverage\/test \n               \/home\/user1\/tmp\/covert\/operator\n               \/home\/user1\/tmp\/coven\/members);\nprint common_prefix('\/', @paths), \"\\n\";\n\n\n","human_summarization":"The code creates a function that identifies and returns the common directory path from a set of given directory paths using a specified directory separator. It tests this function using '\/' as the directory separator and three specific strings as input paths. The function ensures the returned path is a valid directory, not just the longest common string. The code also includes a solution that utilizes a regex engine to identify the common path, and another that uses a conventional method of tallying potential prefixes.","id":3703}
    {"lang_cluster":"Perl","source_code":"\n@a = 0..30;\n\nprintf \"%2d \", $_ for @a; print \"\\n\";\nsattolo_cycle(\\@a);\nprintf \"%2d \", $_ for @a; print \"\\n\";\n\nsub sattolo_cycle {\n    my($array) = @_;\n    for $i (reverse 0 .. -1+@$array) {\n        my $j = int rand $i;\n        @$array[$j, $i] = @$array[$i, $j];\n    }\n}\n\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":3704}
    {"lang_cluster":"Perl","source_code":"\nLibrary: SOAP::LiteLite\nuse SOAP::Lite;\n\nprint SOAP::Lite\n  -> service('http:\/\/example.com\/soap\/wsdl')\n  -> soapFunc(\"hello\");\nprint SOAP::Lite\n  -> service('http:\/\/example.com\/soap\/wsdl')\n  -> anotherSoapFunc(34234);\n\n","human_summarization":"The code establishes a SOAP client to access and call the functions soapFunc() and anotherSoapFunc() from the WSDL located at http:\/\/example.com\/soap\/wsdl. Note, the task and corresponding code may require further clarification.","id":3705}
    {"lang_cluster":"Perl","source_code":"sub median {\n  my @a = sort {$a <=> $b} @_;\n  return ($a[$#a\/2] + $a[@a\/2]) \/ 2;\n}\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.","id":3706}
    {"lang_cluster":"Perl","source_code":"\nuse strict;\nuse warnings;\nuse feature qw(say);\n\nfor my $i (1..100) {\n    say $i\u00a0% 15 == 0\u00a0? \"FizzBuzz\"\n     \u00a0: $i\u00a0%  3 == 0\u00a0? \"Fizz\"\n     \u00a0: $i\u00a0%  5 == 0\u00a0? \"Buzz\"\n     \u00a0: $i;\n}\n\nprint 'Fizz'x!($_\u00a0% 3) . 'Buzz'x!($_\u00a0% 5) || $_, \"\\n\" for 1 .. 100;\n\nprint+(Fizz)[$_%3].(Buzz)[$_%5]||$_,$\/for 1..1e2\n\nmap((Fizz)[$_%3].(Buzz)[$_%5]||$_,1..100);\n\nuse feature \"say\";\n\n@a = (\"FizzBuzz\", 0, 0, \"Fizz\", 0, \"Buzz\", \"Fizz\", 0, 0, \"Fizz\", \"Buzz\", 0, \"Fizz\");\n\nsay $a[$_\u00a0% 15] || $_ for 1..100;\n\nsub fizz_buzz {\n    join(\"\\n\", map {\n        sub mult {$_\u00a0% shift == 0};\n        my @out;\n        if (mult 3) { push @out, \"Fizz\"; }\n        if (mult 5) { push @out, \"Buzz\"; }\n        if (!@out) {push @out, $_; }\n        join('', @out);\n    } (1..100)).\"\\n\";\n}\nprint fizz_buzz;\n\n \n@FB1 = (1..100);\n@FB2 = map{!($_%3 or $_%5)?'FizzBuzz': $_}@FB1;\n@FB3 = map{(\/\\d\/ and\u00a0!($_%3))?'Fizz': $_}@FB2;\n@FB4 = map{(\/\\d\/ and\u00a0!($_%5))?'Buzz': $_}@FB3;\n@FB5 = map{$_.\"\\n\"}@FB4;\nprint @FB5;\n","human_summarization":"print integers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both with 'FizzBuzz'.","id":3707}
    {"lang_cluster":"Perl","source_code":"\n\nuse Math::Complex;\n\nsub mandelbrot {\n    my ($z, $c) = @_[0,0];\n    for (1 .. 20) {\n        $z = $z * $z + $c;\n        return $_ if abs $z > 2;\n    }\n}\n\nfor (my $y = 1; $y >= -1; $y -= 0.05) {\n    for (my $x = -2; $x <= 0.5; $x += 0.0315)\n        {print mandelbrot($x + $y * i)\u00a0? ' '\u00a0: '#'}\n    print \"\\n\"\n}\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. The code is an optimized translation of a Ruby solution.","id":3708}
    {"lang_cluster":"Perl","source_code":"\nmy @list = ( 1, 2, 3 );\n\nmy ( $sum, $prod ) = ( 0, 1 );\n$sum  += $_ foreach @list;\n$prod *= $_ foreach @list;\n\nuse List::Util qw\/sum0 product\/;\nmy @list = (1..9);\n\nsay \"Sum: \", sum0(@list);    # sum0 returns 0 for an empty list\nsay \"Product: \", product(@list);\n\n","human_summarization":"\"Calculates the sum and product of an array of integers, potentially utilizing the List::Util module.\"","id":3709}
    {"lang_cluster":"Perl","source_code":"\nsub isleap {\n    my $year = shift;\n    if ($year\u00a0% 100 == 0) {\n        return ($year\u00a0% 400 == 0);\n    }\n    return ($year\u00a0% 4 == 0);\n}\n\nsub isleap { not $_[0]\u00a0% ($_[0]\u00a0% 100\u00a0? 4\u00a0: 400) }\n\nuse Date::Manip;\nprint Date_LeapYear(2000);\n\nuse Date::Manip::Base;\nmy $dmb = new Date::Manip::Base;\nprint $dmb->leapyear(2000);\n\nuse DateTime;\nmy $date = DateTime->new(year => 2000);\nprint $date->is_leap_year();\n","human_summarization":"determine if a given year is a leap year in the Gregorian calendar using CPAN modules functions\/methods.","id":3710}
    {"lang_cluster":"Perl","source_code":"\n# 20200814 added Perl programming solution\n\nuse strict;\nuse warnings;\n\nuse Crypt::OTP;\nuse Bytes::Random::Secure qw( random_bytes );\n\nprint \"Message    \u00a0: \", my $message = \"show me the monKey\", \"\\n\";\n\nmy $otp = random_bytes(length $message);\nprint \"Ord(OTP)   \u00a0: \", ( map { ord($_).' ' } (split \/\/, $otp)   ) , \"\\n\";\n\nmy $cipher = OTP( $otp, $message, 1 );\nprint \"Ord(Cipher)\u00a0: \", ( map { ord($_).' ' } (split \/\/, $cipher) ) , \"\\n\";\n\nprint \"Decoded    \u00a0: \",  OTP( $otp, $cipher, 1 ), \"\\n\";\n\n\n","human_summarization":"The code implements a One-time pad for encrypting and decrypting messages using only letters. It generates data for a One-time pad based on user-specified filename and length, ensuring the use of \"true random\" numbers. The encryption and decryption process is similar to Rot-13, and much of Vigen\u00e8re cipher is reused with the key read from the One-time pad file. The code also optionally manages One-time pads, allowing users to list, mark as used, delete, and track which pad to use for which partner. It supports the management of pad-files with a \".1tp\" extension, and handles lines starting with \"#\" as comments, lines starting with \"-\" as \"used\", and ignores whitespace within the otp-data.","id":3711}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.10.1 (and later)\nuse strict;\nuse warnings;\nuse integer;\nuse Test::More;\n\nBEGIN { plan tests => 7 }\n\nsub A()   { 0x67_45_23_01 }\nsub B()   { 0xef_cd_ab_89 }\nsub C()   { 0x98_ba_dc_fe }\nsub D()   { 0x10_32_54_76 }\nsub MAX() { 0xFFFFFFFF }\n\nsub padding {\n    my $l = length (my $msg = shift() . chr(128));\n    $msg .= \"\\0\" x (($l%64<=56?56:120)-$l%64);\n    $l = ($l-1)*8;\n    $msg .= pack 'VV', $l & MAX , ($l >> 16 >> 16);\n}\n\nsub rotate_left {\n    ($_[0] << $_[1]) | (( $_[0] >> (32 - $_[1])  )  & ((1 << $_[1]) - 1));\n}\n\nsub gen_code {\n  # Discard upper 32 bits on 64 bit archs.\n  my $MSK = ((1 << 16) << 16) ? ' & ' . MAX : '';\n  my %f = (\n    FF => \"X0=rotate_left((X3^(X1&(X2^X3)))+X0+X4+X6$MSK,X5)+X1$MSK;\",\n    GG => \"X0=rotate_left((X2^(X3&(X1^X2)))+X0+X4+X6$MSK,X5)+X1$MSK;\",\n    HH => \"X0=rotate_left((X1^X2^X3)+X0+X4+X6$MSK,X5)+X1$MSK;\",\n    II => \"X0=rotate_left((X2^(X1|(~X3)))+X0+X4+X6$MSK,X5)+X1$MSK;\",\n  );\n\n  my %s = (  # shift lengths\n    S11 => 7, S12 => 12, S13 => 17, S14 => 22, S21 => 5, S22 => 9, S23 => 14,\n    S24 => 20, S31 => 4, S32 => 11, S33 => 16, S34 => 23, S41 => 6, S42 => 10,\n    S43 => 15, S44 => 21\n  );\n\n  my $insert = \"\\n\";\n  while(defined( my $data = <DATA> )) {\n    chomp $data;\n    next unless $data =~ \/^[FGHI]\/;\n    my ($func,@x) = split \/,\/, $data;\n    my $c = $f{$func};\n    $c =~ s\/X(\\d)\/$x[$1]\/g;\n    $c =~ s\/(S\\d{2})\/$s{$1}\/;\n    $c =~ s\/^(.*)=rotate_left\\((.*),(.*)\\)\\+(.*)$\/\/;\n\n    my $su = 32 - $3;\n    my $sh = (1 << $3) - 1;\n\n    $c = \"$1=(((\\$r=$2)<<$3)|((\\$r>>$su)&$sh))+$4\";\n\n    $insert .= \"\\t$c\\n\";\n  }\n  close DATA;\n\n  my $dump = '\n  sub round {\n    my ($a,$b,$c,$d) = @_[0 .. 3];\n    my $r;' . $insert . '\n    $_[0]+$a' . $MSK . ', $_[1]+$b ' . $MSK .\n    ', $_[2]+$c' . $MSK . ', $_[3]+$d' . $MSK . ';\n  }';\n  eval $dump;\n}\n\ngen_code();\n\nsub _encode_hex { unpack 'H*', $_[0] }\n\nsub md5 {\n    my $message = padding(join'',@_);\n    my ($a,$b,$c,$d) = (A,B,C,D);\n    my $i;\n    for $i (0 .. (length $message)\/64-1) {\n        my @X = unpack 'V16', substr $message,$i*64,64;\n        ($a,$b,$c,$d) = round($a,$b,$c,$d,@X);\n    }\n    pack 'V4',$a,$b,$c,$d;\n}\n\nmy $strings = {\n    'd41d8cd98f00b204e9800998ecf8427e' => '',\n    '0cc175b9c0f1b6a831c399e269772661' => 'a',\n    '900150983cd24fb0d6963f7d28e17f72' => 'abc',\n    'f96b697d7cb7938d525a2f31aaf161d0' => 'message digest',\n    'c3fcd3d76192e4007dfb496cca67e13b' => 'abcdefghijklmnopqrstuvwxyz',\n    'd174ab98d277d9f5a5611c2c9f419d9f' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',\n    '57edf4a22be3c955ac49da2e2107b67a' => '12345678901234567890123456789012345678901234567890123456789012345678901234567890',\n};\n\nfor my $k (keys %$strings) {\n    my $digest = _encode_hex md5($strings->{$k});\n    is($digest, $k, \"$digest is MD5 digest $strings->{$k}\");\n}\n\n__DATA__\nFF,$a,$b,$c,$d,$_[4],7,0xd76aa478,\/* 1 *\/\nFF,$d,$a,$b,$c,$_[5],12,0xe8c7b756,\/* 2 *\/\nFF,$c,$d,$a,$b,$_[6],17,0x242070db,\/* 3 *\/\nFF,$b,$c,$d,$a,$_[7],22,0xc1bdceee,\/* 4 *\/\nFF,$a,$b,$c,$d,$_[8],7,0xf57c0faf,\/* 5 *\/\nFF,$d,$a,$b,$c,$_[9],12,0x4787c62a,\/* 6 *\/\nFF,$c,$d,$a,$b,$_[10],17,0xa8304613,\/* 7 *\/\nFF,$b,$c,$d,$a,$_[11],22,0xfd469501,\/* 8 *\/\nFF,$a,$b,$c,$d,$_[12],7,0x698098d8,\/* 9 *\/\nFF,$d,$a,$b,$c,$_[13],12,0x8b44f7af,\/* 10 *\/\nFF,$c,$d,$a,$b,$_[14],17,0xffff5bb1,\/* 11 *\/\nFF,$b,$c,$d,$a,$_[15],22,0x895cd7be,\/* 12 *\/\nFF,$a,$b,$c,$d,$_[16],7,0x6b901122,\/* 13 *\/\nFF,$d,$a,$b,$c,$_[17],12,0xfd987193,\/* 14 *\/\nFF,$c,$d,$a,$b,$_[18],17,0xa679438e,\/* 15 *\/\nFF,$b,$c,$d,$a,$_[19],22,0x49b40821,\/* 16 *\/\nGG,$a,$b,$c,$d,$_[5],5,0xf61e2562,\/* 17 *\/\nGG,$d,$a,$b,$c,$_[10],9,0xc040b340,\/* 18 *\/\nGG,$c,$d,$a,$b,$_[15],14,0x265e5a51,\/* 19 *\/\nGG,$b,$c,$d,$a,$_[4],20,0xe9b6c7aa,\/* 20 *\/\nGG,$a,$b,$c,$d,$_[9],5,0xd62f105d,\/* 21 *\/\nGG,$d,$a,$b,$c,$_[14],9,0x2441453,\/* 22 *\/\nGG,$c,$d,$a,$b,$_[19],14,0xd8a1e681,\/* 23 *\/\nGG,$b,$c,$d,$a,$_[8],20,0xe7d3fbc8,\/* 24 *\/\nGG,$a,$b,$c,$d,$_[13],5,0x21e1cde6,\/* 25 *\/\nGG,$d,$a,$b,$c,$_[18],9,0xc33707d6,\/* 26 *\/\nGG,$c,$d,$a,$b,$_[7],14,0xf4d50d87,\/* 27 *\/\nGG,$b,$c,$d,$a,$_[12],20,0x455a14ed,\/* 28 *\/\nGG,$a,$b,$c,$d,$_[17],5,0xa9e3e905,\/* 29 *\/\nGG,$d,$a,$b,$c,$_[6],9,0xfcefa3f8,\/* 30 *\/\nGG,$c,$d,$a,$b,$_[11],14,0x676f02d9,\/* 31 *\/\nGG,$b,$c,$d,$a,$_[16],20,0x8d2a4c8a,\/* 32 *\/\nHH,$a,$b,$c,$d,$_[9],4,0xfffa3942,\/* 33 *\/\nHH,$d,$a,$b,$c,$_[12],11,0x8771f681,\/* 34 *\/\nHH,$c,$d,$a,$b,$_[15],16,0x6d9d6122,\/* 35 *\/\nHH,$b,$c,$d,$a,$_[18],23,0xfde5380c,\/* 36 *\/\nHH,$a,$b,$c,$d,$_[5],4,0xa4beea44,\/* 37 *\/\nHH,$d,$a,$b,$c,$_[8],11,0x4bdecfa9,\/* 38 *\/\nHH,$c,$d,$a,$b,$_[11],16,0xf6bb4b60,\/* 39 *\/\nHH,$b,$c,$d,$a,$_[14],23,0xbebfbc70,\/* 40 *\/\nHH,$a,$b,$c,$d,$_[17],4,0x289b7ec6,\/* 41 *\/\nHH,$d,$a,$b,$c,$_[4],11,0xeaa127fa,\/* 42 *\/\nHH,$c,$d,$a,$b,$_[7],16,0xd4ef3085,\/* 43 *\/\nHH,$b,$c,$d,$a,$_[10],23,0x4881d05,\/* 44 *\/\nHH,$a,$b,$c,$d,$_[13],4,0xd9d4d039,\/* 45 *\/\nHH,$d,$a,$b,$c,$_[16],11,0xe6db99e5,\/* 46 *\/\nHH,$c,$d,$a,$b,$_[19],16,0x1fa27cf8,\/* 47 *\/\nHH,$b,$c,$d,$a,$_[6],23,0xc4ac5665,\/* 48 *\/\nII,$a,$b,$c,$d,$_[4],6,0xf4292244,\/* 49 *\/\nII,$d,$a,$b,$c,$_[11],10,0x432aff97,\/* 50 *\/\nII,$c,$d,$a,$b,$_[18],15,0xab9423a7,\/* 51 *\/\nII,$b,$c,$d,$a,$_[9],21,0xfc93a039,\/* 52 *\/\nII,$a,$b,$c,$d,$_[16],6,0x655b59c3,\/* 53 *\/\nII,$d,$a,$b,$c,$_[7],10,0x8f0ccc92,\/* 54 *\/\nII,$c,$d,$a,$b,$_[14],15,0xffeff47d,\/* 55 *\/\nII,$b,$c,$d,$a,$_[5],21,0x85845dd1,\/* 56 *\/\nII,$a,$b,$c,$d,$_[12],6,0x6fa87e4f,\/* 57 *\/\nII,$d,$a,$b,$c,$_[19],10,0xfe2ce6e0,\/* 58 *\/\nII,$c,$d,$a,$b,$_[10],15,0xa3014314,\/* 59 *\/\nII,$b,$c,$d,$a,$_[17],21,0x4e0811a1,\/* 60 *\/\nII,$a,$b,$c,$d,$_[8],6,0xf7537e82,\/* 61 *\/\nII,$d,$a,$b,$c,$_[15],10,0xbd3af235,\/* 62 *\/\nII,$c,$d,$a,$b,$_[6],15,0x2ad7d2bb,\/* 63 *\/\nII,$b,$c,$d,$a,$_[13],21,0xeb86d391,\/* 64 *\/\n\n\n","human_summarization":"The code is an implementation of the MD5 Message Digest Algorithm, developed directly from the algorithm specification without using built-in or external hashing libraries. It produces a correct message digest for an input string but does not mimic all calling modes. The code also includes handling of bit manipulation, unsigned integers, and little-endian data, with attention to details like boundary conditions and padding. The implementation is validated against the verification strings and hashes from RFC 1321.","id":3712}
    {"lang_cluster":"Perl","source_code":"\n#!\/usr\/bin\/perl\n\nmy @even_numbers;\n\nfor (1..7)\n{\n  if ( $_ % 2 == 0)\n  {\n    push @even_numbers, $_;\n  }\n}\n\t\nprint \"Police\\tFire\\tSanitation\\n\";\n\nforeach my $police_number (@even_numbers)\n{\n  for my $fire_number (1..7)\n  {\n    for my $sanitation_number (1..7)\n    {\n      if ( $police_number + $fire_number + $sanitation_number == 12 && \n           $police_number != $fire_number && \n           $fire_number != $sanitation_number && \n           $sanitation_number != $police_number)\n      {\n        print \"$police_number\\t$fire_number\\t$sanitation_number\\n\";\n      }\n    }\n  }\t\n}\n\n\n#!\/usr\/bin\/perl\n\nuse strict;   # Not necessary but considered good perl style\nuse warnings; # this one too\n\nprint \"Police\\t-\\tFire\\t-\\tSanitation\\n\";\nfor my $p ( 1..7 )  # Police Department\n{\n  for my $f ( 1..7) # Fire Department\n  {\n    for my $s ( 1..7 ) # Sanitation Department\n    {\n      if ( $p % 2 == 0 && $p + $f + $s == 12 && $p != $f && $f != $s  && $s != $p && $f != $s) # Check if the combination of numbers is valid\n      {\n        print \"$p\\t-\\t$f\\t-\\t$s\\n\";\n      }\n    }\n  }\n}\n\n\nPolice  -       Fire    -       Sanitation\n2       -       3       -       7\n2       -       4       -       6\n2       -       6       -       4\n2       -       7       -       3\n4       -       1       -       7\n4       -       2       -       6\n4       -       3       -       5\n4       -       5       -       3\n4       -       6       -       2\n4       -       7       -       1\n6       -       1       -       5\n6       -       2       -       4\n6       -       4       -       2\n6       -       5       -       1\n\n#!\/usr\/bin\/perl\n\nuse strict; # https:\/\/rosettacode.org\/wiki\/Department_numbers\nuse warnings;\n\nprint \"P S F\\n\\n\";\n\n'246 1234567 1234567' =~\n  \/(.).* \\s .*?(?!\\1)(.).* \\s .*(?!\\1)(?!\\2)(.)\n  (??{$1+$2+$3!=12})\n  (?{ print \"@{^CAPTURE}\\n\" })(*FAIL)\/x;\n\n\n","human_summarization":"generate all valid combinations of numbers between 1 and 7 (inclusive) for three departments (police, sanitation, fire) in a city. The numbers must be unique, add up to 12, and the police department number must be even.","id":3713}
    {"lang_cluster":"Perl","source_code":"\n\nmy $original = 'Hello.';\nmy $new = $original;\n$new = 'Goodbye.';\nprint \"$original\\n\";   # prints \"Hello.\"\n\n\nmy $original = 'Hello.';\nmy $ref = \\$original;\n$$ref = 'Goodbye.';\nprint \"$original\\n\";   # prints \"Goodbye.\"\n\n\nmy $original = 'Hello.';\nour $alias;\nlocal *alias = \\$original;\n$alias = 'Good evening.';\nprint \"$original\\n\";   # prints \"Good evening.\"\n\nuse Lexical::Alias;\nmy $original = 'Hello.';\nmy $alias;\nalias $alias, $original;\n$alias = 'Good evening.';\nprint \"$original\\n\";   # prints \"Good evening.\"\n","human_summarization":"demonstrate how to copy a string, create a reference to an existing string, assign a new name to the same string, and make a lexical variable as an alias of another variable using the Lexical::Alias module in Perl. It also highlights the dynamic binding of local variables and the potential modifications by subroutines within the same scope.","id":3714}
    {"lang_cluster":"Perl","source_code":"\nsub F { my $n = shift; $n ? $n - M(F($n-1)) : 1 }\nsub M { my $n = shift; $n ? $n - F(M($n-1)) : 0 }\n\n# Usage:\nforeach my $sequence (\\&F, \\&M) {\n    print join(' ', map $sequence->($_), 0 .. 19), \"\\n\";\n}\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":3715}
    {"lang_cluster":"Perl","source_code":"\nmy @array = qw(a b c);\nprint $array[ rand @array ];\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":3716}
    {"lang_cluster":"Perl","source_code":"\nsub urldecode {\n    my $s = shift;\n    $s =~ tr\/\\+\/ \/;\n    $s =~ s\/\\%([A-Fa-f0-9]{2})\/pack('C', hex($1))\/eg;\n    return $s;\n}\n\nprint urldecode('http%3A%2F%2Ffoo+bar%2F').\"\\n\";\n\n#!\/usr\/bin\/perl -w\nuse strict ;\nuse URI::Escape ;\n\nmy $encoded = \"http%3A%2F%2Ffoo%20bar%2F\" ;\nmy $unencoded = uri_unescape( $encoded ) ;\nprint \"The unencoded string is $unencoded\u00a0!\\n\" ;\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":3717}
    {"lang_cluster":"Perl","source_code":"\n\nsub binary_search {\n    my ($array_ref, $value, $left, $right) = @_;\n    while ($left <= $right) {\n        my $middle = int(($right + $left) >> 1);\n        if ($value == $array_ref->[$middle]) {\n            return $middle;\n        }\n        elsif ($value < $array_ref->[$middle]) {\n            $right = $middle - 1;\n        }\n        else {\n            $left = $middle + 1;\n        }\n    }\n    return -1;\n}\n\nsub binary_search {\n    my ($array_ref, $value, $left, $right) = @_;\n    return -1 if ($right < $left);\n    my $middle = int(($right + $left) >> 1);\n    if ($value == $array_ref->[$middle]) {\n        return $middle;\n    }\n    elsif ($value < $array_ref->[$middle]) {\n        binary_search($array_ref, $value, $left, $middle - 1);\n    }\n    else {\n        binary_search($array_ref, $value, $middle + 1, $right);\n    }\n}\n","human_summarization":"The code implements a binary search algorithm to find a specific number in a sorted integer array. It includes both recursive and iterative versions of the algorithm. The binary search algorithm divides the range of values into halves and continues to narrow down the search field until the target value is found. The code also handles cases of multiple equal values and returns the index of the target value if found. Additionally, it provides the leftmost and rightmost insertion points for the target value. The code also includes a fix for potential overflow bugs.","id":3718}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.x\n\nmy @params = @ARGV;\nmy $params_size = @ARGV; \nmy $second = $ARGV[1];\nmy $fifth = $ARGV[4];\n\n\nuse Getopt::Long;\nGetOptions ( \n    'help|h'     => \\my $help,\n    'verbose|v'  => \\my $verbose,\n);\n\n","human_summarization":"\"Code retrieves and prints the list of command-line arguments given to the program. It uses @ARGV array to store all command-line parameters. Also, it provides an option to import a module if needed. Example command line usage is 'myprogram -c \"alpha beta\" -h \"gamma\"'. For intelligent parsing of these arguments, refer to 'Parsing command-line arguments'.\"","id":3719}
    {"lang_cluster":"Perl","source_code":"\nLibrary: Perl\/Tk\nuse strict;\nuse warnings;\nuse Tk; \nuse Math::Trig qw\/:pi\/;\n\nmy $root =  new MainWindow( -title => 'Pendulum Animation' );\nmy $canvas = $root->Canvas(-width => 320, -height => 200);\nmy $after_id;\n\nfor ($canvas) {\n\t$_->createLine(   0,  25, 320,  25, -tags => [qw\/plate\/], -width => 2, -fill => 'grey50' );\n\t$_->createOval( 155,  20, 165,  30, -tags => [qw\/pivot outline\/], -fill => 'grey50' );\n\t$_->createLine(   1,   1,    1,  1, -tags => [qw\/rod width\/], -width => 3, -fill => 'black' );\n\t$_->createOval(   1,   1,    2,  2, -tags => [qw\/bob outline\/], -fill => 'yellow' );\n}\n\n$canvas->raise('pivot');\n$canvas->pack(-fill => 'both', -expand => 1);\nmy ($Theta, $dTheta, $length, $homeX, $homeY) =\n\t(45, 0, 150, 160, 25);\n\nsub show_pendulum {\n  my $angle = $Theta * pi() \/ 180;\n  my $x = $homeX + $length * sin($angle);\n  my $y = $homeY + $length * cos($angle);\n  $canvas->coords('rod', $homeX, $homeY, $x, $y);\n  $canvas->coords('bob', $x-15, $y-15, $x+15, $y+15);\n}\n\n\n \nsub recompute_angle {\n  my $scaling = 3000.0 \/ ($length ** 2);\n  # first estimate\n  my $firstDDTheta = -sin($Theta * pi \/ 180) * $scaling;\n  my $midDTheta = $dTheta + $firstDDTheta;\n  my $midTheta = $Theta + ($dTheta + $midDTheta)\/2;\n  # second estimate\n  my $midDDTheta = -sin($midTheta * pi\/ 180) * $scaling;\n  $midDTheta = $dTheta + ($firstDDTheta + $midDDTheta)\/2;\n  $midTheta = $Theta + ($dTheta + $midDTheta)\/2;\n  # again, first\n  $midDDTheta = -sin($midTheta * pi\/ 180) * $scaling;\n  my $lastDTheta = $midDTheta + $midDDTheta;\n  my $lastTheta = $midTheta + ($midDTheta + $lastDTheta)\/2;\n  # again, second\n  my $lastDDTheta = -sin($lastTheta * pi\/180) * $scaling;\n  $lastDTheta = $midDTheta + ($midDDTheta + $lastDDTheta)\/2;\n  $lastTheta = $midTheta + ($midDTheta + $lastDTheta)\/2;\n  # Now put the values back in our globals\n  $dTheta  = $lastDTheta;\n  $Theta = $lastTheta;\n}\n \n\nsub animate {\n  recompute_angle;\n  show_pendulum;\n  $after_id = $root->after(15 => sub {animate() });\n}\n\nshow_pendulum;\n$after_id = $root->after(500 => sub {animate});\n \n$canvas->bind('<Destroy>' => sub {$after_id->cancel});\nMainLoop;\n\n","human_summarization":"simulate and animate a simple gravity pendulum model, without window resizing handling functionality.","id":3720}
    {"lang_cluster":"Perl","source_code":"\nLibrary: JSON\nuse JSON;\n\nmy $data = decode_json('{ \"foo\": 1, \"bar\": [10, \"apples\"] }');\n\nmy $sample = { blue => [1,2], ocean => \"water\" };\nmy $json_string = encode_json($sample);\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":3721}
    {"lang_cluster":"Perl","source_code":"use strict;\n\nsub nthroot ($$)\n{\n    my ( $n, $A ) = @_;\n\n    my $x0 = $A \/ $n;\n    my $m = $n - 1.0;\n    while(1) {\n\tmy $x1 = ($m * $x0 + $A \/ ($x0 ** $m)) \/ $n;\n\treturn $x1 if abs($x1 - $x0) < abs($x0 * 1e-9);\n\t$x0 = $x1;\n    }\n}\n\nprint nthroot(5, 34), \"\\n\";\nprint nthroot(10, 7131.5 ** 10), \"\\n\";\nprint nthroot(0.5, 7), \"\\n\";\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":3722}
    {"lang_cluster":"Perl","source_code":"\nWorks with: Perl version 5.8.6\nLibrary: Sys::HostnameHostname\nuse Sys::Hostname;\n\n$name = hostname;\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":3723}
    {"lang_cluster":"Perl","source_code":"\nno warnings 'experimental::signatures';\nuse feature 'signatures';\n\nsub leonardo ($n, $l0 = 1, $l1 = 1, $add = 1) {\n  ($l0, $l1) = ($l1, $l0+$l1+$add)  for 1..$n;\n  $l0;\n}\n\nmy @L = map { leonardo($_) } 0..24;\nprint \"Leonardo[1,1,1]: @L\\n\";\nmy @F = map { leonardo($_,0,1,0) } 0..24;\nprint \"Leonardo[0,1,0]: @F\\n\";\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":3724}
    {"lang_cluster":"Perl","source_code":"\n#!\/usr\/bin\/env perl\nuse warnings;\nuse strict;\nuse feature 'say';\n\nprint <<'EOF';\nThe 24 Game\n\nGiven any four digits in the range 1 to 9, which may have repetitions,\nUsing just the +, -, *, and \/ operators; and the possible use of\nparentheses, (), show how to make an answer of 24.\n\nAn answer of \"q\" or EOF will quit the game.\nA blank answer will generate a new set of four digits.\nOtherwise you are repeatedly asked for an expression until it evaluates to 24.\n\nNote: you cannot form multiple digit numbers from the supplied digits,\nso an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\nEOF\n\nmy $try = 1;\nwhile (1) {\n  my @digits = map { 1+int(rand(9)) } 1..4;\n  say \"\\nYour four digits: \", join(\" \", @digits);\n  print \"Expression (try \", $try++, \"): \";\n\n  my $entry = <>;\n  if (!defined $entry || $entry eq 'q') \n    { say \"Goodbye.  Sorry you couldn't win.\"; last; }\n  $entry =~ s\/\\s+\/\/g;  # remove all white space\n  next if $entry eq '';\n\n  my $given_digits = join \"\", sort @digits;\n  my $entry_digits = join \"\", sort grep { \/\\d\/ } split(\/\/, $entry);\n  if ($given_digits ne $entry_digits ||  # not correct digits\n      $entry =~ \/\\d\\d\/ ||                # combined digits\n      $entry =~ m|[-+*\/]{2}| ||          # combined operators\n      $entry =~ tr|-0-9()+*\/||c)         # Invalid characters\n    { say \"That's not valid\";  next; }\n\n  my $n = eval $entry;\n\n  if    (!defined $n) { say \"Invalid expression\"; }\n  elsif ($n == 24)    { say \"You win!\"; last; }\n  else                { say \"Sorry, your expression is $n, not 24\"; }\n}\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":3725}
    {"lang_cluster":"Perl","source_code":"\n\nsub encode {\n    shift =~ s\/(.)\\1*\/length($&).$1\/grse;\n}\n\nsub decode {\n    shift =~ s\/(\\d+)(.)\/$2 x $1\/grse;\n}\n\n\nsub encode {\n    shift =~ s\/(.)\\1{0,254}\/pack(\"C\", length($&)).$1\/grse;\n}\n\nsub decode {\n    shift =~ s\/(.)(.)\/$2 x unpack(\"C\", $1)\/grse;\n}\n\n\nsub encode {\n    my $str = shift;\n    my $ret = \"\";\n    my $nonrep = \"\";\n    while ($str =~ m\/(.)\\1{0,127}|\\z\/gs) {\n        my $len = length($&);\n        if (length($nonrep) && (length($nonrep) == 127 || $len != 1)) {\n            $ret .= pack(\"C\", 128 + length($nonrep)) . $nonrep;\n            $nonrep = \"\";\n        }\n        if    ($len == 1) { $nonrep .= $1 }\n        elsif ($len > 1)  { $ret .= pack(\"C\", $len) . $1 }\n    }\n    return $ret;\n}\n\nsub decode {\n    my $str = shift;\n    my $ret = \"\";\n    for (my $i = 0; $i < length($str);) {\n        my $len = unpack(\"C\", substr($str, $i, 1));\n        if ($len <= 128) {\n            $ret .= substr($str, $i + 1, 1) x $len;\n            $i += 2;\n        }\n        else {\n            $ret .= substr($str, $i + 1, $len - 128);\n            $i += 1 + $len - 128;\n        }\n    }\n    return $ret;\n}\n\n\nuse Data::Dump qw(dd);\ndd my $str = \"XXXXXABCDEFGHIoooooooooooooooooooooooooAAAAAA\";\ndd my $enc = encode($str);\ndd decode($enc);\n\n\n","human_summarization":"implement a run-length encoding and decoding system. The codes compress repeated runs of the same uppercase character in a string by storing the length of the run. It also provides a function to reverse the compression. The codes can handle arbitrary byte strings as input and support compact representation of longer non-repeating substrings.","id":3726}
    {"lang_cluster":"Perl","source_code":"\nmy $s = 'hello';\nprint $s . ' literal', \"\\n\";\nmy $s1 = $s . ' literal';\nprint $s1, \"\\n\";\n\n\n$s .= ' literal';\nprint $s, \"\\n\";\n\n","human_summarization":"Create a string variable, concatenate it with another string, and display the result.","id":3727}
    {"lang_cluster":"Perl","source_code":"\nsub urlencode {\n    my $s = shift;\n    $s =~ s\/([^-A-Za-z0-9_.!~*'() ])\/sprintf(\"%%%02X\", ord($1))\/eg;\n    $s =~ tr\/ \/+\/;\n    return $s;\n}\n\nprint urlencode('http:\/\/foo bar\/').\"\\n\";\n\n\n","human_summarization":"The code provides a function to convert a given string into URL encoding format. It converts special, control, and extended characters into a percent symbol followed by a two-digit hexadecimal code. Characters other than 0-9, A-Z, and a-z are converted. The function also supports variations like lowercase escapes and different encodings for special characters according to different standards like RFC 3986, HTML 5, and encodeURI function in Javascript. An optional feature allows the use of an exception string containing symbols that don't need conversion.","id":3728}
    {"lang_cluster":"Perl","source_code":"\n@c{@$_}++ for [5,1,3,8,9,4,8,7], [3,5,9,8,4], [1,3,7,9];\nprint join ' ', sort keys %c;\n@c{@$_}++ for [qw<not all is integer\u00a0? is not\u00a0! 4.2>];\nprint join ' ', sort keys %c;\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":3729}
    {"lang_cluster":"Perl","source_code":"\nmy @items = sort { $b->[2]\/$b->[1] <=> $a->[2]\/$a->[1] }\n(\n        [qw'beef    3.8 36'],\n        [qw'pork    5.4 43'],\n        [qw'ham     3.6 90'],\n        [qw'greaves 2.4 45'],\n        [qw'flitch  4.0 30'],\n        [qw'brawn   2.5 56'],\n        [qw'welt    3.7 67'],\n        [qw'salami  3.0 95'],\n        [qw'sausage 5.9 98'],\n);\n\nmy ($limit, $value) = (15, 0);\n\nprint \"item   fraction weight value\\n\";\nfor (@items) {\n        my $ratio = $_->[1] > $limit ? $limit\/$_->[1] : 1;\n        print \"$_->[0]\\t\";\n        $value += $_->[2] * $ratio;\n        $limit -= $_->[1];\n        if ($ratio == 1) {\n                print \"  all\\t$_->[1]\\t$_->[2]\\n\";\n        } else {\n                printf \"%5.3f   %s   %8.3f\\n\", $ratio, $_->[1] * $ratio, $_->[2] * $ratio;\n                last;\n        }\n}\n\nprint \"-\" x 40, \"\\ntotal value: $value\\n\";\n\n","human_summarization":"determine the optimal combination of items a thief can steal from a butcher's shop without exceeding a total weight of 15 kg in his knapsack, with the possibility of cutting items proportionally to their original price, in order to maximize the total value.","id":3730}
    {"lang_cluster":"Perl","source_code":"\nuse List::Util 'max';\n\nmy @words = split \"\\n\", do { local( @ARGV, $\/ ) = ( 'unixdict.txt' ); <> };\nmy %anagram;\nfor my $word (@words) {\n    push @{ $anagram{join '', sort split '', $word} }, $word;\n}\n\nmy $count = max(map {scalar @$_} values %anagram);\nfor my $ana (values %anagram) {\n    print \"@$ana\\n\" if @$ana == $count;\n}\n\n\npush @{$anagram{ join '' => sort split '' }}, $_ for @words;\n$max > @$_  or  $max = @$_    for values %anagram;\n@$_ == $max and print \"@$_\\n\" for values %anagram;\n\n\n","human_summarization":"find the sets of words from the provided URL that are anagrams of each other, i.e., composed of the same characters but in a different order. The code specifically identifies the sets with the most words in them. The calculation of $max eliminates the need for the CPAN module.","id":3731}
    {"lang_cluster":"Perl","source_code":"\nmy @c = '##'; \n@c = (map($_ x 3, @c), map($_.(' ' x length).$_, @c), map($_ x 3, @c)) \n        for 1 .. 3;\nprint join(\"\\n\", @c), \"\\n\";\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":3732}
    {"lang_cluster":"Perl","source_code":"\nuse 5.10.0;\nuse strict;\n\n# produce encode and decode dictionary from a tree\nsub walk {\n\tmy ($node, $code, $h, $rev_h) = @_;\n\n\tmy $c = $node->[0];\n\tif (ref $c) { walk($c->[$_], $code.$_, $h, $rev_h) for 0,1 }\n\telse        { $h->{$c} = $code; $rev_h->{$code} = $c }\n\n\t$h, $rev_h\n}\n\n# make a tree, and return resulting dictionaries\nsub mktree {\n\tmy (%freq, @nodes);\n\t$freq{$_}++ for split '', shift;\n\t@nodes = map([$_, $freq{$_}], keys %freq);\n\n\tdo {\t# poor man's priority queue\n\t\t@nodes = sort {$a->[1] <=> $b->[1]} @nodes;\n\t\tmy ($x, $y) = splice @nodes, 0, 2;\n\t\tpush @nodes, [[$x, $y], $x->[1] + $y->[1]]\n\t} while (@nodes > 1);\n\n\twalk($nodes[0], '', {}, {})\n}\n\nsub encode {\n\tmy ($str, $dict) = @_;\n\tjoin '', map $dict->{$_}\/\/die(\"bad char $_\"), split '', $str\n}\n\nsub decode {\n\tmy ($str, $dict) = @_;\n\tmy ($seg, @out) = (\"\");\n\n\t# append to current segment until it's in the dictionary\n\tfor (split '', $str) {\n\t\t$seg .= $_;\n\t\tmy $x = $dict->{$seg} \/\/ next;\n\t\tpush @out, $x;\n\t\t$seg = '';\n\t}\n\tdie \"bad code\" if length($seg);\n\tjoin '', @out\n}\n\nmy $txt = 'this is an example for huffman encoding';\nmy ($h, $rev_h) = mktree($txt);\nfor (keys %$h) { print \"'$_': $h->{$_}\\n\" }\n\nmy $enc = encode($txt, $h);\nprint \"$enc\\n\";\n\nprint decode($enc, $rev_h), \"\\n\";\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":3733}
    {"lang_cluster":"Perl","source_code":"\nuse Tk;\n\n$main = MainWindow->new;\n$l = $main->Label('-text' => 'There have been no clicks yet.')->pack;\n$count = 0;\n$main->Button(\n  -text => ' Click Me ',\n  -command => sub { $l->configure(-text => 'Number of clicks: '.(++$count).'.'); },\n)->pack;\nMainLoop();\n\nuse Gtk '-init';\n\n# Window.\n$window = Gtk::Window->new;\n$window->signal_connect('destroy' => sub { Gtk->main_quit; });\n\n# VBox.\n$vbox = Gtk::VBox->new(0, 0);\n$window->add($vbox);\n\n# Label.\n$label = Gtk::Label->new('There have been no clicks yet.');\n$vbox->add($label);\n\n# Button.\n$count = 0;\n$button = Gtk::Button->new(' Click Me ');\n$vbox->add($button);\n$button->signal_connect('clicked', sub {\n  $label->set_text(++$count);\n});\n\n# Show.\n$window->show_all;\n\n# Main loop.\nGtk->main;\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":3734}
    {"lang_cluster":"Perl","source_code":"\nuse DBI;\n\nmy $db = DBI->connect('DBI:mysql:database:server','login','password');\n\nmy $statment = <<EOF;\nCREATE TABLE `Address` (\n    `addrID`       int(11)     NOT NULL   auto_increment,\n    `addrStreet`   varchar(50) NOT NULL   default '',\n    `addrCity`     varchar(25) NOT NULL   default '',\n    `addrState`    char(2)     NOT NULL   default '',\n    `addrZIP`      char(10)    NOT NULL   default '',\n    PRIMARY KEY (`addrID`)\n);\nEOF\n\nmy $exec = $db->prepare($statment);\n$exec->execute;\n\n\n","human_summarization":"\"Creates a table in a chosen database to store US postal addresses, including fields for unique identifier, street address, city, state code, and zipcode. Also demonstrates how to open a database connection in non-database languages.\"","id":3735}
    {"lang_cluster":"Perl","source_code":"\nforeach (reverse 0..10) {\n  print \"$_\\n\";\n}\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":3736}
    {"lang_cluster":"Perl","source_code":"\nif( @ARGV != 3 ){\n  printHelp();\n}\n\n  # translate to upper-case, remove anything else\nmap( (tr\/a-z\/A-Z\/, s\/[^A-Z]\/\/g), @ARGV );\n\nmy $cipher_decipher = $ARGV[ 0 ];\n\nif( $cipher_decipher !~ \/ENC|DEC\/ ){\n  printHelp();  # user should say what to do\n}\n\nprint \"Key: \" . (my $key = $ARGV[ 2 ]) . \"\\n\";\n\nif( $cipher_decipher =~ \/ENC\/ ){\n  print \"Plain-text: \" . (my $plain = $ARGV[ 1 ]) . \"\\n\";\n  print \"Encrypted: \" . Vigenere( 1, $key, $plain ) . \"\\n\";\n}elsif( $cipher_decipher =~ \/DEC\/ ){\n  print \"Cipher-text: \" . (my $cipher = $ARGV[ 1 ]) . \"\\n\";\n  print \"Decrypted: \" . Vigenere( -1, $key, $cipher ) . \"\\n\";\n}\n\nsub printHelp{\n  print \"Usage:\\n\" .\n        \"Encrypting:\\n perl cipher.pl ENC (plain text) (key)\\n\" .\n        \"Decrypting:\\n perl cipher.pl DEC (cipher text) (key)\\n\";\n  exit -1;\n}\n\nsub Vigenere{\n  my ($direction, $key, $text) = @_;\n  for( my $count = 0; $count < length $text; $count ++ ){\n    $key_offset = $direction * ord substr( $key, $count % length $key, 1);\n    $char_offset = ord substr( $text, $count, 1 );\n    $cipher .= chr 65 + ((($char_offset % 26) + ($key_offset % 26)) % 26);\n      # 65 is the ASCII character code for 'A'\n  }\n  return $cipher;\n}\n\n\n$ perl cipher.pl ENC 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!' VIGENERECIPHER\nKey: VIGENERECIPHER\nPlain-text: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\nEncrypted: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\n\n$ perl cipher.pl DEC WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY VIGENERECIPHER\nKey: VIGENERECIPHER\nCipher-text: WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\nDecrypted: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\n\n$ perl cipher.pl FOO WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY VIGENERECIPHER\nUsage:\nEncrypting:\n perl cipher.pl ENC (plain text) (key)\nDecrypting:\n perl cipher.pl DEC (cipher text) (key)\n","human_summarization":"Implement and demonstrate a Vigen\u00e8re cipher for both encryption and decryption. The code handles keys and text of unequal length, capitalizes all characters, and discards non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted in the code.","id":3737}
    {"lang_cluster":"Perl","source_code":"\nfor($i=2; $i <= 8; $i += 2) {\n  print \"$i, \";\n}\nprint \"who do we appreciate?\\n\";\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":3738}
    {"lang_cluster":"Perl","source_code":"\nmy $i;\nsub sum {\n    my ($i, $lo, $hi, $term) = @_; \n    my $temp = 0;\n    for ($$i = $lo; $$i <= $hi; $$i++) {\n        $temp += $term->();\n    }\n    return $temp;\n}\n\nprint sum(\\$i, 1, 100, sub { 1 \/ $i }), \"\\n\";\n\n\nmy $i;\nsub sum {\n    my (undef, $lo, $hi, $term) = @_; \n    my $temp = 0;\n    for ($_[0] = $lo; $_[0] <= $hi; $_[0]++) {\n        $temp += $term->();\n    }\n    return $temp;\n}\n\nprint sum($i, 1, 100, sub { 1 \/ $i }), \"\\n\";\n\n\n","human_summarization":"\"Implement Jensen's Device, a programming technique that exploits call by name for parameter passing. The program computes the 100th harmonic number using a summation function, which takes in a bound variable and an expression, both passed by name. The result is dependent on the re-evaluation of the expression in the caller's context each time the parameter's value is required. The output is 5.18737751763962.\"","id":3739}
    {"lang_cluster":"Perl","source_code":"\nuse GD;\n\nmy $img = GD::Image->new(256, 256, 1);\n\nfor my $y (0..255) {\n        for my $x (0..255) {\n                my $color = $img->colorAllocate( abs(255 - $x - $y),  (255-$x) ^ $y , $x ^ (255-$y));\n                $img->setPixel($x, $y, $color);\n        }\n}\n\nprint $img->png\n\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":3740}
    {"lang_cluster":"Perl","source_code":"\nuse List::Util 'max';\n\nmy ($w, $h) = @ARGV;\n$w ||= 26;\n$h ||= 127;\nmy $avail = $w * $h;\n\n# cell is padded by sentinel col and row, so I don't check array bounds\nmy @cell = (map([(('1') x $w), 0], 1 .. $h), [('') x ($w + 1)]);\nmy @ver = map([(\"|  \") x $w], 1 .. $h);\nmy @hor = map([(\"+--\") x $w], 0 .. $h);\n\nsub walk {\n\tmy ($x, $y) = @_;\n\t$cell[$y][$x] = '';\n\t$avail-- or return;\t# no more bottles, er, cells\n\n\tmy @d = ([-1, 0], [0, 1], [1, 0], [0, -1]);\n\twhile (@d) {\n\t\tmy $i = splice @d, int(rand @d), 1;\n\t\tmy ($x1, $y1) = ($x + $i->[0], $y + $i->[1]);\n\n\t\t$cell[$y1][$x1] or next;\n\n\t\tif ($x == $x1) { $hor[ max($y1, $y) ][$x] = '+  ' }\n\t\tif ($y == $y1) { $ver[$y][ max($x1, $x) ] = '   ' }\n\t\twalk($x1, $y1);\n\t}\n}\n\nwalk(int rand $w, int rand $h);\t# generate\n\nfor (0 .. $h) {\t\t\t# display\n\tprint @{$hor[$_]}, \"+\\n\";\n\tprint @{$ver[$_]}, \"|\\n\" if $_ < $h;\n}\n\n\n\nSample 4 x 1 output:\n+--+--+--+--+\n|           |\n+--+--+--+--+\n","human_summarization":"generate a maze using the Depth-first search algorithm. It starts at a random cell, marks it as visited, and gets a list of its neighbors. For each neighbor, it checks if it's visited, removes the wall between the current cell and the neighbor if not, and then recurses with the neighbor as the current cell. The maze can be run with custom width and height or use default dimensions.","id":3741}
    {"lang_cluster":"Perl","source_code":"\n\n\nsub pistream {\n  my $digits = shift;\n  my(@out, @a);\n  my($b, $c, $d, $e, $f, $g, $i, $d4, $d3, $d2, $d1);\n  my $outi = 0;\n\n  $digits++;\n  $b = $d = $e = $g = $i = 0;\n  $f = 10000;\n  $c = 14 * (int($digits\/4)+2);\n  @a = (20000000) x $c;\n  print \"3.\";\n  while (($b = $c -= 14) > 0 && $i < $digits) {\n    $d = $e = $d % $f;\n    while (--$b > 0) {\n      $d = $d * $b + $a[$b];\n      $g = ($b << 1) - 1;\n      $a[$b] = ($d % $g) * $f;\n      $d = int($d \/ $g);\n    }\n    $d4 = $e + int($d\/$f);\n    if ($d4 > 9999) {\n      $d4 -= 10000;\n      $out[$i-1]++;\n      for ($b = $i-1; $out[$b] == 1; $b--) {\n        $out[$b] = 0;\n        $out[$b-1]++;\n      }\n    }\n    $d3 = int($d4\/10);\n    $d2 = int($d3\/10);\n    $d1 = int($d2\/10);\n    $out[$i++] = $d1;\n    $out[$i++] = $d2-$d1*10;\n    $out[$i++] = $d3-$d2*10;\n    $out[$i++] = $d4-$d3*10;\n    print join \"\", @out[$i-15 .. $i-15+3]  if $i >= 16;\n  }\n  # We've closed the spigot.  Print the remainder without rounding.\n  print join \"\", @out[$i-15+4 .. $digits-2], \"\\n\";\n}\n\nuse bigint try=>\"GMP\";\nsub stream { \n    my ($next, $safe, $prod, $cons, $z, $x) = @_;\n    $x = $x->();\n    sub {\n        while (1) {\n            my $y = $next->($z);\n            if ($safe->($z, $y)) {\n                $z = $prod->($z, $y);\n                return $y;\n            } else {\n                $z = $cons->($z, $x->());\n            }\n        }\n    }\n}\n \nsub extr {\n    use integer;\n    my ($q, $r, $s, $t) = @{shift()};\n    my $x = shift;\n    ($q * $x + $r) \/ ($s * $x + $t);\n}\n \nsub comp {\n    my ($q, $r, $s, $t) = @{shift()};\n    my ($u, $v, $w, $x) = @{shift()};\n    [$q * $u + $r * $w,\n     $q * $v + $r * $x,\n     $s * $u + $t * $w,\n     $s * $v + $t * $x];\n}\n \nmy $pi_stream = stream\n    sub { extr shift, 3 },\n    sub { my ($z, $n) = @_; $n == extr $z, 4 },\n    sub { my ($z, $n) = @_; comp([10, -10*$n, 0, 1], $z) },\n    \\&comp,\n    [1, 0, 0, 1],\n    sub { my $n = 0; sub { $n++; [$n, 4 * $n + 2, 0, 2 * $n + 1] } },\n;\n$|++;\nprint $pi_stream->(), '.';\nprint $pi_stream->() while 1;\n\n\nuse bigint try=>\"GMP\";\n\n# Pi\/4 = 4 arctan 1\/5 - arctan 1\/239\n# expanding it with Taylor series with what's probably the dumbest method\n\nmy ($ds, $ns) = (1, 0);\nmy ($n5, $d5) = (16 * (25 * 3 - 1), 3 * 5**3);\nmy ($n2, $d2) = (4 * (239 * 239 * 3 - 1), 3 * 239**3);\n\nsub next_term {\n\tmy ($coef, $p) = @_[1, 2];\n\t$_[0] \/= ($p - 4) * ($p - 2);\n\t$_[0] *= $p * ($p + 2) * $coef**4;\n}\n\nmy $p2 = 5;\nmy $pow = 1;\n\n$| = 1;\nfor (my $x = 5; ; $x += 4) {\n\t($ns, $ds) = ($ns * $d5 + $n5 * $pow * $ds, $ds * $d5);\n\n\tnext_term($d5, 5, $x);\n\t$n5 = 16 * (5 * 5 * ($x + 2) - $x);\n\n\twhile ($d5 > $d2) {\n\t\t($ns, $ds) = ($ns * $d2 - $n2 * $pow * $ds, $ds * $d2);\n\t\t$n2 = 4 * (239 * 239 * ($p2 + 2) - $p2);\n\t\tnext_term($d2, 239, $p2);\n\t\t$p2 += 4;\n\t}\n\n\tmy $ppow = 1;\n\twhile ($pow * $n5 * 5**4 < $d5 && $pow * $n2 * $n2 * 239**4 < $d2) {\n\t\t$pow *= 10;\n\t\t$ppow *= 10;\n\t}\n\n\tif ($ppow > 1) {\n\t\t$ns *= $ppow;\n\t#FIX?\tmy $out = $ns->bdiv($ds);   # bugged?\n\t\tmy $out = $ns \/ $ds;\n\t\t$ns %= $ds;\n\n\t\t$out = (\"0\" x (length($ppow) - length($out) - 1)) . $out;\n\t\tprint $out;\n\t}\n\n\tif ( $p2 % 20 == 1) {\n\t\tmy $g = Math::BigInt::bgcd($ds, $ns);\n\t\t$ds \/= $g;\n\t\t$ns \/= $g;\n\t}\n}\n\n\nLibrary: ntheory\nuse ntheory qw\/Pi\/;\nsay Pi(10000);\n\nuse Math::Pari qw\/setprecision Pi\/;\nsetprecision(10000);\nsay Pi;\n\nuse Math::MPFR;\nmy $pi = Math::MPFR->new();\nMath::MPFR::Rmpfr_set_prec($pi, int(10000 * 3.322)+40);\nMath::MPFR::Rmpfr_const_pi($pi, 0);\nsay Math::MPFR::Rmpfr_get_str($pi, 10, 10000, 0);\n\nuse Math::BigFloat try=>\"GMP\";    # Slow without Math::BigInt::GMP installed\nsay Math::BigFloat::bpi(10000);   # For over ~2k digits, slower than AGM\n\nuse Math::Big qw\/pi\/;    # Very slow\nsay pi(10000);\n\n","human_summarization":"The code continuously calculates and outputs the next decimal digit of Pi, starting from 3.14159265. The program runs indefinitely until manually stopped by the user. It uses various methods and libraries like Math::BigInt::GMP, Raku spigot, and Machin's formula for the calculation. The performance can be significantly improved by using Math::GMP instead of bigint. It doesn't require any modules or bigints. The code also accepts a number-of-digits argument to specify the precision of the calculation.","id":3742}
    {"lang_cluster":"Perl","source_code":"\nuse strict;\nuse warnings;\n\nsub orderlists {\n    my ($firstlist, $secondlist) = @_;\n\n    my ($first, $second);\n    while (@{$firstlist}) {\n        $first = shift @{$firstlist};\n        if (@{$secondlist}) {\n            $second = shift @{$secondlist};\n            if ($first < $second) {\n                return 1;\n            }\n            if ($first > $second) {\n                return 0;\n            }\n        }\n        else {\n            return 0;\n        }\n    }\n\n    @{$secondlist} ? 1 : 0;\n}\n\nforeach my $pair (\n    [[1, 2, 4], [1, 2, 4]],\n    [[1, 2, 4], [1, 2,  ]],\n    [[1, 2,  ], [1, 2, 4]],\n    [[55,53,1], [55,62,83]],\n    [[20,40,51],[20,17,78,34]],\n) {\n    my $first  = $pair->[0];\n    my $second = $pair->[1];\n    my $before = orderlists([@$first], [@$second]) ? 'true' : 'false';\n    print \"(@$first) comes before (@$second)\u00a0: $before\\n\";\n}\n\n\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise.\"","id":3743}
    {"lang_cluster":"Perl","source_code":"\n\n{\n    my @memo;\n    sub A {\n        my( $m, $n ) = @_;\n        $memo[ $m ][ $n ] and return $memo[ $m ][ $n ];\n        $m or return $n + 1;\n        return $memo[ $m ][ $n ] = (\n            $n\n              \u00a0? A( $m - 1, A( $m, $n - 1 ) )\n              \u00a0: A( $m - 1, 1 )\n        );\n    }\n}\n\nsub A {\n    my ($m, $n) = @_;\n    if    ($m == 0) { $n + 1 }\n    elsif ($n == 0) { A($m - 1, 1) }\n    else            { A($m - 1, A($m, $n - 1)) }\n}\n\nsub A {\n  my ($m, $n) = @_;\n  $m == 0\u00a0? $n + 1\u00a0:\n  $n == 0\u00a0? A($m - 1, 1)\u00a0:\n            A($m - 1, A($m, $n - 1))\n}\n\nuse Memoize;  memoize('ack2');\nuse bigint try=>\"GMP\";\n\nsub ack2 {\n   my ($m, $n) = @_;\n   $m == 0\u00a0? $n + 1\u00a0:\n   $m == 1\u00a0? $n + 2\u00a0:\n   $m == 2\u00a0? 2*$n + 3\u00a0:\n   $m == 3\u00a0? 8 * (2**$n - 1) + 5\u00a0:\n   $n == 0\u00a0? ack2($m-1, 1)\n          \u00a0: ack2($m-1, ack2($m, $n-1));\n}\nprint \"ack2(3,4) is \", ack2(3,4), \"\\n\";\nprint \"ack2(4,1) is \", ack2(4,1), \"\\n\";\nprint \"ack2(4,2) has \", length(ack2(4,2)), \" digits\\n\";\n\n","human_summarization":"The code implements the Ackermann function, a non-primitive recursive function, which takes two non-negative integers as arguments and returns their Ackermann value. The function is optimized for larger values by memoizing calls and using a stack instead of recursion. The function also supports arbitrary precision due to the rapid growth of the Ackermann function.","id":3744}
    {"lang_cluster":"Perl","source_code":"\nuse strict;\nuse warnings;\nuse constant pi => 4*atan2(1, 1);\nuse constant e  => exp(1);\n\n# Normally would be:  use Math::MPFR\n# but this will use it if it's installed and ignore otherwise\nmy $have_MPFR = eval { require Math::MPFR; Math::MPFR->import(); 1; };\n \nsub Gamma {\n    my $z = shift;\n    my $method = shift \/\/ 'lanczos';\n    if ($method eq 'lanczos') {\n        use constant g => 9;\n        $z <  .5 ?  pi \/ sin(pi * $z) \/ Gamma(1 - $z, $method) :\n        sqrt(2* pi) *\n        ($z + g - .5)**($z - .5) *\n        exp(-($z + g - .5)) *\n        do {\n            my @coeff = qw{\n            1.000000000000000174663\n        5716.400188274341379136\n      -14815.30426768413909044\n       14291.49277657478554025\n       -6348.160217641458813289\n        1301.608286058321874105\n        -108.1767053514369634679\n           2.605696505611755827729\n          -0.7423452510201416151527e-2\n           0.5384136432509564062961e-7\n          -0.4023533141268236372067e-8\n            };\n            my ($sum, $i) = (shift(@coeff), 0);\n            $sum += $_ \/ ($z + $i++) for @coeff;\n            $sum;\n        }\n    } elsif ($method eq 'taylor') {\n        $z <  .5 ? Gamma($z+1, $method)\/$z     :\n        $z > 1.5 ? ($z-1)*Gamma($z-1, $method) :\n\tdo {\n\t    my $s = 0; ($s *= $z-1) += $_ for qw{\n\t    0.00000000000000000002 -0.00000000000000000023 0.00000000000000000141\n\t    0.00000000000000000119 -0.00000000000000011813 0.00000000000000122678\n\t    -0.00000000000000534812 -0.00000000000002058326 0.00000000000051003703\n\t    -0.00000000000369680562 0.00000000000778226344 0.00000000010434267117\n\t    -0.00000000118127457049 0.00000000500200764447 0.00000000611609510448\n\t    -0.00000020563384169776 0.00000113302723198170 -0.00000125049348214267\n\t    -0.00002013485478078824 0.00012805028238811619 -0.00021524167411495097\n\t    -0.00116516759185906511 0.00721894324666309954 -0.00962197152787697356\n\t    -0.04219773455554433675 0.16653861138229148950 -0.04200263503409523553\n\t    -0.65587807152025388108 0.57721566490153286061 1.00000000000000000000\n\t    }; 1\/$s;\n\t}\n    } elsif ($method eq 'stirling') {\n        no warnings qw(recursion);\n        $z < 100 ? Gamma($z + 1, $method)\/$z :\n        sqrt(2*pi*$z)*($z\/e + 1\/(12*e*$z))**$z \/ $z;\n    } elsif ($method eq 'MPFR') {\n        my $result = Math::MPFR->new();\n        Math::MPFR::Rmpfr_gamma($result, Math::MPFR->new($z), 0);\n        $result;\n    } else { die \"unknown method '$method'\" }\n}\n \nfor my $method (qw(MPFR lanczos taylor stirling)) {\n    next if $method eq 'MPFR' && !$have_MPFR;\n    printf \"%10s: \", $method;\n    print join(' ', map { sprintf \"%.12f\", Gamma($_\/3, $method) } 1 .. 10);\n    print \"\\n\";\n}\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":3745}
    {"lang_cluster":"Perl","source_code":"\nmy ($board_size, @occupied, @past, @solutions);\n\nsub try_column {\n        my ($depth, @diag) = shift;\n        if ($depth == $board_size) {\n                push @solutions, \"@past\\n\";\n                return;\n        }\n\n        # @diag: marks cells diagonally attackable by any previous queens.\n        #        Here it's pre-allocated to double size just so we don't need\n        #        to worry about negative indices.\n        $#diag = 2 * $board_size;\n        for (0 .. $#past) {\n                $diag[ $past[$_] + $depth - $_ ] = 1;\n                $diag[ $past[$_] - $depth + $_ ] = 1;\n        }\n\n        for my $row (0 .. $board_size - 1) {\n                next if $occupied[$row] || $diag[$row];\n\n                # @past:     row numbers of previous queens\n                # @occupied: rows already used. This gets inherited by each\n                #            recursion so we don't need to repeatedly look them up\n                push @past, $row;\n                $occupied[$row] = 1;\n\n                try_column($depth + 1);\n\n                # clean up, for next recursion\n                $occupied[$row] = 0;\n                pop @past;\n        }\n}\n\n$board_size = 12;\ntry_column(0);\n\n#print for @solutions; # un-comment to see all solutions\nprint \"total \" . @solutions . \" solutions\\n\";\n\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":3746}
    {"lang_cluster":"Perl","source_code":"\n\nmy @arr1 = (1, 2, 3);\nmy @arr2 = (4, 5, 6);\nmy @arr3 = (@arr1, @arr2);\n\nmy @arr1 = (1, 2, 3);\nmy @arr2 = (4, 5, 6);\npush @arr1, @arr2;\nprint \"@arr1\\n\"; # prints \"1 2 3 4 5 6\"\n","human_summarization":"demonstrate how to concatenate two arrays in Perl using the push function.","id":3747}
    {"lang_cluster":"Perl","source_code":"\n\nmy $raw = <<'TABLE';\nmap\t\t\t9\t150\ncompass\t\t\t13\t35\nwater\t\t\t153\t200\nsandwich\t\t50\t160\nglucose\t\t\t15\t60\ntin\t\t\t68\t45\nbanana\t\t\t27\t60\napple\t\t\t39\t40\ncheese\t\t\t23\t30\nbeer\t\t\t52\t10\nsuntancream\t\t11\t70\ncamera\t\t\t32\t30\nT-shirt\t\t\t24\t15\ntrousers\t\t48\t10\numbrella\t\t73\t40\nwaterproof trousers\t42\t70\nwaterproof overclothes\t43\t75\nnote-case\t\t22\t80\nsunglasses\t\t7\t20\ntowel\t\t\t18\t12\nsocks\t\t\t4\t50\nbook\t\t\t30\t10\nTABLE\n\nmy (@name, @weight, @value);\nfor (split \"\\n\", $raw) {\n    for ([ split \/\\t+\/ ]) {\n        push @name,   $_->[0];\n        push @weight, $_->[1];\n        push @value,  $_->[2];\n    }\n}\n\nmy $max_weight = 400;\nmy @p = map [map undef, 0 .. 1+$max_weight], 0 .. $#name;\n\nsub optimal {\n    my ($i, $w) = @_;\n    return [0, []] if $i < 0;\n    return $p[$i][$w] if $p[$i][$w];\n\n    if ($weight[$i] > $w) {\n        $p[$i][$w] = optimal($i - 1, $w)\n    } else {\n        my $x = optimal($i - 1, $w);\n        my $y = optimal($i - 1, $w - $weight[$i]);\n\n        if ($x->[0] > $y->[0] + $value[$i]) {\n            $p[$i][$w] = $x\n        } else {\n            $p[$i][$w] = [  $y->[0] + $value[$i], [ @{$y->[1]}, $name[$i] ]]\n        }\n    }\n    return $p[$i][$w]\n}\n\nmy $solution = optimal($#name, $max_weight);\nprint \"$solution->[0]: @{$solution->[1]}\\n\";\n\n\n","human_summarization":"<output> implement a solution to the 0-1 Knapsack problem. The codes determine the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg, to maximize the total value of the items. The items, their weights, and their values are provided in a list, and only whole units of any item can be taken. <\/output>","id":3748}
    {"lang_cluster":"Perl","source_code":"\n#!\/usr\/bin\/env perl \nuse strict;\nuse warnings;\nuse feature qw\/say\/;\nuse List::Util qw(first);\n\nmy %Likes = (\n  M => {\n    abe  => [qw\/ abi eve cath ivy jan dee fay bea hope gay \/],\n    bob  => [qw\/ cath hope abi dee eve fay bea jan ivy gay \/],\n    col  => [qw\/ hope eve abi dee bea fay ivy gay cath jan \/],\n    dan  => [qw\/ ivy fay dee gay hope eve jan bea cath abi \/],\n    ed   => [qw\/ jan dee bea cath fay eve abi ivy hope gay \/],\n    fred => [qw\/ bea abi dee gay eve ivy cath jan hope fay \/],\n    gav  => [qw\/ gay eve ivy bea cath abi dee hope jan fay \/],\n    hal  => [qw\/ abi eve hope fay ivy cath jan bea gay dee \/],\n    ian  => [qw\/ hope cath dee gay bea abi fay ivy jan eve \/],\n    jon  => [qw\/ abi fay jan gay eve bea dee cath ivy hope \/],\n  },\n\n  W => {\n    abi  => [qw\/ bob fred jon gav ian abe dan ed col hal \/],\n    bea  => [qw\/ bob abe col fred gav dan ian ed jon hal \/],\n    cath => [qw\/ fred bob ed gav hal col ian abe dan jon \/],\n    dee  => [qw\/ fred jon col abe ian hal gav dan bob ed \/],\n    eve  => [qw\/ jon hal fred dan abe gav col ed ian bob \/],\n    fay  => [qw\/ bob abe ed ian jon dan fred gav col hal \/],\n    gay  => [qw\/ jon gav hal fred bob abe col ed dan ian \/],\n    hope => [qw\/ gav jon bob abe ian dan hal ed col fred \/],\n    ivy  => [qw\/ ian col hal gav fred bob abe ed jon dan \/],\n    jan  => [qw\/ ed hal gav abe bob jon col ian fred dan \/],\n  },\n);\n\nmy %Engaged;\nmy %Proposed;\n\nmatch_them();\ncheck_stability();\nperturb();\ncheck_stability();\n\nsub match_them {\n    say 'Matchmaking:';\n    while(my $man = unmatched_man()) {\n        my $woman = preferred_choice($man);\n        $Proposed{$man}{$woman} = 1;\n        if(! $Engaged{W}{$woman}) {\n            engage($man, $woman);\n            say \"\\t$woman and $man\";\n        }\n        else {\n            if(woman_prefers($woman, $man)) {\n                my $engaged_man = $Engaged{W}{$woman};\n                engage($man, $woman);\n                undef $Engaged{M}{$engaged_man};\n                say \"\\t$woman dumped $engaged_man for $man\";\n            }\n        }\n    }\n}\n\nsub check_stability {\n    say 'Stablility:';\n    my $stable = 1;\n    foreach my $m (men()) {\n        foreach my $w (women()) {\n            if(man_prefers($m, $w) && woman_prefers($w, $m)) {\n                say \"\\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}\";\n                $stable = 0;\n            }\n        }\n    }\n    if($stable) {\n        say \"\\t(all marriages stable)\";\n    }\n}\n\nsub unmatched_man {\n    return first { ! $Engaged{M}{$_} } men();\n}\n\nsub preferred_choice {\n    my $man = shift;\n    return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} };\n}\n\nsub engage {\n    my ($man, $woman) = @_;\n    $Engaged{W}{$woman} = $man;\n    $Engaged{M}{$man} = $woman;\n}\n\nsub prefers {\n    my $sex = shift;\n    return sub {\n        my ($person, $prospect) = @_;\n\n        my $choices = join ' ', @{ $Likes{$sex}{$person} };\n        return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person});\n    }\n}\n\nBEGIN {\n    *woman_prefers = prefers('W');\n    *man_prefers   = prefers('M');\n}\n\nsub perturb {\n    say 'Perturb:';\n    say \"\\tengage abi with fred and bea with jon\";\n    engage('fred' => 'abi');\n    engage('jon'  => 'bea');\n}\n\nsub men   { keys %{ $Likes{M} } }\nsub women { keys %{ $Likes{W} } }\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":3749}
    {"lang_cluster":"Perl","source_code":"\n\nsub a { print 'A'; return $_[0] }\nsub b { print 'B'; return $_[0] }\n\n# Test-driver\nsub test {\n    for my $op ('&&','||') {\n        for (qw(1,1 1,0 0,1 0,0)) {\n           my ($x,$y) = \/(.),(.)\/;\n           print my $str = \"a($x) $op b($y)\", ': ';\n           eval $str; print \"\\n\"; } }\n}    \n\n# Test and display\ntest();\n\n\n","human_summarization":"The code defines two functions, 'a' and 'b', both of which take a boolean value as input, return the same value, and print their name when called. The code then calculates the values of two equations, 'x = a(i) and b(j)' and 'y = a(i) or b(j)', ensuring that function 'b' is only called when necessary, utilizing the concept of short-circuit evaluation. If the programming language does not support short-circuit evaluation, nested 'if' statements are used to achieve the same effect. The code is optimized for languages like Perl that use short-circuit boolean evaluation.","id":3750}
    {"lang_cluster":"Perl","source_code":"\nuse Acme::AGMorse qw(SetMorseVals SendMorseMsg);\nSetMorseVals(20,30,400);\nSendMorseMsg('Hello World! abcdefg @\\;');  # note, caps are ingnored in Morse Code\nexit;\n\n\nAcme::AGMorse\nAudio::Beep\nSwitch\n\n1) pcspkr may not be available by default. Run: sudo modprobe pcspkr\n2) pcspkr may be available but muted.\n    - Check your sound prefrences,usually a right click over the speaker icon\n","human_summarization":"send a string as Morse code to an audio device, ignoring unknown characters or indicating them with a different pitch. Known issues exist on UNIX systems.","id":3751}
    {"lang_cluster":"Perl","source_code":"\n\n#!\/usr\/bin\/perl\nuse warnings;\nuse strict;\n\n\nsub can_make_word {\n    my ($word, @blocks) = @_;\n    $_ = uc join q(), sort split \/\/ for @blocks;\n    my %blocks;\n    $blocks{$_}++ for @blocks;\n    return _can_make_word(uc $word, %blocks)\n}\n\n\nsub _can_make_word {\n    my ($word, %blocks) = @_;\n    my $char = substr $word, 0, 1, q();\n\n    my @candidates = grep 0 <= index($_, $char), keys %blocks;\n    for my $candidate (@candidates) {\n        next if $blocks{$candidate} <= 0;\n        local $blocks{$candidate} = $blocks{$candidate} - 1;\n        return 1 if q() eq $word or _can_make_word($word, %blocks);\n    }\n    return\n}\n\nuse Test::More tests => 8;\n\nmy @blocks1 = qw(BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM);\nis(can_make_word(\"A\",       @blocks1), 1);\nis(can_make_word(\"BARK\",    @blocks1), 1);\nis(can_make_word(\"BOOK\",    @blocks1), undef);\nis(can_make_word(\"TREAT\",   @blocks1), 1);\nis(can_make_word(\"COMMON\",  @blocks1), undef);\nis(can_make_word(\"SQUAD\",   @blocks1), 1);\nis(can_make_word(\"CONFUSE\", @blocks1), 1);\n\nmy @blocks2 = qw(US TZ AO QA);\nis(can_make_word('auto', @blocks2), 1);\n\n#!\/usr\/bin\/perl\n\nuse strict; # https:\/\/rosettacode.org\/wiki\/ABC_Problem\nuse warnings;\n\nprintf \"%30s  %s\\n\", $_, can_make_word( $_,\n  'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM' )\n  for qw( A BARK BOOK TREAT COMMON SQUAD CONFUSE );\n\nsub can_make_word\n  {\n  my ($word, $blocks) = @_;\n  my $letter = chop $word or return 'True';\n  can_make_word( $word, $` . $' ) eq 'True' and return 'True'\n    while $blocks =~ \/\\w?$letter\\w?\/gi;\n  return 'False';\n  }\n\n\n","human_summarization":"The code is a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value indicating whether or not the word can be spelled with the provided blocks. The function is tested with seven different words.","id":3752}
    {"lang_cluster":"Perl","source_code":"\nLibrary: Digest::MD5MD5\nuse Digest::MD5 qw(md5_hex);\n\nprint md5_hex(\"The quick brown fox jumped over the lazy dog's back\"), \"\\n\";\n\n\nuse Digest::MD5;\n\n$md5 = Digest::MD5->new;\n$md5->add(\"The quick brown fox jumped over the lazy dog's back\");\nprint $md5->hexdigest, \"\\n\";\n\n","human_summarization":"The code implements the MD5 algorithm to encode a string. It optionally validates the implementation using test values from IETF RFC 1321. However, due to MD5's known weaknesses, it suggests using stronger alternatives for production-grade cryptography. The code also provides an object-oriented implementation of the MD5 algorithm.","id":3753}
    {"lang_cluster":"Perl","source_code":"\nmy @OIDs = qw(\n    1.3.6.1.4.1.11.2.17.19.3.4.0.10\n    1.3.6.1.4.1.11.2.17.5.2.0.79\n    1.3.6.1.4.1.11.2.17.19.3.4.0.4\n    1.3.6.1.4.1.11150.3.4.0.1\n    1.3.6.1.4.1.11.2.17.19.3.4.0.1\n    1.3.6.1.4.1.11150.3.4.0\n);\n\nmy @sorted =\n    map { $_->[0] }\n    sort { $a->[1] cmp $b->[1] }\n    map { [$_, join '', map { sprintf \"%8d\", $_ } split \/\\.\/, $_] }\n    @OIDs;\n\nprint \"$_\\n\" for @sorted;\n\n\n","human_summarization":"sorts a list of Object Identifiers (OIDs). An OID is a string of non-negative integers in base 10, separated by dots. The sorting is done lexicographically based on the dot-separated fields, using numeric comparison between fields. The codes can also sort the OIDs as \"version strings\", a Perl syntax where characters' codes are specified as a dot-delimited sequence of integers.","id":3754}
    {"lang_cluster":"Perl","source_code":"\nuse Socket;\n\n$host = gethostbyname('localhost');\n$in = sockaddr_in(256, $host);\n$proto = getprotobyname('tcp');\nsocket(Socket_Handle, AF_INET, SOCK_STREAM, $proto);\nconnect(Socket_Handle, $in);\nsend(Socket_Handle, 'hello socket world', 0, $in);\nclose(Socket_Handle);\n\n\nuse Socket::Class;\n\n$sock = Socket::Class->new(\n  'remote_port' => 256,\n) || die Socket::Class->error;\n$sock->send('hello socket world');\n$sock->free;\n\n","human_summarization":"Open a socket to localhost on port 256, send the message \"hello socket world\", and then close the socket in an object-oriented manner. Error handling is not implemented.","id":3755}
    {"lang_cluster":"Perl","source_code":"\n\nuse Net::SMTP;\nuse Authen::SASL;\n  # Net::SMTP's 'auth' method needs Authen::SASL to work, but\n  # this is undocumented, and if you don't have the latter, the\n  # method will just silently fail. Hence we explicitly use\n  # Authen::SASL here.\n\nsub send_email {\n  my %o =\n     (from => '', to => [], cc => [],\n      subject => '', body => '',\n      host => '', user => '', password => '',\n      @_);\n  ref $o{$_} or $o{$_} = [$o{$_}] foreach 'to', 'cc';\n\n  my $smtp = Net::SMTP->new($o{host} ? $o{host} : ())\n      or die \"Couldn't connect to SMTP server\";\n\n  $o{password} and\n     $smtp->auth($o{user}, $o{password}) ||\n     die 'SMTP authentication failed';\n\n  $smtp->mail($o{user});\n  $smtp->recipient($_) foreach @{$o{to}}, @{$o{cc}};\n  $smtp->data;\n  $o{from} and $smtp->datasend(\"From: $o{from}\\n\");\n  $smtp->datasend('To: ' . join(', ', @{$o{to}}) . \"\\n\");\n  @{$o{cc}} and $smtp->datasend('Cc: ' . join(', ', @{$o{cc}}) . \"\\n\");\n  $o{subject} and $smtp->datasend(\"Subject: $o{subject}\\n\");\n  $smtp->datasend(\"\\n$o{body}\");\n  $smtp->dataend;\n\n  return 1;\n}\n\n\nsend_email\n   from => 'A. T. Tappman',\n   to => ['suchandsuch@example.com', 'soandso@example.org'],\n   cc => 'somebodyelse@example.net',\n   subject => 'Important message',\n   body => 'I yearn for you tragically.',\n   host => 'smtp.example.com:587',\n   user => 'tappman@example.com',\n   password => 'yossarian';\n\n\nsend_email\n   to => 'suchandsuch@example.com',\n   user => 'tappman@example.com';\n\n\nuse strict;\nuse LWP::UserAgent;\nuse HTTP::Request;\n\nsub send_email {\n  my ($from, $to, $cc, $subject, $text) = @_;\n\n  my $ua = LWP::UserAgent->new;\n  my $req = HTTP::Request->new (POST => \"mailto:$to\",\n                                [ From => $from,\n                                  Cc => $cc,\n                                  Subject => $subject ],\n                                $text);\n  my $resp = $ua->request($req);\n  if (! $resp->is_success) {\n    print $resp->status_line,\"\\n\";\n  }\n}\n\nsend_email('from-me@example.com', 'to-foo@example.com', '',\n           \"very important subject\",\n           \"Body text\\n\");\n\n","human_summarization":"implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, server name and login details. The function throws an error if it fails to connect to the server or authenticate. It uses libraries or functions from the language and works on any platform that supports Perl. If the host parameter is omitted, it uses the SMTP_Hosts defined in Net::Config. It can also send email by a POST to a mailto: URL. The solution is portable across different operating systems.","id":3756}
    {"lang_cluster":"Perl","source_code":"\n\nuse POSIX;\nprintf \"%o\\n\", $_ for (0 .. POSIX::UINT_MAX);\n\n\nuse bigint;\nmy $i = 0;\nprintf \"%o\\n\", $i++ while 1\n\n\n#!\/usr\/bin\/perl\n\n$_ = 0;\ns\/([^7])?(7*)$\/ $1 + 1 . $2 =~ tr!7!0!r \/e while print \"$_\\n\";\n\n","human_summarization":"generate a sequential count in octal format, starting from zero and incrementing by one. Each number is printed on a separate line. The program continues until it is terminated or the maximum value of the numeric type in use is reached.","id":3757}
    {"lang_cluster":"Perl","source_code":"\n\n($y, $x) = ($x, $y);\n\nsub swap {@_[0, 1] = @_[1, 0]}\n","human_summarization":"implement a generic swap function or operator that can exchange the values of two variables or storage places, regardless of their types. The function handles both statically and dynamically typed languages, with certain limitations for each. In statically typed languages, the function may require variables to have mutually compatible types. In dynamically typed languages, the function may struggle with destructively swapping two variables. The function may not support swapping in some functional languages or static languages lacking support for parametric polymorphism. Perl's built-in swap functionality is also mentioned.","id":3758}
    {"lang_cluster":"Perl","source_code":"\n\npalindrome uses the built-in function reverse().\npalindrome_c uses iteration; it is a translation of the C solution.\npalindrome_r uses recursion.\npalindrome_e uses a recursive regular expression.\n\n# Palindrome.pm\npackage Palindrome;\n\nuse strict;\nuse warnings;\n\nuse Exporter 'import';\nour @EXPORT = qw(palindrome palindrome_c palindrome_r palindrome_e);\n\nsub palindrome\n{\n    my $s = (@_\u00a0? shift\u00a0: $_);\n    return $s eq reverse $s;\n}\n\nsub palindrome_c\n{\n    my $s = (@_\u00a0? shift\u00a0: $_);\n    for my $i (0 .. length($s) >> 1)\n    {\n        return 0 unless substr($s, $i, 1) eq substr($s, -1 - $i, 1);\n    }\n    return 1;\n}\n\nsub palindrome_r\n{\n    my $s = (@_\u00a0? shift\u00a0: $_);\n    if (length $s <= 1) { return 1; }\n    elsif (substr($s, 0, 1) ne substr($s, -1, 1)) { return 0; }\n    else { return palindrome_r(substr($s, 1, -1)); }\n}\n\nsub palindrome_e\n{\n    (@_\u00a0? shift\u00a0: $_) =~ \/^(.?|(.)(?1)\\2)$\/ + 0\n}\n\n# pbench.pl\nuse strict;\nuse warnings;\n\nuse Benchmark qw(cmpthese);\nuse Palindrome;\n\nprintf(\"%d, %d, %d, %d: %s\\n\",\n       palindrome, palindrome_c, palindrome_r, palindrome_e, $_)\nfor\n    qw\/a aa ab abba aBbA abca abba1 1abba\n    ingirumimusnocteetconsumimurigni\/,\n    'ab cc ba',\t'ab ccb a';\n\nprintf \"\\n\";\n\nmy $latin = \"ingirumimusnocteetconsumimurigni\";\ncmpthese(100_000, {\n    palindrome => sub { palindrome $latin },\n    palindrome_c => sub { palindrome_c $latin },\n    palindrome_r => sub { palindrome_r $latin },\n    palindrome_e => sub { palindrome_e $latin },\n});\n\n","human_summarization":"The code includes a function to check if a given sequence of characters forms a palindrome. It supports Unicode characters and has an additional function to detect inexact palindromes, ignoring white-space, punctuation, and case sensitivity. The functions take a parameter or default to $_ if no parameter is provided. The functions do not ignore case or strip characters, but this can be achieved by using a specific command before calling the functions. The code also includes an example of how to use the functions. The palindrome function is optimized for speed.","id":3759}
    {"lang_cluster":"Perl","source_code":"\n\nprint $ENV{HOME}, \"\\n\";\n\n\nuse POSIX 'getenv';\nprint getenv(\"HOME\"),\"\\n\";\n\n","human_summarization":"demonstrate how to retrieve a specific environment variable from a process using the %ENV hash and the getenv() function from the POSIX module. The common environment variables available on Unix systems such as PATH, HOME, and USER are used as examples.","id":3760}
    {"lang_cluster":"Perl","source_code":"\n\nuse v5.36;\nuse experimental 'for_list';\n\nsub F1($n, $x, $y) { $n ? $y ? F1($n-1, F2($n,$x,$y-1), F3($n,$x,$y-1)+$y) : $x : $x+$y }\n\nsub F2($n, $x, $y) { $n == 0 ? $x+$y : $y == 0 ? $x : F2($n-1, F1($n,$x,$y-1), F3($n,$x,$y-1)+$y) }\n\nsub F3($n, $x, $y) {\n  return $x + $y if $n == 0;\n  return $x      if $y == 0;\n  F3($n-1, F1($n, $x, $y-1), F2($n, $x, $y-1) + $y)\n}\n\nfor my($n,$x,$y) (0,0,0, 1,1,1, 2,1,1, 3,1,1, 2,2,1) {\n    say join ' ',F1($n,$x,$y), F2($n,$x,$y), F3($n,$x,$y)\n}\n\n\n","human_summarization":"implement the Sudan function, a non-primitive recursive function, which calculates and returns the value of F(x, y) based on the defined rules.","id":3761}
    {"lang_cluster":"MATLAB","source_code":"function f = fib(n)\n\t\n\tf = [1 1\u00a0; 1 0]^(n-1);\n\tf = f(1,1);\n\t\nend\nfunction F = fibonacci(n)\n    \n    Fn = [1 0]; %Fn(1) is F_{n-2}, Fn(2) is F_{n-1} \n    F = 0; %F is F_{n}\n    \n    for i = (1:abs(n))\n        Fn(2) = F;\n        F = sum(Fn);\n        Fn(1) = Fn(2);\n    end\n        \n    if n < 0\n        F = F*((-1)^(n+1));\n    end   \n\nend\n\nfunction number = fibonacci2(n)\n    \n    if n == 1\n        number = 1;\n    elseif n == 0\n        number = 0;\n    elseif n < 0\n        number = ((-1)^(n+1))*fibonacci2(-n);;\n    else\n        number = det(gallery('dramadah',n,3));\n    end\n\nend\nfunction number = fibonacci(n)\n%construct the Tartaglia\/Pascal Triangle\n    pt=tril(ones(n));\n    for r = 3\u00a0: n\n   \u00a0% Every element is the addition of the two elements\n   \u00a0% on top of it. That means the previous row.\n        for c = 2\u00a0: r-1\n            pt(r, c) = pt(r-1, c-1) + pt(r-1, c);\n        end   \n    end\n    number=trace(rot90(pt));\nend\n","human_summarization":"implement a function to generate the nth Fibonacci number, either iteratively or recursively. The function also has the optional feature to support negative n values by using the inverse of the positive definition. Additionally, the codes utilize the method suggested by MATLAB help file, using the determinate of the Dramadah Matrix of type 3 and size n-by-n to generate the nth Fibonacci number.","id":3762}
    {"lang_cluster":"MATLAB","source_code":"\nfunction evens = selectEvenNumbers(list)\n\n    evens = list( mod(list,2) == 0 );\n\nend\n\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":3763}
    {"lang_cluster":"MATLAB","source_code":"\n\n>> fliplr(['She told me that she spoke English and I said great. '...\n'Grabbed her hand out the club and I said let''s skate.'])\n\nans =\n\n.etaks s'tel dias I dna bulc eht tuo dnah reh debbarG .taerg dias I dna hsilgnE ekops ehs taht em dlot ehS\n","human_summarization":"\"Function to reverse a string, with additional functionality to preserve Unicode combining characters. Includes a test for the built-in 'fliplr()' function's handling of Unicode characters.\"","id":3764}
    {"lang_cluster":"MATLAB","source_code":"\n\n>> unique([1 2 6 3 6 4 5 6])\n\nans =\n\n     1     2     3     4     5     6\n\n\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) using a hash table, 2) sorting the elements and removing consecutive duplicates, and 3) iterating through the list and discarding any repeated elements. It also mentions the use of MATLAB's built-in function \"unique(list)\" for this task, which only works for vectors.","id":3765}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction sortedArray = quickSort(array)\n\n    if numel(array) <= 1 %If the array has 1 element then it can't be sorted       \n        sortedArray = array;\n        return\n    end\n    \n    pivot = array(end);\n    array(end) = [];\n        \n    %Create two new arrays which contain the elements that are less than or\n    %equal to the pivot called \"less\" and greater than the pivot called\n    %\"greater\"\n    less = array( array <= pivot );\n    greater = array( array > pivot );\n    \n    %The sorted array is the concatenation of the sorted \"less\" array, the\n    %pivot and the sorted \"greater\" array in that order\n    sortedArray = [quickSort(less) pivot quickSort(greater)];\n    \nend\n\n\nfunction sortedArray = quickSort(array)\n\n    if numel(array) <= 1 %If the array has 1 element then it can't be sorted       \n        sortedArray = array;\n        return\n    end\n    \n    pivot = array(end);\n    array(end) = [];\n    \n    sortedArray = [quickSort( array(array <= pivot) ) pivot quickSort( array(array > pivot) )];\n    \nend\n\n\nquickSort([4,3,7,-2,9,1])\n\nans =\n\n    -2     1     3     4     7     9\n","human_summarization":"implement the Quicksort algorithm to sort an array or list. The algorithm selects a pivot element from the array and divides the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and combines them with the pivot to get the sorted array. The codes also handle the selection of the pivot element and the allocation of new arrays or in-place sorting.","id":3766}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction pset = powerset(theSet)\n\n    pset = cell(size(theSet)); %Preallocate memory\n\n    %Generate all numbers from 0 to 2^(num elements of the set)-1\n    for i = ( 0:(2^numel(theSet))-1 )\n       \n        %Convert i into binary, convert each digit in binary to a boolean\n        %and store that array of booleans\n        indicies = logical(bitget( i,(1:numel(theSet)) )); \n        \n        %Use the array of booleans to extract the members of the original\n        %set, and store the set containing these members in the powerset\n        pset(i+1) = {theSet(indicies)};\n       \n    end\n    \nend\n\n\npowerset({{}})\n\nans = \n\n     {}    {1x1 cell} %This is the same as { {},{{}} }\n\n\npowerset({{1,2},3})\n\nans = \n\n    {1x0 cell}    {1x1 cell}    {1x1 cell}    {1x2 cell} %This is the same as { {},{{1,2}},{3},{{1,2},3} }\n\n","human_summarization":"The code defines a function that takes a set as input and outputs its power set. The power set includes all possible subsets of the input set, including the empty set and the set itself. The function can handle sets of any type of data structure, thanks to the use of cell arrays in MATLAB. It also demonstrates support for power sets of the empty set and the set containing only the empty set.","id":3767}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction [closest,closestpair] = closestPair(xP,yP)\n\n    N = numel(xP);\n\n    if(N <= 3)\n        \n        %Brute force closestpair\n        if(N < 2)\n            closest = +Inf;\n            closestpair = {};\n        else        \n            closest = norm(xP{1}-xP{2});\n            closestpair = {xP{1},xP{2}};\n\n            for i = ( 1:N-1 )\n                for j = ( (i+1):N )\n                    if ( norm(xP{i} - xP{j}) < closest )\n                        closest = norm(xP{i}-xP{j});\n                        closestpair = {xP{i},xP{j}};\n                    end %if\n                end %for\n            end %for\n        end %if (N < 2)\n    else\n        \n        halfN = ceil(N\/2);\n        \n        xL = { xP{1:halfN} };\n        xR = { xP{halfN+1:N} };\n        xm = xP{halfN}(1);\n        \n        %cellfun( @(p)le(p(1),xm),yP ) is the same as { p \u2208 yP\u00a0: px \u2264 xm }\n        yLIndicies = cellfun( @(p)le(p(1),xm),yP );\n        \n        yL = { yP{yLIndicies} };\n        yR = { yP{~yLIndicies} };\n\n        [dL,pairL] = closestPair(xL,yL);\n        [dR,pairR] = closestPair(xR,yR);\n        \n        if dL < dR\n            dmin = dL;\n            pairMin = pairL;\n        else\n            dmin = dR;\n            pairMin = pairR;\n        end\n\n        %cellfun( @(p)lt(norm(xm-p(1)),dmin),yP ) is the same as\n        %{ p \u2208 yP\u00a0: |xm - px| < dmin }\n        yS = {yP{ cellfun( @(p)lt(norm(xm-p(1)),dmin),yP ) }};\n        nS = numel(yS);\n\n        closest = dmin;\n        closestpair = pairMin;\n\n        for i = (1:nS-1)\n            k = i+1;\n\n            while( (k<=nS) && (yS{k}(2)-yS{i}(2) < dmin) )\n\n                if norm(yS{k}-yS{i}) < closest\n                    closest = norm(yS{k}-yS{i});\n                    closestpair = {yS{k},yS{i}};\n                end\n\n                k = k+1;\n            end %while\n        end %for\n    end %if (N <= 3)\nend %closestPair\n\n\n","human_summarization":"The code provides two functions to solve the Closest Pair of Points problem in a two-dimensional space. The first function uses a brute-force approach, iterating through each pair of points to find the pair with the smallest distance. The second function uses a divide and conquer approach, recursively dividing the set of points and finding the closest pair in each subset. The points are sorted by x and y coordinates for efficient comparison. The code also includes references for further reading.","id":3768}
    {"lang_cluster":"MATLAB","source_code":"\nfunction r=rot13(s)\n    if ischar(s)\n        r=s;  % preallocation and copy of non-letters\n        for i=1:size(s,1)\n            for j=1:size(s,2)\n                if isletter(s(i,j))\n                    if s(i,j)>=97   % lower case\n                        base = 97;\n                    else            % upper case\n                        base = 65;\n                    end\n                    r(i,j)=char(mod(s(i,j)-base+13,26)+base);\n                end\n            end\n        end\n    else\n        error('Argument must be a CHAR')\n    end\nend\n\n\n>> rot13('Hello World!')\n\nans =\n\nUryyb Jbeyq!\n\n\nfunction text = rot13(text)\n    if ischar(text)\n        \n        selectedLetters = ( (text >= 'A') & (text <= 'Z') ); %Select upper case letters\n        text(selectedLetters) = char( mod( text(selectedLetters)-'A'+13,26 )+'A' );\n        \n        selectedLetters = ( (text >= 'a') & (text <= 'z') ); %Select lower case letters\n        text(selectedLetters) = char( mod( text(selectedLetters)-'a'+13,26 )+'a' );\n\n    else\n        error('Argument must be a string.')\n    end\nend\n\n\n>> plainText = char((64:123))\n\nplainText =\n\n@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{\n\n>> rot13(plainText)\n\nans =\n\n@NOPQRSTUVWXYZABCDEFGHIJKLM[\\]^_`nopqrstuvwxyzabcdefghijklm{\n\n","human_summarization":"implement a rot-13 encoding function that can be optionally wrapped in a utility program. This function replaces every ASCII alphabet letter with the letter that is 13 characters away from it in the 26 letter alphabet, wrapping from z to a as needed. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. The function can be used to obfuscate text to prevent casual reading of spoilers or offensive material.","id":3769}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction result = halveInt(number)\n    \n    result = idivide(number,2,'floor');\n\nend\n\n\nfunction result = doubleInt(number)\n\n    result = times(2,number);\n\nend\n\n\n%Returns a logical 1 if the number is even, 0 otherwise.\nfunction trueFalse = isEven(number)\n\n    trueFalse = logical( mod(number,2)==0 );\n    \nend\n\n\nfunction answer = ethiopianMultiplication(multiplicand,multiplier)\n \n    %Generate columns\n    while multiplicand(end)>1\n        multiplicand(end+1,1) = halveInt( multiplicand(end) );\n        multiplier(end+1,1) = doubleInt( multiplier(end) );\n    end\n \n    %Strike out appropriate rows\n    multiplier( isEven(multiplicand) ) = [];\n \n    %Generate answer\n    answer = sum(multiplier);\n \nend\n\n\nethiopianMultiplication( int32(17),int32(34) )\n\nans =\n\n   578\n\n","human_summarization":"The code defines four functions for Ethiopian multiplication. The first function halves an integer, the second function doubles an integer, and the third function checks if an integer is even. These functions are used in the fourth function, which performs Ethiopian multiplication. The multiplication function works by repeatedly halving the first number and doubling the second number, discarding rows where the first number is even, and then summing the remaining values in the second column to get the product of the original two numbers.","id":3770}
    {"lang_cluster":"MATLAB","source_code":"\n\nanswer = factorial(N)\nfunction f=fac(n)\n    if n==0\n        f=1;\n        return\n    else\n        f=n*fac(n-1);\n    end\n\n  function b=factorial(a)\n\tb=1;\t\n\tfor i=1:a\t\n\t    b=b*i;\n\tend\n","human_summarization":"implement a function to calculate the factorial of a given number. The function can be either iterative or recursive. It optionally includes error handling for negative input values. The function is similar to the built-in factorial function in MATLAB, but without the precision limitations for numbers greater than 21.","id":3771}
    {"lang_cluster":"MATLAB","source_code":"\nfunction BullsAndCows\n% Plays the game Bulls and Cows as the \"game master\"\n    \n    % Create a secret number\n    nDigits = 4;\n    lowVal = 1;\n    highVal = 9;\n    digitList = lowVal:highVal;\n    secret = zeros(1, 4);\n    for k = 1:nDigits\n        idx = randi(length(digitList));\n        secret(k) = digitList(idx);\n        digitList(idx) = [];\n    end\n    \n    % Give game information\n    fprintf('Welcome to Bulls and Cows!\\n')\n    fprintf('Try to guess the %d-digit number (no repeated digits).\\n', nDigits)\n    fprintf('Digits are between %d and %d (inclusive).\\n', lowVal, highVal)\n    fprintf('Score: 1 Bull per correct digit in correct place.\\n')\n    fprintf('       1 Cow per correct digit in incorrect place.\\n')\n    fprintf('The number has been chosen. Now it''s your moooooove!\\n')\n    gs = input('Guess: ', 's');\n    \n    % Loop until user guesses right or quits (no guess)\n    nGuesses = 1;\n    while gs\n        gn = str2double(gs);\n        if isnan(gn) || length(gn) > 1  % Not a scalar\n            fprintf('Malformed guess. Keep to valid scalars.\\n')\n            gs = input('Try again: ', 's');\n        else\n            g = sprintf('%d', gn) - '0';\n            if length(g) ~= nDigits || any(g < lowVal) || any(g > highVal) || ...\n                    length(unique(g)) ~= nDigits    % Invalid number for game\n                fprintf('Malformed guess. Remember:\\n')\n                fprintf('  %d digits\\n', nDigits)\n                fprintf('  Between %d and %d inclusive\\n', lowVal, highVal)\n                fprintf('  No repeated digits\\n')\n                gs = input('Try again: ', 's');\n            else\n                score = CountBullsCows(g, secret);\n                if score(1) == nDigits\n                    fprintf('You win! Bully for you! Only %d guesses.\\n', nGuesses)\n                    gs = '';\n                else\n                    fprintf('Score: %d Bulls, %d Cows\\n', score)\n                    gs = input('Guess: ', 's');\n                end\n            end\n        end\n        nGuesses = nGuesses+1;  % Counts malformed guesses\n    end\nend\n\nfunction score = CountBullsCows(guess, correct)\n% Checks the guessed array of digits against the correct array to find the score\n% Assumes arrays of same length and valid numbers\n    bulls = guess == correct;\n    cows = ismember(guess(~bulls), correct);\n    score = [sum(bulls) sum(cows)];\nend\n\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":3772}
    {"lang_cluster":"MATLAB","source_code":"\n\n    mu = 1; sd = 0.5; \n    x = randn(1000,1) * sd + mu;\n\n\n   x = normrnd(mu, sd, [1000,1]);\n\n\nfunction randNum = randNorm(mu0,chi2, sz)\n           \n    radiusSquared = +Inf;\n\n    while (radiusSquared >= 1)\n        u = ( 2 * rand(sz) ) - 1;\n        v = ( 2 * rand(sz) ) - 1;\n\n        radiusSquared = u.^2 + v.^2;\n    end\n\n    scaleFactor = sqrt( ( -2*log(radiusSquared) ).\/ radiusSquared );\n    randNum = (v .* scaleFactor .* chi2) + mu0;\n\nend\n\n\n>> randNorm(1,.5, [1000,1])\n\nans =\n\n   0.693984121077029\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5. If only uniformly distributed random numbers can be generated, transformation algorithms like Box-Mueller Transform are used. The statistics toolbox function is also utilized in the process.","id":3773}
    {"lang_cluster":"MATLAB","source_code":"\n\nA = [1 3 -5]\nB = [4 -2 -1]\nC = dot(A,B)\n\n\nfunction C = DotPro(A,B)\n  C = sum( A.*B );\nend\n\n","human_summarization":"Implement a function to compute the dot product of two vectors of arbitrary length. The vectors should be of the same length, and the function should multiply corresponding terms from each vector and sum the products to produce the result. The function can also handle vector products.","id":3774}
    {"lang_cluster":"MATLAB","source_code":"\ndocNode = com.mathworks.xml.XMLUtils.createDocument('root');\ndocRootNode = docNode.getDocumentElement;\nthisElement = docNode.createElement('element'); \nthisElement.appendChild(docNode.createTextNode('Some text here'));\ndocRootNode.appendChild(thisElement);\n\n\n xmlwrite(docNode)\n\nans =\n\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n   <element>Some text here<\/element>\n<\/root>\n\n","human_summarization":"Create a simple DOM and serialize it into the specified XML format.","id":3775}
    {"lang_cluster":"MATLAB","source_code":"\n\nfigure; sphere\n\n","human_summarization":"\"Code to draw a graphical or ASCII art representation of a sphere, with options for static or rotational projection.\"","id":3776}
    {"lang_cluster":"MATLAB","source_code":"\nfunction s = nth(n)\n    tens = mod(n, 100);\n    if tens > 9 && tens < 20\n        suf = 'th';\n    else\n        switch mod(n, 10)\n            case 1\n                suf = 'st';\n            case 2\n                suf = 'nd';\n            case 3\n                suf = 'rd';\n            otherwise\n                suf = 'th';\n        end\n    end\n    s = sprintf('%d%s', n, suf);\nend\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":3777}
    {"lang_cluster":"MATLAB","source_code":"\nnumber = ceil(10*rand(1));\n[guess, status] = str2num(input('Guess a number between 1 and 10: ','s'));\n\nwhile (~status || guess ~= number)\n    [guess, status] = str2num(input('Guess again: ','s'));\nend\ndisp('Well guessed!')\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":3778}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction passed = luhn(num)\nif nargin == 0 % evaluate test cases\n  testnum = [49927398716 49927398717 1234567812345678 1234567812345670];\n  for num = testnum\n    disp([int2str(num) ': ' int2str(luhn(num))])\n  end\n  return  \nend\n% luhn function starts here\nd = int2str(num) - '0';\t% convert number into vector of digits\nm = [2:2:8,1:2:9];\t% rule 3: maps 1:9 to [2 4 6 8 1 3 5 7 9]\npassed = ~mod(sum(d(end:-2:1)) + sum(m(d(end-1:-2:1))), 10);  \nend\n\n\n","human_summarization":"The code implements the Luhn test for validating credit card numbers. It first reverses the order of the digits in the number, then sums every other odd digit to form a partial sum s1. For every other even digit, it multiplies each by two and sums the digits if the result is greater than nine to form partial sums for the even digits, and then sums these to form s2. If the sum of s1 and s2 ends in zero, the number is a valid credit card number. The code validates the numbers 49927398716, 49927398717, 1234567812345678, and 1234567812345670 using this method.","id":3779}
    {"lang_cluster":"MATLAB","source_code":"\nfunction [indAlive] = josephus(numPeople,count)\n% Josephus: Given a circle of numPeople individuals, with a count of count,\n% find the index (starting at 1) of the survivor [see Josephus Problem]\n\n%% Definitions:\n%   0 = dead position\n%   1 = alive position\n%   index = # of person\n\n%% Setting up\narrPeople = ones(1, numPeople);\ncurrInd = 0;\n\n%% Counting\nwhile (length(arrPeople(arrPeople == 1)) > 1)     % While more than 1 person is alive\n    counter = 0;\n    while counter ~= count                       % Counting until we hit the count\n        currInd = currInd + 1;                  % Move to the next person\n        \n        if currInd > numPeople                  % If overflow, wraparound\n            currInd = currInd - numPeople;\n        end\n        \n        if arrPeople(currInd)                   % If the current person is alive\n            counter = counter + 1;                % Add 1 person to the count\n            %fprintf(\"Index: %d \\t| Counter: %d\\n\", currInd, counter)          \u00a0% Uncomment to display index and counter location\n        end\n\n    end\n    \n    arrPeople(currInd) = 0;                     % Kill the person we reached\n    %fprintf(\"Killed person %d \\n\", currInd)                                  \u00a0% Uncomment to display order of killing\n    %disp(arrPeople)                                                          \u00a0% Uncomment to display current status of people\nend\n\nindAlive = find(arrPeople);\n\nend\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":3780}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction towerOfHanoi(n,A,C,B)\n    if (n~=0)\n        towerOfHanoi(n-1,A,B,C);\n        disp(sprintf('Move plate %d from tower %d to tower %d',[n A C]));\n        towerOfHanoi(n-1,B,C,A);\n    end\nend\n\n\nSample output:\ntowerOfHanoi(3,1,3,2)\nMove plate 1 from tower 1 to tower 3\nMove plate 2 from tower 1 to tower 2\nMove plate 1 from tower 3 to tower 2\nMove plate 3 from tower 1 to tower 3\nMove plate 1 from tower 2 to tower 1\nMove plate 2 from tower 2 to tower 3\nMove plate 1 from tower 1 to tower 3\n","human_summarization":"Implement a recursive solution for the Towers of Hanoi problem, based on the Python example provided in the Wikipedia entry for the Tower of Hanoi puzzle.","id":3781}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction [grayImage] = colortograyscale(inputImage)\n   grayImage = rgb2gray(inputImage);\n\n","human_summarization":"extend the data storage type to support grayscale images, define operations to convert color images to grayscale and vice versa using the specified formulas, and ensure no rounding errors cause run-time problems or distorted results when storing calculated luminance as an unsigned integer.","id":3782}
    {"lang_cluster":"MATLAB","source_code":"\n>> length('m\u00f8\u00f8se')\n\nans =\n\n     5\n\n>> numel(dec2hex('m\u00f8\u00f8se'))\n\nans =\n\n    10\n","human_summarization":"The code calculates the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. It handles Unicode code points correctly, distinguishing between actual character counts and code unit counts. It also provides the string length in graphemes if possible. The code works properly with strings encoded in UTF-16, like MATLAB does.","id":3783}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction solution = sudokuSolver(sudokuGrid)\n\n    %Define what each of the sub-boxes of the sudoku grid are by defining\n    %the start and end coordinates of each sub-box. The indecies represent\n    %the column and row of a grid coordinate on the actual sudoku grid.\n    %The contents of each cell with the same grid coordinates contain the\n    %information to determine which sub-box that grid coordinate is\n    %contained in on the sudoku grid. The array in position 1, i.e.\n    %subBoxes{row,column}(1), represents the row indecies of the subbox.\n    %The array in position 2, i.e. subBoxes{row,column}(2),represents the\n    %column indecies of the subbox.\n    \n    subBoxes(1:9,1:9) = {{(1:3),(1:3)}};\n    subBoxes(4:6,:)= {{(4:6),(1:3)}};\n    subBoxes(7:9,:)= {{(7:9),(1:3)}};\n    \n    for column = (4:6)\n        for row = (1:9) \n            subBoxes{row,column}(2)= {4:6};\n        end\n    end\n    for column = (7:9)\n        for row = (1:9) \n            subBoxes{row,column}(2)= {7:9};\n        end\n    end\n\n    %Generate a cell of arrays which contain the possible values of the\n    %sudoku grid for each cell in the grid. The possible values a specific\n    %grid coordinate can take share the same indices as the sudoku grid\n    %coordinate they represent.\n    %For example sudokuGrid(m,n) can be possibly filled in by the\n    %values stored in the array at possibleValues(m,n).\n    possibleValues(1:9,1:9) = { (1:9) };\n    \n    %Filter the possibleValues so that no entry exists for coordinates that\n    %have already been filled in. This will replace any array with an empty\n    %array in the possibleValues cell matrix at the coordinates of a grid\n    %already filled in the sudoku grid.\n    possibleValues( ~isnan(sudokuGrid) )={[]};\n    \n    %Iterate through each grid coordinate and filter out the possible\n    %values for that grid point that aren't alowed by the rules given the\n    %current values that are filled in. Or, if there is only one possible\n    %value for the current coordinate, fill it in.\n    \n    solution = sudokuGrid; %so the original sudoku input isn't modified\n    memory = 0; %contains the previous iterations possibleValues\n    dontStop = true; %stops the while loop when nothing else can be reasoned about the sudoku\n    \n    while( dontStop )\n \n%% Process of elimination deduction method\n\n        while( ~isequal(possibleValues,memory) ) %Stops using the process of elimination deduction method when this deduction rule stops working\n\n            memory = possibleValues; %Copies the current possibleValues into memory, for the above conditional on the next iteration.\n\n            %Iterate through everything\n            for row = (1:9) \n                for column = (1:9)\n\n                    if isnan( solution(row,column) ) %If grid coordinate hasn't been filled in, try to determine it's value.\n\n                        %Look at column to see what values have already\n                        %been filled in and thus the current grid\n                        %coordinate can't be\n                        removableValues = solution( ~isnan(solution(:,column)),column );\n\n                        %If there are any values that have been assigned to\n                        %other cells in the same column, filter those out\n                        %of the current cell's possiblValues\n                        if ~isempty(removableValues)\n                            for m = ( 1:numel(removableValues) )\n                                possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];\n                            end\n                        end\n\n                        %If the current grid coordinate can only atain one\n                        %possible value, assign it that value\n                        if numel( possibleValues{row,column} ) == 1\n                            solution(row,column) = possibleValues{row,column};\n                            possibleValues(row,column)={[]};\n                        end\n                    end  %end if\n\n                    if isnan( solution(row,column) ) %If grid coordinate hasn't been filled in, try to determine it's value. \n\n                        %Look at row to see what values have already\n                        %been filled in and thus the current grid\n                        %coordinate can't be\n                        removableValues = solution( row,~isnan(solution(row,:)) );\n\n                        %If there are any values that have been assigned to\n                        %other cells in the same row, filter those out\n                        %of the current cell's possiblValues\n                        if ~isempty(removableValues)\n                            for m = ( 1:numel(removableValues) )\n                                possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];\n                            end\n                        end\n                        \n                        %If the current grid coordinate can only atain one\n                        %possible value, assign it that value\n                        if numel( possibleValues{row,column} ) == 1\n                            solution(row,column) = possibleValues{row,column};\n                            possibleValues(row,column)={[]};\n                        end\n                    end %end if\n\n                    if isnan( solution(row,column) ) %If grid coordinate hasn't been filled in, try to determine it's value. \n                        \n                        %Look at sub-box to see if any possible values can be\n                        %filtered out. First pull the boundaries of the sub-box\n                        %containing the current array coordinate           \n                        currentBoxBoundaries=subBoxes{row,column};\n\n                        %Then pull the sub-boxes values out of the solution\n                        box = solution(currentBoxBoundaries{:});\n\n                        %Look at sub-box to see what values have already\n                        %been filled in and thus the current grid\n                        %coordinate can't be\n                        removableValues = box( ~isnan(box) );\n\n                        %If there are any values that have been assigned to\n                        %other cells in the same sub-box, filter those out\n                        %of the current cell's possiblValues\n                        if ~isempty(removableValues)\n                            for m = ( 1:numel(removableValues) )\n                                possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];\n                            end\n                        end\n                        \n                        %If the current grid coordinate can only atain one\n                        %possible value, assign it that value\n                        if numel( possibleValues{row,column} ) == 1\n                            solution(row,column) = possibleValues{row,column};\n                            possibleValues(row,column)={[]};\n                        end\n                    end %end if\n                    \n                end %end for column\n            end %end for row\n        end %stop process of elimination\n        \n%% Check that there are no contradictions in the solved grid coordinates.\n        \n        %Check that each row at most contains one of each of the integers\n        %from 1 to 9\n        if ~isempty( find( histc( solution,(1:9),1 )>1 ) )\n            solution = false;\n            return\n        end\n        \n        %Check that each column at most contains one of each of the integers\n        %from 1 to 9\n        if ~isempty( find( histc( solution,(1:9),2 )>1 ) )\n            solution = false;\n            return\n        end\n        \n        %Check that each sub-box at most contains one of each of the integers\n        %from 1 to 9\n        subBoxBins = zeros(9,9);\n        counter = 0;\n        for row = [2 5 8]\n            for column = [2 5 8]\n                counter = counter +1;\n                \n                %because the sub-boxes are extracted as square matricies,\n                %we need to reshape them into row vectors so all of the \n                %boxes can be input into histc simultaneously\n                subBoxBins(counter,:) = reshape( solution(subBoxes{row,column}{:}),1,9 ); \n            end\n        end\n        if ~isempty( find( histc( subBoxBins,(1:9),2 )>1 ) )\n            solution = false;\n            return\n        end\n                \n        %Check to make sure there are no grid coordinates that are not\n        %filled in and have no possible values.\n        \n        [rowStack,columnStack] = find(isnan(solution)); %extracts the indicies of the unsolved grid coordinates\n        if (numel(rowStack) > 0)\n            \n            for counter = (1:numel(rowStack))\n                if isempty(possibleValues{rowStack(counter),columnStack(counter)})\n                    solution = false;\n                    return\n                end  \n            end\n        \n        %if there are no more grid coordinates to be filed in then the\n        %sudoku is solved and we can return the solution without further \n        %computation\n        elseif (numel(rowStack) == 0)\n            return\n        end   \n        \n%% Use the unique relative compliment of sets deduction method\n\n        %Because no more information can be determined by the process of\n        %ellimination we have to try a new method of reasoning. Now we will\n        %look at the possible values a cell can take. If there is a value that\n        %that grid coordinate can take but no other coordinates in the same row,\n        %column or sub-box can take that value then we assign that coordinate\n        %that value.\n\n        keepGoing = true; %signals to keep applying rules to the current grid-coordinate because it hasn't been solved using previous rules\n        dontStop = false; %if this method doesn't figure anything out, this will terminate the top level while loop\n        \n        [rowStack,columnStack] = find(isnan(solution)); %This will also take care of the case where the sudoku is solved\n        counter = 0; %makes sure the loop terminates when there are no more cells to consider\n        \n        while( keepGoing && (counter < numel(rowStack)) ) %stop this method of reasoning when the value of one of the cells has been determined and return to the process of elimination method\n        \n            counter = counter + 1;\n            \n            row = rowStack(counter);\n            column = columnStack(counter);\n            \n            gridPossibles = [possibleValues{row,column}];\n            \n            coords = (1:9);\n            coords(column) = [];\n            rowPossibles = [possibleValues{row,coords}]; %extract possible values for everything in the same row except the current grid coordinate\n            \n            totalMatches = zeros( numel(gridPossibles),1 ); %preallocate for speed\n            \n            %count how many times a possible value for the current cell\n            %appears as a possible value for the cells in the same row\n            for n = ( 1:numel(gridPossibles) )\n                totalMatches(n) = sum( (rowPossibles == gridPossibles(n)) ); \n            end\n            \n            %remove any possible values for the current cell that have\n            %matches in other cells\n            gridPossibles = gridPossibles(totalMatches==0);\n            \n            %if there is only one possible value that the current cell can\n            %take that aren't shared by other cells, assign that value to\n            %the current cell.\n            if numel(gridPossibles) == 1\n                \n                solution(row,column) = gridPossibles;\n                possibleValues(row,column)={[]};\n                keepGoing = false; %stop this method of deduction and return to the process of elimination\n                dontStop = true; %keep the top level loop going\n                \n            end\n            \n            if(keepGoing) %do the same as above but for the current cell's column\n\n                gridPossibles = [possibleValues{row,column}];\n                \n                coords = (1:9);\n                coords(row) = [];\n                columnPossibles = [possibleValues{coords,column}];\n\n                totalMatches = zeros( numel(gridPossibles),1 );\n                for n = ( 1:numel(gridPossibles) )\n                    totalMatches(n) = sum( (columnPossibles == gridPossibles(n)) );\n                end\n\n                gridPossibles = gridPossibles(totalMatches==0);\n\n                if numel(gridPossibles) == 1\n\n                    solution(row,column) = gridPossibles;\n                    possibleValues(row,column)={[]};\n                    keepGoing = false;\n                    dontStop = true;\n\n                end\n            end\n            \n            if(keepGoing) %do the same as above but for the current cell's sub-box\n\n                gridPossibles = [possibleValues{row,column}];\n                \n                currentBoxBoundaries = subBoxes{row,column};\n                subBoxPossibles = [];\n                for m = currentBoxBoundaries{1}\n                    for n = currentBoxBoundaries{2}\n                        if ~((m == row) && (n == column))\n                            subBoxPossibles = [subBoxPossibles possibleValues{m,n}];\n                        end\n                    end\n                end\n\n                totalMatches = zeros( numel(gridPossibles),1 );\n                for n = ( 1:numel(gridPossibles) )\n                    totalMatches(n) = sum( (subBoxPossibles == gridPossibles(n)) );\n                end\n\n                gridPossibles = gridPossibles(totalMatches==0);\n\n                if numel(gridPossibles) == 1\n\n                    solution(row,column) = gridPossibles;\n                    possibleValues(row,column)={[]};\n                    keepGoing = false;\n                    dontStop = true;\n\n                end\n            end %end \n            \n        end %end  set comliment rule while loop \n    end %end top-level while loop\n\n%% Depth-first search of the solution tree\n\n    %There is no more reasoning that can solve the puzzle so now it is time\n    %for a depth-first search of the possible answers, basically\n    %guess-and-check. This is implimented recursively.\n    \n    [rowStack,columnStack] = find(isnan(solution)); %Get all of the unsolved cells\n    \n    if (numel(rowStack) > 0) %If all of the above stuff terminates then there will be at least one grid coordinate not filled in\n                \n        %Treat the rowStack and columnStack like stacks, and pop the top\n        %value off the stack to act as the current node whose\n        %possibleValues to search through, then assign the possible values\n        %of that grid coordinate to a variable that holds that values to\n        %search through\n        searchTreeNodes = possibleValues{rowStack(1),columnStack(1)}; \n        \n        keepSearching = true; %used to continue the search\n        counter = 0; %counts the amount of possible values searched for the current node\n        tempSolution = solution; %used so that the solution is not overriden until a solution hase been found\n        \n        while( keepSearching && (counter < numel(searchTreeNodes)) ) %stop recursing if we run out of possible values for the current node\n        \n            counter = counter + 1;\n            tempSolution(rowStack(1),columnStack(1)) = searchTreeNodes(counter); %assign a possible value to the current node in the tree\n            tempSolution = sudokuSolver(tempSolution); %recursively call the solver with the current guess value for the current grid coordinate           \n            \n            if ~islogical(tempSolution) %if tempSolution is not a boolean but a valid sudoku stop recursing and set solution to tempSolution\n               keepSearching = false;\n               solution = tempSolution;\n            elseif counter == numel(searchTreeNodes) %if we have run out of guesses for the current node, stop recursing and return a value of \"false\" for the solution\n               solution = false;\n            else %reset tempSolution to the current state of the board and try the next guess for the possible value of the current cell\n               tempSolution = solution;\n            end\n            \n        end %end recursion\n    end  %end if \n    \n%% End of program\nend %end sudokuSolver\n\n\nsudoku = [NaN   NaN   NaN   NaN     8     3     9   NaN   NaN\n     1   NaN   NaN   NaN   NaN   NaN   NaN     3   NaN\n   NaN   NaN     4   NaN   NaN   NaN   NaN     7   NaN\n   NaN     4     2   NaN     3   NaN   NaN   NaN   NaN\n     6   NaN   NaN   NaN   NaN   NaN   NaN   NaN     4\n   NaN   NaN   NaN   NaN     7   NaN   NaN     1   NaN\n   NaN     2   NaN   NaN   NaN   NaN   NaN   NaN   NaN\n   NaN     8   NaN   NaN   NaN     9     2   NaN   NaN\n   NaN   NaN   NaN     2     5   NaN   NaN   NaN     6]\n\n\nsolution =\n\n     7     6     5     4     8     3     9     2     1\n     1     9     8     7     2     6     4     3     5\n     2     3     4     9     1     5     6     7     8\n     8     4     2     5     3     1     7     6     9\n     6     1     7     8     9     2     3     5     4\n     3     5     9     6     7     4     8     1     2\n     9     2     6     1     4     7     5     8     3\n     5     8     1     3     6     9     2     4     7\n     4     7     3     2     5     8     1     9     6\n\n","human_summarization":"implement a Sudoku solver that uses a recursive, depth-first search to fill in a partially completed 9x9 Sudoku grid. The solver prunes the search tree using logical deduction rules. It can solve complex puzzles in about a minute. The code is structured in blocks that could be refactored into separate functions or a Sudoku class for improved readability and efficiency. The code should be saved in a file named \"sudokuSolver.m\". It takes a grid with empty cells represented as NaN as input and outputs the solved Sudoku in a human-readable format.","id":3784}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction list = knuthShuffle(list)\n\n    for i = (numel(list):-1:2)  \n        \n        j = floor(i*rand(1) + 1); %Generate random int between 1 and i\n        \n        %Swap element i with element j.\n        list([j i]) = list([i j]);    \n    end\nend\n\n\nfunction list = randSort(list)\n    \n    list = list( randperm(numel(list)) );\n    \nend\n\n","human_summarization":"implement the Knuth shuffle algorithm, also known as the Fisher-Yates shuffle. This algorithm randomly shuffles the elements of an array in-place, starting from the last index down to the first. It can be modified to return a new array or to iterate from left to right if necessary. The algorithm is not vectorizable using built-in MATLAB functions. An alternate version of the algorithm is also mentioned which operates similarly, saves space, and can be implemented in-line without a function call.","id":3785}
    {"lang_cluster":"MATLAB","source_code":"\nfunction [gcdValue] = greatestcommondivisor(integer1, integer2)\n   gcdValue = gcd(integer1, integer2);\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":3786}
    {"lang_cluster":"MATLAB","source_code":"\n  function r = isnum(a)\n    r = ~isnan(str2double(a))\n  end \n\n% tests\ndisp(isnum(123)) % 1\ndisp(isnum(\"123\")) % 1\ndisp(isnum(\"foo123\")) % 0\ndisp(isnum(\"123bar\")) % 0\ndisp(isnum(\"3.1415\")) % 1\n\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":3787}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction trigExample(angleDegrees)\n\n    angleRadians = angleDegrees * (pi\/180);\n    \n    disp(sprintf('sin(%f)= %f\\nasin(%f)= %f',[angleRadians sin(angleRadians) sin(angleRadians) asin(sin(angleRadians))]));\n    disp(sprintf('sind(%f)= %f\\narcsind(%f)= %f',[angleDegrees sind(angleDegrees) sind(angleDegrees) asind(sind(angleDegrees))]));\n    disp('-----------------------');\n    disp(sprintf('cos(%f)= %f\\nacos(%f)= %f',[angleRadians cos(angleRadians) cos(angleRadians) acos(cos(angleRadians))]));\n    disp(sprintf('cosd(%f)= %f\\narccosd(%f)= %f',[angleDegrees cosd(angleDegrees) cosd(angleDegrees) acosd(cosd(angleDegrees))]));\n    disp('-----------------------');\n    disp(sprintf('tan(%f)= %f\\natan(%f)= %f',[angleRadians tan(angleRadians) tan(angleRadians) atan(tan(angleRadians))]));\n    disp(sprintf('tand(%f)= %f\\narctand(%f)= %f',[angleDegrees tand(angleDegrees) tand(angleDegrees) atand(tand(angleDegrees))]));\nend\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions such as sine, cosine, tangent, and their inverses in a specific programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the same angle is used for each radian\/degree pair. For inverse functions, the same number is converted to radians and degrees. If the language lacks built-in trigonometric functions, the code provides custom functions based on known approximations or identities.","id":3788}
    {"lang_cluster":"MATLAB","source_code":"\n\nWorks with: MATLAB version 7.6 (R2008a) and later\nfunction sigintHandle\n    k = 1;\n    tic\n    catchObj = onCleanup(@toc);\n    while true\n        pause(0.5)\n        fprintf('%d\\n', k)\n        k = k+1;\n    end\nend\n\n\n","human_summarization":"The code outputs an integer every half second. It handles SIGINT or SIGQUIT signals, often triggered by user's ctrl-C or ctrl-\\ inputs, by stopping the integer output, displaying the program's runtime, and then terminating the program. In MATLAB versions 6.5 (R13) and newer, CTRL+C can't be caught with a try-catch block, but the onCleanup() function, introduced in version 7.6 (R2008a), is used to ensure the function executes regardless of how the function ends.","id":3789}
    {"lang_cluster":"MATLAB","source_code":"\nfunction numStr = incrementNumStr(numStr)\n    numStr = num2str(str2double(numStr) + 1);\nend\n\n","human_summarization":"\"Increments a given numerical string.\"","id":3790}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction medianValue = findmedian(setOfValues)    \n   medianValue = median(setOfValues);\nend\n\n","human_summarization":"\"Calculates the median of a vector of floating-point numbers using the selection algorithm. If the vector has an even number of elements, the function returns the average of the two middle values. It does not handle the case of an empty vector.\"","id":3791}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction fizzBuzz() \n    for i = (1:100)\n        if mod(i,15) == 0\n           fprintf('FizzBuzz ')\n        elseif mod(i,3) == 0\n           fprintf('Fizz ')\n        elseif mod(i,5) == 0\n           fprintf('Buzz ')\n        else\n           fprintf('%i ',i)) \n        end\n    end\n    fprintf('\\n');    \nend\n\nfunction out = fizzbuzzS()\n\tnums = [3, 5];\n\twords = {'fizz', 'buzz'};\n\tfor (n=1:100)\n\t\ttempstr = '';\n\t\tfor (i = 1:2)\n\t\t\tif mod(n,nums(i))==0\n\t\t\t\ttempstr = [tempstr,  words{i}];\n\t\t\tend\n\t\tend\n\t\tif length(tempstr) == 0 \n\t\t\tdisp(n);\n\t\telse \n\t\t\tdisp(tempstr);\n\t\tend\n\tend\nend\n\nx            = string(1:100);\nx(3:3:$)     = 'Fizz';\nx(5:5:$)     = 'Buzz';\nx(3*5:3*5:$) = 'FizzBuzz'\n","human_summarization":"The code prints integers from 1 to 100. For multiples of three, it prints 'Fizz' instead of the number, for multiples of five, it prints 'Buzz' instead of the number, and for multiples of both three and five, it prints 'FizzBuzz' instead of the number. It also includes a more extendible version that uses disp() to print the output.","id":3792}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction [theSet,realAxis,imaginaryAxis] = mandelbrotSet(start,gridSpacing,last,maxIteration)\n\n    %Define the escape time algorithm\n    function escapeTime = escapeTimeAlgorithm(z0)\n        \n        escapeTime = 0;\n        z = 0;\n        \n        while( (abs(z)<=2) && (escapeTime < maxIteration) )\n            z = (z + z0)^2;            \n            escapeTime = escapeTime + 1;\n        end\n                \n    end\n    \n    %Define the imaginary axis\n    imaginaryAxis = (imag(start):imag(gridSpacing):imag(last));\n    \n    %Define the real axis\n    realAxis = (real(start):real(gridSpacing):real(last));\n    \n    %Construct the complex plane from the real and imaginary axes\n    complexPlane = meshgrid(realAxis,imaginaryAxis) + meshgrid(imaginaryAxis(end:-1:1),realAxis)'.*i;\n    \n    %Apply the escape time algorithm to each point in the complex plane \n    theSet = arrayfun(@escapeTimeAlgorithm, complexPlane);\n    \n\n    %Draw the set\n    pcolor(realAxis,imaginaryAxis,theSet);\n    shading flat;\n    \nend\n\n\nlower left hand corner of the complex plane from which to start the image,  \n  the grid spacing in both the imaginary and real directions,\n  the upper right hand corner of the complex plane at which to end the image and\n  the maximum iterations for the escape time algorithm.\n\n\n\nLower Left Corner: -2.05-1.2i\n  Grid Spacing: 0.004+0.0004i\n  Upper Right Corner: 0.45+1.2i\n  Maximum Iterations: 500\n\n\nmandelbrotSet(-2.05-1.2i,0.004+0.0004i,0.45+1.2i,500);\n","human_summarization":"generate and draw the Mandelbrot set using the escape time algorithm. The function requires high memory for high-resolution computations. The code can be simplified through vectorization but may become obfuscated.","id":3793}
    {"lang_cluster":"MATLAB","source_code":"\n\n>> array = [1 2 3;4 5 6;7 8 9]\n\narray =\n\n     1     2     3\n     4     5     6\n     7     8     9\n\n>> sum(array,1)\n\nans =\n\n    12    15    18\n\n>> sum(array,2)\n\nans =\n\n     6\n    15\n    24\n\n>> prod(array,1)\n\nans =\n\n    28    80   162\n\n>> prod(array,2)\n\nans =\n\n     6\n   120\n   504\n\n","human_summarization":"Computes the sum and product of an array of integers using MATLAB's built-in \"sum(array)\" and \"prod(array)\" functions.","id":3794}
    {"lang_cluster":"MATLAB","source_code":"\nstring1 = 'Hello';\nstring2 = string1;\n\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":3795}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction Fn = female(n)\n\n    if n == 0\n        Fn = 1;\n        return\n    end\n    \n    Fn = n - male(female(n-1));\nend\n\n\nfunction Mn = male(n)\n    \n    if n == 0\n        Mn = 0;\n        return\n    end\n    \n    Mn = n - female(male(n-1));\nend\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions are defined such that the Female function at n is equal to n minus the Male function at the Female function at n-1, and the Male function at n is equal to n minus the Female function at the Male function at n-1. The base cases for Female and Male functions are 1 and 0 respectively.","id":3796}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction mid = binarySearchRec(list,value,low,high)\n\n    if( high < low )\n        mid = [];\n        return\n    end\n    \n    mid = floor((low + high)\/2);\n    \n    if( list(mid) > value )\n        mid = binarySearchRec(list,value,low,mid-1);\n        return\n    elseif( list(mid) < value )\n        mid = binarySearchRec(list,value,mid+1,high);\n        return\n    else\n        return\n    end\n        \nend\n\n>> binarySearchRec([1 2 3 4 5 6 6.5 7 8 9 11 18],6.5,1,numel([1 2 3 4 5 6 6.5 7 8 9 11 18]))\n\nans =\n\n     7\n\nfunction mid = binarySearchIter(list,value)\n\n    low = 1;\n    high = numel(list) - 1;\n    \n    while( low <= high )\n        mid = floor((low + high)\/2);\n    \n        if( list(mid) > value )\n            high = mid - 1;\n        elseif( list(mid) < value )\n        \tlow = mid + 1;\n        else\n            return\n        end\n    end\n    \n    mid = [];\n            \nend\n\n>> binarySearchIter([1 2 3 4 5 6 6.5 7 8 9 11 18],6.5)\n\nans =\n\n     7\n","human_summarization":"The code implements a binary search algorithm on a sorted integer array. It takes a starting point, an ending point, and a \"secret value\" as input. The algorithm divides the range of values into halves and continues to narrow down the search field until the secret value is found. The implementation can be either recursive or iterative. The code also handles multiple values equal to the given value and indicates whether the element was found or not. If the number was found in the array, the index is printed. It also includes measures to prevent overflow bugs.","id":3797}
    {"lang_cluster":"MATLAB","source_code":"\n\n%This is a numerical simulation of a pendulum with a massless pivot arm.\n\n%% User Defined Parameters\n%Define external parameters\ng = -9.8;\ndeltaTime = 1\/50; %Decreasing this will increase simulation accuracy\nendTime = 16;\n\n%Define pendulum\nrodPivotPoint = [2 2]; %rectangular coordinates\nrodLength = 1;\nmass = 1; %of the bob\nradius = .2; %of the bob\ntheta = 45; %degrees, defines initial position of the bob\nvelocity = [0 0]; %cylindrical coordinates; first entry is radial velocity,\n                  %second entry is angular velocity\n\n%% Simulation\nassert(radius < rodLength,'Pendulum bob radius must be less than the length of the rod.');\n\nposition = rodPivotPoint - (rodLength*[-sind(theta) cosd(theta)]); %in rectangular coordinates\n\n%Generate graphics, render pendulum\nfigure;\naxesHandle = gca;\nxlim(axesHandle, [(rodPivotPoint(1) - rodLength - radius) (rodPivotPoint(1) + rodLength + radius)] );\nylim(axesHandle, [(rodPivotPoint(2) - rodLength - radius) (rodPivotPoint(2) + rodLength + radius)] );\n\nrectHandle = rectangle('Position',[(position - radius\/2) radius radius],...\n    'Curvature',[1,1],'FaceColor','g'); %Pendulum bob\nhold on\nplot(rodPivotPoint(1),rodPivotPoint(2),'^'); %pendulum pivot\nlineHandle = line([rodPivotPoint(1) position(1)],...\n    [rodPivotPoint(2) position(2)]); %pendulum rod\nhold off\n\n%Run simulation, all calculations are performed in cylindrical coordinates\nfor time = (deltaTime:deltaTime:endTime)\n        \n    drawnow; %Forces MATLAB to render the pendulum\n    \n    %Find total force\n    gravitationalForceCylindrical = [mass*g*cosd(theta) mass*g*sind(theta)];\n    \n    %This code is just incase you want to add more forces,e.g friction\n    totalForce = gravitationalForceCylindrical; \n    \n    %If the rod isn't massless or is a spring, etc., modify this line\n    %accordingly\n    rodForce = [-totalForce(1) 0]; %cylindrical coordinates\n    \n    totalForce = totalForce + rodForce;\n    \n    acceleration = totalForce \/ mass; %F = ma\n    velocity = velocity + acceleration * deltaTime;\n    rodLength = rodLength + velocity(1) * deltaTime;\n    theta = theta + velocity(2) * deltaTime; % Attention!! Mistake here. \n    % Velocity needs to be divided by pendulum length and scaled to degrees:\n    % theta = theta + velocity(2) * deltaTime\/rodLength\/pi*180;\n    \n    position = rodPivotPoint - (rodLength*[-sind(theta) cosd(theta)]);\n    \n    %Update figure with new position info\n    set(rectHandle,'Position',[(position - radius\/2) radius radius]);\n    set(lineHandle,'XData',[rodPivotPoint(1) position(1)],'YData',...\n        [rodPivotPoint(2) position(2)]);\n\nend\n\n","human_summarization":"simulate and animate a simple gravity pendulum model.","id":3798}
    {"lang_cluster":"MATLAB","source_code":"\nfunction answer = nthRoot(number,root)\n\n    format long\n\n    answer = number \/ root;\n    guess = number;\n    \n    while not(guess == answer)\n       guess = answer;\n       answer = (1\/root)*( ((root - 1)*guess) + ( number\/(guess^(root - 1)) ) ); \n    end\n\nend\n\n\n>> nthRoot(2,2)\n\nans =\n\n   1.414213562373095\n\n","human_summarization":"implement the principal nth root computation of a positive real number A.","id":3799}
    {"lang_cluster":"MATLAB","source_code":"\n\n[failed,hostname] = system('hostname')\n\n","human_summarization":"Implement a built-in MATLAB function to retrieve the hostname of the system where the routine is running. The function returns a Boolean 'failed' which is false if the command sent to the OS is successful, and a string 'hostname' containing the system's hostname if the external command hostname exists.","id":3800}
    {"lang_cluster":"MATLAB","source_code":"\nn = 3;\nc = string('#');\nfor k = 1 : n\n  c = [c + c + c, c + c.replace('#', ' ') + c, c + c + c];\nend\ndisp(c.join(char(10)))\n\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":3801}
    {"lang_cluster":"MATLAB","source_code":"\nsize = 256;\n[x,y] = meshgrid([0:size-1]);\n\nc = bitxor(x,y);\n\ncolormap bone(size);\nimage(c);\naxis equal;\n\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":3802}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction pi_str = piSpigot(N)\n% Return N digits of pi using Gibbons's first spigot algorithm.\n% If N is omitted, the digits are printed ad infinitum.\n% Uses the expansion\n%   pi = sum_{i=0} (i!)^2 2^{i+1} \/(2i+1)!\n%      = 2 + 1\/3 * ( 2 + 2\/5 * (2 + 3\/7 * ( 2 + 4\/9 * ( ..... )))))\n%      = (2 + 1\/3 *)(2 + 2\/5 *)(2 + 3\/7 *)...\n% where the terms in the last expression represent Linear Fractional \n% Transforms (LFTs).\n%\n% Requires the Variable Precision Integer (vpi) Toolbox\n%\n% Reference:\n% \"Unbounded Spigot Algorithms for the Digits of Pi\" by J. Gibbons, 2004\n% American Mathematical Monthly, vol. 113. \nif nargin < 1\n    N = Inf;\n    lineLength = 50;\nelse\n    pi_str = repmat(' ',1,N);\nend\n\nq = vpi(1);\nr = vpi(0);\nt = vpi(1);\nk = 1; % If printing more than 3E15 digits, use k = vpi(1);\n\ni = 1;\nfirst_digit = true;\nwhile i <= N\n    threeQplusR = 3*q + r;\n    n = double(threeQplusR \/ t);\n    if q+threeQplusR < (n+1)*t\n        d = num2str(n);\n        if isinf(N)\n            fprintf(1,'%s', d);\n            if first_digit\n                fprintf(1,'.');\n                first_digit = false;\n                i = i+1;\n            end\n            if i == lineLength \n                fprintf(1,'\\n');\n                i = 0;\n            end\n        else\n            pi_str(i) = d;\n        end\n        q = 10*q;\n        r = 10*(r-n*t);\n        i = i + 1;\n    else\n        t = (2*k+1)*t;\n        r = (4*k+2)*q + (2*k+1)*r;\n        q = k*q;\n        k = k + 1;\n    end\nend\nend\n\n>> piSpigot\n3.141592653589793238462643383279502884197169399375\n10582097494459230781640628620899862803482534211706\n79821480865132823066470938446095505822317253594081\n28481117450284102701938521105559644622948954930381\n96442881097566593344612847564823378678316527120190\n91456485669234603486104543266482133936072602491412\n\n","human_summarization":"The code continually calculates and outputs the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. It requires the Variable Precision Integer (vpi) Toolbox and is related to the task of calculating Pi using the Arithmetic-geometric mean.","id":3803}
    {"lang_cluster":"MATLAB","source_code":"\nfunction A = ackermannFunction(m,n)\n    if m == 0\n        A = n+1;\n    elseif (m > 0) && (n == 0)\n        A = ackermannFunction(m-1,1);\n    else\n        A = ackermannFunction( m-1,ackermannFunction(m,n-1) );\n    end\nend\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":3804}
    {"lang_cluster":"MATLAB","source_code":"\n\nn=8;\nsolutions=[[]];\nv = 1:n;\nP = perms(v);\nfor i=1:length(P)\n    for j=1:n\n        sub(j)=P(i,j)-j;\n        add(j)=P(i,j)+j;\n    end\n    if n==length(unique(sub)) && n==length(unique(add))\n        solutions(end+1,:)=P(i,:);\n    end\nend\n\nfprintf('Number of solutions with %i queens: %i', n, length(solutions));\n\nif ~isempty(solutions)\n    %Print first possible solution\n    board=solutions(1,:);\n    s = repmat('-',n);\n    for k=1:length(board)\n        s(k,board(k)) = 'Q';\n    end\n    s\nend\n\n\n","human_summarization":"\"Implement a solution to solve the N-queens puzzle, including the eight queens puzzle, using a permutations based approach inspired by Raymond Hettinger's Python solution. The code also provides the number of solutions for small values of N as per OEIS: A000170.\"","id":3805}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction [morseText,morseSound] = text2morse(string,playSound)\n\n%% Translate AlphaNumeric Text to Morse Text\n\n    string = lower(string);\n    \n    %Defined such that the ascii code of the characters in the string map\n    %to the indecies of the dictionary.\n    morseDictionary = {{' ',' '},{'',''},{'',''},{'',''},...\n                       {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},...\n                       {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},...\n                       {'0','-----'},{'1','.----'},{'2','..---'},{'3','...--'},...\n                       {'4','....-'},{'5','.....'},{'6','-....'},{'7','--...'},...\n                       {'8','---..'},{'9','----.'},...\n                       {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},...\n                       {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},...\n                       {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},...\n                       {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},...\n                       {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},...\n                       {'',''},{'',''},{'',''},{'',''},{'',''},{'',''},...\n                       {'',''},{'',''},{'',''},...\n                       {'a','.-'},{'b','-...'},{'c','-.-.'},{'d','-..'},...\n                       {'e','.'},{'f','..-.'},{'g','--.'},{'h','....'},...\n                       {'i','..'},{'j','.---'},{'k','-.-'},{'l','.-..'},...\n                       {'m','--'},{'n','-.'},{'o','---'},{'p','.--.'},...\n                       {'q','--.-'},{'r','.-.'},{'s','...'},{'t','-'},...\n                       {'u','..-'},{'v','...-'},{'w','.--'},{'x','-..-'},...\n                       {'y','-.--'},{'z','--..'}};\n    \n    %Iterates through each letter in the string and converts it to morse\n    %code\n    morseText = arrayfun(@(x)[morseDictionary{x}{2} '|'],(string - 31),'UniformOutput',false);\n    \n    %The output of the previous operation is a cell array, we want it to be\n    %a string. This line accomplishes that.\n    morseText = cell2mat(morseText);\n    \n    morseText(end) = []; %delete extra pipe\n    \n%% Translate Morse Text to Morse Audio\n    \n    %Generate the tones for each element of the code\n    SamplingFrequency = 8192; %Hz\n    ditLength = .1; %s\n    dit = (0:1\/SamplingFrequency:ditLength);\n    dah = (0:1\/SamplingFrequency:3*ditLength);\n    dit = sin(3520*dit);\n    dah = sin(3520*dah);\n    silent = zeros(1,length(dit));\n\n    %A dictionary of the audio components of each symbol\n    morseTiming = {{'.',[dit silent]},{'-',[dah silent]},{'|',[silent silent]},{' ',[silent silent]}};\n    morseSound = [];\n\n    for i = (1:length(morseText))\n\n        %Iterate through each cell in the morseTiming cell array and\n        %find which timing sequence corresponds to the current morse\n        %text symbol.\n        cellNum = find(cellfun(@(x)(x{1}==morseText(i)),morseTiming));\n\n        morseSound = [morseSound morseTiming{cellNum}{2}];\n    end\n\n    morseSound(end-length(silent):end) = []; %Delete the extra silent tone at the end\n    \n    if(playSound)\n        sound(morseSound,SamplingFrequency); %Play sound\n    end\n    \nend %text2morse\n\n\n","human_summarization":"The code converts a given string into Morse code and outputs it as audible signals through an audio device such as a PC speaker. It ignores or indicates any characters not defined in the Morse code standard.","id":3806}
    {"lang_cluster":"MATLAB","source_code":"\n\nfunction digest = md5(message)\n    % digest = md5(message)\n    %  Compute the MD5 digest of the message, as a hexadecimal digest.\n\n    % Follow the MD5 algorithm from RFC 1321 [1] and Wikipedia [2].\n    %  [1] http:\/\/tools.ietf.org\/html\/rfc1321\n    %  [2] http:\/\/en.wikipedia.org\/wiki\/MD5\n\n    % m is the modulus for 32-bit unsigned arithmetic.\n    m = 2 ^ 32;\n\n    % s is the shift table for circshift(). Each shift is negative\n    % because it is a left shift.\n    s = [-7, -12, -17, -22\n         -5,  -9, -14, -20\n         -4, -11, -16, -23\n         -6, -10, -15, -21];\n\n    % t is the sine table. Each sine is a 32-bit integer, unsigned.\n    t = floor(abs(sin(1:64)) .* m);\n\n    % Initialize the hash, as a row vector of 32-bit integers.\n    digest = [hex2dec('67452301') ...\n              hex2dec('EFCDAB89') ...\n              hex2dec('98BADCFE') ...\n              hex2dec('10325476')];\n\n    % If message contains characters, convert them to ASCII values.\n    message = double(message);\n    bytelen = numel(message);\n\n    % Pad the message by appending a 1, then appending enough 0s to make\n    % the bit length congruent to 448 mod 512. Because we have bytes, we\n    % append 128 '10000000', then append enough 0s '00000000's to make\n    % the byte length congruent to 56 mod 64.\n    message = [message, 128, zeros(1, mod(55 - bytelen, 64))];\n\n    % Convert the message to 32-bit integers, little endian.\n    % For little endian, first byte is least significant byte.\n    message = reshape(message, 4, numel(message) \/ 4);\n    message = message(1,:) + ...           \u00a0% least significant byte\n              message(2,:) * 256 + ...\n              message(3,:) * 65536 + ...\n              message(4,:) * 16777216;      % most significant byte\n\n    % Append the bit length as a 64-bit integer, little endian.\n    bitlen = bytelen * 8;\n    message = [message, mod(bitlen, m), mod(bitlen \/ m, m)];\n\n    % Process each 512-bit block. Because we have 32-bit integers, each\n    % block has 16 elements, message(k + (0:15)).\n    for k = 1:16:numel(message)\n        % Copy hash.\n        a = digest(1); b = digest(2); c = digest(3); d = digest(4);\n\n        % Do 64 operations.\n        for i = (1:64)\n            % Convert b, c, d to row vectors of bits (0s and 1s).\n            bv = dec2bin(b, 32) - '0';\n            cv = dec2bin(c, 32) - '0';\n            dv = dec2bin(d, 32) - '0';\n\n            % Find f  = mix of b, c, d.\n            %      ki = index in 0:15, to message(k + ki).\n            %      sr = row in 1:4, to s(sr,\u00a0:).\n            if i <= 16          % Round 1\n                f = (bv & cv) | (~bv & dv);\n                ki = i - 1;\n                sr = 1;\n            elseif i <= 32      % Round 2\n                f = (bv & dv) | (cv & ~dv);\n                ki = mod(5 * i - 4, 16);\n                sr = 2;\n            elseif i <= 48      % Round 3\n                f = xor(bv, xor(cv, dv));\n                ki = mod(3 * i + 2, 16);\n                sr = 3;\n            else                % Round 4\n                f = xor(cv, bv | ~dv);\n                ki = mod(7 * i - 7, 16);\n                sr = 4;\n            end\n\n            % Convert f, from row vector of bits, to 32-bit integer.\n            f = bin2dec(char(f + '0'));\n\n            % Do circular shift of sum.\n            sc = mod(i - 1, 4) + 1;\n            sum = mod(a + f + message(k + ki) + t(i), m);\n            sum = dec2bin(sum, 32);\n            sum = circshift(sum, [0, s(sr, sc)]);\n            sum = bin2dec(sum);\n\n            % Update a, b, c, d.\n            temp = d;\n            d = c;\n            c = b;\n            b = mod(b + sum, m);\n            a = temp;\n        end %for i\n\n        % Add hash of this block to hash of previous blocks.\n        digest = mod(digest + [a, b, c, d], m);\n    end %for k\n\n    % Convert hash from 32-bit integers, little endian, to bytes.\n    digest = [digest                % least significant byte\n              digest \/ 256\n              digest \/ 65536\n              digest \/ 16777216];   % most significant byte\n    digest = reshape(mod(floor(digest), 256), 1, numel(digest));\n\n    % Convert hash to hexadecimal.\n    digest = dec2hex(digest);\n    digest = reshape(transpose(digest), 1, numel(digest));\nend %md5\n\n\noctave:14> md5('Rosetta Code')\nans = CCA1BF66B09554E10F837838C3D3EFB1\n\n","human_summarization":"implement the MD5 encoding algorithm for a given string. They also validate the implementation using test values from IETF RFC 1321. The codes provide an alternative to MD5 due to its known weaknesses, suggesting SHA-256 or SHA-3 for production-grade cryptography. If a library solution is used, an implementation from scratch is also available. The codes are compatible with Octave.","id":3807}
    {"lang_cluster":"MATLAB","source_code":"\nfunction trueFalse = isPalindrome(string)\n    \n    trueFalse = all(string == fliplr(string)); %See if flipping the string produces the original string\n\n    if not(trueFalse) %If not a palindrome\n        string = lower(string); %Lower case everything\n        trueFalse = all(string == fliplr(string)); %Test again\n    end\n    \n    if not(trueFalse) %If still not a palindrome\n        string(isspace(string)) = []; %Strip all space characters out\n        trueFalse = all(string == fliplr(string)); %Test one last time\n    end\n    \nend\n\nSample Usage:\n>> isPalindrome('In girum imus nocte et consumimur igni')\n\nans =\n\n     1\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":3808}
    {"lang_cluster":"F#","source_code":"\n\ntype Stack<'a> \/\/'\/\/(workaround for syntax highlighting problem)\n  (?items) =\n  let items = defaultArg items []\n\n  member x.Push(A) = Stack(A::items)\n\n  member x.Pop() =\n    match items with\n      | x::xr ->  (x, Stack(xr))\n      | [] -> failwith \"Stack is empty.\"\n\n  member x.IsEmpty() = items = []\n\n\/\/ example usage\nlet anEmptyStack = Stack<int>()\nlet stack2 = anEmptyStack.Push(42)\nprintfn \"%A\" (stack2.IsEmpty())\nlet (x, stack3) = stack2.Pop()\nprintfn \"%d\" x\nprintfn \"%A\" (stack3.IsEmpty())\n\n","human_summarization":"implement a stack data structure that supports basic operations such as push (adding an element to the top of the stack), pop (removing the last added element from the stack), and empty (checking if the stack contains no elements). The stack follows a last in, first out (LIFO) access policy.","id":3809}
    {"lang_cluster":"F#","source_code":"\n\nlet fibonacci n\u00a0: bigint =\n  let rec f a b n =\n    match n with\n    | 0 -> a\n    | 1 -> b\n    | n -> (f b (a + b) (n - 1))\n  f (bigint 0) (bigint 1) n\n> fibonacci 100;;\nval it\u00a0: bigint = 354224848179261915075I\n\nlet rec fib = seq { yield! [0;1];\n                    for (a,b) in Seq.zip fib (Seq.skip 1 fib) -> a+b}\n\nlet fibonacci = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (0I,1I)\nfibonacci |> Seq.nth 10000\n\nopen System\nopen System.Diagnostics\nopen System.Numerics\n\n\/\/\/ Finds the highest power of two which is less than or equal to a given input.\nlet inline prevPowTwo (x\u00a0: int) =\n    let mutable n = x\n    n <- n - 1\n    n <- n ||| (n >>> 1)\n    n <- n ||| (n >>> 2)\n    n <- n ||| (n >>> 4)\n    n <- n ||| (n >>> 8)\n    n <- n ||| (n >>> 16)\n    n <- n + 1\n    match x with\n    | x when x = n -> x\n    | _ -> n\/2\n\n\/\/\/ Evaluates the nth Fibonacci number using matrix arithmetic and\n\/\/\/ exponentiation by squaring.\nlet crazyFib (n\u00a0: int) =\n    let powTwo = prevPowTwo n\n\n    \/\/\/ Applies 2n rule repeatedly until another application of the rule would\n    \/\/\/ go over the target value (or the target value has been reached).\n    let rec iter1 i q r s =\n        match i with\n        | i when i < powTwo ->\n            iter1 (i*2) (q*q + r*r) (r * (q+s)) (r*r + s*s)\n        | _ -> i, q, r, s\n\n    \/\/\/ Applies n+1 rule until the target value is reached.\n    let rec iter2 (i, q, r, s) =\n        match i with\n        | i when i < n -> \n            iter2 ((i+1), (q+r), q, r)\n        | _ -> q\n\n    match n with\n    | 0 -> 1I\n    | _ ->\n        iter1 1 1I 1I 0I\n        |> iter2\n","human_summarization":"implement a function to generate the nth Fibonacci number using either an iterative or recursive approach. The function also has an optional feature to support negative n using a straightforward inverse of the positive definition. The implementation uses a fast tail-recursive approach with F# big integer support and employs a sequence workflow for lazy evaluation. However, due to nested recursions on sequences, this approach can be slow. An alternative approach uses the sequence unfold anamorphism for better efficiency. The code also includes a method similar to the Matrix algorithm in C#, with some shortcuts and uses exponentiation by squaring for quick calculations, especially when n is a power of 2.","id":3810}
    {"lang_cluster":"F#","source_code":"\nlet lst = [1;2;3;4;5;6]\nList.filter (fun x -> x % 2 = 0) lst;;\n\nval it : int list = [2; 4; 6]\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":3811}
    {"lang_cluster":"F#","source_code":"\n[<EntryPoint>]\nlet main args =\n    let s = \"\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\"\n    let n, m  = 3, 2\n    let c = '\u516d'\n    let z = \"\u516d\u4e03\u516b\"\n\n    printfn \"%s\" (s.Substring(n, m))\n    printfn \"%s\" (s.Substring(n))\n    printfn \"%s\" (s.Substring(0, s.Length - 1))\n    printfn \"%s\" (s.Substring(s.IndexOf(c), m))\n    printfn \"%s\" (s.Substring(s.IndexOf(z), m))\n    0\n\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":3812}
    {"lang_cluster":"F#","source_code":"\n\/\/ Reverse a string. Nigel Galloway: August 14th., 2019\nlet strRev \u03b1=let N=System.Globalization.StringInfo.GetTextElementEnumerator(\u03b1)\n             List.unfold(fun n->if n then Some(N.GetTextElement(),N.MoveNext()) else None)(N.MoveNext())|>List.rev|>String.concat \"\"\n\n\nprintfn \"%s\" (strRev \"as\u20dddf\u0305\")\nprintfn \"%s\" (strRev \"Nigel\")\n\n\n","human_summarization":"The code takes a string as input and returns its reverse. It also preserves the position of Unicode combining characters in the reversed string. For instance, \"asdf\" is reversed to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":3813}
    {"lang_cluster":"F#","source_code":"\n\/\/Dijkstra's algorithm: Nigel Galloway, August 5th., 2018\n[<CustomEquality;CustomComparison>]\ntype Dijkstra<'N,'G when 'G:comparison>={toN:'N;cost:Option<'G>;fromN:'N}\n                                        override g.Equals n =match n with| :? Dijkstra<'N,'G> as n->n.cost=g.cost|_->false\n                                        override g.GetHashCode() = hash g.cost\n                                        interface System.IComparable with\n                                          member n.CompareTo g =\n                                            match g with\n                                            | :? Dijkstra<'N,'G> as n when n.cost=None -> (-1)\n                                            | :? Dijkstra<'N,'G>      when n.cost=None -> 1\n                                            | :? Dijkstra<'N,'G> as g                  -> compare n.cost g.cost\n                                            | _-> invalidArg \"n\" \"expecting type Dijkstra<'N,'G>\"\nlet inline Dijkstra N G y =\n  let rec fN l f=\n    if List.isEmpty l then f\n    else let n=List.min l\n         if n.cost=None then f else\n         fN(l|>List.choose(fun n'->if n'.toN=n.toN then None else match n.cost,n'.cost,Map.tryFind (n.toN,n'.toN) G with\n                                                                  |Some g,None,Some wg                ->Some {toN=n'.toN;cost=Some(g+wg);fromN=n.toN}\n                                                                  |Some g,Some g',Some wg when g+wg<g'->Some {toN=n'.toN;cost=Some(g+wg);fromN=n.toN}\n                                                                  |_                                  ->Some n'))((n.fromN,n.toN)::f)\n  let r = fN (N|>List.map(fun n->{toN=n;cost=(Map.tryFind(y,n)G);fromN=y})) []\n  (fun n->let rec fN z l=match List.tryFind(fun (_,g)->g=z) r with\n                         |Some(n',g') when y=n'->Some(n'::g'::l)\n                         |Some(n',g')          ->fN n' (g'::l)\n                         |_                    ->None\n          fN n [])\n\ntype Node= |A|B|C|D|E|F\nlet G=Map[((A,B),7);((A,C),9);((A,F),14);((B,C),10);((B,D),15);((C,D),11);((C,F),2);((D,E),6);((E,F),9)]\nlet paths=Dijkstra [B;C;D;E;F] G A\nprintfn \"%A\" (paths E)\nprintfn \"%A\" (paths F)\n\n\n","human_summarization":"Implement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges representing the shortest path to each reachable node. The program also interprets the output to display the shortest path from the source node to specific nodes.","id":3814}
    {"lang_cluster":"F#","source_code":"\nopen System\n\nlet add (a:double, b:double) (x:double, y:double) = (a + x, b + y)\nlet sub (a:double, b:double) (x:double, y:double) = (a - x, b - y)\nlet magSqr (a:double, b:double) = a * a + b * b\nlet mag a:double = Math.Sqrt(magSqr a)\nlet mul (a:double, b:double) c = (a * c, b * c)\nlet div2 (a:double, b:double) c = (a \/ c, b \/ c)\nlet perp (a:double, b:double) = (-b, a)\nlet norm a = div2 a (mag a)\n\nlet circlePoints p q (radius:double) =\n    let diameter = radius * 2.0\n    let pq = sub p q\n    let magPQ = mag pq\n    let midpoint = div2 (add p q) 2.0\n    let halfPQ = magPQ \/ 2.0\n    let magMidC = Math.Sqrt(Math.Abs(radius * radius - halfPQ * halfPQ))\n    let midC = mul (norm (perp pq)) magMidC\n    let center1 = add midpoint midC\n    let center2 = sub midpoint midC\n    if radius = 0.0 then None\n    else if p = q then None\n    else if diameter < magPQ then None\n    else Some (center1, center2)\n\n[<EntryPoint>]\nlet main _ = \n    printfn \"%A\" (circlePoints (0.1234, 0.9876) (0.8765, 0.2345) 2.0)\n    printfn \"%A\" (circlePoints (0.0, 2.0) (0.0, 0.0) 1.0)\n    printfn \"%A\" (circlePoints (0.1234, 0.9876) (0.1234, 0.9876) 2.0)\n    printfn \"%A\" (circlePoints (0.1234, 0.9876) (0.8765, 0.2345) 0.5)\n    printfn \"%A\" (circlePoints (0.1234, 0.9876) (0.1234, 0.1234) 0.0)\n\n    0 \/\/ return an integer exit code\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":3815}
    {"lang_cluster":"F#","source_code":"\n\/\/ Loops\/Break. Nigel Galloway: February 21st., 2022\nlet n=System.Random()\nlet rec fN g=printf \"%d \" g; if g <> 10 then fN(n.Next(20))\nfN(n.Next(20))\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":3816}
    {"lang_cluster":"F#","source_code":"\nopen System.IO\nopen System.Xml.XPath\n\nlet xml = new StringReader(\"\"\"\n<inventory title=\"OmniCorp Store #45x10^3\">\n  <section name=\"health\">\n    <item upc=\"123456789\" stock=\"12\">\n      <name>Invisibility Cream<\/name>\n      <price>14.50<\/price>\n      <description>Makes you invisible<\/description>\n    <\/item>\n    <item upc=\"445322344\" stock=\"18\">\n      <name>Levitation Salve<\/name>\n      <price>23.99<\/price>\n      <description>Levitate yourself for up to 3 hours per application<\/description>\n    <\/item>\n  <\/section>\n  <section name=\"food\">\n    <item upc=\"485672034\" stock=\"653\">\n      <name>Blork and Freen Instameal<\/name>\n      <price>4.95<\/price>\n      <description>A tasty meal in a tablet; just add water<\/description>\n    <\/item>\n    <item upc=\"132957764\" stock=\"44\">\n      <name>Grob winglets<\/name>\n      <price>3.56<\/price>\n      <description>Tender winglets of Grob. Just add water<\/description>\n    <\/item>\n  <\/section>\n<\/inventory>\n\"\"\")\n\nlet nav = XPathDocument(xml).CreateNavigator()\n\n\/\/ first \"item\"; throws if none exists\nlet item = nav.SelectSingleNode(@\"\/\/item[1]\")\n\n\/\/ apply a operation (print text value) to all price elements\nfor price in nav.Select(@\"\/\/price\") do\n    printfn \"%s\" (price.ToString())\n\n\/\/ array of all name elements\nlet names = seq { for name in nav.Select(@\"\/\/name\") do yield name } |> Seq.toArray\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":3817}
    {"lang_cluster":"F#","source_code":"\n\n[<EntryPoint>]\nlet main args =\n    \/\/ Create some sets (of int):\n    let s1 = Set.ofList [1;2;3;4;3]\n    let s2 = Set.ofArray [|3;4;5;6|]\n\n    printfn \"Some sets (of int):\"\n    printfn \"s1 = %A\" s1\n    printfn \"s2 = %A\" s2\n    printfn \"Set operations:\"\n    printfn \"2 \u2208 s1? %A\" (s1.Contains 2)\n    printfn \"10 \u2208 s1? %A\" (s1.Contains 10)\n    printfn \"s1 \u222a s2 = %A\" (Set.union s1 s2)\n    printfn \"s1 \u2229 s2 = %A\" (Set.intersect s1 s2)\n    printfn \"s1 \u2216 s2 = %A\" (Set.difference s1 s2)\n    printfn \"s1 \u2286 s2? %A\" (Set.isSubset s1 s1)\n    printfn \"{3, 1} \u2286 s1? %A\" (Set.isSubset (Set.ofList [3;1]) s1)\n    printfn \"{3, 2, 4, 1} = s1? %A\" ((Set.ofList [3;2;4;1]) = s1)\n    printfn \"s1 = s2? %A\" (s1 = s2)\n    printfn \"More set operations:\"\n    printfn \"#s1 = %A\" s1.Count\n    printfn \"s1 \u222a {99} = %A\" (s1.Add 99)\n    printfn \"s1 \u2216 {3} = %A\" (s1.Remove 3)\n    printfn \"s1 \u2282 s1? %A\" (Set.isProperSubset s1 s1)\n    printfn \"s1 \u2282 s2? %A\" (Set.isProperSubset s1 s2)\n    0\n\n\n","human_summarization":"implement various set operations such as creation, checking if an element belongs to a set, union, intersection, difference, subset and equality between two sets. It also optionally showcases other set operations and modifications on a mutable set. The set can be implemented using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also includes the implementation of the Collections.Set<'T> class which creates immutable sets based on binary trees.","id":3818}
    {"lang_cluster":"F#","source_code":"\nopen System\n\n[ 2008 .. 2121 ]\n|> List.choose (fun y -> if DateTime(y,12,25).DayOfWeek = DayOfWeek.Sunday then Some(y) else None)\n|> printfn \"%A\"\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":3819}
    {"lang_cluster":"F#","source_code":"\n\/\/ QR decomposition. Nigel Galloway: January 11th., 2022\nlet n=[[12.0;-51.0;4.0];[6.0;167.0;-68.0];[-4.0;24.0;-41.0]]|>MathNet.Numerics.LinearAlgebra.MatrixExtensions.matrix\nlet g=n|>MathNet.Numerics.LinearAlgebra.Matrix.qr\nprintfn $\"Matrix\\n------\\n%A{n}\\nQ\\n-\\n%A{g.Q}\\nR\\n-\\n%A{g.R}\"\n\n\n","human_summarization":"The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.","id":3820}
    {"lang_cluster":"F#","source_code":"\n\nset [|1;2;3;2;3;4|]\n\n\nval it : Set<int> = seq [1; 2; 3; 4]\n\n","human_summarization":"\"Remove duplicate elements from an array using three methods: 1) Utilizing a hash table, 2) Sorting the elements and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements. The simplest method involves constructing a set from the given array.\"","id":3821}
    {"lang_cluster":"F#","source_code":"\nlet rec qsort = function\n    hd :: tl ->\n        let less, greater = List.partition ((>=) hd) tl\n        List.concat [qsort less; [hd]; qsort greater]\n    | _ -> []\n\n","human_summarization":"implement the Quicksort algorithm to sort an array or list of elements. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions - one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to get the sorted array. The codes also include an optimized version of Quicksort that works in place by swapping elements within the array to avoid memory allocation of more arrays. The pivot selection method is not specified.","id":3822}
    {"lang_cluster":"F#","source_code":"\n\n> open System;;\n> Console.WriteLine( DateTime.Now.ToString(\"yyyy-MM-dd\") );;\n2010-08-13\n> Console.WriteLine( \"{0:D}\", DateTime.Now );;\nFriday, August 13, 2010\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":3823}
    {"lang_cluster":"F#","source_code":"\n\nlet subsets xs = List.foldBack (fun x rest -> rest @ List.map (fun ys -> x::ys) rest) xs [[]]\n\n\nlet rec pow = \n    function\n    | [] -> [[]]\n    | x::xs -> [for i in pow xs do yield! [i;x::i]]\n\n","human_summarization":"The code takes a set S as input and generates the power set of S. It can handle edge cases such as an empty set and a set containing only the empty set. It also demonstrates that the language supports these last two powersets.","id":3824}
    {"lang_cluster":"F#","source_code":"\nlet digit x y z = function\n    1 -> x\n  | 2 -> x + x\n  | 3 -> x + x + x\n  | 4 -> x + y\n  | 5 -> y\n  | 6 -> y + x\n  | 7 -> y + x + x\n  | 8 -> y + x + x + x\n  | 9 -> x + z\n  | _ -> failwith \"invalid call to digit\"\n \nlet rec to_roman acc = function\n    | x when x >= 1000 -> to_roman (acc + \"M\") (x - 1000)\n    | x when x >= 100 -> to_roman (acc + digit \"C\" \"D\" \"M\" (x \/ 100)) (x % 100)\n    | x when x >= 10 -> to_roman (acc + digit \"X\" \"L\" \"C\" (x \/ 10)) (x % 10)\n    | x when x > 0 -> acc + digit \"I\" \"V\" \"X\" x\n    | 0 -> acc\n    | _ -> failwith \"invalid call to_roman (negative input)\"\n\nlet roman n = to_roman \"\" n\n\n[<EntryPoint>]\nlet main args =\n    [1990; 2008; 1666]\n    |> List.map (fun n -> roman n)\n    |> List.iter (printfn \"%s\")\n    0\n\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":3825}
    {"lang_cluster":"F#","source_code":"\n\n> Array.create 6 'A';;\nval it\u00a0: char [] = [|'A'; 'A'; 'A'; 'A'; 'A'; 'A'|]\n> Array.init 8 (fun i -> i * 10)\u00a0;;\nval it\u00a0: int [] = [|0; 10; 20; 30; 40; 50; 60; 70|]\n> let arr = [|0; 1; 2; 3; 4; 5; 6 |]\u00a0;;\nval arr\u00a0: int [] = [|0; 1; 2; 3; 4; 5; 6|]\n> arr.[4];;\nval it\u00a0: int = 4\n> arr.[4] <- 65\u00a0;;\nval it\u00a0: unit = ()\n> arr;;\nval it\u00a0: int [] = [|0; 1; 2; 3; 65; 5; 6|]\n\n> let arr = new ResizeArray<int>();;\nval arr\u00a0: ResizeArray<int>\n> arr.Add(42);;\nval it\u00a0: unit = ()\n> arr.[0];;\nval it\u00a0: int = 42\n> arr.[0] <- 13;;\nval it\u00a0: unit = ()\n> arr.[0];;\nval it\u00a0: int = 13\n> arr.[1];;\n> System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.\nParameter name: index ...\n> arr;;\nval it\u00a0: ResizeArray<int> = seq [13]\n","human_summarization":"demonstrate the basic syntax of arrays in the specified language. They involve creating both fixed-length and dynamic arrays, assigning values to them, and retrieving an element from them. The dynamic array utilizes the .NET class System.Collections.Generic.List<'T> or Microsoft.FSharp.Collections.ResizeArray<'T>. The code also includes elements from the obsolete tasks of creating an array, assigning values to an array, and retrieving an element of an array.","id":3826}
    {"lang_cluster":"F#","source_code":"\n\nopen System.IO\n\nlet copyFile fromTextFileName toTextFileName =\n    let inputContent = File.ReadAllText fromTextFileName\n    inputContent |> fun text -> File.WriteAllText(toTextFileName, text)\n\n[<EntryPoint>]\nlet main argv =\n    copyFile \"input.txt\" \"output.txt\"\n    0\n\n","human_summarization":"demonstrate how to read the contents of \"input.txt\" into an intermediate variable and then write these contents into a new file called \"output.txt\". The codes do not use functional programming idioms and do not skip the use of the intermediate variable.","id":3827}
    {"lang_cluster":"F#","source_code":"\nlet s = \"alphaBETA\"\nlet upper = s.ToUpper()\nlet lower = s.ToLower()\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":3828}
    {"lang_cluster":"F#","source_code":"\n\nlet closest_pairs (xys: Point []) =\n  let n = xys.Length\n  seq { for i in 0..n-2 do\n          for j in i+1..n-1 do\n            yield xys.[i], xys.[j] }\n  |> Seq.minBy (fun (p0, p1) -> (p1 - p0).LengthSquared)\n\n\nclosest_pairs\n  [|Point(0.0, 0.0); Point(1.0, 0.0); Point (2.0, 2.0)|]\n\n\n(0,0, 1,0)\n\n\nopen System;\nopen System.Drawing;\nopen System.Diagnostics;\n \nlet Length (seg : (PointF * PointF) option) =\n    match seg with\n    | None -> System.Single.MaxValue\n    | Some(line) ->\n        let f = fst line\n        let t = snd line\n \n        let dx = f.X - t.X\n        let dy = f.Y - t.Y\n        sqrt (dx*dx + dy*dy)\n \n \nlet Shortest a b =\n    if Length(a) < Length(b) then\n        a\n    else\n        b\n \n \nlet rec ClosestBoundY from maxY (ptsByY : PointF list) =\n    match ptsByY with\n    | [] -> None\n    | hd :: tl ->\n        if hd.Y > maxY then\n            None\n        else\n            let toHd = Some(from, hd)\n            let bestToRest = ClosestBoundY from maxY tl\n            Shortest toHd bestToRest\n\n \nlet rec ClosestWithinRange ptsByY maxDy =\n    match ptsByY with\n    | [] -> None\n    | hd :: tl ->\n        let fromHd = ClosestBoundY hd (hd.Y + maxDy) tl\n        let fromRest = ClosestWithinRange tl  maxDy\n        Shortest fromHd fromRest\n\n\n\/\/ Cuts pts half way through it's length\n\/\/ Order is not maintained in result lists however\nlet Halve pts =\n    let rec ShiftToFirst first second n =\n        match (n, second) with\n        | 0, _ -> (first, second)   \/\/ finished the split, so return current state\n        | _, [] -> (first, [])      \/\/ not enough items, so first takes the whole original list\n        | n, hd::tl -> ShiftToFirst (hd :: first) tl (n-1)  \/\/ shift 1st item from second to first, then recurse with n-1\n\n    let n = (List.length pts) \/ 2\n    ShiftToFirst [] pts n\n    \n\nlet rec ClosestPair (pts : PointF list) =\n    if List.length pts < 2 then\n        None\n    else\n        let ptsByX = pts |> List.sortBy(fun(p) -> p.X)\n \n        let (left, right) = Halve ptsByX\n        let leftResult = ClosestPair left\n        let rightResult = ClosestPair right\n \n        let bestInHalf = Shortest  leftResult rightResult\n        let bestLength = Length bestInHalf\n \n        let divideX = List.head(right).X\n        let inBand = pts |> List.filter(fun(p) -> Math.Abs(p.X - divideX) < bestLength)\n \n        let byY = inBand |> List.sortBy(fun(p) -> p.Y)\n        let bestCross = ClosestWithinRange byY bestLength\n        Shortest bestInHalf bestCross\n\n\nlet GeneratePoints n =\n    let rand = new Random()\n    [1..n] |> List.map(fun(i) -> new PointF(float32(rand.NextDouble()), float32(rand.NextDouble())))\n\nlet timer = Stopwatch.StartNew()\nlet pts = GeneratePoints (50 * 1000)\nlet closest = ClosestPair pts\nlet takenMs = timer.ElapsedMilliseconds\n\nprintfn \"Closest Pair '%A'.  Distance %f\" closest (Length closest)\nprintfn \"Took %d [ms]\" takenMs\n\n","human_summarization":"The code provides two functions to solve the Closest Pair of Points problem in a two-dimensional space. The first function uses a brute force algorithm with a time complexity of O(n^2) to find the closest pair by comparing the distance between each pair of points. The second function uses a more efficient divide and conquer approach with a time complexity of O(n log n), which sorts the points by x and y coordinates, divides the set into two halves, finds the closest pairs in each half, and finally checks the pairs across the halves.","id":3829}
    {"lang_cluster":"F#","source_code":"\n\nlet rec print (lst : int list) =\n    match lst with\n    | hd :: [] ->\n        printf \"%i \" hd\n    | hd :: tl ->\n        printf \"%i, \" hd\n        print tl\n    | [] -> printf \"\\n\"\n\nprint [1..10]\n\n","human_summarization":"a comma-separated list of numbers from 1 to 10, using separate output statements for the number and the comma within a loop. The functional version works for lists of any length.","id":3830}
    {"lang_cluster":"F#","source_code":"\n[<EntryPoint>]\nlet main args =\n\n    let text = \"\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\"\n    let starts = \"\u4e00\u4e8c\"\n    let ends = \"\u4e5d\u5341\"\n    let contains = \"\u4e94\u516d\"\n    let notContains = \"\u767e\"\n\n    printfn \"text = %A\" text\n    printfn \"starts with %A: %A\" starts (text.StartsWith(starts))\n    printfn \"starts with %A: %A\" ends (text.StartsWith(ends))\n    printfn \"ends with %A: %A\" ends (text.EndsWith(ends))\n    printfn \"ends with %A: %A\" starts (text.EndsWith(starts))\n    printfn \"contains %A: %A\" contains (text.Contains(contains))\n    printfn \"contains %A: %A\" notContains (text.Contains(notContains))\n    printfn \"substring %A begins at position %d (zero-based)\" contains (text.IndexOf(contains))\n    let text2 = text + text\n    printfn \"text = %A\" text2\n    Seq.unfold (fun (n : int) ->\n            let idx = text2.IndexOf(contains, n)\n            if idx < 0 then None else Some (idx, idx+1)) 0\n    |> Seq.iter (printfn \"substring %A begins at position %d (zero-based)\" contains)\n    0\n\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":3831}
    {"lang_cluster":"F#","source_code":"\n(* A simple function to generate the sequence\n   Nigel Galloway: January 31st., 2017 *)\ntype G = {d:int;x:int;b:int;f:int}\nlet N n g = \n  {(max (n-g) n) .. (min (g-n) g)} |> Seq.collect(fun d->{(max (d+n+n) (n+n))..(min (g+g) (d+g+g))}           |> Seq.collect(fun x -> \n  seq{for a in n .. g do for b in n .. g do if (a+b) = x then for c in n .. g do if (b+c+d) = x then yield b} |> Seq.collect(fun b ->\n  seq{for f in n .. g do for G in n .. g do if (f+G) = x then for e in n .. g do if (f+e+d) = x then yield f} |> Seq.map(fun f -> {d=d;x=x;b=b;f=f}))))\n\n\nprintfn \"%d\" (Seq.length (N 0 9))\n\n\n","human_summarization":"The code finds all possible solutions for a puzzle where seven variables (a, b, c, d, e, f, g) are replaced with unique decimal digits within a given range (LOW to HIGH) such that the sum of variables in each of the four squares is equal. It provides solutions for ranges 1-7 and 3-9, and counts the number of solutions for non-unique variables in the range 0-9.","id":3832}
    {"lang_cluster":"F#","source_code":"\nopen System.Text.RegularExpressions\n\nlet numberTemplate = \"\"\"\n _     _  _     _     __ _  _       \n\/ \\ \/|  ) _)|_||_  \/   \/(_)(_) * \n\\_\/  | \/_ _)  | _)(_) \/ (_) \/  * \n\"\"\"\nlet g =\n    numberTemplate.Split([|'\\n';'\\r'|], System.StringSplitOptions.RemoveEmptyEntries)\n    |> Array.map (fun s ->\n        Regex.Matches(s, \"...\")\n        |> Seq.cast<Match>\n        |> Seq.map (fun m -> m.ToString())\n        |> Seq.toArray)\n\nlet idx c =\n    let v c = ((int) c) - ((int) '0')\n    let i = v c\n    if 0 <= i && i <= 9 then i\n    elif c = ':' then 10\n    else failwith (\"Cannot draw character \" + c.ToString())\n\nlet draw (s :string) =\n    System.Console.Clear()\n    g\n    |> Array.iter (fun a ->\n        s.ToCharArray() |> Array.iter (fun c ->\n            let i = idx c\n            printf \"%s\" (a.[i]))\n        printfn \"\"\n        )\n\n[<EntryPoint>]\nlet main argv =\n    let showTime _ = draw (System.String.Format(\"{0:HH:mm:ss}\", (System.DateTime.Now)))\n    let timer = new System.Timers.Timer(500.)\n    timer.AutoReset <- true \/\/ The timer triggers cyclically\n    timer.Elapsed \/\/ An event stream\n    |> Observable.subscribe showTime |> ignore \/\/ Subscribe to the event stream\n    timer.Start() \/\/ Now it counts\n    System.Console.ReadLine() |> ignore \/\/ Until return is hit\n    showTime ()\n    0\n\n\n","human_summarization":"illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.","id":3833}
    {"lang_cluster":"F#","source_code":"let isqrt n =\n    let rec iter t =\n        let d = n - t*t\n        if (0 <= d) && (d < t+t+1) \/\/ t*t <= n < (t+1)*(t+1)\n        then t else iter ((t+(n\/t))\/2)\n    iter 1\n \nlet rec gcd a b =\n    let t = a % b\n    if t = 0 then b else gcd b t\n \nlet coprime a b = gcd a b = 1\n \nlet num_to ms =\n    let mutable ctr = 0\n    let mutable prim_ctr = 0\n    let max_m = isqrt (ms\/2)\n    for m = 2 to max_m do\n        for j = 0 to (m\/2) - 1 do\n            let n = m-(2*j+1)\n            if coprime m n then\n                let s = 2*m*(m+n)\n                if s <= ms then\n                    ctr <- ctr + (ms\/s)\n                    prim_ctr <- prim_ctr + 1\n    (ctr, prim_ctr)\n \nlet show i =\n    let s, p = num_to i in\n    printfn \"For perimeters up to %d there are %d total and %d primitive\" i s p;;\n \nList.iter show [ 100; 1000; 10000; 100000; 1000000; 10000000; 100000000 ]\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a + b + c) no larger than 100. It also determines the number of these triples that are primitive, meaning a, b, and c are co-prime. The code is also optimized to handle large values up to a maximum perimeter of 100,000,000.","id":3834}
    {"lang_cluster":"F#","source_code":"\n\nLibrary: Windows Forms\n open System.Windows.Forms\n \n [<System.STAThread>]\n do\n     Form(Text = \"F# Window\")\n     |> Application.Run\n\n","human_summarization":"create a GUI window using .NET runtime, similar to C#, that can respond to close requests, but doesn't contain any content.","id":3835}
    {"lang_cluster":"F#","source_code":"\nlet alphabet =\n    ['A'..'Z'] |> Set.ofList\n\nlet letterFreq (text : string) =\n    text.ToUpper().ToCharArray()\n    |> Array.filter (fun x -> alphabet.Contains(x))\n    |> Seq.countBy (fun x -> x)\n    |> Seq.sort\n\nlet v = \"Now is the time for all good men to come to the aid of the party\"\n\nlet res = letterFreq v\n\nfor (letter, freq) in res do\n    printfn \"%A, %A\" letter freq\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":3836}
    {"lang_cluster":"F#","source_code":"let (cos, sin, pi) = System.Math.Cos, System.Math.Sin, System.Math.PI\n\nlet (width, height) = 1000., 1000. \/\/ image dimension\nlet scale = 6.\/10.                 \/\/ branch scale relative to trunk\nlet length = 400.                  \/\/ trunk size\n\nlet rec tree x y length angle =\n    if length >= 1. then\n        let (x2, y2) = x + length * (cos angle),  y + length * (sin angle)\n        printfn \"<line x1='%f' y1='%f' x2='%f' y2='%f' style='stroke:rgb(0,0,0);stroke-width:1'\/>\"\n            x y x2 y2\n        tree x2 y2 (length*scale) (angle + pi\/5.)\n        tree x2 y2 (length*scale) (angle - pi\/5.)\n\nprintfn \"<?xml version='1.0' encoding='utf-8' standalone='no'?>\n<!DOCTYPE svg PUBLIC '-\/\/W3C\/\/DTD SVG 1.1\/\/EN' \n'http:\/\/www.w3.org\/Graphics\/SVG\/1.1\/DTD\/svg11.dtd'>\n<svg width='100%%' height='100%%' version='1.1'\nxmlns='http:\/\/www.w3.org\/2000\/svg'>\"\ntree (width\/2.) height length (3.*pi\/2.)\nprintfn \"<\/svg>\"\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":3837}
    {"lang_cluster":"F#","source_code":"\n\nlet factors number = seq {\n    for divisor in 1 .. (float >> sqrt >> int) number do\n    if number % divisor = 0 then\n        yield divisor\n        if number <> 1 then yield number \/ divisor \/\/special case condition: when number=1 then divisor=(number\/divisor), so don't repeat it\n}\n\n[6;120;2048;402642;1206432] |> Seq.iter(fun n->printf \"%d\u00a0:\" n; [1..n]|>Seq.filter(fun g->n%g=0)|>Seq.iter(fun n->printf \" %d\" n); printfn \"\");;\n\n\n","human_summarization":"compute the factors of a positive integer. The factors are determined by dividing the number by all positive integers up to its square root. If the remainder is zero, both the divisor and the quotient are considered as factors. The code does not handle cases for zero or negative integers. It also assumes that every prime number has only two factors: 1 and itself.","id":3838}
    {"lang_cluster":"F#","source_code":"\nopen System\nopen System.IO\n\nlet tableFromPath path =\n    let lines =\n        [ for line in File.ReadAllLines(path) -> (line.TrimEnd('$').Split('$')) ]\n    let width = List.fold (fun max (line : string[]) -> if max < line.Length then line.Length else max) 0 lines\n    List.map (fun (a : string[]) -> (List.init width (fun i -> if i < a.Length then a.[i] else \"\"))) lines\n\nlet rec trans m =\n    match m with\n    | []::_ -> []\n    | _ -> (List.map List.head m) :: trans (List.map List.tail m)\n\nlet colWidth table =\n    List.map (fun col -> List.max (List.map String.length col)) (trans table)\n\nlet left = (fun (s : string) n -> s.PadRight(n))\nlet right = (fun (s : string) n -> s.PadLeft(n))\nlet center = (fun (s : string) n -> s.PadLeft((n + s.Length) \/ 2).PadRight(n))\n\n[<EntryPoint>]\nlet main argv =\n    let table = tableFromPath argv.[0]\n    let width = Array.ofList (colWidth table)\n    let format table align =\n        List.map (fun (row : string list) -> List.mapi (fun i s -> sprintf \"%s\" (align s width.[i])) row) table\n        |> List.iter (fun row -> printfn \"%s\" (String.Join(\" \", Array.ofList row)))\n\n    for align in [ left; right; center ] do\n        format table align\n        printfn \"%s\" (new String('-', (Array.sum width) + width.Length - 1))\n    0\n\n\nGiven      a          text       file   of     many      lines,     where    fields  within  a      line\nare        delineated by         a      single 'dollar'  character, write    a       program\nthat       aligns     each       column of     fields    by         ensuring that    words   in     each\ncolumn     are        separated  by     at     least     one        space.\nFurther,   allow      for        each   word   in        a          column   to      be      either left\njustified, right      justified, or     center justified within     its      column.\n--------------------------------------------------------------------------------------------------------\n     Given          a       text   file     of      many     lines,    where  fields  within      a line\n       are delineated         by      a single  'dollar' character,    write       a program\n      that     aligns       each column     of    fields         by ensuring    that   words     in each\n    column        are  separated     by     at     least        one   space.\n  Further,      allow        for   each   word        in          a   column      to      be either left\njustified,      right justified,     or center justified     within      its column.\n--------------------------------------------------------------------------------------------------------\n  Given        a         text     file    of     many      lines,    where   fields  within    a    line\n   are     delineated     by       a    single 'dollar'  character,  write      a    program\n   that      aligns      each    column   of    fields       by     ensuring  that    words    in   each\n  column      are     separated    by     at     least      one      space.\n Further,    allow       for      each   word     in         a       column    to      be    either left\njustified,   right    justified,   or   center justified   within     its    column.\n--------------------------------------------------------------------------------------------------------\n","human_summarization":"The code reads a text file where fields within a line are separated by a dollar sign. It aligns each column of fields by ensuring that words in each column are separated by at least one space. It also allows for each word in a column to be either left justified, right justified, or center justified. The minimum space between columns is computed from the text and not hard-coded. The code handles trailing dollar characters and insignificant consecutive space characters at the end of lines. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":3839}
    {"lang_cluster":"F#","source_code":"\nlet adObject = new System.DirectoryServices.DirectoryEntry(\"LDAP:\/\/DC=onecity,DC=corp,DC=fabrikam,DC=com\")\n\n\nlet ldapServer = new System.DirectoryServices.Protocols.LdapDirectoryIdentifier(\"127.0.0.1\")\nlet connect = new System.DirectoryServices.Protocols.LdapConnection(ldapServer)\nconnect.Bind()\n\n","human_summarization":"establish a connection to either an Active Directory or Lightweight Directory Access Protocol server using the System.DirectoryServices library for Active Directory and System.DirectoryServices.Protocol for LDAP. It also includes a minimal example of an anonymous connection to the local machine on LDAP port 389.","id":3840}
    {"lang_cluster":"F#","source_code":"\n\nlet rot13 (s : string) =\n   let rot c =\n       match c with\n       | c when c > 64 && c < 91 -> ((c - 65 + 13) % 26) + 65\n       | c when c > 96 && c < 123 -> ((c - 97 + 13) % 26) + 97\n       | _ -> c\n   s |> Array.of_seq\n   |> Array.map(int >> rot >> char)\n   |> (fun seq -> new string(seq))\n\n","human_summarization":"implement a rot-13 encoding function that can be optionally wrapped in a utility program. This function replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters in the 26 letter alphabet. It works on both upper and lower case letters, preserves case, and passes all non-alphabetic characters without alteration. The function can be used for line-by-line encoding of input files or as a filter on standard input. It also illustrates turning a string into an array of chars, type casting, and function composition.","id":3841}
    {"lang_cluster":"F#","source_code":"\n\nlet persons = [| (\"Joe\", 120); (\"foo\", 31); (\"bar\", 51) |]\nArray.sortInPlaceBy fst persons\nprintfn \"%A\" persons\n\n\n[|(\"Joe\", 120); (\"bar\", 51); (\"foo\", 31)|]\n\ntype Person = { name:string; id:int }\nlet persons2 = [{name=\"Joe\"; id=120}; {name=\"foo\"; id=31}; {name=\"bar\"; id=51}]\nlet sorted = List.sortBy (fun p -> p.id) persons2\nfor p in sorted do printfn \"%A\" p\n\n\n{name = \"foo\";\n id = 31;}\n{name = \"bar\";\n id = 51;}\n{name = \"Joe\";\n id = 120;}\n","human_summarization":"define a composite structure named pair with two string properties: name and value. It also sorts an array of these pairs by the name property using a custom comparator. The F# sortBy function is utilized for this purpose in the given examples.","id":3842}
    {"lang_cluster":"F#","source_code":"\n#light\n[<EntryPoint>]\nlet main args =\n    for i = 1 to 5 do\n        for j = 1 to i do\n            printf \"*\"\n        printfn \"\"\n    0\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":3843}
    {"lang_cluster":"F#","source_code":"\n\nlet dic = System.Collections.Generic.Dictionary<string,string>() ;;\ndic.Add(\"key\",\"val\") ;\ndic.[\"key\"] <- \"new val\" ;\n\n\nlet d = [(\"key\",\"val\");(\"other key\",\"other val\")] |> Map.ofList\nlet newd = d.Add(\"new key\",\"new val\")\n\nlet takeVal (d:Map<string,string>) = \n    match d.TryFind(\"key\") with\n        | Some(v) -> printfn \"%s\" v\n        | None -> printfn \"not found\"\n\n","human_summarization":"Create an associative array, dictionary, map, or hash using .NET 3.5 Generic Dictionary (mutable) and Functional dictionary (immutable).","id":3844}
    {"lang_cluster":"F#","source_code":"\nmodule lcg =\n    let bsd seed =\n        let state = ref seed\n        (fun (_:unit) ->\n            state := (1103515245 * !state + 12345) &&& System.Int32.MaxValue\n            !state)\n \n    let ms seed =\n        let state = ref seed\n        (fun (_:unit) ->\n            state := (214013 * !state + 2531011) &&& System.Int32.MaxValue\n            !state \/ (1<<<16))\n\nlet rndBSD = lcg.bsd 0;; \nlet BSD=[for n in [0 .. 9] -> rndBSD()];;\n\nlet rndMS = lcg.ms 0;; \nlet MS=[for n in [0 .. 9] -> rndMS()];;\n\nval BSD\u00a0: int list =\n  [12345; 1406932606; 654583775; 1449466924; 229283573; 1109335178; 1051550459;\n   1293799192; 794471793; 551188310]\nval MS\u00a0: int list =\n  [38; 7719; 21238; 2437; 8855; 11797; 8365; 32285; 10450; 30612]\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":3845}
    {"lang_cluster":"F#","source_code":"\nlet ethopian n m =\n    let halve n = n \/ 2\n    let double n = n * 2\n    let even n = n % 2 = 0\n    let rec loop n m result =\n        if n <= 1 then result + m\n        else if even n then loop (halve n) (double m) result\n        else loop (halve n) (double m) (result + m)\n    loop n m 0\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":3846}
    {"lang_cluster":"F#","source_code":"\n\nopen System\n\nlet rec gcd x y = if x = y || x = 0 then y else if x < y then gcd y x else gcd y (x-y)\nlet abs (x : int) = Math.Abs x\nlet sign (x: int) = Math.Sign x\nlet cint s = Int32.Parse(s)\n\ntype Rat(x : int, y : int) =\n    let g = if y = 0 then 0 else gcd (abs x) (abs y)\n    member this.n = if g = 0 then sign y * sign x else sign y * x \/ g   \/\/ store a minus sign in the numerator\n    member this.d =\n        if y = 0 then 0 else sign y * y \/ g\n    static member (~-) (x : Rat) = Rat(-x.n, x.d)\n    static member (+) (x : Rat, y : Rat) = Rat(x.n * y.d + y.n * x.d, x.d * y.d)\n    static member (-) (x : Rat, y : Rat) = x + Rat(-y.n, y.d)\n    static member (*) (x : Rat, y : Rat) = Rat(x.n * y.n, x.d * y.d)\n    static member (\/) (x : Rat, y : Rat) = x * Rat(y.d, y.n)\n    interface System.IComparable with\n      member this.CompareTo o = \n        match o with\n        | :? Rat as that -> compare (this.n * that.d) (that.n * this.d)\n        | _ -> invalidArg \"o\" \"cannot compare values of differnet types.\"\n    override this.Equals(o) =\n        match o with\n        | :? Rat as that -> this.n = that.n && this.d = that.d\n        | _ -> false\n    override this.ToString() =\n        if this.d = 1 then this.n.ToString()\n        else sprintf @\"<%d,%d>\" this.n this.d\n    new(x : string, y : string) = if y = \"\" then Rat(cint x, 1) else Rat(cint x, cint y)\n\ntype expression =\n    | Const of Rat\n    | Sum  of expression * expression\n    | Diff of expression * expression\n    | Prod of expression * expression\n    | Quot of expression * expression\n \nlet rec eval = function\n    | Const c -> c\n    | Sum (f, g) -> eval f + eval g\n    | Diff(f, g) -> eval f - eval g\n    | Prod(f, g) -> eval f * eval g\n    | Quot(f, g) -> eval f \/ eval g\n\nlet print_expr expr =\n    let concat (s : seq<string>) = System.String.Concat s\n    let paren p prec op_prec = if prec > op_prec then p else \"\"\n    let rec print prec = function\n    | Const c -> c.ToString()\n    | Sum(f, g) ->\n        concat [ (paren \"(\" prec 0); (print 0 f); \" + \"; (print 0 g); (paren \")\" prec 0) ]\n    | Diff(f, g) ->\n        concat [ (paren \"(\" prec 0); (print 0 f); \" - \"; (print 1 g); (paren \")\" prec 0) ]\n    | Prod(f, g) ->\n        concat [ (paren \"(\" prec 2); (print 2 f); \" * \"; (print 2 g); (paren \")\" prec 2) ]\n    | Quot(f, g) ->\n        concat [ (paren \"(\" prec 2); (print 2 f); \" \/ \"; (print 3 g); (paren \")\" prec 2) ]\n    print 0 expr\n    \nlet rec normal expr =\n    let norm epxr =\n        match expr with\n        | Sum(x, y) -> if eval x <= eval y then expr else Sum(normal y, normal x)\n        | Prod(x, y) -> if eval x <= eval y then expr else Prod(normal y, normal x)\n        | _ -> expr\n    match expr with\n    | Const c -> expr\n    | Sum(x, y) -> norm (Sum(normal x, normal y))\n    | Prod(x, y) -> norm (Prod(normal x, normal y))\n    | Diff(x, y) -> Diff(normal x, normal y)\n    | Quot(x, y) -> Quot(normal x, normal y)\n \nlet rec insert v = function\n    | [] -> [[v]]\n    | x::xs as li -> (v::li) :: (List.map (fun y -> x::y) (insert v xs))\n \nlet permutations li = \n    List.foldBack (fun x z -> List.concat (List.map (insert x) z)) li [[]]\n\nlet rec comp expr rest = seq {\n    match rest with\n    | x::xs ->\n        yield! comp (Sum (expr, x)) xs;\n        yield! comp (Diff(x, expr)) xs;\n        yield! comp (Diff(expr, x)) xs;\n        yield! comp (Prod(expr, x)) xs;\n        yield! comp (Quot(x, expr)) xs;\n        yield! comp (Quot(expr, x)) xs;\n    | [] -> if eval expr = Rat(24,1) then yield print_expr (normal expr)\n}\n\n[<EntryPoint>]\nlet main argv =\n    let digits = List.init 4 (fun i -> Const (Rat(argv.[i],\"\")))\n    let solutions =\n        permutations digits\n        |> Seq.groupBy (sprintf \"%A\")\n        |> Seq.map snd |> Seq.map Seq.head\n        |> Seq.map (fun x -> comp (List.head x) (List.tail x))\n        |> Seq.choose (fun x -> if Seq.isEmpty x then None else Some x)\n        |> Seq.concat\n    if Seq.isEmpty solutions then\n        printfn \"No solutions.\"\n    else\n        solutions\n        |> Seq.groupBy id\n        |> Seq.iter (fun x -> printfn \"%s\" (fst x))\n    0\n\n\n","human_summarization":"The code takes four digits as input, either provided by the user or generated randomly, and computes all possible arithmetic expressions following the rules of the 24 game. It also removes any duplicate solutions resulting from transposing equal digits. The code is an adaptation of the OCaml program.","id":3847}
    {"lang_cluster":"F#","source_code":"\n\/\/val inline factorial\u00a0:\n\/\/   ^a ->  ^a\n\/\/    when  ^a\u00a0: (static member get_One\u00a0: ->  ^a) and\n\/\/          ^a\u00a0: (static member ( + )\u00a0:  ^a *  ^a ->  ^a) and\n\/\/          ^a\u00a0: (static member ( * )\u00a0:  ^a *  ^a ->  ^a)\nlet inline factorial n = Seq.reduce (*) [ LanguagePrimitives.GenericOne .. n ]\n\n> factorial 8;;\nval it\u00a0: int = 40320\n> factorial 800I;;\nval it\u00a0: bigint = 771053011335386004144639397775028360595556401816010239163410994033970851827093069367090769795539033092647861224230677444659785152639745401480184653174909762504470638274259120173309701702610875092918816846985842150593623718603861642063078834117234098513725265045402523056575658860621238870412640219629971024686826624713383660963127048195572279707711688352620259869140994901287895747290410722496106151954257267396322405556727354786893725785838732404646243357335918597747405776328924775897564519583591354080898117023132762250714057271344110948164029940588827847780442314473200479525138318208302427727803133219305210952507605948994314345449325259594876385922128494560437296428386002940601874072732488897504223793518377180605441783116649708269946061380230531018291930510748665577803014523251797790388615033756544830374909440162270182952303329091720438210637097105616258387051884030288933650309756289188364568672104084185529365727646234588306683493594765274559497543759651733699820639731702116912963247441294200297800087061725868223880865243583365623482704395893652711840735418799773763054887588219943984673401051362280384187818611005035187862707840912942753454646054674870155072495767509778534059298038364204076299048072934501046255175378323008217670731649519955699084482330798811049166276249251326544312580289357812924825898217462848297648349400838815410152872456707653654424335818651136964880049831580548028614922852377435001511377656015730959254647171290930517340367287657007606177675483830521499707873449016844402390203746633086969747680671468541687265823637922007413849118593487710272883164905548707198762911703545119701275432473548172544699118836274377270607420652133092686282081777383674487881628800801928103015832821021286322120460874941697199487758769730544922012389694504960000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000I\n\n\n","human_summarization":"The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.","id":3848}
    {"lang_cluster":"F#","source_code":"\nopen System\n\nlet generate_number targetSize =\n    let rnd = Random()\n    let initial = Seq.initInfinite (fun _ -> rnd.Next(1,9))\n    initial |> Seq.distinct |> Seq.take(targetSize) |> Seq.toList\n\nlet countBulls guess target =\n    let hits = List.map2 (fun g t -> if g = t then true else false) guess target\n    List.filter (fun x -> x = true) hits |> List.length\n\nlet countCows guess target =\n    let mutable score = 0\n    for g in guess do\n        for t in target do\n            if g = t then\n                score <- score + 1\n            else\n                score <- score\n    score\n\nlet countScore guess target =\n    let bulls = countBulls guess target\n    let cows = countCows guess target\n    (bulls, cows)\n\nlet playRound guess target =\n    countScore guess target\n\nlet inline ctoi c : int =\n    int c - int '0'\n\nlet lineToList (line: string) =\n    let listc = Seq.map(fun c -> c |> string) line |> Seq.toList\n    let conv = List.map(fun x -> Int32.Parse x) listc\n    conv\n\nlet readLine() =\n    let line = Console.ReadLine()\n    if line <> null then\n        if line.Length = 4 then\n            Ok (lineToList line)\n        else\n            Error(\"Input guess must be 4 characters!\")\n    else\n        Error(\"Input guess cannot be empty!\")\n\nlet rec handleInput() =\n    let line = readLine()\n    match line with\n    | Ok x -> x\n    | Error s ->\n        printfn \"%A\" s\n        handleInput()\n\n[<EntryPoint>]\nlet main argv =\n    let target = generate_number 4\n    let mutable shouldEnd = false\n    while shouldEnd = false do\n        let guess = handleInput()\n        let (b, c) = playRound guess target\n        printfn \"Bulls: %i | Cows: %i\" b c\n        if b = 4 then\n            shouldEnd <- true\n        else\n            shouldEnd <- false\n    0\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":3849}
    {"lang_cluster":"F#","source_code":"\nlet n = MathNet.Numerics.Distributions.Normal(1.0,0.5)\nList.init 1000 (fun _->n.Sample())\n\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":3850}
    {"lang_cluster":"F#","source_code":"\nlet dot_product (a:array<'a>) (b:array<'a>) =\n    if Array.length a <> Array.length b then failwith \"invalid argument: vectors must have the same lengths\"\n    Array.fold2 (fun acc i j -> acc + (i * j)) 0 a b\n\n> dot_product [| 1; 3; -5 |] [| 4; -2; -1 |]\u00a0;;\nval it\u00a0: int = 3\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":3851}
    {"lang_cluster":"F#","source_code":"\n\nlet lines_of_file file =\n  seq { use stream = System.IO.File.OpenRead file\n        use reader = new System.IO.StreamReader(stream)\n        while not reader.EndOfStream do\n          yield reader.ReadLine() }\n\n\n","human_summarization":"\"Implement an input loop to read data from a text stream either word-by-word or line-by-line until the end of the stream. The code also reopens the file every time the sequence is traversed and reads lines on-demand, allowing it to handle files of any size.\"","id":3852}
    {"lang_cluster":"F#","source_code":"\nopen System.Xml\n\n[<EntryPoint>]\nlet main argv =\n    let xd = new XmlDocument()\n    \/\/ Create the required nodes:\n    xd.AppendChild (xd.CreateXmlDeclaration(\"1.0\", null, null)) |> ignore\n    let root = xd.AppendChild (xd.CreateNode(\"element\", \"root\", \"\"))\n    let element = root.AppendChild (xd.CreateElement(\"element\", \"element\", \"\"))\n    element.AppendChild (xd.CreateTextNode(\"Some text here\")) |> ignore\n    \/\/ The same can be accomplished with:\n    \/\/ xd.LoadXml(\"\"\"<?xml version=\"1.0\"?><root><element>Some text here<\/element><\/root>\"\"\")\n\n    let xw = new XmlTextWriter(System.Console.Out)\n    xw.Formatting <- Formatting.Indented\n    xd.WriteContentTo(xw)\n    0\n\n\n<?xml version=\"1.0\"?>\n<root>\n  <element>Some text here<\/element>\n<\/root>\n","human_summarization":"Create and serialize a simple DOM to XML format. The XML structure includes a root element containing a child element with some text.","id":3853}
    {"lang_cluster":"F#","source_code":"\nprintfn \"%s\" (System.DateTime.Now.ToString(\"u\"))\n\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":3854}
    {"lang_cluster":"F#","source_code":"\nopen System\nlet Inputs = [\"710889\"; \"B0YBKJ\"; \"406566\"; \"B0YBLH\"; \"228276\"; \"B0YBKL\"\n              \"557910\"; \"B0YBKR\"; \"585284\"; \"B0YBKT\"; \"B00030\"]\n\nlet Vowels = set ['A'; 'E'; 'I'; 'O'; 'U']\nlet Weights = [1; 3; 1; 7; 3; 9; 1]\n\nlet inline isVowel c = Vowels.Contains (Char.ToUpper c)\n\nlet char2value c =   \n    if Char.IsDigit c then int c - 0x30 \n    else (['A'..'Z'] |> List.findIndex ((=) (Char.ToUpper c))) + 10\n        \nlet sedolCheckDigit (input: string) =\n    if input.Length <> 6 || input |> Seq.exists isVowel then \n        failwithf \"Input must be six characters long and not contain vowels: %s\" input\n\n    let sum = Seq.map2 (fun ch weight -> (char2value ch) * weight) input Weights |> Seq.sum\n    (10 - sum%10)%10              \n\nlet addCheckDigit inputs =\n    inputs |> List.map (fun s -> s + (sedolCheckDigit s).ToString())\n\nlet processDigits() =\n    try\n        addCheckDigit Inputs |> List.iter (printfn \"%s\")\n    with \n        ex -> printfn \"ERROR: %s\" ex.Message\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":3855}
    {"lang_cluster":"F#","source_code":"\nopen System\n\nlet ordinalsuffix n =\n    let suffixstrings = [|\"th\"; \"st\"; \"nd\"; \"rd\"|]\n    let (d, r) = Math.DivRem(n, 10)\n    n.ToString() + suffixstrings.[ if r < 4 && (d &&& 1) = 0 then r else 0 ]\n    \n\n[<EntryPoint>]\nlet main argv =\n    let show = (Seq.iter (ordinalsuffix >> (printf \" %s\"))) >> (Console.WriteLine)\n    [0..25] |> show\n    [250..265] |> show\n    [1000..1025] |> show\n    0\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":3856}
    {"lang_cluster":"F#","source_code":"\nlet stripChars text (chars:string) =\n    Array.fold (\n        fun (s:string) c -> s.Replace(c.ToString(),\"\")\n    ) text (chars.ToCharArray())\n\n[<EntryPoint>]\nlet main args =\n    printfn \"%s\" (stripChars \"She was a soul stripper. She took my heart!\" \"aei\")\n    0\n\n\nSh ws  soul strppr. Sh took my hrt!\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":3857}
    {"lang_cluster":"F#","source_code":"\nlet mutable s = \"world!\"\ns <- \"Hello, \" + s\nprintfn \"%s\" s\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":3858}
    {"lang_cluster":"F#","source_code":"\nUsing Library: Windows Presentation Foundation for visualization:\nopen System.Windows\nopen System.Windows.Media\n\nlet m = Matrix(0.0, 0.5, -0.5, 0.0, 0.0, 0.0)\n\nlet step segs =\n  seq { for a: Point, b: Point in segs do\n          let x = a + 0.5 * (b - a) + (b - a) * m\n          yield! [a, x; b, x] }\n\nlet rec nest n f x =\n  if n=0 then x else nest (n-1) f (f x)\n\n[<System.STAThread>]\ndo\n  let path = Shapes.Path(Stroke=Brushes.Black, StrokeThickness=0.001)\n  path.Data <-\n    PathGeometry\n      [ for a, b in nest 13 step (seq [Point(0.0, 0.0), Point(1.0, 0.0)]) ->\n          PathFigure(a, [(LineSegment(b, true) :> PathSegment)], false) ]\n  (Application()).Run(Window(Content=Controls.Viewbox(Child=path))) |> ignore\n\n","human_summarization":"generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.","id":3859}
    {"lang_cluster":"F#","source_code":"\nlet lower = ['a'..'z']\n\nprintfn \"%A\" lower\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":3860}
    {"lang_cluster":"F#","source_code":"\n\nopen System\nfor i in [5; 50; 9000] do printfn \"%s\" <| Convert.ToString (i, 2)\n\n\nopen System\n\n\/\/ define the function\nlet printBin (i: int) = \n    Convert.ToString (i, 2)\n    |> printfn \"%s\" \n\n\/\/ use the function\n[5; 50; 9000] \n|> List.iter printBin\n\n\nopen System\nopen System.IO\n\n\/\/ define a callback function for %a\nlet bin (tw: TextWriter) value = \n    tw.Write(\"{0}\", Convert.ToString(int64 value, 2))\n\n\/\/ use it with printfn with %a\n[5; 50; 9000] \n|> List.iter (printfn \"binary: %a\" bin)\n\n\n101\n110010\n10001100101000\n\n","human_summarization":"The code takes a non-negative integer as input and converts it into its corresponding binary representation. It uses either built-in radix functions or a user-defined function to achieve this. The output consists solely of the binary digits of the input number, followed by a newline, with no additional whitespace, radix or sign markers, and no leading zeros. The code can be implemented in various styles, including an inflexible imperative style, a more flexible function-based style, or an idiomatic style compatible with printf-style functions and the %a format specifier.","id":3861}
    {"lang_cluster":"F#","source_code":"\n\n\/\/ Merge and aggregate datasets. Nigel Galloway: January 6th., 2021\nlet rFile(fName)=seq{use n=System.IO.File.OpenText(fName)\n                     n.ReadLine() |> ignore\n                     while not n.EndOfStream do yield n.ReadLine().Split [|','|]}\nlet N=rFile(\"file1.txt\") |> Seq.sort\nlet G=rFile(\"file2.txt\") |> Seq.groupBy(fun n->n.[0]) |> Map.ofSeq\nlet fN n i g e l=printfn \"|\u00a0%-10s |\u00a0%-8s | %10s | \u00a0%-9s |\u00a0%-9s |\" n i g e l \nlet fG n g=let z=G.[n]|>Seq.sumBy(fun n->try float n.[2] with :? System.FormatException->0.0)\n           fN n g (G.[n]|>Seq.sort|>Seq.last).[1] (if z=0.0 then \"\" else string z) (if z=0.0 then \"\" else string(z\/(float(Seq.length G.[n]))))\n\n\n","human_summarization":"\"Merge and aggregate two provided .csv datasets based on patient id and last name, calculate the maximum visit date, and compute the sum and average of the scores per patient. The resulting dataset can be displayed on the screen, stored in-memory, or saved to a file.\"","id":3862}
    {"lang_cluster":"F#","source_code":"\n\nopen System.Windows.Forms\nopen System.Drawing\n\nlet f = new Form()\nf.Size <- new Size(320,240)\nf.Paint.Add(fun e -> e.Graphics.FillRectangle(Brushes.Red, 100, 100 ,1,1))\nApplication.Run(f)\n\n","human_summarization":"Creates a 320x240 window using Windows Forms and draws a red pixel at position (100,100).","id":3863}
    {"lang_cluster":"F#","source_code":"open System\n\n[<Measure>] type deg\n[<Measure>] type rad\n[<Measure>] type km\n\nlet haversine (\u03b8: float<rad>) = 0.5 * (1.0 - Math.Cos(\u03b8\/1.0<rad>))\n\nlet radPerDeg =  (Math.PI \/ 180.0) * 1.0<rad\/deg>\n\ntype pos(latitude: float<deg>, longitude: float<deg>) =\n    member this.\u03c6 = latitude * radPerDeg\n    member this.\u03c8 = longitude * radPerDeg\n\nlet rEarth = 6372.8<km>\n\nlet hsDist (p1: pos) (p2: pos) =\n    2.0 * rEarth *\n        Math.Asin(Math.Sqrt(haversine(p2.\u03c6 - p1.\u03c6)+\n                    Math.Cos(p1.\u03c6\/1.0<rad>)*Math.Cos(p2.\u03c6\/1.0<rad>)*haversine(p2.\u03c8 - p1.\u03c8)))\n\n[<EntryPoint>]\nlet main argv =\n    printfn \"%A\" (hsDist (pos(36.12<deg>, -86.67<deg>)) (pos(33.94<deg>, -118.40<deg>)))\n    0\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":3864}
    {"lang_cluster":"F#","source_code":"\n\nlet wget (url : string) =\n    use c = new System.Net.WebClient()\n    c.DownloadString(url)\n\nprintfn \"%s\" (wget \"http:\/\/www.rosettacode.org\/\")\n\n\nopen System.Net\nopen System.IO\n\nlet wgetAsync url =\n    async { let request = WebRequest.Create (url:string)\n            use! response = request.AsyncGetResponse()\n            use responseStream = response.GetResponseStream()\n            use reader = new StreamReader(responseStream)\n            return reader.ReadToEnd() }\n\nlet urls = [\"http:\/\/www.rosettacode.org\/\"; \"http:\/\/www.yahoo.com\/\"; \"http:\/\/www.google.com\/\"]\nlet content = urls\n              |> List.map wgetAsync\n              |> Async.Parallel\n              |> Async.RunSynchronously\n\n","human_summarization":"Access and print the content of a URL using the .NET library in F#, with an asynchronous workflow to avoid blocking threads while waiting for server response. The code also allows for simultaneous download of three URLs.","id":3865}
    {"lang_cluster":"F#","source_code":"\nlet luhn (s:string) =\n  let rec g r c = function\n  | 0 -> r\n  | i ->\n      let d = ((int s.[i - 1]) - 48) <<< c\n      g (r + if d < 10 then d else d - 9) (1 - c) (i - 1)\n  (g 0 0 s.Length) % 10 = 0\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":3866}
    {"lang_cluster":"F#","source_code":"\n> String.replicate 5 \"ha\";;\nval it : string = \"hahahahaha\"\n\n\n> String.Concat( Array.create 5 \"ha\" );;\nval it : string = \"hahahahaha\"\n\n","human_summarization":"\"Implements a function to repeat a given string or character a specified number of times.\"","id":3867}
    {"lang_cluster":"F#","source_code":"open System\nopen System.Text.RegularExpressions\n\n[<EntryPoint>]\nlet main argv =\n    let str = \"I am a string\"\n    if Regex(\"string$\").IsMatch(str) then Console.WriteLine(\"Ends with string.\")\n \n    let rstr = Regex(\" a \").Replace(str, \" another \")\n    Console.WriteLine(rstr)\n    0\n\n","human_summarization":"\"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression.\"","id":3868}
    {"lang_cluster":"F#","source_code":"\n\ndo\n  let a, b = int Sys.argv.[1], int Sys.argv.[2]\n  for str, f in [\"+\", ( + ); \"-\", ( - ); \"*\", ( * ); \"\/\", ( \/ ); \"%\", ( % )] do\n    printf \"%d %s %d = %d\\n\" a str b (f a b)\n\n\n4 + 3 = 7\n4 - 3 = 1\n4 * 3 = 12\n4 \/ 3 = 1\n4 % 3 = 1\n\n","human_summarization":"The code takes two integers as input from the user and calculates their sum, difference, product, integer quotient, remainder, and exponentiation. It also specifies how the quotient is rounded and the sign of the remainder. The code does not include error handling. Additionally, it provides an example of the 'divmod' operator. The code is written in F# and uses a list of pairs of function names and functions to perform and print the operations.","id":3869}
    {"lang_cluster":"F#","source_code":"\n\nopen System\n\nlet countSubstring (where :string) (what : string) =\n    match what with\n    | \"\" -> 0 \/\/ just a definition; infinity is not an int\n    | _ -> (where.Length - where.Replace(what, @\"\").Length) \/ what.Length\n    \n\n[<EntryPoint>]\nlet main argv =\n    let show where what =\n        printfn @\"countSubstring(\"\"%s\"\", \"\"%s\"\") = %d\" where what (countSubstring where what)\n    show \"the three truths\" \"th\"\n    show \"ababababab\" \"abab\"\n    show \"abc\" \"\"\n    0\n\ncountSubstring(\"the three truths\", \"th\") = 3\ncountSubstring(\"ababababab\", \"abab\") = 2\ncountSubstring(\"abc\", \"\") = 0\n","human_summarization":"\"Implement a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments: the main string and the substring to search for. The function returns an integer representing the count of non-overlapping occurrences. Overlapping substrings are not counted multiple times.\"","id":3870}
    {"lang_cluster":"F#","source_code":"\n#light\nlet rec hanoi num start finish =\n  match num with\n  | 0 -> [ ]\n  | _ -> let temp = (6 - start - finish)\n         (hanoi (num-1) start temp) @ [ start, finish ] @ (hanoi (num-1) temp finish)\n\n[<EntryPoint>]\nlet main args =\n  (hanoi 4 1 2) |> List.iter (fun pair -> match pair with\n                                          | a, b -> printf \"Move disc from %A to %A\\n\" a b)\n  0\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":3871}
    {"lang_cluster":"F#","source_code":"\nlet choose n k = List.fold (fun s i -> s * (n-i+1)\/i ) 1 [1..k]\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":3872}
    {"lang_cluster":"F#","source_code":"\nLibrary: Windows Presentation Foundation\nopen System.Windows\n\nlet str = \"Hello world! \"\nlet mutable i = 0\nlet mutable d = 1\n\n[<System.STAThread>]\ndo\n  let button = Controls.Button()\n  button.Click.Add(fun _ -> d <- str.Length - d)\n  let update _ =\n    i <- (i + d) % str.Length\n    button.Content <- str.[i..] + str.[..i-1]\n  Media.CompositionTarget.Rendering.Add update\n  (Application()).Run(Window(Content=button)) |> ignore\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":3873}
    {"lang_cluster":"F#","source_code":"\n\nlet rec loop n =\n  printfn \"%d \" n\n  if (n+1)%6 > 0 then loop (n+1)\nloop 0\n\n\nSeq.initInfinite id |> Seq.takeWhile(fun n->n=0 || n%6>0) |> Seq.iter (fun n-> printfn \"%d\" n)\n\n\n\n","human_summarization":"Code summarization: The code initiates a value at 0 and enters a do-while loop. In each iteration, it increments the value by 1 and prints it. The loop continues until the value modulo 6 is not 0. The loop is guaranteed to execute at least once. The output is a sequence of numbers from 1 to 6.","id":3874}
    {"lang_cluster":"F#","source_code":"\n\nopen System.Text\nlet byte_length str = Encoding.UTF8.GetByteCount(str)\n\n\"Hello, World\".Length\n\n","human_summarization":"The code calculates the character and byte length of a string, considering UTF-8 and UTF-16 encodings. It correctly handles non-BMP code points and provides the actual character counts in code points, not in code unit counts. It also has the capability to provide the string length in graphemes. The results are marked with ===Character Length===, ===Byte Length===, and ===Grapheme Length=== respectively. The functionality is implemented using the standard .Net framework string and encoding functions.","id":3875}
    {"lang_cluster":"F#","source_code":"\n[<EntryPoint>]\nlet main args =\n    let s = \"\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\"\n    printfn \"%A\" (s.Substring(1))\n    printfn \"%A\" (s.Substring(0, s.Length - 1))\n    printfn \"%A\" (s.Substring(1, s.Length - 2))\n    0\n\n\n\"\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\u5341\"\n\"\u4e00\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\"\n\"\u4e8c\u4e09\u56db\u4e94\u516d\u4e03\u516b\u4e5d\"\n","human_summarization":"demonstrate the removal of the first character, the last character, and both the first and last characters from a string. The program ensures compatibility with any valid Unicode code point and references logical characters rather than 8-bit or 16-bit code units.","id":3876}
    {"lang_cluster":"F#","source_code":"\nmodule SudokuBacktrack\n\n\/\/Helpers\nlet tuple2 a b = a,b\nlet flip  f a b = f b a\nlet (>>=) f g = Option.bind g f\n\n\/\/\/ \"A1\" to \"I9\" squares as key in values dictionary\nlet key a b = $\"{a}{b}\"\n\n\/\/\/ Cross product of elements in ax and elements in bx\nlet cross ax bx = [| for a in ax do for b in bx do key a b |]\n\n\/\/ constants\nlet valid   = \"1234567890.,\"\nlet rows    = \"ABCDEFGHI\"\nlet cols    = \"123456789\"    \nlet squares = cross rows cols\n\n\/\/ List of all row, cols and boxes:  aka units\nlet unitList = \n    [for c in cols do cross rows (string c) ]@ \/\/ row units\n    [for r in rows do cross (string r) cols ]@ \/\/ col units\n    [for rs in [\"ABC\";\"DEF\";\"GHI\"] do for cs in [\"123\";\"456\";\"789\"] do cross rs cs ] \/\/ box units\n\n\/\/\/ Dictionary of units for each square\nlet units = \n    [for s in squares do s, [| for u in unitList do if u |> Array.contains s then u |] ] |> Map.ofSeq \n\n\/\/\/ Dictionary of all peer squares in the relevant units wrt square in question\nlet peers = \n    [for s in squares do units[s] |> Array.concat |> Array.distinct |> Array.except [s] |> tuple2 s] |> Map.ofSeq\n\n\/\/\/ Should parse grid in many input formats or return None\nlet parseGrid grid = \n    let ints = [for c in grid do if valid |> Seq.contains c then if \",.\" |> Seq.contains c then 0 else (c |> string |> int)]\n    if Seq.length ints = 81 then ints |> Seq.zip squares |> Map.ofSeq |> Some else None\n\n\/\/\/ Outputs single line puzzle with 0 as empty squares\nlet asString  =  function\n    | Some values -> values |> Map.toSeq |> Seq.map (snd>>string) |> String.concat \"\" \n    | _ ->  \"No solution or Parse Failure\"  \n\n\/\/\/ Outputs puzzle in 2D format with 0 as empty squares\nlet prettyPrint = function\n    | Some (values:Map<_,_>) -> \n        [for r in rows do [for c in cols do (values[key r c] |> string) ] |> String.concat \" \" ] |> String.concat \"\\n\"        \n    | _ ->  \"No solution or Parse Failure\"  \n\n\/\/\/ Is digit allowed in the square in question?\u00a0!!! hot path\u00a0!!!! \n\/\/\/ Array\/Array2D no faster and they need explicit copy since not immutable\nlet constraints (values:Map<_,_>) s d = peers[s] |> Seq.map (fun p -> values[p]) |> Seq.exists ((=) d) |> not \n\n\/\/\/ Move to next square or None if out of bounds\nlet next s = squares |> Array.tryFindIndex ((=)s) |> function Some i when i + 1 < 81 -> Some squares[i + 1] | _ -> None\n\n\/\/\/ Backtrack recursively and immutably from index \nlet rec backtracker (values:Map<_,_>) = function\n    | None -> Some values \/\/ solved!\n    | Some s when values[s] > 0 -> backtracker values (next s)  \/\/ square not empty\n    | Some s -> \n        let rec tracker  = function\n            | [] -> None\n            | d::dx ->\n                values\n                |> Map.change s (Option.map (fun _ -> d)) \n                |> flip backtracker (next s) \n                |> function\n                | None ->  tracker dx \n                | success -> success\n        [for d in 1..9 do if constraints values s d then d] |> tracker\n    \n\/\/\/ solve sudoku using simple backtracking\nlet solve grid = grid |> parseGrid >>= flip backtracker (Some \"A1\")\n\n\nopen System\nopen SudokuBacktrack \n\n[<EntryPoint>]\nlet main argv =\n     let puzzle =  \"000028000800010000000000700000600403200004000100700000030400500000000010060000000\"\n     puzzle |> printfn \"Puzzle:\\n%s\"\n     puzzle |> parseGrid |> prettyPrint |> printfn \"Formatted:\\n%s\"\n     puzzle |> solve |> prettyPrint |> printfn \"Solution:\\n%s\"\n\n     printfn \"Press any key to exit\"\n     Console.ReadKey() |> ignore\n     0\n\n\n","human_summarization":"\"Code implements a Sudoku solver that takes a partially filled 9x9 grid as input and displays the solved Sudoku grid in a human-readable format. The solution is based on the Algorithmics of Sudoku and a Python Sudoku Solver Computerphile video.\"","id":3877}
    {"lang_cluster":"F#","source_code":"\n\nopen System\n\nlet FisherYatesShuffle (initialList : array<'a>) =                  \/\/ '\n    let availableFlags = Array.init initialList.Length (fun i -> (i, true))\n                                                                    \/\/ Which items are available and their indices\n    let rnd = new Random()  \n    let nextItem nLeft =\n        let nItem = rnd.Next(0, nLeft)                              \/\/ Index out of available items\n        let index =                                                 \/\/ Index in original deck\n            availableFlags                                          \/\/ Go through available array\n            |> Seq.filter (fun (ndx,f) -> f)                        \/\/ and pick out only the available tuples\n            |> Seq.nth nItem                                        \/\/ Get the one at our chosen index\n            |> fst                                                  \/\/ and retrieve it's index into the original array\n        availableFlags.[index] <- (index, false)                    \/\/ Mark that index as unavailable\n        initialList.[index]                                         \/\/ and return the original item\n    seq {(initialList.Length) .. -1 .. 1}                           \/\/ Going from the length of the list down to 1\n    |> Seq.map (fun i -> nextItem i)                                \/\/ yield the next item\n\n\nlet KnuthShuffle (lst : array<'a>) =                   \/\/ '\n    let Swap i j =                                                  \/\/ Standard swap\n        let item = lst.[i]\n        lst.[i] <- lst.[j]\n        lst.[j] <- item\n    let rnd = new Random()\n    let ln = lst.Length\n    [0..(ln - 2)]                                                   \/\/ For all indices except the last\n    |> Seq.iter (fun i -> Swap i (rnd.Next(i, ln)))                 \/\/ swap th item at the index with a random one following it (or itself)\n    lst                                                             \/\/ Return the list shuffled in place\n\n\n> KnuthShuffle [| \"Darrell\"; \"Marvin\"; \"Doug\"; \"Greg\"; \"Sam\"; \"Ken\" |];;\nval it : string array = [|\"Marvin\"; \"Doug\"; \"Sam\"; \"Darrell\"; \"Ken\"; \"Greg\"|]\n\n","human_summarization":"implement the Knuth shuffle algorithm, also known as the Fisher-Yates shuffle. This algorithm randomly shuffles the elements of an input array. It can work with an integer array or, if possible, an array of any type. The algorithm modifies the input array in-place, but can be adjusted to return a new array if necessary. It can also be amended to iterate from left to right. The function also includes test cases for validation.","id":3878}
    {"lang_cluster":"F#","source_code":"\n\/\/ A program that will run in the interpreter (fsi.exe)\nprintf \"Goodbye, World!\";;\n\n\/\/ A compiled program\n[<EntryPoint>]\nlet main args =\n    printf \"Goodbye, World!\"\n    0\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":3879}
    {"lang_cluster":"F#","source_code":"\nmodule caesar =\n    open System\n\n    let private cipher n s =\n        let shift c =\n            if Char.IsLetter c then\n                let a = (if Char.IsLower c then 'a' else 'A') |> int\n                (int c - a + n) % 26 + a |> char\n            else c\n        String.map shift s\n\n    let encrypt n = cipher n\n    let decrypt n = cipher (26 - n)\n\n> caesar.encrypt 2 \"HI\";;\nval it\u00a0: string = \"JK\"\n> caesar.encrypt 20 \"HI\";;\nval it\u00a0: string = \"BC\"\n> let c = caesar.encrypt 13 \"The quick brown fox jumps over the lazy dog.\";;\nval c\u00a0: string = \"Gur dhvpx oebja sbk whzcf bire gur ynml qbt.\"\n> caesar.decrypt 13 c;;\nval it\u00a0: string = \"The quick brown fox jumps over the lazy dog.\"\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":3880}
    {"lang_cluster":"F#","source_code":"\nlet rec gcd x y = if y = 0 then abs x else gcd y (x % y)\n\nlet lcm x y = x * y \/ (gcd x y)\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":3881}
    {"lang_cluster":"F#","source_code":"\n\/\/ Validate CUSIP: Nigel Galloway. June 2nd., 2021\nlet fN=function n when n>47 && n<58->n-48 |n when n>64 && n<91->n-55 |42->36 |64->37 |_->38\nlet cD(n:string)=(10-(fst((n.[0..7])|>Seq.fold(fun(z,n)g->let g=(fN(int g))*(n+1) in (z+g\/10+g%10,(n+1)%2))(0,0)))%10)%10=int(n.[8])-48\n[\"037833100\";\"17275R102\";\"38259P508\";\"594918104\";\"68389X103\";\"68389X105\"]|>List.iter(fun n->printfn \"CUSIP %s is %s\" n (if cD n then \"valid\" else \"invalid\"))\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":3882}
    {"lang_cluster":"F#","source_code":"\n\nopen System\nopen System.Runtime.InteropServices\nopen System.Diagnostics\n\n[<DllImport(\"kernel32.dll\", SetLastError = true, CallingConvention = CallingConvention.Winapi)>]\nextern bool IsWow64Process(nativeint hProcess, bool &wow64Process);\n\nlet answerHostInfo =\n    let Is64Bit() =\n        let mutable f64Bit = false;\n        IsWow64Process(Process.GetCurrentProcess().Handle, &f64Bit) |> ignore\n        f64Bit\n    let IsLittleEndian() = BitConverter.IsLittleEndian\n    (IsLittleEndian(), Is64Bit())\n\n","human_summarization":"The code outputs the word size and endianness of the host machine. It is designed to work independently of the machine it was compiled on, but is limited to Win32 machines due to interop. The code may also call to wow64Process without checking the OS version.","id":3883}
    {"lang_cluster":"F#","source_code":"\nopen System\nopen System.Text.RegularExpressions\n    \n[<EntryPoint>]\nlet main argv =\n    let rosettacodeSpecialCategoriesAddress =\n        \"http:\/\/www.rosettacode.org\/mw\/index.php?title=Special:Categories&limit=5000\"\n    let rosettacodeProgrammingLaguagesAddress =\n        \"http:\/\/rosettacode.org\/wiki\/Category:Programming_Languages\"\n\n    let getWebContent (url :string)  =\n        using (new System.Net.WebClient()) (fun x -> x.DownloadString url)\n\n    let regexForTitleCategoryFollowedOptionallyByMembercount =\n        new Regex(\"\"\"\n            title=\"Category: (?<Name> [^\"]* ) \">    # capture the name of the category\n            (                   # group begin for optional part\n                [^(]*           # ignore up to next open paren (on this line)\n                \\(              # verbatim open paren\n                    (?<Number>\n                        \\d+     # a number (= some digits)\n                    )\n                    \\s+         # whitespace\n                    member(s?)  # verbatim text members (maybe singular)\n                \\)              # verbatim closing paren\n            )?                  # end of optional part\n            \"\"\", \/\/ \" <- Make syntax highlighting happy\n            RegexOptions.IgnorePatternWhitespace ||| RegexOptions.ExplicitCapture)\n    let matchesForTitleCategoryFollowedOptionallyByMembercount str =\n        regexForTitleCategoryFollowedOptionallyByMembercount.Matches(str)\n\n    let languages =\n        matchesForTitleCategoryFollowedOptionallyByMembercount\n            (getWebContent rosettacodeProgrammingLaguagesAddress)\n        |> Seq.cast\n        |> Seq.map (fun (m: Match) -> (m.Groups.Item(\"Name\").Value, true))\n        |> Map.ofSeq\n\n    let entriesWithCount =\n        let parse str = match Int32.TryParse(str) with | (true, n) -> n | (false, _) -> -1\n        matchesForTitleCategoryFollowedOptionallyByMembercount\n            (getWebContent rosettacodeSpecialCategoriesAddress)\n        |> Seq.cast\n        |> Seq.map (fun (m: Match) ->\n            (m.Groups.Item(\"Name\").Value, parse (m.Groups.Item(\"Number\").Value)))\n        |> Seq.filter (fun p -> (snd p) > 0 &&  Map.containsKey (fst p) languages)\n        |> Seq.sortBy (fun x -> -(snd x))\n        \n\n    Seq.iter2 (fun i x -> printfn \"%4d. %s\" i x)\n        (seq { 1 .. 20 })\n        (entriesWithCount |> Seq.map (fun x -> sprintf \"%3d - %s\" (snd x) (fst x)))\n    0\n\n\n   1. 721 - Tcl\n   2. 665 - Python\n   3. 647 - C\n   4. 626 - PicoLisp\n   5. 622 - J\n   6. 588 - Go\n   7. 588 - Ruby\n   8. 585 - D\n   9. 569 - Perl 6\n  10. 565 - Ada\n  11. 555 - Mathematica\n  12. 535 - Perl\n  13. 533 - Haskell\n  14. 514 - BBC BASIC\n  15. 505 - REXX\n  16. 491 - Java\n  17. 480 - OCaml\n  18. 469 - PureBasic\n  19. 462 - Unicon\n  20. 430 - AutoHotkey\n","human_summarization":"The code sorts and ranks the most popular computer programming languages based on the number of members in their respective Rosetta Code categories. It accesses data through either web scraping or API methods, with optional filtering of incorrect results. The code also provides a complete ranked list of all programming languages, updated periodically. The sample output shows the top 10 languages as of a specific date and time.","id":3884}
    {"lang_cluster":"F#","source_code":"\n\nfor i in [1 .. 10] do printfn \"%d\" i\n\nList.iter (fun i -> printfn \"%d\" i) [1 .. 10]\n\n","human_summarization":"Iterates through each element in a collection in sequential order using a \"for each\" loop or another type of loop if \"for each\" is not available.","id":3885}
    {"lang_cluster":"F#","source_code":"\nSystem.String.Join(\".\", \"Hello,How,Are,You,Today\".Split(','))\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":3886}
    {"lang_cluster":"F#","source_code":"\nlet rec gcd a b =\n  if b = 0 \n    then abs a\n  else gcd b (a % b)\n \n>gcd 400 600\nval it : int = 200\n\n","human_summarization":"calculate the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":3887}
    {"lang_cluster":"F#","source_code":"\nopen System.IO\nopen System.Net\nopen System.Net.Sockets\n\nlet service (client:TcpClient) =\n    use stream = client.GetStream()\n    use out = new StreamWriter(stream, AutoFlush = true)\n    use inp = new StreamReader(stream)\n    while not inp.EndOfStream do\n        match inp.ReadLine() with\n        | line -> printfn \"< %s\" line\n                  out.WriteLine(line)\n    printfn \"closed %A\" client.Client.RemoteEndPoint\n    client.Close |> ignore\n\nlet EchoService = \n    let socket = new TcpListener(IPAddress.Loopback, 12321)\n    do socket.Start()\n    printfn \"echo service listening on %A\" socket.Server.LocalEndPoint\n    while true do\n        let client = socket.AcceptTcpClient()\n        printfn \"connect from %A\" client.Client.RemoteEndPoint\n        let job = async {\n            use c = client in try service client with _ -> () }\n        Async.Start job\n\n[<EntryPoint>]\nlet main _ =\n    EchoService\n    0\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":3888}
    {"lang_cluster":"F#","source_code":"\nlet is_numeric a = fst (System.Double.TryParse a)\n\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":3889}
    {"lang_cluster":"F#","source_code":"\n\n#light\nlet wget (url : string) =\n    let c = new System.Net.WebClient()\n    c.DownloadString(url)\n\n","human_summarization":"The code sends a GET request to the URL \"https:\/\/www.w3.org\/\" and prints the obtained resource to the console. It checks the validity of the host certificate but does not perform authentication. The handling of secure and insecure web connections is done by the underlying .NET classes.","id":3890}
    {"lang_cluster":"F#","source_code":"\nopen NUnit.Framework\nopen FsUnit\n\n\/\/ radian\n\n[<Test>]\nlet ``Verify that sin pi returns 0`` () =\n  let x = System.Math.Sin System.Math.PI\n  System.Math.Round(x,5) |> should equal 0\n\n[<Test>]\nlet ``Verify that cos pi returns -1`` () =\n  let x = System.Math.Cos System.Math.PI\n  System.Math.Round(x,5) |> should equal -1\n\n[<Test>]\nlet ``Verify that tan pi returns 0`` () =\n  let x = System.Math.Tan System.Math.PI\n  System.Math.Round(x,5) |> should equal 0\n\n[<Test>]\nlet ``Verify that sin pi\/2 returns 1`` () =\n  let x = System.Math.Sin (System.Math.PI \/ 2.0)\n  System.Math.Round(x,5) |> should equal 1\n\n[<Test>]\nlet ``Verify that cos pi\/2 returns -1`` () =\n  let x = System.Math.Cos (System.Math.PI \/ 2.0)\n  System.Math.Round(x,5) |> should equal 0\n\n[<Test>]\nlet ``Verify that sin pi\/3 returns sqrt 3\/2`` () =\n  let actual = System.Math.Sin (System.Math.PI \/ 3.0)\n  let expected = System.Math.Round((System.Math.Sqrt 3.0) \/ 2.0, 5)\n  System.Math.Round(actual,5) |> should equal expected\n\n[<Test>]\nlet ``Verify that cos pi\/3 returns -1`` () =\n  let x = System.Math.Cos (System.Math.PI \/ 3.0)\n  System.Math.Round(x,5) |> should equal 0.5\n\n[<Test>]\nlet ``Verify that cos and sin of pi\/4 return same value`` () =\n  let c = System.Math.Cos (System.Math.PI \/ 4.0)\n  let s = System.Math.Sin (System.Math.PI \/ 4.0)\n  System.Math.Round(c,5) = System.Math.Round(s,5) |> should be True\n\n[<Test>]\nlet ``Verify that acos pi\/3 returns 1\/2`` () =\n  let actual = System.Math.Acos 0.5\n  let expected = System.Math.Round((System.Math.PI \/ 3.0),5)\n  System.Math.Round(actual,5) |> should equal expected\n\n[<Test>]\nlet ``Verify that asin 1 returns pi\/2`` () =\n  let actual = System.Math.Asin 1.0\n  let expected = System.Math.Round((System.Math.PI \/ 2.0),5)\n  System.Math.Round(actual,5) |> should equal expected\n\n[<Test>]\nlet ``Verify that atan 0 returns 0`` () =\n  let actual = System.Math.Atan 0.0\n  let expected = System.Math.Round(0.0,5)\n  System.Math.Round(actual,5) |> should equal expected\n\n\/\/ degree\n\nlet toRadians d = d * System.Math.PI \/ 180.0\n\n[<Test>]\nlet ``Verify that pi is 180 degrees`` () =\n  toRadians 180.0 |> should equal System.Math.PI\n\n[<Test>]\nlet ``Verify that pi\/2 is 90 degrees`` () =\n  toRadians 90.0 |> should equal (System.Math.PI \/ 2.0)\n\n[<Test>]\nlet ``Verify that pi\/3 is 60 degrees`` () =\n  toRadians 60.0 |> should equal (System.Math.PI \/ 3.0)\n\n[<Test>]\nlet ``Verify that sin 180 returns 0`` () =\n  let x = System.Math.Sin (toRadians 180.0)\n  System.Math.Round(x,5) |> should equal 0\n\n[<Test>]\nlet ``Verify that cos 180 returns -1`` () =\n  let x = System.Math.Cos (toRadians 180.0)\n  System.Math.Round(x,5) |> should equal -1\n\n[<Test>]\nlet ``Verify that tan 180 returns 0`` () =\n  let x = System.Math.Tan (toRadians 180.0)\n  System.Math.Round(x,5) |> should equal 0\n\n[<Test>]\nlet ``Verify that sin 90 returns 1`` () =\n  let x = System.Math.Sin (toRadians 90.0)\n  System.Math.Round(x,5) |> should equal 1\n\n[<Test>]\nlet ``Verify that cos 90 returns -1`` () =\n  let x = System.Math.Cos (toRadians 90.0)\n  System.Math.Round(x,5) |> should equal 0\n\n[<Test>]\nlet ``Verify that sin 60 returns sqrt 3\/2`` () =\n  let actual = System.Math.Sin (toRadians 60.0)\n  let expected = System.Math.Round((System.Math.Sqrt 3.0) \/ 2.0, 5)\n  System.Math.Round(actual,5) |> should equal expected\n\n[<Test>]\nlet ``Verify that cos 60 returns -1`` () =\n  let x = System.Math.Cos (toRadians 60.0)\n  System.Math.Round(x,5) |> should equal 0.5\n\n[<Test>]\nlet ``Verify that cos and sin of 45 return same value`` () =\n  let c = System.Math.Cos (toRadians 45.0)\n  let s = System.Math.Sin (toRadians 45.0)\n  System.Math.Round(c,5) = System.Math.Round(s,5) |> should be True\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":3891}
    {"lang_cluster":"F#","source_code":"\nopen System\n\nlet rec loop n = Console.WriteLine( n:int )\n                 Threading.Thread.Sleep( 500 )\n                 loop (n + 1)\n\nlet main() =\n   let start = DateTime.Now\n   Console.CancelKeyPress.Add(\n      fun _ -> let span = DateTime.Now - start\n               printfn \"Program has run for\u00a0%.0f seconds\" span.TotalSeconds\n             )\n   loop 1\n\nmain()\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.","id":3892}
    {"lang_cluster":"F#","source_code":"\n\/\/ Increment a numerical string. Nigel Galloway: April 4th., 2023\nlet inc=int>>(+)1>>string\nprintfn \"%s\" (inc(\"1234\"))\n\n\n","human_summarization":"\"Increments a given numerical string.\"","id":3893}
    {"lang_cluster":"F#","source_code":"\nopen System\n\nlet (|SeqNode|SeqEmpty|) s =\n    if Seq.isEmpty s then SeqEmpty\n    else SeqNode ((Seq.head s), Seq.skip 1 s)\n\n[<EntryPoint>]\nlet main args =\n    let splitBySeparator (str : string) = Seq.ofArray (str.Split('\/'))\n\n    let rec common2 acc = function\n        | SeqEmpty -> Seq.ofList (List.rev acc)\n        | SeqNode((p1, p2), rest) ->\n            if p1 = p2 then common2 (p1::acc) rest\n            else Seq.ofList (List.rev acc)\n\n    let commonPrefix paths =\n        match Array.length(paths) with\n        | 0 -> [||]\n        | 1 -> Seq.toArray (splitBySeparator paths.[0])\n        | _ ->\n            let argseq = Seq.ofArray paths\n            Seq.fold (\n                fun (acc : seq<string>) items ->\n                    common2 [] (List.ofSeq (Seq.zip acc (splitBySeparator items)))\n            ) (splitBySeparator (Seq.head argseq)) (Seq.skip 1 argseq)\n            |> Seq.toArray\n\n    printfn \"The common preffix is: %A\" (String.Join(\"\/\", (commonPrefix args)))\n    0\n\n\nThe common preffix is: \"\/home\/user1\/tmp\"\n","human_summarization":"\"Code identifies the common directory path from a set of given directory paths using a specified directory separator character.\"","id":3894}
    {"lang_cluster":"F#","source_code":"\nlet rnd=System.Random()\nlet sottolo(n:int[])=let rec fN g=match g with -1|0->() |_->let e=rnd.Next(g-1) in let l=n.[g] in n.[g]<-n.[e]; n.[e]<-l; fN (g-1) in fN((Array.length n)-1)\n[[||];[|10|];[|10;20|];[|10;20;30|];[|11..22|]]|>List.iter(fun n->printf \"%A->\" n; sottolo n; printfn \"%A\" n)\n\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":3895}
    {"lang_cluster":"F#","source_code":"\n\nopen Microsoft.FSharp.Data.TypeProviders\n\ntype Wsdl = WsdlService<\"http:\/\/example.com\/soap\/wsdl\">\nlet result = Wsdl.soapFunc(\"hello\")\nlet result2 = Wsdl.anotherSoapFunc(34234)\n\n","human_summarization":"implement a SOAP client that accesses and calls the functions soapFunc( ) and anotherSoapFunc( ) defined at http:\/\/example.com\/soap\/wsdl. The availability of functions and parameter types are verified at compile time with support for auto-completion and parameter information. Note: The task is flagged for clarification and the current code may be marked incorrect pending task clarification.","id":3896}
    {"lang_cluster":"F#","source_code":"\n\nlet rec splitToFives list = \n    match list with\n        | a::b::c::d::e::tail ->\n            ([a;b;c;d;e])::(splitToFives tail)\n        | [] -> []\n        | _ -> \n                let left = 5 - List.length (list)\n                let last = List.append list (List.init left (fun _ -> System.Double.PositiveInfinity) )\n                in [last]\n\nlet medianFromFives =\n    List.map ( fun (i:float list) ->\n        List.nth (List.sort i) 2 ) \n\nlet start l = \n    let rec magicFives list k =\n        if List.length(list) <= 10 then\n            List.nth (List.sort list) (k-1)\n        else\n            let s = splitToFives list\n            let M = medianFromFives s\n            let m = magicFives M (int(System.Math.Ceiling((float(List.length M))\/2.)))\n            let (ll,lg) = List.partition ( fun i -> i < m ) list\n            let (le,lg) = List.partition ( fun i -> i = m ) lg\n            in\n               if (List.length ll >= k) then \n                    magicFives ll k\n               else if (List.length ll + List.length le >= k ) then m\n               else\n                    magicFives lg (k-(List.length ll)-(List.length le))\n    in\n        let len = List.length l in\n        if (len % 2 = 1) then\n            magicFives l ((len+1)\/2)\n        else\n            let a = magicFives l (len\/2)\n            let b = magicFives l ((len\/2)+1)\n            in (a+b)\/2.\n\n\nlet z = [1.;5.;2.;8.;7.;2.]\nstart z\nlet z' = [1.;5.;2.;8.;7.]\nstart z'\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers, handling even number of elements by returning the average of two middle values. It uses the selection algorithm for optimal performance. It also includes tasks for calculating various statistical measures such as mean, mode, standard deviation, and implements the Median of Medians algorithm.","id":3897}
    {"lang_cluster":"F#","source_code":"\nlet fizzbuzz n =\n    match n%3 = 0, n%5 = 0 with\n    | true, false -> \"fizz\"\n    | false, true -> \"buzz\"\n    | true, true  -> \"fizzbuzz\"\n    | _ -> string n\n\nlet printFizzbuzz() =\n    [1..100] |> List.iter (fizzbuzz >> printfn \"%s\")\n[1..100] \n|> List.map (fun x ->\n            match x with \n            | _ when x\u00a0% 15 = 0 ->\"fizzbuzz\"\n            | _ when x\u00a0% 5 = 0 -> \"buzz\"\n            | _ when x\u00a0% 3 = 0 -> \"fizz\"\n            | _ ->  x.ToString())\n|> List.iter (fun x -> printfn \"%s\" x)\n\nlet (|MultipleOf|_|) divisors number =\n    if Seq.exists ((%) number >> (<>) 0) divisors\n    then None\n    else Some ()\n\nlet fizzbuzz = function\n| MultipleOf [3; 5] -> \"fizzbuzz\"\n| MultipleOf [3]    -> \"fizz\"\n| MultipleOf [5]    -> \"buzz\"\n| n                 -> string n\n\n{ 1 .. 100 }\n|> Seq.iter (fizzbuzz >> printfn \"%s\")\n","human_summarization":"The code prints integers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":3898}
    {"lang_cluster":"F#","source_code":"\nopen System.Drawing \nopen System.Windows.Forms\ntype Complex =\n    { \n        re : float;\n        im : float\n    }\nlet cplus (x:Complex) (y:Complex) : Complex = \n    {\n        re = x.re + y.re;\n        im = x.im + y.im\n    }\nlet cmult (x:Complex) (y:Complex) : Complex = \n    {\n        re = x.re * y.re - x.im * y.im;\n        im = x.re * y.im + x.im * y.re;\n    }\n\nlet norm (x:Complex) : float =\n    x.re*x.re + x.im*x.im\n\ntype Mandel = class\n    inherit Form\n    static member xPixels = 500\n    static member yPixels = 500\n    val mutable bmp : Bitmap\n    member x.mandelbrot xMin xMax yMin yMax maxIter =\n        let rec mandelbrotIterator z c n =\n            if (norm z) > 2.0 then false else\n                match n with\n                    | 0 -> true\n                    | n -> let z' = cplus ( cmult z z ) c in\n                            mandelbrotIterator z' c (n-1)\n        let dx = (xMax - xMin) \/ (float (Mandel.xPixels))\n        let dy = (yMax - yMin) \/ (float (Mandel.yPixels))\n        in\n        for xi = 0 to Mandel.xPixels-1 do\n            for yi = 0 to Mandel.yPixels-1 do\n                let c = {re = xMin + (dx * float(xi) ) ;\n                         im = yMin + (dy * float(yi) )} in\n                if (mandelbrotIterator {re=0.;im=0.;} c maxIter) then\n                    x.bmp.SetPixel(xi,yi,Color.Azure)\n                else\n                    x.bmp.SetPixel(xi,yi,Color.Black)\n            done\n        done\n\n    member public x.generate () = x.mandelbrot (-1.5) 0.5 (-1.0) 1.0 200 ; x.Refresh()\n\n    new() as x = {bmp = new Bitmap(Mandel.xPixels , Mandel.yPixels)} then\n        x.Text <- \"Mandelbrot set\" ;\n        x.Width <- Mandel.xPixels ;\n        x.Height <- Mandel.yPixels ;\n        x.BackgroundImage <- x.bmp;\n        x.generate();\n        x.Show();   \nend\n\nlet f = new Mandel()\ndo Application.Run(f)\n\n\nlet getMandelbrotValues width height maxIter ((xMin,xMax),(yMin,yMax)) =\n  let mandIter (cr:float,ci:float) =\n    let next (zr,zi) = (cr + (zr * zr - zi * zi)), (ci + (zr * zi + zi * zr))\n    let rec loop = function\n      | step,_ when step=maxIter->0\n      | step,(zr,zi) when ((zr * zr + zi * zi) > 2.0) -> step\n      | step,z -> loop ((step + 1), (next z))\n    loop (0,(0.0, 0.0))\n  let forPos =\n    let dx, dy = (xMax - xMin) \/ (float width), (yMax - yMin) \/ (float height)\n    fun y x -> mandIter ((xMin + dx * float(x)), (yMin + dy * float(y)))\n  [0..height-1] |> List.map(fun y->[0..width-1] |> List.map (forPos y))\n\n\ngetMandelbrotValues 80 25 50 ((-2.0,1.0),(-1.0,1.0))\n|> List.map(fun row-> row |> List.map (function | 0 ->\" \" |_->\".\") |> String.concat \"\")\n|> List.iter (printfn \"%s\")\n\n\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions. The results are displayed in both text and graphical format.","id":3899}
    {"lang_cluster":"F#","source_code":"\nlet numbers = [| 1..10 |]\nlet sum = numbers |> Array.sum\nlet product = numbers |> Array.reduce (*)\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":3900}
    {"lang_cluster":"F#","source_code":"\nlet isLeapYear = System.DateTime.IsLeapYear\nassert isLeapYear 1996\nassert isLeapYear 2000\nassert not (isLeapYear 2001)\nassert not (isLeapYear 1900)\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":3901}
    {"lang_cluster":"F#","source_code":"\n\nlet fxyz x y z : uint32 = (x &&& y) ||| (~~~x &&& z)\nlet gxyz x y z : uint32 = (z &&& x) ||| (~~~z &&& y)\nlet hxyz x y z : uint32 = x ^^^ y ^^^ z\nlet ixyz x y z : uint32 = y ^^^ (x ||| ~~~z)\nlet fghi = [ fxyz; gxyz; hxyz; ixyz ] |> List.collect (List.replicate 16)\nlet g1Idx = id\nlet g2Idx i = (5 * i + 1) % 16\nlet g3Idx i = (3 * i + 5) % 16\nlet g4Idx i = (7 * i) % 16\n\nlet gIdxs = \n  [ g1Idx; g2Idx; g3Idx; g4Idx ]\n  |> List.collect (List.replicate 16)\n  |> List.map2 (fun idx func -> func idx) [ 0..63 ]\n\nlet s = \n  [ [ 7; 12; 17; 22 ]\n    [ 5; 9; 14; 20 ]\n    [ 4; 11; 16; 23 ]\n    [ 6; 10; 15; 21 ] ]\n  |> List.collect (List.replicate 4)\n  |> List.concat\n\nlet k = \n  [ 1...64. ] |> List.map (sin\n                           >> abs\n                           >> ((*) (2. ** 32.))\n                           >> floor\n                           >> uint32)\n\ntype MD5 = \n  { a : uint32\n    b : uint32\n    c : uint32\n    d : uint32 }\n\nlet initialMD5 = \n  { a = 0x67452301u\n    b = 0xefcdab89u\n    c = 0x98badcfeu\n    d = 0x10325476u }\n\nlet md5round (msg : uint32 []) { MD5.a = a; MD5.b = b; MD5.c = c; MD5.d = d } i = \n  let rotateL32 r x = (x <<< r) ||| (x >>> (32 - r))\n  let f = fghi.[i] b c d\n  let a' = b + (a + f + k.[i] + msg.[gIdxs.[i]]\n                |> rotateL32 s.[i])\n  { a = d\n    b = a'\n    c = b\n    d = c }\n\nlet md5plus m (bs : byte []) = \n  let msg = \n    bs\n    |> Array.chunkBySize 4\n    |> Array.take 16\n    |> Array.map (fun elt -> System.BitConverter.ToUInt32(elt, 0))\n  \n  let m' = List.fold (md5round msg) m [ 0..63 ]\n  { a = m.a + m'.a\n    b = m.b + m'.b\n    c = m.c + m'.c\n    d = m.d + m'.d }\n\nlet padMessage (msg : byte []) = \n  let msgLen = Array.length msg\n  let msgLenInBits = (uint64 msgLen) * 8UL\n  \n  let lastSegmentSize = \n    let m = msgLen % 64\n    if m = 0 then 64\n    else m\n  \n  let padLen = \n    64 - lastSegmentSize + (if lastSegmentSize >= 56 then 64\n                            else 0)\n  \n  [| yield 128uy\n     for i in 2..padLen - 8 do\n       yield 0uy\n     for i in 0..7 do\n       yield ((msgLenInBits >>> (8 * i)) |> byte) |]\n  |> Array.append msg\n\nlet md5sum (msg : string) = \n  System.Text.Encoding.ASCII.GetBytes msg\n  |> padMessage\n  |> Array.chunkBySize 64\n  |> Array.fold md5plus initialMD5\n  |> (fun { MD5.a = a; MD5.b = b; MD5.c = c; MD5.d = d } -> \n    System.BitConverter.GetBytes a\n    |> (fun x -> System.BitConverter.GetBytes b |> Array.append x)\n    |> (fun x -> System.BitConverter.GetBytes c |> Array.append x)\n    |> (fun x -> System.BitConverter.GetBytes d |> Array.append x))\n  |> Array.map (sprintf \"%02X\")\n  |> Array.reduce (+)\n\n","human_summarization":"implement the MD5 Message Digest Algorithm directly without using any built-in or external hashing libraries. The implementation produces a correct message digest for an input string. It also provides practical illustrations of bit manipulation, unsigned integers, and working with little-endian data. The code does not mimic all calling modes and does not use any built-in MD5 functions or library routines written in other languages. The implementation is tested and verified using the verification strings and hashes from RFC 1321.","id":3902}
    {"lang_cluster":"F#","source_code":"\n\/\/ A function to generate department numbers. Nigel Galloway: May 2nd., 2018\ntype dNum = {Police:int; Fire:int; Sanitation:int}\nlet fN n=n.Police%2=0&&n.Police+n.Fire+n.Sanitation=12&&n.Police<>n.Fire&&n.Police<>n.Sanitation&&n.Fire<>n.Sanitation\nList.init (7*7*7) (fun n->{Police=n%7+1;Fire=(n\/7)%7+1;Sanitation=(n\/49)+1})|>List.filter fN|>List.iter(printfn \"%A\")\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":3903}
    {"lang_cluster":"F#","source_code":"\n\nlet str = \"hello\"\nlet additionalReference = str\nlet deepCopy = System.String.Copy( str )\n\nprintfn \"%b\" <| System.Object.ReferenceEquals( str, additionalReference ) \/\/ prints true\nprintfn \"%b\" <| System.Object.ReferenceEquals( str, deepCopy )            \/\/ prints false\n\n","human_summarization":"demonstrate how to copy a string in .NET by distinguishing between copying the contents of a string and making an additional reference to an existing string, using a static method of the System.String type.","id":3904}
    {"lang_cluster":"F#","source_code":"\nlet rec f n =\n    match n with\n    | 0 -> 1\n    | _ -> n - (m (f (n-1)))\nand m n =\n    match n with\n    | 0 -> 0\n    | _ -> n - (f (m (n-1)))\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions call themselves and each other. If the programming language does not support mutually recursive functions, it should be stated.","id":3905}
    {"lang_cluster":"F#","source_code":"\nlet list = [\"a\"; \"b\"; \"c\"; \"d\"; \"e\"]\nlet rand = new System.Random()\nprintfn \"%s\" list.[rand.Next(list.Length)]\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":3906}
    {"lang_cluster":"F#","source_code":"open System\n\nlet decode uri = Uri.UnescapeDataString(uri)\n\n[<EntryPoint>]\nlet main argv =\n    printfn \"%s\" (decode \"http%3A%2F%2Ffoo%20bar%2F\")\n    0\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":3907}
    {"lang_cluster":"F#","source_code":"\n\nlet rec binarySearch (myArray:array<IComparable>, low:int, high:int, value:IComparable) =\n    if (high < low) then\n        null\n    else\n        let mid = (low + high) \/ 2\n\n        if (myArray.[mid] > value) then\n            binarySearch (myArray, low, mid-1, value)\n        else if (myArray.[mid] < value) then\n            binarySearch (myArray, mid+1, high, value)\n        else\n            myArray.[mid]\n\n","human_summarization":"The code implements a binary search algorithm, which is a \"divide and conquer\" strategy to find a specific value within a sorted integer array. The algorithm can be either recursive or iterative and it divides the search range into halves until the target value is found. The code also handles multiple instances of the target value and returns the index of the found value. Additionally, it provides the functionality to return the leftmost and rightmost insertion points for the target value. The code also contains a fix for potential overflow bugs.","id":3908}
    {"lang_cluster":"F#","source_code":"\n\n#light\n[<EntryPoint>]\nlet main args =\n    Array.iter (fun x -> printfn \"%s\" x) args\n    0\n\n","human_summarization":"<output> retrieves the list of command-line arguments provided to the program, and prints each argument on a separate line. It also includes functionality for parsing these arguments intelligently. The program is designed to be run directly with specific arguments, as demonstrated with the example command line: myprogram -c \"alpha beta\" -h \"gamma\".<\/output>","id":3909}
    {"lang_cluster":"F#","source_code":"\n\nopen System\nopen System.Drawing\nopen System.Windows.Forms\n\n\/\/ define units of measurement\n[<Measure>] type m;  \/\/ metres\n[<Measure>] type s;  \/\/ seconds\n\n\/\/ a pendulum is represented as a record of physical quantities\ntype Pendulum =\n { length   : float<m>\n   gravity  : float<m\/s^2>\n   velocity : float<m\/s>\n   angle    : float\n }\n\n\/\/ calculate the next state of a pendulum\nlet next pendulum deltaT : Pendulum =\n  let k = -pendulum.gravity \/ pendulum.length\n  let acceleration = k * Math.Sin pendulum.angle * 1.0<m> \n  let newVelocity = pendulum.velocity + acceleration * deltaT\n  let newAngle = pendulum.angle + newVelocity * deltaT \/ 1.0<m>\n  { pendulum with velocity = newVelocity; angle = newAngle }\n\n\/\/ paint a pendulum (using hard-coded screen coordinates)\nlet paint pendulum (gr: System.Drawing.Graphics) =\n  let homeX = 160\n  let homeY = 50\n  let length = 140.0\n  \/\/ draw plate\n  gr.DrawLine( new Pen(Brushes.Gray, width=2.0f), 0, homeY, 320, homeY )\n  \/\/ draw pivot\n  gr.FillEllipse( Brushes.Gray,           homeX-5, homeY-5, 10, 10 )\n  gr.DrawEllipse( new Pen(Brushes.Black), homeX-5, homeY-5, 10, 10 )\n  \/\/ draw the pendulum itself\n  let x = homeX + int( length * Math.Sin pendulum.angle )\n  let y = homeY + int( length * Math.Cos pendulum.angle )\n  \/\/ draw rod\n  gr.DrawLine( new Pen(Brushes.Black, width=3.0f), homeX, homeY, x, y )\n  \/\/ draw bob\n  gr.FillEllipse( Brushes.Yellow,         x-15, y-15, 30, 30 )\n  gr.DrawEllipse( new Pen(Brushes.Black), x-15, y-15, 30, 30 )\n\n\/\/ defines an operator \"-?\" that calculates the time from t2 to t1  \n\/\/ where t2 is optional\nlet (-?) (t1: DateTime) (t2: DateTime option) : float<s> =\n  match t2 with\n  | None   -> 0.0<s> \/\/ only one timepoint given -> difference is 0\n  | Some t -> (t1 - t).TotalSeconds * 1.0<s>\n\n\/\/ our main window is double-buffered form that reacts to paint events\ntype PendulumForm() as self = \n  inherit Form(Width=325, Height=240, Text=\"Pendulum\")\n  let mutable pendulum = { length   = 1.0<m>;\n                           gravity  = 9.81<m\/s^2>\n                           velocity = 0.0<m\/s>\n                           angle    = Math.PI \/ 2.0\n                         }\n  let mutable lastPaintedAt = None\n  let updateFreq = 0.01<s>\n\n  do self.DoubleBuffered <- true\n     self.Paint.Add( fun args ->\n       let now = DateTime.Now\n       let deltaT = now -? lastPaintedAt |> min 0.01<s> \n       lastPaintedAt <- Some now\n\n       pendulum <- next pendulum deltaT\n\n       let gr = args.Graphics\n       gr.Clear( Color.LightGray )\n       paint pendulum gr\n\n       \/\/ initiate a new paint event after a while (non-blocking)\n       async { do! Async.Sleep( int( 1000.0 * updateFreq \/ 1.0<s> ) )\n               self.Invalidate()\n            }\n       |> Async.Start \n     )\n\n[<STAThread>]\nApplication.Run( new PendulumForm( Visible=true ) )\n\n","human_summarization":"simulate and animate a simple gravity pendulum using F#'s support for units of measure.","id":3910}
    {"lang_cluster":"F#","source_code":"\n\nopen Newtonsoft.Json\ntype Person = {ID: int; Name:string}\nlet xs = [{ID = 1; Name = \"First\"} ; { ID = 2; Name = \"Second\"}]\n\nlet json = JsonConvert.SerializeObject(xs)\njson |> printfn \"%s\"\n\nlet xs1 = JsonConvert.DeserializeObject<Person list>(json)\nxs1 |> List.iter(fun x -> printfn \"%i  %s\" x.ID x.Name)\n\n\n[{\"ID\":1,\"Name\":\"First\"},{\"ID\":2,\"Name\":\"Second\"}]\n1  First\n2  Second\n\n\nopen FSharp.Data\nopen FSharp.Data.JsonExtensions\n\ntype Person = {ID: int; Name:string}\nlet xs = [{ID = 1; Name = \"First\"} ; { ID = 2; Name = \"Second\"}]\n\nlet infos = xs |> List.map(fun x -> JsonValue.Record([| \"ID\", JsonValue.Number(decimal x.ID); \"Name\", JsonValue.String(x.Name) |]))\n            |> Array.ofList |> JsonValue.Array\n\ninfos |> printfn \"%A\"\nmatch JsonValue.Parse(infos.ToString()) with\n| JsonValue.Array(x) -> x |> Array.map(fun x -> {ID = System.Int32.Parse(string x?ID); Name = (string x?Name)})\n| _ -> failwith \"fail json\"\n|> Array.iter(fun x -> printfn \"%i  %s\" x.ID x.Name)\n\n\n[\n  {\n    \"ID\": 1,\n    \"Name\": \"First\"\n  },\n  {\n    \"ID\": 2,\n    \"Name\": \"Second\"\n  }\n]\n1  \"First\"\n2  \"Second\"\n\n\nopen FSharp.Data\ntype Person = {ID: int; Name:string}\ntype People = JsonProvider<\"\"\" [{\"ID\":1,\"Name\":\"First\"},{\"ID\":2,\"Name\":\"Second\"}] \"\"\">\n\nPeople.GetSamples()\n|> Array.map(fun x -> {ID = x.Id; Name = x.Name} )\n|> Array.iter(fun x -> printfn \"%i  %s\" x.ID x.Name)\n\nPrint:1  First\n2  Second\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure and serialize it into JSON using objects and arrays. The codes ensure the JSON is valid and demonstrate different methods including Json.Net, FSharp.Data, and JsonProvider.\"","id":3911}
    {"lang_cluster":"F#","source_code":"\nlet nthroot n A =\n    let rec f x =\n        let m = n - 1.\n        let x' = (m * x + A\/x**m) \/ n\n        match abs(x' - x) with\n        | t when t < abs(x * 1e-9) -> x'\n        | _ -> f x'\n    f (A \/ double n)\n\n[<EntryPoint>]\nlet main args =\n    if args.Length <> 2 then\n        eprintfn \"usage: nthroot n A\"\n        exit 1\n    let (b, n) = System.Double.TryParse(args.[0])\n    let (b', A) = System.Double.TryParse(args.[1])\n    if (not b) || (not b') then\n        eprintfn \"error: parameter must be a number\"\n        exit 1\n    printf \"%A\" (nthroot n A)\n    0\n\nCompiled using fsc nthroot.fs example output:nthroot 0.5 7\n49.0\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":3912}
    {"lang_cluster":"F#","source_code":"\nprintfn \"%s\" (System.Net.Dns.GetHostName())\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":3913}
    {"lang_cluster":"F#","source_code":"open System\n\nlet leo l0 l1 d =\n    Seq.unfold (fun (x, y) -> Some (x, (y, x + y + d))) (l0, l1)\n\nlet leonardo = leo 1 1 1\nlet fibonacci = leo 0 1 0\n\n[<EntryPoint>]\nlet main _ = \n    let leoNums = Seq.take 25 leonardo |> Seq.chunkBySize 16\n    printfn \"First 25 of the (1, 1, 1) Leonardo numbers:\\n%A\" leoNums\n    Console.WriteLine()\n\n    let fibNums = Seq.take 25 fibonacci |> Seq.chunkBySize 16\n    printfn \"First 25 of the (0, 1, 0) Leonardo numbers (= Fibonacci number):\\n%A\" fibNums\n\n    0 \/\/ return an integer exit code\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":3914}
    {"lang_cluster":"F#","source_code":"\nopen System\nopen System.Text.RegularExpressions\n\n\/\/ Some utilities\nlet (|Parse|_|) regex str =\n   let m = Regex(regex).Match(str)\n   if m.Success then Some ([for g in m.Groups -> g.Value]) else None\nlet rec gcd x y = if x = y || x = 0 then y else if x < y then gcd y x else gcd y (x-y)\nlet abs (x : int) = Math.Abs x\nlet sign (x: int) = Math.Sign x\nlet cint s = Int32.Parse(s)\nlet replace m (s : string) t = Regex.Replace(t, m, s)\n\n\/\/ computing in Rationals\ntype Rat(x : int, y : int) =\n    let g = if y <> 0 then gcd (abs x) (abs y) else raise <| DivideByZeroException()\n    member this.n = sign y * x \/ g   \/\/ store a minus sign in the numerator\n    member this.d =\n        if y <> 0 then sign y * y \/ g else raise <| DivideByZeroException()\n    static member (~-) (x : Rat) = Rat(-x.n, x.d)\n    static member (+) (x : Rat, y : Rat) = Rat(x.n * y.d + y.n * x.d, x.d * y.d)\n    static member (-) (x : Rat, y : Rat) = x + Rat(-y.n, y.d)\n    static member (*) (x : Rat, y : Rat) = Rat(x.n * y.n, x.d * y.d)\n    static member (\/) (x : Rat, y : Rat) = x * Rat(y.d, y.n)\n    override this.ToString() = sprintf @\"<%d,%d>\" this.n this.d\n    new(x : string, y : string) = if y = \"\" then Rat(cint x, 1) else Rat(cint x, cint y)\n\n\/\/ Due to the constraints imposed by the game (reduced set\n\/\/ of operators, all left associativ) we can get away with a repeated reduction\n\/\/ to evaluate the algebraic expression.\nlet rec reduce (str :string) =\n    let eval (x : Rat) (y : Rat) = function\n    | \"*\" -> x * y | \"\/\" -> x \/ y | \"+\" -> x + y | \"-\" -> x - y | _ -> failwith \"unknown op\"\n    let subst s r = str.Replace(s, r.ToString())\n    let rstr =\n        match str with\n        | Parse @\"\\(<(-?\\d+),(\\d+)>([*\/+-])<(-?\\d+),(\\d+)>\\)\" [matched; xn; xd; op; yn; yd] -> \n            subst matched <| eval (Rat(xn,xd)) (Rat(yn,yd)) op\n        | Parse @\"<(-?\\d+),(\\d+)>([*\/])<(-?\\d+),(\\d+)>\" [matched; xn; xd; op; yn; yd] -> \n            subst matched <| eval (Rat(xn,xd)) (Rat(yn,yd)) op\n        | Parse @\"<(-?\\d+),(\\d+)>([+-])<(-?\\d+),(\\d+)>\" [matched; xn; xd; op; yn; yd] -> \n            subst matched <| eval (Rat(xn,xd)) (Rat(yn,yd)) op\n        | Parse @\"\\(<(-?\\d+),(\\d+)>\\)\" [matched; xn; xd] -> \n            subst matched <| Rat(xn,xd)\n        | Parse @\"(?<!>)-<(-?\\d+),(\\d+)>\" [matched; xn; xd] -> \n            subst matched <| -Rat(xn,xd)\n        | _ -> str\n    if str = rstr then str else reduce rstr\n\nlet gameLoop() =\n    let checkInput dddd input =\n        match input with\n        | \"n\" | \"q\" -> Some(input)\n        | Parse @\"[^1-9()*\/+-]\" [c] ->\n            printfn \"You used an illegal character in your expression: %s\" c\n            None\n        | Parse @\"^\\D*(\\d)\\D+(\\d)\\D+(\\d)\\D+(\\d)(?:\\D*(\\d))*\\D*$\" [m; d1; d2; d3; d4; d5] ->\n            if d5 = \"\" && (String.Join(\" \", Array.sort [|d1;d2;d3;d4|])) = dddd then Some(input)\n            elif d5 = \"\" then\n                printfn \"Use this 4 digits with operators in between: %s.\" dddd\n                None\n            else \n                printfn \"Use only this 4 digits with operators in between: %s.\" dddd\n                None\n        | _ ->\n            printfn \"Use all 4 digits with operators in between: %s.\" dddd\n            None\n        \n    let rec userLoop dddd  =\n        let tryAgain msg =\n            printfn \"%s\" msg\n            userLoop dddd\n        printf \"[Expr|n|q]: \"\n        match Console.ReadLine() |> replace @\"\\s\" \"\" |> checkInput dddd with\n        | Some(input) -> \n            let data = input |> replace @\"((?<!\\d)-)?\\d+\" @\"<$&,1>\"\n            match data with\n            | \"n\" -> true | \"q\" -> false\n            | _ ->\n                try\n                    match reduce data with\n                    | Parse @\"^<(-?\\d+),(\\d+)>$\" [_; x; y] ->\n                        let n, d = (cint x), (cint y)\n                        if n = 24 then\n                            printfn \"Correct!\"\n                            true\n                        elif d=1 then tryAgain <| sprintf \"Wrong! Value = %d.\" n\n                        else tryAgain <| sprintf \"Wrong! Value = %d\/%d.\" n d\n                    | _ -> tryAgain \"Wrong! not a well-formed expression!\"\n                with\n                    | :? System.DivideByZeroException ->\n                        tryAgain \"Wrong! Your expression results in a division by zero!\"\n                    | ex ->\n                        tryAgain <| sprintf \"There is an unforeseen problem with yout input: %s\" ex.Message\n        | None -> userLoop dddd\n\n    let random = new Random(DateTime.Now.Millisecond)\n    let rec loop() =\n        let dddd = String.Join(\" \", Array.init 4 (fun _ -> 1 + random.Next 9) |> Array.sort)\n        printfn \"\\nCompute 24 from the following 4 numbers: %s\" dddd\n        printfn \"Use them in any order with * \/ + - and parentheses; n = new numbers; q = quit\"\n        if userLoop dddd then loop()\n\n    loop()\n\ngameLoop()\n\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":3915}
    {"lang_cluster":"F#","source_code":"\nopen System\nopen System.Text.RegularExpressions\n\nlet encode data =\n    \/\/ encodeData\u00a0: seq<'T> -> seq<int * 'T> i.e. Takes a sequence of 'T types and return a sequence of tuples containing the run length and an instance of 'T.\n    let rec encodeData input =\n        seq { if not (Seq.isEmpty input) then\n                 let head = Seq.head input              \n                 let runLength = Seq.length (Seq.takeWhile ((=) head) input)\n                 yield runLength, head\n                 yield! encodeData (Seq.skip runLength input) }\n \n    encodeData data |> Seq.fold(fun acc (len, d) -> acc + len.ToString() + d.ToString()) \"\"\n\nlet decode str =\n    [ for m in Regex.Matches(str, \"(\\d+)(.)\") -> m ]\n    |> List.map (fun m -> Int32.Parse(m.Groups.[1].Value), m.Groups.[2].Value)\n    |> List.fold (fun acc (len, s) -> acc + String.replicate len s) \"\"\n\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":3916}
    {"lang_cluster":"F#","source_code":"open System\n\n[<EntryPoint>]\nlet main args =\n    let s = \"hello\"\n    Console.Write(s)\n    Console.WriteLine(\" literal\")\n    let s2 = s + \" literal\"\n    Console.WriteLine(s2)\n    0\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":3917}
    {"lang_cluster":"F#","source_code":"\nopen System\n\n[<EntryPoint>]\nlet main args =\n    printfn \"%s\" (Uri.EscapeDataString(args.[0]))\n    0\n\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":3918}
    {"lang_cluster":"F#","source_code":"\n\/\/ Common sorted list. Nigel Galloway: February 25th., 2021\nlet nums=[|[5;1;3;8;9;4;8;7];[3;5;9;8;4];[1;3;7;9]|]\nprintfn \"%A\" (nums|>Array.reduce(fun n g->n@g)|>List.distinct|>List.sort)\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":3919}
    {"lang_cluster":"F#","source_code":"\n\/\/Fill a knapsack optimally - Nigel Galloway: February 1st., 2015\nlet items = [(\"beef\", 3.8, 36);(\"pork\", 5.4, 43);(\"ham\", 3.6, 90);(\"greaves\", 2.4, 45);(\"flitch\" , 4.0, 30);(\"brawn\", 2.5, 56);(\"welt\", 3.7, 67);(\"salami\" , 3.0, 95);(\"sausage\", 5.9, 98)]\n            |> List.sortBy(fun(_,weight,value) -> float(-value)\/weight) \n\n\nlet knap items maxW=\n  let rec take(n,g,a) = \n    match g with\n      | i::e -> let name, weight, value = i\n                let total = n + weight\n                if total <= maxW then \n                  printfn \"Take all %s\" name\n                  take(total, e, a+float(value))\n                else\n                  printfn \"Take %0.2f kg of %s\\nTotal value of swag is %0.2f\" (maxW - n) name (a + (float(value)\/weight)*(maxW - n))\n      | []   -> printfn \"Everything taken! Total value of swag is \u00a3%0.2f; Total weight of bag is %0.2fkg\" a n\n  take(0.0, items, 0.0)\n\n\n","human_summarization":"\"Implement a solution for the continuous knapsack problem where a thief maximizes his profit by selecting and potentially cutting items from a butcher's shop. The total weight of the items should not exceed 15 kg. The price of an item after cutting is proportional to its original price by the ratio of masses.\"","id":3920}
    {"lang_cluster":"F#","source_code":"\n\nlet xss = Seq.groupBy (Array.ofSeq >> Array.sort) (System.IO.File.ReadAllLines \"unixdict.txt\")\nSeq.map snd xss |> Seq.filter (Seq.length >> ( = ) (Seq.map (snd >> Seq.length) xss |> Seq.max))\n\n\nval it : string seq seq =\n  seq\n    [seq [\"abel\"; \"able\"; \"bale\"; \"bela\"; \"elba\"];\n     seq [\"alger\"; \"glare\"; \"lager\"; \"large\"; \"regal\"];\n     seq [\"angel\"; \"angle\"; \"galen\"; \"glean\"; \"lange\"];\n     seq [\"caret\"; \"carte\"; \"cater\"; \"crate\"; \"trace\"];\n     seq [\"elan\"; \"lane\"; \"lean\"; \"lena\"; \"neal\"];\n     seq [\"evil\"; \"levi\"; \"live\"; \"veil\"; \"vile\"]]\n\n","human_summarization":"The code reads a dictionary from a given URL, groups words by their sorted letters, identifies the longest sets of anagrams, and extracts these sets. It converts sorted letter sequences to arrays for accurate comparison. The process takes approximately 0.8 seconds to complete.","id":3921}
    {"lang_cluster":"F#","source_code":"open System\n\nlet blank x = new String(' ', String.length x)\n\nlet nextCarpet carpet = \n  List.map (fun x -> x + x + x) carpet @\n  List.map (fun x -> x + (blank x) + x) carpet @\n  List.map (fun x -> x + x + x) carpet\n \nlet rec sierpinskiCarpet n =\n  let rec aux n carpet =\n    if n = 0 then carpet\n             else aux (n-1) (nextCarpet carpet)\n  aux n [\"#\"]\n \nList.iter (printfn \"%s\") (sierpinskiCarpet 3)\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":3922}
    {"lang_cluster":"F#","source_code":"type 'a HuffmanTree =\n    | Leaf of int * 'a\n    | Node of int * 'a HuffmanTree * 'a HuffmanTree\n \nlet freq = function Leaf (f, _) | Node (f, _, _) -> f\nlet freqCompare a b = compare (freq a) (freq b)\n \nlet buildTree charFreqs =\n    let leaves = List.map (fun (c,f) -> Leaf (f,c)) charFreqs\n    let freqSort = List.sortWith freqCompare\n    let rec aux = function\n        | [] -> failwith \"empty list\"\n        | [a] -> a\n        | a::b::tl ->\n            let node = Node(freq a + freq b, a, b)\n            aux (freqSort(node::tl))\n    aux (freqSort leaves)\n \nlet rec printTree = function\n  | code, Leaf (f, c) ->\n      printfn \"%c\\t%d\\t%s\" c f (String.concat \"\" (List.rev code));\n  | code, Node (_, l, r) ->\n      printTree (\"0\"::code, l);\n      printTree (\"1\"::code, r)\n \nlet () =\n  let str = \"this is an example for huffman encoding\"\n  let charFreqs =\n    str |> Seq.groupBy id\n        |> Seq.map (fun (c, vals) -> (c, Seq.length vals))\n        |> Map.ofSeq\n         \n  let tree = charFreqs |> Map.toList |> buildTree\n  printfn \"Symbol\\tWeight\\tHuffman code\";\n  printTree ([], tree)\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":3923}
    {"lang_cluster":"F#","source_code":"open System.Windows.Forms\n\nlet mutable clickCount = 0\n\nlet form = new Form()\n\nlet label = new Label(Text = \"There have been no clicks yet.\", Dock = DockStyle.Top)\nform.Controls.Add(label)\n\nlet button = new Button(Text = \"Click me\", Dock = DockStyle.Bottom)\nbutton.Click.Add(fun _ ->\n    clickCount <- clickCount+1\n    label.Text <- sprintf \"Number of clicks: %i.\" clickCount)\nform.Controls.Add(button)\n\nApplication.Run(form)\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":3924}
    {"lang_cluster":"F#","source_code":"\n\nfor i in 10..-1..0 do\n  printfn \"%d\" i\n\n\nfor i = 10 downto 0 do\n  printfn \"%d\" i\n\n","human_summarization":"implement a countdown from 10 to 0 using a 'for' loop and the 'downto' keyword.","id":3925}
    {"lang_cluster":"F#","source_code":"\nmodule vigenere =\n    let keyschedule (key:string) =\n        let s = key.ToUpper().ToCharArray() |> Array.filter System.Char.IsLetter\n        let l = Array.length s\n        (fun n -> int s.[n % l])\n\n    let enc k c = ((c + k - 130) % 26) + 65\n    let dec k c = ((c - k + 130) % 26) + 65\n    let crypt f key = Array.mapi (fun n c -> f (key n) c |> char)\n\n    let encrypt key (plaintext:string) =\n        plaintext.ToUpper().ToCharArray()\n        |> Array.filter System.Char.IsLetter\n        |> Array.map int\n        |> crypt enc (keyschedule key)\n        |> (fun a -> new string(a))\n\n    let decrypt key (ciphertext:string) =\n        ciphertext.ToUpper().ToCharArray()\n        |> Array.map int\n        |> crypt dec (keyschedule key)\n        |> (fun a -> new string(a))\n\nlet passwd = \"Vigenere Cipher\"\nlet cipher = vigenere.encrypt passwd \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\nlet plain = vigenere.decrypt passwd cipher\nprintfn \"%s\\n%s\" cipher plain\n\nC:\\src\\fsharp>fsi vigenere.fsx\nWMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY\nBEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":3926}
    {"lang_cluster":"F#","source_code":"\nfor i in 2..2..8 do\n   printf \"%d, \" i\nprintfn \"done\"\n\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":3927}
    {"lang_cluster":"F#","source_code":"\nprintfn \"%.14f\" (List.fold(fun n g->n+1.0\/g) 0.0 [1.0..100.0]);;\n\n\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":3928}
    {"lang_cluster":"F#","source_code":"\n\nlet rnd : int -> int =\n  let gen = new System.Random()\n  fun max -> gen.Next(max)\n\n\/\/ randomly choose an element of a list\nlet choose (xs:_ list) = xs.[rnd xs.Length]\n\ntype Maze(width, height) =\n  \/\/ (x,y) -> have we been here before?\n  let visited = Array2D.create width height false\n  \/\/ (x,y) -> is there a wall between (x,y) and (x+1,y)?\n  let horizWalls = Array2D.create width height true\n  \/\/ (x,y) -> is there a wall between (x,y) and (x,y+1)?\n  let vertWalls = Array2D.create width height  true\n  \n  let isLegalPoint (x,y) =\n    x >= 0 && x < width && y >= 0 && y < height\n  \n  let neighbours (x,y) = \n    [(x-1,y);(x+1,y);(x,y-1);(x,y+1)] |> List.filter isLegalPoint\n    \n  let removeWallBetween (x1,y1) (x2,y2) =\n    if x1 <> x2 then\n      horizWalls.[min x1 x2, y1] <- false\n    else\n      vertWalls.[x1, min y1 y2] <- false\n \n  let rec visit (x,y as p) = \n    let rec loop ns =\n      let (nx,ny) as n = choose ns\n      if not visited.[nx,ny] then\n        removeWallBetween p n\n        visit n\n      match List.filter ((<>) n) ns with\n      | [] -> ()\n      | others -> loop others\n\n    visited.[x,y] <- true\n    loop (neighbours p)\n\n  do visit (rnd width, rnd height)\n\n  member x.Print() =\n    (\"+\" + (String.replicate width \"-+\")) ::\n    [for y in 0..(height-1) do\n       yield \"\\n|\"\n       for x in 0..(width-1) do \n         yield if horizWalls.[x,y] then \" |\" else \"  \"\n       yield \"\\n+\"\n       for x in 0..(width-1) do \n         yield if vertWalls.[x,y] then \"-+\" else \" +\"\n    ]\n    |> String.concat \"\"\n    |> printfn \"%s\"\n\nlet m = new Maze(10,10)\nm.Print()\n\n\nOutput example:\n+-+-+-+-+-+-+-+-+-+-+\n|         |     |   |\n+ +-+-+-+-+ +-+ + + +\n|       |   |   | | |\n+ +-+-+ + +-+-+ +-+ +\n|     | |     |     |\n+-+ +-+ +-+-+ +-+-+ +\n|   |   |     |     |\n+ +-+ +-+ +-+-+-+ +-+\n| | |   |       |   |\n+ + +-+ +-+ +-+ +-+ +\n| |   | | |   |   | |\n+ + +-+ + +-+-+-+ + +\n|   |   |         | |\n+-+ + +-+-+-+-+-+-+ +\n|   |     |       | |\n+ +-+-+ +-+ +-+-+ + +\n| |   |   |     |   |\n+ +-+ +-+ +-+-+ +-+-+\n|       |           |\n+-+-+-+-+-+-+-+-+-+-+\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts at a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, then recursively repeats the process with the neighbor as the current cell. The state is maintained using a 2D array.","id":3929}
    {"lang_cluster":"F#","source_code":"let rec g q r t k n l = seq {\n    if 4I*q+r-t < n*t\n    then\n        yield n\n        yield! (g (10I*q) (10I*(r-n*t)) t k ((10I*(3I*q+r))\/t - 10I*n) l)\n    else\n        yield! (g (q*k) ((2I*q+r)*l) (t*l) (k+1I) ((q*(7I*k+2I)+r*l)\/(t*l)) (l+2I))\n}\n\nlet \u03c0 = (g 1I 0I 1I 1I 3I 3I)\n\nSeq.take 1 \u03c0 |> Seq.iter (printf \"%A.\")\n\/\/ 6 digits beginning at position 762 of \u03c0 are '9'\nSeq.take 767 (Seq.skip 1 \u03c0) |> Seq.iter (printf \"%A\")\n\n\n","human_summarization":"The code continually calculates and outputs the next decimal digit of Pi, starting from 3.14159265. The process continues indefinitely until manually stopped by the user. The task is focused on the calculation of Pi, not on using built-in Pi constants.","id":3930}
    {"lang_cluster":"F#","source_code":"\n\nlet inline cmp x y = if x < y then -1 else if x = y then 0 else 1\nlet before (s1 : seq<'a>) (s2 : seq<'a>) = (Seq.compareWith cmp s1 s2) < 0\n\n[\n    ([0], []);\n    ([], []);\n    ([], [0]);\n    ([-1], [0]);\n    ([0], [0]);\n    ([0], [-1]);\n    ([0], [0; -1]);\n    ([0], [0; 0]);\n    ([0], [0; 1]);\n    ([0; -1], [0]);\n    ([0; 0], [0]);\n    ([0; 0], [1]);\n]\n|> List.iter (fun (x, y) -> printf \"%A %s %A\\n\" x (if before x y then \"< \" else \">=\") y)\n\n\n","human_summarization":"\"Function to compare and order two numerical lists based on lexicographic order using the Collection.Seq Module's Seq.compareWith method. It returns true if the first list should be ordered before the second, and false otherwise.\"","id":3931}
    {"lang_cluster":"F#","source_code":"\n\nlet rec ackermann m n = \n    match m, n with\n    | 0, n -> n + 1\n    | m, 0 -> ackermann (m - 1) 1\n    | m, n -> ackermann (m - 1) ackermann m (n - 1)\n\ndo\n    printfn \"%A\" (ackermann (int fsi.CommandLineArgs.[1]) (int fsi.CommandLineArgs.[2]))\n\n\nlet ackermann M N =\n    let rec acker (m, n, k) =\n        match m,n with\n            | 0, n -> k(n + 1)\n            | m, 0 -> acker ((m - 1), 1, k)\n            | m, n -> acker (m, (n - 1), (fun x -> acker ((m - 1), x, k)))\n    acker (M, N, (fun x -> x))\n\n","human_summarization":"implement the Ackermann function, a non-primitive recursive function that grows rapidly in value. The function takes two non-negative arguments and always terminates. It is implemented in F# and transformed into continuation passing style to avoid limited stack space issues. The function is expected to return the value of A(m, n) with arbitrary precision preferred due to the rapid growth of the function.","id":3932}
    {"lang_cluster":"F#","source_code":"\n\nopen System\n\nlet gamma z = \n    let lanczosCoefficients = [76.18009172947146;-86.50532032941677;24.01409824083091;-1.231739572450155;0.1208650973866179e-2;-0.5395239384953e-5]\n    let rec sumCoefficients acc i coefficients =\n        match coefficients with\n        | []   -> acc\n        | h::t -> sumCoefficients (acc + (h\/i)) (i+1.0) t\n    let gamma = 5.0\n    let x = z - 1.0\n    Math.Pow(x + gamma + 0.5, x + 0.5) * Math.Exp( -(x + gamma + 0.5) ) * Math.Sqrt( 2.0 * Math.PI ) * sumCoefficients 1.000000000190015 (x + 1.0) lanczosCoefficients\n\nseq { for i in 1 .. 20 do yield ((double)i\/10.0) } |> Seq.iter ( fun v -> System.Console.WriteLine(\"{0}\u00a0: {1}\", v, gamma v ) )\nseq { for i in 1 .. 10 do yield ((double)i*10.0) } |> Seq.iter ( fun v -> System.Console.WriteLine(\"{0}\u00a0: {1}\", v, gamma v ) )\n\n","human_summarization":"Implement and compare the Gamma function using built-in\/library function and other algorithms such as Lanczos approximation and Stirling's approximation. The function also includes a translation from C# to F# to support complex numbers.","id":3933}
    {"lang_cluster":"F#","source_code":"\nlet rec iterate f value = seq { \n    yield value\n    yield! iterate f (f value) }\n\nlet up i = i + 1\nlet right i = i\nlet down i = i - 1\n\nlet noCollisionGivenDir solution number dir =\n    Seq.forall2 (<>) solution (Seq.skip 1 (iterate dir number))\n\nlet goodAddition solution number =\n    List.forall (noCollisionGivenDir solution number) [ up; right; down ]\n\nlet rec extendSolution n ps =\n    [0..n - 1]\n    |> List.filter (goodAddition ps)\n    |> List.map (fun num -> num :: ps)\n\nlet allSolutions n =\n    iterate (List.collect (extendSolution n)) [[]]\n\n\/\/ Print one solution for the 8x8 case\nlet printOneSolution () =\n    allSolutions 8\n    |> Seq.item 8\n    |> Seq.head\n    |> List.iter (fun rowIndex ->\n        printf \"|\"\n        [0..8] |> List.iter (fun i -> printf (if i = rowIndex then \"X|\" else \" |\"))\n        printfn \"\")\n\n\/\/ Print number of solution for the other cases\nlet printNumberOfSolutions () =\n    printfn \"Size\\tNr of solutions\"\n    [1..11]\n    |> List.map ((fun i -> Seq.item i (allSolutions i)) >> List.length)\n    |> List.iteri (fun i cnt -> printfn \"%d\\t%d\" (i+1) cnt)\n\nprintOneSolution()\n\nprintNumberOfSolutions()\n\n\n| | | |X| | | | | |\n| |X| | | | | | | |\n| | | | | | |X| | |\n| | |X| | | | | | |\n| | | | | |X| | | |\n| | | | | | | |X| |\n| | | | |X| | | | |\n|X| | | | | | | | |\n\nSize    Nr of solutions\n1       1\n2       0\n3       0\n4       2\n5       10\n6       4\n7       40\n8       92\n9       352\n10      724\n11      2680\n\n","human_summarization":"\"Solve the N-queens problem for a board of size NxN and provide the number of solutions for small values of N as per OEIS: A000170.\"","id":3934}
    {"lang_cluster":"F#","source_code":"\n\nlet a = [|1; 2; 3|]\nlet b = [|4; 5; 6;|]\nlet c = Array.append a b\n\n\nlet x = [1; 2; 3]\nlet y = [4; 5; 6]\nlet z1 = x @ y\nlet z2 = List.append x y\n\n","human_summarization":"demonstrate how to concatenate two arrays using either the '+' operator or the 'List.append' method.","id":3935}
    {"lang_cluster":"F#","source_code":"\n\/\/Solve Knapsack 0-1 using A* algorithm\n\/\/Nigel Galloway, August 3rd., 2018\nlet knapStar items maxW=\n  let l=List.length items\n  let p=System.Collections.Generic.SortedSet<float*int*float*float*list<int>>() \/\/H*; level; value of items taken so far; weight so far\n  p.Add (0.0,0,0.0,0.0,[])|>ignore\n  let H items maxW=let rec H n g a=match g with |(_,w,v)::e->let t=n+w\n                                                             if t<=maxW then H t e (a+v) else a+(v\/w)*(maxW-n)\n                                                |_->a\n                   H 0.0 items 0.0\n  let pAdd ((h,_,_,_,_) as n) bv=if h>bv then p.Add n |> ignore\n  let fH n (bv,t) w' v' t'=let _,w,v=List.item n items\n                           let e=max bv (if w<=(maxW-w') then v'+v else bv)\n                           let rt=n::t'\n                           if n+1<l then pAdd ((v'+H (List.skip (n+1) items) maxW),n+1,v',w',t') bv\n                                         if w<=(maxW-w') then pAdd ((v'+v+H (List.skip (n+1) items) (maxW-w')),n+1,v'+v,w'+w,rt) bv\n                           if e>bv then (e,rt) else (bv,t)\n  let rec fN (bv,t)=\n    let h,zl,zv,zw,zt as r=p.Max\n    p.Remove r |> ignore\n    if bv>=h then t else fN (fH zl (bv,t) zw zv zt)\n  fN (fH 0 (0.0,[]) 0.0 0.0 [])\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":3936}
    {"lang_cluster":"F#","source_code":"\nlet menPrefs =\n  Map.ofList\n            [\"abe\",  [\"abi\";\"eve\";\"cath\";\"ivy\";\"jan\";\"dee\";\"fay\";\"bea\";\"hope\";\"gay\"];\n             \"bob\",  [\"cath\";\"hope\";\"abi\";\"dee\";\"eve\";\"fay\";\"bea\";\"jan\";\"ivy\";\"gay\"];\n             \"col\",  [\"hope\";\"eve\";\"abi\";\"dee\";\"bea\";\"fay\";\"ivy\";\"gay\";\"cath\";\"jan\"];\n             \"dan\",  [\"ivy\";\"fay\";\"dee\";\"gay\";\"hope\";\"eve\";\"jan\";\"bea\";\"cath\";\"abi\"];\n             \"ed\",   [\"jan\";\"dee\";\"bea\";\"cath\";\"fay\";\"eve\";\"abi\";\"ivy\";\"hope\";\"gay\"];\n             \"fred\", [\"bea\";\"abi\";\"dee\";\"gay\";\"eve\";\"ivy\";\"cath\";\"jan\";\"hope\";\"fay\"];\n             \"gav\",  [\"gay\";\"eve\";\"ivy\";\"bea\";\"cath\";\"abi\";\"dee\";\"hope\";\"jan\";\"fay\"];\n             \"hal\",  [\"abi\";\"eve\";\"hope\";\"fay\";\"ivy\";\"cath\";\"jan\";\"bea\";\"gay\";\"dee\"];\n             \"ian\",  [\"hope\";\"cath\";\"dee\";\"gay\";\"bea\";\"abi\";\"fay\";\"ivy\";\"jan\";\"eve\"];\n             \"jon\",  [\"abi\";\"fay\";\"jan\";\"gay\";\"eve\";\"bea\";\"dee\";\"cath\";\"ivy\";\"hope\"];\n            ]\n\nlet womenPrefs =\n   Map.ofList\n              [\"abi\",  [\"bob\";\"fred\";\"jon\";\"gav\";\"ian\";\"abe\";\"dan\";\"ed\";\"col\";\"hal\"];\n               \"bea\",  [\"bob\";\"abe\";\"col\";\"fred\";\"gav\";\"dan\";\"ian\";\"ed\";\"jon\";\"hal\"];\n               \"cath\", [\"fred\";\"bob\";\"ed\";\"gav\";\"hal\";\"col\";\"ian\";\"abe\";\"dan\";\"jon\"];\n               \"dee\",  [\"fred\";\"jon\";\"col\";\"abe\";\"ian\";\"hal\";\"gav\";\"dan\";\"bob\";\"ed\"];\n               \"eve\",  [\"jon\";\"hal\";\"fred\";\"dan\";\"abe\";\"gav\";\"col\";\"ed\";\"ian\";\"bob\"];\n               \"fay\",  [\"bob\";\"abe\";\"ed\";\"ian\";\"jon\";\"dan\";\"fred\";\"gav\";\"col\";\"hal\"];\n               \"gay\",  [\"jon\";\"gav\";\"hal\";\"fred\";\"bob\";\"abe\";\"col\";\"ed\";\"dan\";\"ian\"];\n               \"hope\", [\"gav\";\"jon\";\"bob\";\"abe\";\"ian\";\"dan\";\"hal\";\"ed\";\"col\";\"fred\"];\n               \"ivy\",  [\"ian\";\"col\";\"hal\";\"gav\";\"fred\";\"bob\";\"abe\";\"ed\";\"jon\";\"dan\"];\n               \"jan\",  [\"ed\";\"hal\";\"gav\";\"abe\";\"bob\";\"jon\";\"col\";\"ian\";\"fred\";\"dan\"];\n              ]\n\nlet men = menPrefs |> Map.toList |> List.map fst |> List.sort\nlet women = womenPrefs |> Map.toList |> List.map fst |> List.sort\n\n\ntype Configuration =\n {\n   proposed: Map<string,string list>; \/\/ man -> list of women\n   wifeOf: Map<string, string>; \/\/ man -> woman\n   husbandOf: Map<string, string>;  \/\/ woman -> man\n }\n\n\n\/\/ query functions\n\nlet isFreeMan config man = config.wifeOf.TryFind man = None\n\nlet isFreeWoman config woman = config.husbandOf.TryFind woman = None\n\nlet hasProposedTo config man woman =\n  defaultArg (config.proposed.TryFind(man)) []\n  |> List.exists ((=) woman)\n\n\/\/ helper\nlet negate f = fun x -> not (f x)\n\n\/\/ returns those 'women' who 'man' has not proposed to before\nlet notProposedBy config man women = List.filter (negate (hasProposedTo config man)) women\n \nlet prefers (prefs:Map<string,string list>) w m1 m2 =\n  let order = prefs.[w]\n  let m1i = List.findIndex ((=) m1) order\n  let m2i = List.findIndex ((=) m2) order\n  m1i < m2i\n\nlet womanPrefers = prefers womenPrefs\nlet manPrefers = prefers menPrefs\n\n\/\/ returns the women that m likes better than his current fianc\u00e9e\nlet preferredWomen config m =\n  let w = config.wifeOf.[m]\n  women\n  |> List.filter (fun w' -> manPrefers m w' w)  \/\/ '\n\n\/\/ whether there is a woman who m likes better than his current fianc\u00e9e\n\/\/ and who also likes him better than her current fianc\u00e9\nlet prefersAWomanWhoAlsoPrefersHim config m =\n  preferredWomen config m\n  |> List.exists (fun w -> womanPrefers w m config.husbandOf.[w])\n\nlet isStable config =\n  not (List.exists (prefersAWomanWhoAlsoPrefersHim config) men)\n\n\n\/\/ modifiers (return new configurations)\n\nlet engage config man woman =\n  { config with wifeOf = config.wifeOf.Add(man, woman);\n                husbandOf = config.husbandOf.Add(woman, man) }\n\nlet breakOff config man =\n  let woman = config.wifeOf.[man]\n  { config with wifeOf = config.wifeOf.Remove(man);\n                husbandOf = config.husbandOf.Remove(woman) }\n\nlet propose config m w =\n  \/\/ remember the proposition\n  let proposedByM = defaultArg (config.proposed.TryFind m) []\n  let proposed' = config.proposed.Add(m, w::proposedByM) \/\/ '\n  let config = { config with proposed = proposed'}  \/\/ '\n  \/\/ actually try to engage\n  if isFreeWoman config w then engage config m w\n  else\n    let m' = config.husbandOf.[w] \/\/ '\n    if womanPrefers w m m' then \/\/ '\n      let config = breakOff config m' \/\/ '\n      engage config m w\n    else\n      config\n\n\/\/ do one step of the algorithm; returns None if no more steps are possible\nlet step config : Configuration option =\n  let freeMen = men |> List.filter (isFreeMan config)\n  let menWhoCanPropose =\n    freeMen |>\n    List.filter (fun man -> (notProposedBy config man women) <> [] )\n  match menWhoCanPropose with\n  | [] -> None\n  | m::_ -> let unproposedByM = menPrefs.[m] |> notProposedBy config m\n            \/\/ w is automatically the highest ranked because menPrefs.[m] is the source\n            let w = List.head unproposedByM\n            Some( propose config m w )\n              \nlet rec loop config =\n  match step config with\n  | None -> config\n  | Some config' -> loop config' \/\/ '\n\n\n\/\/ find solution and print it\nlet solution = loop { proposed = Map.empty<string, string list>;\n                      wifeOf = Map.empty<string, string>;\n                      husbandOf = Map.empty<string, string> }\n\nfor woman, man in Map.toList solution.husbandOf do\n  printfn \"%s is engaged to %s\" woman man\n\nprintfn \"Solution is stable: %A\" (isStable solution)\n\n\n\/\/ create unstable configuration by perturbing the solution\nlet perturbed = \n  let gal0 = women.[0]\n  let gal1 = women.[1]\n  let guy0 = solution.husbandOf.[gal0]\n  let guy1 = solution.husbandOf.[gal1]\n  { solution with wifeOf = solution.wifeOf.Add( guy0, gal1 ).Add( guy1, gal0 );\n                  husbandOf = solution.husbandOf.Add( gal0, guy1 ).Add( gal1, guy0 ) }\n\nprintfn \"Perturbed is stable: %A\" (isStable perturbed)\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":3937}
    {"lang_cluster":"F#","source_code":"\nlet a (x : bool) = printf \"(a)\"; x\nlet b (x : bool) = printf \"(b)\"; x\n\n[for x in [true; false] do for y in [true; false] do yield (x, y)]\n|> List.iter (fun (x, y) ->\n    printfn \"%b AND %b = %b\" x y ((a x) && (b y))\n    printfn \"%b OR %b = %b\" x y ((a x) || (b y)))\n\n\n(a)(b)true AND true = true\n(a)true OR true = true\n(a)(b)true AND false = false\n(a)true OR false = true\n(a)false AND true = false\n(a)(b)false OR true = true\n(a)false AND false = false\n(a)(b)false OR false = false\n","human_summarization":"The code creates two functions, a and b, that return the same boolean value they receive as input and print their names when called. It then calculates the values of two equations, x = a(i) and b(j), and y = a(i) or b(j), using short-circuit evaluation to ensure function b is only called when necessary. If the language doesn't support short-circuit evaluation, this is achieved using nested if statements.","id":3938}
    {"lang_cluster":"F#","source_code":"\nopen System\nopen System.Threading\n\nlet morse = Map.ofList\n                [('a', \"._ \"); ('b', \"_... \"); ('c', \"_._. \"); ('d', \"_.. \");\n                ('e', \". \"); ('f', \".._. \"); ('g', \"__. \"); ('h', \".... \");\n                ('i', \".. \"); ('j', \".___ \"); ('k', \"_._ \"); ('l', \"._.. \");\n                ('m', \"__ \"); ('n', \"_. \"); ('o', \"___ \"); ('p', \".__. \");\n                ('q', \"__._ \"); ('r', \"._. \"); ('s', \"... \"); ('t', \"_ \");\n                ('u', \".._ \"); ('v', \"..._ \"); ('w', \".__ \"); ('x', \"_.._ \");\n                ('y', \"_.__ \"); ('z', \"__.. \"); ('0', \"_____ \"); ('1', \".____ \");\n                ('2', \"..___ \"); ('3', \"...__ \"); ('4', \"...._ \"); ('5', \"..... \");\n                ('6', \"_.... \"); ('7', \"__... \"); ('8', \"___.. \"); ('9', \"____. \")]\n\nlet beep c =\n    match c with\n    | '.' ->\n        printf \".\"\n        Console.Beep(1200, 250)\n    | '_' ->\n        printf \"_\"\n        Console.Beep(1200, 1000)\n    | _ ->\n        printf \" \"\n        Thread.Sleep(125)\n\nlet trim (s: string) = s.Trim()\nlet toMorse c = Map.find c morse\nlet lower (s: string) = s.ToLower()\nlet sanitize = String.filter Char.IsLetterOrDigit\n\nlet send = sanitize >> lower >> String.collect toMorse >> trim >> String.iter beep\n\nsend \"Rosetta Code\"\n\n\n","human_summarization":"<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":3939}
    {"lang_cluster":"F#","source_code":"\n\nlet rec spell_word_with blocks w =\n    let rec look_for_right_candidate candidates noCandidates c rest =\n        match candidates with\n        | [] -> false\n        | c0::cc -> \n            if spell_word_with (cc@noCandidates) rest then true\n            else look_for_right_candidate cc (c0::noCandidates) c rest\n\n    match w with\n    | \"\" -> true\n    | w ->\n        let c = w.[0]\n        let rest = w.Substring(1)\n        let (candidates, noCandidates) = List.partition(fun (c1,c2) -> c = c1 || c = c2) blocks\n        look_for_right_candidate candidates noCandidates c rest\n\n[<EntryPoint>]\nlet main argv =\n    let default_blocks = \"BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY PC ZM\"\n    let blocks =\n        (if argv.Length > 0 then argv.[0] else default_blocks).Split()\n        |> List.ofArray\n        |> List.map(fun s -> s.ToUpper())\n        |> List.map(fun s2 -> s2.[0], s2.[1])\n    let words =\n        (if argv.Length > 0 then List.ofArray(argv).Tail else [])\n        |> List.map(fun s -> s.ToUpper())\n\n    List.iter (fun w -> printfn \"Using the blocks we can make the word '%s': %b\" w (spell_word_with blocks w)) words\n    0\n\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed. It also includes test cases for seven different words.\"","id":3940}
    {"lang_cluster":"F#","source_code":"\n\nlet md5ootb (msg: string) =\n  use md5 = System.Security.Cryptography.MD5.Create()\n  msg\n  |> System.Text.Encoding.ASCII.GetBytes\n  |> md5.ComputeHash\n  |> Seq.map (fun c -> c.ToString(\"X2\"))\n  |> Seq.reduce ( + )\n\nmd5ootb @\"The quick brown fox jumped over the lazy dog's back\"\n\n","human_summarization":"Implement and encode a string using the MD5 algorithm, with an option to validate the implementation using test values from IETF RFC (1321). The codes also provide a warning about the known weaknesses of MD5 and suggest stronger alternatives for production-grade cryptography. If a library solution is used, an implementation from scratch can be found at MD5\/Implementation. The codes also utilize the built-in System.Security.Cryptography.MD5 class.","id":3941}
    {"lang_cluster":"F#","source_code":"\nlet rec countInOctal num : unit =\n  printfn \"%o\" num\n  countInOctal (num + 1)\n\ncountInOctal 1\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":3942}
    {"lang_cluster":"F#","source_code":"\nlet swap (a,b) = (b,a)\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain limitations based on language semantics and support for parametric polymorphism.","id":3943}
    {"lang_cluster":"F#","source_code":"\nlet isPalindrome (s: string) =\n   let arr = s.ToCharArray()\n   arr = Array.rev arr\n\n\nisPalindrome \"abcba\"\nval it : bool = true\nisPalindrome (\"In girum imus nocte et consumimur igni\".Replace(\" \", \"\").ToLower());;\nval it : bool = true\nisPalindrome \"abcdef\"\nval it : bool = false\n\n","human_summarization":"The code checks if a given sequence of characters is a palindrome, supporting Unicode characters. It also includes a function to detect inexact palindromes by ignoring white-space, punctuation, and case sensitivity.","id":3944}
    {"lang_cluster":"F#","source_code":"\nopen System\n\n[<EntryPoint>]\nlet main args =\n    printfn \"%A\" (Environment.GetEnvironmentVariable(\"PATH\"))\n    0\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":3945}
    {"lang_cluster":"F#","source_code":"let rec sudan = function\n   0L, x, y -> x + y\n  |_, x, 0L -> x\n  |n, x, y -> let x' = sudan (n, x, y-1L) in sudan (n-1L, x', x' + y)\nprintfn \"%d\\n%d\\n%d\" (sudan(1L, 13L, 14L)) (sudan(2L, 5L, 1L)) (sudan(2L, 2L, 2L))\n\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.","id":3946}
    {"lang_cluster":"Delphi","source_code":"\nprogram Stack;\n\n{$APPTYPE CONSOLE}\n\nuses Generics.Collections;\n\nvar\n  lStack: TStack<Integer>;\nbegin\n  lStack := TStack<Integer>.Create;\n  try\n    lStack.Push(1);\n    lStack.Push(2);\n    lStack.Push(3);\n    Assert(lStack.Peek = 3); \/\/ 3 should be at the top of the stack\n\n    Writeln(lStack.Pop); \/\/ 3\n    Writeln(lStack.Pop); \/\/ 2\n    Writeln(lStack.Pop); \/\/ 1\n    Assert(lStack.Count = 0); \/\/ should be empty\n  finally\n    lStack.Free;\n  end;\nend.\n\n","human_summarization":"implement a stack data structure with basic operations such as push (to add elements), pop (to remove and return the last added element), and empty (to check if the stack is empty). This stack follows a Last-In-First-Out (LIFO) access policy.","id":3947}
    {"lang_cluster":"Delphi","source_code":"\nfunction FibonacciI(N: Word): UInt64;\nvar\n  Last, New: UInt64;\n  I: Word;\nbegin\n  if N < 2 then\n    Result\u00a0:= N\n  else begin\n    Last\u00a0:= 0;\n    Result\u00a0:= 1;\n    for I\u00a0:= 2 to N do\n    begin\n      New\u00a0:= Last + Result;\n      Last\u00a0:= Result;\n      Result\u00a0:= New;\n    end;\n  end;\nend;\nfunction Fibonacci(N: Word): UInt64;\nbegin\n  if N < 2 then\n    Result\u00a0:= N\n  else\n   Result\u00a0:= Fibonacci(N - 1) + Fibonacci(N - 2);\nend;\n\n\n\n\n\n\n\n(\n\n\n\n1\n\n\n1\n\n\n\n\n1\n\n\n0\n\n\n\n)\n\nn\n\n=\n\n(\n\n\n\nF\n(\nn\n+\n1\n)\n\n\nF\n(\nn\n)\n\n\n\n\nF\n(\nn\n)\n\n\nF\n(\nn\n\u2212\n1\n)\n\n\n\n)\n\n\n\n{\\displaystyle \\begin{pmatrix}1&1\\\\1&0\\end{pmatrix}^n = \\begin{pmatrix}F(n+1)&F(n)\\\\F(n)&F(n-1)\\end{pmatrix}}\n\n.\nfunction fib(n: Int64): Int64;\n\n  type TFibMat = array[0..1] of array[0..1] of Int64;\n\t\n  function FibMatMul(a,b: TFibMat): TFibMat;\n  var i,j,k: integer;\n      tmp: TFibMat;\n  begin\n    for i\u00a0:= 0 to 1 do\n      for j\u00a0:= 0 to 1 do\n      begin\n\ttmp[i,j]\u00a0:= 0;\n\tfor k\u00a0:= 0 to 1 do tmp[i,j]\u00a0:= tmp[i,j] + a[i,k] * b[k,j];\n      end;\n    FibMatMul\u00a0:= tmp;\n  end;\n\t\n  function FibMatExp(a: TFibMat; n: Int64): TFibmat;\n  begin\n    if n <= 1 then fibmatexp\u00a0:= a\n    else if (n mod 2 = 0) then FibMatExp\u00a0:= FibMatExp(FibMatMul(a,a), n div 2)\n    else if (n mod 2 = 1) then FibMatExp\u00a0:= FibMatMul(a, FibMatExp(FibMatMul(a,a), n div 2));\n  end;\n\nvar \n  matrix: TFibMat;\n\t\nbegin\n  matrix[0,0]\u00a0:= 1;\n  matrix[0,1]\u00a0:= 1;\n  matrix[1,0]\u00a0:= 1;\n  matrix[1,1]\u00a0:= 0;\n  if n > 1 then\n    matrix\u00a0:= fibmatexp(matrix,n-1);\n  fib\u00a0:= matrix[0,0];\nend;\n","human_summarization":"generate the nth Fibonacci number, supporting both positive and negative indices. The function can be implemented using either iterative or recursive methods.","id":3948}
    {"lang_cluster":"Delphi","source_code":"\nprogram FilterEven;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils, Types;\n\nconst\n  SOURCE_ARRAY: array[0..9] of Integer = (0,1,2,3,4,5,6,7,8,9);\nvar\n  i: Integer;\n  lEvenArray: TIntegerDynArray;\nbegin\n  for i in SOURCE_ARRAY do\n  begin\n    if not Odd(i) then\n    begin\n      SetLength(lEvenArray, Length(lEvenArray) + 1);\n      lEvenArray[Length(lEvenArray) - 1] := i;\n    end;\n  end;\n\n  for i in lEvenArray do\n    Write(i:3);\n  Writeln;\nend.\n\n\n\nLibrary:  System.SysUtils\nLibrary:  Types\nLibrary:  Boost.Int\nprogram FilterEven;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils,\n  Types,\n  Boost.Int;\n\nvar\n  Source, Destiny: TIntegerDynArray;\n\nbegin\n  Source.Assign([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\n\n  \/\/ Non-destructively\n  Destiny := Source.Filter(\n    function(Item: Integer): Boolean\n    begin\n      Result := not odd(Item) and (Item <> 0);\n    end);\n\n  Writeln('[' + Destiny.Comma + ']');\n  Readln;\nend.\n\n  \/\/ Destructively\n  Source.Remove(\n    function(Item: Integer): Boolean\n    begin\n      Result := odd(Item) or (Item = 0);\n    end);\n\n  Writeln('[' + Source.Comma + ']');\nEnd.\n\n\n","human_summarization":"select specific elements from an array, in this case, all even numbers, into a new array. Optionally, it also provides a destructive filtering method that modifies the original array instead of creating a new one. An alternative solution using Boost.Int is also provided.","id":3949}
    {"lang_cluster":"Delphi","source_code":"\nprogram ShowSubstring;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils;\n\nconst\n  s = '0123456789';\n  n = 3;\n  m = 4;\n  c = '2';\n  sub = '456';\nbegin\n  Writeln(Copy(s, n, m));             \/\/ starting from n characters in and of m length;\n  Writeln(Copy(s, n, Length(s)));     \/\/ starting from n characters in, up to the end of the string;\n  Writeln(Copy(s, 1, Length(s) - 1)); \/\/ whole string minus last character;\n  Writeln(Copy(s, Pos(c, s), m));     \/\/ starting from a known character within the string and of m length;\n  Writeln(Copy(s, Pos(sub, s), m));   \/\/ starting from a known substring within the string and of m length.\nend.\n\n\n","human_summarization":"- Extracts a substring starting from the nth character of a specific length m.\n- Extracts a substring starting from the nth character up to the end of the string.\n- Returns the entire string excluding the last character.\n- Extracts a substring starting from a known character within the string of length m.\n- Extracts a substring starting from a known substring within the string of length m.\n- Supports any valid Unicode code point, including those in the Basic Multilingual Plane or above it.\n- References logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.","id":3950}
    {"lang_cluster":"Delphi","source_code":"\nfunction ReverseString(const InString: string): string;\nvar\n  i: integer;\nbegin\n  for i := Length(InString) downto 1 do\n    Result := Result + InString[i];\nend;\n\n\nStrUtils.ReverseString\n\n\nfunction Reverse(const s: string): string;\nvar\n  i, aLength, ahalfLength: Integer;\n  c: Char;\nbegin\n  Result := s;\n  aLength := Length(s);\n  ahalfLength := aLength div 2;\n  if aLength > 1 then\n    for i := 1 to ahalfLength do\n    begin\n      c := result[i];\n      result[i] := result[aLength - i + 1];\n      result[aLength - i + 1] := c;\n    end;\nend;\n\n\n","human_summarization":"The code takes a string as input, reverses it while preserving any Unicode combining characters. It also utilizes the RTL function introduced in Delphi 6, and recommends using StrUtils for optimal performance.","id":3951}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram Rosetta_Dijkstra_Console;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils; \/\/ for printing the result\n\n\/\/ Conventional values (any negative values would do)\nconst\n  INFINITY  = -1;\n  NO_VERTEX = -2;\n\nconst\n  NR_VERTICES = 6;\n\n\/\/ DISTANCE_MATRIX[u, v] = length of directed edge from u to v, or -1 if no such edge exists.\n\/\/ A simple way to represent a directed graph with not many vertices.\nconst DISTANCE_MATRIX : array [0..(NR_VERTICES - 1), 0..(NR_VERTICES - 1)] of integer\n= ((-1,  7,  9, -1, -1, -1),\n   (-1, -1, 10, 15, -1, -1),\n   (-1, -1, -1, 11, -1,  2),\n   (-1, -1, -1, -1,  6, -1),\n   (-1, -1, -1, -1, -1,  9),\n   (-1, -1, -1, -1, -1, -1));\n\ntype TVertex = record\n  Distance : integer; \/\/ distance from vertex 0; infinity if a path has not yet been found\n  Previous : integer; \/\/ previous vertex in the path from vertex 0\n  Visited  : boolean; \/\/ as defined in the algorithm\nend;\n\n\/\/ For distances x and y, test whether x < y, using the convention that -1 means infinity.\nfunction IsLess( x, y : integer) : boolean;\nbegin\n  result := (x <> INFINITY)\n        and ( (y = INFINITY) or (x < y) );\nend;\n\n\/\/ Main routine\nvar\n  v : array [0..NR_VERTICES - 1] of TVertex; \/\/ array of vertices\n  c : integer; \/\/ index of current vertex\n  j : integer; \/\/ loop counter\n  trialDistance : integer;\n  minDistance : integer;\n  \/\/ Variables for printing the result\n  p : integer;\n  lineOut : string;\nbegin\n  \/\/ Initialize the vertices\n  for j := 0 to NR_VERTICES - 1 do begin\n    v[j].Distance := INFINITY;\n    v[j].Previous := NO_VERTEX;\n    v[j].Visited  := false;\n  end;\n\n  \/\/ Start with vertex 0 as the current vertex\n  c := 0;\n  v[c].Distance := 0;\n\n  \/\/ Main loop of Dijkstra's algorithm\n  repeat\n\n    \/\/ Work through unvisited neighbours of the current vertex, updating them where possible.\n    \/\/ \"Neighbour\" means the end of a directed edge from the current vertex.\n    \/\/ Note that v[c].Distance is always finite.\n    for j := 0 to NR_VERTICES - 1 do begin\n      if (not v[j].Visited) and (DISTANCE_MATRIX[c, j] >= 0) then begin\n        trialDistance := v[c].Distance + DISTANCE_MATRIX[c, j];\n        if IsLess( trialDistance, v[j].Distance) then begin\n          v[j].Distance := trialDistance;\n          v[j].Previous := c;\n        end;\n      end;\n    end;\n\n    \/\/ When all neighbours have been tested, mark the current vertex as visited.\n    v[c].Visited := true;\n\n    \/\/ The new current vertex is the unvisited vertex with the smallest finite distance.\n    \/\/ If there is no such vertex, the algorithm is finished.\n    c := NO_VERTEX;\n    minDistance := INFINITY;\n    for j := 0 to NR_VERTICES - 1 do begin\n      if (not v[j].Visited) and IsLess( v[j].Distance, minDistance) then begin\n        minDistance := v[j].Distance;\n        c := j;\n      end;\n    end;\n  until (c = NO_VERTEX);\n\n  \/\/ Print the result\n  for j := 0 to NR_VERTICES - 1 do begin\n    if (v[j].Distance = INFINITY) then begin\n      \/\/ The algorithm never found a path to v[j]\n      lineOut := SysUtils.Format( '%2d: inaccessible', [j]);\n    end\n    else begin\n      \/\/ Build up the path of vertices, working backwards from v[j]\n      lineOut := SysUtils.Format( '%2d', [j]);\n      p := v[j].Previous;\n      while (p <> NO_VERTEX) do begin\n        lineOut := SysUtils.Format( '%2d --> ', [p]) + lineOut;\n        p := v[p].Previous;\n      end;\n      \/\/ Print the path of vertices, preceded by distance from vertex 0\n      lineOut := SysUtils.Format( '%2d: distance = %3d, ', [j, v[j].Distance]) + lineOut;\n    end;\n    WriteLn( lineOut);\n  end;\nend.\n\n\n","human_summarization":"The code implements Dijkstra's algorithm to find the shortest path from a given source node to all other nodes in a graph. The graph is represented as a directed and weighted graph with non-negative edge path costs. The algorithm outputs a set of edges depicting the shortest path to each reachable node from the source. It also includes functionality to interpret the output and provide the shortest path from the source node to specified destination nodes.","id":3952}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  System.Types\nLibrary:  System.Mathprogram Circles_of_given_radius_through_two_points;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils,\n  System.Types,\n  System.Math;\n\nconst\n  Cases: array[0..9] of TPointF = ((\n    x: 0.1234;\n    y: 0.9876\n  ), (\n    x: 0.8765;\n    y: 0.2345\n  ), (\n    x: 0.0000;\n    y: 2.0000\n  ), (\n    x: 0.0000;\n    y: 0.0000\n  ), (\n    x: 0.1234;\n    y: 0.9876\n  ), (\n    x: 0.1234;\n    y: 0.9876\n  ), (\n    x: 0.1234;\n    y: 0.9876\n  ), (\n    x: 0.8765;\n    y: 0.2345\n  ), (\n    x: 0.1234;\n    y: 0.9876\n  ), (\n    x: 0.1234;\n    y: 0.9876\n  ));\n  radii: array of double = [2.0, 1.0, 2.0, 0.5, 0.0];\n\nprocedure FindCircles(p1, p2: TPointF; radius: double);\nvar\n  separation, mirrorDistance: double;\nbegin\n  separation := p1.Distance(p2);\n  if separation = 0.0 then\n  begin\n    if radius = 0 then\n      write(format(#10'No circles can be drawn through (%.4f,%.4f)', [p1.x, p1.y]))\n    else\n      write(format(#10'Infinitely many circles can be drawn through (%.4f,%.4f)',\n        [p1.x, p1.y]));\n    exit;\n  end;\n\n  if separation = 2 * radius then\n  begin\n    write(format(#10'Given points are opposite ends of a diameter of the circle with center (%.4f,%.4f) and radius\u00a0%.4f',\n      [(p1.x + p2.x) \/ 2, (p1.y + p2.y) \/ 2, radius]));\n    exit;\n  end;\n\n  if separation > 2 * radius then\n  begin\n    write(format(#10'Given points are farther away from each other than a diameter of a circle with radius\u00a0%.4f',\n      [radius]));\n    exit;\n  end;\n\n  mirrorDistance := sqrt(Power(radius, 2) - Power(separation \/ 2, 2));\n  write(#10'Two circles are possible.');\n  write(format(#10'Circle C1 with center (%.4f,%.4f), radius\u00a0%.4f and Circle C2 with center (%.4f,%.4f), radius\u00a0%.4f',\n    [(p1.x + p2.x) \/ 2 + mirrorDistance * (p1.y - p2.y) \/ separation, (p1.y + p2.y)\n    \/ 2 + mirrorDistance * (p2.x - p1.x) \/ separation, radius, (p1.x + p2.x) \/ 2\n    - mirrorDistance * (p1.y - p2.y) \/ separation, (p1.y + p2.y) \/ 2 -\n    mirrorDistance * (p2.x - p1.x) \/ separation, radius]));\n\nend;\n\nbegin\n  for var i := 0 to 4 do\n  begin\n    write(#10'Case ', i + 1,')');\n    findCircles(cases[2 * i], cases[2 * i + 1], radii[i]);\n  end;\n  readln;\nend.\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":3953}
    {"lang_cluster":"Delphi","source_code":"\nprogram Project5;\n\n{$APPTYPE CONSOLE}\n\nvar\n  num:Integer;\nbegin\n  Randomize;\n  while true do\n  begin\n    num:=Random(20);\n    Writeln(num);\n    if num=10 then break;\n  end;\nend.\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":3954}
    {"lang_cluster":"Delphi","source_code":"\nprogram FactorsMersenneNumber(input, output);\n\nfunction isPrime(n: longint): boolean;\n  var\n    d: longint;\n  begin\n    isPrime := true;\n    if (n mod 2) = 0 then\n    begin\n      isPrime := (n = 2);\n      exit;\n    end;\n    if (n mod 3) = 0 then\n    begin\n      isPrime := (n = 3);\n      exit;\n    end;\n    d := 5;\n    while d*d <= n do\n    begin\n      if (n mod d) = 0 then\n      begin\n\tisPrime := false;\n\texit;\n      end;\n      d := d + 2;\n    end;\n  end;\n\nfunction btest(n, pos: longint): boolean;\n  begin\n    btest := (n shr pos) mod 2 = 1;\n  end;\n\nfunction MFactor(p: longint): longint;\n  var\n    i, k,  maxk, msb, n, q: longint;\n  begin\n    for i := 30 downto 0 do\n      if btest(p, i) then\n      begin\n\tmsb := i;\n\tbreak;\n      end;\n    maxk := 16384 div p;     \/\/ limit for k to prevent overflow of 32 bit signed integer\n    for k := 1 to maxk do\n    begin\n      q := 2*p*k + 1;\n      if not isprime(q) then\n\tcontinue;\n      if ((q mod 8) <> 1) and ((q mod 8) <> 7) then\n\tcontinue;\n      n := 1;\n      for i := msb downto 0 do\n\tif btest(p, i) then\n\t  n := (n*n*2) mod q\n\telse\n\t  n := (n*n) mod q;\n      if n = 1 then\n      begin\n\tmfactor := q;\n\texit;\n      end;\n    end;\n    mfactor := 0;\n  end;\n\nvar\n  exponent, factor: longint;\n\nbegin\n  write('Enter the exponent of the Mersenne number (suggestion: 929): ');\n  readln(exponent);\n  if not isPrime(exponent) then\n  begin\n    writeln('M', exponent, ' (2**', exponent, ' - 1) is not prime.');\n    exit;\n  end;\n  factor := MFactor(exponent);\n  if factor = 0 then\n    writeln('M', exponent, ' (2**', exponent, ' - 1) has no factor.')\n  else\n    writeln('M', exponent, ' (2**', exponent, ' - 1) has the factor: ', factor);\nend.\n","human_summarization":"The code implements an algorithm to find a factor of a Mersenne number, specifically 2^929-1 (M929). It uses efficient methods to determine if a number divides 2^P-1 by using the modPow operation. It also incorporates properties of Mersenne numbers to refine the process, ensuring any potential factor is of the form 2kP+1 and is 1 or 7 mod 8. The algorithm stops when 2kP+1 > sqrt(N). This method only works for Mersenne numbers where P is prime.","id":3955}
    {"lang_cluster":"Delphi","source_code":"\nprogram XMLXPath;\n\n{$APPTYPE CONSOLE}\n\nuses ActiveX, MSXML;\n\nconst\n  XML =\n    '<inventory title=\"OmniCorp Store #45x10^3\">' +\n    '  <section name=\"health\">' +\n    '    <item upc=\"123456789\" stock=\"12\">' +\n    '      <name>Invisibility Cream<\/name>' +\n    '      <price>14.50<\/price>' +\n    '      <description>Makes you invisible<\/description>' +\n    '    <\/item>' +\n    '    <item upc=\"445322344\" stock=\"18\">' +\n    '      <name>Levitation Salve<\/name>' +\n    '      <price>23.99<\/price>' +\n    '      <description>Levitate yourself for up to 3 hours per application<\/description>' +\n    '    <\/item>' +\n    '  <\/section>' +\n    '  <section name=\"food\">' +\n    '    <item upc=\"485672034\" stock=\"653\">' +\n    '      <name>Blork and Freen Instameal<\/name>' +\n    '      <price>4.95<\/price>' +\n    '      <description>A tasty meal in a tablet; just add water<\/description>' +\n    '    <\/item>' +\n    '    <item upc=\"132957764\" stock=\"44\">' +\n    '      <name>Grob winglets<\/name>' +\n    '      <price>3.56<\/price>' +\n    '      <description>Tender winglets of Grob. Just add water<\/description>' +\n    '    <\/item>' +\n    '  <\/section>' +\n    '<\/inventory>';\n\nvar\n  i: Integer;\n  s: string;\n  lXMLDoc: IXMLDOMDocument2;\n  lNodeList: IXMLDOMNodeList;\n  lNode: IXMLDOMNode;\n  lItemNames: array of string;\nbegin\n  CoInitialize(nil);\n  lXMLDoc := CoDOMDocument.Create;\n  lXMLDoc.setProperty('SelectionLanguage', 'XPath');\n  lXMLDoc.loadXML(XML);\n\n  Writeln('First item node:');\n  lNode := lXMLDoc.selectNodes('\/\/item')[0];\n  Writeln(lNode.xml);\n  Writeln('');\n\n  lNodeList := lXMLDoc.selectNodes('\/\/price');\n  for i := 0 to lNodeList.length - 1 do\n    Writeln('Price = ' + lNodeList[i].text);\n  Writeln('');\n\n  lNodeList := lXMLDoc.selectNodes('\/\/item\/name');\n  SetLength(lItemNames, lNodeList.length);\n  for i := 0 to lNodeList.length - 1 do\n    lItemNames[i] := lNodeList[i].text;\n  for s in lItemNames do\n    Writeln('Item name = ' + s);\nend.\n\n\nFirst item node:\n<item upc=\"123456789\" stock=\"12\">\n\t<name>Invisibility Cream<\/name>\n\t<price>14.50<\/price>\n\t<description>Makes you invisible<\/description>\n<\/item>\n\nPrice = 14.50\nPrice = 23.99\nPrice = 4.95\nPrice = 3.56\n\nItem name = Invisibility Cream\nItem name = Levitation Salve\nItem name = Blork and Freen Instameal\nItem name = Grob winglets\n\n","human_summarization":"The code performs three XPath queries on a given XML document: it retrieves the first \"item\" element, prints out each \"price\" element, and creates an array of all the \"name\" elements.","id":3956}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  Boost.Generics.Collection\n\nprogram Set_task;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils,\n  Boost.Generics.Collection;\n\nbegin\n  var s1 := TSet<Integer>.Create([1, 2, 3, 4, 5, 6]);\n  var s2 := TSet<Integer>.Create([2, 5, 6, 3, 4, 8]);\n  var s3 := TSet<Integer>.Create([1, 2, 5]);\n\n  Writeln('S1 ', s1.ToString);\n  Writeln('S2 ', s2.ToString);\n  Writeln('S3 ', s3.ToString, #10);\n\n  Writeln('4 is in S1? ', s1.Has(4));\n  Writeln('S1 union S2 ', (s1 + S2).ToString);\n  Writeln('S1 intersection S2 ', (s1 * S2).ToString);\n  Writeln('S1 difference S2 ', (s1 - S2).ToString);\n  Writeln('S3 is subset S2 ', s1.IsSubSet(s3));\n  Writeln('S1 equality S2? ', s1 = s2);\n  readln;\nend.\n\n\n","human_summarization":"demonstrate various set operations including set creation, checking if an element belongs to a set, performing union, intersection, and difference of two sets, checking if a set is a subset or equal to another set. It also optionally shows other set operations and modifications on a mutable set. The set can be implemented using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also includes the time complexity of the basic test operation with different data structures. It also references the Boost.Generics.Collection library.","id":3957}
    {"lang_cluster":"Delphi","source_code":"\nLibrary: sysutils always in uses clause in Delphi\nprocedure IsXmasSunday(fromyear, toyear: integer);\nvar\ni: integer;\nTestDate: TDateTime;\noutputyears: string;\nbegin\noutputyears := '';\n  for i:= fromyear to toyear do\n  begin\n    TestDate := EncodeDate(i,12,25);\n    if dayofweek(TestDate) = 1 then\n    begin\n      outputyears := outputyears + inttostr(i) + ' ';\n    end;\n  end;\n  \/\/CONSOLE\n  \/\/writeln(outputyears);\n  \/\/GUI \n  form1.label1.caption := outputyears;\nend;\n\n\n\n","human_summarization":"\"Determines the years between 2008 and 2121 where December 25th falls on a Sunday using standard date handling libraries. Compares the calculated dates with other languages to identify any anomalies in date\/time representation. Outputs a space-delimited array of years without error checking for year range validity.\"","id":3958}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram RemoveDuplicateElements;\n\n{$APPTYPE CONSOLE}\n\nuses Generics.Collections;\n\nvar\n  i: Integer;\n  lIntegerList: TList<Integer>;\nconst\n  INT_ARRAY: array[1..7] of Integer = (1, 2, 2, 3, 4, 5, 5);\nbegin\n  lIntegerList := TList<Integer>.Create;\n  try\n  for i in INT_ARRAY do\n    if not lIntegerList.Contains(i) then\n      lIntegerList.Add(i);\n\n  for i in lIntegerList do\n    Writeln(i);\n  finally\n    lIntegerList.Free;\n  end;\nend.\n\n\n","human_summarization":"The code removes duplicate elements from an array using three methods: 1) Utilizing a hash table that doesn't allow duplicates, 2) Sorting the elements and removing consecutive duplicates, 3) Iterating through the list and discarding any element that appears more than once. The code is compatible with Delphi2009's generics feature.","id":3959}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\n{Dynamic array of pointers}\n\ntype TPointerArray = array of Pointer;\n\nprocedure QuickSort(SortList: TPointerArray; L, R: Integer; SCompare: TListSortCompare);\n{Do quick sort on items held in TPointerArray}\n{SCompare controls how the pointers are interpreted}\nvar I, J: Integer;\nvar P,T: Pointer;\nbegin\nrepeat\n\tbegin\n\tI := L;\n\tJ := R;\n\tP := SortList[(L + R) shr 1];\n\trepeat\n\t\tbegin\n\t\twhile SCompare(SortList[I], P) < 0 do Inc(I);\n\t\twhile SCompare(SortList[J], P) > 0 do Dec(J);\n\t\tif I <= J then\n\t\t\tbegin\n\t\t\t{Exchange itesm}\n\t\t\tT:=SortList[I];\n\t\t\tSortList[I]:=SortList[J];\n\t\t\tSortList[J]:=T;\n\t\t\tif P = SortList[I] then P := SortList[J]\n\t\t\telse if P = SortList[J] then P := SortList[I];\n\t\t\tInc(I);\n\t\t\tDec(J);\n\t\t\tend;\n\t\tend\n\tuntil I > J;\n\tif L < J then QuickSort(SortList, L, J, SCompare);\n\tL := I;\n\tend\nuntil I >= R;\nend;\n\n\n\nprocedure DisplayStrings(Memo: TMemo; PA: TPointerArray);\n{Display pointers as strings}\nvar I: integer;\nvar S: string;\nbegin\nS:='[';\nfor I:=0 to High(PA) do\n\tbegin\n\tif I>0 then S:=S+' ';\n\tS:=S+string(PA[I]^);\n\tend;\nS:=S+']';\nMemo.Lines.Add(S);\nend;\n\n\nprocedure DisplayIntegers(Memo: TMemo; PA: TPointerArray);\n{Display pointer array as integers}\nvar I: integer;\nvar S: string;\nbegin\nS:='[';\nfor I:=0 to High(PA) do\n\tbegin\n\tif I>0 then S:=S+' ';\n\tS:=S+IntToStr(Integer(PA[I]));\n\tend;\nS:=S+']';\nMemo.Lines.Add(S);\nend;\n\n\nfunction IntCompare(Item1, Item2: Pointer): Integer;\n{Compare for integer sort}\nbegin\nResult:=Integer(Item1)-Integer(Item2);\nend;\n\n\n\nfunction StringCompare(Item1, Item2: Pointer): Integer;\n{Compare for alphabetical string sort}\nbegin\nResult:=AnsiCompareText(string(Item1^),string(Item2^));\nend;\n\nfunction StringRevCompare(Item1, Item2: Pointer): Integer;\n{Compare for reverse alphabetical order}\nbegin\nResult:=AnsiCompareText(string(Item2^),string(Item1^));\nend;\n\n\nfunction StringLenCompare(Item1, Item2: Pointer): Integer;\n{Compare for string length sort}\nbegin\nResult:=Length(string(Item1^))-Length(string(Item2^));\nend;\n\n{Arrays of strings and integers}\n\nvar IA: array [0..9] of integer = (23, 14, 62, 28, 56, 91, 33, 30, 75, 5);\nvar SA: array [0..15] of string = ('Now','is','the','time','for','all','good','men','to','come','to','the','aid','of','the','party.');\n\nprocedure ShowQuickSort(Memo: TMemo);\nvar L: TStringList;\nvar PA: TPointerArray;\nvar I: integer;\nbegin\nMemo.Lines.Add('Integer Sort');\nSetLength(PA,Length(IA));\nfor I:=0 to High(IA) do PA[I]:=Pointer(IA[I]);\nMemo.Lines.Add('Before Sorting');\nDisplayIntegers(Memo,PA);\nQuickSort(PA,0,High(PA),IntCompare);\nMemo.Lines.Add('After Sorting');\nDisplayIntegers(Memo,PA);\n\nMemo.Lines.Add('');\nMemo.Lines.Add('String Sort - Alphabetical');\nSetLength(PA,Length(SA));\nfor I:=0 to High(SA) do PA[I]:=Pointer(@SA[I]);\nMemo.Lines.Add('Before Sorting');\nDisplayStrings(Memo,PA);\nQuickSort(PA,0,High(PA),StringCompare);\nMemo.Lines.Add('After Sorting');\nDisplayStrings(Memo,PA);\n\nMemo.Lines.Add('');\nMemo.Lines.Add('String Sort - Reverse Alphabetical');\nQuickSort(PA,0,High(PA),StringRevCompare);\nMemo.Lines.Add('After Sorting');\nDisplayStrings(Memo,PA);\n\nMemo.Lines.Add('');\nMemo.Lines.Add('String Sort - By Length');\nQuickSort(PA,0,High(PA),StringLenCompare);\nMemo.Lines.Add('After Sorting');\nDisplayStrings(Memo,PA);\nend;\n\n\n","human_summarization":"implement the quicksort algorithm to sort an array or list of elements. The algorithm selects a pivot element and divides the rest of the elements into two partitions: one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and combines them with the pivot to produce the sorted array. The codes also include an optimized version of quicksort that performs sorting in place to avoid additional memory allocation. The quicksort routine is versatile and can sort arrays of pointers containing different data types like integers, strings, floating point numbers, and objects. The sorting order can be customized through a compare routine.","id":3960}
    {"lang_cluster":"Delphi","source_code":"\nShowMessage(FormatDateTime('yyyy-mm-dd', Now) +#13#10+ FormatDateTime('dddd, mmmm dd, yyyy', Now));\n\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":3961}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtilsprogram Power_set;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils;\n\nconst\n  n = 4;\n\nvar\n  buf: TArray<Integer>;\n\nprocedure rec(ind, bg: Integer);\nbegin\n  for var i := bg to n - 1 do\n  begin\n    buf[ind] := i;\n    for var j := 0 to ind do\n      write(buf[j]: 2);\n    writeln;\n    rec(ind + 1, buf[ind] + 1);\n  end;\nend;\n\nbegin\n  SetLength(buf, n);\n  rec(0,0);\n  {$IFNDEF UNIX}readln;{$ENDIF}\nend.\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":3962}
    {"lang_cluster":"Delphi","source_code":"program RomanNumeralsEncode;\n\n{$APPTYPE CONSOLE}\n\nfunction IntegerToRoman(aValue: Integer): string;\nvar\n  i: Integer;\nconst\n  WEIGHTS: array[0..12] of Integer = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1);\n  SYMBOLS: array[0..12] of string = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I');\nbegin\n  for i := Low(WEIGHTS) to High(WEIGHTS) do\n  begin\n    while aValue >= WEIGHTS[i] do\n    begin\n      Result := Result + SYMBOLS[i];\n      aValue := aValue - WEIGHTS[i];\n    end;\n    if aValue = 0 then\n      Break;\n  end;\nend;\n\nbegin\n  Writeln(IntegerToRoman(1990)); \/\/ MCMXC\n  Writeln(IntegerToRoman(2008)); \/\/ MMVIII\n  Writeln(IntegerToRoman(1666)); \/\/ MDCLXVI\nend.\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":3963}
    {"lang_cluster":"Delphi","source_code":"\n\nprocedure TForm1.Button1Click(Sender: TObject);\nvar\n  StaticArray: array[1..10] of Integer; \/\/ static arrays can start at any index\n  DynamicArray: array of Integer; \/\/ dynamic arrays always start at 0\n  StaticArrayText,\n  DynamicArrayText: string;\n  ixS, ixD: Integer;\nbegin\n  \/\/ Setting the length of the dynamic array the same as the static one\n  SetLength(DynamicArray, Length(StaticArray));\n  \/\/ Asking random numbers storing into the static array\n  for ixS := Low(StaticArray) to High(StaticArray) do\n  begin\n    StaticArray[ixS] := StrToInt(\n      InputBox('Random number',\n               'Enter a random number for position',\n               IntToStr(ixS)));\n  end;\n  \/\/ Storing entered numbers of the static array in reverse order into the dynamic\n  ixD := High(DynamicArray);\n  for ixS := Low(StaticArray) to High(StaticArray) do\n  begin\n    DynamicArray[ixD] := StaticArray[ixS];\n    Dec(ixD);\n  end;\n  \/\/ Concatenating the static and dynamic array into a single string variable\n  StaticArrayText := '';\n  for ixS := Low(StaticArray) to High(StaticArray) do\n    StaticArrayText := StaticArrayText + IntToStr(StaticArray[ixS]);\n  DynamicArrayText := '';\n  for ixD := Low(DynamicArray) to High(DynamicArray) do\n    DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[ixD]);\n  end;\n  \/\/ Displaying both arrays (#13#10 = Carriage Return\/Line Feed)\n  ShowMessage(StaticArrayText + #13#10 + DynamicArrayText);\nend;\n\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. It includes creating both static and dynamic arrays, assigning values to them, and retrieving an element from them. The code also involves storing a series of numbers in a static array, reversing them into a dynamic array, concatenating the numbers into two single string variables, and displaying these strings in a popup window.","id":3964}
    {"lang_cluster":"Delphi","source_code":"\n\n- Read(F,V1..Vn)\n- ReadLn(F,V1..Vn)\n- Write(F,V1[,V2..Vn])\n- WriteLn(f,V1[,V2..Vn])\n- BlockRead(F,Buff,BytesToRead[,BytesRead])\n- BlockWrite(F,Buff,BytesToRead[,BytesWritten])\n\n\n\n\n\n\nvar\n  f : TextFile ;\n  s : string ;\nbegin\n  AssignFile(f,[fully qualified file name);\n  Reset(f);\n  writeln(f,s);\n  Reset(f);\n  ReadLn(F,S);  \n  CloseFile(\nend;\n\n\nvar\n  f         : File ;\n  buff      : array[1.1024] of byte ;\n  BytesRead : Integer ;\nbegin\n  AssignFile(f,fully qualified file name);  \n  Reset(f,1);\n  Blockread(f,Buff,SizeOf(Buff),BytesRead); \n  CloseFile(f);\nend;\n\n\ntype \n\n  tAddressBook = Record\n                  FName   : string[20];\n                  LName   : string[30];\n                  Address : string[30];\n                  City    : string[30];\n                  State   : string[2];\n                  Zip5    : string[5];\n                  Zip4    : string[4];\n                  Phone   : string[14];\n                  Deleted : boolean ;\n                end;\n\nvar\n  f     : file of tAddressBook ;\n  v     : tAddressBook ;\n  bytes : integer ;\nbegin\n  AssignFile(f,fully qualified file name);  \n  Reset(f);\n  Blockread(f,V,1,Bytes);\n  Edit(v);\n  Seek(F,FilePos(f)-1);\n  BlockWrite(f,v,1,bytes);\n  CloseFile(f);\nend;\n\n","human_summarization":"The code reads the contents of an \"input.txt\" file into an intermediate variable, then writes the contents of this variable into a new file called \"output.txt\". It demonstrates file input\/output operations in Delphi, including reading from a file into a variable and writing a variable's contents into a file. The code also handles file operations for both typed and untyped files, as well as text files, and includes error handling for non-existing files or unexpected end of file situations. It also utilizes Delphi's Streams, specifically TFileStream, for file handling.","id":3965}
    {"lang_cluster":"Delphi","source_code":"\nwriteln(uppercase('alphaBETA'));\nwriteln(lowercase('alphaBETA'));\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":3966}
    {"lang_cluster":"Delphi","source_code":"\nprogram closestPoints;\n{$IFDEF FPC}\n   {$MODE Delphi}\n{$ENDIF}\nconst\n  PointCnt = 10000;\/\/31623;\ntype\n  TdblPoint = Record\n               ptX,\n               ptY : double;\n              end;\n  tPtLst =  array of TdblPoint;\n\n  tMinDIstIdx  = record\n                   md1,\n                   md2 : NativeInt;\n                 end;\n\nfunction ClosPointBruteForce(var  ptl :tPtLst):tMinDIstIdx;\nVar\n  i,j,k : NativeInt;\n  mindst2,dst2: double; \/\/square of distance, no need to sqrt\n  p0,p1 : ^TdblPoint;   \/\/using pointer, since calc of ptl[?] takes much time\nBegin\n  i := Low(ptl);\n  j := High(ptl);\n  result.md1 := i;result.md2 := j;\n  mindst2 := sqr(ptl[i].ptX-ptl[j].ptX)+sqr(ptl[i].ptY-ptl[j].ptY);\n  repeat\n    p0 := @ptl[i];\n    p1 := p0; inc(p1);\n    For k := i+1 to j do\n    Begin\n      dst2:= sqr(p0^.ptX-p1^.ptX)+sqr(p0^.ptY-p1^.ptY);\n      IF mindst2 > dst2  then\n      Begin\n        mindst2 :=  dst2;\n        result.md1 := i;\n        result.md2 := k;\n      end;\n      inc(p1);\n    end;\n    inc(i);\n  until i = j;\nend;\n\nvar\n  PointLst :tPtLst;\n  cloPt : tMinDIstIdx;\n  i : NativeInt;\nBegin\n  randomize;\n  setlength(PointLst,PointCnt);\n  For i := 0 to PointCnt-1 do\n    with PointLst[i] do\n    Begin\n      ptX := random;\n      ptY := random;\n    end;\n  cloPt:=  ClosPointBruteForce(PointLst) ;\n  i := cloPt.md1;\n  Writeln('P[',i:4,']= x: ',PointLst[i].ptX:0:8,\n                     ' y: ',PointLst[i].ptY:0:8);\n  i := cloPt.md2;\n  Writeln('P[',i:4,']= x: ',PointLst[i].ptX:0:8,\n                     ' y: ',PointLst[i].ptY:0:8);\nend.","human_summarization":"The code provides two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute-force approach with a time complexity of O(n^2) to find the pair of points with the minimum distance. The second function uses a recursive divide and conquer strategy with a time complexity of O(n log n) to find the closest pair of points. The points are sorted by x and y coordinates for efficient computation.","id":3967}
    {"lang_cluster":"Delphi","source_code":"\n\n\/\/ Creates and initializes a new integer Array\nvar\n    \/\/ Dynamics arrays can be initialized, if it's global variable in declaration scope \n    intArray: TArray<Integer> = [1, 2, 3, 4, 5];\n    intArray2: array of Integer = [1, 2, 3, 4, 5];\n    \n    \/\/Cann't initialize statics arrays in declaration scope\n    intArray3: array [0..4]of Integer;\n    intArray4: array [10..14]of Integer;\n\nprocedure \nvar\n    \/\/ Any arrays can't be initialized, if it's local variable in declaration scope\n    intArray5: TArray<Integer>;\nbegin\n  \/\/ Dynamics arrays can be full assigned in routine scope\n  intArray := [1,2,3];\n  intArray2 := [1,2,3];\n\n  \/\/ Dynamics arrays zero-based  \n  intArray[0] := 1;\n\n  \/\/ Dynamics arrays must set size, if it not was initialized before\n  SetLength(intArray,5);\n\n  \/\/ Inline dynamics arrays can be created and initialized routine scope\n  \/\/ only for version after 10.3 Tokyo\n  var intArray6 := [1, 2, 3];\n  var intArray7: TArray<Integer> := [1, 2, 3];\nend;\n\n\nvar\n    \/\/ TLists can't be initialized or created in declaration scope\n    List1, List2:TList<Integer>;\nbegin\n    List1 := TList<Integer>.Create;\n    List1.Add(1);\n    list1.AddRange([2, 3]);\n    List1.free;\n\n    \/\/ TList can be initialized using a class derivative from TEnumerable, like it self\n    List1 := TList<Integer>.Create;    \n    list1.AddRange([1,2, 3]);\n\n    List2 := TList<Integer>.Create(list1);\n    Writeln(List2[2]); \/\/ 3\n    List1.free;\n    List2.free;\n    \n\n    \/\/ Inline TList can be created in routine scope\n    \/\/ only for version after 10.3 Tokyo\n    var List3:= TList<Integer>.Create;\n    List3.Add(2);\n    List3.free;\n\n    var List4: TList<Integer>:= TList<Integer>.Create;\n    List4.free;\nend;\n\n\n var\n    \/\/ TDictionary can't be initialized or created in declaration scope\n    Dic1: TDictionary<string, Integer>;\nbegin\n    Dic1 := TDictionary<string, Integer>.Create;\n    Dic1.Add('one',1);\n    Dic1.free;\n\n    \/\/ Inline TDictionary can be created in routine scope\n    \/\/ only for version after 10.3 Tokyo\n    var Dic2:= TDictionary<string, Integer>.Create;\n    Dic2.Add('one',1);\n    Dic2.free;\n\n    var Dic3: TDictionary<string, Integer>:= TDictionary<string, Integer>.Create.Create;\n    Dic3.Add('one',1);\n    Dic3.free;\nend;\n\n\nvar\n    Queue1, Queue2: TQueue<Integer>;\n    List1:TList<Integer>;\nbegin\n    Queue1 := TQueue<Integer>.Create;\n    Queue1.Enqueue(1);\n    Queue1.Enqueue(2);\n    Writeln(Queue1.Dequeue); \/\/ 1\n    Writeln(Queue1.Dequeue); \/\/ 2\n    Queue1.free;\n\n    \/\/ TQueue can be initialized using a class derivative from TEnumerable, like TList<T>\n    List1 := TList<Integer>.Create;\n    List1.Add(3);    \n    Queue2:= TQueue<Integer>.Create(List1);\n    Writeln(Queue2.Dequeue); \/\/ 3\n    List1.free;\n    Queue2.free;\n\n    \/\/ Inline TQueue can be created in routine scope\n    \/\/ only for version after 10.3 Tokyo\n    var Queue3 := TQueue<Integer>.Create;\n    Queue3.free;\nend;\n\n\nvar\n    Stack1, Stack2: TStack<Integer>;    \n    List1:TList<Integer>;\nbegin\n    Stack1:= TStack<Integer>.Create;\n    Stack1.Push(1);\n    Stack1.Push(2);\n    Writeln(Stack1.Pop); \/\/ 2\n    Writeln(Stack1.Pop); \/\/ 1\n    Stack1.free;\n    \n    \/\/ TStack can be initialized using a class derivative from TEnumerable, like TList<T>\n    List1 := TList<Integer>.Create;\n    List1.Add(3);\n    Stack2:= TStack<Integer>.Create(List1);\n    Writeln(Stack2.Pop); \/\/ 3\n    List1.free;\n    Stack2.free;\n\n    \/\/ Inline TStack can be created in routine scope\n    \/\/ only for version after 10.3 Tokyo\n    var Stack3:= TStack<Integer>.Create;\n    Stack3.free;\nend;\n\n\nvar\n    Str1:String;  \/\/ default WideString\n    Str2:WideString;\n    Str3:UnicodeString;\n    Str4:AnsiString;\n    Str5: PChar; \/\/PWideChar is the same\n    Str6: PAnsiChar;\n\n    \/\/ Strings can be initialized, if it's global variable in declaration scope \n    Str4: string = 'orange';\nbegin\n    Str1 := 'apple';\n\n    \/\/ WideString and AnsiString can be converted implicitly, but in some times can lost information about char\n    Str4 := Str1;\n\n    \/\/ PChar is a poiter to string (WideString), must be converted using type cast\n    Str5 := Pchar(Str1);\n    \n    \/\/ PChar not must type cast to convert back string\n    Str2 := Str5;\n\n    \/\/In any string, index start in 1 and end on length of string\n    Writeln(Str1[1]); \/\/ 'a'\n    Writeln(Str1[5]); \/\/ 'e'\n    Writeln(Str1[length(str1)]); \/\/ the same above\nend;\n\n\n","human_summarization":"create and manage different types of collections, including arrays, lists, and generic classes like TDictionary, TQueue, and TStack. These collections represent sets of values, key\/value pairs, and data stored in specific modes. The code also handles memory management for these collections, releasing them after use. Additionally, it deals with strings as arrays of chars.","id":3968}
    {"lang_cluster":"Delphi","source_code":"\nprogram LoopsNPlusOneHalf;\n\n{$APPTYPE CONSOLE}\n\nvar\n  i: integer;\nconst\n  MAXVAL = 10;\nbegin\n  for i := 1 to MAXVAL do\n  begin\n    Write(i);\n    if i < MAXVAL then\n      Write(', ');\n  end;\n  Writeln;\nend.\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":3969}
    {"lang_cluster":"Delphi","source_code":"\nprogram CharacterMatching;\n\n{$APPTYPE CONSOLE}\n\nuses StrUtils;\n\nbegin\n  WriteLn(AnsiStartsText('ab', 'abcd')); \/\/ True\n  WriteLn(AnsiEndsText('zn', 'abcd')); \/\/ False\n  WriteLn(AnsiContainsText('abcd', 'bb')); \/\/ False\n  Writeln(AnsiContainsText('abcd', 'ab')); \/\/ True\n  WriteLn(Pos('ab', 'abcd')); \/\/ 1\nend.\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":3970}
    {"lang_cluster":"Delphi","source_code":"\nprogram square4;\n{$MODE DELPHI}\n{$R+,O+}\nconst\n  LoDgt = 0;\n  HiDgt = 9;\ntype\n  tchkset = set of LoDgt..HiDgt;\n  tSol = record\n           solMin : integer;\n           solDat : array[1..7] of integer;\n         end;\n\nvar\n  sum,a,b,c,d,e,f,g,cnt,uniqueCount : NativeInt;\n  sol : array of tSol;\n\nprocedure SolOut;\nvar\n  i,j,mn: NativeInt;\nBegin\n  mn := 0;\n  repeat\n    writeln(mn:3,' ...',mn+6:3);\n    For i := Low(sol) to High(sol) do\n      with sol[i] do\n        IF solMin = mn then\n        Begin\n          For j := 1 to 7 do\n            write(solDat[j]:3);\n          writeln;\n        end;\n    writeln;\n    inc(mn);\n  until mn > HiDgt-6;\nend;\n\nfunction CheckUnique:Boolean;\nvar\n  i,sum,mn: NativeInt;\n  chkset : tchkset;\n\nBegin\n  chkset:= [];\n  include(chkset,a);include(chkset,b);include(chkset,c);\n  include(chkset,d);include(chkset,e);include(chkset,f);\n  include(chkset,g);\n  sum := 0;\n  For i := LoDgt to HiDgt do\n    IF i in chkset then\n      inc(sum);\n\n  result := sum = 7;\n  IF result then\n  begin\n    inc(uniqueCount);\n    \/\/find the lowest entry\n    mn:= LoDgt;\n    For i := LoDgt to HiDgt do\n      IF i in chkset then\n      Begin\n        mn := i;\n        BREAK;\n      end;\n    \/\/ are they consecutive\n    For i := mn+1 to mn+6  do\n      IF NOT(i in chkset) then\n        EXIT;\n\n    setlength(sol,Length(sol)+1);\n    with sol[high(sol)] do\n      Begin\n        solMin:= mn;\n        solDat[1]:= a;solDat[2]:= b;solDat[3]:= c;\n        solDat[4]:= d;solDat[5]:= e;solDat[6]:= f;\n        solDat[7]:= g;\n      end;\n  end;\nend;\n\nBegin\n  cnt := 0;\n  uniqueCount := 0;\n  For a:= LoDgt to HiDgt do\n  Begin\n    For b := LoDgt to HiDgt do\n    Begin\n      sum := a+b;\n      \/\/a+b = b+c+d => a = c+d => d := a-c\n      For c := a-LoDgt downto LoDgt do\n      begin\n        d := a-c;\n        e := sum-d;\n        IF e>HiDgt then\n          e:= HiDgt;\n        For e := e downto LoDgt do\n          begin\n          f := sum-e-d;\n          IF f in [loDGt..Hidgt]then\n          Begin\n            g := sum-f;\n            IF g in [loDGt..Hidgt]then\n            Begin\n              inc(cnt);\n              CheckUnique;\n            end;\n          end;\n        end;\n      end;\n    end;\n  end;\n  SolOut;\n  writeln('       solution count for ',loDgt,' to ',HiDgt,' = ',cnt);\n  writeln('unique solution count for ',loDgt,' to ',HiDgt,' = ',uniqueCount);\nend.\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square's sum is equal. It first finds solutions where each letter (a-g) represents a unique number between 1 and 7, then between 3 and 9. Finally, it calculates the number of solutions where each letter can represent a non-unique number between 0 and 9.","id":3971}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  Winapi.Windows\nLibrary:  System.SysUtils\nLibrary:  System.Classes\nLibrary:  Vcl.Graphics\nLibrary:  Vcl.Forms\nLibrary:  Vcl.ExtCtrls\nunit main;\n\ninterface\n\nuses\n  Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms,\n  Vcl.ExtCtrls;\n\ntype\n  TClock = class(TForm)\n    tmrTimer: TTimer;\n    procedure FormResize(Sender: TObject);\n    procedure tmrTimerTimer(Sender: TObject);\n  private\n    { Private declarations }\n    const\n      degrees06 = PI \/ 30;\n      degrees30 = degrees06 * 5;\n      degrees90 = degrees30 * 3;\n      margin = 20;\n    var\n      p0: TPoint;\n      MinP0XY: Integer;\n    class function IfThen(Condition: Boolean; TrueValue, FalseValue: Integer):\n      Integer; overload; static;\n    class function IfThen(Condition: Boolean; TrueValue, FalseValue: Double):\n      Double; overload; static;\n    procedure Paint; override;\n    procedure DrawHand(Color: TColor; Angle, Size: Double; aWidth: Integer = 2);\n    procedure DrawFace;\n    procedure DrawCenter;\n    procedure DrawNumbers(Angle: Double; Value: Integer);\n  public\n    { Public declarations }\n  end;\n\nvar\n  Clock: TClock;\n\nimplementation\n\n{$R *.dfm}\n\n{ TClock }\n\nprocedure TClock.DrawCenter;\nvar\n  radius: Integer;\nbegin\n  radius := 6;\n  with Canvas do\n  begin\n    pen.Color := clNone;\n    Brush.Color := clBlack;\n    Ellipse(p0.x - radius, p0.y - radius, p0.x + radius, p0.y + radius);\n  end;\nend;\n\nprocedure TClock.DrawFace;\nvar\n  radius, h, m: Integer;\nbegin\n  radius := MinP0XY - margin;\n  with Canvas do\n  begin\n    Pen.Color := clBlack;\n    Pen.Width := 2;\n    Brush.Color := clWhite;\n    Ellipse(p0.x - radius, p0.y - radius, p0.x + radius, p0.y + radius);\n    for m := 0 to 59 do\n      DrawHand(clGray, m * degrees06, -0.08, 2);\n\n    for h := 0 to 11 do\n    begin\n      DrawHand(clBlack, h * degrees30, -0.09, 3);\n      DrawNumbers((h + 3) * degrees30, 12 - h);\n    end;\n  end;\nend;\n\nprocedure TClock.DrawHand(Color: TColor; Angle, Size: Double; aWidth: Integer = 2);\nvar\n  radius, x0, y0, x1, y1: Integer;\nbegin\n  radius := MinP0XY - margin;\n\n  x0 := p0.X + (IfThen(Size > 0, 0, Round(radius * (Size + 1) * cos(Angle))));\n  y0 := p0.Y + (IfThen(Size > 0, 0, Round(radius * (Size + 1) * sin(-Angle))));\n\n  x1 := p0.X + round(radius * IfThen(Size > 0, Size, 1) * cos(Angle));\n  y1 := p0.y + round(radius * IfThen(Size > 0, Size, 1) * sin(-Angle));\n\n  with Canvas do\n  begin\n    Pen.Color := Color;\n    pen.Width := aWidth;\n    MoveTo(x0, y0);\n    LineTo(x1, y1);\n  end;\nend;\n\nprocedure TClock.DrawNumbers(Angle: Double; Value: Integer);\nvar\n  radius, x0, y0, x1, y1, h, w: Integer;\n  Size: Double;\n  s: string;\nbegin\n  radius := MinP0XY - margin;\n  Size := 0.85;\n  s := (Value).ToString;\n\n  x1 := p0.X + round(radius * Size * cos(Angle));\n  y1 := p0.y + round(radius * Size * sin(-Angle));\n\n  with Canvas do\n  begin\n    radius := 5;\n    Font.Size := 12;\n    w := TextWidth(s);\n    h := TextHeight(s);\n\n    x0 := x1 - (w div 2);\n    y0 := y1 - (h div 2);\n\n    TextOut(x0, y0, s);\n  end;\nend;\n\nprocedure TClock.FormResize(Sender: TObject);\nbegin\n  p0 := Tpoint.create(ClientRect.CenterPoint);\n  MinP0XY := p0.x;\n  if MinP0XY > p0.Y then\n    MinP0XY := p0.y;\n  Refresh();\nend;\n\nclass function TClock.IfThen(Condition: Boolean; TrueValue, FalseValue: Double): Double;\nbegin\n  if Condition then\n    exit(TrueValue);\n  exit(FalseValue);\nend;\n\nclass function TClock.IfThen(Condition: Boolean; TrueValue, FalseValue: Integer): Integer;\nbegin\n  if Condition then\n    exit(TrueValue);\n  exit(FalseValue);\nend;\n\nprocedure TClock.Paint;\nvar\n  t: TDateTime;\n  second, minute, hour: Integer;\n  angle, minsecs, hourmins: Double;\nbegin\n  inherited;\n\n  t := time;\n  second := trunc(Frac(t * 24 * 60) * 60);\n  minute := trunc(Frac(t * 24) * 60);\n  hour := trunc(t * 24);\n\n  DrawFace;\n\n  angle := degrees90 - (degrees06 * second);\n  DrawHand(clred, angle, 0.95, 3);\n\n  minsecs := (minute + second \/ 60.0);\n\n  angle := degrees90 - (degrees06 * minsecs);\n  DrawHand(clGreen, angle, 0.8, 4);\n\n  hourmins := (hour + minsecs \/ 60.0);\n  angle := degrees90 - (degrees30 * hourmins);\n  DrawHand(clBlue, angle, 0.6, 5);\n\n  DrawCenter;\n\n  Caption := Format('%.2d:%.2d:%.2d', [hour, minute, second]);\nend;\n\nprocedure TClock.tmrTimerTimer(Sender: TObject);\nbegin\n  Refresh;\nend;\n\nend.\n\n\nobject Clock: TClock\n  Left = 0\n  Top = 0\n  Caption = 'Draw_a_clock'\n  ClientHeight = 462\n  ClientWidth = 484\n  Color = clBtnFace\n  DoubleBuffered = True\n  Font.Charset = DEFAULT_CHARSET\n  Font.Color = clWindowText\n  Font.Height = -11\n  Font.Name = 'Tahoma'\n  Font.Style = []\n  OldCreateOrder = False\n  Position = poDesktopCenter\n  OnResize = FormResize\n  PixelsPerInch = 96\n  TextHeight = 13\n  object tmrTimer: TTimer\n    OnTimer = tmrTimerTimer\n    Left = 16\n    Top = 8\n  end\nend\n\n\n\n","human_summarization":"The code creates a simple, animated clock that updates every second. It utilizes system or language-specific timers instead of constantly polling system resources. The clock, which could be any time-keeping device, only needs to display seconds and should align with the system clock. The code is designed to be clear, concise, and efficient, avoiding unnecessary complexity and CPU usage.","id":3972}
    {"lang_cluster":"Delphi","source_code":"\nProgram PythagoreanTriples (output);\n\nvar\n  total, prim, maxPeri: int64;\n\nprocedure newTri(s0, s1, s2: int64);\n  var\n    p: int64;\n  begin\n    p := s0 + s1 + s2;\n    if p <= maxPeri then\n    begin\n      inc(prim);\n      total := total + maxPeri div p;\n      newTri( s0 + 2*(-s1+s2),  2*( s0+s2) - s1,  2*( s0-s1+s2) + s2);\n      newTri( s0 + 2*( s1+s2),  2*( s0+s2) + s1,  2*( s0+s1+s2) + s2);\n      newTri(-s0 + 2*( s1+s2),  2*(-s0+s2) + s1,  2*(-s0+s1+s2) + s2);\n    end;\n  end;\n  \nbegin\n  maxPeri := 100;\n  while maxPeri <= 1e10 do\n  begin\n    prim := 0;\n    total := 0;\n    newTri(3, 4, 5);\n    writeln('Up to ', maxPeri, ': ', total, ' triples, ', prim, ' primitives.');\n    maxPeri := maxPeri * 10;\n  end;\nend.\n","human_summarization":"The code calculates the number of Pythagorean triples (a, b, c) where a, b, and c are positive integers, a < b < c, and a^2 + b^2 = c^2, with a perimeter (a+b+c) no larger than 100. It also identifies the number of these triples that are primitive, i.e., a, b, and c are co-prime. The code is optimized to handle large values up to a maximum perimeter of 100,000,000.","id":3973}
    {"lang_cluster":"Delphi","source_code":"\n\n\/\/ The project file (Project1.dpr)\nprogram Project1;\n\nuses\n  Forms,\n  \/\/ Include file with Window class declaration (see below)\n  Unit0 in 'Unit1.pas' {Form1};\n\n{$R *.res}\n\nbegin\n  Application.Initialize;\n  Application.CreateForm(TForm1, Form1);\n  Application.Run;\nend.\n\n\n\/\/ The Window class declaration\nunit Unit1;\n\ninterface\n\nuses\n  Forms;\n\ntype\n  TForm1 = class(TForm)\n  end;\n\nvar\n  Form1: TForm1;\n\nimplementation\n\n{$R *.dfm} \/\/ The window definition resource (see below)\n\nend.\n\n\/\/ A textual rendition of the Window (form) definition file (Unit1.dfm)\nobject Form1: TForm1\n  Left = 469\n  Top = 142\n  Width = 800\n  Height = 600\n  Caption = 'Form1'\n  Color = clBtnFace\n  Font.Charset = DEFAULT_CHARSET\n  Font.Color = clWindowText\n  Font.Height = -11\n  Font.Name = 'MS Shell Dlg 2'\n  Font.Style = []\n  OldCreateOrder = False\n  Position = poScreenCenter\n  PixelsPerInch = 96\n  TextHeight = 13\nend\n\n\nprogram Project3;\n\nuses\n  Windows,\n  Messages;\n\nvar\n  WndClass: TWndClass;\n  Msg: TMsg;\n  winT, winL: Integer;\n\n\/\/ Initial height\/width of the window\nconst\n  winW: Integer = 800;\n  winH: Integer = 600;\n\n\/\/ Callback function to processes messages sent to the window\nfunction WindowProc(hWnd,Msg,wParam,lParam:Integer): Integer; stdcall;\nbegin\n  \/\/ Trap the WM_DESTROY message\n  if (Msg = WM_DESTROY) then PostQuitMessage(0);\n  Result := DefWindowProc(hWnd,Msg,wParam,lParam);\nend;\n\nbegin\n  \/\/ Fill the WndClass structure with the window class attributes\n  \/\/ to be registered by the RegisterClass function\n  with WndClass do\n    begin\n      lpszClassName:= 'Form1';\n      lpfnWndProc :=  @WindowProc; \/\/ Pointer to our message handling callback\n      style := CS_OWNDC or         \/\/ Request a unique device context\n               CS_VREDRAW or       \/\/ Redraw window when resized vertically\n               CS_HREDRAW;         \/\/ Redraw window when resized horizontally\n      hInstance := hInstance;      \/\/ The instance that the window procedure of this class is within\n      hbrBackground := HBRUSH(COLOR_BTNFACE+1); \/\/ Background colour of the window\n    end;\n\n  \/\/ Register the window class for use by CreateWindow\n  RegisterClass(WndClass);\n\n  \/\/ Calculate initial top and left positions of the window\n  winT := (GetSystemMetrics(SM_CYFULLSCREEN) - winH) div 2;\n  winL := (GetSystemMetrics(SM_CXFULLSCREEN) - winW) div 2;\n\n  \/\/ Create the window\n  CreateWindow(WndClass.lpszClassName,              \/\/ Class name\n               'Form1',                             \/\/ Window name\n               WS_OVERLAPPEDWINDOW or WS_VISIBLE,   \/\/ Window style\n               winL,                                \/\/ Horizontal Position (Left)\n               winT,                                \/\/ Vertical Position (Top)\n               winW,                                \/\/ Width\n               winH,                                \/\/ Height\n               0,                                   \/\/ Window parent\/owner handle\n               0,                                   \/\/ Menu handle\n               hInstance,                           \/\/ Handle to application instance\n               nil);                                \/\/ Pointer to window creation data\n\n \/\/ Handle messages\n while GetMessage(Msg,0,0,0) do\n   DispatchMessage(Msg);\n\nend.\n\n","human_summarization":"create a GUI window that can respond to close requests. Two methods are demonstrated: one using Delphi's standard window creation procedure, resulting in a 362KB executable, and a second 'pure' Windows API approach, not using the Delphi Visual Component Library, resulting in a 15KB executable.","id":3974}
    {"lang_cluster":"Delphi","source_code":"\nprogram letterFrequency(input, output);\nvar\n\tchart: array[char] of 0..maxInt value [otherwise 0];\n\tc: char;\nbegin\n\t{ parameter-less EOF checks for EOF(input) }\n\twhile not EOF do\n\tbegin\n\t\tread(c);\n\t\tchart[c] := chart[c] + 1\n\tend;\n\t\n\t{ now, chart[someLetter] gives you the letter\u2019s frequency }\nend.\n","human_summarization":"\"Open a text file, count the frequency of each letter from A to Z, and optionally include punctuation characters.\"","id":3975}
    {"lang_cluster":"Delphi","source_code":"\n\nType\n  pOneWayList = ^OneWayList;\n  OneWayList = record\n                pData : pointer ;\n                Next  : pOneWayList ;\n               end;\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member that can hold a numeric value and a mutable link to the next element. It's a simple one-way list that uses a generic pointer for the data, allowing it to point to any structure or variable. However, in Standard Pascal, a specific data type must be used as there are no generic pointers.","id":3976}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\nprocedure DrawTree(Image: TImage; X1, Y1: integer; Angle: double; Depth: integer);\nvar X2,Y2: integer;\nbegin\nif Depth = 0 then exit;\nX2:=trunc(X1 + cos(DegToRad(Angle)) * Depth * 5);\nY2:=trunc(Y1 + sin(DegToRad(Angle)) * Depth * 5);\nImage.Canvas.Pen.Color:=ColorMap47[MulDiv(High(ColorMap47),Depth,11)];\nImage.Canvas.Pen.Width:=MulDiv(Depth,5,10);\nImage.Canvas.MoveTo(X1,Y1);\nImage.Canvas.LineTo(X2,Y2);\nDrawTree(Image, X2, Y2, Angle - 10, Depth - 1);\nDrawTree(Image, X2, Y2, Angle + 35, Depth - 1);\nend;\n\n\nprocedure ShowFactalTree(Image: TImage);\nbegin\nClearImage(Image,clBlack);\nDrawTree(Image, 250, 350, -90, 11);\nImage.Invalidate;\nend;\n\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":3977}
    {"lang_cluster":"Delphi","source_code":"\nprogram Factors;\nvar\n  i, number: integer;\nbegin \n  write('Enter a number between 1 and 2147483647: ');\n  readln(number);\n \n  for i := 1 to round(sqrt(number)) - 1 do\n    if number mod i = 0 then\n      write (i, ' ',  number div i, ' ');\n \n  \/\/ Check to see if number is a square\n  i := round(sqrt(number));\n  if i*i = number then\n     write(i)\n  else if number mod i = 0 then\n     write(i, number\/i);\n  writeln;\nend.\n","human_summarization":"calculate the factors of a given positive integer, excluding zero and negative integers. It also notes that every prime number has two factors: 1 and itself.","id":3978}
    {"lang_cluster":"Delphi","source_code":"\nLibrary: Delphi StdCtrls, Classes, SysUtils, StrUtils, Contnrs\nUSES\n   StdCtrls, Classes, SysUtils, StrUtils, Contnrs;\n\nprocedure AlignByColumn(","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":3979}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtilsprogram Draw_a_cuboid;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils;\n\nprocedure cubLine(n, dx, dy: Integer; cde: string);\nvar\n  i: integer;\nbegin\n  write(format('%' + (n + 1).ToString + 's', [cde.Substring(0, 1)]));\n\n  for i := 9 * dx - 1 downto 1 do\n    Write(cde.Substring(1, 1));\n\n  Write(cde.Substring(0, 1));\n  Writeln(cde.Substring(2, cde.Length).PadLeft(dy + 1));\nend;\n\nprocedure cuboid(dx, dy, dz: integer);\nvar\n  i: integer;\nbegin\n  Writeln(Format('cuboid %d %d %d:', [dx, dy, dz]));\n\n  cubLine(dy + 1, dx, 0, '+-');\n\n  for i := 1 to dy do\n    cubLine(dy - i + 1, dx, i - 1, '\/ |');\n\n  cubLine(0, dx, dy, '+-|');\n\n  for i := 4 * dz - dy - 2 downto 1 do\n    cubLine(0, dx, dy, '| |');\n\n  cubLine(0, dx, dy, '| +');\n\n  for i := 1 to dy do\n    cubLine(0, dx, dy - i, '| \/');\n\n  cubLine(0, dx, 0, '+-');\n  Writeln;\nend;\n\nbegin\n  cuboid(2, 3, 4);\n  cuboid(1, 1, 1);\n  cuboid(6, 2, 1);\n\n  readln;\nend.\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":3980}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtilsprogram Rot13;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils;\n\nfunction Rot13char(c: AnsiChar): AnsiChar;\nbegin\n  Result := c;\n  if c in ['a'..'m', 'A'..'M'] then\n    Result := AnsiChar(ord(c) + 13)\n  else if c in ['n'..'z', 'N'..'Z'] then\n    Result := AnsiChar(ord(c) - 13);\nend;\n\nfunction Rot13Fn(s: ansistring): ansistring;\nvar i: Integer;\nbegin\n  SetLength(result, length(s));\n  for i := 1 to length(s) do\n    Result[i] := Rot13char(s[i]);\nend;\n\nbegin\n  writeln(Rot13Fn('nowhere ABJURER'));\n  readln;\nend.\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":3981}
    {"lang_cluster":"Delphi","source_code":"\nprogram SortCompositeStructures;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils, Generics.Collections, Generics.Defaults;\n\ntype\n  TStructurePair = record\n    name: string;\n    value: string;\n    constructor Create(const aName, aValue: string);\n  end;\n\nconstructor TStructurePair.Create(const aName, aValue: string);\nbegin\n  name := aName;\n  value := aValue;\nend;\n\nvar\n  lArray: array of TStructurePair;\nbegin\n  SetLength(lArray, 3);\n  lArray[0] := TStructurePair.Create('dog', 'rex');\n  lArray[1] := TStructurePair.Create('cat', 'simba');\n  lArray[2] := TStructurePair.Create('horse', 'trigger');\n\n  TArray.Sort<TStructurePair>(lArray , TDelegatedComparer<TStructurePair>.Construct(\n  function(const Left, Right: TStructurePair): Integer\n  begin\n    Result := CompareText(Left.Name, Right.Name);\n  end));\nend.\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":3982}
    {"lang_cluster":"Delphi","source_code":"\nprogram LoopFor;\n\n{$APPTYPE CONSOLE}\n\nvar\n  i, j: Integer;\nbegin\n  for i := 1 to 5 do\n  begin\n    for j := 1 to i do\n      Write('*');\n    Writeln;\n  end;\nend.\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":3983}
    {"lang_cluster":"Delphi","source_code":"\nprogram AssociativeArrayCreation;\n\n{$APPTYPE CONSOLE}\n\nuses Generics.Collections;\n\nvar\n  lDictionary: TDictionary<string, Integer>;\nbegin\n  lDictionary := TDictionary<string, Integer>.Create;\n  try\n    lDictionary.Add('foo', 5);\n    lDictionary.Add('bar', 10);\n    lDictionary.Add('baz', 15);\n    lDictionary.AddOrSetValue('foo', 6); \/\/ replaces value if it exists\n  finally\n    lDictionary.Free;\n  end;\nend.\n\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":3984}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  Winapi.Windowsprogram Linear_congruential_generator;\n\n{$APPTYPE CONSOLE}\n{$R *.res}\n\nuses\n  System.SysUtils,\n  Winapi.Windows;\n\ntype\n  TRandom = record\n  private\n    FSeed: Cardinal;\n    FBsdCurrent: Cardinal;\n    FMsvcrtCurrent: Cardinal;\n    class function Next(seed, a, b: Cardinal): Cardinal; static;\n  public\n    constructor Create(const seed: Cardinal);\n    function Rand(Bsd: Boolean = True): Cardinal;\n    property Seed: Cardinal read FSeed;\n  end;\n\n{ TRandom }\n\nclass function TRandom.Next(seed, a, b: Cardinal): Cardinal;\nbegin\n  Result := (a * seed + b) and MAXDWORD;\nend;\n\nfunction TRandom.Rand(Bsd: Boolean): Cardinal;\nbegin\n  if Bsd then\n  begin\n    FBsdCurrent := Next(FBsdCurrent, 1103515245, 12345);\n    Result := FBsdCurrent;\n  end\n  else\n  begin\n    FMsvcrtCurrent := Next(FMsvcrtCurrent shl 16, 214013, 2531011) shr 16;\n    Result := FMsvcrtCurrent;\n  end;\nend;\n\nconstructor TRandom.Create(const seed: Cardinal);\nbegin\n  FSeed := seed;\n  FBsdCurrent := FSeed;\n  FMsvcrtCurrent := FSeed;\nend;\n\nvar\n  r: TRandom;\n\nprocedure PrintRandom(count: Integer; IsBsd: Boolean);\nconst\n  NAME: array[Boolean] of string = ('MS', 'BSD');\nvar\n  i: Integer;\nbegin\n  Writeln(NAME[IsBsd], ' next ', count, ' Random'#10);\n  for i := 0 to count - 1 do\n    writeln('   ', r.Rand(IsBsd));\n  writeln;\nend;\n\nbegin\n  r.Create(GetTickCount);\n  PrintRandom(10, True);\n  PrintRandom(10, False);\n  readln;\nend.\n\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":3985}
    {"lang_cluster":"Delphi","source_code":"\n\n\/\/ Using the same type defs from the one way list example.\n\nType\n\n  \/\/ The pointer to the list structure\n  pOneWayList = ^OneWayList;\n\n  \/\/ The list structure\n  OneWayList = record\n                 pData : pointer ;\n                 Next  : pOneWayList ;\n               end;\n\n\/\/ I will illustrate a simple function that will return a pointer to the \n\/\/ new node or it will return NIL.  In this example I will always insert\n\/\/ right, to keep the code clear.  Since I am using a function all operations\n\/\/ for the new node will be conducted on the functions result.  This seems\n\/\/ somewhat counter intuitive, but it is the simplest way to accomplish this.\n\nFunction InsertNode(VAR CurrentNode:pOneWayList): pOneWayList\nbegin\n\n    \/\/ I try not to introduce different parts of the language, and keep each\n    \/\/ example to just the code required.  in this case it is important to use\n    \/\/ a try\/except block.  In any OS that is multi-threaded and has many apps\n    \/\/ running at the same time, you cannot rely on a call to check memory available\n    \/\/ and then attempting to allocate.  In the time between the two, another \n    \/\/ program may have grabbed the memory you were trying to get.\n\n    Try\n      \/\/ Try to allocate enough memory for a variable the size of OneWayList\n      GetMem(Result,SizeOf(OneWayList));\n    Except\n      On EOutOfMemoryError do\n         begin\n           Result := NIL\n           exit;\n         end;\n    end;\n\n    \/\/ Initialize the variable.\n    Result.Next  := NIL ;\n    Reuslt.pdata := NIL ;\n\n    \/\/ Ok now we will insert to the right.\n\n    \/\/ Is the Next pointer of CurrentNode Nil?  If it is we are just tacking\n    \/\/ on to the end of the list.\n\n    if CurrentNode.Next = NIL then\n       CurrentNode.Next := Result\n    else\n      \/\/ We are inserting into the middle of this list\n      Begin\n         Result.Next      := CurrentNode.Next ;\n         CurrentNode.Next := result ;\n      end;\nend;\n\n","human_summarization":"define a method to insert an element into a singly-linked list after a specified element. This method is then used to insert an element 'C' into a list containing elements 'A' and 'B', placing 'C' after 'A'. The code is designed to be compatible with Turbo Pascal, with considerations for its lack of C++-style comments and the Try Except block. The data pointer is kept generic to accommodate any structure or variable.","id":3986}
    {"lang_cluster":"Delphi","source_code":"\nprogram EthiopianMultiplication;\n  {$IFDEF FPC}\n    {$MODE DELPHI}\n  {$ENDIF}\n  function Double(Number: Integer): Integer;\n  begin\n    Result := Number * 2\n  end;\n\n  function Halve(Number: Integer): Integer;\n  begin\n    Result := Number div 2\n  end;\n\n  function Even(Number: Integer): Boolean;\n  begin\n    Result := Number mod 2 = 0\n  end;\n\n  function Ethiopian(NumberA, NumberB: Integer): Integer;\n  begin\n    Result := 0;\n    while NumberA >= 1 do\n\tbegin\n\t  if not Even(NumberA) then\n\t    Result := Result + NumberB;\n\t  NumberA := Halve(NumberA);\n\t  NumberB := Double(NumberB)\n\tend\n  end;\n\nbegin\n  Write(Ethiopian(17, 34))\nend.\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using only addition, doubling, and halving. The multiplication process involves creating a table with two columns, repeatedly halving the first number and doubling the second number, discarding rows where the first number is even, and summing the remaining values in the second column to get the product.","id":3987}
    {"lang_cluster":"Delphi","source_code":"\nprogram Factorial1;\n\n{$APPTYPE CONSOLE}\n\nfunction FactorialIterative(aNumber: Integer): Int64;\nvar\n  i: Integer;\nbegin\n  Result\u00a0:= 1;\n  for i\u00a0:= 1 to aNumber do\n    Result\u00a0:= i * Result;\nend;\n\nbegin\n  Writeln('5! = ', FactorialIterative(5));\nend.\nprogram Factorial2;\n\n{$APPTYPE CONSOLE}\n\nfunction FactorialRecursive(aNumber: Integer): Int64;\nbegin\n  if aNumber < 1 then\n    Result\u00a0:= 1\n  else\n    Result\u00a0:= aNumber * FactorialRecursive(aNumber - 1);\nend;\n\nbegin\n  Writeln('5! = ', FactorialRecursive(5));\nend.\nTail program Factorial3;\n\n{$APPTYPE CONSOLE}\n\nfunction FactorialTailRecursive(aNumber: Integer): Int64;\n\n  function FactorialHelper(aNumber: Integer; aAccumulator: Int64): Int64;\n  begin\n    if aNumber = 0 then\n      Result\u00a0:= aAccumulator\n    else\n      Result\u00a0:= FactorialHelper(aNumber - 1, aNumber * aAccumulator);\n    end;\n\nbegin\n  if aNumber < 1 then\n    Result\u00a0:= 1\n  else\n    Result\u00a0:= FactorialHelper(aNumber, 1);\nend;\n\nbegin\n  Writeln('5! = ', FactorialTailRecursive(5));\nend.\n","human_summarization":"The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.","id":3988}
    {"lang_cluster":"Delphi","source_code":"\nProgram BullCow;\n\n{$mode objFPC}\n\nuses Math, SysUtils;\n\ntype\n   TFourDigit = array[1..4] of integer;\n\nProcedure WriteFourDigit(fd: TFourDigit);\n{ Write out a TFourDigit with no line break following. }\nvar\n   i: integer;\nbegin\n   for i := 1 to 4 do\n   begin\n      Write(fd[i]);\n   end;\nend;\n   \nFunction WellFormed(Tentative: TFourDigit): Boolean;\n{ Does the TFourDigit avoid repeating digits? }\nvar\n   current, check: integer;\nbegin\n\n   Result := True;\n   \n   for current := 1 to 4 do\n   begin\n      for check := current + 1 to 4 do\n      begin\n         if Tentative[check] = Tentative[current] then\n         begin\n            Result := False;\n         end;\n      end;\n   end;\n   \nend;\n\nFunction MakeNumber(): TFourDigit;\n{ Make a random TFourDigit, keeping trying until it is well-formed. }\nvar\n   i: integer;\nbegin\n   for i := 1 to 4 do\n   begin\n      Result[i] := RandomRange(1, 9);\n   end;\n   if not WellFormed(Result) then\n   begin\n      Result := MakeNumber();\n   end;\nend;\n\nFunction StrToFourDigit(s: string): TFourDigit;\n{ Convert an (input) string to a TFourDigit. }\nvar\n   i: integer;\nbegin\n   for i := 1 to Length(s) do\n   begin\n      StrToFourDigit[i] := StrToInt(s[i]);\n   end;\nend;\n\nFunction Wins(Num, Guess: TFourDigit): Boolean;\n{ Does the guess win? }\nvar\n   i: integer;\nbegin\n   Result := True;\n   for i := 1 to 4 do\n   begin\n      if Num[i] <> Guess[i] then\n      begin\n         Result := False;\n         Exit;\n      end;\n   end;\nend;\n\nFunction GuessScore(Num, Guess: TFourDigit): string;\n{ Represent the score of the current guess as a string. }\nvar\n   i, j, bulls, cows: integer;\nbegin\n\n   bulls := 0;\n   cows := 0;\n\n   { Count the cows and bulls. }\n   for i := 1 to 4 do\n   begin\n      for j := 1 to 4 do\n      begin\n         if  (Num[i] = Guess[j]) then\n         begin\n            { If the indices are the same, that would be a bull. }\n            if (i = j) then\n            begin\n               bulls := bulls + 1;\n            end\n            else\n            begin\n               cows := cows + 1;\n            end;\n         end;\n      end;\n   end;\n\n   { Format the result as a sentence. }\n   Result := IntToStr(bulls) + ' bulls, ' + IntToStr(cows) + ' cows.';\n   \nend;\n\nFunction GetGuess(): TFourDigit;\n{ Get a well-formed user-supplied TFourDigit guess. }\nvar\n   input: string;\nbegin\n\n   WriteLn('Enter a guess:');\n   ReadLn(input);\n\n   { Must be 4 digits. }\n   if Length(input) = 4 then\n   begin\n   \n      Result := StrToFourDigit(input);\n      \n      if not WellFormed(Result) then\n      begin\n         WriteLn('Four unique digits, please.');\n         Result := GetGuess();\n      end;\n      \n   end\n   else\n   begin\n      WriteLn('Please guess a four-digit number.');\n      Result := GetGuess();\n   end;\n   \nend;\n   \nvar\n   Num, Guess: TFourDigit;\n   Turns: integer;\nbegin\n\n   { Initialize the randymnity. }\n   Randomize();\n\n   { Make the secred number. }\n   Num := MakeNumber();\n\n   WriteLn('I have a secret number. Guess it!');\n\n   Turns := 0;\n\n   { Guess until the user gets it. }\n   While True do\n   begin\n\n      Guess := GetGuess();\n\n      { Count each guess as a turn. }\n      Turns := Turns + 1;\n\n      { If the user won, tell them and ditch. }\n      if Wins(Num, Guess) then\n      begin\n         WriteLn('You won in ' + IntToStr(Turns) + ' tries.');\n         Write('The number was ');\n         WriteFourDigit(Num);\n         WriteLn('!');\n         Exit;\n      end\n      else { Otherwise, score it and get a new guess. }\n      begin\n         WriteLn(GuessScore(Num, Guess));\n      end;\n      \n   end;\n      \nend.\n","human_summarization":"generate a unique four-digit number, accept user guesses, validate the format of the guesses, calculate scores based on the number of correct digits in the correct and incorrect positions, and terminate the program if the guess matches the generated number.","id":3989}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram Randoms;\n\n{$APPTYPE CONSOLE}\n\nuses\n  Math;\n\nvar\n  Values: array[0..999] of Double;\n  I: Integer;\n\nbegin\n\/\/  Randomize;   Commented to obtain reproducible results\n  for I:= Low(Values) to High(Values) do\n    Values[I]:= RandG(1.0, 0.5);  \/\/ Mean = 1.0, StdDev = 0.5\n  Writeln('Mean          = ', Mean(Values):6:4);\n  Writeln('Std Deviation = ', StdDev(Values):6:4);\n  Readln;\nend.\n\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5 using Delphi's RandG function and Marsaglia-Bray algorithm.","id":3990}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Lazarus\nprogram Project1;\n\n{$APPTYPE CONSOLE}\n\ntype\n  doublearray = array of Double;\n\nfunction DotProduct(const A, B : doublearray): Double;\nvar\nI: integer;\nbegin\n  assert (Length(A) = Length(B), 'Input arrays must be the same length');\n  Result := 0;\n  for I := 0 to Length(A) - 1 do\n    Result := Result + (A[I] * B[I]);\nend;\n\nvar\n  x,y: doublearray;\nbegin\n  SetLength(x, 3);\n  SetLength(y, 3);\n  x[0] := 1; x[1] := 3; x[2] := -5;\n  y[0] := 4; y[1] :=-2; y[2] := -1;\n  WriteLn(DotProduct(x,y));\n  ReadLn;\nend.\n\n\n","human_summarization":"The code implements a function to calculate the dot product of two vectors. The vectors can be of arbitrary length, but must be the same length for the operation. The dot product is computed by multiplying corresponding terms from each vector and summing the products. The function also handles the case where arrays cannot be declared in procedure headings, as in Delphi, by declaring them beforehand.","id":3991}
    {"lang_cluster":"Delphi","source_code":"\nprogram InputLoop;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils, Classes;\n\nvar\n  lReader: TStreamReader; \/\/ Introduced in Delphi XE\nbegin\n  lReader := TStreamReader.Create('input.txt', TEncoding.Default);\n  try\n    while lReader.Peek >= 0 do\n      Writeln(lReader.ReadLine);\n  finally\n    lReader.Free;\n  end;\nend.\n\n","human_summarization":"\"Continuously read words or lines from a text stream until there is no more data available.\"","id":3992}
    {"lang_cluster":"Delphi","source_code":"\nlblDateTime.Caption := FormatDateTime('dd mmmm yyyy hh:mm:ss', Now);\nThis populates a label with the date\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":3993}
    {"lang_cluster":"Delphi","source_code":"\nprogram Sedol;\n\n{$APPTYPE CONSOLE}\n\nuses\n  SysUtils;\n\n\nconst\n  SEDOL_CHR_COUNT = 6;\n  DIGITS = ['0'..'9'];\n  LETTERS = ['A'..'Z'];\n  VOWELS = ['A', 'E', 'I', 'O', 'U'];\n  ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS;\n  WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9);\n  LETTER_OFFSET = 9;\n\n\nfunction AddSedolCheckDigit(Sedol : string) : string;\nvar\n  iChr : integer;\n  Checksum : integer;\n  CheckDigit : char;\nbegin\n  if Sedol <> uppercase(Sedol) then\n    raise ERangeError.CreateFmt('%s contains lower case characters',[Sedol]);\n  if length(Sedol) <> SEDOL_CHR_COUNT then\n    raise ERangeError.CreateFmt('\"%s\" length is invalid. Should be 6 characters',[Sedol]);\n\n  Checksum := 0;\n  for iChr := 1 to SEDOL_CHR_COUNT do\n  begin\n\n    if Sedol[iChr] in Vowels then\n      raise ERangeError.CreateFmt('%s contains a vowel (%s) at chr %d',[Sedol, Sedol[iChr], iChr]);\n    if not (Sedol[iChr] in ACCEPTABLE_CHRS) then\n      raise ERangeError.CreateFmt('%s contains an invalid chr (%s) at position %d',[Sedol, Sedol[iChr], iChr]);\n\n    if Sedol[iChr] in DIGITS then\n      Checksum := Checksum + (ord(Sedol[iChr]) - ord('0')) * WEIGHTS[iChr]\n    else\n      Checksum := Checksum + (ord(Sedol[iChr]) - ord('A') + 1 + LETTER_OFFSET) * WEIGHTS[iChr];\n\n  end;\n\n  Checksum := (Checksum mod 10);\n  if Checksum <> 0 then\n    Checksum := 10 - Checksum;\n  CheckDigit := chr(CheckSum + ord('0'));\n\n  Result := Sedol + CheckDigit;\nend;\n\n\nprocedure Test(First6 : string);\nbegin\n  writeln(First6, ' becomes ', AddSedolCheckDigit(First6));\nend;\n\n\nbegin\n  try\n    Test('710889');\n    Test('B0YBKJ');\n    Test('406566');\n    Test('B0YBLH');\n    Test('228276');\n    Test('B0YBKL');\n    Test('557910');\n    Test('B0YBKR');\n    Test('585284');\n    Test('B0YBKT');\n    Test('B00030');\n  except\n    on E : Exception do\n      writeln(E.Message);\n  end;\n  readln;\nend.\n\n\n710889 becomes 7108899\nB0YBKJ becomes B0YBKJ7\n406566 becomes 4065663\nB0YBLH becomes B0YBLH2\n228276 becomes 2282765\nB0YBKL becomes B0YBKL9\n557910 becomes 5579107\nB0YBKR becomes B0YBKR5\n585284 becomes 5852842\nB0YBKT becomes B0YBKT7\nB00030 becomes B000300\n","human_summarization":"The code takes a list of 6-digit SEDOL numbers as input, calculates and appends the checksum digit to each SEDOL number, and outputs the updated SEDOL numbers. It also validates the input to ensure that it contains only valid characters for a SEDOL string.","id":3994}
    {"lang_cluster":"Delphi","source_code":"\nprogram DrawASphere;\n\n{$APPTYPE CONSOLE}\n\nuses\n  SysUtils,\n  Math;\n\ntype\n  TDouble3  = array[0..2] of Double;\n  TChar10 = array[0..9] of Char;\n\nvar\n  shades: TChar10 = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@');\n  light: TDouble3 = (30, 30, -50 );\n\n  procedure normalize(var v: TDouble3);\n  var\n    len: Double;\n  begin\n    len:= sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);\n    v[0] := v[0] \/ len;\n    v[1] := v[1] \/ len;\n    v[2] := v[2] \/ len;\n  end;\n\n  function dot(x, y: TDouble3): Double;\n  begin\n    Result:= x[0]*y[0] + x[1]*y[1] + x[2]*y[2];\n    Result:= IfThen(Result < 0, -Result, 0 );\n  end;\n\n  procedure drawSphere(R, k, ambient: Double);\n  var\n    vec: TDouble3;\n    x, y, b: Double;\n    i, j,\n    intensity: Integer;\n  begin\n    for i:= Floor(-R) to Ceil(R) do\n    begin\n      x := i + 0.5;\n      for j:= Floor(-2*R) to Ceil(2 * R) do\n      begin\n        y:= j \/ 2 + 0.5;\n        if(x * x + y * y <= R * R) then\n        begin\n          vec[0]:= x;\n          vec[1]:= y;\n          vec[2]:= sqrt(R * R - x * x - y * y);\n          normalize(vec);\n          b:= Power(dot(light, vec), k) + ambient;\n          intensity:= IfThen(b <= 0,\n                             Length(shades) - 2,\n                             Trunc(max( (1 - b) * (Length(shades) - 1), 0 )));\n          Write(shades[intensity]);\n        end\n        else\n          Write(' ');\n      end;\n      Writeln;\n    end;\n  end;\n\nbegin\n  normalize(light);\n  drawSphere(19, 4, 0.1);\n  drawSphere(10, 2, 0.4);\n  Readln;\nend.\n\n\n","human_summarization":"The code generates a graphical or ASCII art representation of a sphere, with either static or rotational projection. On Windows, if the sphere appears distorted, the console width can be increased to maintain roundness.","id":3995}
    {"lang_cluster":"Delphi","source_code":"\nProgram n_th;\n\nfunction Suffix(N: NativeInt):AnsiString;\nvar\n  res: AnsiString;\nbegin\n  res:= 'th';\n  case N mod 10 of\n  1:IF N mod 100 <> 11 then\n      res:= 'st';\n  2:IF N mod 100 <> 12 then\n      res:= 'nd';\n  3:IF N mod 100 <> 13 then\n      res:= 'rd';\n  else\n  end;\n  Suffix := res;\nend;\n\nprocedure Print_Images(loLim, HiLim: NativeInt);\nvar\n  i : NativeUint;\nbegin\n  for I := LoLim to HiLim do\n    write(i,Suffix(i),' ');\n  writeln;\nend;\n\nbegin\n   Print_Images(   0,   25);\n   Print_Images( 250,  265);\n   Print_Images(1000, 1025);\nend.\n","human_summarization":"The code is a function that takes an integer input greater than or equal to zero and returns a string of the number with an apostrophe and an ordinal suffix. The function is demonstrated with the integer ranges of 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes is optional.","id":3996}
    {"lang_cluster":"Delphi","source_code":"\nprogram StripCharacters;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils;\n\nfunction StripChars(const aSrc, aCharsToStrip: string): string;\nvar\n  c: Char;\nbegin\n  Result := aSrc;\n  for c in aCharsToStrip do\n    Result := StringReplace(Result, c, '', [rfReplaceAll, rfIgnoreCase]);\nend;\n\nconst\n  TEST_STRING = 'She was a soul stripper. She took my heart!';\nbegin\n  Writeln(TEST_STRING);\n  Writeln(StripChars(TEST_STRING, 'aei'));\nend.\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":3997}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nprogram String_preappend;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils;\n\ntype\n  TStringHelper = record helper for string\n    procedure Preappend(str: string);\n  end;\n\n{ TStringHelper }\n\nprocedure TStringHelper.Preappend(str: string);\nbegin\n  Self := str + self;\nend;\n\nbegin\n  var h: string;\n\n  \/\/ with + operator\n  h := 'World';\n  h := 'Hello ' + h;\n  writeln(h);\n\n  \/\/ with a function concat\n  h := 'World';\n  h := concat('Hello ', h);\n  writeln(h);\n\n  \/\/ with helper\n  h := 'World';\n  h.Preappend('Hello ');\n  writeln(h);\n  readln;\nend.\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":3998}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  Winapi.Windows\nLibrary:  System.SysUtils\nLibrary:  System.Classes\nLibrary:  Vcl.Graphicsprogram Dragon_curve;\n\n{$APPTYPE CONSOLE}\n\nuses\n  Winapi.Windows,\n  System.SysUtils,\n  System.Classes,\n  Vcl.Graphics;\n\ntype\n  TDragon = class\n  private\n    p: TColor;\n    _sin: TArray<double>;\n    _cos: TArray<double>;\n    s: double;\n    b: TBitmap;\n    FAsBitmap: TBitmap;\n    const\n      sep = 512;\n      depth = 14;\n    procedure Dragon(n, a, t: Integer; d, x, y: Double; var b: TBitmap);\n  public\n    constructor Create;\n    destructor Destroy; override;\n    property AsBitmap: TBitmap read b;\n  end;\n\n{ TDragon }\n\nprocedure TDragon.Dragon(n, a, t: Integer; d, x, y: Double; var b: TBitmap);\nbegin\n  if n <= 1 then\n  begin\n    with b.Canvas do\n    begin\n      Pen.Color := p;\n      MoveTo(Trunc(x + 0.5), Trunc(y + 0.5));\n      LineTo(Trunc(x + d * _cos[a] + 0.5), Trunc(y + d * _sin[a] + 0.5));\n      exit;\n    end;\n  end;\n\n  d := d * s;\n  var a1 := (a - t) and 7;\n  var a2 := (a + t) and 7;\n\n  dragon(n - 1, a1, 1, d, x, y, b);\n  dragon(n - 1, a2, -1, d, x + d * _cos[a1], y + d * _sin[a1], b);\nend;\n\nconstructor TDragon.Create;\nbegin\n  s := sqrt(2) \/ 2;\n  _sin := [0, s, 1, s, 0, -s, -1, -s];\n  _cos := [1.0, s, 0.0, -s, -1.0, -s, 0.0, s];\n  p := Rgb(64, 192, 96);\n  b := TBitmap.create;\n\n  var width := Trunc(sep * 11 \/ 6);\n  var height := Trunc(sep * 4 \/ 3);\n  b.SetSize(width, height);\n  with b.Canvas do\n  begin\n    Brush.Color := clWhite;\n    Pen.Width := 3;\n    FillRect(Rect(0, 0, width, height));\n  end;\n  dragon(14, 0, 1, sep, sep \/ 2, sep * 5 \/ 6, b);\nend;\n\ndestructor TDragon.Destroy;\nbegin\n  b.Free;\n  inherited;\nend;\n\nvar\n  Dragon: TDragon;\n\nbegin\n  Dragon := TDragon.Create;\n  Dragon.AsBitmap.SaveToFile('dragon.bmp');\n  Dragon.Free;\nend.\n\n","human_summarization":"generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.","id":3999}
    {"lang_cluster":"Delphi","source_code":"\nprogram GuessTheNumber;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils;\n\nvar\n  theDigit : String ;\n  theAnswer : String ;\n\nbegin\n  Randomize ;\n  theDigit := IntToStr(Random(9)+1) ;\n  while ( theAnswer <> theDigit ) do Begin\n    Writeln('Please enter a digit between 1 and 10' ) ;\n    Readln(theAnswer);\n  End ;\n  Writeln('Congratulations' ) ;\nend.\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":4000}
    {"lang_cluster":"Delphi","source_code":"\nprogram atoz;\n\nvar\n  ch : char;\n\nbegin\n  for ch in ['a'..'z'] do\n  begin\n    write(ch);\n  end;\nend.\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":4001}
    {"lang_cluster":"Delphi","source_code":"\nprogram BinaryDigit;\n{$APPTYPE CONSOLE}\nuses\n  sysutils;\n\nfunction IntToBinStr(AInt : LongWord) : string;\nbegin\n  Result := '';\n  repeat\n    Result := Chr(Ord('0')+(AInt and 1))+Result;\n    AInt := AInt div 2;\n  until (AInt = 0);\nend;\n\nBegin\n  writeln('   5: ',IntToBinStr(5));\n  writeln('  50: ',IntToBinStr(50));\n  writeln('9000: '+IntToBinStr(9000));\nend.\n\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":4002}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  Windows\nLibrary:  Messages\nLibrary:  SysUtils\n\nprogram Draw_a_pixel;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n  Windows,\n  Messages,\n  SysUtils;\n\nvar\n  Msg: TMSG;\n  LWndClass: TWndClass;\n  hMainHandle: HWND;\n\nprocedure Paint(Handle: hWnd); forward;\n\nprocedure ReleaseResources;\nbegin\n  PostQuitMessage(0);\nend;\n\nfunction WindowProc(hWnd, Msg: Longint; wParam: wParam; lParam: lParam): Longint; stdcall;\nbegin\n  case Msg of\n    WM_PAINT:\n      Paint(hWnd);\n    WM_DESTROY:\n      ReleaseResources;\n  end;\n  Result := DefWindowProc(hWnd, Msg, wParam, lParam);\nend;\n\n\nprocedure CreateWin(W, H: Integer);\nbegin\n  LWndClass.hInstance := hInstance;\n  with LWndClass do\n  begin\n    lpszClassName := 'OneRedPixel';\n    Style := CS_PARENTDC or CS_BYTEALIGNCLIENT;\n    hIcon := LoadIcon(hInstance, 'MAINICON');\n    lpfnWndProc := @WindowProc;\n    hbrBackground := COLOR_BTNFACE + 1;\n    hCursor := LoadCursor(0, IDC_ARROW);\n  end;\n\n  RegisterClass(LWndClass);\n  hMainHandle := CreateWindow(LWndClass.lpszClassName,\n    'Draw a red pixel on (100,100)', WS_CAPTION or WS_MINIMIZEBOX or WS_SYSMENU\n    or WS_VISIBLE, ((GetSystemMetrics(SM_CXSCREEN) - W) div 2), ((GetSystemMetrics\n    (SM_CYSCREEN) - H) div 2), W, H, 0, 0, hInstance, nil);\nend;\n\nprocedure ShowModal;\nbegin\n  while GetMessage(Msg, 0, 0, 0) do\n  begin\n    TranslateMessage(Msg);\n    DispatchMessage(Msg);\n  end;\nend;\n\nprocedure Paint(Handle: hWnd);\nvar\n  ps: PAINTSTRUCT;\n  Dc: HDC;\nbegin\n  Dc := BeginPaint(Handle, ps);\n\n  \/\/ Fill bg with white\n  FillRect(Dc, ps.rcPaint, CreateSolidBrush($FFFFFF));\n\n  \/\/ Do the magic\n  SetPixel(Dc, 100, 100, $FF);\n\n  EndPaint(Handle, ps);\nend;\n\nbegin\n  CreateWin(320, 240);\n  ShowModal();\nend.\n\n\n","human_summarization":"create a 320x240 window using Windows API and draw a red pixel at the position (100, 100).","id":4003}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  uSettings\n\nunit uSettings;\n\ninterface\n\nuses\n  System.SysUtils, System.IoUtils, System.Generics.Collections, System.Variants;\n\ntype\n  TVariable = record\n    value: variant;\n    function ToString: string;\n    class operator Implicit(a: variant): TVariable;\n    class operator Implicit(a: TVariable): TArray<string>;\n    class operator Implicit(a: TVariable): string;\n  end;\n\n  TSettings = class(TDictionary<string, TVariable>)\n  private\n    function GetVariable(key: string): TVariable;\n    procedure SetVariable(key: string; const Value: TVariable);\n    function GetKey(line: string; var key: string; var value: variant; var\n      disable: boolean): boolean;\n    function GetAllKeys: TList<string>;\n  public\n    procedure LoadFromFile(Filename: TfileName);\n    procedure SaveToFile(Filename: TfileName);\n    property Variable[key: string]: TVariable read GetVariable write SetVariable; default;\n  end;\n\nimplementation\n\n{ TVariable }\n\nclass operator TVariable.Implicit(a: variant): TVariable;\nbegin\n  Result.value := a;\nend;\n\nclass operator TVariable.Implicit(a: TVariable): TArray<string>;\nbegin\n  if VarIsType(a.value, varArray or varOleStr) then\n    Result := a.value\n  else\n    raise Exception.Create('Error: can''t convert this type data in array');\nend;\n\nclass operator TVariable.Implicit(a: TVariable): string;\nbegin\n  Result := a.ToString;\nend;\n\nfunction TVariable.ToString: string;\nvar\n  arr: TArray<string>;\nbegin\n  if VarIsType(value, varArray or varOleStr) then\n  begin\n    arr := value;\n    Result := string.Join(', ', arr).Trim;\n  end\n  else\n    Result := value;\n  Result := Result.Trim;\nend;\n\n{ TSettings }\n\nfunction TSettings.GetAllKeys: TList<string>;\nvar\n  key: string;\nbegin\n  Result := TList<string>.Create;\n  for key in Keys do\n    Result.Add(key);\nend;\n\nfunction TSettings.GetKey(line: string; var key: string; var value: variant; var\n  disable: boolean): boolean;\nvar\n  line_: string;\n  j: integer;\nbegin\n  line_ := line.Trim;\n  Result := not (line_.IsEmpty or (line_[1] = '#'));\n  if not Result then\n    exit;\n\n  disable := (line_[1] = ';');\n  if disable then\n    delete(line_, 1, 1);\n\n  var data := line_.Split([' '], TStringSplitOptions.ExcludeEmpty);\n  case length(data) of\n    1: \/\/Boolean\n      begin\n        key := data[0].ToUpper;\n        value := True;\n      end;\n\n    2: \/\/Single String\n      begin\n        key := data[0].ToUpper;\n        value := data[1].Trim;\n      end;\n\n  else \/\/ Mult String value or Array of value\n    begin\n      key := data[0];\n      delete(line_, 1, key.Length);\n      if line_.IndexOf(',') > -1 then\n      begin\n        data := line_.Trim.Split([','], TStringSplitOptions.ExcludeEmpty);\n        for j := 0 to High(data) do\n          data[j] := data[j].Trim;\n        value := data;\n      end\n      else\n        value := line_.Trim;\n    end;\n  end;\n  Result := true;\nend;\n\nfunction TSettings.GetVariable(key: string): TVariable;\nbegin\n  key := key.Trim.ToUpper;\n  if not ContainsKey(key) then\n    add(key, false);\n\n  result := Items[key];\nend;\n\nprocedure TSettings.LoadFromFile(Filename: TfileName);\nvar\n  key, line: string;\n  value: variant;\n  disabled: boolean;\n  Lines: TArray<string>;\nbegin\n  if not FileExists(Filename) then\n    exit;\n\n  Clear;\n  Lines := TFile.ReadAllLines(Filename);\n  for line in Lines do\n  begin\n    if GetKey(line, key, value, disabled) then\n    begin\n      if disabled then\n        AddOrSetValue(key, False)\n      else\n        AddOrSetValue(key, value)\n    end;\n  end;\nend;\n\nprocedure TSettings.SaveToFile(Filename: TfileName);\nvar\n  key, line: string;\n  value: variant;\n  disabled: boolean;\n  Lines: TArray<string>;\n  i: Integer;\n  All_kyes: TList<string>;\nbegin\n  All_kyes := GetAllKeys();\n  SetLength(Lines, 0);\n  i := 0;\n  if FileExists(Filename) then\n  begin\n    Lines := TFile.ReadAllLines(Filename);\n    for i := high(Lines) downto 0 do\n    begin\n      if GetKey(Lines[i], key, value, disabled) then\n      begin\n        if not ContainsKey(key) then\n        begin\n          Lines[i] := '; ' + Lines[i];\n          Continue;\n        end;\n\n        All_kyes.Remove(key);\n\n        disabled := VarIsType(Variable[key].value, varBoolean) and (Variable[key].value\n          = false);\n        if not disabled then\n        begin\n          if VarIsType(Variable[key].value, varBoolean) then\n            Lines[i] := key\n          else\n            Lines[i] := format('%s %s', [key, Variable[key].ToString])\n        end\n        else\n          Lines[i] := '; ' + key;\n      end;\n    end;\n\n  end;\n\n  \/\/ new keys\n  i := high(Lines) + 1;\n  SetLength(Lines, Length(Lines) + All_kyes.Count);\n  for key in All_kyes do\n  begin\n    Lines[i] := format('%s %s', [key, Variable[key].ToString]);\n    inc(i);\n  end;\n\n  Tfile.WriteAllLines(Filename, Lines);\n\n  All_kyes.Free;\nend;\n\nprocedure TSettings.SetVariable(key: string; const Value: TVariable);\nbegin\n  AddOrSetValue(key.Trim.ToUpper, Value);\nend;\nend.\n\n\nprogram ReadAConfigFile;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils,\n  uSettings;\n\nconst\n  FileName = 'Config.txt';\n\nvar\n  Settings: TSettings;\n\nprocedure show(key: string; value: string);\nbegin\n  writeln(format('%14s = %s', [key, value]));\nend;\n\nbegin\n  Settings := TSettings.Create;\n  Settings.LoadFromFile(FileName);\n\n  for var k in Settings.Keys do\n    show(k, Settings[k]);\n\n  Settings.Free;\n  Readln;\nend.\n\n\n","human_summarization":"The code reads a standard configuration file, ignores lines beginning with a hash or semicolon, and blank lines. It sets variables based on the configuration parameters: fullname, favouritefruit, needspeeling, seedsremoved, and otherfamily. The 'otherfamily' parameter can have multiple values, stored in an array. The code also handles optional equals signs separating parameter data from the option name, and ignores leading and trailing whitespace around parameter names and data fields. The configuration option names are case insensitive, while the parameter data is case sensitive.","id":4004}
    {"lang_cluster":"Delphi","source_code":"\nprogram HaversineDemo;\nuses Math;\n\nfunction HaversineDist(th1, ph1, th2, ph2:double):double;\nconst diameter = 2 * 6372.8;\nvar   dx, dy, dz:double;\nbegin\n  ph1    := degtorad(ph1 - ph2);\n  th1    := degtorad(th1);\n  th2    := degtorad(th2);\n\n  dz     := sin(th1) - sin(th2);\n  dx     := cos(ph1) * cos(th1) - cos(th2);\n  dy     := sin(ph1) * cos(th1);\n  Result := arcsin(sqrt(sqr(dx) + sqr(dy) + sqr(dz)) \/ 2) * diameter;\nend;\n\nbegin\n  Writeln('Haversine distance: ', HaversineDist(36.12, -86.67, 33.94, -118.4):7:2, ' km.');\nend.\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":4005}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram HTTP;\n\n{$APPTYPE CONSOLE}\n\n{$DEFINE DEBUG}\n\nuses\n  Classes,\n  httpsend; \/\/ Synapse httpsend class\n\nvar\n  Response: TStrings;\n  HTTPObj: THTTPSend;\n\nbegin\n  HTTPObj := THTTPSend.Create;\n  try\n    { Stringlist object to capture HTML returned\n      from URL }\n    Response := TStringList.Create;\n    try\n      if HTTPObj.HTTPMethod('GET','http:\/\/www.mgis.uk.com') then\n        begin\n          { Load HTTP Document into Stringlist }\n          Response.LoadFromStream(HTTPObj.Document);\n          { Write the response to the console window }\n          Writeln(Response.Text);\n        end\n        else\n        Writeln('Error retrieving data');\n\n    finally\n      Response.Free;\n    end;\n\n  finally\n    HTTPObj.Free;\n  end;\n\n  \/\/ Keep console window open\n  Readln;\n\nend.\n\n\nprogram ShowHTTP;\n\n{$APPTYPE CONSOLE}\n\nuses IdHttp;\n\nvar\n  s: string;\n  lHTTP: TIdHTTP;\nbegin\n  lHTTP := TIdHTTP.Create(nil);\n  try\n    lHTTP.HandleRedirects := True;\n    s := lHTTP.Get('http:\/\/www.rosettacode.org');\n    Writeln(s);\n  finally\n    lHTTP.Free;\n  end;\nend.\n\n","human_summarization":"print the content of a specified URL to the console using either the Synapse TCP\/IP library or Indy. Note that this does not cover HTTPS requests.","id":4006}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\n{Test data arrays}\n\nconst Num1: array [0..10] of byte = (4,9,9,2,7,3,9,8,7,1,6);\nconst Num2: array [0..10] of byte = (4,9,9,2,7,3,9,8,7,1,7);\nconst Num3: array [0..15] of byte = (1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8);\nconst Num4: array [0..15] of byte = (1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,0);\n\n{Simplifies cases where we have to sum a two digit number}\n\nconst DigitSum: array [0..18] of byte = (0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9);\n\nfunction ValidateCreditCard(CardNum: array of byte): boolean;\n{Validate a Credit Card number}\nvar I,J,Len,Sum,Sum1,Sum2: integer;\nvar Rev: array of byte;\nbegin\nSum1:=0; Sum2:=0;\nLen:=High(CardNum);\nfor I:=Len downto 0 do\n if ((I-Len) and 1)=0 then Sum1:=Sum1 + CardNum[I]\n else Sum2:=Sum2 + DigitSum[CardNum[I]*2];\nSum:=Sum1+Sum2;\nResult:=(Sum mod 10)=0;\nend;\n\n\nfunction CardNumberToStr(CardNum: array of byte): string;\n{Convert card number to a string}\nvar I: integer;\nbegin\nResult:='';\nfor I:=0 to High(CardNum) do\nResult:=Result+IntToStr(CardNum[I]);\nend;\n\n\nprocedure TestDisplayNumber(Memo: TMemo; Num: array of byte);\n{Test a credit card number and display results}\nvar S: string;\nbegin\nS:=CardNumberToStr(Num);\nif ValidateCreditCard(Num) then S:=S+': Valid'\nelse S:=S+': Not Valid';\nMemo.Lines.Add(S);\nend;\n\n\nprocedure TestCreditCardNums(Memo: TMemo);\n{Test all credit card numbers}\nbegin\nTestDisplayNumber(Memo,Num1);\nTestDisplayNumber(Memo,Num2);\nTestDisplayNumber(Memo,Num3);\nTestDisplayNumber(Memo,Num4);\nend;\n\n\n","human_summarization":"\"Implements the Luhn test to validate credit card numbers. The function reverses the input number, calculates the sum of odd and even digits (with even digits being doubled and, if the result is a two-digit number, summed again), and checks if the total sum ends in zero. The function is used to validate a set of given numbers. The process uses an array to handle two-digit results from the doubling operation and avoids reversing the number by traversing the array backwards.\"","id":4007}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,Classes,StdCtrls,ExtCtrl\n\ntype TIntArray = array of integer;\n\nprocedure GetJosephusSequence(N,K: integer; var IA: TIntArray);\n{Analyze sequence of deleting every K of N numbers}\n{Retrun result in Integer Array}\nvar LS: TList;\nvar I,J: integer;\nbegin\nSetLength(IA,N);\nLS:=TList.Create;\ntry\n{Store number 0..N-1 in list}\nfor I:=0 to N-1 do LS.Add(Pointer(I));\nJ:=0;\nfor I:=0 to N-1 do\n\tbegin\n\t{Advance J by K-1 because iterms are deleted}\n\t{And wrapping around if it J exceed the count }\n        J:=(J+K-1) mod LS.Count;\n        {Caption the sequence}\n        IA[I]:=Integer(LS[J]);\n        {Delete (kill) one item}\n        LS.Delete(J);\n\tend;\nfinally LS.Free; end;\nend;\n\nprocedure ShowJosephusProblem(Memo: TMemo; N,K: integer);\n{Analyze and display one Josephus Problem}\nvar IA: TIntArray;\nvar I: integer;\nvar S: string;\nconst CRLF = #$0D#$0A;\nbegin\nGetJosephusSequence(N,K,IA);\nS:='';\nfor I:=0 to High(IA) do\n\tbegin\n\tif I>0 then S:=S+',';\n\tif (I mod 12)=11 then S:=S+CRLF+'           ';\n\tS:=S+IntToStr(IA[I]);\n\tend;\nMemo.Lines.Add('N='+IntToStr(N)+' K='+IntToStr(K));\nMemo.Lines.Add('Sequence: ['+S+']');\nMemo.Lines.Add('Survivor: '+IntToStr(IA[High(IA)]));\nMemo.Lines.Add('');\nend;\n\nprocedure TestJosephusProblem(Memo: TMemo);\n{Test suite of Josephus Problems}\nbegin\nShowJosephusProblem(Memo,5,2);\nShowJosephusProblem(Memo,41,3);\nend;\n\n\n","human_summarization":"The code implements the Josephus problem, a mathematical puzzle where n prisoners are sequentially numbered and every k-th prisoner is executed until only one remains. The code determines the final survivor given any n and k. It also provides a way to calculate the position of any prisoner in the killing sequence. The code uses a standard Delphi TList to hold and delete numbers as it processes the data.","id":4008}
    {"lang_cluster":"Delphi","source_code":"\n\nfunction RepeatString(const s: string; count: cardinal): string;\nvar\n  i: Integer;\nbegin\n  for i := 1 to count do\n    Result := Result + s;\nend;\n\nWriteln(RepeatString('ha',5));\n\n\nWriteln( StringOfChar('a',5) );\n\n\nfunction RepeatStr(const s: string; i: Cardinal): string;\nbegin\n  if i = 0 then\n    result := ''\n  else\n   result := s + RepeatStr(s, i-1)\nend;\n\n\nStrUtils.DupeString\n\n","human_summarization":"Code summarization: The code repeats a given string or character a specified number of times, demonstrating both a general method and a more efficient method for single characters. It also includes a recursion method and a built-in RTL function.","id":4009}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  System.RegularExpressions\n\nprogram Regular_expressions;\n\n{$APPTYPE CONSOLE}\n{$R *.res}\n\nuses\n  System.SysUtils,\n  System.RegularExpressions;\n\nconst\n  CPP_IF = '\\s*if\\s*\\(\\s*(?<COND>.*)\\s*\\)\\s*\\{\\s*return\\s+(?<RETURN>.+);\\s*\\}';\n  PASCAL_IF = 'If ${COND} then result:= ${RETURN};';\n\nvar\n  RegularExpression: TRegEx;\n  str: string;\n\nbegin\n  str := ' if ( a < 0 ) { return -a; }';\n\n  Writeln('Expression: '#10#10, str);\n\n  if RegularExpression.Create(CPP_IF).IsMatch(str) then\n  begin\n    Writeln(#10'   Is a single If in Cpp:'#10);\n\n    Writeln('Translate to Pascal:'#10);\n    str := RegularExpression.Create(CPP_IF).Replace(str, PASCAL_IF);\n    Writeln(str);\n  end;\n  readln;\nend.\n\n\n","human_summarization":"\"Code matches a string with a regular expression and substitutes part of the string using the same regular expression, specifically to translate a line of code from C++ to Pascal.\"","id":4010}
    {"lang_cluster":"Delphi","source_code":"\nprogram IntegerArithmetic;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils, Math;\n\nvar\n  a, b: Integer;\nbegin\n  a := StrToInt(ParamStr(1));\n  b := StrToInt(ParamStr(2));\n\n  WriteLn(Format('%d + %d = %d', [a, b, a + b]));\n  WriteLn(Format('%d - %d = %d', [a, b, a - b]));\n  WriteLn(Format('%d * %d = %d', [a, b, a * b]));\n  WriteLn(Format('%d \/ %d = %d', [a, b, a div b])); \/\/ rounds towards 0\n  WriteLn(Format('%d\u00a0%% %d = %d', [a, b, a mod b])); \/\/ matches sign of the first operand\n  WriteLn(Format('%d ^ %d = %d', [a, b, Trunc(Power(a, b))]));\nend.\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":4011}
    {"lang_cluster":"Delphi","source_code":"\nprogram OccurrencesOfASubstring;\n\n{$APPTYPE CONSOLE}\n\nuses StrUtils;\n\nfunction CountSubstring(const aString, aSubstring: string): Integer;\nvar\n  lPosition: Integer;\nbegin\n  Result := 0;\n  lPosition := PosEx(aSubstring, aString);\n  while lPosition <> 0 do\n  begin\n    Inc(Result);\n    lPosition := PosEx(aSubstring, aString, lPosition + Length(aSubstring));\n  end;\nend;\n\nbegin\n  Writeln(CountSubstring('the three truths', 'th'));\n  Writeln(CountSubstring('ababababab', 'abab'));\nend.\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":4012}
    {"lang_cluster":"Delphi","source_code":"\nprogram Hanoi;\ntype\n  TPole = (tpLeft, tpCenter, tpRight);\nconst\n  strPole:array[TPole] of string[6]=('left','center','right');\n\n procedure MoveStack (const Ndisks : integer; const Origin,Destination,Auxiliary:TPole);\n begin\n  if Ndisks >0 then begin\n     MoveStack(Ndisks - 1, Origin,Auxiliary, Destination );\n     Writeln('Move disk ',Ndisks ,' from ',strPole[Origin],' to ',strPole[Destination]);\n     MoveStack(Ndisks - 1, Auxiliary, Destination, origin);\n  end;\n end;\n\nbegin\n MoveStack(4,tpLeft,tpCenter,tpRight);\nend.\n","human_summarization":"implement a recursive solution for the Towers of Hanoi problem.","id":4013}
    {"lang_cluster":"Delphi","source_code":"\nprogram Binomial;\n\n{$APPTYPE CONSOLE}\n\nfunction BinomialCoff(N, K: Cardinal): Cardinal;\nvar\n  L: Cardinal;\n\nbegin\n  if N < K then\n    Result:= 0      \/\/ Error\n  else begin\n    if K > N - K then\n      K:= N - K;    \/\/ Optimization\n    Result:= 1;\n    L:= 0;\n    while L < K do begin\n      Result:= Result * (N - L);\n      Inc(L);\n      Result:= Result div L;\n    end;\n  end;\nend;\n\nbegin\n  Writeln('C(5,3) is ', BinomialCoff(5, 3));\n  ReadLn;\nend.\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":4014}
    {"lang_cluster":"Delphi","source_code":"\nProcedure ShellSort(var buf:Array of Integer);\nconst\n  gaps:array[0..7] of Integer = (701, 301, 132, 57, 23, 10, 4, 1);\n\nvar\n  whichGap, i, j, n, gap, temp : Integer;\n\nbegin\n  n := high(buf);\n  for whichGap := 0 to high(gaps) do begin\n    gap := gaps[whichGap];\n    for i := gap to n do begin\n      temp := buf[i];\n\n      j := i;\n      while ( (j >= gap ) and ( (buf[j-gap] > dt) ) do begin\n        buf[j] := buf[j-gap];\n        dec(j, gap);\n      end;\n      buf[j] := temp;\n    end;\n  end;\nend;\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":4015}
    {"lang_cluster":"Delphi","source_code":"\nprogram BtmAndPpm;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n  System.SysUtils,\n  System.Classes,\n  Winapi.Windows,\n  Vcl.Graphics;\n\ntype\n  TBitmapHelper = class helper for TBitmap\n  private\n  public\n    procedure SaveAsPPM(FileName: TFileName; useGrayScale: Boolean = False);\n    procedure LoadFromPPM(FileName: TFileName; useGrayScale: Boolean = False);\n  end;\n\nfunction ColorToGray(Color: TColor): TColor;\nvar\n  L: Byte;\nbegin\n  L := round(0.2126 * GetRValue(Color) + 0.7152 * GetGValue(Color) + 0.0722 *\n    GetBValue(Color));\n  Result := RGB(L, L, L);\nend;\n\n{ TBitmapHelper }\n\nprocedure TBitmapHelper.SaveAsPPM(FileName: TFileName; useGrayScale: Boolean = False);\nvar\n  i, j, color: Integer;\n  Header: AnsiString;\n  ppm: TMemoryStream;\nbegin\n  ppm := TMemoryStream.Create;\n  try\n    Header := Format('P6'#10'%d %d'#10'255'#10, [Self.Width, Self.Height]);\n    writeln(Header);\n    ppm.Write(Tbytes(Header), Length(Header));\n\n    for i := 0 to Self.Height - 1 do\n      for j := 0 to Self.Width - 1 do\n      begin\n        if useGrayScale then\n          color := ColorToGray(ColorToRGB(Self.Canvas.Pixels[i, j]))\n        else\n          color := ColorToRGB(Self.Canvas.Pixels[i, j]);\n        ppm.Write(color, 3);\n      end;\n    ppm.SaveToFile(FileName);\n  finally\n    ppm.Free;\n  end;\nend;\n\nprocedure TBitmapHelper.LoadFromPPM(FileName: TFileName; useGrayScale: Boolean = False);\nvar\n  p: Integer;\n  ppm: TMemoryStream;\n  sW, sH: string;\n  temp: AnsiChar;\n  W, H: Integer;\n  Color: TColor;\n\n  function ReadChar: AnsiChar;\n  begin\n    ppm.Read(Result, 1);\n  end;\n\nbegin\n  ppm := TMemoryStream.Create;\n  ppm.LoadFromFile(FileName);\n  if ReadChar + ReadChar <> 'P6' then\n    exit;\n\n  repeat\n    temp := ReadChar;\n    if temp in ['0'..'9'] then\n      sW := sW + temp;\n  until temp = ' ';\n\n  repeat\n    temp := ReadChar;\n    if temp in ['0'..'9'] then\n      sH := sH + temp;\n  until temp = #10;\n\n  W := StrToInt(sW);\n  H := StrToInt(sH);\n\n  if ReadChar + ReadChar + ReadChar <> '255' then\n    exit;\n\n  ReadChar(); \/\/skip newLine\n\n  SetSize(W, H);\n  p := 0;\n  while ppm.Read(Color, 3) > 0 do\n  begin\n    if useGrayScale then\n      Color := ColorToGray(Color);\n    Canvas.Pixels[p mod W, p div W] := Color;\n    inc(p);\n  end;\n  ppm.Free;\nend;\n\nbegin\n  with TBitmap.Create do\n  begin\n    \/\/ Load bmp\n    LoadFromFile('Input.bmp');\n    \/\/ Save as ppm\n    SaveAsPPM('Output.ppm');\n\n    \/\/ Load as ppm and convert in grayscale\n    LoadFromPPM('Output.ppm', True);\n\n    \/\/ Save as bmp\n    SaveToFile('Output.bmp');\n\n    Free;\n  end;\nend.\n","human_summarization":"extend the data storage type to support grayscale images, convert a color image to a grayscale image and vice versa using the CIE recommended formula for luminance. The code also ensures that rounding errors in floating-point arithmetic do not cause run-time problems or distorted results.","id":4016}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  Winapi.Windows\nLibrary:  System.SysUtils\nLibrary:  System.Classes\nLibrary:  Vcl.Controls\nLibrary:  Vcl.Forms\nLibrary:  Vcl.StdCtrls\nLibrary:  Vcl.ExtCtrls\nunit Main;\n\ninterface\n\nuses\n  Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms,\n  Vcl.StdCtrls, Vcl.ExtCtrls;\n\ntype\n  TForm1 = class(TForm)\n    lblAniText: TLabel;\n    tmrAniFrame: TTimer;\n    procedure lblAniTextClick(Sender: TObject);\n    procedure tmrAniFrameTimer(Sender: TObject);\n  end;\n\nvar\n  Form1: TForm1;\n  Reverse: boolean = false;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TForm1.lblAniTextClick(Sender: TObject);\nbegin\n  Reverse := not Reverse;\nend;\n\nfunction Shift(text: string; direction: boolean): string;\nbegin\n  if direction then\n    result := text[text.Length] + text.Substring(0, text.Length - 1)\n  else\n    result := text.Substring(1, text.Length) + text[1];\nend;\n\nprocedure TForm1.tmrAniFrameTimer(Sender: TObject);\nbegin\n  with lblAniText do\n    Caption := Shift(Caption, Reverse);\nend;\nend.\n\n\nobject Form1: TForm1\n  ClientHeight = 132\n  ClientWidth = 621\n  object lblAniText: TLabel\n    Align = alClient\n    Alignment = taCenter\n    Caption = 'Hello World! '\n    Font.Height = -96\n    OnClick = lblAniTextClick\n  end\n  object tmrAniFrame: TTimer\n    Interval = 200\n    OnTimer = tmrAniFrameTimer\n  end\nend\n\n","human_summarization":"\"Creates a GUI window displaying a rotating \"Hello World!\" text. The rotation direction reverses upon user click.\"","id":4017}
    {"lang_cluster":"Delphi","source_code":"\nprogram Loop;\n\n{$APPTYPE CONSOLE}\n\nvar\n  I: Integer;\n\nbegin\n  I:= 0;\n  repeat\n    Inc(I);\n    Write(I:2);\n  until I mod 6 = 0;\n  Writeln;\n  Readln;\nend.\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":4018}
    {"lang_cluster":"Delphi","source_code":"\nconst \n  s = 'abcdef';\nbegin\n  writeln (length(s))\nend.\n","human_summarization":"The code calculates the character and byte length of a string, correctly handling encodings like UTF-8 and Unicode code points. It also correctly handles non-BMP code points. The code provides the actual character counts in code points, not in code unit counts. It can also provide the string length in graphemes if the language supports it.","id":4019}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  Winapi.WinCrypt[[1]]\nprogram Random_number_generator;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils,\n  Winapi.WinCrypt;\n\nvar\n  hCryptProv: NativeUInt;\n  i: Byte;\n  UserName: PChar;\n\nfunction Random: UInt64;\nvar\n  pbData: array[0..7] of byte;\n  i: integer;\nbegin\n  if not CryptGenRandom(hCryptProv, 8, @pbData[0]) then\n    exit(0);\n  Result := 0;\n  for i := 0 to 7 do\n    Result := Result + (pbData[i] shl (8 * i));\nend;\n\nprocedure Randomize;\nbegin\n  CryptAcquireContext(hCryptProv, UserName, nil, PROV_RSA_FULL, 0);\nend;\n\nbegin\n  Randomize;\n  for i := 0 to 9 do\n    Writeln(Random);\n  Readln;\nend.\n\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using a system's built-in mechanism, not relying solely on a software algorithm like \/dev\/urandom devices in Unix.","id":4020}
    {"lang_cluster":"Delphi","source_code":"\nprogram TopAndTail;\n\n{$APPTYPE CONSOLE}\n\nconst\n  TEST_STRING = '1234567890';\nbegin\n  Writeln(TEST_STRING);                                    \/\/ full string\n  Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING)));      \/\/ first character removed\n  Writeln(Copy(TEST_STRING, 1, Length(TEST_STRING) - 1));  \/\/ last character removed\n  Writeln(Copy(TEST_STRING, 2, Length(TEST_STRING) - 2));  \/\/ first and last characters removed\n\n  Readln;\nend.\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":4021}
    {"lang_cluster":"Delphi","source_code":"\nprogram OneInstance;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils, Windows;\n\nvar\n  FMutex: THandle;\nbegin\n  FMutex := CreateMutex(nil, True, 'OneInstanceMutex');\n  if FMutex = 0 then\n    RaiseLastOSError\n  else\n  begin\n    try\n      if GetLastError = ERROR_ALREADY_EXISTS then\n        Writeln('Program already running.  Closing...')\n      else\n      begin\n        \/\/ do stuff ...\n        Readln;\n      end;\n    finally\n      CloseHandle(FMutex);\n    end;\n  end;\nend.\n\n","human_summarization":"\"Check if an application instance is already running, display a message if so, and terminate the program.\"","id":4022}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  Winapi.Windows\nLibrary:  System.SysUtils\nLibrary:  Vcl.Forms\nunit Main;\n\ninterface\n\nuses\n  Winapi.Windows, System.SysUtils, Vcl.Forms;\n\ntype\n  TForm1 = class(TForm)\n    procedure FormCreate(Sender: TObject);\n  end;\n\nvar\n  Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TForm1.FormCreate(Sender: TObject);\nvar\n w,h:Integer;\nbegin\n  w := Screen.Monitors[0].WorkareaRect.Width;\n  h := Screen.Monitors[0].WorkareaRect.Height;\n  Caption:= format('%d x %d',[w,h]);\n  SetBounds(0,0,w,h);\nend;\n\nend.\n\n\nobject Form1: TForm1\n  OnCreate = FormCreate\nend\n\n","human_summarization":"determine the maximum height and width of a window that can fit within the physical display area of the screen without scrolling, considering multiple monitors and tiling window managers.","id":4023}
    {"lang_cluster":"Delphi","source_code":"\n\ntype\n  TIntArray = array of Integer;\n\n  { TSudokuSolver }\n\n  TSudokuSolver = class\n  private\n    FGrid: TIntArray;\n\n    function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean;\n    function ToString: string; reintroduce;\n    function PlaceNumber(pos: Integer): Boolean;\n  public\n    constructor Create(s: string);\n\n    procedure Solve;\n  end;\n\nimplementation\n\nuses\n  Dialogs;\n\n{ TSudokuSolver }\n\nfunction TSudokuSolver.CheckValidity(val: Integer; x: Integer; y: Integer\n  ): Boolean;\nvar\n  i: Integer;\n  j: Integer;\n  StartX: Integer;\n  StartY: Integer;\nbegin\n  for i := 0 to 8 do\n  begin\n    if (FGrid[y * 9 + i] = val) or\n       (FGrid[i * 9 + x] = val) then\n    begin\n      Result := False;\n      Exit;\n    end;\n  end;\n  StartX := (x div 3) * 3;\n  StartY := (y div 3) * 3;\n  for i := StartY to Pred(StartY + 3) do\n  begin\n    for j := StartX to Pred(StartX + 3) do\n    begin\n      if FGrid[i * 9 + j] = val then\n      begin\n        Result := False;\n        Exit;\n      end;\n    end;\n  end;\n  Result := True;\nend;\n\nfunction TSudokuSolver.ToString: string;\nvar\n  sb: string;\n  i: Integer;\n  j: Integer;\n  c: char;\nbegin\n  sb := '';\n  for i := 0 to 8 do\n  begin\n    for j := 0 to 8 do\n    begin\n      c := (IntToStr(FGrid[i * 9 + j]) + '0')[1];\n      sb := sb + c + ' ';\n      if (j = 2) or (j = 5) then sb := sb + '| ';\n    end;\n    sb := sb + #13#10;\n    if (i = 2) or (i = 5) then\n      sb := sb + '-----+-----+-----' + #13#10;\n  end;\n  Result := sb;\nend;\n\nfunction TSudokuSolver.PlaceNumber(pos: Integer): Boolean;\nvar\n  n: Integer;\nbegin\n  Result := False;\n  if Pos = 81 then\n  begin\n    Result := True;\n    Exit;\n  end;\n  if FGrid[pos] > 0 then\n  begin\n    Result := PlaceNumber(Succ(pos));\n    Exit;\n  end;\n  for n := 1 to 9 do\n  begin\n    if CheckValidity(n, pos mod 9, pos div 9) then\n    begin\n      FGrid[pos] := n;\n      Result := PlaceNumber(Succ(pos));\n      if not Result then\n        FGrid[pos] := 0;\n    end;\n  end;\nend;\n\nconstructor TSudokuSolver.Create(s: string);\nvar\n  lcv: Cardinal;\nbegin\n  SetLength(FGrid, 81);\n  for lcv := 0 to Pred(Length(s)) do\n    FGrid[lcv] := StrToInt(s[Succ(lcv)]);\nend;\n\nprocedure TSudokuSolver.Solve;\nbegin\n  if not PlaceNumber(0) then\n    ShowMessage('Unsolvable')\n  else\n    ShowMessage('Solved!');\n  end;\nend;\n\n\nvar\n  SudokuSolver: TSudokuSolver;\nbegin\n  SudokuSolver := TSudokuSolver.Create('850002400' +\n                                       '720000009' +\n                                       '004000000' +\n                                       '000107002' +\n                                       '305000900' +\n                                       '040000000' +\n                                       '000080070' +\n                                       '017000000' +\n                                       '000036040');\n  try\n    SudokuSolver.Solve;\n  finally\n    FreeAndNil(SudokuSolver);\n  end;\nend;\n\n","human_summarization":"\"Code implements a Sudoku solver for a 9x9 grid. It takes a partially filled grid as input and displays the solved Sudoku in a human-readable format. The solution is based on the Algorithmics of Sudoku and Python Sudoku Solver Computerphile video.\"","id":4024}
    {"lang_cluster":"Delphi","source_code":"\nprogram Knuth;\n\nconst\n  startIdx = -5;\n  max = 11;\ntype\n  tmyData = string[9];\n  tmylist = array [startIdx..startIdx+max-1] of tmyData;\n\nprocedure InitList(var a: tmylist);\nvar\n  i: integer;\nBegin\n  for i := Low(a) to High(a) do\n    str(i:3,a[i])\nend;\n\nprocedure shuffleList(var a: tmylist);\nvar\n  i,k : integer;\n  tmp: tmyData;\nbegin\n  for i := High(a)-low(a) downto 1 do begin\n    k := random(i+1) + low(a);\n    tmp := a[i+low(a)]; a[i+low(a)] := a[k]; a[k] := tmp\n  end\nend;\n\nprocedure DisplayList(const a: tmylist);\nvar\n  i : integer;\nBegin\n  for i := Low(a) to High(a) do\n    write(a[i]);\n  writeln\nend;\n\n{ Test and display }\nvar\n a: tmylist;\n i: integer;\nbegin\n  randomize;\n  InitList(a);\n  DisplayList(a);\n  writeln;\n  For i := 0 to 4 do\n  Begin\n    shuffleList(a);\n    DisplayList(a);\n  end;\nend.\n","human_summarization":"implement the Knuth shuffle algorithm, also known as the Fisher-Yates shuffle. This algorithm shuffles the elements of an array randomly. It works by iterating through the array from the last element to the first, and for each element, it swaps it with a random element in the range from the first element to the current one. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary.","id":4025}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram LastFridayOfMonth;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils, System.DateUtils;\n\nvar\n  Year: Word;\n  Month: Word;\n  D1: TDateTime;\n  D2: Word;\n\nbegin\n  Write('Enter year: ');\n  ReadLn(Year);\n\n  for Month := MonthJanuary to MonthDecember do begin\n    D1 := EndOfAMonth(Year, Month);\n    D2 := DayOfTheWeek(D1);\n    while D2 <> DayFriday do begin\n      D1 := IncDay(D1, -1);\n      D2 := DayOfTheWeek(D1);\n    end;\n    WriteLn(DateToStr(D1));\n  end;\nend.\n\n\n","human_summarization":"The code takes a year as input and returns the dates of the last Fridays of each month for that given year. The year can be inputted through any simple method such as command line or standard input. The code uses the standard Delphi library.","id":4026}
    {"lang_cluster":"Delphi","source_code":"\nprogram Project1;\n\n{$APPTYPE CONSOLE}\n\nbegin\n  Write('Goodbye, World!');\nend.\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":4027}
    {"lang_cluster":"Delphi","source_code":"\nprogram UserInputGraphical;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils, Dialogs;\n\nvar\n  s: string;\n  lStringValue: string;\n  lIntegerValue: Integer;\nbegin\n  lStringValue := InputBox('User input\/Graphical', 'Enter a string', '');\n\n  repeat\n    s := InputBox('User input\/Graphical', 'Enter the number 75000', '75000');\n    lIntegerValue := StrToIntDef(s, 0);\n    if lIntegerValue <> 75000 then\n      ShowMessage('Invalid entry: ' + s);\n  until lIntegerValue = 75000;\nend.\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":4028}
    {"lang_cluster":"Delphi","source_code":"\nProgram CaesarCipher(output);\n\nprocedure encrypt(var message: string; key: integer);\n  var\n    i: integer;\n  begin\n    for i := 1 to length(message) do\n      case message[i] of\n        'A'..'Z': message[i] := chr(ord('A') + (ord(message[i]) - ord('A') + key) mod 26);\n        'a'..'z': message[i] := chr(ord('a') + (ord(message[i]) - ord('a') + key) mod 26);\n      end;\n  end;\n \nprocedure decrypt(var message: string; key: integer);\n  var\n    i: integer;\n  begin\n    for i := 1 to length(message) do\n      case message[i] of\n       'A'..'Z': message[i] := chr(ord('A') + (ord(message[i]) - ord('A') - key + 26) mod 26);\n       'a'..'z': message[i] := chr(ord('a') + (ord(message[i]) - ord('a') - key + 26) mod 26);\n      end;\n  end;\n\nvar\n  key: integer;\n  message: string;\n\nbegin\n  key := 3;\n  message := 'The five boxing wizards jump quickly';\n  writeln ('Original message: ', message);\n  encrypt(message, key);\n  writeln ('Encrypted message: ', message);\n  decrypt(message, key);\n  writeln ('Decrypted message: ', message);\n  readln;\nend.\n","human_summarization":"implement a Caesar cipher for both encoding and decoding. The cipher uses a key ranging from 1 to 25 to rotate the letters of the alphabet, replacing each letter with the next 1st to 25th letter. The cipher is identical to Vigen\u00e8re cipher with a key of length 1 and Rot-13 with key 13. However, it provides almost no security as the encoded message can be easily decrypted.","id":4029}
    {"lang_cluster":"Delphi","source_code":"\nProgram LeastCommonMultiple(output);\n\n{$IFDEF FPC}\n  {$MODE DELPHI}\n{$ENDIF}\n\nfunction lcm(a, b: longint): longint;\nbegin\n  result := a;\n  while (result mod b) <> 0 do\n    inc(result, a);\nend;\n\nbegin\n  writeln('The least common multiple of 12 and 18 is: ', lcm(12, 18));\nend.\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. It also handles the special case where if either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until one is found that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. Additionally, the LCM can be found by merging the prime decompositions of both m and n.","id":4030}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\ntype TCUSIPInfo = record\n ID,Company: string;\n end;\n\nvar CUSIPArray: array [0..5] of TCUSIPInfo = (\n  (ID:'037833100'; Company: 'Apple Incorporated'),\n  (ID:'17275R102'; Company: 'Cisco Systems'),\n  (ID:'38259P508'; Company: 'Google Incorporated'),\n  (ID:'594918104'; Company: 'Microsoft Corporation'),\n  (ID:'68389X106'; Company: 'Oracle Corporation'),\n  (ID:'68389X105'; Company: 'Oracle Corporation'));\n\nfunction IsValidCUSIP(Info: TCUSIPInfo): boolean;\n{Calculate checksum on first 7 chars of CUSIP }\n{And compare with the last char - the checksum char}\nvar I,V,Sum: integer;\nvar C: char;\nbegin\nSum:=0;\nfor I:=1 to Length(Info.ID)-1 do\n\tbegin\n\tC:=Info.ID[I];\n\tif C in ['0'..'9'] then V:=byte(C)-$30\n\telse if C in ['A'..'Z'] then V:=(byte(C)-$40) + 9\n\telse case C of\n\t '*': V:=36;\n\t '@': V:=37;\n\t '#': V:=38;\n\t end;\n\tif (I and 1)=0 then V:=V*2;\n\tSum:=Sum + (V div 10) + (V mod 10);\n\tend;\nSum:=(10 - (Sum mod 10)) mod 10;\nResult:=StrToInt(Info.ID[Length(Info.ID)])=Sum;\nend;\n\n\nprocedure TestCUSIPList(Memo: TMemo);\n{Test every item in the CSUIP array}\nvar I: integer;\nvar S: string;\nbegin\nfor I:=0 to High(CUSIPArray) do\n\tbegin\n\tif IsValidCUSIP(CUSIPArray[I]) then S:='Valid' else S:='Invalid';\n\tMemo.Lines.Add(CUSIPArray[I].ID+'\t'+CUSIPArray[I].Company+':\t'+S);\n\tend;\nend;\n\n\n","human_summarization":"The code verifies the correctness of the last digit (check digit) of a CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The code uses an algorithm that takes an 8-character CUSIP as input, calculates a sum based on the numeric value or ordinal position of each character, and returns the result of a specific calculation involving this sum. The correctness of the check digit is then assessed against this result. The code is designed to facilitate the clearing and settlement of trades.","id":4031}
    {"lang_cluster":"Delphi","source_code":"\nprogram HostIntrospection ;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils;\n\nbegin\n  Writeln('word size: ', SizeOf(Integer));\n  Writeln('endianness: little endian'); \/\/ Windows is always little endian\nend.\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":4032}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  System.Classes\nLibrary:  IdHttp\nLibrary:  IdBaseComponent\nLibrary:  IdComponent\nLibrary:  IdIOHandler\nLibrary:  IdIOHandlerSocket\nLibrary:  IdIOHandlerStack\nLibrary:  IdSSL\nLibrary:  IdSSLOpenSSL\nLibrary:  System.RegularExpressions\nLibrary:  System.Generics.Collections\nLibrary:  System.Generics.Defaults\n\nprogram Rank_languages_by_popularity;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n  System.SysUtils,\n  System.Classes,\n  IdHttp,\n  IdBaseComponent,\n  IdComponent,\n  IdIOHandler,\n  IdIOHandlerSocket,\n  IdIOHandlerStack,\n  IdSSL,\n  IdSSLOpenSSL,\n  System.RegularExpressions,\n  System.Generics.Collections,\n  System.Generics.Defaults;\n\nconst\n  AURL = 'https:\/\/www.rosettacode.org\/mw\/index.php?title=Special:Categories&limit=5000';\n  UserAgent =\n    'Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/74.0.3729.169 Safari\/537.36';\n\ntype\n  TPair = record\n    Language: string;\n    Users: Integer;\n    constructor Create(lang, user: string);\n  end;\n\n  TPairs = TList<TPair>;\n\n\n  { TPair }\n\nconstructor TPair.Create(lang, user: string);\nbegin\n  Language := lang;\n  Users := StrToIntDef(user, 0);\nend;\n\nfunction GetFullCode: string;\nbegin\n  with TIdHttp.create(nil) do\n  begin\n    HandleRedirects := True;\n    Request.UserAgent := UserAgent;\n    IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);\n    Result := Get(AURL);\n    IOHandler.Free;\n    Free;\n  end;\nend;\n\nfunction GetList(const Code: string): TPairs;\nvar\n  RegularExpression: TRegEx;\n  Match: TMatch;\n  language, users: string;\nbegin\n  Result := TPairs.Create;\n\n  RegularExpression.Create('>(?<LANG>[^<,;]*)<\\\/a>.. \\((?<USERS>[,\\d]*)');\n  Match := RegularExpression.Match(Code);\n\n  while Match.Success do\n  begin\n    users := Match.Groups.Item['USERS'].Value.Replace(',', '');\n    language := Match.Groups.Item['LANG'].Value;\n\n    Result.Add(TPair.Create(language, users));\n    Match := Match.NextMatch;\n  end;\nend;\n\nprocedure Sort(List: TPairs);\nbegin\n  List.Sort(TComparer<TPair>.Construct(\n    function(const Left, Right: TPair): Integer\n    begin\n      result := Right.Users - Left.Users;\n      if result = 0 then\n        result := CompareText(Left.Language, Right.Language);\n    end));\nend;\n\nfunction SumUsers(List: TPairs): Cardinal;\nvar\n  p: TPair;\nbegin\n  Result := 0;\n  for p in List do\n  begin\n    Inc(Result, p.Users);\n  end;\nend;\n\nvar\n  Data: TStringList;\n  Code, line: string;\n  List: TPairs;\n  i: Integer;\n\nbegin\n  Data := TStringList.Create;\n  Writeln('Downloading code...');\n\n  Code := GetFullCode;\n  data.Clear;\n\n  List := GetList(Code);\n\n  Sort(List);\n\n  Writeln('Total languages: ', List.Count);\n  Writeln('Total Users: ', SumUsers(List));\n  Writeln('Top 10:'#10);\n\n  for i := 0 to List.Count - 1 do\n  begin\n    line := Format('%5dth %5d %s', [i + 1, List[i].users, List[i].language]);\n    Data.Add(line);\n    if i < 10 then\n      Writeln(line);\n  end;\n\n  Data.SaveToFile('Rank.txt');\n  List.Free;\n  Data.Free;\n\n  Readln;\nend.\n\n\nOutput (as of Jul 27, 2020):\nDownloading code...\nTotal languages: 3267\nTotal Users: 96532\nTop 10:\n\n    1th  1261 Go\n    2th  1228 Phix\n    3th  1221 Julia\n    4th  1210 Raku\n    5th  1148 Python\n    6th  1139 Perl\n    7th  1090 Kotlin\n    8th  1053 C\n    9th  1052 Java\n   10th  1051 Racket\n\n","human_summarization":"The code sorts the most popular computer programming languages based on the number of members in Rosetta Code categories. It uses either web scraping or API methods to access the data. The code also has an optional feature to filter incorrect results. The results can be checked against a complete, accurate, sortable, wikitable listing of all programming languages. For safe execution, the code requires the dlls: libeay32.dll & ssleay32.dll in the executable path.","id":4033}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram LoopForEach;\n\n{$APPTYPE CONSOLE}\n\nvar\n  s: string;\nbegin\n  for s in 'Hello' do\n    Writeln(s);\nend.\n\n\nH\ne\nl\nl\no\n","human_summarization":"utilize a \"for each\" loop or an alternative loop to iterate through and print each element in a collection in order. The codes support arrays (single, multidimensional, and dynamic), sets, strings, collections and any class or interface that implements GetEnumerator(), using for..in loops introduced in Delphi 2005.","id":4034}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nprogram Tokenize_a_string;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils;\n\nvar\n  Words: TArray<string>;\n\nbegin\n  Words := 'Hello,How,Are,You,Today'.Split([',']);\n  Writeln(string.Join(#10, Words));\n\n  Readln;\nend.\n\nprogram TokenizeString;\n\n{$APPTYPE CONSOLE}\n\nuses\n  Classes;\n\nvar\n  tmp: TStringList;\n  i: Integer;\n\nbegin\n\n  \/\/ Instantiate TStringList class\n  tmp := TStringList.Create;\n  try\n    { Use the TStringList's CommaText property to get\/set\n      all the strings in a single comma-delimited string }\n    tmp.CommaText := 'Hello,How,Are,You,Today';\n\n    { Now loop through the TStringList and display each\n      token on the console }\n    for i := 0 to Pred(tmp.Count) do\n      Writeln(tmp[i]);\n\n  finally\n    tmp.Free;\n  end;\n\n  Readln;\n\nend.\n\n\nHello\nHow\nAre\nYou\nToday\n\n","human_summarization":"\"Tokenizes a string by separating it by commas into an array, then displays the words to the user separated by a period, including a trailing period.\"","id":4035}
    {"lang_cluster":"Delphi","source_code":"\nPROGRAM EXRECURGCD.PAS;\n\n{$IFDEF FPC}\n    {$mode objfpc}{$H+}{$J-}{R+}\n{$ELSE}\n    {$APPTYPE CONSOLE}\n{$ENDIF}\n\n(*) \n    Free Pascal Compiler version 3.2.0 [2020\/06\/14] for x86_64\n    The free and readable alternative at C\/C++ speeds\n    compiles natively to almost any platform, including raspberry PI\n(*)\n\nFUNCTION gcd_recursive(u, v: longint): longint;\n\n    BEGIN\n        IF ( v = 0 ) THEN Exit ( u ) ;\n        result := gcd_recursive ( v, u MOD v ) ;\n    END;\n\nBEGIN\n\n    WriteLn ( gcd_recursive ( 231, 7 ) ) ;\n\nEND.\n","human_summarization":"finds the greatest common divisor (GCD), also known as greatest common factor (gcf) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on greatest common divisor. The code is written in Pascal\/Delphi\/Free Pascal.","id":4036}
    {"lang_cluster":"Delphi","source_code":"\nprogram EchoServer;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils, IdContext, IdTCPServer;\n\ntype\n  TEchoServer = class\n  private\n    FTCPServer: TIdTCPServer;\n  public\n    constructor Create;\n    destructor Destroy; override;\n    procedure TCPServerExecute(AContext: TIdContext);\n  end;\n\nconstructor TEchoServer.Create;\nbegin\n  FTCPServer := TIdTCPServer.Create(nil);\n  FTCPServer.DefaultPort := 12321;\n  FTCPServer.OnExecute := TCPServerExecute;\n  FTCPServer.Active := True;\nend;\n\ndestructor TEchoServer.Destroy;\nbegin\n  FTCPServer.Active := False;\n  FTCPServer.Free;\n  inherited Destroy;\nend;\n\nprocedure TEchoServer.TCPServerExecute(AContext: TIdContext);\nvar\n  lCmdLine: string;\nbegin\n  lCmdLine := AContext.Connection.IOHandler.ReadLn;\n  Writeln('>' + lCmdLine);\n  AContext.Connection.IOHandler.Writeln('>' + lCmdLine);\n\n  if SameText(lCmdLine, 'QUIT') then\n  begin\n    AContext.Connection.IOHandler.Writeln('Disconnecting');\n    AContext.Connection.Disconnect;\n  end;\nend;\n\nvar\n  lEchoServer: TEchoServer;\nbegin\n  lEchoServer := TEchoServer.Create;\n  try\n    Writeln('Delphi Echo Server');\n    Writeln('Press Enter to quit');\n    Readln;\n  finally\n    lEchoServer.Free;\n  end;\nend.\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":4037}
    {"lang_cluster":"Delphi","source_code":"\n\nfunction IsNumericString(const inStr: string): Boolean;\nvar\n  i: extended;\nbegin\n  Result := TryStrToFloat(inStr,i);\nend;\n\n\nprogram isNumeric;\n\n{$APPTYPE CONSOLE}\n\nuses\n  Classes,\n  SysUtils;\n\nfunction IsNumericString(const inStr: string): Boolean;\nvar\n  i: extended;\nbegin\n  Result := TryStrToFloat(inStr,i);\nend;\n\n\n{ Test function }\nvar\n  s: string;\n  c: Integer;\n\nconst\n  MAX_TRIES = 10;\n  sPROMPT   = 'Enter a string (or type \"quit\" to exit):';\n  sIS       = ' is numeric';\n  sISNOT    = ' is NOT numeric';\n\nbegin\n  c := 0;\n  s := '';\n  repeat\n    Inc(c);\n    Writeln(sPROMPT);\n    Readln(s);\n    if (s <> '') then\n      begin\n        tmp.Add(s);\n        if IsNumericString(s) then\n          begin\n            Writeln(s+sIS);\n          end\n          else\n          begin\n            Writeln(s+sISNOT);\n          end;\n        Writeln('');\n      end;\n  until\n    (c >= MAX_TRIES) or (LowerCase(s) = 'quit');\n\nend.\n\n\n","human_summarization":"\"Implements a boolean function in Delphi that checks if a given string is a numeric string, including floating point and negative numbers. The function is tested in a console application.\"","id":4038}
    {"lang_cluster":"Delphi","source_code":"\nLibrary: OpenSSL\nprogram ShowHTTPS;\n\n{$APPTYPE CONSOLE}\n\nuses IdHttp, IdSSLOpenSSL;\n\nvar\n  s: string;\n  lHTTP: TIdHTTP;\nbegin\n  lHTTP := TIdHTTP.Create(nil);\n  try\n    lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP);\n    lHTTP.HandleRedirects := True;\n    s := lHTTP.Get('https:\/\/sourceforge.net\/');\n    Writeln(s);\n  finally\n    lHTTP.Free;\n  end;\nend.\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":4039}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\nprocedure ShowTrigFunctions(Memo: TMemo);\nconst AngleDeg = 45.0;\nvar AngleRad,ArcSine,ArcCosine,ArcTangent: double;\nbegin\nAngleRad:=DegToRad(AngleDeg);\n\nMemo.Lines.Add(Format('Angle:      Degrees: %3.5f   Radians: %3.6f',[AngleDeg,AngleRad]));\nMemo.Lines.Add('-------------------------------------------------');\nMemo.Lines.Add(Format('Sine:       Degrees: %3.6f   Radians: %3.6f',[sin(DegToRad(AngleDeg)),sin(AngleRad)]));\nMemo.Lines.Add(Format('Cosine:     Degrees: %3.6f   Radians: %3.6f',[cos(DegToRad(AngleDeg)),cos(AngleRad)]));\nMemo.Lines.Add(Format('Tangent:    Degrees: %3.6f   Radians: %3.6f',[tan(DegToRad(AngleDeg)),tan(AngleRad)]));\nArcSine:=ArcSin(Sin(AngleRad));\nMemo.Lines.Add(Format('Arcsine:    Degrees: %3.6f   Radians: %3.6f',[DegToRad(ArcSine),ArcSine]));\nArcCosine:=ArcCos(cos(AngleRad));\nMemo.Lines.Add(Format('Arccosine:  Degrees: %3.6f   Radians: %3.6f',[DegToRad(ArcCosine),ArcCosine]));\nArcTangent:=ArcTan(tan(AngleRad));\nMemo.Lines.Add(Format('Arctangent: Degrees: %3.6f   Radians: %3.6f',[DegToRad(ArcTangent),ArcTangent]));\nend;\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) in a given programming language, using the same angle in both radians and degrees. The codes also include the conversion of results for inverse functions to radians and degrees. If the language lacks built-in trigonometric functions, the codes provide custom functions based on known approximations or identities.","id":4040}
    {"lang_cluster":"Delphi","source_code":"\nprogram IncrementNumericalString;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils;\n\nconst\n  STRING_VALUE = '12345';\nbegin\n  WriteLn(Format('\"%s\" + 1 = %d', [STRING_VALUE, StrToInt(STRING_VALUE) + 1]));\n\n  Readln;\nend.\n\n\n","human_summarization":"\"Increments a given numerical string.\"","id":4041}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nprogram Find_common_directory_path;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils;\n\nfunction FindCommonPath(Separator: Char; Paths: TArray<string>): string;\nvar\n  SeparatedPath: array of TArray<string>;\n  minLength, index: Integer;\n  isSame: Boolean;\n  j, i: Integer;\n  cmp: string;\nbegin\n  SetLength(SeparatedPath, length(Paths));\n  minLength := MaxInt;\n  for i := 0 to High(SeparatedPath) do\n  begin\n    SeparatedPath[i] := Paths[i].Split([Separator]);\n    if minLength > length(SeparatedPath[i]) then\n      minLength := length(SeparatedPath[i]);\n  end;\n\n  index := -1;\n\n  for i := 0 to minLength - 1 do\n  begin\n    isSame := True;\n    cmp := SeparatedPath[0][i];\n    for j := 1 to High(SeparatedPath) do\n      if SeparatedPath[j][i] <> cmp then\n      begin\n        isSame := False;\n        Break;\n      end;\n    if not isSame then\n    begin\n      index := i - 1;\n      Break;\n    end;\n  end;\n\n  Result := '';\n  if index >= 0 then\n    for i := 0 to index do\n    begin\n      Result := Result + SeparatedPath[0][i];\n      if i < index then\n        Result := Result + Separator;\n    end;\nend;\n\nbegin\n  Writeln(FindCommonPath('\/', [\n    '\/home\/user1\/tmp\/coverage\/test',\n    '\/home\/user1\/tmp\/covert\/operator',\n    '\/home\/user1\/tmp\/coven\/members']));\n  Readln;\nend.\n\n\n","human_summarization":"The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '\/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.","id":4042}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\nprocedure DoSattoloCycle(var IA: array of integer);\n{Shuffle integers in array using Sattolo cycle}\nvar I,J,T: integer;\nbegin\n{Make sure random number generator is random}\nRandomize;\n{Randomly shuffle every item in the array}\nfor I:=High(IA) downto 0 do\n\tbegin\n\tJ:=Random(I);\n\tT:=IA[I]; IA[I]:=IA[J]; IA[J]:=T;\n\tend;\nend;\n\n{Test data specified in problem}\n\nvar SatTest1: array of integer;\nvar SatTest2: array [0..0] of integer = (10);\nvar SatTest3: array [0..1] of integer = (10, 20);\nvar SatTest4: array [0..2] of integer = (10, 20, 30);\nvar SatTest5: array [0..11] of integer = (11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22);\n\n\nprocedure ShowSattoloCycle(Memo: TMemo);\n\n\tprocedure ShowIntArray(Title: string; IA: array of integer);\n\t{Display title and array}\n\tvar I: integer;\n\tvar S: string;\n\tbegin\n\tS:=Title+' [';\n\tfor I:=0 to High(IA) do\n\t\tbegin\n\t\tif I<>0 then S:=S+' ';\n\t\tS:=S+IntToStr(IA[I]);\n\t\tend;\n\tS:=S+']';\n\tMemo.Lines.Add(S);\n\tend;\n\n\n\tprocedure ShowShuffleData(var IA: array of integer);\n\t{Shuffle and display specified array}\n\tbegin\n\tShowIntArray('Original data:', IA);\n\tDoSattoloCycle(IA);\n\tShowIntArray('Shuffled data:',IA);\n\tend;\n\n\nbegin\n{Shuffle and display all data items}\nShowShuffleData(SatTest1);\nShowShuffleData(SatTest2);\nShowShuffleData(SatTest3);\nShowShuffleData(SatTest4);\nShowShuffleData(SatTest5);\nend;\n\n\n","human_summarization":"implement the Sattolo cycle algorithm to randomly shuffle an array ensuring each element is in a new position. The algorithm modifies the input array in-place or returns a new shuffled array. It differs from the Knuth shuffle by choosing a random integer from a range ensuring each element ends up in a new position.","id":4043}
    {"lang_cluster":"Delphi","source_code":"\nprogram AveragesMedian;\n\n{$APPTYPE CONSOLE}\n\nuses Generics.Collections, Types;\n\nfunction Median(aArray: TDoubleDynArray): Double;\nvar\n  lMiddleIndex: Integer;\nbegin\n  TArray.Sort<Double>(aArray);\n\n  lMiddleIndex := Length(aArray) div 2;\n  if Odd(Length(aArray)) then\n    Result := aArray[lMiddleIndex]\n  else\n    Result := (aArray[lMiddleIndex - 1] + aArray[lMiddleIndex]) \/ 2;\nend;\n\nbegin\n  Writeln(Median(TDoubleDynArray.Create(4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)));\n  Writeln(Median(TDoubleDynArray.Create(4.1, 7.2, 1.7, 9.3, 4.4, 3.2)));\nend.\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.","id":4044}
    {"lang_cluster":"Delphi","source_code":"\nprogram FizzBuzz;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils;\n\nvar\n  i: Integer;\nbegin\n  for i\u00a0:= 1 to 100 do\n  begin\n    if i mod 15 = 0 then\n      Writeln('FizzBuzz')\n    else if i mod 3 = 0 then\n      Writeln('Fizz')\n    else if i mod 5 = 0 then\n      Writeln('Buzz')\n    else\n      Writeln(i);\n  end;\nend.\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":4045}
    {"lang_cluster":"Delphi","source_code":"\nprogram mandelbrot;\n \n  {$IFDEF FPC}\n      {$MODE DELPHI}  \n  {$ENDIF}\n\nconst\n   ixmax = 800;\n   iymax = 800;\n   cxmin = -2.5;\n   cxmax =  1.5;\n   cymin = -2.0;\n   cymax =  2.0;\n   maxcolorcomponentvalue = 255;\n   maxiteration = 200;\n   escaperadius = 2;\n \ntype\n   colortype = record\n      red   : byte;\n      green : byte;\n      blue  : byte;\n   end;\n \nvar\n   ix, iy      : integer;\n   cx, cy      : real;\n   pixelwidth  : real = (cxmax - cxmin) \/ ixmax;\n   pixelheight : real = (cymax - cymin) \/ iymax;\n   filename    : string = 'new1.ppm';\n   comment     : string = '# ';\n   outfile     : textfile;\n   color       : colortype;\n   zx, zy      : real;\n   zx2, zy2    : real;\n   iteration   : integer;\n   er2         : real = (escaperadius * escaperadius);\n \nbegin\n   {$I-}\n   assign(outfile, filename);\n   rewrite(outfile);\n   if ioresult <> 0 then\n   begin\n      {$IFDEF FPC}\n         writeln(stderr, 'Unable to open output file: ', filename);\n      {$ELSE}\n         writeln('ERROR: Unable to open output file: ', filename);\n      {$ENDIF}      \n      exit;\n   end;\n \n   writeln(outfile, 'P6');\n   writeln(outfile, ' ', comment);\n   writeln(outfile, ' ', ixmax);\n   writeln(outfile, ' ', iymax);\n   writeln(outfile, ' ', maxcolorcomponentvalue);\n \n   for iy := 1 to iymax do\n   begin\n      cy := cymin + (iy - 1)*pixelheight;\n      if abs(cy) < pixelheight \/ 2 then cy := 0.0;\n      for ix := 1 to ixmax do\n      begin\n         cx := cxmin + (ix - 1)*pixelwidth;\n         zx := 0.0;\n         zy := 0.0;\n         zx2 := zx*zx;\n         zy2 := zy*zy;\n         iteration := 0;\n         while (iteration < maxiteration) and (zx2 + zy2 < er2) do\n         begin\n            zy := 2*zx*zy + cy;\n            zx := zx2 - zy2 + cx;\n            zx2 := zx*zx;\n            zy2 := zy*zy;\n            iteration := iteration + 1;\n         end;\n         if iteration = maxiteration then\n         begin\n            color.red   := 0;\n            color.green := 0;\n            color.blue  := 0;\n         end\n         else\n         begin\n            color.red   := 255;\n            color.green := 255;\n            color.blue  := 255;\n         end;\n         write(outfile, chr(color.red), chr(color.green), chr(color.blue));\n      end;\n   end;\n \n   close(outfile);\nend.\n","human_summarization":"generate and draw the Mandelbrot set using various available algorithms and functions.","id":4046}
    {"lang_cluster":"Delphi","source_code":"\nprogram SumAndProductOfArray;\n\n{$APPTYPE CONSOLE}\n\nvar\n  i: integer;\n  lIntArray: array [1 .. 5] of integer = (1, 2, 3, 4, 5);\n  lSum: integer = 0;\n  lProduct: integer = 1;\nbegin\n  for i := 1 to length(lIntArray) do\n  begin\n    Inc(lSum, lIntArray[i]);\n    lProduct := lProduct * lIntArray[i]\n  end;\n\n  Write('Sum: ');\n  Writeln(lSum);\n  Write('Product: ');\n  Writeln(lProduct);\nend.\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":4047}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  System.Classesprogram MD5Implementation;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils,\n  System.Classes;\n\ntype\n  TTestCase = record\n    hashCode: string;\n    _: string;\n  end;\n\nvar\n  testCases: array[0..6] of TTestCase = ((\n    hashCode: 'D41D8CD98F00B204E9800998ECF8427E';\n    _: ''\n  ), (\n    hashCode: '0CC175B9C0F1B6A831C399E269772661';\n    _: 'a'\n  ), (\n    hashCode: '900150983CD24FB0D6963F7D28E17F72';\n    _: 'abc'\n  ), (\n    hashCode: 'F96B697D7CB7938D525A2F31AAF161D0';\n    _: 'message digest'\n  ), (\n    hashCode: 'C3FCD3D76192E4007DFB496CCA67E13B';\n    _: 'abcdefghijklmnopqrstuvwxyz'\n  ), (\n    hashCode: 'D174AB98D277D9F5A5611C2C9F419D9F';\n    _: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\n  ), (\n    hashCode: '57EDF4A22BE3C955AC49DA2E2107B67A';\n    _: '12345678901234567890123456789' + '012345678901234567890123456789012345678901234567890'\n  ));\n  shift: array of UInt32 = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];\n  table: array[0..63] of UInt32;\n\nprocedure Init();\nvar\n  i: integer;\n\n  function fAbs(x: Extended): Extended;\n  begin\n    if x < 0 then\n      exit(-x);\n    exit(x);\n  end;\n\nbegin\n  for i := 0 to High(table) do\n    table[i] := Trunc((UInt64(1) shl 32) * fAbs(Sin(i + 1.0)));\nend;\n\nfunction Md5(s: string): TBytes;\nconst\n  BUFFER_SIZE = 16;\nvar\n  binary: TBytesStream;\n  buffer: Tarray<UInt32>;\n  messageLenBits: UInt64;\n  i, j, bufferIndex, count: integer;\n  byte_data: byte;\n  string_data: ansistring;\n  k, k1: Tarray<UInt32>;\n  f, rnd, sa: UInt32;\n  tmp: UInt64;\nbegin\n  k := [$67452301, $EFCDAB89, $98BADCFE, $10325476];\n\n  binary := TBytesStream.Create();\n\n  if not s.IsEmpty then\n  begin\n    string_data := Utf8ToAnsi(s);\n    binary.Write(Tbytes(string_data), length(string_data));\n  end;\n\n  byte_data := $80;\n  binary.Write(byte_data, 1);\n\n  messageLenBits := UInt64(s.Length * 8);\n  count := s.Length + 1;\n\n  while (count mod 64) <> 56 do\n  begin\n    byte_data := $00;\n    binary.Write(byte_data, 1);\n    inc(count);\n  end;\n\n  binary.Write(messageLenBits, sizeof(messageLenBits));\n\n  SetLength(buffer, BUFFER_SIZE);\n  SetLength(k1, length(k));\n\n  binary.Seek(0, soFromBeginning);\n\n  while binary.Read(buffer[0], BUFFER_SIZE * 4) > 0 do\n  begin\n    for i := 0 to 3 do\n      k1[i] := k[i];\n\n    for i := 0 to 63 do\n    begin\n      f := 0;\n      bufferIndex := i;\n      rnd := i shr 4;\n      case rnd of\n        0:\n          f := (k1[1] and k1[2]) or (not k1[1] and k1[3]);\n        1:\n          begin\n            f := (k1[1] and k1[3]) or (k1[2] and not k1[3]);\n            bufferIndex := (bufferIndex * 5 + 1) and $0F\n          end;\n        2:\n          begin\n            f := k1[1] xor k1[2] xor k1[3];\n            bufferIndex := (bufferIndex * 3 + 5) and $0F;\n          end;\n        3:\n          begin\n            f := k1[2] xor (k1[1] or not k1[3]);\n            bufferIndex := (bufferIndex * 7) and $0F;\n          end;\n      end;\n\n      sa := shift[(rnd shl 2) or (i and 3)];\n\n      k1[0] := k1[0] + f + buffer[bufferIndex] + table[i];\n\n      tmp := k1[0];\n\n      k1[0] := k1[3];\n      k1[3] := k1[2];\n      k1[2] := k1[1];\n\n      k1[1] := ((tmp shl sa) or (tmp shr (32 - sa))) + k1[1];\n    end;\n\n    for i := 0 to 3 do\n      k[i] := k[i] + k1[i];\n  end;\n\n  SetLength(result, BUFFER_SIZE);\n\n  binary.Clear;\n  for i := 0 to 3 do\n    binary.Write(k[i], 4);\n\n  binary.Seek(0, soBeginning);\n\n  binary.Read(Result, BUFFER_SIZE);\n\n  binary.Free;\nend;\n\nfunction BytesToString(b: TBytes): string;\nvar\n  v: byte;\nbegin\n  Result := '';\n  for v in b do\n    Result := Result + v.ToHexString(2);\nend;\n\nvar\n  tc: TTestCase;\n\nbegin\n  Init;\n\n  for tc in testCases do\n    Writeln(Format('%s'#10'%s'#10, [tc.hashCode, BytesToString(md5(tc._))]));\n  Readln;\nend.\n\n","human_summarization":"The code is an implementation of the MD5 Message Digest Algorithm, developed directly from the algorithm specification without using built-in or external hashing libraries. It produces a correct message digest for an input string but does not mimic all calling modes. The code also includes handling of bit manipulation, unsigned integers, and little-endian data, with attention to details like boundary conditions and padding. The implementation is validated against the verification strings and hashes from RFC 1321.","id":4048}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtilsprogram Department_numbers;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils;\n\nvar\n  i, j, k, count: Integer;\n\nbegin\n  writeln('Police  Sanitation  Fire');\n  writeln('------  ----------  ----');\n  count := 0;\n  i := 2;\n  while i < 7 do\n  begin\n    for j := 1 to 7 do\n    begin\n      if j = i then\n        Continue;\n      for k := 1 to 7 do\n      begin\n        if (k = i) or (k = j) then\n          Continue;\n        if i + j + k <> 12 then\n          Continue;\n        writeln(format('  %d         %d         %d', [i, j, k]));\n        inc(count);\n      end;\n    end;\n    inc(i, 2);\n  end;\n  writeln(#10, count, ' valid combinations');\n  readln;\nend.\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":4049}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram CopyString;\n\n{$APPTYPE CONSOLE}\n\nvar\n  s1: string;\n  s2: string;\nbegin\n  s1 := 'Goodbye';\n  s2 := s1; \/\/ S2 points at the same string as S1\n  s2 := s2 + ', World!'; \/\/ A new string is created for S2\n\n  Writeln(s1);\n  Writeln(s2);\nend.\n\n\n","human_summarization":"implement the functionality of copying a string in Delphi, differentiating between copying the string's contents and creating an additional reference to the existing string, utilizing the reference counting with copy on write semantics feature of Delphi strings.","id":4050}
    {"lang_cluster":"Delphi","source_code":"\nunit Hofstadter;\n\ninterface\n\ntype\n  THofstadterFemaleMaleSequences = class\n  public\n    class function F(n: Integer): Integer;\n    class function M(n: Integer): Integer;\n  end;\n\nimplementation\n\nclass function THofstadterFemaleMaleSequences.F(n: Integer): Integer;\nbegin\n  Result:= 1;\n  if (n > 0) then\n    Result:= n - M(F(n-1));\nend;\n\nclass function THofstadterFemaleMaleSequences.M(n: Integer): Integer;\nbegin\n  Result:= 0;\n  if (n > 0) then\n    Result:= n - F(M(n - 1));\nend;\n\nend.\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":4051}
    {"lang_cluster":"Delphi","source_code":"\nProgram PickRandomElement (output);\n\nconst\n  s: array [1..5] of string = ('1234', 'ABCDE', 'Charlie', 'XB56ds', 'lala');\n\nbegin\n  randomize;\n  writeln(s[low(s) + random(length(s))]);\nend.\n\n","human_summarization":"demonstrate how to select a random element from a list in Pascal\/Delphi\/Free Pascal.","id":4052}
    {"lang_cluster":"Delphi","source_code":"\nprogram URLEncoding;\n\n{$APPTYPE CONSOLE}\n\nuses IdURI;\n\nbegin\n  Writeln(TIdURI.URLDecode('http%3A%2F%2Ffoo%20bar%2F'));\nend.\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":4053}
    {"lang_cluster":"Delphi","source_code":"\nfunction binary_search(element: real; list: array of real): integer;\nvar\n    l, m, h: integer;\nbegin\n    l := Low(list);\n    h := High(list);\n    binary_search := -1;\n    while l <= h do\n    begin\n        m := (l + h) div 2;\n        if list[m] > element then\n        begin\n            h := m - 1;\n        end\n        else if list[m] < element then\n        begin\n            l := m + 1;\n        end\n        else\n        begin\n            binary_search := m;\n            break;\n        end;\n    end;\nend;\n","human_summarization":"The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It includes both recursive and iterative versions of traditional binary search, leftmost insertion point, and rightmost insertion point algorithms. The code also handles potential overflow bugs. It returns the index of the found element or the insertion point if the element is not found. The code also prints whether the number was found in the array and its index if it was.","id":4054}
    {"lang_cluster":"Delphi","source_code":"\n\/\/ The program name and the directory it was called from are in\n\/\/ param[0] , so given the axample of myprogram -c \"alpha beta\" -h \"gamma\"\n\n  for x := 0 to paramcount do\n      writeln('param[',x,'] = ',param[x]);\n\n\/\/ will yield ( assuming windows and the c drive as the only drive)\u00a0:\n\n\/\/  param[0] = c:\\myprogram\n\/\/  param[1] = -c\n\/\/  param[2] = alpha beta\n\/\/  param[3] = -h\n\/\/  param[4] = gamma\n\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program, such as 'myprogram -c \"alpha beta\" -h \"gamma\"'. It also includes functionalities for intelligent parsing of these arguments.","id":4055}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  Vcl.Forms\nLibrary:  Vcl.Graphics\nLibrary:  Vcl.ExtCtrlsunit main;\n\ninterface\n\nuses\n  Vcl.Forms, Vcl.Graphics, Vcl.ExtCtrls;\n\ntype\n  TForm1 = class(TForm)\n    procedure FormCreate(Sender: TObject);\n    procedure FormDestroy(Sender: TObject);\n  private\n    Timer: TTimer;\n    angle, angleAccel, angleVelocity, dt: double;\n    len: Integer;\n    procedure Tick(Sender: TObject);\n  end;\n\nvar\n  Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TForm1.FormCreate(Sender: TObject);\nbegin\n  Width := 200;\n  Height := 200;\n  DoubleBuffered := True;\n  Timer := TTimer.Create(nil);\n  Timer.Interval := 30;\n  Timer.OnTimer := Tick;\n  Caption := 'Pendulum';\n\n  \/\/ initialize\n  angle := PI \/ 2;\n  angleAccel := 0;\n  angleVelocity := 0;\n  dt := 0.1;\n  len := 50;\nend;\n\nprocedure TForm1.FormDestroy(Sender: TObject);\nbegin\n  Timer.Free;\nend;\n\nprocedure TForm1.Tick(Sender: TObject);\nconst\n  HalfPivot = 4;\n  HalfBall = 7;\nvar\n  anchorX, anchorY, ballX, ballY: Integer;\nbegin\n  anchorX := Width div 2 - 12;\n  anchorY := Height div 4;\n  ballX := anchorX + Trunc(Sin(angle) * len);\n  ballY := anchorY + Trunc(Cos(angle) * len);\n\n  angleAccel := -9.81 \/ len * Sin(angle);\n  angleVelocity := angleVelocity + angleAccel * dt;\n  angle := angle + angleVelocity * dt;\n\n  with canvas do\n  begin\n    Pen.Color := clBlack;\n\n    with Brush do\n    begin\n      Style := bsSolid;\n      Color := clWhite;\n    end;\n\n    FillRect(ClientRect);\n    MoveTo(anchorX, anchorY);\n    LineTo(ballX, ballY);\n\n    Brush.Color := clGray;\n    Ellipse(anchorX - HalfPivot, anchorY - HalfPivot, anchorX + HalfPivot,\n      anchorY + HalfPivot);\n\n    Brush.Color := clYellow;\n    Ellipse(ballX - HalfBall, ballY - HalfBall, ballX + HalfBall, ballY + HalfBall);\n  end;\nend;\n\nend.\n\n","human_summarization":"create and animate a simple physical model of a gravity pendulum.","id":4056}
    {"lang_cluster":"Delphi","source_code":"program JsonTest;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n  System.SysUtils,\n  Json;\n\ntype\n  TJsonObjectHelper = class helper for TJsonObject\n  public\n    class function Deserialize(data: string): TJsonObject; static;\n    function Serialize: string;\n  end;\n\n{ TJsonObjectHelper }\n\nclass function TJsonObjectHelper.Deserialize(data: string): TJsonObject;\nbegin\n  Result := TJSONObject.ParseJSONValue(data) as TJsonObject;\nend;\n\nfunction TJsonObjectHelper.Serialize: string;\nbegin\n  Result := ToJson;\nend;\n\nvar\n  people, deserialized: TJsonObject;\n  bar: TJsonArray;\n  _json: string;\n\nbegin\n  people := TJsonObject.Create();\n  people.AddPair(TJsonPair.Create('1', 'John'));\n  people.AddPair(TJsonPair.Create('2', 'Susan'));\n\n  _json := people.Serialize;\n  Writeln(_json);\n\n  deserialized := TJSONObject.Deserialize(_json);\n  Writeln(deserialized.Values['2'].Value);\n\n  deserialized := TJSONObject.Deserialize('{\"foo\":1 , \"bar\":[10,\"apples\"]}');\n\n  bar := deserialized.Values['bar'] as TJSONArray;\n  Writeln(bar.Items[1].Value);\n\n  deserialized.Free;\n  people.Free;\n\n  Readln;\nend.\n\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":4057}
    {"lang_cluster":"Delphi","source_code":"\nUSES\n   Math;\n\nfunction NthRoot(A, Precision: Double; n: Integer): Double;\nvar\n   x_p, X: Double;\nbegin\n   x_p := Sqrt(A);\n   while Abs(A - Power(x_p, n)) > Precision do\n   begin\n      x := (1\/n) * (((n-1) * x_p) + (A\/(Power(x_p, n - 1))));\n      x_p := x;\n   end;\n   Result := x_p;\nend;\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":4058}
    {"lang_cluster":"Delphi","source_code":"\nprogram ShowHostName;\n\n{$APPTYPE CONSOLE}\n\nuses Windows;\n\nvar\n  lHostName: array[0..255] of char;\n  lBufferSize: DWORD;\nbegin\n  lBufferSize := 256;\n  if GetComputerName(lHostName, lBufferSize) then\n    Writeln(lHostName)\n  else\n    Writeln('error getting host name');\nend.\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":4059}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\ntype TIntArray = array of integer;\n\nfunction GetLeonardoNumbers(Cnt,SN1,SN2,Add: integer): TIntArray;\nvar N: integer;\nbegin\nSetLength(Result,Cnt);\nResult[0]:=SN1; Result[1]:=SN2;\nfor N:=2 to Cnt-1 do\n\tbegin\n\tResult[N]:=Result[N-1] + Result[N-2] + Add;\n\tend;\nend;\n\n\nprocedure TestLeonardoNumbers(Memo: TMemo);\nvar IA: TIntArray;\nvar S: string;\nvar I: integer;\nbegin\nMemo.Lines.Add('Leonardo Numbers:');\nIA:=GetLeonardoNumbers(25,1,1,1);\nS:='';\nfor I:=0 to High(IA) do\n\tbegin\n\tS:=S+' '+Format('%6d',[IA[I]]);\n\tif I mod 5 = 4 then S:=S+#$0D#$0A;\n\tend;\nMemo.Lines.Add(S);\nMemo.Lines.Add('Fibonacci Numbers:');\nIA:=GetLeonardoNumbers(25,0,1,0);\nS:='';\nfor I:=0 to High(IA) do\n\tbegin\n\tS:=S+' '+Format('%6d',[IA[I]]);\n\tif I mod 5 = 4 then S:=S+#$0D#$0A;\n\tend;\nMemo.Lines.Add(S);\nend;\n\n\n","human_summarization":"The code calculates and displays the first 25 Leonardo numbers, starting from L(0). It allows customization of the first two Leonardo numbers (L(0) and L(1)) and the add number (default is 1). It also displays the first 25 Leonardo numbers when L(0) and L(1) are set to 0 and 1, and the add number is set to 0, which results in the Fibonacci sequence.","id":4060}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\nvar ErrorFlag: boolean;\nvar ErrorStr: string;\n\n\nfunction EvaluateExpression(Express: string): double;\n{ Recursive descent expression evaluator }\nvar Atom: char;\nvar ExpressStr: string;\nvar ExpressInx: integer;\nconst Tab_Char = #$09; SP_char = #$20;\n\n\tprocedure HandleError(S: string);\n\tbegin\n\tErrorStr:=S;\n\tErrorFlag:=True;\n\tAbort;\n\tend;\n\n\n\tprocedure GetChar;\n\tbegin\n\tif ExpressInx > Length(ExpressStr) then\n\t\tbegin\n\t\tAtom:= ')';\n\t\tend\n\t else\tbegin\n\t\tAtom:= ExpressStr[ExpressInx];\n\t\tInc(ExpressInx);\n\t\tend;\n\tend;\n\n\n\n\tprocedure SkipWhiteSpace;\n\t{ Skip Tabs And Spaces In Expression }\n\tbegin\n\twhile (Atom=TAB_Char) or (Atom=SP_char) do GetChar;\n\tend;\n\n\n\n\tprocedure SkipSpaces;\n\t{ Get Next Character, Ignoring Any Space Characters }\n\tbegin\n\trepeat GetChar until Atom <> SP_CHAR;\n\tend;\n\n\n\n\tfunction GetDecimal: integer;\n\t{ Read In A Decimal String And Return Its Value }\n\tvar S: string;\n\tbegin\n\tResult:=0;\n\tS:='';\n\twhile True do\n\t\tbegin\n\t\tif not (Atom in ['0'..'9']) then break;\n\t\tS:=S+Atom;\n\t\tGetChar;\n\t\tend;\n\tif S='' then HandleError('Number Expected')\n\telse Result:=StrToInt(S);\n\tif Result>9 then HandleError('Only Numbers 0..9 allowed')\n\tend;\n\n\n\tfunction Expression: double;\n\t{ Returns The Value Of An Expression }\n\n\n\n\t\tfunction Factor: double;\n\t\t{ Returns The Value Of A Factor }\n\t\tvar NEG: boolean;\n\t\tbegin\n\t\tResult:=0;\n\t\twhile Atom='+' do SkipSpaces;\t\t{ Ignore Unary \"+\" }\n\t\tNEG:= False;\n\t\twhile Atom ='-' do\t\t\t{ Unary \"-\" }\n\t\t\tbegin\n\t\t\tSkipSpaces;\n\t\t\tNEG:= not NEG;\n\t\t\tend;\n\n\t\tif (Atom>='0') and (Atom<='9') then Result:= GetDecimal\t{ Unsigned Integer }\n\t\telse case Atom of\n\t\t  '(':\tbegin\t\t\t\t{ Subexpression }\n\t\t\tSkipSpaces;\n\t\t\tResult:= Expression;\n\t\t\tif Atom<>')' then HandleError('Mismatched Parenthesis');\n\t\t\tSkipSpaces;\n\t\t\tend;\n\t\t  else\tHandleError('Syntax Error');\n\t\t  end;\n\t\t{ Numbers May Terminate With A Space Or Tab }\n\t\tSkipWhiteSpace;\n\t\tif NEG then Result:=-Result;\n\t\tend;\t{ Factor }\n\n\n\n\t\tfunction Term: double;\n\t\t{ Returns Factor * Factor, Etc. }\n\t\tvar R: double;\n\t\tbegin\n\t\tResult:= Factor;\n\t\twhile True do\n\t\t\tcase Atom of\n\t\t\t  '*':\tbegin\n\t\t\t  \tSkipSpaces;\n\t\t\t  \tResult:= Result * Factor;\n\t\t\t  \tend;\n\t\t\t  '\/':\tbegin\n\t\t\t  \tSkipSpaces;\n\t\t\t  \tR:=Factor;\n\t\t\t  \tif R=0 then HandleError('Divide By Zero');\n\t\t\t  \tResult:= Result \/ R;\n\t\t\t  \tend;\n\t\t\t  else\tbreak;\n\t\t\tend;\n\t\tend;\n\t\t{ Term }\n\n\n\n\t\tfunction AlgebraicExpression: double;\n\t\t{ Returns Term + Term, Etc. }\n\t\tbegin\n\t\tResult:= Term;\n\t\twhile True do\n\t\t\tcase Atom of\n\t\t\t  '+':\tbegin SkipSpaces; Result:= Result + Term; end;\n\t\t\t  '-':\tbegin SkipSpaces; Result:= Result - Term; end\n\t\t\telse\tbreak;\n\t\t\tend;\n\t\tend; { Algexp }\n\n\n\n\tbegin\t{ Expression }\n\tSkipWhiteSpace;\n\tResult:= AlgebraicExpression;\n\tend;\t{ Expression }\n\n\n\nbegin\t{ EvaluateExpression }\nErrorFlag:=False;\nErrorStr:='';\nExpressStr:=Express;\nExpressInx:=1;\ntry\nGetChar;\nResult:= Expression;\nexcept end;\nend;\n\n\nfunction WaitForString(Memo: TMemo; Prompt: string): string;\n{Wait for key stroke on TMemo component}\nvar MW: TMemoWaiter;\nvar C: char;\nvar Y: integer;\nbegin\n{Use custom object to wait and capture key strokes}\nMW:=TMemoWaiter.Create(Memo);\ntry\nMemo.Lines.Add(Prompt);\nMemo.SelStart:=Memo.SelStart-1;\nMemo.SetFocus;\nResult:=MW.WaitForLine;\nfinally MW.Free; end;\nend;\n\n\n\n\n\nprocedure Play24Game(Memo: TMemo);\n{Play the 24 game}\nvar R: double;\nvar Nums: array [0..4-1] of char;\nvar I: integer;\nvar Express,RS: string;\nvar RB: boolean;\n\n\tprocedure GenerateNumbers;\n\t{Generate and display four random number 1..9}\n\tvar S: string;\n\tvar I: integer;\n\tbegin\n\t{Generate random numbers}\n\tfor I:=0 to High(Nums) do\n\t Nums[I]:=char(Random(9)+$31);\n\t{Display them}\n\tS:='';\n\tfor I:=0 to High(Nums) do\n\t S:=S+' '+Nums[I];\n\tMemo.Lines.Add('Your Digits: '+S);\n\tend;\n\n\tfunction TestMatchingNums: boolean;\n\t{Make sure numbers entered by user match the target numbers}\n\tvar SL1,SL2: TStringList;\n\tvar I: integer;\n\tbegin\n\tResult:=False;\n\tSL1:=TStringList.Create;\n\tSL2:=TStringList.Create;\n\ttry\n\t{Load target numbers into string list}\n\tfor I:=0 to High(Nums) do SL1.Add(Nums[I]);\n\t{Load users expression number int string list}\n\tfor I:=1 to Length(Express) do\n\t if Express[I] in ['0'..'9'] then SL2.Add(Express[I]);\n\t{There should be the same number }\n\tif SL1.Count<>SL2.Count then exit;\n\t{Sort them to facilitate testing}\n\tSL1.Sort; SL2.Sort;\n\t{Are number identical, if not exit}\n\tfor I:=0 to SL1.Count-1 do\n\t if SL1[I]<>SL2[I] then exit;\n\t{Users numbers passed all tests}\n\tResult:=True;\n\tfinally\n\t SL2.Free;\n\t SL1.Free;\n\t end;\n\tend;\n\n\tfunction TestUserExpression(var S: string): boolean;\n\t{Test expression user entered }\n\tbegin\n\tResult:=False;\n\tif not TestMatchingNums then\n\t\tbegin\n\t\tS:='Numbers Do not Match';\n\t\texit;\n\t\tend;\n\n\tR:=EvaluateExpression(Express);\n\tS:='Expression Value = '+FloatToStrF(R,ffFixed,18,0)+CRLF;\n\tif ErrorFlag then\n\t\tbegin\n\t\tS:=S+'Expression Problem: '+ErrorStr;\n\t\texit;\n\t\tend;\n\tif R<>24 then\n\t\tbegin\n\t\tS:=S+'Expression is incorrect value';\n\t\texit;\n\t\tend;\n\tS:=S+'!!!!!! Winner\u00a0!!!!!!!';\n\tResult:=True;\n\tend;\n\n\nbegin\nRandomize;\nMemo.Lines.Add('=========== 24 Game ===========');\nGenerateNumbers;\nwhile true do\n\tbegin\n\tif Application.Terminated then exit;\n\tExpress:=WaitForString(Memo,'Enter expression, Q = quit, N = New numbers: '+CRLF);\n\tif Pos('N',UpperCase(Express))>0 then\n\t\tbegin\n\t\tGenerateNumbers;\n\t\tContinue;\n\t\tend;\n\tif Pos('Q',UpperCase(Express))>0 then exit;\n\tRB:=TestUserExpression(RS);\n\tMemo.Lines.Add(RS);\n\tif not RB then continue;\n\tRS:=WaitForString(Memo,'Play again Y=Yes, N=No'+CRLF);\n\tif Pos('N',UpperCase(RS))>0 then exit;\n\tGenerateNumbers;\n\tend;\nend;\n\n\n","human_summarization":"The code generates four random digits from 1 to 9 and prompts the user to form an arithmetic expression using all of these digits exactly once. The expression should evaluate to 24 using only addition, subtraction, multiplication, and division operations. The code checks and evaluates the user's expression, preserving remainders for division. The order of the digits in the expression does not matter. The code does not form multiple digit numbers from the supplied digits. It uses a recursive descent expression evaluator to handle any user input.","id":4061}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nprogram RunLengthTest;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils;\n\ntype\n  TRLEPair = record\n    count: Integer;\n    letter: Char;\n  end;\n\n  TRLEncoded = TArray<TRLEPair>;\n\n  TRLEncodedHelper = record helper for TRLEncoded\n  public\n    procedure Clear;\n    function Add(c: Char): Integer;\n    procedure Encode(Data: string);\n    function Decode: string;\n    function ToString: string;\n  end;\n\n{ TRLEncodedHelper }\n\nfunction TRLEncodedHelper.Add(c: Char): Integer;\nbegin\n  SetLength(self, length(self) + 1);\n  Result := length(self) - 1;\n  with self[Result] do\n  begin\n    count := 1;\n    letter := c;\n  end;\nend;\n\nprocedure TRLEncodedHelper.Clear;\nbegin\n  SetLength(self, 0);\nend;\n\nfunction TRLEncodedHelper.Decode: string;\nvar\n  p: TRLEPair;\nbegin\n  Result := '';\n  for p in Self do\n    Result := Result + string.Create(p.letter, p.count);\nend;\n\nprocedure TRLEncodedHelper.Encode(Data: string);\nvar\n  pivot: Char;\n  i, index: Integer;\nbegin\n  Clear;\n  if Data.Length = 0 then\n    exit;\n\n  pivot := Data[1];\n  index := Add(pivot);\n\n  for i := 2 to Data.Length do\n  begin\n    if pivot = Data[i] then\n      inc(self[index].count)\n    else\n    begin\n      pivot := Data[i];\n      index := Add(pivot);\n    end;\n  end;\nend;\n\nfunction TRLEncodedHelper.ToString: string;\nvar\n  p: TRLEPair;\nbegin\n  Result := '';\n  for p in Self do\n    Result := Result + p.count.ToString + p.letter;\nend;\n\nconst\n  Input = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW';\n\nvar\n  Data: TRLEncoded;\n\nbegin\n  Data.Encode(Input);\n  Writeln(Data.ToString);\n  writeln(Data.Decode);\n  Readln;\nend.\n\n\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":4062}
    {"lang_cluster":"Delphi","source_code":"\nprogram Concat;\n\n{$APPTYPE CONSOLE}\n\nvar\n  s1, s2: string;\nbegin\n  s1 := 'Hello';\n  s2 := s1 + ' literal';\n  WriteLn(s1);\n  WriteLn(s2);\nend.\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":4063}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\nfunction EncodeURL(URL: string): string;\nvar I: integer;\nbegin\nResult:='';\nfor I:=1 to Length(URL) do\n if URL[I] in ['0'..'9', 'A'..'Z', 'a'..'z'] then Result:=Result+URL[I]\n else Result:=Result+'%'+IntToHex(byte(URL[I]),2);\nend;\n\nprocedure EncodeAndShowURL(Memo: TMemo; URL: string);\nvar ES: string;\nbegin\nMemo.Lines.Add('Unencoded URL: '+URL);\nES:=EncodeURL(URL);\nMemo.Lines.Add('Encoded URL:   '+ES);\nMemo.Lines.Add('');\nend;\n\nprocedure ShowEncodedURLs(Memo: TMemo);\nbegin\nEncodeAndShowURL(Memo,'http:\/\/foo bar\/');\nEncodeAndShowURL(Memo,'https:\/\/rosettacode.org\/wiki\/URL_encoding');\nEncodeAndShowURL(Memo,'https:\/\/en.wikipedia.org\/wiki\/Pikes_Peak_granite');\nend;\n\n\n","human_summarization":"The code provides a function to convert any given string into its URL encoded representation. It converts special, control, and extended characters into a percent symbol followed by a two-digit hexadecimal code. The only exceptions are characters 0-9, A-Z, and a-z. It also allows for variations in encoding standards and the use of an exception string.","id":4064}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\n{Structure to hold the data}\n\ntype TButcherInfo = record\n Name: string;\n Weight,Cost,PerKG: double;\n end;\ntype PButcherInfo = ^TButcherInfo;\n\n{Array of actual data}\n\nvar Items: array [0..8] of TButcherInfo =(\n\t(Name: 'beef';    Weight: 3.8; Cost: 36.0),\n\t(Name: 'pork';    Weight: 5.4; Cost: 43.0),\n\t(Name: 'ham';     Weight: 3.6; Cost: 90.0),\n\t(Name: 'greaves'; Weight: 2.4; Cost: 45.0),\n\t(Name: 'flitch';  Weight: 4.0; Cost: 30.0),\n\t(Name: 'brawn';   Weight: 2.5; Cost: 56.0),\n\t(Name: 'welt';    Weight: 3.7; Cost: 67.0),\n\t(Name: 'salami';  Weight: 3.0; Cost: 95.0),\n\t(Name: 'sausage'; Weight: 5.9; Cost: 98.0)\n\t);\n\n\nfunction CompareButcher(List: TStringList; Index1, Index2: Integer): Integer;\n{Compare routine to sort by Per Kilograph cost}\nvar Info1,Info2: TButcherInfo;\nbegin\nInfo1:=PButcherInfo(List.Objects[Index1])^;\nInfo2:=PButcherInfo(List.Objects[Index2])^;\nResult:=Trunc(Info2.PerKG * 100 - Info1.PerKG * 100);\nend;\n\n\nprocedure KnapsackProblem(Memo: TMemo);\n{Solve the knapsack problem}\nvar SL: TStringList;\nvar I,Inx: integer;\nvar Info: TButcherInfo;\nvar Weight,Cost,Diff: double;\nconst Limit = 15;\nbegin\nSL:=TStringList.Create;\ntry\n{Calculate the per Kilogram cost for each item}\nfor I:=0 to High(Items) do\n\tbegin\n\tItems[I].PerKG:=Items[I].Cost\/Items[I].Weight;\n\tSL.AddObject(Items[I].Name,@Items[I]);\n\tend;\n{Sort most expensive items to top of list}\nSL.CustomSort(CompareButcher);\n\n{Take the most expensive items }\nWeight:=0; Cost:=0;\nfor I:=0 to SL.Count-1 do\n\tbegin\n\tInfo:=PButcherInfo(SL.Objects[I])^;\n\t{Item exceeds the weight limit? }\n\tif (Weight+Info.Weight)>=Limit then\n\t\tbegin\n\t\t{Calculate percent to fill gap}\n\t\tDiff:=(Limit-Weight)\/Info.Weight;\n\t\t{Save index}\n\t\tInx:=I;\n\t\tbreak;\n\t\tend\n\telse\n\t\tbegin\n\t\t{Add up totals}\n\t\tWeight:=Weight+Info.Weight;\n\t\tCost:=Cost+Info.Cost;\n\t\tend;\n\tend;\n\n{Display all items}\nMemo.Lines.Add('Item      Portion    Value');\nMemo.Lines.Add('--------------------------');\nfor I:=0 to Inx-1 do\n\tbegin\n\tInfo:=PButcherInfo(SL.Objects[I])^;\n\tMemo.Lines.Add(Format('%-8s %8.2f %8.2f',[Info.Name,Info.Weight,Info.Cost]));\n\tend;\nInfo:=PButcherInfo(SL.Objects[Inx])^;\n{Calculate cost and weight to fill gap}\nweight:=Weight+Info.Weight*Diff;\nCost:=Cost+Info.Cost*Diff;\n{Display gap filling item}\nMemo.Lines.Add(Format('%-8s %8.2f %8.2f',[Info.Name,Info.Weight*Diff,Info.Cost*Diff]));\nMemo.Lines.Add('--------------------------');\nMemo.Lines.Add(Format('Totals   %8.2f %8.2f',[Weight,Cost]));\nfinally SL.Free; end;\nend;\n\n\n","human_summarization":"\"Determines the optimal selection of items from a butcher's shop for a thief to maximize profit without exceeding a 15 kg weight limit, considering the possibility of cutting items proportionally to their original price.\"","id":4065}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  System.Classes\nLibrary:  System.Diagnostics\nprogram AnagramsTest;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n  System.SysUtils,\n  System.Classes,\n  System.Diagnostics;\n\nfunction Sort(s: string): string;\nvar\n  c: Char;\n  i, j, aLength: Integer;\nbegin\n  aLength := s.Length;\n\n  if aLength = 0 then\n    exit('');\n\n  Result := s;\n\n  for i := 1 to aLength - 1 do\n    for j := i + 1 to aLength do\n      if result[i] > result[j] then\n      begin\n        c := result[i];\n        result[i] := result[j];\n        result[j] := c;\n      end;\nend;\n\nfunction IsAnagram(s1, s2: string): Boolean;\nbegin\n  if s1.Length <> s2.Length then\n    exit(False);\n\n  Result := Sort(s1) = Sort(s2);\n\nend;\n\nfunction Split(s: string; var Count: Integer; var words: string): Boolean;\nvar\n  sCount: string;\nbegin\n  sCount := s.Substring(0, 4);\n  words := s.Substring(5);\n  Result := TryStrToInt(sCount, Count);\nend;\n\nfunction CompareLength(List: TStringList; Index1, Index2: Integer): Integer;\nbegin\n  result := List[Index1].Length - List[Index2].Length;\n  if Result = 0 then\n    Result := CompareText(Sort(List[Index2]), Sort(List[Index1]));\nend;\n\nvar\n  Dict: TStringList;\n  i, j, Count, MaxCount, WordLength, Index: Integer;\n  words: string;\n  StopWatch: TStopwatch;\n\nbegin\n  StopWatch := TStopwatch.Create;\n  StopWatch.Start;\n\n  Dict := TStringList.Create();\n  Dict.LoadFromFile('unixdict.txt');\n\n  Dict.CustomSort(CompareLength);\n\n  Index := 0;\n  words := Dict[Index];\n  Count := 1;\n\n  while Index + Count < Dict.Count do\n  begin\n    if IsAnagram(Dict[Index], Dict[Index + Count]) then\n    begin\n      words := words + ',' + Dict[Index + Count];\n      Dict[Index + Count] := '';\n      inc(Count);\n    end\n    else\n    begin\n      Dict[Index] := format('%.4d', [Count]) + ',' + words;\n      inc(Index, Count);\n      words := Dict[Index];\n      Count := 1;\n    end;\n  end;\n\n  \/\/ The last one not match any one\n  if not Dict[Dict.count - 1].IsEmpty then\n    Dict.Delete(Dict.count - 1);\n\n  Dict.Sort;\n\n  while Dict[0].IsEmpty do\n    Dict.Delete(0);\n\n  StopWatch.Stop;\n\n  Writeln(Format('Time pass: %d ms [i7-4500U Windows 7]', [StopWatch.ElapsedMilliseconds]));\n\n  Split(Dict[Dict.count - 1], MaxCount, words);\n  writeln(#10'The anagrams that contain the most words, has ', MaxCount, ' words:'#10);\n  writeln('Words found:'#10);\n\n  Writeln('  ', words);\n\n  for i := Dict.Count - 2 downto 0 do\n  begin\n    Split(Dict[i], Count, words);\n    if Count = MaxCount then\n      Writeln('  ', words)\n    else\n      Break;\n  end;\n\n  Dict.Free;\n  Readln;\nend.\n\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":4066}
    {"lang_cluster":"Delphi","source_code":"\nprogram SierpinskiCarpet;\n\nuses\n  Math;\n\nfunction In_carpet(a, b: longint): boolean;\nvar\n  x, y: longint;\nbegin\n  x := a;\n  y := b;\n  while true do\n  begin\n    if (x = 0) or (y = 0) then\n    begin\n      In_carpet := true;\n      break;\n    end\n    else if ((x mod 3) = 1) and ((y mod 3) = 1) then\n    begin\n      In_carpet := false;\n      break;\n    end;\n    x := x div 3;\n    y := y div 3;\n  end;\nend;\n\nprocedure Carpet(n: integer);\nvar\n  i, j, limit: longint;\nbegin\n{$IFDEF FPC}\n  limit := 3 *  * n - 1;\n{$ELSE}\n  limit := Trunc(IntPower(3, n) - 1);\n{$ENDIF}\n\n  for i := 0 to limit do\n  begin\n    for j := 0 to limit do\n      if In_carpet(i, j) then\n        write('*')\n      else\n        write(' ');\n    writeln;\n  end;\nend;\n\nbegin\n  Carpet(3);\n  {$IFNDEF UNIX}      readln; {$ENDIF}\nend.\n","human_summarization":"generate an ASCII-art or graphical representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the placement of these characters being the crucial requirement. The '#' character is used as an example, but is not strictly necessary.","id":4067}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 5.0\n\n-- begin file --\n\n   Program SingleWinApp ;\n \n   \/\/ This is the equivalent of the C #include\n   Uses Forms, Windows, Messages, Classes, Graphics, Controls, StdCtrls ;\n\n   \n   type\n     \n     \/\/ The only reason for this declaration is to allow the connection of the\n     \/\/ on click method to the forms button object. This class declaration adds\n     \/\/ a procedure.\n\n     TMainForm class(tform) \n       Procedure AddClicks(sender : tObject);\n     end;\n\n\n   \/\/ Use these globals.  \n   var\n  \n     MainForm : tForm ;\n     aLabel   : tLabel ;\n     aButton  : tButton ;\n     i        : integer = 0 ;\n\n\n    \/\/ This is the Method call that we connect to the button object\n    \/\/ to start counting the clicks.\n    Procedure tMainForm.AddClicks(sender :tObject)\n    begin\n      inc(i);\n      aLabel.Caption := IntToStr(i) + ' Clicks since startup' ;\n    end;\n\n\n    Begin\n      \/\/ Do all the behind the scenes stuff that sets up the Windows environment \n      Application.Initialize ;\n\n      \/\/ Create the form\n      \n      \/\/ Forms can either be created with an owner, like I have done here, or with\n      \/\/ the owner set to Nil. In pascal (all versions of Borland) '''NIL''' is a\n      \/\/ reserved, (the equivalent of '''NULL''' in Ansi C) word and un-sets any pointer \n      \/\/ variable. Setting the owner to the application object will ensure that the form is\n      \/\/ freed by the application object when the application shuts down. If I had set\n      \/\/ the owner to NIL then i would have had to make sure I freed the form explicitly\n      \/\/ or it would have been orphaned, thus creating a memory leak.\n\n      \/\/ I must direct your attention to the CreateNew constructor.  This is \n      \/\/ a non standard usage.  Normally the constructor Create() will call this\n      \/\/ as part of the initialization routine for the form. Normally as you drop\n      \/\/ various components on a form in deign mode, a DFM file is created with \n      \/\/ all the various initial states of the controls. This bypasses the \n      \/\/ DFM file altogether although all components AND the form are created\n      \/\/ with default values. (see the Delphi help file).\n\n      MainForm          := tMainForm.CreateNew(Application);\n      MainForm.Parent   := Application ;\n      MainForm.Position := poScreenCenter ;\n      MainForm.Caption  := 'Single Window Application' ;\n\n      \/\/ Create the Label, set its owner as MaiaForm\n      aLabel          := tLabel.Create(mainForm);\n      aLabel.Parent   := MainForm;\n      aLabel.Caption  := IntToStr(i) + ' Clicks since startup' ;\n      aLabel.Left     := 20 ;\n      aLabel.Top      := MainForm.ClientRect.Bottom div 2 ;\n\n      \/\/ Create the button, set its owner to MainForm\n      aButton         := tButton.Create(MainForm);\n      aButton.Parent  := MainForm ;\n      aButton.Caption := 'Click Me!';\n      aButton.Left    := (MainForm.ClientRect.Right div 2)-(aButton.Width div 2 );\n      aButton.Top     := MainForm.ClientRect.Bottom - aButton.Height - 10 ;\n      aButton.OnClick := AddClicks ;\n\n      \/\/ Show the main form, Modaly. The ONLY reason to do this is because in this\n      \/\/ demonstration if you only call the SHOW method, the form will appear and\n      \/\/ disappear in a split second.\n      MainForm.ShowModal ;\n      \n      Application.Run ;\n\n   end. \/\/ Program\n\n","human_summarization":"The code creates a simple windowed application in Delphi that includes a label and a button. Initially, the label displays \"There have been no clicks yet\", and the button displays \"click me\". When the button is clicked, the label updates to show the number of times the button has been clicked. The application is dynamically created from the main program file, SingleWinApp.dpr. The project can be built either through the IDE or the command line compiler.","id":4068}
    {"lang_cluster":"Delphi","source_code":"\nfor i := 10 downto 0 do\n  writeln(i);\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":4069}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\nfunction UpperAlphaOnly(S: string): string;\n{Remove all }\nvar I: integer;\nbegin\nResult:='';\nS:=UpperCase(S);\nfor I:=1 to Length(S) do\nif S[I] in ['A'..'Z'] then Result:=Result+S[I];\nend;\n\n\nfunction VigenereEncrypt(Text, Key: string): string;\n{Encrypt Text using specified key}\nvar KInx,TInx,I: integer;\nvar TC: byte;\nbegin\nResult:='';\n{Force Text and Key upper case}\nText:=UpperAlphaOnly(Text);\nKey:=UpperAlphaOnly(Key);\n{Point to first Key-character}\nKInx:=1;\nfor I:=1 to Length(Text) do\n\tbegin\n\t{Offset Text-char by key-char amount}\n\tTC:=byte(Text[I])-byte('A')+Byte(Key[KInx]);\n\t{if it is shifted past \"Z\", wrap back around past \"A\"}\n\tif TC>Byte('Z') then TC:=byte('@')+(TC-Byte('Z'));\n\t{Store in output string}\n\tResult:=Result+Char(TC);\n\t{Point to next Key-char}\n\tInc(Kinx);\n\t{If index post end of key, start over}\n\tif KInx>Length(Key) then KInx:=1;\n\tend;\nend;\n\n\nfunction VigenereDecrypt(Text, Key: string): string;\n{Encrypt Text using specified key}\nvar KInx,TInx,I: integer;\nvar TC: byte;\nbegin\nResult:='';\n{For Key and text uppercase}\nText:=UpperAlphaOnly(Text);\nKey:=UpperAlphaOnly(Key);\nKInx:=1;\nfor I:=1 to Length(Text) do\n\tbegin\n\t{subtrack key-char from text-char}\n\tTC:=byte(Text[I])-Byte(Key[Kinx])+Byte('A');\n\t{if result below \"A\" wrap back around to \"Z\"}\n\tif TC<Byte('A') then TC:=(byte('Z')-((Byte('A')-TC)))+1;\n\t{store in result}\n\tResult:=Result+Char(TC);\n\t{Point to next key char}\n\tInc(Kinx);\n\t{Past the end, start over}\n\tif KInx>Length(Key) then KInx:=1;\n\tend;\nend;\n\nconst TestKey = 'VIGENERECIPHER';\nconst TestStr = 'Beware the Jabberwock, my son! The jaws that bite, the claws that catch!';\n\n\nprocedure VigenereCipher(Memo: TMemo);\nvar S: string;\nbegin\n{Show plain text}\nMemo.Lines.Add(TestStr);\nS:=VigenereEncrypt(TestStr, TestKey);\n{Show encrypted text}\nMemo.Lines.Add(S);\nS:=VigenereDecrypt(S, TestKey);\n{Show decrypted text}\nMemo.Lines.Add(S);\nend;\n\n\n","human_summarization":"Implement and decrypt a Vigen\u00e8re cipher, accommodating keys and text of varying lengths, capitalizing all text, and discarding non-alphabetic characters.","id":4070}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram LoopWithStep;\n \n{$APPTYPE CONSOLE}\n \nvar\n  i: Integer;\nbegin\n  i:=2;\n  while i <= 8 do begin\n    WriteLn(i);\n    Inc(i, 2);\n  end;\nend.\n\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one, using a simulated While loop due to Delphi's For loop not supporting a step value.","id":4071}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\ntype TTerm = function(i: integer): real;\n\nfunction Term(I: integer): double;\nbegin\nTerm := 1 \/ I;\nend;\n\n\nfunction Sum(var I: integer; Lo, Hi: integer; Term: TTerm): double;\nbegin\nResult := 0;\nI := Lo;\nwhile I <= Hi do\n\tbegin\n\tResult := Result + Term(I);\n\tInc(I);\n\tend;\nend;\n\n\nprocedure ShowJensenDevice(Memo: TMemo);\nvar I: LongInt;\nbegin\nMemo.Lines.Add(FloatToStrF(Sum(I, 1, 100, @Term), ffFixed,18,15));\nend;\n\n\n","human_summarization":"The code implements Jensen's Device, a technique in computer programming that exploits call by name. It calculates the 100th harmonic number by passing parameters by name to a sum procedure. The sum procedure iteratively adds terms, re-evaluating the passed expression in the caller's context each time. The result is dependent on the re-evaluation of the actual parameter in the caller's context. The code also demonstrates the importance of passing the first parameter by name or reference for visibility of changes in the caller's context.","id":4072}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: Windows,Types,ExtCtrls,Graphics\n\nprocedure MunchingSquares(Image: TImage);\n{XOR's X and Y to select an RGB level}\nvar W,H,X,Y: integer;\nbegin\nW:=Image.Width;\nH:=Image.Height;\nfor Y:=0 to Image.Height-1 do\n for X:=0 to Image.Width-1 do\n\tbegin\n\tImage.Canvas.Pixels[X,Y]:=RGB(0,X xor Y,0);\n\tend;\nend;\n\n\n","human_summarization":"generate a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, as described in the Munching Squares programming task.","id":4073}
    {"lang_cluster":"Delphi","source_code":"\nprogram MazeGen_Rosetta;\n\n{$APPTYPE CONSOLE}\n\nuses System.SysUtils, System.Types, System.Generics.Collections, System.IOUtils;\n\ntype\n  TMCell = record\n    Visited  : Boolean;\n    PassTop  : Boolean;\n    PassLeft : Boolean;\n  end;\n  TMaze  = array of array of TMCell;\n  TRoute = TStack<TPoint>;\n\nconst\n  mwidth  = 24;\n  mheight = 14;\n\nprocedure ClearVisited(var AMaze: TMaze);\nvar\n  x, y: Integer;\nbegin\n  for y := 0 to mheight - 1 do\n    for x := 0 to mwidth - 1 do\n      AMaze[x, y].Visited := False;\nend;\n\nprocedure PrepareMaze(var AMaze: TMaze);\nvar\n  Route    : TRoute;\n  Position : TPoint;\n  d        : Integer;\n  Pool     : array of TPoint; \/\/ Pool of directions to pick randomly from\nbegin\n  SetLength(AMaze, mwidth, mheight);\n  ClearVisited(AMaze);\n  Position := Point(Random(mwidth), Random(mheight));\n  Route := TStack<TPoint>.Create;\n  try\n    with Position do\n    while True do\n    begin\n      repeat\n        SetLength(Pool, 0);\n        if (y > 0)         and not AMaze[x, y-1].Visited then Pool := Pool + [Point(0, -1)];\n        if (x < mwidth-1)  and not AMaze[x+1, y].Visited then Pool := Pool + [Point(1,  0)];\n        if (y < mheight-1) and not AMaze[x, y+1].Visited then Pool := Pool + [Point(0,  1)];\n        if (x > 0)         and not AMaze[x-1, y].Visited then Pool := Pool + [Point(-1, 0)];\n\n        if Length(Pool) = 0 then \/\/ no direction to draw from\n        begin\n          if Route.Count = 0 then Exit; \/\/ and we are back at start so this is the end\n          Position := Route.Pop;\n        end;\n      until Length(Pool) > 0;\n\n      d := Random(Length(Pool));\n      Offset(Pool[d]);\n\n      AMaze[x, y].Visited := True;\n      if Pool[d].y = -1 then AMaze[x, y+1].PassTop  := True; \/\/ comes from down to up ( ^ )\n      if Pool[d].x =  1 then AMaze[x, y].PassLeft   := True; \/\/ comes from left to right ( --> )\n      if Pool[d].y =  1 then AMaze[x, y].PassTop    := True; \/\/ comes from left to right ( v )\n      if Pool[d].x = -1 then AMaze[x+1, y].PassLeft := True; \/\/ comes from right to left ( <-- )\n      Route.Push(Position);\n    end;\n  finally\n    Route.Free;\n  end;\nend;\n\nfunction MazeToString(const AMaze: TMaze; const S, E: TPoint): String; overload;\nvar\n  x, y: Integer;\n  v   : Char;\nbegin\n  Result := '';\n  for y := 0 to mheight - 1 do\n  begin\n    for x := 0 to mwidth - 1 do\n      if AMaze[x, y].PassTop then Result := Result + '+'#32#32#32 else Result := Result + '+---';\n    Result := Result + '+' + sLineBreak;\n    for x := 0 to mwidth - 1 do\n    begin\n      if S = Point(x, y) then v := 'S' else\n        if E = Point(x, y) then v := 'E' else\n          v := #32'*'[Ord(AMaze[x, y].Visited) + 1];\n\n      Result := Result + '|'#32[Ord(AMaze[x, y].PassLeft) + 1] + #32 + v + #32;\n    end;\n    Result := Result + '|' + sLineBreak;\n  end;\n  for x := 0 to mwidth - 1 do Result := Result + '+---';\n  Result := Result + '+' + sLineBreak;\nend;\n\nprocedure Main;\nvar\n  Maze: TMaze;\nbegin\n  Randomize;\n  PrepareMaze(Maze);\n  ClearVisited(Maze);     \/\/ show no route\n  Write(MazeToString(Maze, Point(-1, -1), Point(-1, -1)));\n  ReadLn;\nend;\n\nbegin\n  Main;\n\nend.\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":4074}
    {"lang_cluster":"Delphi","source_code":"\nunit Pi_BBC_Main;\n\ninterface\n\nuses\n  Classes, Controls, Forms, Dialogs, StdCtrls;\n\ntype\n  TForm1 = class(TForm)\n    btnRunSpigotAlgo: TButton;\n    memScreen: TMemo;\n    procedure btnRunSpigotAlgoClick(Sender: TObject);\n    procedure FormCreate(Sender: TObject);\n  private\n    fScreenWidth : integer;\n    fLineBuffer : string;\n    procedure ClearText();\n    procedure AddText( const s : string);\n    procedure FlushText();\n  end;\n\nvar\n  Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nuses SysUtils;\n\n\/\/ Button clicked to run algorithm\nprocedure TForm1.btnRunSpigotAlgoClick(Sender: TObject);\nvar\n  \/\/ BBC Basic variables. Delphi longint is 32 bits.\n  B : array of longint;\n  A, C, D, E, I, L, M, P : longint;\n  \/\/ Added for Delphi version\n  temp : string;\n  h, j, t : integer;\nbegin\n  fScreenWidth := 80;\n  ClearText();\n  M := 5368709; \/\/ floor( (2^31 - 1)\/400 )\n\n  \/\/ DIM B%(M%) in BBC Basic declares an array [0..M%], i.e. M% + 1 elements\n  SetLength( B, M + 1);\n  for I := 0 to M do B[I] := 20;\n  E := 0;\n  L := 2;\n\n  \/\/ FOR C% = M% TO 14 STEP -7\n  \/\/ In Delphi (or at least Delphi 7) the step size in a for loop has to be 1.\n  \/\/ So the BBC Basic FOR loop has been replaced by a repeat loop.\n  C := M;\n  repeat\n    D := 0;\n    A := C*2 - 1;\n    for P := C downto 1 do begin\n      D := D*P + B[P]*$64; \/\/ hex notation copied from BBC version\n      B[P] := D mod A;\n      D := D div A;\n      dec( A, 2);\n    end;\n\n    \/\/ The BBC CASE statement here amounts to a series of if ... else\n    if (D = 99) then begin\n      E := E*100 + D;\n      inc( L, 2);\n    end\n    else if (C = M) then begin\n      AddText( SysUtils.Format( '%2.1f', [1.0*(D div 100) \/ 10.0] ));\n      E := D mod 100;\n    end\n    else begin\n      \/\/ PRINT RIGHT$(STRING$(L%,\"0\") + STR$(E% + D% DIV 100),L%);\n      \/\/ This can't be done so concisely in Delphi 7\n      SetLength( temp, L);\n      for j := 1 to L do temp[j] := '0';\n      temp := temp + SysUtils.IntToStr( E + D div 100);\n      t := Length( temp);\n      AddText( Copy( temp, t - L + 1, L));\n      E := D mod 100;\n      L := 2;\n    end;\n    dec( C, 7);\n  until (C < 14);\n  FlushText();\n\n  \/\/ Delphi addition: Write screen output to a file for checking\n  h := SysUtils.FileCreate( 'C:\\Delphi\\PiDigits.txt'); \/\/ h = file handle\n  for j := 0 to memScreen.Lines.Count - 1 do\n    SysUtils.FileWrite( h, memScreen.Lines[j][1], Length( memScreen.Lines[j]));\n  SysUtils.FileClose( h);\nend;\n\n{=========================== Auxiliary routines ===========================}\n\n\/\/ Form created\nprocedure TForm1.FormCreate(Sender: TObject);\nbegin\n  fScreenWidth := 80; \/\/ in case not set by the algotithm\n  ClearText();\nend;\n\n\/\/ This Delphi version builds each screen line in a buffer and puts\n\/\/   the line into the TMemo when the buffer is full.\n\/\/ This is faster than writing to the TMemo a few characters at a time,\n\/\/   but note that the buffer must be flushed at the end of the program.\nprocedure TForm1.ClearText();\nbegin\n  memScreen.Lines.Clear();\n  fLineBuffer := '';\nend;\n\nprocedure TForm1.AddText( const s : string);\nvar\n  nrChars, nrLeft : integer;\nbegin\n  nrChars := Length( s);\n  nrLeft := fScreenWidth - Length( fLineBuffer); \/\/ nr chars left in line\n  if (nrChars <= nrLeft) then fLineBuffer := fLineBuffer + s\n  else begin\n    fLineBuffer := fLineBuffer + Copy( s, 1, nrLeft);\n    memScreen.Lines.Add( fLineBuffer);\n    fLineBuffer := Copy( s, nrLeft + 1, nrChars - nrLeft);\n  end;\nend;\n\nprocedure TForm1.FlushText();\nbegin\n  if (Length(fLineBuffer) > 0) then begin\n    memScreen.Lines.Add( fLineBuffer);\n    fLineBuffer := '';\n  end;\nend;\n\nend.\n\n\n","human_summarization":"The code continuously calculates and outputs the successive decimal digits of Pi, starting from 3.14159265. The calculation process continues indefinitely until manually stopped by the user. The number of digits calculated is determined by the variable M, with the output written to a disk file. The code is a translation from the original BBC micro code and has been tested for accuracy up to 1,533,913 decimal places.","id":4075}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  System.Generics.Defaults\nprogram Order_two_numerical_lists;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils,\n  System.Generics.Defaults;\n\ntype\n  TArray = record\n    class function LessOrEqual<T>(first, second: TArray<T>): Boolean; static;\n  end;\n\nclass function TArray.LessOrEqual<T>(first, second: TArray<T>): Boolean;\nbegin\n  if Length(first) = 0 then\n    exit(true);\n  if Length(second) = 0 then\n    exit(false);\n  var comp := TComparer<T>.Default.Compare(first[0], second[0]);\n  if comp = 0 then\n    exit(LessOrEqual(copy(first, 1, length(first)), copy(second, 1, length(second))));\n  Result := comp < 0;\nend;\n\nbegin\n  writeln(TArray.LessOrEqual<Integer>([1, 2, 3], [2, 3, 4]));\n  writeln(TArray.LessOrEqual<Integer>([2, 3, 4], [1, 2, 3]));\n  writeln(TArray.LessOrEqual<Integer>([1, 2], [1, 2, 3]));\n  writeln(TArray.LessOrEqual<Integer>([1, 2, 3], [1, 2]));\n  writeln(TArray.LessOrEqual<Char>(['a', 'c', 'b'], ['a', 'b', 'b']));\n  writeln(TArray.LessOrEqual<string>(['this', 'is', 'a', 'test'], ['this', 'is',\n    'not', 'a', 'test']));\n  readln;\nend.\n\n\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second and false otherwise.\"","id":4076}
    {"lang_cluster":"Delphi","source_code":"\nfunction Ackermann(m,n:Int64):Int64;\nbegin\n    if m = 0 then\n        Result := n + 1\n    else if n = 0 then\n        Result := Ackermann(m-1, 1)\n    else\n        Result := Ackermann(m-1, Ackermann(m, n - 1));\nend;\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":4077}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtils\nLibrary:  System.Mathprogram Gamma_function;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils,\n  System.Math;\n\nfunction lanczos7(z: double): Double;\nbegin\n  var t := z + 6.5;\n  var x := 0.99999999999980993 + 676.5203681218851 \/ z - 1259.1392167224028 \/ (z\n    + 1) + 771.32342877765313 \/ (z + 2) - 176.61502916214059 \/ (z + 3) +\n    12.507343278686905 \/ (z + 4) - 0.13857109526572012 \/ (z + 5) +\n    9.9843695780195716e-6 \/ (z + 6) + 1.5056327351493116e-7 \/ (z + 7);\n\n  Result := Sqrt(2) * Sqrt(pi) * Power(t, z - 0.5) * exp(-t) * x;\nend;\n\nbegin\n  var xs: TArray<double> := [-0.5, 0.1, 0.5, 1, 1.5, 2, 3, 10, 140, 170];\n  writeln('    x              Lanczos7');\n  for var x in xs do\n    writeln(format('%5.1f %24.16g', [x, lanczos7(x)]));\n  readln;\nend.\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":4078}
    {"lang_cluster":"Delphi","source_code":"\nLibrary:  System.SysUtilsprogram N_queens_problem;\n\n{$APPTYPE CONSOLE}\n\nuses\n  System.SysUtils;\n\nvar\n  i: Integer;\n  q: boolean;\n  a: array[0..8] of boolean;\n  b: array[0..16] of boolean;\n  c: array[0..14] of boolean;\n  x: array[0..8] of Integer;\n\nprocedure TryMove(i: Integer);\nbegin\n  var j := 1;\n  while True do\n  begin\n    q := false;\n    if a[j] and b[i + j] and c[i - j + 7] then\n    begin\n      x[i] := j;\n      a[j] := false;\n      b[i + j] := false;\n      c[i - j + 7] := false;\n\n      if i < 8 then\n      begin\n        TryMove(i + 1);\n        if not q then\n        begin\n          a[j] := true;\n          b[i + j] := true;\n          c[i - j + 7] := true;\n        end;\n      end\n      else\n        q := true;\n    end;\n    if q or (j = 8) then\n      Break;\n    inc(j);\n  end;\nend;\n\nbegin\n  for i := 1 to 8 do\n    a[i] := true;\n\n  for i := 2 to 16 do\n    b[i] := true;\n\n  for i := 0 to 14 do\n    c[i] := true;\n\n  TryMove(1);\n\n  if q then\n    for i := 1 to 8 do\n      writeln(i, ' ', x[i]);\n  readln;\nend.\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":4079}
    {"lang_cluster":"Delphi","source_code":"\n\n\/\/ This example works on stuff as old as Delphi 5 (maybe older)\n\/\/ Modern Delphi \/ Object Pascal has both \n\/\/   \u2022 generic types\n\/\/   \u2022 the ability to concatenate arrays with the '+' operator\n\/\/ So I could just say:\n\/\/   myarray\u00a0:= [1] + [2, 3];\n\/\/ But if you do not have access to the latest\/greatest, then:\n{$apptype console}\n\ntype \n  \/\/ Array types must be declared in order to return them from functions\n  \/\/ They can also be used with open array parameters.\n  TArrayOfString = array of string;\n\nfunction Concat( a, b : array of string ): TArrayOfString; overload;\n{\n  Every array type needs its own 'Concat' function:\n    function Concat( a, b\u00a0: array of integer ): TArrayOfInteger; overload;\n    function Concat( a, b\u00a0: array of double  ): TArrayOfDouble;  overload;\n    etc\n  Also, dynamic and open array types ALWAYS start at 0. No need to complicate indexing here.\n}\nvar\n  n : Integer;\nbegin\n  SetLength( result, Length(a)+Length(b) );\n  for n := 0 to High(a) do result[          n] := a[n];\n  for n := 0 to High(b) do result[Length(a)+n] := b[n]\nend;\n\n\/\/ Example time!\nfunction Join( a : array of string; sep : string = ' ' ): string;\nvar\n  n : integer;\nbegin\n  if Length(a) > 0 then result := a[0];\n  for n := 1 to High(a) do result := result + sep + a[n]\nend;\n\nvar\n  names : TArrayOfString;\nbegin\n  \/\/ Here we use the open array parameter constructor as a convenience\n  names := Concat( ['Korra', 'Asami'], ['Bolin', 'Mako'] );\n  WriteLn( Join(names) );\n\n  \/\/ Also convenient: open array parameters are assignment-compatible with our array type!\n  names := Concat( names, ['Varrick', 'Zhu Li'] );\n  WriteLn( #13#10, Join(names, ', ') );\n  \n  names := Concat( ['Tenzin'], names );\n  Writeln( #13#10, Join(names, #13#10 ) );\nend.\n\n\nKorra Asami Bolin Mako\n\nKorra, Asami, Bolin, Mako, Varrick, Zhu Li\n\nTenzin\nKorra\nAsami\nBolin\nMako\nVarrick\nZhu Li\n\n\ntype\n  TReturnArray = array of integer; \/\/you need to define a type to be able to return it\n\nfunction ConcatArray(a1,a2:array of integer):TReturnArray;\nvar\n  i,r:integer;\nbegin\n  { Low(array) is not necessarily 0 }\n  SetLength(result,High(a1)-Low(a1)+High(a2)-Low(a2)+2); \/\/BAD idea to set a length you won't release, just to show the idea!\n  r:=0; \/\/index on the result may be different to indexes on the sources\n  for i := Low(a1) to High(a1) do begin\n    result[r] := a1[i];\n    Inc(r);\n  end;\n  for i := Low(a2) to High(a2) do begin\n    result[r] := a2[i];\n    Inc(r);\n  end;\nend;\n\nprocedure TForm1.Button1Click(Sender: TObject);\nvar\n  a1,a2:array of integer;\n  r1:array of integer;\n  i:integer;\nbegin\n  SetLength(a1,4);\n  SetLength(a2,3);\n  for i := Low(a1) to High(a1) do\n    a1[i] := i;\n  for i := Low(a2) to High(a2) do\n    a2[i] := i;\n  TReturnArray(r1) := ConcatArray(a1,a2);\n  for i := Low(r1) to High(r1) do\n    showMessage(IntToStr(r1[i]));\n  Finalize(r1); \/\/IMPORTANT!\n  ShowMessage(IntToStr(High(r1)));\nend;\n\n","human_summarization":"demonstrate how to concatenate two arrays in the given programming language. The process may be as simple as using array1 + array2. The code also includes older content with commentary about memory management, specifically noting that Delphi handles dynamic array memory effectively.","id":4080}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\n{Item to store data in}\n\ntype TPackItem = record\n Name: string;\n Weight,Value: integer;\n end;\n\n{List of items, weights and values}\n\nconst ItemsList: array [0..21] of TPackItem = (\n   (Name: 'map'; Weight: 9; Value: 150),\n   (Name: 'compass'; Weight: 13; Value: 35),\n   (Name: 'water'; Weight: 153; Value: 200),\n   (Name: 'sandwich'; Weight: 50; Value: 160),\n   (Name: 'glucose'; Weight: 15; Value: 60),\n   (Name: 'tin'; Weight: 68; Value: 45),\n   (Name: 'banana'; Weight: 27; Value: 60),\n   (Name: 'apple'; Weight: 39; Value: 40),\n   (Name: 'cheese'; Weight: 23; Value: 30),\n   (Name: 'beer'; Weight: 52; Value: 10),\n   (Name: 'suntan cream'; Weight: 11; Value: 70),\n   (Name: 'camera'; Weight: 32; Value: 30),\n   (Name: 't-shirt'; Weight: 24; Value: 15),\n   (Name: 'trousers'; Weight: 48; Value: 10),\n   (Name: 'umbrella'; Weight: 73; Value: 40),\n   (Name: 'waterproof trousers'; Weight: 42; Value: 70),\n   (Name: 'waterproof overclothes'; Weight: 43; Value: 75),\n   (Name: 'note-case'; Weight: 22; Value: 80),\n   (Name: 'sunglasses'; Weight: 7; Value: 20),\n   (Name: 'towel'; Weight: 18; Value: 12),\n   (Name: 'socks'; Weight: 4; Value: 50),\n   (Name: 'book'; Weight: 30; Value: 10));\n\n{Iterater object to step through all the indices\n{ corresponding to the bits in \"N\". This is used }\n{ step through all the combinations of items }\n\ntype TBitIterator = class(TObject)\n private\n   FNumber,FIndex: integer;\n public\n  procedure Start(StartNumber: integer);\n  function Next(var Index: integer): boolean;\n end;\n\nprocedure TBitIterator.Start(StartNumber: integer);\n{Set the starting value of the number }\nbegin\nFNumber:=StartNumber;\nend;\n\n\nfunction TBitIterator.Next(var Index: integer): boolean;\n{Return the next available index}\nbegin\nResult:=False;\nwhile FNumber>0 do\n\tbegin\n\tResult:=(FNumber and 1)=1;\n\tif Result then Index:=FIndex;\n\tFNumber:=FNumber shr 1;\n\tInc(FIndex);\n\tif Result then break;\n\tend;\nend;\n\n{=============================================================================}\n\n\nprocedure GetSums(N: integer; var Weight,Value: integer);\n{Iterate through all indices corresponding to N}\n{Get get the sum of their values}\nvar Inx: integer;\nvar BI: TBitIterator;\nbegin\nBI:=TBitIterator.Create;\ntry\nBI.Start(N);\nWeight:=0; Value:=0;\nwhile BI.Next(Inx) do\n\tbegin\n\tWeight:=Weight+ItemsList[Inx].Weight;\n\tValue:=Value+ItemsList[Inx].Value;\n\tend;\nfinally BI.Free; end;\nend;\n\n\n\nprocedure DoKnapsackProblem(Memo: TMemo);\n{Find optimized solution to Knapsack problem}\n{By iterating through all binary combinations}\nvar I,J,Inx: integer;\nvar Max: integer;\nvar WeightSum,ValueSum: integer;\nvar BestValue,BestIndex,BestWeight: integer;\nvar S: string;\nvar BI: TBitIterator;\nbegin\nBI:=TBitIterator.Create;\ntry\n{Get value that will cover all binary combinations}\nMax:=1 shl Length(ItemsList)-1;\nBestValue:=0;\n{Iterate through all combinations of bits}\nfor I:=1 to Max do\n\tbegin\n\t{Get the sum of the weights and values}\n\tGetSums(I,WeightSum,ValueSum);\n\t{Ignore any weight greater than 400}\n\tif WeightSum>400 then continue;\n\t{Test if this is the best value so far}\n\tif ValueSum>BestValue then\n\t\tbegin\n\t\tBestValue:=ValueSum;\n\t\tBestWeight:=WeightSum;\n\t\tBestIndex:=I;\n\t\tend;\n\tend;\n{Display the best result}\nMemo.Lines.Add('  Item                    Weight  Value');\nMemo.Lines.Add('---------------------------------------');\nBI.Start(BestIndex);\nwhile BI.Next(Inx) do\n\tbegin\n\tS:='  '+Format('%-25s',[ItemsList[Inx].Name]);\n\tS:=S+Format('%5d',[ItemsList[Inx].Weight]);\n\tS:=S+Format('%7d',[ItemsList[Inx].Value]);\n\tMemo.Lines.Add(S);\n\tend;\nMemo.Lines.Add('---------------------------------------');\nMemo.Lines.Add(Format('Total                     %6d %6d',[BestWeight,BestValue]));\nMemo.Lines.Add('Best Inx: '+IntToStr(BestIndex));\nMemo.Lines.Add('Best Value: '+IntToStr(BestValue));\nMemo.Lines.Add('Best Weight: '+IntToStr(BestWeight));\nfinally BI.Free; end;\nend;\n\n\n","human_summarization":"The code determines the optimal combination of items the tourist can carry in his knapsack, given a maximum weight limit of 4kg. It iterates through all possible combinations of items, ensuring the total weight does not exceed 400 decagrams and the total value is maximized. The items cannot be divided or diminished.","id":4081}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram ShortCircuitEvaluation;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils;\n\nfunction A(aValue: Boolean): Boolean;\nbegin\n  Writeln('a');\n  Result := aValue;\nend;\n\nfunction B(aValue: Boolean): Boolean;\nbegin\n  Writeln('b');\n  Result := aValue;\nend;\n\nvar\n  i, j: Boolean;\nbegin\n  for i in [False, True] do\n  begin\n    for j in [False, True] do\n    begin\n      Writeln(Format('%s and %s = %s', [BoolToStr(i, True), BoolToStr(j, True), BoolToStr(A(i) and B(j), True)]));\n      Writeln;\n      Writeln(Format('%s or %s = %s', [BoolToStr(i, True), BoolToStr(j, True), BoolToStr(A(i) or B(j), True)]));\n      Writeln;\n    end;\n  end;\nend.\n\n","human_summarization":"The code defines two functions, 'a' and 'b', which both accept and return a boolean value, and print their name when called. It then calculates the values of two boolean expressions, 'x' and 'y', using short-circuit evaluation. The function 'b' is only called when necessary, depending on the result of function 'a'. If the programming language does not support short-circuit evaluation, the same result is achieved using nested 'if' statements. In Delphi, short-circuit evaluation is enabled by default but can be turned off using the compiler directive {$BOOLEVAL OFF}.","id":4082}
    {"lang_cluster":"Delphi","source_code":"\nprogram Morse;\n\n{$APPTYPE CONSOLE}\n\n{$R *.res}\n\nuses\n  System.Generics.Collections,\n  SysUtils,\n  Windows;\n\nconst\n  Codes: array[0..35, 0..1] of string =\n   (('a', '.-   '), ('b', '-... '), ('c', '-.-. '), ('d', '-..  '),\n    ('e', '.    '), ('f', '..-. '), ('g', '--.  '), ('h', '.... '),\n    ('i', '..   '), ('j', '.--- '), ('k', '-.-  '), ('l', '.-.. '),\n    ('m', '--   '), ('n', '-.   '), ('o', '---  '), ('p', '.--. '),\n    ('q', '--.- '), ('r', '.-.  '), ('s', '...  '), ('t', '-    '),\n    ('u', '..-  '), ('v', '...- '), ('w', '.--  '), ('x', '-..- '),\n    ('y', '-.-- '), ('z', '--.. '), ('0', '-----'), ('1', '.----'),\n    ('2', '..---'), ('3', '...--'), ('4', '....-'), ('5', '.....'),\n    ('6', '-....'), ('7', '--...'), ('8', '---..'), ('9', '----.'));\nvar\n  Dictionary: TDictionary<String, String>;\n\nprocedure InitCodes;\nvar\n  i: Integer;\nbegin\n  for i := 0 to High(Codes) do\n    Dictionary.Add(Codes[i, 0], Codes[i, 1]);\nend;\n\nprocedure SayMorse(const Word: String);\nvar\n  s: String;\nbegin\n  for s in Word do\n    if s = '.' then\n      Windows.Beep(1000, 250)\n    else if s = '-' then\n      Windows.Beep(1000, 750)\n    else\n      Windows.Beep(1000, 1000);\nend;\n\nprocedure ParseMorse(const Word: String);\nvar\n  s, Value: String;\nbegin\n  for s in word do\n    if Dictionary.TryGetValue(s, Value) then\n    begin\n      Write(Value + ' ');\n      SayMorse(Value);\n    end;\nend;\n\nbegin\n  Dictionary := TDictionary<String, String>.Create;\n  try\n    InitCodes;\n    if ParamCount = 0 then\n      ParseMorse('sos')\n    else if ParamCount = 1 then\n      ParseMorse(LowerCase(ParamStr(1)))\n    else\n      Writeln('Usage: Morse.exe anyword');\n\n    Readln;\n  finally\n    Dictionary.Free;\n  end;\nend.\n\n","human_summarization":"<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":4083}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram ABC;\n{$APPTYPE CONSOLE}\n\nuses SysUtils;\n\ntype\n  TBlock = set of char;\n\nconst\n  TheBlocks : array [0..19] of TBlock =\n  (\n    [ 'B', 'O' ],    [ 'X', 'K' ],    [ 'D', 'Q' ],    [ 'C', 'P' ],    [ 'N', 'A' ],\n    [ 'G', 'T' ],    [ 'R', 'E' ],    [ 'T', 'G' ],    [ 'Q', 'D' ],    [ 'F', 'S' ],\n    [ 'J', 'W' ],    [ 'H', 'U' ],    [ 'V', 'I' ],    [ 'A', 'N' ],    [ 'O', 'B' ],\n    [ 'E', 'R' ],    [ 'F', 'S' ],    [ 'L', 'Y' ],    [ 'P', 'C' ],    [ 'Z', 'M' ]\n  );\n\nfunction SolveABC(Target : string; Blocks : array of TBlock) : boolean;\nvar\n  iChr : integer;\n  Used : array [0..19] of boolean;\n\n  function FindUnused(TargetChr : char) : boolean;  \/\/ Nested routine\n  var\n    iBlock : integer;\n  begin\n    Result := FALSE;\n    for iBlock := low(Blocks) to high(Blocks) do\n      if (not Used[iBlock]) and ( TargetChr in Blocks[iBlock] ) then\n      begin\n        Result := TRUE;\n        Used[iBlock] := TRUE;\n        Break;\n      end;\n  end;\n\nbegin\n  FillChar(Used, sizeof(Used), ord(FALSE));\n  Result := TRUE;\n  iChr := 1;\n  while Result and (iChr <= length(Target)) do\n    if FindUnused(Target[iChr]) then inc(iChr)\n                                else Result := FALSE;\nend;\n\nprocedure CheckABC(Target : string);\nbegin\n  if SolveABC(uppercase(Target), TheBlocks) then\n    writeln('Can make ' + Target)\n  else\n    writeln('Can NOT make ' + Target);\nend;\n\nbegin\n  CheckABC('A');\n  CheckABC('BARK');\n  CheckABC('BOOK');\n  CheckABC('TREAT');\n  CheckABC('COMMON');\n  CheckABC('SQUAD');\n  CheckABC('CONFUSE');\n  readln;\nend.\n\n\n","human_summarization":"The code implements a function that checks if a given word can be spelled using a predefined collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive. The output for seven example words is displayed.","id":4084}
    {"lang_cluster":"Delphi","source_code":"\n\nprogram MD5Hash;\n\n{$APPTYPE CONSOLE}\n\nuses\n  SysUtils,\n  IdHashMessageDigest;\n\nfunction MD5(aValue: string): string;\nbegin\n  with TIdHashMessageDigest5.Create do\n  begin\n    Result:= HashStringAsHex(aValue);\n    Free;\n  end;\nend;\n\nbegin\n  Writeln(MD5(''));\n  Writeln(MD5('a'));\n  Writeln(MD5('abc'));\n  Writeln(MD5('message digest'));\n  Writeln(MD5('abcdefghijklmnopqrstuvwxyz'));\n  Writeln(MD5('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'));\n  Writeln(MD5('12345678901234567890123456789012345678901234567890123456789012345678901234567890'));\n  Readln;\nend.\n\n\nD41D8CD98F00B204E9800998ECF8427E\n0CC175B9C0F1B6A831C399E269772661\n900150983CD24FB0D6963F7D28E17F72\nF96B697D7CB7938D525A2F31AAF161D0\nC3FCD3D76192E4007DFB496CCA67E13B\nD174AB98D277D9F5A5611C2C9F419D9F\n57EDF4A22BE3C955AC49DA2E2107B67A\n\n","human_summarization":"Implement and validate an MD5 encoding algorithm for a given string. The implementation should be tested against the test values in IETF RFC (1321) for MD5. The code also includes a warning about the known weaknesses of MD5 and suggests stronger alternatives for production-grade cryptography. If a library solution is used, there's a reference to MD5\/Implementation for a native implementation.","id":4085}
    {"lang_cluster":"Delphi","source_code":"\nprogram Sockets;\n\n{$APPTYPE CONSOLE}\n\nuses IdTCPClient;\n\nvar\n  lTCPClient: TIdTCPClient;\nbegin\n  lTCPClient := TIdTCPClient.Create(nil);\n  try\n    lTCPClient.Host := '127.0.0.1';\n    lTCPClient.Port := 256;\n    lTCPClient.Connect;\n    lTCPClient.IOHandler.WriteLn('hello socket world');\n  finally\n    lTCPClient.Free;\n  end;\nend.\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":4086}
    {"lang_cluster":"Delphi","source_code":"\nprocedure SendEmail;\nvar\n  msg: TIdMessage;\n  smtp: TIdSMTP;\nbegin\n  smtp := TIdSMTP.Create;\n  try\n    smtp.Host := 'smtp.server.com';\n    smtp.Port := 587;\n    smtp.Username := 'login';\n    smtp.Password := 'password';\n    smtp.AuthType := satNone;\n    smtp.Connect;\n    msg := TIdMessage.Create(nil);\n    try\n      with msg.Recipients.Add do begin\n        Address := 'doug@gmail.com';\n        Name := 'Doug';\n      end;\n      with msg.Sender do begin\n        Address := 'fred@server.com';\n        Name := 'Fred';\n      end;\n      msg.Subject := 'subj';\n      msg.Body.Text := 'here goes email message';\n      smtp.Send(msg);\n    finally\n      msg.Free;\n    end;\n  finally\n    smtp.Free;\n  end;\nend;\n\n","human_summarization":"Implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The code also provides notifications for any issues or success, and uses libraries or external programs for execution. It ensures portability across different operating systems. Sensitive data used in examples is obfuscated.","id":4087}
    {"lang_cluster":"Delphi","source_code":"\nprogram CountingInOctal;\n\n{$APPTYPE CONSOLE}\n\nuses SysUtils;\n\nfunction DecToOct(aValue: Integer): string;\nvar\n  lRemainder: Integer;\nbegin\n  Result := '';\n  repeat\n    lRemainder := aValue mod 8;\n    Result := IntToStr(lRemainder) + Result;\n    aValue := aValue div 8;\n  until aValue = 0;\nend;\n\nvar\n  i: Integer;\nbegin\n  for i := 0 to 20 do\n    WriteLn(DecToOct(i));\nend.\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":4088}
    {"lang_cluster":"Delphi","source_code":"\n\nprocedure Swap_T(var a, b: T);\nvar\n  temp: T;\nbegin\n  temp := a;\n  a := b;\n  b := temp;\nend;\n\n\nprogram GenericSwap;\n\ntype\n  TSwap = class\n    class procedure Swap<T>(var left, right: T);\n  end;\n\nclass procedure TSwap.Swap<T>(var left, right: T);\nvar\n  temp : T;\nbegin\n  temp := left;\n  left := right;\n  right := temp;\nend;\n\nvar\n  a, b : integer;\n  \nbegin\n  a := 5;\n  b := 3;\n  writeln('Before swap: a=', a, ' b=', b);\n  TSwap.Swap<integer>(a, b);\n  writeln('After swap: a=', a, ' b=', b);\nend.\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. The function is designed to work with both statically and dynamically typed languages, with certain restrictions for type compatibility and support for parametric polymorphism. In the case of Delphi, the function needs to be copied and adjusted for each required type, as it does not inherently support generics.","id":4089}
    {"lang_cluster":"Delphi","source_code":"\nuses\n  SysUtils, StrUtils;\n\nfunction IsPalindrome(const aSrcString: string): Boolean;\nbegin\n  Result := SameText(aSrcString, ReverseString(aSrcString));\nend;\n\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":4090}
    {"lang_cluster":"Delphi","source_code":"\nWorks with: Delphi version 6.0\nLibrary: SysUtils,StdCtrls\n\nfunction SudanFunction(N,X,Y: integer): integer;\nbegin\nif n = 0 then Result:=X + Y\nelse if y = 0 then Result:=X\nelse Result:=SudanFunction(N - 1, SudanFunction(N, X, Y - 1), SudanFunction(N, X, Y - 1) + Y);\nend;\n\n\nprocedure ShowSudanFunction(Memo: TMemo; N,X,Y: integer);\nbegin\nMemo.Lines.Add(Format('Sudan(%d,%d,%d)=%d',[n,x,y,SudanFunction(N,X,Y)]));\nend;\n\n\nprocedure ShowSudanFunctions(Memo: TMemo);\nvar N,X,Y: integer;\nvar S: string;\nbegin\nfor N:=0 to 1 do\n\tbegin\n\tMemo.Lines.Add(Format('Sudan(%d,X,Y)',[N]));\n\tMemo.Lines.Add('Y\/X    0   1   2   3   4   5');\n\tMemo.Lines.Add('----------------------------');\n\tfor Y:=0 to 6 do\n\t\tbegin\n\t\tS:=Format('%2d | ',[Y]);\n\t\tfor X:=0 to 5 do\n\t\t\tbegin\n\t\t\tS:=S+Format('%3d ',[SudanFunction(N,X,Y)]);\n\t\t\tend;\n\t\tMemo.Lines.Add(S);\n\t\tend;\n\tMemo.Lines.Add('');\n\tend;\n\nShowSudanFunction(Memo, 1, 3, 3);\nShowSudanFunction(Memo, 2, 1, 1);\nShowSudanFunction(Memo, 2, 2, 1);\nShowSudanFunction(Memo, 3, 1, 1);\nend;\n\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function, which takes two arguments (x, y) and returns their computed value based on the defined recursive rules.","id":4091}
    {"lang_cluster":"PowerShell","source_code":"\n\n$stack = New-Object -TypeName System.Collections.Stack\n# or\n$stack = [System.Collections.Stack] @()\n\n\n1, 2, 3, 4 | ForEach-Object {$stack.Push($_)}\n\n$stack -join \", \"\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and check if the stack is empty. It also allows for viewing the topmost element without modifying the stack.","id":4092}
    {"lang_cluster":"PowerShell","source_code":"\nfunction FibonacciNumber ( $count )\n{\n    $answer = @(0,1)\n    while ($answer.Length -le $count)\n    {\n        $answer += $answer[-1] + $answer[-2]\n    }\n    return $answer\n}\n\n$count = 8\n$answer = @(0,1)\n0..($count - $answer.Length) | Foreach { $answer += $answer[-1] + $answer[-2] }\n$answer\nfunction fib($n) {\n    switch ($n) {\n        0            { return 0 }\n        1            { return 1 }\n        { $_ -lt 0 } { return [Math]::Pow(-1, -$n + 1) * (fib (-$n)) }\n        default      { return (fib ($n - 1)) + (fib ($n - 2)) }\n    }\n}\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also optionally supports negative index values in the Fibonacci sequence.","id":4093}
    {"lang_cluster":"PowerShell","source_code":"\n$array = -15..37\n$array | Where-Object { $_\u00a0% 2 -eq 0 }\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":4094}
    {"lang_cluster":"PowerShell","source_code":"\n\n# test string\n$s = \"abcdefgh\"\n# test parameters\n$n, $m, $c, $s2 = 2, 3, [char]'d', $s2 = 'cd'\n\n# starting from n characters in and of m length\n# n = 2, m = 3\n$s.Substring($n-1, $m)              # returns 'bcd'\n\n# starting from n characters in, up to the end of the string\n# n = 2\n$s.Substring($n-1)                  # returns 'bcdefgh'\n\n# whole string minus last character\n$s.Substring(0, $s.Length - 1)      # returns 'abcdefg'\n\n# starting from a known character within the string and of m length\n# c = 'd', m =3\n$s.Substring($s.IndexOf($c), $m)    # returns 'def'\n\n# starting from a known substring within the string and of m length\n# s2 = 'cd', m = 3\n$s.Substring($s.IndexOf($s2), $m)   # returns 'cde'\n\n","human_summarization":"- Displays a substring starting from a specified character index and of a given length.\n- Displays a substring starting from a specified character index to the end of the string.\n- Displays the entire string excluding the last character.\n- Displays a substring starting from a known character within the string and of a specified length.\n- Displays a substring starting from a known substring within the string and of a specified length.\n- Supports any valid Unicode code point in UTF-8 or UTF-16 encoding.\n- References logical characters (code points) instead of 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- Adjusts character indexes by reducing by one for .NET and PowerShell due to their zero-based indexing.","id":4095}
    {"lang_cluster":"PowerShell","source_code":"\n\n$s = \"asdf\"\n\nWorks with: PowerShell version 1\n[string]::Join('', $s[$s.Length..0])\nWorks with: PowerShell version 2\n-join ($s[$s.Length..0])\nWorks with: PowerShell version 2\n[array]::Reverse($s)\n\nWorks with: PowerShell version 1\n$s -replace\n      ('(.)' * $s.Length),\n      [string]::Join('', ($s.Length..1 | ForEach-Object { \"`$$_\" }))\nWorks with: PowerShell version 2\n$s -replace\n      ('(.)' * $s.Length),\n      -join ($s.Length..1 | ForEach-Object { \"`$$_\" } )\nWorks with: PowerShell version 3\n[Regex]::Matches($s,'.','RightToLeft').Value -join ''\n\n$a = 'abc \ud83d\udc27 def'\n$enum = $a.EnumerateRunes() |\u00a0% { \"$_\" }\n-join $enum[$enum.length..0] # fed \ud83d\udc27 cba\n\n$a = \"aeiou`u{0308}yz\"\n$enum = [System.Globalization.StringInfo]::GetTextElementEnumerator($a)\n$arr = @()\nwhile($enum.MoveNext()) { $arr += $enum.GetTextElement() }\n[array]::reverse($arr)\n$arr -join '' # zy\u00fcoiea\n","human_summarization":"The code takes a string input, reverses it and outputs the reversed string. It also preserves Unicode combining characters during the reversal. It creates a character array from the end to the start of the string and joins it into a new string. It uses a regular expression substitution to capture every character of the string and constructs the reversed string. It also enumerates Unicode codepoints for multi-byte characters but not for composing or joining. For composing or joining, it enumerates graphemes.","id":4096}
    {"lang_cluster":"PowerShell","source_code":"\n$r = New-Object Random\nfor () {\n    $n = $r.Next(20)\n    Write-Host $n\n    if ($n -eq 10) {\n        break\n    }\n    Write-Host $r.Next(20)\n}\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":4097}
    {"lang_cluster":"PowerShell","source_code":"\n\n$document = [xml]@'\n<inventory title=\"OmniCorp Store #45x10^3\">\n  <section name=\"health\">\n    <item upc=\"123456789\" stock=\"12\">\n      <name>Invisibility Cream<\/name>\n      <price>14.50<\/price>\n      <description>Makes you invisible<\/description>\n    <\/item>\n    <item upc=\"445322344\" stock=\"18\">\n      <name>Levitation Salve<\/name>\n      <price>23.99<\/price>\n      <description>Levitate yourself for up to 3 hours per application<\/description>\n    <\/item>\n  <\/section>\n  <section name=\"food\">\n    <item upc=\"485672034\" stock=\"653\">\n      <name>Blork and Freen Instameal<\/name>\n      <price>4.95<\/price>\n      <description>A tasty meal in a tablet; just add water<\/description>\n    <\/item>\n    <item upc=\"132957764\" stock=\"44\">\n      <name>Grob winglets<\/name>\n      <price>3.56<\/price>\n      <description>Tender winglets of Grob. Just add water<\/description>\n    <\/item>\n  <\/section>\n<\/inventory>\n'@\n\n$query = \"\/inventory\/section\/item\"\n$items = $document.SelectNodes($query)\n\n\n$items[0]\n\n\n","human_summarization":"The code performs three XPath queries on a given XML document. It retrieves the first \"item\" element, prints out each \"price\" element, and gathers an array of all the \"name\" elements. The XML document is cast as [xml] to access .NET methods for XML manipulation.","id":4098}
    {"lang_cluster":"PowerShell","source_code":"\n\n[System.Collections.Generic.HashSet[object]]$set1 = 1..4\n[System.Collections.Generic.HashSet[object]]$set2 = 3..6\n\n#            Operation           +     Definition      +          Result\n#--------------------------------+---------------------+-------------------------\n$set1.UnionWith($set2)           # Union                 $set1 = 1, 2, 3, 4, 5, 6\n$set1.IntersectWith($set2)       # Intersection          $set1 = 3, 4\n$set1.ExceptWith($set2)          # Difference            $set1 = 1, 2\n$set1.SymmetricExceptWith($set2) # Symmetric difference  $set1 = 1, 2, 6, 5\n$set1.IsSupersetOf($set2)        # Test superset         False\n$set1.IsSubsetOf($set2)          # Test subset           False\n$set1.Equals($set2)              # Test equality         False\n$set1.IsProperSupersetOf($set2)  # Test proper superset  False\n$set1.IsProperSubsetOf($set2)    # Test proper subset    False\n\n5 -in $set1                      # Test membership       False\n7 -notin $set1                   # Test non-membership   True\n\n","human_summarization":"demonstrate various set operations including set creation, element testing, union, intersection, difference, subset, and equality. It also optionally shows additional set operations and modifications to a mutable set. The implementation can be done using an associative array, binary search tree, hash table, or an ordered array of binary bits. The basic element test operation's complexity varies based on the implementation. The code also explores the use of the HashSet type in .NET, specifically in PowerShell.","id":4099}
    {"lang_cluster":"PowerShell","source_code":"\n2008..2121 | Where-Object { (Get-Date $_-12-25).DayOfWeek -eq \"Sunday\" }\nfunction Get-ChristmasHoliday\n{\n    [CmdletBinding()]\n    [OutputType([PSCustomObject])]\n    Param\n    (\n        [Parameter(Mandatory=$false,\n                   ValueFromPipeline=$true,\n                   ValueFromPipelineByPropertyName=$true,\n                   Position=0)]\n        [ValidateRange(1,9999)]\n        [int[]]\n        $Year = (Get-Date).Year\n    )\n\n    Process\n    {\n        [datetime]$christmas = Get-Date $Year\/12\/25\n\n        switch ($christmas.DayOfWeek)\n        {\n            \"Sunday\"   {[datetime[]]$dates = 1..5 | ForEach-Object {$christmas.AddDays($_)}}\n            \"Monday\"   {[datetime[]]$dates = $christmas, $christmas.AddDays(1)}\n            \"Saturday\" {[datetime[]]$dates = $christmas.AddDays(-2), $christmas.AddDays(-1)}\n            Default    {[datetime[]]$dates = $christmas.AddDays(-1), $christmas}\n        }\n\n        $dates | Group-Object  -Property Year |\n                 Select-Object -Property @{Name=\"Year\"    \u00a0; Expression={$_.Name}},\n                                         @{Name=\"DayOfWeek\"; Expression={$christmas.DayOfWeek}},\n                                         @{Name=\"Christmas\"; Expression={$christmas.ToString(\"MM\/dd\/yyyy\")}},\n                                         @{Name=\"DaysOff\" \u00a0; Expression={$_.Group | ForEach-Object {$_.ToString(\"MM\/dd\/yyyy\")}}}\n    }\n}\n\n2008..2121 | Get-ChristmasHoliday | where DayOfWeek -match Su\n\n","human_summarization":"1. Determines the years between 2008 and 2121 when Christmas falls on a Sunday.\n2. Uses standard date handling libraries to perform the calculation.\n3. Compares the calculated dates with outputs from other languages to identify any discrepancies due to issues like overflow in date\/time representation.\n4. Provides the number of days off for a random year.\n5. Calculates the days off for the current year using the Year property returned by Get-Date.\n6. Returns the days off for the current year as [DateTime] objects.","id":4100}
    {"lang_cluster":"PowerShell","source_code":"\nfunction qr([double[][]]$A) {\n    $m,$n = $A.count, $A[0].count\n    $pm,$pn = ($m-1), ($n-1)\n    [double[][]]$Q = 0..($m-1) | foreach{$row = @(0) * $m; $row[$_] = 1; ,$row} \n    [double[][]]$R = $A | foreach{$row = $_; ,@(0..$pn | foreach{$row[$_]})}\n    foreach ($h in 0..$pn) { \n        [double[]]$u = $R[$h..$pm] | foreach{$_[$h]} \n        [double]$nu = $u | foreach {[double]$sq = 0} {$sq += $_*$_} {[Math]::Sqrt($sq)} \n        $u[0] -= if ($u[0] -lt 0) {$nu} else {-$nu}\n        [double]$nu = $u | foreach {$sq = 0} {$sq += $_*$_} {[Math]::Sqrt($sq)} \n        [double[]]$u = $u | foreach { $_\/$nu}\n        [double[][]]$v = 0..($u.Count - 1) | foreach{$i = $_; ,($u | foreach{2*$u[$i]*$_})}\n        [double[][]]$CR = $R | foreach{$row = $_; ,@(0..$pn | foreach{$row[$_]})}\n        [double[][]]$CQ = $Q | foreach{$row = $_; ,@(0..$pm | foreach{$row[$_]})}\n        foreach ($i in  $h..$pm) {\n            foreach ($j in  $h..$pn) {\n                $R[$i][$j] -=  $h..$pm | foreach {[double]$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CR[$_][$j]} {$sum}\n            }\n        }\n        if (0 -eq $h)  {\n            foreach ($i in  $h..$pm) {\n                foreach ($j in  $h..$pm) {\n                    $Q[$i][$j] -=  $h..$pm | foreach {$sum = 0} {$sum += $v[$i][$_]*$CQ[$_][$j]} {$sum}\n                }\n            }\n        } else  {\n            $p = $h-1\n            foreach ($i in  $h..$pm) {\n                foreach ($j in  0..$p) {\n                    $Q[$i][$j] -=  $h..$pm | foreach {$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CQ[$_][$j]} {$sum}\n                }\n                foreach ($j in  $h..$pm) {\n                    $Q[$i][$j] -=  $h..$pm | foreach {$sum = 0} {$sum += $v[$i-$h][$_-$h]*$CQ[$_][$j]} {$sum}\n                }\n            }\n        }\n    }\n    foreach ($i in  0..$pm) {\n        foreach ($j in  $i..$pm) {$Q[$i][$j],$Q[$j][$i] = $Q[$j][$i],$Q[$i][$j]}\n    }\n    [PSCustomObject]@{\"Q\" = $Q; \"R\" = $R}\n}\n\nfunction leastsquares([Double[][]]$A,[Double[]]$y) {\n    $QR = qr $A\n    [Double[][]]$Q = $QR.Q\n    [Double[][]]$R = $QR.R\n    $m,$n = $A.count, $A[0].count\n    [Double[]]$z = foreach ($j in  0..($m-1)) { \n            0..($m-1) | foreach {$sum = 0} {$sum += $Q[$_][$j]*$y[$_]} {$sum}\n    }\n    [Double[]]$x = @(0)*$n\n    for ($i = $n-1; $i -ge 0; $i--) {\n        for ($j = $i+1; $j -lt $n; $j++) {\n            $z[$i] -= $x[$j]*$R[$i][$j]\n        }\n        $x[$i] = $z[$i]\/$R[$i][$i]\n    }\n    $x\n}\n\nfunction polyfit([Double[]]$x,[Double[]]$y,$n) {\n    $m = $x.Count \n    [Double[][]]$A = 0..($m-1) | foreach{$row = @(1) * ($n+1); ,$row} \n    for ($i = 0; $i -lt $m; $i++) {\n        for ($j = $n-1; 0 -le $j; $j--) {\n            $A[$i][$j] = $A[$i][$j+1]*$x[$i]\n        }\n    }\n    leastsquares $A $y\n}\n\nfunction show($m) {$m | foreach {write-host \"$_\"}}\n\n$A = @(@(12,-51,4), @(6,167,-68), @(-4,24,-41))\n$x = @(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n$y = @(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321)\n$QR = qr $A\n$ps = (polyfit $x $y 2)\n\"Q = \"\nshow $QR.Q\n\"R = \"\nshow $QR.R\n\"polyfit \"\n\"X^2 X constant\"\n\"$(polyfit $x $y 2)\"\n\n\n","human_summarization":"The code performs QR decomposition of a given matrix using the Householder reflections method. It demonstrates this decomposition on a specific example matrix and uses it to solve linear least squares problems. The code also handles cases where the matrix is not square by cutting off zero padded bottom rows. Finally, it solves the square upper triangular system by back substitution.","id":4101}
    {"lang_cluster":"PowerShell","source_code":"\n\n$data = 1,2,3,1,2,3,4,1\n\n$h = @{}\nforeach ($x in $data) {\n    $h[$x] = 1\n}\n$h.Keys\n\n$data | Sort-Object -Unique\n\n$data | Select-Object -Unique\n","human_summarization":"implement three methods to remove duplicate elements from an array. The first method uses a hash table, the second one sorts the elements before removing duplicates, and the third one iterates through the list to discard any recurring elements. Additionally, the code includes the use of Sort-Object and Select-Object cmdlets for sorting and removing duplicates respectively.","id":4102}
    {"lang_cluster":"PowerShell","source_code":"\nFunction SortThree( [Array] $data )\n{\n\tif( $data[ 0 ] -gt $data[ 1 ] )\n\t{\n\t\tif( $data[ 0 ] -lt $data[ 2 ] )\n\t\t{\n\t\t\t$data = $data[ 1, 0, 2 ]\n\t\t} elseif ( $data[ 1 ] -lt $data[ 2 ] ){\n\t\t\t$data = $data[ 1, 2, 0 ]\n\t\t} else {\n\t\t\t$data = $data[ 2, 1, 0 ]\n\t\t}\n\t} else {\n\t\tif( $data[ 0 ] -gt $data[ 2 ] )\n\t\t{\n\t\t\t$data = $data[ 2, 0, 1 ]\n\t\t} elseif( $data[ 1 ] -gt $data[ 2 ] ) {\n\t\t\t$data = $data[ 0, 2, 1 ]\n\t\t}\n\t}\n\t$data\n}\n\nFunction QuickSort( [Array] $data, $rand = ( New-Object Random ) )\n{\n\t$datal = $data.length\n\tif( $datal -gt 3 )\n\t{\n\t\t[void] $datal--\n\t\t$median = ( SortThree $data[ 0, ( $rand.Next( 1, $datal - 1 ) ), -1 ] )[ 1 ]\n\t\t$lt = @()\n\t\t$eq = @()\n\t\t$gt = @()\n\t\t$data | ForEach-Object { if( $_ -lt $median ) { $lt += $_ } elseif( $_ -eq $median ) { $eq += $_ } else { $gt += $_ } }\n\t\t$lt = ( QuickSort $lt $rand )\n\t\t$gt = ( QuickSort $gt $rand )\n\t\t$data = @($lt) + $eq + $gt\n\t} elseif( $datal -eq 3 ) {\n\t\t$data = SortThree( $data )\n\t} elseif( $datal -eq 2 ) {\n\t\tif( $data[ 0 ] -gt $data[ 1 ] )\n\t\t{\n\t\t\t$data = $data[ 1, 0 ]\n\t\t}\n\t}\n\t$data\n}\n\nQuickSort 5,3,1,2,4 \nQuickSort 'e','c','a','b','d' \nQuickSort 0.5,0.3,0.1,0.2,0.4 \n$l = 100; QuickSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } )\n\nfunction quicksort($array) {\n    $less, $equal, $greater = @(), @(), @()\n    if( $array.Count -gt 1 ) { \n        $pivot = $array[0]\n        foreach( $x in $array) {\n            if($x -lt $pivot) { $less += @($x) }\n            elseif ($x -eq $pivot) { $equal += @($x)}\n            else { $greater += @($x) }\n        }    \n        $array = (@(quicksort $less) + @($equal) + @(quicksort $greater))\n    }\n    $array\n}\n$array = @(60, 21, 19, 36, 63, 8, 100, 80, 3, 87, 11)\n\"$(quicksort $array)\"\nThe output is: 3 8 11 19 21 36 60 63 80 87 100\n\nfunction quicksort($in) {\n    $n = $in.count\n    switch ($n) {\n        0 {}\n        1 { $in[0] }\n        2 { if ($in[0] -lt $in[1]) {$in[0], $in[1]} else {$in[1], $in[0]} }\n        default {\n            $pivot = $in | get-random\n            $lt = $in |\u00a0? {$_ -lt $pivot}\n            $eq = $in |\u00a0? {$_ -eq $pivot}\n            $gt = $in |\u00a0? {$_ -gt $pivot}\n            @(quicksort $lt) + @($eq) + @(quicksort $gt)\n        }\n    }\n}\n","human_summarization":"implement the quicksort algorithm to sort an array or list. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions, one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and joins them with the pivot to form the sorted array. The codes also include an optimized version of quicksort that works in place by swapping elements within the array to avoid additional memory allocation. The pivot selection method is not specified and can vary.","id":4103}
    {"lang_cluster":"PowerShell","source_code":"\n\"{0:yyyy-MM-dd}\" -f (Get-Date)\n\"{0:dddd, MMMM d, yyyy}\" -f (Get-Date)\n# or\n(Get-Date).ToString(\"yyyy-MM-dd\")\n(Get-Date).ToString(\"dddd, MMMM d, yyyy\")\n\n\n","human_summarization":"display the current date in the formats \"2007-11-23\" and \"Friday, November 23, 2007\", respecting the currently set locale for names of months and days.","id":4104}
    {"lang_cluster":"PowerShell","source_code":"\nfunction power-set ($array) {\n    if($array) {\n        $n = $array.Count\n        function state($set, $i){  \n            if($i -gt -1) {\n                state $set ($i-1)\n                state ($set+@($array[$i])) ($i-1)   \n            } else {\n                \"$($set | sort)\"\n            }\n        }\n        $set = state @() ($n-1)\n        $power = 0..($set.Count-1) | foreach{@(0)}\n        $i = 0\n        $set | sort | foreach{$power[$i++] = $_.Split()}\n        $power | sort {$_.Count}\n    } else {@()}\n\n}\n$OFS = \" \"\n$setA = power-set  @(1,2,3,4)\n\"number of sets in setA: $($setA.Count)\"\n\"sets in setA:\"\n$OFS = \", \"\n$setA | foreach{\"{\"+\"$_\"+\"}\"} \n$setB = @()\n\"number of sets in setB: $($setB.Count)\"\n\"sets in setB:\"\n$setB | foreach{\"{\"+\"$_\"+\"}\"} \n$setC = @(@(), @(@()))\n\"number of sets in setC: $($setC.Count)\"\n\"sets in setC:\"\n$setC | foreach{\"{\"+\"$_\"+\"}\"} \n$OFS = \" \"\n\nnumber of sets in setA: 16\nsets in setA:\n{}\n{1}\n{2}\n{3}\n{4}\n{1, 2}\n{1, 3}\n{1, 4}\n{2, 3}\n{2, 4}\n{3, 4}\n{1, 2, 3}\n{1, 2, 4}\n{1, 3, 4}\n{2, 3, 4}\n{1, 2, 3, 4}\nnumber of sets in setB: 0\nsets in setB:\nnumber of sets in setC: 2\nsets in setC:\n{}\n{}\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all possible subsets of the input set, including the empty set and the set itself. The function also demonstrates the ability to generate power sets of the empty set and a set containing only the empty set.","id":4105}
    {"lang_cluster":"PowerShell","source_code":"\nFilter ToRoman {\n\t$output = ''\n\t\n\tif ($_ -ge 4000) {\n\t\tthrow 'Number too high'\n\t}\n\t\n\t$current = 1000\n\t$subtractor = 'M'\n\t$whole = $False\n\t$decimal = $_\n\t'C','D','X','L','I','V',' ' `\n\t|\u00a0%{\n\t\t$divisor = $current\n\t\tif ($whole =\u00a0!$whole) {\n\t\t\t$current \/= 10\n\t\t\t$subtractor = $_ + $subtractor[0]\n\t\t\t$_ = $subtractor[1]\n\t\t}\n\t\telse {\n\t\t\t$divisor *= 5 \n\t\t\t$subtractor = $subtractor[0] + $_\n\t\t}\n\t\t\n\t\t$multiple = [Math]::floor($decimal \/ $divisor)\n\t\tif ($multiple) {\n\t\t\t$output += [string]$_ * $multiple\n\t\t\t$decimal\u00a0%= $divisor\n\t\t}\n\t\tif ($decimal -ge ($divisor -= $current)) {\n\t\t\t$output += $subtractor\n\t\t\t$decimal -= $divisor\n\t\t}\n\t}\n\t\n\t$output\n}\n19,4,0,2479,3001 | ToRoman\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":4106}
    {"lang_cluster":"PowerShell","source_code":"\n\n$a = @()\n\n$a = ,2\n$a = @(2)  # alternative\n\n$a = 1,2,3\n\n$a += 5\n\n$a[1]\n\n$a[1] = 42\n\n$r = 1..100\n\n$r[0..9+25..27+80,85,90]\n\n$r[-1]  # last index\n","human_summarization":"demonstrate the basic syntax of arrays in a given programming language. The codes include creating an array, assigning a value to it, and retrieving an element from it. The codes also show both fixed-length and dynamic arrays, and how to push a value into an array. The codes further illustrate how to create an empty array, an array with one member, and longer arrays by separating values with commas. The codes demonstrate how to append a value to an array using the += operator, retrieve values using indexing syntax, replace values, and create arrays of integers using the range operator. The codes also show how to index for retrieval using arrays and negative numbers for indexing from the end of the array.","id":4107}
    {"lang_cluster":"PowerShell","source_code":"\n\nGet-Content $PWD\\input.txt | Out-File $PWD\\output.txt\n\nGet-Content $PWD\\input.txt | Set-Content $PWD\\output.txt\n","human_summarization":"The code reads content from \"input.txt\" file into an intermediate variable, then writes the content from the variable into a new file called \"output.txt\". It assumes both files are located in the same directory as the script. It does not directly copy the file content, but uses an intermediate variable.","id":4108}
    {"lang_cluster":"PowerShell","source_code":"\n$string = 'alphaBETA'\n$lower  = $string.ToLower()\n$upper  = $string.ToUpper()\n$title  = (Get-Culture).TextInfo.ToTitleCase($string)\n\n$lower, $upper, $title\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":4109}
    {"lang_cluster":"PowerShell","source_code":"\n\n\n# Create an Array by separating the elements with commas:\n$array = \"one\", 2, \"three\", 4\n\n# Using explicit syntax:\n$array = @(\"one\", 2, \"three\", 4)\n\n# Send the values back into individual variables:\n$var1, $var2, $var3, $var4 = $array\n\n# An array of several integer ([int]) values:\n$array = 0, 1, 2, 3, 4, 5, 6, 7\n\n# Using the range operator (..):\n$array = 0..7\n\n# Strongly typed:\n[int[]] $stronglyTypedArray = 1, 2, 4, 8, 16, 32, 64, 128\n\n# An empty array:\n$array = @()\n\n# An array with a single element:\n$array = @(\"one\")\n\n# I suppose this would be a jagged array:\n$jaggedArray = @((11, 12, 13),\n                 (21, 22, 23),\n                 (31, 32, 33))\n\n$jaggedArray | Format-Wide {$_} -Column 3 -Force\n\n$jaggedArray[1][1] # returns 22\n\n# A Multi-dimensional array:\n$multiArray = New-Object -TypeName \"System.Object[,]\" -ArgumentList 6,6\n\nfor ($i = 0; $i -lt 6; $i++)\n{ \n    for ($j = 0; $j -lt 6; $j++)\n    { \n        $multiArray[$i,$j] = ($i + 1) * 10 + ($j + 1)\n    }\n}\n\n$multiArray | Format-Wide {$_} -Column 6 -Force\n\n$multiArray[2,2] # returns 33\n\n# An empty Hash Table:\n$hash = @{}\n\n# A Hash table populated with some values:\n$nfcCentralDivision = @{\n    Packers = \"Green Bay\"\n    Bears   = \"Chicago\"\n    Lions   = \"Detroit\"\n}\n\n# Add items to a Hash Table:\n$nfcCentralDivision.Add(\"Vikings\",\"Minnesota\")\n$nfcCentralDivision.Add(\"Buccaneers\",\"Tampa Bay\")\n\n# Remove an item from a Hash Table:\n$nfcCentralDivision.Remove(\"Buccaneers\")\n\n# Searching for items\n$nfcCentralDivision.ContainsKey(\"Packers\")\n$nfcCentralDivision.ContainsValue(\"Green Bay\")\n\n# A bad value...\n$hash1 = @{\n    One = 1\n    Two = 3\n}\n\n# Edit an item in a Hash Table:\n$hash1.Set_Item(\"Two\",2)\n\n# Combine Hash Tables:\n\n$hash2 = @{\n    Three = 3\n    Four  = 4\n}\n\n$hash1 + $hash2\n\n# Using the ([ordered]) accelerator the items in the Hash Table retain the order in which they were input:\n$nfcCentralDivision = [ordered]@{\n    Bears   = \"Chicago\"\n    Lions   = \"Detroit\"\n    Packers = \"Green Bay\"\n    Vikings = \"Minnesota\"\n}\n\n$list = New-Object -TypeName System.Collections.ArrayList -ArgumentList 1,2,3\n\n# or...\n\n$list = [System.Collections.ArrayList]@(1,2,3)\n\n\n$list.Add(4) | Out-Null\n$list.RemoveAt(2)\n","human_summarization":"create a collection in a statically-typed language, add a few values to it, and demonstrate the use of common collection types in PowerShell such as arrays, hash tables, and ArrayList from .NET. The code also explains the zero-based indexing of arrays and the two types of hash tables: normal and ordered.","id":4110}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 3.0\n#  Define the items to pack\n$Item = @(\n    [pscustomobject]@{ Name = 'panacea'; Unit = 'vials'  ; value = 3000; Weight = 0.3; Volume = 0.025 }\n    [pscustomobject]@{ Name = 'ichor'  ; Unit = 'ampules'; value = 1800; Weight = 0.2; Volume = 0.015 }\n    [pscustomobject]@{ Name = 'gold'   ; Unit = 'bars'   ; value = 2500; Weight = 2.0; Volume = 0.002 }\n    )\n \n#  Define our maximums\n$MaxWeight = 25\n$MaxVolume = 0.25\n \n#  Set our default value to beat\n$OptimalValue = 0\n \n#  Iterate through the possible quantities of item 0, without going over the weight or volume limit\nForEach ( $Qty0 in 0..( [math]::Min( [math]::Truncate( $MaxWeight \/ $Item[0].Weight ), [math]::Truncate( $MaxVolume \/ $Item[0].Volume ) ) ) )\n    {\n    #  Calculate the remaining space\n    $RemainingWeight = $MaxWeight - $Qty0 * $Item[0].Weight\n    $RemainingVolume = $MaxVolume - $Qty0 * $Item[0].Volume\n \n    #  Iterate through the possible quantities of item 1, without going over the weight or volume limit\n    ForEach ( $Qty1 in 0..( [math]::Min( [math]::Truncate( $RemainingWeight \/ $Item[1].Weight ), [math]::Truncate( $RemainingVolume \/ $Item[1].Volume ) ) ) )\n        {\n        #  Calculate the remaining space\n        $RemainingWeight2 = $RemainingWeight - $Qty1 * $Item[1].Weight\n        $RemainingVolume2 = $RemainingVolume - $Qty1 * $Item[1].Volume\n \n        #  Calculate the maximum quantity of item 2 for the remaining space, without going over the weight or volume limit\n        $Qty2 = [math]::Min( [math]::Truncate( $RemainingWeight2 \/ $Item[2].Weight ), [math]::Truncate( $RemainingVolume2 \/ $Item[2].Volume ) )\n \n        #  Calculate the total value of the items packed\n        $TrialValue =   $Qty0 * $Item[0].Value +\n                        $Qty1 * $Item[1].Value +\n                        $Qty2 * $Item[2].Value\n \n        #  Describe the trial solution\n        $Solution  = \"$Qty0 $($Item[0].Unit) of $($Item[0].Name), \"\n        $Solution += \"$Qty1 $($Item[1].Unit) of $($Item[1].Name), and \"\n        $Solution += \"$Qty2 $($Item[2].Unit) of $($Item[2].Name) worth a total of $TrialValue.\"\n \n        #  If the trial value is higher than previous most valuable trial...\n        If ( $TrialValue -gt $OptimalValue )\n            {\n            #  Set the new number to beat\n            $OptimalValue = $TrialValue\n \n            #  Overwrite the previous optimal solution(s) with the trial solution\n            $Solutions  = @( $Solution )\n            }\n \n        #  Else if the trial value matches the previous most valuable trial...\n       ElseIf ( $TrialValue -eq $OptimalValue )\n            {\n            #  Add the trial solution to the list of optimal solutions\n            $Solutions += @( $Solution )\n            }\n        }\n    }\n \n#  Show the results\n$Solutions\n\n\n","human_summarization":"determine the maximum value of items that a traveler can carry in his knapsack, given the weight and volume constraints. The items include vials of panacea, ampules of ichor, and bars of gold. The code calculates the optimal quantity of each item to maximize the total value, considering that only whole units of any item can be taken.","id":4111}
    {"lang_cluster":"PowerShell","source_code":"for ($i = 1; $i -le 10; $i++) {\n    Write-Host -NoNewLine $i\n    if ($i -eq 10) {\n        Write-Host\n        break\n    }\n    Write-Host -NoNewLine \", \"\n}\n\nswitch (1..10) {\n    { $true }     { Write-Host -NoNewLine $_ }\n    { $_ -lt 10 } { Write-Host -NoNewLine \", \" }\n    { $_ -eq 10 } { Write-Host }\n}\n","human_summarization":"The code outputs a comma-separated list of numbers from 1 to 10, using separate output statements for the number and the comma within a loop structure. An alternative solution uses a switch statement to iterate over the given range.","id":4112}
    {"lang_cluster":"PowerShell","source_code":"\n#Input Data\n$a=@\"\ndes_system_lib   std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\ndw01             ieee dw01 dware gtech\ndw02             ieee dw02 dware\ndw03             std synopsys dware dw03 dw02 dw01 ieee gtech\ndw04             dw04 ieee dw01 dware gtech\ndw05             dw05 ieee dware\ndw06             dw06 ieee dware\ndw07             ieee dware\ndware            ieee dware\ngtech            ieee gtech\nramlib           std ieee\nstd_cell_lib     ieee std_cell_lib\nsynopsys         \n\"@\n#Convert to Object[]\n$c = switch ( $a.split([char] 10) ) { \n    $_ {\n        $b=$_.split(' ')\n        New-Object PSObject -Property @{\n            Library = $b[0]\n            \"Library Dependencies\" = @( $( $b[1..($b.length-1)] | Where-Object { $_ -match '\\w' } ) )\n        } \n    }\n}\n#Add pure dependencies\n$c | ForEach-Object {\n    $_.\"Library Dependencies\" | Where-Object {\n        $d=$_\n        $(:andl foreach($i in $c) {\n            if($d -match $i.Library) {\n                $false\n                break andl\n            }\n        }) -eq $null\n    } | ForEach-Object {\n        $c+=New-Object PSObject -Property @{\n            Library=$_\n            \"Library Dependencies\"=@()\n        }\n    }\n}\n#Associate with a dependency value\n##Initial Dependency Value\n$d = $c | Sort Library | Select-Object Library,\"Library Dependencies\",@{\n    Name=\"Dep Value\"\n    Expression={\n        1\n    }\n}\n##Modify Dependency Value, perform check for incorrect dependency\n##Dep Value is determined by a parent child relationship, if a library is a parent, all libraries dependant on it are children\nfor( $i=0; $i -lt $d.count; $i++ ) {\n    $errmsg=\"\"\n    foreach( $j in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $i } ) ) {\n        #Foreach other Child Library where this is a dependency, increase the Dep Value of the Child\n        if( $( :orl foreach( $k in $d[$j].\"Library Dependencies\" ) {\n            if( $k -match $d[$i].Library ) {\n                foreach( $n in $d[$i].\"Library Dependencies\" ) {\n                    if( $n -match $d[$j].Library ) {\n                        $errmsg=\"Error Cyclic Dependency {0}<->{1}\" -f $d[$i].Library, $d[$j].Library\n                        break\n                    }\n                }\n                $true\n                break orl\n            }\n        } ) ) {\n            #If the child has already been processed, increase the Dep Value of its children\n            if( $j -lt $i ) {\n                foreach( $l in ( 0..( $d.count - 1 ) | Where-Object { $_ -ne $j } ) ) {\n                    if( $( :orl2 foreach( $m in $d[$l].\"Library Dependencies\" ) {\n                        if( $m -match $d[$j].Library ) {\n                            $true\n                            break orl2\n                        }\n                    } ) ) {\n                        $d[$l].\"Dep Value\"+=$d[$i].\"Dep Value\"\n                    }\n                }\n            }\n            $d[$j].\"Dep Value\"+=$d[$i].\"Dep Value\"\n        }\n        if( $errmsg -ne \"\" ) {\n            $errmsg\n            $d=$null\n            break\n        }\n    }\n}\n#Sort and Display\nif( $d ) {\n    $d | Sort \"Dep Value\",Library | ForEach-Object { \n        \"{0,-14} LIBRARY DEPENDENCIES`n{1,-14} ====================\" -f \"LIBRARY\", \"=======\"\n    } {\n        \"{0,-14} $($_.\"Library Dependencies\")\" -f $_.Library\n    }\n}\n\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":4113}
    {"lang_cluster":"PowerShell","source_code":"\n\"spicywiener\".StartsWith(\"spicy\")\n\"spicywiener\".Contains(\"icy\")\n\"spicywiener\".EndsWith(\"wiener\")\n\"spicywiener\".IndexOf(\"icy\")\n[regex]::Matches(\"spicywiener\", \"i\").count\n\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":4114}
    {"lang_cluster":"PowerShell","source_code":"\nfunction triples($p) {\n    if($p -gt 4) {\n        # ai + bi + ci = pi <= p\n        # ai < bi < ci --> 3ai < pi <= p and ai + 2bi < pi <= p\n        $pa = [Math]::Floor($p\/3)\n        1..$pa | foreach {\n            $ai = $_\n            $pb = [Math]::Floor(($p-$ai)\/2)\n            ($ai+1)..$pb | foreach {\n                $bi = $_\n                $pc = $p-$ai-$bi\n                ($bi+1)..$pc | where {\n                    $ci = $_\n                    $pi = $ai + $bi + $ci\n                    $ci*$ci -eq $ai*$ai + $bi*$bi\n                 } | \n                foreach { \n                    [pscustomobject]@{\n                        a = \"$ai\"\n                        b = \"$bi\"\n                        c = \"$ci\"\n                        p = \"$pi\"\n                    }\n                }\n            }\n        }\n    }\n    else {\n        Write-Error \"$p is not greater than 4\"\n    }   \n}\nfunction gcd ($a, $b)  {\n    function pgcd ($n, $m)  {\n        if($n -le $m) { \n            if($n -eq 0) {$m}\n            else{pgcd $n ($m%$n)}\n        }\n        else {pgcd $m $n}\n    }\n    $n = [Math]::Abs($a)\n    $m = [Math]::Abs($b)\n    (pgcd $n $m)\n}\n$triples = (triples 100)\n \n$coprime = $triples | \nwhere {((gcd $_.a $_.b) -eq 1) -and ((gcd $_.a $_.c) -eq 1) -and  ((gcd $_.b $_.c) -eq 1)}\n \n\"There are $(($triples).Count) Pythagorean triples with perimeter no larger than 100\n and $(($coprime).Count) of them are coprime.\"\n\n\nThere are 17 Pythagorean triples with perimeter no larger than 100 and 7 of them are coprime.\n\n","human_summarization":"\"Calculate the number of Pythagorean triples with a perimeter no larger than 100 and count how many of these are primitive. The program should also be capable of handling large perimeter values up to 100,000,000.\"","id":4115}
    {"lang_cluster":"PowerShell","source_code":"\nLibrary: WPK\nNew-Window -Show\n\nLibrary: Windows Forms\n$form = New-Object Windows.Forms.Form\n$form.Text = \"A Window\"\n$form.Size = New-Object Drawing.Size(150,150)\n$form.ShowDialog() | Out-Null\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":4116}
    {"lang_cluster":"PowerShell","source_code":"\nfunction frequency ($string) {\n    $arr = $string.ToUpper().ToCharArray() |where{$_ -match '[A-KL-Z]'} \n    $n = $arr.count\n    $arr | group | foreach{\n        [pscustomobject]@{letter = \"$($_.name)\"; frequency  = \"$([math]::round($($_.Count\/$n),5))\"; count = \"$($_.count)\"}\n    } | sort letter\n}\n$file = \"$($MyInvocation.MyCommand.Name )\" #Put the name of your file here\nfrequency $(get-content $file -Raw)\n\n\nletter frequency count\n------ --------- -----\nA      0.06809   16   \nB      0.00426   1    \nC      0.06809   16   \nD      0.00851   2    \nE      0.11064   26   \nF      0.0383    9    \nG      0.01702   4    \nH      0.02979   7    \nI      0.03404   8    \nJ      0.00426   1    \nK      0.00426   1    \nL      0.02553   6    \nM      0.04255   10   \nN      0.09362   22   \nO      0.08085   19   \nP      0.02128   5    \nQ      0.01277   3    \nR      0.10638   25   \nS      0.02128   5    \nT      0.10213   24   \nU      0.05957   14   \nV      0.00426   1    \nW      0.00851   2    \nY      0.02979   7    \nZ      0.00426   1 \n\n","human_summarization":"Open a text file, count the frequency of each letter from A to Z, and optionally include punctuation characters.","id":4117}
    {"lang_cluster":"PowerShell","source_code":"\nfunction Get-Factor ($a) {\n    1..$a | Where-Object { $a\u00a0% $_ -eq 0 }\n}\n\nfunction Get-Factor ($a) {\n    1..[Math]::Sqrt($a) `\n        | Where-Object { $a\u00a0% $_ -eq 0 } `\n        | ForEach-Object { $_; $a \/ $_ } `\n        | Sort-Object -Unique\n}\n\n","human_summarization":"calculate the factors of a given positive integer. The factors are the positive integers that can divide the input number to give a positive integer result. The code does not handle zero or negative integers. It uses a range of integers up to the square root of the input number for efficiency. It filters out the factors and calculates the corresponding larger factors, returning all factors of the input number.","id":4118}
    {"lang_cluster":"PowerShell","source_code":"\n$file = \n@'\nGiven$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\n'@.Split(\"`n\")\n\n$arr = @()\n$file | foreach {\n    $line = $_\n    $i = 0\n    $hash = [ordered]@{}\n    $line.split('$') | foreach{\n        $hash[\"$i\"] = \"$_\"\n        $i++\n     }\n    $arr += @([pscustomobject]$hash)\n}\n$arr | Format-Table -HideTableHeaders -Wrap *\n\n\nGiven      a          text       file   of     many      lines,     where    fields  within   a      line   \nare        delineated by         a      single 'dollar'  character, write    a       program                \nthat       aligns     each       column of     fields    by         ensuring that    words    in     each   \ncolumn     are        separated  by     at     least     one        space.                                  \nFurther,   allow      for        each   word   in        a          column   to      be       either left   \njustified, right      justified, or     center justified within     its      column.\n\n","human_summarization":"\"Code reads a text file with lines separated by dollar characters. It aligns each column of words by adding at least one space between them and allows for left, right, or center justification within each column. The code also handles trailing dollar characters, ensures all columns share the same alignment, and disregards consecutive spaces at the end of lines. The minimum space between columns is computed from the text, not hard-coded, and there's no need to add separating characters between or around columns.\"","id":4119}
    {"lang_cluster":"PowerShell","source_code":"\n$e = \"This is a test Guvf vf n grfg\"\n\n[char[]](0..64+78..90+65..77+91..96+110..122+97..109+123..255)[[char[]]$e] -join \"\"\n\nfunction Invoke-Rot13 {\n  param(\n    [char[]]$message\n  )\n  begin {\n    $outString = New-Object System.Collections.ArrayList\n    $alpha = 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'\n    $alphaL = $alpha + $alpha\n    $alphaU = $alphaL.toUpper()\n    $int = 13\n  }\n  process{\n    $message | ForEach-Object {\n      # test if char is special\n      if ($_ -match '[^\\p{L}\\p{Nd}]') {\n        $outString += $_\n      }\n      # test if char is digit\n      elseif ($_ -match '\\d') {\n        $outString += $_\n      }\n      # test if char is upperCase\n      elseif ($_ -ceq $_.ToString().ToUpper()) {\n        $charIndex = $alphaU.IndexOf($_.tostring())\n        $outString += $alphaU[$charIndex+$int]\n      }\n      # test if char is lowerCase\n      elseif ($_ -ceq $_.ToString().ToLower()) {\n        $charIndex = $alphaL.IndexOf($_.tostring())\n        $outString += $alphaL[$charIndex+$int]\n      }\n      else {\n        $outString += $_\n      }\n    } # end foreach\n  } # end process\n  end {\n    # output string and join all chars\n    $outString -join \"\"\n  }\n} # end function\n\nPS> $message = '{!This is \/A\\ Test123}'\nPS> $messageE = Invoke-Rot13 -message $message\nPS> $messageE\nPS> Invoke-Rot13 -message $messageE\n{!Guvf vf \/N\\ Grfg123}\n{!This is \/A\\ Test123}\n","human_summarization":"The code implements a rot-13 function that encodes every line of input from a file or standard input. It replaces every letter of the ASCII alphabet with the letter rotated 13 characters around the 26 letter alphabet. The function works on both upper and lower case letters, preserves case, and passes all non-alphabetic characters without alteration. It can be wrapped in a utility program similar to a common UNIX utility.","id":4120}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 4.0\n$list = @{\n\"def\" = \"one\"\n\"abc\" = \"two\"\n\"jkl\" = \"three\"\n\"abcdef\" = \"four\"\n\"ghi\" = \"five\"\n\"ghijkl\" = \"six\"\n }\n $list.GetEnumerator() | sort {-($PSItem.Name).length}, Name\n\n\nName                           Value                                                                               \n----                           -----                                                                               \nabcdef                         four                                                                                \nghijkl                         six                                                                                 \nabc                            two                                                                                 \ndef                            one                                                                                 \nghi                            five                                                                                \njkl                            three                                                                                  \n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key 'name' using a custom comparator.","id":4121}
    {"lang_cluster":"PowerShell","source_code":"\nfor ($i = 1; $i -le 5; $i++) {\n    for ($j = 1; $j -le $i; $j++) {\n        Write-Host -NoNewline *\n    }\n    Write-Host\n}\n\n1..5 | ForEach-Object {\n    1..$_ | ForEach-Object {\n        Write-Host -NoNewline *\n    }\n    Write-Host\n}\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations of the inner loop is controlled by the outer loop. The pattern consists of increasing number of asterisks on each line. The same result can also be achieved using the range operator and ForEach-Object cmdlet, replacing the inner loop with \"*\" * $_.","id":4122}
    {"lang_cluster":"PowerShell","source_code":"\n\n$hashtable = @{}\n\n$hashtable = @{\n    \"key1\" = \"value 1\"\n    key2 = 5            # if the key name has no spaces, no quotes are needed.\n}\n\n$hashtable.foo    = \"bar\"\n$hashtable['bar'] = 42\n$hashtable.\"a b\"  = 3.14  # keys can contain spaces, property-style access needs quotation marks, then\n$hashtable[5]     = 8     # keys don't need to be strings\n\n# Case insensitive keys, both end up as the same key:\n$h=@{}\n$h['a'] = 1\n$h['A'] = 2\n$h\n\nName                           Value                                                                                              \n----                           -----                                                                                              \na                              2     \n\n# Case sensitive keys:\n$h = New-Object -TypeName System.Collections.Hashtable\n$h['a'] = 1\n$h['A'] = 2\n$h\n\nName                           Value                                                                                              \n----                           -----                                                                                              \nA                              2                                                                                                  \na                              1\n\n$hashtable.key1     # value 1\n$hashtable['key2']  # 5\n\n$obj = [PSCustomObject]@{\n    \"key1\" = \"value 1\"\n    key2 = 5            \n}\n\n","human_summarization":"create and manipulate an associative array or hashtable. The codes initialize the hashtable with key\/value pairs, assign or replace individual values using a property-style access method or indexing, and retrieve values. They also handle case-insensitive string comparison in PowerShell. Additionally, they demonstrate the creation of an object using a hashtable literal, which is a more efficient method.","id":4123}
    {"lang_cluster":"PowerShell","source_code":"\nFunction msstate{\n    Param($current_seed)\n    Return (214013*$current_seed+2531011)%2147483648}\n    \nFunction randMS{\n    Param($MSState)\n    Return [int]($MSState\/65536)}\n    \nFunction randBSD{\n    Param($BSDState)\n    Return (1103515245*$BSDState+12345)%2147483648}    \n\nWrite-Host \"MS: seed=0\"\n$seed=0 #initialize seed\nFor($i=1;$i-le5;$i++){\n    $seed = msstate($seed)\n    $rand = randMS($seed)\n    Write-Host $rand}\n\nWrite-Host \"BSD: seed=0\"\n$seed=0 #initialize seed\nFor($j=1;$j-le5;$j++){\n    $seed = randBSD($seed)\n    Write-Host $seed}\n\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":4124}
    {"lang_cluster":"PowerShell","source_code":"\nfunction isEven {\n\tparam ([int]$value)\n\treturn [bool]($value % 2 -eq 0)\n}\n\nfunction doubleValue {\n\tparam ([int]$value)\n\treturn [int]($value * 2)\n}\n\nfunction halveValue {\n\tparam ([int]$value)\n\treturn [int]($value \/ 2)\n}\n\nfunction multiplyValues {\n\tparam (\n\t\t[int]$plier,\n\t\t[int]$plicand,\n\t\t[int]$temp = 0\n\t)\n\t\n\twhile ($plier -ge 1)\n\t{\n\t\tif (!(isEven $plier)) {\n\t\t\t$temp += $plicand\n\t\t}\n\t\t$plier = halveValue $plier\n\t\t$plicand = doubleValue $plicand\n\t}\n\t\nreturn $temp\n}\n\nmultiplyValues 17 34\n\n\nfunction halveInt( [int] $rhs )\n{\n\t[math]::floor( $rhs \/ 2 )\n}\n\nfunction doubleInt( [int] $rhs )\n{\n\t$rhs*2\n}\n\nfunction isEven( [int] $rhs )\n{\n\t-not ( $_ % 2 )\n}\n\nfunction Ethiopian( [int] $lhs , [int] $rhs )\n{\n\t$scratch = @{}\n\t1..[math]::floor( [math]::log( $lhs , 2 ) + 1 ) | \n\tForEach-Object { \n\t\t$scratch[$lhs] = $rhs\n\t\t$lhs\n\t\t$lhs = halveInt( $lhs )\n\t\t$rhs = doubleInt( $rhs ) } | \n\tWhere-Object { -not ( isEven $_ ) } | \n\tForEach-Object { $sum = 0 } { $sum += $scratch[$_] } { $sum }\n}\n\nEthiopian 17 34\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement the Ethiopian multiplication method, which multiplies two numbers using only addition, doubling, and halving operations. The multiplication process involves repeatedly halving the first number and doubling the second number, discarding rows where the first number is even, and summing the remaining values in the second column to get the product.","id":4125}
    {"lang_cluster":"PowerShell","source_code":"\nfunction Get-Factorial ($x) {\n    if ($x -eq 0) {\n        return 1\n    }\n    return $x * (Get-Factorial ($x - 1))\n}\nfunction Get-Factorial ($x) {\n    if ($x -eq 0) {\n        return 1\n    } else {\n        $product = 1\n        1..$x | ForEach-Object { $product *= $_ }\n        return $product\n    }\n}\nWorks with: PowerShell version 2\n\nfunction Get-Factorial ($x) {\n    if ($x -eq 0) {\n        return 1\n    }\n    return (Invoke-Expression (1..$x -join '*'))\n}\n","human_summarization":"\"Function to calculate and return the factorial of a given number, either through iterative or recursive methods. The function optionally includes error handling for negative input values.\"","id":4126}
    {"lang_cluster":"PowerShell","source_code":"\n[int]$guesses = $bulls = $cows = 0\n[string]$guess = \"none\"\n[string]$digits = \"\"\n\nwhile ($digits.Length -lt 4)\n{\n    $character = [char](49..57 | Get-Random)\n\n    if ($digits.IndexOf($character) -eq -1) {$digits += $character}\n}\n\nWrite-Host \"`nGuess four digits (1-9) using no digit twice.`n\" -ForegroundColor Cyan\n\nwhile ($bulls -lt 4)\n{\n    do\n    {\n        $prompt = \"Guesses={0:0#}, Last='{1,4}', Bulls={2}, Cows={3}; Enter your guess\" -f $guesses, $guess, $bulls, $cows\n        $guess = Read-Host $prompt\n\n        if ($guess.Length -ne 4)                     {Write-Host \"`nMust be a four-digit number`n\" -ForegroundColor Red}\n        if ($guess -notmatch \"[1-9][1-9][1-9][1-9]\") {Write-Host \"`nMust be numbers 1-9`n\"         -ForegroundColor Red}\n    }\n    until ($guess.Length -eq 4)\n\n    $guesses += 1\n    $bulls = $cows = 0\n\n    for ($i = 0; $i -lt 4; $i++)\n    { \n        $character = $digits.Substring($i,1)\n\n        if ($guess.Substring($i,1) -eq $character)\n        {\n            $bulls += 1\n        }\n        else\n        {\n            if ($guess.IndexOf($character) -ge 0)\n            {\n                $cows += 1\n            }\n        }\n    }\n}\n\nWrite-Host \"`nYou won after $($guesses - 1) guesses.\" -ForegroundColor Cyan\n\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":4127}
    {"lang_cluster":"PowerShell","source_code":"\n\nfunction Get-RandomNormal\n    {\n    [CmdletBinding()]\n    Param ( [double]$Mean, [double]$StandardDeviation )\n \n    $RandomNormal = $Mean + $StandardDeviation * [math]::Sqrt( -2 * [math]::Log( ( Get-Random -Minimum 0.0 -Maximum 1.0 ) ) ) * [math]::Cos( 2 * [math]::PI * ( Get-Random -Minimum 0.0 -Maximum 1.0 ) )\n \n    return $RandomNormal\n    }\n \n#  Standard deviation function for testing\nfunction Get-StandardDeviation\n    {\n    [CmdletBinding()]\n    param ( [double[]]$Numbers )\n \n    $Measure = $Numbers | Measure-Object -Average\n    $PopulationDeviation = 0\n    ForEach ($Number in $Numbers) { $PopulationDeviation += [math]::Pow( ( $Number - $Measure.Average ), 2 ) }\n    $StandardDeviation = [math]::Sqrt( $PopulationDeviation \/ ( $Measure.Count - 1 ) )\n    return $StandardDeviation\n    }\n \n#  Test\n$RandomNormalNumbers = 1..1000 | ForEach { Get-RandomNormal -Mean 1 -StandardDeviation 0.5 }\n \n$Measure = $RandomNormalNumbers | Measure-Object -Average\n \n$Stats = [PSCustomObject]@{\n    Count             = $Measure.Count\n    Average           = $Measure.Average\n    StandardDeviation = Get-StandardDeviation -Numbers $RandomNormalNumbers\n}\n\n$Stats | Format-List\n\n\n","human_summarization":"\"Generates a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using specific algorithms if only uniformly distributed random numbers can be generated by the libraries.\"","id":4128}
    {"lang_cluster":"PowerShell","source_code":"\nfunction dotproduct( $a, $b) {\n    $a | foreach -Begin {$i = $res = 0} -Process { $res += $_*$b[$i++] } -End{$res}\n} \ndotproduct (1..2) (1..2) \ndotproduct (1..10) (11..20)\n\n\n \n5 \n935\n\n","human_summarization":"implement a function to calculate the dot product of two vectors of the same length by multiplying corresponding terms and summing the products.","id":4129}
    {"lang_cluster":"PowerShell","source_code":"\nGet-Content c:\\file.txt |\n    ForEach-Object {\n        $_\n    }\n\n\nForEach-Object -inputobject (get-content c:\\file.txt) {$_}\n\n","human_summarization":"\"Reads data from a text stream either word-by-word or line-by-line until the end of the stream, which has an unknown amount of data.\"","id":4130}
    {"lang_cluster":"PowerShell","source_code":"\nUsing a cmdlet:Get-Date\nor using .NET classes and properties:[DateTime]::Now\n\n\n","human_summarization":"the system time in a specified unit. This can be utilized for debugging, network information, generating random number seeds, or tracking program performance. The code may use a system command or a built-in language function to achieve this. The related task involves formatting the date.","id":4131}
    {"lang_cluster":"PowerShell","source_code":"\nfunction Add-SEDOLCheckDigit\n    {\n    Param ( #  Validate input as six-digit SEDOL number\n            [ValidatePattern( \"^[0123456789bcdfghjklmnpqrstvwxyz]{6}$\" )]\n            [parameter ( Mandatory = $True ) ]\n            [string]\n            $SixDigitSEDOL )\n \n    #  Convert to array of single character strings, using type char as an intermediary\n    $SEDOL = [string[]][char[]]$SixDigitSEDOL\n \n    #  Define place weights\n    $Weight = @( 1, 3, 1, 7, 3, 9 )\n \n    #  Define character values (implicit in 0-based location within string)\n    $Characters = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n \n    $CheckSum = 0\n   \n    #  For each digit, multiply the character value by the weight and add to check sum\n    0..5 | ForEach { $CheckSum += $Characters.IndexOf( $SEDOL[$_].ToLower() ) * $Weight[$_] }\n \n    #  Derive the check digit from the partial check sum\n    $CheckDigit = ( 10 - $CheckSum % 10 ) % 10\n \n    #  Return concatenated result\n    return ( $SixDigitSEDOL + $CheckDigit )\n    }\n \n#  Test\n$List = @(\n    \"710889\"\n    \"B0YBKJ\"\n    \"406566\"\n    \"B0YBLH\"\n    \"228276\"\n    \"B0YBKL\"\n    \"557910\"\n    \"B0YBKR\"\n    \"585284\"\n    \"B0YBKT\"\n    \"B00030\"\n    )\n \nForEach ( $PartialSEDOL in $List )\n    {\n    Add-SEDOLCheckDigit -SixDigitSEDOL $PartialSEDOL\n    }\n\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":4132}
    {"lang_cluster":"PowerShell","source_code":"\nfunction nth($inp){\n    $suffix = \"th\"\n\n    switch($inp % 100){\n        11{$suffix=\"th\"}\n        12{$suffix=\"th\"}\n        13{$suffix=\"th\"}\n        default{\n            switch($inp % 10){\n                1{$suffix=\"st\"}\n                2{$suffix=\"nd\"}\n                3{$suffix=\"rd\"}\n            }\n        }\n    }\n    return \"$inp$suffix \"\n}\n\n0..25 | %{Write-host -nonewline (nth \"$_\")};\"\"\n250..265 | %{Write-host -nonewline (nth \"$_\")};\"\"\n1000..1025 | %{Write-host -nonewline (nth \"$_\")};\"\"\n\n\n","human_summarization":"The code generates a string representation of an integer with its ordinal suffix. It takes an integer greater than or equal to zero as input and returns the number followed by an apostrophe and its ordinal suffix. The function is tested with ranges of integer inputs: 0..25, 250..265, 1000..1025.","id":4133}
    {"lang_cluster":"PowerShell","source_code":"\n$limit = 20\n$data  = @(\"3 Fizz\",\"5 Buzz\",\"7 Baxx\")\n\t#An array with whitespace as the delimiter\n\t#Between the factor and the word\n \nfor ($i = 1;$i -le $limit;$i++){\n\t$outP = \"\"\n\tforeach ($x in $data){\n\t\t$data_split = $x -split \" \"\t#Split the \"<factor> <word>\"\n\t\tif (($i % $data_split[0]) -eq 0){\n\t\t\t$outP += $data_split[1]\t#Append the <word> to outP\n\t\t}\n\t}\n\tif(!$outP){\t#Is outP equal to NUL?\n\t\tWrite-HoSt $i\n\t} else {\n\t\tWrite-HoSt $outP\n\t}\n}\n\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":4134}
    {"lang_cluster":"PowerShell","source_code":"\n$str = \"World!\"\n$str = \"Hello, \" + $str\n$str\n\nHello, World!\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":4135}
    {"lang_cluster":"PowerShell","source_code":"Library: turtle\n# handy constants with script-wide scope\n[Single]$script:QUARTER_PI=0.7853982\n[Single]$script:HALF_PI=1.570796\n\n# leverage GDI (Forms and Drawing)\nAdd-Type -AssemblyName System.Drawing\nAdd-Type -AssemblyName System.Windows.Forms\n$script:TurtlePen = New-Object Drawing.Pen darkGreen\n$script:Form = New-Object Windows.Forms.Form\n$script:Canvas = $Form.CreateGraphics()\n\n# implement a turtle graphics model\nClass Turtle { # relies on the script-scoped $TurtlePen and $Canvas\n  # member properties for turtle's position and orientation\n  [Single]$TurtleX\n  [Single]$TurtleY\n  [Single]$TurtleAngle\n\n  # constructors\n  Turtle() {\n    $this.TurtleX, $this.TurtleY = 44.0, 88.0\n    $this.TurtleAngle = 0.0\n  }\n  Turtle([Single]$InitX, [Single]$InitY, [Single]$InitAngle) {\n    $this.TurtleX, $this.TurtleY = $InitX, $InitY\n    $this.TurtleAngle = $InitAngle\n  }\n\n  # methods for turning and drawing\n  [Void]Turn([Single]$Angle) {  # $Angle measured in radians\n    $this.TurtleAngle += $Angle  # use positive $Angle for right turn, negative for left turn\n  }\n  [Void]Forward([Single]$Distance) {\n    # draw line segment\n    $TargetX = $this.TurtleX + $Distance * [Math]::Cos($this.TurtleAngle)\n    $TargetY = $this.TurtleY + $Distance * [Math]::Sin($this.TurtleAngle)\n    $script:Canvas.DrawLine($script:TurtlePen, $this.TurtleX, $this.TurtleY, $TargetX, $TargetY)\n    # relocate turtle to other end of segment\n    $this.TurtleX = $TargetX\n    $this.TurtleY = $TargetY\n  }\n} # end of Turtle class definition\n\n# Implement dragon curve drawing methods in a subclass that inherits Turtle\nClass DragonTurtle : Turtle {\n\n  # DCL: recursive dragon curve, starting with left turns\n  [Void]DCL([Byte]$Step, [Single]$Length) {\n    $AdjustedStep = $Step - 1\n    $AdjustedLength = $Length \/ [Math]::Sqrt(2.0)\n\n    $this.Turn(-$script:QUARTER_PI)\n    if ($AdjustedStep -gt 0) {\n      $this.DCR($AdjustedStep, $AdjustedLength)\n    } else {\n      $this.Forward($AdjustedLength)\n    }\n    $this.Turn($script:HALF_PI)\n    if ($AdjustedStep -gt 0) {\n      $this.DCL($AdjustedStep, $AdjustedLength)\n    } else {\n      $this.Forward($AdjustedLength)\n    }\n    $this.Turn(-$script:QUARTER_PI)\n  }\n\n  # DCR: recursive dragon curve, starting with right turns\n  [Void]DCR([Byte]$Step, [Single]$Length) {\n    $AdjustedStep = $Step - 1\n    $AdjustedLength = $Length \/ [Math]::Sqrt(2.0)\n\n    $this.Turn($script:QUARTER_PI)\n    if ($AdjustedStep -gt 0) {\n      $this.DCR($AdjustedStep, $AdjustedLength)\n    } else {\n      $this.Forward($AdjustedLength)\n    }\n    $this.Turn(-$script:HALF_PI)\n    if ($AdjustedStep -gt 0) {\n      $this.DCL($AdjustedStep, $AdjustedLength)\n    } else {\n      $this.Forward($AdjustedLength)\n    }\n    $this.Turn($script:QUARTER_PI)\n  }\n} # end of DragonTurtle subclass definition\n\n# prepare anonymous dragon-curve painting function for WinForms dialog\n$Form.add_paint({\n  [DragonTurtle]$Dragon = [DragonTurtle]::new()\n  $Dragon.DCR(14,128)\n})\n\n# display the GDI Form window, which triggers its prepared anonymous drawing function\n$Form.ShowDialog()\n\n","human_summarization":"generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.","id":4136}
    {"lang_cluster":"PowerShell","source_code":"\n\nFunction GuessNumber($Guess)\n{\n    $Number = Get-Random -min 1 -max 11\n    Write-Host \"What number between 1 and 10 am I thinking of?\"\n        Do\n        {\n        Write-Warning \"Try again!\"\n        $Guess = Read-Host \"What's the number?\"\n        }\n        While ($Number -ne $Guess)\n    Write-Host \"Well done! You successfully guessed the number $Guess.\"\n}\n\n$myNumber = Read-Host \"What's the number?\"\nGuessNumber $myNumber\n\n","human_summarization":"The code generates a random number between 1 and 10. It then prompts the user to guess the number. If the guess is incorrect, the user is prompted to guess again. This process continues until the user guesses the correct number, at which point the program displays a \"Well guessed!\" message and terminates. A conditional loop is used to facilitate repeated guessing until the correct number is identified. The code also includes a function that analyzes the provided number each time it is called.","id":4137}
    {"lang_cluster":"PowerShell","source_code":"\n$asString = 97..122 | ForEach-Object -Begin {$asArray = @()} -Process {$asArray += [char]$_} -End {$asArray -join('')}\n$asString\n\n\n","human_summarization":"generate a sequence of all lowercase ASCII characters from 'a' to 'z'. The sequence can be in the form of an array, list, lazy sequence, or an indexable string. The code should be written in a robust and reliable style, suitable for a large program, and should use strong typing if available. The code should avoid manually enumerating all the lowercase characters to prevent bugs. The code should be clear and easy to understand during a code review. An alternative method for PowerShell-v6.0.0rc is also provided.","id":4138}
    {"lang_cluster":"PowerShell","source_code":"\nLibrary: Microsoft .NET Framework\n@(5,50,900) | foreach-object { [Convert]::ToString($_,2) }\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":4139}
    {"lang_cluster":"PowerShell","source_code":"\nfunction Read-ConfigurationFile\n{\n    [CmdletBinding()]\n    Param\n    (\n        # Path to the configuration file.  Default is \"C:\\ConfigurationFile.cfg\"\n        [Parameter(Mandatory=$false, Position=0)]\n        [string]\n        $Path = \"C:\\ConfigurationFile.cfg\"\n    )\n\n    [string]$script:fullName = \"\"\n    [string]$script:favouriteFruit = \"\" \n    [bool]$script:needsPeeling = $false \n    [bool]$script:seedsRemoved = $false\n    [string[]]$script:otherFamily = @()\n\n    function Get-Value ([string]$Line)\n    {\n        if ($Line -match \"=\")\n        {\n            [string]$value = $Line.Split(\"=\",2).Trim()[1]\n        }\n        elseif ($Line -match \" \")\n        {\n            [string]$value = $Line.Split(\" \",2).Trim()[1]\n        }\n\n        $value\n    }\n\n    # Process each line in file that is not a comment.\n    Get-Content $Path | Select-String -Pattern \"^[^#;]\" | ForEach-Object {\n\n        [string]$line = $_.Line.Trim()\n\n        if ($line -eq [String]::Empty)\n        {\n            # do nothing for empty lines\n        }\n        elseif ($line.ToUpper().StartsWith(\"FULLNAME\"))\n        {\n            $script:fullName = Get-Value $line\n        }\n        elseif ($line.ToUpper().StartsWith(\"FAVOURITEFRUIT\"))\n        {\n            $script:favouriteFruit = Get-Value $line\n        }\n        elseif ($line.ToUpper().StartsWith(\"NEEDSPEELING\"))\n        {\n            $script:needsPeeling = $true\n        }\n        elseif ($line.ToUpper().StartsWith(\"SEEDSREMOVED\"))\n        {\n            $script:seedsRemoved = $true\n        }\n        elseif ($line.ToUpper().StartsWith(\"OTHERFAMILY\"))\n        {\n            $script:otherFamily = (Get-Value $line).Split(',').Trim()\n        }\n    }\n\n    Write-Verbose -Message (\"{0,-15}= {1}\" -f \"FULLNAME\", $script:fullName)\n    Write-Verbose -Message (\"{0,-15}= {1}\" -f \"FAVOURITEFRUIT\", $script:favouriteFruit)\n    Write-Verbose -Message (\"{0,-15}= {1}\" -f \"NEEDSPEELING\", $script:needsPeeling)\n    Write-Verbose -Message (\"{0,-15}= {1}\" -f \"SEEDSREMOVED\", $script:seedsRemoved)\n    Write-Verbose -Message (\"{0,-15}= {1}\" -f \"OTHERFAMILY\", ($script:otherFamily -join \", \"))\n}\n\n\nRead-ConfigurationFile -Path .\\temp.txt -Verbose\n\n\n","human_summarization":"The code reads a configuration file in standard format from \".\\temp.txt\", ignoring lines beginning with a hash or semicolon and blank lines. It sets variables based on the configuration entries, with four specific variables 'fullname', 'favouritefruit', 'needspeeling', and 'seedsremoved' being set to specific values. An additional option with multiple parameters is stored in an array 'otherfamily'. The code tests if the variables are set and displays them if the -Verbose switch is used.","id":4140}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 3\nAdd-Type -AssemblyName System.Device\n \n$BNA = New-Object System.Device.Location.GeoCoordinate 36.12, -86.67\n$LAX = New-Object System.Device.Location.GeoCoordinate 33.94, -118.40\n \n$BNA.GetDistanceTo( $LAX ) \/ 1000\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":4141}
    {"lang_cluster":"PowerShell","source_code":"\n$wc = New-Object Net.WebClient\n$wc.DownloadString('http:\/\/www.rosettacode.org')\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":4142}
    {"lang_cluster":"PowerShell","source_code":"\nfunction Test-LuhnNumber\n{\n  <#\n    .SYNOPSIS\n        Tests validity of credit card numbers.\n    .DESCRIPTION\n        Tests validity of credit card numbers using the Luhn test.\n    .PARAMETER Number\n        The number must be 11 or 16 digits.\n    .EXAMPLE\n        Test-LuhnNumber 49927398716\n    .EXAMPLE\n        [int64[]]$numbers = 49927398716, 49927398717, 1234567812345678, 1234567812345670\n        C:\\PS>$numbers | ForEach-Object {\n                  \"{0,-17}: {1}\" -f $_,\"$(if(Test-LuhnNumber $_) {'Is valid.'} else {'Is not valid.'})\"\n              }\n  #>\n    [CmdletBinding()]\n    [OutputType([bool])]\n    Param\n    (\n        [Parameter(Mandatory=$true,\n                   Position=0)]\n        [ValidateScript({$_.Length -eq 11 -or $_.Length -eq 16})]\n        [ValidatePattern(\"^\\d+$\")]\n        [string]\n        $Number\n    )\n\n    $digits = ([Regex]::Matches($Number,'.','RightToLeft')).Value\n    \n    $digits |\n        ForEach-Object `\n               -Begin   {$i = 1} `\n               -Process {if ($i++\u00a0% 2) {$_}} |\n        ForEach-Object `\n               -Begin   {$sumOdds = 0} `\n               -Process {$sumOdds += [Char]::GetNumericValue($_)}\n    $digits |\n        ForEach-Object `\n               -Begin   {$i = 0} `\n               -Process {if ($i++\u00a0% 2) {$_}} |\n        ForEach-Object `\n               -Process {[Char]::GetNumericValue($_) * 2} |\n        ForEach-Object `\n               -Begin   {$sumEvens = 0} `\n               -Process {\n                            $_number = $_.ToString()\n                            if ($_number.Length -eq 1)\n                            {\n                                $sumEvens += [Char]::GetNumericValue($_number)\n                            }\n                            elseif ($_number.Length -eq 2)\n                            {\n                                $sumEvens += [Char]::GetNumericValue($_number[0]) + [Char]::GetNumericValue($_number[1])\n                            }\n                        }\n\n    ($sumOdds + $sumEvens).ToString()[-1] -eq \"0\"\n}\nTest-LuhnNumber 49927398716\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":4143}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 2\n\nfunction Get-JosephusPrisoners ( [int]$N, [int]$K )\n    {\n    #  Just for convenience\n    $End = $N - 1\n \n    #  Create circle of prisoners\n    $Prisoners = New-Object System.Collections.ArrayList ( , (0..$End) )\n \n    #  For each starting point of the reducing circle...\n    ForEach ( $Start in 0..($End - 1) )\n        {\n        #  We subtract one from K for the one we advanced by incrementing $Start\n        #  Then take K modulus the length of the remaining circle\n        $RoundK = ( $K - 1 ) % ( $End - $Start + 1 )\n       \n        #  Rotate the remaining prisoners K places around the remaining circle\n        $Prisoners.SetRange( $Start, $Prisoners[ $Start..$End ][ ( $RoundK + $Start - $End - 1 )..( $RoundK - 1 ) ] )\n        }\n    return $Prisoners\n    }\n\n#  Get the prisoner order for a circle of 41 prisoners, selecting every third\n$Prisoners = Get-JosephusPrisoners -N 41 -K 3\n \n#  Display the prisoner order\n$Prisoners -join \" \"\n \n#  Display the last remaining prisoner\n\"Last prisoner remmaining: \" + $Prisoners[-1]\n \n#  Display the last three remaining prisoners\n$S = 3\n\"Last $S remaining: \" + $Prisoners[-$S..-1]\n\n\n","human_summarization":"The code implements the Josephus problem, where given 'n' prisoners and 'k' as the step count, it determines the final survivor. It also provides a way to calculate which prisoner is at any given position on the killing sequence. The code follows an iterative algorithm, rotating the circle of prisoners equivalent to the executioner walking around, and selects the next prisoner to be executed. It also handles the scenario where multiple survivors are allowed.","id":4144}
    {"lang_cluster":"PowerShell","source_code":"\n\"ha\" * 5  # ==> \"hahahahaha\"\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":4145}
    {"lang_cluster":"PowerShell","source_code":"\n\"I am a string\" -match '\\bstr'       # true\n\"I am a string\" -replace 'a\\b','no'  # I am no string\n\n\n","human_summarization":"utilize regular expressions to match and substitute parts of a string. The -match and -replace operators are used by default, which are case-insensitive. However, case-sensitive operations can be achieved using the -cmatch and -creplace operators.","id":4146}
    {"lang_cluster":"PowerShell","source_code":"\n$a = [int] (Read-Host First Number)\n$b = [int] (Read-Host Second Number)\n\nWrite-Host \"Sum:                              $($a + $b)\"\nWrite-Host \"Difference:                       $($a - $b)\"\nWrite-Host \"Product:                          $($a * $b)\"\nWrite-Host \"Quotient:                         $($a \/ $b)\"\nWrite-Host \"Quotient, round to even:          $([Math]::Round($a \/ $b))\"\nWrite-Host \"Remainder, sign follows first:    $($a % $b)\"\n\n\n[Math]::Pow($a, $b)\n\n","human_summarization":"take two integers as input from the user, calculate and display their sum, difference, product, integer quotient, remainder, and exponentiation (if possible). The code does not include error handling. It specifies the rounding direction for the quotient and the sign of the remainder. It also includes an example of the 'divmod' operator. The code automatically converts numbers to accommodate the result, expanding Int32 to Int64 or converting to a floating-point type for non-integer quotients. The remainder carries the sign of the first operand. The code uses .NET BCL to perform exponentiation if no operator exists.","id":4147}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 4.0\n[regex]::Matches(\"the three truths\", \"th\").count\n\n\n3\n\n[regex]::Matches(\"ababababab\",\"abab\").count\n\n\n2\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the string to be searched and the substring to look for. It returns an integer representing the count of non-overlapping occurrences. The matching is done either from left-to-right or right-to-left to yield the highest number of non-overlapping matches.","id":4148}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 4.0\nfunction hanoi($n, $a,  $b, $c) {\n    if($n -eq 1) {\n        \"$a -> $c\"\n    } else{    \n         hanoi ($n - 1) $a $c $b\n         hanoi 1 $a $b $c\n         hanoi ($n - 1) $b $a $c\n    }\n}\nhanoi 3 \"A\" \"B\" \"C\"\n\nA -> C\nA -> B\nC -> B\nA -> C\nB -> A\nB -> C\nA -> C\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":4149}
    {"lang_cluster":"PowerShell","source_code":"\nfunction choose($n,$k) {\n    if($k -le $n -and 0 -le $k) {\n        $numerator = $denominator = 1\n        0..($k-1) | foreach{\n            $numerator *= ($n-$_)\n            $denominator *= ($_ + 1)\n        }\n        $numerator\/$denominator\n    } else {\n        \"$k is greater than $n or lower than 0\"\n    }\n}\nchoose 5 3\nchoose 2 1\nchoose 10 10\nchoose 10 2\nchoose 10 8\n\n\n10\n2\n1\n45\n45\n\n","human_summarization":"The code calculates any binomial coefficient, with a specific emphasis on outputting the binomial coefficient of 5 choose 3, which equals 10. It uses the formula for binomial coefficients and includes tasks for combinations, permutations, combinations with repetitions, and permutations with repetitions. The code also handles cases where order is important or unimportant, and with or without replacement.","id":4150}
    {"lang_cluster":"PowerShell","source_code":"\nFunction ShellSort( [Array] $data )\n{\n\t# http:\/\/oeis.org\/A108870\n\t$A108870 = [Int64[]] ( 1, 4, 9, 20, 46, 103, 233, 525, 1182, 2660, 5985, 13467, 30301, 68178, 153401, 345152, 776591, 1747331, 3931496, 8845866, 19903198, 44782196, 100759940, 226709866, 510097200, 1147718700, 2582367076, 5810325920, 13073233321, 29414774973 )\n\t$datal = $data.length - 1\n\t$inci = [Array]::BinarySearch( $A108870, [Int64] ( [Math]::Floor( $datal \/ 2 ) ) )\n\tif( $inci -lt 0 )\n\t{\n\t\t$inci = ( $inci -bxor -1 ) - 1\n\t}\n\t$A108870[ $inci..0 ] | ForEach-Object {\n\t\t$inc = $_\n\t\t$_..$datal | ForEach-Object {\n\t\t\t$temp = $data[ $_ ]\n\t\t\t$j = $_\n\t\t\tfor( ; ( $j -ge $inc ) -and ( $data[ $j - $inc ] -gt $temp ); $j -= $inc )\n\t\t\t{\n\t\t\t\t$data[ $j ] = $data[ $j - $inc ]\n\t\t\t}\n\t\t\t$data[ $j ] = $temp\n\t\t}\n\t}\n\t$data\n}\n\n$l = 10000; ShellSort( ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) )\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":4151}
    {"lang_cluster":"PowerShell","source_code":"\n$n = 0\ndo {\n    $n++\n    $n\n} while ($n\u00a0% 6 -ne 0)\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":4152}
    {"lang_cluster":"PowerShell","source_code":"\n$s = \"H\u00ebll\u00f3 W\u00f8r\u0142\u00f0\"\n$s.Length\n$s = \"H\u00ebll\u00f3 W\u00f8r\u0142\u00f0\"\n[System.Text.Encoding]::Unicode.GetByteCount($s)\n\n[System.Text.Encoding]::UTF8.GetByteCount($s)\n","human_summarization":"The code calculates the character and byte length of a string, considering different encodings like UTF-8 and UTF-16. It handles Unicode code points correctly, including Non-BMP code points, providing the actual character counts in code points, not in code unit counts. It also provides the string length in graphemes if the language supports it.","id":4153}
    {"lang_cluster":"PowerShell","source_code":"\nfunction Get-RandomInteger\n{\n    Param\n    (\n        [Parameter(Mandatory=$false,\n                   ValueFromPipeline=$true,\n                   ValueFromPipelineByPropertyName=$true, \n                   Position=0)]\n        [ValidateScript({$_ -ge 4})]\n        [int[]]\n        $InputObject = 64\n    )\n\n    Begin\n    {\n        $rng = New-Object -TypeName System.Security.Cryptography.RNGCryptoServiceProvider\n    }\n    Process\n    {\n        foreach($count in $InputObject)\n        {\n            $bytes = New-Object -TypeName Byte[] -Argument $count\n            $rng.GetBytes($bytes)\n            [System.BitConverter]::ToInt32($bytes,0)\n        }\n    }\n    End \n    {\n        Remove-Variable -Name rng -Scope Local\n    }\n}\n\n4,8,16,32,64,128 | Get-RandomInteger | Format-Wide {$_} -Column 6 -Force\n\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using a system's built-in mechanism, not just a software algorithm like \/dev\/urandom devices in Unix. The generated number is also presented in hexadecimal format.","id":4154}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 4.0\n$string = \"top and tail\"\n$string\n$string.Substring(1)\n$string.Substring(0, $string.Length - 1)\n$string.Substring(1, $string.Length - 2)\n\n$string = \"top and tail\"\n$string\n$string[1..($string.Length - 1)] -join \"\"\n$string[0..($string.Length - 2)] -join \"\"\n$string[1..($string.Length - 2)] -join \"\"\n\n\ntop and tail\nop and tail\ntop and tai\nop and tai\n\n","human_summarization":"demonstrate how to remove the first, last, or both characters from a string, accounting for any valid Unicode code point in UTF-8 or UTF-16 encoding. The program references logical characters, not 8-bit or 16-bit code units.","id":4155}
    {"lang_cluster":"PowerShell","source_code":"\nif (Get-Process -Name \"notepad\" -ErrorAction SilentlyContinue)\n{\n    Write-Warning -Message \"notepad is already running.\"\n}\nelse\n{\n    Start-Process -FilePath C:\\Windows\\notepad.exe\n}\n\n\n\n","human_summarization":"The code checks if an instance of an application is already running. If so, it displays a warning message and exits. If not, it starts the application.","id":4156}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 3\n$A = 1, 2, 3, 4, 5\nGet-Random $A -Count $A.Count\nWorks with: PowerShell version 2\nfunction shuffle ($a) {\n    $c = $a.Clone()  # make copy to avoid clobbering $a\n    1..($c.Length - 1) | ForEach-Object {\n        $i = Get-Random -Minimum $_ -Maximum $c.Length\n        $c[$_-1],$c[$i] = $c[$i],$c[$_-1]\n        $c[$_-1]  # return newly-shuffled value\n    }\n    $c[-1]  # last value\n}\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. It can be modified to return a new shuffled array if in-place modification is not possible. The algorithm can also be adjusted to iterate from left to right if needed. The function takes an array as input and returns a shuffled array.","id":4157}
    {"lang_cluster":"PowerShell","source_code":"\nfunction last-dayofweek {\n    param(\n     [Int][ValidatePattern(\"[1-9][0-9][0-9][0-9]\")]$year,\n     [String][validateset('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')]$dayofweek\n    )\n    $date = (Get-Date -Year $year -Month 1 -Day 1)\n    while($date.DayOfWeek -ne $dayofweek) {$date = $date.AddDays(1)}\n    while($date.year -eq $year) {\n        if($date.Month -ne $date.AddDays(7).Month) {$date.ToString(\"yyyy-dd-MM\")}\n        $date = $date.AddDays(7)\n    }\n}\nlast-dayofweek 2012 \"Friday\"\n\n\n2012-01-27\n2012-02-24\n2012-03-30\n2012-04-27\n2012-05-25\n2012-06-29\n2012-07-27\n2012-08-31\n2012-09-28\n2012-10-26\n2012-11-30\n2012-12-28\n\n\nfunction Get-Date0fDayOfWeek\n{\n    [CmdletBinding(DefaultParameterSetName=\"None\")]\n    [OutputType([datetime])]\n    Param\n    (\n        [Parameter(Mandatory=$false,\n                   ValueFromPipeline=$true,\n                   ValueFromPipelineByPropertyName=$true,\n                   Position=0)]\n        [ValidateRange(1,12)]\n        [int]\n        $Month = (Get-Date).Month,\n\n        [Parameter(Mandatory=$false,\n                   ValueFromPipelineByPropertyName=$true,\n                   Position=1)]\n        [ValidateRange(1,9999)]\n        [int]\n        $Year = (Get-Date).Year,\n\n        [Parameter(Mandatory=$true, ParameterSetName=\"Sunday\")]\n        [switch]\n        $Sunday,\n\n        [Parameter(Mandatory=$true, ParameterSetName=\"Monday\")]\n        [switch]\n        $Monday,\n\n        [Parameter(Mandatory=$true, ParameterSetName=\"Tuesday\")]\n        [switch]\n        $Tuesday,\n\n        [Parameter(Mandatory=$true, ParameterSetName=\"Wednesday\")]\n        [switch]\n        $Wednesday,\n\n        [Parameter(Mandatory=$true, ParameterSetName=\"Thursday\")]\n        [switch]\n        $Thursday,\n\n        [Parameter(Mandatory=$true, ParameterSetName=\"Friday\")]\n        [switch]\n        $Friday,\n\n        [Parameter(Mandatory=$true, ParameterSetName=\"Saturday\")]\n        [switch]\n        $Saturday,\n\n        [switch]\n        $First,\n\n        [switch]\n        $Last,\n\n        [switch]\n        $AsString,\n\n        [Parameter(Mandatory=$false)]\n        [ValidateNotNullOrEmpty()]\n        [string]\n        $Format = \"dd-MMM-yyyy\"\n    )\n\n    Process\n    {\n        [datetime[]]$dates = 1..[DateTime]::DaysInMonth($Year,$Month) | ForEach-Object {\n            Get-Date -Year $Year -Month $Month -Day $_ -Hour 0 -Minute 0 -Second 0 |\n            Where-Object -Property DayOfWeek -Match $PSCmdlet.ParameterSetName\n        }\n\n        if ($First -or $Last)\n        {\n            if ($AsString)\n            {\n                if ($First) {$dates[0].ToString($Format)}\n                if ($Last)  {$dates[-1].ToString($Format)}\n            }\n            else\n            {\n                if ($First) {$dates[0]}\n                if ($Last)  {$dates[-1]}\n            }\n        }\n        else\n        {\n            if ($AsString)\n            {\n                $dates | ForEach-Object {$_.ToString($Format)}\n            }\n            else\n            {\n                $dates\n            }\n        }\n    }\n}\n\n\n1..12 | Get-Date0fDayOfWeek -Year 2012 -Last -Friday\n\n\n","human_summarization":"The code takes a year as input and returns the dates of the last Fridays of each month for that year. It accepts both integer and DateTime values for the month and year parameters, and can output the results as DateTime objects or formatted time strings. It also supports pipeline input based on the month parameter.","id":4158}
    {"lang_cluster":"PowerShell","source_code":"\nWrite-Host -NoNewLine \"Goodbye, \"\nWrite-Host -NoNewLine \"World!\"\n\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":4159}
    {"lang_cluster":"PowerShell","source_code":"\n\n#region Define the Windows Form\n[Void][Reflection.Assembly]::LoadWithPartialName(\"System.Windows.Forms\")\n\n$Form1 = New-Object System.Windows.Forms.Form\n$label1 = New-Object System.Windows.Forms.Label\n$label2 = New-Object System.Windows.Forms.Label\n$txtInputText = New-Object System.Windows.Forms.TextBox\n$txtInputNumber = New-Object System.Windows.Forms.TextBox\n$btnAccept = New-Object System.Windows.Forms.Button\n$label3 = New-Object System.Windows.Forms.Label\n$btnCancel = New-Object System.Windows.Forms.Button\n$SuspendLayout\n# \n# label1\n# \n$label1.AutoSize = $true\n$label1.Location = New-Object System.Drawing.Point(23, 36)\n$label1.Name = \"label1\"\n$label1.Size = New-Object System.Drawing.Size(34, 13)\n$label1.TabIndex = 0\n$label1.Text = \"String\"\n# \n# label2\n# \n$label2.AutoSize = $true\n$label2.Location = New-Object System.Drawing.Point(13, 62)\n$label2.Name = \"label2\"\n$label2.Size = New-Object System.Drawing.Size(44, 13)\n$label2.TabIndex = 1\n$label2.Text = \"Number\"\n# \n# txtInputText\n# \n$txtInputText.Location = New-Object System.Drawing.Point(63, 33)\n$txtInputText.Name = \"txtInputText\"\n$txtInputText.Size = New-Object System.Drawing.Size(100, 20)\n$txtInputText.TabIndex = 0\n# \n# txtInputNumber\n# \n$txtInputNumber.Location = New-Object System.Drawing.Point(63, 59)\n$txtInputNumber.Name = \"txtInputNumber\"\n$txtInputNumber.Size = New-Object System.Drawing.Size(100, 20)\n$txtInputNumber.TabIndex = 1\n$txtInputNumber.Text = \"75000\"\n# \n# btnAccept\n# \n$btnAccept.DialogResult = [System.Windows.Forms.DialogResult]::OK\n$btnAccept.Location = New-Object System.Drawing.Point(16, 94)\n$btnAccept.Name = \"btnAccept\"\n$btnAccept.Size = New-Object System.Drawing.Size(75, 23)\n$btnAccept.TabIndex = 2\n$btnAccept.Text = \"Accept\"\n$btnAccept.UseVisualStyleBackColor = $true\n$btnAccept.add_Click({$rc=\"Accept\"; $Form1.Close()})\n# \n# label3\n# \n$label3.AutoSize = $true\n$label3.Location = New-Object System.Drawing.Point(13, 9)\n$label3.Name = \"label3\"\n$label3.Size = New-Object System.Drawing.Size(173, 13)\n$label3.TabIndex = 5\n$label3.Text = \"Please input a string and a number:\"\n# \n# btnCancel\n# \n$btnCancel.DialogResult = [System.Windows.Forms.DialogResult]::Cancel\n$btnCancel.Location = New-Object System.Drawing.Point(97, 94)\n$btnCancel.Name = \"btnCancel\"\n$btnCancel.Size = New-Object System.Drawing.Size(75, 23)\n$btnCancel.TabIndex = 3\n$btnCancel.Text = \"Cancel\"\n$btnCancel.UseVisualStyleBackColor = $true\n# \n# Form1\n# \n$Form1.AcceptButton = $btnAccept\n$Form1.CancelButton = $btnCancel\n$Form1.ClientSize = New-Object System.Drawing.Size(196, 129)\n$Form1.ControlBox = $false\n$Form1.Controls.Add($btnCancel)\n$Form1.Controls.Add($label3)\n$Form1.Controls.Add($btnAccept)\n$Form1.Controls.Add($txtInputNumber)\n$Form1.Controls.Add($txtInputText)\n$Form1.Controls.Add($label2)\n$Form1.Controls.Add($label1)\n$Form1.Name = \"Form1\"\n$Form1.Text = \"RosettaCode\"\n\n#endregion Define the Windows Form\n\n### Show the input form\n$f = $Form1.ShowDialog()\nif ( $f -eq [System.Windows.Forms.DialogResult]::Cancel ) { \"User selected Cancel\" }\nelse { \"User entered `\"{0}`\" for the text and {1} for the number\" -f $txtInputText.Text, $txtInputNumber.Text }\n\n","human_summarization":"implement a graphical user interface in PowerShell, a .NET language, to input a string and the integer 75000, utilizing the full functionality of the System.Windows.Forms assembly.","id":4160}
    {"lang_cluster":"PowerShell","source_code":"\n# Author: M. McNabb\nfunction Get-CaesarCipher\n{\nParam\n(\n[Parameter(\nMandatory=$true,ValueFromPipeline=$true)]\n[string]\n$Text,\n\n[ValidateRange(1,25)]\n[int]\n$Key = 1,\n\n[switch]\n$Decode\n)\n\nbegin\n{    \n    $LowerAlpha = [char]'a'..[char]'z'\n    $UpperAlpha = [char]'A'..[char]'Z'\n}\n\nprocess\n{\n    $Chars = $Text.ToCharArray()\n    \n    function encode\n    {\n        param\n        (\n        $Char,\n        $Alpha = [char]'a'..[char]'z'\n        )\n        $Index = $Alpha.IndexOf([int]$Char)\n        $NewIndex = ($Index + $Key) - $Alpha.Length\n        $Alpha[$NewIndex]\n    }\n    \n    function decode\n    {\n        param\n        (\n        $Char,\n        $Alpha = [char]'a'..[char]'z'\n        )\n        $Index = $Alpha.IndexOf([int]$Char)\n        $int = $Index - $Key\n        if ($int -lt 0) {$NewIndex = $int + $Alpha.Length}\n        else {$NewIndex = $int}\n        $Alpha[$NewIndex]\n    }\n\n    foreach ($Char in $Chars)\n    {\n        if ([int]$Char -in $LowerAlpha)\n        {\n            if ($Decode) {$Char = decode $Char}\n            else {$Char = encode $Char}\n        }\n        elseif ([int]$Char -in $UpperAlpha)\n        {\n            if ($Decode) {$Char = decode $Char $UpperAlpha}\n            else {$Char = encode $Char $UpperAlpha}\n        }\n        \n        $Char = [char]$Char\n        [string]$OutText += $Char\n    }\n\n    $OutText\n    $OutText = $null\n}\n}\n\n\nEncode:\nPS C:\\> 'Pack my box with five dozen liquor jugs.' | Get-CaesarCipher -key 3\nSdfn pb era zlwk ilyh grchq oltxru mxjv.\n\nDecode:\nPS C:\\> 'Sdfn pb era zlwk ilyh grchq oltxru mxjv.' | Get-CaesarCipher -key 3 -Decode\nPack my box with five dozen liquor jugs.\n\nEncode lines of text from a file:\nPS C:\\> Get-Content C:\\Text.txt | Get-CaesarCipher -key 10\nVsxo yxo.\nVsxo dgy!\nVsxo drboo;\n\n","human_summarization":"implement both encoding and decoding functions for a Caesar cipher. The cipher uses a key between 1 and 25 to rotate the alphabet letters either left or right. The encoding function replaces each letter with the 1st to 25th next letter in the alphabet, looping from Z back to A. The code also includes examples of how to use the cipher. Despite its simplicity, the cipher provides minimal security as it can be easily cracked through frequency analysis or by trying all 25 keys. The Caesar cipher is identical to the Vigen\u00e8re cipher with a key length of 1 and to the Rot-13 cipher with a key of 13.","id":4161}
    {"lang_cluster":"PowerShell","source_code":"\nfunction gcd ($a, $b)  {\n    function pgcd ($n, $m)  {\n        if($n -le $m) { \n            if($n -eq 0) {$m}\n            else{pgcd $n ($m-$n)}\n        }\n        else {pgcd $m $n}\n    }\n    $n = [Math]::Abs($a)\n    $m = [Math]::Abs($b)\n    (pgcd $n $m)\n}\nfunction lcm ($a, $b)  {\n    [Math]::Abs($a*$b)\/(gcd $a $b)\n}\nlcm 12 18\n\n\nfunction gcd ($a, $b)  {\n    function pgcd ($n, $m)  {\n        if($n -le $m) { \n            if($n -eq 0) {$m}\n            else{pgcd $n ($m%$n)}\n        }\n        else {pgcd $m $n}\n    }\n    $n = [Math]::Abs($a)\n    $m = [Math]::Abs($b)\n    (pgcd $n $m)\n}\nfunction lcm ($a, $b)  {\n    [Math]::Abs($a*$b)\/(gcd $a $b)\n}\nlcm 12 18\n\n\n36\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers, m and n. The LCM is the smallest positive integer that is a multiple of both m and n. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m x n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of m and n.","id":4162}
    {"lang_cluster":"PowerShell","source_code":"\nfunction Get-CheckDigitCUSIP {\n    [CmdletBinding()]\n    [OutputType([int])]\n    Param ( #  Validate input\n        [Parameter(Mandatory=$true, Position=0)]\n        [ValidatePattern( '^[A-Z0-9@#*]{8}\\d$' )] # @#*\n        [ValidateScript({$_.Length -eq 9})]\n        [string]\n        $cusip\n    )\n    $sum = 0\n    0..7 | ForEach { $c = $cusip[$_] ; $v = $null\n        if ([Char]::IsDigit($c)) { $v = [char]::GetNumericValue($c) }\n        if ([Char]::IsLetter($c)) { $v = [int][char]$c - [int][char]'A' +10 }\n        if ($c -eq '*') { $v = 36 }\n        if ($c -eq '@') { $v = 37 }\n        if ($c -eq '#') { $v = 38 }\n        if($_ % 2){ $v += $v }\n        $sum += [int][Math]::Floor($v \/ 10 ) + ($v % 10)\n    }\n    [int]$checkDigit_calculated = ( 10 - ($sum % 10) ) % 10\n    return( $checkDigit_calculated )\n}\n\nfunction Test-IsCUSIP {\n    [CmdletBinding()]\n    [OutputType([bool])]\n    Param (\n        [Parameter(Mandatory=$true, Position=0)]\n        [ValidatePattern( '^[A-Z0-9@#*]{8}\\d$' )]\n        [ValidateScript({$_.Length -eq 9})]\n        [string]\n        $cusip\n    )\n    [int]$checkDigit_told = $cusip[-1].ToString()\n    $checkDigit_calculated = Get-CheckDigitCUSIP $cusip\n    ($checkDigit_calculated -eq $checkDigit_told)\n}\n\n$data = @\"\n037833100`tApple Incorporated\n17275R102`tCisco Systems\n38259P508`tGoogle Incorporated\n594918104`tMicrosoft Corporation\n68389X106`tOracle Corporation   (incorrect)\n68389X105`tOracle Corporation\n\"@ -split \"`n\"\n$data |%{ Test-IsCUSIP $_.Split(\"`t\")[0] }\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":4163}
    {"lang_cluster":"PowerShell","source_code":"\nWrite-Host Word Size: ((Get-WMIObject Win32_Processor).DataWidth)\nWrite-Host -NoNewLine \"Endianness: \"\nif ([BitConverter]::IsLittleEndian) {\n    Write-Host Little-Endian\n} else {\n    Write-Host Big-Endian\n}\n\n\n","human_summarization":"prints the word size and endianness of the host machine. It's important to note that the endianness check is mostly irrelevant for PowerShell as it currently only has a Windows implementation, and current Windows versions don't operate on big-endian systems. However, theoretically, this check should still function.","id":4164}
    {"lang_cluster":"PowerShell","source_code":"$get1 = (New-Object Net.WebClient).DownloadString(\"http:\/\/www.rosettacode.org\/w\/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=700&format=json\")\n$get2 = (New-Object Net.WebClient).DownloadString(\"http:\/\/www.rosettacode.org\/w\/index.php?title=Special:Categories&limit=5000\")\n$match1 = [regex]::matches($get1, \"`\"title`\":`\"Category:(.+?)`\"\")\n$match2 = [regex]::matches($get2, \"title=`\"Category:([^`\"]+?)`\">[^<]+?<\/a>[^\\(]*\\((\\d+) members\\)\")\n$r = 1\n$langs = $match1 | foreach { $_.Groups[1].Value.Replace(\"\\\",\"\") }\n$res = $match2 | sort -Descending {[Int]$($_.Groups[2].Value)} | foreach {\n    if ($langs.Contains($_.Groups[1].Value))\n    {\n        [pscustomobject]@{\n            Rank = \"$r\"\n            Members =  \"$($_.Groups[2].Value)\"\n            Language = \"$($_.Groups[1].Value)\"           \n        }\n        $r++\n    }\n} \n1..30 | foreach{ \n    [pscustomobject]@{\n        \"Rank 1..30\" = \"$($_)\"\n        \"Members 1..30\" =  \"$($res[$_-1].Members)\"\n        \"Language 1..30\" = \"$($res[$_-1].Language)\"\n        \"Rank 31..60\" = \"$($_+30)\"\n        \"Members 31..60\" =  \"$($res[$_+30].Members)\"\n        \"Language 31..60\" = \"$($res[$_+30].Language)\"\n    } \n}| Format-Table -AutoSize\n\n\nRank 1..30 Members 1..30 Language 1..30 Rank 31..60 Members 31..60 Language 31..60\n---------- ------------- -------------- ----------- -------------- ---------------\n1          887           Tcl            31          405            Seed7          \n2          877           Racket         32          397            Julia          \n3          853           Python         33          389            PL\/I           \n4          798           J              34          387            Fortran        \n5          775           Ruby           35          386            ALGOL 68       \n6          766           Perl 6         36          376            Lua            \n7          758           C              37          369            Pascal         \n8          746           Go             38          367            R              \n9          740           D              39          364            Groovy         \n10         710           Perl           40          363            F Sharp        \n11         701           REXX           41          363            Forth          \n12         692           PicoLisp       42          358            PHP            \n13         682           Haskell        43          342            AWK            \n14         675           Mathematica    44          340            Sidef          \n15         652           Java           45          335            MATLAB         \n16         623           Ada            46          325            Liberty BASIC  \n17         591           AutoHotkey     47          297            Octave         \n18         562           C++            48          287            Factor         \n19         551           Common Lisp    49          286            Scheme         \n20         548           Scala          50          285            NetRexx        \n21         532           BBC BASIC      51          284            Oforth         \n22         523           Icon           52          280            Oz             \n23         516           C sharp        53          274            Run BASIC      \n24         508           OCaml          54          272            E              \n25         502           Nim            55          271            Bracmat        \n26         488           PureBasic      56          268            PowerShell     \n27         487           Clojure        57          263            Prolog         \n28         455           Erlang         58          260            Lasso          \n29         441           PARI\/GP        59          249            Delphi         \n30         434           JavaScript     60          239            Smalltalk  \n$response = (New-Object Net.WebClient).DownloadString(\"http:\/\/rosettacode.org\/wiki\/Category:Programming_Languages\")\n$languages = [regex]::matches($response,'title=\"Category:(.*?)\">') | foreach {$_.Groups[1].Value}\n\n$response = [Net.WebClient]::new().DownloadString(\"http:\/\/rosettacode.org\/w\/index.php?title=Special:Categories&limit=5000\")\n$response = [regex]::Replace($response,'(\\d+),(\\d+)','$1$2') \n\n$members  = [regex]::matches($response,'<li><a[^>]+>([^<]+)<\/a>[^(]*[(](\\d+) member[s]?[)]<\/li>') | foreach { [pscustomobject]@{\n            Members =  [Int]($_.Groups[2].Value)\n            Language = [String]($_.Groups[1].Value)          \n        }} | where {$languages.Contains($_.Language)} | sort -Descending Members\n\nGet-Date -UFormat \"Sample output on %d %B %Y at %R %Z\"\n$members | Select-Object -First 10 | foreach -Begin {$r, $rank, $count = 0, 0,-1} {\n    $r++\n    if ($count -ne $_.Members) {$rank = $r}\n    $count = $_.Members\n    $x = $_.Members.ToString(\"N0\",[System.Globalization.CultureInfo]::CreateSpecificCulture('en-US'))\n    $entry = \"($x entries)\"\n    [String]::Format(\"Rank: {0,2} {1,15} {2}\",$rank,$entry,$_.Language)\n}\n\n\n","human_summarization":"The code sorts and ranks the most popular computer programming languages based on the number of members in Rosetta Code categories. It accesses data through web scraping or API methods, with optional filtering for incorrect results. The code also provides a complete ranked listing of all programming languages.","id":4165}
    {"lang_cluster":"PowerShell","source_code":"\n$colors = \"Black\",\"Blue\",\"Cyan\",\"Gray\",\"Green\",\"Magenta\",\"Red\",\"White\",\"Yellow\",\n          \"DarkBlue\",\"DarkCyan\",\"DarkGray\",\"DarkGreen\",\"DarkMagenta\",\"DarkRed\",\"DarkYellow\"\n\nforeach ($color in $colors)\n{\n    Write-Host \"$color\" -ForegroundColor $color\n}\n\n","human_summarization":"Iterates through each element in a collection in order and prints it, using a \"for each\" loop or another loop if \"for each\" is not available in the language.","id":4166}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 1\n$words = \"Hello,How,Are,You,Today\".Split(',')\n[string]::Join('.', $words)\nWorks with: PowerShell version 2\n$words = \"Hello,How,Are,You,Today\" -split ','\n$words -join '.'\nWorks with: PowerShell version 2\n\n\"Hello,How,Are,You,Today\", \",,Hello,,Goodbye,,\" | ForEach-Object {($_.Split(',',[StringSplitOptions]::RemoveEmptyEntries)) -join \".\"}\n\n","human_summarization":"\"Tokenizes a string by separating it into an array using commas, then displays the words to the user separated by a period, while ensuring no empty elements are returned using the StringSplitOptions enumeration.\"","id":4167}
    {"lang_cluster":"PowerShell","source_code":"\nfunction Get-GCD ($x, $y)\n{\n  if ($x -eq $y) { return $y }\n  if ($x -gt $y) {\n    $a = $x\n    $b = $y\n  }\n  else {\n    $a = $y\n    $b = $x\n  }\n  while ($a\u00a0% $b -ne 0) {\n    $tmp = $a\u00a0% $b\n    $a = $b\n    $b = $tmp\n  }\n  return $b\n}\n\nfunction Get-GCD ($x, $y) {\n  if ($y -eq 0) { $x } else { Get-GCD $y ($x%$y) }\n}\n\nFunction Get-GCD( $x, $y ) {\n    while ($y -ne 0) {\n        $x, $y = $y, ($x\u00a0% $y)\n    }\n    [Math]::abs($x)\n}\n","human_summarization":"find the greatest common divisor (GCD), also known as the greatest common factor (GCF) or greatest common measure, of two integers. It is related to the task of finding the least common multiple. The implementation is based on Python.","id":4168}
    {"lang_cluster":"PowerShell","source_code":"\n\nfunction isNumeric ($x) {\n    try {\n        0 + $x | Out-Null\n        return $true\n    } catch {\n        return $false\n    }\n}\n\nfunction isNumeric ($x) {\n    $x2 = 0\n    $isNum = [System.Int32]::TryParse($x, [ref]$x2)\n    return $isNum\n}\n","human_summarization":"implement a boolean function to check if a given string is numeric, including floating point and negative numbers. The function uses arithmetic operations and returns false if it fails. However, it doesn't correctly handle strings like \"8.\". Alternatively, it can use the .NET framework's System.Int32.TryParse() method. Note that PowerShell 1.0 does not support 'try'.","id":4169}
    {"lang_cluster":"PowerShell","source_code":"\n$wc = New-Object Net.WebClient\n$wc.DownloadString('https:\/\/sourceforge.net')\n\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\" without authentication, print the obtained resource to the console, and check the host certificate for validity. If the certificate is not valid, an exception is thrown.","id":4170}
    {"lang_cluster":"PowerShell","source_code":"\nfunction Get-Ranking\n{\n    [CmdletBinding(DefaultParameterSetName=\"Standard\")]\n    [OutputType([PSCustomObject])]\n    Param\n    (\n        [Parameter(Mandatory=$true,\n                   ValueFromPipeline=$true,\n                   ValueFromPipelineByPropertyName=$true,\n                   Position=0)]\n        [string]\n        $InputObject,\n\n        [Parameter(Mandatory=$false,\n                   ParameterSetName=\"Standard\")]\n        [switch]\n        $Standard,\n\n        [Parameter(Mandatory=$false,\n                   ParameterSetName=\"Modified\")]\n        [switch]\n        $Modified,\n\n        [Parameter(Mandatory=$false,\n                   ParameterSetName=\"Dense\")]\n        [switch]\n        $Dense,\n\n        [Parameter(Mandatory=$false,\n                   ParameterSetName=\"Ordinal\")]\n        [switch]\n        $Ordinal,\n\n        [Parameter(Mandatory=$false,\n                   ParameterSetName=\"Fractional\")]\n        [switch]\n        $Fractional\n    )\n\n    Begin\n    {\n        function Get-OrdinalRank ([PSCustomObject[]]$Values)\n        {\n            for ($i = 0; $i -lt $Values.Count; $i++)\n            { \n                $Values[$i].Rank = $i + 1\n            }\n\n            $Values\n        }\n\n        function Get-Rank ([PSCustomObject[]]$Scores)\n        {\n            foreach ($score in $Scores)\n            {\n                $score.Group | ForEach-Object {$_.Rank = $score.Rank}\n            }\n\n            $Scores.Group\n        }\n\n        function New-Competitor ([string]$Name, [int]$Score, [int]$Rank = 0)\n        {\n            [PSCustomObject]@{\n                Name  = $Name\n                Score = $Score\n                Rank  = $Rank\n            }\n        }\n\n        $competitors = @()\n        $scores = @()\n    }\n    Process\n    {\n        @($input) | ForEach-Object {$competitors += New-Competitor -Name $_.Split()[1] -Score $_.Split()[0]}\n    }\n    End\n    {\n        $scores = $competitors |\n            Sort-Object   -Property Score -Descending |\n            Group-Object  -Property Score |\n            Select-Object -Property @{Name=\"Score\"; Expression={[int]$_.Name}}, @{Name=\"Rank\"; Expression={0}}, Count, Group\n\n        switch ($PSCmdlet.ParameterSetName)\n        {\n            \"Standard\"\n            {\n                $rank = 1\n\n                for ($i = 0; $i -lt $scores.Count; $i++)\n                { \n                    $scores[$i].Rank = $rank\n                    $rank += $scores[$i].Count\n                }\n\n                Get-Rank $scores\n            }\n            \"Modified\"\n            {\n                $rank = 0\n\n                foreach ($score in $scores)\n                {\n                    $rank = $score.Count + $rank\n                    $score.Rank = $rank\n                }\n\n                Get-Rank $scores\n            }\n            \"Dense\"\n            {\n                for ($i = 0; $i -lt $scores.Count; $i++)\n                { \n                    $scores[$i].Rank = $i + 1\n                }\n\n                Get-Rank $scores\n            }\n            \"Ordinal\"\n            {\n                Get-OrdinalRank $competitors\n            }\n            \"Fractional\"\n            {\n                Get-OrdinalRank $competitors | Group-Object -Property Score | ForEach-Object {\n                    if ($_.Count -gt 1)\n                    {\n                        $rank = ($_.Group.Rank | Measure-Object -Average).Average\n\n                        foreach ($competitor in $_.Group)\n                        {\n                            $competitor.Rank = $rank\n                        }\n                    }\n                }\n\n                $competitors\n            }\n        }\n    }\n}\n\n$scores = \"44 Solomon\",\"42 Jason\",\"42 Errol\",\"41 Garry\",\"41 Bernard\",\"41 Barry\",\"39 Stephen\"\n\n$scores | Get-Ranking -Standard\n\n\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":4171}
    {"lang_cluster":"PowerShell","source_code":"$rad = [Math]::PI \/ 4\n$deg = 45\n'{0,10} {1,10}' -f 'Radians','Degrees'\n'{0,10:N6} {1,10:N6}' -f [Math]::Sin($rad), [Math]::Sin($deg * [Math]::PI \/ 180)\n'{0,10:N6} {1,10:N6}' -f [Math]::Cos($rad), [Math]::Cos($deg * [Math]::PI \/ 180)\n'{0,10:N6} {1,10:N6}' -f [Math]::Tan($rad), [Math]::Tan($deg * [Math]::PI \/ 180)\n$temp = [Math]::Asin([Math]::Sin($rad))\n'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 \/ [Math]::PI)\n$temp = [Math]::Acos([Math]::Cos($rad))\n'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 \/ [Math]::PI)\n$temp = [Math]::Atan([Math]::Tan($rad))\n'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 \/ [Math]::PI)\n\n\n","human_summarization":"demonstrate the use of trigonometric functions including sine, cosine, tangent and their inverses using the same angle in both radians and degrees. The output is an array of objects containing the results in both radians and degrees. The code also handles cases where the language does not have built-in trigonometric functions, by calculating these functions based on known approximations or identities.","id":4172}
    {"lang_cluster":"PowerShell","source_code":"\n$Start_Time = (Get-date).second\nWrite-Host \"Type CTRL-C to Terminate...\"\n$n = 1\nTry\n{\n    While($true)\n    {\n        Write-Host $n\n        $n ++\n        Start-Sleep -m 500\n    }\n}\nFinally\n{\n    $End_Time = (Get-date).second\n    $Time_Diff = $End_Time - $Start_Time\n    Write-Host \"Total time in seconds\"$Time_Diff\n}\n\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.","id":4173}
    {"lang_cluster":"PowerShell","source_code":"\n\n$s = \"12345\"\n$t = [string] ([int] $s + 1)\n\n$t = [string] (1 + $s)\n","human_summarization":"convert a numerical string to an integer, increment the value, and then convert it back to a string. The code also utilizes PowerShell's automatic casting based on the left-most operand to reduce the number of casts.","id":4174}
    {"lang_cluster":"PowerShell","source_code":"\n<#\n.Synopsis\n    Finds the deepest common directory path of files passed through the pipeline.\n.Parameter File\n    PowerShell file object.\n#>\nfunction Get-CommonPath {\n[CmdletBinding()]\n    param (\n        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]\n        [System.IO.FileInfo] $File\n    )\n    process {\n        # Get the current file's path list\n        $PathList =  $File.FullName -split \"\\$([IO.Path]::DirectorySeparatorChar)\"\n        # Get the most common path list\n        if ($CommonPathList) {\n            $CommonPathList = (Compare-Object -ReferenceObject $CommonPathList -DifferenceObject $PathList -IncludeEqual `\n                -ExcludeDifferent -SyncWindow 0).InputObject\n        } else {\n            $CommonPathList = $PathList\n        }\n    }\n    end {\n        $CommonPathList -join [IO.Path]::DirectorySeparatorChar\n    }\n}\n\n\n\"C:\\a\\b\\c\\d\\e\",\"C:\\a\\b\\e\\f\",\"C:\\a\\b\\c\\d\\x\" | Get-CommonPath\nC:\\a\\b\n\n","human_summarization":"\"Output: The code defines a routine that identifies the common directory path from a set of directory paths using a specified directory separator. It tests this routine using '\/' as the directory separator and three specific strings as input paths. The code also identifies if there's a built-in function in the language used that can perform this task.\"","id":4175}
    {"lang_cluster":"PowerShell","source_code":"\n\nfunction Measure-Data\n{\n    [CmdletBinding()]\n    [OutputType([PSCustomObject])]\n    Param\n    (\n        [Parameter(Mandatory=$true,\n                   Position=0)]\n        [double[]]\n        $Data\n    )\n\n    Begin\n    {\n        function Get-Mode ([double[]]$Data)\n        {\n            if ($Data.Count -gt ($Data | Select-Object -Unique).Count)\n            {\n                $groups = $Data | Group-Object | Sort-Object -Property Count -Descending\n\n                return ($groups | Where-Object {[double]$_.Count -eq [double]$groups[0].Count}).Name | ForEach-Object {[double]$_}\n            }\n            else\n            {\n                return $null\n            }\n        }\n\n        function Get-StandardDeviation ([double[]]$Data)\n        {\n            $variance = 0            \n            $average  = $Data | Measure-Object -Average | Select-Object -Property Count, Average\n\n            foreach ($number in $Data)\n            {            \n                $variance +=  [Math]::Pow(($number - $average.Average),2)\n            }\n\n            return [Math]::Sqrt($variance \/ ($average.Count-1))\n        }\n\n        function Get-Median ([double[]]$Data)\n        {\n            if ($Data.Count % 2)\n            {\n                return $Data[[Math]::Floor($Data.Count\/2)]\n            }\n            else\n            {\n                return ($Data[$Data.Count\/2], $Data[$Data.Count\/2-1] | Measure-Object -Average).Average\n            }\n        }\n    }\n    Process\n    {\n        $Data = $Data | Sort-Object\n\n        $Data | Measure-Object -Maximum -Minimum -Sum -Average |\n                Select-Object -Property Count,\n                                        Sum,\n                                        Minimum,\n                                        Maximum,\n                                        @{Name='Range'; Expression={$_.Maximum - $_.Minimum}},\n                                        @{Name='Mean' ; Expression={$_.Average}} |\n                Add-Member -MemberType NoteProperty -Name Median            -Value (Get-Median $Data)            -PassThru |\n                Add-Member -MemberType NoteProperty -Name StandardDeviation -Value (Get-StandardDeviation $Data) -PassThru |\n                Add-Member -MemberType NoteProperty -Name Mode              -Value (Get-Mode $Data)              -PassThru\n    }\n}\n\n$statistics = Measure-Data 4, 5, 6, 7, 7, 7, 8, 1, 1, 1, 2, 3\n$statistics\n\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles cases with even number of elements by returning the average of the two middle values. It uses the selection algorithm for efficient computation. It also includes functions for calculating various statistical measures like mean, mode, and standard deviation.","id":4176}
    {"lang_cluster":"PowerShell","source_code":"\nfor ($i = 1; $i -le 100; $i++) {\n    if ($i\u00a0% 15 -eq 0) {\n        \"FizzBuzz\"\n    } elseif ($i\u00a0% 5 -eq 0) {\n        \"Buzz\"\n    } elseif ($i\u00a0% 3 -eq 0) {\n        \"Fizz\"\n    } else {\n        $i\n    }\n}\n$txt=$null\n1..100 | ForEach-Object {\n    switch ($_) {\n        { $_\u00a0% 3 -eq 0 }  { $txt+=\"Fizz\" }\n        { $_\u00a0% 5 -eq 0 }  { $txt+=\"Buzz\" }\n        $_                { if($txt) { $txt } else { $_ }; $txt=$null }\n    }\n}1..100 | ForEach-Object {\n    $s = ''\n    if ($_\u00a0% 3 -eq 0) { $s += \"Fizz\" }\n    if ($_\u00a0% 5 -eq 0) { $s += \"Buzz\" }\n    if (-not $s) { $s = $_ }\n    $s\n}\nPiping, Evaluation, 1..100 |\u00a0% {write-host(\"$(if(($_\u00a0% 3 -ne 0) -and ($_\u00a0% 5 -ne 0)){$_})$(if($_\u00a0% 3 -eq 0){\"Fizz\"})$(if($_\u00a0% 5 -eq 0){\"Buzz\"})\")}\nfilter fizz-buzz{\n    @(\n        $_, \n        \"Fizz\", \n        \"Buzz\", \n        \"FizzBuzz\"\n    )[\n        2 * \n        ($_ -match '[05]$') + \n        ($_ -match '(^([369][0369]?|[258][147]|[147][258]))$')\n    ]\n}\n\n1..100 | fizz-buzz\n(1..100 -join \"`n\") + \"`nFizzBuzz\" -replace '(?ms)(^([369]([369]|(?=0|$))|[258][147]|[147]([28]|(?=5))))(?=[05]?$.*(Fizz))|(((?<=[369])|[^369])0+|((?<=[147\\s])|[^147\\s])5)(?=$.*(Buzz))|FizzBuzz', '$5$9'\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":4177}
    {"lang_cluster":"PowerShell","source_code":"\n$x = $y = $i = $j = $r = -16\n$colors = [Enum]::GetValues([System.ConsoleColor])\n\nwhile(($y++) -lt 15)\n{\n    for($x=0; ($x++) -lt 84; Write-Host \" \" -BackgroundColor ($colors[$k -band 15]) -NoNewline)\n    {\n        $i = $k = $r = 0\n\n        do\n        {\n            $j = $r * $r - $i * $i -2 + $x \/ 25\n            $i = 2 * $r * $i + $y \/ 10\n            $r = $j\n        }\n        while (($j * $j + $i * $i) -lt 11 -band ($k++) -lt 111)\n    }\n\n    Write-Host\n}\n","human_summarization":"generate and draw the Mandelbrot set using various available algorithms and functions.","id":4178}
    {"lang_cluster":"PowerShell","source_code":"\n\nfunction Get-Sum ($a) {\n    return ($a | Measure-Object -Sum).Sum\n}\n\nfunction Get-Product ($a) {\n    if ($a.Length -eq 0) {\n        return 0\n    } else {\n        $p = 1\n        foreach ($x in $a) {\n            $p *= $x\n        }\n        return $p\n    }\n}\n\nWorks with: PowerShell version 2\nfunction Get-Product ($a) {\n    if ($a.Length -eq 0) {\n        return 0\n    }\n    $s = $a -join '*'\n    return (Invoke-Expression $s)\n}\n\nfunction Get-SumAndProduct ($a) {\n    $sum = 0\n    if ($a.Length -eq 0) {\n        $prod = 0\n    } else {\n        $prod = 1\n        foreach ($x in $a) {\n            $sum += $x\n            $prod *= $x\n        }\n    }\n    $ret = New-Object PSObject\n    $ret | Add-Member NoteProperty Sum $sum\n    $ret | Add-Member NoteProperty Product $prod\n    return $ret\n}\n\n","human_summarization":"compute the sum and product of an array of integers using the Measure-Object cmdlet in PowerShell. The function returns a custom object with appropriate properties for both calculations.","id":4179}
    {"lang_cluster":"PowerShell","source_code":"\n$Year = 2016\n[System.DateTime]::IsLeapYear( $Year )\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":4180}
    {"lang_cluster":"PowerShell","source_code":"\n\n$str = \"foo\"\n$dup = $str\n\n$dup = $str.Clone()\n","human_summarization":"make a copy of a string or create an additional reference to an existing string in PowerShell using .NET, considering the immutability of .NET strings. The Clone() method is used for actual copying.","id":4181}
    {"lang_cluster":"PowerShell","source_code":"\nfunction F($n) {\n    if ($n -eq 0) { return 1 }\n    return $n - (M (F ($n - 1)))\n}\n\nfunction M($n) {\n    if ($n -eq 0) { return 0 }\n    return $n - (F (M ($n - 1)))\n}\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":4182}
    {"lang_cluster":"PowerShell","source_code":"\n[System.Web.HttpUtility]::UrlDecode(\"http%3A%2F%2Ffoo%20bar%2F\")\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":4183}
    {"lang_cluster":"PowerShell","source_code":"\nfunction BinarySearch-Iterative ([int[]]$Array, [int]$Value)\n{\n    [int]$low = 0\n    [int]$high = $Array.Count - 1\n\n    while ($low -le $high)\n    {\n        [int]$mid = ($low + $high) \/ 2\n\n        if ($Array[$mid] -gt $Value)\n        {\n            $high = $mid - 1\n        }\n        elseif ($Array[$mid] -lt $Value)\n        {\n            $low = $mid + 1\n        }\n        else\n        {\n            return $mid\n        }\n    }\n\n    return -1\n}\n\nfunction BinarySearch-Recursive ([int[]]$Array, [int]$Value, [int]$Low = 0, [int]$High = $Array.Count)\n{\n    if ($High -lt $Low)\n    {\n        return -1\n    }\n\n    [int]$mid = ($Low + $High) \/ 2\n\n    if ($Array[$mid] -gt $Value)\n    {\n        return BinarySearch $Array $Value $Low ($mid - 1)\n    }\n    elseif ($Array[$mid] -lt $Value)\n    {\n        return BinarySearch $Array $Value ($mid + 1) $High\n    }\n    else\n    {\n        return $mid\n    }\n}\n\nfunction Show-SearchResult ([int[]]$Array, [int]$Search, [ValidateSet(\"Iterative\", \"Recursive\")][string]$Function)\n{\n    switch ($Function)\n    {\n        \"Iterative\" {$index = BinarySearch-Iterative -Array $Array -Value $Search}\n        \"Recursive\" {$index = BinarySearch-Recursive -Array $Array -Value $Search}\n    }\n\n    if ($index -ge 0)\n    {\n        Write-Host (\"Using BinarySearch-{0}: {1} is at index {2}\" -f $Function, $numbers[$index], $index)\n    }\n    else\n    {\n        Write-Host (\"Using BinarySearch-{0}: {1} not found\" -f $Function, $Search) -ForegroundColor Red\n    }\n}\nShow-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 41 -Function Iterative\nShow-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 99 -Function Iterative\nShow-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 86 -Function Recursive\nShow-SearchResult -Array 10, 28, 41, 46, 58, 74, 76, 86, 89, 98 -Search 11 -Function Recursive\n\n","human_summarization":"The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It takes a sorted integer array, a starting point, an ending point, and a \"secret value\" as inputs. The algorithm can be either recursive or iterative and returns whether the number was in the array and its index if found. The code also includes variations of the binary search algorithm that return the leftmost or rightmost insertion point for the given value. It also handles potential overflow bugs.","id":4184}
    {"lang_cluster":"PowerShell","source_code":"\n\n$i = 0\nforeach ($s in $args) {\n    Write-Host Argument (++$i) is $s\n}\n\n","human_summarization":"retrieve and print the list of command-line arguments provided to the program. It also parses these arguments intelligently. In the case of PowerShell, it accesses script arguments through the $args array. An example command line is also provided for reference.","id":4185}
    {"lang_cluster":"PowerShell","source_code":"\n# JSON input is being stored in ordered hashtable.\n# Ordered hashtable is available in PowerShell v3 and higher.\n[ordered]@{ \"foo\"= 1; \"bar\"= 10, \"apples\" } | ConvertTo-Json\n\n# ConvertFrom-Json converts a JSON-formatted string to a custom object.\n# If you use the Invoke-RestMethod cmdlet there is not need for the ConvertFrom-Json cmdlet\nInvoke-WebRequest -Uri \"http:\/\/date.jsontest.com\" | ConvertFrom-Json\n\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON, and validate the JSON.\"","id":4186}
    {"lang_cluster":"PowerShell","source_code":"\n\n#NoTeS: This sample code does not validate inputs\n#\tThus, if there are errors the 'scary' red-text\n#\terror messages will appear.\n#\n#\tThis code will not work properly in floating point values of n,\n#\tand negative values of A.\n#\n#\tSupports negative values of n by reciprocating the root.\n\n$epsilon=1E-10\t\t#Sample Epsilon (Precision)\n\nfunction power($x,$e){\t#As I said in the comment\n\t$ret=1\n\tfor($i=1;$i -le $e;$i++){\n\t\t$ret*=$x\n\t}\n\treturn $ret\n}\nfunction root($y,$n){\t\t\t\t\t#The main Function\n\tif (0+$n -lt 0){$tmp=-$n} else {$tmp=$n}\t#This checks if n is negative.\n\t$ans=1\n\n\tdo{\n\t\t$d = ($y\/(power $ans ($tmp-1)) - $ans)\/$tmp\n\t\t$ans+=$d\n\t} while ($d -lt -$epsilon -or $d -gt $epsilon)\n\n\tif (0+$n -lt 0){return 1\/$ans} else {return $ans}\n}\n\n#Sample Inputs\nroot 625 2\nroot 2401 4\nroot 2 -2\nroot 1.23456789E-20 34\nroot 9.87654321E20 10\t#Quite slow here, I admit...\n\n((root 5 2)+1)\/2\t#Extra: Computes the golden ratio\n((root 5 2)-1)\/2\n\n\n","human_summarization":"Implement the principal nth root of a positive real number A, without using System.Math classes.","id":4187}
    {"lang_cluster":"PowerShell","source_code":"\n\n$Env:COMPUTERNAME\n\n\n[Net.Dns]::GetHostName()\n\n","human_summarization":"Find the hostname of the current system using the ComputerName environment variable in Windows or .NET classes and methods in PowerShell.","id":4188}
    {"lang_cluster":"PowerShell","source_code":"\n\nCLS\n\nFunction isNumeric ($x)\n{\n    $x2 = 0    \n    $isNum = [System.Int32]::TryParse($x,[ref]$x2)\nReturn $isNum\n}\n\n$NumberArray = @()\nWhile( $NumberArray.Count -lt 4 ){\n    $NumberArray += Random -Minimum 1 -Maximum 10\n}\n\nWrite-Host @\"\nWelcome to the 24 game!\n\nHere are your numbers: $($NumberArray -join \",\").\nUse division, multiplication, subtraction and addition to get 24 as a result with these 4 numbers.\n\"@\n\nDo\n{\n$Wrong = 0\n$EndResult = $null\n$TempChar = $null\n$TempChar2 = $null\n$Count = $null\n\n$AllowableCharacters = $NumberArray + \"+-*\/()\".ToCharArray()\n    $Result = Read-Host\n        Foreach($Char in $Result.ToCharArray())\n        {\n            If( $AllowableCharacters -notcontains $Char ){ $Wrong = 1 }\n        }\n\n        If($Wrong -eq 1)\n        {\n            Write-Warning \"Wrong input! Please use only the given numbers.\"\n        }\n        Foreach($Char in $Result.ToCharArray())\n        {\n            If((IsNumeric $TempChar) -AND (IsNumeric $Char))\n            {\n                Write-Warning \"Wrong input! Combining two or more numbers together is not allowed!\"\n            }\n            $TempChar = $Char\n        }\n        Foreach($Char in $Result.ToCharArray())\n        {\n            If(IsNumeric $Char)\n            {\n                $Count++\n            }\n        }\n        If($Count -eq 4)\n        {\n            $EndResult = Invoke-Expression $Result\n                If($EndResult -eq 24)\n                {\n                    Write-Host \"`nYou've won the game!\"\n                }\n                Else\n                {\n                    Write-Host \"`n$EndResult is not 24! Too bad.\"\n                }\n        }\n        Else\n        {\n            Write-Warning \"Wrong input! You did not supply four numbers.\"\n        }\n}\nWhile($EndResult -ne 24)\n\n","human_summarization":"The code randomly selects and displays four digits from 1 to 9, and prompts the player to form an arithmetic expression using these digits exactly once. The expression should evaluate to 24 using addition, subtraction, multiplication, and division operations. The code checks and evaluates the player's input expression, but does not generate or test the possibility of an expression. It also includes a function to determine if a string is numeric.","id":4189}
    {"lang_cluster":"PowerShell","source_code":"\nfunction Compress-RLE ($s) {\n    $re = [regex] '(.)\\1*'\n    $ret = \"\"\n    foreach ($m in $re.Matches($s)) {\n        $ret += $m.Length\n        $ret += $m.Value[0]\n    }\n    return $ret\n}\n\nfunction Expand-RLE ($s) {\n    $re = [regex] '(\\d+)(.)'\n    $ret = \"\"\n    foreach ($m in $re.Matches($s)) {\n        $ret += [string] $m.Groups[2] * [int] [string] $m.Groups[1]\n    }\n    return $ret\n}\n\n\nPS> Compress-RLE \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\n12W1B12W3B24W1B14W\nPS> Expand-RLE \"12W1B12W3B24W1B14W\"\nWWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\n","human_summarization":"implement a run-length encoding and decoding function for a string containing uppercase characters. The function compresses repeated characters by storing the length of the run and can also reverse the compression.","id":4190}
    {"lang_cluster":"PowerShell","source_code":"\n$s = \"Hello\"\nWrite-Host $s World.\n\n# alternative, using variable expansion in strings\nWrite-Host \"$s World.\"\n\n$s2 = $s + \" World.\"\nWrite-Host $s2\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":4191}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 2\n$c = New-Object Net.WebClient\n$words = -split ($c.DownloadString('http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt'))\n$top_anagrams = $words `\n    | ForEach-Object {\n          $_ | Add-Member -PassThru NoteProperty Characters `\n                   (-join (([char[]] $_) | Sort-Object))\n      } `\n    | Group-Object Characters `\n    | Group-Object Count `\n    | Sort-Object Count `\n    | Select-Object -First 1\n\n$top_anagrams.Group | ForEach-Object { $_.Group -join ', ' }\n\n\n","human_summarization":"The code identifies sets of words from a given list (http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt) that are anagrams of each other, focusing on those sets with the most words. The implementation significantly improves runtime, reducing it from 2 minutes to 1.5 seconds using more .Net methods.","id":4192}
    {"lang_cluster":"PowerShell","source_code":"\nText based solution\nWorks with: PowerShell version 2\nfunction Draw-SierpinskiCarpet ( [int]$N )\n    {\n    $Carpet = @( '#' ) * [math]::Pow( 3, $N )\n    ForEach ( $i in 1..$N )\n        {\n        $S = [math]::Pow( 3, $i - 1 )\n        ForEach ( $Row in 0..($S-1) )\n            {\n            $Carpet[$Row+$S+$S] = $Carpet[$Row] * 3\n            $Carpet[$Row+$S]    = $Carpet[$Row] + ( \" \" * $Carpet[$Row].Length ) + $Carpet[$Row]\n            $Carpet[$Row]       = $Carpet[$Row] * 3\n            }\n        }\n    $Carpet\n    }\n \nDraw-SierpinskiCarpet 3\n\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":4193}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 2\nfunction Get-HuffmanEncodingTable ( $String )\n    {\n    #  Create leaf nodes\n    $ID = 0\n    $Nodes = [char[]]$String |\n        Group-Object |\n        ForEach { $ID++; $_ } |\n        Select  @{ Label = 'Symbol'  ; Expression = { $_.Name  } },\n                @{ Label = 'Count'   ; Expression = { $_.Count } },\n                @{ Label = 'ID'      ; Expression = { $ID      } },\n                @{ Label = 'Parent'  ; Expression = { 0        } },\n                @{ Label = 'Code'    ; Expression = { ''       } }\n \n    #  Grow stems under leafs\n    ForEach ( $Branch in 2..($Nodes.Count) )\n        {\n        #  Get the two nodes with the lowest count\n        $LowNodes = $Nodes | Where Parent -eq 0 | Sort Count | Select -First 2\n \n        #  Create a new stem node\n        $ID++\n        $Nodes += '' |\n            Select  @{ Label = 'Symbol'  ; Expression = { ''       } },\n                    @{ Label = 'Count'   ; Expression = { $LowNodes[0].Count + $LowNodes[1].Count } },\n                    @{ Label = 'ID'      ; Expression = { $ID      } },\n                    @{ Label = 'Parent'  ; Expression = { 0        } },\n                    @{ Label = 'Code'    ; Expression = { ''       } }\n \n        #  Put the two nodes in the new stem node\n        $LowNodes[0].Parent = $ID\n        $LowNodes[1].Parent = $ID\n \n        #  Assign 0 and 1 to the left and right nodes\n        $LowNodes[0].Code = '0'\n        $LowNodes[1].Code = '1'\n        }\n   \n    #  Assign coding to nodes\n    ForEach ( $Node in $Nodes[($Nodes.Count-2)..0] )\n        {\n        $Node.Code = ( $Nodes | Where ID -eq $Node.Parent ).Code + $Node.Code\n        }\n \n    $EncodingTable = $Nodes | Where { $_.Symbol } | Select Symbol, Code | Sort Symbol\n    return $EncodingTable\n    }\n \n#  Get table for given string\n$String = \"this is an example for huffman encoding\"\n$HuffmanEncodingTable = Get-HuffmanEncodingTable $String\n \n#  Display table\n$HuffmanEncodingTable | Format-Table -AutoSize\n \n#  Encode string\n$EncodedString = $String\nForEach ( $Node in $HuffmanEncodingTable )\n    {\n    $EncodedString = $EncodedString.Replace( $Node.Symbol, $Node.Code )\n    }\n$EncodedString\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in the given string \"this is an example for huffman encoding\". It first creates a tree of nodes based on the frequency of each character. Then, it traverses the tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those characters. The output is a table of Huffman encodings for each character.","id":4194}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 3\n$Label1  = [System.Windows.Forms.Label]@{\n            Text = 'There have been no clicks yet'\n            Size = '200, 20' }\n$Button1 = [System.Windows.Forms.Button]@{\n            Text = 'Click me'\n            Location = '0, 20' }\n \n$Button1.Add_Click(\n    {\n    $Script:Clicks++\n    If ( $Clicks -eq 1 ) { $Label1.Text = \"There has been 1 click\" }\n    Else                 { $Label1.Text = \"There have been $Clicks clicks\" }\n    } )\n \n$Form1 = New-Object System.Windows.Forms.Form\n$Form1.Controls.AddRange( @( $Label1, $Button1 ) )\n \n$Clicks = 0\n \n$Result = $Form1.ShowDialog()\n\nWorks with: PowerShell version 2\nAdd-Type -AssemblyName System.Windows.Forms\n \n$Label1 = New-Object System.Windows.Forms.Label\n$Label1.Text = 'There have been no clicks yet'\n$Label1.Size = '200, 20'\n \n$Button1 = New-Object System.Windows.Forms.Button\n$Button1.Text = 'Click me'\n$Button1.Location = '0, 20'\n \n$Button1.Add_Click(\n    {\n    $Script:Clicks++\n    If ( $Clicks -eq 1 ) { $Label1.Text = \"There has been 1 click\" }\n    Else                 { $Label1.Text = \"There have been $Clicks clicks\" }\n    } )\n \n$Form1 = New-Object System.Windows.Forms.Form\n$Form1.Controls.AddRange( @( $Label1, $Button1 ) )\n \n$Clicks = 0\n \n$Result = $Form1.ShowDialog()\n\n[xml]$Xaml = @\"\n<Window\n    xmlns=\"http:\/\/schemas.microsoft.com\/winfx\/2006\/xaml\/presentation\"\n    xmlns:x=\"http:\/\/schemas.microsoft.com\/winfx\/2006\/xaml\"\n    x:Name = \"Window1\"\n    Width  = \"200\"\n    Height = \"120\"\n    ShowInTaskbar = \"True\">\n    <StackPanel>\n        <Label\n            x:Name  = \"Label1\"\n            Height  = \"40\"\n            Width   = \"200\"\n            Content = \"There have been no clicks\"\/>\n        <Button\n            x:Name  = \"Button1\"\n            Height  = \"25\"\n            Width   = \"60\"\n            Content = \"Click me\"\/>\n    <\/StackPanel>\n<\/Window>\n\"@\n \n$Window1 = [Windows.Markup.XamlReader]::Load( [System.Xml.XmlNodeReader]$Xaml )\n \n$Label1  = $Window1.FindName( \"Label1\"  )\n$Button1 = $Window1.FindName( \"Button1\" )\n \n$Button1.Add_Click(\n    {\n    $Script:Clicks++\n    If ( $Clicks -eq 1 ) { $Label1.Content = \"There has been 1 click\" }\n    Else                 { $Label1.Content = \"There have been $Clicks clicks\" }\n    } )\n \n$Clicks = 0\n \n$Result = $Window1.ShowDialog()\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":4195}
    {"lang_cluster":"PowerShell","source_code":"\nfor ($i = 10; $i -ge 0; $i--) {\n    $i\n}\n\n10..0\n","human_summarization":"The code uses a for loop to perform a countdown from 10 to 0. It may also utilize the range operator to generate a continuous range of integers.","id":4196}
    {"lang_cluster":"PowerShell","source_code":"\n# Author: D. Cudnohufsky\nfunction Get-VigenereCipher\n{\n    Param\n    (\n        [Parameter(Mandatory=$true)]\n        [string] $Text,\n \n        [Parameter(Mandatory=$true)]\n        [string] $Key,\n \n        [switch] $Decode\n    )\n \n    begin\n    {    \n        $map = [char]'A'..[char]'Z'\n    }\n \n    process\n    {\n        $Key = $Key -replace '[^a-zA-Z]',''\n        $Text = $Text -replace '[^a-zA-Z]',''\n\n        $keyChars = $Key.toUpper().ToCharArray()\n        $Chars = $Text.toUpper().ToCharArray()\n \n        function encode\n        {\n\n            param\n            (\n                $Char,\n                $keyChar,\n                $Alpha = [char]'A'..[char]'Z'\n            )\n\n            $charIndex = $Alpha.IndexOf([int]$Char)\n            $keyIndex = $Alpha.IndexOf([int]$keyChar)\n            $NewIndex = ($charIndex + $KeyIndex) - $Alpha.Length\n            $Alpha[$NewIndex]\n\n        }\n \n        function decode\n        {\n\n            param\n            (\n                $Char,\n                $keyChar,\n                $Alpha = [char]'A'..[char]'Z'\n            )\n\n            $charIndex = $Alpha.IndexOf([int]$Char)\n            $keyIndex = $Alpha.IndexOf([int]$keyChar)\n            $int = $charIndex - $keyIndex\n            if ($int -lt 0) { $NewIndex = $int + $Alpha.Length }\n            else { $NewIndex = $int }\n            $Alpha[$NewIndex]\n        }\n\n        while ( $keyChars.Length -lt $Chars.Length ) \n        {\n            $keyChars = $keyChars + $keyChars\n        }\n\n        for ( $i = 0; $i -lt $Chars.Length; $i++ )\n        {\n\n            if ( [int]$Chars[$i] -in $map -and [int]$keyChars[$i] -in $map )\n            {\n                if ($Decode) {$Chars[$i] = decode $Chars[$i] $keyChars[$i] $map}\n                else {$Chars[$i] = encode $Chars[$i] $keyChars[$i] $map}\n\n                $Chars[$i] = [char]$Chars[$i]\n                [string]$OutText += $Chars[$i]\n            }\n\n        }\n \n        $OutText\n        $OutText = $null\n    }\n}\n\n\nEncode:\nPS C:\\> Get-VigenereCipher 'We attack at dawn.' 'lemon'\nHIMHGLGWOGOEIB\n\nDecode:\nPS C:\\> Get-VigenereCipher 'HIMHGLGWOGOEIB' 'lemon' -Decode\nWEATTACKATDAWN\n\n","human_summarization":"Implement and decrypt a Vigen\u00e8re cipher. The code handles keys and text of unequal length, capitalizes all characters, and discards non-alphabetic characters. If non-alphabetic characters are handled differently, a note is made.","id":4197}
    {"lang_cluster":"PowerShell","source_code":"\nfor ($i = 0; $i -lt 10; $i += 2) {\n    $i\n}\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":4198}
    {"lang_cluster":"PowerShell","source_code":"\nfunction  order($as,$bs) {\n    if($as -and $bs) {\n        $a, $as = $as\n        $b, $bs = $bs\n        if($a -eq $b) {order $as $bs}\n        else{$a -lt $b}\n    } elseif ($bs) {$true} else {$false}\n}\n\"$(order @(1,2,1,3,2) @(1,2,0,4,4,0,0,0))\"\n\n\nFalse\n\nfunction Test-Order ([int[]]$ReferenceArray, [int[]]$DifferenceArray)\n{\n    for ($i = 0; $i -lt $ReferenceArray.Count; $i++)\n    { \n        if ($ReferenceArray[$i] -lt $DifferenceArray[$i])\n        {\n            return $true\n        }\n        elseif ($ReferenceArray[$i] -gt $DifferenceArray[$i])\n        {\n            return $false\n        }\n    }\n\n    return ($ReferenceArray.Count -lt $DifferenceArray.Count) -or (Compare-Object $ReferenceArray $DifferenceArray) -eq $null\n}\n\nTest-Order -ReferenceArray 1, 2, 1, 3, 2 -DifferenceArray 1, 2, 0, 4, 4, 0, 0, 0\nTest-Order -ReferenceArray 1, 2, 1, 3, 2 -DifferenceArray 1, 2, 2, 4, 4, 0, 0, 0\nTest-Order -ReferenceArray 1, 2, 3       -DifferenceArray 1, 2\nTest-Order -ReferenceArray 1, 2          -DifferenceArray 1, 2, 3\nTest-Order -ReferenceArray 1, 2          -DifferenceArray 1, 2\n\n\n","human_summarization":"\"Function to compare two numerical lists in lexicographic order and return true if the first list should be ordered before the second, false otherwise.\"","id":4199}
    {"lang_cluster":"PowerShell","source_code":"function ackermann ([long] $m, [long] $n) {\n    if ($m -eq 0) {\n        return $n + 1\n    }\n    \n    if ($n -eq 0) {\n        return (ackermann ($m - 1) 1)\n    }\n    \n    return (ackermann ($m - 1) (ackermann $m ($n - 1)))\n}\n\nforeach ($m in 0..3) {\n    foreach ($n in 0..6) {\n        Write-Host -NoNewline (\"{0,5}\" -f (ackermann $m $n))\n    }\n    Write-Host\n}\n\n","human_summarization":"The code implements the Ackermann function, a non-primitive recursive function. It takes two non-negative arguments and returns their Ackermann value. The function grows quickly in value and its call tree size. It also includes a feature to save the result to an array for future use and display it using the Format-Wide cmdlet. The code handles arbitrary precision but it's not mandatory.","id":4200}
    {"lang_cluster":"PowerShell","source_code":"\n\nAdd-Type -Path \"C:\\Program Files (x86)\\Math\\MathNet.Numerics.3.12.0\\lib\\net40\\MathNet.Numerics.dll\"\n\n1..20 | ForEach-Object {[MathNet.Numerics.SpecialFunctions]::Gamma($_ \/ 10)}\n\n\n","human_summarization":"The code implements an algorithm to compute the Gamma function in the real field. It compares the results of this implementation with built-in\/library functions. The Gamma function is computed using numerical integration, Lanczos approximation, and Stirling's approximation. The code also involves the use of Math.NET Numerics dll(s).","id":4201}
    {"lang_cluster":"PowerShell","source_code":"\nWorks with: PowerShell version 2\nfunction PlaceQueen ( [ref]$Board, $Row, $N )\n    {\n    #  For the current row, start with the first column\n    $Board.Value[$Row] = 0\n\n    #  While haven't exhausted all columns in the current row...\n    While ( $Board.Value[$Row] -lt $N )\n        {\n        #  If not the first row, check for conflicts\n        $Conflict = $Row -and\n                    (   (0..($Row-1)).Where{ $Board.Value[$_] -eq $Board.Value[$Row] }.Count -or\n                        (0..($Row-1)).Where{ $Board.Value[$_] -eq $Board.Value[$Row] - $Row + $_ }.Count -or\n                        (0..($Row-1)).Where{ $Board.Value[$_] -eq $Board.Value[$Row] + $Row - $_ }.Count )\n \n        #  If no conflicts and the current column is a valid column...\n        If ( -not $Conflict -and $Board.Value[$Row] -lt $N )\n            {\n\n            #  If this is the last row\n            #    Board completed successfully\n            If ( $Row -eq ( $N - 1 ) )\n                {\n                return $True\n                }\n\n            #  Recurse\n            #  If all nested recursions were successful\n            #    Board completed successfully\n            If ( PlaceQueen $Board ( $Row + 1 ) $N )\n                {\n                return $True\n                }\n            }\n        \n        #  Try the next column\n        $Board.Value[$Row]++\n        }\n\n    #  Everything was tried, nothing worked\n    Return $False\n    }\n \nfunction Get-NQueensBoard ( $N )\n    {\n    #  Start with a default board (array of column positions for each row)\n    $Board = @( 0 ) * $N\n\n    #  Place queens on board\n    #  If successful...\n    If ( PlaceQueen -Board ([ref]$Board) -Row 0 -N $N )\n        {\n        #  Convert board to strings for display\n        $Board | ForEach { ( @( \"\" ) + @(\" \") * $_ + \"Q\" + @(\" \") * ( $N - $_ ) ) -join \"|\" }\n        }\n    Else\n        {\n        \"There is no solution for N = $N\"\n        }\n    }\n\nGet-NQueensBoard 8\n''\nGet-NQueensBoard 3\n''\nGet-NQueensBoard 4\n''\nGet-NQueensBoard 14\n\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":4202}
    {"lang_cluster":"PowerShell","source_code":"\n$a = 1,2,3\n$b = 4,5,6\n\n$c = $a + $b\nWrite-Host $c\n","human_summarization":"demonstrate how to concatenate two arrays.","id":4203}
    {"lang_cluster":"PowerShell","source_code":"\nusing namespace System.Collections.Generic\n$ErrorActionPreference = 'Stop'\nclass Person{\n    #private\n    hidden [int] $_candidateIndex;\n    [string] $Name\n    #[System.Collections.Generic.List[Person]] $Prefs\n    [List[Person]] $Prefs\n    [Person] $Fiance\n    \n    Person([string] $name) {\n            $this.Name = $name;\n            $this.Prefs = $null;\n            $this.Fiance = $null;\n            $this._candidateIndex = 0;\n        }\n    [bool] Prefers([Person] $p) {\n            return $this.Prefs.FindIndex({ param($o) $o -eq $p }) -lt $this.Prefs.FindIndex({ param($o) $o -eq $this.Fiance });\n        }\n    \n    [Person] NextCandidateNotYetProposedTo() {\n            if ($this._candidateIndex -ge $this.Prefs.Count) {return $null;}\n            return $this.Prefs[$this._candidateIndex++];\n        }\n    \n    [void] EngageTo([Person] $p) {\n            if ($p.Fiance -ne $null) {$p.Fiance.Fiance = $null};\n            $p.Fiance = $this;\n            if ($this.Fiance -ne $null){$this.Fiance.Fiance = $null};\n            $this.Fiance = $p;\n        }\n\n    \n    }\n\n\n    class MainClass\n    {\n        static  [bool] IsStable([List[Person]] $men) {\n            [List[Person]] $women = $men[0].Prefs;\n            foreach ($guy in $men){ \n                foreach ($gal in $women) {\n                    if ($guy.Prefers($gal) -and $gal.Prefers($guy))\n                        {return $false};\n                }\n            }\n            return $true;\n        }\n\n        static [void] DoMarriage() {\n            [Person] $abe  = [Person]::new(\"abe\");\n            [Person] $bob  = [Person]::new(\"bob\");\n            [Person] $col  = [Person]::new(\"col\");\n            [Person] $dan  = [Person]::new(\"dan\");\n            [Person] $ed   = [Person]::new(\"ed\");\n            [Person] $fred = [Person]::new(\"fred\");\n            [Person] $gav  = [Person]::new(\"gav\");\n            [Person] $hal  = [Person]::new(\"hal\");\n            [Person] $ian  = [Person]::new(\"ian\");\n            [Person] $jon  = [Person]::new(\"jon\");\n            [Person] $abi  = [Person]::new(\"abi\");\n            [Person] $bea  = [Person]::new(\"bea\");\n            [Person] $cath = [Person]::new(\"cath\");\n            [Person] $dee  = [Person]::new(\"dee\");\n            [Person] $eve  = [Person]::new(\"eve\");\n            [Person] $fay  = [Person]::new(\"fay\");\n            [Person] $gay  = [Person]::new(\"gay\");\n            [Person] $hope = [Person]::new(\"hope\");\n            [Person] $ivy  = [Person]::new(\"ivy\");\n            [Person] $jan  = [Person]::new(\"jan\");\n\n            $abe.Prefs =[Person[]]@($abi, $eve, $cath, $ivy, $jan, $dee, $fay, $bea, $hope, $gay)\n            $bob.Prefs  = [Person[]] @($cath, $hope, $abi, $dee, $eve, $fay, $bea, $jan, $ivy, $gay);\n            $col.Prefs  = [Person[]] @($hope, $eve, $abi, $dee, $bea, $fay, $ivy, $gay, $cath, $jan);\n            $dan.Prefs  = [Person[]] @($ivy, $fay, $dee, $gay, $hope, $eve, $jan, $bea, $cath, $abi);\n            $ed.Prefs   = [Person[]] @($jan, $dee, $bea, $cath, $fay, $eve, $abi, $ivy, $hope, $gay);\n            $fred.Prefs = [Person[]] @($bea, $abi, $dee, $gay, $eve, $ivy, $cath, $jan, $hope, $fay);\n            $gav.Prefs  = [Person[]] @($gay, $eve, $ivy, $bea, $cath, $abi, $dee, $hope, $jan, $fay);\n            $hal.Prefs  = [Person[]] @($abi, $eve, $hope, $fay, $ivy, $cath, $jan, $bea, $gay, $dee);\n            $ian.Prefs  = [Person[]] @($hope, $cath, $dee, $gay, $bea, $abi, $fay, $ivy, $jan, $eve);\n            $jon.Prefs  = [Person[]] @($abi, $fay, $jan, $gay, $eve, $bea, $dee, $cath, $ivy, $hope);\n            $abi.Prefs  = [Person[]] @($bob, $fred, $jon, $gav, $ian, $abe, $dan, $ed, $col, $hal);\n            $bea.Prefs  = [Person[]] @($bob, $abe, $col, $fred, $gav, $dan, $ian, $ed, $jon, $hal);\n            $cath.Prefs = [Person[]] @($fred, $bob, $ed, $gav, $hal, $col, $ian, $abe, $dan, $jon);\n            $dee.Prefs  = [Person[]] @($fred, $jon, $col, $abe, $ian, $hal, $gav, $dan, $bob, $ed);\n            $eve.Prefs  = [Person[]] @($jon, $hal, $fred, $dan, $abe, $gav, $col, $ed, $ian, $bob);\n            $fay.Prefs  = [Person[]] @($bob, $abe, $ed, $ian, $jon, $dan, $fred, $gav, $col, $hal);\n            $gay.Prefs  = [Person[]] @($jon, $gav, $hal, $fred, $bob, $abe, $col, $ed, $dan, $ian);\n            $hope.Prefs = [Person[]] @($gav, $jon, $bob, $abe, $ian, $dan, $hal, $ed, $col, $fred);\n            $ivy.Prefs  = [Person[]] @($ian, $col, $hal, $gav, $fred, $bob, $abe, $ed, $jon, $dan);\n            $jan.Prefs  = [Person[]] @($ed, $hal, $gav, $abe, $bob, $jon, $col, $ian, $fred, $dan);\n\n            [List[Person]] $men = [List[Person]]::new($abi.Prefs);\n\n            [int] $freeMenCount = $men.Count;\n            while ($freeMenCount -gt 0) {\n                foreach ($guy in $men) {\n                    if ($guy.Fiance -eq $null) {\n                        [Person]$gal = $guy.NextCandidateNotYetProposedTo();\n                        if ($gal.Fiance -eq $null) {\n                            $guy.EngageTo($gal);\n                            $freeMenCount--;\n                        }\n                        else{\n                            if ($gal.Prefers($guy)) {\n                                $guy.EngageTo($gal);\n                            }\n                        }\n                        \n                    }\n                }\n            }\n\n            foreach ($guy in $men) {\n                write-host $guy.Name \" is engaged to \" $guy.Fiance.Name\n               \n            }\n            write-host \"Stable = \" ([MainClass]::IsStable($men))\n            \n            write-host \"Switching fred & jon's partners\";\n            [Person] $jonsFiance = $jon.Fiance;\n            [Person] $fredsFiance = $fred.Fiance;\n            $fred.EngageTo($jonsFiance);\n            $jon.EngageTo($fredsFiance);\n            write-host \"Stable = \" ([MainClass]::IsStable($men));\n\n        }\n     static [void] Main([string[]] $args)\n        {\n            [MainClass]::DoMarriage();\n        }\n\n\n    }\n\n[MainClass]::DoMarriage()\n\n\n","human_summarization":"The code implements the Gale-Shapley algorithm to solve the Stable Marriage Problem. It takes as input the preferences of ten males and ten females for potential partners. The algorithm generates a stable set of engagements where no individual prefers someone else over their current partner, who also prefers them over their current partner. The code also perturbs this stable set to create an unstable set and checks its stability.","id":4204}
    {"lang_cluster":"PowerShell","source_code":"\n\n#  Simulated fast function\nfunction a ( [boolean]$J ) { return $J }\n \n#  Simulated slow function\nfunction b ( [boolean]$J ) { Sleep -Seconds 2; return $J }\n \n#  These all short-circuit and do not evaluate the right hand function\n( a $True  ) -or  ( b $False )\n( a $True  ) -or  ( b $True  )\n( a $False ) -and ( b $False )\n( a $False ) -and ( b $True  )\n \n#  Measure of execution time\nMeasure-Command {\n( a $True  ) -or  ( b $False )\n( a $True  ) -or  ( b $True  )\n( a $False ) -and ( b $False )\n( a $False ) -and ( b $True  )\n} | Select TotalMilliseconds\n \n#  These all appropriately do evaluate the right hand function\n( a $False ) -or  ( b $False )\n( a $False ) -or  ( b $True  )\n( a $True  ) -and ( b $False )\n( a $True  ) -and ( b $True  )\n \n#  Measure of execution time\nMeasure-Command {\n( a $False ) -or  ( b $False )\n( a $False ) -or  ( b $True  )\n( a $True  ) -and ( b $False )\n( a $True  ) -and ( b $True  )\n} | Select TotalMilliseconds\n\n\n","human_summarization":"The code defines two functions, 'a' and 'b', both of which take a boolean value as input, return the same value, and print their name when called. The code then calculates the values of two boolean expressions 'x' and 'y' using these functions. The calculation is done in such a way that function 'b' is only called when necessary, utilizing the concept of short-circuit evaluation. If the language does not support short-circuit evaluation, nested 'if' statements are used instead. PowerShell natively supports this feature.","id":4205}
    {"lang_cluster":"PowerShell","source_code":"\n\nfunction Send-MorseCode\n{\n    [CmdletBinding()]\n    [OutputType([string])]\n    Param\n    (\n        [Parameter(Mandatory=$true,\n                   ValueFromPipeline=$true,\n                   Position=0)]\n        [string]\n        $Message,\n\n        [switch]\n        $ShowCode\n    )\n\n    Begin\n    {\n        $morseCode = @{\n            a = \".-\"   ; b = \"-...\" ; c = \"-.-.\" ; d = \"-..\"\n            e = \".\"    ; f = \"..-.\" ; g = \"--.\"  ; h = \"....\"\n            i = \"..\"   ; j = \".---\" ; k = \"-.-\"  ; l = \".-..\"\n            m = \"--\"   ; n = \"-.\"   ; o = \"---\"  ; p = \".--.\"\n            q = \"--.-\" ; r = \".-.\"  ; s = \"...\"  ; t = \"-\"\n            u = \"..-\"  ; v = \"...-\" ; w = \".--\"  ; x = \"-..-\"\n            y = \"-.--\" ; z = \"--..\" ; 0 = \"-----\"; 1 = \".----\"\n            2 = \"..---\"; 3 = \"...--\"; 4 = \"....-\"; 5 = \".....\"\n            6 = \"-....\"; 7 = \"--...\"; 8 = \"---..\"; 9 = \"----.\"\n        }    \n    }\n    Process\n    {\n        foreach ($word in $Message)\n        {\n            $word.Split(\" \",[StringSplitOptions]::RemoveEmptyEntries) | ForEach-Object {\n\n                foreach ($char in $_.ToCharArray())\n                {\n                    if ($char -in $morseCode.Keys)\n                    {\n                        foreach ($code in ($morseCode.\"$char\").ToCharArray())\n                        {\n                            if ($code -eq \".\") {$duration = 250} else {$duration = 750}\n\n                            [System.Console]::Beep(1000, $duration)\n                            Start-Sleep -Milliseconds 50\n                        }\n\n                        if ($ShowCode) {Write-Host (\"{0,-6}\" -f (\"{0,6}\" -f $morseCode.\"$char\")) -NoNewLine}\n                    }\n                }\n\n                if ($ShowCode) {Write-Host}\n            }\n\n            if ($ShowCode) {Write-Host}\n        }\n    }\n}\n\nSend-MorseCode -Message \"S.O.S\" -ShowCode\n\n\n","human_summarization":"\"Function to convert a given string into Morse code and play it as audible sound through an audio device. It handles unknown characters by either ignoring them or indicating them with a different pitch. The function is case insensitive and can optionally display the Morse code.\"","id":4206}
    {"lang_cluster":"PowerShell","source_code":"\n<#\n.Synopsis\n  ABC Problem\n.DESCRIPTION\n   You are given a collection of ABC blocks. Just like the ones you had when you were a kid. \n   There are twenty blocks with two letters on each block. You are guaranteed to have a \n   complete alphabet amongst all sides of the blocks\n   blocks = \"BO\",\"XK\",\"DQ\",\"CP\",\"NA\",\"GT\",\"RE\",\"TG\",\"QD\",\"FS\",\"JW\",\"HU\",\"VI\",\"AN\",\"OB\",\"ER\",\"FS\",\"LY\",\"PC\",\"ZM\"\n   The goal of this task is to write a function that takes a string and can determine whether \n   you can spell the word with the given collection of blocks. \n\n   The rules are simple: \n        1.Once a letter on a block is used that block cannot be used again \n        2.The function should be case-insensitive \n        3. Show your output on this page for the following words:\n        >>> can_make_word(\"A\")\n        True\n        >>> can_make_word(\"BARK\")\n        True\n        >>> can_make_word(\"BOOK\")\n        False\n        >>> can_make_word(\"TREAT\")\n        True\n        >>> can_make_word(\"COMMON\")\n        False\n        >>> can_make_word(\"SQUAD\")\n        True\n        >>> can_make_word(\"CONFUSE\")\n        True\n\n   Using the examples below  you can either see just the value or \n   status and the values using the verbose switch\n\n.EXAMPLE\n   test-blocks -testword confuse\n\n.EXAMPLE\n   test-blocks -testword confuse -verbose\n\n#>\n\nfunction test-blocks\n{\n\t[CmdletBinding()]\n\t#  [OutputType([int])]\n\tParam\n\t(\n\t\t# word to test against blocks\n\t\t[Parameter(Mandatory = $true,\n\t\t\t\t   ValueFromPipelineByPropertyName = $true)]\n\t\t$testword\n\t\t\n\t)\n\n\t$word = $testword\n\t\n\t#define array of blocks\n\t[System.Collections.ArrayList]$blockarray = \"BO\", \"XK\", \"DQ\", \"CP\", \"NA\", \"GT\", \"RE\", \"TG\", \"QD\", \"FS\", \"JW\", \"HU\", \"VI\", \"AN\", \"OB\", \"ER\", \"FS\", \"LY\", \"PC\", \"ZM\"\n\t\n\t#send word to chararray\n\t$chararray = $word.ToCharArray()\n\t$chars = $chararray\n\t\n\t#get the character count\n\t$charscount = $chars.count\n\t\n\t#get the initial count of the blocks\n\t$blockcount = $blockarray.Count\n\t\n\t#find out how many blocks should be left from the difference\n\t#of the blocks and characters in the word - 1 letter\/1 block\n\t$correctblockcount = $blockcount - $charscount\n\t\n\t#loop through the characters in the word\n\tforeach ($char in $chars)\n\t{\n\t\t\n\t\t#loop through the blocks\n\t\tforeach ($block in $blockarray)\n\t\t{\n\t\t\t\n\t\t\t#check the current character against each letter on the current block\n\t\t\t#and break if found so the array can reload\n\t\t\tif ($char -in $block[0] -or $char -in $block[1])\n\t\t\t{\n\t\t\t\t\n\t\t\t\twrite-verbose \"match for letter - $char - removing block $block\"\n\t\t\t\t$blockarray.Remove($block)\n\t\t\t\tbreak\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t}\n\t#get final count of blocks left in array to determine if the word was\n\t#correctly made\n\t$finalblockcount = $blockarray.count\n\tif ($finalblockcount -ne $correctblockcount)\n\t{\n\t\twrite-verbose \"$word\u00a0: $false \"\n\t\treturn $false\n\t}\n\telse\n\t{\n\t\twrite-verbose \"$word\u00a0: $true \"\n\t\treturn $true\n\t}\n\t\n}\n\n#loop all the words and pass them to the function\n$wordlist = \"a\", \"bark\", \"book\", \"treat\", \"common\", \"squad\", \"confuse\"\nforeach ($word in $wordlist)\n{\n\ttest-blocks -testword $word -Verbose\n}\n\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":4207}
    {"lang_cluster":"PowerShell","source_code":"$string = \"The quick brown fox jumped over the lazy dog's back\"\n$data = [Text.Encoding]::UTF8.GetBytes($string)\n$hash = [Security.Cryptography.MD5]::Create().ComputeHash($data)\n([BitConverter]::ToString($hash) -replace '-').ToLower()\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":4208}
    {"lang_cluster":"PowerShell","source_code":"\n\n[hashtable]$mailMessage = @{\n    From = \"weirdBoy@gmail.com\"\n    To = \"anudderBoy@YourDomain.com\"\n    Cc = \"daWaghBoss@YourDomain.com\"\n    Attachment = \"C:\\temp\\Waggghhhh!_plan.txt\"\n    Subject = \"Waggghhhh!\"\n    Body = \"Wagggghhhhhh!\"\n    SMTPServer = \"smtp.gmail.com\"\n    SMTPPort = \"587\"\n    UseSsl = $true\n    ErrorAction = \"SilentlyContinue\" \n}\n\nSend-MailMessage @mailMessage\n\n","human_summarization":"implement a function to send an email using PowerShell's 'Send-MailMessage' cmdlet. The function includes parameters for setting 'From', 'To', 'Cc' addresses, 'Subject', and 'message text'. Optional fields for server name and login details are also included. The solution is portable across different operating systems.","id":4209}
    {"lang_cluster":"PowerShell","source_code":"\n[int64]$i = 0\nWhile ( $True )\n    {\n    [Convert]::ToString( ++$i, 8 )\n    }\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":4210}
    {"lang_cluster":"PowerShell","source_code":"\n\n$b, $a = $a, $b\n\nfunction swap ([ref] $a, [ref] $b) {\n    $a.Value, $b.Value = $b.Value, $a.Value\n}\n\nswap ([ref] $a) ([ref] $b)\n","human_summarization":"define a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. This function should work in both statically and dynamically typed languages, with certain constraints for type compatibility. In functional languages, the function may not allow destructive operations. The function should also handle issues related to parametric polymorphism in static languages. In PowerShell, the function can use tuple assignment for swapping.","id":4211}
    {"lang_cluster":"PowerShell","source_code":"\n\nFunction Test-Palindrome( [String] $Text ){\n    $CharArray = $Text.ToCharArray()\n    [Array]::Reverse($CharArray)\n    $Text -eq [string]::join('', $CharArray)\n}\n\nfunction Test-Palindrome\n{\n  <#\n    .SYNOPSIS\n        Tests if a string is a palindrome.\n    .DESCRIPTION\n        Tests if a string is a true palindrome or, optionally, an inexact palindrome.\n    .EXAMPLE\n        Test-Palindrome -Text \"racecar\"\n    .EXAMPLE\n        Test-Palindrome -Text '\"Deliver desserts,\" demanded Nemesis, \"emended, named, stressed, reviled.\"' -Inexact\n  #>\n    [CmdletBinding()]\n    [OutputType([bool])]\n    Param\n    (\n        # The string to test for palindrominity.\n        [Parameter(Mandatory=$true)]\n        [string]\n        $Text,\n\n        # When specified, detects an inexact palindrome.\n        [switch]\n        $Inexact\n    )\n\n    if ($Inexact)\n    {\n        # Strip all punctuation and spaces\n        $Text = [Regex]::Replace(\"$Text($7&\",\"[^1-9a-zA-Z]\",\"\")\n    }\n\n    $Text -match \"^(?'char'[a-z])+[a-z]?(?:\\k'char'(?'-char'))+(?(char)(?!))$\"\n}\nTest-Palindrome -Text 'radar'\n\n","human_summarization":"The code defines a function to check if a given sequence of characters is a palindrome. It supports Unicode characters and also includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case. The code uses string reversal and Unicode categories for character identification.","id":4212}
    {"lang_cluster":"PowerShell","source_code":"\n\n$Env:Path\n\n\nGet-ChildItem Env:\n\n","human_summarization":"demonstrate how to access a process's environment variables such as PATH, HOME, and USER, which are commonly found on Unix systems. The environment variables are located in the Env: drive and can be retrieved using a specific variable syntax. The code also includes a feature to list all environment variables by querying the drive's contents.","id":4213}
    {"lang_cluster":"Haskell","source_code":"\n\ntype Stack a = [a]\n\ncreate :: Stack a\ncreate = []\n\npush :: a -> Stack a -> Stack a\npush = (:)\n\npop :: Stack a -> (a, Stack a)\npop []     = error \"Stack empty\"\npop (x:xs) = (x,xs)\n\nempty :: Stack a -> Bool\nempty = null\n\npeek :: Stack a -> a\npeek []    = error \"Stack empty\"\npeek (x:_) = x\n\n\nimport Control.Monad.State\n\ntype Stack a b = State [a] b\n\npush :: a -> Stack a ()\npush = modify . (:)\n\npop :: Stack a a\npop = do\n    nonEmpty\n    x <- peek\n    modify tail\n    return x\n\nempty :: Stack a Bool\nempty = gets null\n\npeek :: Stack a a\npeek = nonEmpty >> gets head\n\nnonEmpty :: Stack a ()\nnonEmpty = empty >>= flip when (fail \"Stack empty\")\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and is accessed through its top. The 'push' operation stores a new element onto the stack top, 'pop' returns and removes the last pushed stack element, and 'empty' checks if the stack contains no elements. The topmost element can be accessed for read or write without modifying the stack. The implementation also supports a purely functional approach where pop returns both the element and the changed stack.","id":4214}
    {"lang_cluster":"Haskell","source_code":"\nWorks with: exact-real version 0.12.5.1\n\nimport Data.CReal\n\nphi = (1 + sqrt 5) \/ 2\n\nfib\u00a0:: (Integral b) => b -> CReal 0\nfib n = (phi^^n - (-phi)^^(-n))\/sqrt 5\n\n\u03bb> fib 10\u00a0:: CReal 0\n55\n(0.01 secs, 137,576 bytes)\n\u03bb> fib 100\u00a0:: CReal 0\n354224848179261915075\n(0.01 secs, 253,152 bytes)\n\u03bb> fib 10000\u00a0:: CReal 0\n33644764876431783266621612005107543310302148460680063906564769974680081442166662368155595513633734025582065332680836159373734790483865268263040892463056431887354544369559827491606602099884183933864652731300088830269235673613135117579297437854413752130520504347701602264758318906527890855154366159582987279682987510631200575428783453215515103870818298969791613127856265033195487140214287532698187962046936097879900350962302291026368131493195275630227837628441540360584402572114334961180023091208287046088923962328835461505776583271252546093591128203925285393434620904245248929403901706233888991085841065183173360437470737908552631764325733993712871937587746897479926305837065742830161637408969178426378624212835258112820516370298089332099905707920064367426202389783111470054074998459250360633560933883831923386783056136435351892133279732908133732642652633989763922723407882928177953580570993691049175470808931841056146322338217465637321248226383092103297701648054726243842374862411453093812206564914032751086643394517512161526545361333111314042436854805106765843493523836959653428071768775328348234345557366719731392746273629108210679280784718035329131176778924659089938635459327894523777674406192240337638674004021330343297496902028328145933418826817683893072003634795623117103101291953169794607632737589253530772552375943788434504067715555779056450443016640119462580972216729758615026968443146952034614932291105970676243268515992834709891284706740862008587135016260312071903172086094081298321581077282076353186624611278245537208532365305775956430072517744315051539600905168603220349163222640885248852433158051534849622434848299380905070483482449327453732624567755879089187190803662058009594743150052402532709746995318770724376825907419939632265984147498193609285223945039707165443156421328157688908058783183404917434556270520223564846495196112460268313970975069382648706613264507665074611512677522748621598642530711298441182622661057163515069260029861704945425047491378115154139941550671256271197133252763631939606902895650288268608362241082050562430701794976171121233066073310059947366875\n(0.02 secs, 4,847,128 bytes)\n\u03bb> fib (-10)\u00a0:: CReal 0\n-55\n(0.01 secs, 138,408 bytes)\n\nfib x =\n  if x < 1\n    then 0\n    else if x < 2\n           then 1\n           else fib (x - 1) + fib (x - 2)\n\nfib x =\n  if x < 1\n    then 0\n    else if x == 1\n           then 1\n           else fibs\u00a0!! (x - 1) + fibs\u00a0!! (x - 2)\n  where\n    fibs = map fib [0 ..]\n\nimport Data.MemoTrie\nfib\u00a0:: Integer -> Integer\nfib = memo f where\n   f 0 = 0\n   f 1 = 1\n   f n = fib (n-1) + fib (n-2)\n\nimport Data.MemoTrie\nfib\u00a0:: Integer -> Integer\nfib = memo $ \\x -> case x of\n   0 -> 0\n   1 -> 1\n   n -> fib (n-1) + fib (n-2)\n\n{-# Language LambdaCase #-}\nimport Data.MemoTrie\nfib\u00a0:: Integer -> Integer\nfib = memo $ \\case \n   0 -> 0\n   1 -> 1\n   n -> fib (n-1) + fib (n-2)\n\n{-# Language LambdaCase #-}\nimport Data.MemoTrie\nfib\u00a0:: Integer -> Integer\nfib = memo $ \\case \n   0 -> 0\n   1 -> 1\n   n | n>0 -> fib (n-1) + fib (n-2)\n     | otherwise -> fib (n+2) - fib (n+1)\nfib n = go n 0 1\n  where\n    go n a b\n      | n == 0 = a\n      | otherwise = go (n - 1) b (a + b)\n\nfib = 0\u00a0: 1\u00a0: zipWith (+) fib (tail fib)\n\nfib = 0\u00a0: 1\u00a0: (zipWith (+) <*> tail) fib\n\nfib = 0\u00a0: 1\u00a0: next fib where next (a: t@(b:_)) = (a+b)\u00a0: next t\n\nfib = 0\u00a0: scanl (+) 1 fib\n\nimport Data.List (foldl') --'\n\nfib\u00a0:: Integer -> Integer\nfib n =\n  fst $\n  foldl' --'\n    (\\(a, b) _ -> (b, a + b))\n    (0, 1)\n    [1 .. n]\n\nimport Data.List (transpose)\n\nfib\n \u00a0:: (Integral b, Num a)\n  => b -> a\nfib 0 = 0 -- this line is necessary because \"something ^ 0\" returns \"fromInteger 1\", which unfortunately\n-- in our case is not our multiplicative identity (the identity matrix) but just a 1x1 matrix of 1\nfib n = (last . head . unMat) (Mat [[1, 1], [1, 0]] ^ n)\n\n-- Code adapted from Matrix exponentiation operator task ---------------------\n(<+>)\n \u00a0:: Num c\n  => [c] -> [c] -> [c]\n(<+>) = zipWith (+)\n\n(<*>)\n \u00a0:: Num a\n  => [a] -> [a] -> a\n(<*>) = (sum .) . zipWith (*)\n\nnewtype Mat a = Mat\n  { unMat\u00a0:: [[a]]\n  } deriving (Eq)\n\ninstance Show a =>\n         Show (Mat a) where\n  show xm = \"Mat \" ++ show (unMat xm)\n\ninstance Num a =>\n         Num (Mat a) where\n  negate xm = Mat $ map (map negate) $ unMat xm\n  xm + ym = Mat $ zipWith (<+>) (unMat xm) (unMat ym)\n  xm * ym =\n    Mat\n      [ [ xs Main.<*> ys -- to distinguish from standard applicative operator\n        | ys <- transpose $ unMat ym ]\n      | xs <- unMat xm ]\n  fromInteger n = Mat [[fromInteger n]]\n  abs = undefined\n  signum = undefined\n\n-- TEST ----------------------------------------------------------------------\nmain\u00a0:: IO ()\nmain = (print . take 10 . show . fib) (10 ^ 5)\n\n\n","human_summarization":"The code defines a function to generate the nth Fibonacci number, either iteratively or recursively. It optionally supports negative numbers using an inverse definition. The function can also use Binet's formula and an exact real arithmetic library for precise calculations, even for large numbers. It includes an optimized version using a memoizer for faster execution. The code also demonstrates the use of lazy lists to generate an infinite list of all Fibonacci numbers. It includes a version that supports negative numbers and uses accumulator to hold the last two members of the series. The code also uses Fibonacci recurrence identities for efficient calculation of large Fibonacci numbers.","id":4215}
    {"lang_cluster":"Haskell","source_code":"\n\nary = [1..10]\nevens = [x | x <- ary, even x]\n\n\nevens = filter even ary\n\n\nimport Data.Array\n\nary = listArray (1,10) [1..10]\nevens = listArray (1,n) l where\n  n = length l\n  l = [x | x <- elems ary, even x]\n\n\n","human_summarization":"select specific elements from an array, in this case, even numbers, and place them into a new array. Alternatively, the code can modify the original array directly. In Haskell, this operation is typically done on a list, but it can also be done on an array by converting it into a list. The bounds of the array must be known before its creation.","id":4216}
    {"lang_cluster":"Haskell","source_code":"\nWorks with: Haskell version 6.10.4\n\nThe first three tasks are simply:\n*Main> take 3 $ drop 2 \"1234567890\"\n\"345\"\n\n*Main> drop 2 \"1234567890\"\n\"34567890\"\n\n*Main> init \"1234567890\"\n\"123456789\"\n\nThe last two can be formulated with the following function:\nt45 n c s | null sub = []\n          | otherwise = take n. head $ sub\n  where sub = filter(isPrefixOf c) $ tails s\n\n*Main> t45 3 \"4\" \"1234567890\"\n\"456\"\n\n*Main> t45 3 \"45\" \"1234567890\"\n\"456\"\n\n*Main> t45 3 \"31\" \"1234567890\"\n\"\"\n\nWorks with: Haskell version 8.0.2\n{-# LANGUAGE OverloadedStrings #-}\n\nimport qualified Data.Text as T (Text, take, drop, init, breakOn)\nimport qualified Data.Text.IO as O (putStrLn)\n\nfromMforN :: Int -> Int -> T.Text -> T.Text\nfromMforN n m s = T.take m (T.drop n s)\n\nfromNtoEnd :: Int -> T.Text -> T.Text\nfromNtoEnd = T.drop\n\nallButLast :: T.Text -> T.Text\nallButLast = T.init\n\nfromCharForN, fromStringForN :: Int -> T.Text -> T.Text -> T.Text\nfromCharForN m needle haystack = T.take m $ snd $ T.breakOn needle haystack\n\nfromStringForN = fromCharForN\n\n-- TEST ---------------------------------------------------\nmain :: IO ()\nmain =\n  mapM_\n    O.putStrLn\n    ([ fromMforN 9 10\n     , fromNtoEnd 20\n     , allButLast\n     , fromCharForN 6 \"\u8bdd\"\n     , fromStringForN 6 \"\u5927\u52bf\"\n     ] <*>\n     [\"\u5929\u5730\u4e0d\u4ec1\u4ec1\u8005\u4eba\u4e5f\ud83d\udc12\u8bdd\u8bf4\u5929\u4e0b\u5927\u52bf\u5206\u4e45\u5fc5\u5408\ud83c\udf51\u5408\u4e45\u5fc5\u5206\ud83d\udd25\"])\n\n\n","human_summarization":"The code performs the following tasks: \n1. Displays a substring starting from 'n' characters in and of 'm' length.\n2. Displays a substring starting from 'n' characters in, up to the end of the string.\n3. Displays the whole string minus the last character.\n4. Displays a substring starting from a known character within the string and of 'm' length.\n5. Displays a substring starting from a known substring within the string and of 'm' length.\nThe code is compatible with any valid Unicode code point, including UTF-8 or UTF-16, and references logical characters, not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. It is not required to handle all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP. In Haskell, the string is represented as a list of chars: [Char]. The code also includes tests with an extended set of characters using Data.Text functions, including breakOn.","id":4217}
    {"lang_cluster":"Haskell","source_code":"\nreverse = foldl (flip (:)) []\n\n\naccumulatingReverse :: [a] -> [a]\naccumulatingReverse lst =\n  let rev xs a = foldl (flip (:)) a xs\n  in rev lst []\n\nimport Data.Char (isMark)\nimport Data.List (groupBy)\nmyReverse = concat . reverse . groupBy (const isMark)\n\n\n","human_summarization":"\"Function to reverse a string while preserving Unicode combining characters. For instance, it transforms 'asdf' into 'fdsa' and 'as\u20dddf\u0305' into 'f\u0305ds\u20dda'. The function is optimized using a helper function with an accumulator argument, and it uses 'groupBy (const isMark)' for splitting a string into its combined characters.\"","id":4218}
    {"lang_cluster":"Haskell","source_code":"\n\n\nThis example is incorrect.  Please fix the code and remove this message.Details: TREESTUMP -> TREXSTUMPX, should be TREXESTUMP\n\n\nimport Control.Monad     (guard)\nimport Data.Array        (Array, assocs, elems, listArray, (!))\nimport Data.Char         (toUpper)\nimport Data.List         (nub, (\\\\))\nimport Data.List.Split   (chunksOf)\nimport Data.Maybe        (listToMaybe)\nimport Data.String.Utils (replace)\n\ntype Square a = Array (Int, Int) a\n\n-- | Turns a list into an n*m-array.\narray2D ::\n       (Int, Int) -- ^ n * m\n    -> [e] -> Square e\narray2D maxCoord = listArray ((1, 1), maxCoord)\n\n-- | Generates a playfair table starting with the specified string.\n--\n-- >>> makeTable \"hello\"\n-- \"HELOABCDFGIKMNPQRSTUVWXYZ\"\nmakeTable :: String -> String\nmakeTable k = nub key ++ (alpha \\\\ key)\n    where\n      alpha = ['A' .. 'Z'] \\\\ \"J\"\n      key = map toUpper =<< words k\n\n-- | Turns a playfair table into a 5*5 alphabet square.\nmakeSquare :: [a] -> Square a\nmakeSquare = array2D (5, 5)\n\n-- | Displays a playfair square, formatted as a square.\nshowSquare :: Square Char -> String\nshowSquare d = unlines $ chunksOf 5 (elems d)\n\n-- | Given a value and an association list of x-coordinate * y-coordinate * value, returns the coordinates\ngetIndex' :: (Eq a) => a -> [((Int, Int), a)] -> Maybe (Int, Int)\ngetIndex' el = fmap fst . listToMaybe . filter ((== el) . snd)\n\nencodePair, decodePair :: Eq a => Square a -> (a, a) -> Maybe (a, a)\nencodePair = pairHelper (\\x -> if x == 5 then 1 else x + 1)\ndecodePair = pairHelper (\\x -> if x == 1 then 5 else x - 1)\n\npairHelper :: (Eq t)\n    => (Int -> Int) -- ^ a function used for wrapping around the square\n    -> Square t -- ^ a playfair square\n    -> (t, t) -- ^ two characters\n    -> Maybe (t, t) -- ^ the two resulting\/encoded characters\npairHelper adjust sqr (c1, c2) =\n    do let ps = assocs sqr\n       -- assigns an association list of (x-coord * y-coord) * value to ps\n       (x1, y1) <- getIndex' c1 ps\n       (x2, y2) <- getIndex' c2 ps\n       -- returns the coordinates of two values in the square\n       -- these will later be swapped\n       guard $ c1 \/= c2\n       -- the characters (and coordinates) cannot be the same\n       let get x = sqr ! x\n       -- a small utility function for extracting a value from the square\n       Just $\n           -- wrap the coordinates around and find the encrypted characters\n           case () of\n             () | y1 == y2 ->\n                    (get (adjust x1, y1), get (adjust x2, y2))\n                | x1 == x2 ->\n                    (get (x1, adjust y1), get (x2, adjust y2))\n                | otherwise ->\n                    (get (x1, y2), get (x2, y1))\n\n-- | Turns two characters into a tuple.\nparsePair :: String -> [(Char, Char)]\nparsePair = fmap (\\[x, y] -> (x, y)) . words . fmap toUpper\n\n-- | Turns a tuple of two characters into a string.\nunparsePair :: [(Char, Char)] -> String\nunparsePair = unwords . fmap (\\(x, y) -> [x, y])\n\ncodeHelper :: (Square Char -> (Char, Char) -> Maybe (Char, Char))\n    -> String -> String -> Maybe String\ncodeHelper subs key =\n    fmap unparsePair .\n    mapM (subs (makeSquare $ makeTable key)) .\n    parsePair\n\nplayfair, unplayfair :: String -> String -> Maybe String\nplayfair key = codeHelper encodePair key . formatEncode\nunplayfair = codeHelper decodePair\n\nformatEncode :: String -> String\nformatEncode =\n    map toUpper .\n    unwords .\n    map (\\[x, y] -> if x == y then [x, 'x'] else [x, y]) .\n    chunksOf 2 .\n    replace \"j\" \"i\" .\n    concatMap adjustLength .\n    words .\n    filter (\\n -> n `elem` (['A'..'Z'] ++ ['a'..'z']))\n    where\n      adjustLength str\n          | odd (length str) = str ++ \"x\"\n          | otherwise = str\n\n>>> playfair \"playfair example\" \"hide the gold in the tree stump\"\nJust \"BM OD ZB XD NA BE KU DM UI XM KZ ZR YI\"\n\n>>> unplayfair \"playfair example\" \"BM OD ZB XD NA BE KU DM UI XM KZ ZR YI\"\nJust \"HI DE TH EG OL DI NT HE TR EX ST UM PX\"\n\n","human_summarization":"Implement a Playfair cipher for both encryption and decryption. The user has the option to replace 'J' with 'I' or exclude 'Q' from the alphabet. The resulting encrypted and decrypted messages are displayed in capitalized digraphs, separated by spaces.","id":4219}
    {"lang_cluster":"Haskell","source_code":"\n{-# LANGUAGE FlexibleContexts #-}\nimport Data.Array\nimport Data.Array.MArray\nimport Data.Array.ST\nimport Control.Monad.ST\nimport Control.Monad (foldM)\nimport Data.Set as S\n\ndijkstra :: (Ix v, Num w, Ord w, Bounded w) => v -> v -> Array v [(v,w)] -> (Array v w, Array v v)\ndijkstra src invalid_index adj_list = runST $ do\n  min_distance <- newSTArray b maxBound\n  writeArray min_distance src 0\n  previous <- newSTArray b invalid_index\n  let aux vertex_queue =\n        case S.minView vertex_queue of\n          Nothing -> return ()\n          Just ((dist, u), vertex_queue') ->\n            let edges = adj_list ! u\n                f vertex_queue (v, weight) = do\n                  let dist_thru_u = dist + weight\n                  old_dist <- readArray min_distance v\n                  if dist_thru_u >= old_dist then\n                    return vertex_queue\n                  else do\n                    let vertex_queue' = S.delete (old_dist, v) vertex_queue\n                    writeArray min_distance v dist_thru_u\n                    writeArray previous v u\n                    return $ S.insert (dist_thru_u, v) vertex_queue'\n            in\n            foldM f vertex_queue' edges >>= aux  -- note that aux is being called within its own definition (i.e. aux is recursive). The foldM only iterates on the neighbours of v, it does not execute the while loop itself in Dijkstra's\n  aux (S.singleton (0, src))\n  m <- freeze min_distance\n  p <- freeze previous\n  return (m, p)\n  where b = bounds adj_list\n        newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)\n        newSTArray = newArray\n\nshortest_path_to :: (Ix v) => v -> v -> Array v v -> [v]\nshortest_path_to target invalid_index previous =\n  aux target [] where\n    aux vertex acc | vertex == invalid_index = acc\n                   | otherwise = aux (previous ! vertex) (vertex : acc)\n\nadj_list :: Array Char [(Char, Int)]\nadj_list = listArray ('a', 'f') [ [('b',7), ('c',9), ('f',14)],\n                                  [('a',7), ('c',10), ('d',15)],\n                                  [('a',9), ('b',10), ('d',11), ('f',2)],\n                                  [('b',15), ('c',11), ('e',6)],\n                                  [('d',6), ('f',9)],\n                                  [('a',14), ('c',2), ('e',9)] ]\n\nmain :: IO ()\nmain = do\n  let (min_distance, previous) = dijkstra 'a' ' ' adj_list\n  putStrLn $ \"Distance from a to e: \" ++ show (min_distance ! 'e')\n  let path = shortest_path_to 'e' ' ' previous\n  putStrLn $ \"Path: \" ++ show path\n\n","human_summarization":"\"Implement Dijkstra's algorithm to find the shortest path from a single source to all other vertices in a graph with non-negative edge path costs. The algorithm takes a directed and weighted graph, represented by an adjacency matrix or list, and a start node as inputs. It outputs a set of edges depicting the shortest path to each reachable node from the origin. The code also includes functionality to interpret the output and display the shortest path from a specific node to other specified nodes.\"","id":4220}
    {"lang_cluster":"Haskell","source_code":"\n\ndata Tree a\n  = Leaf\n  | Node\n      Int\n      (Tree a)\n      a\n      (Tree a)\n  deriving (Show, Eq)\n \nfoldTree :: Ord a => [a] -> Tree a\nfoldTree = foldr insert Leaf\n \nheight :: Tree a -> Int\nheight Leaf = -1\nheight (Node h _ _ _) = h\n \ndepth :: Tree a -> Tree a -> Int\ndepth a b = succ (max (height a) (height b))\n \ninsert :: Ord a => a -> Tree a -> Tree a\ninsert v Leaf = Node 1 Leaf v Leaf\ninsert v t@(Node n left v_ right)\n  | v_ < v = rotate $ Node n left v_ (insert v right)\n  | v_ > v = rotate $ Node n (insert v left) v_ right\n  | otherwise = t\n \nmax_ :: Ord a => Tree a -> Maybe a\nmax_ Leaf = Nothing\nmax_ (Node _ _ v right) =\n  case right of\n    Leaf -> Just v\n    _ -> max_ right\n \ndelete :: Ord a => a -> Tree a -> Tree a\ndelete _ Leaf = Leaf\ndelete x (Node h left v right)\n  | x == v =\n    maybe left (rotate . (Node h left <*> (`delete` right))) (max_ right)\n  | x > v = rotate $ Node h left v (delete x right)\n  | x < v = rotate $ Node h (delete x left) v right\n \nrotate :: Tree a -> Tree a\nrotate Leaf = Leaf\nrotate (Node h (Node lh ll lv lr) v r)\n  -- Left Left.\n  | lh - height r > 1 && height ll - height lr > 0 =\n    Node lh ll lv (Node (depth r lr) lr v r)\nrotate (Node h l v (Node rh rl rv rr))\n  -- Right Right.\n  | rh - height l > 1 && height rr - height rl > 0 =\n    Node rh (Node (depth l rl) l v rl) rv rr\nrotate (Node h (Node lh ll lv (Node rh rl rv rr)) v r)\n  -- Left Right.\n  | lh - height r > 1 =\n    Node h (Node (rh + 1) (Node (lh - 1) ll lv rl) rv rr) v r\nrotate (Node h l v (Node rh (Node lh ll lv lr) rv rr))\n  -- Right Left.\n  | rh - height l > 1 =\n    Node h l v (Node (lh + 1) ll lv (Node (rh - 1) lr rv rr))\nrotate (Node h l v r) =\n  -- Re-weighting.\n  let (l_, r_) = (rotate l, rotate r)\n   in Node (depth l_ r_) l_ v r_\n \ndraw :: Show a => Tree a -> String\ndraw t = '\\n' : draw_ t 0 <> \"\\n\"\n  where\n    draw_ Leaf _ = []\n    draw_ (Node h l v r) d = draw_ r (d + 1) <> node <> draw_ l (d + 1)\n      where\n        node = padding d <> show (v, h) <> \"\\n\"\n        padding n = replicate (n * 4) ' '\n \nmain :: IO ()\nmain = putStr $ draw $ foldTree [1 .. 31]\n\n\n","human_summarization":"implement an AVL tree with basic operations. The AVL tree is a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The tree rebalances itself after each insertion or deletion to maintain this property. The basic operations including lookup, insertion, and deletion all take O(log n) time. The tree does not allow duplicate node keys. The implementation is based on the solution of homework #4 from the course at http:\/\/www.seas.upenn.edu\/~cis194\/spring13\/lectures.html.","id":4221}
    {"lang_cluster":"Haskell","source_code":"\nadd (a, b) (x, y) = (a + x, b + y)\nsub (a, b) (x, y) = (a - x, b - y)\nmagSqr (a, b)     = (a ^^ 2) + (b ^^ 2)\nmag a             = sqrt $ magSqr a\nmul (a, b) c      = (a * c, b * c)\ndiv2 (a, b) c     = (a \/ c, b \/ c)\nperp (a, b)       = (negate b, a)\nnorm a            = a `div2` mag a\n\ncirclePoints :: (Ord a, Floating a) =>\n                (a, a) -> (a, a) -> a -> Maybe ((a, a), (a, a))\ncirclePoints p q radius\n  | radius == 0      = Nothing\n  | p == q           = Nothing\n  | diameter < magPQ = Nothing\n  | otherwise        = Just (center1, center2)\n  where\n    diameter = radius * 2\n    pq       = p `sub` q\n    magPQ    = mag pq\n    midpoint = (p `add` q) `div2` 2\n    halfPQ   = magPQ \/ 2\n    magMidC  = sqrt . abs $ (radius ^^ 2) - (halfPQ ^^ 2)\n    midC     = (norm $ perp pq) `mul` magMidC\n    center1  = midpoint `add` midC\n    center2  = midpoint `sub` midC\n\nuncurry3 f (a, b, c) = f a b c\n\nmain :: IO ()\nmain = mapM_ (print . uncurry3 circlePoints)\n  [((0.1234, 0.9876), (0.8765, 0.2345), 2),\n   ((0     , 2     ), (0     , 0     ), 1),\n   ((0.1234, 0.9876), (0.1234, 0.9876), 2),\n   ((0.1234, 0.9876), (0.8765, 0.2345), 0.5),\n   ((0.1234, 0.9876), (0.1234, 0.1234), 0)]\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":4222}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad\nimport System.Random\n\nloopBreak n k = do \n  r <- randomRIO (0,n)\n  print r\n  unless (r==k) $ do\n    print =<< randomRIO (0,n)\n    loopBreak n k\n\n\nloopBreak 19 10\n\n","human_summarization":"Generates and prints random numbers from 0 to 19. If the first generated number is 10, the loop stops. If not, a second random number is generated and printed before the loop restarts. If 10 is never the first number, the loop continues indefinitely.","id":4223}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List\nimport HFM.Primes (isPrime)\nimport Control.Monad\nimport Control.Arrow\n\nint2bin = reverse.unfoldr(\\x -> if x==0 then Nothing\n                                else Just ((uncurry.flip$(,))$divMod x 2))\n\ntrialfac m = take 1. dropWhile ((\/=1).(\\q -> foldl (((`mod` q).).pm) 1 bs)) $ qs\n  where qs = filter (liftM2 (&&) (liftM2 (||) (==1) (==7) .(`mod`8)) isPrime ).\n              map (succ.(2*m*)). enumFromTo 1 $ m `div` 2\n        bs = int2bin m\n        pm n b = 2^b*n*n\n\n*Main> trialfac 929\n[13007]\n\n","human_summarization":"The code implements a method to find a factor of a Mersenne number, specifically 2^929-1 (M929). It uses the modPow operation to determine if a number divides 2^P-1. The code also uses the properties of Mersenne numbers to refine the process, where any factor q of 2^P-1 must be of the form 2kP+1 and must be 1 or 7 mod 8. The algorithm stops when 2kP+1 > sqrt(N). The code utilizes the Primes module by David Amos for prime number testing.","id":4224}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List\nimport Control.Arrow\nimport Control.Monad\n\ntakeWhileIncl           :: (a -> Bool) -> [a] -> [a]\ntakeWhileIncl _ []      =  []\ntakeWhileIncl p (x:xs)\n            | p x       =  x : takeWhileIncl p xs\n            | otherwise =  [x] \n\ngetmultiLineItem n = takeWhileIncl(not.isInfixOf (\"<\/\" ++ n)). dropWhile(not.isInfixOf ('<': n))\ngetsingleLineItems n = map (takeWhile(\/='<'). drop 1. dropWhile(\/='>')). filter (isInfixOf ('<': n))\n\nmain = do\n  xml <- readFile \".\/Rosetta\/xmlpath.xml\"\n  let xmlText = lines xml\n      \n  putStrLn \"\\n== First item ==\\n\"\n  mapM_ putStrLn $ head $ unfoldr (Just. liftM2 (id &&&) (\\\\) (getmultiLineItem \"item\")) xmlText\n  \n  putStrLn \"\\n== Prices ==\\n\"\n  mapM_ putStrLn $ getsingleLineItems \"price\" xmlText\n  \n  putStrLn \"\\n== Names ==\\n\"\n  print $ getsingleLineItems \"name\" xmlText\n\n\n{-# LANGUAGE Arrows #-}\nimport Text.XML.HXT.Arrow\n{- For HXT version >= 9.0, use instead:\nimport Text.XML.HXT.Core\n-}\n\ndeepElem name = deep (isElem >>> hasName name)\n\nprocess = proc doc -> do\n  item <- single (deepElem \"item\") -< doc\n  _ <- listA (arrIO print <<< deepElem \"price\") -< doc\n  names <- listA (deepElem \"name\") -< doc\n  returnA -< (item, names)\n  \nmain = do\n  [(item, names)] <- runX (readDocument [] \"xmlpath.xml\" >>> process)\n  print item\n  print names\n\n","human_summarization":"The code performs three XPath queries on a given XML document. It retrieves the first \"item\" element, prints out each \"price\" element, and creates an array of all the \"name\" elements. The operations are performed using the Haskell XML Toolkit (HXT).","id":4225}
    {"lang_cluster":"Haskell","source_code":"\nWorks with: GHC\n\nPrelude> import Data.Set\nPrelude Data.Set> empty :: Set Integer -- Empty set\nfromList []\nPrelude Data.Set> let s1 = fromList [1,2,3,4,3] -- Convert list into set\nPrelude Data.Set> s1\nfromList [1,2,3,4]\nPrelude Data.Set> let s2 = fromList [3,4,5,6] \nPrelude Data.Set> union s1 s2 -- Union\nfromList [1,2,3,4,5,6]\nPrelude Data.Set> intersection s1 s2 -- Intersection\nfromList [3,4]\nPrelude Data.Set> s1 \\\\ s2 -- Difference\nfromList [1,2]\nPrelude Data.Set> s1 `isSubsetOf` s1 -- Subset\nTrue\nPrelude Data.Set> fromList [3,1] `isSubsetOf` s1\nTrue\nPrelude Data.Set> s1 `isProperSubsetOf` s1 -- Proper subset\nFalse\nPrelude Data.Set> fromList [3,1] `isProperSubsetOf` s1\nTrue\nPrelude Data.Set> fromList [3,2,4,1] == s1 -- Equality\nTrue\nPrelude Data.Set> s1 == s2\nFalse\nPrelude Data.Set> 2 `member` s1 -- Membership\nTrue\nPrelude Data.Set> 10 `notMember` s1\nTrue\nPrelude Data.Set> size s1 -- Cardinality\n4\nPrelude Data.Set> insert 99 s1 -- Create a new set by inserting\nfromList [1,2,3,4,99]\nPrelude Data.Set> delete 3 s1 -- Create a new set by deleting\nfromList [1,2,4]\n\n\nPrelude> import Data.List\nPrelude Data.List> let s3 = nub [1,2,3,4,3] -- Remove duplicates from list\nPrelude Data.List> s3\n[1,2,3,4]\nPrelude Data.List> let s4 = [3,4,5,6]\nPrelude Data.List> union s3 s4 -- Union\n[1,2,3,4,5,6]\nPrelude Data.List> intersect s3 s4 -- Intersection\n[3,4]\nPrelude Data.List> s3 \\\\ s4 -- Difference\n[1,2]\nPrelude Data.List> 42 : s3 -- Return new list with element inserted at the beginning\n[42,1,2,3,4]\nPrelude Data.List> delete 3 s3 -- Return new list with first occurrence of element removed\n[1,2,4]\n\n","human_summarization":"implement a set data structure with operations including set creation, checking if an element is in a set, union, intersection, difference, subset, and equality of sets. Optional operations include other set operations and modification of a mutable set. The set can be implemented using an associative array, a binary search tree, a hash table, or an ordered array of binary bits. The code also includes the functionality of using regular lists as sets with some helper functions. The code uses GHC's Data.Set module for a functional, persistent set data structure.","id":4226}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.Time (fromGregorian)\nimport Data.Time.Calendar.WeekDate (toWeekDate)\n\n--------------------- DAY OF THE WEEK --------------------\n\nisXmasSunday :: Integer -> Bool\nisXmasSunday year = 7 == weekDay\n  where\n    (_, _, weekDay) = toWeekDate $ fromGregorian year 12 25\n\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n  mapM_\n    putStrLn\n    [ \"Sunday 25 December \" <> show year\n      | year <- [2008 .. 2121],\n        isXmasSunday year\n    ]\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any date\/time handling anomalies, such as overflow issues similar to the y2k problem. The code also acknowledges the potential for overflow in the System.Time module at the Unix epoch in 2038 on 64-bit systems running current versions of GHC.","id":4227}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List\nimport Text.Printf (printf)\n\neps = 1e-6 :: Double\n\n-- a matrix is represented as a list of columns\nmmult :: Num a => [[a]] -> [[a]] -> [[a]] \nnth :: Num a => [[a]] -> Int -> Int -> a\nmmult_num :: Num a => [[a]] -> a -> [[a]]\nmadd :: Num a => [[a]] -> [[a]] -> [[a]]\nidMatrix :: Num a => Int -> Int -> [[a]]\n\nadjustWithE :: [[Double]] -> Int -> [[Double]]\n\nmmult a b = [ [ sum $ zipWith (*) ak bj | ak <- (transpose a) ] | bj <- b ]\nnth mA i j = (mA !! j) !! i\nmmult_num mA n = map (\\c -> map (*n) c) mA\nmadd mA mB = zipWith (\\c1 c2 -> zipWith (+) c1 c2) mA mB\nidMatrix n m = [ [if (i==j) then 1 else 0 | i <- [1..n]] | j <- [1..m]]\n\nadjustWithE mA n = let lA = length mA in\n    (idMatrix n (n - lA)) ++ (map (\\c -> (take (n - lA) (repeat 0.0)) ++ c ) mA)\n\n-- auxiliary functions\nsqsum :: Floating a => [a] -> a\nnorm :: Floating a => [a] -> a\nepsilonize :: [[Double]] -> [[Double]]\n\nsqsum a = foldl (\\x y -> x + y*y) 0 a\nnorm a = sqrt $! sqsum a\nepsilonize mA = map (\\c -> map (\\x -> if abs x <= eps then 0 else x) c) mA\n\n-- Householder transformation; householder A = (Q, R)\nuTransform :: [Double] -> [Double]\nhMatrix :: [Double] -> Int -> Int -> [[Double]]\nhouseholder :: [[Double]] -> ([[Double]], [[Double]])\n\n-- householder_rec Q R A\nhouseholder_rec :: [[Double]] -> [[Double]] -> Int -> ([[Double]], [[Double]])\n\nuTransform a = let t = (head a) + (signum (head a))*(norm a) in\n    1 : map (\\x -> x\/t) (tail a)\n\nhMatrix a n i = let u = uTransform (drop i a) in\n    madd\n        (idMatrix (n-i) (n-i))\n        (mmult_num\n            (mmult [u] (transpose [u]))\n            ((\/) (-2) (sqsum u)))\n\nhouseholder_rec mQ mR 0 = (mQ, mR)\nhouseholder_rec mQ mR n = let mSize = length mR in\n    let mH = adjustWithE (hMatrix (mR!!(mSize - n)) mSize (mSize - n)) mSize in\n        householder_rec (mmult mQ mH) (mmult mH mR) (n - 1)\n\nhouseholder mA = let mSize = length mA in\n    let (mQ, mR) = householder_rec (idMatrix mSize mSize) mA mSize in\n        (epsilonize mQ, epsilonize mR)\n\nbackSubstitution :: [[Double]] -> [Double] -> [Double] -> [Double]\nbackSubstitution mR [] res = res\nbackSubstitution mR@(hR:tR) q@(h:t) res =\n    let x = (h \/ (head hR)) in\n        backSubstitution\n            (map tail tR)\n            (tail (zipWith (-) q (map (*x) hR)))\n            (x : res)\n\nshowMatrix :: [[Double]] -> String\nshowMatrix mA =\n    concat $ intersperse \"\\n\"\n        (map (\\x -> unwords $ printf \"%10.4f\" <$> (x::[Double])) (transpose mA))\n\nmY = [[12, 6, -4], [-51, 167, 24], [4, -68, -41]] :: [[Double]]\nq = [21, 245, 35] :: [Double]\nmain = let (mQ, mR) = householder mY in\n    putStrLn (\"Q: \\n\" ++ showMatrix mQ) >>\n    putStrLn (\"R: \\n\" ++ showMatrix mR) >>\n    putStrLn (\"q: \\n\" ++ show q) >>\n    putStrLn (\"x: \\n\" ++ show (backSubstitution (reverse (map reverse mR)) (reverse q) []))\n\n\n","human_summarization":"Implement QR decomposition using Householder reflections. The code takes a rectangular matrix and decomposes it into a product of an orthogonal matrix and an upper triangular matrix. It also demonstrates the QR decomposition on a given example matrix and uses it to solve linear least squares problems. The code handles the case when the matrix is not square by cutting off the zero padded bottom rows. It finally solves the square upper triangular system by back substitution.","id":4228}
    {"lang_cluster":"Haskell","source_code":"\n print $ unique [4, 5, 4, 2, 3, 3, 4]\n\n[4,5,2,3]\n\n\nimport qualified Data.Set as Set\n\nunique :: Ord a => [a] -> [a]\nunique = Set.toList . Set.fromList\n\n\nimport Data.Set\n\nunique :: Ord a => [a] -> [a]\nunique = loop empty\n  where\n    loop s []                    = []\n    loop s (x : xs) | member x s = loop s xs\n                    | otherwise  = x : loop (insert x s) xs\n\n\nimport Data.List\n\nunique :: Eq a => [a] -> [a]\nunique []       = []\nunique (x : xs) = x : unique (filter (x \/=) xs)\n\nimport Data.List\nData.List.nub :: Eq a => [a] -> [a]\nData.List.Unique.unique :: Ord a => [a] -> [a]\n\n","human_summarization":"implement three methods to remove duplicate elements from an array: \n\n1. Using a hash table to eliminate duplicates, with an average complexity of O(n) and worst-case complexity of O(n^2).\n2. Sorting the array and removing consecutive duplicates, with a complexity of O(n log n).\n3. Iterating through the array and discarding any element that appears more than once, with a complexity of O(n^2). \n\nThe first two methods require a partial ordering of elements, whereas the third only requires that elements can be compared for equality.","id":4229}
    {"lang_cluster":"Haskell","source_code":"\n\nqsort [] = []\nqsort (x:xs) = qsort [y | y <- xs, y < x] ++ [x] ++ qsort [y | y <- xs, y >= x]\n\n\nimport Data.List (partition)\n\nqsort :: Ord a => [a] -> [a]\nqsort [] = []\nqsort (x:xs) = qsort ys ++ [x] ++ qsort zs where\n    (ys, zs) = partition (< x) xs\n\n","human_summarization":"implement a quicksort algorithm to sort an array or list of elements. The algorithm selects a pivot element and divides the rest of the elements into two partitions, one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts both partitions and merges them with the pivot. The codes also include an optimized version of quicksort that works in place by swapping elements within the array to save memory allocation. The pivot selection method is not specified and can vary.","id":4230}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Time\n       (FormatTime, formatTime, defaultTimeLocale, utcToLocalTime,\n        getCurrentTimeZone, getCurrentTime)\n\nformats :: FormatTime t => [t -> String]\nformats = (formatTime defaultTimeLocale) <$>  [\"%F\", \"%A, %B %d, %Y\"]\n\nmain :: IO ()\nmain = do\n  t <- pure utcToLocalTime <*> getCurrentTimeZone <*> getCurrentTime\n  putStrLn $ unlines (formats <*> pure t)\n\n\n2017-06-05\nMonday, June 05, 2017\n","human_summarization":"\"Display the current date in two different formats: '2007-11-23' and 'Friday, November 23, 2007'.\"","id":4231}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Set\nimport Control.Monad\n\npowerset :: Ord a => Set a -> Set (Set a)\npowerset = fromList . fmap fromList . listPowerset . toList\n\nlistPowerset :: [a] -> [[a]]\nlistPowerset = filterM (const [True, False])\n\n\npowerset [] = [[]]\npowerset (head:tail) = acc ++ map (head:) acc where acc = powerset tail\n\n\npowerSet :: [a] -> [[a]]\npowerSet = foldr (\\x acc -> acc ++ map (x:) acc) [[]]\n\n\npowerSet :: [a] -> [[a]]\npowerSet = foldr ((mappend <*>) . fmap . (:)) (pure [])\n\n\n*Main> listPowerset [1,2,3]\n[[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]]\n*Main> powerset (Data.Set.fromList [1,2,3])\n{{},{1},{1,2},{1,2,3},{1,3},{2},{2,3},{3}}\n\nWorks with: GHC version 6.10\nPrelude> import Data.List\nPrelude Data.List> subsequences [1,2,3]\n[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]\n\n\nimport qualified Data.Set as Set\ntype Set=Set.Set\nunionAll :: (Ord a) => Set (Set a) -> Set a\nunionAll = Set.fold Set.union Set.empty\n\n--slift is the analogue of liftA2 for sets.\nslift :: (Ord a, Ord b, Ord c) => (a->b->c) -> Set a -> Set b -> Set c\nslift f s0 s1 = unionAll (Set.map (\\e->Set.map (f e) s1) s0)\n\n--a -> {{},{a}}\nmakeSet :: (Ord a) => a -> Set (Set a)\nmakeSet = (Set.insert Set.empty) . Set.singleton.Set.singleton\n\npowerSet :: (Ord a) => Set a -> Set (Set a)\npowerSet = (Set.fold (slift Set.union) (Set.singleton Set.empty)) . Set.map makeSet\n\n\nPrelude Data.Set> powerSet fromList [1,2,3]\nfromList [fromList [], fromList [1], fromList [1,2], fromList [1,2,3], fromList [1,3], fromList [2], fromList [2,3], fromList [3]]\n\n","human_summarization":"The code takes a set S as input and generates the power set of S. It can either use a built-in set type or define a set type with necessary operations. The power set includes all possible subsets of the input set, including the empty set. The code also demonstrates the ability to handle power sets of the empty set and the set containing only the empty set. An alternate solution uses set operations and set mapping.","id":4232}
    {"lang_cluster":"Haskell","source_code":"\n\ndigit :: Char -> Char -> Char -> Integer -> String\ndigit x y z k =\n  [[x], [x, x], [x, x, x], [x, y], [y], [y, x], [y, x, x], [y, x, x, x], [x, z]] !!\n  (fromInteger k - 1)\n\ntoRoman :: Integer -> String\ntoRoman 0 = \"\"\ntoRoman x\n  | x < 0 = error \"Negative roman numeral\"\ntoRoman x\n  | x >= 1000 = 'M' : toRoman (x - 1000)\ntoRoman x\n  | x >= 100 = digit 'C' 'D' 'M' q ++ toRoman r\n  where\n    (q, r) = x `divMod` 100\ntoRoman x\n  | x >= 10 = digit 'X' 'L' 'C' q ++ toRoman r\n  where\n    (q, r) = x `divMod` 10\ntoRoman x = digit 'I' 'V' 'X' x\n\nmain :: IO ()\nmain = print $ toRoman <$> [1999, 25, 944]\n\n\n","human_summarization":"The code takes a positive integer as input and returns its Roman numeral representation as a string. It processes each digit separately, starting from the leftmost digit and ignoring zeros. The code also includes a function, romanFromInt, which uses mapAccumL for explicit decimal digit representation. It also abstracts Roman patterns and applies a simple logic programming idiom.","id":4233}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.Array.IO\n\nmain = do arr <- newArray (1,10) 37\u00a0:: IO (IOArray Int Int)\n          a <- readArray arr 1\n          writeArray arr 1 64\n          b <- readArray arr 1 \n          print (a,b)\n","human_summarization":"demonstrate the basic syntax of arrays in a specific programming language. They include creating an array, assigning a value to it, and retrieving an element from it. Both fixed-length and dynamic arrays are shown, with a value being pushed into the latter. The codes also incorporate elements from previous tasks related to array creation, value assignment, and element retrieval.","id":4234}
    {"lang_cluster":"Haskell","source_code":"\n\nmain = readFile \"input.txt\" >>= writeFile \"output.txt\"\n\n","human_summarization":"demonstrate reading the contents of \"input.txt\" file into a variable, and then writing these contents into a new file called \"output.txt\". The process does not keep the file in memory due to buffering provided by lazy evaluation. The code does not use oneliners that skip the intermediate variable.","id":4235}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Char\n\ns = \"alphaBETA\"\n\nlower = map toLower s\nupper = map toUpper s\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":4236}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List (minimumBy, tails, unfoldr, foldl1') --'\n\nimport System.Random (newStdGen, randomRs)\n\nimport Control.Arrow ((&&&))\n\nimport Data.Ord (comparing)\n\nvecLeng [[a, b], [p, q]] = sqrt $ (a - p) ^ 2 + (b - q) ^ 2\n\nfindClosestPair =\n  foldl1'' ((minimumBy (comparing vecLeng) .) . (. return) . (:)) .\n  concatMap (\\(x:xs) -> map ((x :) . return) xs) . init . tails\n\ntestCP = do\n  g <- newStdGen\n  let pts :: [[Double]]\n      pts = take 1000 . unfoldr (Just . splitAt 2) $ randomRs (-1, 1) g\n  print . (id &&& vecLeng) . findClosestPair $ pts\n\nmain = testCP\n\nfoldl1'' = foldl1'\n\n\n","human_summarization":"The code provides two solutions to the Closest Pair of Points problem in a two-dimensional plane. The first solution uses a brute-force algorithm with a time complexity of O(n^2), iterating through all possible pairs to find the minimum distance. The second solution uses a recursive divide-and-conquer approach with a time complexity of O(n log n), sorting the points by x and y coordinates, dividing the set into two halves, and recursively finding the closest pairs in each half. The code then compares the closest pairs from both halves and a strip in the middle to find the overall closest pair.","id":4237}
    {"lang_cluster":"Haskell","source_code":"\n\n[1, 2, 3, 4, 5]\n\n\n1 : [2, 3, 4]\n\n\n[1, 2] ++ [3, 4]\n\n\nconcat [[1, 2], [3, 4], [5, 6, 7]]\n\n\nimport Data.Array (Array, listArray, Ix, (!))\n\ntriples :: Array Int (Char, String, String)\ntriples =\n  listArray (0, 11) $\n  zip3\n    \"\u9f20\u725b\u864e\u5154\u9f8d\u86c7\u99ac\u7f8a\u7334\u9e21\u72d7\u8c6c\" -- \u751f\u8096 shengxiao \u2013 symbolic animals\n    (words \"sh\u01d4 ni\u00fa h\u01d4 t\u00f9 l\u00f3ng sh\u00e9 m\u01ce y\u00e1ng h\u00f3u j\u012b g\u01d2u zh\u016b\")\n    (words \"rat ox tiger rabbit dragon snake horse goat monkey rooster dog pig\")\n\nindexedItem\n  :: Ix i\n  => Array i (Char, String, String) -> i -> String\nindexedItem a n =\n  let (c, w, w1) = a ! n\n  in c : unwords [\"\\t\", w, w1]\n\nmain :: IO ()\nmain = (putStrLn . unlines) $ indexedItem triples <$> [2, 4, 6]\n\n\n","human_summarization":"create a collection and add values to it. It includes operations like prepending an element to a list, concatenating two lists, concatenating a list of lists, retrieving by index, key-value indexing, and efficient set operations. The code also considers different collection types for efficiency and flexible access.","id":4238}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List (maximumBy)\nimport Data.Ord (comparing)\n\n(maxWgt, maxVol) = (25, 0.25)\nitems =\n   [Bounty  \"panacea\"  3000  0.3  0.025,\n    Bounty  \"ichor\"    1800  0.2  0.015,\n    Bounty  \"gold\"     2500  2.0  0.002]\n\ndata Bounty = Bounty\n   {itemName :: String,\n    itemVal :: Int,\n    itemWgt, itemVol :: Double}\n\nnames = map itemName items\nvals = map itemVal items\nwgts = map itemWgt items\nvols = map itemVol items\n\ndotProduct :: (Num a, Integral b) => [a] -> [b] -> a\ndotProduct factors = sum . zipWith (*) factors . map fromIntegral\n\noptions :: [[Int]]\noptions = filter fits $ mapM f items\n  where f (Bounty _ _ w v) = [0 .. m]\n          where m = floor $ min (maxWgt \/ w) (maxVol \/ v)\n        fits opt = dotProduct wgts opt <= maxWgt &&\n                   dotProduct vols opt <= maxVol\n\nshowOpt :: [Int] -> String\nshowOpt opt = concat (zipWith showItem names opt) ++\n    \"total weight: \" ++ show (dotProduct wgts opt) ++\n    \"\\ntotal volume: \" ++ show (dotProduct vols opt) ++\n    \"\\ntotal value: \" ++ show (dotProduct vals opt) ++ \"\\n\"\n  where showItem name num = name ++ \": \" ++ show num ++ \"\\n\"\n\nmain = putStr $ showOpt $ best options\n  where best = maximumBy $ comparing $ dotProduct vals\n\n\npanacea: 9\nichor: 0\ngold: 11\ntotal weight: 24.7\ntotal volume: 0.247\ntotal value: 54500\n","human_summarization":"\"Generate a brute-force solution to the unbounded Knapsack problem, where a traveler in Shangri La can take as many items as he can carry and fit in his knapsack, with the goal of maximizing the total value of the items. The code generates all possible combinations of items, ensuring the total weight and volume do not exceed the knapsack's capacity, and then selects the combination with the highest total value.\"","id":4239}
    {"lang_cluster":"Haskell","source_code":"\nmain :: IO ()\nmain = forM_ [1 .. 10] $ \\n -> do\n            putStr $ show n\n            putStr $ if n == 10 then \"\\n\" else \", \"\n\n\nintercalate \", \" (map show [1..10])\n\n","human_summarization":"The code generates a comma-separated list of numbers from 1 to 10, using separate output statements for the number and the comma within the loop body. It also demonstrates how to execute only part of the loop body in the last iteration.","id":4240}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List ((\\\\), elemIndex, intersect, nub)\nimport Data.Bifunctor (bimap, first)\n\ncombs 0 _ = [[]]\ncombs _ [] = []\ncombs k (x:xs) = ((x :) <$> combs (k - 1) xs) ++ combs k xs\n\ndepLibs :: [(String, String)]\ndepLibs =\n  [ ( \"des_system_lib\"\n    , \"std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\")\n  , (\"dw01\", \"ieee dw01 dware gtech\")\n  , (\"dw02\", \"ieee dw02 dware\")\n  , (\"dw03\", \"std synopsys dware dw03 dw02 dw01 ieee gtech\")\n  , (\"dw04\", \"dw04 ieee dw01 dware gtech\")\n  , (\"dw05\", \"dw05 ieee dware\")\n  , (\"dw06\", \"dw06 ieee dware\")\n  , (\"dw07\", \"ieee dware\")\n  , (\"dware\", \"ieee dware\")\n  , (\"gtech\", \"ieee gtech\")\n  , (\"ramlib\", \"std ieee\")\n  , (\"std_cell_lib\", \"ieee std_cell_lib\")\n  , (\"synopsys\", [])\n  ]\n\ntoposort :: [(String, String)] -> [String]\ntoposort xs\n  | (not . null) cycleDetect =\n    error $ \"Dependency cycle detected for libs \" ++ show cycleDetect\n  | otherwise = foldl makePrecede [] dB\n  where\n    dB = (\\(x, y) -> (x, y \\\\ x)) . bimap return words <$> xs\n    makePrecede ts ([x], xs) =\n      nub $\n      case elemIndex x ts of\n        Just i -> uncurry (++) $ first (++ xs) $ splitAt i ts\n        _ -> ts ++ xs ++ [x]\n    cycleDetect =\n      filter ((> 1) . length) $\n      (\\[(a, as), (b, bs)] -> (a `intersect` bs) ++ (b `intersect` as)) <$>\n      combs 2 dB\n\nmain :: IO ()\nmain = print $ toposort depLibs\n\n\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":4241}
    {"lang_cluster":"Haskell","source_code":"\n> import Data.List\n> \"abc\" `isPrefixOf` \"abcdefg\"\nTrue\n> \"efg\" `isSuffixOf` \"abcdefg\"\nTrue\n> \"bcd\" `isInfixOf` \"abcdefg\"\nTrue\n> \"abc\" `isInfixOf` \"abcdefg\" -- Prefixes and suffixes are also infixes\nTrue\n> let infixes a b = findIndices (isPrefixOf a) $ tails b\n> infixes \"ab\" \"abcdefabqqab\"\n[0,6,10]\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":4242}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List\nimport Control.Monad\n\nperms :: (Eq a) => [a] -> [[a]]\nperms [] = [[]]\nperms xs = [ x:xr | x <- xs, xr <- perms (xs\\\\[x]) ]\n\ncombs :: (Eq a) => Int -> [a] -> [[a]]\ncombs 0 _ = [[]]\ncombs n xs = [ x:xr | x <- xs, xr <- combs (n-1) xs ]\n\nringCheck :: [Int] -> Bool\nringCheck [x0, x1, x2, x3, x4, x5, x6] = \n          v == x1+x2+x3 \n       && v == x3+x4+x5 \n       && v == x5+x6\n    where v = x0 + x1\n\nfourRings :: Int -> Int -> Bool -> Bool -> IO ()\nfourRings low high allowRepeats verbose = do\n    let candidates = if allowRepeats\n                     then combs 7 [low..high]\n                     else perms [low..high]\n\n        solutions = filter ringCheck candidates\n\n    when verbose $ mapM_ print solutions\n\n    putStrLn $    show (length solutions)  \n               ++ (if allowRepeats then \" non\" else \"\")\n               ++ \" unique solutions for \" \n               ++ show low \n               ++ \" to \" \n               ++ show high\n\n    putStrLn \"\"\n\nmain = do\n   fourRings 1 7 False True\n   fourRings 3 9 False True\n   fourRings 0 9 True False\n\n\n","human_summarization":"The code finds all possible solutions for a 4-rings or 4-squares puzzle where each square sums up to the same total. It replaces letters a-g with unique decimal digits from a given range (LOW to HIGH). It provides solutions for two specific ranges, LOW=1, HIGH=7 and LOW=3, HIGH=9. Additionally, it calculates the total number of solutions when digits can be non-unique within the range LOW=0, HIGH=9. The code uses a nested search approach for faster performance.","id":4243}
    {"lang_cluster":"Haskell","source_code":"\nLibrary: ansi-terminal\nimport Control.Concurrent\nimport Data.List\nimport System.Time\n\n-- Library: ansi-terminal\nimport System.Console.ANSI\n\nnumber :: (Integral a) => a -> [String]\nnumber 0 =\n  [\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"\u2588\u2588  \u2588\u2588\"\n  ,\"\u2588\u2588  \u2588\u2588\"\n  ,\"\u2588\u2588  \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"]\nnumber 1 =\n  [\"    \u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"    \u2588\u2588\"]\nnumber 2 =\n  [\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"\u2588\u2588    \"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"]\nnumber 3 =\n  [\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"]\nnumber 4 =\n  [\"\u2588\u2588  \u2588\u2588\"\n  ,\"\u2588\u2588  \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"    \u2588\u2588\"]\nnumber 5 =\n  [\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"\u2588\u2588    \"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"]\nnumber 6 =\n  [\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"\u2588\u2588    \"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"\u2588\u2588  \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"]\nnumber 7 =\n  [\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"    \u2588\u2588\"]\nnumber 8 =\n  [\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"\u2588\u2588  \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"\u2588\u2588  \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"]\nnumber 9 =\n  [\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"\u2588\u2588  \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"\n  ,\"    \u2588\u2588\"\n  ,\"\u2588\u2588\u2588\u2588\u2588\u2588\"]\n\ncolon :: [String]\ncolon =\n  [\"      \"\n  ,\"  \u2588\u2588  \"\n  ,\"      \"\n  ,\"  \u2588\u2588  \"\n  ,\"      \"]\n\nnewline :: [String]\nnewline =\n  [\"\\n\"\n  ,\"\\n\"\n  ,\"\\n\"\n  ,\"\\n\"\n  ,\"\\n\"]\n\nspace :: [String]\nspace =\n  [\" \"\n  ,\" \"\n  ,\" \"\n  ,\" \"\n  ,\" \"]\n\nleadingZero :: (Integral a) => a -> [[String]]\nleadingZero num =\n  let (tens, ones) = divMod num 10\n  in [number tens, space, number ones]\n\nfancyTime :: CalendarTime -> String\nfancyTime time =\n  let hour   = leadingZero $ ctHour time\n      minute = leadingZero $ ctMin time\n      second = leadingZero $ ctSec time\n      nums   = hour ++ [colon] ++ minute ++ [colon] ++ second ++ [newline]\n  in concat $ concat $ transpose nums\n\nmain :: IO ()\nmain = do\n  time <- getClockTime >>= toCalendarTime\n  putStr $ fancyTime time\n  threadDelay 1000000\n  setCursorColumn 0\n  cursorUp 5\n  main\n\n","human_summarization":"illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.","id":4244}
    {"lang_cluster":"Haskell","source_code":"\npytr :: Int -> [(Bool, Int, Int, Int)]\npytr n =\n  filter\n    (\\(_, a, b, c) -> a + b + c <= n)\n    [ (prim a b c, a, b, c)\n      | a <- xs,\n        b <- drop a xs,\n        c <- drop b xs,\n        a ^ 2 + b ^ 2 == c ^ 2\n    ]\n  where\n    xs = [1 .. n]\n    prim a b _ = gcd a b == 1\n\nmain :: IO ()\nmain =\n  putStrLn $\n    \"Up to 100 there are \"\n      <> show (length xs)\n      <> \" triples, of which \"\n      <> show (length $ filter (\\(x, _, _, _) -> x) xs)\n      <> \" are primitive.\"\n  where\n    xs = pytr 100\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples (a set of three positive integers a, b, c where a<b<c and a^2 + b^2 = c^2) with a perimeter no larger than 100. It also determines the number of these triples that are primitive, meaning the three numbers are co-prime. The code is optimized to handle large values, able to calculate for a maximum perimeter up to 100,000,000.","id":4245}
    {"lang_cluster":"Haskell","source_code":"\nUsing Library: HGL from HackageDB.\n\nimport Graphics.HGL\n\naWindow =  runGraphics $\n  withWindow_ \"Rosetta Code task: Creating a window\" (300, 200) $ \\ w -> do\n\tdrawInWindow w $ text (100, 100) \"Hello World\"\n\tgetKey w\n\n","human_summarization":"create a GUI window that can respond to close requests, utilizing a simplified graphics library which provides access to key features of the Win32 Graphics Device Interface and X11 library.","id":4246}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List (group,sort)\nimport Control.Arrow ((&&&))\nmain = interact (show . map (head &&& length) . group . sort)\n\n\nimport Data.List (sortBy)\nimport qualified Data.Map.Strict as M\nimport Data.Ord (comparing)\n\ncharCounts :: String -> M.Map Char Int\ncharCounts = foldr (M.alter f) M.empty\n  where\n    f (Just x) = Just (succ x)\n    f _ = Just 1\n\nmain :: IO ()\nmain =\n  readFile \"miserables.txt\"\n    >>= mapM_ print\n      . sortBy\n        (flip $ comparing snd)\n      . M.toList\n      . charCounts\n\n\n","human_summarization":"\"Open a text file, count the frequency of each letter, and optionally include punctuation. Alternatively, use a container as an accumulator for a single fold instead of sorting and grouping the entire string.\"","id":4247}
    {"lang_cluster":"Haskell","source_code":"\n\n data List a = Nil | Cons a (List a)\n\n\n data IntList s = Nil | Cons Integer (STRef s (IntList s))\n\n\n","human_summarization":"define a data structure for a singly-linked list element. This element holds a numeric value and has a mutable link to the next element. This is not a common practice in Haskell due to its immutability and frequent use of lists with any data member type.","id":4248}
    {"lang_cluster":"Haskell","source_code":"\n\nLibrary: Gloss\nimport Graphics.Gloss\n\ntype Model = [Picture -> Picture]\n       \nfractal :: Int -> Model -> Picture -> Picture\nfractal n model pict = pictures $ take n $ iterate (mconcat model) pict\n\ntree1 _ = fractal 10 branches $ Line [(0,0),(0,100)]\n  where branches = [ Translate 0 100 . Scale 0.75 0.75 . Rotate 30 \n                   , Translate 0 100 . Scale 0.5 0.5 . Rotate (-30) ]\n\nmain = animate (InWindow \"Tree\" (800, 800) (0, 0)) white $ tree1 . (* 60)\n\n\n--animated tree\ntree2 t = fractal 8 branches $ Line [(0,0),(0,100)]\n  where branches = [ Translate 0 100 . Scale 0.75 0.75 . Rotate t\n                   , Translate 0 100 . Scale 0.6 0.6 . Rotate 0\n                   , Translate 0 100 . Scale 0.5 0.5 . Rotate (-2*t) ]\n\n--animated fractal clock\ncircles t = fractal 10 model $ Circle 100\n  where model = [ Translate 0 50 . Scale 0.5 0.5 . Rotate t\n                , Translate 0 (-50) . Scale 0.5 0.5 . Rotate (-2*t) ]\n\n--Pythagoras tree\npithagor _ = fractal 10 model $ rectangleWire 100 100\n  where model = [ Translate 50 100 . Scale s s . Rotate 45\n                , Translate (-50) 100 . Scale s s . Rotate (-45)]\n        s = 1\/sqrt 2\n\n--Sierpinski pentagon\npentaflake _ = fractal 5 model $ pentagon\n  where model =  map copy [0,72..288]\n        copy a = Scale s s . Rotate a . Translate 0 x\n        pentagon = Line [ (sin a, cos a) | a <- [0,2*pi\/5..2*pi] ]\n        x = 2*cos(pi\/5)\n        s = 1\/(1+x)\n\n\nLibrary: HGL\nimport Graphics.HGL.Window\nimport Graphics.HGL.Run\nimport Control.Arrow\nimport Control.Monad\nimport Data.List\n\nenumBase :: Int -> Int -> [[Int]]\nenumBase n = mapM (enumFromTo 0). replicate n. pred\n\npsPlus (a,b) (p,q) = (a+p, b+q)\n\ntoInt :: Double -> Int\ntoInt = fromIntegral.round\n\nintPoint = toInt *** toInt\n  \npts n = \n  map (map (intPoint.psPlus (100,0)). ((0,300):). scanl1 psPlus. ((r,300):). zipWith (\\h a -> (h*cos a, h*sin a)) rs) hs\n  where\n    [r,h,sr,sh] = [50, pi\/5, 0.9, 0.75]\n    rs   = take n $ map (r*) $ iterate(*sr) sr\n    lhs  = map (map (((-1)**).fromIntegral)) $ enumBase n 2\n    rhs  = take n $ map (h*) $ iterate(*sh) 1\n    hs   = map (scanl1 (+). zipWith (*)rhs) lhs\n\nfractalTree :: Int -> IO ()\nfractalTree n =\n   runWindow \"Fractal Tree\" (500,600)\n    (\\w -> setGraphic w (overGraphics ( map polyline $ pts (n-1))) >> getKey w)\n\nmain = fractalTree 10\n\n","human_summarization":"generates a fractal tree by drawing a trunk and then recursively drawing branches at the end of each branch, splitting at a certain angle until a specified level of branching is reached. The code allows for customization of the fractal geometric structures. It also provides an alternative solution using the J contribution method.","id":4249}
    {"lang_cluster":"Haskell","source_code":"\n\nimport HFM.Primes (primePowerFactors)\nimport Control.Monad (mapM)\nimport Data.List (product)\n\n-- primePowerFactors\u00a0:: Integer -> [(Integer,Int)]\n\nfactors = map product .\n          mapM (\\(p,m)-> [p^i | i<-[0..m]]) . primePowerFactors\n\n\n~> factors 42\n[1,7,3,21,2,14,6,42]\n\n\nimport Data.List (group)\nprimePowerFactors = map (\\x-> (head x, length x)) . group . factorize\n\n\nintegerFactors :: Int -> [Int]\nintegerFactors n\n  | 1 > n = []\n  | otherwise = lows <> (quot n <$> part n (reverse lows))\n  where\n    part n\n      | n == square = tail\n      | otherwise = id\n    (square, lows) =\n      (,) . (^ 2)\n        <*> (filter ((0 ==) . rem n) . enumFromTo 1)\n        $ floor (sqrt $ fromIntegral n)\n\nmain :: IO ()\nmain = print $ integerFactors 600\n\n\n","human_summarization":"compute the factors of a positive integer. It uses D. Amos'es Primes module to find prime factors and can also derive cofactors from factors up to the square root. The factors are returned out of order. The code also includes a version that doesn't require sorting and is productive immediately. It doesn't handle the cases of zero or negative integers. It's best suited for numbers of up to 50-60 digits.","id":4250}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List (unfoldr, transpose)\nimport Control.Arrow (second)\n\ndat =\n  \"Given$a$text$file$of$many$lines,$where$fields$within$a$line$\\n\" ++\n  \"are$delineated$by$a$single$'dollar'$character,$write$a$program\\n\" ++\n  \"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\\n\" ++\n  \"column$are$separated$by$at$least$one$space.\\n\" ++\n  \"Further,$allow$for$each$word$in$a$column$to$be$either$left$\\n\" ++\n  \"justified,$right$justified,$or$center$justified$within$its$column.\\n\"\n\nbrkdwn =\n  takeWhile (not . null) . unfoldr (Just . second (drop 1) . span ('$' \/=))\n\nformat j ls = map (unwords . zipWith align colw) rows\n  where\n    rows = map brkdwn $ lines ls\n    colw = map (maximum . map length) . transpose $ rows\n    align cw w =\n      case j of\n        'c' -> replicate l ' ' ++ w ++ replicate r ' '\n        'r' -> replicate dl ' ' ++ w\n        'l' -> w ++ replicate dl ' '\n      where\n        dl = cw - length w\n        (l, r) = (dl `div` 2, dl - l)\n\n\n","human_summarization":"The code reads a text file where fields within a line are separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. The words in a column can be left justified, right justified, or center justified. The code handles trailing dollar characters, aligns all columns similarly, ignores consecutive spaces at the end of lines, views output text in a mono-spaced font on a plain text editor or basic terminal, calculates minimum space between columns from the text, and does not require adding separating characters between or around columns.","id":4251}
    {"lang_cluster":"Haskell","source_code":"\nimport Graphics.Rendering.OpenGL\nimport Graphics.UI.GLUT\n\n-- Draw a cuboid.  Its vertices are those of a unit cube, which is then scaled\n-- to the required dimensions.  We only specify the visible faces, each of\n-- which is composed of two triangles.  The faces are rotated into position and\n-- rendered with a perspective transformation.\n\ntype Fl = GLfloat\n\ncuboid :: IO ()\ncuboid = do\n  color red   ; render front  \n  color green ; render side\n  color blue  ; render top\n\nred,green,blue :: Color4 GLfloat\nred   = Color4 1 0 0 1\ngreen = Color4 0 1 0 1\nblue  = Color4 0 0 1 1\n\nrender :: [(Fl, Fl, Fl)] -> IO ()\nrender = renderPrimitive TriangleStrip . mapM_ toVertex\n  where toVertex (x,y,z) = vertex $ Vertex3 x y z\n\nfront,side,top :: [(Fl,Fl,Fl)]\nfront = vertices [0,1,2,3]\nside  = vertices [4,1,5,3]\ntop   = vertices [3,2,5,6]\n\nvertices :: [Int] -> [(Fl,Fl,Fl)]\nvertices = map (verts !!)\n\nverts :: [(Fl,Fl,Fl)]\nverts = [(0,0,1), (1,0,1), (0,1,1), (1,1,1), (1,0,0), (1,1,0), (0,1,0)]\n\ntransform :: IO ()\ntransform = do\n  translate $ Vector3 0 0 (-10 :: Fl)\n  rotate (-14) $ Vector3 0 0 (1 :: Fl)\n  rotate (-30) $ Vector3 0 1 (0 :: Fl)\n  rotate   25  $ Vector3 1 0 (0 :: Fl)\n  scale 2 3 (4 :: Fl)\n  translate $ Vector3 (-0.5) (-0.5) (-0.5 :: Fl)\n\ndisplay :: IO ()\ndisplay = do\n  clear [ColorBuffer]\n  perspective 40 1 1 (15 :: GLdouble)\n  transform\n  cuboid\n  flush\n\nmain :: IO ()\nmain = do\n  let name = \"Cuboid\"\n  initialize name []\n  createWindow name\n  displayCallback $= display\n  mainLoop\n\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, showing at least three visible faces, with either static or rotational projection.","id":4252}
    {"lang_cluster":"Haskell","source_code":"\n\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main (main) where\n\nimport           Data.Foldable (for_)\nimport qualified Data.Text.Encoding as Text (encodeUtf8)\nimport           Ldap.Client (Attr(..), Filter(..))\nimport qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly)\n\nmain :: IO ()\nmain = do\n    entries <- Ldap.with (Ldap.Plain \"localhost\") 389 $ \\ldap ->\n        Ldap.search ldap (Ldap.Dn \"o=example.com\") (Ldap.typesOnly True) (Attr \"uid\" := Text.encodeUtf8 \"user\") []\n    for_ entries $ \\entry ->\n        print entry\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server using the ldap-client package.","id":4253}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.Char (chr, isAlpha, ord, toLower)\nimport Data.Bool (bool)\n\nrot13 :: Char -> Char\nrot13 c\n  | isAlpha c = chr $ bool (-) (+) ('m' >= toLower c) (ord c) 13\n  | otherwise = c\n\n-- Simple test\nmain :: IO ()\nmain = print $ rot13 <$> \"Abjurer nowhere\"\n\n\nimport Data.Char (chr, isAlpha, ord, toLower)\nimport Data.Bool (bool)\n\nrot13 :: Char -> Char\nrot13 =\n  let rot = flip ((bool (-) (+) . ('m' >=) . toLower) <*> ord)\n  in (bool <*> chr . rot 13) <*> isAlpha\n\n-- Simple test\nmain :: IO ()\nmain = print $ rot13 <$> \"Abjurer nowhere\"\n\n\n","human_summarization":"The code implements a rot-13 function that encodes every line of input from a file or standard input. It also wraps this function in a utility program similar to a common UNIX utility. The rot-13 encoding replaces every ASCII alphabet letter with the letter rotated 13 characters around the 26 letter alphabet. The code maintains the case of the letters and passes all non-alphabetic characters without alteration. The code also includes a framework to wrap the rot13 function as a utility program, which reads the file lazily, providing buffering.","id":4254}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List\nimport Data.Function (on)\n\ndata Person =\n  P String\n    Int\n  deriving (Eq)\n\ninstance Show Person where\n  show (P name val) = \"Person \" ++ name ++ \" with value \" ++ show val\n\ninstance Ord Person where\n  compare (P a _) (P b _) = compare a b\n\npVal :: Person -> Int\npVal (P _ x) = x\n\npeople :: [Person]\npeople = [P \"Joe\" 12, P \"Bob\" 8, P \"Alice\" 9, P \"Harry\" 2]\n\n\nmain :: IO ()\nmain = do\n  mapM_ print $ sort people\n  putStrLn []\n  mapM_ print $ sortBy (on compare pVal) people\n\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator. It also includes a general function, sortBy, that sorts a list based on a provided comparison function.","id":4255}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad\n\nmain = do\n  forM_ [1..5] $ \\i -> do\n    forM_ [1..i] $ \\j -> do\n      putChar '*'\n    putChar '\\n'\n\n\nimport Data.List (inits)\n\nmain = mapM_ putStrLn $ tail $ inits $ replicate 5 '*'\n\n\nputStrLn $ unlines [replicate n '*' | n <- [1..5]]\n\n\nputStrLn . unlines . take 5 $ iterate ('*':) \"*\"\n\n","human_summarization":"The code demonstrates the use of nested for loops. The outer loop controls the number of iterations performed by the inner loop, which in turn prints out a pattern of asterisks. The pattern starts with a single asterisk and increases by one each line. The code also includes alternative Haskell solutions using list comprehension and an infinite stream of increasing length lines.","id":4256}
    {"lang_cluster":"Haskell","source_code":"\n\nWorks with: GHC\nimport Data.Map\n\ndict = fromList [(\"key1\",\"val1\"), (\"key2\",\"val2\")]\n\nans = Data.Map.lookup \"key2\" dict  -- evaluates to Just \"val2\"\n\n\ndict = [(\"key1\",\"val1\"), (\"key2\",\"val2\")]\n\nans = lookup \"key2\" dict  -- evaluates to Just \"val2\"\n\n\n","human_summarization":"The code creates an associative array, also known as a dictionary, map, or hash. It also demonstrates the use of association lists, which are simple but inefficient due to their O(n) lookup. The code also references the Data.HashTable module, which was removed in GHC 7.8, and other standard associative arrays libraries like Data.IntMap and Data.HasMap.","id":4257}
    {"lang_cluster":"Haskell","source_code":"\nbsd = tail . iterate (\\n -> (n * 1103515245 + 12345) `mod` 2^31)\nmsr = map (`div` 2^16) . tail . iterate (\\n -> (214013 * n + 2531011) `mod` 2^31)\n\nmain = do\n\tprint $ take 10 $ bsd 0 -- can take seeds other than 0, of course\n\tprint $ take 10 $ msr 0\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":4258}
    {"lang_cluster":"Haskell","source_code":"\n\ninsertAfter a b (c:cs) | a==c = a : b : cs\n                       | otherwise = c : insertAfter a b cs\ninsertAfter _ _ [] = error \"Can't insert\"\n\n","human_summarization":"define a method to insert an element into a singly-linked list after a specified element. The method is then used to insert element C into a list of elements A->B, after element A.","id":4259}
    {"lang_cluster":"Haskell","source_code":"\nimport Prelude hiding (odd)\nimport Control.Monad (join)\n\nhalve :: Int -> Int\nhalve = (`div` 2)\n\ndouble :: Int -> Int\ndouble = join (+)\n\nodd :: Int -> Bool\nodd = (== 1) . (`mod` 2)\n\nethiopicmult :: Int -> Int -> Int\nethiopicmult a b =\n  sum $\n  map snd $\n  filter (odd . fst) $\n  zip (takeWhile (>= 1) $ iterate halve a) (iterate double b)\n\nmain :: IO ()\nmain = print $ ethiopicmult 17 34 == 17 * 34\n\n\n","human_summarization":"The code defines three functions to halve an integer, double an integer, and check if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using only addition, doubling, and halving. The multiplication process involves repeatedly halving the first number and doubling the second number, discarding rows where the first number is even, and summing the remaining values in the second column. The code can also replicate a string n times or raise an integer to the nth power using Ethiopian multiplication.","id":4260}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List\nimport Data.Ratio\nimport Control.Monad\nimport System.Environment (getArgs)\n\ndata Expr = Constant Rational |\n    Expr :+ Expr | Expr :- Expr |\n    Expr :* Expr | Expr :\/ Expr\n    deriving (Eq)\n\nops = [(:+), (:-), (:*), (:\/)]\n\ninstance Show Expr where\n    show (Constant x) = show $ numerator x\n      -- In this program, we need only print integers.\n    show (a :+ b)     = strexp \"+\" a b\n    show (a :- b)     = strexp \"-\" a b\n    show (a :* b)     = strexp \"*\" a b\n    show (a :\/ b)     = strexp \"\/\" a b\n\nstrexp :: String -> Expr -> Expr -> String\nstrexp op a b = \"(\" ++ show a ++ \" \" ++ op ++ \" \" ++ show b ++ \")\"\n\ntemplates :: [[Expr] -> Expr]\ntemplates = do\n    op1 <- ops\n    op2 <- ops\n    op3 <- ops\n    [\\[a, b, c, d] -> op1 a $ op2 b $ op3 c d,\n     \\[a, b, c, d] -> op1 (op2 a b) $ op3 c d,\n     \\[a, b, c, d] -> op1 a $ op2 (op3 b c) d,\n     \\[a, b, c, d] -> op1 (op2 a $ op3 b c) d,\n     \\[a, b, c, d] -> op1 (op2 (op3 a b) c) d]\n\neval :: Expr -> Maybe Rational\neval (Constant c) = Just c\neval (a :+ b)     = liftM2 (+) (eval a) (eval b)\neval (a :- b)     = liftM2 (-) (eval a) (eval b)\neval (a :* b)     = liftM2 (*) (eval a) (eval b)\neval (a :\/ b)     = do\n    denom <- eval b\n    guard $ denom \/= 0\n    liftM (\/ denom) $ eval a\n\nsolve :: Rational -> [Rational] -> [Expr]\nsolve target r4 = filter (maybe False (== target) . eval) $\n    liftM2 ($) templates $\n    nub $ permutations $ map Constant r4 \n\nmain = getArgs >>= mapM_ print . solve 24 . map (toEnum . read)\n\n\n$ runghc 24Player.hs 2 3 8 9\n(8 * (9 - (3 * 2)))\n(8 * (9 - (2 * 3)))\n((9 - (2 * 3)) * 8)\n((9 - (3 * 2)) * 8)\n((9 - 3) * (8 \/ 2))\n((8 \/ 2) * (9 - 3))\n(8 * ((9 - 3) \/ 2))\n(((9 - 3) \/ 2) * 8)\n((9 - 3) \/ (2 \/ 8))\n((8 * (9 - 3)) \/ 2)\n(((9 - 3) * 8) \/ 2)\n(8 \/ (2 \/ (9 - 3)))\nimport Control.Applicative\nimport Data.List\nimport Text.PrettyPrint\n\n\ndata Expr = C Int | Op String Expr Expr\n\ntoDoc (C     x  ) = int x\ntoDoc (Op op x y) = parens $ toDoc x <+> text op <+> toDoc y\n\nops :: [(String, Int -> Int -> Int)]\nops = [(\"+\",(+)), (\"-\",(-)), (\"*\",(*)), (\"\/\",div)]\n\n\nsolve :: Int -> [Int] -> [Expr]\nsolve res = filter ((Just res ==) . eval) . genAst\n  where\n    genAst [x] = [C x]\n    genAst xs  = do\n      (ys,zs) <- split xs\n      let f (Op op _ _) = op `notElem` [\"+\",\"*\"] || ys <= zs\n      filter f $ Op <$> map fst ops <*> genAst ys <*> genAst zs\n\n    eval (C      x  ) = Just x\n    eval (Op \"\/\" _ y) | Just 0 <- eval y = Nothing\n    eval (Op op  x y) = lookup op ops <*> eval x <*> eval y\n\n\nselect :: Int -> [Int] -> [[Int]]\nselect 0 _  = [[]]\nselect n xs = [x:zs | k <- [0..length xs - n]\n                    , let (x:ys) = drop k xs\n                    , zs <- select (n - 1) ys\n                    ]\n\nsplit :: [Int] -> [([Int],[Int])]\nsplit xs = [(ys, xs \\\\ ys) | n <- [1..length xs - 1]\n                           , ys <- nub . sort $ select n xs\n                           ]\n\n                           \nmain = mapM_ (putStrLn . render . toDoc) $ solve 24 [2,3,8,9]\n\n\n","human_summarization":"The code takes four digits as input, either provided by the user or generated randomly, and calculates arithmetic expressions based on the rules of the 24 game. It also displays examples of the solutions it generates.","id":4261}
    {"lang_cluster":"Haskell","source_code":"\n\nfactorial n = product [1..n]\n\nfactorial = product . enumFromTo 1\n\nfactorial n = foldl (*) 1 [1..n]\n\nfactorials = scanl (*) 1 [1..]\n\nfactorial\u00a0:: Integral -> Integral\nfactorial 0 = 1\nfactorial n = n * factorial (n-1)\n\nfac n\n    | n >= 0    = go 1 n\n    | otherwise = error \"Negative factorial!\"\n        where go acc 0 = acc\n              go acc n = go (acc * n) (n - 1)\n\n{-# LANGUAGE PostfixOperators #-}\n\n(!)\u00a0:: Integer -> Integer\n(!) 0 = 1\n(!) n = n * (pred n\u00a0!)\n\nmain\u00a0:: IO ()\nmain = do\n  print (5\u00a0!)\n  print ((4\u00a0!)\u00a0!)\n\n\n-- product of [a,a+1..b]\nproductFromTo a b = \n  if a>b then 1 \n  else if a == b then a \n  else productFromTo a c * productFromTo (c+1) b \n  where c = (a+b) `div` 2\n\nfactorial = productFromTo 1\n","human_summarization":"implement a function to calculate the factorial of a number. This function can be either iterative or recursive. It optionally handles negative number errors. The factorial is the product of all positive integers from 1 to the given number. The code may also include a more efficient method for large numbers.","id":4262}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List (partition, intersect, nub)\nimport Control.Monad\nimport System.Random (StdGen, getStdRandom, randomR)\nimport Text.Printf\n\nnumberOfDigits = 4 :: Int\n\nmain = bullsAndCows\n\nbullsAndCows :: IO ()\nbullsAndCows = do\n    digits <- getStdRandom $ pick numberOfDigits ['1' .. '9']\n    putStrLn \"Guess away!\"\n    loop digits\n\n  where loop digits = do\n            input <- getLine\n            if okay input\n              then\n                  let (bulls, cows) = score digits input in\n                  if bulls == numberOfDigits then\n                      putStrLn \"You win!\"\n                  else do\n                      printf \"%d bulls, %d cows.\\n\" bulls cows\n                      loop digits\n              else do\n                  putStrLn \"Malformed guess; try again.\"\n                  loop digits\n\n        okay :: String -> Bool\n        okay input =\n            length input == numberOfDigits && \n            input == nub input &&\n            all legalchar input\n          where legalchar c = '1' <= c && c <= '9'\n\n        score :: String -> String -> (Int, Int)\n        score secret guess = (length bulls, cows)\n          where (bulls, nonbulls) = partition (uncurry (==)) $\n                    zip secret guess\n                cows = length $ uncurry intersect $ unzip nonbulls\n\npick :: Int -> [a] -> StdGen -> ([a], StdGen)\n{- Randomly selects items from a list without replacement. -}\npick n l g = f n l g (length l - 1) []\n  where  f 0 _ g _   ps = (ps, g)\n         f n l g max ps =\n             f (n - 1) (left ++ right) g' (max - 1) (picked : ps)\n          where (i, g') = randomR (0, max) g\n                (left, picked : right) = splitAt i l\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":4263}
    {"lang_cluster":"Haskell","source_code":"\nimport System.Random\n\npairs :: [a] -> [(a,a)]\npairs (x:y:zs) = (x,y):pairs zs\npairs _        = []\n\ngauss mu sigma (r1,r2) = \n  mu + sigma * sqrt (-2 * log r1) * cos (2 * pi * r2)\n\ngaussians :: (RandomGen g, Random a, Floating a) => Int -> g -> [a]\ngaussians n g = take n $ map (gauss 1.0 0.5) $ pairs $ randoms g\n\nresult :: IO [Double]\nresult = getStdGen >>= \\g -> return $ gaussians 1000 g\n\n\nreplicateM 1000 $ normal 1 0.5\n\n\nimport  Data.Random\nimport Control.Monad\n\nthousandRandomNumbers :: RVar [Double]\nthousandRandomNumbers =  replicateM 1000 $ normal 1 0.5\n\nmain = do\n   x <- sample thousandRandomNumbers\n   print x\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using either built-in libraries or the Data.Random from the random-fu package. The numbers are then printed.","id":4264}
    {"lang_cluster":"Haskell","source_code":"\ndotp :: Num a => [a] -> [a] -> a \ndotp a b | length a == length b = sum (zipWith (*) a b)\n         | otherwise = error \"Vector sizes must match\"\n \nmain = print $ dotp [1, 3, -5] [4, -2, -1] -- prints 3\n\n\ndotProduct :: Num a => [a] -> [a] -> Maybe a\ndotProduct a b \n  | length a == length b = Just $ dp a b\n  | otherwise = Nothing\n    where\n      dp x y = sum $ zipWith (*) x y\n\n\nmain :: IO ()\nmain = print n\n  where\n    Just n = dotProduct [1, 3, -5] [4, -2, -1]\n\n","human_summarization":"\"Implements a function to compute the dot product of two vectors of the same length, by multiplying corresponding terms from each vector and summing the products. The function can handle vectors of arbitrary length and uses the Maybe monad to avoid exceptions and ensure composability.\"","id":4265}
    {"lang_cluster":"Haskell","source_code":"\n\nimport System.IO\n\nreadLines :: Handle -> IO [String]\nreadLines h = do\n  s <- hGetContents h\n  return $ lines s\n\nreadWords :: Handle -> IO [String]\nreadWords h = do\n  s <- hGetContents h\n  return $ words s\n\n","human_summarization":"read a text stream either word-by-word or line-by-line until there's no more data. It uses standard functions to convert the file contents into lists of lines or words.","id":4266}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List\nimport Text.XML.Light\n\nxmlDOM :: String -> String\nxmlDOM txt = showTopElement $ Element\n    (unqual \"root\")\n    []\n    [ Elem $ Element\n      (unqual \"element\")\n      []\n      [Text $ CData CDataText txt Nothing]\n      Nothing\n    ]\n    Nothing\n\n\n*Main> mapM_ (putStrLn.ppContent) $ parseXML (xmlDOM \"  Some text  \")\n<?xml version=\"1.0\"\u00a0?>\n<root>\n  <element>  Some text  <\/element>\n<\/root>\n","human_summarization":"Create a simple DOM and serialize it into XML format using the XML.Light module from HackageDB. The XML output includes a root element containing a child element with some text.","id":4267}
    {"lang_cluster":"Haskell","source_code":"\nimport System.Time\n       (getClockTime, toCalendarTime, formatCalendarTime)\n\nimport System.Locale (defaultTimeLocale)\n\nmain :: IO ()\nmain = do\n  ct <- getClockTime\n  print ct -- print default format, or\n  cal <- toCalendarTime ct\n  putStrLn $ formatCalendarTime defaultTimeLocale \"%a %b %e %H:%M:%S %Y\" cal\n\n\nimport Data.Time (getZonedTime, formatTime, defaultTimeLocale)\n\nmain :: IO ()\nmain = do\n  zt <- getZonedTime\n  print zt -- print default format, or\n  putStrLn $ formatTime defaultTimeLocale \"%a %b %e %H:%M:%S %Y\" zt\n\n","human_summarization":"the system time, which can be used for debugging, network information, random number seeds, or program performance. The time is outputted either by a system command or a built-in language function. The units of time are also noted. The code is related to the task of date formatting and uses the time library.","id":4268}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Char (isAsciiUpper, isDigit, ord)\n\n-------------------------- SEDOLS ------------------------\n\ncheckSum :: String -> String\ncheckSum x =\n  case traverse sedolValue x of\n    Right xs -> (show . checkSumFromSedolValues) xs\n    Left annotated -> annotated\n\ncheckSumFromSedolValues :: [Int] -> Int\ncheckSumFromSedolValues xs =\n  rem\n    ( 10\n        - rem\n          ( sum $\n              zipWith\n                (*)\n                [1, 3, 1, 7, 3, 9]\n                xs\n          )\n          10\n    )\n    10\n\nsedolValue :: Char -> Either String Int\nsedolValue c\n  | c `elem` \"AEIOU\" = Left \" \u2190 Unexpected vowel.\"\n  | isDigit c = Right (ord c - ord '0')\n  | isAsciiUpper c = Right (ord c - ord 'A' + 10)\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n  mapM_\n    (putStrLn . ((<>) <*> checkSum))\n    [ \"710889\",\n      \"B0YBKJ\",\n      \"406566\",\n      \"B0YBLH\",\n      \"228276\",\n      \"B0YBKL\",\n      \"557910\",\n      \"B0YBKR\",\n      \"585284\",\n      \"B0YBKT\",\n      \"BOYBKT\", -- Ill formed test case - illegal vowel.\n      \"B00030\"\n    ]\n\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":4269}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Graphics.Rendering.OpenGL.GL\nimport Graphics.UI.GLUT.Objects\nimport Graphics.UI.GLUT\n\nsetProjection :: IO ()\nsetProjection = do\n  matrixMode $= Projection\n  ortho (-1) 1 (-1) 1 0 (-1)\n         \ngrey1,grey9,red,white :: Color4 GLfloat\ngrey1 = Color4 0.1 0.1 0.1 1\ngrey9 = Color4 0.9 0.9 0.9 1\nred   = Color4 1   0   0   1\nwhite = Color4 1   1   1   1\n\nsetLights :: IO ()\nsetLights = do\n  let l = Light 0\n  ambient  l $= grey1\n  diffuse  l $= white\n  specular l $= white\n  position l $= Vertex4 (-4) 4 3 (0 :: GLfloat)\n  light    l $= Enabled\n  lighting   $= Enabled\n\nsetMaterial :: IO ()\nsetMaterial = do\n  materialAmbient   Front $= grey1\n  materialDiffuse   Front $= red\n  materialSpecular  Front $= grey9\n  materialShininess Front $= (32 :: GLfloat)\n\ndisplay :: IO()\ndisplay = do\n  clear [ColorBuffer]\n  renderObject Solid $ Sphere' 0.8 64 64\n  swapBuffers\n\nmain :: IO()\nmain = do\n  _ <- getArgsAndInitialize\n  _ <- createWindow \"Sphere\"\n  clearColor $= Color4 0.0 0.0 0.0 0.0\n  setProjection\n  setLights\n  setMaterial\n  displayCallback $= display\n  mainLoop\nimport Data.List (genericLength)\n\nshades = \".:!*oe%#&@\"\nn = genericLength shades\ndot a b = sum $ zipWith (*) a b\nnormalize x = (\/ sqrt (x `dot` x)) <$> x\n\nsphere r k amb light = unlines $\n  [ [ if x*x + y*y <= r*r\n      then let vec = normalize [x, y, sqrt (r*r-x*x-y*y)]\n               b = (light `dot` vec) ** k + amb\n               intensity = (1 - b)*(n - 1)\n           in shades !! round ((0 `max` intensity) `min` n)\n      else ' '\n    | y <- map (\/2.12) [- 2*r - 0.5 .. 2*r + 0.5]  ]\n  | x <- [ - r - 0.5 .. r + 0.5] ]\n\n\u03bb> putStrLn $ sphere 10 4 0.1 (normalize [30,30,-50])\n                                          \n              #%%%%%%%####&&              \n          eoo*****oooee%%%###&&&          \n       eo*!!::::!!!**ooee%%%###&&&&       \n     e*!::......::!!**ooee%%####&&&&&     \n   %o!::.........::!!**ooee%%###&&&&&&&   \n  eo!::..........::!!**ooee%%###&&&&&&&&  \n %o*!:..........::!!**ooee%%%###&&&&&&&&& \n#eo*!::.......:::!!**ooeee%%####&&&&&&&&&&\n%eo*!!:::::::::!!***ooeee%%####&&&&&&&&&&&\n%eeo**!!!!!!!!****ooeee%%%####&&&&&&&&&&&&\n#%eeooo*******ooooeee%%%%####&&&&&&&&&&&&&\n##%%eeeoooooooeeeee%%%%####&&&&&&&&&&&&&&&\n&###%%%%eeeeee%%%%%%######&&&&&&&&&&&&&&&#\n &&####%%%%%%%%########&&&&&&&&&&&&&&&&&& \n  &&&##############&&&&&&&&&&&&&&&&&&&&&  \n   &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#   \n     &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&     \n       &&&&&&&&&&&&&&&&&&&&&&&&&&&&       \n          &&&&&&&&&&&&&&&&&&&&&&          \n              &&&&&&&&&&&&&#              \n                                          \n\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":4270}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Array\n\nordSuffs :: Array Integer String\nordSuffs = listArray (0,9) [\"th\", \"st\", \"nd\", \"rd\", \"th\",\n                            \"th\", \"th\", \"th\", \"th\", \"th\"]\n\nordSuff :: Integer -> String\nordSuff n = show n ++ suff n\n  where suff m | (m `rem` 100) >= 11 && (m `rem` 100) <= 13 = \"th\"\n               | otherwise          = ordSuffs ! (m `rem` 10)\n\nprintOrdSuffs :: [Integer] -> IO ()\nprintOrdSuffs = putStrLn . unwords . map ordSuff\n\nmain :: IO ()\nmain = do\n  printOrdSuffs [   0..  25]\n  printOrdSuffs [ 250.. 265]\n  printOrdSuffs [1000..1025]\n\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":4271}
    {"lang_cluster":"Haskell","source_code":"\n\nstripChars :: String -> String -> String\nstripChars = filter . flip notElem\n\n\nTesting in GHCI:\n> stripChars \"aei\" \"She was a soul stripper. She took my heart!\"\n\"Sh ws  soul strppr. Sh took my hrt!\"\n","human_summarization":"The code defines a function that takes two strings as input, strips the characters from the first string that are present in the second string, and returns the modified string. The function is designed to be partially applied with the characters to be stripped.","id":4272}
    {"lang_cluster":"Haskell","source_code":"\nfizz :: (Integral a, Show a) => a -> [(a, String)] -> String\nfizz a xs\n    | null result = show a\n    | otherwise   = result\n    where result = concatMap (fizz' a) xs\n          fizz' a (factor, str)\n              | a `mod` factor == 0 = str\n              | otherwise           = \"\"\n\nmain = do\n    line <- getLine\n    let n = read line\n    contents <- getContents\n    let multiples = map (convert . words) $ lines contents\n    mapM_ (\\ x -> putStrLn $ fizz x multiples) [1..n]\n    where convert [x, y] = (read x, y)\n\n\ntype Rule = (Int, String)\n\n----------------- FIZZETC (USING RULE SET) ---------------\n\nfizzEtc :: [(Int, String)] -> [String]\nfizzEtc rules = foldr nextLine [] [1 ..]\n  where\n    nextLine x a\n      | null noise = show x : a\n      | otherwise = noise : a\n      where\n        noise = foldl reWrite [] rules\n        reWrite s (m, k)\n          | 0 == rem x m = s <> k\n          | otherwise = s\n\n\n------------------- TEST OF SAMPLE RULES -----------------\nfizzTest :: [String]\nfizzTest = fizzEtc [(3, \"Fizz\"), (5, \"Buzz\"), (7, \"Baxx\")]\n\nmain :: IO ()\nmain = mapM_ putStrLn $ take 20 fizzTest\n\n\n","human_summarization":"is a generalized FizzBuzz program that accepts a maximum number and a list of factors with their corresponding words from the user. It prints numbers from 1 to the maximum number, replacing multiples of the given factors with their associated words. If a number is a multiple of more than one factor, it prints all the corresponding words in ascending order of their factors.","id":4273}
    {"lang_cluster":"Haskell","source_code":"\nPrelude> let f = (++\" World!\")\nPrelude> f \"Hello\"\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":4274}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List\nimport Graphics.Gnuplot.Simple\n\n-- diamonds\n-- pl = [[0,1],[1,0]]\n\npl = [[0,0],[0,1]]\nr_90 = [[0,1],[-1,0]]\n\nip :: [Int] -> [Int] -> Int\nip xs = sum . zipWith (*) xs\nmatmul xss yss = map (\\xs -> map (ip xs ). transpose $ yss) xss\n\nvmoot xs = (xs++).map (zipWith (+) lxs). flip matmul r_90.\n          map (flip (zipWith (-)) lxs) .reverse . init $ xs\n   where lxs = last xs\n\ndragoncurve = iterate vmoot pl\n\n\nplotPath [] . map (\\[x,y] -> (x,y)) $ dragoncurve!!13\n\n\nx 0 = \"\"\nx n = (x$n-1)++\" +\"++(y$n-1)++\" f +\"\ny 0 = \"\"\ny n = \" - f\"++(x$n-1)++\" -\"++(y$n-1)\n\ndragon n =\n\tconcat [\"0 setlinewidth 300 400 moveto\",\n\t\t\"\/f{2 0 rlineto}def\/+{90 rotate}def\/-{-90 rotate}def\\n\",\n\t\t\"f\", x n, \" stroke showpage\"]\n\nmain = putStrLn $ dragon 14\n\n","human_summarization":"The code generates a dragon curve fractal, either displaying it directly or writing it to an image file. It uses various algorithms to create the fractal, including recursive and iterative methods, as well as successive approximation and Lindenmayer system of expansions. The code can also calculate the absolute direction and X,Y coordinates of a point, and test whether a given point or segment is on the curve. The curve can be drawn to a desired expansion level and the curl direction can be a parameter. The code uses the gnuplot interface module for plotting and can output a postscript.","id":4275}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad\nimport System.Random\n\n-- Repeat the action until the predicate is true.\nuntil_ act pred = act >>= pred >>= flip unless (until_ act pred)\n\nanswerIs ans guess \n    | ans == guess = putStrLn \"You got it!\" >> return True\n    | otherwise = putStrLn \"Nope. Guess again.\" >> return False\n\nask = liftM read getLine\n\nmain = do\n  ans <- randomRIO (1,10) :: IO Int\n  putStrLn \"Try to guess my secret number between 1 and 10.\"\n  ask `until_` answerIs ans\n\n\nimport System.Random\n\nmain = randomRIO (1,10) >>= gameloop\n\ngameloop :: Int -> IO ()\ngameloop r = do\t\n\ti <- fmap read getLine\n\tif i == r \n\t  then putStrLn \"You got it!\"\n\t  else putStrLn \"Nope. Guess again.\" >> gameloop r\n\n","human_summarization":"generate a random number between 1 and 10, prompt the user to guess the number, and continue prompting until the correct number is guessed, at which point a \"Well guessed!\" message is displayed and the program exits. A conditional loop is used to repeat the guessing process.","id":4276}
    {"lang_cluster":"Haskell","source_code":"\nlower = ['a' .. 'z']\n\nmain = print lower\n\n\nalpha :: String\nalpha = enumFromTo 'a' 'z'\n\nmain :: IO ()\nmain = print alpha\n\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z, using a reliable and strong typing coding style if available, to avoid manual enumeration which can be bug prone.","id":4277}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List\nimport Numeric\nimport Text.Printf\n\n-- Use the built-in function showBin.\ntoBin n = showBin n \"\"\n\n-- Use the built-in function showIntAtBase.\ntoBin n = showIntAtBase 2 (\"01\" !!) n \"\"\n\n-- Implement our own version.\ntoBin1 0 = []\ntoBin1 x =  (toBin1 $ x `div` 2) ++ (show $ x `mod` 2)\n\n-- Or even more efficient (due to fusion) and universal implementation\ntoBin2 = foldMap show . reverse . toBase 2\n\ntoBase base = unfoldr modDiv\n  where modDiv 0 = Nothing\n        modDiv n = let (q, r) = (n `divMod` base) in Just (r, q) \n\n\nprintToBin n = putStrLn $ printf \"%4d  %14s  %14s\" n (toBin n) (toBin1 n)\n\nmain = do\n  putStrLn $ printf \"%4s  %14s  %14s\" \"N\" \"toBin\" \"toBin1\"\n  mapM_ printToBin [5, 50, 9000]\n\n\n","human_summarization":"The code takes a non-negative integer as input and converts it into its binary equivalent. It uses built-in radix functions or a user-defined function to achieve this. The output is a sequence of binary digits, without any leading zeros, whitespace, radix or sign markers. Each binary sequence is followed by a newline.","id":4278}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List\nimport Data.Maybe\nimport System.IO (readFile)\nimport Text.Read (readMaybe)\nimport Control.Applicative ((<|>))\n\n------------------------------------------------------------\n\nnewtype DB = DB { entries :: [Patient] }\n  deriving Show\n\ninstance Semigroup DB where\n  DB a <> DB b = normalize $ a <> b\n\ninstance Monoid DB where\n  mempty = DB []\n\nnormalize :: [Patient] -> DB\nnormalize = DB\n            . map mconcat \n            . groupBy (\\x y -> pid x == pid y)\n            . sortOn pid\n \n------------------------------------------------------------\n\ndata Patient = Patient { pid :: String\n                       , name :: Maybe String\n                       , visits :: [String]\n                       , scores :: [Float] }\n  deriving Show\n\ninstance Semigroup Patient where\n  Patient p1 n1 v1 s1 <> Patient p2 n2 v2 s2 =\n    Patient (fromJust $ Just p1 <|> Just p2)\n            (n1 <|> n2)\n            (v1 <|> v2)\n            (s1 <|> s2)\n\ninstance Monoid Patient where\n  mempty = Patient mempty mempty mempty mempty\n    \n------------------------------------------------------------\n\nreadDB :: String  -> DB\nreadDB = normalize\n         . mapMaybe readPatient\n         . readCSV\n\nreadPatient r = do\n  i <- lookup \"PATIENT_ID\" r\n  let n = lookup \"LASTNAME\" r\n  let d = lookup \"VISIT_DATE\" r >>= readDate\n  let s = lookup \"SCORE\" r >>= readMaybe\n  return $ Patient i n (maybeToList d) (maybeToList s)\n  where\n    readDate [] = Nothing\n    readDate d = Just d\n\nreadCSV :: String -> [(String, String)]\nreadCSV txt = zip header <$> body\n  where\n    header:body = splitBy ',' <$> lines txt\n    splitBy ch = unfoldr go\n      where\n        go [] = Nothing\n        go s  = Just $ drop 1 <$> span (\/= ch) s\n\nlet patients = readDB <$> readFile \"patients.csv\"\n*Main> let visits = readDB <$> readFile \"visits.csv\" \n\n*Main> mapM_ print . entries =<< patients\nPatient {pid = \"1001\", name = Just \"Hopper\", visits = [], scores = []}\nPatient {pid = \"2002\", name = Just \"Gosling\", visits = [], scores = []}\nPatient {pid = \"3003\", name = Just \"Kemeny\", visits = [], scores = []}\nPatient {pid = \"4004\", name = Just \"Wirth\", visits = [], scores = []}\nPatient {pid = \"5005\", name = Just \"Kurtz\", visits = [], scores = []}\n\n*Main> mapM_ print . entries =<< visits\nPatient {pid = \"1001\", name = Nothing, visits = [\"2020-09-17\",\"2020-11-19\"], scores = [5.3,6.6,5.5]}\nPatient {pid = \"2002\", name = Nothing, visits = [\"2020-09-10\",\"2020-10-08\"], scores = [6.8]}\nPatient {pid = \"3003\", name = Nothing, visits = [\"2020-11-12\"], scores = []}\nPatient {pid = \"4004\", name = Nothing, visits = [\"2020-09-24\",\"2020-11-05\"], scores = [7.0,8.4]}\n\n*Main> mapM_ print . entries =<< patients <> visits\nPatient {pid = \"1001\", name = Just \"Hopper\", visits = [\"2020-09-17\",\"2020-11-19\"], scores = [5.3,6.6,5.5]}\nPatient {pid = \"2002\", name = Just \"Gosling\", visits = [\"2020-09-10\",\"2020-10-08\"], scores = [6.8]}\nPatient {pid = \"3003\", name = Just \"Kemeny\", visits = [\"2020-11-12\"], scores = []}\nPatient {pid = \"4004\", name = Just \"Wirth\", visits = [\"2020-09-24\",\"2020-11-05\"], scores = [7.0,8.4]}\nPatient {pid = \"5005\", name = Just \"Kurtz\", visits = [], scores = []}\ntabulateDB (DB ps) header cols = intercalate \"|\" <$> body\n  where\n    body = transpose $ zipWith pad width table\n    table = transpose $ header : map showPatient ps\n    showPatient p = sequence cols p\n    width = maximum . map length <$> table\n    pad n col = (' ' :) . take (n+1) . (++ repeat ' ') <$> col\n\nmain = do\n  a <- readDB <$> readFile \"patients.csv\"\n  b <- readDB <$> readFile \"visits.csv\"\n  mapM_ putStrLn $ tabulateDB (a <> b) header fields\n  where\n    header = [ \"PATIENT_ID\", \"LASTNAME\", \"VISIT_DATE\"\n             , \"SCORES SUM\",\"SCORES AVG\"]\n    fields = [ pid\n             , fromMaybe [] . name\n             , \\p -> case visits p of {[] -> []; l -> last l}\n             , \\p -> case scores p of {[] -> []; s -> show (sum s)}\n             , \\p -> case scores p of {[] -> []; s -> show (mean s)} ]\n\n    mean lst = sum lst \/ genericLength lst\n\n*Main> main\n PATIENT_ID | LASTNAME | VISIT_DATE | SCORES SUM | SCORES AVG \n 1001       | Hopper   | 2020-11-19 | 17.4       | 5.7999997  \n 2002       | Gosling  | 2020-10-08 | 6.8        | 6.8        \n 3003       | Kemeny   | 2020-11-12 |            |            \n 4004       | Wirth    | 2020-11-05 | 15.4       | 7.7        \n 5005       | Kurtz    |            |            |            \n","human_summarization":"\"Code merges and aggregates two datasets from .csv files, grouping by patient id and last name. It calculates the maximum visit date, and the sum and average of the scores per patient. The resulting dataset can be displayed on the screen or saved to a file.\"","id":4279}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Char\nimport Data.List\nimport Data.List.Split\n\nmain :: IO ()\nmain = readFile \"config\" >>= (print . parseConfig)\n\nparseConfig :: String -> Config\nparseConfig = foldr addConfigValue defaultConfig . clean . lines\n    where clean = filter (not . flip any [\"#\", \";\", \"\", \" \"] . (==) . take 1)\n          \naddConfigValue :: String -> Config -> Config\naddConfigValue raw config = case key of\n    \"fullname\"       -> config {fullName      = values}\n    \"favouritefruit\" -> config {favoriteFruit = values}\n    \"needspeeling\"   -> config {needsPeeling  = True}\n    \"seedsremoved\"   -> config {seedsRemoved  = True}\n    \"otherfamily\"    -> config {otherFamily   = splitOn \",\" values}\n    _                -> config\n    where (k, vs) = span (\/= ' ') raw\n          key = map toLower k\n          values = tail vs\n\ndata Config = Config\n    { fullName      :: String\n    , favoriteFruit :: String\n    , needsPeeling  :: Bool\n    , seedsRemoved  :: Bool\n    , otherFamily   :: [String]\n    } deriving (Show)\n\ndefaultConfig :: Config\ndefaultConfig = Config \"\" \"\" False False []\n\n\nimport Data.ConfigFile\nimport Data.Either.Utils\n\ngetSetting cp x = forceEither $ get cp \"Default\" x\n\ncp <- return . forceEither =<< readfile emptyCP \"name_of_configuration_file\"\nlet username = getSetting cp \"username\"\n    password = getSetting cp \"password\"\n\n\n# this is a comment\nusername  = myname\n\n","human_summarization":"The code reads a standard configuration file, ignores lines beginning with a hash or semicolon, and blank lines. It sets variables based on the configuration parameters, treats configuration option names as case insensitive, but preserves case sensitivity for parameter data. It also allows an optional equals sign to separate parameter data from the option name, and supports multiple parameters separated by commas. The code sets four variables: fullname, favouritefruit, needspeeling, and seedsremoved based on the configuration entries. It also stores multiple parameters in an array or uses Data.Configfile for standard format configuration files.","id":4280}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad (join)\nimport Data.Bifunctor (bimap)\nimport Text.Printf (printf)\n\n-------------------- HAVERSINE FORMULA -------------------\n\n-- The haversine of an angle.\nhaversine :: Float -> Float\nhaversine = (^ 2) . sin . (\/ 2)\n\n-- The approximate distance, in kilometers,\n-- between two points on Earth.\n-- The latitude and longtitude are assumed to be in degrees.\ngreatCircleDistance ::\n  (Float, Float) ->\n  (Float, Float) ->\n  Float\ngreatCircleDistance = distDeg 6371\n  where\n    distDeg radius p1 p2 =\n      distRad\n        radius\n        (deg2rad p1)\n        (deg2rad p2)\n    distRad radius (lat1, lng1) (lat2, lng2) =\n      (2 * radius)\n        * asin\n          ( min\n              1.0\n              ( sqrt $\n                  haversine (lat2 - lat1)\n                    + ( (cos lat1 * cos lat2)\n                          * haversine (lng2 - lng1)\n                      )\n              )\n          )\n    deg2rad = join bimap ((\/ 180) . (pi *))\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n  printf\n    \"The distance between BNA and LAX is about %0.f km.\\n\"\n    (greatCircleDistance bna lax)\n  where\n    bna = (36.12, -86.67)\n    lax = (33.94, -118.40)\n\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":4281}
    {"lang_cluster":"Haskell","source_code":"\nUsing Library: HTTP from HackageDB\nimport Network.Browser\nimport Network.HTTP\nimport Network.URI\n \nmain = do \n    rsp <- Network.Browser.browse $ do\n        setAllowRedirects True\n        setOutHandler $ const (return ())\n        request $ getRequest \"http:\/\/www.rosettacode.org\/\"\n    putStrLn $ rspBody $ snd rsp\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":4282}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Char (digitToInt)\nluhn = (0 ==) . (`mod` 10) . sum . map (uncurry (+) . (`divMod` 10)) .\n       zipWith (*) (cycle [1,2]) . map digitToInt . reverse\n\n\n","human_summarization":"\"Output: The code defines a function that validates credit card numbers using the Luhn test. It first reverses the order of the digits, then calculates two partial sums: one for the odd digits and one for the even digits. The even digits are multiplied by two and if the result is greater than nine, the digits of the result are summed. The function checks if the sum of the two partial sums ends in zero, indicating a valid credit card number. The function is then used to validate four given credit card numbers.\"","id":4283}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List ((\\\\))\nimport System.Environment (getArgs)\n\nprisoners :: Int -> [Int]\nprisoners n = [0 .. n - 1]\n\ncounter :: Int -> [Int]\ncounter k = cycle [k, k-1 .. 1]\n\nkillList :: [Int] -> [Int] -> ([Int], [Int], [Int])\nkillList xs cs = (killed, survivors, newCs)\n    where\n        (killed, newCs) = kill xs cs []\n        survivors = xs \\\\ killed\n        kill [] cs rs = (rs, cs)\n        kill (x:xs) (c:cs) rs\n            | c == 1 =\n                let ts = rs ++ [x]\n                in  kill xs cs ts\n            | otherwise =\n                kill xs cs rs\n\nkillRecursive :: [Int] -> [Int] -> Int -> ([Int], [Int])\nkillRecursive xs cs m = killR ([], xs, cs)\n    where\n        killR (killed, remaining, counter)\n            | length remaining <= m = (killed, remaining)\n            | otherwise =\n                let (newKilled, newRemaining, newCounter) =\n                        killList remaining counter\n                    allKilled = killed ++ newKilled\n                in  killR (allKilled, newRemaining, newCounter)\n\nmain :: IO ()\nmain = do\n    args <- getArgs\n    case args of\n        [n, k, m] -> print $ snd $ killRecursive (prisoners (read n))\n                        (counter (read k)) (read m)\n        _         -> print $ snd $ killRecursive (prisoners 41) (counter 3) 1\n\n\njseq :: Int -> Int -> [Int]\njseq n k = f n [1 .. n]\n  where\n    f 0 _ = []\n    f m s = x : f (m - 1) (right ++ left)\n      where\n        (left, x:right) = splitAt (mod (k - 1) m) s\n\n-- the final survivor is ((k + ...((k + ((k + 0)`mod` 1)) `mod` 2) ... ) `mod` n)\njos :: Int -> Int -> Int\njos n k = 1 + foldl (mod . (k +)) 0 [2 .. n]\n\nmain :: IO ()\nmain = do\n  print $ jseq 41 3\n  print $ jos 10000 100\n\n","human_summarization":"The code takes in the number of prisoners (n), the step count (k), and the number of survivors (m) as inputs. It simulates the Josephus problem, where prisoners are sequentially numbered and every k-th prisoner is killed until only m survivors remain. The code calculates and returns the final survivor(s) and the killing sequence. It also provides the functionality to calculate which prisoner is at any given position on the killing sequence. The prisoners can be numbered either from 0 to n-1 or 1 to n. For larger numbers, the code uses modulo and list split for faster execution.","id":4284}
    {"lang_cluster":"Haskell","source_code":"\n\nconcat $ replicate 5 \"ha\"\n\n\n[1..5] >> \"ha\"\n\n\n[1..5] *> \"ha\"\n\n\ncycle \"ha\"\n\n\nreplicate 5 '*'\n\n\nrepString :: String -> Int -> String\nrepString s n =\n  let rep x = xs\n        where\n          xs = mappend x xs\n  in take (n * length s) (rep s)\n\nmain :: IO ()\nmain = print $ repString \"ha\" 5\n\n\n","human_summarization":"implement a function to repeat a given string a certain number of times. It also includes an optimized method for repeating a single character. The code also contains various methods for repeating a string of finite length, an infinitely long string, and a method that utilizes progressive duplication for efficiency as the number of repetitions increases.","id":4285}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Text.Regex\n\nstr = \"I am a string\"\n\ncase matchRegex (mkRegex \".*string$\") str of\n  Just _  -> putStrLn $ \"ends with 'string'\"\n  Nothing -> return ()\n\n\nimport Text.Regex\n\norig = \"I am the original string\"\nresult = subRegex (mkRegex \"original\") orig \"modified\"\nputStrLn $ result\n\n","human_summarization":"\"Matches a string with a regular expression and substitutes a part of the string using the same regular expression.\"","id":4286}
    {"lang_cluster":"Haskell","source_code":"\nmain = do\n  a <- readLn :: IO Integer\n  b <- readLn :: IO Integer\n  putStrLn $ \"a + b = \" ++ show (a + b)\n  putStrLn $ \"a - b = \" ++ show (a - b)\n  putStrLn $ \"a * b = \" ++ show (a * b)\n  putStrLn $ \"a to the power of b = \" ++ show (a ** b)\n  putStrLn $ \"a to the power of b = \" ++ show (a ^ b)\n  putStrLn $ \"a to the power of b = \" ++ show (a ^^ b)\n  putStrLn $ \"a `div` b = \"  ++ show (a `div` b)  -- truncates towards negative infinity\n  putStrLn $ \"a `mod` b = \"  ++ show (a `mod` b)  -- same sign as second operand\n  putStrLn $ \"a `divMod` b = \"  ++ show (a `divMod` b)\n  putStrLn $ \"a `quot` b = \" ++ show (a `quot` b) -- truncates towards 0\n  putStrLn $ \"a `rem` b = \"  ++ show (a `rem` b)  -- same sign as first operand\n  putStrLn $ \"a `quotRem` b = \"  ++ show (a `quotRem` b)\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":4287}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Text hiding (length)\n\n-- Return the number of non-overlapping occurrences of sub in str.\ncountSubStrs str sub = length $ breakOnAll (pack sub) (pack str)\n\nmain = do\n  print $ countSubStrs \"the three truths\" \"th\"\n  print $ countSubStrs \"ababababab\" \"abab\"\n\n\n","human_summarization":"\"Define a function to count the non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the main string and the substring to be searched for. It returns an integer count of the occurrences. The function matches from left-to-right or right-to-left for the highest number of non-overlapping matches. The order of arguments can be reversed in languages supporting currying. The function can also be used for counting subsequences in a list, even though list-based strings are not the ideal representation of texts.\"","id":4288}
    {"lang_cluster":"Haskell","source_code":"\n\nhanoi :: Integer -> a -> a -> a -> [(a, a)]\nhanoi 0 _ _ _ = []\nhanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a\n\n\nhanoi :: Integer -> a -> a -> a -> [(a, a)]\n\nhanoi n a b c = hanoiToList n a b c []\n  where\n    hanoiToList 0 _ _ _ l = l\n    hanoiToList n a b c l = hanoiToList (n-1) a c b ((a, b) : hanoiToList (n-1) c b a l)\n\n\nhanoiIO n = mapM_ f $ hanoi n 1 2 3 where\n  f (x,y) = putStrLn $ \"Move \" ++ show x ++ \" to \" ++ show y\n\n\nhanoiM :: Integer -> IO ()\nhanoiM n = hanoiM' n 1 2 3 where\n  hanoiM' 0 _ _ _ = return ()\n  hanoiM' n a b c = do\n    hanoiM' (n-1) a c b\n    putStrLn $ \"Move \" ++ show a ++ \" to \" ++ show b\n    hanoiM' (n-1) c b a\n\n\n-------------------------- HANOI -------------------------\n\nhanoi ::\n  Int ->\n  String ->\n  String ->\n  String ->\n  [(String, String)]\nhanoi 0 _ _ _ = mempty\nhanoi n l r m =\n  hanoi (n - 1) l m r\n    <> [(l, r)]\n    <> hanoi (n - 1) m r l\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain = putStrLn $ showHanoi 5\n\n------------------------- DISPLAY ------------------------\nshowHanoi :: Int -> String\nshowHanoi n =\n  unlines $\n    fmap\n      ( \\(from, to) ->\n          concat [justifyRight 5 ' ' from, \" -> \", to]\n      )\n      (hanoi n \"left\" \"right\" \"mid\")\n\njustifyRight :: Int -> Char -> String -> String\njustifyRight n c = (drop . length) <*> (replicate n c <>)\n\n\n","human_summarization":"implement a recursive solution to the Towers of Hanoi problem. The program uses a functional approach, returning a list of movements from one point to another. It also includes an option to produce output using the IO monad directly or by defining it as a monoid. Additionally, the program can be executed imperatively, displaying movements as side effects during execution.","id":4289}
    {"lang_cluster":"Haskell","source_code":"\n\nchoose :: (Integral a) => a -> a -> a\nchoose n k = product [k+1..n] `div` product [1..n-k]\n\n> 5 `choose` 3\n10\n\n\nchoose :: (Integral a) => a -> a -> a\nchoose n k = foldl (\\z i -> (z * (n-i+1)) `div` i) 1 [1..k]\n\n\ncoeffs = iterate next [1] \n  where\n    next ns = zipWith (+) (0:ns) $ ns ++ [0]\n\nmain = print $ coeffs !! 5 !! 3\n\n","human_summarization":"calculate any binomial coefficient using the provided formula. It is capable of outputting the binomial coefficient of (5,3) which is 10. The calculation can be done directly or iteratively to avoid computation with large numbers. It also includes the functionality of generating binomial coefficients with or without replacement, considering the order of elements as important or unimportant. The program also utilizes caching for efficiency.","id":4290}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List\n\nshellSort xs = foldr (invColumnize (map (foldr insert []))) xs gaps\n  where gaps = takeWhile (< length xs) $ iterate (succ.(3*)) 1\n        invColumnize f k = concat. transpose. f. transpose\n                           . takeWhile (not.null). unfoldr (Just. splitAt k)\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. The algorithm, invented by Donald Shell, is a sequence of interleaved insertion sorts with a diminishing increment size. The increment size is reduced after each pass until it reaches 1, at which point the data is almost sorted. The algorithm works with any sequence that ends in 1, with a geometric increment sequence with a ratio of about 2.2 showing good performance in empirical studies.","id":4291}
    {"lang_cluster":"Haskell","source_code":"\nmodule Bitmap.Gray(module Bitmap.Gray) where\n\nimport Bitmap\nimport Control.Monad.ST\n\nnewtype Gray = Gray Int deriving (Eq, Ord)\n\ninstance Color Gray where\n    luminance (Gray x) = x\n    black = Gray 0\n    white = Gray 255\n    toNetpbm = map $ toEnum . luminance\n    fromNetpbm = map $ Gray . fromEnum\n    netpbmMagicNumber _ = \"P5\"\n    netpbmMaxval _ = \"255\"\n\ntoGrayImage :: Color c => Image s c -> ST s (Image s Gray)\ntoGrayImage = mapImage $ Gray . luminance\n\n\n","human_summarization":"extend the data storage type to support grayscale images, implement two operations for converting a color image to a grayscale image and vice versa using the CIE recommended formula for luminance calculation, and ensure no rounding errors cause run-time problems or distorted results. It also includes a function for converting a Gray image to an RGB image using Bitmap.RGB.toRGBImage.","id":4292}
    {"lang_cluster":"Haskell","source_code":"\nUsing simple graphics Library: HGL from HackageDB\nimport Graphics.HGL.Units (Time, Point, Size, )\nimport Graphics.HGL.Draw.Monad (Graphic, )\nimport Graphics.HGL.Draw.Text\nimport Graphics.HGL.Draw.Font\nimport Graphics.HGL.Window\nimport Graphics.HGL.Run\nimport Graphics.HGL.Utils\n\nimport Control.Exception (bracket, )\n\nrunAnim = runGraphics $\n bracket\n  (openWindowEx \"Basic animation task\" Nothing (250,50) DoubleBuffered (Just 110))\n  closeWindow\n  (\\w -> do\n    f <- createFont (64,28) 0 False False \"courier\" \n    let loop t dir = do\n\t  e <- maybeGetWindowEvent w\n\t  let d = case e of\n\t\t  Just (Button _ True False)  -> -dir\n\t\t  _ -> dir\n\t      t' = if d == 1 then last t : init t else tail t ++ [head t]\n\t  setGraphic w (withFont f $ text (5,10) t') >> getWindowTick w \n\t  loop  t' d\n\t      \n    loop \"Hello world\u00a0! \" 1  )\n\n\n*Main> runAnim\n\n","human_summarization":"Create a GUI animation where a window displays the string \"Hello World! \". The text appears to rotate right as one letter is periodically removed from the end of the string and attached to the front. The direction of rotation reverses when the user clicks on the text within the window. The animation runs within the GHCi interpreter.","id":4293}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List\nimport Control.Monad\nimport Control.Arrow\n\ndoWhile p f n = (n:) $ takeWhile p $ unfoldr (Just.(id &&& f)) $ succ n\n\n\n*Main> mapM_ print $ doWhile ((\/=0).(`mod`6)) succ 0\n0\n1\n2\n3\n4\n5\n\n\nmain :: IO ()\nmain =\n  mapM_ print . reverse $\n  until\n    (\\(x:_) -> (x > 0) && (mod x 6 == 0)) \n    (\\xs@(x:_) -> succ x : xs) \n    [0]\n\n\n","human_summarization":"The code initializes a value at 0 and enters a do-while loop. In each iteration, the code increments the value by 1 and prints it. The loop continues until the value modulo 6 is not equal to 0. The loop is guaranteed to run at least once. This functionality is achieved using the 'until' function from the standard Prelude, and 'iterateWhile' from the monad-loops package in GHCi.","id":4294}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.Encoding\nimport Data.ByteString as B\n\nstrUTF8  :: ByteString \nstrUTF8  = encode UTF8  \"Hello World!\"\n\nstrUTF32 :: ByteString \nstrUTF32 = encode UTF32 \"Hello World!\"\n\nstrlenUTF8  = B.length strUTF8\nstrlenUTF32 = B.length strUTF32\n\nWorks with: GHCi version 6.6\nWorks with: Hugs\n\nstrlen = length \"Hello, world!\"\n\n","human_summarization":"determine the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. It handles Unicode code points and non-BMP code points correctly, providing actual character counts in code points, not in code unit counts. It also provides the string length in graphemes if possible. However, it does not calculate the byte length for ordinary strings in Haskell as they are represented as a boxed list of Unicode characters. For byte sequences, it uses Data.ByteString and Data.ByteString.Char8 interface. It also uses encoding libraries for Unicode encoding.","id":4295}
    {"lang_cluster":"Haskell","source_code":"\nLibrary: Entropy\nWorks with: GHC version 7.4.1\n#!\/usr\/bin\/env runhaskell\n\nimport System.Entropy\nimport Data.Binary.Get\nimport qualified Data.ByteString.Lazy as B\n\nmain = do\n  bytes <- getEntropy 4\n  print (runGet getWord32be $ B.fromChunks [bytes])\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.","id":4296}
    {"lang_cluster":"Haskell","source_code":"\n-- We define the functions to return an empty string if the argument is too\n-- short for the particular operation.\n\nremFirst, remLast, remBoth :: String -> String\n\nremFirst \"\" = \"\"\nremFirst cs = tail cs\n\nremLast \"\" = \"\"\nremLast cs = init cs\n\nremBoth (c:cs) = remLast cs\nremBoth  _     = \"\"\n\nmain :: IO ()\nmain = do\n  let s = \"Some string.\"  \n  mapM_ (\\f -> putStrLn . f $ s) [remFirst, remLast, remBoth]\n\n\nword = \"knights\"\n\nmain = do\n    -- You can drop the first item\n    -- using `tail`\n    putStrLn (tail word)\n\n    -- The `init` function will drop\n    -- the last item\n    putStrLn (init word)\n\n    -- We can combine these two to drop\n    -- the last and the first characters\n    putStrLn (middle word)\n\n-- You can combine functions using `.`,\n-- which is pronounced \"compose\" or \"of\"\nmiddle = init . tail\n\n\nmain :: IO ()\nmain = mapM_ print $ [tail, init, init . tail] <*> [\"knights\"]\n\n\n","human_summarization":"demonstrate the removal of the first and last characters from a string, including cases where only the first or last character is removed. The codes work with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters rather than 8-bit or 16-bit code units. Handling all Unicode characters for other encodings is not required.","id":4297}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Control.Concurrent\nimport System.Directory (doesFileExist, getAppUserDataDirectory,\n    removeFile)\nimport System.IO (withFile, Handle, IOMode(WriteMode), hPutStr)\n\noneInstance :: IO ()\noneInstance = do\n    -- check if file \"$HOME\/.myapp.lock\" exists\n    user <- getAppUserDataDirectory \"myapp.lock\"\n    locked <- doesFileExist user\n    if locked\n    then print \"There is already one instance of this program running.\"\n    else do\n        t <- myThreadId\n        -- this is the entry point to the main program:\n        -- withFile creates a file, then calls a function,\n        -- then closes the file\n        withFile user WriteMode (do_program t)\n        -- remove the lock when we're done\n        removeFile user\n\ndo_program :: ThreadId -> Handle -> IO ()\ndo_program t h = do\n    let s = \"Locked by thread: \" ++ show t\n    -- print what thread has acquired the lock\n    putStrLn s\n    -- write the same message to the file, to show that the\n    -- thread \"owns\" the file\n    hPutStr h s\n    -- wait for one second\n    threadDelay 1000000\n\nmain :: IO ()\nmain = do\n    -- launch the first thread, which will create the lock file\n    forkIO oneInstance\n    -- wait for half a second\n    threadDelay 500000\n    -- launch the second thread, which will find the lock file and\n    -- thus will exit immediately\n    forkIO oneInstance\n    return ()\n\n","human_summarization":"determine if only one instance of an application is running. If another instance is found, a message is displayed and the program exits. This is achieved through a lock file implementation, where the first thread creates a lock file preventing the second thread from starting until the lock file is deleted.","id":4298}
    {"lang_cluster":"Haskell","source_code":"\nimport Graphics.UI.Gtk\nimport Control.Monad (when)\nimport Control.Monad.Trans (liftIO)\n\nmaximumWindowDimensions :: IO ()\nmaximumWindowDimensions = do\n    -- initialize the internal state of the GTK toolkit\n    initGUI\n    -- create a window\n    window <- windowNew\n    -- quit the application when the window is closed\n    on window objectDestroy mainQuit\n    -- query the size of the window when its dimensions change\n    on window configureEvent printSize\n    -- get the screen the window will be drawn upon\n    screen <- windowGetScreen window\n    -- get the size of the screen\n    x <- screenGetWidth screen\n    y <- screenGetHeight screen\n    -- print the dimensions of the screen\n    putStrLn (\"The screen is \" ++ show x ++ \" pixels wide and \" ++\n        show y ++ \" pixels tall for an undecorated fullscreen window.\")\n    -- maximize the window and show it. printSize will then be called\n    windowMaximize window\n    widgetShowAll window\n    -- run the main GTK loop.\n    -- close the window manually.\n    mainGUI\n\n-- On my Xfce4 desktop, the configure_event is called three times when a\n-- top level window is maximized. The first time, the window size\n-- returned is the size prior to maximizing, and the last two times\n-- it is the size after maximizing.\n-- If the window is (un)maximized manually, the size returned is always\n-- the size of the unmaximized window.\n-- That means: either GTK or Xfce4 does not handle window maximization\n-- correctly, or the GTK bindings for Haskell are buggy, or there is an\n-- error in this program.\n\nprintSize :: EventM EConfigure Bool\nprintSize = do\n    -- get the window that has been resized\n    w <- eventWindow\n    -- is the window maximized?\n    s <- liftIO $ drawWindowGetState w\n    when (WindowStateMaximized `elem` s) $ do\n        -- get the size of the window that has been resized\n        (x, y) <- eventSize\n        -- print the dimensions out\n        liftIO $ putStrLn (\"The inner window region is now \" ++ show x ++\n            \" pixels wide and \" ++ show y ++ \" pixels tall.\")\n    return True\n\n","human_summarization":"calculate the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations, menubars, multiple monitors, and tiling window managers.","id":4299}
    {"lang_cluster":"Haskell","source_code":"\nimport System\nimport Control.Monad\nimport Data.List\nimport Data.Array.IO\n\ntype SodokuBoard = IOArray Int Int\n\nmain = do\n    [f] <- getArgs\n    a <- newArray (1, 81) 0\n    readFile f >>= readSodokuBoard a\n    putStrLn \"Original:\"\n    printSodokuBoard a\n    putStrLn \"Solutions:\"\n    solve a (1,1)\n\nreadSodokuBoard a xs = sequence_ $ do (i,ys) <- zip [1..9] (lines xs)\n                                      (j,n)  <- zip [1..9] (words ys)\n                                      return $ writeBoard a (j,i) (read n)\n\nprintSodokuBoard a =\n   let printLine a y =\n     mapM (x -> readBoard a (x,y)) [1..9] >>= mapM_ (putStr . show) in do\n                     putStrLn \"-----------\"\n                     mapM_ (\\y -> putStr \"|\" >> printLine a y >> putStrLn \"|\") [1..9]\n                     putStrLn \"-----------\"\n\n-- the meat of the program.  Checks the current square.\n-- If 0, then get the list of nums and try to \"solve' \"\n-- Otherwise, go to the next square.\nsolve :: SodokuBoard  -> (Int, Int) -> IO (Maybe SodokuBoard)\nsolve a (10,y) = solve a (1,y+1)\nsolve a (_, 10)= printSodokuBoard a >> return (Just a)\nsolve a (x,y)  = do v <- readBoard a (x,y)\n                    case v of\n                      0 -> availableNums a (x,y) >>= solve' a (x,y)\n                      _ ->  solve a (x+1,y)\n     -- solve' handles the backtacking\n  where solve' a (x,y) []     = return Nothing\n        solve' a (x,y) (v:vs) = do writeBoard a (x,y) v   -- put a guess onto the board\n                                   r <- solve a (x+1,y)\n                                   writeBoard a (x,y) 0   -- remove the guess from the board\n                                   solve' a (x,y) vs      -- recurse over the remainder of the list\n\n-- get the \"taken\" numbers from a row, col or box.\ngetRowNums a y = sequence [readBoard a (x',y) | x' <- [1..9]]\ngetColNums a x = sequence [readBoard a (x,y') | y' <- [1..9]]\ngetBoxNums a (x,y) = sequence [readBoard a (x'+u, y'+v) | u <- [0..2], v <- [0..2]] \n  where x' = (3 * ((x-1) `quot` 3)) + 1\n        y' = (3 * ((y-1) `quot` 3)) + 1\n\n-- return the numbers that are available for a particular square\navailableNums a (x,y) = do r <- getRowNums a y \n                           c <- getColNums a x\n                           b <- getBoxNums a (x,y)\n                           return $ [0..9] \\ (r `union` c `union` b)  \n\n-- aliases of read and write array that flatten the index\nreadBoard a (x,y) = readArray a (x+9*(y-1))\nwriteBoard a (x,y) e = writeArray a (x+9*(y-1)) e\n","human_summarization":"\"The code implements a Sudoku solver for a 9x9 grid. It takes a partially filled grid as input, solves it, and displays the result in a human-readable format. The implementation is based on the Algorithmics of Sudoku and references from Python Sudoku Solver Computerphile video and Haskell wiki Sudoku.\"","id":4300}
    {"lang_cluster":"Haskell","source_code":"\nimport System.Random (randomRIO)\n\nmkRands :: Int -> IO [Int]\nmkRands = mapM (randomRIO . (,) 0) . enumFromTo 1 . pred\n\nreplaceAt :: Int -> a -> [a] -> [a]\nreplaceAt i c l =\n  let (a, b) = splitAt i l\n  in a ++ c : drop 1 b\n\nswapElems :: (Int, Int) -> [a] -> [a]\nswapElems (i, j) xs\n  | i == j = xs\n  | otherwise = replaceAt j (xs !! i) $ replaceAt i (xs !! j) xs\n\nknuthShuffle :: [a] -> IO [a]\nknuthShuffle xs = (foldr swapElems xs . zip [1 ..]) <$> mkRands (length xs)\n\n\nimport System.Random (randomRIO)\nimport Data.Bool (bool)\n\nknuthShuffle :: [a] -> IO [a]\nknuthShuffle xs = (foldr swapped xs . zip [1 ..]) <$> randoms (length xs)\n\nswapped :: (Int, Int) -> [a] -> [a]\nswapped (i, j) xs =\n  let go (a, b)\n        | a == b = xs\n        | otherwise =\n          let (m, n) = bool (b, a) (a, b) (b > a)\n              (l, hi:t) = splitAt m xs\n              (ys, lo:zs) = splitAt (pred (n - m)) t\n          in concat [l, lo : ys, hi : zs]\n  in bool xs (go (i, j)) $ ((&&) . (i <) <*> (j <)) $ length xs\n\nrandoms :: Int -> IO [Int]\nrandoms x = mapM (randomRIO . (,) 0) [1 .. pred x]\n\nmain :: IO ()\nmain = knuthShuffle ['a' .. 'k'] >>= print\n\n\n*Main> knuthShuffle  ['a'..'k']\n\"bhjdgfciake\"\n\n*Main> knuthShuffle $ map(ap (,)(+10)) [0..9]\n[(0,10),(8,18),(2,12),(3,13),(9,19),(4,14),(7,17),(1,11),(6,16),(5,15)]\n\nknuthShuffleProcess :: (Show a) => [a] -> IO ()\nknuthShuffleProcess = \n   (mapM_ print. reverse =<<). ap (fmap. (. zip [1..]). scanr swapElems) (mkRands. length)\n\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an input array. The shuffling is done in-place, but can be modified to return a new array if necessary. The algorithm can also be adjusted to iterate from left to right. The function accepts an array and returns a shuffled version of the array.","id":4301}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Time.Calendar\n       (Day, addDays, showGregorian, fromGregorian, gregorianMonthLength)\nimport Data.Time.Calendar.WeekDate (toWeekDate)\nimport Data.List (transpose, intercalate)\n\n-- [1 .. 7] for [Mon .. Sun]\nfindWeekDay :: Int -> Day -> Day\nfindWeekDay dayOfWeek date =\n  head\n    (filter\n       (\\x ->\n           let (_, _, day) = toWeekDate x\n           in day == dayOfWeek)\n       ((`addDays` date) <$> [-6 .. 0]))\n\nweekDayDates :: Int -> Integer -> [String]\nweekDayDates dayOfWeek year =\n  ((showGregorian . findWeekDay dayOfWeek) .\n   (fromGregorian year <*> gregorianMonthLength year)) <$>\n  [1 .. 12]\n\nmain :: IO ()\nmain =\n  mapM_\n    putStrLn\n    (intercalate \"  \" <$> transpose (weekDayDates 5 <$> [2012 .. 2017]))\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":4302}
    {"lang_cluster":"Haskell","source_code":"\nmain = putStr \"Goodbye, world\"\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":4303}
    {"lang_cluster":"Haskell","source_code":"\nUsing Library: gtk from HackageDB\nimport Graphics.UI.Gtk\nimport Control.Monad\n\nmain = do\n  initGUI\n\n  window <- windowNew\n  set window [windowTitle := \"Graphical user input\", containerBorderWidth := 10]\n\n  vb <- vBoxNew False 0\n  containerAdd window vb\n\n  hb1 <- hBoxNew False 0\n  boxPackStart vb hb1 PackNatural 0\n  hb2 <- hBoxNew False 0\n  boxPackStart vb hb2 PackNatural 0\n\n  lab1 <- labelNew (Just \"Enter number 75000\")\n  boxPackStart hb1 lab1 PackNatural 0\n  nrfield <- entryNew\n  entrySetText nrfield \"75000\"\n  boxPackStart hb1 nrfield PackNatural 5\n\n  strfield <- entryNew\n  boxPackEnd hb2 strfield PackNatural 5\n  lab2 <- labelNew (Just \"Enter a text\")\n  boxPackEnd hb2 lab2 PackNatural 0\n  \n  accbox    <- hBoxNew False 0\n  boxPackStart vb accbox PackNatural 5\n  im <- imageNewFromStock stockApply IconSizeButton\n  acceptButton <- buttonNewWithLabel \"Accept\"\n  buttonSetImage acceptButton im\n  boxPackStart accbox acceptButton PackRepel 0\n\n  txtstack <- statusbarNew\n  boxPackStart vb txtstack PackNatural 0\n  id <- statusbarGetContextId txtstack \"Line\"\n\n  widgetShowAll window\n\n  onEntryActivate nrfield (showStat nrfield txtstack id)\n  onEntryActivate strfield (showStat strfield txtstack id)\n    \n  onPressed acceptButton $ do\n    g <- entryGetText nrfield\n    if g==\"75000\" then\n      widgetDestroy window\n     else do\n       msgid <- statusbarPush txtstack id \"You didn't enter 75000. Try again\"\n       return ()\n  \n  onDestroy window mainQuit\n  mainGUI\n\nshowStat :: Entry -> Statusbar -> ContextId -> IO ()\nshowStat fld stk id = do\n    txt <- entryGetText fld\n    let mesg = \"You entered \\\"\" ++ txt ++ \"\\\"\"\n    msgid <- statusbarPush stk id mesg\n    return ()\n\n\n*Main> main\n\n","human_summarization":"\"Code allows for the input of a string and the integer 75000 through a graphical user interface.\"","id":4304}
    {"lang_cluster":"Haskell","source_code":"\nmodule Caesar (caesar, uncaesar) where \n\nimport Data.Char\n\ncaesar, uncaesar :: (Integral a) => a -> String -> String\ncaesar k = map f\n    where f c = case generalCategory c of\n              LowercaseLetter -> addChar 'a' k c\n              UppercaseLetter -> addChar 'A' k c\n              _               -> c\nuncaesar k = caesar (-k)\n\naddChar :: (Integral a) => Char -> a -> Char -> Char\naddChar b o c = chr $ fromIntegral (b' + (c' - b' + o) `mod` 26)\n    where b' = fromIntegral $ ord b\n          c' = fromIntegral $ ord c\n\n\n*Main> caesar 1 \"hal\"\n\"ibm\"\n*Main> unCaesar 1 \"ibm\"\n\"hal\"\n\n\nimport Data.Bool (bool)\nimport Data.Char (chr, isAlpha, isUpper, ord)\n\n---------------------- CAESAR CIPHER ---------------------\n\ncaesar, uncaesar :: Int -> String -> String\ncaesar = fmap . tr\nuncaesar = caesar . negate\n\ntr :: Int -> Char -> Char\ntr offset c\n  | isAlpha c =\n      chr\n        . ((+) <*> (flip mod 26 . (-) (offset + ord c)))\n        $ bool 97 65 (isUpper c)\n  | otherwise = c\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain = do\n  let k = -114\n      cipher = caesar k\n      plain = \"Curio, Cesare venne, e vide e vinse\u00a0? \"\n  mapM_ putStrLn $ [cipher, uncaesar k . cipher] <*> [plain]\n\n\n","human_summarization":"implement both encoding and decoding functionalities of a Caesar cipher. The key for the cipher is an integer ranging from 1 to 25, which rotates the letters of the alphabet either left or right. The encoding process replaces each letter with the next 1st to 25th letter in the alphabet, wrapping Z back to A. The code also considers negative cipher keys and uses isAlpha, isUpper, negate for proper error handling. The Caesar cipher is identical to the Vigen\u00e8re cipher with a key length of 1 and the Rot-13 cipher with a key of 13.","id":4305}
    {"lang_cluster":"Haskell","source_code":"\n\nlcm :: (Integral a) => a -> a -> a\nlcm _ 0 =  0\nlcm 0 _ =  0\nlcm x y =  abs ((x `quot` (gcd x y)) * y)\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers, m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m * n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":4306}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List(elemIndex)\n\ndata Result = Valid | BadCheck | TooLong | TooShort | InvalidContent deriving Show\n\n-- convert a list of Maybe to a Maybe list.\n-- result is Nothing if any of values from the original list are Nothing\nallMaybe :: [Maybe a] -> Maybe [a]\nallMaybe = sequence\n\ntoValue :: Char -> Maybe Int\ntoValue c = elemIndex c $ ['0'..'9'] ++ ['A'..'Z'] ++ \"*@#\" \n\n-- check a list of ints to see if they represent a valid CUSIP\nvalid :: [Int] -> Bool\nvalid ns0 = \n    let -- multiply values with even index by 2\n        ns1 = zipWith (\\i n -> (if odd i then n else 2*n)) [1..] $ take 8 ns0\n\n        -- apply div\/mod formula from site and sum up results\n        sm = sum $ fmap (\\s -> ( s `div` 10 ) + s `mod` 10) ns1\n\n    in  -- apply mod\/mod formula from site and compare to last value in list\n        ns0!!8 == (10 - (sm `mod` 10)) `mod` 10\n\n-- check a String to see if it represents a valid CUSIP\ncheckCUSIP :: String -> Result\ncheckCUSIP cs \n       | l < 9     = TooShort\n       | l > 9     = TooLong\n       | otherwise = case allMaybe (fmap toValue cs) of\n                         Nothing -> InvalidContent\n                         Just ns -> if valid ns then Valid else BadCheck\n    where l = length cs\n\ntestData =  \n    [ \"037833100\"\n    , \"17275R102\"\n    , \"38259P508\"\n    , \"594918104\"\n    , \"68389X106\"\n    , \"68389X105\"\n    ]\n\nmain = mapM_ putStrLn (fmap (\\s -> s ++ \": \" ++ show (checkCUSIP s)) testData)\n\n\n","human_summarization":"The code validates the last digit of a CUSIP code, which is a nine-character alphanumeric code identifying North American financial securities. It checks the digit against a list of predefined CUSIP codes for various corporations. The validation algorithm involves calculating a sum based on the ordinal positions of the characters in the CUSIP code, with special conditions for digits, letters, and specific special characters. The function returns the modulus of the difference between 10 and the modulus of the sum by 10.","id":4307}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Bits\nimport ADNS.Endian -- http:\/\/hackage.haskell.org\/package\/hsdns\n\nmain = do\n  putStrLn $ \"Word size: \" ++ bitsize\n  putStrLn $ \"Endianness: \" ++ show endian\n      where\n        bitsize = show $ bitSize (undefined :: Int)\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":4308}
    {"lang_cluster":"Haskell","source_code":"\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.Aeson \nimport Network.HTTP.Base (urlEncode)\nimport Network.HTTP.Conduit (simpleHttp)\nimport Data.List (sortBy, groupBy)\nimport Data.Function (on)\nimport Data.Map (Map, toList)\n\n-- Record representing a single language.  \ndata Language =\n    Language { \n        name      :: String,\n        quantity  :: Int\n    } deriving (Show)\n\n-- Make Language an instance of FromJSON for parsing of query response.\ninstance FromJSON Language where\n    parseJSON (Object p) = do\n        categoryInfo <- p .:? \"categoryinfo\" \n\n        let quantity = case categoryInfo of\n                           Just ob -> ob .: \"size\"\n                           Nothing -> return 0\n\n            name = p .: \"title\"\n\n        Language <$> name <*> quantity\n\n-- Record representing entire response to query.  \n-- Contains collection of languages and optional continuation string.\ndata Report =\n    Report { \n        continue    :: Maybe String,\n        languages   :: Map String Language\n    } deriving (Show)\n\n-- Make Report an instance of FromJSON for parsing of query response.\ninstance FromJSON Report where\n    parseJSON (Object p) = do\n        querycontinue <- p .:? \"query-continue\"\n\n        let continue \n                = case querycontinue of\n                      Just ob -> fmap Just $ \n                                     (ob .: \"categorymembers\") >>= \n                                     (   .: \"gcmcontinue\")\n                      Nothing -> return Nothing\n\n            languages = (p .: \"query\") >>= (.: \"pages\") \n\n        Report <$> continue <*> languages\n\n-- Pretty print a single language\nshowLanguage :: Int -> Bool -> Language -> IO ()\nshowLanguage rank tie (Language languageName languageQuantity) = \n    let rankStr = show rank\n    in putStrLn $ rankStr ++ \".\" ++ \n                      replicate (4 - length rankStr) ' ' ++\n                      (if tie then \" (tie)\" else \"      \") ++\n                      \" \" ++ drop 9 languageName ++\n                      \" - \" ++ show languageQuantity\n\n-- Pretty print languages with common rank\nshowRanking :: (Int,  [Language]) -> IO ()\nshowRanking (ranking, languages) = \n    mapM_ (showLanguage ranking $ length languages > 1) languages\n\n-- Sort and group languages by rank, then pretty print them.\nshowLanguages :: [Language] -> IO ()\nshowLanguages allLanguages =\n    mapM_ showRanking $ \n          zip [1..] $ \n          groupBy ((==) `on` quantity) $\n          sortBy (flip compare `on` quantity) allLanguages\n\n-- Mediawiki api style query to send to rosettacode.org\nqueryStr = \"http:\/\/rosettacode.org\/mw\/api.php?\" ++ \n           \"format=json\" ++ \n           \"&action=query\" ++ \n           \"&generator=categorymembers\" ++ \n           \"&gcmtitle=Category:Programming%20Languages\" ++ \n           \"&gcmlimit=100\" ++ \n           \"&prop=categoryinfo\" \n\n-- Issue query to get a list of Language descriptions\nrunQuery :: [Language] -> String -> IO ()\nrunQuery ls query = do\n    Just (Report continue langs) <- decode <$> simpleHttp query \n    let accLanguages = ls ++ map snd (toList langs)\n\n    case continue of\n        -- If there is no continue string we are done so display the accumulated languages.\n        Nothing -> showLanguages accLanguages\n\n        -- If there is a continue string, recursively continue the query.\n        Just continueStr -> do\n            let continueQueryStr = queryStr ++ \"&gcmcontinue=\" ++ urlEncode continueStr\n            runQuery accLanguages continueQueryStr\n\nmain :: IO ()\nmain = runQuery [] queryStr\n\n\n","human_summarization":"The code sorts and ranks the most popular computer programming languages based on the number of members in their respective Rosetta Code categories. It uses either web scraping or API methods to access the data. The code also optionally filters incorrect results and checks the results against a complete, accurate, sortable, wikitable listing of all programming languages. The final output is a ranked list of all languages, with a sample output provided for the top 10 languages as of 02 August 2022.","id":4309}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad (forM_)\nforM_ collect print\n\n\nmapM_ print collect\n\n","human_summarization":"Iterates through each element in a collection in order using a \"for each\" loop or another loop if \"for each\" is not available, and prints each element.","id":4310}
    {"lang_cluster":"Haskell","source_code":"\n\n{-# OPTIONS_GHC -XOverloadedStrings #-}\nimport Data.Text (splitOn,intercalate)\nimport qualified Data.Text.IO as T (putStrLn)\n\nmain = T.putStrLn . intercalate \".\" $ splitOn \",\" \"Hello,How,Are,You,Today\"\n\n\nsplitBy :: (a -> Bool) -> [a] -> [[a]]\nsplitBy _ [] = []\nsplitBy f list = first : splitBy f (dropWhile f rest) where\n  (first, rest) = break f list\n\nsplitRegex :: Regex -> String -> [String]\n\njoinWith :: [a] -> [[a]] -> [a]\njoinWith d xs = concat $ List.intersperse d xs\n-- \"concat $ intersperse\" can be replaced with \"intercalate\" from the Data.List in GHC 6.8 and later\n\nputStrLn $ joinWith \".\" $ splitBy (== ',') $ \"Hello,How,Are,You,Today\"\n\n-- using regular expression to split:\nimport Text.Regex\nputStrLn $ joinWith \".\" $ splitRegex (mkRegex \",\") $ \"Hello,How,Are,You,Today\"\n\n\n*Main> mapM_ putStrLn $ takeWhile (not.null) $ unfoldr (Just . second(drop 1). break (==',')) \"Hello,How,Are,You,Today\"\nHello\nHow\nAre\nYou\nToday\n\nYou need to import the modules Data.List and Control.Arrow\n\n","human_summarization":"\"Tokenizes a given string by commas into an array, and then displays the words separated by a period. The code also includes an alternate solution using unfoldr and break functions. Special cases for splitting\/joining by white space and newlines are handled by the Prelude functions words\/unwords and lines\/unlines respectively.\"","id":4311}
    {"lang_cluster":"Haskell","source_code":"\n\ngcd :: (Integral a) => a -> a -> a\ngcd x y = gcd_ (abs x) (abs y)\n  where\n    gcd_ a 0 = a\n    gcd_ a b = gcd_ b (a `rem` b)\n\n","human_summarization":"implement a function to find the greatest common divisor (GCD), also known as the greatest common factor (gcf) or greatest common measure, of two integers. The function is already available in the Prelude. The related task is to find the least common multiple. Refer to MathWorld and Wikipedia entries for more information on the greatest common divisor.","id":4312}
    {"lang_cluster":"Haskell","source_code":"\nmodule Main where\nimport Network (withSocketsDo, accept, listenOn, sClose, PortID(PortNumber))\nimport Control.Monad (forever)\nimport System.IO (hGetLine, hPutStrLn, hFlush, hClose)\nimport System.IO.Error (isEOFError)\nimport Control.Concurrent (forkIO)\nimport Control.Exception (bracket)\n\n-- For convenience in testing, ensure that the listen socket is closed if the main loop is aborted\nwithListenOn port body = bracket (listenOn port) sClose body\n\necho (handle, host, port) = catch (forever doOneLine) stop where\n  doOneLine = do line <- hGetLine handle\n                 print (host, port, init line)\n                 hPutStrLn handle line\n                 hFlush handle\n  stop error = do putStrLn $ \"Closed connection from \" ++ show (host, port) ++ \" due to \" ++ show error\n                  hClose handle\n\nmain = withSocketsDo $\n  withListenOn (PortNumber 12321) $ \\listener ->\n    forever $ do\n      acc@(_, host, port) <- accept listener\n      putStrLn $ \"Accepted connection from \" ++ show (host, port)\n      forkIO (echo acc)\n\n","human_summarization":"Implement an echo server that listens on TCP port 12321, accepts and handles multiple simultaneous connections from localhost, echoes complete lines back to clients, and logs connection information. The server remains responsive even if a client sends a partial line or stops reading responses.","id":4313}
    {"lang_cluster":"Haskell","source_code":"\n\nisInteger s = case reads s :: [(Integer, String)] of\n  [(_, \"\")] -> True\n  _         -> False\n\nisDouble s = case reads s :: [(Double, String)] of\n  [(_, \"\")] -> True\n  _         -> False\n\nisNumeric :: String -> Bool\nisNumeric s = isInteger s || isDouble s\n\n\nareDigits = all isDigit\nisDigit  selects ASCII digits i.e. '0'..'9'\nisOctDigit selects '0'..'7'\nisHexDigit selects '0'..'9','A'..'F','a'..'f'\n\n\n","human_summarization":"\"Create a boolean function to check if a string is numeric, including floating point and negative numbers. The function attempts to convert the string to an integer or double, and handles parsing failures. It can be extended to check for rational or complex numbers. It can also use the Data.Char module for more reliable results.\"","id":4314}
    {"lang_cluster":"Haskell","source_code":"\nLibrary: http-conduit\nWorks with: GHC version 7.4.1\n\n#!\/usr\/bin\/runhaskell\n\nimport Network.HTTP.Conduit\nimport qualified Data.ByteString.Lazy as L\nimport Network (withSocketsDo)\n\nmain = withSocketsDo\n    $ simpleHttp \"https:\/\/sourceforge.net\/\" >>= L.putStr\n\n","human_summarization":"send a GET request to the URL \"https:\/\/www.w3.org\/\" without authentication, check the host certificate for validity, and print the obtained resource to the console. This is done using the Network.HTTP.Conduit library which natively supports HTTPS.","id":4315}
    {"lang_cluster":"Haskell","source_code":"\nmodule SuthHodgClip (clipTo) where\n\nimport Data.List\n\ntype   Pt a = (a, a)\ntype   Ln a = (Pt a, Pt a)\ntype Poly a = [Pt a]\n\n-- Return a polygon from a list of points.\npolyFrom ps = last ps : ps\n\n-- Return a list of lines from a list of points.\nlinesFrom pps@(_:ps) = zip pps ps\n\n-- Return true if the point (x,y) is on or to the left of the oriented line\n-- defined by (px,py) and (qx,qy).\n(.|) :: (Num a, Ord a) => Pt a -> Ln a -> Bool\n(x,y) .| ((px,py),(qx,qy)) = (qx-px)*(y-py) >= (qy-py)*(x-px)\n\n-- Return the intersection of two lines.\n(><) :: Fractional a => Ln a -> Ln a -> Pt a\n((x1,y1),(x2,y2)) >< ((x3,y3),(x4,y4)) =\n    let (r,s) = (x1*y2-y1*x2, x3*y4-y3*x4)\n        (t,u,v,w) = (x1-x2, y3-y4, y1-y2, x3-x4)\n        d = t*u-v*w \n    in ((r*w-t*s)\/d, (r*u-v*s)\/d)\n\n-- Intersect the line segment (p0,p1) with the clipping line's left halfspace,\n-- returning the point closest to p1.  In the special case where p0 lies outside\n-- the halfspace and p1 lies inside we return both the intersection point and\n-- p1.  This ensures we will have the necessary segment along the clipping line.\n(-|) :: (Fractional a, Ord a) => Ln a -> Ln a -> [Pt a]\nln@(p0, p1) -| clipLn =\n    case (p0 .| clipLn, p1 .| clipLn) of\n      (False, False) -> []\n      (False, True)  -> [isect, p1]\n      (True,  False) -> [isect]\n      (True,  True)  -> [p1]\n    where isect = ln >< clipLn\n\n-- Intersect the polygon with the clipping line's left halfspace.\n(<|) :: (Fractional a, Ord a) => Poly a -> Ln a -> Poly a\npoly <| clipLn = polyFrom $ concatMap (-| clipLn) (linesFrom poly)\n\n-- Intersect a target polygon with a clipping polygon.  The latter is assumed to\n-- be convex.\nclipTo :: (Fractional a, Ord a) => [Pt a] -> [Pt a] -> [Pt a]\ntargPts `clipTo` clipPts = \n    let targPoly = polyFrom targPts\n        clipLines = linesFrom (polyFrom clipPts)\n    in foldl' (<|) targPoly clipLines\n\n\nimport Graphics.HGL\nimport SuthHodgClip\n\ntargPts = [( 50,150), (200, 50), (350,150), (350,300), (250,300), \n           (200,250), (150,350), (100,250), (100,200)] :: [(Float,Float)]\nclipPts = [(100,100), (300,100), (300,300), (100,300)] :: [(Float,Float)]\n\ntoInts = map (\\(a,b) -> (round a, round b))\ncomplete xs = last xs : xs\n\ndrawSolid w c = drawInWindow w . withRGB c . polygon\ndrawLines w p = drawInWindow w . withPen p . polyline . toInts . complete\n\nblue  = RGB 0x99 0x99 0xff\ngreen = RGB 0x99 0xff 0x99\npink  = RGB 0xff 0x99 0x99\nwhite = RGB 0xff 0xff 0xff\n\nmain = do\n  let resPts = targPts `clipTo` clipPts\n      sz = 400\n      win = [(0,0), (sz,0), (sz,sz), (0,sz)]\n  runWindow \"Sutherland-Hodgman Polygon Clipping\" (sz,sz) $ \\w -> do\n         print $ toInts resPts\n         penB <- createPen Solid 3 blue\n         penP <- createPen Solid 5 pink\n         drawSolid w white win\n         drawLines w penB targPts\n         drawLines w penP clipPts\n         drawSolid w green $ toInts resPts\n         getKey w\n\n\n","human_summarization":"Implement the Sutherland-Hodgman polygon clipping algorithm to find the intersection of a given polygon and a rectangle. The polygon is defined by a sequence of points and the rectangle is defined by four points. The code prints the sequence of points that define the resulting clipped polygon. Additionally, the code displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west. The resulting list of points is printed and the polygons are displayed in a window.","id":4316}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List (groupBy, sortBy, intercalate)\n\ntype Item = (Int, String)\n\ntype ItemList = [Item]\n\ntype ItemGroups = [ItemList]\n\ntype RankItem a = (a, Int, String)\n\ntype RankItemList a = [RankItem a]\n\n-- make sure the input is ordered and grouped by score\nprepare :: ItemList -> ItemGroups\nprepare = groupBy gf . sortBy (flip compare)\n  where\n    gf (a, _) (b, _) = a == b\n\n-- give an item a rank\nrank\n  :: Num a\n  => a -> Item -> RankItem a\nrank n (a, b) = (n, a, b)\n\n-- ranking methods\nstandard, modified, dense, ordinal :: ItemGroups -> RankItemList Int\nstandard = ms 1\n  where\n    ms _ [] = []\n    ms n (x:xs) = (rank n <$> x) ++ ms (n + length x) xs\n\nmodified = md 1\n  where\n    md _ [] = []\n    md n (x:xs) =\n      let l = length x\n          nl = n + l\n          nl1 = nl - 1\n      in (rank nl1 <$> x) ++ md (n + l) xs\n\ndense = md 1\n  where\n    md _ [] = []\n    md n (x:xs) = map (rank n) x ++ md (n + 1) xs\n\nordinal = zipWith rank [1 ..] . concat\n\nfractional :: ItemGroups -> RankItemList Double\nfractional = mf 1.0\n  where\n    mf _ [] = []\n    mf n (x:xs) =\n      let l = length x\n          o = take l [n ..]\n          ld = fromIntegral l\n          a = sum o \/ ld\n      in map (rank a) x ++ mf (n + ld) xs\n\n-- sample data\ntest :: ItemGroups\ntest =\n  prepare\n    [ (44, \"Solomon\")\n    , (42, \"Jason\")\n    , (42, \"Errol\")\n    , (41, \"Garry\")\n    , (41, \"Bernard\")\n    , (41, \"Barry\")\n    , (39, \"Stephen\")\n    ]\n\n-- print rank items nicely\nnicePrint\n  :: Show a\n  => String -> RankItemList a -> IO ()\nnicePrint xs items = do\n  putStrLn xs\n  mapM_ np items\n  putStr \"\\n\"\n  where\n    np (a, b, c) = putStrLn $ intercalate \"\\t\" [show a, show b, c]\n\nmain :: IO ()\nmain = do\n  nicePrint \"Standard:\" $ standard test\n  nicePrint \"Modified:\" $ modified test\n  nicePrint \"Dense:\" $ dense test\n  nicePrint \"Ordinal:\" $ ordinal test\n  nicePrint \"Fractional:\" $ fractional test\n\n\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":4317}
    {"lang_cluster":"Haskell","source_code":"\n\nfromDegrees :: Floating a => a -> a\nfromDegrees deg = deg * pi \/ 180\n\ntoDegrees :: Floating a => a -> a\ntoDegrees rad = rad * 180 \/ pi\n\nmain :: IO ()\nmain =\n  mapM_\n    print\n    [ sin (pi \/ 6)\n    , sin (fromDegrees 30)\n    , cos (pi \/ 6)\n    , cos (fromDegrees 30)\n    , tan (pi \/ 6)\n    , tan (fromDegrees 30)\n    , asin 0.5\n    , toDegrees (asin 0.5)\n    , acos 0.5\n    , toDegrees (acos 0.5)\n    , atan 0.5\n    , toDegrees (atan 0.5)\n    ]\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions such as sine, cosine, and tangent, and their inverses using the same angle in both radians and degrees. The codes also include conversion of angles from radians to degrees and vice versa. If trigonometric functions are not available, the codes provide custom functions to calculate these using known approximations or identities.","id":4318}
    {"lang_cluster":"Haskell","source_code":"\n\ninv = \t[(\"map\",9,150,1), (\"compass\",13,35,1), (\"water\",153,200,2), (\"sandwich\",50,60,2),\n\t(\"glucose\",15,60,2), (\"tin\",68,45,3), (\"banana\",27,60,3), (\"apple\",39,40,3),\n\t(\"cheese\",23,30,1), (\"beer\",52,10,3), (\"cream\",11,70,1), (\"camera\",32,30,1),\n\t-- what to do if we end up taking one trouser?\n\t(\"tshirt\",24,15,2), (\"trousers\",48,10,2), (\"umbrella\",73,40,1), (\"wtrousers\",42,70,1),\n\t(\"woverclothes\",43,75,1), (\"notecase\",22,80,1), (\"sunglasses\",7,20,1), (\"towel\",18,12,2),\n\t(\"socks\",4,50,1), (\"book\",30,10,2)]\n\nknapsack = foldr addItem (repeat (0,[])) where\n\taddItem (name,w,v,c) old = foldr inc old [1..c] where\n\t\tinc i list = left ++ zipWith max right new where\n\t\t\t(left, right) = splitAt (w * i) list\n\t\t\tnew = map (\\(val,itms)->(val + v * i, (name,i):itms)) old\n\nmain = print $ (knapsack inv) !! 400\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, without exceeding a total weight of 4 kg. It maximizes the total value of the items, considering the weight, value, and quantity of each item. The items cannot be divided, only whole units can be taken. The code uses a cache for faster and easier lookup.","id":4319}
    {"lang_cluster":"Haskell","source_code":"\nimport Prelude hiding (catch)\nimport Control.Exception (catch, throwIO, AsyncException(UserInterrupt))\nimport Data.Time.Clock (getCurrentTime, diffUTCTime)\nimport Control.Concurrent (threadDelay)\n\nmain = do t0 <- getCurrentTime\n          catch (loop 0)\n                (\\e -> if e == UserInterrupt\n                         then do t1 <- getCurrentTime\n                                 putStrLn (\"\\nTime: \" ++ show (diffUTCTime t1 t0))\n                         else throwIO e)\n\nloop i = do print i\n            threadDelay 500000 {- \u00b5s -}\n            loop (i + 1)\n\n","human_summarization":"an integer every half second. It handles SIGINT or SIGQUIT signals to stop outputting integers, display the program's runtime in seconds, and then terminate the program.","id":4320}
    {"lang_cluster":"Haskell","source_code":"\n(show . (+1) . read) \"1234\"\n\n\n(show . succ) (read \"1234\" :: Int)\n\nimport Text.Read (readMaybe)\nimport Data.Maybe (mapMaybe)\n\nsuccString :: Bool -> String -> String\nsuccString pruned s =\n  let succs\n        :: (Num a, Show a)\n        => a -> Maybe String\n      succs = Just . show . (1 +)\n      go w\n        | elem '.' w = (readMaybe w :: Maybe Double) >>= succs\n        | otherwise = (readMaybe w :: Maybe Integer) >>= succs\n      opt w\n        | pruned = Nothing\n        | otherwise = Just w\n  in unwords $\n     mapMaybe\n       (\\w ->\n           case go w of\n             Just s -> Just s\n             _ -> opt w)\n       (words s)\n\n\n-- TEST ---------------------------------------------------\nmain :: IO ()\nmain =\n  (putStrLn . unlines) $\n  succString <$> [True, False] <*>\n  pure \"41.0 pine martens in 1491 -1.5 mushrooms \u2260 136\"\n\n\n","human_summarization":"\"Increments a numerical string, supports both floating point and integral numeric strings, handles multiple numeric expressions within a single string, and provides an option to retain or remove non-numeric noise. For integral values, the 'succ' function from Prelude is used.\"","id":4321}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List\n\n-- Return the common prefix of two lists.\ncommonPrefix2 (x:xs) (y:ys) | x == y = x : commonPrefix2 xs ys\ncommonPrefix2 _ _ = []\n\n-- Return the common prefix of zero or more lists.\ncommonPrefix (xs:xss) = foldr commonPrefix2 xs xss\ncommonPrefix _ = []\n\n-- Split a string into path components.\nsplitPath = groupBy (\\_ c -> c \/= '\/')\n\n-- Return the common prefix of zero or more paths.\n-- Note that '\/' by itself is not considered a path component,\n-- so \"\/\" and \"\/foo\" are treated as having nothing in common.\ncommonDirPath = concat . commonPrefix . map splitPath\n\nmain = putStrLn $ commonDirPath [\n        \"\/home\/user1\/tmp\/coverage\/test\",\n        \"\/home\/user1\/tmp\/covert\/operator\",\n        \"\/home\/user1\/tmp\/coven\/members\"\n       ]\n\n\nimport Data.List (transpose, intercalate)\nimport Data.List.Split (splitOn)\n\n\n------------------ COMMON DIRECTORY PATH -----------------\n\ncommonDirectoryPath :: [String] -> String\ncommonDirectoryPath [] = []\ncommonDirectoryPath xs =\n  intercalate \"\/\" $\n  head <$> takeWhile ((all . (==) . head) <*> tail) $\n  transpose (splitOn \"\/\" <$> xs)\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n  (putStrLn . commonDirectoryPath)\n    [ \"\/home\/user1\/tmp\/coverage\/test\"\n    , \"\/home\/user1\/tmp\/covert\/operator\"\n    , \"\/home\/user1\/tmp\/coven\/members\"\n    ]\n\n\n","human_summarization":"\"Output: The code creates a routine that finds and returns the common directory path from a set of given directory paths, using a specified directory separator. The routine is tested with '\/' as the separator and three specific strings as input paths. The code also identifies if there's an existing function in the language used that performs this task.\"","id":4322}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad ((>=>), (>>=), forM_)\nimport Control.Monad.Primitive\nimport qualified Data.Vector as V\nimport qualified Data.Vector.Mutable as M\nimport System.Random.MWC\n\ntype MutVec m a = M.MVector (PrimState m) a\n\n-- Perform an in-place shuffle of the vector, making it a single random cyclic\n-- permutation of its initial value.  The vector is also returned for\n-- convenience.\ncyclicPermM :: PrimMonad m => Gen (PrimState m) -> MutVec m a -> m (MutVec m a)\ncyclicPermM rand vec = forM_ [1..M.length vec-1] upd >> return vec\n  where upd i = uniformR (0, i-1) rand >>= M.swap vec i\n\n-- Return a vector that is a single random cyclic permutation of the argument.\ncyclicPerm :: PrimMonad m => Gen (PrimState m) -> V.Vector a -> m (V.Vector a)\ncyclicPerm rand = V.thaw >=> cyclicPermM rand >=> V.unsafeFreeze\n\n--------------------------------------------------------------------------------\n\ntest :: Show a => [a] -> IO ()\ntest xs = do\n  let orig = V.fromList xs\n  cyc <- withSystemRandom . asGenIO $ \\rand -> cyclicPerm rand orig\n  putStrLn $ \"original: \" ++ show orig\n  putStrLn $ \"  cycled: \" ++ show cyc\n\nmain :: IO ()\nmain = do\n  test ([] :: [()])\n  test [10 :: Int]\n  test [10, 20 :: Int]\n  test [10, 20, 30 :: Int]\n  test [11..22 :: Int]\n  -- Also works for other types.\n  test \"abcdef\"\n\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":4323}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List (partition)\n\nnth :: Ord t => [t] -> Int -> t\nnth (x:xs) n\n  | k == n = x\n  | k > n = nth ys n\n  | otherwise = nth zs $ n - k - 1\n  where\n    (ys, zs) = partition (< x) xs\n    k = length ys\n\nmedianMay :: (Fractional a, Ord a) => [a] -> Maybe a\nmedianMay xs\n  | n < 1 = Nothing\n  | even n = Just ((nth xs (div n 2) + nth xs (div n 2 - 1)) \/ 2.0)\n  | otherwise = Just (nth xs (div n 2))\n  where\n    n = length xs\n\nmain :: IO ()\nmain =\n  mapM_\n    (printMay . medianMay)\n    [[], [7], [5, 3, 4], [5, 4, 2, 3], [3, 4, 1, -8.4, 7.2, 4, 1, 1.2]]\n  where\n    printMay = maybe (putStrLn \"(not defined)\") print\n\n\n","human_summarization":"\"Calculates the median value of a vector of floating-point numbers using the selection algorithm. Handles even number of elements by returning the average of the two middle values. The program does not handle empty vectors. It also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation.\"","id":4324}
    {"lang_cluster":"Haskell","source_code":"\n\nfizzbuzz\u00a0:: Int -> String\nfizzbuzz x\n  | f 15 = \"FizzBuzz\"\n  | f 3 = \"Fizz\"\n  | f 5 = \"Buzz\"\n  | otherwise = show x\n  where\n    f = (0 ==) . rem x\n\nmain\u00a0:: IO ()\nmain = mapM_ (putStrLn . fizzbuzz) [1 .. 100]\nfizzbuzz\u00a0:: Int -> String\nfizzbuzz n =\n  '\\n'\u00a0:\n  if null (fizz ++ buzz)\n    then show n\n    else fizz ++ buzz\n  where\n    fizz =\n      if mod n 3 == 0\n        then \"Fizz\"\n        else \"\"\n    buzz =\n      if mod n 5 == 0\n        then \"Buzz\"\n        else \"\"\n\nmain\u00a0:: IO ()\nmain = putStr $ concatMap fizzbuzz [1 .. 100]\n\nmain = mapM_ (putStrLn . fizzbuzz) [1..100]\n\nfizzbuzz n = \n    show n <|> [fizz| n `mod` 3 == 0] ++ \n               [buzz| n `mod` 5 == 0]\n\n-- A simple default choice operator. \n-- Defaults if both fizz and buzz fail, concats if any succeed.\ninfixr 0 <|>\nd <|> [] = d\n_ <|> x = concat x\n\nfizz = \"Fizz\"\nbuzz = \"Buzz\"\n\nmain = mapM_ putStrLn $ take 100 $ zipWith show_number_or_fizzbuzz [1..] fizz_buzz_list           \n\nshow_number_or_fizzbuzz x y = if null y then show x else y\n\nfizz_buzz_list = zipWith (++) (cycle [\"\",\"\",\"Fizz\"]) (cycle [\"\",\"\",\"\",\"\",\"Buzz\"])\n\nimport Control.Applicative ( ZipList(ZipList, getZipList) )\n\nfizzBuzz\u00a0:: [String]\nfizzBuzz =\n  getZipList $ go <$> \n    ZipList (cycle $ replicate 2 [] <> [\"fizz\"]) <*>\n    ZipList (cycle $ replicate 4 [] <> [\"buzz\"]) <*>\n    ZipList (show <$> [1 ..])\n\ngo\u00a0:: String -> String -> String -> String\ngo f b n\n  | null f && null b = n\n  | otherwise = f <> b\n\n\nmain\u00a0:: IO ()\nmain = mapM_ putStrLn $ take 100 fizzBuzz\n\nimport Data.Bool (bool)\n\nfizzBuzz\u00a0:: [String]\nfizzBuzz =\n  let fb n k = cycle $ replicate (pred n) [] <> [k]\n   in zipWith\n        (flip . bool <*> null)\n        (zipWith (<>) (fb 3 \"fizz\") (fb 5 \"buzz\"))\n        (show <$> [1 ..])\n\nmain\u00a0:: IO ()\nmain = mapM_ putStrLn $ take 100 fizzBuzz\n\nimport Control.Monad.State\nimport Control.Monad.Trans\nimport Control.Monad.Writer\n\nmain = putStr $ execWriter $ mapM_ (flip execStateT True . fizzbuzz) [1..100]\n\nfizzbuzz\u00a0:: Int -> StateT Bool (Writer String) ()\nfizzbuzz x = do\n when (x `mod` 3 == 0) $ tell \"Fizz\" >> put False\n when (x `mod` 5 == 0) $ tell \"Buzz\" >> put False\n get >>= (flip when $ tell $ show x)\n tell \"\\n\"\n\nfizzBuzz\u00a0:: (Integral a) => a -> String\nfizzBuzz i\n  | fizz && buzz = \"FizzBuzz\"\n  | fizz         = \"Fizz\"\n  | buzz         = \"Buzz\"\n  | otherwise    = show i\n  where fizz = i `mod` 3 == 0\n        buzz = i `mod` 5 == 0\n\nmain = mapM_ (putStrLn . fizzBuzz) [1..100]\n\nimport Data.Monoid\n\nfizzbuzz = max\n       <$> show\n       <*> \"fizz\" `when` divisibleBy 3\n       <>  \"buzz\" `when` divisibleBy 5\n       <>  \"quxx\" `when` divisibleBy 7\n  where\n    when m p x = if p x then m else mempty\n    divisibleBy n x = x `mod` n == 0\n\nmain = mapM_ (putStrLn . fizzbuzz) [1..100]\n\nfizzbuzz n = case (rem n 3, rem n 5) of\n               (0, 0) -> \"FizzBuzz\"\n               (0, _) -> \"Fizz\"\n               (_, 0) -> \"Buzz\"\n               (_, _) -> show n\n\nmain = mapM_ (putStrLn . fizzbuzz) [1..100]\n\nwordthing\u00a0:: [(Int, String)] -> Int -> String\nwordthing lst n =\n  if matches == [] then\n    show n\n  else\n    concat $ map snd matches\n  where matches = filter (\\x -> n `mod` (fst x) == 0) lst\n\nfizzbuzz\u00a0:: Int -> String\nfizzbuzz = wordthing [(3, \"Fizz\"), (5, \"Buzz\")]\n\nmain = do\n  mapM_ (putStrLn . fizzbuzz) [1..100]\n","human_summarization":"print the numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":4325}
    {"lang_cluster":"Haskell","source_code":"import Data.Bool ( bool )\nimport Data.Complex (Complex ((:+)), magnitude)\n\nmandelbrot :: RealFloat a => Complex a -> Complex a\nmandelbrot a = iterate ((a +) . (^ 2)) 0 !! 50\n\nmain :: IO ()\nmain =\n  mapM_\n    putStrLn\n    [ [ bool ' ' '*' (2 > magnitude (mandelbrot (x :+ y)))\n        | x <- [-2, -1.9685 .. 0.5]\n      ]\n      | y <- [1, 0.95 .. -1]\n    ]\n\n\n","human_summarization":"generate and draw the Mandelbrot set using various algorithms and functions.","id":4326}
    {"lang_cluster":"Haskell","source_code":"\n\nvalues = [1..10]\n\ns = sum values           -- the easy way\np = product values\n\ns1 = foldl (+) 0 values  -- the hard way\np1 = foldl (*) 1 values\n\n\nimport Data.Array\n\nvalues = listArray (1,10) [1..10]\n\ns = sum . elems $ values\np = product . elems $ values\n\n\nimport Data.Array (listArray, elems)\n\nmain :: IO ()\nmain = mapM_ print $ [sum, product] <*> [elems $ listArray (1, 10) [11 .. 20]]\n\n\n","human_summarization":"Computes the sum and product of an array of integers by converting it to a list.","id":4327}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List\nimport Control.Monad\nimport Control.Arrow\n\nleaptext x b | b = show x ++ \" is a leap year\"\n\t     | otherwise = show x ++  \" is not a leap year\"\n\nisleapsf j | 0==j`mod`100 = 0 == j`mod`400\n\t   | otherwise    = 0 == j`mod`4\n\n\nisleap = foldl1 ((&&).not).flip map [400, 100, 4]. ((0==).).mod\n\n\n*Main> mapM_ (putStrLn. (ap leaptext isleap)) [1900,1994,1996,1997,2000]\n1900 is not a leap year\n1994 is not a leap year\n1996 is a leap year\n1997 is not a leap year\n2000 is a leap year\n\n\nimport Test.HUnit\n\nisLeapYear::Int->Bool\nisLeapYear y\n  | mod y 400 == 0 = True\n  | mod y 100 == 0 = False\n  | mod y 4 == 0 = True\n  | otherwise = False \n\ntests = TestList[TestCase $ assertEqual \"4 is a leap year\" True $ isLeapYear 4\n                ,TestCase $ assertEqual \"1 is not a leap year\" False $ isLeapYear 1\n                ,TestCase $ assertEqual \"64 is a leap year\" True $ isLeapYear 64\n                ,TestCase $ assertEqual \"2000 is a leap year\" True $ isLeapYear 2000\n                ,TestCase $ assertEqual \"1900 is not a leap year\" False $ isLeapYear 1900]\n\n","human_summarization":"determine if a specified year is a leap year in the Gregorian calendar.","id":4328}
    {"lang_cluster":"Haskell","source_code":"\n-- To compile into an executable:\n-- ghc -main-is OneTimePad OneTimePad.hs\n-- To run:\n-- .\/OneTimePad --help\n\nmodule OneTimePad (main) where\n\nimport           Control.Monad\nimport           Data.Char\nimport           Data.Function         (on)\nimport qualified Data.Text             as T\nimport qualified Data.Text.IO          as TI\nimport           Data.Time\nimport           System.Console.GetOpt\nimport           System.Environment\nimport           System.Exit\nimport           System.IO\n\n-- Command-line options parsing\ndata Options = Options  { optCommand :: String\n                        , optInput   :: IO T.Text\n                        , optOutput  :: T.Text -> IO ()\n                        , optPad     :: (IO T.Text, T.Text -> IO ())\n                        , optLines   :: Int\n                        }\n\nstartOptions :: Options\nstartOptions = Options  { optCommand    = \"decrypt\"\n                        , optInput      = TI.getContents\n                        , optOutput     = TI.putStr\n                        , optPad        = (TI.getContents, TI.putStr)\n                        , optLines      = 0\n                        }\n\noptions :: [ OptDescr (Options -> IO Options) ]\noptions =\n    [ Option \"e\" [\"encrypt\"]\n        (NoArg\n            (\\opt -> return opt { optCommand = \"encrypt\" }))\n        \"Encrypt file\"\n    , Option \"d\" [\"decrypt\"]\n        (NoArg\n            (\\opt -> return opt { optCommand = \"decrypt\" }))\n        \"Decrypt file (default)\"\n    , Option \"g\" [\"generate\"]\n        (NoArg\n            (\\opt -> return opt { optCommand = \"generate\" }))\n        \"Generate a one-time pad\"\n    , Option \"i\" [\"input\"]\n        (ReqArg\n            (\\arg opt -> return opt { optInput = TI.readFile arg })\n            \"FILE\")\n        \"Input file (for decryption and encryption)\"\n    , Option \"o\" [\"output\"]\n        (ReqArg\n            (\\arg opt -> return opt { optOutput = TI.writeFile arg })\n            \"FILE\")\n        \"Output file (for generation, decryption, and encryption)\"\n    , Option \"p\" [\"pad\"]\n        (ReqArg\n            (\\arg opt -> return opt { optPad = (TI.readFile arg,\n                                                TI.writeFile arg) })\n            \"FILE\")\n        \"One-time pad to use (for decryption and encryption)\"\n    , Option \"l\" [\"lines\"]\n        (ReqArg\n            (\\arg opt -> return opt { optLines = read arg :: Int })\n            \"LINES\")\n        \"New one-time pad's length (in lines of 48 characters) (for generation)\"\n    , Option \"V\" [\"version\"]\n        (NoArg\n            (\\_ -> do\n                hPutStrLn stderr \"Version 0.01\"\n                exitWith ExitSuccess))\n        \"Print version\"\n    , Option \"h\" [\"help\"]\n        (NoArg\n            (\\_ -> do\n                prg <- getProgName\n                putStrLn \"usage: OneTimePad [-h] [-V] [--lines LINES] [-i FILE] [-o FILE] [-p FILE] [--encrypt | --decrypt | --generate]\"\n                hPutStrLn stderr (usageInfo prg options)\n                exitWith ExitSuccess))\n        \"Show this help message and exit\"\n    ]\n\nmain :: IO ()\nmain = do\n  args <- getArgs\n  let (actions, nonOptions, errors) = getOpt RequireOrder options args\n  opts <- Prelude.foldl (>>=) (return startOptions) actions\n  let Options { optCommand = command\n              , optInput   = input\n              , optOutput  = output\n              , optPad     = (inPad, outPad)\n              , optLines   = linecnt } = opts\n\n  case command of\n    \"generate\" -> generate linecnt output\n    \"encrypt\"  -> do\n      inputContents <- clean <$> input\n      padContents <- inPad\n      output $ format $ encrypt inputContents $ unformat $ T.concat\n        $ dropWhile (\\t -> T.head t == '-' || T.head t == '#')\n        $ T.lines padContents\n    \"decrypt\"  -> do\n      inputContents <- unformat <$> input\n      padContents <- inPad\n      output $ decrypt inputContents $ unformat $ T.concat\n        $ dropWhile (\\t -> T.head t == '-' || T.head t == '#')\n        $ T.lines padContents\n      let discardLines = ceiling\n            $ ((\/) `on` fromIntegral) (T.length inputContents) 48\n      outPad $ discard discardLines $ T.lines padContents\n\n{- | Discard used pad lines. Is only called at decryption to enable using the\nsame pad file for both encryption and decryption.\n-}\ndiscard :: Int -> [T.Text] -> T.Text\ndiscard 0 ts = T.unlines ts\ndiscard x (t:ts) = if (T.head t == '-' || T.head t == '#')\n  then T.unlines [t, (discard x ts)]\n  else T.unlines [(T.append (T.pack \"- \") t), (discard (x-1) ts)]\n\n{- | Clean the text from symbols that cannot be encrypted.\n-}\nclean :: T.Text -> T.Text\nclean = T.map toUpper . T.filter (\\c -> let oc = ord c\n                                   in oc >= 65 && oc <= 122\n                                   && (not $ oc >=91 && oc <= 96))\n\n{- | Format text (usually encrypted text) for pretty-printing it in a similar\nway to the example from Wikipedia (see Rosetta Code page for this task)\n-}\nformat :: T.Text -> T.Text\nformat = T.unlines . map (T.intercalate (T.pack \" \") . T.chunksOf 6)\n  . T.chunksOf 48\n\n{- | Unformat encrypted text, getting rid of characters that are irrelevant for\ndecryption.\n-}\nunformat :: T.Text -> T.Text\nunformat = T.filter (\\c -> c\/='\\n' && c\/=' ')\n\n{- | Generate a one-time pad and write it to file (specified as second\nparameter). Note: this only works on operating systems that have the\n\"\/dev\/random\" file.\n-}\ngenerate :: Int -> (T.Text -> IO ()) -> IO ()\ngenerate lines output = do\n  withBinaryFile \"\/dev\/random\" ReadMode\n    (\\handle -> do\n        contents <- replicateM (48 * lines) $ hGetChar handle\n        time <- getCurrentTime\n        output\n          $ T.unlines [ T.pack\n                        $ \"# OTP pad, generated by https:\/\/github.com\/kssytsrk\/one-time-pad on \"\n                        ++ show time\n                      , format $ T.pack\n                        $ map (chr . (65 +) . flip mod 26 . ord) contents\n                      ])\n\n-- Helper function for encryption\/decryption.\ncrypt :: (Int -> Int -> Int) -> T.Text -> T.Text -> T.Text\ncrypt f = T.zipWith ((chr .) . f `on` ord)\n\n-- Encrypt first parameter's contents, using the second parameter as a key.\nencrypt :: T.Text -> T.Text -> T.Text\nencrypt = crypt ((((+65) . flip mod 26 . subtract 130) .) . (+))\n\n-- Decrypt first parameter's contents, using the second parameter as a key.\ndecrypt :: T.Text -> T.Text -> T.Text\ndecrypt = crypt ((((+65) . flip mod 26) .) . (-))\n\n\n","human_summarization":"The code implements a One-time pad for encrypting and decrypting messages using only letters. It includes sub-tasks such as generating data for a One-time pad with user-specified filename and length, getting \"true random\" numbers, and encryption\/decryption operations similar to Rot-13. It also manages One-time pads by listing, marking as used, deleting, etc., and supports pad-files management. The code also includes a help message for generating a pad, encrypting and decrypting a message, and displaying the contents of the pad and encrypted and decrypted texts.","id":4329}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad (replicateM)\n\nimport qualified Data.ByteString.Lazy as BL\nimport qualified Data.ByteString.Lazy.Char8 as BLC\nimport Data.Binary.Get\nimport Data.Binary.Put\nimport Data.Bits\n\nimport Data.Array (Array, listArray, (!))\nimport Data.List (foldl)\nimport Data.Word (Word32)\n\nimport Numeric (showHex)\n\n\n-- functions\ntype Fun = Word32 -> Word32 -> Word32 -> Word32\n\nfunF, funG, funH, funI :: Fun\nfunF x y z = (x .&. y) .|. (complement x .&. z)\nfunG x y z = (x .&. z) .|. (complement z .&. y)\nfunH x y z = x `xor` y `xor` z\nfunI x y z = y `xor` (complement z .|. x)\n\nidxF, idxG, idxH, idxI :: Int -> Int\nidxF i = i\nidxG i = (5 * i + 1) `mod` 16\nidxH i = (3 * i + 5) `mod` 16\nidxI i = 7 * i `mod` 16\n\n\n-- arrays\nfunA :: Array Int Fun\nfunA = listArray (1,64) $ replicate 16 =<< [funF, funG, funH, funI]\n\nidxA :: Array Int Int\nidxA = listArray (1,64) $ zipWith ($) (replicate 16 =<< [idxF, idxG, idxH, idxI]) [0..63]\n\nrotA :: Array Int Int\nrotA = listArray (1,64) $ concat . replicate 4 =<<\n       [[7, 12, 17, 22], [5, 9, 14, 20], [4, 11, 16, 23], [6, 10, 15, 21]]\n\nsinA :: Array Int Word32\nsinA = listArray (1,64) $ map (floor . (*mult) . abs . sin) [1..64]\n    where mult = 2 ** 32 :: Double\n\n\n-- to lazily calculate MD5 sum for standart input:\n-- main = putStrLn . md5sum =<< BL.getContents\n\nmain :: IO ()\nmain = mapM_ (putStrLn . md5sum . BLC.pack)\n        [ \"\" \n        , \"a\"\n        , \"abc\"\n        , \"message digest\"\n        , \"abcdefghijklmnopqrstuvwxyz\"\n        , \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\"\n        , \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"\n        ]\n\n\nmd5sum :: BL.ByteString -> String\nmd5sum input =\n    let MD5 a b c d = getMD5 initial `runGet` input\n    in  foldr hex [] . BL.unpack . runPut $ mapM_ putWord32le [a,b,c,d]\n    where\n      initial = MD5 0x67452301 0xEFCDAB89 0x98BADCFE 0x10325476\n\n      hex x s | x < 16    = '0' : showHex x s -- quick hack: like \"%02x\"\n              | otherwise =       showHex x s\n\n\ndata MD5 = MD5\n    { a :: {-# UNPACK #-} !Word32\n    , b :: {-# UNPACK #-} !Word32\n    , c :: {-# UNPACK #-} !Word32\n    , d :: {-# UNPACK #-} !Word32\n    }\n\n\ngetMD5 :: MD5 -> Get MD5\ngetMD5 md5 = do\n  chunk <- getLazyByteString 64\n  let len = BL.length chunk\n\n  if len == 64\n  then getMD5 $! md5 <+> chunk  -- apply and process next chunk\n\n  else do                       -- input is totally eaten, finalize\n    bytes <- bytesRead\n    let fin   = runPut . putWord64le $ fromIntegral (bytes - 64 + len) * 8\n        pad n = chunk `BL.append` (0x80 `BL.cons` BL.replicate (n - 1) 0x00)\n\n    return $ if len >= 56\n        then md5 <+> pad (64 - len) <+> BL.replicate 56 0x00 `BL.append` fin\n        else md5 <+> pad (56 - len) `BL.append` fin\n\n\n(<+>) :: MD5 -> BL.ByteString -> MD5\ninfixl 5  <+>\nmd5@(MD5 a b c d) <+> bs =\n    let datA = listArray (0,15) $ replicateM 16 getWord32le `runGet` bs\n        MD5 a' b' c' d' = foldl' (md5round datA) md5 [1..64]\n    in MD5 (a + a') (b + b') (c + c') (d + d')\n\n\nmd5round :: Array Int Word32 -> MD5 -> Int -> MD5\nmd5round datA (MD5 a b c d) i =\n    let f  =  funA ! i\n        w  =  datA ! (idxA ! i)\n        a' =  b + (a + f b c d + w + sinA ! i) `rotateL` rotA ! i\n    in MD5 d a' b c\n\n","human_summarization":"The code is an implementation of the MD5 Message Digest Algorithm, developed directly from the algorithm specification without using built-in or external hashing libraries. It produces a correct message digest for an input string but does not mimic all calling modes. The code also includes handling of bit manipulation, unsigned integers, and little-endian data, with attention to details like boundary conditions and padding. The implementation is validated against the verification strings and hashes from RFC 1321.","id":4330}
    {"lang_cluster":"Haskell","source_code":"\n\nmain :: IO ()\nmain =\n  mapM_ print $\n  [2, 4, 6] >>=\n  \\x ->\n     [1 .. 7] >>=\n     \\y ->\n        [12 - (x + y)] >>=\n        \\z ->\n           case y \/= z && 1 <= z && z <= 7 of\n             True -> [(x, y, z)]\n             _ -> []\n\n\nmain :: IO ()\nmain =\n  mapM_\n    print\n    [ (x, y, z)\n    | x <- [2, 4, 6] \n    , y <- [1 .. 7] \n    , z <- [12 - (x + y)] \n    , y \/= z && 1 <= z && z <= 7 ]\n\n\nmain :: IO ()\nmain =\n  mapM_ print $\n  do x <- [2, 4, 6]\n     y <- [1 .. 7]\n     z <- [12 - (x + y)]\n     if y \/= z && 1 <= z && z <= 7\n       then [(x, y, z)]\n       else []\n\n\nimport Data.List (nub)\n\nmain :: IO ()\nmain =\n  let xs = [1 .. 7]\n  in mapM_ print $\n     xs >>=\n     \\x ->\n        xs >>=\n        \\y ->\n           xs >>=\n           \\z ->\n              [ (x, y, z)\n              | even x && 3 == length (nub [x, y, z]) && 12 == sum [x, y, z] ]\n\n\n","human_summarization":"The code generates all valid combinations of department numbers for police, sanitation, and fire departments. The numbers range from 1 to 7, must be unique, and their sum should be 12. The police department number is always even.","id":4331}
    {"lang_cluster":"Haskell","source_code":"\n\nf 0 = 1\nf n | n > 0 = n - m (f $ n-1)\n\nm 0 = 0 \nm n | n > 0 = n - f (m $ n-1)\n \nmain = do\n       print $ map f [0..19]\n       print $ map m [0..19]\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions follow the defined rules: F(0) = 1, M(0) = 0, F(n) = n - M(F(n-1)) for n > 0, and M(n) = n - F(M(n-1)) for n > 0. If the programming language does not support mutual recursion, it should be stated instead of providing a solution by other means.","id":4332}
    {"lang_cluster":"Haskell","source_code":"\n\nimport System.Random (randomRIO)\n\npick :: [a] -> IO a\npick xs = fmap (xs !!) $ randomRIO (0, length xs - 1)\n\nx <- pick [1, 2, 3]\n\n\nimport Data.Random\nsample $ randomElement  [1, 2, 3]\n\n\ndo \n  x <- sample $ randomElement  [1, 2, 3]\n  print x\n\n","human_summarization":"demonstrate the functionality of a custom function that uses the random-fu library to pick a random element from a list.","id":4333}
    {"lang_cluster":"Haskell","source_code":"\nimport qualified Data.Char as Char\n\nurlDecode :: String -> Maybe String\nurlDecode [] = Just []\nurlDecode ('%':xs) =\n  case xs of\n    (a:b:xss) ->\n      urlDecode xss\n      >>= return . ((Char.chr . read $ \"0x\" ++ [a,b]) :)\n    _ -> Nothing\nurlDecode ('+':xs) = urlDecode xs >>= return . (' ' :)\nurlDecode (x:xs) = urlDecode xs >>= return . (x :)\n\nmain :: IO ()\nmain = putStrLn . maybe \"Bad decode\" id $ urlDecode \"http%3A%2F%2Ffoo%20bar%2F\"\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. The function handles various test cases including strings with special characters and percentages.","id":4334}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.Array (Array, Ix, (!), listArray, bounds)\n\n-- BINARY SEARCH --------------------------------------------------------------\nbSearch\n  :: Integral a\n  => (a -> Ordering) -> (a, a) -> Maybe a\nbSearch p (low, high)\n  | high < low = Nothing\n  | otherwise =\n    let mid = (low + high) `div` 2\n    in case p mid of\n         LT -> bSearch p (low, mid - 1)\n         GT -> bSearch p (mid + 1, high)\n         EQ -> Just mid\n\n-- Application to an array:\nbSearchArray\n  :: (Ix i, Integral i, Ord e)\n  => Array i e -> e -> Maybe i\nbSearchArray a x = bSearch (compare x . (a !)) (bounds a)\n\n-- TEST -----------------------------------------------------------------------\naxs\n  :: (Num i, Ix i)\n  => Array i String\naxs =\n  listArray\n    (0, 11)\n    [ \"alpha\"\n    , \"beta\"\n    , \"delta\"\n    , \"epsilon\"\n    , \"eta\"\n    , \"gamma\"\n    , \"iota\"\n    , \"kappa\"\n    , \"lambda\"\n    , \"mu\"\n    , \"theta\"\n    , \"zeta\"\n    ]\n\nmain :: IO ()\nmain =\n  let e = \"mu\"\n      found = bSearchArray axs e\n  in putStrLn $\n     '\\'' :\n     e ++\n     case found of\n       Nothing -> \"' Not found\"\n       Just x -> \"' found at index \" ++ show x\n\n\n","human_summarization":"implement a binary search algorithm that can find a specific number in a sorted integer array. The algorithm can be either recursive or iterative and will print the index of the number if found, or indicate if the number is not in the array. The binary search algorithm works by dividing the range of values into halves until the desired number is found. It also includes variations that handle multiple equal values and indicate the insertion point for a non-existent element. The code also ensures to avoid overflow bugs.","id":4335}
    {"lang_cluster":"Haskell","source_code":"\n\nimport System\nmain = getArgs >>= print\n\nmyprog a -h b c\n=> [\"a\",\"-h\",\"b\",\"c\"]\n\n","human_summarization":"The code retrieves the list of command-line arguments provided to the program using the getArgs function from the System module. It intelligently parses these arguments, and for programs that only print the arguments when run directly, it refers to the Scripted main. The example command line used is 'myprogram -c \"alpha beta\" -h \"gamma\"'. The program name is also considered in this process.","id":4336}
    {"lang_cluster":"Haskell","source_code":"\nLibrary: HGL\nimport Graphics.HGL.Draw.Monad (Graphic, )\nimport Graphics.HGL.Draw.Picture\nimport Graphics.HGL.Utils\nimport Graphics.HGL.Window\nimport Graphics.HGL.Run\n \nimport Control.Exception (bracket, )\nimport Control.Arrow\n \ntoInt = fromIntegral.round\n \npendulum = runGraphics $\n  bracket\n    (openWindowEx \"Pendulum animation task\" Nothing (600,400) DoubleBuffered (Just 30))\n    closeWindow\n    (\\w -> mapM_ ((\\ g -> setGraphic w g >> getWindowTick w).\n                    (\\ (x, y) -> overGraphic (line (300, 0) (x, y))\n                                    (ellipse (x - 12, y + 12) (x + 12, y - 12)) )) pts)\n where\n    dt = 1\/30\n    t = - pi\/4\n    l = 1\n    g = 9.812 \n    nextAVT (a,v,t) = (a', v', t + v' * dt) where\n        a' = - (g \/ l) * sin t\n        v' = v + a' * dt\n    pts = map (\\(_,t,_) -> (toInt.(300+).(300*).cos &&& toInt. (300*).sin) (pi\/2+0.6*t) )\n        $ iterate nextAVT (- (g \/ l) * sin t, t, 0)\n\n\n*Main> pendulum\n\nLibrary: Gloss\nimport Graphics.Gloss\n\n-- Initial conditions\ng_  = (-9.8)        :: Float    --Gravity acceleration\nv_0 = 0             :: Float    --Initial tangential speed\na_0 = 0 \/ 180 * pi  :: Float    --Initial angle\ndt  = 0.01          :: Float    --Time step\nt_f = 15            :: Float    --Final time for data logging\nl_  = 200           :: Float    --Rod length\n\n-- Define a type to represent the pendulum: \ntype Pendulum = (Float, Float, Float) -- (rod length, tangential speed, angle)\n\n-- Pendulum's initial state\ninitialstate :: Pendulum\ninitialstate = (l_, v_0, a_0)\n\n-- Step funtion: update pendulum to new position\nmovePendulum :: Float -> Pendulum -> Pendulum\nmovePendulum dt (l,v,a) = ( l , v_2 , a + v_2 \/ l * dt*10 )\n    where   v_2 = v + g_ * (cos a) * dt\n\n-- Convert from Pendulum to [Picture] for display\nrenderPendulum :: Pendulum -> [Picture]\nrenderPendulum (l,v,a) = map (uncurry Translate newOrigin)\n                            [ Line    [ ( 0 , 0 ) , ( l * (cos a), l * (sin a) ) ] \n                            , polygon [ ( 0 , 0 ) , ( -5 , 8.66 ) , ( 5 , 8.66 ) ]\n                            , Translate ( l * (cos a)) (l * (sin a)) (circleSolid (0.04*l_))\n                            , Translate (-1.1*l) (-1.3*l) (Scale 0.1 0.1 (Text currSpeed))\n                            , Translate (-1.1*l) (-1.3*l + 20) (Scale 0.1 0.1 (Text currAngle))\n                            ]\n    where   currSpeed = \"Speed (pixels\/s) = \" ++ (show v)\n            currAngle = \"Angle (deg) = \" ++ (show ( 90 + a \/ pi * 180 ) )\n\n-- New origin to beter display the animation\nnewOrigin = (0, l_ \/ 2)\n\n-- Calcule a proper window size (for angles between 0 and -pi)\nwindowSize :: (Int, Int)\nwindowSize = ( 300 + 2 * round (snd newOrigin)\n             , 200 + 2 * round (snd newOrigin) )\n\n-- Run simulation\nmain :: IO ()\nmain = do   --plotOnGNU\n            simulate window background fps initialstate render update\n                where   window      = InWindow \"Animate a pendulum\" windowSize (40, 40)\n                        background  = white         \n                        fps         = round (1\/dt)\n                        render xs   = pictures $ renderPendulum xs\n                        update _    = movePendulum\n\n","human_summarization":"simulate and animate a simple gravity pendulum model.","id":4337}
    {"lang_cluster":"Haskell","source_code":"\n\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Data.Aeson\nimport Data.Attoparsec (parseOnly)\nimport Data.Text\nimport qualified Data.ByteString.Lazy.Char8 as B\nimport qualified Data.ByteString.Char8 as S\n\ntestdoc = object [\n    \"foo\"   .= (1 :: Int),\n    \"bar\"   .= ([1.3, 1.6, 1.9] :: [Double]),\n    \"baz\"   .= (\"some string\" :: Text),\n    \"other\" .= object [\n        \"yes\" .= (\"sir\" :: Text)\n        ]\n    ]\n\nmain = do\n    let out = encode testdoc\n    B.putStrLn out\n    case parseOnly json (S.concat $ B.toChunks out) of\n        Left e -> error $ \"strange error re-parsing json: \" ++ (show e)\n        Right v | v \/= testdoc -> error \"documents not equal!\"\n        Right v | otherwise    -> print v\n\n\n{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}\nimport Data.Aeson\nimport Data.Aeson.TH\n\ndata Person = Person { firstName :: String\n                     , lastName  :: String\n                     , age :: Maybe Int\n                     } deriving (Show, Eq)\n\n$(deriveJSON defaultOptions ''Person)\n\nmain = do\n    let test1 = \"{\\\"firstName\\\":\\\"Bob\\\", \\\"lastName\\\":\\\"Smith\\\"}\"\n        test2 = \"{\\\"firstName\\\":\\\"Miles\\\", \\\"lastName\\\":\\\"Davis\\\", \\\"age\\\": 45}\"\n    print (decode test1 :: Maybe Person)\n    print (decode test2 :: Maybe Person)\n\n\n{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}\nimport Data.Aeson\nimport GHC.Generics\n\ndata Person = Person { firstName :: String\n                     , lastName  :: String\n                     , age :: Maybe Int\n                     } deriving (Show, Eq, Generic)\n\ninstance FromJSON Person\ninstance ToJSON Person\n\nmain = do\n    let test1 = \"{\\\"firstName\\\":\\\"Bob\\\", \\\"lastName\\\":\\\"Smith\\\"}\"\n        test2 = \"{\\\"firstName\\\":\\\"Miles\\\", \\\"lastName\\\":\\\"Davis\\\", \\\"age\\\": 45}\"\n    print (decode test1 :: Maybe Person)\n    print (decode test2 :: Maybe Person)\n\n","human_summarization":"The code uses the Aeson library to load a JSON string into a data structure, and also creates a new data structure, serializing it into JSON. It handles the absence of keys using Aeson with TemplateHaskell and GHC.Generics. The code ensures the JSON is valid and uses objects and arrays as appropriate for the language.","id":4338}
    {"lang_cluster":"Haskell","source_code":"\n\nn `nthRoot` x = fst $ until (uncurry(==)) (\\(_,x0) -> (x0,((n-1)*x0+x\/x0**(n-1))\/n)) (x,x\/n)\n\n\n*Main> 2 `nthRoot` 2\n1.414213562373095\n\n*Main> 5 `nthRoot` 34\n2.024397458499885\n\n*Main> 10 `nthRoot` (734^10)\n734.0\n\n*Main> 0.5 `nthRoot` 7\n49.0\n\nnthRoot :: Double -> Double -> Double\nnthRoot n x =\n  fst $\n  until\n    (uncurry (==))\n    (((,) <*> ((\/ n) . ((+) . (pn *) <*> (x \/) . (** pn)))) . snd)\n    (x, x \/ n)\n  where\n    pn = pred n\n\n-------------------------- TESTS --------------------------\nmain :: IO ()\nmain =\n  putStrLn $\n  fTable\n    \"Nth roots:\"\n    (\\(a, b) -> show a ++ \" `nthRoot` \" ++ show b)\n    show\n    (uncurry nthRoot)\n    [(2, 2), (5, 34), (10, 734 ^ 10), (0.5, 7)]\n\n-------------------- FORMAT OF RESULTS --------------------\nfTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String\nfTable s xShow fxShow f xs =\n  let w = maximum (length . xShow <$> xs)\n      rjust n c = drop . length <*> (replicate n c ++)\n  in unlines $\n     s : fmap (((++) . rjust w ' ' . xShow) <*> ((\"  ->  \" ++) . fxShow . f)) xs\n\n\n","human_summarization":"Implement the algorithm to compute the principal nth root of a positive real number A, as per the method explained on the Wikipedia page. The function stops when there's no difference between two successive values. The output is formatted.","id":4339}
    {"lang_cluster":"Haskell","source_code":"\nLibrary: network\nimport Network.BSD\nmain = do hostName <- getHostName\n          putStrLn hostName\n\n\nmodule GetHostName where\n\nimport Foreign.Marshal.Array ( allocaArray0, peekArray0 )\nimport Foreign.C.Types ( CInt(..), CSize(..) )\nimport Foreign.C.String ( CString, peekCString )\nimport Foreign.C.Error ( throwErrnoIfMinus1_ )\n\ngetHostName :: IO String\ngetHostName = do\n  let size = 256\n  allocaArray0 size $ \\ cstr -> do\n    throwErrnoIfMinus1_ \"getHostName\" $ c_gethostname cstr (fromIntegral size)\n    peekCString cstr\n\nforeign import ccall \"gethostname\" \n   c_gethostname :: CString -> CSize -> IO CInt\n\nmain = do hostName <- getHostName\n          putStrLn hostName\n\n","human_summarization":"Implement a routine to determine the hostname of the current system, without relying on the network package.","id":4340}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List (intercalate, unfoldr)\nimport Data.List.Split (chunksOf)\n\n--------------------- LEONARDO NUMBERS ---------------------\n-- L0 -> L1 -> Add number -> Series (infinite)\nleo :: Integer -> Integer -> Integer -> [Integer]\nleo l0 l1 d = unfoldr (\\(x, y) -> Just (x, (y, x + y + d))) (l0, l1)\n\nleonardo :: [Integer]\nleonardo = leo 1 1 1\n\nfibonacci :: [Integer]\nfibonacci = leo 0 1 0\n\n--------------------------- TEST ---------------------------\nmain :: IO ()\nmain =\n  (putStrLn . unlines)\n    [ \"First 25 default (1, 1, 1) Leonardo numbers:\\n\"\n    , f $ take 25 leonardo\n    , \"First 25 of the (0, 1, 0) Leonardo numbers (= Fibonacci numbers):\\n\"\n    , f $ take 25 fibonacci\n    ]\n  where\n    f = unlines . fmap (('\\t' :) . intercalate \",\") . chunksOf 16 . fmap show\n\n\n","human_summarization":"The code generates the first 25 Leonardo numbers, starting from L(0). It allows the specification of the first two Leonardo numbers [for L(0) and L(1)] and the addition number (with a default of 1). The code also displays the first 25 Leonardo numbers when 0 and 1 are specified for L(0) and L(1), and 0 for the addition number, which results in the Fibonacci numbers.","id":4341}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List (sort)\nimport Data.Char (isDigit)\nimport Data.Maybe (fromJust)\nimport Control.Monad (foldM)\nimport System.Random (randomRs, getStdGen)\nimport System.IO (hSetBuffering, stdout, BufferMode(NoBuffering))\n\nmain = do\n  hSetBuffering stdout NoBuffering\n  mapM_\n    putStrLn\n    [ \"THE 24 GAME\\n\"\n    , \"Given four digits in the range 1 to 9\"\n    , \"Use the +, -, *, and \/ operators in reverse polish notation\"\n    , \"To show how to make an answer of 24.\\n\"\n    ]\n  digits <- fmap (sort . take 4 . randomRs (1, 9)) getStdGen :: IO [Int]\n  putStrLn (\"Your digits: \" ++ unwords (fmap show digits))\n  guessLoop digits\n  where\n    guessLoop digits =\n      putStr \"Your expression: \" >> fmap (processGuess digits . words) getLine >>=\n      either (\\m -> putStrLn m >> guessLoop digits) putStrLn\n\nprocessGuess _ [] = Right \"\"\nprocessGuess digits xs\n  | not matches = Left \"Wrong digits used\"\n  where\n    matches = digits == (sort . fmap read $ filter (all isDigit) xs)\nprocessGuess digits xs = calc xs >>= check\n  where\n    check 24 = Right \"Correct\"\n    check x = Left (show (fromRational (x :: Rational)) ++ \" is wrong\")\n\n-- A Reverse Polish Notation calculator with full error handling\ncalc xs =\n  foldM simplify [] xs >>=\n  \\ns ->\n     (case ns of\n        [n] -> Right n\n        _ -> Left \"Too few operators\")\n\nsimplify (a:b:ns) s\n  | isOp s = Right ((fromJust $ lookup s ops) b a : ns)\nsimplify _ s\n  | isOp s = Left (\"Too few values before \" ++ s)\nsimplify ns s\n  | all isDigit s = Right (fromIntegral (read s) : ns)\nsimplify _ s = Left (\"Unrecognized symbol: \" ++ s)\n\nisOp v = elem v $ fmap fst ops\n\nops = [(\"+\", (+)), (\"-\", (-)), (\"*\", (*)), (\"\/\", (\/))]\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":4342}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List (group)\n\n-- Datatypes\ntype Encoded = [(Int, Char)] -- An encoded String with form [(times, char), ...]\n\ntype Decoded = String\n\n-- Takes a decoded string and returns an encoded list of tuples\nrlencode :: Decoded -> Encoded\nrlencode = fmap ((,) <$> length <*> head) . group\n\n-- Takes an encoded list of tuples and returns the associated decoded String\nrldecode :: Encoded -> Decoded\nrldecode = concatMap (uncurry replicate)\n\nmain :: IO ()\nmain = do\n  let input = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\n      -- Output encoded and decoded versions of input\n      encoded = rlencode input\n      decoded = rldecode encoded\n  putStrLn $ \"Encoded: \" <> show encoded <> \"\\nDecoded: \" <> show decoded\n\n\n","human_summarization":"implement a run-length encoding algorithm that compresses a string of uppercase characters by storing the length of repeated characters. It also provides a function to reverse the compression.","id":4343}
    {"lang_cluster":"Haskell","source_code":"\nimport System.IO\ns = \"hello\"\ns1 = s ++ \" literal\"\nmain = do putStrLn (s ++ \" literal\")\n          putStrLn s1\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":4344}
    {"lang_cluster":"Haskell","source_code":"\nimport qualified Data.Char as Char\nimport Text.Printf\n\nencode :: Char -> String\nencode c\n  | c == ' ' = \"+\"\n  | Char.isAlphaNum c || c `elem` \"-._~\" = [c]\n  | otherwise = printf \"%%%02X\" c\n\nurlEncode :: String -> String\nurlEncode = concatMap encode\n\nmain :: IO ()\nmain = putStrLn $ urlEncode \"http:\/\/foo bar\/\"\n\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":4345}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List (nub, sort)\n\n-------------------- COMMON SORTED LIST ------------------\n\ncommonSorted :: Ord a => [[a]] -> [a]\ncommonSorted = sort . nub . concat\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n  print $\n    commonSorted\n      [ [5, 1, 3, 8, 9, 4, 8, 7],\n        [3, 5, 9, 8, 4],\n        [1, 3, 7, 9]\n      ]\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":4346}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List (sortBy)\nimport Data.Ord (comparing)\nimport Text.Printf (printf)\nimport Control.Monad (forM_)\nimport Data.Ratio (numerator, denominator)\n\nmaxWgt :: Rational\nmaxWgt = 15\n\ndata Bounty = Bounty\n  { itemName :: String\n  , itemVal, itemWgt :: Rational\n  }\n\nitems :: [Bounty]\nitems =\n  [ Bounty \"beef\" 36 3.8\n  , Bounty \"pork\" 43 5.4\n  , Bounty \"ham\" 90 3.6\n  , Bounty \"greaves\" 45 2.4\n  , Bounty \"flitch\" 30 4.0\n  , Bounty \"brawn\" 56 2.5\n  , Bounty \"welt\" 67 3.7\n  , Bounty \"salami\" 95 3.0\n  , Bounty \"sausage\" 98 5.9\n  ]\n\nsolution :: [(Rational, Bounty)]\nsolution = g maxWgt $ sortBy (flip $ comparing f) items\n  where\n    g room (b@(Bounty _ _ w):bs) =\n      if w < room\n        then (w, b) : g (room - w) bs\n        else [(room, b)]\n    f (Bounty _ v w) = v \/ w\n\nmain :: IO ()\nmain = do\n  forM_ solution $ \\(w, b) -> printf \"%s kg of %s\\n\" (mixedNum w) (itemName b)\n  (printf \"Total value: %s\\n\" . mixedNum . sum) $ f <$> solution\n  where\n    f (w, Bounty _ v wtot) = v * (w \/ wtot)\n    mixedNum q =\n      if b == 0\n        then show a\n        else printf \"%d %d\/%d\" a (numerator b) (denominator b)\n      where\n        a = floor q\n        b = q - toEnum a\n\n\n","human_summarization":"implement a solution to the continuous knapsack problem. It uses a greedy algorithm to determine which items a thief should steal from a butcher's shop to maximize profit without exceeding a 15kg weight limit. The items can be cut, with their value decreasing proportionally to their weight.","id":4347}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List\n\ngroupon f x y = f x == f y\n\nmain = do\n  f <- readFile \".\/..\/Puzzels\/Rosetta\/unixdict.txt\"\n  let  words = lines f\n       wix = groupBy (groupon fst) . sort $ zip (map sort words) words\n       mxl = maximum $ map length wix\n  mapM_ (print . map snd) . filter ((==mxl).length) $ wix\n\n\n","human_summarization":"find the largest sets of anagrams from the word list provided at http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt. The process is optimized by packing the String lists of Chars to the Text type for faster sorting and grouping.","id":4348}
    {"lang_cluster":"Haskell","source_code":"\ninCarpet :: Int -> Int -> Bool\ninCarpet 0 _ = True\ninCarpet _ 0 = True\ninCarpet x y = not ((xr == 1) && (yr == 1)) && inCarpet xq yq\n  where ((xq, xr), (yq, yr)) = (x `divMod` 3, y `divMod` 3)\n\ncarpet :: Int -> [String]\ncarpet n = map\n            (zipWith\n              (\\x y -> if inCarpet x y then '#' else ' ')\n              [0..3^n-1]\n             . repeat)\n            [0..3^n-1]\n\nprintCarpet :: Int -> IO ()\nprintCarpet = mapM_ putStrLn . carpet\nnextCarpet :: [String] -> [String]\nnextCarpet carpet = border ++ map f carpet ++ border\n  where border = map (concat . replicate 3) carpet\n        f x = x ++ map (const ' ') x ++ x\n \nsierpinskiCarpet :: Int -> [String]\nsierpinskiCarpet n = iterate nextCarpet [\"#\"] !! n\n \nmain :: IO ()\nmain = mapM_ putStrLn $ sierpinskiCarpet 3\n\n\nmain :: IO ()\nmain = putStr . unlines . (!!3) $ iterate next [\"#\"]\n\nnext :: [String] -> [String]\nnext block = \n    block ! block  ! block\n              ++\n    block ! center ! block\n              ++\n    block ! block  ! block\n    where\n      (!)    = zipWith (++)\n      center = map (map $ const ' ') block\n\n\ncarpet :: Int -> String\ncarpet = unlines . (iterate weave [\"\u2588\u2588\"] !!)\n\nweave :: [String] -> [String]\nweave xs =\n  let f = zipWith (<>)\n      g = flip f\n   in concatMap\n        (g xs . f xs)\n        [ xs,\n          fmap (const ' ') <$> xs,\n          xs\n        ]\n\nmain :: IO ()\nmain = mapM_ (putStrLn . carpet) [0 .. 2]\n\n\ncarpet :: Int -> String\ncarpet = unlines . (iterate weave [\"\u2588\u2588\"] !!)\n\nweave :: [String] -> [String]\nweave =\n  let thread = zipWith (<>)\n   in ( (>>=)\n          . ( (:)\n                <*> ( ((:) . fmap (fmap (const ' ')))\n                        <*> return\n                    )\n            )\n      )\n        <*> ((.) <$> flip thread <*> thread)\n\nmain :: IO ()\nmain = mapM_ (putStrLn . carpet) [0 .. 2]\n\n\n","human_summarization":"generate an ASCII or graphical representation of a Sierpinski carpet of a given order N. The representation uses specific patterns of whitespace and non-whitespace characters. The character '#' is used as an example, but not strictly required.","id":4349}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List (group, insertBy, sort, sortBy)\nimport Control.Arrow ((&&&), second)\nimport Data.Ord (comparing)\n\ndata HTree a\n  = Leaf a\n  | Branch (HTree a)\n           (HTree a)\n  deriving (Show, Eq, Ord)\n\ntest :: String -> IO ()\ntest =\n  mapM_ (\\(a, b) -> putStrLn ('\\'' : a : (\"'\u00a0: \" ++ b))) .\n  serialize . huffmanTree . freq\n\nserialize :: HTree a -> [(a, String)]\nserialize (Branch l r) =\n  (second ('0' :) <$> serialize l) ++ (second ('1' :) <$> serialize r)\nserialize (Leaf x) = [(x, \"\")]\n\nhuffmanTree\n  :: (Ord w, Num w)\n  => [(w, a)] -> HTree a\nhuffmanTree =\n  snd .\n  head . until (null . tail) hstep . sortBy (comparing fst) . fmap (second Leaf)\n\nhstep\n  :: (Ord a, Num a)\n  => [(a, HTree b)] -> [(a, HTree b)]\nhstep ((w1, t1):(w2, t2):wts) =\n  insertBy (comparing fst) (w1 + w2, Branch t1 t2) wts\n\nfreq\n  :: Ord a\n  => [a] -> [(Int, a)]\nfreq = fmap (length &&& head) . group . sort\n\nmain :: IO ()\nmain = test \"this is an example for huffman encoding\"\n\n\n","human_summarization":"The code generates Huffman encoding for each character in a given string. It first creates a priority queue with a leaf node for each character symbol. Then, it constructs a binary tree by continuously removing the two nodes with the highest priority (lowest probability) and creating a new internal node with these two nodes as children. The process continues until only one node (the root node) remains in the queue. The code then traverses the binary tree from root to leaves, assigning and accumulating '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf constitute the Huffman encoding for the corresponding character symbol.","id":4350}
    {"lang_cluster":"Haskell","source_code":"\nLibrary: Gtk from HackageDB\nimport Graphics.UI.Gtk\nimport Data.IORef\n\nmain :: IO ()\nmain = do\n  initGUI\n  window <- windowNew\n  window `onDestroy` mainQuit\n  windowSetTitle window \"Simple Windowed App\"\n  set window [ containerBorderWidth := 10 ]\n\n  hbox <- hBoxNew True 5\n\n  set window [ containerChild := hbox ]\n  \n  lab <- labelNew (Just \"There have been no clicks yet\")\n  button <- buttonNewWithLabel \"Click me\"\n  set hbox [ containerChild := lab ]\n  set hbox [ containerChild := button ]\n  \n  m <- newIORef 0\n\n  onClicked button $ do\n    v <- readIORef m\n    writeIORef m (v+1)\n    set lab [ labelText := \"There have been \" ++ show (v+1) ++ \" clicks\" ]\n\n  widgetShowAll window\n\n  mainGUI\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":4351}
    {"lang_cluster":"Haskell","source_code":"Library: SQLite\nLibrary: sqlite-simple\n{-# LANGUAGE OverloadedStrings #-}\n\nimport Database.SQLite.Simple\n\nmain = do\n     db <- open \"postal.db\"\n     execute_ db \"\\ \n     \\CREATE TABLE address (\\\n        \\addrID     INTEGER PRIMARY KEY AUTOINCREMENT, \\\n        \\addrStreet TEXT NOT NULL, \\\n        \\addrCity   TEXT NOT NULL, \\\n        \\addrState  TEXT NOT NULL, \\\n        \\addrZIP    TEXT NOT NULL  \\\n     \\)\"\n     close db\n\n","human_summarization":"create a table in a database to store US postal addresses, including fields for a unique identifier, street address, city, state code, and zipcode. The codes also demonstrate how to establish a database connection in non-database languages.","id":4352}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad\n\nmain :: IO ()\nmain = forM_ [10,9 .. 0] print\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":4353}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.Char\nimport Text.Printf\n\n-- Perform encryption or decryption, depending on f.\ncrypt f key = map toLetter . zipWith f (cycle key)\n  where toLetter = chr . (+) (ord 'A')\n\n-- Encrypt or decrypt one letter.\nenc k c = (ord k + ord c) `mod` 26\ndec k c = (ord c - ord k) `mod` 26\n\n-- Given a key, encrypt or decrypt an input string.\nencrypt = crypt enc\ndecrypt = crypt dec\n\n-- Convert a string to have only upper case letters.\nconvert = map toUpper . filter isLetter\n\nmain :: IO ()\nmain = do\n  let key  = \"VIGENERECIPHER\"\n      text = \"Beware the Jabberwock, my son! The jaws that bite, \"\n             ++ \"the claws that catch!\"\n      encr = encrypt key $ convert text\n      decr = decrypt key encr\n  printf \"    Input: %s\\n      Key: %s\\nEncrypted: %s\\nDecrypted: %s\\n\"\n    text key encr decr\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":4354}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad (forM_)\nmain = do forM_ [2,4..8] (\\x -> putStr (show x ++ \", \"))\n          putStrLn \"who do we appreciate?\"\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":4355}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad.ST\nimport Data.STRef\n\nsum_ :: STRef s Double -> Double -> Double \n     -> ST s Double -> ST s Double\nsum_ ref lo hi term = \n   do\n     vs <- forM [lo .. hi] \n            (\\k -> do { writeSTRef ref k\n                      ; term } )\n     return $ sum vs\n\nfoo :: Double\nfoo =\n  runST $\n  do ref <- newSTRef undefined\n          -- initial value doesn't matter\n     sum_ ref 1 100 $\n       do\n         k <- readSTRef ref\n         return $ recip k\n\nmain :: IO ()\nmain = print foo\n\n\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":4356}
    {"lang_cluster":"Haskell","source_code":"\nimport qualified Data.ByteString as BY (writeFile, pack)\n\nimport Data.Bits (xor)\n\nmain :: IO ()\nmain =\n  BY.writeFile\n    \"out.pgm\"\n    (BY.pack\n       (fmap (fromIntegral . fromEnum) \"P5\\n256 256\\n256\\n\" ++\n        [ x `xor` y\n        | x <- [0 .. 255] \n        , y <- [0 .. 255] ]))\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":4357}
    {"lang_cluster":"Haskell","source_code":"\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE TypeFamilies #-}\n\nimport Data.Array.ST\n       (STArray, freeze, newArray, readArray, writeArray)\nimport Data.STRef (STRef, newSTRef, readSTRef, writeSTRef)\nimport System.Random (Random(..), getStdGen, StdGen)\nimport Control.Monad (forM_, unless)\nimport Control.Monad.ST (ST, stToIO)\nimport Data.Array (Array, (!), bounds)\nimport Data.Bool (bool)\n\nrand\n  :: Random a\n  => (a, a) -> STRef s StdGen -> ST s a\nrand range gen = do\n  (a, g) <- randomR range <$> readSTRef gen\n  gen `writeSTRef` g\n  return a\n\ndata Maze = Maze\n  { rightWalls, belowWalls :: Array (Int, Int) Bool\n  }\n\nmaze :: Int -> Int -> StdGen -> ST s Maze\nmaze width height gen = do\n  visited <- mazeArray False\n  rWalls <- mazeArray True\n  bWalls <- mazeArray True\n  gen <- newSTRef gen\n  (,) <$> rand (0, maxX) gen <*> rand (0, maxY) gen >>=\n    visit gen visited rWalls bWalls\n  Maze <$> freeze rWalls <*> freeze bWalls\n  where\n    visit gen visited rWalls bWalls here = do\n      writeArray visited here True\n      let ns = neighbors here\n      i <- rand (0, length ns - 1) gen\n      forM_ (ns !! i : take i ns ++ drop (i + 1) ns) $\n        \\there -> do\n          seen <- readArray visited there\n          unless seen $\n            do removeWall here there\n               visit gen visited rWalls bWalls there\n      where\n        removeWall (x1, y1) (x2, y2) =\n          writeArray (bool rWalls bWalls (x1 == x2)) (min x1 x2, min y1 y2) False\n    neighbors (x, y) =\n      bool [(x - 1, y)] [] (0 == x) ++\n      bool [(x + 1, y)] [] (maxX == x) ++\n      bool [(x, y - 1)] [] (0 == y) ++ bool [(x, y + 1)] [] (maxY == y)\n    maxX = width - 1\n    maxY = height - 1\n    mazeArray =\n      newArray ((0, 0), (maxX, maxY)) :: Bool -> ST s (STArray s (Int, Int) Bool)\n\nprintMaze :: Maze -> IO ()\nprintMaze (Maze rWalls bWalls) = do\n  putStrLn $ '+' : concat (replicate (maxX + 1) \"---+\")\n  forM_ [0 .. maxY] $\n    \\y -> do\n      putStr \"|\"\n      forM_ [0 .. maxX] $\n        \\x -> do\n          putStr \"   \"\n          putStr $ bool \" \" \"|\" (rWalls ! (x, y))\n      putStrLn \"\"\n      forM_ [0 .. maxX] $\n        \\x -> do\n          putStr \"+\"\n          putStr $ bool \"   \" \"---\" (bWalls ! (x, y))\n      putStrLn \"+\"\n  where\n    maxX = fst (snd $ bounds rWalls)\n    maxY = snd (snd $ bounds rWalls)\n\nmain :: IO ()\nmain = getStdGen >>= stToIO . maze 11 8 >>= printMaze\n\n\nSample output:\n +---+---+---+---+---+---+---+---+---+---+---+\n |               |                           |\n +   +---+---+---+   +---+---+---+---+---+   +\n |               |           |   |       |   |\n +   +---+---+   +---+---+   +   +   +   +   +\n |   |   |       |           |       |   |   |\n +   +   +   +---+---+---+---+   +---+   +   +\n |       |   |                   |   |       |\n +---+---+   +   +---+---+---+---+   +---+---+\n |       |   |   |                       |   |\n +   +   +   +   +---+---+---+   +---+   +   +\n |   |       |   |               |       |   |\n +   +---+---+   +   +---+---+---+   +---+   +\n |               |       |           |       |\n +   +---+---+---+---+   +   +---+---+   +   +\n |                       |               |   |\n +---+---+---+---+---+---+---+---+---+---+---+\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":4358}
    {"lang_cluster":"Haskell","source_code":"\n\npi_ = g (1, 0, 1, 1, 3, 3)\n  where\n    g (q, r, t, k, n, l) =\n      if 4 * q + r - t < n * t\n        then n :\n             g\n               ( 10 * q\n               , 10 * (r - n * t)\n               , t\n               , k\n               , div (10 * (3 * q + r)) t - 10 * n\n               , l)\n        else g\n               ( q * k\n               , (2 * q + r) * l\n               , t * l\n               , k + 1\n               , div (q * (7 * k + 2) + r * l) (t * l)\n               , l + 2)\n\nWorks with: GHC version 7.4.1\n#!\/usr\/bin\/runhaskell\n\nimport Control.Monad\nimport System.IO\n\npi_ = g(1,0,1,1,3,3) where\n  g (q,r,t,k,n,l) =\n   if 4*q+r-t < n*t\n    then n : g (10*q, 10*(r-n*t), t, k, div (10*(3*q+r)) t - 10*n, l)\n    else g (q*k, (2*q+r)*l, t*l, k+1, div (q*(7*k+2)+r*l) (t*l), l+2)\n\ndigs = insertPoint digs'\n  where insertPoint (x:xs) = x:'.':xs\n        digs' = map (head . show) pi_\n\nmain = do\n  hSetBuffering stdout $ BlockBuffering $ Just 80\n  forM_ digs putChar\n\n\n","human_summarization":"The code continually calculates and outputs the next decimal digit of Pi. It runs indefinitely until manually stopped by the user. The output starts from the decimal sequence 3.14159265. The code is efficient as each term converges in less than one step, with a slight chance of incorrect digit if checked enough digits. The task is about calculating Pi, not using built-in constants.","id":4359}
    {"lang_cluster":"Haskell","source_code":"\n\nPrelude>  [1,2,1,3,2] < [1,2,0,4,4,0,0,0]\nFalse\n\n","human_summarization":"\"Function to compare and order two numerical lists based on lexicographic order, returning true if the first list should be ordered before the second, and false otherwise.\"","id":4360}
    {"lang_cluster":"Haskell","source_code":"\nack :: Int -> Int -> Int\nack 0 n = succ n\nack m 0 = ack (pred m) 1\nack m n = ack (pred m) (ack m (pred n))\n\nmain :: IO ()\nmain = mapM_ print $ uncurry ack <$> [(0, 0), (3, 4)]\n\n\n","human_summarization":"implement the Ackermann function, which is a non-primitive recursive function that takes two non-negative integers as arguments and returns a value based on the provided conditions. The function should ideally have arbitrary precision due to its rapid growth.","id":4361}
    {"lang_cluster":"Haskell","source_code":"\n\nThe Gamma and Beta function as described in 'Numerical Recipes in C++', the approximation is taken from [Lanczos, C. 1964 SIAM Journal on Numerical Analysis, ser. B, vol. 1, pp. 86-96]\ncof :: [Double]\ncof =\n  [ 76.18009172947146\n  , -86.50532032941677\n  , 24.01409824083091\n  , -1.231739572450155\n  , 0.001208650973866179\n  , -0.000005395239384953\n  ]\n\nser :: Double\nser = 1.000000000190015\n\ngammaln :: Double -> Double\ngammaln xx =\n  let tmp_ = (xx + 5.5) - (xx + 0.5) * log (xx + 5.5)\n      ser_ = ser + sum (zipWith (\/) cof [xx + 1 ..])\n  in -tmp_ + log (2.5066282746310005 * ser_ \/ xx)\n\nmain :: IO ()\nmain = mapM_ print $ gammaln <$> [0.1,0.2 .. 1.0]\n\n\nimport Control.Applicative\n\ncof :: [Double]\ncof =\n  [ 76.18009172947146\n  , -86.50532032941677\n  , 24.01409824083091\n  , -1.231739572450155\n  , 0.001208650973866179\n  , -0.000005395239384953\n  ]\n\ngammaln :: Double -> Double\ngammaln =\n  ((+) . negate . (((-) . (5.5 +)) <*> (((*) . (0.5 +)) <*> (log . (5.5 +))))) <*>\n  (log .\n   ((\/) =<<\n    (2.5066282746310007 *) .\n    (1.000000000190015 +) . sum . zipWith (\/) cof . enumFrom . (1 +)))\n\nmain :: IO ()\nmain = mapM_ print $ gammaln <$> [0.1,0.2 .. 1.0]\n\n\n","human_summarization":"implement one or more algorithms to compute the Gamma function in the real field. The implementation's results are compared with the built-in\/library function results. The Gamma function is computed through numerical integration, Lanczos approximation, or Stirling's approximation. The code also includes a point-free applicative expression.","id":4362}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad\nimport Data.List\n\n-- given n, \"queens n\" solves the n-queens problem, returning a list of all the\n-- safe arrangements. each solution is a list of the columns where the queens are\n-- located for each row\nqueens :: Int -> [[Int]]\nqueens n = map fst $ foldM oneMoreQueen ([],[1..n]) [1..n]  where \n\n  -- foldM\u00a0:: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a\n  -- foldM folds (from left to right) in the list monad, which is convenient for \n  -- \"nondeterminstically\" finding \"all possible solutions\" of something. the \n  -- initial value [] corresponds to the only safe arrangement of queens in 0 rows\n\n  -- given a safe arrangement y of queens in the first i rows, and a list of \n  -- possible choices, \"oneMoreQueen y _\" returns a list of all the safe \n  -- arrangements of queens in the first (i+1) rows along with remaining choices \n  oneMoreQueen (y,d) _ = [(x:y, delete x d) | x <- d, safe x]  where\n\n    -- \"safe x\" tests whether a queen at column x is safe from previous queens\n    safe x = and [x \/= c + n && x \/= c - n | (n,c) <- zip [1..] y]\n\n-- prints what the board looks like for a solution; with an extra newline\nprintSolution y = do\n     let n = length y\n     mapM_ (\\x -> putStrLn [if z == x then 'Q' else '.' | z <- [1..n]]) y\n     putStrLn \"\"\n\n-- prints all the solutions for 6 queens\nmain = mapM_ printSolution $ queens 6\n\n\nimport Control.Monad (foldM)\nimport Data.List ((\\\\))\n\nmain :: IO ()\nmain = mapM_ print $ queens 8\n\nqueens :: Int -> [[Int]]\nqueens n = foldM f [] [1..n]\n    where\n      f qs _ = [q:qs | q <- [1..n] \\\\ qs, q `notDiag` qs]\n      q `notDiag` qs = and [abs (q - qi) \/= i | (qi,i) <- qs `zip` [1..]]\n\n\nimport Data.List (nub, permutations)\n\n-- checks if queens are on the same diagonal\n-- with [0..] we place each queen on her own row\ncheck f = length . nub . zipWith f [0..]\n\n-- filters out results where 2 or more queens are on the same diagonal\n-- with [0..n-1] we place each queeen on her own column\ngenerate n = filter (\\x -> check (+) x == n && check (-) x == n) $ permutations [0..n-1]\n\n-- 8 is for \"8 queens\"\nmain = print $ generate 8\n\nimport Data.List (intercalate, transpose)\n\n--------------------- N QUEENS PROBLEM -------------------\n\nqueenPuzzle :: Int -> Int -> [[Int]]\nqueenPuzzle nRows nCols\n  | nRows <= 0 = [[]]\n  | otherwise =\n      foldr\n        (\\x y -> y <> foldr (go x) [] [1 .. nCols])\n        []\n        $ queenPuzzle (pred nRows) nCols\n  where\n    go qs iCol b\n      | safe (nRows - 1) iCol qs = b <> [qs <> [iCol]]\n      | otherwise = b\n\nsafe :: Int -> Int -> [Int] -> Bool\nsafe iRow iCol qs =\n  (not . or) $\n    zipWith\n      ( \\sc sr ->\n          (iCol == sc) || (sc + sr == (iCol + iRow))\n            || (sc - sr == (iCol - iRow))\n      )\n      qs\n      [0 .. iRow - 1]\n\n--------------------------- TEST -------------------------\n-- 10 columns of solutions for the 7*7 board:\nshowSolutions :: Int -> Int -> [String]\nshowSolutions nCols nSize =\n  unlines\n    . fmap (intercalate \"   \")\n    . transpose\n    . map boardLines\n    <$> chunksOf nCols (queenPuzzle nSize nSize)\n  where\n    go r x\n      | r == x = '\u265b'\n      | otherwise = '.'\n    boardLines rows =\n      [ go r <$> [1 .. (length rows)]\n        | r <- rows\n      ]\n\nchunksOf :: Int -> [a] -> [[a]]\nchunksOf i = splits\n  where\n    splits [] = []\n    splits l = take i l : splits (drop i l)\n\nmain :: IO ()\nmain = (putStrLn . unlines) $ showSolutions 10 7\n\n\n","human_summarization":"\"Code solves the N-queens problem, including the eight queens puzzle, by generating unique horizontal and vertical positions for each queen using permutations. It checks only diagonals for conflicts and includes a backtracking variant using Prelude's plain foldr. The code can also return just one solution by taking the head of the result, leveraging Haskell's laziness.\"","id":4363}
    {"lang_cluster":"Haskell","source_code":"\n\n(++) :: [a] -> [a] -> [a]\n\nAppend two lists, i.e.: \n[x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]\n[x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]\n\n[] ++ x = x\n(h:t) ++ y = h : (t ++ y)\n\n\nx ++ y = foldr (:) y x\n\n","human_summarization":"demonstrate how to concatenate two arrays in Haskell, using either explicit recursion or folding. The '++' operator is used for this task. If the first list is infinite, the output will be the first list.","id":4364}
    {"lang_cluster":"Haskell","source_code":"\n\ninv = [(\"map\",9,150), (\"compass\",13,35), (\"water\",153,200), (\"sandwich\",50,160),\n\t(\"glucose\",15,60), (\"tin\",68,45), (\"banana\",27,60), (\"apple\",39,40),\n\t(\"cheese\",23,30), (\"beer\",52,10), (\"cream\",11,70), (\"camera\",32,30),\n\t(\"tshirt\",24,15), (\"trousers\",48,10), (\"umbrella\",73,40), (\"trousers\",42,70),\n\t(\"overclothes\",43,75), (\"notecase\",22,80), (\"sunglasses\",7,20), (\"towel\",18,12),\n\t(\"socks\",4,50), (\"book\",30,10)]\n\n-- get all combos of items under total weight sum; returns value sum and list\ncombs [] _ = [ (0, []) ]\ncombs ((name,w,v):rest) cap = combs rest cap ++ \n\t\t      if w > cap then [] else map (prepend (name,w,v)) (combs rest (cap - w))\n\t\t      \twhere prepend (name,w,v) (v2, lst) = (v2 + v, (name,w,v):lst)\n\nmain = do\n\tputStr \"Total value: \"; print value\n\tmapM_ print items\n\t\twhere (value, items) = maximum $ combs inv 400\n\n\n","human_summarization":"The code implements a solution for the 0-1 Knapsack problem. It helps a tourist to determine the combination of items he can carry in his knapsack, with a weight limit of 4kg, in such a way that the total value of the items is maximized. The code considers a list of items with their respective weights and values, and uses a dynamic programming approach with a list for caching to find the optimal combination of items. The solution does not allow for cutting or diminishing the items, meaning only whole units of any item can be taken.","id":4365}
    {"lang_cluster":"Haskell","source_code":"\n\n{-# LANGUAGE TemplateHaskell #-}\nimport Lens.Micro\nimport Lens.Micro.TH\nimport Data.List (union, delete)\n\ntype Preferences a = (a, [a])\ntype Couple a = (a,a)\ndata State a = State { _freeGuys :: [a]\n                     , _guys :: [Preferences a]\n                     , _girls :: [Preferences a]}\n\nmakeLenses ''State\n\n\nname n = lens get set\n  where get = head . dropWhile ((\/= n).fst)\n        set assoc (_,v) = let (prev, _:post) = break ((== n).fst) assoc\n                      in prev ++ (n, v):post\n\nfianceesOf n = guys.name n._2\nfiancesOf n = girls.name n._2\n\n\n ^.  -- access to a field\n\u00a0%~  -- modification of a field\n .~  -- setting a field the value\n\n\nstableMatching :: Eq a => State a -> [Couple a]\nstableMatching = getPairs . until (null._freeGuys) step\n  where\n    getPairs s = map (_2 %~ head) $ s^.guys \n\nstep :: Eq a => State a -> State a\nstep s = foldl propose s (s^.freeGuys)\n  where\n    propose s guy =\n      let girl                = s^.fianceesOf guy & head\n          bestGuy : otherGuys = s^.fiancesOf girl\n          modify\n            | guy == bestGuy       = freeGuys %~ delete guy\n            | guy `elem` otherGuys = (fiancesOf girl %~ dropWhile (\/= guy)) .\n                                     (freeGuys %~ guy `replaceBy` bestGuy)\n            | otherwise            = fianceesOf guy %~ tail\n      in modify s\n\n    replaceBy x y [] = []\n    replaceBy x y (h:t) | h == x = y:t\n                        | otherwise = h:replaceBy x y t\n\nunstablePairs :: Eq a => State a -> [Couple a] -> [(Couple a, Couple a)]\nunstablePairs s pairs =\n  [ ((m1, w1), (m2,w2)) | (m1, w1) <- pairs\n                        , (m2,w2) <- pairs\n                        , m1 \/= m2\n                        , let fm = s^.fianceesOf m1\n                        , elemIndex w2 fm < elemIndex w1 fm\n                        , let fw = s^.fiancesOf w2\n                        , elemIndex m2 fw < elemIndex m1 fw ]\n\n\n\nguys0 =\n  [(\"abe\", [\"abi\", \"eve\", \"cath\", \"ivy\", \"jan\", \"dee\", \"fay\", \"bea\", \"hope\", \"gay\"]),\n   (\"bob\", [\"cath\", \"hope\", \"abi\", \"dee\", \"eve\", \"fay\", \"bea\", \"jan\", \"ivy\", \"gay\"]),\n   (\"col\", [\"hope\", \"eve\", \"abi\", \"dee\", \"bea\", \"fay\", \"ivy\", \"gay\", \"cath\", \"jan\"]),\n   (\"dan\", [\"ivy\", \"fay\", \"dee\", \"gay\", \"hope\", \"eve\", \"jan\", \"bea\", \"cath\", \"abi\"]),\n   (\"ed\",  [\"jan\", \"dee\", \"bea\", \"cath\", \"fay\", \"eve\", \"abi\", \"ivy\", \"hope\", \"gay\"]),\n   (\"fred\",[\"bea\", \"abi\", \"dee\", \"gay\", \"eve\", \"ivy\", \"cath\", \"jan\", \"hope\", \"fay\"]),\n   (\"gav\", [\"gay\", \"eve\", \"ivy\", \"bea\", \"cath\", \"abi\", \"dee\", \"hope\", \"jan\", \"fay\"]),\n   (\"hal\", [\"abi\", \"eve\", \"hope\", \"fay\", \"ivy\", \"cath\", \"jan\", \"bea\", \"gay\", \"dee\"]),\n   (\"ian\", [\"hope\", \"cath\", \"dee\", \"gay\", \"bea\", \"abi\", \"fay\", \"ivy\", \"jan\", \"eve\"]),\n   (\"jon\", [\"abi\", \"fay\", \"jan\", \"gay\", \"eve\", \"bea\", \"dee\", \"cath\", \"ivy\", \"hope\"])]\n  \ngirls0 = \n  [(\"abi\",  [\"bob\", \"fred\", \"jon\", \"gav\", \"ian\", \"abe\", \"dan\", \"ed\", \"col\", \"hal\"]),\n   (\"bea\",  [\"bob\", \"abe\", \"col\", \"fred\", \"gav\", \"dan\", \"ian\", \"ed\", \"jon\", \"hal\"]),\n   (\"cath\", [\"fred\", \"bob\", \"ed\", \"gav\", \"hal\", \"col\", \"ian\", \"abe\", \"dan\", \"jon\"]),\n   (\"dee\",  [\"fred\", \"jon\", \"col\", \"abe\", \"ian\", \"hal\", \"gav\", \"dan\", \"bob\", \"ed\"]),\n   (\"eve\",  [\"jon\", \"hal\", \"fred\", \"dan\", \"abe\", \"gav\", \"col\", \"ed\", \"ian\", \"bob\"]),\n   (\"fay\",  [\"bob\", \"abe\", \"ed\", \"ian\", \"jon\", \"dan\", \"fred\", \"gav\", \"col\", \"hal\"]),\n   (\"gay\",  [\"jon\", \"gav\", \"hal\", \"fred\", \"bob\", \"abe\", \"col\", \"ed\", \"dan\", \"ian\"]),\n   (\"hope\", [\"gav\", \"jon\", \"bob\", \"abe\", \"ian\", \"dan\", \"hal\", \"ed\", \"col\", \"fred\"]),\n   (\"ivy\",  [\"ian\", \"col\", \"hal\", \"gav\", \"fred\", \"bob\", \"abe\", \"ed\", \"jon\", \"dan\"]),\n   (\"jan\",  [\"ed\", \"hal\", \"gav\", \"abe\", \"bob\", \"jon\", \"col\", \"ian\", \"fred\", \"dan\"])]\n\n\ns0 = State (fst <$> guys0) guys0 ((_2 %~ reverse) <$> girls0)\n\n\n\u03bb> let pairs = stableMatching s0\n\u03bb> mapM_ print pairs\n(\"abe\",\"ivy\")\n(\"bob\",\"cath\")\n(\"col\",\"dee\")\n(\"dan\",\"fay\")\n(\"ed\",\"jan\")\n(\"fred\",\"bea\")\n(\"gav\",\"gay\")\n(\"hal\",\"eve\")\n(\"ian\",\"hope\")\n(\"jon\",\"abi\")\n\u03bb> unstablePairs s0 pairs\n[]\n\n\u03bb> let fiance n = name n._2\n\u03bb> let pairs' = pairs & (fiance \"abe\" .~ \"cath\") & (fiance \"bob\" .~ \"ivy\")\n\u03bb> mapM_ print $ unstablePairs s0 pairs'\n((\"bob\",\"ivy\"),(\"abe\",\"cath\"))\n((\"bob\",\"ivy\"),(\"dan\",\"fay\"))\n((\"bob\",\"ivy\"),(\"fred\",\"bea\"))\n((\"bob\",\"ivy\"),(\"ian\",\"hope\"))\n((\"bob\",\"ivy\"),(\"jon\",\"abi\"))\n","human_summarization":"The code implements the Gale\/Shapley algorithm to solve the Stable Marriage Problem. It takes as input a list of ten males and ten females, along with their ranked preferences for each other. The algorithm iteratively pairs the individuals in a way that no man prefers a woman over his current partner, and vice versa. The code also includes a functionality to perturb the stable set of engagements to form an unstable set, and then checks this new set for stability. The code uses lenses for easy access to elements of the state, which consists of the list of free individuals and their preference lists.","id":4366}
    {"lang_cluster":"Haskell","source_code":"\n\nmodule ShortCircuit where\n\nimport Prelude hiding ((&&), (||))\nimport Debug.Trace\n\nFalse && _     = False\nTrue  && False = False\n_     && _     = True\n\nTrue  || _     = True\nFalse || True  = True\n_     || _     = False\n\na p = trace (\"<a \" ++ show p ++ \">\") p\nb p = trace (\"<b \" ++ show p ++ \">\") p\n\nmain = mapM_ print (    [ a p || b q | p <- [False, True], q <- [False, True] ]\n                     ++ [ a p && b q | p <- [False, True], q <- [False, True] ])\n\n\n","human_summarization":"The code defines two functions, a and b, which both take and return the same boolean value while also printing their name when called. The code then calculates and assigns the values of two equations, x = a(i) and b(j) and y = a(i) or b(j), ensuring that function b is only called when necessary. This is achieved through short-circuit evaluation or, if not available, through nested if statements. The code also demonstrates the use of lazy evaluation and pattern matching to control the order of function execution.","id":4367}
    {"lang_cluster":"Haskell","source_code":"\n\nimport System.IO\nimport MorseCode\nimport MorsePlaySox\n\n-- Read standard input, converting text to Morse code, then playing the result.\n-- We turn off buffering on stdin so it will play as you type.\nmain = do\n  hSetBuffering stdin NoBuffering\n  text <- getContents\n  play $ toMorse text\n\n\nmodule MorseCode (Morse, MSym(..), toMorse) where\n\nimport Data.List\nimport Data.Maybe\nimport qualified Data.Map as M\n\ntype Morse = [MSym]\ndata MSym = Dot | Dash | SGap | CGap | WGap deriving (Show)\n\n-- Based on the table of International Morse Code letters and numerals at \n-- http:\/\/en.wikipedia.org\/wiki\/Morse_code.\ndict = M.fromList\n       [('a', m \".-\"   ), ('b', m \"-...\" ), ('c', m \"-.-.\" ), ('d', m \"-..\"  ),\n        ('e', m \".\"    ), ('f', m \"..-.\" ), ('g', m \"--.\"  ), ('h', m \"....\" ),\n        ('i', m \"..\"   ), ('j', m \".---\" ), ('k', m \"-.-\"  ), ('l', m \".-..\" ),\n        ('m', m \"--\"   ), ('n', m \"-.\"   ), ('o', m \"---\"  ), ('p', m \".--.\" ),\n        ('q', m \"--.-\" ), ('r', m \".-.\"  ), ('s', m \"...\"  ), ('t', m \"-\"    ),\n        ('u', m \"..-\"  ), ('v', m \"...-\" ), ('w', m \".--\"  ), ('x', m \"-..-\" ),\n        ('y', m \"-.--\" ), ('z', m \"--..\" ), ('1', m \".----\"), ('2', m \"..---\"), \n        ('3', m \"...--\"), ('4', m \"....-\"), ('5', m \".....\"), ('6', m \"-....\"), \n        ('7', m \"--...\"), ('8', m \"---..\"), ('9', m \"----.\"), ('0', m \"-----\")]\n    where m = intersperse SGap . map toSym\n          toSym '.' = Dot\n          toSym '-' = Dash\n\n-- Convert a string to a stream of Morse symbols.  We enhance the usual dots\n-- and dashes with special \"gap\" symbols, which indicate the border between\n-- symbols, characters and words.  This allows a player to easily adjust its\n-- timing by simply looking at the current symbol, rather than trying to keep\n-- track of state.\ntoMorse :: String -> Morse\ntoMorse = fromWords . words . weed\n    where fromWords = intercalate [WGap] . map fromWord\n          fromWord  = intercalate [CGap] . map fromChar\n          fromChar  = fromJust . flip M.lookup dict\n          weed      = filter (\\c -> c == ' ' || M.member c dict)\n\n\nmodule MorsePlaySox (play) where\n\nimport Sound.Sox.Play\nimport Sound.Sox.Option.Format\nimport Sound.Sox.Signal.List\nimport Data.Int\nimport System.Exit\nimport MorseCode\n\nsamps = 15           -- samples\/cycle\nfreq  = 700          -- cycles\/second (frequency)\nrate  = samps * freq -- samples\/second (sampling rate)\n\ntype Samples = [Int16]\n\n-- One cycle of silence and a sine wave.\nmute, sine :: Samples\nmute = replicate samps 0\nsine = let n = fromIntegral samps\n           f k = 8000.0 * sin (2*pi*k\/n)\n       in map (round . f . fromIntegral) [0..samps-1]\n\n-- Repeat samples until we have the specified duration in seconds.\nrep :: Float -> Samples -> Samples\nrep dur = take n . cycle\n    where n = round (dur * fromIntegral rate)\n\n-- Convert Morse symbols to samples.  Durations are in seconds, based on \n-- http:\/\/en.wikipedia.org\/wiki\/Morse_code#Representation.2C_timing_and_speeds.\ntoSamples :: MSym -> Samples\ntoSamples Dot  = rep 0.1 sine\ntoSamples Dash = rep 0.3 sine\ntoSamples SGap = rep 0.1 mute\ntoSamples CGap = rep 0.3 mute\ntoSamples WGap = rep 0.7 mute\n\n-- Interpret the stream of Morse symbols as sound.\nplay :: Morse -> IO ExitCode\nplay = simple put none rate . concatMap toSamples\n\n","human_summarization":"The code converts a given string into Morse code and outputs it as audible sound through an audio device. It handles unknown characters by either ignoring them or indicating them with a different pitch. The implementation relies on the \"play\" program of the SoX package. It includes modules for text-to-Morse code conversion and for interpreting Morse code symbols as sound.","id":4368}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.List (delete)\nimport Data.Char (toUpper)\n\n-- returns list of all solutions, each solution being a list of blocks\nabc :: (Eq a) => [[a]] -> [a] -> [[[a]]]\nabc _ [] = [[]]\nabc blocks (c:cs) = [b:ans | b <- blocks, c `elem` b,\n                             ans <- abc (delete b blocks) cs]\n\nblocks = [\"BO\", \"XK\", \"DQ\", \"CP\", \"NA\", \"GT\", \"RE\", \"TG\", \"QD\", \"FS\",\n          \"JW\", \"HU\", \"VI\", \"AN\", \"OB\", \"ER\", \"FS\", \"LY\", \"PC\", \"ZM\"]\n\nmain :: IO ()\nmain = mapM_ (\\w -> print (w, not . null $ abc blocks (map toUpper w)))\n         [\"\", \"A\", \"BARK\", \"BoOK\", \"TrEAT\", \"COmMoN\", \"SQUAD\", \"conFUsE\"]\n\n\n","human_summarization":"The code is a function that checks if a given word can be spelled using a specific set of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value indicating whether the word can be formed or not. The function also tests this functionality with seven example words.","id":4369}
    {"lang_cluster":"Haskell","source_code":"\n\nimport Data.Digest.OpenSSL.MD5 (md5sum)\nimport Data.ByteString (pack)\nimport Data.Char (ord)\n\nmain = do\n  let message = \"The quick brown fox jumped over the lazy dog's back\"\n      digest  = (md5sum . pack . map (fromIntegral . ord)) message\n  putStrLn digest\n\n\n*Main> main\ne38ca1d920c4b8b8d3946b2c72f01680\n\nLibrary: Cryptonite\n#!\/usr\/bin\/env runhaskell\n\nimport Data.ByteString.Char8 (pack)\nimport System.Environment (getArgs)\nimport Crypto.Hash\n\nmain :: IO ()\nmain = print . md5 . pack . unwords =<< getArgs\n         where md5 x = hash x :: Digest MD5\n\n\n","human_summarization":"The code implements the MD5 algorithm to encode a given string. It uses the nano-MD5 and ByteString modules from HackageDB and the Cryptonite package. The code also includes an optional validation feature by running test values from IETF RFC 1321. However, due to known weaknesses of MD5 such as collisions and forged signatures, it is recommended to consider stronger alternatives like SHA-256 or SHA-3 for production-grade cryptography.","id":4370}
    {"lang_cluster":"Haskell","source_code":"\nimport Data.List ( sort , intercalate ) \n\nsplitString :: Eq a => (a) -> [a] -> [[a]]\nsplitString c [] = []\nsplitString c s = let ( item , rest ) = break ( == c ) s\n                      ( _ , next ) = break ( \/= c ) rest\n\t\t  in item : splitString c next\n\nconvertIntListToString :: [Int] -> String\nconvertIntListToString = intercalate \".\" . map show\n\norderOID :: [String] -> [String]\norderOID = map convertIntListToString . sort . map ( map read . splitString '.' )\n\noid :: [String]\noid = [\"1.3.6.1.4.1.11.2.17.19.3.4.0.10\" ,\n    \"1.3.6.1.4.1.11.2.17.5.2.0.79\" ,\n    \"1.3.6.1.4.1.11.2.17.19.3.4.0.4\" ,\n    \"1.3.6.1.4.1.11150.3.4.0.1\" ,\n    \"1.3.6.1.4.1.11.2.17.19.3.4.0.1\" ,\n    \"1.3.6.1.4.1.11150.3.4.0\"]\n\nmain :: IO ( )\nmain = do\n   mapM_ putStrLn $ orderOID oid\n\n\n","human_summarization":"The code sorts a list of Object Identifiers (OIDs). OIDs are strings used to identify objects in network data, consisting of one or more non-negative integers in base 10, separated by dots. The sorting is done lexicographically with regard to the dot-separated fields, using numeric comparison between fields. The code uses the split function from the Data.List.Split library.","id":4371}
    {"lang_cluster":"Haskell","source_code":"\nimport Network\n\nmain = withSocketsDo $ sendTo \"localhost\" (PortNumber $ toEnum 256) \"hello socket world\"\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":4372}
    {"lang_cluster":"Haskell","source_code":"\n\n{-# LANGUAGE OverloadedStrings #-}\n\nmodule Main (main) where\n\nimport           Network.Mail.SMTP\n                    ( Address(..)\n                    , htmlPart\n                    , plainTextPart\n                    , sendMailWithLogin'\n                    , simpleMail\n                    )\n\nmain :: IO ()\nmain =\n    sendMailWithLogin' \"smtp.example.com\" 25 \"user\" \"password\" $\n        simpleMail\n            (Address (Just \"From Example\") \"from@example.com\")\n            [Address (Just \"To Example\") \"to@example.com\"]\n            [] -- CC\n            [] -- BCC\n            \"Subject\"\n            [ plainTextPart \"This is plain text.\"\n            , htmlPart \"<h1>Title<\/h1><p>This is HTML.<\/p>\"\n            ]\n\n","human_summarization":"implement a function to send an email with parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. The solution uses smtp-mail package and provides notifications for success or problems. It is portable across different operating systems.","id":4373}
    {"lang_cluster":"Haskell","source_code":"\nimport Numeric (showOct)\n\nmain :: IO ()\nmain =\n  mapM_\n    (putStrLn . flip showOct \"\")\n    [1 .. maxBound :: Int]\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":4374}
    {"lang_cluster":"Haskell","source_code":"\n\nswap :: (a, b) -> (b, a)\nswap (x, y) = (y, x)\n\n\n\nimport Control.Monad.Ref\nswap :: MonadRef r m => r a -> r a -> m ()\nswap xRef yRef = do \n   x<-readRef xRef\n   y<-readRef yRef\n   writeRef xRef y\n   writeRef yRef x\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, irrespective of their types. This function works with both statically and dynamically typed languages, with certain constraints for type compatibility. The function also handles issues related to programming language semantics, including difficulties with generic programming in some static languages and the need for indirection in dynamically typed languages. In functional languages, the function does not perform a destructive operation. The code also includes a function that swaps the contents of two mutable references.","id":4375}
    {"lang_cluster":"Haskell","source_code":"\n\nis_palindrome x = x == reverse x\n\n\nimport Data.Bifunctor (second)\nimport Data.Char (toLower)\n\n------------------- PALINDROME DETECTION -----------------\n\nisPalindrome :: Eq a => [a] -> Bool\nisPalindrome = (==) <*> reverse\n\n-- Or, comparing just the leftward characters with\n-- with a reflection of just the rightward characters.\n\nisPal :: String -> Bool\nisPal s =\n  let (q, r) = quotRem (length s) 2\n   in uncurry (==) $\n        second (reverse . drop r) $ splitAt q s\n\n--------------------------- TEST -------------------------\nmain :: IO ()\nmain =\n  mapM_ putStrLn $\n    (showResult <$> [isPalindrome, isPal])\n      <*> fmap\n        prepared\n        [ \"\",\n          \"a\",\n          \"ab\",\n          \"aba\",\n          \"abba\",\n          \"In girum imus nocte et consumimur igni\"\n        ]\n\nprepared :: String -> String\nprepared cs = [toLower c | c <- cs, ' ' \/= c]\n\nshowResult f s = (show s) <> \" -> \" <> show (f s)\n\n\n","human_summarization":"The code includes a function to check if a given sequence of characters is a palindrome. It supports Unicode characters and also has a second function to detect inexact palindromes, ignoring white-space, punctuation, and case differences. The palindrome detection is done both recursively and non-recursively. The non-recursive method involves reversing the string and comparing it with the original, while the recursive method is explained with reference to the C palindrome_r code.","id":4376}
    {"lang_cluster":"Haskell","source_code":"\nimport System.Environment\nmain = do getEnv \"HOME\" >>= print  -- get env var\n          getEnvironment >>= print -- get the entire environment as a list of (key, value) pairs\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":4377}
    {"lang_cluster":"Haskell","source_code":"\nimport Control.Monad.Memo (Memo, memo, startEvalMemo)\nimport Data.List.Split (chunksOf)\nimport System.Environment (getArgs)\nimport Text.Tabular (Header(..), Properties(..), Table(..))\nimport Text.Tabular.AsciiArt (render)\n\ntype SudanArgs = (Int, Integer, Integer)\n\n-- Given argument (n, x, y) calculate F\u2099(x, y).  For performance reasons we do\n-- the calculation in a memoization monad.\nsudan :: SudanArgs -> Memo SudanArgs Integer Integer\nsudan (0, x, y) = return $ x + y\nsudan (_, x, 0) = return x\nsudan (n, x, y) = memo sudan (n, x, y-1) >>= \\x2 -> sudan (n-1, x2, x2 + y)\n\n-- A table of F\u2099(x, y) values, where the rows are y values and the columns are\n-- x values.\nsudanTable :: Int -> [Integer] -> [Integer] -> String\nsudanTable n xs ys = render show show show\n                   $ Table (Group NoLine $ map Header ys)\n                           (Group NoLine $ map Header xs)\n                   $ chunksOf (length xs)\n                   $ startEvalMemo\n                   $ sequence\n                   $ [sudan (n, x, y) | y <- ys, x <- xs]\n\nmain :: IO ()\nmain = do\n  args <- getArgs\n  case args of\n    [n, xlo, xhi, ylo, yhi] -> do\n      putStrLn $ \"F\u2099(x, y), where the rows are y values \" ++\n                 \"and the columns are x values.\\n\"\n      putStr $ sudanTable (read n)\n                          [read xlo .. read xhi]\n                          [read ylo .. read yhi]\n    _ -> error \"Usage: sudan n xmin xmax ymin ymax\"\n\n\n","human_summarization":"Implement the Sudan function, a non-primitive recursive function. The function takes two arguments, x and y, and returns a value based on the defined recursive rules.","id":4378}
    {"lang_cluster":"Groovy","source_code":"\n\ndef stack = []\nassert stack.empty\n\nstack.push(55)\nstack.push(21)\nstack.push('kittens')\nassert stack.last() == 'kittens'\nassert stack.size() == 3\nassert ! stack.empty\n \nprintln stack\n\nassert stack.pop() == \"kittens\"\nassert stack.size() == 2\n\nprintln stack\n\nstack.push(-20)\n\nprintln stack\n\nstack.push( stack.pop() * stack.pop() )\nassert stack.last() == -420\nassert stack.size() == 2\n\nprintln stack\n\nstack.push(stack.pop() \/ stack.pop())\nassert stack.size() == 1\n\nprintln stack\n\nprintln stack.pop()\nassert stack.size() == 0\nassert stack.empty\n\ntry { stack.pop() } catch (NoSuchElementException e) { println e.message }\n\n\n","human_summarization":"implement a stack data structure with basic operations such as push, pop, and empty. The stack follows a last in, first out (LIFO) access policy and allows access to the last pushed element without modifying the stack. It also includes functionality to check if the stack is empty.","id":4379}
    {"lang_cluster":"Groovy","source_code":"\n\n\ndef rFib\nrFib = { \n    it == 0  \u00a0? 0 \n   \u00a0: it == 1\u00a0? 1 \n   \u00a0: it > 1 \u00a0? rFib(it-1) + rFib(it-2)\n    \/*it < 0*\/: rFib(it+2) - rFib(it+1)\n    \n}\ndef iFib = { \n    it == 0  \u00a0? 0 \n   \u00a0: it == 1\u00a0? 1 \n   \u00a0: it > 1 \u00a0? (2..it).inject([0,1]){i, j -> [i[1], i[0]+i[1]]}[1]\n    \/*it < 0*\/: (-1..it).inject([0,1]){i, j -> [i[1]-i[0], i[0]]}[0]\n}\nfinal \u03c6 = (1 + 5**(1\/2))\/2\ndef aFib = { (\u03c6**it - (-\u03c6)**(-it))\/(5**(1\/2)) as BigInteger }\n\ndef time = { Closure c ->\n    def start = System.currentTimeMillis()\n    def result = c()\n    def elapsedMS = (System.currentTimeMillis() - start)\/1000\n    printf '(%6.4fs elapsed)', elapsedMS\n    result\n}\n\nprint \"  F(n)      elapsed time   \"; (-10..10).each { printf ' %3d', it }; println()\nprint \"--------- -----------------\"; (-10..10).each { print ' ---' }; println()\n[recursive:rFib, iterative:iFib, analytic:aFib].each { name, fib ->\n    printf \"%9s \", name\n    def fibList = time { (-10..10).collect {fib(it)} }\n    fibList.each { printf ' %3d', it }\n    println()\n}\n\n","human_summarization":"The code implements a function to generate the nth Fibonacci number. It uses either an iterative or recursive approach, with the recursive method being potentially slower. The function also optionally supports negative n values by inversely applying the Fibonacci sequence formula. A recursive closure is pre-declared for full solutions.","id":4380}
    {"lang_cluster":"Groovy","source_code":"\n def evens = [1, 2, 3, 4, 5].findAll{it % 2 == 0}\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":4381}
    {"lang_cluster":"Groovy","source_code":"\n\ndef str = 'abcdefgh'\ndef n = 2\ndef m = 3\n\/\/ #1\nprintln str[n..n+m-1]\n\/* or *\/\nprintln str[n..<(n+m)]\n\/\/ #2\nprintln str[n..-1]\n\/\/ #3\nprintln str[0..-2]\n\/\/ #4\ndef index1 = str.indexOf('d')\nprintln str[index1..index1+m-1]\n\/* or *\/\nprintln str[index1..<(index1+m)]\n\/\/ #5\ndef index2 = str.indexOf('de')\nprintln str[index2..index2+m-1]\n\/* or *\/\nprintln str[index2..<(index2+m)]\n\n","human_summarization":"- Display a substring starting from a specified character index and of a specified length.\n- Display a substring starting from a specified character index to the end of the string.\n- Display the entire string except the last character.\n- Display a substring starting from a known character within the string and of a specified length.\n- Display a substring starting from a known substring within the string and of a specified length.\n- The code supports any valid Unicode code point in UTF-8 or UTF-16 encoding.\n- The code references logical characters, not 8-bit code units for UTF-8 or 16-bit code units for UTF-16.\n- The code does not necessarily support all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP.\n- Strings in the code are 0-indexed.","id":4382}
    {"lang_cluster":"Groovy","source_code":"\nprintln \"Able was I, 'ere I saw Elba.\".reverse()\n\n\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":4383}
    {"lang_cluster":"Groovy","source_code":"class Circles {\n    private static class Point {\n        private final double x, y\n\n        Point(Double x, Double y) {\n            this.x = x\n            this.y = y\n        }\n\n        double distanceFrom(Point other) {\n            double dx = x - other.x\n            double dy = y - other.y\n            return Math.sqrt(dx * dx + dy * dy)\n        }\n\n        @Override\n        boolean equals(Object other) {\n            \/\/if (this == other) return true\n            if (other == null || getClass() != other.getClass()) return false\n            Point point = (Point) other\n            return x == point.x && y == point.y\n        }\n\n        @Override\n        String toString() {\n            return String.format(\"(%.4f,\u00a0%.4f)\", x, y)\n        }\n    }\n\n    private static Point[] findCircles(Point p1, Point p2, double r) {\n        if (r < 0.0) throw new IllegalArgumentException(\"the radius can't be negative\")\n        if (r == 0.0.toDouble() && p1 != p2) throw new IllegalArgumentException(\"no circles can ever be drawn\")\n        if (r == 0.0.toDouble()) return [p1, p1]\n        if (Objects.equals(p1, p2)) throw new IllegalArgumentException(\"an infinite number of circles can be drawn\")\n        double distance = p1.distanceFrom(p2)\n        double diameter = 2.0 * r\n        if (distance > diameter) throw new IllegalArgumentException(\"the points are too far apart to draw a circle\")\n        Point center = new Point((p1.x + p2.x) \/ 2.0, (p1.y + p2.y) \/ 2.0)\n        if (distance == diameter) return [center, center]\n        double mirrorDistance = Math.sqrt(r * r - distance * distance \/ 4.0)\n        double dx = (p2.x - p1.x) * mirrorDistance \/ distance\n        double dy = (p2.y - p1.y) * mirrorDistance \/ distance\n        return [\n            new Point(center.x - dy, center.y + dx),\n            new Point(center.x + dy, center.y - dx)\n        ]\n    }\n\n    static void main(String[] args) {\n        Point[] p = [\n            new Point(0.1234, 0.9876),\n            new Point(0.8765, 0.2345),\n            new Point(0.0000, 2.0000),\n            new Point(0.0000, 0.0000)\n        ]\n        Point[][] points = [\n            [p[0], p[1]],\n            [p[2], p[3]],\n            [p[0], p[0]],\n            [p[0], p[1]],\n            [p[0], p[0]],\n        ]\n        double[] radii = [2.0, 1.0, 2.0, 0.5, 0.0]\n        for (int i = 0; i < radii.length; ++i) {\n            Point p1 = points[i][0]\n            Point p2 = points[i][1]\n            double r = radii[i]\n            printf(\"For points %s and %s with radius %f\\n\", p1, p2, r)\n            try {\n                Point[] circles = findCircles(p1, p2, r)\n                Point c1 = circles[0]\n                Point c2 = circles[1]\n                if (Objects.equals(c1, c2)) {\n                    printf(\"there is just one circle with center at %s\\n\", c1)\n                } else {\n                    printf(\"there are two circles with centers at %s and %s\\n\", c1, c2)\n                }\n            } catch (IllegalArgumentException ex) {\n                println(ex.getMessage())\n            }\n            println()\n        }\n    }\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":4384}
    {"lang_cluster":"Groovy","source_code":"\nfinal random = new Random()\n\nwhile (true) {\n    def random1 = random.nextInt(20)\n    print random1\n    if (random1 == 10) break\n    print '     '\n    println random.nextInt(20)\n}\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":4385}
    {"lang_cluster":"Groovy","source_code":"\ndef inventory = new XmlSlurper().parseText(\"<inventory...\")    \/\/optionally parseText(new File(\"inv.xml\").text)\ndef firstItem = inventory.section.item[0]                      \/\/1. first item\ninventory.section.item.price.each { println it }               \/\/2. print each price\ndef allNamesArray = inventory.section.item.name.collect {it}   \/\/3. collect item names into an array\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":4386}
    {"lang_cluster":"Groovy","source_code":"\ndef s1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as Set\ndef m1 = 6\ndef m2 = 7\ndef s2 = [0, 2, 4, 6, 8] as Set\nassert m1 in s1                                        : 'member'\nassert ! (m2 in s2)                                    : 'not a member'\ndef su = s1 + s2\nassert su == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as Set : 'union'\ndef si = s1.intersect(s2)\nassert si == [8, 6, 4, 2] as Set                       : 'intersection'\ndef sd = s1 - s2\nassert sd == [1, 3, 5, 7, 9, 10] as Set                : 'difference'\nassert s1.containsAll(si)                              : 'subset'\nassert ! s1.containsAll(s2)                            : 'not a subset'\nassert (si + sd) == s1                                 : 'equality'\nassert (s2 + sd) != s1                                 : 'inequality'\nassert s1 != su && su.containsAll(s1)                  : 'proper subset'\ns1 << 0\nassert s1 == su                                        : 'added element 0 to s1'\n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":4387}
    {"lang_cluster":"Groovy","source_code":"\n\ndef yuletide = { start, stop -> (start..stop).findAll { Date.parse(\"yyyy-MM-dd\", \"${it}-12-25\").format(\"EEE\") == \"Sun\" } }\n\n\nprintln yuletide(2008, 2121)\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas day falls on a Sunday, using standard date handling libraries. It also compares the results with outputs from other languages to identify any discrepancies due to issues like overflow in date\/time representation.","id":4388}
    {"lang_cluster":"Groovy","source_code":"\ndef list = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nassert list.size() == 12\nprintln \"             Original List: ${list}\"\n\n\/\/ Filtering the List (non-mutating)\ndef list2 = list.unique(false)\nassert list2.size() == 8\nassert list.size() == 12\nprintln \"             Filtered List: ${list2}\"\n\n\/\/ Filtering the List (in place)\nlist.unique()\nassert list.size() == 8\nprintln \"   Original List, filtered: ${list}\"\n\ndef list3 = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nassert list3.size() == 12\n\n\/\/ Converting to Set\ndef set = list as Set\nassert set.size() == 8\nprintln \"                       Set: ${set}\"\n\n\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":4389}
    {"lang_cluster":"Groovy","source_code":"\n\ndef isoFormat = { date -> date.format(\"yyyy-MM-dd\") }\ndef longFormat = { date -> date.format(\"EEEE, MMMM dd, yyyy\") }\n\n\ndef now = new Date()\nprintln isoFormat(now)\nprintln longFormat(now)\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":4390}
    {"lang_cluster":"Groovy","source_code":"\n\ndef powerSetRec(head, tail) {\n    if (!tail) return [head]\n    powerSetRec(head, tail.tail()) + powerSetRec(head + [tail.head()], tail.tail())\n}\n\ndef powerSet(set) { powerSetRec([], set as List) as Set}\n\n\ndef vocalists = [ 'C', 'S', 'N', 'Y' ] as Set\nprintln vocalists\nprintln powerSet(vocalists)\n\n\n","human_summarization":"The code is a function that takes a set S as input and returns the power set of S. The power set includes all possible subsets of S, including the empty set and the set itself. The function can handle edge cases such as the power set of an empty set and the power set of a set containing only the empty set. The code is written in Groovy and uses a combination of Set and List data structures for its implementation.","id":4391}
    {"lang_cluster":"Groovy","source_code":"\nsymbols = [ 1:'I', 4:'IV', 5:'V', 9:'IX', 10:'X', 40:'XL', 50:'L', 90:'XC', 100:'C', 400:'CD', 500:'D', 900:'CM', 1000:'M' ]\n\ndef roman(arabic) {\n    def result = \"\"\n    symbols.keySet().sort().reverse().each { \n        while (arabic >= it) {\n            arabic-=it\n            result+=symbols[it]\n        }\n    }\n    return result\n}\nassert roman(1) == 'I'\nassert roman(2) == 'II'\nassert roman(4) == 'IV'\nassert roman(8) == 'VIII'\nassert roman(16) == 'XVI'\nassert roman(32) == 'XXXII'\nassert roman(25) == 'XXV'\nassert roman(64) == 'LXIV'\nassert roman(128) == 'CXXVIII'\nassert roman(256) == 'CCLVI'\nassert roman(512) == 'DXII'\nassert roman(954) == 'CMLIV'\nassert roman(1024) == 'MXXIV'\nassert roman(1666) == 'MDCLXVI'\nassert roman(1990) == 'MCMXC'\nassert roman(2008) == 'MMVIII'\n\n","human_summarization":"create a function that converts a positive integer into its equivalent Roman numeral representation.","id":4392}
    {"lang_cluster":"Groovy","source_code":"\n\ndef aa = [ 1, 25, 31, -3 ]           \/\/ list\ndef a = [0] * 100                    \/\/ list of 100 zeroes\ndef b = 1..9                         \/\/ range notation\ndef c = (1..10).collect { 2.0**it }  \/\/ each output element is 2**(corresponding invoking list element)\n\n\/\/ There are no true \"multi-dimensional\" arrays in Groovy (as in most C-derived languages).\n\/\/ Use lists of lists in natural (\"row major\") order as a stand in.\ndef d = (0..1).collect { i -> (1..5).collect { j -> 2**(5*i+j) as double } }\ndef e = [ [  1.0,  2.0,  3.0,  4.0 ],\n          [  5.0,  6.0,  7.0,  8.0 ],\n          [  9.0, 10.0, 11.0, 12.0 ],\n          [ 13.0, 14.0, 15.0, 16.0 ] ]\n\nprintln aa\nprintln b\nprintln c\nprintln()\nd.each { print \"[\"; it.each { elt -> printf \"%7.1f \", elt }; println \"]\" }\nprintln()\ne.each { print \"[\"; it.each { elt -> printf \"%7.1f \", elt }; println \"]\" }\n\n","human_summarization":"demonstrate the basic syntax of arrays in Groovy, including creating an array, assigning a value, and retrieving an element. Both fixed-length and dynamic arrays are shown, with an example of pushing a value into an array. The code also includes a function that creates and returns a square identity matrix of order N. It highlights the use of zero-based array\/list indexing, the validity of negative indices, and the ability to resequence and subsequence Groovy lists by providing lists or ranges of indices.","id":4393}
    {"lang_cluster":"Groovy","source_code":"\n\ncontent = new File('input.txt').text\nnew File('output.txt').write(content)\n\n\nnew AntBuilder().copy(file:'input.txt', toFile:'output.txt', overwrite:true)\n\n\nnew File('output.txt').withWriter( w ->\n  new File('input.txt').withReader( r -> w << r }\n}\n\n","human_summarization":"demonstrate how to read the contents of \"input.txt\" file into an intermediate variable and then write those contents into a new file called \"output.txt\". It also shows how to use File, Ant, and Buffered methods. The code does not include oneliners that skip the intermediate variable.","id":4394}
    {"lang_cluster":"Groovy","source_code":"\ndef str = 'alphaBETA'\n\nprintln str.toUpperCase()\nprintln str.toLowerCase()\n\n\nALPHABETA\nalphabeta\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to both upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter, if available in the language's library. Note that in some languages, the conversion between lower and upper case may not be reversible.","id":4395}
    {"lang_cluster":"Groovy","source_code":"\n\nclass Point {\n    final Number x, y\n    Point(Number x = 0, Number y = 0) { this.x = x; this.y = y }\n    Number distance(Point that) { ((this.x - that.x)**2 + (this.y - that.y)**2)**0.5 }\n    String toString() { \"{x:${x}, y:${y}}\" } \n}\n\n\ndef bruteClosest(Collection pointCol) {\n    assert pointCol\n    List l = pointCol\n    int n = l.size()\n    assert n > 1\n    if (n == 2) return [distance:l[0].distance(l[1]), points:[l[0],l[1]]]\n    def answer = [distance: Double.POSITIVE_INFINITY]\n    (0..<(n-1)).each { i ->\n        ((i+1)..<n).findAll { j ->\n            (l[i].x - l[j].x).abs() < answer.distance &&\n            (l[i].y - l[j].y).abs() < answer.distance \n        }.each { j ->\n            if ((l[i].x - l[j].x).abs() < answer.distance &&\n                (l[i].y - l[j].y).abs() < answer.distance) {\n                def dist = l[i].distance(l[j])\n                if (dist < answer.distance) {\n                    answer = [distance:dist, points:[l[i],l[j]]]\n                }\n            }\n        }\n    }\n    answer\n}\n\n\ndef elegantClosest(Collection pointCol) {\n    assert pointCol\n    List xList = (pointCol as List).sort { it.x }\n    List yList = xList.clone().sort { it.y }\n    reductionClosest(xList, xList)\n}\n\ndef reductionClosest(List xPoints, List yPoints) {\n\/\/    assert xPoints && yPoints\n\/\/    assert (xPoints as Set) == (yPoints as Set)\n    int n = xPoints.size()\n    if (n < 10) return bruteClosest(xPoints)\n    \n    int nMid = Math.ceil(n\/2)\n    List xLeft = xPoints[0..<nMid]\n    List xRight = xPoints[nMid..<n]\n    Number xMid = xLeft[-1].x\n    List yLeft = yPoints.findAll { it.x <= xMid }\n    List yRight = yPoints.findAll { it.x > xMid }\n    if (xRight[0].x == xMid) {\n        yLeft = xLeft.collect{ it }.sort { it.y }\n        yRight = xRight.collect{ it }.sort { it.y }\n    }\n    \n    Map aLeft = reductionClosest(xLeft, yLeft)\n    Map aRight = reductionClosest(xRight, yRight)\n    Map aMin = aRight.distance < aLeft.distance ? aRight : aLeft\n    List yMid = yPoints.findAll { (xMid - it.x).abs() < aMin.distance }\n    int nyMid = yMid.size()\n    if (nyMid < 2) return aMin\n    \n    Map answer = aMin\n    (0..<(nyMid-1)).each { i ->\n        ((i+1)..<nyMid).findAll { j ->\n            (yMid[j].x - yMid[i].x).abs() < aMin.distance &&\n            (yMid[j].y - yMid[i].y).abs() < aMin.distance &&\n            yMid[j].distance(yMid[i]) < aMin.distance\n        }.each { k ->\n            if ((yMid[k].x - yMid[i].x).abs() < answer.distance && (yMid[k].y - yMid[i].y).abs() < answer.distance) {\n                def ikDist = yMid[i].distance(yMid[k])\n                if ( ikDist < answer.distance) {\n                    answer = [distance:ikDist, points:[yMid[i],yMid[k]]]\n                }\n            }\n        }\n    }\n    answer\n}\n\n\ndef random = new Random()\n\n(1..4).each {\ndef point10 = (0..<(10**it)).collect { new Point(random.nextInt(1000001) - 500000,random.nextInt(1000001) - 500000) }\n\ndef startE = System.currentTimeMillis()\ndef closestE = elegantClosest(point10)\ndef elapsedE = System.currentTimeMillis() - startE\nprintln \"\"\"\n${10**it} POINTS\n-----------------------------------------\nElegant reduction:\nelapsed: ${elapsedE\/1000} s\nclosest: ${closestE}\n\"\"\"\n\n\ndef startB = System.currentTimeMillis()\ndef closestB = bruteClosest(point10)\ndef elapsedB = System.currentTimeMillis() - startB\nprintln \"\"\"Brute force:\nelapsed: ${elapsedB\/1000} s\nclosest: ${closestB}\n\nSpeedup ratio (B\/E): ${elapsedB\/elapsedE}\n=========================================\n\"\"\"\n}\n\n\n10 POINTS\n-----------------------------------------\nElegant reduction:\nelapsed: 0.019 s\nclosest: [distance:85758.5249173515, points:[{x:310073, y:-27339}, {x:382387, y:18761}]]\n\nBrute force:\nelapsed: 0.001 s\nclosest: [distance:85758.5249173515, points:[{x:310073, y:-27339}, {x:382387, y:18761}]]\n\nSpeedup ratio (B\/E): 0.0526315789\n=========================================\n\n\n100 POINTS\n-----------------------------------------\nElegant reduction:\nelapsed: 0.019 s\nclosest: [distance:3166.229934796271, points:[{x:-343735, y:-244394}, {x:-341099, y:-246148}]]\n\nBrute force:\nelapsed: 0.027 s\nclosest: [distance:3166.229934796271, points:[{x:-343735, y:-244394}, {x:-341099, y:-246148}]]\n\nSpeedup ratio (B\/E): 1.4210526316\n=========================================\n\n\n1000 POINTS\n-----------------------------------------\nElegant reduction:\nelapsed: 0.241 s\nclosest: [distance:374.22586762542215, points:[{x:411817, y:-83016}, {x:412038, y:-82714}]]\n\nBrute force:\nelapsed: 0.618 s\nclosest: [distance:374.22586762542215, points:[{x:411817, y:-83016}, {x:412038, y:-82714}]]\n\nSpeedup ratio (B\/E): 2.5643153527\n=========================================\n\n\n10000 POINTS\n-----------------------------------------\nElegant reduction:\nelapsed: 1.957 s\nclosest: [distance:79.00632886041473, points:[{x:187928, y:-452338}, {x:187929, y:-452259}]]\n\nBrute force:\nelapsed: 51.567 s\nclosest: [distance:79.00632886041473, points:[{x:187928, y:-452338}, {x:187929, y:-452259}]]\n\nSpeedup ratio (B\/E): 26.3500255493\n=========================================\n","human_summarization":"The code provides two solutions to solve the Closest Pair of Points problem in a two-dimensional plane. The first solution uses a brute force approach with a time complexity of O(n^2), which calculates the minimum distance between any two points. The second solution uses a divide-and-conquer strategy with a time complexity of O(n log n), which sorts the points based on x and y coordinates, divides them into two halves, and recursively finds the closest pairs. Both solutions incorporate X-only and Y-only pre-checks to optimize the square root calculations.","id":4396}
    {"lang_cluster":"Groovy","source_code":"\n\ndef emptyList = []\nassert emptyList.isEmpty() : \"These are not the items you're looking for\"\nassert emptyList.size() == 0 : \"Empty list has size 0\"\nassert ! emptyList : \"Empty list evaluates as boolean 'false'\"\n\ndef initializedList = [ 1, \"b\", java.awt.Color.BLUE ]\nassert initializedList.size() == 3\nassert initializedList : \"Non-empty list evaluates as boolean 'true'\"\nassert initializedList[2] == java.awt.Color.BLUE : \"referencing a single element (zero-based indexing)\"\nassert initializedList[-1] == java.awt.Color.BLUE : \"referencing a single element (reverse indexing of last element)\"\n\ndef combinedList = initializedList + [ \"more stuff\", \"even more stuff\" ]\nassert combinedList.size() == 5\nassert combinedList[1..3] == [\"b\", java.awt.Color.BLUE, \"more stuff\"] : \"referencing a range of elements\"\n\ncombinedList << \"even more stuff\"\nassert combinedList.size() == 6\nassert combinedList[-1..-3] == \\\n        [\"even more stuff\", \"even more stuff\", \"more stuff\"] \\\n                : \"reverse referencing last 3 elements\"\nprintln ([combinedList: combinedList])\n\n\n","human_summarization":"The code creates a collection and adds a few values to it. It utilizes the concept of collections, which are abstractions to represent sets of values, typically of a common data type in statically-typed languages. The code might also involve operations with Lists, Maps, and Sets.","id":4397}
    {"lang_cluster":"Groovy","source_code":"\n\ndef totalWeight = { list -> list.collect{ it.item.weight * it.count }.sum() }\ndef totalVolume = { list -> list.collect{ it.item.volume * it.count }.sum() }\ndef totalValue = { list -> list.collect{ it.item.value * it.count }.sum() }\n\ndef knapsackUnbounded = { possibleItems, BigDecimal weightMax, BigDecimal volumeMax ->\n    def n = possibleItems.size()\n    def wm = weightMax.unscaledValue()\n    def vm = volumeMax.unscaledValue()\n    def m = (0..n).collect{ i -> (0..wm).collect{ w -> (0..vm).collect{ v -> [] } } }\n    (1..wm).each { w ->\n        (1..vm).each { v ->\n            (1..n).each { i ->\n                def item = possibleItems[i-1]\n                def wi = item.weight.unscaledValue()\n                def vi = item.volume.unscaledValue()\n                def bi = [w.intdiv(wi),v.intdiv(vi)].min()\n                m[i][w][v] = (0..bi).collect{ count ->\n                    m[i-1][w - wi * count][v - vi * count] + [[item:item, count:count]]\n                }.max(totalValue).findAll{ it.count }\n            }\n        }\n    }\n    m[n][wm][vm]\n}\n\n\nSet solutions = []\nitems.eachPermutation { itemList ->\n    def start = System.currentTimeMillis()\n    def packingList = knapsackUnbounded(itemList, 25.0, 0.250)\n    def elapsed = System.currentTimeMillis() - start\n    \n    println \"\\n  Item Order: ${itemList.collect{ it.name.split()[0] }}\"\n    println \"Elapsed Time: ${elapsed\/1000.0} s\"\n    \n    solutions << (packingList as Set)\n}\n\nsolutions.each { packingList ->\n    println \"\\nTotal Weight: ${totalWeight(packingList)}\"\n    println \"Total Volume: ${totalVolume(packingList)}\"\n    println \" Total Value: ${totalValue(packingList)}\"\n    packingList.each {\n        printf ('  item:\u00a0%-22s  count:%2d  weight:%4.1f  Volume:%5.3f\\n',\n                it.item.name, it.count, it.item.weight * it.count, it.item.volume * it.count)\n    }\n}\n\n\n  Item Order: [panacea, ichor, gold]\nElapsed Time: 26.883 s\n\n  Item Order: [panacea, gold, ichor]\nElapsed Time: 27.17 s\n\n  Item Order: [ichor, panacea, gold]\nElapsed Time: 25.884 s\n\n  Item Order: [ichor, gold, panacea]\nElapsed Time: 26.126 s\n\n  Item Order: [gold, panacea, ichor]\nElapsed Time: 26.596 s\n\n  Item Order: [gold, ichor, panacea]\nElapsed Time: 26.47 s\n\nTotal Weight: 25.0\nTotal Volume: 0.247\n Total Value: 54500\n  item: gold (bars)             count:11  weight:22.0  Volume:0.022\n  item: ichor (ampules of)      count:15  weight: 3.0  Volume:0.225\n\nTotal Weight: 24.7\nTotal Volume: 0.247\n Total Value: 54500\n  item: gold (bars)             count:11  weight:22.0  Volume:0.022\n  item: panacea (vials of)      count: 9  weight: 2.7  Volume:0.225\n\nTotal Weight: 24.9\nTotal Volume: 0.247\n Total Value: 54500\n  item: gold (bars)             count:11  weight:22.0  Volume:0.022\n  item: ichor (ampules of)      count:10  weight: 2.0  Volume:0.150\n  item: panacea (vials of)      count: 3  weight: 0.9  Volume:0.075\n\nTotal Weight: 24.8\nTotal Volume: 0.247\n Total Value: 54500\n  item: gold (bars)             count:11  weight:22.0  Volume:0.022\n  item: ichor (ampules of)      count: 5  weight: 1.0  Volume:0.075\n  item: panacea (vials of)      count: 6  weight: 1.8  Volume:0.150\n","human_summarization":"implement a dynamic programming solution for the unbounded Knapsack problem. The task is to determine the maximum value of items a traveler can carry from Shangri La, given the weight and volume constraints of his knapsack and the weight, volume, and value of each available item. The solution also considers the possibility of multiple optimal solutions due to items with the same value and volume but different weights.","id":4398}
    {"lang_cluster":"Groovy","source_code":"\n\nfor(i in (1..10)) {\n    print i\n    if (i == 10) break\n    print ', '\n}\n\n\n1, 2, 3, 4, 5, 6, 7, 8, 9, 10\n","human_summarization":"generates a comma-separated list of numbers from 1 to 10, using separate output statements for the number and the comma within the loop body.","id":4399}
    {"lang_cluster":"Groovy","source_code":"\n\nassert \"abcd\".startsWith(\"ab\")\nassert ! \"abcd\".startsWith(\"zn\")\nassert \"abcd\".endsWith(\"cd\")\nassert ! \"abcd\".endsWith(\"zn\")\nassert \"abab\".contains(\"ba\")\nassert ! \"abab\".contains(\"bb\")\n\n\nassert \"abab\".indexOf(\"bb\") == -1 \/\/ not found flag\nassert \"abab\".indexOf(\"ab\") == 0\n\ndef indicesOf = { string, substring ->\n    if (!string) { return [] }\n    def indices = [-1]\n    while (true) {\n        indices << string.indexOf(substring, indices.last()+1)\n        if (indices.last() == -1) break\n    }\n    indices[1..<(indices.size()-1)]\n}\nassert indicesOf(\"abab\", \"ab\") == [0, 2]\nassert indicesOf(\"abab\", \"ba\") == [1]\nassert indicesOf(\"abab\", \"xy\") == []\n\n\n","human_summarization":"The code performs three types of string matching operations: checks if the first string starts with the second string, checks if the first string contains the second string at any location, and checks if the first string ends with the second string. Optionally, it can print the location of the match and handle multiple occurrences of a string.","id":4400}
    {"lang_cluster":"Groovy","source_code":"class FourRings {\n    static void main(String[] args) {\n        fourSquare(1, 7, true, true)\n        fourSquare(3, 9, true, true)\n        fourSquare(0, 9, false, false)\n    }\n\n    private static void fourSquare(int low, int high, boolean unique, boolean print) {\n        int count = 0\n\n        if (print) {\n            println(\"a b c d e f g\")\n        }\n        for (int a = low; a <= high; ++a) {\n            for (int b = low; b <= high; ++b) {\n                if (notValid(unique, a, b)) continue\n\n                int fp = a + b\n                for (int c = low; c <= high; ++c) {\n                    if (notValid(unique, c, a, b)) continue\n                    for (int d = low; d <= high; ++d) {\n                        if (notValid(unique, d, a, b, c)) continue\n                        if (fp != b + c + d) continue\n\n                        for (int e = low; e <= high; ++e) {\n                            if (notValid(unique, e, a, b, c, d)) continue\n                            for (int f = low; f <= high; ++f) {\n                                if (notValid(unique, f, a, b, c, d, e)) continue\n                                if (fp != d + e + f) continue\n\n                                for (int g = low; g <= high; ++g) {\n                                    if (notValid(unique, g, a, b, c, d, e, f)) continue\n                                    if (fp != f + g) continue\n\n                                    ++count\n                                    if (print) {\n                                        printf(\"%d %d %d %d %d %d %d%n\", a, b, c, d, e, f, g)\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        if (unique) {\n            printf(\"There are %d unique solutions in [%d, %d]%n\", count, low, high)\n        } else {\n            printf(\"There are %d non-unique solutions in [%d, %d]%n\", count, low, high)\n        }\n    }\n\n    private static boolean notValid(boolean unique, int needle, int ... haystack) {\n        return unique && Arrays.stream(haystack).anyMatch({ p -> p == needle })\n    }\n}\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":4401}
    {"lang_cluster":"Groovy","source_code":"\n\nclass Triple {\n    BigInteger a, b, c\n    def getPerimeter() { this.with { a + b + c } }\n    boolean isValid() { this.with { a*a + b*b == c*c } }\n}\n\ndef initCounts (def n = 10) {\n    (n..1).collect { 10g**it }.inject ([:]) { Map map, BigInteger perimeterLimit ->\n        map << [(perimeterLimit): [primative: 0g, total: 0g]]\n    }\n}\n\ndef findPythagTriples, findChildTriples\n\nfindPythagTriples = {Triple t = new Triple(a:3, b:4, c:5), Map counts = initCounts() ->\n    def p = t.perimeter\n    def currentCounts = counts.findAll { pLimit, tripleCounts -> p <= pLimit }\n    if (! currentCounts || ! t.valid) { return }\n    currentCounts.each { pLimit, tripleCounts ->\n        tripleCounts.with { primative ++; total += pLimit.intdiv(p) }\n    }\n    findChildTriples(t, currentCounts)\n    counts\n}\n\nfindChildTriples = { Triple t, Map counts ->\n    t.with {\n        [\n            [ a - 2*b + 2*c,  2*a - b + 2*c,  2*a - 2*b + 3*c],\n            [ a + 2*b + 2*c,  2*a + b + 2*c,  2*a + 2*b + 3*c],\n            [-a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c]\n        ]*.sort().each { aa, bb, cc ->\n            findPythagTriples(new Triple(a:aa, b:bb, c:cc), counts)\n        }\n    }\n}\n\n\nprintf ('    LIMIT       PRIMATIVE          ALL\\n')\nfindPythagTriples().sort().each { perimeterLimit, result ->\n    def exponent = perimeterLimit.toString().size() - 1\n    printf ('a+b+c <= 10E%2d  %9d %12d\\n', exponent, result.primative, result.total)\n}\n\n\n    LIMIT       PRIMATIVE          ALL\na+b+c <= 10E 1          0            0\na+b+c <= 10E 2          7           17\na+b+c <= 10E 3         70          325\na+b+c <= 10E 4        703         4858\na+b+c <= 10E 5       7026        64741\na+b+c <= 10E 6      70229       808950\na+b+c <= 10E 7     702309      9706567\na+b+c <= 10E 8    7023027    113236940\na+b+c <= 10E 9   70230484   1294080089\na+b+c <= 10E10  702304875  14557915466\n","human_summarization":"determine the number of Pythagorean triples with a perimeter not exceeding 100, as well as the number of these triples that are primitive. The code also includes an extra feature to handle large perimeter values up to 100,000,000 efficiently.","id":4402}
    {"lang_cluster":"Groovy","source_code":"\n import groovy.swing.SwingBuilder\n\n new SwingBuilder().frame(title:'My Window', size:[200,100]).show()\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":4403}
    {"lang_cluster":"Groovy","source_code":"\ndef frequency = { it.inject([:]) { map, value -> map[value] = (map[value] ?: 0) + 1; map } }\n\nfrequency(new File('frequency.groovy').text).each { key, value ->\n    println \"'$key': $value\"\n}\n\n\n","human_summarization":"Open a text file, count the frequency of each letter, and differentiate between counting all characters or only letters A to Z.","id":4404}
    {"lang_cluster":"Groovy","source_code":"\n\nclass ListNode {\n    Object payload\n    ListNode next\n    String toString() { \"${payload} -> ${next}\" }\n}\n\n\ndef n1 = new ListNode(payload:25)\nn1.next = new ListNode(payload:88)\n\nprintln n1\n\n\n25 -> 88 -> null\n","human_summarization":"define the data structure for a singly-linked list element, which includes a numeric data member and a mutable link to the next element.","id":4405}
    {"lang_cluster":"Groovy","source_code":"\n\ndef factorize = { long target -> \n\n    if (target == 1) return [1L]\n\n    if (target < 4) return [1L, target]\n\n    def targetSqrt = Math.sqrt(target)\n    def lowfactors = (2L..targetSqrt).grep { (target % it) == 0 }\n    if (lowfactors == []) return [1L, target]\n    def nhalf = lowfactors.size() - ((lowfactors[-1] == targetSqrt) ? 1 : 0)\n    \n    [1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target]\n}\n\n\n((1..30) + [333333]).each { println ([number:it, factors:factorize(it)]) }\n\n\n","human_summarization":"Calculate the factors of a positive integer using a brute force approach up to the square root of the input number. The code does not handle cases of zero or negative integers. For prime numbers, the factors will be 1 and the number itself.","id":4406}
    {"lang_cluster":"Groovy","source_code":"\n\ndef alignColumns = { align, rawText ->\n    def lines = rawText.tokenize('\\n')\n    def words = lines.collect { it.tokenize(\/\\$\/) }\n    def maxLineWords = words.collect {it.size()}.max()\n    words = words.collect { line -> line + [''] * (maxLineWords - line.size()) }\n    def columnWidths = words.transpose().collect{ column -> column.collect { it.size() }.max() }\n\n    def justify = [   Right  : { width, string -> string.padLeft(width) },\n                            Left   : { width, string -> string.padRight(width) },\n                            Center : { width, string -> string.center(width) }      ]\n    def padAll = { pad, colWidths, lineWords -> [colWidths, lineWords].transpose().collect { pad(it) + ' ' } }\n\n    words.each { padAll(justify[align], columnWidths, it).each { print it }; println() }\n}\n\n\ndef rawTextInput = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.'''\n\n['Left', 'Center', 'Right'].each { align -> \n    println \"${align} Justified:\"\n    alignColumns(align, rawTextInput)\n    println()\n}\n\n\n","human_summarization":"The code reads a text file with multiple lines, where fields within a line are separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. The code also allows for each word in a column to be left justified, right justified, or center justified. The minimum space between columns is computed from the text, not hard-coded. The code handles trailing dollar characters and insignificant consecutive spaces at the end of lines. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":4407}
    {"lang_cluster":"Groovy","source_code":"\n\ndef rot13 = { String s ->\n    (s as List).collect { ch ->\n        switch (ch) {\n            case ('a'..'m') + ('A'..'M'):\n                return (((ch as char) + 13) as char)\n            case ('n'..'z') + ('N'..'Z'):\n                return (((ch as char) - 13) as char)\n            default:\n                return ch\n        }\n    }.inject (\"\") { string, ch -> string += ch}\n}\n\n\nprintln rot13(\"Noyr jnf V, 'rer V fnj Ryon.\")\n\n\nAble was I, 'ere I saw Elba.\n","human_summarization":"implement a rot-13 encoding function that can be optionally wrapped in a utility program. This function replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters \"around\" the 26 letter alphabet. It should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration.","id":4408}
    {"lang_cluster":"Groovy","source_code":"\nclass Holiday {\n    def date\n    def name\n    Holiday(dateStr, name) { this.name = name; this.date = format.parse(dateStr) }\n    String toString() { \"${format.format date}: ${name}\" }\n    static format = new java.text.SimpleDateFormat(\"yyyy-MM-dd\")\n}\n\ndef holidays = [ new Holiday(\"2009-12-25\", \"Christmas Day\"),\n                 new Holiday(\"2009-04-22\", \"Earth Day\"),\n                 new Holiday(\"2009-09-07\", \"Labor Day\"),\n                 new Holiday(\"2009-07-04\", \"Independence Day\"),\n                 new Holiday(\"2009-10-31\", \"Halloween\"),\n                 new Holiday(\"2009-05-25\", \"Memorial Day\"),\n                 new Holiday(\"2009-03-14\", \"PI Day\"),\n                 new Holiday(\"2009-01-01\", \"New Year's Day\"),\n                 new Holiday(\"2009-12-31\", \"New Year's Eve\"),\n                 new Holiday(\"2009-11-26\", \"Thanksgiving\"),\n                 new Holiday(\"2009-02-14\", \"St. Valentine's Day\"),\n                 new Holiday(\"2009-03-17\", \"St. Patrick's Day\"),\n                 new Holiday(\"2009-01-19\", \"Martin Luther King Day\"),\n                 new Holiday(\"2009-02-16\", \"President's Day\") ]\n\nholidays.sort { x, y -> x.date <=> y.date }\nholidays.each { println it }\n\n\n2009-01-01: New Year's Day\n2009-01-19: Martin Luther King Day\n2009-02-14: St. Valentine's Day\n2009-02-16: President's Day\n2009-03-14: PI Day\n2009-03-17: St. Patrick's Day\n2009-04-22: Earth Day\n2009-05-25: Memorial Day\n2009-07-04: Independence Day\n2009-09-07: Labor Day\n2009-10-31: Halloween\n2009-11-26: Thanksgiving\n2009-12-25: Christmas Day\n2009-12-31: New Year's Eve\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key 'name' using a custom comparator.","id":4409}
    {"lang_cluster":"Groovy","source_code":"\n\nfor(i in (1..6)) {\n    for(j in (1..i)) {\n        print '*'\n    }\n    println ()\n}\n\n","human_summarization":"demonstrate how to nest two \"for\" loops, where the number of iterations of the inner loop is controlled by the outer loop. The code prints a pattern of asterisks, with each line containing one more asterisk than the previous line.","id":4410}
    {"lang_cluster":"Groovy","source_code":"\n\nmap = [:]\nmap[7] = 7\nmap['foo'] = 'foovalue'\nmap.put('bar', 'barvalue')\nmap.moo = 'moovalue'\n\nassert 7 == map[7]\nassert 'foovalue' == map.foo\nassert 'barvalue' == map['bar']\nassert 'moovalue' == map.get('moo')\n\n\nmap = [7:7, foo:'foovalue', bar:'barvalue', moo:'moovalue']\n\nassert 7 == map[7]\nassert 'foovalue' == map.foo\nassert 'barvalue' == map['bar']\nassert 'moovalue' == map.get('moo')\n\n","human_summarization":"Create and populate an associative array, verify its values, and add new values to an empty map.","id":4411}
    {"lang_cluster":"Groovy","source_code":"\n\nclass NodeList {\n    private enum Flag { FRONT }\n    private ListNode head\n    void insert(value, insertionPoint=Flag.FRONT) {\n        if (insertionPoint == Flag.FRONT) {\n            head = new ListNode(payload: value, next: head)\n        } else {\n            def node = head\n            while (node.payload != insertionPoint) {\n                node = node.next\n                if (node == null) {\n                    throw new IllegalArgumentException(\n                        \"Insertion point ${afterValue} not already contained in list\")\n                }\n            }\n            node.next = new ListNode(payload:value, next:node.next)\n        }\n    }\n    String toString() { \"${head}\" }\n}\n\n\ndef list = new NodeList()\nlist.insert('B')\nlist.insert('A')\nprintln list\n\nlist.insert('C', 'A')\nprintln list\n\n\nA -> B -> null\nA -> C -> B -> null\n","human_summarization":"define a method to insert an element into a singly-linked list after a specified element. The method is then used to insert element C into a list containing elements A and B, following element A.","id":4412}
    {"lang_cluster":"Groovy","source_code":"\n\ndef rFact\nrFact = { (it > 1)\u00a0? it * rFact(it - 1)\u00a0: 1 as BigInteger }\ndef iFact = { (it > 1)\u00a0? (2..it).inject(1 as BigInteger) { i, j -> i*j }\u00a0: 1 }\n\ndef time = { Closure c ->\n    def start = System.currentTimeMillis()\n    def result = c()\n    def elapsedMS = (System.currentTimeMillis() - start)\/1000\n    printf '(%6.4fs elapsed)', elapsedMS\n    result\n}\n\ndef dashes = '---------------------'\nprint \"   n!       elapsed time   \"; (0..15).each { def length = Math.max(it - 3, 3); printf \"\u00a0%${length}d\", it }; println()\nprint \"--------- -----------------\"; (0..15).each { def length = Math.max(it - 3, 3); print \" ${dashes[0..<length]}\" }; println()\n[recursive:rFact, iterative:iFact].each { name, fact ->\n    printf \"%9s \", name\n    def factList = time { (0..15).collect {fact(it)} }\n    factList.each { printf ' %3d', it }\n    println()\n}\n\n","human_summarization":"The code calculates the factorial of a given number either iteratively or recursively. It optionally handles errors for negative input values. A recursive closure is pre-declared for this purpose. The code is also related to the task of generating primorial numbers.","id":4413}
    {"lang_cluster":"Groovy","source_code":"\nclass BullsAndCows {\n    static void main(args) {\n        def inputReader = System.in.newReader()\n        def numberGenerator = new Random()\n        def targetValue\n        while (targetValueIsInvalid(targetValue = numberGenerator.nextInt(9000) + 1000)) continue\n        def targetStr = targetValue.toString()\n        def guessed = false\n        def guesses = 0\n        while (!guessed) {\n            def bulls = 0, cows = 0\n            print 'Guess a 4-digit number with no duplicate digits: '\n            def guess = inputReader.readLine()\n            if (guess.length() != 4 || !guess.isInteger() || targetValueIsInvalid(guess.toInteger())) {\n                continue\n            }\n            guesses++\n            4.times {\n                if (targetStr[it] == guess[it]) {\n                    bulls++\n                } else if (targetStr.contains(guess[it])) {\n                    cows++\n                }\n            }\n            if (bulls == 4) {\n                guessed = true\n            } else {\n                println \"$cows Cows and $bulls Bulls.\"\n            }\n        }\n        println \"You won after $guesses guesses!\"\n    }\n\n    static targetValueIsInvalid(value) {\n        def digitList = []\n        while (value > 0) {\n            if (digitList[value % 10] == 0 || digitList[value % 10]) {\n                return true\n            }\n            digitList[value % 10] = true\n            value = value.intdiv(10)\n        }\n        false\n    }\n}\n\n","human_summarization":"generate a unique four-digit number, accept and validate user guesses, calculate and print scores based on matching digits and their positions, and end the program when the user guess matches the generated number.","id":4414}
    {"lang_cluster":"Groovy","source_code":"\nrnd = new Random()\nresult = (1..1000).inject([]) { r, i -> r << rnd.nextGaussian() }\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5.","id":4415}
    {"lang_cluster":"Groovy","source_code":"\n\ndef dotProduct = { x, y ->\n    assert x && y && x.size() == y.size()\n    [x, y].transpose().collect{ xx, yy -> xx * yy }.sum()\n}\n\n\nprintln dotProduct([1, 3, -5], [4, -2, -1])\n\n\n","human_summarization":"implement a function that calculates the dot product of two vectors of arbitrary length. The vectors must be of the same length, and the function works by multiplying corresponding terms from each vector and summing the products.","id":4416}
    {"lang_cluster":"Groovy","source_code":"\n\ndef lineMap = [:]\nSystem.in.eachLine { line, i ->\n    lineMap[i] = line\n}\nlineMap.each { println it }\n\n\nTest:\n$ groovy -e 'def lineMap = [:]\n> System.in.eachLine { line, i ->\n>     lineMap[i] = line\n> }\n> lineMap.each { println it }' <<EOF\n> \n> Whose woods these are I think I know\n> His house is in the village tho'\n> He will not see me stopping here\n> To watch his woods fill up with snow\n> EOF\n\n","human_summarization":"continuously read data from a text stream either word-by-word or line-by-line until there is no more data available in the stream.","id":4417}
    {"lang_cluster":"Groovy","source_code":"\nimport groovy.xml.MarkupBuilder\ndef writer = new StringWriter() << '<?xml version=\"1.0\"\u00a0?>\\n'\ndef xml = new MarkupBuilder(writer)\nxml.root() {\n    element('Some text here' ) \n}\nprintln writer\n\n","human_summarization":"Create a simple DOM and serialize it into the specified XML format.","id":4418}
    {"lang_cluster":"Groovy","source_code":"\nSolution (based on Java solution).def nowMillis = new Date().time\nprintln 'Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == ' + nowMillis\n\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":4419}
    {"lang_cluster":"Groovy","source_code":"\ndef checksum(text) {\n    assert text.size() == 6 && !text.toUpperCase().find(\/[AEIOU]+\/) : \"Invalid SEDOL text: $text\"\n\n    def sum = 0\n    (0..5).each { index ->\n        sum +=  Character.digit(text.charAt(index), 36) * [1, 3, 1, 7, 3, 9][index]\n    }\n    text + (10 - (sum % 10)) % 10\n}\nString.metaClass.sedol = { this.&checksum(delegate) }\n\n\n[ '710889': '7108899', 'B0YBKJ': 'B0YBKJ7', '406566': '4065663', 'B0YBLH': 'B0YBLH2',\n  '228276': '2282765', 'B0YBKL': 'B0YBKL9', '557910': '5579107', 'B0YBKR': 'B0YBKR5',\n  '585284': '5852842', 'B0YBKT': 'B0YBKT7', 'B00030': 'B000300'].each { text, expected ->\n    println \"Checking $text -> $expected\"\n    assert expected == text.sedol()\n}\n\n\nChecking 710889 -> 7108899\nChecking B0YBKJ -> B0YBKJ7\nChecking 406566 -> 4065663\nChecking B0YBLH -> B0YBLH2\nChecking 228276 -> 2282765\nChecking B0YBKL -> B0YBKL9\nChecking 557910 -> 5579107\nChecking B0YBKR -> B0YBKR5\nChecking 585284 -> 5852842\nChecking B0YBKT -> B0YBKT7\nChecking B00030 -> B000300\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the respective SEDOL. It also validates the input to ensure it consists of valid characters allowed in a SEDOL string.","id":4420}
    {"lang_cluster":"Groovy","source_code":"\n\ndef stripChars = { string, stripChars ->\n    def list = string as List\n    list.removeAll(stripChars as List)\n    list.join()\n}\n\n\nprintln (stripChars('She was a soul stripper. She took my heart!', 'aei'))\n\n\n","human_summarization":"\"Function to remove specified characters from a given string.\"","id":4421}
    {"lang_cluster":"Groovy","source_code":"\ndef log = ''\n(1..40).each {Integer value -> log +=(value %3 == 0) ? (value %5 == 0)? 'FIZZBUZZ\\n':(value %7 == 0)? 'FIZZBAXX\\n':'FIZZ\\n'\n                                    :(value %5 == 0) ? (value %7 == 0)? 'BUZBAXX\\n':'BUZZ\\n'\n                                    :(value %7 == 0) ?'BAXX\\n'\n                                    :(value+'\\n')}\nprintln log\n\n1\n2\nFIZZ\n4\nBUZZ\nFIZZ\nBAXX\n8\nFIZZ\nBUZZ\n11\nFIZZ\n13\nBAXX\nFIZZBUZZ\n16\n17\nFIZZ\n19\nBUZZ\nFIZZBAXX\n22\n23\nFIZZ\nBUZZ\n26\nFIZZ\nBAXX\n29\nFIZZBUZZ\n31\n32\nFIZZ\n34\nBUZBAXX\nFIZZ\n37\n38\nFIZZ\nBUZZ\n\n\ndef fizzBuzz = { i -> [[3,'Fizz'],[5,'Buzz'],[7,'Baxx']].collect{i%it[0]?'':it[1]}.join()?:i}\n1.upto(100){println fizzBuzz(it)}\n\n","human_summarization":"generates a custom FizzBuzz sequence based on user-defined parameters. The user inputs a maximum number and three pairs of factors and corresponding words. The program then prints numbers from 1 to the maximum number, replacing multiples of the factors with the associated words. In cases where a number is a multiple of multiple factors, all corresponding words are printed in the order of the factors.","id":4422}
    {"lang_cluster":"Groovy","source_code":"\ndef random = new Random()\ndef keyboard = new Scanner(System.in)\ndef number = random.nextInt(10) + 1\nprintln \"Guess the number which is between 1 and 10: \"\ndef guess = keyboard.nextInt()\nwhile (number != guess) {\n    println \"Guess again: \"\n    guess = keyboard.nextInt()\n}\nprintln \"Hurray! You guessed correctly!\"\n\n","human_summarization":"\"Implement a number guessing game where the computer selects a number between 1 and 10. The player is repeatedly prompted to guess the number until the correct number is guessed, upon which a 'Well guessed!' message is displayed and the program terminates. A conditional loop is used to facilitate repeated guessing.\"","id":4423}
    {"lang_cluster":"Groovy","source_code":"\ndef lower = ('a'..'z')\n\n\nassert 'abcdefghijklmnopqrstuvwxyz' == lower.join('')\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from 'a' to 'z' using a reliable coding style and strong typing if available. The code avoids manually enumerating all the lowercase characters to prevent bugs. It also demonstrates how to access such a sequence if it exists in the standard library.","id":4424}
    {"lang_cluster":"Groovy","source_code":"\n\nprint '''\n  n        binary\n----- ---------------\n'''\n[5, 50, 9000].each {\n    printf('%5d %15s\\n', it, Integer.toBinaryString(it))\n}\n\n\n","human_summarization":"\"Generate and display the binary representation of a given non-negative integer without leading zeros, whitespace, radix or sign markers. The output for each number is followed by a newline.\"","id":4425}
    {"lang_cluster":"Groovy","source_code":"\ndef config = [:]\ndef loadConfig = { File file ->\n    String regex = \/^(;{0,1})\\s*(\\S+)\\s*(.*)$\/\n    file.eachLine { line ->\n        (line =~ regex).each { matcher, invert, key, value ->\n            if (key == '' || key.startsWith(\"#\")) return\n            parts = value ? value.split(\/\\s*,\\s*\/) : (invert ? [false] : [true])\n            if (parts.size() > 1) {\n                parts.eachWithIndex{ part, int i -> config[\"$key(${i + 1})\"] = part}\n            } else {\n                config[key] = parts[0]\n            }\n        }\n    }\n}\n\n\nloadConfig new File('config.ini')\nconfig.each { println it }\n\n\n","human_summarization":"The code reads a standard configuration file, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration parameters, preserving case sensitivity for parameter data. It also handles optional equals signs, and multiple parameters separated by commas. The variables set include fullname, favouritefruit, needspeeling, seedsremoved, and otherfamily which is stored in an array. The boolean variables are set to true if present and false if commented out.","id":4426}
    {"lang_cluster":"Groovy","source_code":"\ndef haversine(lat1, lon1, lat2, lon2) {\n  def R = 6372.8\n  \/\/ In kilometers\n  def dLat = Math.toRadians(lat2 - lat1)\n  def dLon = Math.toRadians(lon2 - lon1)\n  lat1 = Math.toRadians(lat1)\n  lat2 = Math.toRadians(lat2)\n\n  def a = Math.sin(dLat \/ 2) * Math.sin(dLat \/ 2) + Math.sin(dLon \/ 2) * Math.sin(dLon \/ 2) * Math.cos(lat1) * Math.cos(lat2)\n  def c = 2 * Math.asin(Math.sqrt(a))\n  R * c\n}\n\nhaversine(36.12, -86.67, 33.94, -118.40)\n\n> 2887.25995060711\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":4427}
    {"lang_cluster":"Groovy","source_code":"\nnew URL(\"http:\/\/www.rosettacode.org\").eachLine { println it }\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":4428}
    {"lang_cluster":"Groovy","source_code":"\ndef checkLuhn(number) {\n    int total\n    (number as String).reverse().eachWithIndex { ch, index ->\n        def digit = Integer.parseInt(ch)\n        total += (index % 2 ==0) ? digit : [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][digit]\n    }\n    total % 10 == 0\n}\n\n\ndef verifyLuhn(number, expected) {\n    println \"Checking: $number (${checkLuhn(number)})\"\n    assert expected == checkLuhn(number)\n}\n\n[49927398716: true, 49927398717: false, 1234567812345678: false, 1234567812345670: true].each { number, expected ->\n    verifyLuhn number, expected\n}\n\n\n","human_summarization":"The code implements the Luhn test for validating credit card numbers. It first reverses the order of the digits in the number. Then, it calculates the sum of every other odd digit (s1) and the sum of the doubled even digits (s2). If the sum of s1 and s2 ends in zero, the number is a valid credit card number. The code validates the numbers 49927398716, 49927398717, 1234567812345678, and 1234567812345670 using this method.","id":4429}
    {"lang_cluster":"Groovy","source_code":"\nint[] Josephus (int size, int kill, int survivors) {\n    \/\/ init user pool\n    def users = new int[size];\n    \n    \/\/ give initial values such that [0] = 1 (first person) [1] = 2 (second person) etc\n    users.eachWithIndex() {obj, i -> users[i] = i + 1};\n    \n    \/\/ keep track of which person we are on (ranging from 1 to kill)\n    def person = 1;\n    \n    \/\/ keep going until we have the desired number of survivors\n    while (users.size() > survivors)\n    {\n        \/\/ for each person, if they are the kill'th person, set them to -1 to show eliminated\n        users.eachWithIndex() {obj, i ->\n            if (person++ % kill == 0) {\n                users[i] = -1;\n            }\n            \n            \/\/ if person overflowed kill then reset back to 1\n            if (person > kill) {person = 1;}\n        }\n        \n        \/\/ clear out all eliminated persons\n        users = users.findAll{w -> w >= 0};\n    }\n    \n    \/\/ resulting set is the safe positions\n    return users;\n}\n\n\/\/ Run some test cases\n\nprintln \"Final survivor for n = 10201 and k = 17: \" + Josephus(10201,17,1)[0];\n\nprintln \"4 safe spots for n = 10201 and k = 17: \" + Josephus(10201,17,4);\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":4430}
    {"lang_cluster":"Groovy","source_code":"\n println 'ha' * 5\n\n","human_summarization":"The code takes a string or a character as input and repeats it a specified number of times. For example, if the input is \"ha\" and 5, the output will be \"hahahahaha\". Similarly, if the input is \"*\" and 5, the output will be \"*****\".","id":4431}
    {"lang_cluster":"Groovy","source_code":"\n\nimport java.util.regex.*;\n\ndef woodchuck = \"How much wood would a woodchuck chuck if a woodchuck could chuck wood?\"\ndef pepper = \"Peter Piper picked a peck of pickled peppers\"\n\n\nprintln \"=== Regular-expression String syntax (\/string\/) ===\"\ndef woodRE = \/[Ww]o\\w+d\/\ndef piperRE = \/[Pp]\\w+r\/\nassert woodRE instanceof String && piperRE instanceof String\nassert (\/[Ww]o\\w+d\/ == \"[Ww]o\\\\w+d\") && (\/[Pp]\\w+r\/ == \"[Pp]\\\\w+r\")\nprintln ([woodRE: woodRE, piperRE: piperRE])\nprintln ()\n\n\nprintln \"=== Pattern (~) operator ===\"\ndef woodPat = ~\/[Ww]o\\w+d\/\ndef piperPat = ~piperRE\nassert woodPat instanceof Pattern && piperPat instanceof Pattern\n\ndef woodList = woodchuck.split().grep(woodPat)\nprintln ([exactTokenMatches: woodList])\nprintln ([exactTokenMatches: pepper.split().grep(piperPat)])\nprintln ()\n\n\nprintln \"=== Matcher (=~) operator ===\"\ndef wwMatcher = (woodchuck =~ woodRE)\ndef ppMatcher = (pepper =~ \/[Pp]\\w+r\/)\ndef wpMatcher = (woodchuck =~ \/[Pp]\\w+r\/)\nassert wwMatcher instanceof Matcher && ppMatcher instanceof Matcher\nassert wwMatcher.toString() == woodPat.matcher(woodchuck).toString()\nassert ppMatcher.toString() == piperPat.matcher(pepper).toString()\nassert wpMatcher.toString() == piperPat.matcher(woodchuck).toString()\n\nprintln ([ substringMatches: wwMatcher.collect { it }])\nprintln ([ substringMatches: ppMatcher.collect { it }])\nprintln ([ substringMatches: wpMatcher.collect { it }])\nprintln ()\n\n\nprintln \"=== Exact Match (==~) operator ===\"\ndef containsWoodRE = \/.*\/ + woodRE + \/.*\/\ndef containsPiperRE = \/.*\/ + piperRE + \/.*\/\ndef wwMatches = (woodchuck ==~ containsWoodRE)\nassert wwMatches instanceof Boolean\ndef wwNotMatches = ! (woodchuck ==~ woodRE)\ndef ppMatches = (pepper ==~ containsPiperRE)\ndef pwNotMatches = ! (pepper ==~ containsWoodRE)\ndef wpNotMatches = ! (woodchuck ==~ containsPiperRE)\nassert wwMatches && wwNotMatches && ppMatches && pwNotMatches && pwNotMatches\n\nprintln (\"'${woodchuck}' ${wwNotMatches\u00a0? 'does not'\u00a0: 'does'} match '${woodRE}' exactly\")\nprintln (\"'${woodchuck}' ${wwMatches\u00a0? 'does'\u00a0: 'does not'} match '${containsWoodRE}' exactly\")\n\n\n","human_summarization":"1. Matches a string with a specified regular expression.\n2. Replaces a certain part of a string using a specified regular expression.\n3. Provides a reusable solution for replacing parts of a string using a regular expression.","id":4432}
    {"lang_cluster":"Groovy","source_code":"\n\ndef arithmetic = { a, b ->\n    println \"\"\"\n       a + b =        ${a} + ${b} = ${a + b}\n       a - b =        ${a} - ${b} = ${a - b}\n       a * b =        ${a} * ${b} = ${a * b}\n       a \/ b =        ${a} \/ ${b} = ${a \/ b}  \u00a0!!! Converts to floating point!\n(int)(a \/ b) = (int)(${a} \/ ${b}) = ${(int)(a \/ b)}             \u00a0!!! Truncates downward after the fact\n a.intdiv(b) =  ${a}.intdiv(${b}) = ${a.intdiv(b)}             \u00a0!!! Behaves as if truncating downward, actual implementation varies\n       a\u00a0% b =        ${a}\u00a0% ${b} = ${a\u00a0% b}\n\nExponentiation is also a base arithmetic operation in Groovy, so:\n      a ** b =       ${a} ** ${b} = ${a ** b}\n\"\"\"\n}\n\n\narithmetic(5,3)\n\n\n","human_summarization":"take two integers as input from the user and calculate their sum, difference, product, integer quotient, remainder and exponentiation. The code does not include error handling. It also indicates the rounding method for the quotient and the sign of the remainder. Additionally, it includes an example of the integer 'divmod' operator.","id":4433}
    {"lang_cluster":"Groovy","source_code":"\n\nprintln (('the three truths' =~ \/th\/).count)\nprintln (('ababababab' =~ \/abab\/).count)\nprintln (('abaabba*bbaba*bbab' =~ \/a*b\/).count)\nprintln (('abaabba*bbaba*bbab' =~ \/a\\*b\/).count)\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a specific substring within a given string. The function takes two arguments, the main string and the substring to search for. It returns an integer representing the count of non-overlapping matches. The function does not count overlapping substrings and matches from either left-to-right or right-to-left for the highest number of matches. The solution utilizes Groovy's \"find\" operator and \"count\" property.","id":4434}
    {"lang_cluster":"Groovy","source_code":"\n\ndef tail = { list, n ->  def m = list.size(); list.subList([m - n, 0].max(),m) }\n\nfinal STACK = [A:[],B:[],C:[]].asImmutable()\n\ndef report = { it -> }\ndef check = { it -> }\n\ndef moveRing = { from, to ->  to << from.pop(); report(); check(to) }\n\ndef moveStack\nmoveStack = { from, to, using = STACK.values().find { !(it.is(from) || it.is(to)) } ->\n    if (!from) return\n    def n = from.size()\n    moveStack(tail(from, n-1), using, to)\n    moveRing(from, to)\n    moveStack(tail(using, n-1), to, from)\n}\n\n\nenum Ring {\n    S('\u00b0'), M('o'), L('O'), XL('( )');\n    private sym\n    private Ring(sym) { this.sym=sym }\n    String toString() { sym }\n}\n\nreport = { STACK.each { k, v ->  println \"${k}: ${v}\" }; println() }\ncheck = { to -> assert to == ([] + to).sort().reverse() }\n\nRing.values().reverseEach { STACK.A << it }\nreport()\ncheck(STACK.A)\nmoveStack(STACK.A, STACK.C)\n\n\n","human_summarization":"\"Implement a recursive solution for the Towers of Hanoi problem, manipulating actual stacks of rings.\"","id":4435}
    {"lang_cluster":"Groovy","source_code":"\n\ndef factorial = { x ->\n    assert x > -1\n    x == 0 ? 1 : (1..x).inject(1G) { BigInteger product, BigInteger factor -> product *= factor }\n}\n\ndef combinations = { n, k ->\n    assert k >= 0\n    assert n >= k\n    factorial(n).intdiv(factorial(k)*factorial(n-k))\n}\n\n\nassert combinations(20, 0) == combinations(20, 20)\nassert combinations(20, 10) == (combinations(19, 9) + combinations(19, 10))\nassert combinations(5, 3) == 10\nprintln combinations(5, 3)\n\n\n","human_summarization":"\"Calculate any binomial coefficient using the given formula, with specific capability to output the binomial coefficient of 5 and 3. The code also handles tasks related to combinations and permutations, both with and without replacement.\"","id":4436}
    {"lang_cluster":"Groovy","source_code":"\n\ndef i = 0\ndo {\n    i++\n    println i\n} while (i % 6 != 0)\n\n\ndef i = 0\nwhile (true) {\n    i++\n    println i\n    if (i % 6 == 0) break\n}\n\n\n","human_summarization":"Initializes a value at 0 and increments it by 1 in each iteration of a loop. The loop continues as long as the incremented value modulo 6 is not equal to 0. The value is printed in each iteration. The loop is guaranteed to run at least once. This is implemented in Groovy 3.0.0 and later versions. In previous versions, an infinite while loop with a conditional break at the end is used as a workaround due to the absence of a bottom-checking loop construct.","id":4437}
    {"lang_cluster":"Groovy","source_code":"\n\nprintln \"Hello World!\".size()\nprintln \"m\u00f8\u00f8se\".size()\nprintln \"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\".size()\nprintln \"J\u0332o\u0332s\u0332\u00e9\u0332\".size()\n\n\n12\n5\n14\n8\n\n\n","human_summarization":"calculates the character and byte length of a string, considering the UTF-8 and UTF-16 encodings. It accurately counts the Unicode code points, not user-visible graphemes or code unit counts. The code also handles non-BMP code points correctly. It provides the string length in graphemes if the language supports it. However, it does not calculate the in-memory storage size in bytes. The code uses the Java \"String.length()\" method or \"size()\" for Groovy extensions to java.lang.String for calculating the character length.","id":4438}
    {"lang_cluster":"Groovy","source_code":"\n\ndef rng = new java.security.SecureRandom()\n\n\n(0..4).each { println rng.nextInt() }\n\n\n","human_summarization":"\"Generate a 32-bit random number using the system's built-in random number generator, not just a software algorithm like \/dev\/urandom devices in Unix.\"","id":4439}
    {"lang_cluster":"Groovy","source_code":"\n\ndef top  = { it.size() > 1 ? it[0..-2] : '' }\ndef tail = { it.size() > 1 ? it[1..-1] : '' }\n\n\ndef testVal = 'upraisers'\nprintln \"\"\"\noriginal: ${testVal}\ntop:      ${top(testVal)}\ntail:     ${tail(testVal)}\ntop&tail: ${tail(top(testVal))}\n\"\"\"\n\n\noriginal: upraisers\ntop:      upraiser\ntail:     praisers\ntop&tail: praiser\n","human_summarization":"demonstrate the removal of the first character, the last character, and both the first and last characters from a string. The codes also ensure compatibility with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters rather than 8-bit or 16-bit code units. Handling all Unicode characters for other encodings is not required.","id":4440}
    {"lang_cluster":"Groovy","source_code":"\ndef window = java.awt.GraphicsEnvironment.localGraphicsEnvironment.maximumWindowBounds\n\nprintln \"width: $window.width, height: $window.height\"\n\n","human_summarization":"calculate the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations, menubars, multiple monitors, and tiling window managers.","id":4441}
    {"lang_cluster":"Groovy","source_code":"\n\nfinal CELL_VALUES = ('1'..'9')\n \nclass GridException extends Exception {\n    GridException(String message) { super(message) }\n}\n \ndef string2grid = { string ->\n    assert string.size() == 81\n    (0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } }\n}\n \ndef gridRow = { grid, slot -> grid[slot.i] as Set }\n \ndef gridCol = { grid, slot -> grid.collect { it[slot.j] } as Set }\n \ndef gridBox = { grid, slot ->\n    def t, l; (t, l) = [slot.i.intdiv(3)*3, slot.j.intdiv(3)*3]\n    (0..2).collect { row -> (0..2).collect { col -> grid[t+row][l+col] } }.flatten() as Set\n}\n \ndef slotList = { grid ->\n    def slots = (0..8).collect { i -> (0..8).findAll { j -> grid[i][j] == '.' } \\\n            .collect {j -> [i: i, j: j] } }.flatten()\n}\n \ndef assignCandidates = { grid, slots = slotList(grid) ->\n    slots.each { slot ->\n        def unavailable = [gridRow, gridCol, gridBox].collect { it(grid, slot) }.sum() as Set\n        slot.candidates = CELL_VALUES - unavailable\n    }\n    slots.sort { - it.candidates.size() }\n    if (slots && ! slots[-1].candidates) {\n        throw new GridException('Invalid Sudoku Grid, overdetermined slot: ' + slots[-1])\n    }\n    slots\n}\n \ndef isSolved = { grid -> ! (grid.flatten().find { it == '.' }) }\n \ndef solve \nsolve = { grid ->\n    def slots = assignCandidates(grid)\n    if (! slots) { return grid }\n    while (slots[-1].candidates.size() == 1) {\n        def slot = slots.pop()\n        grid[slot.i][slot.j] = slot.candidates[0]\n        if (! slots) { return grid }\n        slots = assignCandidates(grid, slots)\n    }\n    if (! slots) { return grid } \n    def slot = slots.pop()\n    slot.candidates.each {\n        if (! isSolved(grid)) {\n            try {\n                def sGrid = grid.collect { row -> row.collect { cell -> cell } }\n                sGrid[slot.i][slot.j] = it\n                grid = solve(sGrid)\n            } catch (GridException ge) {\n                grid[slot.i][slot.j] = '.'\n            }\n        }\n    }\n    if (!isSolved(grid)) {\n        slots = assignCandidates(grid)\n        throw new GridException('Invalid Sudoku Grid, underdetermined slots: ' + slots)\n    }\n    grid\n}\n\n\ndef sudokus = [\n  \/\/Used in Curry solution:                             ~ 0.1 seconds\n    '819..5.....2...75..371.4.6.4..59.1..7..3.8..2..3.62..7.5.7.921..64...9.....2..438',\n \n  \/\/Used in Perl and PicoLisp solutions:                ~ 0.1 seconds\n    '53..247....2...8..1..7.39.2..8.72.49.2.98..7.79.....8.....3.5.696..1.3...5.69..1.',\n \n  \/\/Used in Fortran solution:                           ~ 0.1 seconds\n    '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..',\n \n  \/\/Used in many other solutions, notably Algol 68:     ~ 0.1 seconds\n    '394..267....3..4..5..69..2..45...9..6.......7..7...58..1..67..8..9..8....264..735',\n \n  \/\/Used in C# solution:                                ~ 0.2 seconds\n    '97.3...6..6.75.........8.5.......67.....3.....539..2..7...25.....2.1...8.4...73..',\n \n  \/\/Used in Oz solution:                                ~ 0.2 seconds\n    '4......6.5...8.9..3....1....2.7....1.9.....4.8....3.5....2....7..6.5...8.1......6',\n \n  \/\/Used in many other solutions, notably C++:          ~ 0.3 seconds\n    '85...24..72......9..4.........1.7..23.5...9...4...........8..7..17..........36.4.',\n \n  \/\/Used in VBA solution:                               ~ 0.3 seconds\n    '..1..5.7.92.6.......8...6...9..2.4.1.........3.4.8..9...7...3.......7.69.1.8..7..',\n \n  \/\/Used in Forth solution:                             ~ 0.8 seconds\n    '.9...4..7.....79..8........4.58.....3.......2.....97.6........4..35.....2..6...8.',\n \n  \/\/3rd \"exceptionally difficult\" example in Wikipedia: ~ 2.3 seconds\n    '12.3....435....1....4........54..2..6...7.........8.9...31..5.......9.7.....6...8',\n \n  \/\/Used in Curry solution:                             ~ 2.4 seconds\n    '9..2..5...4..6..3...3.....6...9..2......5..8...7..4..37.....1...5..2..4...1..6..9',\n \n  \/\/\"AL Escargot\", so-called \"hardest sudoku\" (HA!):    ~ 3.0 seconds\n    '1....7.9..3..2...8..96..5....53..9...1..8...26....4...3......1..4......7..7...3..',\n \n  \/\/1st \"exceptionally difficult\" example in Wikipedia: ~ 6.5 seconds\n    '12.4..3..3...1..5...6...1..7...9.....4.6.3.....3..2...5...8.7....7.....5.......98',\n \n  \/\/Used in Bracmat and Scala solutions:                ~ 6.7 seconds\n    '..............3.85..1.2.......5.7.....4...1...9.......5......73..2.1........4...9',\n \n  \/\/2nd \"exceptionally difficult\" example in Wikipedia: ~ 8.8 seconds\n    '.......39.....1..5..3.5.8....8.9...6.7...2...1..4.......9.8..5..2....6..4..7.....',\n \n  \/\/Used in MATLAB solution:                            ~15   seconds\n    '....839..1......3...4....7..42.3....6.......4....7..1..2........8...92.....25...6',\n \n  \/\/4th \"exceptionally difficult\" example in Wikipedia: ~29   seconds\n    '..3......4...8..36..8...1...4..6..73...9..........2..5..4.7..686........7..6..5..']\n \nsudokus.each { sudoku ->\n    def grid = string2grid(sudoku)\n    println '\\nPUZZLE'\n    grid.each { println it }\n \n    println '\\nSOLUTION'\n    def start = System.currentTimeMillis()\n    def solution = solve(grid)\n    def elapsed = (System.currentTimeMillis() - start)\/1000\n    solution.each { println it }\n    println \"\\nELAPSED: ${elapsed} seconds\"\n}\n\n\n","human_summarization":"implement a Sudoku solver that fills in a partially completed 9x9 grid. The solution uses an iterative non-guessing approach followed by a recursive guessing method, with exception handling for incorrect guesses. It also includes test cases for exceptionally difficult Sudokus.","id":4442}
    {"lang_cluster":"Groovy","source_code":"\n\ndef shuffle = { list ->\n    if (list == null || list.empty) return list\n    def r = new Random()\n    def n = list.size()\n    (n..1).each { i ->\n        def j = r.nextInt(i)\n        list[[i-1, j]] = list[[j, i-1]]\n    }\n    list\n}\n\n\ndef list = [] + (0..20)\nprintln list\nprintln shuffle(list)\nprintln shuffle(list)\nprintln shuffle(list)\n\n\n","human_summarization":"implement the Knuth shuffle algorithm, which randomly shuffles the elements of an array. The algorithm modifies the input array in-place, but can be amended to return a new array if necessary. It can also be adjusted to iterate from left to right.","id":4443}
    {"lang_cluster":"Groovy","source_code":"\n\ndef ymd = { it.format('yyyy-MM-dd') }\ndef lastFridays = lastWeekDays.curry(Day.Fri)\nlastFridays(args[0] as int).each { println (ymd(it)) }\n\n\n[2273] groovy lastFridays.groovy 2012\n\n","human_summarization":"The code takes a year as input and returns the dates of the last Fridays of each month for that year.","id":4444}
    {"lang_cluster":"Groovy","source_code":"\nprint \"Goodbye, world\"\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":4445}
    {"lang_cluster":"Groovy","source_code":"Library: Swing\n\nimport javax.swing.JOptionPane\n\ndef number = JOptionPane.showInputDialog (\"Enter an Integer\") as Integer\ndef string = JOptionPane.showInputDialog (\"Enter a String\")\n\nassert number instanceof Integer\nassert string instanceof String\n\n","human_summarization":"\"Code allows for the input of a string and the integer 75000 via a graphical user interface.\"","id":4446}
    {"lang_cluster":"Groovy","source_code":"\n\ndef caesarEncode(\u200bcipherKey, text) {\n    def builder = new StringBuilder()\n    text.each { character ->\n        int ch = character[0] as char\n        switch(ch) {\n            case 'a'..'z': ch = ((ch - 97 + cipherKey) % 26 + 97); break\n            case 'A'..'Z': ch = ((ch - 65 + cipherKey) % 26 + 65); break\n        }\n        builder << (ch as char)\n    } \n    builder as String\n}\ndef caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }\n\n\ndef caesarEncode(cipherKey, text) {            \n    text.chars.collect { c -> \n        int off = c.isUpperCase() ? 'A' : 'a'\n        c.isLetter() ? (((c as int) - off + cipherKey) % 26 + off) as char : c \n    }.join()    \n}   \ndef caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }\n\n\ndef caesarEncode(k, text) { \n    (text as int[]).collect { it==' ' ? ' ' : (((it & 0x1f) + k - 1) % 26 + 1 | it & 0xe0) as char }.join()\n}   \ndef caesarDecode(k, text) { caesarEncode(26 - k, text) }\n\n\ndef caesarEncode(k, text) {\n    text.tr('a-zA-Z', ((('a'..'z')*2)[k..(k+25)] + (('A'..'Z')*2)[k..(k+25)]).join())\n}\ndef caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }\n\n\ndef caesarEncode(k, text) {\n    def c = { (it*2)[k..(k+25)].join() }\n    text.tr('a-zA-Z', c('a'..'z') + c('A'..'Z'))\n}\ndef caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) }\n\n\ndef plainText = \"The Quick Brown Fox jumped over the lazy dog\"\ndef cipherKey = 12\ndef cipherText = caesarEncode(cipherKey, plainText)\ndef decodedText = caesarDecode(cipherKey, cipherText)\n \nprintln \"plainText: $plainText\"\nprintln \"cypherText($cipherKey): $cipherText\"\nprintln \"decodedText($cipherKey): $decodedText\"\n \nassert  plainText == decodedText\n\n\n","human_summarization":"implement both encoding and decoding of a Caesar cipher. The cipher uses a key ranging from 1 to 25 to rotate the letters of the alphabet, replacing each letter with the 1st to 25th next letter. The codes also consider the case of wrapping Z to A. The implemented cipher is identical to Vigen\u00e8re cipher with a key of length 1 and Rot-13 with key 13. Despite its simplicity, the cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks.","id":4447}
    {"lang_cluster":"Groovy","source_code":"\ndef gcd\ngcd = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m : m%n == 0 ? n : gcd(n, m % n) }\n\ndef lcd = { m, n -> Math.abs(m * n) \/ gcd(m, n) }\n\n[[m: 12, n: 18, l: 36],\n [m: -6, n: 14, l: 42],\n [m: 35, n: 0, l: 0]].each { t ->\n    println \"LCD of $t.m, $t.n is $t.l\"\n    assert lcd(t.m, t.n) == t.l\n}\n\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":4448}
    {"lang_cluster":"Groovy","source_code":"class Cusip {\n    private static Boolean isCusip(String s) {\n        if (s.length() != 9) return false\n        int sum = 0\n        for (int i = 0; i <= 7; i++) {\n            char c = s.charAt(i)\n\n            int v\n            if (c >= ('0' as char) && c <= ('9' as char)) {\n                v = c - 48\n            } else if (c >= ('A' as char) && c <= ('Z' as char)) {\n                v = c - 55  \/\/ lower case letters apparently invalid\n            } else if (c == '*' as char) {\n                v = 36\n            } else if (c == '@' as char) {\n                v = 37\n            } else if (c == '#' as char) {\n                v = 38\n            } else {\n                return false\n            }\n            if (i % 2 == 1) v *= 2  \/\/ check if odd as using 0-based indexing\n            sum += v \/ 10 + v % 10\n        }\n        return s.charAt(8) - 48 == (10 - (sum % 10)) % 10\n    }\n\n    static void main(String[] args) {\n        List<String> candidates=new ArrayList<>()\n        candidates.add(\"037833100\")\n        candidates.add(\"17275R102\")\n        candidates.add(\"38259P508\")\n        candidates.add(\"594918104\")\n        candidates.add(\"68389X106\")\n        candidates.add(\"68389X105\")\n        for (String candidate : candidates) {\n            System.out.printf(\"%s -> %s%n\", candidate, isCusip(candidate) ? \"correct\" : \"incorrect\")\n        }\n    }\n}\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":4449}
    {"lang_cluster":"Groovy","source_code":"\n\nprintln \"word size:  ${System.getProperty('sun.arch.data.model')}\"\nprintln \"endianness: ${System.getProperty('sun.cpu.endian')}\"\n\n\n","human_summarization":"The code prints the word size and endianness of the host machine in Java.","id":4450}
    {"lang_cluster":"Groovy","source_code":"\ndef html = new URL('http:\/\/rosettacode.org\/mw\/index.php?title=Special:Categories&limit=5000').getText([\n        connectTimeout:500,\n        readTimeout:15000,\n        requestProperties: [ 'User-Agent': 'Firefox\/2.0.0.4']])\ndef count = [:]\n(html =~ '<li><a[^>]+>([^<]+)<\/a>[^(]*[(](\\\\d+) member[s]*[)]<\/li>').each { match, language, members ->\n    count[language] = (members as int)\n}\ncount.sort { v1, v2 -> v2.value <=> v1.value }.eachWithIndex { value, index -> println \"${index + 1} $value\" }\n\n\n1 Tcl=766\n2 Racket=726\n3 Python=712\n4 Programming Tasks=695\n5 C=681\n6 Perl 6=649\n...\n48 Groovy=323\n","human_summarization":"\"Sorts and ranks computer programming languages based on the number of members in their respective Rosetta Code categories. The ranking can be obtained either by web scraping or using the API method. The code also provides an option to filter incorrect results. The final output is a complete, ranked list of all programming languages.\"","id":4451}
    {"lang_cluster":"Groovy","source_code":"\n\ndef beatles = [\"John\", \"Paul\", \"George\", \"Ringo\"]\n\nfor(name in beatles) {\n    println name\n}\n\n\nbeatles.each {\n    println it\n}\n\n\nJohn\nPaul\nGeorge\nRingo\n","human_summarization":"print each element in a collection in a sequential order using either a \"for each\" loop or any other loop if \"for each\" is not available. In Groovy, the \"each()\" method is preferred over the \"for\" loop for this task.","id":4452}
    {"lang_cluster":"Groovy","source_code":"\nprintln 'Hello,How,Are,You,Today'.split(',').join('.')\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":4453}
    {"lang_cluster":"Groovy","source_code":"\ndef gcdR\ngcdR = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m : m%n == 0 ? n : gcdR(n, m%n) }\n\ndef gcdI = { m, n -> m = m.abs(); n = n.abs(); n == 0 ? m : { while(m%n != 0) { t=n; n=m%n; m=t }; n }() }\n\n\nprintln \"                R     I\"\nprintln \"gcd(28, 0)   = ${gcdR(28, 0)} == ${gcdI(28, 0)}\"\nprintln \"gcd(0, 28)   = ${gcdR(0, 28)} == ${gcdI(0, 28)}\"\nprintln \"gcd(0, -28)  = ${gcdR(0, -28)} == ${gcdI(0, -28)}\"\nprintln \"gcd(70, -28) = ${gcdR(70, -28)} == ${gcdI(70, -28)}\"\nprintln \"gcd(70, 28)  = ${gcdR(70, 28)} == ${gcdI(70, 28)}\"\nprintln \"gcd(28, 70)  = ${gcdR(28, 70)} == ${gcdI(28, 70)}\"\nprintln \"gcd(800, 70) = ${gcdR(800, 70)} == ${gcdI(800, 70)}\"\nprintln \"gcd(27, -70) =  ${gcdR(27, -70)} ==  ${gcdI(27, -70)}\"\n\n\n                R     I\ngcd(28, 0)   = 28 == 28\ngcd(0, 28)   = 28 == 28\ngcd(0, -28)  = 28 == 28\ngcd(70, -28) = 14 == 14\ngcd(70, 28)  = 14 == 14\ngcd(28, 70)  = 14 == 14\ngcd(800, 70) = 10 == 10\ngcd(27, -70) =  1 ==  1\n","human_summarization":"find the greatest common divisor (GCD) or greatest common factor (GCF) of two integers. This is related to the task of finding the least common multiple. For more information, refer to the MathWorld and Wikipedia entries on the greatest common divisor.","id":4454}
    {"lang_cluster":"Groovy","source_code":"\n\ndef isNumeric = {\n    def formatter = java.text.NumberFormat.instance\n    def pos = [0] as java.text.ParsePosition\n    formatter.parse(it, pos)\n    \n    \/\/ if parse position index has moved to end of string\n    \/\/ them the whole string was numeric\n    pos.index == it.size()\n}\n\n\nprintln isNumeric('1')\nprintln isNumeric('-.555')\nprintln isNumeric('1,000,000')\nprintln isNumeric(' 1 1 1 1 ')\nprintln isNumeric('abcdef')\n\n\n","human_summarization":"\"Code creates a boolean function to check if a given string is numeric, including floating point and negative numbers, using the positional parser in java.text.NumberFormat. The function returns true if the parse position is at the end of the string, indicating that the entire string is a valid number.\"","id":4455}
    {"lang_cluster":"Groovy","source_code":"\nnew URL(\"https:\/\/sourceforge.net\").eachLine { println it }\n\n","human_summarization":"Send a GET request to the URL \"https:\/\/www.w3.org\/\", validate the host certificate, and print the obtained resource to the console without any authentication.","id":4456}
    {"lang_cluster":"Groovy","source_code":"\n\ndef radians = Math.PI\/4\ndef degrees = 45\n\ndef d2r = { it*Math.PI\/180 }\ndef r2d = { it*180\/Math.PI }\n\nprintln \"sin(\\u03C0\/4) = ${Math.sin(radians)}  == sin(45\\u00B0) = ${Math.sin(d2r(degrees))}\"\nprintln \"cos(\\u03C0\/4) = ${Math.cos(radians)}  == cos(45\\u00B0) = ${Math.cos(d2r(degrees))}\"\nprintln \"tan(\\u03C0\/4) = ${Math.tan(radians)}  == tan(45\\u00B0) = ${Math.tan(d2r(degrees))}\"\nprintln \"asin(\\u221A2\/2) = ${Math.asin(2**(-0.5))} == asin(\\u221A2\/2)\\u00B0 = ${r2d(Math.asin(2**(-0.5)))}\\u00B0\"\nprintln \"acos(\\u221A2\/2) = ${Math.acos(2**(-0.5))} == acos(\\u221A2\/2)\\u00B0 = ${r2d(Math.acos(2**(-0.5)))}\\u00B0\"\nprintln \"atan(1) = ${Math.atan(1)} == atan(1)\\u00B0 = ${r2d(Math.atan(1))}\\u00B0\"\n\n\n","human_summarization":"demonstrate the use of trigonometric functions including sine, cosine, tangent and their inverses in a given programming language. The functions are applied on the same angle in both radians and degrees. For non-inverse functions, the same angle is used for each radian\/degree pair. For inverse functions, the same number is used and its answer is converted to both radians and degrees. If the language does not support these functions, they are calculated using known approximations or identities. The code also handles conversion between radians and degrees.","id":4457}
    {"lang_cluster":"Groovy","source_code":"\n\ndef totalWeight = { list -> list.collect{ it.item.weight * it.count }.sum() }\ndef totalValue = { list -> list.collect{ it.item.value * it.count }.sum() }\n\ndef knapsackBounded = { possibleItems ->\n    def n = possibleItems.size()\n    def m = (0..n).collect{ i -> (0..400).collect{ w -> []} }\n    (1..400).each { w ->\n        (1..n).each { i ->\n            def item = possibleItems[i-1]\n            def wi = item.weight, pi = item.pieces\n            def bi = [w.intdiv(wi),pi].min()\n            m[i][w] = (0..bi).collect{ count ->\n                m[i-1][w - wi * count] + [[item:item, count:count]]\n            }.max(totalValue).findAll{ it.count }\n        }\n    }\n    m[n][400]\n}\n\n\ndef items = [ \n        [name:\"map\",                    weight:  9, value:150, pieces:1],\n        [name:\"compass\",                weight: 13, value: 35, pieces:1],\n        [name:\"water\",                  weight:153, value:200, pieces:2],\n        [name:\"sandwich\",               weight: 50, value: 60, pieces:2],\n        [name:\"glucose\",                weight: 15, value: 60, pieces:2],\n        [name:\"tin\",                    weight: 68, value: 45, pieces:3],\n        [name:\"banana\",                 weight: 27, value: 60, pieces:3],\n        [name:\"apple\",                  weight: 39, value: 40, pieces:3],\n        [name:\"cheese\",                 weight: 23, value: 30, pieces:1],\n        [name:\"beer\",                   weight: 52, value: 10, pieces:3],\n        [name:\"suntan cream\",           weight: 11, value: 70, pieces:1],\n        [name:\"camera\",                 weight: 32, value: 30, pieces:1],\n        [name:\"t-shirt\",                weight: 24, value: 15, pieces:2],\n        [name:\"trousers\",               weight: 48, value: 10, pieces:2],\n        [name:\"umbrella\",               weight: 73, value: 40, pieces:1],\n        [name:\"waterproof trousers\",    weight: 42, value: 70, pieces:1],\n        [name:\"waterproof overclothes\", weight: 43, value: 75, pieces:1],\n        [name:\"note-case\",              weight: 22, value: 80, pieces:1],\n        [name:\"sunglasses\",             weight:  7, value: 20, pieces:1],\n        [name:\"towel\",                  weight: 18, value: 12, pieces:2],\n        [name:\"socks\",                  weight:  4, value: 50, pieces:1],\n        [name:\"book\",                   weight: 30, value: 10, pieces:2],\n]\n \ndef start = System.currentTimeMillis()\ndef packingList = knapsackBounded(items)\ndef elapsed = System.currentTimeMillis() - start\n\nprintln \"Elapsed Time: ${elapsed\/1000.0} s\"\nprintln \"Total Weight: ${totalWeight(packingList)}\"\nprintln \" Total Value: ${totalValue(packingList)}\"\npackingList.each {\n    printf ('  item:\u00a0%-22s  weight:%4d  value:%4d  count:%2d\\n',\n            it.item.name, it.item.weight, it.item.value, it.count)\n}\n\n\n","human_summarization":"The code implements a solution to the bounded knapsack problem using dynamic programming. It helps a tourist to determine the optimal combination of items to carry in his knapsack, given a weight limit of 4 kg. The items have varying weights, values, and quantities. The goal is to maximize the total value of the items in the knapsack without exceeding the weight limit. The code ensures that only whole units of an item can be taken.","id":4458}
    {"lang_cluster":"Groovy","source_code":"\n\nprintln (((\"23455\" as BigDecimal) + 1) as String)\nprintln (((\"23455.78\" as BigDecimal) + 1) as String)\n\n\n","human_summarization":"increment a given numerical string.","id":4459}
    {"lang_cluster":"Groovy","source_code":"\n\ndef commonPath = { delim, Object[] paths ->\n    def pathParts = paths.collect { it.split(delim) }\n    pathParts.transpose().inject([match:true, commonParts:[]]) { aggregator, part ->\n        aggregator.match = aggregator.match && part.every { it == part [0] }\n        if (aggregator.match) { aggregator.commonParts << part[0] }\n        aggregator\n    }.commonParts.join(delim)\n}\n\n\nprintln commonPath('\/',\n    '\/home\/user1\/tmp\/coverage\/test',\n    '\/home\/user1\/tmp\/covert\/operator',\n    '\/home\/user1\/tmp\/coven\/members')\n\nprintln commonPath('\/',\n    '\/home\/user1\/tmp\/coverage\/test',\n    '\/home\/user1\/tmp\/covert\/test',\n    '\/home\/user1\/tmp\/coven\/test',\n    '\/home\/user1\/tmp\/covers\/test')\n\n\n\/home\/user1\/tmp\n\/home\/user1\/tmp\n","human_summarization":"finds the common directory path from a set of given directory paths using a specified directory separator character. It ensures that the returned path is a valid directory and not just the longest common string. The code also includes a mention of any built-in function in the language that performs the same task.","id":4460}
    {"lang_cluster":"Groovy","source_code":"\n\ndef median(Iterable col) {\n    def s = col as SortedSet\n    if (s == null) return null\n    if (s.empty) return 0\n    def n = s.size()\n    def m = n.intdiv(2)\n    def l = s.collect { it }\n    n%2 == 1 ? l[m] : (l[m] + l[m-1])\/2 \n}\n\n\ndef a = [4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5]\ndef sz = a.size()\n\n(0..sz).each {\n    println \"\"\"${median(a[0..<(sz-it)])} == median(${a[0..<(sz-it)]})\n${median(a[it..<sz])} == median(${a[it..<sz]})\"\"\"\n}\n\n\n4.45 == median([4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5])\n4.45 == median([4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5])\n4.4 == median([4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3])\n4.5 == median([2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5])\n3.35 == median([4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9, 8.2])\n5.55 == median([-1.7, 7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5])\n2.3 == median([4.4, 2.3, -1.7, 7.5, 6.6, 0.0, 1.9])\n6.6 == median([7.5, 6.6, 0.0, 1.9, 8.2, 9.3, 4.5])\n3.35 == median([4.4, 2.3, -1.7, 7.5, 6.6, 0.0])\n5.55 == median([6.6, 0.0, 1.9, 8.2, 9.3, 4.5])\n4.4 == median([4.4, 2.3, -1.7, 7.5, 6.6])\n4.5 == median([0.0, 1.9, 8.2, 9.3, 4.5])\n3.35 == median([4.4, 2.3, -1.7, 7.5])\n6.35 == median([1.9, 8.2, 9.3, 4.5])\n2.3 == median([4.4, 2.3, -1.7])\n8.2 == median([8.2, 9.3, 4.5])\n3.35 == median([4.4, 2.3])\n6.9 == median([9.3, 4.5])\n4.4 == median([4.4])\n4.5 == median([4.5])\n0 == median([])\n0 == median([])\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles the case of an even number of elements by returning the average of the two middle values. The code uses the selection algorithm to find the median in O(n) time. It also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. The solution uses brute force sorting with arithmetic averaging of dual midpoints for even sizes.","id":4461}
    {"lang_cluster":"Groovy","source_code":"\n1.upto(100) { i -> println \"${i\u00a0% 3\u00a0? ''\u00a0: 'Fizz'}${i\u00a0% 5\u00a0? ''\u00a0: 'Buzz'}\"\u00a0?: i }\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":4462}
    {"lang_cluster":"Groovy","source_code":"\n\n[1,2,3,4,5].sum()\n\n\n[1,2,3,4,5].inject(0) { sum, val -> sum + val }\n[1,2,3,4,5].inject(1) { prod, val -> prod * val }\n\n\nprintln ([1,2,3,4,5].inject([sum: 0, product: 1]) { result, value ->\n    [sum: result.sum + value, product: result.product * value]})\n\n","human_summarization":"calculates the sum and product of an array of integers using Groovy's \"sum()\" method and the \"inject()\" method for the product calculation.","id":4463}
    {"lang_cluster":"Groovy","source_code":"\n\n(1900..2012).findAll {new GregorianCalendar().isLeapYear(it)}.each {println it}\n\n\n","human_summarization":"determine if a given year is a leap year in the Gregorian calendar.","id":4464}
    {"lang_cluster":"Groovy","source_code":"\nclass MD5 {\n\n    private static final int INIT_A = 0x67452301\n    private static final int INIT_B = (int)0xEFCDAB89L\n    private static final int INIT_C = (int)0x98BADCFEL\n    private static final int INIT_D = 0x10325476\n\n    private static final int[] SHIFT_AMTS = [\n            7, 12, 17, 22,\n            5,  9, 14, 20,\n            4, 11, 16, 23,\n            6, 10, 15, 21\n    ]\n\n    private static final int[] TABLE_T = new int[64]\n    static\n    {\n        for (int i in 0..63)\n            TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)))\n    }\n\n    static byte[] computeMD5(byte[] message)\n    {\n        int messageLenBytes = message.length\n        int numBlocks = ((messageLenBytes + 8) >>> 6) + 1\n        int totalLen = numBlocks << 6\n        byte[] paddingBytes = new byte[totalLen - messageLenBytes]\n        paddingBytes[0] = (byte)0x80\n\n        long messageLenBits = (long)messageLenBytes << 3\n        for (int i in 0..7)\n        {\n            paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits\n            messageLenBits >>>= 8\n        }\n\n        int a = INIT_A\n        int b = INIT_B\n        int c = INIT_C\n        int d = INIT_D\n        int[] buffer = new int[16]\n        for (int i in 0..(numBlocks - 1))\n        {\n            int index = i << 6\n            for (int j in 0..63) {\n                buffer[j >>> 2] = ((int) ((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8)\n                index++\n            }\n            int originalA = a\n            int originalB = b\n            int originalC = c\n            int originalD = d\n            for (int j in 0..63)\n            {\n                int div16 = j >>> 4\n                int f = 0\n                int bufferIndex = j\n                switch (div16)\n                {\n                    case 0:\n                        f = (b & c) | (~b & d)\n                        break\n\n                    case 1:\n                        f = (b & d) | (c & ~d)\n                        bufferIndex = (bufferIndex * 5 + 1) & 0x0F\n                        break\n\n                    case 2:\n                        f = b ^ c ^ d\n                        bufferIndex = (bufferIndex * 3 + 5) & 0x0F\n                        break\n\n                    case 3:\n                        f = c ^ (b | ~d)\n                        bufferIndex = (bufferIndex * 7) & 0x0F\n                        break\n                }\n                int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)])\n                a = d\n                d = c\n                c = b\n                b = temp\n            }\n\n            a += originalA\n            b += originalB\n            c += originalC\n            d += originalD\n        }\n\n        byte[] md5 = new byte[16]\n        int count = 0\n        for (int i in 0..3)\n        {\n            int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d))\n            for (int j in 0..3)\n            {\n                md5[count++] = (byte)n\n                n >>>= 8\n            }\n        }\n        return md5\n    }\n\n    static String toHexString(byte[] b)\n    {\n        StringBuilder sb = new StringBuilder()\n        for (int i in 0..(b.length - 1))\n        {\n            sb.append(String.format(\"%02X\", b[i] & 0xFF))\n        }\n        return sb.toString()\n    }\n\n    static void main(String[] args)\n    {\n        String[] testStrings = [\"\", \"a\", \"abc\", \"message digest\", \"abcdefghijklmnopqrstuvwxyz\",\n                                \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",\n                                \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\" ]\n        for (String s : testStrings)\n            System.out.println(\"0x\" + toHexString(computeMD5(s.getBytes())) + \" <== \\\"\" + s + \"\\\"\")\n    }\n\n}\n\n","human_summarization":"The code is an implementation of the MD5 Message Digest Algorithm, developed directly from the algorithm specification without using built-in or external hashing libraries. It produces a correct message digest for an input string but does not mimic all calling modes. The code also includes handling of bit manipulation, unsigned integers, and little-endian data, with attention to details like boundary conditions and padding. The implementation is validated against the verification strings and hashes from RFC 1321.","id":4465}
    {"lang_cluster":"Groovy","source_code":"class DepartmentNumbers {\n    static void main(String[] args) {\n        println(\"Police  Sanitation  Fire\")\n        println(\"------  ----------  ----\")\n        int count = 0\n        for (int i = 2; i <= 6; i += 2) {\n            for (int j = 1; j <= 7; ++j) {\n                if (j == i) continue\n                for (int k = 1; k <= 7; ++k) {\n                    if (k == i || k == j) continue\n                    if (i + j + k != 12) continue\n                    println(\"  $i         $j         $k\")\n                    count++\n                }\n            }\n        }\n        println()\n        println(\"$count valid combinations\")\n    }\n}\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":4466}
    {"lang_cluster":"Groovy","source_code":"\n\ndef string = 'Scooby-doo-bee-doo'    \/\/ assigns string object to a variable reference\ndef stringRef = string               \/\/ assigns another variable reference to the same object\ndef stringCopy = new String(string)  \/\/ copies string value into a new object, and assigns to a third variable reference\n\n\nassert string == stringRef           \/\/ they have equal values (like Java equals(), not like Java ==)\nassert string.is(stringRef)          \/\/ they are references to the same objext (like Java ==)\nassert string == stringCopy          \/\/ they have equal values\nassert ! string.is(stringCopy)       \/\/ they are references to different objects (like Java\u00a0!=)\n\n\n","human_summarization":"The code demonstrates how to copy a string in Groovy, highlighting the difference between copying the contents of a string and creating an additional reference to an existing string. It also explains the difference in the use of the equality operator in Groovy compared to Java. The code advises against unnecessary copying of strings in Groovy due to their immutable nature.","id":4467}
    {"lang_cluster":"Groovy","source_code":"\n\ndef f, m  \/\/ recursive closures must be declared before they are defined\nf = { n -> n == 0 ? 1 : n - m(f(n-1)) }\nm = { n -> n == 0 ? 0 : n - f(m(n-1)) }\n\n\nprintln 'f(0..20): ' + (0..20).collect { f(it) }\nprintln 'm(0..20): ' + (0..20).collect { m(it) }\n\n\n","human_summarization":"The code implements two mutually recursive functions to compute the Hofstadter Female and Male sequences. The Female function is initialized with F(0) = 1 and the Male function with M(0) = 0. For n > 0, the Female function computes n minus the result of the Male function at the index of the previous Female sequence, and the Male function computes n minus the result of the Female function at the index of the previous Male sequence.","id":4468}
    {"lang_cluster":"Groovy","source_code":"\n\ndef list = [25, 30, 1, 450, 3, 78]\ndef random = new Random();\n\n(0..3).each {\n    def i = random.nextInt(list.size())\n    println \"list[${i}] == ${list[i]}\"\n}\n\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":4469}
    {"lang_cluster":"Groovy","source_code":"\nassert URLDecoder.decode('http%3A%2F%2Ffoo%20bar%2F') == 'http:\/\/foo bar\/'\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":4470}
    {"lang_cluster":"Groovy","source_code":"\n\ndef binSearchR\n\/\/define binSearchR closure.\nbinSearchR = { a, key, offset=0 ->\n    def m = n.intdiv(2)\n    def n = a.size()\n    a.empty \\\n        ? [\"The insertion point is\": offset] \\\n        : a[m] > key \\\n            ? binSearchR(a[0..<m],key, offset) \\\n            : a[m] < target \\\n                ? binSearchR(a[(m + 1)..<n],key, offset + m + 1) \\\n                : [index: offset + m]\n}\n\ndef binSearchI = { aList, target ->\n    def a = aList\n    def offset = 0\n    while (!a.empty) {\n        def n = a.size()\n        def m = n.intdiv(2)\n        if(a[m] > target) {\n            a = a[0..<m]\n        } else if (a[m] < target) {\n            a = a[(m + 1)..<n]\n            offset += m + 1\n        } else {\n            return [index: offset + m]\n        }\n    }\n    return [\"insertion point\": offset]\n}\n\n\ndef a = [] as Set\ndef random = new Random()\nwhile (a.size() < 20) { a << random.nextInt(30) }\ndef source = a.sort()\nsource[0..-2].eachWithIndex { si, i -> assert si < source[i+1] }\n\nprintln \"${source}\"\n1.upto(5) {\n    target = random.nextInt(10) + (it - 2) * 10\n    print \"Trial #${it}. Looking for: ${target}\"\n    def answers = [binSearchR, binSearchI].collect { search ->\n        search(source, target)\n    }\n    assert answers[0] == answers[1]\n    println \"\"\"\n    Answer: ${answers[0]},\u00a0: ${source[answers[0].values().iterator().next()]}\"\"\"\n}\n\n\n[1, 2, 5, 8, 9, 10, 11, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29]\nTrial #1. Looking for: -9\n    Answer: [insertion point:0],\u00a0: 1\nTrial #2. Looking for: 7\n    Answer: [insertion point:3],\u00a0: 8\nTrial #3. Looking for: 18\n    Answer: [index:9],\u00a0: 18\nTrial #4. Looking for: 29\n    Answer: [index:19],\u00a0: 29\nTrial #5. Looking for: 32\n    Answer: [insertion point:20],\u00a0: null\n","human_summarization":"The code implements a binary search algorithm to find a specific number in a sorted integer array. It includes both recursive and iterative methods. The code also handles multiple instances of the same value and indicates whether the element was found or not. It provides the index of the found element or the potential insertion point if the element is not found. The code also includes leftmost and rightmost insertion point algorithms. Additionally, it contains a fix for potential overflow bugs. The code also prints out if the number was found in the array and its index.","id":4471}
    {"lang_cluster":"Groovy","source_code":"\n\nprintln args\n\n\n$ groovy Echo this is an argument list\n[this, is, an, argument, list]\n$ groovy Echo -x alkfrew4oij -cdkjei +22\n[-x, alkfrew4oij, -cdkjei, +22]\n$\n\n","human_summarization":"The code retrieves and prints the list of command-line arguments provided to the program. It uses the args list variable to access these arguments. The code is designed to work with a command line interpreter and has been tested on a Microsoft Windows XP system using a cygwin bash shell. For intelligent parsing of command-line arguments, it utilizes the CliBuilder library, which extends the Java-based Apache Commons CLI library to Groovy.","id":4472}
    {"lang_cluster":"Groovy","source_code":"\n\nimport java.awt.*;\nimport javax.swing.*;\n\nclass Pendulum extends JPanel implements Runnable {\n\n    private angle = Math.PI \/ 2;\n    private length;\n\n    Pendulum(length) {\n        this.length = length;\n        setDoubleBuffered(true);\n    }\n\n    @Override\n    void paint(Graphics g) {\n        g.setColor(Color.WHITE);\n        g.fillRect(0, 0, getWidth(), getHeight());\n        g.setColor(Color.BLACK);\n        int anchorX = getWidth() \/ 2, anchorY = getHeight() \/ 4;\n        def ballX = anchorX + (Math.sin(angle) * length) as int;\n        def ballY = anchorY + (Math.cos(angle) * length) as int;\n        g.drawLine(anchorX, anchorY, ballX, ballY);\n        g.fillOval(anchorX - 3, anchorY - 4, 7, 7);\n        g.fillOval(ballX - 7, ballY - 7, 14, 14);\n    }\n\n    void run() {\n        def angleAccel, angleVelocity = 0, dt = 0.1;\n        while (true) {\n            angleAccel = -9.81 \/ length * Math.sin(angle);\n            angleVelocity += angleAccel * dt;\n            angle += angleVelocity * dt;\n            repaint();\n            try { Thread.sleep(15); } catch (InterruptedException ex) {}\n        }\n    }\n\n    @Override\n    Dimension getPreferredSize() {\n        return new Dimension(2 * length + 50, (length \/ 2 * 3) as int);\n    }\n\n    static void main(String[] args) {\n        def f = new JFrame(\"Pendulum\");\n        def p = new Pendulum(200);\n        f.add(p);\n        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n        f.pack();\n        f.setVisible(true);\n        new Thread(p).start();\n    }\n}\n\n","human_summarization":"simulate a physical system of a simple gravity pendulum and animate it. The Java solution has been converted to Groovy style by removing explicit definitions and converting casts where necessary.","id":4473}
    {"lang_cluster":"Groovy","source_code":"\n\ndef slurper = new groovy.json.JsonSlurper()\ndef result = slurper.parseText('''\n{\n    \"people\":[\n        {\"name\":{\"family\":\"Flintstone\",\"given\":\"Frederick\"},\"age\":35,\"relationships\":{\"wife\":\"people[1]\",\"child\":\"people[4]\"}},\n        {\"name\":{\"family\":\"Flintstone\",\"given\":\"Wilma\"},\"age\":32,\"relationships\":{\"husband\":\"people[0]\",\"child\":\"people[4]\"}},\n        {\"name\":{\"family\":\"Rubble\",\"given\":\"Barnard\"},\"age\":30,\"relationships\":{\"wife\":\"people[3]\",\"child\":\"people[5]\"}},\n        {\"name\":{\"family\":\"Rubble\",\"given\":\"Elisabeth\"},\"age\":32,\"relationships\":{\"husband\":\"people[2]\",\"child\":\"people[5]\"}},\n        {\"name\":{\"family\":\"Flintstone\",\"given\":\"Pebbles\"},\"age\":1,\"relationships\":{\"mother\":\"people[1]\",\"father\":\"people[0]\"}},\n        {\"name\":{\"family\":\"Rubble\",\"given\":\"Bam-Bam\"},\"age\":1,\"relationships\":{\"mother\":\"people[3]\",\"father\":\"people[2]\"}},\n    ]\n}\n''')\n\n\nresult.each { println it.key; it.value.each {person -> println person} }\n\nassert result.people[0].name == [family:'Flintstone', given:'Frederick']\nassert result.people[4].age == 1\nassert result.people[2].relationships.wife == 'people[3]'\nassert result.people[3].name == [family:'Rubble', given:'Elisabeth']\nassert Eval.x(result, 'x.' + result.people[2].relationships.wife + '.name') == [family:'Rubble', given:'Elisabeth']\nassert Eval.x(result, 'x.' + result.people[1].relationships.husband + '.name') == [family:'Flintstone', given:'Frederick']\n\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure and serialize it into JSON using Groovy 1.8 or later. The code also ensures the JSON is valid and can handle extra commas in arrays.\"","id":4474}
    {"lang_cluster":"Groovy","source_code":"\n\nimport static Constants.tolerance\nimport static java.math.RoundingMode.HALF_UP\n\ndef root(double base, double n) {\n    double xOld = 1\n    double xNew = 0\n    while (true) {\n        xNew = ((n - 1) * xOld + base\/(xOld)**(n - 1))\/n\n    if ((xNew - xOld).abs() < tolerance) { break }\n        xOld = xNew\n    }\n    (xNew as BigDecimal).setScale(7, HALF_UP)\n}\n\n\nclass Constants {\n    static final tolerance = 0.00001\n}\n\nprint '''\n   Base   Power  Calc'd Root  Actual Root\n-------  ------  -----------  -----------\n'''\ndef testCases = [\n    [b:32.0, n:5.0, r:2.0],\n    [b:81.0, n:4.0, r:3.0],\n    [b:Math.PI**2, n:4.0, r:Math.PI**(0.5)],\n    [b:7.0, n:0.5, r:49.0],\n]\n\ntestCases.each {\n    def r = root(it.b, it.n)\n    printf('%7.4f  %6.4f  %11.4f  %11.4f\\n',\n        it.b, it.n, r, it.r)\n    assert (r - it.r).abs() <= tolerance\n}\n\n\n   Base   Power  Calc'd Root  Actual Root\n-------  ------  -----------  -----------\n32.0000  5.0000       2.0000       2.0000\n81.0000  4.0000       3.0000       3.0000\n 9.8696  4.0000       1.7725       1.7725\n 7.0000  0.5000      49.0000      49.0000\n","human_summarization":"implement the principal nth root computation algorithm for a positive real number A.","id":4475}
    {"lang_cluster":"Groovy","source_code":"\nprintln InetAddress.localHost.hostName\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":4476}
    {"lang_cluster":"Groovy","source_code":"\nfinal random = new Random()\nfinal input = new Scanner(System.in)\n\n\ndef evaluate = { expr ->\n    if (expr == 'QUIT') {\n        return 'QUIT'\n    } else {\n        try { Eval.me(expr.replaceAll(\/(\\d)\/, '$1.0')) }\n        catch (e) { 'syntax error' }\n    }\n}\n\n\ndef readGuess = { digits ->\n    while (true) {\n        print \"Enter your guess using ${digits} (q to quit): \"\n        def expr = input.nextLine()\n        \n        switch (expr) {\n            case ~\/^[qQ].*\/:\n                return 'QUIT'\n\n            case ~\/.*[^\\d\\s\\+\\*\\\/\\(\\)-].*\/:\n                def badChars = expr.replaceAll(~\/[\\d\\s\\+\\*\\\/\\(\\)-]\/, '')\n                println \"invalid characters in input: ${(badChars as List) as Set}\"\n                break\n\n            case { (it.replaceAll(~\/\\D\/, '') as List).sort() != ([]+digits).sort() }:\n                println '''you didn't use the right digits'''\n                break\n\n            case ~\/.*\\d\\d.*\/:\n                println 'no multi-digit numbers allowed'\n                break\n\n            default:\n                return expr\n        }\n    }\n}\n\n\ndef digits = (1..4).collect { (random.nextInt(9) + 1) as String }\n\nwhile (true) {\n    def guess = readGuess(digits)\n    def result = evaluate(guess)\n    \n    switch (result) {\n        case 'QUIT':\n            println 'Awwww. Maybe next time?'\n            return\n            \n        case 24:\n            println 'Yes! You got it.'\n            return\n            \n        case 'syntax error':\n            println \"A ${result} was found in ${guess}\" \n            break\n            \n        default:\n            println \"Nope: ${guess} == ${result}, not 24\"\n            println 'One more try, then?'\n    }\n}\n\n\n$ groovy TwentyFour.gsh\nEnter your guess using [4, 8, 3, 6] (q to quit): 4836\nno multi-digit numbers allowed\nEnter your guess using [4, 8, 3, 6] (q to quit): 4  ++ ++ 8\/ 3-6\nA syntax error was found in 4  ++ ++ 8\/ 3-6\nEnter your guess using [4, 8, 3, 6] (q to quit): btsjsb\ninvalid characters in input: [t, s, b, j]\nEnter your guess using [4, 8, 3, 6] (q to quit): 1+3+2+2\nyou didn't use the right digits\nEnter your guess using [4, 8, 3, 6] (q to quit): q\nAwwww. Maybe next time?\n\n$ groovy TwentyFour.gsh\nEnter your guess using [6, 3, 2, 6] (q to quit): 6+6+3+2\nNope: 6+6+3+2 == 17.0, not 24\nOne more try, then?\nEnter your guess using [6, 3, 2, 6] (q to quit): (6*3 - 6) * 2\nYes! You got it.\n","human_summarization":"The code implements the 24 Game, where it randomly selects four digits from 1 to 9 and prompts the player to form an arithmetic expression that equals 24 using these digits. The expression can only use each digit once and can include multiplication, division, addition, and subtraction. The code also allows for the use of brackets and floating point division. It does not allow the formation of multiple digit numbers from the provided digits. The game quits if a line starting with \"q\" is entered.","id":4477}
    {"lang_cluster":"Groovy","source_code":"\ndef rleEncode(text) {\n    def encoded = new StringBuilder()\n    (text =~ \/(([A-Z])\\2*)\/).each { matcher ->\n        encoded.append(matcher[1].size()).append(matcher[2])\n    }\n    encoded.toString()\n}\n\ndef rleDecode(text) {\n    def decoded = new StringBuilder()\n    (text =~ \/([0-9]+)([A-Z])\/).each { matcher ->\n        decoded.append(matcher[2] * Integer.parseInt(matcher[1]))\n    }\n    decoded.toString()\n}\n\n\ndef text = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'\ndef rleEncoded = rleEncode(text)\nassert rleEncoded == '12W1B12W3B24W1B14W'\nassert text == rleDecode(rleEncoded)\n\nprintln \"Original Text: $text\"\nprintln \"Encoded Text: $rleEncoded\"\n\n\nOriginal Text: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\nEncoded Text: 12W1B12W3B24W1B14W\n","human_summarization":"implement a run-length encoding algorithm that compresses strings of repeated uppercase characters by storing the length of the run. It also provides a function to reverse the compression. The output can be any format that can be used to recreate the original input.","id":4478}
    {"lang_cluster":"Groovy","source_code":"\ndef s = \"Greetings \"\nprintln s + \"Earthlings\"\n\ndef s1 = s + \"Earthlings\"\nprintln s1\n\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":4479}
    {"lang_cluster":"Groovy","source_code":"\ndef normal = \"http:\/\/foo bar\/\"\ndef encoded = URLEncoder.encode(normal, \"utf-8\")\nprintln encoded\n\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":4480}
    {"lang_cluster":"Groovy","source_code":"\n\nimport static java.math.RoundingMode.*\n\ndef knapsackCont = { list, maxWeight = 15.0 ->\n    list.sort{ it.weight \/ it.value }\n    def remainder = maxWeight\n    List sack = []\n    for (item in list) {\n        if (item.weight < remainder) {\n            sack << [name: item.name, weight: item.weight,\n                        value: (item.value as BigDecimal).setScale(2, HALF_UP)]\n        } else {\n            sack << [name: item.name, weight: remainder,\n                        value: (item.value * remainder \/ item.weight).setScale(2, HALF_UP)]\n            break\n        }\n        remainder -= item.weight\n    }\n    sack\n}\n\n\ndef possibleItems = [\n    [name:'beef',    weight:3.8, value:36],\n    [name:'pork',    weight:5.4, value:43],\n    [name:'ham',     weight:3.6, value:90],\n    [name:'greaves', weight:2.4, value:45],\n    [name:'flitch',  weight:4.0, value:30],\n    [name:'brawn',   weight:2.5, value:56],\n    [name:'welt',    weight:3.7, value:67],\n    [name:'salami',  weight:3.0, value:95],\n    [name:'sausage', weight:5.9, value:98],\n]\n\ndef contents = knapsackCont(possibleItems)\nprintln \"Total Value: ${contents*.value.sum()}\"\ncontents.each {\n    printf(\"    name:\u00a0%-7s  weight: ${it.weight}  value: ${it.value}\\n\", it.name)\n}\n\n\nTotal Value: 349.38\n    name: salami   weight: 3.0  value: 95.00\n    name: ham      weight: 3.6  value: 90.00\n    name: brawn    weight: 2.5  value: 56.00\n    name: greaves  weight: 2.4  value: 45.00\n    name: welt     weight: 3.5  value: 63.38\n","human_summarization":"implement a solution for the continuous knapsack problem. The thief can select and cut items from a butcher's shop to maximize his profit, given a knapsack with a maximum capacity of 15 kg. The items have different weights and prices, and the price after cutting is proportional to the original price by the ratio of masses. The code determines the optimal selection of items to maximize total value without exceeding the knapsack's weight limit.","id":4481}
    {"lang_cluster":"Groovy","source_code":"\n\ndef words = new URL('http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt').text.readLines()\ndef groups = words.groupBy{ it.toList().sort() }\ndef bigGroupSize = groups.collect{ it.value.size() }.max()\ndef isBigAnagram = { it.value.size() == bigGroupSize }\nprintln groups.findAll(isBigAnagram).collect{ it.value }.collect{ it.join(' ') }.join('\\n')\n\n\n","human_summarization":"<output> find the largest sets of anagrams from a given word list located at http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt.","id":4482}
    {"lang_cluster":"Groovy","source_code":"\n\ndef base3 = { BigInteger i -> i.toString(3) }\n\ndef sierpinskiCarpet = { int order ->\n    StringBuffer sb = new StringBuffer()\n    def positions = 0..<(3**order)\n    def digits = 0..<([order,1].max())\n\n    positions.each { i ->\n        String i3 = base3(i).padLeft(order, '0')\n\n        positions.each { j ->\n            String j3 = base3(j).padLeft(order, '0')\n\n            sb << (digits.any{ i3[it] == '1' && j3[it] == '1' } ? '  ' : order.toString().padRight(2) )\n        }\n        sb << '\\n'\n    }\n    sb.toString()\n}\n\n\n(0..4).each { println sierpinskiCarpet(it) }\n\n\n","human_summarization":"generate an ASCII-art or graphical representation of a Sierpinski carpet of a given order N, using the placement of whitespace and non-whitespace characters. The program uses list-indexing of base 3 string representation to achieve this. The '#' character is used for ASCII art but is not strictly necessary.","id":4483}
    {"lang_cluster":"Groovy","source_code":"\n\nimport groovy.transform.*\n\n@Canonical\n@Sortable(includes = ['freq', 'letter'])\nclass Node {\n    String letter\n    int freq\n    Node left\n    Node right\n    boolean isLeaf() { left == null && right == null }    \n}\n\nMap correspondance(Node n, Map corresp = [:], String prefix = '') {\n    if (n.isLeaf()) {\n        corresp[n.letter] = prefix ?: '0'\n    } else {\n        correspondance(n.left,  corresp, prefix + '0')\n        correspondance(n.right, corresp, prefix + '1')\n    }\n    return corresp\n}\n\nMap huffmanCode(String message) {\n    def queue = message.toList().countBy { it } \/\/ char frequencies\n        .collect { String letter, int freq ->   \/\/ transformed into tree nodes\n            new Node(letter, freq) \n        } as TreeSet \/\/ put in a queue that maintains ordering\n    \n    while(queue.size() > 1) {\n        def (nodeLeft, nodeRight)  = [queue.pollFirst(), queue.pollFirst()]\n        \n        queue << new Node(\n            freq:   nodeLeft.freq   + nodeRight.freq,\n            letter: nodeLeft.letter + nodeRight.letter,\n            left: nodeLeft, right: nodeRight\n        )\n    }\n    \n    return correspondance(queue.pollFirst())\n}\n\nString encode(CharSequence msg, Map codeTable) {\n    msg.collect { codeTable[it] }.join()\n}\n\nString decode(String codedMsg, Map codeTable, String decoded = '') {\n    def pair = codeTable.find { k, v -> codedMsg.startsWith(v) }\n    pair ? pair.key + decode(codedMsg.substring(pair.value.size()), codeTable)\n         : decoded   \n}\n\n\ndef message = \"this is an example for huffman encoding\"\n\ndef codeTable = huffmanCode(message)\ncodeTable.each { k, v -> println \"$k: $v\" }\n\ndef encoded = encode(message, codeTable)\nprintln encoded\n\ndef decoded = decode(encoded, codeTable)\nprintln decoded\n\n\n","human_summarization":"The code implements Huffman encoding algorithm to generate binary codes for each character in a given string based on their frequency of occurrence. It first creates a priority queue with each character as a leaf node. It then constructs a binary tree by continuously removing two nodes with the highest priority (lowest probability) and creating a new internal node with these two nodes as children. The process continues until there's only one node left in the queue, which becomes the root node. The code then traverses the binary tree from root to leaves, assigning '0' for one branch and '1' for the other at each node. The accumulated zeros and ones at each leaf form the Huffman encoding for the corresponding character.","id":4484}
    {"lang_cluster":"Groovy","source_code":"\nimport groovy.swing.SwingBuilder\n\ncount = 0\nnew SwingBuilder().edt {\n  frame(title:'Click frame', pack: true, show: true) {\n    vbox {  \n      countLabel = label(\"There have been no clicks yet.\")\n      button('Click Me', actionPerformed: {count++; countLabel.text = \"Clicked ${count} time(s).\"})\n    }\n  }\n}\n\n\nimport groovy.swing.SwingBuilder\nimport groovy.beans.Bindable\n\n@Bindable class Model {\n   Integer count = 0\n}\nmodel = new Model()\nnew SwingBuilder().edt {\n  frame(title:'Click frame', pack: true, show: true) {\n    vbox {  \n      label(text: bind(source: model, sourceProperty: 'count',\n        converter: { v -> !v ? \"There have been no clicks yet.\" : \"Clicked ${v} time(s).\"}))\n      button('Click Me', actionPerformed: {model.count++})\n    }\n  }\n}\n\n","human_summarization":"\"Create a windowed application with a label and a button. The label initially displays 'There have been no clicks yet'. The button, labeled 'click me', updates the label to show the number of times it has been clicked when pressed.\"","id":4485}
    {"lang_cluster":"Groovy","source_code":"\nfor (i in (10..0)) {\n    println i\n}\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":4486}
    {"lang_cluster":"Groovy","source_code":"\n\nfor(i in (2..9).step(2)) {\n    print \"${i} \"\n}\nprintln \"Who do we appreciate?\"\n\n\n(2..9).step(2).each {\n    print \"${it} \"\n}\nprintln \"Who do we appreciate?\"\n\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one and also illustrate the use of the \"each()\" method, which is a preferred alternative to a \"for\" loop in Groovy programming.","id":4487}
    {"lang_cluster":"Groovy","source_code":"\ndef sum = { i, lo, hi, term ->\n    (lo..hi).sum { i.value = it; term() }\n}\ndef obj = [:]\nprintln (sum(obj, 1, 100, { 1 \/ obj.value }))\n\n\n5.1873775176\n","human_summarization":"The code demonstrates Jensen's Device, a programming technique that uses call by name. It calculates the 100th harmonic number by passing parameters by name to a sum procedure. The procedure re-evaluates the expression in the caller's context every time the parameter's value is required. The first parameter to the sum, representing the \"bound\" variable of the summation, is also passed by name to make changes visible in the caller's context. The global variable does not have to use the same identifier as the formal parameter.","id":4488}
    {"lang_cluster":"Groovy","source_code":"\nBigInteger q = 1, r = 0, t = 1, k = 1, n = 3, l = 3\nString nn\nboolean first = true\n\nwhile (true) {\n    (nn, first, q, r, t, k, n, l) = (4*q + r - t < n*t) \\\n        ? [\"${n}${first?'.':''}\", false, 10*q, 10*(r - n*t), t  , k    , 10*(3*q + r)\/t - 10*n    , l    ] \\\n       \u00a0: [''                   , first, q*k , (2*q + r)*l , t*l, k + 1, (q*(7*k + 2) + r*l)\/(t*l), l + 2]\n    print nn\n}\n\n\n3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337\n","human_summarization":"continuously calculate and display the next decimal digit of Pi. The program runs indefinitely until manually stopped by the user. The output starts with the decimal sequence 3.14159265. The task is specifically about calculating Pi, not using built-in Pi constants.","id":4489}
    {"lang_cluster":"Groovy","source_code":"\n\nclass CList extends ArrayList implements Comparable {\n    CList() { }\n    CList(Collection c) { super(c) }\n    int compareTo(Object that) {\n        assert that instanceof List\n        def n = [this.size(), that.size()].min()\n        def comp = [this[0..<n], that[0..<n]].transpose().find { it[0] != it[1] }\n        comp ? comp[0] <=> comp[1] : this.size() <=> that.size()\n    }\n}\n\n\nCList a, b; (a, b) = [[], []]; assert ! (a < b)\nb = [1] as CList;              assert   (a < b)\na = [1] as CList;              assert ! (a < b)\nb = [2] as CList;              assert   (a < b)\na = [2, -1, 0] as CList;       assert ! (a < b)\nb = [2, -1] as CList;          assert ! (a < b)\nb = [2, -1, 0] as CList;       assert ! (a < b)\nb = [2, -1, 0, -17] as CList;  assert   (a < b)\na = [2,  8, 0] as CList;       assert ! (a < b)\n\n","human_summarization":"\"Function to compare two numerical lists lexicographically and return true if the first list should be ordered before the second, false otherwise.\"","id":4490}
    {"lang_cluster":"Groovy","source_code":"\ndef ack ( m, n ) {\n    assert m >= 0 && n >= 0 : 'both arguments must be non-negative'\n    m == 0 ? n + 1 : n == 0 ? ack(m-1, 1) : ack(m-1, ack(m, n-1))\n}\n\n\ndef ackMatrix = (0..3).collect { m -> (0..8).collect { n -> ack(m, n) } }\nackMatrix.each { it.each { elt -> printf \"%7d\", elt }; println() }\n\n\n","human_summarization":"The code is a function that implements the Ackermann function, a non-primitive recursive function. It takes two non-negative arguments and returns their Ackermann value. The function is designed to handle large values due to the rapid growth of the Ackermann function. However, it may cause a stack overflow error for certain inputs.","id":4491}
    {"lang_cluster":"Groovy","source_code":"a = [ 1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108,\n     -0.04200263503409523553, 0.16653861138229148950, -0.04219773455554433675,\n     -0.00962197152787697356, 0.00721894324666309954, -0.00116516759185906511,\n     -0.00021524167411495097, 0.00012805028238811619, -0.00002013485478078824,\n     -0.00000125049348214267, 0.00000113302723198170, -0.00000020563384169776,\n      0.00000000611609510448, 0.00000000500200764447, -0.00000000118127457049,\n      0.00000000010434267117, 0.00000000000778226344, -0.00000000000369680562,\n      0.00000000000051003703, -0.00000000000002058326, -0.00000000000000534812,\n      0.00000000000000122678, -0.00000000000000011813, 0.00000000000000000119,\n      0.00000000000000000141, -0.00000000000000000023, 0.00000000000000000002].reverse()\n\ndef gamma = { 1.0 \/ a.inject(0) { sm, a_i -> sm * (it - 1) + a_i } }\n\n(1..10).each{ printf(\"%  1.9e\\n\", gamma(it \/ 3.0)) }\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":4492}
    {"lang_cluster":"Groovy","source_code":"\n\ndef listOrder = { a, b ->\n    def k = [a.size(), b.size()].min()\n    def i = (0..<k).find { a[it] != b[it] }\n    (i != null) ? a[i] <=> b[i] : a.size() <=> b.size()\n}\n\ndef orderedPermutations = { list ->\n    def n = list.size()\n    (0..<n).permutations().sort(listOrder)\n}\n\ndef diagonalSafe = { list ->\n    def n = list.size()\n    n == 1 || (0..<(n-1)).every{ i ->\n        ((i+1)..<n).every{ j ->\n            !([list[i]+j-i, list[i]+i-j].contains(list[j]))\n        }\n    }\n}\n\ndef queensDistinctSolutions = { n ->\n    \/\/ each permutation is an N-Rooks solution\n    orderedPermutations((0..<n)).findAll (diagonalSafe)\n}\n\n\nclass Reflect {\n    public static final diag = { list ->\n        final n = list.size()\n        def tList = [0] * n\n        (0..<n).each { tList[list[it]] = it }\n        tList\n    }\n    \n    public static final vert = { list ->\n        list.reverse()\n    }\n    \n    public static final horiz = { list ->\n        final n = list.size()\n        list.collect { n - it - 1 }\n    }\n}\n\nenum Rotations {\n    r0([]),\n    r90([Reflect.vert, Reflect.diag]),\n    r180([Reflect.vert, Reflect.diag, Reflect.vert, Reflect.diag]),\n    r270([Reflect.diag, Reflect.vert]);\n    \n    private final List operations\n    \n    private Rotations(List ops) {\n        operations = ops ?: []\n    }\n    \n    public static void eliminateDups(primary, solutions) {\n        (r0..r270).each { rot -> rot.eliminateDuplicates(primary, solutions) }\n    }\n    \n    private void eliminateDuplicates(primary, solutions) {\n        def rotated = [] + primary\n        operations.each { rotated = it(rotated) }\n        solutions.removeAll([rotated, Reflect.vert(rotated)])\n    }\n}\n\ndef queensUniqueSolutions = { start ->\n    assert start instanceof Number || start instanceof List\n    def qus = (start instanceof Number) \\\n                ? queensDistinctSolutions(start) \\\n                : [] + start\n    for (def i = 0; i < qus.size()-1; i++) {\n        Rotations.eliminateDups(qus[i], qus[(i+1)..<(qus.size())])\n    }\n    qus\n}\n\n\n(1..9).each { n ->\n    def qds = queensDistinctSolutions(n)\n    def qus = queensUniqueSolutions(qds)\n    println ([boardSize:n, \"number of distinct solutions\":qds.size(), \"number of unique solutions\":qus.size()])\n    if(n < 9) { qus.each { println it } }\n    else { println \"first:${qus[0]}\"; println \"last:${qus[-1]}\" }\n    println()\n}\n\n\n[1, 3, 0, 2]\n\nrow 0 has a queen in column 1\nrow 1 has a queen in column 3\nrow 2 has a queen in column 0\nrow 3 has a queen in column 2\n\n   ---- ---- ---- ---- \n3 |    |\/\/\/\/| \u265b |\/\/\/\/|\n   ---- ---- ---- ---- \n2 |\/\u265b\/|    |\/\/\/\/|    |\n   ---- ---- ---- ---- \n1 |    |\/\/\/\/|    |\/\u265b\/|\n   ---- ---- ---- ----\n0 |\/\/\/\/| \u265b |\/\/\/\/|    |\n   ---- ---- ---- ---- \n    0    1    2    3\n\n[boardSize:1, number of distinct solutions:1, number of unique solutions:1]\n[0]\n\n[boardSize:2, number of distinct solutions:0, number of unique solutions:0]\n\n[boardSize:3, number of distinct solutions:0, number of unique solutions:0]\n\n[boardSize:4, number of distinct solutions:2, number of unique solutions:1]\n[1, 3, 0, 2]\n\n[boardSize:5, number of distinct solutions:10, number of unique solutions:2]\n[0, 2, 4, 1, 3]\n[1, 4, 2, 0, 3]\n\n[boardSize:6, number of distinct solutions:4, number of unique solutions:1]\n[1, 3, 5, 0, 2, 4]\n\n[boardSize:7, number of distinct solutions:40, number of unique solutions:6]\n[0, 2, 4, 6, 1, 3, 5]\n[0, 3, 6, 2, 5, 1, 4]\n[1, 3, 0, 6, 4, 2, 5]\n[1, 4, 0, 3, 6, 2, 5]\n[1, 4, 6, 3, 0, 2, 5]\n[1, 5, 2, 6, 3, 0, 4]\n\n[boardSize:8, number of distinct solutions:92, number of unique solutions:12]\n[0, 4, 7, 5, 2, 6, 1, 3]\n[0, 5, 7, 2, 6, 3, 1, 4]\n[1, 3, 5, 7, 2, 0, 6, 4]\n[1, 4, 6, 0, 2, 7, 5, 3]\n[1, 4, 6, 3, 0, 7, 5, 2]\n[1, 5, 0, 6, 3, 7, 2, 4]\n[1, 5, 7, 2, 0, 3, 6, 4]\n[1, 6, 2, 5, 7, 4, 0, 3]\n[1, 6, 4, 7, 0, 3, 5, 2]\n[2, 4, 1, 7, 0, 6, 3, 5]\n[2, 4, 7, 3, 0, 6, 1, 5]\n[2, 5, 1, 4, 7, 0, 6, 3]\n\n[boardSize:9, number of distinct solutions:352, number of unique solutions:46]\nfirst:[0, 2, 5, 7, 1, 3, 8, 6, 4]\nlast:[3, 1, 6, 8, 0, 7, 4, 2, 5]\n","human_summarization":"\"Output: The code solves the N-queens puzzle by generating N! distinct solutions from the N-Rooks problem, then filters out the candidates where all Queens are mutually diagonal-safe. It provides both distinct and unique solutions, accounting for reflections and rotations. The results are presented as a list of N numbers, each representing a column number within the list-indexed row.\"","id":4493}
    {"lang_cluster":"Groovy","source_code":"\n\ndef list = [1, 2, 3] + [\"Crosby\", \"Stills\", \"Nash\", \"Young\"]\n\n\nprintln list\n\n\n","human_summarization":"demonstrate how to concatenate two arrays.","id":4494}
    {"lang_cluster":"Groovy","source_code":"\n\ndef totalWeight = { list -> list*.weight.sum() }\ndef totalValue = { list -> list*.value.sum() }\n \ndef knapsack01bf = { possibleItems ->\n    possibleItems.subsequences().findAll{ ss ->\n        def w = totalWeight(ss)\n        350 < w && w < 401\n    }.max(totalValue)\n}\n\n\ndef knapsack01dp = { possibleItems ->\n    def n = possibleItems.size()\n    def m = (0..n).collect{ i -> (0..400).collect{ w -> []} }\n    (1..400).each { w ->\n        (1..n).each { i ->\n            def wi = possibleItems[i-1].weight\n            m[i][w] = wi > w ? m[i-1][w] : ([m[i-1][w], m[i-1][w-wi] + [possibleItems[i-1]]].max(totalValue))\n        }\n    }\n    m[n][400]\n}\n\n\ndef items = [ \n        [name:\"map\", weight:9, value:150],\n        [name:\"compass\", weight:13, value:35],\n        [name:\"water\", weight:153, value:200],\n        [name:\"sandwich\", weight:50, value:160],\n        [name:\"glucose\", weight:15, value:60],\n        [name:\"tin\", weight:68, value:45],\n        [name:\"banana\", weight:27, value:60],\n        [name:\"apple\", weight:39, value:40],\n        [name:\"cheese\", weight:23, value:30],\n        [name:\"beer\", weight:52, value:10],\n        [name:\"suntan cream\", weight:11, value:70],\n        [name:\"camera\", weight:32, value:30],\n        [name:\"t-shirt\", weight:24, value:15],\n        [name:\"trousers\", weight:48, value:10],\n        [name:\"umbrella\", weight:73, value:40],\n        [name:\"waterproof trousers\", weight:42, value:70],\n        [name:\"waterproof overclothes\", weight:43, value:75],\n        [name:\"note-case\", weight:22, value:80],\n        [name:\"sunglasses\", weight:7, value:20],\n        [name:\"towel\", weight:18, value:12],\n        [name:\"socks\", weight:4, value:50],\n        [name:\"book\", weight:30, value:10],\n]\n\n[knapsack01bf, knapsack01dp].each { knapsack01 ->\n    def start = System.currentTimeMillis()\n    def packingList = knapsack01(items)\n    def elapsed = System.currentTimeMillis() - start\n    \n    println \"\\n\\n\\nElapsed Time: ${elapsed\/1000.0} s\"\n    println \"Total Weight: ${totalWeight(packingList)}\"\n    println \" Total Value: ${totalValue(packingList)}\"\n    packingList.each {\n        printf (\"  item:\u00a0%-25s  weight:%4d  value:%4d\\n\", it.name, it.weight, it.value)\n    }\n}\n\n\n","human_summarization":"\"Output: The code determines the optimal combination of items the tourist can carry in his knapsack, with a maximum weight limit of 4kg, to maximize the total value. It uses brute force and dynamic programming methods to solve the 0-1 Knapsack problem.\"","id":4495}
    {"lang_cluster":"Groovy","source_code":"\nimport static Man.*\nimport static Woman.*\n\nMap<Woman,Man> match(Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {\n    Map<Woman,Man> engagedTo = new TreeMap()\n    List<Man> freeGuys = (Man.values()).clone()\n    while(freeGuys) {\n        Man thisGuy = freeGuys[0]\n        freeGuys -= thisGuy\n        List<Woman> guyChoices = Woman.values().sort{ she -> - guysGalRanking[thisGuy][she] }\n        for(Woman girl in guyChoices) {\n            if(! engagedTo[girl]) {\n                engagedTo[girl] = thisGuy\n                break\n            } else {\n                Man thatGuy = engagedTo[girl]\n                if (galsGuyRanking[girl][thisGuy] > galsGuyRanking[girl][thatGuy]) {\n                    engagedTo[girl] = thisGuy\n                    freeGuys << thatGuy\n                    break\n                }\n            }\n        }\n    }\n    engagedTo\n}\n\n\nboolean isStable(Map<Woman,Man> matches, Map<Man,Map<Woman,Integer>> guysGalRanking, Map<Woman,Map<Man,Integer>> galsGuyRanking) {\n    matches.collect{ girl, guy ->\n        int guysRank = galsGuyRanking[girl][guy]\n        List<Man> sheLikesBetter = Man.values().findAll{ he -> galsGuyRanking[girl][he] > guysRank }\n        for(Man otherGuy : sheLikesBetter) {\n            Woman otherGuyFiancee = matches.find{ pair -> pair.value == otherGuy }.key\n            if(guysGalRanking[otherGuy][girl] > guysGalRanking[otherGuy][otherGuyFiancee]) {\n                println \"\"\"O. M. G. ... ${otherGuy} likes ${girl} better than ${otherGuyFiancee}, and ${girl} likes ${otherGuy} better than ${guy}!\n                            I am TOTALLY 'shipping ${girl} and ${otherGuy} now!\"\"\"\n                return false\n            } \n        }\n        \n        int galsRank = guysGalRanking[guy][girl]\n        List<Woman> heLikesBetter = Woman.values().findAll{ she -> guysGalRanking[guy][she] > galsRank }\n        for(Woman otherGal : heLikesBetter) {\n            Man otherGalFiance = matches[otherGal]\n            if(galsGuyRanking[otherGal][guy] > galsGuyRanking[otherGal][otherGalFiance]) {\n                println \"\"\"O. M. G. ... ${otherGal} likes ${guy} better than ${otherGalFiance}, and ${guy} likes ${otherGal} better than ${girl}!\n                            I am TOTALLY 'shipping ${guy} and ${otherGal} now!\"\"\"\n                return false\n            } \n        }\n        true\n    }.every()\n}\n\n\nenum Man {\n    abe, bob, col, dan, ed, fred, gav, hal, ian, jon\n}\n\nenum Woman {\n    abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan\n}\n\nMap<Man,Map<Woman,Integer>> mansWomanRanking = [\n    (abe): [(abi):10, (eve):9, (cath):8, (ivy):7, (jan):6, (dee):5, (fay):4, (bea):3, (hope):2, (gay):1],\n    (bob): [(cath):10, (hope):9, (abi):8, (dee):7, (eve):6, (fay):5, (bea):4, (jan):3, (ivy):2, (gay):1],\n    (col): [(hope):10, (eve):9, (abi):8, (dee):7, (bea):6, (fay):5, (ivy):4, (gay):3, (cath):2, (jan):1],\n    (dan): [(ivy):10, (fay):9, (dee):8, (gay):7, (hope):6, (eve):5, (jan):4, (bea):3, (cath):2, (abi):1],\n    (ed):  [(jan):10, (dee):9, (bea):8, (cath):7, (fay):6, (eve):5, (abi):4, (ivy):3, (hope):2, (gay):1],\n    (fred):[(bea):10, (abi):9, (dee):8, (gay):7, (eve):6, (ivy):5, (cath):4, (jan):3, (hope):2, (fay):1],\n    (gav): [(gay):10, (eve):9, (ivy):8, (bea):7, (cath):6, (abi):5, (dee):4, (hope):3, (jan):2, (fay):1],\n    (hal): [(abi):10, (eve):9, (hope):8, (fay):7, (ivy):6, (cath):5, (jan):4, (bea):3, (gay):2, (dee):1],\n    (ian): [(hope):10, (cath):9, (dee):8, (gay):7, (bea):6, (abi):5, (fay):4, (ivy):3, (jan):2, (eve):1],\n    (jon): [(abi):10, (fay):9, (jan):8, (gay):7, (eve):6, (bea):5, (dee):4, (cath):3, (ivy):2, (hope):1],\n]\n \nMap<Woman,List<Man>> womansManRanking = [\n    (abi): [(bob):10, (fred):9, (jon):8, (gav):7, (ian):6, (abe):5, (dan):4, (ed):3, (col):2, (hal):1],\n    (bea): [(bob):10, (abe):9, (col):8, (fred):7, (gav):6, (dan):5, (ian):4, (ed):3, (jon):2, (hal):1],\n    (cath):[(fred):10, (bob):9, (ed):8, (gav):7, (hal):6, (col):5, (ian):4, (abe):3, (dan):2, (jon):1],\n    (dee): [(fred):10, (jon):9, (col):8, (abe):7, (ian):6, (hal):5, (gav):4, (dan):3, (bob):2, (ed):1],\n    (eve): [(jon):10, (hal):9, (fred):8, (dan):7, (abe):6, (gav):5, (col):4, (ed):3, (ian):2, (bob):1],\n    (fay): [(bob):10, (abe):9, (ed):8, (ian):7, (jon):6, (dan):5, (fred):4, (gav):3, (col):2, (hal):1],\n    (gay): [(jon):10, (gav):9, (hal):8, (fred):7, (bob):6, (abe):5, (col):4, (ed):3, (dan):2, (ian):1],\n    (hope):[(gav):10, (jon):9, (bob):8, (abe):7, (ian):6, (dan):5, (hal):4, (ed):3, (col):2, (fred):1],\n    (ivy): [(ian):10, (col):9, (hal):8, (gav):7, (fred):6, (bob):5, (abe):4, (ed):3, (jon):2, (dan):1],\n    (jan): [(ed):10, (hal):9, (gav):8, (abe):7, (bob):6, (jon):5, (col):4, (ian):3, (fred):2, (dan):1],\n]\n\n\/\/ STABLE test\nMap<Woman,Man> matches = match(mansWomanRanking, womansManRanking)\nmatches.each { w, m ->\n    println \"${w} (his '${mansWomanRanking[m][w]}' girl) is engaged to ${m} (her '${womansManRanking[w][m]}' guy)\"\n}\nassert matches.keySet() == Woman.values() as Set\nassert matches.values() as Set == Man.values() as Set\nprintln ''\n\nassert isStable(matches, mansWomanRanking, womansManRanking)\n\n\/\/ PERTURBED test\nprintln 'Swapping partners now ...'\ndef temp = matches[abi]\nmatches[abi] = matches[bea]\nmatches[bea] = temp\nmatches.each { w, m ->\n    println \"${w} (his '${mansWomanRanking[m][w]}' girl) is engaged to ${m} (her '${womansManRanking[w][m]}' guy)\"\n}\nprintln ''\n\nassert ! isStable(matches, mansWomanRanking, womansManRanking)\n\n\n","human_summarization":"The code implements the Gale\/Shapley algorithm to solve the Stable Marriage problem. It takes as input a list of ten males and ten females with their respective ranked preferences. The code then finds a stable set of engagements where no individual prefers someone else over their current partner. The code also perturbs this stable set to form an unstable set of engagements and checks for its stability.","id":4496}
    {"lang_cluster":"Groovy","source_code":"\n\ndef f = { println '  AHA!'; it instanceof String }\ndef g = { printf ('%5d ', it); it > 50 }\n\nprintln 'bitwise'\nassert g(100) & f('sss')\nassert g(2) | f('sss')\nassert ! (g(1) & f('sss'))\nassert g(200) | f('sss')\n\nprintln '''\nlogical'''\nassert g(100) && f('sss')\nassert g(2) || f('sss')\nassert ! (g(1) && f('sss'))\nassert g(200) || f('sss')\n\n\n","human_summarization":"The code defines two functions, a and b, both of which take a boolean value as input, return the same value, and print their names when called. It then calculates the values of two equations, x = a(i) and b(j) and y = a(i) or b(j), using short-circuit evaluation to ensure that function b is only called when necessary. If the programming language does not support short-circuit evaluation, this is achieved using nested if statements. The code is written in Groovy, which supports short-circuiting for logical and (&&) and logical or (||) operations, but not for bitwise and (&) and bitwise or (|) operations.","id":4497}
    {"lang_cluster":"Groovy","source_code":"\n\nclass ABCSolver {\n    def blocks\n\n    ABCSolver(blocks = []) { this.blocks = blocks }\n\n    boolean canMakeWord(rawWord) {\n        if (rawWord == '' || rawWord == null) { return true; }\n        def word = rawWord.toUpperCase()\n        def blocksLeft = [] + blocks\n        word.every { letter -> blocksLeft.remove(blocksLeft.find { block -> block.contains(letter) }) }\n    }\n}\n\n\ndef a = new ABCSolver([\"BO\", \"XK\", \"DQ\", \"CP\", \"NA\", \"GT\", \"RE\", \"TG\", \"QD\", \"FS\",\n                      \"JW\", \"HU\", \"VI\", \"AN\", \"OB\", \"ER\", \"FS\", \"LY\", \"PC\", \"ZM\"])\n\n['', 'A', 'BARK', 'book', 'treat', 'COMMON', 'SQuAd', 'CONFUSE'].each {\n    println \"'${it}': ${a.canMakeWord(it)}\"\n}\n\n\n","human_summarization":"The code is a function that checks if a given word can be spelled using a predefined collection of blocks, each with two letters. The blocks can only be used once and the function is case-insensitive. The function is tested with seven different words and returns a boolean value indicating whether or not the word can be spelled with the available blocks.","id":4498}
    {"lang_cluster":"Groovy","source_code":"\nimport java.security.MessageDigest\n\nString.metaClass.md5Checksum = {\n    MessageDigest.getInstance('md5').digest(delegate.bytes).collect { String.format(\"%02x\", it) }.join('')\n}\n\n\nassert 'The quick brown fox jumps over the lazy dog'.md5Checksum() == '9e107d9d372bb6826bd81d3542a419d6'\n\n","human_summarization":"The code implements the MD5 algorithm to encode a string. It optionally validates the implementation using test values from IETF RFC (1321) for MD5. It also includes a warning about MD5's known weaknesses and suggests stronger alternatives for production-grade cryptography. If the solution is a library solution, it refers to MD5\/Implementation for a scratch implementation.","id":4499}
    {"lang_cluster":"Groovy","source_code":"\ns = new java.net.Socket(\"localhost\", 256)\ns << \"hello socket world\"\ns.close()\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":4500}
    {"lang_cluster":"Groovy","source_code":"\n\nimport javax.mail.*\nimport javax.mail.internet.*\n \npublic static void simpleMail(String from, String password, String to,\n    String subject, String body) throws Exception {\n \n    String host = \"smtp.gmail.com\";\n    Properties props = System.getProperties();\n    props.put(\"mail.smtp.starttls.enable\",true);\n    \/* mail.smtp.ssl.trust is needed in script to avoid error \"Could not convert socket to TLS\"  *\/\n    props.setProperty(\"mail.smtp.ssl.trust\", host);\n    props.put(\"mail.smtp.auth\", true);      \n    props.put(\"mail.smtp.host\", host);\n    props.put(\"mail.smtp.user\", from);\n    props.put(\"mail.smtp.password\", password);\n    props.put(\"mail.smtp.port\", \"587\");\n \n    Session session = Session.getDefaultInstance(props, null);\n    MimeMessage message = new MimeMessage(session);\n    message.setFrom(new InternetAddress(from));\n \n    InternetAddress toAddress = new InternetAddress(to);\n \n    message.addRecipient(Message.RecipientType.TO, toAddress);\n \n    message.setSubject(subject);\n    message.setText(body);\n \n    Transport transport = session.getTransport(\"smtp\");\n \n    transport.connect(host, from, password);\n \n    transport.sendMessage(message, message.getAllRecipients());\n    transport.close();\n}\n \n\/* Set email address sender *\/\nString s1 = \"example@gmail.com\";\n \n\/* Set password sender *\/\nString s2 = \"\";\n \n\/* Set email address sender *\/\nString s3 = \"example@gmail.com\"\n \n\/*Call function *\/\nsimpleMail(s1, s2 , s3, \"TITLE\", \"TEXT\");\n\n","human_summarization":"implement a function to send an email with parameters for setting From, To, Cc addresses, Subject, message text, and optional server name and login details. The function also provides notifications for problems\/success and uses libraries or functions from the language, with potential for use of external programs. The solution is portable across different operating systems.","id":4501}
    {"lang_cluster":"Groovy","source_code":"\n\nprintln 'decimal  octal'\nfor (def i = 0; i <= Integer.MAX_VALUE; i++) {\n    printf ('%7d \u00a0%#5o\\n', i, i)\n}\n\n\nprintln 'decimal  octal'\nfor (def i = 0g; true; i += 1g) {\n    printf ('%7d \u00a0%#5o\\n', i, i)\n}\n\n\ndecimal  octal\n      0     00\n      1     01\n      2     02\n      3     03\n      4     04\n      5     05\n      6     06\n      7     07\n      8    010\n      9    011\n     10    012\n     11    013\n     12    014\n     13    015\n     14    016\n     15    017\n     16    020\n     17    021\n...\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line, until the program is terminated or the maximum numeric value is reached.","id":4502}
    {"lang_cluster":"Groovy","source_code":"\n\n(a, b) = [b, a]\n\n\ndef swap(a, b) {\n    [b, a]\n}\n\n\ndef (x, y) = swap(1, 3)\nassert x == 3\nassert y == 1\n\n\ndef listSwap = { a, i, j ->\n    assert (0..<(a.size())).containsAll([i,j]);\n    a[[j,i]] = a[[i,j]]\n}\n\ndef list = [2,4,6,8]\nlistSwap(list, 1, 3)\nassert list == [2,8,6,4]\n\n","human_summarization":"implement a generic swap function or operator that can exchange the values of two variables or storage places, regardless of their types. The function also handles the constraints of statically typed languages and dynamically typed languages. It also includes an in-place swap of indexed elements in a list.","id":4503}
    {"lang_cluster":"Groovy","source_code":"\n\ndef isPalindrome = { String s ->\n    s == s?.reverse()\n}\n\n\nprintln isPalindrome(\"\")\nprintln isPalindrome(\"a\")\nprintln isPalindrome(\"abcdefgfedcba\")\nprintln isPalindrome(\"abcdeffedcba\")\nprintln isPalindrome(\"abcedfgfedcb\")\n\n\n","human_summarization":"The code checks if a given sequence of characters is a palindrome, supporting both standard and Unicode characters. It also includes a function to detect inexact palindromes by ignoring white-space, punctuation, and case differences. The code assumes nulls as palindromes but does not handle nulls in the recursive solution. It also includes a feature to reverse a string.","id":4504}
    {"lang_cluster":"Groovy","source_code":"\nSystem.getenv().each { property, value -> println \"$property = $value\"}\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":4505}
    {"lang_cluster":"Kotlin","source_code":"\n\n\/\/ version 1.1.2\n\nclass Stack<E> {\n    private val data = mutableListOf<E>()\n\n    val size get() = data.size\n\n    val empty get() = size == 0\n\n    fun push(element: E) = data.add(element)\n\n    fun pop(): E {\n        if (empty) throw RuntimeException(\"Can't pop elements from an empty stack\")\n        return data.removeAt(data.lastIndex)\n    }\n\n    val top: E\n        get() {\n            if (empty) throw RuntimeException(\"Empty stack can't have a top element\")\n            return data.last()\n        }\n\n    fun clear() = data.clear()\n\n    override fun toString() = data.toString()\n}\n\nfun main(args: Array<String>) {\n    val s = Stack<Int>()\n    (1..5).forEach { s.push(it) }\n    println(s)\n    println(\"Size of stack = ${s.size}\")\n    print(\"Popping: \")\n    (1..3).forEach { print(\"${s.pop()} \") }\n    println(\"\\nRemaining on stack: $s\")\n    println(\"Top element is now ${s.top}\")\n    s.clear()\n    println(\"After clearing, stack is ${if(s.empty) \"empty\" else \"not empty\"}\")\n    try {\n        s.pop()\n    }\n    catch (e: Exception) {\n        println(e.message)\n    }\n}\n\n\n","human_summarization":"implement a custom Stack class supporting basic operations such as push (adding an element to the top of the stack), pop (removing the topmost element from the stack and returning it), and empty (checking if the stack is empty). This Stack class follows the Last In, First Out (LIFO) principle.","id":4506}
    {"lang_cluster":"Kotlin","source_code":"\nenum class Fibonacci {\n    ITERATIVE {\n        override fun get(n: Int): Long = if (n < 2) {\n            n.toLong()\n        } else {\n            var n1 = 0L\n            var n2 = 1L\n            repeat(n) {\n                val sum = n1 + n2\n                n1 = n2\n                n2 = sum\n            }\n            n1\n        }\n    },\n    RECURSIVE {\n        override fun get(n: Int): Long = if (n < 2) n.toLong() else this[n - 1] + this[n - 2]\n    },\n    CACHING {\n        val cache: MutableMap<Int, Long> = mutableMapOf(0 to 0L, 1 to 1L)\n        override fun get(n: Int): Long = if (n < 2) n.toLong() else impl(n)\n        private fun impl(n: Int): Long = cache.computeIfAbsent(n) { impl(it-1) + impl(it-2) }\n    },\n   \u00a0;\n \n    abstract operator fun get(n: Int): Long\n}\n \nfun main() {\n    val r = 0..30\n    for (fib in Fibonacci.values()) {\n        print(\"${fib.name.padEnd(10)}:\")\n        for (i in r) { print(\" \" + fib[i]) }\n        println()\n    }\n}\n\n","human_summarization":"generate the nth Fibonacci number, using either an iterative or recursive approach. The function also has an optional feature to support negative Fibonacci sequences.","id":4507}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.5-2\n\nfun main(args: Array<String>) {\n    val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)\n    println(array.joinToString(\" \"))\n\n    val filteredArray = array.filter{ it % 2 == 0 }\n    println(filteredArray.joinToString(\" \"))\n\n    val mutableList = array.toMutableList()\n    mutableList.retainAll { it % 2 == 0 }\n    println(mutableList.joinToString(\" \"))\n}\n\n\n","human_summarization":"select certain elements from an array into a new array in a generic way. Specifically, it selects all even numbers from an array. Optionally, it can also filter destructively by modifying the original array instead of creating a new one.","id":4508}
    {"lang_cluster":"Kotlin","source_code":"\n\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n    val s = \"0123456789\"\n    val n = 3\n    val m = 4\n    val c = '5'\n    val z = \"12\"\n    var i: Int\n    println(s.substring(n, n + m))\n    println(s.substring(n))\n    println(s.dropLast(1))\n    i = s.indexOf(c)\n    println(s.substring(i, i + m))\n    i = s.indexOf(z)\n    println(s.substring(i, i + m))\n}\n\n\n","human_summarization":"The code performs the following tasks: \n1. Displays a substring starting from 'n' characters in and of 'm' length.\n2. Displays a substring starting from 'n' characters in, up to the end of the string.\n3. Displays the whole string minus the last character.\n4. Displays a substring starting from a known character within the string and of 'm' length.\n5. Displays a substring starting from a known substring within the string and of 'm' length.\nThe code is compatible with any valid Unicode code point in UTF-8 or UTF-16, and references logical characters, not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. It is not required to handle all Unicode characters for other encodings like 8-bit ASCII, or EUC-JP. The strings in the code are 0-indexed.","id":4509}
    {"lang_cluster":"Kotlin","source_code":"\nfun main(args: Array<String>) {\n    println(\"asdf\".reversed())\n}\n","human_summarization":"Reverses a given string while preserving Unicode combining characters. For instance, it transforms \"asdf\" to \"fdsa\" and \"as\u20dddf\u0305\" to \"f\u0305ds\u20dda\".","id":4510}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.0.5-2\n\nenum class PlayfairOption {\n    NO_Q, \n    I_EQUALS_J\n}\n\nclass Playfair(keyword: String, val pfo: PlayfairOption) {\n    private val table: Array<CharArray> = Array(5, { CharArray(5) })  \/\/ 5 x 5 char array\n\n    init {\n        \/\/ build table\n        val used = BooleanArray(26)  \/\/ all elements false  \n        if (pfo == PlayfairOption.NO_Q) \n            used[16] = true  \/\/ Q used\n        else\n            used[9]  = true  \/\/ J used\n        val alphabet = keyword.toUpperCase() + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n        var i = 0\n        var j = 0\n        var c: Char\n        var d: Int\n        for (k in 0 until alphabet.length) {\n            c = alphabet[k]\n            if (c !in 'A'..'Z') continue\n            d = c.toInt() - 65\n            if (!used[d]) {\n                table[i][j] = c\n                used[d] = true\n                if (++j == 5) { \n                    if (++i == 5) break \/\/ table has been filled \n                    j = 0\n                }\n            }          \n        }\n    }\n    \n    private fun getCleanText(plainText: String): String {\n        val plainText2 = plainText.toUpperCase()  \/\/ ensure everything is upper case\n        \/\/ get rid of any non-letters and insert X between duplicate letters\n        var cleanText = \"\"\n        var prevChar = '\\u0000'  \/\/ safe to assume null character won't be present in plainText\n        var nextChar: Char\n        for (i in 0 until plainText2.length) {\n            nextChar = plainText2[i]\n            \/\/ It appears that Q should be omitted altogether if NO_Q option is specified - we assume so anyway\n            if (nextChar !in 'A'..'Z' || (nextChar == 'Q' && pfo == PlayfairOption.NO_Q)) continue\n            \/\/ If I_EQUALS_J option specified, replace J with I\n            if (nextChar == 'J' && pfo == PlayfairOption.I_EQUALS_J) nextChar = 'I'\n            if (nextChar != prevChar)\n                cleanText += nextChar\n            else\n                cleanText += \"X\" + nextChar\n            prevChar = nextChar\n        }        \n        val len = cleanText.length\n        if (len % 2 == 1)  {  \/\/ dangling letter at end so add another letter to complete digram\n            if (cleanText[len - 1] != 'X')\n                cleanText += 'X'\n            else \n                cleanText += 'Z'\n        }\n        return cleanText    \n    }\n\n    private fun findChar(c: Char): Pair<Int, Int> {\n       for (i in 0..4)\n           for (j in 0..4)\n               if (table[i][j] == c) return Pair(i, j)\n       return Pair(-1, -1)\n    }\n\n    fun encode(plainText: String): String {\n        val cleanText = getCleanText(plainText)\n        var cipherText = \"\"\n        val length = cleanText.length\n        for (i in 0 until length step 2) {\n            val (row1, col1) = findChar(cleanText[i])\n            val (row2, col2) = findChar(cleanText[i + 1])  \n            cipherText += when {\n                row1 == row2 -> table[row1][(col1 + 1) % 5].toString() + table[row2][(col2 + 1) % 5]\n                col1 == col2 -> table[(row1 + 1) % 5][col1].toString() + table[(row2 + 1) % 5][col2]\n                else         -> table[row1][col2].toString() + table[row2][col1]\n            }\n            if (i < length - 1) cipherText += \" \"  \n        }\n        return cipherText\n    }\n\n    fun decode(cipherText: String): String {\n        var decodedText = \"\"\n        val length = cipherText.length\n        for (i in 0 until length step 3) {  \/\/ cipherText will include spaces so we need to skip them\n            val (row1, col1) = findChar(cipherText[i])\n            val (row2, col2) = findChar(cipherText[i + 1])  \n            decodedText += when {\n                row1 == row2 -> table[row1][if (col1 > 0) col1 - 1 else 4].toString() + table[row2][if (col2 > 0) col2 - 1 else 4]\n                col1 == col2 -> table[if (row1 > 0) row1- 1 else 4][col1].toString() + table[if (row2 > 0) row2 - 1 else 4][col2]\n                else         -> table[row1][col2].toString() + table[row2][col1]\n            }\n            if (i < length - 1) decodedText += \" \"\n        }\n        return decodedText\n    }   \n\n    fun printTable() {\n        println(\"The table to be used is\u00a0:\\n\")\n        for (i in 0..4) {\n            for (j in 0..4) print(table[i][j] + \" \")\n            println()\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    print(\"Enter Playfair keyword\u00a0: \")\n    val keyword: String = readLine()!!\n    var ignoreQ: String\n    do {\n         print(\"Ignore Q when buiding table  y\/n\u00a0: \")\n         ignoreQ = readLine()!!.toLowerCase() \n    }\n    while (ignoreQ != \"y\" && ignoreQ != \"n\")\n    val pfo = if (ignoreQ == \"y\") PlayfairOption.NO_Q else PlayfairOption.I_EQUALS_J\n    val playfair = Playfair(keyword, pfo)\n    playfair.printTable()\n    print(\"\\nEnter plain text\u00a0: \")\n    val plainText: String = readLine()!!\n    val encodedText = playfair.encode(plainText)\n    println(\"\\nEncoded text is\u00a0: $encodedText\") \n    val decodedText = playfair.decode(encodedText)\n    println(\"Decoded text is\u00a0: $decodedText\")\n}\n\n\n","human_summarization":"Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.","id":4511}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.51\n\nimport java.util.TreeSet\n\nclass Edge(val v1: String, val v2: String, val dist: Int)\n\n \/** One vertex of the graph, complete with mappings to neighbouring vertices *\/\nclass Vertex(val name: String) : Comparable<Vertex> {\n\n    var dist = Int.MAX_VALUE  \/\/ MAX_VALUE assumed to be infinity\n    var previous: Vertex? = null\n    val neighbours = HashMap<Vertex, Int>()\n\n    fun printPath() {\n        if (this == previous) {\n            print(name)\n        }\n        else if (previous == null) {\n            print(\"$name(unreached)\")\n        }\n        else {\n            previous!!.printPath()\n            print(\" -> $name($dist)\")\n        }\n    }\n\n    override fun compareTo(other: Vertex): Int {\n        if (dist == other.dist) return name.compareTo(other.name)\n        return dist.compareTo(other.dist)\n    }\n\n    override fun toString() = \"($name, $dist)\"\n}\n\nclass Graph(\n    val edges: List<Edge>, \n    val directed: Boolean,\n    val showAllPaths: Boolean = false\n) {\n    \/\/ mapping of vertex names to Vertex objects, built from a set of Edges\n    private val graph = HashMap<String, Vertex>(edges.size)\n\n    init {\n        \/\/ one pass to find all vertices\n        for (e in edges) {\n            if (!graph.containsKey(e.v1)) graph.put(e.v1, Vertex(e.v1))\n            if (!graph.containsKey(e.v2)) graph.put(e.v2, Vertex(e.v2))\n        }\n\n        \/\/ another pass to set neighbouring vertices\n        for (e in edges) {\n            graph[e.v1]!!.neighbours.put(graph[e.v2]!!, e.dist)\n            \/\/ also do this for an undirected graph if applicable\n            if (!directed) graph[e.v2]!!.neighbours.put(graph[e.v1]!!, e.dist)\n        }\n    }\n\n    \/** Runs dijkstra using a specified source vertex *\/\n    fun dijkstra(startName: String) {\n        if (!graph.containsKey(startName)) {\n            println(\"Graph doesn't contain start vertex '$startName'\")\n            return\n        }\n        val source = graph[startName]\n        val q = TreeSet<Vertex>()\n\n        \/\/ set-up vertices\n        for (v in graph.values) {\n            v.previous = if (v == source) source else null\n            v.dist = if (v == source)  0 else Int.MAX_VALUE\n            q.add(v)\n        }\n\n        dijkstra(q)\n    }\n\n    \/** Implementation of dijkstra's algorithm using a binary heap *\/\n    private fun dijkstra(q: TreeSet<Vertex>) {\n        while (!q.isEmpty()) {\n            \/\/ vertex with shortest distance (first iteration will return source)\n            val u = q.pollFirst()\n            \/\/ if distance is infinite we can ignore 'u' (and any other remaining vertices)\n            \/\/ since they are unreachable\n            if (u.dist == Int.MAX_VALUE) break\n\n            \/\/look at distances to each neighbour\n            for (a in u.neighbours) {\n                val v = a.key \/\/ the neighbour in this iteration\n\n                val alternateDist = u.dist + a.value\n                if (alternateDist < v.dist) { \/\/ shorter path to neighbour found\n                    q.remove(v)\n                    v.dist = alternateDist\n                    v.previous = u\n                    q.add(v)\n                }\n            }\n        }\n    }\n\n    \/** Prints a path from the source to the specified vertex *\/\n    fun printPath(endName: String) {\n        if (!graph.containsKey(endName)) {\n            println(\"Graph doesn't contain end vertex '$endName'\")\n            return\n        }\n        print(if (directed) \"Directed  \u00a0: \" else \"Undirected\u00a0: \")\n        graph[endName]!!.printPath()\n        println()\n        if (showAllPaths) printAllPaths() else println()\n    }\n\n    \/** Prints the path from the source to every vertex (output order is not guaranteed) *\/\n    private fun printAllPaths() {\n        for (v in graph.values) {\n            v.printPath()\n            println()\n        }\n        println()\n    }\n}\n\nval GRAPH = listOf(\n    Edge(\"a\", \"b\", 7),\n    Edge(\"a\", \"c\", 9),\n    Edge(\"a\", \"f\", 14),\n    Edge(\"b\", \"c\", 10),\n    Edge(\"b\", \"d\", 15),\n    Edge(\"c\", \"d\", 11),\n    Edge(\"c\", \"f\", 2),\n    Edge(\"d\", \"e\", 6),\n    Edge(\"e\", \"f\", 9)\n)\n\nconst val START = \"a\"\nconst val END = \"e\"\n\nfun main(args: Array<String>) {\n    with (Graph(GRAPH, true)) {   \/\/ directed\n        dijkstra(START)\n        printPath(END)\n    }\n    with (Graph(GRAPH, false)) {  \/\/ undirected\n        dijkstra(START)\n        printPath(END)\n    }\n}\n\n\n","human_summarization":"Implement Dijkstra's algorithm to find the shortest path from a source node to all other nodes in a graph. The graph is represented by an adjacency matrix or list, and a start node. The algorithm outputs a set of edges representing the shortest path to each reachable node. The program also interprets the output to display the shortest path from the source node to specific nodes.","id":4512}
    {"lang_cluster":"Kotlin","source_code":"class AvlTree {\n    private var root: Node? = null\n\n    private class Node(var key: Int, var parent: Node?) {\n        var balance: Int = 0\n        var left : Node? = null\n        var right: Node? = null\n    }\n\n    fun insert(key: Int): Boolean {\n        if (root == null)\n            root = Node(key, null)\n        else {\n            var n: Node? = root\n            var parent: Node\n            while (true) {\n                if (n!!.key == key) return false\n                parent = n\n                val goLeft = n.key > key\n                n = if (goLeft) n.left else n.right\n                if (n == null) {\n                    if (goLeft)\n                        parent.left  = Node(key, parent)\n                    else\n                        parent.right = Node(key, parent)\n                    rebalance(parent)\n                    break\n                }\n            }\n        }\n        return true\n    }\n\n    fun delete(delKey: Int) {\n        if (root == null) return\n        var n:       Node? = root\n        var parent:  Node? = root\n        var delNode: Node? = null\n        var child:   Node? = root\n        while (child != null) {\n            parent = n\n            n = child\n            child = if (delKey >= n.key) n.right else n.left\n            if (delKey == n.key) delNode = n\n        }\n        if (delNode != null) {\n            delNode.key = n!!.key\n            child = if (n.left != null) n.left else n.right\n            if (0 == root!!.key.compareTo(delKey)) {\n                root = child\n\n                if (null != root) {\n                    root!!.parent = null\n                }\n\n            } else {\n                if (parent!!.left == n)\n                    parent.left = child\n                else\n                    parent.right = child\n\n                if (null != child) {\n                    child.parent = parent\n                }\n\n                rebalance(parent)\n            }\n    }\n\n    private fun rebalance(n: Node) {\n        setBalance(n)\n        var nn = n\n        if (nn.balance == -2)\n            if (height(nn.left!!.left) >= height(nn.left!!.right))\n                nn = rotateRight(nn)\n            else\n                nn = rotateLeftThenRight(nn)\n        else if (nn.balance == 2)\n            if (height(nn.right!!.right) >= height(nn.right!!.left))\n                nn = rotateLeft(nn)\n            else\n                nn = rotateRightThenLeft(nn)\n        if (nn.parent != null) rebalance(nn.parent!!)\n        else root = nn\n    }\n\n    private fun rotateLeft(a: Node): Node {\n        val b: Node? = a.right\n        b!!.parent = a.parent\n        a.right = b.left\n        if (a.right != null) a.right!!.parent = a\n        b.left = a\n        a.parent = b\n        if (b.parent != null) {\n            if (b.parent!!.right == a)\n                b.parent!!.right = b\n            else\n                b.parent!!.left = b\n        }\n        setBalance(a, b)\n        return b\n    }\n\n    private fun rotateRight(a: Node): Node {\n        val b: Node? = a.left\n        b!!.parent = a.parent\n        a.left = b.right\n        if (a.left != null) a.left!!.parent = a\n        b.right = a\n        a.parent = b\n        if (b.parent != null) {\n            if (b.parent!!.right == a)\n                b.parent!!.right = b\n            else\n                b.parent!!.left = b\n        }\n        setBalance(a, b)\n        return b\n    }\n\n    private fun rotateLeftThenRight(n: Node): Node {\n        n.left = rotateLeft(n.left!!)\n        return rotateRight(n)\n    }\n\n    private fun rotateRightThenLeft(n: Node): Node {\n        n.right = rotateRight(n.right!!)\n        return rotateLeft(n)\n    }\n\n    private fun height(n: Node?): Int {\n        if (n == null) return -1\n        return 1 + Math.max(height(n.left), height(n.right))\n    }\n\n    private fun setBalance(vararg nodes: Node) {\n        for (n in nodes) n.balance = height(n.right) - height(n.left)\n    }\n\n    fun printKey() {\n        printKey(root)\n        println()\n    }\n\n    private fun printKey(n: Node?) {\n        if (n != null) {\n            printKey(n.left)\n            print(\"${n.key} \")\n            printKey(n.right)\n        }\n    }\n\n    fun printBalance() {\n        printBalance(root)\n        println()\n    }\n\n    private fun printBalance(n: Node?) {\n        if (n != null) {\n            printBalance(n.left)\n            print(\"${n.balance} \")\n            printBalance(n.right)\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    val tree = AvlTree()\n    println(\"Inserting values 1 to 10\")\n    for (i in 1..10) tree.insert(i)\n    print(\"Printing key    \u00a0: \")\n    tree.printKey()\n    print(\"Printing balance\u00a0: \")\n    tree.printBalance()\n}\n\n\n","human_summarization":"implement an AVL tree, a self-balancing binary search tree where the heights of the two child subtrees of any node differ by at most one. The code ensures this by rebalancing the tree after each insertion or deletion. The operations of lookup, insertion, and deletion all take O(log n) time. The code does not allow duplicate node keys. The AVL tree implemented can be compared with red-black trees for its efficiency in lookup-intensive applications.","id":4513}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.51\n\ntypealias IAE = IllegalArgumentException\n\nclass Point(val x: Double, val y: Double) {\n    fun distanceFrom(other: Point): Double {\n        val dx = x - other.x\n        val dy = y - other.y\n        return Math.sqrt(dx * dx + dy * dy )\n    }\n\n    override fun equals(other: Any?): Boolean {\n        if (other == null || other !is Point) return false\n        return (x == other.x && y == other.y)\n    }\n\n    override fun toString() = \"(%.4f,\u00a0%.4f)\".format(x, y)\n}\n\nfun findCircles(p1: Point, p2: Point, r: Double): Pair<Point, Point> {\n    if (r < 0.0) throw IAE(\"the radius can't be negative\")\n    if (r == 0.0 && p1 != p2) throw IAE(\"no circles can ever be drawn\")\n    if (r == 0.0) return p1 to p1\n    if (p1 == p2) throw IAE(\"an infinite number of circles can be drawn\")\n    val distance = p1.distanceFrom(p2)\n    val diameter = 2.0 * r\n    if (distance > diameter) throw IAE(\"the points are too far apart to draw a circle\")\n    val center = Point((p1.x + p2.x) \/ 2.0, (p1.y + p2.y) \/ 2.0)\n    if (distance == diameter) return center to center\n    val mirrorDistance = Math.sqrt(r * r - distance * distance \/ 4.0)\n    val dx =  (p2.x - p1.x) * mirrorDistance \/ distance\n    val dy =  (p2.y - p1.y) * mirrorDistance \/ distance\n    return Point(center.x - dy, center.y + dx) to\n           Point(center.x + dy, center.y - dx)\n}\n\nfun main(args: Array<String>) {\n    val p = arrayOf(\n        Point(0.1234, 0.9876),\n        Point(0.8765, 0.2345),\n        Point(0.0000, 2.0000),\n        Point(0.0000, 0.0000)\n    )\n    val points = arrayOf(\n        p[0] to p[1], p[2] to p[3], p[0] to p[0], p[0] to p[1], p[0] to p[0]\n    )\n    val radii = doubleArrayOf(2.0, 1.0, 2.0, 0.5, 0.0)\n    for (i in 0..4) {\n        try {\n            val (p1, p2) = points[i]            \n            val r  = radii[i]\n            println(\"For points $p1 and $p2 with radius $r\")\n            val (c1, c2) = findCircles(p1, p2, r)\n            if (c1 == c2)\n                println(\"there is just one circle with center at $c1\")\n            else\n                println(\"there are two circles with centers at $c1 and $c2\")\n        }\n        catch(ex: IllegalArgumentException) {\n            println(ex.message)\n        }\n        println()\n    }\n}\n\n\n","human_summarization":"\"Function to calculate two possible circles given two points and a radius in 2D space. The function handles special cases such as when radius is zero, points are coincident, points form a diameter, or points are too distant. The function returns the circles or a special indication when two equal or distinct circles cannot be returned.\"","id":4514}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.4-3\n\nfun Byte.toUInt()  = java.lang.Byte.toUnsignedInt(this)\n\nfun Byte.toULong() = java.lang.Byte.toUnsignedLong(this)\n\nfun Int.toULong()  = java.lang.Integer.toUnsignedLong(this)\n\nval s = arrayOf(\n    byteArrayOf( 4, 10,  9,  2, 13,  8,  0, 14,  6, 11,  1, 12,  7, 15,  5,  3),\n    byteArrayOf(14, 11,  4, 12,  6, 13, 15, 10,  2,  3,  8,  1,  0,  7,  5,  9),\n    byteArrayOf( 5,  8,  1, 13, 10,  3,  4,  2, 14, 15, 12,  7,  6,  0,  9, 11),\n    byteArrayOf( 7, 13, 10,  1,  0,  8,  9, 15, 14,  4,  6, 12, 11,  2,  5,  3),\n    byteArrayOf( 6, 12,  7,  1,  5, 15, 13,  8,  4, 10,  9, 14,  0,  3, 11,  2),\n    byteArrayOf( 4, 11, 10,  0,  7,  2,  1, 13,  3,  6,  8,  5,  9, 12, 15, 14),\n    byteArrayOf(13, 11,  4,  1,  3, 15,  5,  9,  0, 10, 14,  7,  6,  8,  2, 12),\n    byteArrayOf( 1, 15, 13,  0,  5,  7, 10,  4,  9,  2,  3, 14,  6, 11,  8, 12)\n)\n\nclass Gost(val sBox: Array<ByteArray>) {\n\n    val k87 = ByteArray(256)\n    val k65 = ByteArray(256)\n    val k43 = ByteArray(256)\n    val k21 = ByteArray(256)\n    val enc = ByteArray(8)\n\n    init {\n        for (i in 0 until 256) {\n            val j = i ushr 4\n            val k = i and 15 \n            k87[i] = ((sBox[7][j].toUInt() shl 4) or sBox[6][k].toUInt()).toByte()\n            k65[i] = ((sBox[5][j].toUInt() shl 4) or sBox[4][k].toUInt()).toByte()\n            k43[i] = ((sBox[3][j].toUInt() shl 4) or sBox[2][k].toUInt()).toByte()\n            k21[i] = ((sBox[1][j].toUInt() shl 4) or sBox[0][k].toUInt()).toByte()\n        }\n    }\n\n    fun f(x: Int): Int {\n        val y = (k87[(x ushr 24) and 255].toULong() shl 24) or\n                (k65[(x ushr 16) and 255].toULong() shl 16) or\n                (k43[(x ushr  8) and 255].toULong() shl  8) or\n                (k21[ x and 255].toULong())   \n        return ((y shl 11) or (y ushr 21)).toInt()\n    }\n\n    fun u32(ba: ByteArray): Int =\n        (ba[0].toULong() or \n        (ba[1].toULong() shl 8) or \n        (ba[2].toULong() shl 16) or \n        (ba[3].toULong() shl 24)).toInt()\n\n    fun b4(u: Int) {\n        enc[0] = u.toByte()\n        enc[1] = (u ushr  8).toByte()\n        enc[2] = (u ushr 16).toByte()\n        enc[3] = (u ushr 24).toByte()\n    }\n\n    fun mainStep(input: ByteArray, key: ByteArray) {\n        val key32  = u32(key)\n        val input1 = u32(input.sliceArray(0..3))\n        val input2 = u32(input.sliceArray(4..7))\n        val temp   = (key32.toULong() + input1.toULong()).toInt()\n        b4(f(temp) xor input2)\n        for (i in 0..3) enc[4 + i] = input[i]\n    }\n}\n\nfun main(args: Array<String>) {\n    val input = byteArrayOf(0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04)\n    val key = byteArrayOf(0xF9.toByte(), 0x04, 0xC1.toByte(), 0xE2.toByte())   \n    val g = Gost(s)\n    g.mainStep(input, key)\n    for (b in g.enc) print(\"[%02X]\".format(b))\n    println()\n}\n\n\n","human_summarization":"Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.","id":4515}
    {"lang_cluster":"Kotlin","source_code":"\nimport kotlin.random.Random\n\nfun main() {\n    while (true) {\n        val a = Random.nextInt(20)\n        println(a)\n        if (a == 10) break\n        println(Random.nextInt(20))\n    }\n}\n\n\nimport kotlin.random.Random\n\nfun main() {\n    while (Random.nextInt(20).also { println(it) } != 10)\n        println(Random.nextInt(20))\n}\n\n","human_summarization":"generates and prints random numbers from 0 to 19. If the number is 10, the loop stops. If not, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":4516}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.0.6\n\nfun isPrime(n: Int): Boolean {\n    if (n < 2) return false\n    if (n % 2 == 0) return n == 2\n    if (n % 3 == 0) return n == 3\n    var d = 5\n    while (d * d <= n) {\n        if (n % d == 0) return false\n        d += 2\n        if (n % d == 0) return false\n        d += 4\n    }\n    return true\n}\n\nfun main(args: Array<String>) {\n    \/\/ test 929 plus all prime numbers below 100 which are known not to be Mersenne primes\n    val q = intArrayOf(11, 23, 29, 37, 41, 43, 47, 53, 59, 67, 71, 73, 79, 83, 97, 929)\n    for (k in 0 until q.size) {\n        if (isPrime(q[k])) {\n            var i: Long\n            var d: Int\n            var p: Int\n            var r: Int = q[k]\n            while (r > 0) r = r shl 1\n            d = 2 * q[k] + 1\n            while (true) {\n                i = 1L\n                p = r\n                while (p != 0) {\n                    i = (i * i) % d\n                    if (p < 0) i *= 2\n                    if (i > d) i -= d\n                    p = p shl 1\n                }\n                if (i != 1L)\n                    d += 2 * q[k]\n                else\n                    break\n            }\n            println(\"2^${\"%3d\".format(q[k])} - 1 = 0 (mod $d)\")\n        } else {\n            println(\"${q[k]} is not prime\")\n        }\n    }\n}\n\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":4517}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.3\n\nimport javax.xml.parsers.DocumentBuilderFactory\nimport org.xml.sax.InputSource\nimport java.io.StringReader\nimport javax.xml.xpath.XPathFactory\nimport javax.xml.xpath.XPathConstants\nimport org.w3c.dom.Node\nimport org.w3c.dom.NodeList\n\nval xml = \n\"\"\"\n<inventory title=\"OmniCorp Store #45x10^3\">\n  <section name=\"health\">\n    <item upc=\"123456789\" stock=\"12\">\n      <name>Invisibility Cream<\/name>\n      <price>14.50<\/price>\n      <description>Makes you invisible<\/description>\n    <\/item>\n    <item upc=\"445322344\" stock=\"18\">\n      <name>Levitation Salve<\/name>\n      <price>23.99<\/price>\n      <description>Levitate yourself for up to 3 hours per application<\/description>\n    <\/item>\n  <\/section>\n  <section name=\"food\">\n    <item upc=\"485672034\" stock=\"653\">\n      <name>Blork and Freen Instameal<\/name>\n      <price>4.95<\/price>\n      <description>A tasty meal in a tablet; just add water<\/description>\n    <\/item>\n    <item upc=\"132957764\" stock=\"44\">\n      <name>Grob winglets<\/name>\n      <price>3.56<\/price>\n      <description>Tender winglets of Grob. Just add water<\/description>\n    <\/item>\n  <\/section>\n<\/inventory>\n\"\"\"\n\nfun main(args: Array<String>) {\n    val dbFactory = DocumentBuilderFactory.newInstance()\n    val dBuilder  = dbFactory.newDocumentBuilder()\n    val xmlInput = InputSource(StringReader(xml))\n    val doc = dBuilder.parse(xmlInput)\n    val xpFactory = XPathFactory.newInstance()\n    val xPath = xpFactory.newXPath()\n\n    val qNode = xPath.evaluate(\"\/inventory\/section\/item[1]\", doc, XPathConstants.NODE) as Node\n    val upc = qNode.attributes.getNamedItem(\"upc\")\n    val stock = qNode.attributes.getNamedItem(\"stock\")\n    println(\"For the first item\u00a0:  upc = ${upc.textContent} and stock = ${stock.textContent}\")\n\n    val qNodes = xPath.evaluate(\"\/inventory\/section\/item\/price\", doc, XPathConstants.NODESET) as NodeList\n    print(\"\\nThe prices of each item are\u00a0: \")\n    for (i in 0 until qNodes.length) print(\"${qNodes.item(i).textContent}  \")\n    println()\n\n    val qNodes2 = xPath.evaluate(\"\/inventory\/section\/item\/name\", doc, XPathConstants.NODESET) as NodeList\n    val names = Array<String>(qNodes2.length) { qNodes2.item(it).textContent }\n    println(\"\\nThe names of each item are as follows\u00a0:\")\n    println(\"  ${names.joinToString(\"\\n  \")}\")\n}\n\n\n","human_summarization":"1. Retrieves the first \"item\" element from the XML document.\n2. Prints out each \"price\" element from the XML document.\n3. Gets an array of all the \"name\" elements from the XML document.","id":4518}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n   val fruits  = setOf(\"apple\", \"pear\", \"orange\", \"banana\")\n   println(\"fruits \u00a0: $fruits\")\n   val fruits2 = setOf(\"melon\", \"orange\", \"lemon\", \"gooseberry\")\n   println(\"fruits2\u00a0: $fruits2\\n\")\n\n   println(\"fruits  contains 'banana'    \u00a0: ${\"banana\" in fruits}\")\n   println(\"fruits2 contains 'elderberry'\u00a0: ${\"elderbury\" in fruits2}\\n\")\n\n   println(\"Union       \u00a0: ${fruits.union(fruits2)}\")\n   println(\"Intersection\u00a0: ${fruits.intersect(fruits2)}\")\n   println(\"Difference  \u00a0: ${fruits.minus(fruits2)}\\n\")\n\n   println(\"fruits2 is a subset of fruits\u00a0: ${fruits.containsAll(fruits2)}\\n\")\n   val fruits3 = fruits\n   println(\"fruits3\u00a0: $fruits3\\n\")\n   var areEqual = fruits.containsAll(fruits2) && fruits3.containsAll(fruits)\n   println(\"fruits2 and fruits are equal \u00a0: $areEqual\")\n   areEqual = fruits.containsAll(fruits3) && fruits3.containsAll(fruits)\n   println(\"fruits3 and fruits are equal \u00a0: $areEqual\\n\")\n\n   val fruits4 = setOf(\"apple\", \"orange\")\n   println(\"fruits4\u00a0: $fruits4\\n\")\n   var isProperSubset = fruits.containsAll(fruits3) && !fruits3.containsAll(fruits)\n   println(\"fruits3 is a proper subset of fruits\u00a0: $isProperSubset\")\n   isProperSubset = fruits.containsAll(fruits4) && !fruits4.containsAll(fruits)\n   println(\"fruits4 is a proper subset of fruits\u00a0: $isProperSubset\\n\")\n\n   val fruits5 = mutableSetOf(\"cherry\", \"blueberry\", \"raspberry\")\n   println(\"fruits5\u00a0: $fruits5\\n\")\n   fruits5 += \"guava\"\n   println(\"fruits5 + 'guava' \u00a0: $fruits5\")\n   println(\"fruits5 - 'cherry'\u00a0: ${fruits5 - \"cherry\"}\")\n}\n\n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is present in a set, union, intersection, difference, subset and equality of sets. The code also optionally shows other set operations and methods to modify a mutable set. It may implement a set using an associative array, binary search tree, hash table, or an ordered array of binary bits. The code also discusses the time complexity of the basic test operation in different scenarios.","id":4519}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nimport java.util.*\n\nfun main(args: Array<String>) {\n    println(\"Christmas day in the following years falls on a Sunday:\\n\")\n    val calendar = GregorianCalendar(2008, Calendar.DECEMBER, 25)\n    for (year in 2008..2121) {\n        if (Calendar.SUNDAY == calendar[Calendar.DAY_OF_WEEK]) println(year)\n        calendar.add(Calendar.YEAR, 1)\n    }\n}\n\n\n","human_summarization":"The code determines the years between 2008 and 2121 where Christmas (25th December) falls on a Sunday, using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date\/time representation, such as overflow issues similar to y2k problems.","id":4520}
    {"lang_cluster":"Kotlin","source_code":"fun main(args: Array<String>) {\n    val data = listOf(1, 2, 3, \"a\", \"b\", \"c\", 2, 3, 4, \"b\", \"c\", \"d\")\n    val set = data.distinct()\n\n    println(data)\n    println(set)\n}\n\n\n","human_summarization":"implement three methods to remove duplicate elements from an array: 1) Using a hash table, 2) Sorting the array and removing consecutive duplicates, and 3) Iterating through the list and discarding any repeated elements.","id":4521}
    {"lang_cluster":"Kotlin","source_code":"\n\nfun <E : Comparable<E>> List<E>.qsort(): List<E> =\n        if (size < 2) this\n        else filter { it < first() }.qsort() +\n                filter { it == first() } +\n                filter { it > first() }.qsort()\n\n\nfun <E : Comparable<E>> List<E>.qsort(): List<E> =\n        if (size < 2) this\n        else {\n            val (less, high) = subList(1, size).partition { it < first() }\n            less.qsort() + first() + high.qsort()\n        }\n\n","human_summarization":"implement the quicksort algorithm to sort an array or list. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions, one with elements less than the pivot and the other with elements greater than the pivot. It then recursively sorts these partitions and combines them with the pivot to get the sorted array. The codes also include two versions of the quicksort algorithm, one that creates new arrays for the partitions and another that sorts the array in place to save memory. The pivot selection method is not specified.","id":4522}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nimport java.util.GregorianCalendar\n\nfun main(args: Array<String>) {\n    val now = GregorianCalendar()\n    println(\"%tF\".format(now))\n    println(\"%tA, %1\\$tB %1\\$te, %1\\$tY\".format(now))\n}\n\n\n","human_summarization":"display the current date in two formats: \"2007-11-23\" and \"Friday, November 23, 2007\".","id":4523}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ purely functional & lazy version, leveraging recursion and Sequences (a.k.a. streams)\nfun <T> Set<T>.subsets(): Sequence<Set<T>> =\n    when (size) {\n        0 -> sequenceOf(emptySet())\n        else -> {\n            val head = first()\n            val tail = this - head\n            tail.subsets() + tail.subsets().map { setOf(head) + it }\n        }\n    }\n\n\/\/ if recursion is an issue, you may change it this way:\n\nfun <T> Set<T>.subsets(): Sequence<Set<T>> = sequence {\n    when (size) {\n        0 -> yield(emptySet<T>())\n        else -> {\n            val head = first()\n            val tail = this@subsets - head\n            yieldAll(tail.subsets())\n            for (subset in tail.subsets()) {\n                yield(setOf(head) + subset)\n            }\n        }\n    }\n}\n\n\n","human_summarization":"implement a function that takes a set as input and returns its power set. The power set includes all subsets of the input set, including the empty set and the set itself. The function also demonstrates the handling of edge cases where the input set is empty or contains only the empty set.","id":4524}
    {"lang_cluster":"Kotlin","source_code":"\nval romanNumerals = mapOf(\n    1000 to \"M\",\n    900 to \"CM\",\n    500 to \"D\",\n    400 to \"CD\",\n    100 to \"C\",\n    90 to \"XC\",\n    50 to \"L\",\n    40 to \"XL\",\n    10 to \"X\",\n    9 to \"IX\",\n    5 to \"V\",\n    4 to \"IV\",\n    1 to \"I\"\n)\n\nfun encode(number: Int): String? {\n    if (number > 5000 || number < 1) {\n        return null\n    }\n    var num = number\n    var result = \"\"\n    for ((multiple, numeral) in romanNumerals.entries) {\n        while (num >= multiple) {\n            num -= multiple\n            result += numeral\n        }\n    }\n    return result\n}\n\nfun main(args: Array<String>) {\n    println(encode(1990))\n    println(encode(1666))\n    println(encode(2008))\n}\n\n\n","human_summarization":"implement a function that converts a positive integer into its equivalent Roman numeral representation. The function works by expressing each digit separately, starting from the leftmost digit and ignoring any digit with a value of zero.","id":4525}
    {"lang_cluster":"Kotlin","source_code":"\nfun main(x: Array<String>) {\n    var a = arrayOf(1, 2, 3, 4)\n    println(a.asList())\n    a += 5\n    println(a.asList())\n    println(a.reversedArray().asList())\n}\n\n","human_summarization":"demonstrate the basic syntax of arrays in the specific programming language, including creating an array, assigning a value to it, and retrieving an element. It also showcases the use of both fixed-length and dynamic arrays, and includes the functionality of pushing a value into the array.","id":4526}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nimport java.io.File\n\nfun main(args: Array<String>) {\n    val text = File(\"input.txt\").readText()\n    File(\"output.txt\").writeText(text)\n}\n\n","human_summarization":"demonstrate reading the contents of \"input.txt\" file into a variable and then writing this variable's contents into a new file called \"output.txt\".","id":4527}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n    val s = \"alphaBETA\"\n    println(s.toUpperCase())\n    println(s.toLowerCase()) \n    println(s.capitalize())\n    println(s.decapitalize())    \n}\n\n\n","human_summarization":"demonstrate the conversion of the string \"alphaBETA\" to upper-case and lower-case using the default string literal or ASCII encoding. The code also showcases additional case conversion functions such as swapping case or capitalizing the first letter if available in the language's library. Note that in some languages, the toLower and toUpper functions may not be reversible.","id":4528}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\ntypealias Point = Pair<Double, Double>\n\nfun distance(p1: Point, p2: Point) = Math.hypot(p1.first- p2.first, p1.second - p2.second)\n\nfun bruteForceClosestPair(p: List<Point>): Pair<Double, Pair<Point, Point>> {\n    val n = p.size\n    if (n < 2) throw IllegalArgumentException(\"Must be at least two points\")\n    var minPoints = p[0] to p[1]\n    var minDistance = distance(p[0], p[1])\n    for (i in 0 until n - 1)\n        for (j in i + 1 until n) {\n            val dist = distance(p[i], p[j])\n            if (dist < minDistance) {\n                minDistance = dist\n                minPoints = p[i] to p[j]\n            }\n        }\n    return minDistance to Pair(minPoints.first, minPoints.second)\n}\n\nfun optimizedClosestPair(xP: List<Point>, yP: List<Point>): Pair<Double, Pair<Point, Point>> {\n    val n = xP.size\n    if (n <= 3) return bruteForceClosestPair(xP)\n    val xL = xP.take(n \/ 2)\n    val xR = xP.drop(n \/ 2)\n    val xm = xP[n \/ 2 - 1].first\n    val yL = yP.filter { it.first <= xm }\n    val yR = yP.filter { it.first >  xm }\n    val (dL, pairL) = optimizedClosestPair(xL, yL)\n    val (dR, pairR) = optimizedClosestPair(xR, yR)\n    var dmin = dR\n    var pairMin = pairR\n    if (dL < dR) {\n        dmin = dL\n        pairMin = pairL\n    }\n    val yS = yP.filter { Math.abs(xm - it.first) < dmin }\n    val nS = yS.size\n    var closest = dmin\n    var closestPair = pairMin\n    for (i in 0 until nS - 1) {\n        var k = i + 1\n        while (k < nS && (yS[k].second - yS[i].second < dmin)) {\n            val dist = distance(yS[k], yS[i])\n            if (dist < closest) {\n                closest = dist\n                closestPair = Pair(yS[k], yS[i])\n            }\n            k++\n        }\n    }\n    return closest to closestPair\n}\n\n\nfun main(args: Array<String>) {\n    val points = listOf(\n        listOf(\n            5.0 to  9.0, 9.0 to 3.0,  2.0 to 0.0, 8.0 to  4.0, 7.0 to 4.0,\n            9.0 to 10.0, 1.0 to 9.0,  8.0 to 2.0, 0.0 to 10.0, 9.0 to 6.0\n        ),\n        listOf(\n            0.654682 to 0.925557, 0.409382 to 0.619391, 0.891663 to 0.888594,\n            0.716629 to 0.996200, 0.477721 to 0.946355, 0.925092 to 0.818220,\n            0.624291 to 0.142924, 0.211332 to 0.221507, 0.293786 to 0.691701,\n            0.839186 to 0.728260\n        )\n    )\n    for (p in points) {\n        val (dist, pair) = bruteForceClosestPair(p)\n        println(\"Closest pair (brute force) is ${pair.first} and ${pair.second}, distance $dist\")\n        val xP = p.sortedBy { it.first }\n        val yP = p.sortedBy { it.second }\n        val (dist2, pair2) = optimizedClosestPair(xP, yP)\n        println(\"Closest pair (optimized)   is ${pair2.first} and ${pair2.second}, distance $dist2\\n\")\n    }\n}\n\n\n","human_summarization":"provide two functions to solve the Closest Pair of Points problem in a 2D plane. The first function uses a brute force algorithm with a complexity of O(n^2) to find the two closest points. The second function uses a recursive divide and conquer approach with a complexity of O(n log n) to find the two closest points. Both functions return the minimum distance and the pair of points.","id":4529}
    {"lang_cluster":"Kotlin","source_code":"\n\nimport java.util.PriorityQueue\n\nfun main(args: Array<String>) {\n    \/\/ generic array\n    val ga = arrayOf(1, 2, 3)\n    println(ga.joinToString(prefix = \"[\", postfix = \"]\"))\n\n    \/\/ specialized array (one for each primitive type)\n    val da = doubleArrayOf(4.0, 5.0, 6.0)\n    println(da.joinToString(prefix = \"[\", postfix = \"]\"))\n\n    \/\/ immutable list\n    val li = listOf<Byte>(7, 8, 9)\n    println(li)\n\n    \/\/ mutable list\n    val ml = mutableListOf<Short>()\n    ml.add(10); ml.add(11); ml.add(12)\n    println(ml)\n\n    \/\/ immutable map\n    val hm = mapOf('a' to 97, 'b' to 98, 'c' to 99)\n    println(hm)\n\n    \/\/ mutable map\n    val mm = mutableMapOf<Char, Int>()\n    mm.put('d', 100); mm.put('e', 101); mm.put('f', 102)\n    println(mm)\n\n    \/\/ immutable set (duplicates not allowed)\n    val se = setOf(1, 2, 3)\n    println(se)\n\n    \/\/ mutable set (duplicates not allowed)\n    val ms = mutableSetOf<Long>()\n    ms.add(4L); ms.add(5L); ms.add(6L)\n    println(ms)\n\n    \/\/ priority queue (imported from Java)\n    val pq = PriorityQueue<String>()\n    pq.add(\"First\"); pq.add(\"Second\"); pq.add(\"Third\")\n    println(pq)\n}\n\n\n","human_summarization":"demonstrate the creation of a collection in a statically-typed language, with the addition of a few values. The code also highlights the distinction between mutable and immutable collection types in Kotlin, including arrays. It also showcases how Kotlin can access other Java collection types such as LinkedList, Queue, Deque, and Stack.","id":4530}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\ndata class Item(val name: String, val value: Double, val weight: Double, val volume: Double)\n\nval items = listOf(\n    Item(\"panacea\", 3000.0, 0.3, 0.025),\n    Item(\"ichor\", 1800.0, 0.2, 0.015),\n    Item(\"gold\", 2500.0, 2.0, 0.002)\n)\n\nval n = items.size\nval count = IntArray(n)\nval best  = IntArray(n)\nvar bestValue = 0.0\n\nconst val MAX_WEIGHT = 25.0\nconst val MAX_VOLUME = 0.25\n\nfun knapsack(i: Int, value: Double, weight: Double, volume: Double) {\n    if (i == n) {\n        if (value > bestValue) {\n            bestValue = value\n            for (j in 0 until n) best[j] = count[j]\n        }\n        return\n    }\n    val m1 = Math.floor(weight \/ items[i].weight).toInt()\n    val m2 = Math.floor(volume \/ items[i].volume).toInt()\n    val m  = minOf(m1, m2)\n    count[i] = m\n    while (count[i] >= 0) {\n        knapsack(\n            i + 1,\n            value  + count[i] * items[i].value,\n            weight - count[i] * items[i].weight,\n            volume - count[i] * items[i].volume\n        )\n        count[i]--\n    }\n}\n\nfun main(args: Array<String>) {\n    knapsack(0, 0.0, MAX_WEIGHT, MAX_VOLUME)\n    println(\"Item Chosen  Number Value  Weight  Volume\")\n    println(\"-----------  ------ -----  ------  ------\")\n    var itemCount = 0\n    var sumNumber = 0\n    var sumWeight = 0.0\n    var sumVolume = 0.0\n    for (i in 0 until n) {\n        if (best[i] == 0) continue\n        itemCount++\n        val name   = items[i].name\n        val number = best[i]\n        val value  = items[i].value  * number\n        val weight = items[i].weight * number\n        val volume = items[i].volume * number\n        sumNumber += number\n        sumWeight += weight\n        sumVolume += volume\n        print(\"${name.padEnd(11)}   ${\"%2d\".format(number)}    ${\"%5.0f\".format(value)}   ${\"%4.1f\".format(weight)}\")\n        println(\"    ${\"%4.2f\".format(volume)}\")\n    }\n    println(\"-----------  ------ -----  ------  ------\")\n    print(\"${itemCount} items       ${\"%2d\".format(sumNumber)}    ${\"%5.0f\".format(bestValue)}   ${\"%4.1f\".format(sumWeight)}\")\n    println(\"    ${\"%4.2f\".format(sumVolume)}\")\n}\n\n\n","human_summarization":"\"Output: The code implements a solution to the unbounded Knapsack problem. It calculates the maximum value a traveler can carry from Shangri La, given a weight limit of 25 and volume limit of 0.25. The code considers the weight, volume, and value of each item (panacea, ichor, gold) and returns the optimal quantity of each item to maximize the total value. It uses a recursive brute force approach and only needs to provide one of the four possible solutions.\"","id":4531}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n    for (i in 1 .. 10) {\n        print(i)\n        if (i < 10) print(\", \")\n    }\n}\n\n\n","human_summarization":"The code writes a comma-separated list from 1 to 10, using separate output statements for the number and the comma within a loop. The loop executes a partial body in its last iteration.","id":4532}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.51\n\nval s = \"std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, \" +\n        \"dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys\"\n\nval deps = mutableListOf(\n     2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1,\n     3 to 1, 3 to 10, 3 to 11,\n     4 to 1, 4 to 10,\n     5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11,\n     6 to 1, 6 to 3, 6 to 10, 6 to 11,\n     7 to 1, 7 to 10,\n     8 to 1, 8 to 10,\n     9 to 1, 9 to 10,\n     10 to 1,\n     11 to 1,\n     12 to 0, 12 to 1,\n     13 to 1\n)\n\nclass Graph(s: String, edges: List<Pair<Int,Int>>) {\n\n    val vertices = s.split(\", \")\n    val numVertices = vertices.size\n    val adjacency = List(numVertices) { BooleanArray(numVertices) }\n\n    init {\n        for (edge in edges) adjacency[edge.first][edge.second] = true\n    }\n\n    fun hasDependency(r: Int, todo: List<Int>): Boolean {\n        return todo.any { adjacency[r][it] }\n    }\n\n    fun topoSort(): List<String>? {\n        val result = mutableListOf<String>()\n        val todo = MutableList<Int>(numVertices) { it }\n        try {\n            outer@ while(!todo.isEmpty()) {\n                for ((i, r) in todo.withIndex()) {\n                    if (!hasDependency(r, todo)) {\n                        todo.removeAt(i)\n                        result.add(vertices[r])\n                        continue@outer\n                     }\n                }\n                throw Exception(\"Graph has cycles\")\n            }\n        }\n        catch (e: Exception) {\n            println(e)\n            return null\n        }\n        return result\n    }\n}\n\nfun main(args: Array<String>) {\n    val g = Graph(s, deps)\n    println(\"Topologically sorted order:\")\n    println(g.topoSort())\n    println()\n    \/\/ now insert 3 to 6 at index 10 of deps\n    deps.add(10, 3 to 6)\n    val g2 = Graph(s, deps)\n    println(\"Following the addition of dw04 to the dependencies of dw01:\")\n    println(g2.topoSort())\n}\n\n\n","human_summarization":"The code implements a function that performs a topological sort on VHDL libraries based on their dependencies. It ensures that no library is compiled before the ones it depends on. The function also handles cases of self-dependencies and flags un-orderable dependencies. It uses either Kahn's 1962 topological sort or depth-first search algorithm for sorting.","id":4533}
    {"lang_cluster":"Kotlin","source_code":"\nfun main() {\n    val s1 = \"abracadabra\"\n    val s2 = \"abra\"    \n    println(\"$s1 begins with $s2: ${s1.startsWith(s2)}\")\n    println(\"$s1 ends with $s2: ${s1.endsWith(s2)}\")\n    val b = s2 in s1\n    if (b) {\n        print(\"$s1 contains $s2 at these indices: \")\n        \/\/ can use indexOf to get first index or lastIndexOf to get last index\n        \/\/ to get ALL indices, use a for loop or Regex\n        println(\n            s2.toRegex(RegexOption.LITERAL).findAll(s1).joinToString { it.range.start.toString() }\n        )\n    }\n    else println(\"$s1 does not contain $2.\")\n}\n\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":4534}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.2\n\nclass FourSquares(\n    private val lo: Int,\n    private val hi: Int,\n    private val unique: Boolean,\n    private val show: Boolean\n) {\n    private var a = 0\n    private var b = 0\n    private var c = 0\n    private var d = 0\n    private var e = 0\n    private var f = 0\n    private var g = 0\n    private var s = 0\n\n    init {\n        println()\n        if (show) {\n            println(\"a b c d e f g\")\n            println(\"-------------\")\n        }\n        acd()\n        println(\"\\n$s ${if (unique) \"unique\" else \"non-unique\"} solutions in $lo to $hi\")\n    }\n\n    private fun acd() {\n        c = lo\n        while (c <= hi) {\n            d = lo\n            while (d <= hi) {\n                if (!unique || c != d) {\n                    a = c + d\n                    if ((a in lo..hi) && (!unique || (c != 0 && d!= 0))) ge()\n                }\n                d++\n            }\n            c++\n        }\n    }\n\n    private fun bf() {\n        f = lo\n        while (f <= hi) {\n            if (!unique || (f != a && f != c && f != d && f != e && f!= g)) {\n                b = e + f - c\n                if ((b in lo..hi) && (!unique || (b != a && b != c && b != d && b != e && b != f && b!= g))) {\n                    s++\n                    if (show) println(\"$a $b $c $d $e $f $g\")\n                }\n            }\n            f++\n        }\n    }\n\n    private fun ge() {\n        e = lo\n        while (e <= hi) {\n            if (!unique || (e != a && e != c && e != d)) {\n                g = d + e\n                if ((g in lo..hi) && (!unique || (g != a && g != c && g != d && g != e))) bf()\n            }\n            e++\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    FourSquares(1, 7, true, true)\n    FourSquares(3, 9, true, true)\n    FourSquares(0, 9, false, false)\n}\n\n\n","human_summarization":"The code finds all possible solutions for a 4-squares puzzle where each square sums up to the same total. It operates under two conditions: each letter representing a unique value between 1-7 and 3-9, and each letter representing a non-unique value between 0-9. The code also counts the number of non-unique solutions.","id":4535}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1\n\nimport java.awt.*\nimport java.time.LocalTime\nimport javax.swing.*\n\nclass Clock : JPanel() {\n    private val degrees06: Float = (Math.PI \/ 30.0).toFloat()\n    private val degrees30: Float = degrees06 * 5.0f\n    private val degrees90: Float =  degrees30 * 3.0f\n    private val size = 590\n    private val spacing = 40\n    private val diameter = size - 2 * spacing\n    private val cx = diameter \/ 2 + spacing\n    private val cy = cx\n\n    init {\n        preferredSize = Dimension(size, size)\n        background =  Color.white\n        Timer(1000) {\n            repaint()\n        }.start()\n    }\n\n    override public fun paintComponent(gg: Graphics) {\n        super.paintComponent(gg)\n        val g = gg as Graphics2D\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n        drawFace(g)\n        val time  = LocalTime.now()\n        val hour = time.hour\n        val minute = time.minute\n        val second = time.second\n        var angle: Float = degrees90 - degrees06 * second\n        drawHand(g, angle, diameter \/ 2 - 30, Color.red)\n        val minsecs: Float = minute + second \/ 60.0f\n        angle = degrees90 - degrees06 * minsecs\n        drawHand(g, angle, diameter \/ 3 + 10, Color.black)\n        val hourmins: Float = hour + minsecs \/ 60.0f\n        angle = degrees90 - degrees30 * hourmins\n        drawHand(g, angle, diameter \/ 4 + 10, Color.black)\n    }\n\n    private fun drawFace(g: Graphics2D) {\n        g.stroke = BasicStroke(2.0f)\n        g.color = Color.yellow\n        g.fillOval(spacing, spacing, diameter, diameter)\n        g.color = Color.black\n        g.drawOval(spacing, spacing, diameter, diameter)\n    }\n\n    private fun drawHand(g: Graphics2D, angle: Float, radius: Int, color: Color) {\n        val x: Int  = cx + (radius.toDouble() * Math.cos(angle.toDouble())).toInt()\n        val y: Int =  cy - (radius.toDouble() * Math.sin(angle.toDouble())).toInt()\n        g.color = color\n        g.drawLine(cx, cy, x, y)\n    }\n}\n\nfun main(args: Array<String>) {\n    SwingUtilities.invokeLater {\n        val f = JFrame()\n        f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n        f.title = \"Clock\"\n        f.isResizable = false\n        f.add(Clock(), BorderLayout.CENTER)\n        f.pack()\n        f.setLocationRelativeTo(null)\n        f.isVisible = true\n    }\n}\n\n","human_summarization":"illustrate a time-keeping device that updates every second and cycles periodically. It is designed to be simple, efficient, and not to overuse CPU resources by avoiding unnecessary system timer polling. The time displayed aligns with the system clock. Both text-based and graphical representations are supported.","id":4536}
    {"lang_cluster":"Kotlin","source_code":"\n\nIMPORT JAVA.TEXT.*\nIMPORT JAVA.UTIL.*\nIMPORT JAVA.IO.PRINTSTREAM\n \nINTERNAL FUN PRINTSTREAM.PRINTCALENDAR(YEAR: INT, NCOLS: BYTE, LOCALE: LOCALE?) {\n    IF (NCOLS < 1 || NCOLS > 12)\n        THROW ILLEGALARGUMENTEXCEPTION(\"ILLEGAL COLUMN WIDTH.\")\n    VAL W = NCOLS * 24\n    VAL NROWS = MATH.CEIL(12.0 \/ NCOLS).TOINT()\n \n    VAL DATE = GREGORIANCALENDAR(YEAR, 0, 1)\n    VAR OFFS = DATE.GET(CALENDAR.DAY_OF_WEEK) - 1\n \n    VAL DAYS = DATEFORMATSYMBOLS(LOCALE).SHORTWEEKDAYS.SLICE(1..7).MAP { IT.SLICE(0..1) }.JOINTOSTRING(\" \", \" \")\n    VAL MONS = ARRAY(12) { ARRAY(8) { \"\" } }\n    DATEFORMATSYMBOLS(LOCALE).MONTHS.SLICE(0..11).FOREACHINDEXED { M, NAME ->\n        VAL LEN = 11 + NAME.LENGTH \/ 2\n        VAL FORMAT = MESSAGEFORMAT.FORMAT(\"%{0}S%{1}S\", LEN, 21 - LEN)\n        MONS[M][0] = STRING.FORMAT(FORMAT, NAME, \"\")\n        MONS[M][1] = DAYS\n        VAL DIM = DATE.GETACTUALMAXIMUM(CALENDAR.DAY_OF_MONTH)\n        FOR (D IN 1..42) {\n            VAL ISDAY = D > OFFS && D <= OFFS + DIM\n            VAL ENTRY = IF (ISDAY) STRING.FORMAT(\" %2S\", D - OFFS) ELSE \"   \"\n            IF (D % 7 == 1)\n                MONS[M][2 + (D - 1) \/ 7] = ENTRY\n            ELSE\n                MONS[M][2 + (D - 1) \/ 7] += ENTRY\n        }\n        OFFS = (OFFS + DIM) % 7\n        DATE.ADD(CALENDAR.MONTH, 1)\n    }\n \n    PRINTF(\"%\" + (W \/ 2 + 10) + \"S%N\", \"[SNOOPY PICTURE]\")\n    PRINTF(\"%\" + (W \/ 2 + 4) + \"S%N%N\", YEAR)\n \n    FOR (R IN 0..NROWS - 1) {\n        FOR (I IN 0..7) {\n            VAR C = R * NCOLS\n            WHILE (C < (R + 1) * NCOLS && C < 12) {\n                PRINTF(\"   %S\", MONS[C][I].TOUPPERCASE())  \/\/ ORIGINAL CHANGED TO PRINT IN UPPER CASE \n                C++\n            }\n            PRINTLN()\n        }\n        PRINTLN()\n    }\n}\n \nFUN MAIN(ARGS: ARRAY<STRING>) {\n    SYSTEM.OUT.PRINTCALENDAR(1969, 3, LOCALE.US)\n}\n\n\n\/\/ version 1.1.3\n\nimport java.io.File\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\n\nfun main(args: Array<String>) {\n    val keywords = listOf(\n        \"import\", \"internal\", \"fun\", \"if\", \"throw\", \"val\", \"var\", \"for\", \"in\", \"while\"\n    )\n\n    val singleCase = listOf(\n        \"java.text\",\n        \"java.util\",\n        \"java.io\",\n        \"else\",     \/\/ really a keyword but doesn't have a following space here\n        \"ceil\",\n        \"it\",       \/\/ really a keyword but doesn't have a following space here\n        \"get(\",     \/\/ also included in GETACTUALMAXIMUM       \n        \"slice\",\n        \"map\",\n        \"months\",        \n        \"length\",\n        \".format\",  \/\/ also variable called FORMAT        \n        \"add\",\n        \"printf\", \n        \"println\",\n        \"out\",\n        \"main\",\n        \"args\",\n        \"s%{1}s\",\n        \"%2s\",\n        \"s%n%n\",\n        \"s%n\",\n        \"%s\"\n    ) \n         \n    val mixedCase = listOf( \n        \"PRINTSTREAM\" to \"PrintStream\",\n        \"INT,\" to \"Int,\",  \/\/ also included in PRINTCALENDAR\n        \"BYTE\" to \"Byte\",\n        \"LOCALE?\" to \"Locale?\",  \/\/ also variable called LOCALE\n        \"LOCALE.\" to \"Locale.\",\n        \"ILLEGALARGUMENTEXCEPTION\" to \"IllegalArgumentException\",\n        \"MATH\" to \"Math\",\n        \"GREGORIANCALENDAR\" to \"GregorianCalendar\",\n        \"DATEFORMATSYMBOLS\" to \"DateFormatSymbols\",\n        \"ARRAY\" to \"Array\",\n        \"MESSAGEFORMAT\" to \"MessageFormat\",\n        \"JOINTOSTRING\" to \"joinToString\",\n        \"STRING\" to \"String\",\n        \"CALENDAR.\" to \"Calendar.\", \/\/ also included in PRINTCALENDAR\n        \"SYSTEM\" to \"System\",\n        \"TOINT\" to \"toInt\",\n        \"SHORTWEEKDAYS\" to \"shortWeekdays\",\n        \"FOREACHINDEXED\" to \"forEachIndexed\",\n        \"GETACTUALMAXIMUM\" to \"getActualMaximum\",\n        \"TOUPPERCASE\" to \"toUpperCase\"\n    )\n        \n    var text = File(\"calendar_UC.txt\").readText()\n    for (k in keywords)   text = text.replace(\"${k.toUpperCase()} \", \"$k \") \/\/ add a following space to be on safe side\n    for (s in singleCase) text = text.replace(s.toUpperCase(), s)\n    for (m in mixedCase)  text = text.replace(m.first, m.second)\n    File(\"calendar_NC.kt\").writeText(text)\n    val commands = listOf(\"kotlinc\", \"calendar_NC.kt\", \"-include-runtime\", \"-d\", \"calendar_X.jar\")\n    val pb = ProcessBuilder(commands)\n    pb.redirectErrorStream(true)\n    val process = pb.start()\n    process.waitFor()\n    val commands2 = listOf(\"java\", \"-jar\", \"calendar_NC.jar\")\n    val pb2 = ProcessBuilder(commands2)\n    pb2.redirectErrorStream(true)\n    val process2 = pb2.start()\n    val out = StringBuilder()\n    val br = BufferedReader(InputStreamReader(process2.inputStream))\n    while (true) {\n        val line = br.readLine()\n        if (line == null) break\n        out.append(line).append('\\n')\n    }\n    br.close()\n    println(out.toString()) \n}\n\n\nimport java.text.*\nimport java.util.*\nimport java.io.PrintStream\n \ninternal fun PrintStream.PRINTCALENDAR(YEAR: Int, NCOLS: Byte, LOCALE: Locale?) {\n    if (NCOLS < 1 || NCOLS > 12)\n        throw IllegalArgumentException(\"ILLEGAL COLUMN WIDTH.\")\n    val W = NCOLS * 24\n    val NROWS = Math.ceil(12.0 \/ NCOLS).toInt()\n \n    val DATE = GregorianCalendar(YEAR, 0, 1)\n    var OFFS = DATE.get(Calendar.DAY_OF_WEEK) - 1\n \n    val DAYS = DateFormatSymbols(LOCALE).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(\" \", \" \")\n    val MONS = Array(12) { Array(8) { \"\" } }\n    DateFormatSymbols(LOCALE).months.slice(0..11).forEachIndexed { M, NAME ->\n        val LEN = 11 + NAME.length \/ 2\n        val FORMAT = MessageFormat.format(\"%{0}s%{1}s\", LEN, 21 - LEN)\n        MONS[M][0] = String.format(FORMAT, NAME, \"\")\n        MONS[M][1] = DAYS\n        val DIM = DATE.getActualMaximum(Calendar.DAY_OF_MONTH)\n        for (D in 1..42) {\n            val ISDAY = D > OFFS && D <= OFFS + DIM\n            val ENTRY = if (ISDAY) String.format(\" %2s\", D - OFFS) else \"   \"\n            if (D % 7 == 1)\n                MONS[M][2 + (D - 1) \/ 7] = ENTRY\n            else\n                MONS[M][2 + (D - 1) \/ 7] += ENTRY\n        }\n        OFFS = (OFFS + DIM) % 7\n        DATE.add(Calendar.MONTH, 1)\n    }\n \n    printf(\"%\" + (W \/ 2 + 10) + \"s%n\", \"[SNOOPY PICTURE]\")\n    printf(\"%\" + (W \/ 2 + 4) + \"s%n%n\", YEAR)\n \n    for (R in 0..NROWS - 1) {\n        for (I in 0..7) {\n            var C = R * NCOLS\n            while (C < (R + 1) * NCOLS && C < 12) {\n                printf(\"   %s\", MONS[C][I].toUpperCase())  \/\/ ORIGINAL CHANGED TO PRINT in UPPER CASE \n                C++\n            }\n            println()\n        }\n        println()\n    }\n}\n \nfun main(args: Array<String>) {\n    System.out.PRINTCALENDAR(1969, 3, Locale.US)\n}\n\n\n","human_summarization":"The code provides an algorithm for a calendar task, formatted to fit a page that is 132 characters wide, and is entirely in uppercase, inspired by 1969 era line printers and the article \"Real programmers think in UPPERCASE\". The code also considers the limitations of the Kotlin language, which is case-sensitive, by saving the uppercase version of the Calendar program to a text file, and then creating a separate program that makes minimum changes to the uppercase text file to make it runnable. The output is a calendar with a placeholder for a Snoopy image.","id":4537}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nvar total = 0L\nvar prim = 0L\nvar maxPeri = 0L\n\nfun newTri(s0: Long, s1: Long, s2: Long) {\n    val p = s0 + s1 + s2\n    if (p <= maxPeri) {\n        prim++\n        total += maxPeri \/ p\n        newTri( s0 - 2 * s1 + 2 * s2,  2 * s0 - s1 + 2 * s2,  2 * s0 - 2 * s1 + 3 * s2)\n        newTri( s0 + 2 * s1 + 2 * s2,  2 * s0 + s1 + 2 * s2,  2 * s0 + 2 * s1 + 3 * s2)\n        newTri(-s0 + 2 * s1 + 2 * s2, -2 * s0 + s1 + 2 * s2, -2 * s0 + 2 * s1 + 3 * s2)\n    }\n}\n\nfun main(args: Array<String>) {\n    maxPeri = 100\n    while (maxPeri <= 10_000_000_000L) {\n        prim = 0\n        total = 0\n        newTri(3, 4, 5)\n        println(\"Up to $maxPeri: $total triples, $prim primatives\")\n        maxPeri *= 10\n    }\n}\n\n\n","human_summarization":"The code calculates the number of Pythagorean triples with a perimeter not exceeding a given limit, and also determines how many of these triples are primitive. It is optimized to handle large perimeter values up to 10 billion.","id":4538}
    {"lang_cluster":"Kotlin","source_code":"import javax.swing.JFrame\n\nfun main(args : Array<String>) {\n    JFrame(\"Title\").apply {\n        setSize(800, 600)\n        defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n        isVisible = true\n    }\n}\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":4539}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nimport java.io.File\n\nfun main(args: Array<String>) {\n    val text = File(\"input.txt\").readText().toLowerCase()\n    val letterMap = text.filter { it in 'a'..'z' }.groupBy { it }.toSortedMap()\n    for (letter in letterMap) println(\"${letter.key} = ${letter.value.size}\")\n    val sum = letterMap.values.sumBy { it.size }\n    println(\"\\nTotal letters = $sum\")\n}\n\n\n","human_summarization":"Open a text file 'input.txt', count the frequency of each letter from A to Z, and also count all characters including punctuation. The text file contains two pangrams.","id":4540}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nclass Node<T: Number>(var data: T, var next: Node<T>? = null) {\n    override fun toString(): String {\n        val sb = StringBuilder(this.data.toString())\n        var node = this.next\n        while (node != null) {\n            sb.append(\" -> \", node.data.toString())\n            node = node.next\n        }\n        return sb.toString()\n    }\n}\n\nfun main(args: Array<String>) {\n    val n = Node(1, Node(2, Node(3)))\n    println(n)\n}\n\n\n","human_summarization":"define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.","id":4541}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.2\n\nimport java.awt.Color\nimport java.awt.Graphics\nimport javax.swing.JFrame\n\nclass FractalTree : JFrame(\"Fractal Tree\") {\n    init {\n        background = Color.black\n        setBounds(100, 100, 800, 600)\n        isResizable = false\n        defaultCloseOperation = EXIT_ON_CLOSE\n    }\n\n    private fun drawTree(g: Graphics, x1: Int, y1: Int, angle: Double, depth: Int) {\n        if (depth == 0) return\n        val x2 = x1 + (Math.cos(Math.toRadians(angle)) * depth * 10.0).toInt()\n        val y2 = y1 + (Math.sin(Math.toRadians(angle)) * depth * 10.0).toInt()\n        g.drawLine(x1, y1, x2, y2)\n        drawTree(g, x2, y2, angle - 20, depth - 1)\n        drawTree(g, x2, y2, angle + 20, depth - 1)\n    }\n\n    override fun paint(g: Graphics) {\n        g.color = Color.white\n        drawTree(g, 400, 500, -90.0, 9)\n    }\n}\n\nfun main(args: Array<String>) {\n    FractalTree().isVisible = true\n}\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":4542}
    {"lang_cluster":"Kotlin","source_code":"\nfun printFactors(n: Int) {\n    if (n < 1) return\n    print(\"$n => \")\n    (1..n \/ 2)\n        .filter { n\u00a0% it == 0 }\n        .forEach { print(\"$it \") }\n    println(n)\n}\n\nfun main(args: Array<String>) {\n    val numbers = intArrayOf(11, 21, 32, 45, 67, 96)\n    for (number in numbers) printFactors(number)\n}\n\n","human_summarization":"compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.","id":4543}
    {"lang_cluster":"Kotlin","source_code":"\nimport java.nio.charset.StandardCharsets\nimport java.nio.file.Files\nimport java.nio.file.Paths\n\nenum class AlignFunction {\n    LEFT { override fun invoke(s: String, l: Int) = (\"%-\" + l + 's').format((\"%\" + s.length + 's').format(s)) },\n    RIGHT { override fun invoke(s: String, l: Int) = (\"%-\" + l + 's').format((\"%\" + l + 's').format(s)) },\n    CENTER { override fun invoke(s: String, l: Int) = (\"%-\" + l + 's').format((\"%\" + ((l + s.length) \/ 2) + 's').format(s)) };\n\n    abstract operator fun invoke(s: String, l: Int): String\n}\n\n\/** Aligns fields into columns, separated by \"|\".\n * @constructor Initializes columns aligner from lines in a list of strings.\n * @property lines Lines in a single string. Empty string does form a column.\n *\/\nclass ColumnAligner(val lines: List<String>) {\n     operator fun invoke(a: AlignFunction) : String {\n        var result = \"\"\n        for (lineWords in words) {\n            for (i in lineWords.indices) {\n                if (i == 0)\n                    result += '|'\n                result += a(lineWords[i], column_widths[i])\n                result += '|'\n            }\n            result += '\\n'\n        }\n        return result\n    }\n\n    private val words = arrayListOf<Array<String>>()\n    private val column_widths = arrayListOf<Int>()\n\n    init {\n        lines.forEach  {\n            val lineWords = java.lang.String(it).split(\"\\\\$\")\n            words += lineWords\n            for (i in lineWords.indices) {\n                if (i >= column_widths.size) {\n                    column_widths += lineWords[i].length\n                } else {\n                    column_widths[i] = Math.max(column_widths[i], lineWords[i].length)\n                }\n            }\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    if (args.isEmpty()) {\n        println(\"Usage: ColumnAligner file [L|R|C]\")\n        return\n    }\n    val ca = ColumnAligner(Files.readAllLines(Paths.get(args[0]), StandardCharsets.UTF_8))\n    val alignment = if (args.size >= 2) args[1] else \"L\"\n    when (alignment) {\n        \"L\" -> print(ca(AlignFunction.LEFT))\n        \"R\" -> print(ca(AlignFunction.RIGHT))\n        \"C\" -> print(ca(AlignFunction.CENTER))\n        else -> System.err.println(\"Error! Unknown alignment: \" + alignment)\n    }\n}\n\n","human_summarization":"The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.","id":4544}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1\n\nimport java.awt.*\nimport java.awt.event.MouseAdapter\nimport java.awt.event.MouseEvent\nimport javax.swing.*\n\nclass Cuboid: JPanel() {\n    private val nodes = arrayOf(\n        doubleArrayOf(-1.0, -1.0, -1.0),\n        doubleArrayOf(-1.0, -1.0,  1.0),\n        doubleArrayOf(-1.0,  1.0, -1.0),\n        doubleArrayOf(-1.0,  1.0,  1.0),\n        doubleArrayOf( 1.0, -1.0, -1.0),\n        doubleArrayOf( 1.0, -1.0,  1.0),\n        doubleArrayOf( 1.0,  1.0, -1.0),\n        doubleArrayOf( 1.0,  1.0,  1.0)\n    )\n    private val edges = arrayOf(\n        intArrayOf(0, 1),\n        intArrayOf(1, 3),\n        intArrayOf(3, 2),\n        intArrayOf(2, 0),\n        intArrayOf(4, 5),\n        intArrayOf(5, 7),\n        intArrayOf(7, 6),\n        intArrayOf(6, 4),\n        intArrayOf(0, 4),\n        intArrayOf(1, 5),\n        intArrayOf(2, 6),\n        intArrayOf(3, 7)\n    )\n\n    private var mouseX: Int = 0\n    private var prevMouseX: Int = 0\n    private var mouseY: Int = 0\n    private var prevMouseY: Int = 0\n\n    init {\n        preferredSize = Dimension(640, 640)\n        background = Color.white\n        scale(80.0, 120.0, 160.0)\n        rotateCube(Math.PI \/ 5.0, Math.PI \/ 9.0)\n        addMouseListener(object: MouseAdapter() {\n            override fun mousePressed(e: MouseEvent) {\n                mouseX = e.x\n                mouseY = e.y\n            }\n        })\n\n        addMouseMotionListener(object: MouseAdapter() {\n            override fun mouseDragged(e: MouseEvent) {\n                prevMouseX = mouseX\n                prevMouseY = mouseY\n                mouseX = e.x\n                mouseY = e.y\n                val incrX = (mouseX - prevMouseX) * 0.01\n                val incrY = (mouseY - prevMouseY) * 0.01\n                rotateCube(incrX, incrY)\n                repaint()\n            }\n        })\n    }\n\n    private fun scale(sx: Double, sy: Double, sz: Double) {\n        for (node in nodes) {\n            node[0] *= sx\n            node[1] *= sy\n            node[2] *= sz\n        }\n    }\n\n    private fun rotateCube(angleX: Double, angleY: Double) {\n        val sinX = Math.sin(angleX)\n        val cosX = Math.cos(angleX)\n        val sinY = Math.sin(angleY)\n        val cosY = Math.cos(angleY)\n        for (node in nodes) {\n            val x = node[0]\n            val y = node[1]\n            var z = node[2]\n            node[0] = x * cosX - z * sinX\n            node[2] = z * cosX + x * sinX\n            z = node[2]\n            node[1] = y * cosY - z * sinY\n            node[2] = z * cosY + y * sinY\n        }\n    }\n\n    private fun drawCube(g: Graphics2D) {\n        g.translate(width \/ 2, height \/ 2)\n        for (edge in edges) {\n            val xy1 = nodes[edge[0]]\n            val xy2 = nodes[edge[1]]\n            g.drawLine(Math.round(xy1[0]).toInt(), Math.round(xy1[1]).toInt(),\n                       Math.round(xy2[0]).toInt(), Math.round(xy2[1]).toInt())\n        }\n        for (node in nodes) {\n            g.fillOval(Math.round(node[0]).toInt() - 4, Math.round(node[1]).toInt() - 4, 8, 8)\n        }\n    }\n\n    override public fun paintComponent(gg: Graphics) {\n        super.paintComponent(gg)\n        val g = gg as Graphics2D\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n        g.color = Color.blue\n        drawCube(g)\n    }\n}\n\nfun main(args: Array<String>) {\n    SwingUtilities.invokeLater {\n        val f = JFrame()\n        f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n        f.title = \"Cuboid\"\n        f.isResizable = false\n        f.add(Cuboid(), BorderLayout.CENTER)\n        f.pack()\n        f.setLocationRelativeTo(null)\n        f.isVisible = true\n    }\n}\n\n","human_summarization":"generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.","id":4545}
    {"lang_cluster":"Kotlin","source_code":"\nimport org.apache.directory.api.ldap.model.exception.LdapException\nimport org.apache.directory.ldap.client.api.LdapNetworkConnection\nimport java.io.IOException\nimport java.util.logging.Level\nimport java.util.logging.Logger\n\nclass LDAP(map: Map<String, String>) {\n    fun run() {\n        var connection: LdapNetworkConnection? = null\n        try {\n            if (info) log.info(\"LDAP Connection to $hostname on port $port\")\n            connection = LdapNetworkConnection(hostname, port.toInt())\n\n            try {\n                if (info) log.info(\"LDAP bind\")\n                connection.bind()\n            } catch (e: LdapException) {\n                log.severe(e.toString())\n            }\n\n            try {\n                if (info) log.info(\"LDAP unbind\")\n                connection.unBind()\n            } catch (e: LdapException) {\n                log.severe(e.toString())\n            }\n        } finally {\n            try {\n                if (info) log.info(\"LDAP close connection\")\n                connection!!.close()\n            } catch (e: IOException) {\n                log.severe(e.toString())\n            }\n        }\n    }\n\n    private val log = Logger.getLogger(LDAP::class.java.name)\n    private val info = log.isLoggable(Level.INFO)\n    private val hostname: String by map\n    private val port: String by map\n}\n\nfun main(args: Array<String>) = LDAP(mapOf(\"hostname\" to \"localhost\", \"port\"  to \"10389\")).run()\n\n","human_summarization":"establish a connection to an Active Directory or Lightweight Directory Access Protocol server.","id":4546}
    {"lang_cluster":"Kotlin","source_code":"\nimport java.io.*\n\nfun String.rot13() = map {\n    when {\n        it.isUpperCase() -> { val x = it + 13; if (x > 'Z') x - 26 else x }\n        it.isLowerCase() -> { val x = it + 13; if (x > 'z') x - 26 else x }\n        else -> it\n    } }.toCharArray()\n\nfun InputStreamReader.println() =\n        try { BufferedReader(this).forEachLine { println(it.rot13()) } }\n        catch (e: IOException) { e.printStackTrace() }\n\nfun main(args: Array<String>) {\n    if (args.any())\n        args.forEach { FileReader(it).println() }\n    else\n        InputStreamReader(System.`in`).println()\n}\n\n","human_summarization":"implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is \"rotated\" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.","id":4547}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1\n\ndata class Employee(val name: String, var category: String) : Comparable<Employee> {\n    override fun compareTo(other: Employee) = this.name.compareTo(other.name)\n}\n\nfun main(args: Array<String>) {\n    val employees = arrayOf(\n        Employee(\"David\", \"Manager\"),\n        Employee(\"Alice\", \"Sales\"),\n        Employee(\"Joanna\", \"Director\"),\n        Employee(\"Henry\", \"Admin\"),\n        Employee(\"Tim\", \"Sales\"),\n        Employee(\"Juan\", \"Admin\")\n    )\n    employees.sort()\n    for ((name, category) in employees) println(\"${name.padEnd(6)}\u00a0: $category\")\n}\n\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.","id":4548}
    {"lang_cluster":"Kotlin","source_code":"\nfun main(args: Array<String>) {\n    (1..5).forEach {\n        (1..it).forEach { print('*') }\n        println()\n    }\n}\n\n","human_summarization":"demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.","id":4549}
    {"lang_cluster":"Kotlin","source_code":"fun main(args: Array<String>) {\n    \/\/ map definition:\n    val map = mapOf(\"foo\" to 5,\n                    \"bar\" to 10,\n                    \"baz\" to 15,\n                    \"foo\" to 6)\n\n    \/\/ retrieval:\n    println(map[\"foo\"]) \/\/ => 6\n    println(map[\"invalid\"]) \/\/ => null\n\n    \/\/ check keys:\n    println(\"foo\" in map) \/\/ => true\n    println(\"invalid\" in map) \/\/ => false\n\n    \/\/ iterate over keys:\n    for (k in map.keys) print(\"$k \")\n    println()\n\n    \/\/ iterate over values:\n    for (v in map.values) print(\"$v \")\n    println()\n\n    \/\/ iterate over key, value pairs:\n    for ((k, v) in map) println(\"$k => $v\")\n}\n\n","human_summarization":"\"Create an associative array, also known as a dictionary, map, or hash.\"","id":4550}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.3\n\nclass Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {\n    private var state = s\n    \n    fun nextInt(): Long {\n        state = (a * state + c) % m\n        return state \/ d\n    }\n}\n\nfun main(args: Array<String>) {\n    println(\"First 10 BSD random numbers - seed 0\")\n    val bsd = Lcg(1103515245, 12345, 1 shl 31, 1, 0)\n    for (i in 1..10) println(\"${bsd.nextInt()}\")\n    println(\"\\nFirst 10 MSC random numbers - seed 0\")\n    val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, 0)\n    for (i in 1..10) println(\"${msc.nextInt()}\")\n}\n\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":4551}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nclass Node<T: Number>(var data: T, var next: Node<T>? = null) {\n    override fun toString(): String {\n        val sb = StringBuilder(this.data.toString())\n        var node = this.next\n        while (node != null) {\n            sb.append(\" -> \", node.data.toString())\n            node = node.next\n        }\n        return sb.toString()\n    }\n}\n\nfun <T: Number> insertAfter(prev: Node<T>, new: Node<T>) {\n    new.next = prev.next\n    prev.next = new\n}\n\nfun main(args: Array<String>) {\n    val b = Node(3)\n    val a = Node(1, b)\n    println(\"Before insertion\u00a0: $a\")\n    val c = Node(2)\n    insertAfter(a, c)\n    println(\"After  insertion\u00a0: $a\")\n}\n\n\n","human_summarization":"\"Defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element C into a list of elements A->B, after element A.\"","id":4552}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nfun halve(n: Int) = n \/ 2\n\nfun double(n: Int) = n * 2\n\nfun isEven(n: Int) = n % 2 == 0\n\nfun ethiopianMultiply(x: Int, y: Int): Int {\n    var xx = x\n    var yy = y\n    var sum = 0\n    while (xx >= 1) {\n       if (!isEven(xx)) sum += yy\n       xx = halve(xx)\n       yy = double(yy)\n    }\n    return sum\n}\n\nfun main(args: Array<String>) {\n    println(\"17 x 34 = ${ethiopianMultiply(17, 34)}\")\n    println(\"99 x 99 = ${ethiopianMultiply(99, 99)}\")\n}\n\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.","id":4553}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.3\n\nimport java.util.Random\n\nconst val N_CARDS = 4\nconst val SOLVE_GOAL = 24\nconst val MAX_DIGIT = 9\n\nclass Frac(val num: Int, val den: Int)\n\nenum class OpType { NUM, ADD, SUB, MUL, DIV }\n\nclass Expr(\n    var op:    OpType = OpType.NUM,\n    var left:  Expr?  = null,\n    var right: Expr?  = null,\n    var value: Int    = 0\n)\n\nfun showExpr(e: Expr?, prec: OpType, isRight: Boolean) {\n    if (e == null) return\n    val op = when (e.op) {\n        OpType.NUM -> { print(e.value); return }\n        OpType.ADD -> \" + \"\n        OpType.SUB -> \" - \"\n        OpType.MUL -> \" x \"\n        OpType.DIV -> \" \/ \"\n    }\n\n    if ((e.op == prec && isRight) || e.op < prec) print(\"(\")\n    showExpr(e.left, e.op, false)\n    print(op)\n    showExpr(e.right, e.op, true)\n    if ((e.op == prec && isRight) || e.op < prec) print(\")\")\n}\n\nfun evalExpr(e: Expr?): Frac {\n    if (e == null) return Frac(0, 1)\n    if (e.op == OpType.NUM) return Frac(e.value, 1)\n    val l = evalExpr(e.left)\n    val r = evalExpr(e.right)\n    return when (e.op) {\n        OpType.ADD -> Frac(l.num * r.den + l.den * r.num, l.den * r.den)\n        OpType.SUB -> Frac(l.num * r.den - l.den * r.num, l.den * r.den)\n        OpType.MUL -> Frac(l.num * r.num, l.den * r.den)\n        OpType.DIV -> Frac(l.num * r.den, l.den * r.num)\n        else       -> throw IllegalArgumentException(\"Unknown op: ${e.op}\")\n    }\n}\n\nfun solve(ea: Array<Expr?>, len: Int): Boolean {\n    if (len == 1) {\n        val final = evalExpr(ea[0])\n        if (final.num == final.den * SOLVE_GOAL && final.den != 0) {\n            showExpr(ea[0], OpType.NUM, false)\n            return true\n        }\n    }\n\n    val ex = arrayOfNulls<Expr>(N_CARDS)\n    for (i in 0 until len - 1) {\n        for (j in i + 1 until len) ex[j - 1] = ea[j]\n        val node = Expr()\n        ex[i] = node\n        for (j in i + 1 until len) {\n            node.left = ea[i]\n            node.right = ea[j]\n            for (k in OpType.values().drop(1)) {\n                node.op = k\n                if (solve(ex, len - 1)) return true\n            }\n            node.left = ea[j]\n            node.right = ea[i]\n            node.op = OpType.SUB\n            if (solve(ex, len - 1)) return true\n            node.op = OpType.DIV\n            if (solve(ex, len - 1)) return true\n            ex[j] = ea[j]\n        }\n        ex[i] = ea[i]\n    }\n    return false\n}\n\nfun solve24(n: IntArray) =\n    solve (Array(N_CARDS) { Expr(value = n[it]) }, N_CARDS)\n\nfun main(args: Array<String>) {\n    val r = Random()\n    val n = IntArray(N_CARDS)\n    for (j in 0..9) {\n        for (i in 0 until N_CARDS) {\n            n[i] = 1 + r.nextInt(MAX_DIGIT)\n            print(\" ${n[i]}\")\n        }\n        print(\":  \")\n        println(if (solve24(n)) \"\" else \"No solution\")\n    }\n}\n\n\n 8 4 1 7:  (8 - 4) x (7 - 1)\n 6 1 4 1:  ((6 + 1) - 1) x 4\n 8 8 5 4:  (8 \/ 8 + 5) x 4\n 9 6 9 8:  8 \/ ((9 - 6) \/ 9)\n 6 6 9 6:  (6 x 6) \/ 9 x 6\n 9 9 7 7:  No solution\n 1 1 2 5:  No solution\n 6 9 4 1:  6 x (9 - 4 - 1)\n 7 7 6 4:  7 + 7 + 6 + 4\n 4 8 8 4:  4 + 8 + 8 + 4\n\n","human_summarization":"Code summarization: The code accepts or generates four digits and computes arithmetic expressions following the 24 game rules, also providing examples of the solutions.","id":4554}
    {"lang_cluster":"Kotlin","source_code":"\nfun facti(n: Int) = when {\n    n < 0 -> throw IllegalArgumentException(\"negative numbers not allowed\")\n    else  -> {\n        var ans = 1L\n        for (i in 2..n) ans *= i\n        ans\n    }\n}\n\nfun factr(n: Int): Long = when {\n    n < 0 -> throw IllegalArgumentException(\"negative numbers not allowed\")\n    n < 2 -> 1L\n    else  -> n * factr(n - 1)\n}\n\nfun main(args: Array<String>) {\n    val n = 20\n    println(\"$n! = \" + facti(n))\n    println(\"$n! = \" + factr(n))\n}\n\n","human_summarization":"The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.","id":4555}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nimport java.util.Random\n\nconst val MAX_GUESSES = 20  \/\/ say\n\nfun main(args: Array<String>) {\n    val r = Random()\n    var num: String\n    \/\/ generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits\n    do {\n        num = (1234 + r.nextInt(8643)).toString()\n    } while ('0' in num || num.toSet().size < 4)\n\n    println(\"All guesses should have exactly 4 distinct digits excluding zero.\")\n    println(\"Keep guessing until you guess the chosen number (maximum $MAX_GUESSES valid guesses).\\n\")\n    var guesses = 0\n    while (true) {\n        print(\"Enter your guess\u00a0: \")\n        val guess = readLine()!!\n        if (guess == num) {\n            println(\"You've won with ${++guesses} valid guesses!\")\n            return\n        } \n        val n = guess.toIntOrNull()\n        if (n == null) \n            println(\"Not a valid number\")\n        else if ('-' in guess || '+' in guess)\n            println(\"Can't contain a sign\")\n        else if ('0' in guess)\n            println(\"Can't contain zero\")\n        else if (guess.length != 4)\n            println(\"Must have exactly 4 digits\")\n        else if (guess.toSet().size < 4)\n            println(\"All digits must be distinct\")\n        else {            \n            var bulls = 0\n            var cows  = 0\n            for ((i, c) in guess.withIndex()) {\n                if (num[i] == c) bulls++\n                else if (c in num) cows++\n            }\n            println(\"Your score for this guess:  Bulls = $bulls  Cows = $cows\")\n            guesses++\n            if (guesses == MAX_GUESSES) \n                println(\"You've now had $guesses valid guesses, the maximum allowed\") \n        }\n    }\n}\n\n\n\n","human_summarization":"The code generates a random four-digit number from 1 to 9 without duplication. It prompts the user to guess this number, rejects malformed guesses, and calculates a score based on the guess. The score is determined by the number of 'bulls' and 'cows', where a 'bull' is a digit in the guess that matches the corresponding digit in the randomly chosen number, and a 'cow' is a digit in the guess that appears in the randomly chosen number but in a different position. The game ends when the guess matches the randomly chosen number.","id":4556}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nimport java.util.Random\n\nfun main(args: Array<String>) {\n    val r = Random()\n    val da = DoubleArray(1000)\n    for (i in 0 until 1000)  da[i] = 1.0 + 0.5 * r.nextGaussian()\n    \/\/ now check actual mean and SD\n    val mean = da.average()\n    val sd = Math.sqrt(da.map { (it - mean) * (it - mean) }.average())\n    println(\"Mean is $mean\")\n    println(\"S.D. is $sd\")\n}\n\n\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5. If the library only supports uniformly distributed random numbers, it applies a specific algorithm to achieve the task.","id":4557}
    {"lang_cluster":"Kotlin","source_code":"\nWorks with: Kotlin version 1.0+\nfun dot(v1: Array<Double>, v2: Array<Double>) =\n    v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b }\n\nfun main(args: Array<String>) {\n    dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) }\n}\n\n\n","human_summarization":"Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].","id":4558}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1\n\nimport java.util.*\n\nfun main(args: Array<String>) {\n    println(\"Keep entering text or the word 'quit' to end the program:\")\n    val sc = Scanner(System.`in`)\n    val words = mutableListOf<String>()\n    while (true) {\n        val input: String = sc.next()\n        if (input.trim().toLowerCase() == \"quit\") {\n            if (words.size > 0) println(\"\\nYou entered the following words:\\n${words.joinToString(\"\\n\")}\")\n            return\n        }\n        words.add(input)\n    }\n}\n\n\n\n","human_summarization":"\"Reads data from a text stream either word-by-word or line-by-line until there is no more data left in the stream.\"","id":4559}
    {"lang_cluster":"Kotlin","source_code":"\n\n\/\/ version 1.1.3\n\nimport javax.xml.parsers.DocumentBuilderFactory\nimport javax.xml.transform.dom.DOMSource\nimport java.io.StringWriter\nimport javax.xml.transform.stream.StreamResult\nimport javax.xml.transform.TransformerFactory\n\nfun main(args: Array<String>) {\n    val dbFactory = DocumentBuilderFactory.newInstance()\n    val dBuilder  = dbFactory.newDocumentBuilder()\n    val doc = dBuilder.newDocument()\n    val root = doc.createElement(\"root\")  \/\/ create root node\n    doc.appendChild(root)\n    val element = doc.createElement(\"element\")  \/\/ create element node\n    val text = doc.createTextNode(\"Some text here\")  \/\/ create text node\n    element.appendChild(text)\n    root.appendChild(element)\n\n    \/\/ serialize\n    val source = DOMSource(doc)\n    val sw = StringWriter()\n    val result = StreamResult(sw)\n    val tFactory = TransformerFactory.newInstance()\n    tFactory.newTransformer().apply {\n        setOutputProperty(\"indent\", \"yes\")\n        setOutputProperty(\"{http:\/\/xml.apache.org\/xslt}indent-amount\", \"4\") \n        transform(source, result)\n    }\n    println(sw)            \n}\n\n\n","human_summarization":"This code creates a simple Document Object Model (DOM) and serializes it into XML format. The XML output includes a root element with a child element containing text. However, the code does not prevent the default encoding and standalone attributes from appearing in the XML declaration. Setting the standalone attribute to true removes it from the declaration but does not add a carriage return before the root tag. Therefore, the code leaves the declaration as is.","id":4560}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n    println(\"%tc\".format(System.currentTimeMillis()))\n}\n\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":4561}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.0\n\nval weights = listOf(1, 3, 1, 7, 3, 9, 1)\n\nfun sedol7(sedol6: String): String {\n    if (sedol6.length != 6) throw IllegalArgumentException(\"Length of argument string must be 6\")\n    var sum = 0\n    for (i in 0..5) {\n        val c = sedol6[i] \n        val v = when (c) {\n            in '0'..'9' -> c.toInt() - 48  \n            in 'A'..'Z' -> c.toInt() - 55\n            else        -> throw IllegalArgumentException(\"Argument string contains an invalid character\")\n        }\n        sum += v * weights[i]\n    }\n    val check = (10 - (sum % 10)) % 10 \n    return sedol6 + (check + 48).toChar()\n}\n\nfun main(args: Array<String>) {\n    val sedol6s = listOf(\"710889\", \"B0YBKJ\", \"406566\", \"B0YBLH\", \"228276\", \"B0YBKL\",\n                         \"557910\", \"B0YBKR\", \"585284\", \"B0YBKT\", \"B00030\")\n    for (sedol6 in sedol6s) println(\"$sedol6 -> ${sedol7(sedol6)}\")\n}\n\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.","id":4562}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.0.6\n\nconst val shades = \".:!*oe&#%@\"\nval light  = doubleArrayOf(30.0, 30.0, -50.0)\n\nfun normalize(v: DoubleArray) {\n    val len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])\n    v[0] \/= len; v[1] \/= len; v[2] \/= len\n}\n\nfun dot(x: DoubleArray, y: DoubleArray): Double {\n    val d = x[0] * y[0] + x[1] * y[1] + x[2] * y[2]   \n    return if (d < 0.0) -d else 0.0\n}\n\nfun drawSphere(r: Double, k: Double, ambient: Double) {\n    val vec = DoubleArray(3)\n    var intensity: Int\n    var b : Double\n    var x: Double\n    var y: Double\n    for (i in Math.floor(-r).toInt() .. Math.ceil(r).toInt()) {\n        x = i + 0.5\n        for (j in Math.floor(-2.0 * r).toInt() .. Math.ceil(2.0 * r).toInt()) {\n            y = j \/ 2.0 + 0.5\n            if (x * x + y * y <= r * r) {\n                vec[0] = x\n                vec[1] = y\n                vec[2] = Math.sqrt(r * r - x * x - y * y) \n                normalize(vec)\n                b = Math.pow(dot(light, vec), k) + ambient \n                intensity = ((1.0 - b) * (shades.length - 1)).toInt() \n                if (intensity < 0) intensity = 0  \n                if (intensity >= shades.length - 1) intensity = shades.length - 2                 \n                print(shades[intensity])\n            }\n            else print(' ')\n        }\n        println()\n    }\n}\n\nfun main(args: Array<String>) {\n    normalize(light)\n    drawSphere(20.0, 4.0, 0.1)\n    drawSphere(10.0, 2.0, 0.4)\n}\n\n\n","human_summarization":"\"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection.\"","id":4563}
    {"lang_cluster":"Kotlin","source_code":"\nfun Int.ordinalAbbrev() =\n        if (this % 100 \/ 10 == 1) \"th\"\n        else when (this % 10) { 1 -> \"st\" 2 -> \"nd\" 3 -> \"rd\" else -> \"th\" }\n\nfun IntRange.ordinalAbbrev() = map { \"$it\" + it.ordinalAbbrev() }.joinToString(\" \")\n\nfun main(args: Array<String>) {\n    listOf((0..25), (250..265), (1000..1025)).forEach { println(it.ordinalAbbrev()) }\n}\n\n","human_summarization":"The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.","id":4564}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun stripChars(s: String, r: String) = s.replace(Regex(\"[$r]\"), \"\")\n\nfun main(args: Array<String>) {\n    println(stripChars(\"She was a soul stripper. She took my heart!\", \"aei\"))\n}\n\n\n","human_summarization":"\"Function to remove specific characters from a given string\"","id":4565}
    {"lang_cluster":"Kotlin","source_code":"\nfun main(args: Array<String>) {\n\n    \/\/Read the maximum number, set to 0 if it couldn't be read\n    val max = readLine()?.toInt() ?: 0\n    val words = mutableMapOf<Int, String>()\n\n    \/\/Read input three times for a factor and a word\n    (1..3).forEach {\n        readLine()?.let {\n            val tokens = it.split(' ')\n            words.put(tokens[0].toInt(), tokens[1])\n        }\n    }\n\n    \/\/Sort the words so they will be output in arithmetic order\n    val sortedWords = words.toSortedMap()\n\n    \/\/Find the words with matching factors and print them, print the number if no factors match\n    for (i in 1..max) {\n        val wordsToPrint = sortedWords.filter { i % it.key == 0 }.map { it.value }\n        if (wordsToPrint.isNotEmpty()) {\n            wordsToPrint.forEach { print(it) }\n            println()\n        }\n        else\n            println(i)\n    }\n}\n\n","human_summarization":"implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.","id":4566}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n    var s = \"Obama\"\n    s = \"Barack \" + s\n    println(s)\n\n    \/\/ It's also possible to use this standard library function\n    \/\/ though this is not what it's really intended for\n    var t = \"Trump\"\n    t = t.prependIndent(\"Donald \")\n    println(t)\n}\n\n\n","human_summarization":"Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.","id":4567}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.0.6\n\nimport java.awt.Color\nimport java.awt.Graphics\nimport javax.swing.JFrame\n\nclass DragonCurve(iter: Int) : JFrame(\"Dragon Curve\") {\n    private val turns: MutableList<Int>\n    private val startingAngle: Double\n    private val side: Double\n\n    init {\n        setBounds(100, 100, 800, 600)\n        defaultCloseOperation = EXIT_ON_CLOSE\n        turns = getSequence(iter)\n        startingAngle = -iter * Math.PI \/ 4\n        side = 400.0 \/ Math.pow(2.0, iter \/ 2.0)\n    }\n\n    fun getSequence(iterations: Int): MutableList<Int> {\n        val turnSequence = mutableListOf<Int>()\n        for (i in 0 until iterations) {\n            val copy = mutableListOf<Int>()\n            copy.addAll(turnSequence)\n            copy.reverse()\n            turnSequence.add(1)\n            copy.mapTo(turnSequence) { -it }\n        }\n        return turnSequence\n    }\n\n    override fun paint(g: Graphics) {\n        g.color = Color.BLUE\n        var angle = startingAngle\n        var x1 = 230\n        var y1 = 350\n        var x2 = x1 + (Math.cos(angle) * side).toInt()\n        var y2 = y1 + (Math.sin(angle) * side).toInt()\n        g.drawLine(x1, y1, x2, y2)\n        x1 = x2\n        y1 = y2\n        for (turn in turns) {\n            angle += turn * Math.PI \/ 2.0\n            x2 = x1 + (Math.cos(angle) * side).toInt()\n            y2 = y1 + (Math.sin(angle) * side).toInt()\n            g.drawLine(x1, y1, x2, y2)\n            x1 = x2\n            y1 = y2\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    DragonCurve(14).isVisible = true\n}\n\n","human_summarization":"generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.","id":4568}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.5-2\n\nfun main(args: Array<String>) {\n\tval n = (1 + java.util.Random().nextInt(10)).toString()\n\tprintln(\"Guess which number I've chosen in the range 1 to 10\\n\")\n\tdo { print(\" Your guess\u00a0: \") } while (n != readLine())\n\tprintln(\"\\nWell guessed!\")\n}\n\n\n\n","human_summarization":"\"Implements a number guessing game where the computer selects a number between 1 and 10, and prompts the user to guess until the correct number is guessed, upon which it outputs a 'Well guessed!' message and terminates.\"","id":4569}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.3.72\n\nfun main() {\n    val alphabet = CharArray(26) { (it + 97).toChar() }.joinToString(\"\")\n\n    println(alphabet)\n}\n\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.","id":4570}
    {"lang_cluster":"Kotlin","source_code":"\nfun main() {\n    val numbers = intArrayOf(5, 50, 9000)\n    numbers.forEach { println(\"$it -> ${it.toString(2)}\") }\n}\n\n\n","human_summarization":"generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.","id":4571}
    {"lang_cluster":"Kotlin","source_code":"\n\n\/\/ Version 1.2.41\n\nimport java.awt.Color\nimport java.awt.Graphics\nimport java.awt.image.BufferedImage\n\nclass BasicBitmapStorage(width: Int, height: Int) {\n    val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)\n\n    fun fill(c: Color) {\n        val g = image.graphics\n        g.color = c\n        g.fillRect(0, 0, image.width, image.height)\n    }\n\n    fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())\n\n    fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))\n}\n\nfun main(args: Array<String>) {\n    val bbs = BasicBitmapStorage(320, 240)\n    with (bbs) {\n        fill(Color.white) \/\/ say\n        setPixel(100, 100, Color.red)\n        \/\/ check it worked\n        val c = getPixel(100, 100)\n        print(\"The color of the pixel at (100, 100) is \")\n        println(if (c == Color.red) \"red\" else \"white\")\n    }\n}\n\n\n","human_summarization":"create a 320x240 window and draw a red pixel at position (100,100).","id":4572}
    {"lang_cluster":"Kotlin","source_code":"\nWorks with: Kotlin version 1.0.6\n\nimport java.nio.charset.StandardCharsets\nimport java.nio.file.Files\nimport java.nio.file.Paths\n\ndata class Configuration(val map: Map<String, Any?>) {\n    val fullName: String by map\n    val favoriteFruit: String by map\n    val needsPeeling: Boolean by map\n    val otherFamily: List<String> by map\n}\n\nfun main(args: Array<String>) {\n    val lines = Files.readAllLines(Paths.get(\"src\/configuration.txt\"), StandardCharsets.UTF_8)\n    val keyValuePairs = lines.map{ it.trim() }\n            .filterNot { it.isEmpty() }\n            .filterNot(::commentedOut)\n            .map(::toKeyValuePair)\n\n    val configurationMap = hashMapOf<String, Any>(\"needsPeeling\" to false)\n    for (pair in keyValuePairs) {\n        val (key, value) = pair\n        when (key) {\n            \"FULLNAME\"       -> configurationMap.put(\"fullName\", value)\n            \"FAVOURITEFRUIT\" -> configurationMap.put(\"favoriteFruit\", value)\n            \"NEEDSPEELING\"   -> configurationMap.put(\"needsPeeling\", true)\n            \"OTHERFAMILY\"    -> configurationMap.put(\"otherFamily\", value.split(\" , \").map { it.trim() })\n            else             -> println(\"Encountered unexpected key $key=$value\")\n        }\n    }\n    println(Configuration(configurationMap))\n}\n\nprivate fun commentedOut(line: String) = line.startsWith(\"#\") || line.startsWith(\";\")\n\nprivate fun toKeyValuePair(line: String) = line.split(Regex(\" \"), 2).let {\n    Pair(it[0], if (it.size == 1) \"\" else it[1])\n}\n\n","human_summarization":"read and parse a configuration file, set variables based on the file's entries, ignore lines starting with a hash or semicolon, and handle options with multiple parameters by storing them in an array. It also provides immutability to the configuration class.","id":4573}
    {"lang_cluster":"Kotlin","source_code":"\nimport java.lang.Math.*\n\nconst val R = 6372.8 \/\/ in kilometers\n\nfun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {\n    val \u03bb1 = toRadians(lat1)\n    val \u03bb2 = toRadians(lat2)\n    val \u0394\u03bb = toRadians(lat2 - lat1)\n    val \u0394\u03c6 = toRadians(lon2 - lon1)\n    return 2 * R * asin(sqrt(pow(sin(\u0394\u03bb \/ 2), 2.0) + pow(sin(\u0394\u03c6 \/ 2), 2.0) * cos(\u03bb1) * cos(\u03bb2)))\n}\n\nfun main(args: Array<String>) = println(\"result: \" + haversine(36.12, -86.67, 33.94, -118.40))\n\n","human_summarization":"Implement the Haversine formula to calculate the great-circle distance between Nashville International Airport (BNA) and Los Angeles International Airport (LAX) using their respective longitudes and latitudes. The code uses the recommended earth radius value of 6372.8 km for calculations. The code also supports Unicode characters.","id":4574}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nimport java.net.URL\nimport java.io.InputStreamReader\nimport java.util.Scanner\n\nfun main(args: Array<String>) {\n    val url = URL(\"http:\/\/www.puzzlers.org\/pub\/wordlists\/unixdict.txt\")\n    val isr = InputStreamReader(url.openStream())\n    val sc = Scanner(isr)\n    while (sc.hasNextLine()) println(sc.nextLine())\n    sc.close()\n}\n\n","human_summarization":"Print the content of a specified URL to the console using HTTP request.","id":4575}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0\n\nfun checkLuhn(number: String): Boolean {\n    var isOdd = true\n    var sum = 0\n\n    for (index in number.indices.reversed()) {\n        val digit = number[index] - '0'\n        sum += if (isOdd) digit else (digit * 2).let { (it \/ 10) + (it % 10) }\n        isOdd = !isOdd\n    }\n\n    return (sum % 10) == 0\n}\n\nfun main(args: Array<String>) {\n    val numbers = arrayOf(\"49927398716\", \"49927398717\", \"1234567812345678\", \"1234567812345670\")\n    for (number in numbers)\n        println(\"${number.padEnd(16)} is ${if(checkLuhn(number)) \"valid\" else \"invalid\"}\")\n}\n\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.","id":4576}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.3\n\nfun josephus(n: Int, k: Int, m: Int): Pair<List<Int>, List<Int>> {\n    require(k > 0 && m > 0 && n > k && n > m)\n    val killed = mutableListOf<Int>()\n    val survived = MutableList(n) { it }\n    var start = k - 1\n    outer@ while (true) {\n        val end = survived.size - 1\n        var i = start\n        var deleted = 0\n        while (i <= end) {\n            killed.add(survived.removeAt(i - deleted))\n            if (survived.size == m) break@outer\n            deleted++\n            i += k\n        } \n        start = i - end - 1\n    }\n    return Pair(survived, killed)\n}\n \nfun main(args: Array<String>) {\n    val triples = listOf(Triple(5, 2, 1), Triple(41, 3, 1), Triple(41, 3, 3))\n    for (triple in triples) {\n        val(n, k, m) = triple \n        println(\"Prisoners = $n, Step = $m, Survivors = $m\")\n        val (survived, killed)  = josephus(n, k, m)\n        println(\"Survived  \u00a0: $survived\")\n        println(\"Kill order\u00a0: $killed\")\n        println()\n    }\n}\n\n\n","human_summarization":"- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).\n- Calculate the position of any prisoner in the killing sequence.\n- Provide an option to save a certain number of prisoners (m).\n- The numbering of prisoners can start from either 0 or 1.\n- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.","id":4577}
    {"lang_cluster":"Kotlin","source_code":"\nfun main(args: Array<String>) {\n    println(\"ha\".repeat(5))\n}\n\noperator fun String.times(n: Int) = this.repeat(n)\n\nfun main(args: Array<String>) = println(\"ha\" * 5)\n","human_summarization":"Code summarization: The following codes output a string repeated a certain number of times. It also includes a function for repeating a single character to create a new string.","id":4578}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n    val s1 = \"I am the original string\"\n    val r1 = Regex(\"^.*string$\")\n    if (s1.matches(r1)) println(\"`$s1` matches `$r1`\")\n    val r2 = Regex(\"original\")\n    val s3 = \"replacement\"\n    val s2 = s1.replace(r2, s3)\n    if (s2 != s1) println(\"`$s2` replaces `$r2` with `$s3`\")\n}\n\n\n","human_summarization":"\"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression.\"","id":4579}
    {"lang_cluster":"Kotlin","source_code":"\nimport kotlin.math.pow \/\/ not an operator but in the standard library\n\nfun main() {\n    val r = Regex(\"\"\"-?[0-9]+\\s+-?[0-9]+\"\"\")\n    print(\"Enter two integers separated by space(s): \")\n    val input: String = readLine()!!.trim()\n    val index = input.lastIndexOf(' ')\n    val a = input.substring(0, index).trimEnd().toLong()\n    val b = input.substring(index + 1).toLong()\n    println(\"$a + $b = ${a + b}\")\n    println(\"$a - $b = ${a - b}\")\n    println(\"$a * $b = ${a * b}\")\n    println(\"$a \/ $b = ${a \/ b}\")  \/\/ rounds towards zero\n    println(\"$a\u00a0% $b = ${a % b}\")  \/\/ if non-zero, matches sign of first operand\n    println(\"$a ^ $b = ${a.toDouble().pow(b.toDouble())}\")\n}\n}\n\n\n","human_summarization":"take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.","id":4580}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun countSubstring(s: String, sub: String): Int = s.split(sub).size - 1\n\nfun main(args: Array<String>) {\n    println(countSubstring(\"the three truths\",\"th\"))\n    println(countSubstring(\"ababababab\",\"abab\"))\n    println(countSubstring(\"\",\"\"))\n}\n\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":4581}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.0\n\nclass Hanoi(disks: Int) {\n    private var moves = 0\n\n    init {\n        println(\"Towers of Hanoi with $disks disks:\\n\")\n        move(disks, 'L', 'C', 'R')\n        println(\"\\nCompleted in $moves moves\\n\")\n    }\n\n    private fun move(n: Int, from: Char, to: Char, via: Char) {\n        if (n > 0) {\n            move(n - 1, from, via, to)\n            moves++\n            println(\"Move disk $n from $from to $to\")\n            move(n - 1, via, to, from)\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    Hanoi(3)\n    Hanoi(4)\n}\n\n\n","human_summarization":"\"Implement a recursive solution to solve the Towers of Hanoi problem.\"","id":4582}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 2.0\n\nfun binomial(n: Int, k: Int) = when {\n    n < 0 || k < 0 -> throw IllegalArgumentException(\"negative numbers not allowed\")\n    n == k         -> 1L\n    else           -> {\n        val kReduced = min(k, n - k)    \/\/ minimize number of steps\n        var result = 1L\n        var numerator = n\n        var denominator = 1\n        while (denominator <= kReduced)\n            result = result * numerator-- \/ denominator++\n        result\n    }\n}\n\nfun main(args: Array<String>) {\n    for (n in 0..14) {\n        for (k in 0..n)\n            print(\"%4d \".format(binomial(n, k)))\n        println()\n    }\n}\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.","id":4583}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.0\n\nval gaps = listOf(701, 301, 132, 57, 23, 10, 4, 1)  \/\/ Marcin Ciura's gap sequence\n\nfun shellSort(a: IntArray) {\n    for (gap in gaps) {\n        for (i in gap until a.size) {\n            val temp = a[i]\n            var j = i\n            while (j >= gap && a[j - gap] > temp) {\n                a[j] = a[j - gap]\n                j -= gap\n            }\n            a[j] = temp\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    val aa = arrayOf(\n        intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199),\n        intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1),\n        intArrayOf(62, 83, 18, 53, 7, 17, 95, 86, 47, 69, 25, 28)\n    )\n    for (a in aa) {\n        shellSort(a)\n        println(a.joinToString(\", \"))\n    }\n}\n\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.","id":4584}
    {"lang_cluster":"Kotlin","source_code":"\n\n\/\/ version 1.2.10\n\nimport java.io.File\nimport java.awt.image.BufferedImage\nimport javax.imageio.ImageIO\n\nfun BufferedImage.toGrayScale() {\n    for (x in 0 until width) {\n        for (y in 0 until height) {\n            var argb  = getRGB(x, y)\n            val alpha = (argb shr 24) and 0xFF\n            val red   = (argb shr 16) and 0xFF\n            val green = (argb shr  8) and 0xFF\n            val blue  =  argb and 0xFF\n            val lumin = (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt()\n            argb = (alpha shl 24) or (lumin shl 16) or (lumin shl 8) or lumin\n            setRGB(x, y, argb)\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    val image = ImageIO.read(File(\"bbc.jpg\")) \/\/ using BBC BASIC image\n    image.toGrayScale()\n    val grayFile = File(\"bbc_gray.jpg\")\n    ImageIO.write(image, \"jpg\", grayFile)\n}\n\n\n","human_summarization":"extend the data storage type to support grayscale images. It includes two operations: one to convert a color image to a grayscale image using the CIE recommended formula for luminance, and one for the backward conversion. The code ensures that rounding errors in floating-point arithmetic do not cause run-time problems or distorted results. However, the reverse operation is not fully accurate due to the loss of original color information in the conversion process.","id":4585}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.0\n\nimport java.awt.Dimension\nimport java.awt.event.MouseAdapter\nimport java.awt.event.MouseEvent\nimport java.util.*\nimport javax.swing.JFrame\nimport javax.swing.JLabel\n\nclass Rotate : JFrame() {\n    val text = \"Hello World! \"\n    val label = JLabel(text)\n    var rotRight = true\n    var startIdx = 0\n\n    init {\n        preferredSize = Dimension(96, 64)\n        label.addMouseListener(object: MouseAdapter() {\n            override fun mouseClicked(evt: MouseEvent) {\n                rotRight = !rotRight\n            }\n        })\n        add(label)\n        pack()\n        defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n        isVisible = true\n    }\n}\n\nfun getRotatedText(text: String, startIdx: Int): String {\n    val ret = StringBuilder()\n    var i = startIdx\n    do {\n        ret.append(text[i++])\n        i %= text.length\n    }\n    while (i != startIdx)\n    return ret.toString()\n}\n\nfun main(args: Array<String>) {\n    val rot = Rotate()\n    val task = object : TimerTask() {\n        override fun run() {\n            if (rot.rotRight) {\n                if (--rot.startIdx < 0) rot.startIdx += rot.text.length\n            }\n            else {\n                if (++rot.startIdx >= rot.text.length) rot.startIdx -= rot.text.length\n            }\n            rot.label.text = getRotatedText(rot.text, rot.startIdx)\n        }\n    }\n    Timer(false).schedule(task, 0, 500)\n}\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":4586}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n    var value = 0\n    do {\n        println(++value)\n    }\n    while (value % 6 != 0)\n}\n\n\n","human_summarization":"The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.","id":4587}
    {"lang_cluster":"Kotlin","source_code":"\n\nfun main() {\n    val s = \"Jos\u00e9\"\n    println(\"The char length is ${s.length}\")\n    println(\"The byte length is ${Char.SIZE_BYTES * s.length}\")\n}\n\n","human_summarization":"The code calculates the character and byte length of a string, considering UTF-8 and UTF-16 encodings. It correctly handles Unicode code points, including non-BMP ones, and provides the actual character counts in code points, not in code unit counts. It also provides the string length in graphemes if possible. For Kotlin strings, it considers them as a sequence of UTF-16 encoded characters and calculates the byte length as twice the character length.","id":4588}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nimport java.security.SecureRandom\n\nfun main(args: Array<String>) {\n    val rng = SecureRandom()\n    val rn1 = rng.nextInt()\n    val rn2 = rng.nextInt()\n    val newSeed = rn1.toLong() * rn2\n    rng.setSeed(newSeed)    \/\/ reseed using the previous 2 random numbers\n    println(rng.nextInt())  \/\/ get random 32-bit number and print it\n}\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.","id":4589}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\nfun main(args: Array<String>) {\n    val s = \"Rosetta\"\n    println(s.drop(1))\n    println(s.dropLast(1))\n    println(s.drop(1).dropLast(1))\n}\n\n\n","human_summarization":"The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.","id":4590}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nimport java.io.IOException\nimport java.net.*\n\nobject SingleInstance {\n    private var ss: ServerSocket? = null  \n\n    fun alreadyRunning(): Boolean {\n        try {\n            ss = ServerSocket(65000, 10, InetAddress.getLocalHost()) \/\/ using private port 65000        \n        }\n        catch (e: IOException) {\n            \/\/ port already in use so an instance is already running\n            return true   \n        }\n        return false\n    }\n\n    fun close() {\n        if (ss == null || ss?.isClosed() == true) return\n        ss?.close()\n    }\n}\n\nfun main(args: Array<String>) {\n    if (SingleInstance.alreadyRunning()) {\n        println(\"Application is already running, so terminating this instance\")\n        System.exit(0)\n    }\n    else { \n        println(\"OK, only this instance is running but will terminate in 10 seconds\")\n        Thread.sleep(10000)\n        SingleInstance.close()  \n    }\n}\n\n\n","human_summarization":"\"Checks if an application instance is already running, displays a message if so, and exits the program.\"","id":4591}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1\n\nimport java.awt.Toolkit\nimport javax.swing.JFrame\n\nclass Test : JFrame() {\n    init {\n        val r = Regex(\"\"\"\\[.*\\]\"\"\")\n        val toolkit = Toolkit.getDefaultToolkit()\n        val screenSize = toolkit.screenSize\n        println(\"Physical screen size\u00a0: ${formatOutput(screenSize, r)}\")\n        val insets = toolkit.getScreenInsets(graphicsConfiguration)\n        println(\"Insets              \u00a0: ${formatOutput(insets, r)}\")\n        screenSize.width  -= (insets.left + insets.right)\n        screenSize.height -= (insets.top + insets.bottom)\n        println(\"Max available       \u00a0: ${formatOutput(screenSize, r)}\")\n    }\n\n    private fun formatOutput(output: Any, r: Regex) = r.find(output.toString())!!.value.replace(\",\", \", \")\n}\n\nfun main(args: Array<String>) {\n    Test()\n}\n\n\n\n","human_summarization":"\"Determines the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations and menubars. It also handles scenarios with multiple monitors and tiling window managers.\"","id":4592}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.2.10\n\nclass Sudoku(rows: List<String>) {\n    private val grid = IntArray(81)\n    private var solved = false\n\n    init {\n        require(rows.size == 9 && rows.all { it.length == 9 }) {\n            \"Grid must be 9 x 9\"\n        }\n        for (i in 0..8) {\n            for (j in 0..8 ) grid[9 * i + j] = rows[i][j] - '0'\n        }\n    }\n\n    fun solve() {\n        println(\"Starting grid:\\n\\n$this\")\n        placeNumber(0)\n        println(if (solved) \"Solution:\\n\\n$this\" else \"Unsolvable!\")\n    }\n\n    private fun placeNumber(pos: Int) {\n        if (solved) return\n        if (pos == 81) {\n            solved = true\n            return\n        }\n        if (grid[pos] > 0) {\n            placeNumber(pos + 1)\n            return\n        }\n        for (n in 1..9) {\n            if (checkValidity(n, pos % 9, pos \/ 9)) {\n                grid[pos] = n\n                placeNumber(pos + 1)\n                if (solved) return\n                grid[pos] = 0\n            }\n        }\n    }\n\n    private fun checkValidity(v: Int, x: Int, y: Int): Boolean {\n        for (i in 0..8) {\n            if (grid[y * 9 + i] == v || grid[i * 9 + x] == v) return false\n        }\n        val startX = (x \/ 3) * 3\n        val startY = (y \/ 3) * 3\n        for (i in startY until startY + 3) {\n            for (j in startX until startX + 3) {\n                if (grid[i * 9 + j] == v) return false\n            }\n        }\n        return true\n    }\n\n    override fun toString(): String {\n        val sb = StringBuilder()\n        for (i in 0..8) {\n            for (j in 0..8) {\n                sb.append(grid[i * 9 + j])\n                sb.append(\" \")\n                if (j == 2 || j == 5) sb.append(\"| \")\n            }\n            sb.append(\"\\n\")\n            if (i == 2 || i == 5) sb.append(\"------+-------+------\\n\")\n        }\n        return sb.toString()\n    }\n}\n\nfun main(args: Array<String>) {\n    val rows = listOf(\n        \"850002400\",\n        \"720000009\",\n        \"004000000\",\n        \"000107002\",\n        \"305000900\",\n        \"040000000\",\n        \"000080070\",\n        \"017000000\",\n        \"000036040\"\n    )\n    Sudoku(rows).solve()\n}\n\n\n","human_summarization":"\"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format.\"","id":4593}
    {"lang_cluster":"Kotlin","source_code":"\nobject Knuth {\n    internal val gen = java.util.Random()\n}\n\nfun <T> Array<T>.shuffle(): Array<T> {\n    val a = clone()\n    var n = a.size\n    while (n > 1) {\n        val k = Knuth.gen.nextInt(n--)\n        val t = a[n]\n        a[n] = a[k]\n        a[k] = t\n    }\n    return a\n}\n\nfun main(args: Array<String>) {\n    val str = \"abcdefghijklmnopqrstuvwxyz\".toCharArray()\n    (1..10).forEach {\n        val s = str.toTypedArray().shuffle().toCharArray()\n        println(s)\n        require(s.toSortedSet() == str.toSortedSet())\n    }\n\n    val ia = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n    (1..10).forEach {\n        val s = ia.shuffle()\n        println(s.distinct())\n        require(s.toSortedSet() == ia.toSet())\n    }\n}\n\n\n","human_summarization":"implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.","id":4594}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nimport java.util.*\n\nfun main(args: Array<String>) {\n    print(\"Enter a year\u00a0: \")\n    val year = readLine()!!.toInt()\n    \n    println(\"The last Fridays of each month in $year are as follows:\")\n    val calendar = GregorianCalendar(year, 0, 31)\n    for (month in 1..12) {\n        val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)\n        var offset = calendar[Calendar.DAY_OF_WEEK] - Calendar.FRIDAY\n        if (offset < 0) offset += 7\n        val lastFriday = daysInMonth - offset\n        println(\"$year-\" + \"%02d-\".format(month) + \"%02d\".format(lastFriday))\n        if (month < 12) {\n            calendar.add(Calendar.DAY_OF_MONTH, 1)\n            calendar.add(Calendar.MONTH, 1)\n            calendar.add(Calendar.DAY_OF_MONTH, -1)\n        }\n    }\n}\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Friday of each month for that given year.","id":4595}
    {"lang_cluster":"Kotlin","source_code":"fun main(args: Array<String>) = print(\"Goodbye, World!\")\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":4596}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1\n\nimport javax.swing.JOptionPane\n\nfun main(args: Array<String>) {\n    do {\n        val number = JOptionPane.showInputDialog(\"Enter 75000\").toInt()\n    } while (number != 75000)\n}\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":4597}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.5-2\n\nobject Caesar {\n    fun encrypt(s: String, key: Int): String {\n        val offset = key % 26\n        if (offset == 0) return s\n        var d: Char\n        val chars = CharArray(s.length) \n        for ((index, c) in s.withIndex()) {\n            if (c in 'A'..'Z') {\n                d = c + offset\n                if (d > 'Z') d -= 26\n            }\n            else if (c in 'a'..'z') {\n                d = c + offset\n                if (d > 'z') d -= 26\n            }\n            else\n                d = c\n            chars[index] = d\n        } \n        return chars.joinToString(\"\")\n    }\n    \n    fun decrypt(s: String, key: Int): String {\n        return encrypt(s, 26 - key)\n    }\n}\n\nfun main(args: Array<String>) {\n    val encoded = Caesar.encrypt(\"Bright vixens jump; dozy fowl quack.\", 8)\n    println(encoded)\n    val decoded = Caesar.decrypt(encoded, 8)\n    println(decoded)\n}\n\n\n","human_summarization":"implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigen\u00e8re cipher with a key length of 1 and to Rot-13 with a key of 13.","id":4598}
    {"lang_cluster":"Kotlin","source_code":"\nfun main(args: Array<String>) {\n    fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)\n    fun lcm(a: Long, b: Long): Long = a \/ gcd(a, b) * b\n    println(lcm(15, 9))\n}\n\n","human_summarization":"calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m \u00d7 n| \/ gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.","id":4599}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.0\n\nfun isCusip(s: String): Boolean {\n    if (s.length != 9) return false\n    var sum = 0\n    for (i in 0..7) {\n        val c = s[i]\n        var v = when (c) {\n            in '0'..'9'  -> c.toInt() - 48\n            in 'A'..'Z'  -> c.toInt() - 55  \/\/ lower case letters apparently invalid\n            '*'          -> 36\n            '@'          -> 37\n            '#'          -> 38\n            else         -> return false\n        }\n        if (i % 2 == 1) v *= 2  \/\/ check if odd as using 0-based indexing\n        sum += v \/ 10 + v % 10\n    }\n    return s[8].toInt() - 48  == (10 - (sum % 10)) % 10\n}\n\nfun main(args: Array<String>) {\n    val candidates = listOf(\n        \"037833100\",\n        \"17275R102\",\n        \"38259P508\",\n        \"594918104\",\n        \"68389X106\",\n        \"68389X105\"\n    )\n    for (candidate in candidates) \n        println(\"$candidate -> ${if(isCusip(candidate)) \"correct\" else \"incorrect\"}\")\n}\n\n\n","human_summarization":"The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.","id":4600}
    {"lang_cluster":"Kotlin","source_code":"\n\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n    println(\"Word size\u00a0: ${System.getProperty(\"sun.arch.data.model\")} bits\")\n    println(\"Endianness: ${System.getProperty(\"sun.cpu.endian\")}-endian\")\n}\n\n\n","human_summarization":"Code summarization: The code outputs the word size and endianness of the host machine. It may not work on all JVMs but has been tested on a x64 Windows 10 machine.","id":4601}
    {"lang_cluster":"Kotlin","source_code":"import java.net.URL\nimport java.io.*\n\nobject Popularity {\n    \/** Gets language data. *\/\n    fun ofLanguages(): List<String> {\n        val languages = mutableListOf<String>()\n        var gcm = \"\"\n        do {\n            val path = url + (if (gcm == \"\") \"\" else \"&gcmcontinue=\" + gcm) + \"&prop=categoryinfo\" + \"&format=txt\"\n            try {\n                val rc = URL(path).openConnection() \/\/ URL completed, connection opened\n                \/\/ Rosetta Code objects to the default Java user agent so use a blank one\n                rc.setRequestProperty(\"User-Agent\", \"\")\n                val bfr = BufferedReader(InputStreamReader(rc.inputStream))\n                try {\n                    gcm = \"\"\n                    var languageName = \"?\"\n                    var line: String? = bfr.readLine()\n                    while (line != null) {\n                        line = line.trim { it <= ' ' }\n                        if (line.startsWith(\"[title]\")) {\n                            \/\/ have a programming language - should look like \"[title] => Category:languageName\"\n                            languageName = line[':']\n                        } else if (line.startsWith(\"[pages]\")) {\n                            \/\/ number of pages the language has (probably)\n                            val pageCount = line['>']\n                            if (pageCount != \"Array\") {\n                                \/\/ haven't got \"[pages] => Array\" - must be a number of pages\n                                languages += pageCount.toInt().toChar() + languageName\n                                languageName = \"?\"\n                            }\n                        } else if (line.startsWith(\"[gcmcontinue]\"))\n                            gcm = line['>']  \/\/ have an indication of whether there is more data or not\n                        line = bfr.readLine()\n                    }\n                } finally {\n                    bfr.close()\n                }\n            } catch (e: Exception) {\n                e.printStackTrace()\n            }\n        } while (gcm != \"\")\n\n        return languages.sortedWith(LanguageComparator)\n    }\n\n    \/** Custom sort Comparator for sorting the language list.\n     * Assumes the first character is the page count and the rest is the language name. *\/\n    internal object LanguageComparator : java.util.Comparator<String> {\n        override fun compare(a: String, b: String): Int {\n            \/\/ as we \"know\" we will be comparing languages, we will assume the Strings have the appropriate format\n            var r = b.first() - a.first()\n            return if (r == 0) a.compareTo(b) else r\n            \/\/ r == 0: the counts are the same - compare the names\n        }\n    }\n\n    \/** Gets the string following marker in text. *\/\n    private operator fun String.get(c: Char) = substringAfter(c).trim { it <= ' ' }\n\n    private val url = \"http:\/\/www.rosettacode.org\/mw\/api.php?action=query\" +\n            \"&generator=categorymembers\" + \"&gcmtitle=Category:Programming%20Languages\" +\n            \"&gcmlimit=500\"\n}\n\nfun main(args: Array<String>) {\n    \/\/ read\/sort\/print the languages (CSV format):\n    var lastTie = -1\n    var lastCount = -1\n    Popularity.ofLanguages().forEachIndexed { i, lang ->\n        val count = lang.first().toInt()\n        if (count == lastCount)\n            println(\"%12s%s\".format(\"\", lang.substring(1)))\n        else {\n            println(\"%4d, %4d, %s\".format(1 + if (count == lastCount) lastTie else i, count, lang.substring(1)))\n            lastTie = i\n            lastCount = count\n        }\n    }\n}\n\n\n","human_summarization":"sort the most popular computer programming languages based on the number of members in Rosetta Code categories. It fetches data either through web scraping or using the API method. The code also has the functionality to filter incorrect results. The final output is a ranked list of all programming languages.","id":4602}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n    val greek = arrayOf(\"alpha\", \"beta\", \"gamma\", \"delta\")\n    for (letter in greek) print(\"$letter \")\n    println()\n    \/\/ or alternatively\n    greek.forEach { print(\"$it \") }\n    println()\n}\n\n\n","human_summarization":"Iterates through each element in a collection in order and prints it, using a \"for each\" loop or another loop if \"for each\" is not available in the language.","id":4603}
    {"lang_cluster":"Kotlin","source_code":"\nWorks with: Kotlin version 1.0b4\nfun main(args: Array<String>) {\n    val input = \"Hello,How,Are,You,Today\"\n    println(input.split(',').joinToString(\".\"))\n}\n\n\n","human_summarization":"\"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period.\"","id":4604}
    {"lang_cluster":"Kotlin","source_code":"\n\ntailrec fun gcd(a: Int, b: Int): Int = if (b == 0) kotlin.math.abs(a) else gcd(b, a\u00a0% b)\n","human_summarization":"find the greatest common divisor (GCD) or greatest common factor (GCF) of two integers using a recursive one-line solution. It also relates to the task of finding the least common multiple.","id":4605}
    {"lang_cluster":"Kotlin","source_code":"import java.net.ServerSocket\nimport java.net.Socket\n\nfun main() {\n\n    fun handleClient(conn: Socket) {\n        conn.use {\n            val input = conn.inputStream.bufferedReader()\n            val output = conn.outputStream.bufferedWriter()\n\n            input.forEachLine { line ->\n                output.write(line)\n                output.newLine()\n                output.flush()\n            }\n        }\n    }\n\n    ServerSocket(12321).use { listener ->\n        while (true) {\n            val conn = listener.accept()\n            Thread { handleClient(conn) }.start()\n        }\n    }\n}\n\n\n","human_summarization":"implement an echo server that runs on TCP port 12321. It accepts and echoes complete lines from multiple client connections simultaneously. The server only supports connections from localhost and logs connection information to standard output. It continues to respond to other clients even if one client sends a partial line or stops reading responses. A quick test can be performed using netcat.","id":4606}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1\n\nfun isNumeric(input: String): Boolean =\n    try {\n        input.toDouble()\n        true\n    } catch(e: NumberFormatException) {\n        false\n    }\n\nfun main(args: Array<String>) {\n    val inputs = arrayOf(\"152\", \"-3.1415926\", \"Foo123\", \"-0\", \"456bar\", \"1.0E10\")\n    for (input in inputs) println(\"$input is ${if (isNumeric(input)) \"numeric\" else \"not numeric\"}\")\n}\n\n\n","human_summarization":"\"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax.\"","id":4607}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\nimport java.net.URL\nimport javax.net.ssl.HttpsURLConnection\nimport java.io.InputStreamReader\nimport java.util.Scanner\n\nfun main(args: Array<String>) {\n    val url = URL(\"https:\/\/en.wikipedia.org\/wiki\/Main_Page\")\n    val connection = url.openConnection() as HttpsURLConnection\n    val isr = InputStreamReader(connection.inputStream)\n    val sc = Scanner(isr)\n    while (sc.hasNextLine()) println(sc.nextLine())\n    sc.close()\n}\n\n\nimport java.net.URL\n\nfun main(args: Array<String>){\n    println(URL(\"https:\/\/sourceforge.net\").readText())\n}\n\n","human_summarization":"sends a GET request to the URL \"https:\/\/www.w3.org\/\" without authentication, checks the host certificate for validity, and prints the obtained resource to the console. It uses features available in Kotlin 1.2 and above.","id":4608}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.2\n\nimport java.awt.*\nimport java.awt.geom.Line2D\nimport javax.swing.*\n \nclass SutherlandHodgman : JPanel() {\n    private val subject = listOf(\n        doubleArrayOf( 50.0, 150.0), doubleArrayOf(200.0,  50.0), doubleArrayOf(350.0, 150.0), \n        doubleArrayOf(350.0, 300.0), doubleArrayOf(250.0, 300.0), doubleArrayOf(200.0, 250.0), \n        doubleArrayOf(150.0, 350.0), doubleArrayOf(100.0, 250.0), doubleArrayOf(100.0, 200.0)\n    )\n\n    private val clipper = listOf(\n        doubleArrayOf(100.0, 100.0), doubleArrayOf(300.0, 100.0), \n        doubleArrayOf(300.0, 300.0), doubleArrayOf(100.0, 300.0)\n    )\n\n    private var result = subject.toMutableList()\n\n    init {\n        preferredSize = Dimension(600, 500)\n        clipPolygon()\n    } \n\n    private fun clipPolygon() {\n        val len = clipper.size\n        for (i in 0 until len) { \n            val len2 = result.size\n            val input = result\n            result = mutableListOf<DoubleArray>() \n            val a = clipper[(i + len - 1) % len]\n            val b = clipper[i]\n \n            for (j in 0 until len2) {\n                val p = input[(j + len2 - 1) % len2]\n                val q = input[j]\n \n                if (isInside(a, b, q)) {\n                    if (!isInside(a, b, p)) result.add(intersection(a, b, p, q))\n                    result.add(q)\n                } \n                else if (isInside(a, b, p)) result.add(intersection(a, b, p, q))\n            }\n        }\n    } \n\n    private fun isInside(a: DoubleArray, b: DoubleArray, c: DoubleArray) =\n        (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0])\n\n    private fun intersection(a: DoubleArray, b: DoubleArray, \n                             p: DoubleArray, q: DoubleArray): DoubleArray {\n        val a1 = b[1] - a[1]\n        val b1 = a[0] - b[0]\n        val c1 = a1 * a[0] + b1 * a[1]\n \n        val a2 = q[1] - p[1]\n        val b2 = p[0] - q[0]\n        val c2 = a2 * p[0] + b2 * p[1]\n \n        val d = a1 * b2 - a2 * b1\n        val x = (b2 * c1 - b1 * c2) \/ d\n        val y = (a1 * c2 - a2 * c1) \/ d\n \n        return doubleArrayOf(x, y)\n    }\n\n    override fun paintComponent(g: Graphics) {\n        super.paintComponent(g)\n        val g2 = g as Graphics2D         \n        g2.translate(80, 60)\n        g2.stroke = BasicStroke(3.0f)\n        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n                            RenderingHints.VALUE_ANTIALIAS_ON) \n        drawPolygon(g2, subject, Color.blue)\n        drawPolygon(g2, clipper, Color.red)\n        drawPolygon(g2, result, Color.green)\n    }\n\n    private fun drawPolygon(g2: Graphics2D, points: List<DoubleArray>, color: Color) {\n        g2.color = color\n        val len = points.size\n        val line = Line2D.Double()\n        for (i in 0 until len) {\n            val p1 = points[i]\n            val p2 = points[(i + 1) % len]\n            line.setLine(p1[0], p1[1], p2[0], p2[1])\n            g2.draw(line)\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    SwingUtilities.invokeLater {\n        val f = JFrame()\n        with(f) {\n            defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n            add(SutherlandHodgman(), BorderLayout.CENTER)\n            title = \"Sutherland-Hodgman\"\n            pack()\n            setLocationRelativeTo(null)\n            isVisible = true\n        }\n    }\n}\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":4609}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\n\/* all ranking functions assume the array of Pairs is non-empty and already sorted by decreasing order of scores\n   and then, if the scores are equal, by reverse alphabetic order of names\n*\/\n\nfun standardRanking(scores: Array<Pair<Int, String>>): IntArray {   \n    val rankings = IntArray(scores.size)\n    rankings[0] = 1\n    for (i in 1 until scores.size) rankings[i] = if (scores[i].first == scores[i - 1].first) rankings[i - 1] else i + 1\n    return rankings\n}\n\nfun modifiedRanking(scores: Array<Pair<Int, String>>): IntArray {   \n    val rankings = IntArray(scores.size)\n    rankings[0] = 1 \n    for (i in 1 until scores.size) {\n        rankings[i] = i + 1 \n        val currScore = scores[i].first         \n        for (j in i - 1 downTo 0) {\n            if (currScore != scores[j].first) break\n            rankings[j] = i + 1\n        }       \n    }\n    return rankings\n}\n\nfun denseRanking(scores: Array<Pair<Int, String>>): IntArray {   \n    val rankings = IntArray(scores.size)\n    rankings[0] = 1\n    var prevRanking = 1\n    for (i in 1 until scores.size) rankings[i] = if (scores[i].first == scores[i - 1].first) prevRanking else ++prevRanking\n    return rankings\n}\n\nfun ordinalRanking(scores: Array<Pair<Int, String>>) = IntArray(scores.size) { it + 1 }  \n\nfun fractionalRanking(scores: Array<Pair<Int, String>>): DoubleArray {\n    val rankings = DoubleArray(scores.size)\n    rankings[0] = 1.0 \n    for (i in 1 until scores.size) {\n        var k = i \n        val currScore = scores[i].first         \n        for (j in i - 1 downTo 0) {\n            if (currScore != scores[j].first) break\n            k = j\n        }\n        val avg = (k..i).average() + 1.0\n        for (m in k..i) rankings[m] = avg       \n    }\n    return rankings\n}    \n\nfun printRankings(title: String, rankings: IntArray, scores: Array<Pair<Int, String>>) {\n    println(title + \":\")\n    for (i in 0 until rankings.size) { \n        print (\"${rankings[i]}  \")  \n        println(scores[i].toString().removeSurrounding(\"(\", \")\").replace(\",\", \"\"))\n    }\n    println()\n}\n\nfun printFractionalRankings(title: String, rankings: DoubleArray, scores: Array<Pair<Int, String>>) {\n    println(title + \":\")\n    for (i in 0 until rankings.size) { \n        print (\"${\"%3.2f\".format(rankings[i])}  \")  \n        println(scores[i].toString().removeSurrounding(\"(\", \")\").replace(\",\", \"\"))\n    }\n    println()\n}\n\nfun main(args: Array<String>) {\n    val scores = arrayOf(44 to \"Solomon\",  42 to \"Jason\", 42 to \"Errol\",  41 to \"Garry\",\n                         41 to \"Bernard\",  41 to \"Barry\", 39 to \"Stephen\")\n    printRankings(\"Standard ranking\", standardRanking(scores), scores)\n    printRankings(\"Modified ranking\", modifiedRanking(scores), scores)\n    printRankings(\"Dense ranking\", denseRanking(scores), scores)\n    printRankings(\"Ordinal ranking\", ordinalRanking(scores), scores)\n    printFractionalRankings(\"Fractional ranking\", fractionalRanking(scores), scores)\n}\n\n\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":4610}
    {"lang_cluster":"Kotlin","source_code":"\nimport kotlin.math.*\n\nfun main() {\n    fun Double.toDegrees() = this * 180 \/ PI\n    val angle = PI \/ 4\n    \n    println(\"angle = $angle rad = ${angle.toDegrees()}\u00b0\")\n    val sine = sin(angle)\n    println(\"sin(angle) = $sine\")\n    val cosine = cos(angle)\n    println(\"cos(angle) = $cosine\")\n    val tangent = tan(angle)\n    println(\"tan(angle) = $tangent\")\n    println()\n\n    val asin = asin(sine)\n    println(\"asin(sin(angle)) = $asin rad = ${asin.toDegrees()}\u00b0\")\n    val acos = acos(cosine)\n    println(\"acos(cos(angle)) = $acos rad = ${acos.toDegrees()}\u00b0\")\n    val atan = atan(tangent)\n    println(\"atan(tan(angle)) = $atan rad = ${atan.toDegrees()}\u00b0\")\n}\n\n\n","human_summarization":"demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.","id":4611}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.2\n\ndata class Item(val name: String, val weight: Int, val value: Int, val count: Int)\n\nval items = listOf(\n    Item(\"map\", 9, 150, 1),\n    Item(\"compass\", 13, 35, 1),\n    Item(\"water\", 153, 200, 2),\n    Item(\"sandwich\", 50, 60, 2),\n    Item(\"glucose\", 15, 60, 2),\n    Item(\"tin\", 68, 45, 3),\n    Item(\"banana\", 27, 60, 3),\n    Item(\"apple\", 39, 40, 3),\n    Item(\"cheese\", 23, 30, 1),\n    Item(\"beer\", 52, 10, 3),\n    Item(\"suntan cream\", 11, 70, 1),\n    Item(\"camera\", 32, 30, 1),\n    Item(\"T-shirt\", 24, 15, 2),\n    Item(\"trousers\", 48, 10, 2),\n    Item(\"umbrella\", 73, 40, 1),\n    Item(\"waterproof trousers\", 42, 70, 1),\n    Item(\"waterproof overclothes\", 43, 75, 1),\n    Item(\"note-case\", 22, 80, 1),\n    Item(\"sunglasses\", 7, 20, 1),\n    Item(\"towel\", 18, 12, 2),\n    Item(\"socks\", 4, 50, 1),\n    Item(\"book\", 30, 10, 2)\n)\n\nval n = items.size\n\nconst val MAX_WEIGHT = 400\n\nfun knapsack(w: Int): IntArray {\n    val m  = Array(n + 1) { IntArray(w + 1) }\n    for (i in 1..n) {\n        for (j in 0..w) {\n            m[i][j] = m[i - 1][j]\n            for (k in 1..items[i - 1].count) {\n                if (k * items[i - 1].weight > j) break\n                val v = m[i - 1][j - k * items[i - 1].weight] + k * items[i - 1].value\n                if (v > m[i][j]) m[i][j] = v\n            }\n        }\n    }\n    val s = IntArray(n)\n    var j = w\n    for (i in n downTo 1) {\n        val v = m[i][j]\n        var k = 0\n        while (v != m[i - 1][j] + k * items[i - 1].value) {\n            s[i - 1]++\n            j -= items[i - 1].weight\n            k++\n        }\n    }\n    return s\n}\n\nfun main(args: Array<String>) {\n   val s = knapsack(MAX_WEIGHT)\n   println(\"Item Chosen             Weight Value  Number\")\n   println(\"---------------------   ------ -----  ------\")\n   var itemCount = 0\n   var sumWeight = 0\n   var sumValue  = 0\n   var sumNumber = 0\n   for (i in 0 until n) {\n       if (s[i] == 0) continue\n       itemCount++\n       val name   = items[i].name\n       val number = s[i]\n       val weight = items[i].weight * number\n       val value  = items[i].value  * number\n       sumNumber += number\n       sumWeight += weight\n       sumValue  += value\n       println(\"${name.padEnd(22)}    ${\"%3d\".format(weight)}   ${\"%4d\".format(value)}    ${\"%2d\".format(number)}\")\n   }\n   println(\"---------------------   ------ -----  ------\")\n   println(\"Items chosen $itemCount           ${\"%3d\".format(sumWeight)}   ${\"%4d\".format(sumValue)}    ${\"%2d\".format(sumNumber)}\")\n}\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. It selects items based on their importance value and weight, ensuring the total weight does not exceed the limit and the total value is maximized. The code considers the quantity available of each item and only allows whole units to be selected.","id":4612}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.3\n\nimport sun.misc.Signal\nimport sun.misc.SignalHandler\n\nfun main(args: Array<String>) {\n    val startTime = System.currentTimeMillis()\n\n    Signal.handle(Signal(\"INT\"), object : SignalHandler {\n        override fun handle(sig: Signal) {\n            val elapsedTime = (System.currentTimeMillis() - startTime) \/ 1000.0\n            println(\"\\nThe program has run for $elapsedTime seconds\")\n            System.exit(0)\n        }\n    })\n\n    var i = 0\n    while(true) {  \n        println(i++)      \n        Thread.sleep(500)        \n    }\n}\n\n\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n^C\nThe program has run for 5.087 seconds\n\n","human_summarization":"The code outputs an integer every half second. It handles SIGINT or SIGQUIT signals, upon which it stops outputting integers, displays the runtime in seconds, and then terminates.","id":4613}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.5-2\n\n\/** overload ++ operator to increment a numeric string *\/\noperator fun String.inc(): String =\n    try {\n        val num = this.toInt()\n        (num + 1).toString()\n    }\n    catch(e: NumberFormatException) {\n        this  \/\/ return string unaltered\n    }\n\nfun main(args: Array<String>) {\n    var ns = \"12345\"\n    println(++ns)\n    ns = \"ghijk\"  \/\/ not numeric, so won't be changed by increment operator\n    println(++ns)\n}\n\n\n","human_summarization":"\"Increments a given numerical string.\"","id":4614}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.51\n\nfun findCommonDirPath(paths: List<String>, separator: Char): String {\n    if (paths.isEmpty()) return \"\"\n    if (paths.size == 1) return paths[0]\n    val splits = paths[0].split(separator)\n    val n = splits.size\n    val paths2 = paths.drop(1)\n    var k = 0\n    var common = \"\"\n    while (true) {\n        val prevCommon = common\n        common += if (k == 0) splits[0] else separator + splits[k]\n        if (!paths2.all { it.startsWith(common + separator) || it == common } ) return prevCommon\n        if (++k == n) return common\n    }\n}\n\nfun main(args: Array<String>) {\n    val paths = listOf(\n        \"\/home\/user1\/tmp\/coverage\/test\",\n        \"\/home\/user1\/tmp\/covert\/operator\",\n        \"\/home\/user1\/tmp\/coven\/members\"\n    )\n    val pathsToPrint = paths.map { \"   '$it'\" }.joinToString(\"\\n\")\n    println(\"The common directory path of:\\n\\n$pathsToPrint\\n\")\n    println(\"is '${findCommonDirPath(paths, '\/')}'\")\n}\n\n\n","human_summarization":"The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '\/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.","id":4615}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun <T> sattolo(items: Array<T>) {\n    for (i in items.size - 1 downTo 1) {\n        val j = (Math.random() * i).toInt()\n        val t = items[i]\n        items[i] = items[j]\n        items[j] = t\n    }\n}\n\nfun main(args: Array<String>) {\n    val items = arrayOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22)\n    println(items.joinToString())\n    sattolo(items)\n    println(items.joinToString())\n}\n\n\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm modifies the input array in-place or returns a new shuffled array. It can also be adjusted to iterate from left to right. The difference from the Knuth shuffle is in the range of j. The functionality is tested with various input arrays.","id":4616}
    {"lang_cluster":"Kotlin","source_code":"Library: libcurl\nWorks with: Ubuntu 14.04\n\n\/\/ libcurl.def\nheaders = \/usr\/include\/curl\/curl.h\nlinkerOpts.linux = -L\/usr\/lib\/x86_64-linux-gnu -lcurl\n\n\n\/\/ Kotlin Native v0.6\n\nimport kotlinx.cinterop.*\nimport platform.posix.*\nimport libcurl.*\n\nfun writeData(ptr: COpaquePointer?, size: size_t, nmeb: size_t, stream: COpaquePointer?)\n    = fwrite(ptr, size, nmeb, stream?.reinterpret<FILE>())\n\nfun readData(ptr: COpaquePointer?, size: size_t, nmeb: size_t, stream: COpaquePointer?)\n    = fread(ptr, size, nmeb, stream?.reinterpret<FILE>())\n\nfun callSOAP(url: String, inFile: String, outFile: String) {\n    val rfp = fopen(inFile, \"r\")\n    if (rfp == null) {\n        perror(\"Read File Open: \")\n        exit(1)\n    }\n    val wfp = fopen(outFile, \"w+\")\n    if (wfp == null) {\n        perror(\"Write File Open: \")\n        fclose(rfp)\n        exit(1)\n    }\n\n    var header: CPointer<curl_slist>? = null\n    header = curl_slist_append (header, \"Content-Type:text\/xml\")\n    header = curl_slist_append (header, \"SOAPAction: rsc\")\n    header = curl_slist_append (header, \"Transfer-Encoding: chunked\")\n    header = curl_slist_append (header, \"Expect:\")\n\n    val curl = curl_easy_init()\n    if (curl != null) {\n        curl_easy_setopt(curl, CURLOPT_URL, url)\n        curl_easy_setopt(curl, CURLOPT_POST, 1L)\n        curl_easy_setopt(curl, CURLOPT_READFUNCTION, staticCFunction(::readData))\n        curl_easy_setopt(curl, CURLOPT_READDATA, rfp)\n        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, staticCFunction(::writeData))\n        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp)\n        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header)\n        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, -1L)\n        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L)\n        curl_easy_perform(curl)\n        curl_easy_cleanup(curl)\n    }\n\n    curl_slist_free_all(header) \n    fclose(rfp)\n    fclose(wfp)\n}\n\nfun main(args: Array<String>) {\n    if (args.size != 3) {\n        println(\"You need to pass exactly 3 command line arguments, namely\u00a0:-\")\n        println(\"    <URL of WSDL> <Input file path> <Output File Path>\")\n        return\n    }\n    callSOAP(args[0], args[1], args[2])\n}\n\n\n","human_summarization":"create a SOAP client that accesses and calls functions soapFunc() and anotherSoapFunc() from http:\/\/example.com\/soap\/wsdl. It involves building libcurl.klib using a .def file and cinterop tool, compiling a Kotlin program linked against libcurl.klib, and executing the resulting .kexe file with command line arguments similar to the C entry.","id":4617}
    {"lang_cluster":"Kotlin","source_code":"\nWorks with: Kotlin version 1.0+\nfun median(l: List<Double>) = l.sorted().let { (it[it.size \/ 2] + it[(it.size - 1) \/ 2]) \/ 2 }\n\nfun main(args: Array<String>) {\n    median(listOf(5.0, 3.0, 4.0)).let { println(it) }  \/\/ 4\n    median(listOf(5.0, 4.0, 2.0, 3.0)).let { println(it) }  \/\/ 3.5\n    median(listOf(3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2)).let { println(it) }  \/\/ 2.1\n}\n\n\n","human_summarization":"\"Calculates the median value of a vector of floating-point numbers, handling even number of elements by returning the average of the two middle values. Implements the selection algorithm for optimal time complexity. Also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation.\"","id":4618}
    {"lang_cluster":"Kotlin","source_code":"\nfun fizzBuzz() {\n    for (number in 1..100) {\n        println(\n            when {\n                number\u00a0% 15 == 0 -> \"FizzBuzz\"\n                number\u00a0% 3 == 0 -> \"Fizz\"\n                number\u00a0% 5 == 0 -> \"Buzz\"\n                else -> number\n            }\n        )\n    }\n}\nfun fizzBuzz1() {\n    fun fizzBuzz(x: Int) = if (x\u00a0% 15 == 0) \"FizzBuzz\" else x.toString()\n    fun fizz(x: Any) = if (x is Int && x\u00a0% 3 == 0) \"Buzz\" else x\n    fun buzz(x: Any) = if (x is Int && x.toInt()\u00a0% 5 == 0) \"Fizz\" else x\n\n    (1..100).map { fizzBuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) }\n}\nfun fizzBuzz2() {\n    fun fizz(x: Pair<Int, StringBuilder>) = if(x.first\u00a0% 3 == 0) x.apply { second.append(\"Fizz\") } else x\n    fun buzz(x: Pair<Int, StringBuilder>) = if(x.first\u00a0% 5 == 0) x.apply { second.append(\"Buzz\") } else x\n    fun none(x: Pair<Int, StringBuilder>) = if(x.second.isBlank()) x.second.apply { append(x.first) } else x.second\n\n    (1..100).map { Pair(it, StringBuilder()) }\n            .map { fizz(it) }\n            .map { buzz(it) }\n            .map { none(it) }\n            .forEach { println(it) }\n}\nfun fizzBuzz() {\n    (1..100).forEach { println(mapOf(0 to it, it\u00a0% 3 to \"Fizz\", it\u00a0% 5 to \"Buzz\", it\u00a0% 15 to \"FizzBuzz\")[0]) }\n}\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.","id":4619}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.2\n\nimport java.awt.Graphics\nimport java.awt.image.BufferedImage\nimport javax.swing.JFrame\n\nclass Mandelbrot: JFrame(\"Mandelbrot Set\") {\n    companion object {\n        private const val MAX_ITER = 570\n        private const val ZOOM = 150.0\n    }\n\n    private val img: BufferedImage\n\n    init {\n        setBounds(100, 100, 800, 600)\n        isResizable = false\n        defaultCloseOperation = EXIT_ON_CLOSE\n        img = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)\n        for (y in 0 until height) {\n            for (x in 0 until width) {\n                var zx = 0.0\n                var zy = 0.0\n                val cX = (x - 400) \/ ZOOM\n                val cY = (y - 300) \/ ZOOM\n                var iter = MAX_ITER\n                while (zx * zx + zy * zy < 4.0 && iter > 0) {\n                    val tmp = zx * zx - zy * zy + cX\n                    zy = 2.0 * zx * zy + cY\n                    zx = tmp\n                    iter--\n                }\n                img.setRGB(x, y, iter or (iter shl 7))\n            }\n        }\n    }\n\n    override fun paint(g: Graphics) {\n        g.drawImage(img, 0, 0, this)\n    }\n}\n\nfun main(args: Array<String>) {\n    Mandelbrot().isVisible = true\n}\n\n","human_summarization":"generate and draw the Mandelbrot set using various available algorithms and functions.","id":4620}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nfun main(args: Array<String>) {\n    val a = intArrayOf(1, 5, 8, 11, 15)\n    println(\"Array contains\u00a0: ${a.contentToString()}\")\n    val sum = a.sum()\n    println(\"Sum is $sum\")\n    val product = a.fold(1) { acc, i -> acc * i }\n    println(\"Product is $product\")\n}\n\n\n","human_summarization":"Calculate the sum and product of all integers in an array.","id":4621}
    {"lang_cluster":"Kotlin","source_code":"\nfun isLeapYear(year: Int) = year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)\n\n","human_summarization":"\"Determines if a specified year is a leap year in the Gregorian calendar.\"","id":4622}
    {"lang_cluster":"Kotlin","source_code":"\n\n\/\/ version 1.2.31\n\nimport java.io.File\nimport java.security.SecureRandom\n\nconst val CHARS_PER_LINE = 48\nconst val CHUNK_SIZE = 6\nconst val COLS = 8\nconst val DEMO = true  \/\/ would normally be set to false\n\nenum class FileType { OTP, ENC, DEC }\n\nfun Char.isAlpha() = this in 'A'..'Z'\n\nfun String.toAlpha() = this.filter { it.isAlpha() }\n\nfun String.isOtpRelated() = endsWith(\".1tp\") || endsWith(\".1tp_cpy\") ||\n                            endsWith(\".1tp_enc\") || endsWith(\".1tp_dec\")\n\nfun makePad(nLines: Int): String {\n    val nChars = nLines * CHARS_PER_LINE\n    val sr = SecureRandom()\n    val sb = StringBuilder(nChars)\n    \/* generate random upper case letters *\/\n    for (i in 0 until nChars) sb.append((sr.nextInt(26) + 65).toChar())\n    return sb.toString().inChunks(nLines, FileType.OTP)\n}\n\nfun vigenere(text: String, key: String, encrypt: Boolean = true): String {\n    val sb = StringBuilder(text.length)\n    for ((i, c) in text.withIndex()) {\n        val ci = if (encrypt)\n            (c.toInt() + key[i].toInt() - 130) % 26\n        else\n            (c.toInt() - key[i].toInt() +  26) % 26\n        sb.append((ci + 65).toChar())\n    }\n    val temp = sb.length % CHARS_PER_LINE\n    if (temp > 0) {  \/\/ pad with random characters so each line is a full one\n        val sr = SecureRandom()\n        for (i in temp until CHARS_PER_LINE) sb.append((sr.nextInt(26) + 65).toChar())\n    }\n    val ft = if (encrypt) FileType.ENC else FileType.DEC\n    return sb.toString().inChunks(sb.length \/ CHARS_PER_LINE, ft)\n}\n\nfun String.inChunks(nLines: Int, ft: FileType): String {\n    val chunks = this.chunked(CHUNK_SIZE)\n    val sb = StringBuilder(this.length + nLines * (COLS + 1))\n    for (i in 0 until nLines) {\n        val j = i * COLS\n        sb.append(\" ${chunks.subList(j, j + COLS).joinToString(\" \")}\\n\")\n    }\n    val s = \" file\\n\" + sb.toString()\n    return when (ft) {\n        FileType.OTP -> \"# OTP\" + s\n        FileType.ENC -> \"# Encrypted\" + s\n        FileType.DEC -> \"# Decrypted\" + s\n    }\n}\n\nfun menu(): Int {\n    println(\"\"\"\n        |\n        |1. Create one time pad file.\n        |\n        |2. Delete one time pad file.\n        |\n        |3. List one time pad files.\n        |\n        |4. Encrypt plain text.\n        |\n        |5. Decrypt cipher text.\n        |\n        |6. Quit program.\n        |\n        \"\"\".trimMargin())\n    var choice: Int?\n    do {\n        print(\"Your choice (1 to 6)\u00a0: \")\n        choice = readLine()!!.toIntOrNull()\n    }\n    while (choice == null || choice !in 1..6)\n    return choice\n}\n\nfun main(args: Array<String>) {\n    mainLoop@ while (true) {\n        val choice = menu()\n        println()\n        when (choice) {\n            1 -> {  \/\/ Create OTP\n                println(\"Note that encrypted lines always contain 48 characters.\\n\")\n                print(\"OTP file name to create (without extension)\u00a0: \")\n                val fileName = readLine()!! + \".1tp\"  \n                var nLines: Int?\n\n                do {\n                    print(\"Number of lines in OTP (max 1000)\u00a0: \")\n                    nLines = readLine()!!.toIntOrNull()\n                }\n                while (nLines == null || nLines !in 1..1000)\n\n                val key = makePad(nLines)\n                File(fileName).writeText(key)\n                println(\"\\n'$fileName' has been created in the current directory.\")\n                if (DEMO) {\n                    \/\/ a copy of the OTP file would normally be on a different machine\n                    val fileName2 = fileName + \"_cpy\"  \/\/ copy for decryption\n                    File(fileName2).writeText(key)\n                    println(\"'$fileName2' has been created in the current directory.\")\n                    println(\"\\nThe contents of these files are\u00a0:\\n\")\n                    println(key)\n                }\n            }\n\n            2 -> {  \/\/ Delete OTP\n                println(\"Note that this will also delete ALL associated files.\\n\")\n                print(\"OTP file name to delete (without extension)\u00a0: \")\n                val toDelete1 = readLine()!! + \".1tp\"\n                val toDelete2 = toDelete1 + \"_cpy\"\n                val toDelete3 = toDelete1 + \"_enc\"\n                val toDelete4 = toDelete1 + \"_dec\"\n                val allToDelete = listOf(toDelete1, toDelete2, toDelete3, toDelete4)\n                var deleted = 0\n                println()\n                for (name in allToDelete) {\n                    val f = File(name)\n                    if (f.exists()) {\n                        f.delete()\n                        deleted++\n                        println(\"'$name' has been deleted from the current directory.\")\n                    }\n                }\n                if (deleted == 0) println(\"There are no files to delete.\")\n            }\n\n            3 -> {  \/\/ List OTPs\n                println(\"The OTP (and related) files in the current directory are:\\n\")\n                val otpFiles = File(\".\").listFiles().filter {\n                    it.isFile() && it.name.isOtpRelated()\n                }.map { it.name }.toMutableList()\n                otpFiles.sort()\n                println(otpFiles.joinToString(\"\\n\"))\n            }\n\n            4 -> {  \/\/ Encrypt\n                print(\"OTP file name to use (without extension)\u00a0: \")\n                val keyFile = readLine()!! + \".1tp\"\n                val kf = File(keyFile)\n                if (kf.exists()) {\n                    val lines = File(keyFile).readLines().toMutableList()\n                    var first = lines.size\n                    for (i in 0 until lines.size) {\n                        if (lines[i].startsWith(\" \")) {\n                            first = i\n                            break\n                        }\n                    }\n                    if (first == lines.size) {\n                        println(\"\\nThat file has no unused lines.\")\n                        continue@mainLoop\n                    }\n                    val lines2 = lines.drop(first)  \/\/ get rid of comments and used lines\n\n                    println(\"Text to encrypt\u00a0:-\\n\")\n                    val text = readLine()!!.toUpperCase().toAlpha()\n                    val len = text.length\n                    var nLines = len \/ CHARS_PER_LINE\n                    if (len % CHARS_PER_LINE > 0) nLines++\n\n                    if (lines2.size >= nLines) {\n                        val key = lines2.take(nLines).joinToString(\"\").toAlpha()\n                        val encrypted = vigenere(text, key)\n                        val encFile = keyFile + \"_enc\"\n                        File(encFile).writeText(encrypted)\n                        println(\"\\n'$encFile' has been created in the current directory.\")\n                        for (i in first until first + nLines) {\n                            lines[i] = \"-\" + lines[i].drop(1)\n                        }\n                        File(keyFile).writeText(lines.joinToString(\"\\n\"))\n                        if (DEMO) {\n                            println(\"\\nThe contents of the encrypted file are\u00a0:\\n\")\n                            println(encrypted)\n                        }\n                    }\n                    else println(\"Not enough lines left in that file to do encryption\")\n                }\n                else println(\"\\nThat file does not exist.\")\n            }\n\n            5 -> {  \/\/ Decrypt\n                print(\"OTP file name to use (without extension)\u00a0: \")\n                val keyFile = readLine()!! + \".1tp_cpy\"\n                val kf = File(keyFile)\n                if (kf.exists()) {\n                    val keyLines = File(keyFile).readLines().toMutableList()\n                    var first = keyLines.size\n                    for (i in 0 until keyLines.size) {\n                        if (keyLines[i].startsWith(\" \")) {\n                            first = i\n                            break\n                        }\n                    }\n                    if (first == keyLines.size) {\n                        println(\"\\nThat file has no unused lines.\")\n                        continue@mainLoop\n                    }\n                    val keyLines2 = keyLines.drop(first)  \/\/ get rid of comments and used lines\n\n                    val encFile = keyFile.dropLast(3) + \"enc\"\n                    val ef = File(encFile)\n                    if (ef.exists()) {\n                        val encLines = File(encFile).readLines().drop(1)  \/\/ exclude comment line\n                        val nLines = encLines.size\n                        if (keyLines2.size >= nLines) {\n                            val encrypted = encLines.joinToString(\"\").toAlpha()\n                            val key = keyLines2.take(nLines).joinToString(\"\").toAlpha()\n                            val decrypted = vigenere(encrypted, key, false)\n                            val decFile = keyFile.dropLast(3) + \"dec\"\n                            File(decFile).writeText(decrypted)\n                            println(\"\\n'$decFile' has been created in the current directory.\")\n                            for (i in first until first + nLines) {\n                                keyLines[i] = \"-\" + keyLines[i].drop(1)\n                            }\n                            File(keyFile).writeText(keyLines.joinToString(\"\\n\"))\n                            if (DEMO) {\n                                println(\"\\nThe contents of the decrypted file are\u00a0:\\n\")\n                                println(decrypted)\n                            }\n                        }\n                        else println(\"Not enough lines left in that file to do decryption\")\n                    }\n                    else println(\"\\n'$encFile' is missing.\")\n                }\n                else println(\"\\nThat file does not exist.\")\n            }\n\n            else -> return  \/\/ Quit\n        }\n    }\n}\n\n\n","human_summarization":"The code implements a One-time pad for encrypting and decrypting messages using only letters. It includes functionalities to generate data for a One-time pad with user-specified filename and length, ensuring the use of true random numbers. The code also reuses aspects of the Vigen\u00e8re cipher for the encryption\/decryption process, reading the key from the file containing the One-time pad. Additionally, it provides optional management of One-time pads including listing, marking as used, deleting, and tracking which pad is used for which partner. The code also supports the management of pad-files with a specific file-extension, and handles metadata and used status. It uses JDK's SecureRandom class for generating cryptographically strong random numbers.","id":4623}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.3\n\nobject MD5 {\n\n    private val INIT_A = 0x67452301\n    private val INIT_B = 0xEFCDAB89L.toInt()\n    private val INIT_C = 0x98BADCFEL.toInt()\n    private val INIT_D = 0x10325476\n \n    private val SHIFT_AMTS = intArrayOf(\n        7, 12, 17, 22,\n        5,  9, 14, 20,\n        4, 11, 16, 23,\n        6, 10, 15, 21\n    )\n\n    private val TABLE_T = IntArray(64) {\n        ((1L shl 32) * Math.abs(Math.sin(it + 1.0))).toLong().toInt()\n    }\n\n    fun compute(message: ByteArray): ByteArray {\n        val messageLenBytes = message.size\n        val numBlocks = ((messageLenBytes + 8) ushr 6) + 1\n        val totalLen = numBlocks shl 6\n        val paddingBytes = ByteArray(totalLen - messageLenBytes)\n        paddingBytes[0] = 0x80.toByte()\n        var messageLenBits = (messageLenBytes shl 3).toLong()\n\n        for (i in 0..7) {\n            paddingBytes[paddingBytes.size - 8 + i] = messageLenBits.toByte()\n            messageLenBits = messageLenBits ushr 8\n        }\n\n        var a = INIT_A\n        var b = INIT_B\n        var c = INIT_C\n        var d = INIT_D\n        val buffer = IntArray(16)\n\n        for (i in 0 until numBlocks) {\n            var index = i shl 6\n\n            for (j in 0..63) {\n                val temp = if (index < messageLenBytes) message[index] else \n                               paddingBytes[index - messageLenBytes]\n                buffer[j ushr 2] = (temp.toInt() shl 24) or (buffer[j ushr 2] ushr 8) \n                index++\n            }\n\n            val originalA = a\n            val originalB = b\n            val originalC = c\n            val originalD = d\n\n            for (j in 0..63) {\n                val div16 = j ushr 4\n                var f = 0\n                var bufferIndex = j\n                when (div16) {\n                    0 -> {\n                        f = (b and c) or (b.inv() and d)\n                    }\n\n                    1 -> {\n                        f = (b and d) or (c and d.inv()) \n                        bufferIndex = (bufferIndex * 5 + 1) and 0x0F\n                    }\n \n                    2 -> {\n                        f = b xor c xor d;\n                        bufferIndex = (bufferIndex * 3 + 5) and 0x0F\n                    }\n\n                    3 -> {\n                        f = c xor (b or d.inv());\n                        bufferIndex = (bufferIndex * 7) and 0x0F\n                    }\n                } \n\n                val temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + \n                           TABLE_T[j], SHIFT_AMTS[(div16 shl 2) or (j and 3)])\n                a = d\n                d = c\n                c = b\n                b = temp\n            }\n\n            a += originalA\n            b += originalB\n            c += originalC\n            d += originalD\n        }   \n\n        val md5 = ByteArray(16)\n        var count = 0\n\n        for (i in 0..3) {\n            var n = if (i == 0) a else (if (i == 1) b else (if (i == 2) c else d))\n\n            for (j in 0..3) {      \n                md5[count++] = n.toByte()\n                n = n ushr 8\n            }\n        }\n        return md5\n    }\n}\n\nfun ByteArray.toHexString(): String {\n    val sb = StringBuilder()\n    for (b in this) sb.append(String.format(\"%02x\", b.toInt() and 0xFF))\n    return sb.toString()\n}\n\nfun main(args: Array<String>) {\n    val testStrings = arrayOf(\n        \"\",\n        \"a\",\n        \"abc\",\n        \"message digest\",\n        \"abcdefghijklmnopqrstuvwxyz\",\n        \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",\n        \"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"\n    )\n\n    println(\"${\"hash code\".padStart(34)} <== string\") \n    for (s in testStrings) {\n        println(\"0x${MD5.compute(s.toByteArray()).toHexString()} <== \\\"$s\\\"\")\n    }\n}\n\n\n","human_summarization":"The code is an implementation of the MD5 Message Digest Algorithm, developed directly from the algorithm specification without using built-in or external hashing libraries. It produces a correct message digest for an input string but does not mimic all calling modes. The code also includes handling of bit manipulation, unsigned integers, and little-endian data, with attention to details like boundary conditions and padding. The implementation is validated against the verification strings and hashes from RFC 1321.","id":4624}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nfun main(args: Array<String>) {\n    println(\"Police  Sanitation  Fire\")\n    println(\"------  ----------  ----\")\n    var count = 0\n    for (i in 2..6 step 2) {\n        for (j in 1..7) {\n            if (j == i) continue\n            for (k in 1..7) {\n                if (k == i || k == j) continue\n                if (i + j + k != 12) continue\n                println(\"  $i         $j         $k\")\n                count++\n            }\n        }\n    }\n    println(\"\\n$count valid combinations\")\n}\n\n\n","human_summarization":"all possible combinations of unique numbers between 1 and 7 (inclusive) for three different departments (police, sanitation, fire) that add up to 12, with the police department number being an even number.","id":4625}
    {"lang_cluster":"Kotlin","source_code":"\nval s = \"Hello\"\nval alias = s      \/\/ alias === s\nval copy = \"\" + s  \/\/ copy\u00a0!== s\n\n","human_summarization":"\"Implements functionality to copy a string's content and create an additional reference to an existing string where applicable.\"","id":4626}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun f(n: Int): Int = \n    when {\n        n == 0 -> 1\n        else   -> n - m(f(n - 1))\n    }\n\nfun m(n: Int): Int =\n    when {\n        n == 0 -> 0\n        else   -> n - f(m(n - 1))\n    }\n\nfun main(args: Array<String>) {\n    val n = 24\n    print(\"n\u00a0:\")\n    for (i in 0..n) print(\"%3d\".format(i))\n    println()\n    println(\"-\".repeat(78))\n    print(\"F\u00a0:\") \n    for (i in 0..24) print(\"%3d\".format(f(i)))\n    println()\n    print(\"M\u00a0:\") \n    for (i in 0..24) print(\"%3d\".format(m(i)))\n    println()\n}\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. If the programming language does not support mutual recursion, it should be stated.","id":4627}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.2.10\n\nimport java.util.Random\n\n\/**\n * Extension function on any list that will return a random element from index 0 \n * to the last index\n *\/\nfun <E> List<E>.getRandomElement() = this[Random().nextInt(this.size)]\n\n\/**\n * Extension function on any list that will return a list of unique random picks\n * from the list. If the specified number of elements you want is larger than the\n * number of elements in the list it returns null\n *\/\nfun <E> List<E>.getRandomElements(numberOfElements: Int): List<E>? {\n    if (numberOfElements > this.size) {\n        return null\n    }\n    return this.shuffled().take(numberOfElements)\n}\n\nfun main(args: Array<String>) { \n    val list = listOf(1, 16, 3, 7, 17, 24, 34, 23, 11, 2)\n    println(\"The list consists of the following numbers:\\n${list}\")\n \n    \/\/ notice we can call our extension functions as if they were regular member functions of List\n    println(\"\\nA randomly selected element from the list is ${list.getRandomElement()}\")\n    println(\"\\nA random sequence of 5 elements from the list is ${list.getRandomElements(5)}\")\n}\n\n\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":4628}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nimport java.net.URLDecoder\n\nfun main(args: Array<String>) {\n    val encoded = arrayOf(\"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\")\n    for (e in encoded) println(URLDecoder.decode(e, \"UTF-8\"))\n}\n\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":4629}
    {"lang_cluster":"Kotlin","source_code":"\nfun <T : Comparable<T>> Array<T>.iterativeBinarySearch(target: T): Int {\n    var hi = size - 1\n    var lo = 0\n    while (hi >= lo) {\n        val guess = lo + (hi - lo) \/ 2\n        if (this[guess] > target) hi = guess - 1\n        else if (this[guess] < target) lo = guess + 1\n        else return guess\n    }\n    return -1\n}\n\nfun <T : Comparable<T>> Array<T>.recursiveBinarySearch(target: T, lo: Int, hi: Int): Int {\n    if (hi < lo) return -1\n\n    val guess = (hi + lo) \/ 2\n\n    return if (this[guess] > target) recursiveBinarySearch(target, lo, guess - 1)\n    else if (this[guess] < target) recursiveBinarySearch(target, guess + 1, hi)\n    else guess\n}\n\nfun main(args: Array<String>) {\n    val a = arrayOf(1, 3, 4, 5, 6, 7, 8, 9, 10)\n    var target = 6\n    var r = a.iterativeBinarySearch(target)\n    println(if (r < 0) \"$target not found\" else \"$target found at index $r\")\n    target = 250\n    r = a.iterativeBinarySearch(target)\n    println(if (r < 0) \"$target not found\" else \"$target found at index $r\")\n\n    target = 6\n    r = a.recursiveBinarySearch(target, 0, a.size)\n    println(if (r < 0) \"$target not found\" else \"$target found at index $r\")\n    target = 250\n    r = a.recursiveBinarySearch(target, 0, a.size)\n    println(if (r < 0) \"$target not found\" else \"$target found at index $r\")\n}\n\n\n","human_summarization":"The code implements a binary search algorithm, which divides a range of values into halves to find an unknown value. It takes a sorted integer array, a starting point, an ending point, and a \"secret value\" as inputs. The algorithm can be either recursive or iterative and returns whether the number was in the array and its index if found. The code also includes variations of the binary search algorithm that return the leftmost or rightmost insertion point for the given value. It also handles potential overflow bugs.","id":4630}
    {"lang_cluster":"Kotlin","source_code":"fun main(args: Array<String>) {\n     println(\"There are \" + args.size + \" arguments given.\")\n     args.forEachIndexed { i, a -> println(\"The argument #${i+1} is $a and is at index $i\") }\n}\n\n\n","human_summarization":"The code retrieves the list of command-line arguments provided to the program. It intelligently parses these arguments and prints them only when the program is run directly. The code also handles examples of command lines such as \"myprogram -c \"alpha beta\" -h \"gamma\"\".","id":4631}
    {"lang_cluster":"Kotlin","source_code":"\n\nimport java.awt.*\nimport java.util.concurrent.*\nimport javax.swing.*\n\nclass Pendulum(private val length: Int) : JPanel(), Runnable {\n    init {\n        val f = JFrame(\"Pendulum\")\n        f.add(this)\n        f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n        f.pack()\n        f.isVisible = true\n        isDoubleBuffered = true\n    }\n\n    override fun paint(g: Graphics) {\n        with(g) {\n            color = Color.WHITE\n            fillRect(0, 0, width, height)\n            color = Color.BLACK\n            val anchor = Element(width \/ 2, height \/ 4)\n            val ball = Element((anchor.x + Math.sin(angle) * length).toInt(), (anchor.y + Math.cos(angle) * length).toInt())\n            drawLine(anchor.x, anchor.y, ball.x, ball.y)\n            fillOval(anchor.x - 3, anchor.y - 4, 7, 7)\n            fillOval(ball.x - 7, ball.y - 7, 14, 14)\n        }\n    }\n\n    override fun run() {\n        angleVelocity += -9.81 \/ length * Math.sin(angle) * dt\n        angle += angleVelocity * dt\n        repaint()\n    }\n\n    override fun getPreferredSize() = Dimension(2 * length + 50, length \/ 2 * 3)\n\n    private data class Element(val x: Int, val y: Int)\n\n    private val dt = 0.1\n    private var angle = Math.PI \/ 2\n    private var angleVelocity = 0.0\n}\n\nfun main(a: Array<String>) {\n    val executor = Executors.newSingleThreadScheduledExecutor()\n    executor.scheduleAtFixedRate(Pendulum(200), 0, 15, TimeUnit.MILLISECONDS)\n}\n\n","human_summarization":"simulate and animate a simple gravity pendulum model.","id":4632}
    {"lang_cluster":"Kotlin","source_code":"\n\n\/\/ version 1.2.21\n\ndata class JsonObject(val foo: Int, val bar: Array<String>)\n\ndata class JsonObject2(val ocean: String, val blue: Array<Int>)\n\nfun main(args: Array<String>) {\n    \/\/ JSON to object\n    val data: JsonObject = JSON.parse(\"\"\"{ \"foo\": 1, \"bar\": [\"10\", \"apples\"] }\"\"\")\n    println(JSON.stringify(data))\n\n    \/\/ object to JSON\n    val data2 = JsonObject2(\"water\", arrayOf(1, 2))\n    println(JSON.stringify(data2))\n}\n\n\n","human_summarization":"\"Load a JSON string into a data structure and serialize a new data structure into JSON using Kotlin JS, ensuring the JSON is valid.\"","id":4633}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.0.6\n\nfun nthRoot(x: Double, n: Int): Double {\n    if (n < 2) throw IllegalArgumentException(\"n must be more than 1\")\n    if (x <= 0.0) throw IllegalArgumentException(\"x must be positive\")\n    val np = n - 1\n    fun iter(g: Double) = (np * g + x \/ Math.pow(g, np.toDouble())) \/ n\n    var g1 = x\n    var g2 = iter(g1)\n    while (g1 != g2) {\n        g1 = iter(g1)\n        g2 = iter(iter(g2))\n    }\n    return g1\n}\n\nfun main(args: Array<String>) {\n   val numbers = arrayOf(1728.0 to 3, 1024.0 to 10, 2.0 to 2) \n   for (number in numbers)  \n       println(\"${number.first} ^ 1\/${number.second}\\t = ${nthRoot(number.first, number.second)}\")\n}\n\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":4634}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.4\n\nimport java.net.InetAddress\n\nfun main(args: Array<String>) {\n    println(InetAddress.getLocalHost().hostName)\n}\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":4635}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nfun leonardo(n: Int, l0: Int = 1, l1: Int = 1, add: Int = 1): IntArray {\n    val leo = IntArray(n)\n    leo[0] = l0\n    leo[1] = l1\n    for (i in 2 until n) leo[i] = leo[i - 1] + leo[i - 2] + add\n    return leo\n}\n\nfun main(args: Array<String>) {\n    println(\"The first 25 Leonardo numbers with L[0] = 1, L[1] = 1 and add number = 1 are:\")\n    println(leonardo(25).joinToString(\" \"))\n    println(\"\\nThe first 25 Leonardo numbers with L[0] = 0, L[1] = 1 and add number = 0 are:\")\n    println(leonardo(25, 0, 1, 0).joinToString(\" \"))\n}\n\n\n","human_summarization":"generate the first 25 Leonardo numbers, starting from L(0), with the ability to specify the first two Leonardo numbers and the add number. The codes also have the functionality to generate the Fibonacci sequence by specifying 0 and 1 for L(0) and L(1), and 0 for the add number.","id":4636}
    {"lang_cluster":"Kotlin","source_code":"\nimport java.util.Random\nimport java.util.Scanner\nimport java.util.Stack\n\ninternal object Game24 {\n    fun run() {\n        val r = Random()\n        val digits = IntArray(4).map { r.nextInt(9) + 1 }\n        println(\"Make 24 using these digits: $digits\")\n        print(\"> \")\n\n        val s = Stack<Float>()\n        var total = 0L\n        val cin = Scanner(System.`in`)\n        for (c in cin.nextLine()) {\n            when (c) {\n                in '0'..'9' -> {\n                    val d = c - '0'\n                    total += (1 shl (d * 5)).toLong()\n                    s += d.toFloat()\n                }\n                else ->\n                    if (\"+\/-*\".indexOf(c) != -1) {\n                        s += c.applyOperator(s.pop(), s.pop())\n                    }\n            }\n        }\n\n        when {\n            tally(digits) != total ->\n                print(\"Not the same digits. \")\n            s.peek().compareTo(target) == 0 ->\n                println(\"Correct!\")\n            else ->\n                print(\"Not correct.\")\n        }\n    }\n\n    private fun Char.applyOperator(a: Float, b: Float) = when (this) {\n        '+' -> a + b\n        '-' -> b - a\n        '*' -> a * b\n        '\/' -> b \/ a\n        else -> Float.NaN\n    }\n\n    private fun tally(a: List<Int>): Long = a.reduce({ t, i -> t + (1 shl (i * 5)) }).toLong()\n\n    private val target = 24\n}\n\nfun main(args: Array<String>) = Game24.run()\n\n","human_summarization":"\"Generate a game that randomly selects four digits and prompts the user to create an arithmetic expression with these digits that equals 24. The code checks and evaluates the user's expression, allowing for addition, subtraction, multiplication, and division operations. The code does not allow the formation of multiple digit numbers from the given digits.\"","id":4637}
    {"lang_cluster":"Kotlin","source_code":"\n\ntailrec fun runLengthEncoding(text:String,prev:String=\"\"):String {\n    if (text.isEmpty()){\n        return prev\n    }\n    val initialChar = text.get(0)\n    val count = text.takeWhile{ it==initialChar }.count()\n    return runLengthEncoding(text.substring(count),prev + \"$count$initialChar\" )\n}\n\nfun main(args: Array<String>) {\n    assert(runLengthEncoding(\"TTESSST\") == \"2T1E3S1T\")\n    assert(runLengthEncoding(\"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\")\n                   == \"12W1B12W3B24W1B14W\")\n}\n\n","human_summarization":"implement a run-length encoding and decoding system for strings containing uppercase characters. The system compresses repeated characters by storing the length of the run and provides a function to reverse the compression.","id":4638}
    {"lang_cluster":"Kotlin","source_code":"\nfun main() {\n    val s1 = \"James\"\n    val s2 = \"Bond\"\n    println(s1)\n    println(s2)\n    val s3 = s1 + \" \" + s2\n    println(s3)\n}\n\n\n","human_summarization":"Initializes two string variables, one with a text value and the other as a concatenation of the first variable and a string literal, then displays their content.","id":4639}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nimport java.net.URLEncoder\n\nfun main(args: Array<String>) {\n    val url = \"http:\/\/foo bar\/\"\n    println(URLEncoder.encode(url, \"utf-8\")) \/\/ note: encodes space to + not %20\n}\n\n\n","human_summarization":"provide a function to convert a given string into URL encoding. This function encodes all characters except 0-9, A-Z, and a-z into their corresponding hexadecimal code preceded by a percent symbol. ASCII control codes, symbols, and extended characters are all converted. The function also supports variations including lowercase escapes and different encoding standards such as RFC 3986 and HTML 5. An optional feature is the use of an exception string for symbols that don't need conversion. For example, \"http:\/\/foo bar\/\" is encoded as \"http%3A%2F%2Ffoo%20bar%2F\".","id":4640}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\ndata class Item(val name: String, val weight: Double, val value: Double)\n\nval items = mutableListOf(\n    Item(\"beef\", 3.8, 36.0),\n    Item(\"pork\", 5.4, 43.0),\n    Item(\"ham\", 3.6, 90.0),\n    Item(\"greaves\", 2.4, 45.0),\n    Item(\"flitch\", 4.0, 30.0),\n    Item(\"brawn\", 2.5, 56.0),\n    Item(\"welt\", 3.7, 67.0),\n    Item(\"salami\", 3.0, 95.0),\n    Item(\"sausage\", 5.9, 98.0)\n)\n\nconst val MAX_WEIGHT = 15.0\n\nfun main(args: Array<String>) {\n    \/\/ sort items by value per unit weight in descending order\n    items.sortByDescending { it.value \/ it.weight }\n    println(\"Item Chosen   Weight  Value  Percentage\")\n    println(\"-----------   ------ ------  ----------\")\n    var w = MAX_WEIGHT\n    var itemCount = 0\n    var sumValue = 0.0\n    for (item in items) {\n        itemCount++\n        if (item.weight <= w) {\n           sumValue += item.value\n           print(\"${item.name.padEnd(11)}     ${\"%3.1f\".format(item.weight)}   ${\"%5.2f\".format(item.value)}\")\n           println(\"    100.00\")\n        }\n        else {\n           val value  = Math.round((w \/ item.weight * item.value * 100.0)) \/ 100.0\n           val percentage = Math.round((w \/ item.weight * 10000.0)) \/ 100.0\n           sumValue += value\n           print(\"${item.name.padEnd(11)}     ${\"%3.1f\".format(w)}   ${\"%5.2f\".format(value)}\")\n           println(\"     $percentage\")\n           break\n        }\n        w -= item.weight\n        if (w == 0.0) break\n    }\n    println(\"-----------   ------ ------\")\n    println(\"${itemCount} items        15.0  ${\"%6.2f\".format(sumValue)}\")\n}\n\n\n","human_summarization":"The code implements a solution to the continuous knapsack problem. It involves a thief maximizing his profit from burgling a butcher's shop. The code takes into account the weights and prices of each item, the maximum capacity of the thief's knapsack, and the fact that the price of an item decreases proportionally if it is cut. The code uses a non-recursive form of QuickSort to determine the optimal items to steal such that the total weight does not exceed 15 kg and the total value is maximized.","id":4641}
    {"lang_cluster":"Kotlin","source_code":"import java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.net.URL\nimport kotlin.math.max\n\nfun main() {\n    val url = URL(\"http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt\")\n    val isr = InputStreamReader(url.openStream())\n    val reader = BufferedReader(isr)\n    val anagrams = mutableMapOf<String, MutableList<String>>()\n    var count = 0\n    var word = reader.readLine()\n    while (word != null) {\n        val chars = word.toCharArray()\n        chars.sort()\n        val key = chars.joinToString(\"\")\n        if (!anagrams.containsKey(key)) anagrams[key] = mutableListOf()\n        anagrams[key]?.add(word)\n        count = max(count, anagrams[key]?.size ?: 0)\n        word = reader.readLine()\n    }\n    reader.close()\n    anagrams.values\n        .filter { it.size == count }\n        .forEach { println(it) }\n}\n\n\n","human_summarization":"\"Code identifies sets of anagrams with the most words from the provided word list.\"","id":4642}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.2\n\nfun inCarpet(x: Int, y: Int): Boolean {\n    var xx = x\n    var yy = y\n    while (xx != 0 && yy != 0) {\n        if (xx % 3 == 1 && yy % 3 == 1) return false\n        xx \/= 3\n        yy \/= 3\n    }\n    return true\n}\n\nfun carpet(n: Int) {\n    val power = Math.pow(3.0, n.toDouble()).toInt()\n    for(i in 0 until power) {\n        for(j in 0 until power) print(if (inCarpet(i, j)) \"*\" else \" \")\n        println()\n    }\n}\n\nfun main(args: Array<String>) = carpet(3)\n\n\n","human_summarization":"generate a graphical or ASCII-art representation of a Sierpinski carpet of a given order N. The representation uses whitespace and non-whitespace characters, with the non-whitespace character not strictly required to be '#'. The placement of these characters follows the pattern of a Sierpinski carpet.","id":4643}
    {"lang_cluster":"Kotlin","source_code":"\nimport java.util.*\n\nabstract class HuffmanTree(var freq: Int) : Comparable<HuffmanTree> {\n    override fun compareTo(other: HuffmanTree) = freq - other.freq\n}\n\nclass HuffmanLeaf(freq: Int, var value: Char) : HuffmanTree(freq)\n\nclass HuffmanNode(var left: HuffmanTree, var right: HuffmanTree) : HuffmanTree(left.freq + right.freq)\n\nfun buildTree(charFreqs: IntArray) : HuffmanTree {\n    val trees = PriorityQueue<HuffmanTree>()\n\n    charFreqs.forEachIndexed { index, freq ->\n        if(freq > 0) trees.offer(HuffmanLeaf(freq, index.toChar()))\n    }\n\n    assert(trees.size > 0)\n    while (trees.size > 1) {\n        val a = trees.poll()\n        val b = trees.poll()\n        trees.offer(HuffmanNode(a, b))\n    }\n\n    return trees.poll()\n}\n\nfun printCodes(tree: HuffmanTree, prefix: StringBuffer) {\n    when(tree) {\n        is HuffmanLeaf -> println(\"${tree.value}\\t${tree.freq}\\t$prefix\")\n        is HuffmanNode -> {\n            \/\/traverse left\n            prefix.append('0')\n            printCodes(tree.left, prefix)\n            prefix.deleteCharAt(prefix.lastIndex)\n            \/\/traverse right\n            prefix.append('1')\n            printCodes(tree.right, prefix)\n            prefix.deleteCharAt(prefix.lastIndex)\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    val test = \"this is an example for huffman encoding\"\n\n    val maxIndex = test.max()!!.toInt() + 1\n    val freqs = IntArray(maxIndex) \/\/256 enough for latin ASCII table, but dynamic size is more fun\n    test.forEach { freqs[it.toInt()] += 1 }\n\n    val tree = buildTree(freqs)\n    println(\"SYMBOL\\tWEIGHT\\tHUFFMAN CODE\")\n    printCodes(tree, StringBuffer())\n}\n\n\n","human_summarization":"The code takes a string input, calculates the frequency of each character, and generates a Huffman encoding for each character. It constructs a binary tree based on the frequencies, with more frequent characters having shorter codes. The code ensures that no character's encoding is a prefix of another's. The output is a table displaying each character and its Huffman encoding.","id":4644}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.0.6\n\nimport java.awt.BorderLayout\nimport java.awt.event.ActionEvent\nimport java.awt.event.ActionListener\nimport javax.swing.*\n\nclass Clicks : JFrame(), ActionListener {\n    private var clicks = 0\n    private val label: JLabel\n    private val clicker: JButton\n    private var text: String\n\n    init {\n        text = \"There have been no clicks yet\"\n        label = JLabel(text)\n        clicker = JButton(\"click me\")\n        clicker.addActionListener(this)        \/\/ listen to the button\n        layout = BorderLayout()                \/\/ handles placement of components\n        add(label, BorderLayout.CENTER)        \/\/ add the label to the biggest section\n        add(clicker, BorderLayout.SOUTH)       \/\/ put the button underneath it\n        setSize(300, 200)                       \/\/ stretch out the window\n        defaultCloseOperation = EXIT_ON_CLOSE  \/\/ stop the program on \"X\"\n        isVisible = true                       \/\/ show it\n    }\n\n    override fun actionPerformed(arg0: ActionEvent) {\n        if (arg0.source == clicker) {           \/\/ if they clicked the button\n            if (clicks == 0) text = \"There has been \" + (++clicks) + \" click\"\n            else text = \"There have been \" + (++clicks) + \" clicks\"\n            label.text = text                  \/\/ change the text\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    Clicks()  \/\/ call the constructor where all the magic happens\n}\n\nLibrary: TornadoFX\nimport tornadofx.*\n\nclass ClicksView: View(\"Clicks example\") {\n    var clicks = 0\n    override val root = vbox(5) {\n        var label1 = label(\"There have been no clicks yet\")\n        button(\"Click me!\") { action { label1.text = \"Clicked ${++clicks} times.\" } }\n    }\n}\n\nclass ClicksApp: App(ClicksView::class)\n\nfun main(args: Array<String>) = launch<ClicksApp>(args)\n\n","human_summarization":"Implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". The button, labelled \"click me\", updates the label to show the number of times it has been clicked when interacted with.","id":4645}
    {"lang_cluster":"Kotlin","source_code":"\n\n\/\/ Version 1.2.41\n\nimport java.io.File\nimport java.io.RandomAccessFile\n\nfun String.toFixedLength(len: Int) = this.padEnd(len).substring(0, len)\n\nclass Address(\n    var name: String,\n    var street: String = \"\",\n    var city: String = \"\",\n    var state: String = \"\",\n    var zipCode: String = \"\",\n    val autoId: Boolean = true\n) {\n    var id = 0L\n        private set\n\n    init {\n        if (autoId) id = ++nextId\n    }\n\n    companion object {\n        private var nextId = 0L\n\n        const val RECORD_LENGTH = 127  \/\/ including 2 bytes for UTF string length\n\n        fun readRecord(file: File, id: Long): Address {\n            val raf = RandomAccessFile(file, \"r\")\n            val seekPoint = (id - 1) * RECORD_LENGTH\n            raf.use {\n                it.seek(seekPoint)\n                val id2 = it.readLong()\n                if (id != id2) {\n                    println(\"Database is corrupt\")\n                    System.exit(1)\n                }\n                val text    = it.readUTF()\n                val name    = text.substring(0, 30).trimEnd()\n                val street  = text.substring(30, 80).trimEnd()\n                val city    = text.substring(80, 105).trimEnd()\n                val state   = text.substring(105, 107)\n                val zipCode = text.substring(107).trimEnd()\n                val a = Address(name, street, city, state, zipCode, false)\n                a.id = id\n                return a\n            }\n        }\n    }\n\n    override fun toString() =\n        \"Id      \u00a0: ${this.id}\\n\" +\n        \"Name    \u00a0: $name\\n\" +\n        \"Street  \u00a0: $street\\n\" +\n        \"City    \u00a0: $city\\n\" +\n        \"State   \u00a0: $state\\n\" +\n        \"Zip Code\u00a0: $zipCode\\n\"\n\n    fun writeRecord(file: File) {\n        val raf = RandomAccessFile(file, \"rw\")\n        val text =\n            name.toFixedLength(30) +\n            street.toFixedLength(50) +\n            city.toFixedLength(25) +\n            state +\n            zipCode.toFixedLength(10)\n        val seekPoint = (id - 1) * RECORD_LENGTH\n        raf.use {\n            it.seek(seekPoint)\n            it.writeLong(id)\n            it.writeUTF(text)\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    val file = File(\"addresses.dat\")\n    val addresses = listOf(\n        Address(\"FSF Inc.\", \"51 Franklin Street\", \"Boston\", \"MA\", \"02110-1301\"),\n        Address(\"The White House\", \"The Oval Office, 1600 Pennsylvania Avenue NW\", \"Washington\", \"DC\", \"20500\")\n    )\n    \/\/ write the address records to the file\n    addresses.forEach { it.writeRecord(file) }\n\n    \/\/ now read them back in reverse order and print them out\n    for (i in 2 downTo 1) {\n        println(Address.readRecord(file, i.toLong()))\n    }\n}\n\n\n","human_summarization":"\"Create a table in a database to store US postal addresses, including fields for unique identifier, street address, city, state code, and zipcode. For non-database languages, it demonstrates how to connect to a database and create an address table. Utilizes the built-in RandomAccessFile class for this task.\"","id":4646}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.3.61\n\nfun main() {\n    (10 downTo 0).forEach { println(it) }\n}\n\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":4647}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.3\n\nfun vigenere(text: String, key: String, encrypt: Boolean = true): String {\n    val t = if (encrypt) text.toUpperCase() else text\n    val sb = StringBuilder()\n    var ki = 0\n    for (c in t) {\n        if (c !in 'A'..'Z') continue\n        val ci = if (encrypt)\n            (c.toInt() + key[ki].toInt() - 130) % 26\n        else\n            (c.toInt() - key[ki].toInt() +  26) % 26\n        sb.append((ci + 65).toChar())\n        ki = (ki + 1) % key.length\n    }\n    return sb.toString()\n}\n\nfun main(args: Array<String>) {\n    val key = \"VIGENERECIPHER\"\n    val text = \"Beware the Jabberwock, my son! The jaws that bite, the claws that catch!\"\n    val encoded = vigenere(text, key)\n    println(encoded)\n    val decoded = vigenere(encoded, key, false)\n    println(decoded)\n}\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. If non-alphabetic characters are handled differently, it is noted.","id":4648}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun main(args: Array<String>) {\n    for (i in 1 .. 21 step 2) print(\"$i \")\n}\n\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":4649}
    {"lang_cluster":"Kotlin","source_code":"\nfun sum(lo: Int, hi: Int, f: (Int) -> Double) = (lo..hi).sumByDouble(f)\n\nfun main(args: Array<String>) = println(sum(1, 100, { 1.0 \/ it }))\n\n","human_summarization":"implement Jensen's Device, a programming technique devised by J\u00f8rn Jensen. The technique is an exercise in call by name, where it computes the 100th harmonic number. The program uses a sum procedure that takes in four parameters, with the first and the last parameter being passed by name. This allows the expression passed as an actual parameter to be re-evaluated in the caller's context every time the corresponding formal parameter's value is required. The program also demonstrates the importance of passing the first parameter by name or by reference, as changes to it within the sum procedure need to be visible in the caller's context when computing each of the values to be added.","id":4650}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.4-3\n\nimport javax.swing.JFrame\nimport javax.swing.JPanel\nimport java.awt.Graphics\nimport java.awt.Graphics2D\nimport java.awt.Color\nimport java.awt.Dimension\nimport java.awt.BorderLayout\nimport java.awt.RenderingHints\nimport javax.swing.SwingUtilities\n\nclass XorPattern : JPanel() {\n\n    init {\n        preferredSize = Dimension(256, 256)\n        background = Color.white\n    }\n\n    override fun paint(gg: Graphics) {\n        super.paintComponent(gg)\n        val g = gg as Graphics2D\n        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, \n                           RenderingHints.VALUE_ANTIALIAS_ON)\n        for (y in 0 until width) {\n            for (x in 0 until height) {\n                g.color = Color(0, (x xor y) % 256, 255)\n                g.drawLine(x, y, x, y)\n            }\n        }\n    }\n}\n\nfun main(args: Array<String>) {\n    SwingUtilities.invokeLater {\n        val f = JFrame()\n        with (f) {\n            defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n            title = \"Munching squares\"\n            isResizable = false\n            add(XorPattern(), BorderLayout.CENTER)\n            pack()\n            setLocationRelativeTo(null)\n            isVisible = true\n        }\n    }\n}\n\n","human_summarization":"generates a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, implementing the Munching Squares algorithm.","id":4651}
    {"lang_cluster":"Kotlin","source_code":"import java.util.*\n\nclass MazeGenerator(val x: Int, val y: Int) {\n    private val maze = Array(x) { IntArray(y) }\n\n    fun generate(cx: Int, cy: Int) {\n        Direction.values().shuffle().forEach {\n            val nx = cx + it.dx\n            val ny = cy + it.dy\n            if (between(nx, x) && between(ny, y) && maze[nx][ny] == 0) {\n                maze[cx][cy] = maze[cx][cy] or it.bit\n                maze[nx][ny] = maze[nx][ny] or it.opposite!!.bit\n                generate(nx, ny)\n            }\n        }\n    }\n\n    fun display() {\n        for (i in 0..y - 1) {\n            \/\/ draw the north edge\n            for (j in 0..x - 1)\n                print(if (maze[j][i] and 1 == 0) \"+---\" else \"+   \")\n            println('+')\n\n            \/\/ draw the west edge\n            for (j in 0..x - 1)\n                print(if (maze[j][i] and 8 == 0) \"|   \" else \"    \")\n            println('|')\n        }\n\n        \/\/ draw the bottom line\n        for (j in 0..x - 1) print(\"+---\")\n        println('+')\n    }\n\n    inline private fun <reified T> Array<T>.shuffle(): Array<T> {\n        val list = toMutableList()\n        Collections.shuffle(list)\n        return list.toTypedArray()\n    }\n\n    private enum class Direction(val bit: Int, val dx: Int, val dy: Int) {\n        N(1, 0, -1), S(2, 0, 1), E(4, 1, 0),W(8, -1, 0);\n\n        var opposite: Direction? = null\n\n        companion object {\n            init {\n                N.opposite = S\n                S.opposite = N\n                E.opposite = W\n                W.opposite = E\n            }\n        }\n    }\n\n    private fun between(v: Int, upper: Int) = v >= 0 && v < upper\n}\n\nfun main(args: Array<String>) {\n    val x = if (args.size >= 1) args[0].toInt() else 8\n    val y = if (args.size == 2) args[1].toInt() else 8\n    with(MazeGenerator(x, y)) {\n        generate(0, 0)\n        display()\n    }\n}\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":4652}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.2\n\nimport java.math.BigInteger\n\nval ZERO  = BigInteger.ZERO\nval ONE   = BigInteger.ONE \nval TWO   = BigInteger.valueOf(2L)\nval THREE = BigInteger.valueOf(3L)\nval FOUR  = BigInteger.valueOf(4L)\nval SEVEN = BigInteger.valueOf(7L)\nval TEN   = BigInteger.TEN\n\nfun calcPi() {\n    var nn: BigInteger\n    var nr: BigInteger\n    var q = ONE\n    var r = ZERO\n    var t = ONE\n    var k = ONE\n    var n = THREE\n    var l = THREE     \n    var first = true\n    while (true) {\n        if (FOUR * q + r - t < n * t) {\n            print(n)\n            if (first) { print (\".\"); first = false }\n            nr = TEN * (r - n * t)\n            n = TEN * (THREE * q + r) \/ t - TEN * n\n            q *= TEN\n            r = nr\n        }\n        else {\n            nr = (TWO * q + r) * l\n            nn = (q * SEVEN * k + TWO + r * l) \/ (t * l)\n            q *= k\n            t *= l\n            l += TWO\n            k += ONE\n            n = nn\n            r = nr\n        }\n    }\n}\n\nfun main(args: Array<String>) = calcPi()\n\n\n","human_summarization":"are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.","id":4653}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\noperator fun <T> List<T>.compareTo(other: List<T>): Int\n    where T: Comparable<T>, T: Number {\n    for (i in 0 until this.size) {\n        if (other.size == i) return 1\n        when {\n            this[i] < other[i] -> return -1\n            this[i] > other[i] -> return 1\n        }\n    }\n    return if (this.size == other.size) 0 else -1\n} \n\nfun main(args: Array<String>) {\n    val lists = listOf(\n        listOf(1, 2, 3, 4, 5),\n        listOf(1, 2, 1, 5, 2, 2),\n        listOf(1, 2, 1, 5, 2),\n        listOf(1, 2, 1, 5, 2),\n        listOf(1, 2, 1, 3, 2),\n        listOf(1, 2, 0, 4, 4, 0, 0, 0),\n        listOf(1, 2, 0, 4, 4, 1, 0, 0)\n    )\n    for (i in 0 until lists.size) println(\"list${i + 1}\u00a0: ${lists[i]}\")\n    println()  \n    for (i in 0 until lists.size - 1) println(\"list${i + 1} > list${i + 2} = ${lists[i] > lists[i + 1]}\")    \n}\n\n\n","human_summarization":"\"Function to compare and order two numerical lists lexicographically, returning true if the first list should be ordered before the second, and false otherwise.\"","id":4654}
    {"lang_cluster":"Kotlin","source_code":"\ntailrec fun A(m: Long, n: Long): Long {\n    require(m >= 0L) { \"m must not be negative\" }\n    require(n >= 0L) { \"n must not be negative\" }\n    if (m == 0L) {\n        return n + 1L\n    }\n    if (n == 0L) {\n        return A(m - 1L, 1L)\n    }\n    return A(m - 1L, A(m, n - 1L))\n}\n\ninline fun<T> tryOrNull(block: () -> T): T? = try { block() } catch (e: Throwable) { null }\n\nconst val N = 10L\nconst val M = 4L\n\nfun main() {\n    (0..M)\n        .map { it to 0..N }\n        .map { (m, Ns) -> (m to Ns) to Ns.map { n -> tryOrNull { A(m, n) } } }\n        .map { (input, output) -> \"A(${input.first}, ${input.second})\" to output.map { it?.toString()\u00a0?: \"?\" } }\n        .map { (input, output) -> \"$input = $output\" }\n        .forEach(::println)\n}\n\n","human_summarization":"Implement the Ackermann function which is a recursive function that takes two non-negative arguments and returns a value based on the specified conditions. The function should ideally support arbitrary precision due to its rapid growth.","id":4655}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nfun gammaStirling(x: Double): Double = Math.sqrt(2.0 * Math.PI \/ x) * Math.pow(x \/ Math.E, x)\n\nfun gammaLanczos(x: Double): Double {\n    var xx = x\n    val p = doubleArrayOf(\n        0.99999999999980993, \n      676.5203681218851,\n    -1259.1392167224028,\t\t\t     \t  \n      771.32342877765313,\n     -176.61502916214059,\n       12.507343278686905,\n       -0.13857109526572012,\n        9.9843695780195716e-6,\n        1.5056327351493116e-7\n    )\n    val g = 7\n    if (xx < 0.5) return Math.PI \/ (Math.sin(Math.PI * xx) * gammaLanczos(1.0 - xx))\n    xx--\n    var a = p[0]\n    val t = xx + g + 0.5\n    for (i in 1 until p.size) a += p[i] \/ (xx + i)\n    return Math.sqrt(2.0 * Math.PI) * Math.pow(t, xx + 0.5) * Math.exp(-t) * a\n}\n\nfun main(args: Array<String>) {\n    println(\" x\\tStirling\\t\\tLanczos\\n\")\n    for (i in 1 .. 20) {\n        val d = i \/ 10.0\n        print(\"%4.2f\\t\".format(d))\n        print(\"%17.15f\\t\".format(gammaStirling(d)))\n        println(\"%17.15f\".format(gammaLanczos(d)))\n    }\n}\n\n\n","human_summarization":"implement the Gamma function using either the Lanczos or Stirling's approximation. The codes also compare the results of the custom implementation with the built-in\/library function if available. The Gamma function is computed through numerical integration.","id":4656}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.3\n\nvar count = 0\nvar c = IntArray(0)\nvar f = \"\" \n\nfun nQueens(row: Int, n: Int) {\n    outer@ for (x in 1..n) {\n        for (y in 1..row - 1) {\n            if (c[y] == x) continue@outer\n            if (row - y == Math.abs(x - c[y])) continue@outer           \n        }\n        c[row] = x\n        if (row < n) nQueens(row + 1, n)\n        else if (++count == 1) f = c.drop(1).map { it - 1 }.toString()\n    }\n}\n\nfun main(args: Array<String>) {\n   for (n in 1..14) { \n       count = 0\n       c = IntArray(n + 1)\n       f = \"\"\n       nQueens(1, n)\n       println(\"For a $n x $n board:\")\n       println(\"  Solutions = $count\")\n       if (count > 0) println(\"  First is $f\")\n       println()\n   }\n}\n\n\n","human_summarization":"\"Solve the N-queens problem for an NxN board and provide the number of solutions for small values of N.\"","id":4657}
    {"lang_cluster":"Kotlin","source_code":"\nfun main() {\n    val a = intArrayOf(1, 2, 3)\n    val b = intArrayOf(4, 5, 6)\n    val c = a + b \/\/ [1, 2, 3, 4, 5, 6]\n    println(c.contentToString())\n}\n\n","human_summarization":"demonstrate how to concatenate two arrays.","id":4658}
    {"lang_cluster":"Kotlin","source_code":"\/\/ version 1.1.2\n\ndata class Item(val name: String, val weight: Int, val value: Int)\n\nval wants = listOf(\n    Item(\"map\", 9, 150),\n    Item(\"compass\", 13, 35),\n    Item(\"water\", 153, 200),\n    Item(\"sandwich\", 50, 160),\n    Item(\"glucose\", 15, 60),\n    Item(\"tin\", 68, 45),\n    Item(\"banana\", 27, 60),\n    Item(\"apple\", 39, 40),\n    Item(\"cheese\", 23, 30),\n    Item(\"beer\", 52, 10),\n    Item(\"suntan cream\", 11, 70),\n    Item(\"camera\", 32, 30),\n    Item(\"T-shirt\", 24, 15),\n    Item(\"trousers\", 48, 10),\n    Item(\"umbrella\", 73, 40),\n    Item(\"waterproof trousers\", 42, 70),\n    Item(\"waterproof overclothes\", 43, 75),\n    Item(\"note-case\", 22, 80),\n    Item(\"sunglasses\", 7, 20),\n    Item(\"towel\", 18, 12),\n    Item(\"socks\", 4, 50),\n    Item(\"book\", 30, 10)\n)\n\nconst val MAX_WEIGHT = 400\n\nfun m(i: Int, w: Int): Triple<MutableList<Item>, Int, Int> {\n    val chosen = mutableListOf<Item>()\n    if (i < 0 || w == 0) return Triple(chosen, 0, 0)\n    else if (wants[i].weight > w) return m(i - 1, w)\n    val (l0, w0, v0) = m(i - 1, w)\n    var (l1, w1, v1) = m(i - 1, w - wants[i].weight)\n    v1 += wants[i].value\n    if (v1 > v0) {\n        l1.add(wants[i])\n        return Triple(l1, w1 + wants[i].weight, v1)\n    }\n    return Triple(l0, w0, v0)\n}\n\nfun main(args: Array<String>) {\n    val (chosenItems, totalWeight, totalValue) = m(wants.size - 1, MAX_WEIGHT)\n    println(\"Knapsack Item Chosen    Weight Value\")\n    println(\"----------------------  ------ -----\")\n    for (item in chosenItems.sortedByDescending { it.value} )\n        println(\"${item.name.padEnd(24)}  ${\"%3d\".format(item.weight)}    ${\"%3d\".format(item.value)}\")\n    println(\"----------------------  ------ -----\")\n    println(\"Total ${chosenItems.size} Items Chosen     $totalWeight   $totalValue\")\n}\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (400 dag), such that the total value of the items is maximized. The items cannot be divided or diminished.","id":4659}
    {"lang_cluster":"Kotlin","source_code":"\ndata class Person(val name: String) {\n    val preferences = mutableListOf<Person>()\n    var matchedTo: Person? = null\n\n    fun trySwap(p: Person) {\n        if (prefers(p)) {\n            matchedTo?.matchedTo = null\n            matchedTo = p\n            p.matchedTo = this\n        }\n    }\n\n    fun prefers(p: Person) = when (matchedTo) {\n        null -> true\n        else -> preferences.indexOf(p) < preferences.indexOf(matchedTo!!)\n    }\n\n    fun showMatch() = \"$name <=> ${matchedTo?.name}\"\n}\n\nfun match(males: Collection<Person>) {\n    while (males.find { it.matchedTo == null }?.also { match(it) } != null) {\n    }\n}\n\nfun match(male: Person) {\n    while (male.matchedTo == null) {\n        male.preferences.removeAt(0).trySwap(male)\n    }\n}\n\nfun isStableMatch(males: Collection<Person>, females: Collection<Person>): Boolean {\n    return males.all { isStableMatch(it, females) }\n}\n\nfun isStableMatch(male: Person, females: Collection<Person>): Boolean {\n\n    val likesBetter = females.filter { !male.preferences.contains(it) }\n    val stable = !likesBetter.any { it.prefers(male) }\n\n    if (!stable) {\n        println(\"#### Unstable pair: ${male.showMatch()}\")\n    }\n    return stable\n}\n\n\nfun main(args: Array<String>) {\n    val inMales = mapOf(\n            \"abe\" to mutableListOf(\"abi\", \"eve\", \"cath\", \"ivy\", \"jan\", \"dee\", \"fay\", \"bea\", \"hope\", \"gay\"),\n            \"bob\" to mutableListOf(\"cath\", \"hope\", \"abi\", \"dee\", \"eve\", \"fay\", \"bea\", \"jan\", \"ivy\", \"gay\"),\n            \"col\" to mutableListOf(\"hope\", \"eve\", \"abi\", \"dee\", \"bea\", \"fay\", \"ivy\", \"gay\", \"cath\", \"jan\"),\n            \"dan\" to mutableListOf(\"ivy\", \"fay\", \"dee\", \"gay\", \"hope\", \"eve\", \"jan\", \"bea\", \"cath\", \"abi\"),\n            \"ed\" to mutableListOf(\"jan\", \"dee\", \"bea\", \"cath\", \"fay\", \"eve\", \"abi\", \"ivy\", \"hope\", \"gay\"),\n            \"fred\" to mutableListOf(\"bea\", \"abi\", \"dee\", \"gay\", \"eve\", \"ivy\", \"cath\", \"jan\", \"hope\", \"fay\"),\n            \"gav\" to mutableListOf(\"gay\", \"eve\", \"ivy\", \"bea\", \"cath\", \"abi\", \"dee\", \"hope\", \"jan\", \"fay\"),\n            \"hal\" to mutableListOf(\"abi\", \"eve\", \"hope\", \"fay\", \"ivy\", \"cath\", \"jan\", \"bea\", \"gay\", \"dee\"),\n            \"ian\" to mutableListOf(\"hope\", \"cath\", \"dee\", \"gay\", \"bea\", \"abi\", \"fay\", \"ivy\", \"jan\", \"eve\"),\n            \"jon\" to mutableListOf(\"abi\", \"fay\", \"jan\", \"gay\", \"eve\", \"bea\", \"dee\", \"cath\", \"ivy\", \"hope\"))\n\n    val inFemales = mapOf(\n            \"abi\" to listOf(\"bob\", \"fred\", \"jon\", \"gav\", \"ian\", \"abe\", \"dan\", \"ed\", \"col\", \"hal\"),\n            \"bea\" to listOf(\"bob\", \"abe\", \"col\", \"fred\", \"gav\", \"dan\", \"ian\", \"ed\", \"jon\", \"hal\"),\n            \"cath\" to listOf(\"fred\", \"bob\", \"ed\", \"gav\", \"hal\", \"col\", \"ian\", \"abe\", \"dan\", \"jon\"),\n            \"dee\" to listOf(\"fred\", \"jon\", \"col\", \"abe\", \"ian\", \"hal\", \"gav\", \"dan\", \"bob\", \"ed\"),\n            \"eve\" to listOf(\"jon\", \"hal\", \"fred\", \"dan\", \"abe\", \"gav\", \"col\", \"ed\", \"ian\", \"bob\"),\n            \"fay\" to listOf(\"bob\", \"abe\", \"ed\", \"ian\", \"jon\", \"dan\", \"fred\", \"gav\", \"col\", \"hal\"),\n            \"gay\" to listOf(\"jon\", \"gav\", \"hal\", \"fred\", \"bob\", \"abe\", \"col\", \"ed\", \"dan\", \"ian\"),\n            \"hope\" to listOf(\"gav\", \"jon\", \"bob\", \"abe\", \"ian\", \"dan\", \"hal\", \"ed\", \"col\", \"fred\"),\n            \"ivy\" to listOf(\"ian\", \"col\", \"hal\", \"gav\", \"fred\", \"bob\", \"abe\", \"ed\", \"jon\", \"dan\"),\n            \"jan\" to listOf(\"ed\", \"hal\", \"gav\", \"abe\", \"bob\", \"jon\", \"col\", \"ian\", \"fred\", \"dan\"))\n\n\n    fun buildPrefs(person: Person, stringPrefs: List<String>, population: List<Person>) {\n        person.preferences.addAll(\n                stringPrefs.map { name -> population.single { it.name == name } }\n        )\n    }\n\n    val males = inMales.keys.map { Person(it) }\n    val females = inFemales.keys.map { Person(it) }\n\n    males.forEach { buildPrefs(it, inMales[it.name]!!, females) }\n    females.forEach { buildPrefs(it, inFemales[it.name]!!, males) }\n\n\n    match(males)\n    males.forEach { println(it.showMatch()) }\n    println(\"#### match is stable: ${isStableMatch(males, females)}\")\n\n\n    fun swapMatch(male1: Person, male2: Person) {\n        val female1 = male1.matchedTo!!\n        val female2 = male2.matchedTo!!\n\n        male1.matchedTo = female2\n        male2.matchedTo = female1\n\n        female1.matchedTo = male2\n        female2.matchedTo = male1\n    }\n\n    swapMatch(males.single { it.name == \"fred\" }, males.single { it.name == \"jon\" })\n    males.forEach { println(it.showMatch()) }\n    println(\"#### match is stable: ${isStableMatch(males, females)}\")\n}\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":4660}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\nfun a(v: Boolean): Boolean {\n    println(\"'a' called\")\n    return v\n}\n\nfun b(v: Boolean): Boolean {\n    println(\"'b' called\")\n    return v\n}\n\nfun main(args: Array<String>){\n    val pairs = arrayOf(Pair(true, true), Pair(true, false), Pair(false, true), Pair(false, false))\n    for (pair in pairs) {\n        val x = a(pair.first) && b(pair.second)\n        println(\"${pair.first} && ${pair.second} = $x\")\n        val y = a(pair.first) || b(pair.second)\n        println(\"${pair.first} || ${pair.second} = $y\")\n        println()\n    }\n}\n\n\n","human_summarization":"create two functions, a and b, that return the same boolean value they receive as input and print their names when called. The code also calculates the values of two equations, x and y, using these functions. The calculation is done in a way that function b is only called when necessary, utilizing the concept of short-circuit evaluation in boolean expressions. If the programming language doesn't support short-circuit evaluation, nested if statements are used to achieve the same result.","id":4661}
    {"lang_cluster":"Kotlin","source_code":"\n\nimport javax.sound.sampled.AudioFormat\nimport javax.sound.sampled.AudioSystem\n\nval morseCode = hashMapOf(\n        'a' to \".-\", 'b' to \"-...\", 'c' to \"-.-.\",\n        'd' to \"-..\", 'e' to \".\", 'f' to \"..-.\",\n        'g' to \"--.\", 'h' to \"....\", 'i' to \"..\",\n        'j' to \".---\", 'k' to \"-.-\", 'l' to \".-..\",\n        'm' to \"--\", 'n' to \"-.\", 'o' to \"---\",\n        'p' to \".--.\", 'q' to \"--.-\", 'r' to \".-.\",\n        's' to \"...\", 't' to \"-\", 'u' to \"..-\",\n        'v' to \"...-\", 'w' to \".--\", 'x' to \"-..-\",\n        'y' to \"-.--\", 'z' to \"--..\",\n\n        '0' to \".....\", '1' to \"-....\", '2' to \"--...\",\n        '3' to \"---..\", '4' to \"----.\", '5' to \"-----\",\n        '6' to \".----\", '7' to \"..---\", '8' to \"...--\",\n        '9' to \"....-\",\n\n        ' ' to \"\/\", ',' to \"--..--\", '!' to \"-.-.--\",\n        '\"' to \".-..-.\", '.' to \".-.-.-\", '?' to \"..--..\",\n        '\\'' to \".----.\", '\/' to \"-..-.\", '-' to \"-....-\",\n        '(' to \"-.--.-\", ')' to \"-.--.-\"\n)\n\nval symbolDurationInMs = hashMapOf('.' to 200, '-' to 500, '\/' to 1000)\n\n\nfun toMorseCode(message: String) = message.filter { morseCode.containsKey(it) }\n                                          .fold(\"\") { acc, ch -> acc + morseCode[ch]!! }\n\nfun playMorseCode(morseCode: String) = morseCode.forEach { symbol -> beep(symbolDurationInMs[symbol]!!) }\n\nfun beep(durationInMs: Int) {\n    val soundBuffer = ByteArray(durationInMs * 8)\n    for ((i, _) in soundBuffer.withIndex()) {\n        soundBuffer[i] = (Math.sin(i \/ 8.0 * 2.0 * Math.PI) * 80.0).toByte()\n    }\n\n    val audioFormat = AudioFormat(\n            \/*sampleRate*\/ 8000F,\n            \/*sampleSizeInBits*\/ 8,\n            \/*channels*\/ 1,\n            \/*signed*\/ true,\n            \/*bigEndian*\/ false\n    )\n    with (AudioSystem.getSourceDataLine(audioFormat)!!) {\n        open(audioFormat)\n\n        start()\n        write(soundBuffer, 0, soundBuffer.size)\n        drain()\n\n        close()\n    }\n}\n\nfun main(args: Array<String>) {\n    args.forEach {\n        playMorseCode(toMorseCode(it.toLowerCase()))\n    }\n}\n\n","human_summarization":"\"Output: The code converts a given string into audible Morse code, sending it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. It uses Java's Audio API to create a beep method due to lack of easy access to a beep method in Java.\"","id":4662}
    {"lang_cluster":"Kotlin","source_code":"object ABC_block_checker {\n    fun run() {\n        println(\"\\\"\\\": \" + blocks.canMakeWord(\"\"))\n        for (w in words) println(\"$w: \" + blocks.canMakeWord(w))\n    }\n\n    private fun Array<String>.swap(i: Int, j: Int) {\n        val tmp = this[i]\n        this[i] = this[j]\n        this[j] = tmp\n    }\n\n    private fun Array<String>.canMakeWord(word: String): Boolean {\n        if (word.isEmpty())\n            return true\n\n        val c = word.first().toUpperCase()\n        var i = 0\n        forEach { b ->\n            if (b.first().toUpperCase() == c || b[1].toUpperCase() == c) {\n                swap(0, i)\n                if (drop(1).toTypedArray().canMakeWord(word.substring(1)))\n                    return true\n                swap(0, i)\n            }\n            i++\n        }\n\n        return false\n    }\n\n    private val blocks = arrayOf(\n        \"BO\", \"XK\", \"DQ\", \"CP\", \"NA\", \"GT\", \"RE\", \"TG\", \"QD\", \"FS\",\n        \"JW\", \"HU\", \"VI\", \"AN\", \"OB\", \"ER\", \"FS\", \"LY\", \"PC\", \"ZM\"\n    )\n    private val words = arrayOf(\"A\", \"BARK\", \"book\", \"treat\", \"COMMON\", \"SQuAd\", \"CONFUSE\")\n}\n\nfun main(args: Array<String>) = ABC_block_checker.run()\n\n\n","human_summarization":"\"Output: The code defines a function that checks if a given word can be spelled using a specific collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether or not the word can be formed.\"","id":4663}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nimport java.security.MessageDigest\n\nfun main(args: Array<String>) {\n    val text  = \"The quick brown fox jumped over the lazy dog's back\"\n    val bytes = text.toByteArray()\n    val md = MessageDigest.getInstance(\"MD5\")\n    val digest = md.digest(bytes)\n    for (byte in digest) print(\"%02x\".format(byte))\n    println() \n}\n\n\n","human_summarization":"implement an MD5 encoding for a given string. The codes also include an optional validation using test values from IETF RFC (1321) for MD5. However, due to known weaknesses of MD5, alternatives like SHA-256 or SHA-3 are recommended for production-grade cryptography. If the solution is a library, refer to MD5\/Implementation for a scratch implementation.","id":4664}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\nclass Oid(val id: String): Comparable<Oid> {\n    override fun compareTo(other: Oid): Int {\n        val splits1 = this.id.split('.')\n        val splits2 = other.id.split('.')\n        val minSize = if (splits1.size < splits2.size) splits1.size else splits2.size\n        for (i in 0 until minSize) {\n            if (splits1[i].toInt() < splits2[i].toInt()) return -1\n            else if (splits1[i].toInt() > splits2[i].toInt()) return 1\n        }\n        return splits1.size.compareTo(splits2.size)\n    }\n\n    override fun toString() = id\n}\n\nfun main(args: Array<String>) {\n    val oids = arrayOf(\n        Oid(\"1.3.6.1.4.1.11.2.17.19.3.4.0.10\"),\n        Oid(\"1.3.6.1.4.1.11.2.17.5.2.0.79\"),\n        Oid(\"1.3.6.1.4.1.11.2.17.19.3.4.0.4\"),\n        Oid(\"1.3.6.1.4.1.11150.3.4.0.1\"),\n        Oid(\"1.3.6.1.4.1.11.2.17.19.3.4.0.1\"),\n        Oid(\"1.3.6.1.4.1.11150.3.4.0\")\n    )\n    println(oids.sorted().joinToString(\"\\n\"))\n}\n\n\n","human_summarization":"sort a list of Object Identifiers (OIDs) in their natural lexicographical order. The OIDs are strings of non-negative integers separated by dots.","id":4665}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.2.21\n\nimport java.net.Socket\n\nfun main(args: Array<String>) {\n    val sock = Socket(\"localhost\", 256)\n    sock.use {\n        it.outputStream.write(\"hello socket world\".toByteArray())\n    }\n}\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":4666}
    {"lang_cluster":"Kotlin","source_code":"\n\n\/\/ version 1.1.4-3\n\nimport java.util.Properties\nimport javax.mail.Authenticator\nimport javax.mail.PasswordAuthentication\nimport javax.mail.Session\nimport javax.mail.internet.MimeMessage\nimport javax.mail.internet.InternetAddress\nimport javax.mail.Message.RecipientType\nimport javax.mail.Transport\n\nfun sendEmail(user: String, tos: Array<String>, ccs: Array<String>, title: String,\n              body: String, password: String) {\n    val props = Properties()\n    val host = \"smtp.gmail.com\"\n    with (props) {\n        put(\"mail.smtp.host\", host)\n        put(\"mail.smtp.port\", \"587\") \/\/ for TLS\n        put(\"mail.smtp.auth\", \"true\")\n        put(\"mail.smtp.starttls.enable\", \"true\")\n    }\n    val auth = object: Authenticator() {\n        protected override fun getPasswordAuthentication() =\n            PasswordAuthentication(user, password)\n    }\n    val session = Session.getInstance(props, auth)\n    val message = MimeMessage(session)\n    with (message) {\n        setFrom(InternetAddress(user))\n        for (to in tos) addRecipient(RecipientType.TO, InternetAddress(to))\n        for (cc in ccs) addRecipient(RecipientType.TO, InternetAddress(cc))\n        setSubject(title)\n        setText(body)\n    }\n    val transport = session.getTransport(\"smtp\")\n    with (transport) {\n        connect(host, user, password)\n        sendMessage(message, message.allRecipients)\n        close()\n    }\n}\n\nfun main(args: Array<String>) {\n    val user = \"some.user@gmail.com\"\n    val tos = arrayOf(\"other.user@otherserver.com\")\n    val ccs = arrayOf<String>()\n    val title = \"Rosetta Code Example\"\n    val body = \"This is just a test email\"\n    val password = \"secret\"\n    sendEmail(user, tos, ccs, title, body, password)\n}\n\n","human_summarization":"The code is a function that sends an email, allowing parameters for From, To, Cc addresses, Subject, message text, and optional server name and login details. It uses libraries or functions from the language, with potential for external programs. It also considers portability across operating systems. The function may provide notifications for problems\/success. It requires 'javax.mail.jar' on the system and classpath, and may need 'access for less secure apps' enabled for Google SMTP Server.","id":4667}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/  version 1.1\n\n\/\/  counts up to 177 octal i.e. 127 decimal\nfun main(args: Array<String>) {\n    (0..Byte.MAX_VALUE).forEach { println(\"%03o\".format(it)) }\n}\n\n\n","human_summarization":"generate a sequential count in octal starting from zero, incrementing by one for each consecutive number, and stopping when the maximum value of the numeric type in use is reached. Each number is printed on a separate line.","id":4668}
    {"lang_cluster":"Kotlin","source_code":"\n\nfun <T> swap(t1: T, t2: T) = Pair(t2, t1)\n\nfun main() {\n    var a = 3\n    var b = 4\n    val c = swap(a, b) \/\/ infers that swap<Int> be used\n    a = c.first\n    b = c.second\n    println(\"a = $a\")\n    println(\"b = $b\")\n    var d = false\n    var e = true\n    val f = swap(d, e) \/\/ infers that swap<Boolean> be used\n    d = f.first\n    e = f.second\n    println(\"d = $d\")\n    println(\"e = $e\")\n}\n\n\n","human_summarization":"implement a generic swap function or operator that can exchange the values of two variables or storage places, regardless of their types. The function handles static and dynamic types, and also addresses issues related to parametric polymorphism. In the case of Kotlin, an alternative method using a container class is also provided.","id":4669}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.1.2\n\n\/* These functions deal automatically with Unicode as all strings are UTF-16 encoded in Kotlin *\/\n\nfun isExactPalindrome(s: String) = (s == s.reversed())\n\nfun isInexactPalindrome(s: String): Boolean {\n    var t = \"\"\n    for (c in s) if (c.isLetterOrDigit()) t += c\n    t = t.toLowerCase()\n    return t == t.reversed()\n}\n\nfun main(args: Array<String>) {\n    val candidates = arrayOf(\"rotor\", \"rosetta\", \"step on no pets\", \"\u00e9t\u00e9\")\n    for (candidate in candidates) {\n        println(\"'$candidate' is ${if (isExactPalindrome(candidate)) \"an\" else \"not an\"} exact palindrome\")\n    }\n    println()\n    val candidates2 = arrayOf(\n         \"In girum imus nocte et consumimur igni\",\n         \"Rise to vote, sir\",\n         \"A man, a plan, a canal - Panama!\",\n         \"Ce rep\u00e8re, Perec\"  \/\/ note: '\u00e8' considered a distinct character from 'e'\n    )\n    for (candidate in candidates2) {\n        println(\"'$candidate' is ${if (isInexactPalindrome(candidate)) \"an\" else \"not an\"} inexact palindrome\")\n    }\n}\n\n","human_summarization":"implement a function to check if a given sequence of characters is a palindrome. It also supports Unicode characters. Additionally, it includes a second function to detect inexact palindromes, ignoring white-space, punctuation, and case-sensitivity. It may also be useful for testing a function.","id":4670}
    {"lang_cluster":"Kotlin","source_code":"\n\/\/ version 1.0.6\n\n\/\/ tested on Windows 10\n\nfun main(args: Array<String>) {\n   println(System.getenv(\"SystemRoot\"))\n}\n\n\n","human_summarization":"\"Demonstrates how to retrieve a process's environment variables such as PATH, HOME, or USER in a Unix system.\"","id":4671}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.5\n\nfrom collections import deque\nstack = deque()\nstack.append(value) # pushing\nvalue = stack.pop()\nnot stack # is empty?\n\nfrom collections import deque\n\nclass Stack:\n    def __init__(self):\n        self._items = deque()\n    def append(self, item):\n        self._items.append(item)\n    def pop(self):\n        return self._items.pop()\n    def __nonzero__(self):\n        return bool(self._items)\n\nclass Stack:\n    def __init__(self):\n        self._first = None\n    def __nonzero__(self):\n        return self._first is not None \n    def append(self, value):\n        self._first = (value, self._first)\n    def pop(self):\n        if self._first is None:\n            raise IndexError, \"pop from empty stack\"\n        value, self._first = self._first\n        return value\n\nwhile not stack.empty():\n\nwhile stack:\n\n","human_summarization":"implement a stack data structure supporting basic operations such as push, pop, and empty check. The stack follows a last in, first out (LIFO) access policy. The implementation can be done using a deque for faster performance or a linked list for a simpler interface.","id":4672}
    {"lang_cluster":"Python","source_code":"\n\nfrom math import *\n\ndef analytic_fibonacci(n):\n  sqrt_5 = sqrt(5);\n  p = (1 + sqrt_5) \/ 2;\n  q = 1\/p;\n  return int( (p**n + q**n) \/ sqrt_5 + 0.5 )\n\nfor i in range(1,31):\n  print analytic_fibonacci(i),\n\n1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040\n\ndef fibIter(n):\n    if n < 2:\n        return n\n    fibPrev = 1\n    fib = 1\n    for _ in range(2, n):\n        fibPrev, fib = fib, fib + fibPrev\n    return fib\ndef fib(n,x=[0,1]):\n   for i in range(abs(n)-1): x=[x[1],sum(x)]\n   return x[1]*pow(-1,abs(n)-1) if n<0 else x[1] if n else 0\n\nfor i in range(-30,31): print fib(i),\n\n-832040 514229 -317811 196418 -121393 75025 -46368 28657 -17711 10946 -6765 4181 -2584 1597 -987 \n610 -377 233 -144 89 -55 34 -21 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 \n1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040\n\ndef fibRec(n):\n    if n < 2:\n        return n\n    else:\n        return fibRec(n-1) + fibRec(n-2)\ndef fibMemo():\n    pad = {0:0, 1:1}\n    def func(n):\n        if n not in pad:\n            pad[n] = func(n-1) + func(n-2)\n        return pad[n]\n    return func\n\nfm = fibMemo()\nfor i in range(1,31):\n    print fm(i),\n\n1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040\n\n\ndef fibFastRec(n):\n    def fib(prvprv, prv, c):\n        if c < 1: \n            return prvprv\n        else: \n            return fib(prv, prvprv + prv, c - 1) \n    return fib(0, 1, n)\n\ndef fibGen(n):\n    a, b = 0, 1\n    while n>0:\n        yield a\n        a, b, n = b, a+b, n-1\n>>> [i for i in fibGen(11)]\n\n[0,1,1,2,3,5,8,13,21,34,55]\n\ndef prevPowTwo(n):\n    'Gets the power of two that is less than or equal to the given input'\n    if ((n & -n) == n):\n        return n\n    else:\n        n -= 1\n        n |= n >> 1\n        n |= n >> 2\n        n |= n >> 4\n        n |= n >> 8\n        n |= n >> 16\n        n += 1\n        return (n\/2)\n\ndef crazyFib(n):\n    'Crazy fast fibonacci number calculation'\n    powTwo = prevPowTwo(n)\n    \n    q = r = i = 1\n    s = 0\n    \n    while(i < powTwo):\n        i *= 2\n        q, r, s = q*q + r*r, r * (q + s), (r*r + s*s)\n        \n    while(i < n):\n        i += 1\n        q, r, s = q+r, q, r\n        \n    return q\n\ndef fib(n, c={0:1, 1:1}):\n    if n not in c:\n        x = n \/\/ 2\n        c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x)\n    return c[n]\n\nfib(10000000)  # calculating it takes a few seconds, printing it takes eons\n\nF = {0: 0, 1: 1, 2: 1}\ndef fib(n):\n    if n in F:\n        return F[n]\n    f1 = fib(n \/\/ 2 + 1)\n    f2 = fib((n - 1) \/\/ 2)\n    F[n] = (f1 * f1 + f2 * f2 if n & 1 else f1 * f1 - f2 * f2)\n    return F[n]\n\ndef fib():\n    \"\"\"Yield fib[n+1] + fib[n]\"\"\"\n    yield 1  # have to start somewhere\n    lhs, rhs = fib(), fib()\n    yield next(lhs) # move lhs one iteration ahead\n    while True:\n        yield next(lhs)+next(rhs)\n\nf=fib()\nprint [next(f) for _ in range(9)]\n\n[1, 1, 2, 3, 5, 8, 13, 21, 34]\n\nfrom itertools import islice\n\ndef fib():\n    yield 0\n    yield 1\n    a, b = fib(), fib()\n    next(b)\n    while True:\n        yield next(a)+next(b)\n \nprint(tuple(islice(fib(), 10)))\n\nWorks with: Python version 3.7\n'''Fibonacci accumulation'''\n\nfrom itertools import accumulate, chain\nfrom operator import add\n\n\n# fibs\u00a0:: Integer\u00a0:: [Integer]\ndef fibs(n):\n    '''An accumulation of the first n integers in\n       the Fibonacci series. The accumulator is a\n       pair of the two preceding numbers.\n    '''\n    def go(ab, _):\n        return ab[1], add(*ab)\n\n    return [xy[1] for xy in accumulate(\n        chain(\n            [(0, 1)],\n            range(1, n)\n        ),\n        go\n    )]\n\n\n# MAIN ---\nif __name__ == '__main__':\n    print(\n        'First twenty: ' + repr(\n            fibs(20)\n        )\n    )\n\n","human_summarization":"generates the nth Fibonacci number. The function can be implemented either iteratively or recursively. Recursive solutions, while educational, are generally slower. The function optionally supports negative numbers using a simple inverse of the positive definition. The code uses a matrix-based approach for efficiency and can be further optimized by caching the generator results. The Fibonacci sequence can also be defined as a scan or accumulation, and the code utilizes functools.reduce for an efficient rewrite if only the nth term is needed. The code is mindful of memory usage and execution speed.","id":4673}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.4\nvalues = range(10)\nevens = [x for x in values if not x & 1]\nievens = (x for x in values if not x & 1) # lazy\n# alternately but less idiomatic:\nevens = filter(lambda x: not x & 1, values)\n\nvalues = range(10)\nevens = values[::2]\n\nvalues = range(10)\nvalues[::2] = [11,13,15,17,19]\nprint values\n11, 1, 13, 3, 15, 5, 17, 7, 19, 9\n\nWorks with: Python version 3\n'''Functional filtering - by descending generality and increasing brevity'''\n\nfrom functools import (reduce)\nfrom itertools import (chain)\nimport inspect\nimport re\n\n\ndef f1(xs):\n    '''Catamorphism: fold \/ reduce.\n       See [The expressiveness and universality of fold]\n       (http:\/\/www.cs.nott.ac.uk\/~pszgmh\/fold.pdf)'''\n    return reduce(lambda a, x: a + [x] if even(x) else a, xs, [])\n\n\ndef f2(xs):\n    '''List monad bind\/inject operator (concatMap combined with\n       an (a -> [b]) function which wraps its result in a\n       possibly empty list). This is the universal abstraction\n       which underlies list comprehensions.'''\n    return concatMap(lambda x: [x] if even(x) else [])(xs)\n\n\ndef f3(xs):\n    '''Built-in syntactic sugar for list comprehensions.\n       Convenient, and encouraged as 'Pythonic',\n       but less general and expressive than a fold.'''\n    return (x for x in xs if even(x))\n\n\ndef f4(xs):\n    '''Built-in filter function'''\n    return filter(even, xs)\n\n\ndef main():\n    '''Tests'''\n    xs = enumFromTo(0)(10)\n    print(\n        tabulated(showReturn)(\n            'By descending generality and increasing brevity:\\n'\n        )(\n            lambda f: list(f(xs))\n        )([f1, f2, f3, f4])\n    )\n\n\n# GENERIC -------------------------------------------------\n\n\n# concatMap\u00a0:: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n    '''Concatenated list over which a function has been mapped.\n       The list monad can be derived by using a function of the type\n       (a -> [b]) which wraps its output in list\n       (using an empty list to represent computational failure).'''\n    return lambda xs: list(\n        chain.from_iterable(\n            map(f, xs)\n        )\n    )\n\n\n# enumFromTo\u00a0:: (Int, Int) -> [Int]\ndef enumFromTo(m):\n    '''Integer enumeration from m to n.'''\n    return lambda n: list(range(m, 1 + n))\n\n\n# even\u00a0:: Int -> Bool\ndef even(x):\n    '''Predicate'''\n    return 0 == x\u00a0% 2\n\n\n# showReturn\u00a0:: (a -> b) -> String\ndef showReturn(f):\n    '''Stringification of final (return) expression in function body.'''\n    return re.split('return ', inspect.getsource(f))[-1].strip()\n\n\n# tabulated\u00a0:: (a -> String) -> String -> (a -> b) -> [a] -> String\ndef tabulated(fShow):\n    '''heading -> function -> input List -> tabulated output string'''\n    def go(s, f, xs):\n        w = max(len(fShow(x)) for x in xs)\n        return s + '\\n' + '\\n'.join([\n            fShow(x).rjust(w, ' ') +\n            ' -> ' + str(f(x)) for x in xs\n        ])\n    return lambda s: lambda f: lambda xs: go(s, f, xs)\n\n\nif __name__ == '__main__':\n    main()\n\n","human_summarization":"select specific elements from an array into a new array, with an example of selecting all even numbers. It also provides an alternative solution that modifies the original array. The code uses Python's slice syntax with an optional stride expression to filter elements from the array. It also demonstrates how slicing can be used with strings and how to assign to a slice.","id":4674}
    {"lang_cluster":"Python","source_code":"\n\n>>> s = 'abcdefgh'\n>>> n, m, char, chars = 2, 3, 'd', 'cd'\n>>> # starting from n=2 characters in and m=3 in length;\n>>> s[n-1:n+m-1]\n'bcd'\n>>> # starting from n characters in, up to the end of the string;\n>>> s[n-1:]\n'bcdefgh'\n>>> # whole string minus last character;\n>>> s[:-1]\n'abcdefg'\n>>> # starting from a known character char=\"d\" within the string and of m length;\n>>> indx = s.index(char)\n>>> s[indx:indx+m]\n'def'\n>>> # starting from a known substring chars=\"cd\" within the string and of m length. \n>>> indx = s.index(chars)\n>>> s[indx:indx+m]\n'cde'\n>>>\n\n","human_summarization":"The code extracts and displays substrings from a given string in various ways: from a specified character index with a specified length, from a specified character index to the end of the string, excluding the last character of the string, from a known character with a specified length, and from a known substring with a specified length. The code supports any valid Unicode code point and uses logical characters, not 8-bit or 16-bit code units. It does not support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP. The code uses zero-based indexing.","id":4675}
    {"lang_cluster":"Python","source_code":"\ninput()[::-1]\nstring[::-1]\n\n''.join(reversed(string))\n\nimport unicodedata\n\ndef ureverse(ustring):\n    'Reverse a string including unicode combining characters'\n    groupedchars = []\n    uchar = list(ustring)\n    while uchar:\n        if unicodedata.combining(uchar[0])\u00a0!= 0:\n            groupedchars[-1] += uchar.pop(0)\n        else:\n            groupedchars.append(uchar.pop(0))\n    # Grouped reversal\n    groupedchars = groupedchars[::-1]\n \n    return ''.join(groupedchars)\n\ndef say_string(s):\n    return ' '.join([s, '=', ' | '.join(unicodedata.name(ch, '') for ch in s)])\n\ndef say_rev(s):\n    print(f\"Input:              {say_string(s)}\")\n    print(f\"Character reversed: {say_string(s[::-1])}\")\n    print(f\"Unicode reversed:   {say_string(ureverse(s))}\")\n    print(f\"Unicode reverse\u00b2:   {say_string(ureverse(ureverse(s)))}\")\n        \nif __name__ == '__main__':\n    ucode = ''.join(chr(int(n[2:], 16)) for n in \n                     'U+0041 U+030A U+0073 U+0074 U+0072 U+006F U+0308 U+006D'.split())\n    say_rev(ucode)\n\n","human_summarization":"take a string as input, reverse the string while preserving the order of Unicode combining characters, and return the reversed string.","id":4676}
    {"lang_cluster":"Python","source_code":"from string import ascii_uppercase\nfrom itertools import product\nfrom re import findall\n\ndef uniq(seq):\n    seen = {}\n    return [seen.setdefault(x, x) for x in seq if x not in seen]\n\ndef partition(seq, n):\n    return [seq[i : i + n] for i in xrange(0, len(seq), n)]\n\n\n\"\"\"Instantiate a specific encoder\/decoder.\"\"\"\ndef playfair(key, from_ = 'J', to = None):\n    if to is None:\n        to = 'I' if from_ == 'J' else ''\n\n    def canonicalize(s):\n        return filter(str.isupper, s.upper()).replace(from_, to)\n\n    # Build 5x5 matrix.\n    m = partition(uniq(canonicalize(key + ascii_uppercase)), 5)\n\n    # Pregenerate all forward translations.\n    enc = {}\n\n    # Map pairs in same row.\n    for row in m:\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[row[i] + row[j]] = row[(i + 1) % 5] + row[(j + 1) % 5]\n\n    # Map pairs in same column.\n    for c in zip(*m):\n        for i, j in product(xrange(5), repeat=2):\n            if i != j:\n                enc[c[i] + c[j]] = c[(i + 1) % 5] + c[(j + 1) % 5]\n\n    # Map pairs with cross-connections.\n    for i1, j1, i2, j2 in product(xrange(5), repeat=4):\n        if i1 != i2 and j1 != j2:\n            enc[m[i1][j1] + m[i2][j2]] = m[i1][j2] + m[i2][j1]\n\n    # Generate reverse translations.\n    dec = dict((v, k) for k, v in enc.iteritems())\n\n    def sub_enc(txt):\n        lst = findall(r\"(.)(?:(?!\\1)(.))?\", canonicalize(txt))\n        return \" \".join(enc[a + (b if b else 'X')] for a, b in lst)\n\n    def sub_dec(encoded):\n        return \" \".join(dec[p] for p in partition(canonicalize(encoded), 2))\n\n    return sub_enc, sub_dec\n\n\n(encode, decode) = playfair(\"Playfair example\")\norig = \"Hide the gold in...the TREESTUMP!!!\"\nprint \"Original:\", orig\nenc = encode(orig)\nprint \"Encoded:\", enc\nprint \"Decoded:\", decode(enc)\n\n\n","human_summarization":"Implement the Playfair cipher for both encryption and decryption. It allows the user to choose whether 'J' equals 'I' or there's no 'Q' in the alphabet. The resulting encrypted and decrypted messages are presented in capitalized digraphs, separated by spaces.","id":4677}
    {"lang_cluster":"Python","source_code":"\n\nfrom collections import namedtuple, deque\nfrom pprint import pprint as pp\n \n \ninf = float('inf')\nEdge = namedtuple('Edge', ['start', 'end', 'cost'])\n \nclass Graph():\n    def __init__(self, edges):\n        self.edges = [Edge(*edge) for edge in edges]\n        # print(dir(self.edges[0]))\n        self.vertices = {e.start for e in self.edges} | {e.end for e in self.edges}\n \n    def dijkstra(self, source, dest):\n        assert source in self.vertices\n        dist = {vertex: inf for vertex in self.vertices}\n        previous = {vertex: None for vertex in self.vertices}\n        dist[source] = 0\n        q = self.vertices.copy()\n        neighbours = {vertex: set() for vertex in self.vertices}\n        for start, end, cost in self.edges:\n            neighbours[start].add((end, cost))\n            neighbours[end].add((start, cost))\n\n        #pp(neighbours)\n \n        while q:\n            # pp(q)\n            u = min(q, key=lambda vertex: dist[vertex])\n            q.remove(u)\n            if dist[u] == inf or u == dest:\n                break\n            for v, cost in neighbours[u]:\n                alt = dist[u] + cost\n                if alt < dist[v]:                                  # Relax (u,v,a)\n                    dist[v] = alt\n                    previous[v] = u\n        #pp(previous)\n        s, u = deque(), dest\n        while previous[u]:\n            s.appendleft(u)\n            u = previous[u]\n        s.appendleft(u)\n        return s\n \n \ngraph = Graph([(\"a\", \"b\", 7),  (\"a\", \"c\", 9),  (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n               (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2),  (\"d\", \"e\", 6),\n               (\"e\", \"f\", 9)])\npp(graph.dijkstra(\"a\", \"e\"))\n\n\n","human_summarization":"Implement Dijkstra's algorithm to find the shortest path from a given source node to all other nodes in a graph. The graph is represented by an adjacency matrix or list and a start node. The algorithm outputs a set of edges that depict the shortest path to each reachable node from the origin. The code also includes functionality to interpret the output and display the shortest path from the source node to specific nodes.","id":4678}
    {"lang_cluster":"Python","source_code":"\n\nfrom collections import namedtuple\nfrom math import sqrt\n\nPt = namedtuple('Pt', 'x, y')\nCircle = Cir = namedtuple('Circle', 'x, y, r')\n\ndef circles_from_p1p2r(p1, p2, r):\n    'Following explanation at http:\/\/mathforum.org\/library\/drmath\/view\/53027.html'\n    if r == 0.0:\n        raise ValueError('radius of zero')\n    (x1, y1), (x2, y2) = p1, p2\n    if p1 == p2:\n        raise ValueError('coincident points gives infinite number of Circles')\n    # delta x, delta y between points\n    dx, dy = x2 - x1, y2 - y1\n    # dist between points\n    q = sqrt(dx**2 + dy**2)\n    if q > 2.0*r:\n        raise ValueError('separation of points > diameter')\n    # halfway point\n    x3, y3 = (x1+x2)\/2, (y1+y2)\/2\n    # distance along the mirror line\n    d = sqrt(r**2-(q\/2)**2)\n    # One answer\n    c1 = Cir(x = x3 - d*dy\/q,\n             y = y3 + d*dx\/q,\n             r = abs(r))\n    # The other answer\n    c2 = Cir(x = x3 + d*dy\/q,\n             y = y3 - d*dx\/q,\n             r = abs(r))\n    return c1, c2\n\nif __name__ == '__main__':\n    for p1, p2, r in [(Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 2.0),\n                      (Pt(0.0000, 2.0000), Pt(0.0000, 0.0000), 1.0),\n                      (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 2.0),\n                      (Pt(0.1234, 0.9876), Pt(0.8765, 0.2345), 0.5),\n                      (Pt(0.1234, 0.9876), Pt(0.1234, 0.9876), 0.0)]:\n        print('Through points:\\n  %r,\\n  %r\\n  and radius %f\\nYou can construct the following circles:'\n              % (p1, p2, r))\n        try:\n            print('  %r\\n  %r\\n' % circles_from_p1p2r(p1, p2, r))\n        except ValueError as v:\n            print('  ERROR: %s\\n' % (v.args[0],))\n\n\n","human_summarization":"The code defines a function that calculates and returns two circles that can be drawn through two given points with a specified radius. The function handles special cases such as when the radius is zero, the points are coincident, the points form a diameter, or the points are too far apart. The function raises a ValueError for these special cases and uses try-except to handle these exceptions. It also includes a task to calculate the total area of the circles. The function's output for specific inputs is also demonstrated.","id":4679}
    {"lang_cluster":"Python","source_code":"k8 = [\t14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 ] \nk7 = [\t15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 ]\nk6 = [\t10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 ]\nk5 = [\t 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 ]\nk4 = [\t 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 ]\nk3 = [\t12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 ]\nk2 = [\t 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 ]\nk1 = [\t13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 ]\n \nk87 = [0] * 256\nk65 = [0] * 256\nk43 = [0] * 256\nk21 = [0] * 256\n \ndef kboxinit():\n\tfor i in range(256):\n\t\tk87[i] = k8[i >> 4] << 4 | k7[i & 15]\n\t\tk65[i] = k6[i >> 4] << 4 | k5[i & 15]\n\t\tk43[i] = k4[i >> 4] << 4 | k3[i & 15]\n\t\tk21[i] = k2[i >> 4] << 4 | k1[i & 15]\n \ndef f(x):\n\tx = ( k87[x>>24 & 255] << 24 | k65[x>>16 & 255] << 16 |\n\t      k43[x>> 8 & 255] <<  8 | k21[x & 255] )\n\treturn x<<11 | x>>(32-11)\n\n","human_summarization":"Implement the main step of the GOST 28147-89 symmetric encryption algorithm, which involves taking a 64-bit block of text and one of the eight 32-bit encryption key elements, using a replacement table, and returning an encrypted block.","id":4680}
    {"lang_cluster":"Python","source_code":"\nfrom random import randrange\n\nwhile True:\n    a = randrange(20)\n    print(a)\n    if a == 10:\n        break\n    b = randrange(20)\n    print(b)\n\n","human_summarization":"generate and print random numbers from 0 to 19. If the generated number is 10, the loop stops. If the number is not 10, a second random number is generated and printed before the loop restarts. If 10 is never generated, the loop runs indefinitely.","id":4681}
    {"lang_cluster":"Python","source_code":"\ndef is_prime(number):\n    return True # code omitted - see Primality by Trial Division\n\ndef m_factor(p):\n    max_k = 16384 \/ p # arbitrary limit; since Python automatically uses long's, it doesn't overflow\n    for k in xrange(max_k):\n        q = 2*p*k + 1\n        if not is_prime(q):\n            continue\n        elif q % 8 != 1 and q % 8 != 7:\n            continue\n        elif pow(2, p, q) == 1:\n            return q\n    return None\n\nif __name__ == '__main__':\n    exponent = int(raw_input(\"Enter exponent of Mersenne number: \"))\n    if not is_prime(exponent):\n        print \"Exponent is not prime: %d\" % exponent\n    else:\n        factor = m_factor(exponent)\n        if not factor:\n            print \"No factor found for M%d\" % exponent\n        else:\n            print \"M%d has a factor: %d\" % (exponent, factor)\n\n\nExample:\nEnter exponent of Mersenne number: 929\nM929 has a factor: 13007\n\n","human_summarization":"implement a method to find a factor of a Mersenne number (in this case, M929). The method uses efficient algorithms to determine if a number divides 2P-1, including a self-implemented modPow operation. It also incorporates properties of Mersenne numbers to refine the process, such as the form of any factor q of 2P-1 and the conditions that q must meet. The method stops when 2kP+1 > sqrt(N). It only works on Mersenne numbers where P is prime.","id":4682}
    {"lang_cluster":"Python","source_code":"\n# Python has basic xml parsing built in\n\nfrom xml.dom import minidom\n\nxmlfile = file(\"test3.xml\") # load xml document from file \nxmldoc = minidom.parse(xmlfile).documentElement # parse from file stream or...\nxmldoc = minidom.parseString(\"<inventory title=\"OmniCorp Store #45x10^3\">...<\/inventory>\").documentElement # alternatively, parse a string\n\t\n#  1st Task: Retrieve the first \"item\" element\ni = xmldoc.getElementsByTagName(\"item\") # get a list of all \"item\" tags\nfirstItemElement = i[0] # get the first element\n\n# 2nd task: Perform an action on each \"price\" element (print it out)\nfor j in xmldoc.getElementsByTagName(\"price\"): # get a list of all \"price\" tags\n\tprint j.childNodes[0].data # XML Element . TextNode . data of textnode\n\n# 3rd Task: Get an array of all the \"name\" elements\nnamesArray = xmldoc.getElementsByTagName(\"name\")\n\n\nimport xml.etree.ElementTree as ET\n\nxml = open('inventory.xml').read()\ndoc = ET.fromstring(xml)\n\ndoc = ET.parse('inventory.xml')  # or load it directly\n\n# Note, ElementTree's root is the top level element. So you need \".\/\/\" to really start searching from top\n\n# Return first Item\nitem1 = doc.find(\"section\/item\")  # or \".\/\/item\"\n\n# Print each price\nfor p in doc.findall(\"section\/item\/price\"):  # or \".\/\/price\"\n    print \"{0:0.2f}\".format(float(p.text))  # could raise exception on missing text or invalid float() conversion\n\n# list of names\nnames = doc.findall(\"section\/item\/name\")  # or \".\/\/name\"\n\n\nfrom lxml import etree\n\nxml = open('inventory.xml').read()\ndoc = etree.fromstring(xml)\n\ndoc = etree.parse('inventory.xml')  # or load it directly\n\n# Return first item\nitem1 = doc.xpath(\"\/\/section[1]\/item[1]\")\n\n# Print each price\nfor p in doc.xpath(\"\/\/price\"):\n    print \"{0:0.2f}\".format(float(p.text))  # could raise exception on missing text or invalid float() conversion\n\nnames = doc.xpath(\"\/\/name\")  # list of names\n\n","human_summarization":"The code performs three XPath queries on an XML document: it retrieves the first \"item\" element, prints out each \"price\" element, and gathers an array of all the \"name\" elements. The XML document represents an inventory of a store. The code can be executed using Python 2.5+ with ElementTree's limited XPath support or with the lxml package for full XPath support.","id":4683}
    {"lang_cluster":"Python","source_code":"\n\nWorks with: Python version 2.7+ and 3.0+\n>>> s1, s2 = {1, 2, 3, 4}, {3, 4, 5, 6}\n>>> s1 | s2 # Union\n{1, 2, 3, 4, 5, 6}\n>>> s1 & s2 # Intersection\n{3, 4}\n>>> s1 - s2 # Difference\n{1, 2}\n>>> s1 < s1 # True subset\nFalse\n>>> {3, 1} < s1 # True subset\nTrue\n>>> s1 <= s1 # Subset\nTrue\n>>> {3, 1} <= s1 # Subset\nTrue\n>>> {3, 2, 4, 1} == s1 # Equality\nTrue\n>>> s1 == s2 # Equality\nFalse\n>>> 2 in s1 # Membership\nTrue\n>>> 10 not in s1 # Non-membership\nTrue\n>>> {1, 2, 3, 4, 5} > s1 # True superset\nTrue\n>>> {1, 2, 3, 4} > s1 # True superset\nFalse\n>>> {1, 2, 3, 4} >= s1 # Superset\nTrue\n>>> s1 ^ s2 # Symmetric difference\n{1, 2, 5, 6}\n>>> len(s1) # Cardinality\n4\n>>> s1.add(99) # Mutability\n>>> s1\n{99, 1, 2, 3, 4}\n>>> s1.discard(99) # Mutability\n>>> s1\n{1, 2, 3, 4}\n>>> s1 |= s2 # Mutability\n>>> s1\n{1, 2, 3, 4, 5, 6}\n>>> s1 -= s2 # Mutability\n>>> s1\n{1, 2}\n>>> s1 ^= s2 # Mutability\n>>> s1\n{1, 2, 3, 4, 5, 6}\n>>>\n\n","human_summarization":"demonstrate various set operations such as creation, checking if an element is part of a set, union, intersection, difference, subset, and equality. It also optionally showcases other set operations and methods to modify a mutable set. The implementation can be done using an associative array, binary search tree, hash table, or binary bits. It also includes the usage of sets and frozensets in Python, with syntax for set literals supported from Python 2.7 and 3.0 onwards.","id":4684}
    {"lang_cluster":"Python","source_code":"\nfrom calendar import weekday, SUNDAY\n\n[year for year in range(2008, 2122) if weekday(year, 12, 25) == SUNDAY]\n\n","human_summarization":"\"Determines the years between 2008 and 2121 where Christmas falls on a Sunday using standard date handling libraries. It also compares the results with other languages to identify any anomalies in date handling, such as overflow issues similar to Y2K problems. The function uses the proleptic Gregorian calendar for all dates between 1\/1\/1 and 9999\/12\/31, with no gap between 1582\/10\/4 and 1582\/10\/15.\"","id":4685}
    {"lang_cluster":"Python","source_code":"\nLibrary: NumPy\n\n#!\/usr\/bin\/env python3\n\nimport numpy as np\n\ndef qr(A):\n    m, n = A.shape\n    Q = np.eye(m)\n    for i in range(n - (m == n)):\n        H = np.eye(m)\n        H[i:, i:] = make_householder(A[i:, i])\n        Q = np.dot(Q, H)\n        A = np.dot(H, A)\n    return Q, A\n\ndef make_householder(a):\n    v = a \/ (a[0] + np.copysign(np.linalg.norm(a), a[0]))\n    v[0] = 1\n    H = np.eye(a.shape[0])\n    H -= (2 \/ np.dot(v, v)) * np.dot(v[:, None], v[None, :])\n    return H\n\n# task 1: show qr decomp of wp example\na = np.array(((\n    (12, -51,   4),\n    ( 6, 167, -68),\n    (-4,  24, -41),\n)))\n\nq, r = qr(a)\nprint('q:\\n', q.round(6))\nprint('r:\\n', r.round(6))\n\n# task 2: use qr decomp for polynomial regression example\ndef polyfit(x, y, n):\n    return lsqr(x[:, None]**np.arange(n + 1), y.T)\n\ndef lsqr(a, b):\n    q, r = qr(a)\n    _, n = r.shape\n    return np.linalg.solve(r[:n, :], np.dot(q.T, b)[:n])\n\nx = np.array((0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10))\ny = np.array((1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321))\n\nprint('\\npolyfit:\\n', polyfit(x, y, 2))\n\n\n","human_summarization":"implement QR decomposition of a matrix using the method of Householder reflections. The code demonstrates the decomposition on a given example matrix and shows its usage for solving linear least squares problems. The code also includes a reimplementation of the Numpy's QR function to illustrate the construction and use of Householder reflections.","id":4686}
    {"lang_cluster":"Python","source_code":"\n\nitems = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = list(set(items))\n\nitems = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = []\nhelperset = set()\nfor x in items:\n    if x not in helperset:\n        unique.append(x)\n        helperset.add(x)\n\nimport itertools\nitems = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = [k for k,g in itertools.groupby(sorted(items))]\n\nitems = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']\nunique = []\nfor x in items:\n    if x not in unique:\n        unique.append(x)\n\nfrom collections import OrderedDict as od\n\nprint(list(od.fromkeys([1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']).keys()))\n\nfrom itertools import (groupby)\n\n\n# nubByKey\u00a0:: (a -> b) -> [a] -> [a]\ndef nubByKey(k, xs):\n    return list(list(v)[0] for _, v in groupby(sorted(xs, key=k), key=k))\n\n\nxs = [\n    'apple', 'apple',\n    'ampersand', 'aPPLE', 'Apple',\n    'orange', 'ORANGE', 'Orange', 'orange', 'apple'\n]\nfor k in [\n    id,                      # default case sensitive uniqueness\n    lambda x: x.lower(),     # case-insensitive uniqueness\n    lambda x: x[0],          # unique first character (case-sensitive)\n    lambda x: x[0].lower(),  # unique first character (case-insensitive)\n]:\n    print (\n        nubByKey(k, xs)\n    )\n\n","human_summarization":"implement methods to remove duplicate elements from an array. The methods include using a hash table, sorting and removing consecutive duplicates, and checking each element against the rest of the list. Additionally, the codes handle cases where elements are hashable or comparable, and provide a brute-force method when both conditions fail. The codes also consider the order of elements and offer solutions using the OrderedDict module. The codes can handle different types of uniqueness and duplication, including case-insensitivity with strings and uniqueness with respect to a dictionary key. The codes also allow the use of an equality predicate or a key function to define uniqueness.","id":4687}
    {"lang_cluster":"Python","source_code":"\ndef quickSort(arr):\n    less = []\n    pivotList = []\n    more = []\n    if len(arr) <= 1:\n        return arr\n    else:\n        pivot = arr[0]\n        for i in arr:\n            if i < pivot:\n                less.append(i)\n            elif i > pivot:\n                more.append(i)\n            else:\n                pivotList.append(i)\n        less = quickSort(less)\n        more = quickSort(more)\n        return less + pivotList + more\n\na = [4, 65, 2, -31, 0, 99, 83, 782, 1]\na = quickSort(a)\n\ndef qsort(L):\n    return (qsort([y for y in L[1:] if y <  L[0]]) + \n            [L[0]] + \n            qsort([y for y in L[1:] if y >= L[0]])) if len(L) > 1 else L\n\ndef qsort(list):\n    if not list:\n        return []\n    else:\n        pivot = list[0]\n        less = [x for x in list[1:]   if x <  pivot]\n        more = [x for x in list[1:] if x >= pivot]\n        return qsort(less) + [pivot] + qsort(more)\n\nfrom random import *\n\ndef qSort(a):\n    if len(a) <= 1:\n        return a\n    else:\n        q = choice(a)\n        return qSort([elem for elem in a if elem < q]) + [q] * a.count(q) + qSort([elem for elem in a if elem > q])\n\ndef quickSort(a):\n    if len(a) <= 1:\n        return a\n    else:\n        less = []\n        more = []\n        pivot = choice(a)\n        for i in a:\n            if i < pivot:\n                less.append(i)\n            if i > pivot:\n                more.append(i)\n        less = quickSort(less)\n        more = quickSort(more)\n        return less + [pivot] * a.count(pivot) + more\n\ndef qsort(array):\n    if len(array) < 2:\n        return array\n    head, *tail = array\n    less = qsort([i for i in tail if i < head])\n    more = qsort([i for i in tail if i >= head])\n    return less + [head] + more\n\ndef quicksort(array):\n    _quicksort(array, 0, len(array) - 1)\n\ndef _quicksort(array, start, stop):\n    if stop - start > 0:\n        pivot, left, right = array[start], start, stop\n        while left <= right:\n            while array[left] < pivot:\n                left += 1\n            while array[right] > pivot:\n                right -= 1\n            if left <= right:\n                array[left], array[right] = array[right], array[left]\n                left += 1\n                right -= 1\n        _quicksort(array, start, right)\n        _quicksort(array, left, stop)\n","human_summarization":"implement the quicksort algorithm to sort an array or list of elements. The elements have a strict weak order and the index of the array can be of any type. The algorithm works by choosing a pivot element and dividing the rest of the elements into two partitions based on their relation to the pivot. It then recursively sorts both partitions and combines them with the pivot to form the sorted array. The algorithm also includes an optimized version that works in place by swapping elements within the array to avoid additional memory allocation. The pivot selection method is not specified.","id":4688}
    {"lang_cluster":"Python","source_code":"\n\nimport datetime\ntoday = datetime.date.today()\n# The first requested format is a method of datetime objects:\ntoday.isoformat()\n# For full flexibility, use the strftime formatting codes from the link above:\ntoday.strftime(\"%A, %B %d, %Y\")\n# This mechanism is integrated into the general string formatting system.\n# You can do this with positional arguments referenced by number\n\"The date is {0:%A, %B %d, %Y}\".format(d)\n# Or keyword arguments referenced by name\n\"The date is {date:%A, %B %d, %Y}\".format(date=d)\n# Since Python 3.6, f-strings allow the value to be inserted inline\nf\"The date is {d:%A, %B %d, %Y}\"\n\n","human_summarization":"display the current date in the formats \"2007-11-23\" and \"Friday, November 23, 2007\" following the formatting rules provided in the Python time module documentation.","id":4689}
    {"lang_cluster":"Python","source_code":"\ndef list_powerset(lst):\n    # the power set of the empty set has one element, the empty set\n    result = [[]]\n    for x in lst:\n        # for every additional element in our set\n        # the power set consists of the subsets that don't\n        # contain this element (just take the previous power set)\n        # plus the subsets that do contain the element (use list\n        # comprehension to add [x] onto everything in the\n        # previous power set)\n        result.extend([subset + [x] for subset in result])\n    return result\n\n# the above function in one statement\ndef list_powerset2(lst):\n    return reduce(lambda result, x: result + [subset + [x] for subset in result],\n                  lst, [[]])\n\ndef powerset(s):\n    return frozenset(map(frozenset, list_powerset(list(s))))\n\n\nExample:\n>>> list_powerset([1,2,3])\n[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]\n>>> powerset(frozenset([1,2,3]))\nfrozenset([frozenset([3]), frozenset([1, 2]), frozenset([]), frozenset([2, 3]), frozenset([1]), frozenset([1, 3]), frozenset([1, 2, 3]), frozenset([2])])\n\n\ndef powersetlist(s):\n    r = [[]]\n    for e in s:\n        print \"r:\u00a0%-55r e: %r\"\u00a0% (r,e)\n        r += [x+[e] for x in r]\n    return r\n\ns= [0,1,2,3]    \nprint \"\\npowersetlist(%r) =\\n  %r\"\u00a0% (s, powersetlist(s))\n\n","human_summarization":"The code takes a set S as input and generates its power set. The power set includes all possible subsets of the input set, including the empty set and the set itself. The code also demonstrates the ability to handle edge cases such as the power set of an empty set and a set containing only the empty set. It uses either a built-in set type or a custom set type with necessary operations. The code can also convert input and output from lists to sets, and uses the frozenset type for immutable sets. It includes a simplified version for tracing the execution and a recursive version that reflects the recursive definition of a power set. The code follows the principle that if you list the members of the set and include them according to the corresponding bit position of a binary count, you generate the power set.","id":4690}
    {"lang_cluster":"Python","source_code":"\nimport roman\nprint(roman.toRoman(2022))\ndef toRoman(n):\n    res=''\t\t#converts int to str(Roman numeral)\n    reg=n\t\t#using the numerals (M,D,C,L,X,V,I)\n    if reg<4000:#no more than three repetitions\n        while reg>=1000:\t#thousands up to MMM\n            res+='M'\t\t#MAX is MMMCMXCIX\n            reg-=1000\t\t\n        if reg>=900:\t\t#nine hundreds in 900-999\n            res+='CM'\n            reg-=900\n        if reg>=500:\t\t#five hudreds in 500-899\n            res+='D'\n            reg-=500\n        if reg>=400:\t\t#four hundreds in 400-499\n            res+='CD'\n            reg-=400\n        while reg>=100:\t\t#hundreds in 100-399\n            res+='C'\n            reg-=100\n        if reg>=90:\t\t\t#nine tens in 90-99\n            res+='XC'\n            reg-=90\n        if reg>=50:\t\t\t#five Tens in 50-89\n            res+='L'\n            reg-=50\n        if reg>=40:\n            res+='XL'\t\t#four Tens\n            reg-=40\n        while reg>=10:\n            res+=\"X\"\t\t#tens\n            reg-=10\n        if reg>=9:\n            res+='IX'\t\t#nine Units\n            reg-=9\n        if reg>=5:\n            res+='V'\t\t#five Units\n            reg-=5\n        if reg>=4:\n            res+='IV'\t\t#four Units\n            reg-=4\n        while reg>0:\t\t#three or less Units\n            res+='I'\n            reg-=1\n    return res\nVersion for Python 2\nroman =        \"MDCLXVmdclxvi\"; # UPPERCASE for thousands #\nadjust_roman = \"CCXXmmccxxii\";\narabic =       (1000000, 500000, 100000, 50000, 10000, 5000, 1000, 500, 100, 50, 10, 5, 1);\nadjust_arabic = (100000, 100000,  10000, 10000,  1000, 1000,  100, 100,  10, 10,  1, 1, 0);\n\ndef arabic_to_roman(dclxvi):\n  org = dclxvi; # 666 #\n  out = \"\";\n  for scale,arabic_scale  in enumerate(arabic): \n    if org == 0: break\n    multiples = org \/ arabic_scale;\n    org -= arabic_scale * multiples;\n    out += roman[scale] * multiples;\n    if org >= -adjust_arabic[scale] + arabic_scale: \n      org -= -adjust_arabic[scale] + arabic_scale;\n      out +=  adjust_roman[scale] +  roman[scale]\n  return out\n \nif __name__ == \"__main__\": \n  test = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,30,40,50,60,69,70,\n     80,90,99,100,200,300,400,500,600,666,700,800,900,1000,1009,1444,1666,1945,1997,1999,\n     2000,2008,2500,3000,4000,4999,5000,6666,10000,50000,100000,500000,1000000);\n  for val in test: \n    print '%d - %s'%(val, arabic_to_roman(val))\nAn alternative which uses the divmod() functionromanDgts= 'ivxlcdmVXLCDM_'\n\ndef ToRoman(num):\n   namoR = ''\n   if num >=4000000:\n      print 'Too Big -'\n      return '-----'\n   for rdix in range(0, len(romanDgts), 2):\n      if num==0: break\n      num,r = divmod(num,10)\n      v,r = divmod(r, 5)\n      if r==4:\n         namoR += romanDgts[rdix+1+v] + romanDgts[rdix]\n      else:\n         namoR += r*romanDgts[rdix] + (romanDgts[rdix+1] if(v==1) else '')\n   return namoR[-1::-1]\n\nanums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\nrnums = \"M CM D CD C XC L XL X IX V IV I\".split()\n\ndef to_roman(x):\n    ret = []\n    for a,r in zip(anums, rnums):\n        n,x = divmod(x,a)\n        ret.append(r*n)\n    return ''.join(ret)\n        \nif __name__ == \"__main__\":\n    test = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,30,40,\n            50,60,69,70,80,90,99,100,200,300,400,500,600,666,700,800,900,\n            1000,1009,1444,1666,1945,1997,1999,2000,2008,2010,2011,2500,\n            3000,3999)\n    \n    for val in test:\n        print '%d - %s'%(val, to_roman(val))\nVersion for Python 3\ndef arabic_to_roman(dclxvi):\n#===========================\n  '''Convert an integer from the decimal notation to the Roman notation'''\n  org = dclxvi; # 666 #\n  out = \"\";\n  for scale, arabic_scale  in enumerate(arabic):\n    if org == 0: break\n    multiples = org \/\/ arabic_scale;\n    org -= arabic_scale * multiples;\n    out += roman[scale] * multiples;\n    if (org >= -adjust_arabic[scale] + arabic_scale):\n      org -= -adjust_arabic[scale] + arabic_scale;\n      out +=  adjust_roman[scale] +  roman[scale]\n  return out\n\nif __name__ == \"__main__\": \n  test = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,30,40,50,60,69,70,\n     80,90,99,100,200,300,400,500,600,666,700,800,900,1000,1009,1444,1666,1945,1997,1999,\n     2000,2008,2500,3000,4000,4999,5000,6666,10000,50000,100000,500000,1000000);\n  \n  for val in test: \n    print(\"%8d %s\"\u00a0%(val, arabic_to_roman(val)))\n\nrnl = [ { '4'\u00a0: 'MMMM', '3'\u00a0: 'MMM', '2'\u00a0: 'MM', '1'\u00a0: 'M', '0'\u00a0: '' }, { '9'\u00a0: 'CM', '8'\u00a0: 'DCCC', '7'\u00a0: 'DCC',\n          '6'\u00a0: 'DC', '5'\u00a0: 'D', '4'\u00a0: 'CD', '3'\u00a0: 'CCC', '2'\u00a0: 'CC', '1'\u00a0: 'C', '0'\u00a0: '' }, { '9'\u00a0: 'XC',\n          '8'\u00a0: 'LXXX', '7'\u00a0: 'LXX', '6'\u00a0: 'LX', '5'\u00a0: 'L', '4'\u00a0: 'XL', '3'\u00a0: 'XXX', '2'\u00a0: 'XX', '1'\u00a0: 'X',\n          '0'\u00a0: '' }, { '9'\u00a0: 'IX', '8'\u00a0: 'VIII', '7'\u00a0: 'VII', '6'\u00a0: 'VI', '5'\u00a0: 'V', '4'\u00a0: 'IV', '3'\u00a0: 'III',\n          '2'\u00a0: 'II', '1'\u00a0: 'I', '0'\u00a0: '' }]\n# Option 1\ndef number2romannumeral(n):\n    return ''.join([rnl[x][y] for x, y in zip(range(4), str(n).zfill(4)) if n < 5000 and n > -1])\n# Option 2\ndef number2romannumeral(n):\n    return reduce(lambda x, y: x + y, map(lambda x, y: rnl[x][y], range(4), str(n).zfill(4))) if -1 < n < 5000 else None\n\nWorks with: Python version 3'''Encoding Roman Numerals'''\n\nfrom functools import reduce\nfrom itertools import chain\n\n\n# romanFromInt\u00a0::  Int -> String\ndef romanFromInt(n):\n    '''A string of Roman numerals encoding an integer.'''\n    def go(a, ms):\n        m, s = ms\n        q, r = divmod(a, m)\n        return (r, s * q)\n\n    return concat(snd(mapAccumL(go)(n)(\n        zip([\n            1000, 900, 500, 400, 100, 90, 50,\n            40, 10, 9, 5, 4, 1\n        ], [\n            'M', 'CM', 'D', 'CD', 'C', 'XC', 'L',\n            'XL', 'X', 'IX', 'V', 'IV', 'I'\n        ])\n    )))\n\n\n# ------------------------- TEST -------------------------\n# main\u00a0:: IO ()\ndef main():\n    '''Sample of years'''\n    for s in [\n            romanFromInt(x) for x in [\n                1666, 1990, 2008, 2016, 2018, 2020\n            ]\n    ]:\n        print(s)\n\n\n# ------------------ GENERIC FUNCTIONS -------------------\n\n# concat\u00a0:: [[a]] -> [a]\n# concat\u00a0:: [String] -> String\ndef concat(xxs):\n    '''The concatenation of all the elements in a list.'''\n    xs = list(chain.from_iterable(xxs))\n    unit = '' if isinstance(xs, str) else []\n    return unit if not xs else (\n        ''.join(xs) if isinstance(xs[0], str) else xs\n    )\n\n\n# mapAccumL\u00a0:: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y])\ndef mapAccumL(f):\n    '''A tuple of an accumulation and a list derived by a\n       combined map and fold,\n       with accumulation from left to right.'''\n    def go(a, x):\n        tpl = f(a[0], x)\n        return (tpl[0], a[1] + [tpl[1]])\n    return lambda acc: lambda xs: (\n        reduce(go, xs, (acc, []))\n    )\n\n\n# snd\u00a0:: (a, b) -> b\ndef snd(tpl):\n    '''Second component of a tuple.'''\n    return tpl[1]\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n","human_summarization":"The code takes a positive integer as input and returns its equivalent in Roman numerals. The Roman numeral representation is created by expressing each digit of the integer separately, starting from the leftmost digit and ignoring any digit with a value of zero. The code also demonstrates the use of zip to iterate over two lists simultaneously.","id":4691}
    {"lang_cluster":"Python","source_code":"\n\narray = []\n\narray.append(1)\narray.append(3)\n\narray[0] = 2\n\nprint(array[0])\n\nmy_array = [0] * size\n\nmy_array = [[0] * width] * height  # DOES NOT WORK AS INTENDED!!!\n\nmy_array = [[0 for x in range(width)] for y in range(height)]\n\nmy_array = list()\nfor x in range(height):\n   my_array.append([0] * width)\n\n# Retrieve an element directly from the array.\nitem = array[index]\n\n# Use the array like a stack.  Note that using the pop() method removes the element.\narray.pop()  # Pop last item in a list\narray.pop(0)  # Pop first item in a list\n\n# Using a negative element counts from the end of the list.\nitem = array[-1]  # Retrieve last element in a list.\n\ntry:\n    # This will cause an exception, which will then be caught.\n    print(array[len(array)])\nexcept IndexError as e:\n    # Print the exception. \n    print(e)\n\nanother_array = my_array[1:3]\n","human_summarization":"demonstrate the basic syntax of arrays in Python. They show how to create both fixed-length and dynamic arrays, assign values to them, and retrieve elements. The codes also handle the creation of a list of lists, taking into consideration the different semantics of immutables and mutables. They also demonstrate how to handle IndexErrors when accessing elements out of range and how slicing a list creates a new list.","id":4692}
    {"lang_cluster":"Python","source_code":"\n\nimport shutil\nshutil.copyfile('input.txt', 'output.txt')\n\ninfile = open('input.txt', 'r')\noutfile = open('output.txt', 'w')\nfor line in infile:\n   outfile.write(line)\noutfile.close()\ninfile.close()\n\nimport sys\ntry:\n    infile = open('input.txt', 'r')\nexcept IOError:\n    print >> sys.stderr, \"Unable to open input.txt for input\"\n    sys.exit(1)\ntry:\n    outfile = open('output.txt', 'w')\nexcept IOError:\n    print >> sys.stderr, \"Unable to open output.txt for output\"\n    sys.exit(1)\ntry:  # for finally\n    try: # for I\/O\n        for line in infile:\n            outfile.write(line)\n    except IOError, e:\n        print >> sys.stderr, \"Some I\/O Error occurred (reading from input.txt or writing to output.txt)\"\nfinally:\n    infile.close()\n    outfile.close()\n\nimport sys\ntry:\n    with open('input.txt') as infile:\n        with open('output.txt', 'w') as outfile:\n            for line in infile:\n                outfile.write(line)\nexcept IOError:\n    print >> sys.stderr, \"Some I\/O Error occurred\"\n    sys.exit(1)\n\n","human_summarization":"demonstrate how to read contents from an \"input.txt\" file into an intermediate variable and then write these contents into a new file called \"output.txt\". It also shows how to handle file I\/O errors and ensure files are properly closed even in the event of an I\/O error, using Python's with statement for automatic file closure. It does not include oneliners that skip the intermediate variable. The code uses the shutil.copyfile function from the standard library.","id":4693}
    {"lang_cluster":"Python","source_code":"\ns = \"alphaBETA\"\nprint s.upper() # => \"ALPHABETA\"\nprint s.lower() # => \"alphabeta\"\n\nprint s.swapcase() # => \"ALPHAbeta\"\n\nprint \"fOo bAR\".capitalize() # => \"Foo bar\"\nprint \"fOo bAR\".title() # => \"Foo Bar\"\n\nimport string\nprint string.capwords(\"fOo bAR\") # => \"Foo Bar\"\n\nprint \"foo's bar\".title()          # => \"Foo'S Bar\"\nprint string.capwords(\"foo's bar\") # => \"Foo's Bar\"\n","human_summarization":"The code converts the string \"alphaBETA\" to both upper-case and lower-case using the default string literal or ASCII encoding. It also demonstrates additional case conversion functions such as swapping case, capitalizing the first letter, and using string.capwords() to define word separators.","id":4694}
    {"lang_cluster":"Python","source_code":"\n\"\"\"\n  Compute nearest pair of points using two algorithms\n  \n  First algorithm is 'brute force' comparison of every possible pair.\n  Second, 'divide and conquer', is based on:\n    www.cs.iupui.edu\/~xkzou\/teaching\/CS580\/Divide-and-conquer-closestPair.ppt \n\"\"\"\n\nfrom random import randint, randrange\nfrom operator import itemgetter, attrgetter\n\ninfinity = float('inf')\n\n# Note the use of complex numbers to represent 2D points making distance == abs(P1-P2)\n\ndef bruteForceClosestPair(point):\n    numPoints = len(point)\n    if numPoints < 2:\n        return infinity, (None, None)\n    return min( ((abs(point[i] - point[j]), (point[i], point[j]))\n                 for i in range(numPoints-1)\n                 for j in range(i+1,numPoints)),\n                key=itemgetter(0))\n\ndef closestPair(point):\n    xP = sorted(point, key= attrgetter('real'))\n    yP = sorted(point, key= attrgetter('imag'))\n    return _closestPair(xP, yP)\n\ndef _closestPair(xP, yP):\n    numPoints = len(xP)\n    if numPoints <= 3:\n        return bruteForceClosestPair(xP)\n    Pl = xP[:numPoints\/2]\n    Pr = xP[numPoints\/2:]\n    Yl, Yr = [], []\n    xDivider = Pl[-1].real\n    for p in yP:\n        if p.real <= xDivider:\n            Yl.append(p)\n        else:\n            Yr.append(p)\n    dl, pairl = _closestPair(Pl, Yl)\n    dr, pairr = _closestPair(Pr, Yr)\n    dm, pairm = (dl, pairl) if dl < dr else (dr, pairr)\n    # Points within dm of xDivider sorted by Y coord\n    closeY = [p for p in yP  if abs(p.real - xDivider) < dm]\n    numCloseY = len(closeY)\n    if numCloseY > 1:\n        # There is a proof that you only need compare a max of 7 next points\n        closestY = min( ((abs(closeY[i] - closeY[j]), (closeY[i], closeY[j]))\n                         for i in range(numCloseY-1)\n                         for j in range(i+1,min(i+8, numCloseY))),\n                        key=itemgetter(0))\n        return (dm, pairm) if dm <= closestY[0] else closestY\n    else:\n        return dm, pairm\n    \ndef times():\n    ''' Time the different functions\n    '''\n    import timeit\n\n    functions = [bruteForceClosestPair, closestPair]\n    for f in functions:\n        print 'Time for', f.__name__, timeit.Timer(\n            '%s(pointList)' % f.__name__,\n            'from closestpair import %s, pointList' % f.__name__).timeit(number=1)\n    \n\n\npointList = [randint(0,1000)+1j*randint(0,1000) for i in range(2000)]\n\nif __name__ == '__main__':\n    pointList = [(5+9j), (9+3j), (2+0j), (8+4j), (7+4j), (9+10j), (1+9j), (8+2j), 10j, (9+6j)]\n    print pointList\n    print '  bruteForceClosestPair:', bruteForceClosestPair(pointList)\n    print '            closestPair:', closestPair(pointList)\n    for i in range(10):\n        pointList = [randrange(11)+1j*randrange(11) for i in range(10)]\n        print '\\n', pointList\n        print ' bruteForceClosestPair:', bruteForceClosestPair(pointList)\n        print '           closestPair:', closestPair(pointList)\n    print '\\n'\n    times()\n    times()\n    times()\n\n\n","human_summarization":"provide two solutions to solve the Closest Pair of Points problem in a two-dimensional plane. The first solution is a brute-force algorithm with a time complexity of O(n^2), which iterates over all pairs of points to find the pair with the minimum distance. The second solution is a more efficient divide-and-conquer algorithm with a time complexity of O(n log n), which sorts the points by x and y coordinates and recursively finds the closest pair. Both algorithms return the minimum distance and the pair of points with that distance.","id":4695}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.5\n\ncollection = [0, '1']                 # Lists are mutable (editable) and can be sorted in place\nx = collection[0]                     # accessing an item (which happens to be a numeric 0 (zero)\ncollection.append(2)                  # adding something to the end of the list\ncollection.insert(0, '-1')            # inserting a value into the beginning\ny = collection[0]                     # now returns a string of \"-1\"\ncollection.extend([2,'3'])            # same as [collection.append(i) for i in [2,'3']] ... but faster\ncollection += [2,'3']                 # same as previous line\ncollection[2:6]                       # a \"slice\" (collection of the list elements from the third up to but not including the sixth)\nlen(collection)                       # get the length of (number of elements in) the collection\ncollection = (0, 1)                   # Tuples are immutable (not editable)\ncollection[:]                         # ... slices work on these too; and this is equivalent to collection[0:len(collection)]\ncollection[-4:-1]                     # negative slices count from the end of the string\ncollection[::2]                       # slices can also specify a stride --- this returns all even elements of the collection\ncollection=\"some string\"              # strings are treated as sequences of characters\nx = collection[::-1]                  # slice with negative step returns reversed sequence (string in this case).\ncollection[::2] == \"some string\"[::2] # True, literal objects don't need to be bound to name\/variable to access slices or object methods\ncollection.__getitem__(slice(0,len(collection),2))  # same as previous expressions.\ncollection = {0: \"zero\", 1: \"one\"}    # Dictionaries (Hash)\ncollection['zero'] = 2                # Dictionary members accessed using same syntax as list\/array indexes.\ncollection = set([0, '1'])            # sets (Hash)\n\n","human_summarization":"create a collection in a statically-typed language and add values to it. The code also demonstrates the use of built-in collection types in Python such as lists, tuples, dictionaries, and sets. It also shows how Python classes can implement indexing, slicing, and attribute management features as collections. Furthermore, it illustrates how to use Python modules like Numeric and NumPy for efficient n-dimensional arrays.","id":4696}
    {"lang_cluster":"Python","source_code":"\nclass Bounty:\n    def __init__(self, value, weight, volume):\n        self.value, self.weight, self.volume = value, weight, volume\n\npanacea = Bounty(3000,  0.3, 0.025)\nichor =   Bounty(1800,  0.2, 0.015)\ngold =    Bounty(2500,  2.0, 0.002)\nsack =    Bounty(   0, 25.0, 0.25)\nbest =    Bounty(   0,    0, 0) \ncurrent = Bounty(   0,    0, 0) \n\nbest_amounts = (0, 0, 0)\n\nmax_panacea = int(min(sack.weight \/\/ panacea.weight, sack.volume \/\/ panacea.volume))\nmax_ichor   = int(min(sack.weight \/\/ ichor.weight,   sack.volume \/\/ ichor.volume))\nmax_gold    = int(min(sack.weight \/\/ gold.weight,    sack.volume \/\/ gold.volume))\n\nfor npanacea in xrange(max_panacea):\n    for nichor in xrange(max_ichor):\n        for ngold in xrange(max_gold):\n            current.value = npanacea * panacea.value + nichor * ichor.value + ngold * gold.value\n            current.weight = npanacea * panacea.weight + nichor * ichor.weight + ngold * gold.weight\n            current.volume = npanacea * panacea.volume + nichor * ichor.volume + ngold * gold.volume\n\n            if current.value > best.value and current.weight <= sack.weight and                current.volume <= sack.volume:\n                best = Bounty(current.value, current.weight, current.volume)\n                best_amounts = (npanacea, nichor, ngold)\n\nprint \"Maximum value achievable is\", best.value\nprint \"This is achieved by carrying (one solution) %d panacea, %d ichor and %d gold\" %        (best_amounts[0], best_amounts[1], best_amounts[2])\nprint \"The weight to carry is %4.1f and the volume used is %5.3f\" % (best.weight, best.volume)\n","human_summarization":"The code calculates the maximum value that a traveler can carry from Shangri La, given the weight and volume constraints of his knapsack and the value, weight, and volume of available items. The solution considers only whole units of items and assumes an unlimited supply of each item. It outputs one of the four possible combinations of items that maximize the total value.","id":4697}
    {"lang_cluster":"Python","source_code":"\n\nprint ( ', '.join(str(i+1) for i in range(10)) )\n\n>>> from sys import stdout\n>>> write = stdout.write\n>>> n, i = 10, 1\n>>> while True:\n    write(i)\n    i += 1\n    if i > n:\n        break\n    write(', ')\n\n    \n1, 2, 3, 4, 5, 6, 7, 8, 9, 10\n>>>\n\n[print(str(i+1) + \", \",end='') if i < 9 else print(i+1) for i in range(10)]\nWorks with: Python version 3.x\nn, i = 10, 1\nwhile True:\n    print(i, end=\"\")\n    i += 1\n    if i > n:\n        break\n    print(\", \", end=\"\")\n","human_summarization":"generates a comma-separated list of numbers from 1 to 10, using separate output statements for the number and the comma within a loop. The last iteration only executes part of the loop body.","id":4698}
    {"lang_cluster":"Python","source_code":"\ntry:\n    from functools import reduce\nexcept:\n    pass\n\ndata = {\n    'des_system_lib':   set('std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee'.split()),\n    'dw01':             set('ieee dw01 dware gtech'.split()),\n    'dw02':             set('ieee dw02 dware'.split()),\n    'dw03':             set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),\n    'dw04':             set('dw04 ieee dw01 dware gtech'.split()),\n    'dw05':             set('dw05 ieee dware'.split()),\n    'dw06':             set('dw06 ieee dware'.split()),\n    'dw07':             set('ieee dware'.split()),\n    'dware':            set('ieee dware'.split()),\n    'gtech':            set('ieee gtech'.split()),\n    'ramlib':           set('std ieee'.split()),\n    'std_cell_lib':     set('ieee std_cell_lib'.split()),\n    'synopsys':         set(),\n    }\n\ndef toposort2(data):\n    for k, v in data.items():\n        v.discard(k) # Ignore self dependencies\n    extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())\n    data.update({item:set() for item in extra_items_in_deps})\n    while True:\n        ordered = set(item for item,dep in data.items() if not dep)\n        if not ordered:\n            break\n        yield ' '.join(sorted(ordered))\n        data = {item: (dep - ordered) for item,dep in data.items()\n                if item not in ordered}\n    assert not data, \"A cyclic dependency exists amongst %r\" % data\n\nprint ('\\n'.join( toposort2(data) ))\n\n\nieee std synopsys\ndware gtech ramlib std_cell_lib\ndw01 dw02 dw05 dw06 dw07\ndes_system_lib dw03 dw04\n\nTraceback (most recent call last):\n  File \"C:\\Documents and Settings\\All Users\\Documents\\Paddys\\topological_sort.py\", line 115, in <module>\n    print ('\\n'.join( toposort2(data) ))\n  File \"C:\\Documents and Settings\\All Users\\Documents\\Paddys\\topological_sort.py\", line 113, in toposort2\n    assert not data, \"A cyclic dependency exists amongst %r\"\u00a0% data\nAssertionError: A cyclic dependency exists amongst {'dw04': {'dw01'}, 'dw03': {'dw01'}, 'dw01': {'dw04'}, 'des_system_lib': {'dw01'}}\nfrom graphlib import TopologicalSorter\n\n#   LIBRARY     mapped_to   LIBRARY DEPENDENCIES\ndata = {\n    'des_system_lib':   set('std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee'.split()),\n    'dw01':             set('ieee dw01 dware gtech'.split()),\n    'dw02':             set('ieee dw02 dware'.split()),\n    'dw03':             set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),\n    'dw04':             set('dw04 ieee dw01 dware gtech'.split()),\n    'dw05':             set('dw05 ieee dware'.split()),\n    'dw06':             set('dw06 ieee dware'.split()),\n    'dw07':             set('ieee dware'.split()),\n    'dware':            set('ieee dware'.split()),\n    'gtech':            set('ieee gtech'.split()),\n    'ramlib':           set('std ieee'.split()),\n    'std_cell_lib':     set('ieee std_cell_lib'.split()),\n    'synopsys':         set(),\n    }\n# Ignore self dependencies\nfor k, v in data.items():\n    v.discard(k)   \n\nts = TopologicalSorter(data)\nprint(tuple(ts.static_order()))\n\n\n","human_summarization":"The code implements a function for topological sorting of VHDL libraries based on their dependencies. It takes into account the constraints that a library must be compiled after any library it depends on. The function returns a valid compile order of libraries, flags any un-orderable dependencies and ignores any self-dependencies. It also handles exceptions when the data becomes un-orderable. The function assumes library names are single words and uses Kahn's 1962 topological sort or depth-first search algorithms for sorting.","id":4699}
    {"lang_cluster":"Python","source_code":"\n\"abcd\".startswith(\"ab\") #returns True\n\"abcd\".endswith(\"zn\") #returns False\n\"bb\" in \"abab\" #returns False\n\"ab\" in \"abab\" #returns True\nloc = \"abab\".find(\"bb\") #returns -1\nloc = \"abab\".find(\"ab\") #returns 0\nloc = \"abab\".find(\"ab\",loc+1) #returns 2\n\n","human_summarization":"The code checks if a given string starts with, contains, or ends with a second string. It also prints the location of the match and handles multiple occurrences of the second string within the first string.","id":4700}
    {"lang_cluster":"Python","source_code":"\nimport itertools\n\ndef all_equal(a,b,c,d,e,f,g):\n    return a+b == b+c+d == d+e+f == f+g\n\ndef foursquares(lo,hi,unique,show):\n    solutions = 0\n    if unique:\n        uorn = \"unique\"\n        citer = itertools.combinations(range(lo,hi+1),7)\n    else:\n        uorn = \"non-unique\"\n        citer =  itertools.combinations_with_replacement(range(lo,hi+1),7)\n                    \n    for c in citer:\n            for p in set(itertools.permutations(c)):\n                if all_equal(*p):\n                    solutions += 1\n                    if show:\n                        print str(p)[1:-1]\n\n    print str(solutions)+\" \"+uorn+\" solutions in \"+str(lo)+\" to \"+str(hi)\n    print\n\n\nfoursquares(1,7,True,True)\n4, 5, 3, 1, 6, 2, 7\n3, 7, 2, 1, 5, 4, 6\n5, 6, 2, 3, 1, 7, 4\n4, 7, 1, 3, 2, 6, 5\n6, 4, 5, 1, 2, 7, 3\n7, 3, 2, 5, 1, 4, 6\n7, 2, 6, 1, 3, 5, 4\n6, 4, 1, 5, 2, 3, 7\n8 unique solutions in 1 to 7\n\n\nfoursquares(3,9,True,True)\n7, 8, 3, 4, 5, 6, 9\n9, 6, 4, 5, 3, 7, 8\n8, 7, 3, 5, 4, 6, 9\n9, 6, 5, 4, 3, 8, 7\n4 unique solutions in 3 to 9\n\n\nfoursquares(0,9,False,False)\n2860 non-unique solutions in 0 to 9\n\ndef foursquares(lo,hi,unique,show):\n\n    def acd_iter():\n        \"\"\"\n        Iterates through all the possible valid values of \n        a, c, and d.\n        \n        a = c + d\n        \"\"\"\n        for c in range(lo,hi+1):\n            for d in range(lo,hi+1):\n                if (not unique) or (c <> d):\n                    a = c + d\n                    if a >= lo and a <= hi:\n                        if (not unique) or (c <> 0 and d <> 0):\n                            yield (a,c,d)\n                            \n    def ge_iter():\n        \"\"\"\n        Iterates through all the possible valid values of \n        g and e.\n        \n        g = d + e\n        \"\"\"\n        for e in range(lo,hi+1):\n            if (not unique) or (e not in (a,c,d)):\n                g = d + e\n                if g >= lo and g <= hi:\n                    if (not unique) or (g not in (a,c,d,e)):\n                        yield (g,e)\n                        \n    def bf_iter():\n        \"\"\"\n        Iterates through all the possible valid values of \n        b and f.\n        \n        b = e + f - c\n        \"\"\"\n        for f in range(lo,hi+1):\n            if (not unique) or (f not in (a,c,d,g,e)):\n                b = e + f - c\n                if b >= lo and b <= hi:\n                    if (not unique) or (b not in (a,c,d,g,e,f)):\n                        yield (b,f)\n\n    solutions = 0                    \n    acd_itr = acd_iter()              \n    for acd in acd_itr:\n        a,c,d = acd\n        ge_itr = ge_iter()\n        for ge in ge_itr:\n            g,e = ge\n            bf_itr = bf_iter()\n            for bf in bf_itr:\n                b,f = bf\n                solutions += 1\n                if show:\n                    print str((a,b,c,d,e,f,g))[1:-1]\n    if unique:\n        uorn = \"unique\"\n    else:\n        uorn = \"non-unique\"\n               \n    print str(solutions)+\" \"+uorn+\" solutions in \"+str(lo)+\" to \"+str(hi)\n    print\n\nOutputfoursquares(1,7,True,True)\n4, 7, 1, 3, 2, 6, 5\n6, 4, 1, 5, 2, 3, 7\n3, 7, 2, 1, 5, 4, 6\n5, 6, 2, 3, 1, 7, 4\n7, 3, 2, 5, 1, 4, 6\n4, 5, 3, 1, 6, 2, 7\n6, 4, 5, 1, 2, 7, 3\n7, 2, 6, 1, 3, 5, 4\n8 unique solutions in 1 to 7\n\n\nfoursquares(3,9,True,True)\n7, 8, 3, 4, 5, 6, 9\n8, 7, 3, 5, 4, 6, 9\n9, 6, 4, 5, 3, 7, 8\n9, 6, 5, 4, 3, 8, 7\n4 unique solutions in 3 to 9\n\n\nfoursquares(0,9,False,False)\n2860 non-unique solutions in 0 to 9\nWorks with: Python version 3.7\n'''4-rings or 4-squares puzzle'''\n\nfrom itertools import chain\n\n\n# rings\u00a0:: noRepeatedDigits -> DigitList -> Lists of solutions\n# rings\u00a0:: Bool -> [Int] -> [[Int]]\ndef rings(uniq):\n    '''Sets of unique or non-unique integer values\n       (drawn from the `digits` argument)\n       for each of the seven names [a..g] such that:\n       (a + b) == (b + c + d) == (d + e + f) == (f + g)\n    '''\n    def go(digits):\n        ns = sorted(digits, reverse=True)\n        h = ns[0]\n\n        # CENTRAL DIGIT\u00a0:: d\n        def central(d):\n            xs = list(filter(lambda x: h >= (d + x), ns))\n\n            # LEFT NEIGHBOUR AND LEFTMOST\u00a0:: c and a\n            def left(c):\n                a = c + d\n                if a > h:\n                    return []\n                else:\n                    # RIGHT NEIGHBOUR AND RIGHTMOST\u00a0:: e and g\n                    def right(e):\n                        g = d + e\n                        if ((g > h) or (uniq and (g == c))):\n                            return []\n                        else:\n                            agDelta = a - g\n                            bfs = difference(ns)(\n                                [d, c, e, g, a]\n                            ) if uniq else ns\n\n                            # MID LEFT AND RIGHT\u00a0:: b and f\n                            def midLeftRight(b):\n                                f = b + agDelta\n                                return [[a, b, c, d, e, f, g]] if (\n                                    (f in bfs) and (\n                                        (not uniq) or (\n                                            f not in [a, b, c, d, e, g]\n                                        )\n                                    )\n                                ) else []\n\n    # CANDIDATE DIGITS BOUND TO POSITIONS [a .. g] --------\n\n                            return concatMap(midLeftRight)(bfs)\n\n                    return concatMap(right)(\n                        difference(xs)([d, c, a]) if uniq else ns\n                    )\n\n            return concatMap(left)(\n                delete(d)(xs) if uniq else ns\n            )\n\n        return concatMap(central)(ns)\n\n    return lambda digits: go(digits) if digits else []\n\n\n# TEST ----------------------------------------------------\n# main\u00a0:: IO ()\ndef main():\n    '''Testing unique digits [1..7], [3..9] and unrestricted digits'''\n\n    print(main.__doc__ + ':\\n')\n    print(unlines(map(\n        lambda tpl: '\\nrings' + repr(tpl) + ':\\n\\n' + unlines(\n            map(repr, uncurry(rings)(*tpl))\n        ), [\n            (True, enumFromTo(1)(7)),\n            (True, enumFromTo(3)(9))\n        ]\n    )))\n    tpl = (False, enumFromTo(0)(9))\n    print(\n        '\\n\\nlen(rings' + repr(tpl) + '):\\n\\n' +\n        str(len(uncurry(rings)(*tpl)))\n    )\n\n\n# GENERIC -------------------------------------------------\n\n# concatMap\u00a0:: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n    '''A concatenated list over which a function has been mapped.\n       The list monad can be derived by using a function f which\n       wraps its output in a list,\n       (using an empty list to represent computational failure).\n    '''\n    return lambda xs: list(\n        chain.from_iterable(map(f, xs))\n    )\n\n\n# delete\u00a0:: Eq a => a -> [a] -> [a]\ndef delete(x):\n    '''xs with the first of any instances of x removed.'''\n    def go(xs):\n        xs.remove(x)\n        return xs\n    return lambda xs: go(list(xs)) if (\n        x in xs\n    ) else list(xs)\n\n\n#  difference\u00a0:: Eq a => [a] -> [a] -> [a]\ndef difference(xs):\n    '''All elements of ys except any also found in xs'''\n    def go(ys):\n        s = set(ys)\n        return [x for x in xs if x not in s]\n    return lambda ys: go(ys)\n\n\n# enumFromTo\u00a0:: (Int, Int) -> [Int]\ndef enumFromTo(m):\n    '''Integer enumeration from m to n.'''\n    return lambda n: list(range(m, 1 + n))\n\n\n# uncurry\u00a0:: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n    '''A function over a pair of arguments,\n       derived from a vanilla or curried function.\n    '''\n    return lambda x, y: f(x)(y)\n\n\n# unlines\u00a0:: [String] -> String\ndef unlines(xs):\n    '''A single string formed by the intercalation\n       of a list of strings with the newline character.\n    '''\n    return '\\n'.join(xs)\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"The code finds all possible solutions for a 4-square puzzle where each square's sum is equal. It first finds solutions where each letter (a-g) represents a unique number from 1 to 7, then from 3 to 9. Finally, it counts the number of solutions where each letter can represent a non-unique number from 0 to 9. It also includes a faster solution that doesn't use itertools.","id":4701}
    {"lang_cluster":"Python","source_code":"\n\nWorks with: Python version 2.6+, 3.0+\nimport time\n\ndef chunks(l, n=5):\n    return [l[i:i+n] for i in range(0, len(l), n)]\n\ndef binary(n, digits=8):\n    n=int(n)\n    return '{0:0{1}b}'.format(n, digits)\n\ndef secs(n):\n    n=int(n)\n    h='x' * n\n    return \"|\".join(chunks(h))\n\ndef bin_bit(h):\n    h=h.replace(\"1\",\"x\")\n    h=h.replace(\"0\",\" \")\n    return \"|\".join(list(h))\n\n\nx=str(time.ctime()).split()\ny=x[3].split(\":\")\n\ns=y[-1]\ny=map(binary,y[:-1])\n\nprint bin_bit(y[0])\nprint\nprint bin_bit(y[1])\nprint\nprint secs(s)\n\n\n","human_summarization":"The code generates a simple, animated clock that updates every second according to the system clock. It uses a system timer event instead of constantly polling system resources. The clock can be any timekeeping device and only needs to display seconds. The code is clear and concise, avoiding unnecessary complexity.","id":4702}
    {"lang_cluster":"Python","source_code":"\n\nfrom fractions import gcd\n\n\ndef pt1(maxperimeter=100):\n    '''\n# Naive method\n    '''\n    trips = []\n    for a in range(1, maxperimeter):\n        aa = a*a\n        for b in range(a, maxperimeter-a+1):\n            bb = b*b\n            for c in range(b, maxperimeter-b-a+1):\n                cc = c*c\n                if a+b+c > maxperimeter or cc > aa + bb: break\n                if aa + bb == cc:\n                    trips.append((a,b,c, gcd(a, b) == 1))\n    return trips\n\ndef pytrip(trip=(3,4,5),perim=100, prim=1):\n    a0, b0, c0 = a, b, c = sorted(trip)\n    t, firstprim = set(), prim>0\n    while a + b + c <= perim:\n        t.add((a, b, c, firstprim>0))\n        a, b, c, firstprim = a+a0, b+b0, c+c0, False\n    #\n    t2 = set()\n    for a, b, c, firstprim in t:\n        a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7\n        if  a5 - b5 + c7 <= perim:\n            t2 |= pytrip(( a - b2 + c2,  a2 - b + c2,  a2 - b2 + c3), perim, firstprim)\n        if  a5 + b5 + c7 <= perim:\n            t2 |= pytrip(( a + b2 + c2,  a2 + b + c2,  a2 + b2 + c3), perim, firstprim)\n        if -a5 + b5 + c7 <= perim:\n            t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)\n    return t | t2\n\ndef pt2(maxperimeter=100):\n    '''\n# Parent\/child relationship method:\n# http:\/\/en.wikipedia.org\/wiki\/Formulas_for_generating_Pythagorean_triples#XI.\n    '''\n    trips = pytrip((3,4,5), maxperimeter, 1)\n    return trips\n\ndef printit(maxperimeter=100, pt=pt1):\n    trips = pt(maxperimeter)\n    print(\"  Up to a perimeter of %i there are %i triples, of which %i are primitive\"\n          % (maxperimeter,\n             len(trips),\n             len([prim for a,b,c,prim in trips if prim])))\n  \nfor algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):\n    print(algo.__doc__)\n    for maxperimeter in range(mn, mx+1, mn):\n        printit(maxperimeter, algo)\n\nOutput\n\n# Naive method\n    \n  Up to a perimeter of 250 there are 56 triples, of which 18 are primitive\n  Up to a perimeter of 500 there are 137 triples, of which 35 are primitive\n  Up to a perimeter of 750 there are 227 triples, of which 52 are primitive\n  Up to a perimeter of 1000 there are 325 triples, of which 70 are primitive\n  Up to a perimeter of 1250 there are 425 triples, of which 88 are primitive\n  Up to a perimeter of 1500 there are 527 triples, of which 104 are primitive\n  Up to a perimeter of 1750 there are 637 triples, of which 123 are primitive\n  Up to a perimeter of 2000 there are 744 triples, of which 140 are primitive\n  Up to a perimeter of 2250 there are 858 triples, of which 156 are primitive\n  Up to a perimeter of 2500 there are 969 triples, of which 175 are primitive\n\n# Parent\/child relationship method:\n# http:\/\/en.wikipedia.org\/wiki\/Formulas_for_generating_Pythagorean_triples#XI.\n    \n  Up to a perimeter of 500 there are 137 triples, of which 35 are primitive\n  Up to a perimeter of 1000 there are 325 triples, of which 70 are primitive\n  Up to a perimeter of 1500 there are 527 triples, of which 104 are primitive\n  Up to a perimeter of 2000 there are 744 triples, of which 140 are primitive\n  Up to a perimeter of 2500 there are 969 triples, of which 175 are primitive\n  Up to a perimeter of 3000 there are 1204 triples, of which 211 are primitive\n  Up to a perimeter of 3500 there are 1443 triples, of which 245 are primitive\n  Up to a perimeter of 4000 there are 1687 triples, of which 280 are primitive\n  Up to a perimeter of 4500 there are 1931 triples, of which 314 are primitive\n  Up to a perimeter of 5000 there are 2184 triples, of which 349 are primitive\n  Up to a perimeter of 5500 there are 2442 triples, of which 385 are primitive\n  Up to a perimeter of 6000 there are 2701 triples, of which 422 are primitive\n  Up to a perimeter of 6500 there are 2963 triples, of which 457 are primitive\n  Up to a perimeter of 7000 there are 3224 triples, of which 492 are primitive\n  Up to a perimeter of 7500 there are 3491 triples, of which 527 are primitive\n  Up to a perimeter of 8000 there are 3763 triples, of which 560 are primitive\n  Up to a perimeter of 8500 there are 4029 triples, of which 597 are primitive\n  Up to a perimeter of 9000 there are 4304 triples, of which 631 are primitive\n  Up to a perimeter of 9500 there are 4577 triples, of which 667 are primitive\n  Up to a perimeter of 10000 there are 4858 triples, of which 703 are primitive\n  Up to a perimeter of 10500 there are 5138 triples, of which 736 are primitive\n  Up to a perimeter of 11000 there are 5414 triples, of which 770 are primitive\n  Up to a perimeter of 11500 there are 5699 triples, of which 804 are primitive\n  Up to a perimeter of 12000 there are 5980 triples, of which 839 are primitive\n  Up to a perimeter of 12500 there are 6263 triples, of which 877 are primitive\n  Up to a perimeter of 13000 there are 6559 triples, of which 913 are primitive\n  Up to a perimeter of 13500 there are 6843 triples, of which 949 are primitive\n  Up to a perimeter of 14000 there are 7129 triples, of which 983 are primitive\n  Up to a perimeter of 14500 there are 7420 triples, of which 1019 are primitive\n  Up to a perimeter of 15000 there are 7714 triples, of which 1055 are primitive\n  Up to a perimeter of 15500 there are 8004 triples, of which 1089 are primitive\n  Up to a perimeter of 16000 there are 8304 triples, of which 1127 are primitive\n  Up to a perimeter of 16500 there are 8595 triples, of which 1159 are primitive\n  Up to a perimeter of 17000 there are 8884 triples, of which 1192 are primitive\n  Up to a perimeter of 17500 there are 9189 triples, of which 1228 are primitive\n  Up to a perimeter of 18000 there are 9484 triples, of which 1264 are primitive\n  Up to a perimeter of 18500 there are 9791 triples, of which 1301 are primitive\n  Up to a perimeter of 19000 there are 10088 triples, of which 1336 are primitive\n  Up to a perimeter of 19500 there are 10388 triples, of which 1373 are primitive\n  Up to a perimeter of 20000 there are 10689 triples, of which 1408 are primitive\nBarebone minimum for this task:from sys import setrecursionlimit\nsetrecursionlimit(2000) # 2000 ought to be big enough for everybody\n\ndef triples(lim, a = 3, b = 4, c = 5):\n    l = a + b + c\n    if l > lim: return (0, 0)\n    return reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), [\n        (1, lim \/ l),\n        triples(lim,  a - 2*b + 2*c,  2*a - b + 2*c,  2*a - 2*b + 3*c),\n        triples(lim,  a + 2*b + 2*c,  2*a + b + 2*c,  2*a + 2*b + 3*c),\n        triples(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c) ])\n\nfor peri in [10 ** e for e in range(1, 8)]:\n    print peri, triples(peri)\n","human_summarization":"The code determines the number of Pythagorean triples with a perimeter not exceeding 100 and counts how many of them are primitive. It also includes an extra functionality to handle large perimeter values up to 100,000,000.","id":4703}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.4 and 2.5\n  import Tkinter\n  \n  w = Tkinter.Tk()\n  w.mainloop()\n\nWorks with: Python version 3.7\nimport tkinter\n \nw = tkinter.Tk()\nw.mainloop()\n\n  from wxPython.wx import *\n  \n  class MyApp(wxApp):\n    def OnInit(self):\n      frame = wxFrame(NULL, -1, \"Hello from wxPython\")\n      frame.Show(true)\n      self.SetTopWindow(frame)\n      return true\n  \n  app = MyApp(0)\n  app.MainLoop()\n\n  import win32ui\n  from pywin.mfc.dialog import Dialog\n  \n  d = Dialog(win32ui.IDD_SIMPLE_INPUT)\n  d.CreateWindow()\n\n  import gtk\n  \n  window = gtk.Window()\n  window.show()\n  gtk.main()\n\n  from PyQt4.QtGui import *\n\n  app = QApplication([])\n  win = QWidget()\n  win.show()\n\n  app.exec_()\n\n","human_summarization":"\"Creates an empty GUI window that can respond to close requests.\"","id":4704}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.7+ and 3.1+\nimport collections, sys\n\ndef filecharcount(openfile):\n    return sorted(collections.Counter(c for l in openfile for c in l).items())\n\nf = open(sys.argv[1])\nprint(filecharcount(f))\n\n\nWorks with: Python version 3\n'''Character counting as a fold'''\n\nfrom functools import reduce\nfrom itertools import repeat\nfrom os.path import expanduser\n\n\n# charCounts\u00a0:: String -> Dict Char Int\ndef charCounts(s):\n    '''A dictionary of\n       (character, frequency) mappings\n    '''\n    def tally(dct, c):\n        dct[c] = 1 + dct[c] if c in dct else 1\n        return dct\n    return reduce(tally, list(s), {})\n\n\n# TEST ----------------------------------------------------\n# main\u00a0:: IO ()\ndef main():\n    '''Listing in descending order of frequency.'''\n\n    print(\n        tabulated(\n            'Descending order of frequency:\\n'\n        )(compose(repr)(fst))(compose(str)(snd))(\n            5\n        )(stet)(\n            sorted(\n                charCounts(\n                    readFile('~\/Code\/charCount\/readme.txt')\n                ).items(),\n                key=swap,\n                reverse=True\n            )\n        )\n    )\n\n\n# GENERIC -------------------------------------------------\n\n# chunksOf\u00a0:: Int -> [a] -> [[a]]\ndef chunksOf(n):\n    '''A series of lists of length n,\n       subdividing the contents of xs.\n       Where the length of xs is not evenly divible,\n       the final list will be shorter than n.'''\n    return lambda xs: reduce(\n        lambda a, i: a + [xs[i:n + i]],\n        range(0, len(xs), n), []\n    ) if 0 < n else []\n\n\n# compose (<<<)\u00a0:: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n    '''Right to left function composition.'''\n    return lambda f: lambda x: g(f(x))\n\n\n# fst\u00a0:: (a, b) -> a\ndef fst(tpl):\n    '''First member of a pair.'''\n    return tpl[0]\n\n\n# readFile\u00a0:: FilePath -> IO String\ndef readFile(fp):\n    '''The contents of any file at the path\n       derived by expanding any ~ in fp.'''\n    with open(expanduser(fp), 'r', encoding='utf-8') as f:\n        return f.read()\n\n\n# paddedMatrix\u00a0:: a -> [[a]] -> [[a]]\ndef paddedMatrix(v):\n    ''''A list of rows padded to equal length\n        (where needed) with instances of the value v.'''\n    def go(rows):\n        return paddedRows(\n            len(max(rows, key=len))\n        )(v)(rows)\n    return lambda rows: go(rows) if rows else []\n\n\n# paddedRows\u00a0:: Int -> a -> [[a]] -[[a]]\ndef paddedRows(n):\n    '''A list of rows padded (but never truncated)\n       to length n with copies of value v.'''\n    def go(v, xs):\n        def pad(x):\n            d = n - len(x)\n            return (x + list(repeat(v, d))) if 0 < d else x\n        return list(map(pad, xs))\n    return lambda v: lambda xs: go(v, xs) if xs else []\n\n\n# showColumns\u00a0:: Int -> [String] -> String\ndef showColumns(n):\n    '''A column-wrapped string\n       derived from a list of rows.'''\n    def go(xs):\n        def fit(col):\n            w = len(max(col, key=len))\n\n            def pad(x):\n                return x.ljust(4 + w, ' ')\n            return ''.join(map(pad, col)).rstrip()\n\n        q, r = divmod(len(xs), n)\n        return '\\n'.join(map(\n            fit,\n            zip(*paddedMatrix('')(\n                chunksOf(q + int(bool(r)))(xs)\n            ))\n        ))\n    return lambda xs: go(xs)\n\n\n# snd\u00a0:: (a, b) -> b\ndef snd(tpl):\n    '''Second member of a pair.'''\n    return tpl[1]\n\n\n# stet\u00a0:: a -> a\ndef stet(x):\n    '''The identity function.\n       The usual 'id' is reserved in Python.'''\n    return x\n\n\n# swap\u00a0:: (a, b) -> (b, a)\ndef swap(tpl):\n    '''The swapped components of a pair.'''\n    return (tpl[1], tpl[0])\n\n\n# tabulated\u00a0:: String -> (a -> String) ->\n#                        (b -> String) ->\n#                        Int ->\n#                        (a -> b) -> [a] -> String\ndef tabulated(s):\n    '''Heading -> x display function -> fx display function ->\n          number of columns -> f -> value list -> tabular string.'''\n    def go(xShow, fxShow, intCols, f, xs):\n        def mxw(fshow, g):\n            return max(map(compose(len)(fshow), map(g, xs)))\n        w = mxw(xShow, lambda x: x)\n        fw = mxw(fxShow, f)\n        return s + '\\n' + showColumns(intCols)([\n            xShow(x).rjust(w, ' ') + ' -> ' + (\n                fxShow(f(x)).rjust(fw, ' ')\n            )\n            for x in xs\n        ])\n    return lambda xShow: lambda fxShow: lambda nCols: (\n        lambda f: lambda xs: go(\n            xShow, fxShow, nCols, f, xs\n        )\n    )\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"open a text file, count the frequency of each letter (A to Z), and print the results. The counting process is expressed using fold\/reduce. The code can be imported into other Python scripts or used as a standalone script. It avoids unnecessary complexity by not using a numerically indexed array and by eliminating the need for converting letters into list indices.","id":4705}
    {"lang_cluster":"Python","source_code":"\n\nclass LinkedList(object):\n     \"\"\"USELESS academic\/classroom example of a linked list implemented in Python.\n        Don't ever consider using something this crude!  Use the built-in list() type!\n     \"\"\"\n\tclass Node(object):\n\t\tdef __init__(self, item):\n\t\t\tself.value  = item\n\t\t\tself.next = None\n\tdef __init__(self, item=None):\n\t\tif item is not None:\n\t\t\tself.head = Node(item); self.tail = self.head\n\t\telse:\n\t\t\tself.head = None; self.tail = None\n\tdef append(self, item):\n\t\tif not self.head:\n\t\t\tself.head = Node(item)\n\t\t\tself.tail = self.head\n\t\telif self.tail:\n\t\t\tself.tail.next = Node(item)\n\t\t\tself.tail = self.tail.next\n\t\telse:\n\t\t\tself.tail = Node(item)\n\tdef __iter__(self):\n\t\tcursor = self.head\n\t\twhile cursor:\n\t\t\tyield cursor.value\n\t\t\tcursor = cursor.next\n\n\n","human_summarization":"The code defines a data structure for a singly-linked list element. The element contains a numeric data member and a mutable link to the next element. The Node class also allows Pythonic iteration over linked lists. However, the implementation of linked lists and nodes in Python is considered an academic exercise. Methods for finding, counting, removing, and inserting elements are not included and left for the reader to implement. For practical applications, it's suggested to use built-in list() or dict() types.","id":4706}
    {"lang_cluster":"Python","source_code":"\nFile:Fractal-tree-python.png\nLibrary: pygame\nimport pygame, math\n\npygame.init()\nwindow = pygame.display.set_mode((600, 600))\npygame.display.set_caption(\"Fractal Tree\")\nscreen = pygame.display.get_surface()\n\ndef drawTree(x1, y1, angle, depth):\n    fork_angle = 20\n    base_len = 10.0\n    if depth > 0:\n        x2 = x1 + int(math.cos(math.radians(angle)) * depth * base_len)\n        y2 = y1 + int(math.sin(math.radians(angle)) * depth * base_len)\n        pygame.draw.line(screen, (255,255,255), (x1, y1), (x2, y2), 2)\n        drawTree(x2, y2, angle - fork_angle, depth - 1)\n        drawTree(x2, y2, angle + fork_angle, depth - 1)\n\ndef input(event):\n    if event.type == pygame.QUIT:\n        exit(0)\n\ndrawTree(300, 550, -90, 9)\npygame.display.flip()\nwhile True:\n    input(pygame.event.wait())\n\n","human_summarization":"generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.","id":4707}
    {"lang_cluster":"Python","source_code":"\n\n>>> def factors(n):\n      return [i for i in range(1, n + 1) if not n%i]\n\n>>> def factors(n):\n      return [i for i in range(1, n\/\/2 + 1) if not n%i] + [n]\n\n>>> factors(45)\n[1, 3, 5, 9, 15, 45]\n\nfrom math import isqrt\ndef factor(n):\n    factors1, factors2 = [], []\n    for x in range(1, isqrt(n)):\n        if n\u00a0% x == 0:\n            factors1.append(x)\n            factors2.append(n \/\/ x)\n    x += 1\n    if x * x == n:\n        factors1.append(x)\n    factors1.extend(reversed(factors2))\n    return factors1\n\nfor i in 45, 53, 64:\n    print(\"%i: factors: %s\"\u00a0% (i, factor(i)))45: factors: [1, 3, 5, 9, 15, 45]\n53: factors: [1, 53]\n64: factors: [1, 2, 4, 8, 16, 32, 64]\n\nfrom itertools import chain, cycle, accumulate # last of which is Python 3 only\n\ndef factors(n):\n    def prime_powers(n):\n        # c goes through 2, 3, 5, then the infinite (6n+1, 6n+5) series\n        for c in accumulate(chain([2, 1, 2], cycle([2,4]))):\n            if c*c > n: break\n            if n%c: continue\n            d,p = (), c\n            while not n%c:\n                n,p,d = n\/\/c, p*c, d + (p,)\n            yield(d)\n        if n > 1: yield((n,))\n\n    r = [1]\n    for e in prime_powers(n):\n        r += [a*b for a in r for b in e]\n    return r\n","human_summarization":"compute the factors of a positive integer, excluding zero and negative integers. The codes also consider the fact that every prime number has two factors, 1 and itself. The codes implement this task in four ways: a naive and slow method that checks all numbers from 1 to n, a slightly better method that realizes there are no factors between n\/2 and n, a much better method that realizes factors come in pairs, the smaller of which is no bigger than sqrt(n), and a more efficient method when factoring many numbers.","id":4708}
    {"lang_cluster":"Python","source_code":"\nfrom itertools import zip_longest\n\ntxt = \"\"\"Given$a$txt$file$of$many$lines,$where$fields$within$a$line$\nare$delineated$by$a$single$'dollar'$character,$write$a$program\nthat$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\ncolumn$are$separated$by$at$least$one$space.\nFurther,$allow$for$each$word$in$a$column$to$be$either$left$\njustified,$right$justified,$or$center$justified$within$its$column.\"\"\"\n \nparts = [line.rstrip(\"$\").split(\"$\") for line in txt.splitlines()]\nwidths = [max(len(word) for word in col) \n          for col in zip_longest(*parts, fillvalue='')]\n \nfor justify in \"<_Left ^_Center >_Right\".split():\n    j, jtext = justify.split('_')\n    print(f\"{jtext} column-aligned output:\\n\")\n    for line in parts:\n        print(' '.join(f\"{wrd:{j}{wdth}}\" for wdth, wrd in zip(widths, line)))\n    print(\"- \" * 52)\n\n\n","human_summarization":"The code reads a text file where each line's fields are separated by a dollar sign. It aligns each column of fields by ensuring at least one space between words in each column. The words in a column can be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. The code works with both Python 2 and 3, and uses a fold\/reduce between two transpositions for alignment. The string justification methods are selected via getattr.","id":4709}
    {"lang_cluster":"Python","source_code":"\ndef _pr(t, x, y, z):\n    txt = '\\n'.join(''.join(t[(n,m)] for n in range(3+x+z)).rstrip()\n                    for m in reversed(range(3+y+z)))\n    return txt\n\t\t\ndef cuboid(x,y,z):\n    t = {(n,m):' ' for n in range(3+x+z) for m in range(3+y+z)}\n    xrow = ['+'] + ['%i' % (i % 10) for i in range(x)] + ['+']\n    for i,ch in enumerate(xrow):\n        t[(i,0)] = t[(i,1+y)] = t[(1+z+i,2+y+z)] = ch\n    if _debug: print(_pr(t, x, y, z))\n    ycol = ['+'] + ['%i' % (j % 10) for j in range(y)] + ['+']\n    for j,ch in enumerate(ycol):\n        t[(0,j)] = t[(x+1,j)] = t[(2+x+z,1+z+j)] = ch\n    zdepth = ['+'] + ['%i' % (k % 10) for k in range(z)] + ['+']\n    if _debug: print(_pr(t, x, y, z))\n    for k,ch in enumerate(zdepth):\n        t[(k,1+y+k)] = t[(1+x+k,1+y+k)] = t[(1+x+k,k)] = ch\n\t\n    return _pr(t, x, y, z)\n\n\n_debug = False\nif __name__ == '__main__':\n    for dim in ((2,3,4), (3,4,2), (4,2,3)):\n        print(\"CUBOID%r\" % (dim,), cuboid(*dim), sep='\\n')\n\n\n","human_summarization":"The following codes output a graphical or ASCII art representation of a cuboid with dimensions 2x3x4. The cuboid has three visible faces and can be displayed either statically or in rotational projection. Additional features include the ability to rotate the cuboid, change its background, color, transparency, and material, display information about the scene and object, and a self-running demo mode.","id":4710}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.6\nLibrary: python-ldap\n\nimport ldap\n\nl = ldap.initialize(\"ldap:\/\/ldap.example.com\")\ntry:\n    l.protocol_version = ldap.VERSION3\n    l.set_option(ldap.OPT_REFERRALS, 0)\n\n    bind = l.simple_bind_s(\"me@example.com\", \"password\")\nfinally:\n    l.unbind()\n\n","human_summarization":"\"Establishes a connection to an Active Directory or Lightweight Directory Access Protocol server using python-ldap.\"","id":4711}
    {"lang_cluster":"Python","source_code":"\n\nWorks with: Python version 2.x\n>>> u'foo'.encode('rot13')\n'sbb'\n>>> 'sbb'.decode('rot13')\nu'foo'\n\nWorks with: Python version 2.x\nWorks with: Python version 3.x\n>>> import codecs\n>>> codecs.encode(\"The quick brown fox jumps over the lazy dog\", \"rot13\")\n'Gur dhvpx oebja sbk whzcf bire gur ynml qbt'\n>>> codecs.decode(_, \"rot13\")\n'The quick brown fox jumps over the lazy dog'\n\nWorks with: Python version 3.x\n#!\/usr\/bin\/env python\nimport string\n\nTRANSLATION_TABLE = str.maketrans(\n    string.ascii_uppercase + string.ascii_lowercase,\n    string.ascii_uppercase[13:] + string.ascii_uppercase[:13] +\n    string.ascii_lowercase[13:] + string.ascii_lowercase[:13]\n)\n\n\ndef rot13(s):\n    \"\"\"Return the rot-13 encoding of s.\"\"\"\n    return s.translate(TRANSLATION_TABLE)\n\n\nif __name__ == \"__main__\":\n    \"\"\"rot-13 encode the input files, or stdin if no files are provided.\"\"\"\n    import fileinput\n    for line in fileinput.input():\n        print(rot13(line), end=\"\")\n\nWorks with: Python version 3.x and Works with: Python version 2.7\n\n#!\/usr\/bin\/env python\nfrom __future__ import print_function\nimport string\nlets = string.ascii_lowercase\nkey = {x:y for (x,y) in zip(lets[13:]+lets[:14], lets)}\nkey.update({x.upper():key[x].upper() for x in key.keys()})\nencode = lambda x: ''.join((key.get(c,c) for c in x))\nif __name__ == '__main__':\n   \"\"\"Peform line-by-line rot-13 encoding on any files listed on our\n      command line or act as a standard UNIX filter (if no arguments\n      specified).\n   \"\"\"\n   import fileinput\n   for line in fileinput.input():\n      print(encode(line), end=\"\")\n","human_summarization":"Implement a rot-13 function that encodes every line of input from each file listed on the command line or from the standard input if no filenames are passed. The function replaces every ASCII alphabet letter with the letter rotated 13 characters around the 26 letter alphabet, wrapping around from z to a as necessary. It maintains case and passes all non-alphabetic characters without alteration. The function can be wrapped in a utility program similar to a common UNIX utility. The implementation also includes a dictionary comprehension to define the key for lowercase and uppercase mappings, and uses a generator expression in a lambda as the encoding function.","id":4712}
    {"lang_cluster":"Python","source_code":"\n\npeople = [('joe', 120), ('foo', 31), ('bar', 51)]\nsorted(people)\n\n\n[('bar', 51), ('foo', 31), ('joe', 120)]\n\n\nfrom operator import itemgetter\npeople = [(120, 'joe'), (31, 'foo'), (51, 'bar')]\npeople.sort(key=itemgetter(1))\n\n\n[(51, 'bar'), (31, 'foo'), (120, 'joe')]\n\n","human_summarization":"sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator. In Python, this can be achieved using the sorted() function and itemgetter for efficiency.","id":4713}
    {"lang_cluster":"Python","source_code":"\nimport sys\nfor i in xrange(5):\n    for j in xrange(i+1):\n        sys.stdout.write(\"*\")\n    print\n\nfor i in range(1,6):\n    print '*' * i\n\nprint('\\n'.join('*' * i for i in range(1, 6)))\n","human_summarization":"demonstrate how to nest two \"for\" loops, where the number of iterations in the inner loop is controlled by the outer loop. The code prints a specific pattern of asterisks, with each line containing one more asterisk than the previous line. The code is written in Python and follows a non-idiomatic style due to the constraint of using two \"for\" loops.","id":4714}
    {"lang_cluster":"Python","source_code":"\n\nhash = dict()  # 'dict' is the dictionary type.\nhash = dict(red=\"FF0000\", green=\"00FF00\", blue=\"0000FF\")\nhash = { 'key1':1, 'key2':2, }\nvalue = hash[key]\n\n# empty dictionary\nd = {}\nd['spam'] = 1\nd['eggs'] = 2  \n\n# dictionaries with two keys\nd1 = {'spam': 1, 'eggs': 2}\nd2 = dict(spam=1, eggs=2)\n\n# dictionaries from tuple list\nd1 = dict([('spam', 1), ('eggs', 2)])\nd2 = dict(zip(['spam', 'eggs'], [1, 2]))\n\n# iterating over keys\nfor key in d:\n  print key, d[key]\n\n# iterating over (key, value) pairs\nfor key, value in d.iteritems():\n  print key, value\n\nmyDict = { '1': 'a string', 1: 'an integer', 1.0: 'a floating point number', (1,): 'a tuple' }\n\n","human_summarization":"create an associative array or dictionary in Python using various methods. The keys can be of any hashable type and user-defined classes implementing the __hash__() method can also be used as keys. The unique ID of the instance object is often used for this purpose.","id":4715}
    {"lang_cluster":"Python","source_code":"\ndef bsd_rand(seed):\n   def rand():\n      rand.seed = (1103515245*rand.seed + 12345) & 0x7fffffff\n      return rand.seed\n   rand.seed = seed\n   return rand\n\ndef msvcrt_rand(seed):\n   def rand():\n      rand.seed = (214013*rand.seed + 2531011) & 0x7fffffff\n      return rand.seed >> 16\n   rand.seed = seed\n   return rand\n\nWorks with: Python version 3.x\ndef bsd_rand(seed):\n   def rand():\n      nonlocal seed\n      seed = (1103515245*seed + 12345) & 0x7fffffff\n      return seed\n   return rand\n\ndef msvcrt_rand(seed):\n   def rand():\n      nonlocal seed\n      seed = (214013*seed + 2531011) & 0x7fffffff\n      return seed >> 16\n   return rand\n\n","human_summarization":"The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.","id":4716}
    {"lang_cluster":"Python","source_code":"\ndef chain_insert(lst, at, item):\n    while lst is not None:\n        if lst[0] == at:\n            lst[1] = [item, lst[1]]\n            return\n        else:\n            lst = lst[1]\n    raise ValueError(str(at) + \" not found\")\n\nchain = ['A', ['B', None]]\nchain_insert(chain, 'A', 'C')\nprint chain\n\n\n['A', ['C', ['B', None]]]\n\n","human_summarization":"\"Implements a method to insert an element into a singly-linked list after a specified element, specifically inserting element C after element A in a list of elements A->B.\"","id":4717}
    {"lang_cluster":"Python","source_code":"\ntutor = True\n\ndef halve(x):\n    return x \/\/ 2\n\ndef double(x):\n    return x * 2\n\ndef even(x):\n    return not x % 2\n\ndef ethiopian(multiplier, multiplicand):\n    if tutor:\n        print(\"Ethiopian multiplication of %i and %i\" %\n              (multiplier, multiplicand))\n    result = 0\n    while multiplier >= 1:\n        if even(multiplier):\n            if tutor:\n                print(\"%4i %6i STRUCK\" %\n                      (multiplier, multiplicand))\n        else:\n            if tutor:\n                print(\"%4i %6i KEPT\" %\n                      (multiplier, multiplicand))\n            result += multiplicand\n        multiplier   = halve(multiplier)\n        multiplicand = double(multiplicand)\n    if tutor:\n        print()\n    return result\n\n\nPython 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> ethiopian(17, 34)\nEthiopian multiplication of 17 and 34\n  17     34 KEPT\n   8     68 STRUCK\n   4    136 STRUCK\n   2    272 STRUCK\n   1    544 KEPT\n\n578\n>>>\n\nhalve  = lambda x: x \/\/ 2\ndouble = lambda x: x*2\neven   = lambda x: not x\u00a0% 2\n \ndef ethiopian(multiplier, multiplicand):\n    result = 0\n\n    while multiplier >= 1:\n        if not even(multiplier):\n            result += multiplicand\n        multiplier   = halve(multiplier)\n        multiplicand = double(multiplicand)\n\n    return result\nUsing some features which Python has for use in functional programming. The example also tries to show how to mix different programming styles while keeping close to the task specification, a kind of \"executable pseudocode\". Note: While column2 could theoretically generate a sequence of infinite length, izip will stop requesting values from it (and so provide the necessary stop condition) when column1 has no more values. When not using the tutor, table will generate the table on the fly in an efficient way, not keeping any intermediate values.tutor = True\n\nfrom itertools import izip, takewhile\n\ndef iterate(function, arg):\n    while 1:\n        yield arg\n        arg = function(arg)\n\ndef halve(x): return x \/\/ 2\ndef double(x): return x * 2\ndef even(x): return x\u00a0% 2 == 0\n\ndef show_heading(multiplier, multiplicand):\n    print \"Multiplying %d by %d\"\u00a0% (multiplier, multiplicand),\n    print \"using Ethiopian multiplication:\"\n    print\n\nTABLE_FORMAT = \"%8s %8s %8s %8s %8s\"\n\ndef show_table(table):\n    for p, q in table:\n        print TABLE_FORMAT\u00a0% (p, q, \"->\",\n                              p, q if not even(p) else \"-\" * len(str(q)))\n\ndef show_result(result):\n    print TABLE_FORMAT\u00a0% ('', '', '', '', \"=\" * (len(str(result)) + 1))\n    print TABLE_FORMAT\u00a0% ('', '', '', '', result)\n\ndef ethiopian(multiplier, multiplicand):\n    def column1(x): return takewhile(lambda v: v >= 1, iterate(halve, x))\n    def column2(x): return iterate(double, x)\n    def rows(x, y): return izip(column1(x), column2(y))\n    table = rows(multiplier, multiplicand)\n    if tutor: \n        table = list(table)\n        show_heading(multiplier, multiplicand)\n        show_table(table)\n    result = sum(q for p, q in table if not even(p))\n    if tutor: \n        show_result(result)\n    return result\nExample output:\n>>> ethiopian(17, 34)\nMultiplying 17 by 34 using Ethiopian multiplication:\n\n     17       34       ->       17       34\n      8       68       ->        8       --\n      4      136       ->        4      ---\n      2      272       ->        2      ---\n      1      544       ->        1      544\n                                       ====\n                                        578\n578\nWorks with: Python version 3.7\n\n'''Ethiopian multiplication'''\n\nfrom functools import reduce\n\n\n# ethMult\u00a0:: Int -> Int -> Int\ndef ethMult(n):\n    '''Ethiopian multiplication of n by m.'''\n\n    def doubled(x):\n        return x + x\n\n    def halved(h):\n        qr = divmod(h, 2)\n        if 0 < h:\n            print('halve:', str(qr).rjust(8, ' '))\n        return qr if 0 < h else None\n\n    def addedWhereOdd(a, remx):\n        odd, x = remx\n        if odd:\n            print(\n                str(a).rjust(2, ' '), '+',\n                str(x).rjust(3, ' '), '->',\n                str(a + x).rjust(3, ' ')\n            )\n            return a + x\n        else:\n            print(str(x).rjust(8, ' '))\n            return a\n\n    return lambda m: reduce(\n        addedWhereOdd,\n        zip(\n            unfoldr(halved)(n),\n            iterate(doubled)(m)\n        ),\n        0\n    )\n\n\n# ------------------------- TEST -------------------------\ndef main():\n    '''Tests of multiplication.'''\n\n    print(\n        '\\nProduct:    ' + str(\n            ethMult(17)(34)\n        ),\n        '\\n_______________\\n'\n    )\n    print(\n        '\\nProduct:    ' + str(\n            ethMult(34)(17)\n        )\n    )\n\n\n# ----------------------- GENERIC ------------------------\n\n# iterate\u00a0:: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n    '''An infinite list of repeated\n       applications of f to x.\n    '''\n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return go\n\n\n# showLog\u00a0:: a -> IO String\ndef showLog(*s):\n    '''Arguments printed with\n       intercalated arrows.'''\n    print(\n        ' -> '.join(map(str, s))\n    )\n\n\n# unfoldr\u00a0:: (b -> Maybe (a, b)) -> b -> [a]\ndef unfoldr(f):\n    '''Dual to reduce or foldr.\n       Where catamorphism reduces a list to a summary value,\n       the anamorphic unfoldr builds a list from a seed value.\n       As long as f returns Just(a, b), a is prepended to the list,\n       and the residual b is used as the argument for the next\n       application of f.\n       When f returns Nothing, the completed list is returned.'''\n    def go(v):\n        xr = v, v\n        xs = []\n        while True:\n            xr = f(xr[0])\n            if xr:\n                xs.append(xr[1])\n            else:\n                return xs\n        return xs\n    return go\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n","human_summarization":"The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method that multiplies two integers using only addition, doubling, and halving operations. The multiplication result is obtained by summing certain values from a table generated during the process.","id":4718}
    {"lang_cluster":"Python","source_code":"\n\n'''\n The 24 Game Player\n \n Given any four digits in the range 1 to 9, which may have repetitions,\n Using just the +, -, *, and \/ operators; and the possible use of\n brackets, (), show how to make an answer of 24.\n \n An answer of \"q\"  will quit the game.\n An answer of \"!\"  will generate a new set of four digits.\n An answer of \"!!\" will ask you for a new set of four digits.\n An answer of \"?\"  will compute an expression for the current digits.\n \n Otherwise you are repeatedly asked for an expression until it evaluates to 24\n \n Note: you cannot form multiple digit numbers from the supplied digits,\n so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n \n'''\n \nfrom   __future__ import division, print_function\nfrom   itertools  import permutations, combinations, product, \\\n                         chain\nfrom   pprint     import pprint as pp\nfrom   fractions  import Fraction as F\nimport random, ast, re\nimport sys\n \nif sys.version_info[0] < 3:\n    input = raw_input\n    from itertools import izip_longest as zip_longest\nelse:\n    from itertools import zip_longest\n \n \ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n \ndef ask4():\n    'get four random digits >0 from the player'\n    digits = ''\n    while len(digits) != 4 or not all(d in '123456789' for d in digits):\n        digits = input('Enter the digits to solve for: ')\n        digits = ''.join(digits.strip().split())\n    return list(digits)\n \ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n \ndef check(answer, digits):\n    allowed = set('() +-*\/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n \ndef solve(digits):\n    \"\"\"\\\n    >>> for digits in '3246 4788 1111 123456 1127 3838'.split():\n            solve(list(digits))\n \n \n    Solution found: 2 + 3 * 6 + 4\n    '2 + 3 * 6 + 4'\n    Solution found: ( 4 + 7 - 8 ) * 8\n    '( 4 + 7 - 8 ) * 8'\n    No solution found for: 1 1 1 1\n    '!'\n    Solution found: 1 + 2 + 3 * ( 4 + 5 ) - 6\n    '1 + 2 + 3 * ( 4 + 5 ) - 6'\n    Solution found: ( 1 + 2 ) * ( 1 + 7 )\n    '( 1 + 2 ) * ( 1 + 7 )'\n    Solution found: 8 \/ ( 3 - 8 \/ 3 )\n    '8 \/ ( 3 - 8 \/ 3 )'\n    >>> \"\"\"\n    digilen = len(digits)\n    # length of an exp without brackets \n    exprlen = 2 * digilen - 1\n    # permute all the digits\n    digiperm = sorted(set(permutations(digits)))\n    # All the possible operator combinations\n    opcomb   = list(product('+-*\/', repeat=digilen-1))\n    # All the bracket insertion points:\n    brackets = ( [()] + [(x,y)\n                         for x in range(0, exprlen, 2)\n                         for y in range(x+4, exprlen+2, 2)\n                         if (x,y) != (0,exprlen+1)]\n                 + [(0, 3+1, 4+2, 7+3)] ) # double brackets case\n    for d in digiperm:\n        for ops in opcomb:\n            if '\/' in ops:\n                d2 = [('F(%s)' % i) for i in d] # Use Fractions for accuracy\n            else:\n                d2 = d\n            ex = list(chain.from_iterable(zip_longest(d2, ops, fillvalue='')))\n            for b in brackets:\n                exp = ex[::]\n                for insertpoint, bracket in zip(b, '()'*(len(b)\/\/2)):\n                    exp.insert(insertpoint, bracket)\n                txt = ''.join(exp)\n                try:\n                    num = eval(txt)\n                except ZeroDivisionError:\n                    continue\n                if num == 24:\n                    if '\/' in ops:\n                        exp = [ (term if not term.startswith('F(') else term[2])\n                               for term in exp ]\n                    ans = ' '.join(exp).rstrip()\n                    print (\"Solution found:\",ans)\n                    return ans\n    print (\"No solution found for:\", ' '.join(digits))            \n    return '!'\n \ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer == '?':\n            solve(digits)\n            answer = '!'\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            trial = 0\n            print (\"\\nNew digits:\", ' '.join(digits))\n            continue\n        if answer == '!!':\n            digits = ask4()\n            trial = 0\n            print (\"\\nNew digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            if '\/' in answer:\n                # Use Fractions for accuracy in divisions\n                answer = ''.join( (('F(%s)' % char) if char in '123456789' else char)\n                                  for char in answer )\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n \nmain()\n\n\n","human_summarization":"The code takes four digits as input, either from the user or randomly generated, and calculates arithmetic expressions according to the rules of the 24 game. It includes a function called 'solve' that is integrated into the game player. The function switches to precise fractional arithmetic during division to accurately solve and recognize cases that do not equal 24 due to Python's double-precision floating point. The code can handle any number of digits by recursively merging two numbers using all available operands until only one value remains.","id":4719}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.6+, 3.x\nimport math\nmath.factorial(n)\ndef factorial(n):\n    result = 1\n    for i in range(1, n+1):\n        result *= i\n    return result\nfrom operator import mul\nfrom functools import reduce\n\ndef factorial(n):\n    return reduce(mul, range(1,n+1), 1)\n\nfrom itertools import (accumulate, chain)\nfrom operator import mul\n\n# factorial\u00a0:: Integer\ndef factorial(n):\n    return list(\n        accumulate(chain([1], range(1, 1 + n)), mul)\n    )[-1]\n\nfrom itertools import (accumulate, chain)\nfrom operator import mul\n\n\n# factorials\u00a0:: [Integer]\ndef factorials(n):\n    return list(\n        accumulate(chain([1], range(1, 1 + n)), mul)\n    )\n\nprint(factorials(5))\n\n# -> [1, 1, 2, 6, 24, 120]\n\nfrom numpy import prod\n\ndef factorial(n):\n    return prod(range(1, n + 1), dtype=int)\ndef factorial(n):\n    z=1\n    if n>1:\n        z=n*factorial(n-1)\n    return z\n\n","human_summarization":"implement a function that calculates the factorial of a given number. The function can be either iterative or recursive. It optionally includes error handling for negative input values. The factorial function is defined as the product of a sequence from the given positive integer down to 1. The code may also include a Lanczos approximation to approximate the gamma function, which extends the domain of the factorial function.","id":4720}
    {"lang_cluster":"Python","source_code":"\n'''\n Bulls and cows. A game pre-dating, and similar to, Mastermind.\n'''\n\nimport random\n\ndigits = '123456789'\nsize = 4\nchosen = ''.join(random.sample(digits,size))\n#print chosen # Debug\nprint '''I have chosen a number from %s unique digits from 1 to 9 arranged in a random order.\nYou need to input a %i digit, unique digit number as a guess at what I have chosen''' % (size, size)\nguesses = 0\nwhile True:\n    guesses += 1\n    while True:\n        # get a good guess\n        guess = raw_input('\\nNext guess [%i]: ' % guesses).strip()\n        if len(guess) == size and \\\n           all(char in digits for char in guess) \\\n           and len(set(guess)) == size:\n            break\n        print \"Problem, try again. You need to enter %i unique digits from 1 to 9\" % size\n    if guess == chosen:\n        print '\\nCongratulations you guessed correctly in',guesses,'attempts'\n        break\n    bulls = cows = 0\n    for i in range(size):\n        if guess[i] == chosen[i]:\n            bulls += 1\n        elif guess[i] in chosen:\n            cows += 1\n    print '  %i Bulls\\n  %i Cows' % (bulls, cows)\n\n\nI have chosen a number from 4 unique digits from 1 to 9 arranged in a random order.\nYou need to input a 4 digit, unique digit number as a guess at what I have chosen\n\nNext guess [1]: 79\nProblem, try again. You need to enter 4 unique digits from 1 to 9\n\nNext guess [1]: 7983\n  2 Bulls\n  2 Cows\n\nNext guess [2]: 7938\n\nCongratulations you guessed correctly in 2 attempts\n","human_summarization":"The code generates a four-digit random number from 1 to 9 without duplication. It prompts the user for guesses, rejects malformed guesses, and calculates a score based on the guess. The score is determined by the number of 'bulls' and 'cows', where a 'bull' is a correct digit in the correct position, and a 'cow' is a correct digit in the wrong position. The game ends when the user's guess matches the generated number.","id":4721}
    {"lang_cluster":"Python","source_code":"\nUsing random.gauss\n\n>>> import random\n>>> values = [random.gauss(1, .5) for i in range(1000)]\n>>>\n\nQuick check of distribution\n\n>>> def quick_check(numbers):\n    count = len(numbers)\n    mean = sum(numbers) \/ count\n    sdeviation = (sum((i - mean)**2 for i in numbers) \/ count)**0.5\n    return mean, sdeviation\n\n>>> quick_check(values)\n(1.0140373306786599, 0.49943411329234066)\n>>>\n\n\nAlternatively using random.normalvariate\n\n>>> values = [ random.normalvariate(1, 0.5) for i in range(1000)]\n>>> quick_check(values)\n(0.990099111944864, 0.5029847005836282)\n>>>\n\n","human_summarization":"generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5, using the random module in the Python standard library or other libraries if necessary.","id":4722}
    {"lang_cluster":"Python","source_code":"\ndef dotp(a,b):\n    assert len(a) == len(b), 'Vector sizes must match'\n    return sum(aterm * bterm for aterm,bterm in zip(a, b))\n\nif __name__ == '__main__':\n    a, b = [1, 3, -5], [4, -2, -1]\n    assert dotp(a,b) == 3\n\n\nWorks with: Python version 3.7\n'''Dot product'''\n\nfrom operator import (mul)\n\n\n# dotProduct\u00a0:: Num a => [a] -> [a] -> Either String a\ndef dotProduct(xs):\n    '''Either the dot product of xs and ys,\n       or a string reporting unmatched vector sizes.\n    '''\n    return lambda ys: Left('vector sizes differ') if (\n        len(xs) != len(ys)\n    ) else Right(sum(map(mul, xs, ys)))\n\n\n# TEST ----------------------------------------------------\n# main\u00a0:: IO ()\ndef main():\n    '''Dot product of other vectors with [1, 3, -5]'''\n\n    print(\n        fTable(main.__doc__ + ':\\n')(str)(str)(\n            compose(\n                either(append('Undefined\u00a0:: '))(str)\n            )(dotProduct([1, 3, -5]))\n        )([[4, -2, -1, 8], [4, -2], [4, 2, -1], [4, -2, -1]])\n    )\n\n\n# GENERIC -------------------------------------------------\n\n# Left\u00a0:: a -> Either a b\ndef Left(x):\n    '''Constructor for an empty Either (option type) value\n       with an associated string.\n    '''\n    return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right\u00a0:: b -> Either a b\ndef Right(x):\n    '''Constructor for a populated Either (option type) value'''\n    return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# append (++)\u00a0:: [a] -> [a] -> [a]\n# append (++)\u00a0:: String -> String -> String\ndef append(xs):\n    '''Two lists or strings combined into one.'''\n    return lambda ys: xs + ys\n\n\n# compose (<<<)\u00a0:: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n    '''Right to left function composition.'''\n    return lambda f: lambda x: g(f(x))\n\n\n# either\u00a0:: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n    '''The application of fl to e if e is a Left value,\n       or the application of fr to e if e is a Right value.\n    '''\n    return lambda fr: lambda e: fl(e['Left']) if (\n        None is e['Right']\n    ) else fr(e['Right'])\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable\u00a0:: String -> (a -> String) ->\n#                     (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n    '''Heading -> x display function -> fx display function ->\n                     f -> xs -> tabular string.\n    '''\n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"The code implements a function to compute the dot product of two vectors of arbitrary length. It ensures that both vectors are of the same length, multiplies corresponding terms from each vector, and sums the products to produce the final result. It also includes an Either type for error handling, which returns either a computed value or an explanatory string.","id":4723}
    {"lang_cluster":"Python","source_code":"\n\nwhile(True):\n      x = input(\"What is your age? \")\n      print(x)\n\n\nmy_file = open(filename, 'r')\ntry:\n    for line in my_file:\n        pass # process line, includes newline\nfinally:\n    my_file.close()\n\n\n#from __future__ import with_statement  # is not needed in Python 3.6\n\nwith open(filename, 'r') as f:\n    for line in f:\n        pass # process line, includes newline\n\n\nline = my_file.readline() # returns a line from the file\nlines = my_file.readlines() # returns a list of the rest of the lines from the file\n\n\nimport fileinput\nfor line in fileinput.input():\n    pass # process line, includes newline\n\n\n","human_summarization":"\"Implements a Python3 input loop that reads data from a text stream either word-by-word or line-by-line until the stream is exhausted. The code uses Python's `input()` function and treats file objects as iterable lists. It also includes functionality to manually retrieve lines from a file, open and automatically close a new stream for reading with a 'with' statement, and handle reading from stdin or multiple filenames given on the command line. Additionally, it utilizes the fileinput module for inplace file editing, tracking line counts, and identifying the current file being read.\"","id":4724}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.5\nfrom xml.dom.minidom import getDOMImplementation\n\ndom = getDOMImplementation()\ndocument = dom.createDocument(None, \"root\", None)\n\ntopElement = document.documentElement\nfirstElement = document.createElement(\"element\")\ntopElement.appendChild(firstElement)\ntextNode = document.createTextNode(\"Some text here\")\nfirstElement.appendChild(textNode)\n\nxmlString = document.toprettyxml(\" \" * 4)\n\nfrom xml.etree import ElementTree as et\n\nroot = et.Element(\"root\")\net.SubElement(root, \"element\").text = \"Some text here\"\nxmlString = et.tostring(root)\n\n","human_summarization":"Create a simple DOM and serialize it into the specified XML format.","id":4725}
    {"lang_cluster":"Python","source_code":"\nimport time\nprint time.ctime()\n","human_summarization":"the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.","id":4726}
    {"lang_cluster":"Python","source_code":"\ndef char2value(c):\n  assert c not in 'AEIOU', \"No vowels\"\n  return int(c, 36)\n\nsedolweight = [1,3,1,7,3,9]\n\ndef checksum(sedol):\n    tmp = sum(map(lambda ch, weight: char2value(ch) * weight,\n                  sedol, sedolweight)\n               )\n    return str((10 - (tmp % 10)) % 10)\n\nfor sedol in '''\n    710889\n    B0YBKJ\n    406566\n    B0YBLH\n    228276\n    B0YBKL\n    557910\n    B0YBKR\n    585284\n    B0YBKT\n    '''.split():\n    print sedol + checksum(sedol)\n\n\nWorks with: Python version 3.7\n'''SEDOL checksum digits'''\n\nfrom functools import reduce\n\n\n# sedolCheckSumDigitLR\u00a0:: String -> Either String Char\ndef sedolCheckSumDigitLR(s):\n    '''Either an explanatory message, or a\n       checksum digit character to append\n       to a given six-character SEDOL string.\n    '''\n    def goLR(lr, cn):\n        c, n = cn\n        return bindLR(lr)(\n            lambda a: bindLR(sedolValLR(c))(\n                lambda x: Right(a + x * n)\n            )\n        )\n    return bindLR(\n        reduce(\n            goLR,\n            zip(s, [1, 3, 1, 7, 3, 9]),\n            Right(0)\n        )\n    )(lambda d: Right(str((10 - (d % 10)) % 10)))\n\n\n# sedolValLR\u00a0:: Char -> Either String Char\ndef sedolValLR(c):\n    '''Either an explanatory message, or the\n       SEDOL value of a given character.\n    '''\n    return Right(int(c, 36)) if (\n        c not in 'AEIOU'\n    ) else Left('Unexpected vowel in SEDOL string: ' + c)\n\n\n# TEST -------------------------------------------------\ndef main():\n    '''Append checksums where valid.'''\n\n    print(\n        fTable(__doc__ + ':\\n')(str)(\n            either(str)(str)\n        )(sedolCheckSumDigitLR)(\n            '''710889\n               B0YBKJ\n               406566\n               B0YBLH\n               228276\n               B0YBKL\n               BOYBKL\n               557910\n               B0YBKR\n               585284\n               B0YBKT\n               B00030\n            '''.split()\n        )\n    )\n\n\n# GENERIC -------------------------------------------------\n\n\n# Left\u00a0:: a -> Either a b\ndef Left(x):\n    '''Constructor for an empty Either (option type) value\n       with an associated string.'''\n    return {'type': 'Either', 'Right': None, 'Left': x}\n\n\n# Right\u00a0:: b -> Either a b\ndef Right(x):\n    '''Constructor for a populated Either (option type) value'''\n    return {'type': 'Either', 'Left': None, 'Right': x}\n\n\n# bindLR (>>=)\u00a0:: Either a -> (a -> Either b) -> Either b\ndef bindLR(m):\n    '''Either monad injection operator.\n       Two computations sequentially composed,\n       with any value produced by the first\n       passed as an argument to the second.'''\n    return lambda mf: (\n        mf(m.get('Right')) if None is m.get('Left') else m\n    )\n\n\n# compose (<<<)\u00a0:: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n    '''Right to left function composition.'''\n    return lambda f: lambda x: g(f(x))\n\n\n# either\u00a0:: (a -> c) -> (b -> c) -> Either a b -> c\ndef either(fl):\n    '''The application of fl to e if e is a Left value,\n       or the application of fr to e if e is a Right value.'''\n    return lambda fr: lambda e: fl(e['Left']) if (\n        None is e['Right']\n    ) else fr(e['Right'])\n\n\n# fTable\u00a0:: String -> (a -> String) ->\n#                     (b -> String) ->\n#        (a -> b) -> [a] -> String\ndef fTable(s):\n    '''Heading -> x display function -> fx display function ->\n          f -> value list -> tabular string.'''\n    def go(xShow, fxShow, f, xs):\n        w = max(map(compose(len)(xShow), xs))\n        return s + '\\n' + '\\n'.join([\n            xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs\n        ])\n    return lambda xShow: lambda fxShow: (\n        lambda f: lambda xs: go(\n            xShow, fxShow, f, xs\n        )\n    )\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"The code takes a list of 6-digit SEDOLs as input, calculates and appends the checksum digit for each SEDOL. It also validates the input to ensure it contains only valid characters allowed in a SEDOL string. In case of disallowed characters, it handles them without assertion errors using reduce with an option type.","id":4727}
    {"lang_cluster":"Python","source_code":"\nimport math\n\nshades = ('.',':','!','*','o','e','&','#','%','@')\n\ndef normalize(v):\n\tlen = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)\n\treturn (v[0]\/len, v[1]\/len, v[2]\/len)\n\ndef dot(x,y):\n\td = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]\n\treturn -d if d < 0 else 0\n\ndef draw_sphere(r, k, ambient, light):\n\tfor i in range(int(math.floor(-r)),int(math.ceil(r)+1)):\n\t\tx = i + 0.5\n\t\tline = ''\n\n\t\tfor j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):\n\t\t\ty = j\/2 + 0.5\n\t\t\tif x*x + y*y <= r*r:\n\t\t\t\tvec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))\n\t\t\t\tb = dot(light,vec)**k + ambient\n\t\t\t\tintensity = int((1-b)*(len(shades)-1))\n\t\t\t\tline += shades[intensity] if 0 <= intensity < len(shades) else shades[0]\n\t\t\telse:\n\t\t\t\tline += ' '\n\n\t\tprint(line)\n\nlight = normalize((30,30,-50))\ndraw_sphere(20,4,0.1, light)\ndraw_sphere(10,2,0.4, light)\n\n\n","human_summarization":"The code utilizes Pygame and Python 3.2.2 to graphically or ASCII art represent a sphere, which can be either static or rotational. It also incorporates random Perlin noise for rendering the sphere. Some unnecessary functions from a 3D graphics library are included in the code.","id":4728}
    {"lang_cluster":"Python","source_code":"\n_suffix = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th']\n\ndef nth(n):\n    return \"%i'%s\" % (n, _suffix[n%10] if n % 100 <= 10 or n % 100 > 20 else 'th')\n\nif __name__ == '__main__':\n    for j in range(0,1001, 250):\n        print(' '.join(nth(i) for i in list(range(j, j+25))))\n\n\n","human_summarization":"The code generates ordinal suffixes for given integers, returning a string of the number followed by an apostrophe and the ordinal suffix. The function handles integer inputs within the ranges of 0 to 25, 250 to 265, and 1000 to 1025. Apostrophes in the output are optional.","id":4729}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.6+\n>>> def stripchars(s, chars):\n...     return s.translate(None, chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n\nWorks with: Python version 2.x\n>>> import string\n>>> def stripchars(s, chars):\n...     return s.translate(string.maketrans(\"\", \"\"), chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n\n\n>>> def stripchars(s, chars):\n...     return \"\".join(c for c in s if c not in chars)\n... \n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n\n>>> import re\n>>> def stripchars(s, chars):\n\treturn re.sub('[%s]+' % re.escape(chars), '', s)\n\n>>> stripchars(\"She was a soul stripper. She took my heart!\", \"aei\")\n'Sh ws  soul strppr. Sh took my hrt!'\n>>>\n\n","human_summarization":"\"Function to remove a set of specified characters from a given string.\"","id":4730}
    {"lang_cluster":"Python","source_code":"\ndef genfizzbuzz(factorwords, numbers):\n    # sort entries by factor\n    factorwords.sort(key=lambda factor_and_word: factor_and_word[0])\n    lines = []\n    for num in numbers:\n        words = ''.join(word for factor, word in factorwords if (num % factor) == 0)\n        lines.append(words if words else str(num))\n    return '\\n'.join(lines)\n\nif __name__ == '__main__':\n    print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))\n\n\n","human_summarization":"\"Implement a generalized version of FizzBuzz that accepts user-defined parameters including a maximum number and three factors each with an associated word. The program prints numbers from 1 to the maximum number, replacing multiples of the given factors with their corresponding words. In case a number is a multiple of more than one factor, it prints all associated words in the order of the factors. The program also handles ranges and preserves order and duplicate moduli.\"","id":4731}
    {"lang_cluster":"Python","source_code":"\n\n#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\n\ns = \"12345678\"\ns = \"0\" + s  # by concatenation\nprint(s)\n\n\n","human_summarization":"create a string variable, prepend it with another string literal, and display the content of the variable. If possible, the task should be accomplished without referring to the variable twice in one expression.","id":4732}
    {"lang_cluster":"Python","source_code":"Library: turtle\nfrom turtle import *\n\ndef dragon(step, length):\n    dcr(step, length)\n\ndef dcr(step, length):\n    step -= 1\n    length \/= 1.41421\n    if step > 0:\n        right(45)\n        dcr(step, length)\n        left(90)\n        dcl(step, length)\n        right(45)\n    else:\n        right(45)\n        forward(length)\n        left(90)\n        forward(length)\n        right(45)\n\ndef dcl(step, length):\n    step -= 1\n    length \/= 1.41421\n\n    if step > 0:\n        left(45)\n        dcr(step, length)\n        right(90)\n        dcl(step, length)\n        left(45)\n    else:\n        left(45)\n        forward(length)\n        right(90)\n        forward(length)\n        left(45)\n\n\nfrom turtle import right, left, forward, speed, exitonclick, hideturtle\n\ndef dragon(level=4, size=200, zig=right, zag=left):\n    if level <= 0:\n        forward(size)\n        return\n\n    size \/= 1.41421\n    zig(45)\n    dragon(level-1, size, right, left)\n    zag(90)\n    dragon(level-1, size, left, right)\n    zig(45)\n\nspeed(0)\nhideturtle()\ndragon(6)\nexitonclick() # click to exit\n\n\nfrom turtle import right, left, forward, speed, exitonclick, hideturtle\n\ndef dragon(level=4, size=200, direction=45):\n    if level:\n        right(direction)\n        dragon(level-1, size\/1.41421356237, 45)\n        left(direction * 2)\n        dragon(level-1, size\/1.41421356237, -45)\n        right(direction)\n    else:\n        forward(size)\n\nspeed(0)\nhideturtle()\ndragon(6)\nexitonclick() # click to exit\n\n","human_summarization":"The code generates a dragon curve fractal, either displaying it directly or writing it to an image file. It uses recursive, successive approximation, iterative, and Lindenmayer system methods to create the fractal. The code also includes functionality to calculate the absolute direction and X, Y coordinates of a point, and to test whether a given point or segment is on the curve. It can handle different curl directions and expansion levels, and can draw other curves defined by L-systems.","id":4733}
    {"lang_cluster":"Python","source_code":"\nimport random\nt,g=random.randint(1,10),0\ng=int(input(\"Guess a number that's between 1 and 10: \"))\nwhile t!=g:g=int(input(\"Guess again! \"))\nprint(\"That's right!\")\n\n\nimport random #milliard.py\nh1 = 0; h2 = 10**16; t = 0; f=0\nc = random.randrange(0,h2) #comp\nh = random.randrange(0,h2) #human DANILIN\n\nwhile f<1:\n    print(t,c,h)\n\n    if h<c:\n        print('MORE')\n        a=h\n        h=int((h+h2)\/2)\n        h1=a\n\n    elif h>c:\n        print('less')\n        a=h\n        h=int((h1+h)\/2)\n        h2=a\n\n    else:\n        print('win by', t, 'steps')\n        f=1\n    t=t+1\n\n\n","human_summarization":"The code is a number guessing game. The program randomly selects a number between 1 and 10. The user is then prompted to guess the number. If the guess is incorrect, the user is prompted to guess again. This continues until the user guesses correctly, at which point the program displays a \"Well guessed!\" message and terminates. The process of guessing is implemented using a conditional loop.","id":4734}
    {"lang_cluster":"Python","source_code":"\n# From the standard library:\nfrom string import ascii_lowercase\n\n# Generation:\nlower = [chr(i) for i in range(ord('a'), ord('z') + 1)]\n\nWorks with: Python version 3.7\n'''Enumeration a-z'''\n\nfrom inspect import signature\nimport enum\n\n\n# TEST ----------------------------------------------------\ndef main():\n    '''Testing particular instances of a general pattern:\n    '''\n    print(\n        fTable(__doc__ + ':\\n')(repr)(showList)(\n            uncurry(enumFromTo)\n        )([\n            ('a', 'z'),\n            ('\u03b1', '\u03c9'),\n            ('\u05d0', '\u05ea'),\n            (1, 10),\n            (round((5**(1 \/ 2) - 1) \/ 2, 5), 5),\n            ('\ud83c\udf31', '\ud83c\udf42')\n        ])\n    )\n\n\n# GENERIC -------------------------------------------------\n\n# enumFromTo\u00a0:: Enum a => a -> a -> [a]\ndef enumFromTo(m):\n    '''Enumeration of values [m..n]'''\n    def go(x, y):\n        t = type(m)\n        i = fromEnum(x)\n        d = 0 if t\u00a0!= float else (x - i)\n        return list(map(\n            lambda x: toEnum(t)(d + x),\n            range(i, 1 + fromEnum(y))\n        ) if int\u00a0!= t else range(x, 1 + y))\n    return lambda n: go(m, n)\n\n\n# fromEnum\u00a0:: Enum a => a -> Int\ndef fromEnum(x):\n    '''Index integer for enumerable value.'''\n    Enum = enum.Enum\n    return ord(x) if isinstance(x, str) else (\n        x.value if isinstance(x, Enum) else int(x)\n    )\n\n\n# toEnum\u00a0:: Type -> Int -> a\ndef toEnum(t):\n    '''Enumerable value from index integer'''\n    dct = {\n        int: int,\n        float: float,\n        str: chr,\n        bool: bool\n    }\n    return lambda x: dct[t](x) if t in dct else t(x)\n\n\n# uncurry\u00a0:: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n    '''A function over a tuple, derived from\n       a vanilla or curried function.\n    '''\n    if 1 < len(signature(f).parameters):\n        return lambda xy: f(*xy)\n    else:\n        return lambda xy: f(xy[0])(xy[1])\n\n\n# FORMATTING -------------------------------------------------\n\n# fTable\u00a0:: String -> (a -> String) ->\n#                     (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n    '''Heading -> x display function -> fx display function ->\n                     f -> xs -> tabular string.\n    '''\n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n# showList\u00a0:: [a] -> String\ndef showList(xs):\n    '''Stringification of a list.'''\n    return '[' + ','.join(str(x) for x in xs) + ']'\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n","human_summarization":"generate a sequence of all lower case ASCII characters from 'a' to 'z' using a reliable coding style suitable for a large program, with strong typing if available. The code avoids manual enumeration of characters to reduce bugs. It also demonstrates accessing a similar sequence from the standard library if available.","id":4735}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 3.X and 2.6+\n>>> for i in range(16): print('{0:b}'.format(i))\n\n0\n1\n10\n11\n100\n101\n110\n111\n1000\n1001\n1010\n1011\n1100\n1101\n1110\n1111\nWorks with: Python version 3.X and 2.6+\n>>> for i in range(16): print(bin(i)[2:])\n\n0\n1\n10\n11\n100\n101\n110\n111\n1000\n1001\n1010\n1011\n1100\n1101\n1110\n1111\n\n>>> oct2bin = {'0': '000', '1': '001', '2': '010', '3': '011', '4': '100', '5': '101', '6': '110', '7': '111'}\n>>> bin = lambda n: ''.join(oct2bin[octdigit] for octdigit in '%o'\u00a0% n).lstrip('0') or '0'\n>>> for i in range(16): print(bin(i))\n\n0\n1\n10\n11\n100\n101\n110\n111\n1000\n1001\n1010\n1011\n1100\n1101\n1110\n1111\n\n'''Binary strings for integers'''\n\n\n# showBinary\u00a0:: Int -> String\ndef showBinary(n):\n    '''Binary string representation of an integer.'''\n    def binaryChar(n):\n        return '1' if n\u00a0!= 0 else '0'\n    return showIntAtBase(2)(binaryChar)(n)('')\n\n\n# TEST ----------------------------------------------------\n\n# main\u00a0:: IO()\ndef main():\n    '''Test'''\n\n    print('Mapping showBinary over integer list:')\n    print(unlines(map(\n        showBinary,\n        [5, 50, 9000]\n    )))\n\n    print(tabulated(\n        '\\nUsing showBinary as a display function:'\n    )(str)(showBinary)(\n        lambda x: x\n    )([5, 50, 9000]))\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<)\u00a0:: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n    '''Right to left function composition.'''\n    return lambda f: lambda x: g(f(x))\n\n\n# enumFromTo\u00a0:: (Int, Int) -> [Int]\ndef enumFromTo(m):\n    '''Integer enumeration from m to n.'''\n    return lambda n: list(range(m, 1 + n))\n\n\n# showIntAtBase\u00a0:: Int -> (Int -> String) -> Int -> String -> String\ndef showIntAtBase(base):\n    '''String representing a non-negative integer\n       using the base specified by the first argument,\n       and the character representation specified by the second.\n       The final argument is a (possibly empty) string to which\n       the numeric string will be prepended.'''\n    def wrap(toChr, n, rs):\n        def go(nd, r):\n            n, d = nd\n            r_ = toChr(d) + r\n            return go(divmod(n, base), r_) if 0\u00a0!= n else r_\n        return 'unsupported base' if 1 >= base else (\n            'negative number' if 0 > n else (\n                go(divmod(n, base), rs))\n        )\n    return lambda toChr: lambda n: lambda rs: (\n        wrap(toChr, n, rs)\n    )\n\n\n# tabulated\u00a0:: String -> (a -> String) ->\n#                        (b -> String) ->\n#                        (a -> b) -> [a] -> String\ndef tabulated(s):\n    '''Heading -> x display function -> fx display function ->\n                f -> value list -> tabular string.'''\n    def go(xShow, fxShow, f, xs):\n        w = max(map(compose(len)(xShow), xs))\n        return s + '\\n' + '\\n'.join(\n            xShow(x).rjust(w, ' ') + ' -> ' + fxShow(f(x)) for x in xs\n        )\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n# unlines\u00a0:: [String] -> String\ndef unlines(xs):\n    '''A single string derived by the intercalation\n       of a list of strings with the newline character.'''\n    return '\\n'.join(xs)\n\n\nif __name__ == '__main__':\n    main()\n\n","human_summarization":"\"Generates and displays a sequence of binary digits for a given non-negative integer. The output consists solely of the binary digits of each number, followed by a newline, without any additional whitespace, radix, or sign markers, and does not include leading zeros. The function can utilize built-in radix functions or a user-defined function to achieve the results.\"","id":4736}
    {"lang_cluster":"Python","source_code":"\n# to install pandas library go to cmd prompt and type:\n# cd %USERPROFILE%\\AppData\\Local\\Programs\\Python\\Python38-32\\Scripts\\\n# pip install pandas\nimport pandas as pd\n\n# load data from csv files\ndf_patients = pd.read_csv (r'patients.csv', sep = \",\", decimal=\".\")\ndf_visits = pd.read_csv (r'visits.csv', sep = \",\", decimal=\".\")\n\n''' # load data hard coded, create data frames\nimport io\nstr_patients = \"\"\"PATIENT_ID,LASTNAME\n1001,Hopper\n4004,Wirth\n3003,Kemeny\n2002,Gosling\n5005,Kurtz\n\"\"\"\ndf_patients = pd.read_csv(io.StringIO(str_patients), sep = \",\", decimal=\".\")\nstr_visits = \"\"\"PATIENT_ID,VISIT_DATE,SCORE\n2002,2020-09-10,6.8\n1001,2020-09-17,5.5\n4004,2020-09-24,8.4\n2002,2020-10-08,\n1001,,6.6\n3003,2020-11-12,\n4004,2020-11-05,7.0\n1001,2020-11-19,5.3\n\"\"\"\ndf_visits = pd.read_csv(io.StringIO(str_visits), sep = \",\", decimal=\".\")\n'''\n\n# typecast from string to datetime so .agg can 'max' it\ndf_visits['VISIT_DATE'] = pd.to_datetime(df_visits['VISIT_DATE'])\n\n# merge on PATIENT_ID\ndf_merge = df_patients.merge(df_visits, on='PATIENT_ID', how='left')\n\n# groupby is an intermediate object\ndf_group = df_merge.groupby(['PATIENT_ID','LASTNAME'], as_index=False)\n\n# note: you can use 'sum' instead of the lambda function but that returns NaN as 0 (zero)\ndf_result = df_group.agg({'VISIT_DATE': 'max', 'SCORE': [lambda x: x.sum(min_count=1),'mean']})\n\nprint(df_result)\n\n  PATIENT_ID LASTNAME LAST_VISIT      SCORE\n                             max <lambda_0> mean\n0       1001   Hopper 2020-11-19       17.4  5.8\n1       2002  Gosling 2020-10-08        6.8  6.8\n2       3003   Kemeny 2020-11-12        NaN  NaN\n3       4004    Wirth 2020-11-05       15.4  7.7\n4       5005    Kurtz        NaT        NaN  NaN\n\n\nimport csv\n\nfnames = 'patients.csv  patients_visits.csv'.split()\n\ndef csv2list(fname):\n    with open(fname) as f:\n        rows = list(csv.reader(f))\n    return rows\n\npatients, visits = data = [csv2list(fname) for fname in fnames]\nresult = [record.copy() for record in patients]\nresult[1:] = sorted(result[1:])\n#%%\nresult[0].append('LAST_VISIT')\nlast = {p: vis for p, vis, *score in visits[1:]}\nfor record in result[1:]:\n    p = record[0]\n    record.append(last.get(p, ''))\n#%%\nresult[0] += ['SCORE_SUM', 'SCORE_AVG']\nn = {p: 0 for p, *_ in patients[1:]}\ntot = n.copy()\nfor record in visits[1:]:\n    p, _, score = record\n    if score:\n        n[p] += 1\n        tot[p] += float(score)\nfor record in result[1:]:\n    p = record[0]\n    if n[p]:\n        record += [f\"{tot[p]:5.1f}\", f\"{tot[p] \/ n[p]:5.2f}\"]\n    else:\n        record += ['', '']\n#%%\nfor record in result:\n    print(f\"| {' | '.join(f'{r:^10}' for r in record)} |\")\n\n\n","human_summarization":"The code merges and aggregates two datasets from .csv files, specifically 'patients.csv' and 'visits.csv'. It groups the data by patient id and last name, calculates the maximum visit date, and computes the sum and average of the scores per patient. The result is either stored in-memory or displayed on the screen or file. The code is particularly suitable for data science and data processing programming languages like F#, Python, R, SPSS, MATLAB etc., and uses standard libraries and the csv and sqlite3 modules for input parsing and output calculation respectively.","id":4737}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python  version 2.7.14\nLibrary: PIL\nfrom PIL import Image\n\nimg = Image.new('RGB', (320, 240))\npixels = img.load()\npixels[100,100] = (255,0,0)\nimg.show()\n\n","human_summarization":"\"Creates a 320x240 window and draws a single red pixel at position (100, 100).\"","id":4738}
    {"lang_cluster":"Python","source_code":"\n\ndef readconf(fn):\n    ret = {}\n    with file(fn) as fp:\n        for line in fp:\n            # Assume whitespace is ignorable\n            line = line.strip()\n            if not line or line.startswith('#'): continue\n            \n            boolval = True\n            # Assume leading \";\" means a false boolean\n            if line.startswith(';'):\n                # Remove one or more leading semicolons\n                line = line.lstrip(';')\n                # If more than just one word, not a valid boolean\n                if len(line.split()) != 1: continue\n                boolval = False\n            \n            bits = line.split(None, 1)\n            if len(bits) == 1:\n                # Assume booleans are just one standalone word\n                k = bits[0]\n                v = boolval\n            else:\n                # Assume more than one word is a string value\n                k, v = bits\n            ret[k.lower()] = v\n    return ret\n\n\nif __name__ == '__main__':\n    import sys\n    conf = readconf(sys.argv[1])\n    for k, v in sorted(conf.items()):\n        print k, '=', v\n\n","human_summarization":"The code reads a standard configuration file, ignores lines starting with a hash or semicolon, and blank lines. It sets variables based on the configuration parameters, preserving case sensitivity for parameter data. It also handles optional equals sign used for separating parameter data from the option name and multiple parameters separated by commas. The variables set are 'fullname', 'favouritefruit', 'needspeeling', 'seedsremoved', and 'otherfamily' which is an array.","id":4739}
    {"lang_cluster":"Python","source_code":"\nfrom math import radians, sin, cos, sqrt, asin\n\n\ndef haversine(lat1, lon1, lat2, lon2):\n    R = 6372.8  # Earth radius in kilometers\n\n    dLat = radians(lat2 - lat1)\n    dLon = radians(lon2 - lon1)\n    lat1 = radians(lat1)\n    lat2 = radians(lat2)\n\n    a = sin(dLat \/ 2)**2 + cos(lat1) * cos(lat2) * sin(dLon \/ 2)**2\n    c = 2 * asin(sqrt(a))\n\n    return R * c\n\n>>> haversine(36.12, -86.67, 33.94, -118.40)\n2887.2599506071106\n>>>\n\n","human_summarization":"Implement a function to calculate the great-circle distance between two points on a sphere using the Haversine formula. The function takes the coordinates of Nashville International Airport (BNA) and Los Angeles International Airport (LAX) as input and returns the distance between them. The calculation uses the recommended earth radius of 6372.8 km or 6371 km, depending on the level of precision required.","id":4740}
    {"lang_cluster":"Python","source_code":"\nPython 3\n\n\nimport urllib.request\nprint(urllib.request.urlopen(\"http:\/\/rosettacode.org\").read())\n\n\nfrom http.client import HTTPConnection\nconn = HTTPConnection(\"example.com\")\n# If you need to use set_tunnel, do so here.\nconn.request(\"GET\", \"\/\")  \n# Alternatively, you can use connect(), followed by the putrequest, putheader and endheaders functions.\nresult = conn.getresponse()\nr1 = result.read() # This retrieves the entire contents.\n\nPython 2\n\n\nimport urllib\nprint urllib.urlopen(\"http:\/\/rosettacode.org\").read()\n\n\nimport urllib2\nprint urllib2.urlopen(\"http:\/\/rosettacode.org\").read()\n\n\nLibrary: Requests\nWorks with: Python version 2.7, 3.4\u20133.7\nimport requests\nprint(requests.get(\"http:\/\/rosettacode.org\").text)\n\n","human_summarization":"The code uses urllib.request, http.client, urllib and urllib2 libraries to access a URL's content and print it to the console. Note that this task does not cover HTTPS requests.","id":4741}
    {"lang_cluster":"Python","source_code":"\n\n>>> def luhn(n):\n\tr = [int(ch) for ch in str(n)][::-1]\n\treturn (sum(r[0::2]) + sum(sum(divmod(d*2,10)) for d in r[1::2]))\u00a0% 10 == 0\n\n>>> for n in (49927398716, 49927398717, 1234567812345678, 1234567812345670):\n\tprint(n, luhn(n))\n\n","human_summarization":"The code validates credit card numbers using the Luhn test. It first reverses the order of the digits in the number, then sums every other odd digit to form a partial sum s1. It then multiplies every other even digit by two, summing the digits if the result is greater than nine to form partial sums for the even digits and sum these to form s2. If the sum of s1 and s2 ends in zero, the number is deemed a valid credit card number. The code includes a function that validates a number with the Luhn test and uses it to validate a set of given numbers. It also offers alternative methods using itertools cycle with map and reduce, or defining the Luhn predicate over strings rather than integers, and cycling lambdas rather than integers.","id":4742}
    {"lang_cluster":"Python","source_code":"\n>>> def j(n, k):\n\tp, i, seq = list(range(n)), 0, []\n\twhile p:\n\t\ti = (i+k-1) % len(p)\n\t\tseq.append(p.pop(i))\n\treturn 'Prisoner killing order: %s.\\nSurvivor: %i' % (', '.join(str(i) for i in seq[:-1]), seq[-1])\n\n>>> print(j(5, 2))\nPrisoner killing order: 1, 3, 0, 4.\nSurvivor: 2\n>>> print(j(41, 3))\nPrisoner killing order: 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3, 34, 15.\nSurvivor: 30\n>>>\n\n\n>>>def josephus(n, k):\n        r = 0\n        for i in xrange(1, n+1):\n            r = (r+k)%i\n        return 'Survivor: %d' %r\n\n>>> print(josephus(5, 2))\nSurvivor: 2\n>>> print(josephus(41, 3))\nSurvivor: 30\n>>>\n\n\ndef josephus(n, k):\n    a = list(range(1, n + 1))\n    a[n - 1] = 0\n    p = 0\n    v = []\n    while a[p] != p:\n        for i in range(k - 2):\n            p = a[p]\n        v.append(a[p])\n        a[p] = a[a[p]]\n        p = a[p]\n    v.append(p)\n    return v\n\njosephus(10, 2)\n[1, 3, 5, 7, 9, 2, 6, 0, 8, 4]\n\njosephus(41, 3)[-1]\n30\n\nfrom itertools import compress, cycle\ndef josephus(prisoner, kill, surviver):\n    p = range(prisoner)\n    k = [0] * kill\n    k[kill-1] = 1\n    s = [1] * kill\n    s[kill -1] = 0\n    queue = p\n    \n    queue = compress(queue, cycle(s))\n    try:\n        while True:\n            p.append(queue.next())        \n    except StopIteration:\n        pass \n\n    kil=[]\n    killed = compress(p, cycle(k))\n    try:\n        while True:\n            kil.append(killed.next())\n    except StopIteration:\n        pass \n        \n    print 'The surviver is: ', kil[-surviver:]\n    print 'The kill sequence is ', kil[:prisoner-surviver]\n\njosephus(41,3,2)\nThe surviver is:  [15, 30]\nThe kill sequence is  [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3, 34]\njosephus(5,2,1)\nThe surviver is:  [2]\nThe kill sequence is  [1, 3, 0, 4]\n\n","human_summarization":"The code implements the Josephus problem, determining the final survivor when n prisoners are arranged in a circle and every k-th prisoner is executed until only one remains. It also provides a method to calculate the prisoner at any given position in the killing sequence. The prisoners can be numbered from either 0 to n-1 or 1 to n. The code returns the killing order, with the last prisoner in the list being the survivor.","id":4743}
    {"lang_cluster":"Python","source_code":"\n\"ha\" * 5  # ==> \"hahahahaha\"\n\n5 * \"ha\"  # ==> \"hahahahaha\"\ndef repeat(s, times):\n    return s * times\n\nprint(repeat(\"ha\", 5))\n\n","human_summarization":"The code takes a string or a character and repeats it a specified number of times. For instance, repeat(\"ha\", 5) will output \"hahahahaha\". Similarly, repeat-char(\"*\", 5) will output \"*****\". It treats characters as strings of length one.","id":4744}
    {"lang_cluster":"Python","source_code":"\nimport re\n\nstring = \"This is a string\"\n\nif re.search('string$', string):\n    print(\"Ends with string.\")\n\nstring = re.sub(\" a \", \" another \", string)\nprint(string)\n\n","human_summarization":"\"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression.\"","id":4745}
    {"lang_cluster":"Python","source_code":"\nx = int(raw_input(\"Number 1: \"))\ny = int(raw_input(\"Number 2: \"))\n\nprint \"Sum: %d\"\u00a0% (x + y)\nprint \"Difference: %d\"\u00a0% (x - y)\nprint \"Product: %d\"\u00a0% (x * y)\nprint \"Quotient: %d\"\u00a0% (x \/ y)     #  or x \/\/ y  for newer python versions.\n                                   # truncates towards negative infinity\nprint \"Remainder: %d\"\u00a0% (x\u00a0% y)    # same sign as second operand\nprint \"Quotient: %d with Remainder: %d\"\u00a0% divmod(x, y)\nprint \"Power: %d\"\u00a0% x**y\n\n## Only used to keep the display up when the program ends\nraw_input( )\n\ndef getnum(prompt):\n    while True: # retrying ...\n        try:\n            n = int(raw_input(prompt))\n        except ValueError:\n            print \"Input could not be parsed as an integer. Please try again.\"\\\n            continue\n        break\n    return n\n\nx = getnum(\"Number1: \")\ny = getnum(\"Number2: \")\n...\n\nquotient, remainder = divmod(355,113)\n\n\ndef arithmetic(x, y):\n    for op in \"+ - * \/\/\u00a0% **\".split():\n        expr = \"%(x)s\u00a0%(op)s\u00a0%(y)s\"\u00a0% vars()\n        print(\"%s\\t=> %s\"\u00a0% (expr, eval(expr)))\n\n\narithmetic(12, 8)\narithmetic(input(\"Number 1: \"), input(\"Number 2: \"))\n\n","human_summarization":"The code takes two integers as input from the user and calculates their sum, difference, product, integer quotient, remainder, and exponentiation. It also indicates how the quotient is rounded and the sign of the remainder. The code does not include error handling. It also provides an example of the 'divmod' operator.","id":4746}
    {"lang_cluster":"Python","source_code":"\n>>> \"the three truths\".count(\"th\")\n3\n>>> \"ababababab\".count(\"abab\")\n2\n\n","human_summarization":"The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.","id":4747}
    {"lang_cluster":"Python","source_code":"\ndef hanoi(ndisks, startPeg=1, endPeg=3):\n    if ndisks:\n        hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)\n        print(f\"Move disk {ndisks} from peg {startPeg} to peg {endPeg}\")\n        hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)\n \nhanoi(4)\n\n","human_summarization":"The following codes solve the Towers of Hanoi problem using recursion and also generate a simple visualization of the solution. The code also includes a refactored version that separates the data definition from its display. Additionally, it references a 3D Hanoi game example from VPython and GitHub.","id":4748}
    {"lang_cluster":"Python","source_code":"\ndef binomialCoeff(n, k):\n    result = 1\n    for i in range(1, k+1):\n        result = result * (n-i+1) \/ i\n    return result\n\nif __name__ == \"__main__\":\n    print(binomialCoeff(5, 3))\n\n\n","human_summarization":"The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which equals 10. The code also considers different scenarios such as combinations and permutations, order importance, and replacement. It also allows for abstracting for legibility and ease of reuse, and includes Python comments and type hints for clarity.","id":4749}
    {"lang_cluster":"Python","source_code":"\ndef shell(seq):\n    inc = len(seq) \/\/ 2\n    while inc:\n        for i, el in enumerate(seq[inc:], inc):\n            while i >= inc and seq[i - inc] > el:\n                seq[i] = seq[i - inc]\n                i -= inc\n            seq[i] = el\n        inc = 1 if inc == 2 else inc * 5 \/\/ 11\n\n\n","human_summarization":"implement the Shell sort algorithm to sort an array of elements. The algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until it reaches 1, at which point the data is almost sorted. The method sorts in place, so a copy should be made if the original unsorted list needs to be preserved.","id":4750}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 3.1\n\n# String masquerading as ppm file (version P3)\nimport io\nppmfileout = io.StringIO('')\n\ndef togreyscale(self):\n    for h in range(self.height):\n        for w in range(self.width):\n            r, g, b = self.get(w, h)\n            l = int(0.2126 * r + 0.7152 * g + 0.0722 * b)\n            self.set(w, h, Colour(l, l, l))\n\nBitmap.togreyscale = togreyscale    \n\n\n# Draw something simple\nbitmap = Bitmap(4, 4, white)\nbitmap.fillrect(1, 0, 1, 2, Colour(127, 0, 63))\nbitmap.set(3, 3, Colour(0, 127, 31))\nprint('Colour:')\n# Write to the open 'file' handle\nbitmap.writeppmp3(ppmfileout)\nprint(ppmfileout.getvalue())\nprint('Grey:')\nbitmap.togreyscale()\nppmfileout = io.StringIO('')\nbitmap.writeppmp3(ppmfileout)\nprint(ppmfileout.getvalue())\n\n\n'''\nThe print statement above produces the following output\u00a0:\n\nColour:\nP3\n# generated from Bitmap.writeppmp3\n4 4\n255\n   255 255 255   255 255 255   255 255 255     0 127  31\n   255 255 255   255 255 255   255 255 255   255 255 255\n   255 255 255   127   0  63   255 255 255   255 255 255\n   255 255 255   127   0  63   255 255 255   255 255 255\n\nGrey:\nP3\n# generated from Bitmap.writeppmp3\n4 4\n254\n   254 254 254   254 254 254   254 254 254    93  93  93\n   254 254 254   254 254 254   254 254 254   254 254 254\n   254 254 254    31  31  31   254 254 254   254 254 254\n   254 254 254    31  31  31   254 254 254   254 254 254\n\n'''\n\n","human_summarization":"extend the data storage type to support grayscale images, convert color images to grayscale and vice versa using the CIE recommended formula for luminance calculation. The code also ensures that rounding errors in floating-point arithmetic do not cause run-time issues or distorted results.","id":4751}
    {"lang_cluster":"Python","source_code":"\nLibrary: PyQt5\n#!\/usr\/bin\/env python3\nimport sys\n\nfrom PyQt5.QtCore import QBasicTimer, Qt\nfrom PyQt5.QtGui import QFont\nfrom PyQt5.QtWidgets import QApplication, QLabel\n\n\nclass Marquee(QLabel):\n    def __init__(self, **kwargs):\n        super().__init__(**kwargs)\n        self.right_to_left_direction = True\n        self.initUI()\n        self.timer = QBasicTimer()\n        self.timer.start(80, self)\n\n    def initUI(self):\n        self.setWindowFlags(Qt.FramelessWindowHint)\n        self.setAttribute(Qt.WA_TranslucentBackground)\n        self.setText(\"Hello World! \")\n        self.setFont(QFont(None, 50, QFont.Bold))\n        # make more irritating for the authenticity with <marquee> element\n        self.setStyleSheet(\"QLabel {color: cyan; }\")\n\n    def timerEvent(self, event):\n        i = 1 if self.right_to_left_direction else -1\n        self.setText(self.text()[i:] + self.text()[:i])  # rotate\n\n    def mouseReleaseEvent(self, event):  # change direction on mouse release\n        self.right_to_left_direction = not self.right_to_left_direction\n\n    def keyPressEvent(self, event):  # exit on Esc\n        if event.key() == Qt.Key_Escape:\n            self.close()\n\n\napp = QApplication(sys.argv)\nw = Marquee()\n# center widget on the screen\nw.adjustSize()  # update w.rect() now\nw.move(QApplication.instance().desktop().screen().rect().center()\n       - w.rect().center())\nw.show()\nsys.exit(app.exec())\n\nLibrary: pygame\nimport pygame, sys\nfrom pygame.locals import *\npygame.init()\n\nYSIZE = 40\nXSIZE = 150\n\nTEXT = \"Hello World! \"\nFONTSIZE = 32\n\nLEFT = False\nRIGHT = True\n\nDIR = RIGHT\n\nTIMETICK = 180\nTICK = USEREVENT + 2\n\nTEXTBOX = pygame.Rect(10,10,XSIZE,YSIZE)\n\npygame.time.set_timer(TICK, TIMETICK)\n\nwindow = pygame.display.set_mode((XSIZE, YSIZE))\npygame.display.set_caption(\"Animation\")\n\nfont = pygame.font.SysFont(None, FONTSIZE)\nscreen = pygame.display.get_surface()\n\ndef rotate():\n    index = DIR and -1 or 1\n    global TEXT\n    TEXT = TEXT[index:]+TEXT[:index]\n\ndef click(position):\n    if TEXTBOX.collidepoint(position):\n        global DIR\n        DIR = not DIR\n\ndef draw():\n    surface = font.render(TEXT, True, (255,255,255), (0,0,0))\n    global TEXTBOX\n    TEXTBOX = screen.blit(surface, TEXTBOX)\n    \ndef input(event):\n    if event.type == QUIT:\n        sys.exit(0)\n    elif event.type == MOUSEBUTTONDOWN:\n        click(event.pos)\n    elif event.type == TICK:\n        draw()\n        rotate()\n\nwhile True:\n    input(pygame.event.wait())\n    pygame.display.flip()\n\nimport Tkinter as tki\n\ndef scroll_text(s, how_many):\n    return s[how_many:] + s[:how_many]\n\ndirection = 1\ntk = tki.Tk()\nvar = tki.Variable(tk)\n\ndef mouse_handler(point):\n    global direction\n    direction *= -1\n\ndef timer_handler():\n    var.set(scroll_text(var.get(),direction))\n    tk.after(125, timer_handler)\n\nvar.set('Hello, World! ')\ntki.Label(tk, textvariable=var).pack()\ntk.bind(\"<Button-1>\", mouse_handler)\ntk.after(125, timer_handler)\ntk.title('Python Animation')\ntki.mainloop()\n\n","human_summarization":"Create a GUI animation where the string \"Hello World! \" appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.","id":4752}
    {"lang_cluster":"Python","source_code":"\n\nval = 0\nwhile True:\n   val +=1\n   print val\n   if val\u00a0% 6 == 0: break\n\nval = 1\nprint val\nwhile val\u00a0% 6\u00a0!= 0:\n   val += 1\n   print val\n","human_summarization":"Initializes a value at 0, then enters a loop where it increments the value by 1 and prints it each iteration. The loop continues until the value modulo 6 equals 0. The loop is guaranteed to execute at least once. Python's lack of a do-while loop means the loop body is executed before the condition is checked.","id":4753}
    {"lang_cluster":"Python","source_code":"\n\nWorks with: Python version 2.x\n\nprint len('ascii')\n# 5\n\n# The letter Alef\nprint len(u'\\u05d0'.encode('utf-8'))\n# 2\nprint len(u'\\u05d0'.encode('iso-8859-8'))\n# 1\n\n#!\/bin\/env python\n# -*- coding: UTF-8 -*-\ns = u\"m\u00f8\u00f8se\"\nassert len(s) == 5\nassert len(s.encode('UTF-8')) == 7\nassert len(s.encode('UTF-16-BE')) == 10 # There are 3 different UTF-16 encodings: LE and BE are little endian and big endian respectively, the third one (without suffix) adds 2 extra leading bytes: the byte-order mark (BOM).\nWorks with: Python version 2.4\n\nimport sys\nsys.maxunicode # 1114111 on a wide build, 65535 on a narrow build\n\nprint len('ascii')\n# 5\nprint len(u'\\u05d0') # the letter Alef as unicode literal\n# 1\nprint len('\\xd7\\x90'.decode('utf-8')) # Same encoded as utf-8 string\n# 1\nprint hex(sys.maxunicode), len(unichr(0x1F4A9))\n# ('0x10ffff', 1)\n\nprint hex(sys.maxunicode), len(unichr(0x1F4A9))\n# ('0xffff', 2)\n\n\nprint(len(b'Hello, World!'))\n# 13\n\n# The letter Alef\nprint(len('\\u05d0'.encode())) # the default encoding is utf-8 in Python3\n# 2\nprint(len('\\u05d0'.encode('iso-8859-8')))\n# 1\n\n#!\/bin\/env python\n# -*- coding: UTF-8 -*-\ns = \"m\u00f8\u00f8se\"\nassert len(s) == 5\nassert len(s.encode('UTF-8')) == 7\nassert len(s.encode('UTF-16-BE')) == 10 # There are 3 different UTF-16 encodings: LE and BE are little endian and big endian respectively, the third one (without suffix) adds 2 extra leading bytes: the byte-order mark (BOM).\nu=\"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\"\nassert len(u.encode()) == 28\nassert len(u.encode('UTF-16-BE')) == 28\n\nprint(len(\"\ud835\udd18\ud835\udd2b\ud835\udd26\ud835\udd20\ud835\udd2c\ud835\udd21\ud835\udd22\")) \n# 7\n\nimport sys\nsys.maxunicode # 1114111 on a wide build, 65535 on a narrow build\nprint(len('ascii'))\n# 5\nprint(len('\\u05d0')) # the letter Alef as unicode literal\n# 1\n\nprint(len(b'\\xd7\\x90'.decode('utf-8'))) # Alef encoded as utf-8 byte sequence\n# 1\nprint(hex(sys.maxunicode), len(unichr(0x1F4A9)))\n# ('0x10ffff', 1)\n\nprint(hex(sys.maxunicode), len(unichr(0x1F4A9)))\n# ('0xffff', 2)\n","human_summarization":"The code calculates the character and byte length of a string, taking into account different encodings like UTF-8 and UTF-16. It handles Unicode code points and non-BMP code points correctly, providing actual character counts in code points. It also provides the string length in graphemes if possible. In Python 2.x, it differentiates between regular and Unicode strings, and in Python 3.x, it handles Unicode strings and byte sequences. It also accounts for different Python build options and their impact on string length calculation.","id":4754}
    {"lang_cluster":"Python","source_code":"\nimport random\nrand = random.SystemRandom()\nrand.randint(1,10)\n\n","human_summarization":"demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.","id":4755}
    {"lang_cluster":"Python","source_code":"\nprint \"knight\"[1:]     # strip first character\nprint \"socks\"[:-1]     # strip last character\nprint \"brooms\"[1:-1]   # strip both first and last characters\n\n\nfrom functools import (reduce)\n\n\ndef main():\n    for xs in transpose(\n        (chunksOf(3)(\n            ap([tail, init, compose(init)(tail)])(\n                ['knights', 'socks', 'brooms']\n            )\n        ))\n    ):\n        print(xs)\n\n\n# GENERIC -------------------------------------------------\n\n# tail\u00a0:: [a] -> [a]\ndef tail(xs):\n    return xs[1:]\n\n\n# init::[a] - > [a]\ndef init(xs):\n    return xs[:-1]\n\n\n# ap (<*>)\u00a0:: [(a -> b)] -> [a] -> [b]\ndef ap(fs):\n    return lambda xs: reduce(\n        lambda a, f: a + reduce(\n            lambda a, x: a + [f(x)], xs, []\n        ), fs, []\n    )\n\n\n# chunksOf\u00a0:: Int -> [a] -> [[a]]\ndef chunksOf(n):\n    return lambda xs: reduce(\n        lambda a, i: a + [xs[i:n + i]],\n        range(0, len(xs), n), []\n    ) if 0 < n else []\n\n\n# compose (<<<)\u00a0:: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n    return lambda f: lambda x: g(f(x))\n\n\n# transpose\u00a0:: [[a]] -> [[a]]\ndef transpose(xs):\n    return list(map(list, zip(*xs)))\n\n\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"demonstrate how to remove the first, last, or both first and last characters from a string, ensuring compatibility with any valid Unicode code point in UTF-8 or UTF-16 encoding. The program references logical characters, not code units. Handling all Unicode characters for other encodings is not required.","id":4756}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.6\n\nimport __main__, os\n\ndef isOnlyInstance():\n    # Determine if there are more than the current instance of the application\n    # running at the current time.\n    return os.system(\"(( $(ps -ef | grep python | grep '[\" +\n                     __main__.__file__[0] + \"]\" + __main__.__file__[1:] +\n                     \"' | wc -l) > 1 ))\") != 0\n\n\n","human_summarization":"The code checks if an application instance is already running. If so, it displays a message and exits. It uses a lock file or directory to ensure only one instance runs at a time. This code must be run from an application, not an interpreter.","id":4757}
    {"lang_cluster":"Python","source_code":"\n#!\/usr\/bin\/env python3\n\nimport tkinter as tk # import the module.\n\nroot = tk.Tk() # Create an instance of the class.\nroot.state('zoomed') # Maximized the window.\nroot.update_idletasks() # Update the display.\ntk.Label(root, text=(str(root.winfo_width())+ \" x \" +str(root.winfo_height())),\n         font=(\"Helvetica\", 25)).pack() # add a label and set the size to text.\nroot.mainloop()\n\n\n1366 x 706\n","human_summarization":"\"Determines the maximum height and width of a window that can fit within the physical display area of the screen, considering adjustments for window decorations and menubars. It also considers scenarios with multiple monitors and tiling window managers.\"","id":4758}
    {"lang_cluster":"Python","source_code":"\n\ndef initiate():\n    box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])\n    box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])\n    box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])\n    box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])\n    box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])\n    box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])\n    box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])\n    box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])\n    box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])\n    for i in range(0, 81, 9):\n        row.append(range(i, i+9))\n    for i in range(9):\n        column.append(range(i, 80+i, 9))\n\ndef valid(n, pos):\n    current_row = pos\/9\n    current_col = pos%9\n    current_box = (current_row\/3)*3 + (current_col\/3)\n    for i in row[current_row]:\n        if (grid[i] == n):\n            return False\n    for i in column[current_col]:\n        if (grid[i] == n):\n            return False\n    for i in box[current_box]:\n        if (grid[i] == n):\n            return False\n    return True\n\ndef solve():\n    i = 0\n    proceed = 1\n    while(i < 81):\n        if given[i]:\n            if proceed:\n                    i += 1\n            else:\n                i -= 1\n        else:\n            n = grid[i]\n            prev = grid[i]\n            while(n < 9):\n              if (n < 9):\n                  n += 1\n              if valid(n, i):\n                  grid[i] = n\n                  proceed = 1\n                  break\n            if (grid[i] == prev):\n               grid[i] = 0\n               proceed = 0\n            if proceed:\n               i += 1\n            else:\n               i -=1\n\ndef inputs():\n    nextt = 'T'\n    number = 0\n    pos = 0\n    while(not(nextt == 'N' or nextt == 'n')):\n        print \"Enter the position:\",\n        pos = int(raw_input())\n        given[pos - 1] = True\n        print \"Enter the numerical:\",\n        number = int(raw_input())\n        grid[pos - 1] = number\n        print \"Do you want to enter another given?(Y, for yes: N, for no)\"\n        nextt = raw_input()\n\n\ngrid = [0]*81\ngiven = [False]*81\nbox = []\nrow = []\ncolumn = []\ninitiate()\ninputs()\nsolve()\nfor i in range(9):\n    print grid[i*9:i*9+9]\nraw_input()\n\n","human_summarization":"implement a Sudoku solver for a 9x9 grid, displaying the result in a human-readable format. The solution uses a simple backtrack algorithm, which may take longer for grids larger than 9x9. The code also references the Algorithmics of Sudoku and Python Sudoku Solver Computerphile video for implementation guidance.","id":4759}
    {"lang_cluster":"Python","source_code":"\n\nfrom random import randrange\n\ndef knuth_shuffle(x):\n    for i in range(len(x)-1, 0, -1):\n        j = randrange(i + 1)\n        x[i], x[j] = x[j], x[i]\n\nx = list(range(10))\nknuth_shuffle(x)\nprint(\"shuffled:\", x)\n\n","human_summarization":"implement the Knuth shuffle algorithm, also known as the Fisher-Yates shuffle, which randomly shuffles the elements of an array. The algorithm modifies the input array in-place, but can be adjusted to return a new shuffled array if necessary. It can also be amended to iterate from left to right for convenience. The Python standard library function random.shuffle uses this algorithm.","id":4760}
    {"lang_cluster":"Python","source_code":"\nimport calendar\n\ndef last_fridays(year):\n    for month in range(1, 13):\n        last_friday = max(week[calendar.FRIDAY]\n            for week in calendar.monthcalendar(year, month))\n        print('{:4d}-{:02d}-{:02d}'.format(year, month, last_friday))\n\n\n","human_summarization":"The code takes a year as input and outputs the dates of the last Fridays of each month for that year.","id":4761}
    {"lang_cluster":"Python","source_code":"\nimport sys\nsys.stdout.write(\"Goodbye, World!\")\n\nWorks with: Python version 3.x\nprint(\"Goodbye, World!\", end=\"\")\n\n","human_summarization":"\"Display the string 'Goodbye, World!' without appending a newline at the end.\"","id":4762}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.5\nLibrary: Tkinter\nimport Tkinter,tkSimpleDialog\n\nroot = Tkinter.Tk()\nroot.withdraw()\n\nnumber = tkSimpleDialog.askinteger(\"Integer\", \"Enter a Number\")\nstring = tkSimpleDialog.askstring(\"String\", \"Enter a String\")\n\nWorks with: Python version 3.7\nLibrary: Tkinter\nimport tkinter\nimport tkinter.simpledialog as tks\n \nroot = tkinter.Tk()\nroot.withdraw()\n \nnumber = tks.askinteger(\"Integer\", \"Enter a Number\")\nstring = tks.askstring(\"String\", \"Enter a String\")\n\ntkinter.messagebox.showinfo(\"Results\", f\"Your input:\\n {number} {string}\")\n\n","human_summarization":"\"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface.\"","id":4763}
    {"lang_cluster":"Python","source_code":"\ndef caesar(s, k, decode = False):\n\tif decode: k = 26 - k\n\treturn \"\".join([chr((ord(i) - 65 + k)\u00a0% 26 + 65)\n\t\t\t\tfor i in s.upper()\n\t\t\t\tif ord(i) >= 65 and ord(i) <= 90 ])\n\nmsg = \"The quick brown fox jumped over the lazy dogs\"\nprint msg\nenc = caesar(msg, 11)\nprint enc\nprint caesar(enc, 11, decode = True)\n\n","human_summarization":"implement both encoding and decoding of a Caesar cipher. The cipher uses a key from 1 to 25 to rotate the letters of the alphabet, replacing each letter with the next 1st to 25th letter. The codes also include a variant with memoization of translation tables as an alternate solution. The Caesar cipher is identical to the Vigen\u00e8re cipher with a key of length 1 and to the Rot-13 cipher with a key of 13.","id":4764}
    {"lang_cluster":"Python","source_code":"\n\n>>> import fractions\n>>> def lcm(a,b): return abs(a * b) \/ fractions.gcd(a,b) if a and b else 0\n\n>>> lcm(12, 18)\n36\n>>> lcm(-6, 14)\n42\n>>> assert lcm(0, 2) == lcm(2, 0) == 0\n>>>\n\n\n'''Least common multiple'''\n\nfrom inspect import signature\n\n\n# lcm\u00a0:: Int -> Int -> Int\ndef lcm(x):\n    '''The smallest positive integer divisible\n       without remainder by both x and y.\n    '''\n    return lambda y: 0 if 0 in (x, y) else abs(\n        y * (x \/\/ gcd_(x)(y))\n    )\n\n\n# gcd_\u00a0:: Int -> Int -> Int\ndef gcd_(x):\n    '''The greatest common divisor in terms of\n       the divisibility preordering.\n    '''\n    def go(a, b):\n        return go(b, a % b) if 0 != b else a\n    return lambda y: go(abs(x), abs(y))\n\n\n# TEST ----------------------------------------------------\n# main\u00a0:: IO ()\ndef main():\n    '''Tests'''\n\n    print(\n        fTable(\n            __doc__ + 's of 60 and [12..20]:'\n        )(repr)(repr)(\n            lcm(60)\n        )(enumFromTo(12)(20))\n    )\n\n    pairs = [(0, 2), (2, 0), (-6, 14), (12, 18)]\n    print(\n        fTable(\n            '\\n\\n' + __doc__ + 's of ' + repr(pairs) + ':'\n        )(repr)(repr)(\n            uncurry(lcm)\n        )(pairs)\n    )\n\n\n# GENERIC -------------------------------------------------\n\n# enumFromTo\u00a0:: (Int, Int) -> [Int]\ndef enumFromTo(m):\n    '''Integer enumeration from m to n.'''\n    return lambda n: list(range(m, 1 + n))\n\n\n# uncurry\u00a0:: (a -> b -> c) -> ((a, b) -> c)\ndef uncurry(f):\n    '''A function over a tuple, derived from\n       a vanilla or curried function.\n    '''\n    if 1 < len(signature(f).parameters):\n        return lambda xy: f(*xy)\n    else:\n        return lambda xy: f(xy[0])(xy[1])\n\n\n# unlines\u00a0:: [String] -> String\ndef unlines(xs):\n    '''A single string derived by the intercalation\n       of a list of strings with the newline character.\n    '''\n    return '\\n'.join(xs)\n\n\n# FORMATTING ----------------------------------------------\n\n# fTable\u00a0:: String -> (a -> String) ->\n#                     (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n    '''Heading -> x display function -> fx display function ->\n                     f -> xs -> tabular string.\n    '''\n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"The code calculates the least common multiple (LCM) of two integers, m and n. It identifies the smallest positive integer that is a factor of both m and n. If either m or n is zero, the LCM is zero. The code may use the greatest common divisor (gcd) formula or merge the prime decompositions of m and n to find the LCM.","id":4765}
    {"lang_cluster":"Python","source_code":"\n\n#!\/usr\/bin\/env python3\n\nimport math\n\ndef cusip_check(cusip):\n    if len(cusip) != 9:\n        raise ValueError('CUSIP must be 9 characters')\n\n    cusip = cusip.upper()\n    total = 0\n    for i in range(8):\n        c = cusip[i]\n        if c.isdigit():\n            v = int(c)\n        elif c.isalpha():\n            p = ord(c) - ord('A') + 1\n            v = p + 9\n        elif c == '*':\n            v = 36\n        elif c == '@':\n            v = 37\n        elif c == '#':\n            v = 38\n\n        if i % 2 != 0:\n            v *= 2\n\n        total += int(v \/ 10) + v % 10\n    check = (10 - (total % 10)) % 10\n    return str(check) == cusip[-1]\n\nif __name__ == '__main__':\n    codes = [\n            '037833100',\n            '17275R102',\n            '38259P508',\n            '594918104',\n            '68389X106',\n            '68389X105'\n            ]\n    for code in codes:\n        print(f'{code} -> {cusip_check(code)}')\n\n\n037833100 -> True\n17275R102 -> True\n38259P508 -> True\n594918104 -> True\n68389X106 -> False\n68389X105 -> True\n\nWorks with: Python version 3.7\n\n'''CUSIP'''\n\nfrom itertools import (cycle, islice, starmap)\nfrom functools import (reduce)\nfrom operator import (add)\nfrom enum import (Enum)\n\n\n# isCusip\u00a0:: Dict -> String -> Bool\ndef isCusip(dct):\n    '''Test for the validity of a CUSIP string in the\n       context of a supplied dictionary of char values'''\n    def go(s):\n        ns = [dct[c] for c in list(s) if c in dct]\n        return 9 == len(ns) and (\n            ns[-1] == (\n                10 - (\n                    sum(zipWith(\n                        lambda f, x: add(*divmod(f(x), 10))\n                    )(cycle([identity, double]))(\n                        take(8)(ns)\n                    )) % 10\n                )\n            ) % 10\n        )\n    return go\n\n\n# cusipCharDict\u00a0:: () -> Dict Char Int\ndef cusipCharDict():\n    '''Dictionary of integer values for CUSIP characters'''\n    def kv(a, ic):\n        i, c = ic\n        a[c] = i\n        return a\n    return reduce(\n        kv,\n        enumerate(\n            enumFromTo('0')('9') + (\n                enumFromTo('A')('Z') + list('*&#')\n            )\n        ),\n        {}\n    )\n\n\n# TEST -------------------------------------------------\n# main\u00a0:: IO ()\ndef main():\n    '''Tests'''\n\n    # cusipTest\u00a0:: String -> Bool\n    cusipTest = isCusip(cusipCharDict())\n\n    print(\n        tabulated('Valid as CUSIP string:')(\n            cusipTest\n        )([\n            '037833100',\n            '17275R102',\n            '38259P508',\n            '594918104',\n            '68389X106',\n            '68389X105'\n        ])\n    )\n\n# GENERIC -------------------------------------------------\n\n\n# double\u00a0:: Num -> Num\ndef double(x):\n    '''Wrapped here as a function for the zipWith expression'''\n    return 2 * x\n\n\n# enumFromTo\u00a0:: Enum a => a -> a -> [a]\ndef enumFromTo(m):\n    '''Enumeration of values [m..n]'''\n    def go(x, y):\n        t = type(m)\n        i = fromEnum(x)\n        d = 0 if t != float else (x - i)\n        return list(map(\n            lambda x: toEnum(t)(d + x),\n            range(i, 1 + fromEnum(y))\n        ) if int != t else range(x, 1 + y))\n    return lambda n: go(m, n)\n\n\n# fromEnum\u00a0:: Enum a => a -> Int\ndef fromEnum(x):\n    '''Index integer for enumerable value.'''\n    return ord(x) if str == type(x) else (\n        x.value if isinstance(x, Enum) else int(x)\n    )\n\n\n# mul\u00a0:: Num -> Num -> Num\ndef mul(x):\n    '''Function version of (*) operator;\n       a curried equivalent of operator.mul'''\n    return lambda y: x * y\n\n\n# identity\u00a0:: a -> a\ndef identity(x):\n    '''The identity function.\n       The usual 'id' is reserved in Python.'''\n    return x\n\n\n# tabulated\u00a0:: String -> (a -> b) -> [a] -> String\ndef tabulated(s):\n    '''heading -> function -> input List -> tabulated output string'''\n    def go(f, xs):\n        def width(x):\n            return len(str(x))\n        w = width(max(xs, key=width))\n        return s + '\\n' + '\\n'.join([\n            str(x).rjust(w, ' ') + ' -> ' + str(f(x)) for x in xs\n        ])\n    return lambda f: lambda xs: go(f, xs)\n\n\n# take\u00a0:: Int -> [a] -> [a]\n# take\u00a0:: Int -> String -> String\ndef take(n):\n    '''The prefix of xs of length n,\n       or xs itself if n > length xs.'''\n    return lambda xs: (\n        xs[0:n]\n        if isinstance(xs, list)\n        else list(islice(xs, n))\n    )\n\n\n# toEnum\u00a0:: Type -> Int -> a\ndef toEnum(t):\n    '''Enumerable value from index integer'''\n    dct = {\n        int: int,\n        float: float,\n        str: chr,\n        bool: bool\n    }\n    return lambda x: dct[t](x) if t in dct else t(x)\n\n\n# zipWith\u00a0:: (a -> b -> c) -> [a] -> [b] -> [c]\ndef zipWith(f):\n    '''Zipping with a custom (rather than tuple) function'''\n    return lambda xs: lambda ys: (\n        list(starmap(f, zip(xs, ys)))\n    )\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"The code verifies the correctness of the last digit (check digit) in a CUSIP code, which is a nine-character alphanumeric code that identifies a North American financial security. It takes an 8-character CUSIP as input and calculates the check digit using the given algorithm, comparing it with the actual check digit to ensure accuracy. The code uses Python 3.6 and includes a number of general and reusable abstractions.","id":4766}
    {"lang_cluster":"Python","source_code":"\n>>> import platform, sys, socket\n>>> platform.architecture()\n('64bit', 'ELF')\n>>> platform.machine()\n'x86_64'\n>>> platform.node()\n'yourhostname'\n>>> platform.system()\n'Linux'\n>>> sys.byteorder\nlittle\n>>> socket.gethostname()\n'yourhostname'\n>>>\n\n","human_summarization":"\"Outputs the word size and endianness of the host machine.\"","id":4767}
    {"lang_cluster":"Python","source_code":"\n\nimport requests\nimport re\n\nresponse = requests.get(\"http:\/\/rosettacode.org\/wiki\/Category:Programming_Languages\").text\nlanguages = re.findall('title=\"Category:(.*?)\">',response)[:-3] # strip last 3\n\nresponse = requests.get(\"http:\/\/rosettacode.org\/mw\/index.php?title=Special:Categories&limit=5000\").text\nresponse = re.sub('(\\d+),(\\d+)',r'\\1'+r'\\2',response)           # strip ',' from popular languages above 999 members\nmembers  = re.findall('<li><a[^>]+>([^<]+)<\/a>[^(]*[(](\\\\d+) member[s]*[)]<\/li>',response) # find language and members\n\nfor cnt, (language, members) in enumerate(sorted(members, key=lambda x: -int(x[1]))[:15]): # show only top 15 languages\n    if language in languages:\n        print(\"{:4d} {:4d} - {}\".format(cnt+1, int(members), language))\n\n\nOutput (as of Dec 21, 2020):\n  1 1306 - Go\n  2 1275 - Phix\n  3 1265 - Julia\n  4 1257 - Raku\n  5 1196 - Python\n  6 1182 - Perl\n  7 1107 - Kotlin\n  8 1080 - C\n  9 1074 - Java\n 10 1061 - Racket\n 11 1022 - REXX\n 12 1012 - Zkl\n 13 1002 - J\n 14  983 - Ruby\n 15  972 - Haskell\n\nimport requests\nimport operator\nimport re\n\napi_url    = 'http:\/\/rosettacode.org\/mw\/api.php'\nlanguages  = {}\n\nparameters = {\n    'format':       'json',\n    'action':       'query',\n    'generator':    'categorymembers',\n    'gcmtitle':     'Category:Programming Languages',\n    'gcmlimit':     '200',\n    'gcmcontinue':  '',\n    'continue':     '',\n    'prop':         'categoryinfo'\n}\n\nwhile(True):\n    response = requests.get(api_url, params=parameters).json()\n    for k,v in response['query']['pages'].items():\n        if 'title' in v and 'categoryinfo' in v:\n          languages[v['title']]=v['categoryinfo']['size']\n    if 'continue' in response:\n        gcmcontinue = response['continue']['gcmcontinue']\n#        print(gcmcontinue)\n        parameters.update({'gcmcontinue': gcmcontinue})\n    else:\n        break\n\n# report top 15 languages                        \nfor i, (language, size) in enumerate(sorted(languages.items(), key=operator.itemgetter(1), reverse=True)[:15]):\n    print(\"{:4d} {:4d} - {}\".format(i+1, size, re.sub('Category:','',language))) # strip Category: from language\n\n\nOutput (as of Dec 21, 2020):\n  1 1306 - Go\n  2 1275 - Phix\n  3 1265 - Julia\n  4 1257 - Raku\n  5 1196 - Python\n  6 1182 - Perl\n  7 1107 - Kotlin\n  8 1080 - C\n  9 1074 - Java\n 10 1061 - Racket\n 11 1022 - REXX\n 12 1012 - Zkl\n 13 1002 - J\n 14  983 - Ruby\n 15  972 - Haskell\n\n","human_summarization":"The code sorts the most popular computer programming languages based on the number of members in Rosetta Code categories. It uses either web scraping or API methods to access the data. The code also has the option to filter incorrect results. The final output is a complete ranked list of all programming languages.","id":4768}
    {"lang_cluster":"Python","source_code":"\nfor i in collection:\n   print i\n\nlines = words = characters = 0\nf = open('somefile','r')\nfor eachline in f:\n    lines += 1\n    for eachword in eachline.split():\n        words += 1\n        for eachchar in eachword:\n            characters += 1\n\nprint lines, words, characters\n\nd = {3: \"Earth\", 1: \"Mercury\", 4: \"Mars\", 2: \"Venus\"}\nfor k in sorted(d):\n    print(\"%i: %s\"\u00a0% (k, d[k]))\n\nd = {\"London\": \"United Kingdom\", \"Berlin\": \"Germany\", \"Rome\": \"Italy\", \"Paris\": \"France\"}\nfor k in sorted(d):\n    print(\"%s: %s\"\u00a0% (k, d[k]))\nWorks with: Python version 2.x\nd = {\"fortytwo\": 42, 3.14159: \"pi\", 23: \"twentythree\", \"zero\": 0, 13: \"thirteen\"}\nfor k in sorted(d):\n    print(\"%s: %s\"\u00a0% (k, d[k]))\n","human_summarization":"Iterates and prints each element in a collection in order using a \"for each\" loop or another loop if \"for each\" is not available. In Python, this includes iterating over lists, tuples, strings, dictionaries, files, etc. The order of iteration depends on the inherent order of the collection. For dictionaries, the iteration can be done in alphabetic or numeric key order by sorting the keys.","id":4769}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.5Works with: Python version 3.0\ntext = \"Hello,How,Are,You,Today\"\ntokens = text.split(',')\nprint ('.'.join(tokens))\n\nprint ('.'.join('Hello,How,Are,You,Today'.split(',')))\n","human_summarization":"Tokenizes a string by commas into an array, and displays the words to the user separated by a period. May display a trailing period.","id":4770}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.6+\nfrom fractions import gcd\nWorks with: Python version 3.7\n\nfrom math import gcd\ndef gcd_iter(u, v):\n    while v:\n        u, v = v, u\u00a0% v\n    return abs(u)\n\ndef gcd(u, v):\n    return gcd(v, u\u00a0% v) if v else abs(u)\n>>> gcd(0,0)\n0\n>>> gcd(0, 10) == gcd(10, 0) == gcd(-10, 0) == gcd(0, -10) == 10\nTrue\n>>> gcd(9, 6) == gcd(6, 9) == gcd(-6, 9) == gcd(9, -6) == gcd(6, -9) == gcd(-9, 6) == 3\nTrue\n>>> gcd(8, 45) == gcd(45, 8) == gcd(-45, 8) == gcd(8, -45) == gcd(-8, 45) == gcd(45, -8) == 1\nTrue\n>>> gcd(40902, 24140) # check Knuth\u00a0:)\n34\n\n\ndef gcd_bin(u, v):\n    u, v = abs(u), abs(v) # u >= 0, v >= 0\n    if u < v:\n        u, v = v, u # u >= v >= 0\n    if v == 0:\n        return u\n   \n    # u >= v > 0\n    k = 1\n    while u & 1 == 0 and v & 1 == 0: # u, v - even\n        u >>= 1; v >>= 1\n        k <<= 1\n       \n    t = -v if u & 1 else u\n    while t:\n        while t & 1 == 0:\n            t >>= 1\n        if t > 0:\n            u = t\n        else:\n            v = -t\n        t = u - v\n    return u * k\n\n","human_summarization":"are designed to find the greatest common divisor (GCD), also known as the greatest common factor (gcf) or greatest common measure, of two integers. The codes include different methods such as Euclid, iterative, and binary, with varying execution times. The codes are written in Python 2.5, as fractions.gcd is deprecated in Python 3.","id":4771}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.3 or above\nimport SocketServer\n\nHOST = \"localhost\"\nPORT = 12321\n\n# this server uses ThreadingMixIn - one thread per connection\n# replace with ForkMixIn to spawn a new process per connection\n\nclass EchoServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):\n    # no need to override anything - default behavior is just fine\n    pass\n\nclass EchoRequestHandler(SocketServer.StreamRequestHandler):\n    \"\"\"\n    Handles one connection to the client.\n    \"\"\"\n    def handle(self):\n        print \"connection from %s\" % self.client_address[0]\n        while True:\n            line = self.rfile.readline()\n            if not line: break\n            print \"%s wrote: %s\" % (self.client_address[0], line.rstrip())\n            self.wfile.write(line)\n        print \"%s disconnected\" % self.client_address[0]\n\n\n# Create the server\nserver = EchoServer((HOST, PORT), EchoRequestHandler)\n\n# Activate the server; this will keep running until you\n# interrupt the program with Ctrl-C\nprint \"server listening on %s:%s\" % server.server_address\nserver.serve_forever()\n\nWorks with: Python version 3.5 or above\n#!\/usr\/bin\/env python\n# $ printf 'echo\\r\\n' | nc localhost 12321\n# echo\nimport asyncio\nimport logging\nimport os\n\nlogger = logging.getLogger('echoserver')\n\nasync def echo_handler(reader, writer):\n  address = writer.get_extra_info('peername')\n  logger.debug('accept: %s', address)\n  message = await reader.readline()\n  writer.write(message)\n  await writer.drain()\n  writer.close()\n\nif __name__ == '__main__':\n  logging.basicConfig()\n  logger.setLevel(logging.DEBUG)\n  loop = asyncio.get_event_loop()\n  factory = asyncio.start_server(\n    echo_handler,\n    os.environ.get('HOST'),\n    os.environ.get('PORT', 12321)\n  )\n  server = loop.run_until_complete(factory)\n  try:\n    loop.run_forever()\n  except KeyboardInterrupt:\n    pass\n  server.close()\n  loop.run_until_complete(server.wait_closed())\n  loop.close()\n\nWorks with: Python version 2 and 3\n\n    #!usr\/bin\/env python\n    import socket\n    import threading\n\n    HOST = 'localhost'\n    PORT = 12321\n    SOCKET_TIMEOUT = 30\n\n    # This function handles reading data sent by a client, echoing it back\n    # and closing the connection in case of timeout (30s) or \"quit\" command\n    # This function is meant to be started in a separate thread\n    # (one thread per client)\n    def handle_echo(client_connection, client_address):\n        client_connection.settimeout(SOCKET_TIMEOUT)\n        try:\n            while True:\n                data = client_connection.recv(1024)\n                # Close connection if \"quit\" received from client\n                if data == b'quit\\r\\n' or data == b'quit\\n':\n                    print('{} disconnected'.format(client_address))\n                    client_connection.shutdown(1)\n                    client_connection.close()\n                    break\n                # Echo back to client\n                elif data:\n                    print('FROM {}\u00a0: {}'.format(client_address,data))\n                    client_connection.send(data)\n        # Timeout and close connection after 30s of inactivity\n        except socket.timeout:\n            print('{} timed out'.format(client_address))\n            client_connection.shutdown(1)\n            client_connection.close()\n\n    # This function opens a socket and listens on specified port. As soon as a\n    # connection is received, it is transfered to another socket so that the main\n    # socket is not blocked and can accept new clients.\n    def listen(host, port):\n        # Create the main socket (IPv4, TCP)\n        connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        connection.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        connection.bind((host, port))\n        # Listen for clients (max 10 clients in waiting)\n        connection.listen(10)\n        # Every time a client connects, allow a dedicated socket and a dedicated\n        # thread to handle communication with that client without blocking others.\n        # Once the new thread has taken over, wait for the next client.\n        while True:\n            current_connection, client_address = connection.accept()\n            print('{} connected'.format(client_address))\n            handler_thread = threading.Thread( \\\n                target = handle_echo, \\\n                args = (current_connection,client_address) \\\n            )\n            # daemon makes sure all threads are killed if the main server process\n            # gets killed\n            handler_thread.daemon = True\n            handler_thread.start()\n\n    if __name__ == \"__main__\":\n        try:\n            listen(HOST, PORT)\n        except KeyboardInterrupt:\n            print('exiting')\n            pass\n\n","human_summarization":"The code implements an echo server that listens on TCP port 12321. It accepts and handles multiple simultaneous connections from localhost only, echoing back complete lines to the clients. It uses low-level socket and threading modules, and can handle more than a single line per connection. It also supports timing out inactive clients and logs connection information to standard output. The server continues to respond to other clients even if one client sends a partial line or stops reading responses.","id":4772}
    {"lang_cluster":"Python","source_code":"\ndef is_numeric(s):\n    try:\n        float(s)\n        return True\n    except (ValueError, TypeError):\n        return False\n\nis_numeric('123.0')\n\n'123'.isdigit()\n\ndef is_numeric(literal):\n    \"\"\"Return whether a literal can be parsed as a numeric value\"\"\"\n    castings = [int, float, complex,\n        lambda s: int(s,2),  #binary\n        lambda s: int(s,8),  #octal\n        lambda s: int(s,16)] #hex\n    for cast in castings:\n        try:\n            cast(literal)\n            return True\n        except ValueError:\n            pass\n    return False\n\ndef numeric(literal):\n    \"\"\"Return value of numeric literal or None if can't parse a value\"\"\"\n    castings = [int, float, complex,\n        lambda s: int(s,2),  #binary\n        lambda s: int(s,8),  #octal\n        lambda s: int(s,16)] #hex\n    for cast in castings:\n        try:\n            return cast(literal)\n        except ValueError:\n            pass\n    return None\n\n\ntests = [\n    '0', '0.', '00', '123', '0123', '+123', '-123', '-123.', '-123e-4', '-.8E-04',\n    '0.123', '(5)', '-123+4.5j', '0b0101', ' +0B101 ', '0o123', '-0xABC', '0x1a1',\n    '12.5%', '1\/2', '\u00bd', '3\u00bc', '\u03c0', '\u216b', '1,000,000', '1 000', '- 001.20e+02', \n    'NaN', 'inf', '-Infinity']\n\nfor s in tests:\n    print(\"%14s ->\u00a0%-14s\u00a0%-20s is_numeric:\u00a0%-5s  str.isnumeric: %s\"\u00a0% (\n        '\"'+s+'\"', numeric(s), type(numeric(s)), is_numeric(s), s.isnumeric() ))\n\n","human_summarization":"\"Create a function to check if a given string represents a numeric value, including floating point, negative numbers, and positive integers, as well as complex, hex, binary, and octal numeric literals. The function returns a boolean value and also demonstrates the use of the standard method str.isnumeric().\"","id":4773}
    {"lang_cluster":"Python","source_code":"\n\nimport urllib.request\nprint(urllib.request.urlopen(\"https:\/\/sourceforge.net\/\").read())\n\n","human_summarization":"send a GET request to the URL \"https:\/\/www.w3.org\/\" without authentication, check the host certificate for validity, and print the response to the console using Python's urllib.request library with SSL support.","id":4774}
    {"lang_cluster":"Python","source_code":"\ndef clip(subjectPolygon, clipPolygon):\n   def inside(p):\n      return(cp2[0]-cp1[0])*(p[1]-cp1[1]) > (cp2[1]-cp1[1])*(p[0]-cp1[0])\n      \n   def computeIntersection():\n      dc = [ cp1[0] - cp2[0], cp1[1] - cp2[1] ]\n      dp = [ s[0] - e[0], s[1] - e[1] ]\n      n1 = cp1[0] * cp2[1] - cp1[1] * cp2[0]\n      n2 = s[0] * e[1] - s[1] * e[0] \n      n3 = 1.0 \/ (dc[0] * dp[1] - dc[1] * dp[0])\n      return [(n1*dp[0] - n2*dc[0]) * n3, (n1*dp[1] - n2*dc[1]) * n3]\n\n   outputList = subjectPolygon\n   cp1 = clipPolygon[-1]\n   \n   for clipVertex in clipPolygon:\n      cp2 = clipVertex\n      inputList = outputList\n      outputList = []\n      s = inputList[-1]\n\n      for subjectVertex in inputList:\n         e = subjectVertex\n         if inside(e):\n            if not inside(s):\n               outputList.append(computeIntersection())\n            outputList.append(e)\n         elif inside(s):\n            outputList.append(computeIntersection())\n         s = e\n      cp1 = cp2\n   return(outputList)\n\n","human_summarization":"implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.","id":4775}
    {"lang_cluster":"Python","source_code":"\ndef mc_rank(iterable, start=1):\n    \"\"\"Modified competition ranking\"\"\"\n    lastresult, fifo = None, []\n    for n, item in enumerate(iterable, start-1):\n        if item[0] == lastresult:\n            fifo += [item]\n        else:\n            while fifo:\n                yield n, fifo.pop(0)\n            lastresult, fifo = item[0], fifo + [item]\n    while fifo:\n        yield n+1, fifo.pop(0)\n\n\ndef sc_rank(iterable, start=1):\n    \"\"\"Standard competition ranking\"\"\"\n    lastresult, lastrank = None, None\n    for n, item in enumerate(iterable, start):\n        if item[0] == lastresult:\n            yield lastrank, item\n        else:\n            yield n, item\n            lastresult, lastrank = item[0], n\n\n\ndef d_rank(iterable, start=1):\n    \"\"\"Dense ranking\"\"\"\n    lastresult, lastrank = None, start - 1,\n    for item in iterable:\n        if item[0] == lastresult:\n            yield lastrank, item\n        else:\n            lastresult, lastrank = item[0], lastrank + 1\n            yield lastrank, item\n\n\ndef o_rank(iterable, start=1):\n    \"\"\"Ordinal  ranking\"\"\"\n    yield from enumerate(iterable, start)\n\n\ndef f_rank(iterable, start=1):\n    \"\"\"Fractional ranking\"\"\"\n    last, fifo = None, []\n    for n, item in enumerate(iterable, start):\n        if item[0] != last:\n            if fifo:\n                mean = sum(f[0] for f in fifo) \/ len(fifo)\n                while fifo:\n                    yield mean, fifo.pop(0)[1]\n        last = item[0]\n        fifo.append((n, item))\n    if fifo:\n        mean = sum(f[0] for f in fifo) \/ len(fifo)\n        while fifo:\n            yield mean, fifo.pop(0)[1]\n\n\nif __name__ == '__main__':\n    scores = [(44, 'Solomon'),\n              (42, 'Jason'),\n              (42, 'Errol'),\n              (41, 'Garry'),\n              (41, 'Bernard'),\n              (41, 'Barry'),\n              (39, 'Stephen')]\n\n    print('\\nScores to be ranked (best first):')\n    for s in scores:\n        print('        %2i %s' % (s ))\n    for ranker in [sc_rank, mc_rank, d_rank, o_rank, f_rank]:\n        print('\\n%s:' % ranker.__doc__)\n        for rank, score in ranker(scores):\n            print('  %3g, %r' % (rank, score))\n\n\n","human_summarization":"\"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties.\"","id":4776}
    {"lang_cluster":"Python","source_code":"\n\nPython 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32\nType \"copyright\", \"credits\" or \"license()\" for more information.\n>>> from math import degrees, radians, sin, cos, tan, asin, acos, atan, pi\n>>> rad, deg = pi\/4, 45.0\n>>> print(\"Sine:\", sin(rad), sin(radians(deg)))\nSine: 0.7071067811865475 0.7071067811865475\n>>> print(\"Cosine:\", cos(rad), cos(radians(deg)))\nCosine: 0.7071067811865476 0.7071067811865476\n>>> print(\"Tangent:\", tan(rad), tan(radians(deg)))\nTangent: 0.9999999999999999 0.9999999999999999\n>>> arcsine = asin(sin(rad))\n>>> print(\"Arcsine:\", arcsine, degrees(arcsine))\nArcsine: 0.7853981633974482 44.99999999999999\n>>> arccosine = acos(cos(rad))\n>>> print(\"Arccosine:\", arccosine, degrees(arccosine))\nArccosine: 0.7853981633974483 45.0\n>>> arctangent = atan(tan(rad))\n>>> print(\"Arctangent:\", arctangent, degrees(arctangent))\nArctangent: 0.7853981633974483 45.0\n>>>\n\n","human_summarization":"demonstrate the use of trigonometric functions such as sine, cosine, tangent, and their inverses in a specific programming language. The functions are applied to the same angle in both radians and degrees. For non-inverse functions, the same angle is used for each radian\/degree pair. For inverse functions, the same number is converted to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities. Python's math module is used for these operations, which only accepts radians, necessitating conversion when using degrees.","id":4777}
    {"lang_cluster":"Python","source_code":"\n\nfrom itertools import groupby\nfrom collections import namedtuple\n\ndef anyvalidcomb(items, maxwt, val=0, wt=0):\n    ' All combinations below the maxwt '\n    if not items:\n        yield [], val, wt\n    else:\n        this, *items = items            # car, cdr\n        for n in range(this.number + 1):\n            w = wt  + n * this.weight\n            if w > maxwt:\n                break\n            v = val + n * this.value\n            this_comb = [this] * n\n            for comb, value, weight in anyvalidcomb(items, maxwt, v, w):\n                yield this_comb + comb, value, weight\n\nmaxwt = 400\nCOMB, VAL, WT = range(3)\nItem  = namedtuple('Items', 'name weight value number')\nitems = [ Item(*x) for x in\n          (\n            (\"map\", 9, 150, 1),\n            (\"compass\", 13, 35, 1),\n            (\"water\", 153, 200, 3),\n            (\"sandwich\", 50, 60, 2),\n            (\"glucose\", 15, 60, 2),\n            (\"tin\", 68, 45, 3),\n            (\"banana\", 27, 60, 3),\n            (\"apple\", 39, 40, 3),\n            (\"cheese\", 23, 30, 1),\n            (\"beer\", 52, 10, 3),\n            (\"suntan cream\", 11, 70, 1),\n            (\"camera\", 32, 30, 1),\n            (\"t-shirt\", 24, 15, 2),\n            (\"trousers\", 48, 10, 2),\n            (\"umbrella\", 73, 40, 1),\n            (\"waterproof trousers\", 42, 70, 1),\n            (\"waterproof overclothes\", 43, 75, 1),\n            (\"note-case\", 22, 80, 1),\n            (\"sunglasses\", 7, 20, 1),\n            (\"towel\", 18, 12, 2),\n            (\"socks\", 4, 50, 1),\n            (\"book\", 30, 10, 2),\n           ) ]  \n\nbagged = max( anyvalidcomb(items, maxwt), key=lambda c: (c[VAL], -c[WT])) # max val or min wt if values equal\nprint(\"Bagged the following %i items\" % len(bagged[COMB]))\nprint('\\n\\t'.join('%i off: %s' % (len(list(grp)), item.name) for item, grp in groupby(sorted(bagged[COMB]))))\nprint(\"for a total value of %i and a total weight of %i\" % bagged[1:])\n\n\n","human_summarization":"The code determines the optimal combination of items that a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. It takes into account the weight, value, and quantity of each item. The code uses a dynamic programming approach to solve the zero-one knapsack problem, ensuring the total weight does not exceed the limit and the total value is maximized.","id":4778}
    {"lang_cluster":"Python","source_code":"\n\nimport time\n\ndef counter():\n    n = 0\n    t1 = time.time()\n    while True:\n        try:\n            time.sleep(0.5)\n            n += 1\n            print n\n        except KeyboardInterrupt, e:\n            print 'Program has run for %5.3f seconds.' % (time.time() - t1)\n            break\n\ncounter()\n\n\nimport time\n\ndef intrptWIN():\n   procDone = False\n   n = 0\n\n   while not procDone:\n      try:\n         time.sleep(0.5)\n         n += 1\n         print n\n      except KeyboardInterrupt, e:\n         procDone = True\n\nt1 = time.time()\nintrptWIN()\ntdelt = time.time() - t1\nprint 'Program has run for %5.3f seconds.' % tdelt\n\n\nimport signal, time, threading\ndone = False\nn = 0\n\ndef counter():\n   global n, timer\n   n += 1\n   print n\n   timer = threading.Timer(0.5, counter)\n   timer.start()\n\ndef sigIntHandler(signum, frame):\n   global done\n   timer.cancel()\n   done = True\n\ndef intrptUNIX():\n   global timer\n   signal.signal(signal.SIGINT, sigIntHandler)\n\n   timer = threading.Timer(0.5, counter)\n   timer.start()\n   while not done:\n      signal.pause()\n\nt1 = time.time()\nintrptUNIX()\ntdelt = time.time() - t1\nprint 'Program has run for %5.3f seconds.' % tdelt\n\n\nimport time, signal\n\nclass WeAreDoneException(Exception):\n    pass\n\ndef sigIntHandler(signum, frame):\n    signal.signal(signal.SIGINT, signal.SIG_DFL) # resets to default handler\n    raise WeAreDoneException\n\nt1 = time.time()\n\ntry:\n    signal.signal(signal.SIGINT, sigIntHandler)\n    n = 0\n    while True:\n        time.sleep(0.5)\n        n += 1\n        print n\nexcept WeAreDoneException:\n    pass\n\ntdelt = time.time() - t1\nprint 'Program has run for %5.3f seconds.' % tdelt\n\n","human_summarization":"The code outputs an integer every half second and handles SIGINT or SIGQUIT signals. On receiving these signals, it stops outputting integers, displays the runtime duration in seconds, and then terminates. The code uses a signal handler and is compatible across all platforms, though the pause() mechanism is not supported on Windows.","id":4779}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.3 through 3.4\nnext = str(int('123') + 1)\n\n# Dropping or keeping any non-numerics in the string\n\n\n# succString\u00a0:: Bool -> String -> String\ndef succString(blnPruned):\n    def go(x):\n        try:\n            return [str(1 + (float(x) if '.' in x else int(x)))]\n        except ValueError:\n            return [] if blnPruned else [x]\n    return lambda s: ' '.join(concatMap(go)(s.split()))\n\n\n# TEST ----------------------------------------------------\ndef main():\n    print(\n        '\\n'.join(\n            [succString(bln)(\n                '41.0 pine martens in 1491 -1.5 mushrooms \u2260 136'\n            ) for bln in [False, True]]\n        )\n    )\n\n\n# GENERIC ---------------------------------------------------\n\n# concatMap\u00a0:: (a -> [b]) -> [a] -> [b]\ndef concatMap(f):\n    return lambda xs: (\n        [ys[0] for ys in [f(x) for x in xs] if ys]\n    )\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n","human_summarization":"\"Increment a numerical string, with options to handle both integer and floating point values, manage noisy or multi-number strings, and retain or remove non-numeric parts.\"","id":4780}
    {"lang_cluster":"Python","source_code":"\n\n>>> import os\n>>> os.path.commonpath(['\/home\/user1\/tmp\/coverage\/test', \n                        '\/home\/user1\/tmp\/covert\/operator', '\/home\/user1\/tmp\/coven\/members'])\n'\/home\/user1\/tmp'\n\n\n>>> import os\n>>> os.path.commonprefix(['\/home\/user1\/tmp\/coverage\/test', \n                          '\/home\/user1\/tmp\/covert\/operator', '\/home\/user1\/tmp\/coven\/members'])\n'\/home\/user1\/tmp\/cove'\n\n\n>>> def commonprefix(args, sep='\/'):\n\treturn os.path.commonprefix(args).rpartition(sep)[0]\n\n>>> commonprefix(['\/home\/user1\/tmp\/coverage\/test', \n                  '\/home\/user1\/tmp\/covert\/operator', '\/home\/user1\/tmp\/coven\/members'])\n'\/home\/user1\/tmp'\n\n\n>>> paths = ['\/home\/user1\/tmp\/coverage\/test', '\/home\/user1\/tmp\/covert\/operator', '\/home\/user1\/tmp\/coven\/members']\n>>> os.path.dirname(os.path.commonprefix(paths))\n'\/home\/user1\/tmp'\n\n\n>>> from itertools import takewhile\n>>> def allnamesequal(name):\n\treturn all(n==name[0] for n in name[1:])\n\n>>> def commonprefix(paths, sep='\/'):\n\tbydirectorylevels = zip(*[p.split(sep) for p in paths])\n\treturn sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))\n\n>>> commonprefix(['\/home\/user1\/tmp\/coverage\/test', \n                  '\/home\/user1\/tmp\/covert\/operator', '\/home\/user1\/tmp\/coven\/members'])\n'\/home\/user1\/tmp'\n>>> # And also\n>>> commonprefix(['\/home\/user1\/tmp', '\/home\/user1\/tmp\/coverage\/test',\n                  '\/home\/user1\/tmp\/covert\/operator', '\/home\/user1\/tmp\/coven\/members'])\n'\/home\/user1\/tmp'\n>>>\n\n","human_summarization":"Create a function to find the common directory path from a set of directory paths using a specified directory separator. The function should return a valid directory path, not just the longest common string. The function is tested with '\/' as the directory separator and three specific strings as input paths. The Python os.path.commonpath function can be used for this task, but the os.path.commonprefix function is not recommended as it may return invalid directory paths.","id":4781}
    {"lang_cluster":"Python","source_code":"\n>>> from random import randrange\n>>> def sattoloCycle(items):\n\tfor i in range(len(items) - 1, 0, -1):\n\t\tj = randrange(i)  # 0 <= j <= i-1\n\t\titems[j], items[i] = items[i], items[j]\n\n\t\t\n>>> # Tests\n>>> for _ in range(10):\n\tlst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\tsattoloCycle(lst)\n\tprint(lst)\n\n\t\n[5, 8, 1, 2, 6, 4, 3, 9, 10, 7]\n[5, 9, 8, 10, 4, 3, 6, 2, 1, 7]\n[10, 5, 8, 3, 9, 1, 4, 2, 6, 7]\n[10, 5, 2, 6, 9, 7, 8, 3, 1, 4]\n[7, 4, 8, 5, 10, 3, 2, 9, 1, 6]\n[2, 3, 10, 9, 4, 5, 8, 1, 7, 6]\n[5, 7, 4, 6, 2, 9, 3, 10, 8, 1]\n[3, 10, 7, 2, 9, 5, 8, 4, 1, 6]\n[2, 6, 5, 3, 9, 8, 10, 7, 1, 4]\n[3, 6, 2, 5, 10, 4, 1, 9, 7, 8]\n>>>\n\n","human_summarization":"implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm works by iterating from the last index to the first, selecting a random index within the range, and swapping the elements at these two indices. The algorithm modifies the input array in-place, but can be adjusted to return a new array or iterate from left to right if necessary. The key distinction from the Knuth shuffle is the range from which the random index is selected.","id":4782}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.4 and 2.5\nfrom SOAPpy import WSDL \nproxy = WSDL.Proxy(\"http:\/\/example.com\/soap\/wsdl\")\nresult = proxy.soapFunc(\"hello\")\nresult = proxy.anotherSoapFunc(34234)\n\n\n","human_summarization":"implement a SOAP client that accesses and calls the functions soapFunc() and anotherSoapFunc() from http:\/\/example.com\/soap\/wsdl using the SOAPpy module. Please note, the task details may be subject to change pending further clarification.","id":4783}
    {"lang_cluster":"Python","source_code":"\ndef median(aray):\n    srtd = sorted(aray)\n    alen = len(srtd)\n    return 0.5*( srtd[(alen-1)\/\/2] + srtd[alen\/\/2])\n\na = (4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2)\nprint a, median(a)\na = (4.1, 7.2, 1.7, 9.3, 4.4, 3.2)\nprint a, median(a)\n\n","human_summarization":"The code calculates the median value of a vector of floating-point numbers. It handles even number of elements by returning the average of the two middle values. The median is found using the selection algorithm for optimal time complexity. The code also includes tasks for calculating various statistical measures like mean, mode, and standard deviation. It also calculates moving (sliding window and cumulative) averages and different types of means such as arithmetic, geometric, harmonic, quadratic, and circular.","id":4784}
    {"lang_cluster":"Python","source_code":"\nfor i in xrange(1, 101):\n    if i\u00a0% 15 == 0:\n        print \"FizzBuzz\"\n    elif i\u00a0% 3 == 0:\n        print \"Fizz\"\n    elif i\u00a0% 5 == 0:\n        print \"Buzz\"\n    else:\n        print i\nfor i in range(1, 101):\n    if i\u00a0% 15 == 0:\n        print(\"FizzBuzz\")\n    elif i\u00a0% 3 == 0:\n        print(\"Fizz\")\n    elif i\u00a0% 5 == 0:\n        print(\"Buzz\")\n    else:\n        print(i)\nfor n in range(1,101):\n    response = ''\n\n    if not n%3:\n        response += 'Fizz'\n    if not n%5:\n        response += 'Buzz'\n\n    print(response or n)\n\nfor i in range(1,101): print(\"Fizz\"*(i%3==0) + \"Buzz\"*(i%5==0) or i)\n\nfor i in range(100):print(i%3\/\/2*'Fizz'+i%5\/\/4*'Buzz'or i+1)\n\nfor n in range(1, 100):\n    fb = ''.join([ denom[1] if n\u00a0% denom[0] == 0 else '' for denom in [(3,'fizz'),(5,'buzz')] ])\n    print fb if fb else n\n\nprint (', '.join([(x%3<1)*'Fizz'+(x%5<1)*'Buzz' or str(x) for x in range(1,101)]))\n[print(\"FizzBuzz\") if i\u00a0% 15 == 0 else print(\"Fizz\") if i\u00a0% 3 == 0 else print(\"Buzz\") if i\u00a0% 5 == 0 else print(i) for i in range(1,101)]\n\nfrom itertools import cycle, izip, count, islice\n\nfizzes = cycle([\"\"] * 2 + [\"Fizz\"])\nbuzzes = cycle([\"\"] * 4 + [\"Buzz\"])\nboth = (f + b for f, b in izip(fizzes, buzzes))\n\n# if the string is \"\", yield the number\n# otherwise yield the string\nfizzbuzz = (word or n for word, n in izip(both, count(1)))\n\n# print the first 100\nfor i in islice(fizzbuzz, 100):\n    print i\n\nWorks with: Python version 3.7\n'''Fizz buzz'''\n\nfrom itertools import count, cycle, islice\n\n\n# fizzBuzz\u00a0:: () -> Generator [String]\ndef fizzBuzz():\n    '''A non-finite stream of fizzbuzz terms.\n    '''\n    return map(\n        lambda f, b, n: (f + b) or str(n),\n        cycle([''] * 2 + ['Fizz']),\n        cycle([''] * 4 + ['Buzz']),\n        count(1)\n    )\n\n\n# ------------------------- TEST -------------------------\ndef main():\n    '''Display of first 100 terms of the fizzbuzz series.\n    '''\n    print(\n        '\\n'.join(\n            list(islice(\n                fizzBuzz(),\n                100\n            ))\n        )\n    )\n\n\nif __name__ == '__main__':\n    main()\nprint(*map(lambda n: 'Fizzbuzz '[(i):i+13] if (i\u00a0:= n**4%-15) > -14 else n, range(1,100)))\n\ndef numsum(n):\n\t''' The recursive sum of all digits in a number \n        unit a single character is obtained'''\n\tres = sum([int(i) for i in str(n)])\n\tif res < 10: return res\n\telse\u00a0: return numsum(res)\n\t\nfor n in range(1,101):\n\tresponse = 'Fizz'*(numsum(n) in [3,6,9]) + \\\n                   'Buzz'*(str(n)[-1] in ['5','0'])\\\n\t            or n\n\tprint(response)\nprint(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\\n' if x\u00a0% (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\\n' if x\u00a0% (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\\n' if x\u00a0% (10 >> 1) == 0 else str(x) + '\\n')() for x in range(1, 101)))\n","human_summarization":"print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'. This is a solution to the FizzBuzz problem, demonstrating basic programming comprehension. The solution can be implemented using string concatenation, list comprehensions, generator expressions, or Python 3 libraries. The code also utilizes the fact that numbers ending in 5 or 0 are divisible by 5, and numbers whose digits sum to 3, 6, or 9 are divisible by 3.","id":4785}
    {"lang_cluster":"Python","source_code":"\n\n# Python 3.0+ and 2.5+\ntry:\n    from functools import reduce\nexcept:\n    pass\n\n\ndef mandelbrot(a):\n    return reduce(lambda z, _: z * z + a, range(50), 0)\n\ndef step(start, step, iterations):\n    return (start + (i * step) for i in range(iterations))\n\nrows = ((\"*\" if abs(mandelbrot(complex(x, y))) < 2 else \" \"\n        for x in step(-2.0, .0315, 80))\n        for y in step(1, -.05, 41))\n\nprint(\"\\n\".join(\"\".join(row) for row in rows))\n\nimport math\n\ndef mandelbrot(z , c , n=40):\n    if abs(z) > 1000:\n        return float(\"nan\")\n    elif n > 0:\n        return mandelbrot(z ** 2 + c, c, n - 1) \n    else:\n        return z ** 2 + c\n\nprint(\"\\n\".join([\"\".join([\"#\" if not math.isnan(mandelbrot(0, x + 1j * y).real) else \" \"\n                 for x in [a * 0.02 for a in range(-80, 30)]]) \n                 for y in [a * 0.05 for a in range(-20, 20)]])\n     )\n\nLibrary: matplotlib\nLibrary: NumPy\nfrom pylab import *\nfrom numpy import NaN\n\ndef m(a):\n\tz = 0\n\tfor n in range(1, 100):\n\t\tz = z**2 + a\n\t\tif abs(z) > 2:\n\t\t\treturn n\n\treturn NaN\n\nX = arange(-2, .5, .002)\nY = arange(-1,  1, .002)\nZ = zeros((len(Y), len(X)))\n\nfor iy, y in enumerate(Y):\n\tprint (iy, \"of\", len(Y))\n\tfor ix, x in enumerate(X):\n\t\tZ[iy,ix] = m(x + 1j * y)\n\nimshow(Z, cmap = plt.cm.prism, interpolation = 'none', extent = (X.min(), X.max(), Y.min(), Y.max()))\nxlabel(\"Re(c)\")\nylabel(\"Im(c)\")\nsavefig(\"mandelbrot_python.svg\")\nshow()\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nnpts = 300\nmax_iter = 100\n\nX = np.linspace(-2, 1, 2 * npts)\nY = np.linspace(-1, 1, npts)\n\n#broadcast X to a square array\nC = X[:, None] + 1J * Y\n#initial value is always zero\nZ = np.zeros_like(C)\n\nexit_times = max_iter * np.ones(C.shape, np.int32)\nmask = exit_times > 0\n\nfor k in range(max_iter):\n    Z[mask] = Z[mask] * Z[mask] + C[mask]\n    mask, old_mask = abs(Z) < 2, mask\n    #use XOR to detect the area which has changed \n    exit_times[mask ^ old_mask] = k\n\nplt.imshow(exit_times.T,\n           cmap=plt.cm.prism,\n           extent=(X.min(), X.max(), Y.min(), Y.max()))\nplt.show()\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nd, h = 800, 500  # pixel density (= image width) and image height\nn, r = 200, 500  # number of iterations and escape radius (r > 2)\n\nx = np.linspace(0, 2, num=d+1)\ny = np.linspace(0, 2 * h \/ d, num=h+1)\n\nA, B = np.meshgrid(x - 1, y - h \/ d)\nC = 2.0 * (A + B * 1j) - 0.5\n\nZ, dZ = np.zeros_like(C), np.zeros_like(C)\nD, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape)\n\nfor k in range(n):\n    M = abs(Z) < r\n    S[M], T[M] = S[M] + np.exp(- abs(Z[M])), T[M] + 1\n    Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1\n\nplt.imshow(S ** 0.1, cmap=plt.cm.twilight_shifted, origin=\"lower\")\nplt.savefig(\"Mandelbrot_set_1.png\", dpi=200)\n\nN = abs(Z) >= r  # normalized iteration count\nT[N] = T[N] - np.log2(np.log(np.abs(Z[N])) \/ np.log(r))\n\nplt.imshow(T ** 0.1, cmap=plt.cm.twilight_shifted, origin=\"lower\")\nplt.savefig(\"Mandelbrot_set_2.png\", dpi=200)\n\nN = abs(Z) > 2  # exterior distance estimation\nD[N] = np.log(abs(Z[N])) * abs(Z[N]) \/ abs(dZ[N])\n\nplt.imshow(D ** 0.1, cmap=plt.cm.twilight_shifted, origin=\"lower\")\nplt.savefig(\"Mandelbrot_set_3.png\", dpi=200)\n\nN, thickness = D > 0, 0.01  # boundary detection\nD[N] = np.maximum(1 - D[N] \/ thickness, 0)\n\nplt.imshow(D ** 2.0, cmap=plt.cm.binary, origin=\"lower\")\nplt.savefig(\"Mandelbrot_set_4.png\", dpi=200)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nd, h = 800, 500  # pixel density (= image width) and image height\nn, r = 200, 500  # number of iterations and escape radius (r > 2)\n\ndirection, height = 45, 1.5  # direction and height of the incoming light\nstripes, damping = 4.0, 2.0  # stripe density and damping parameter\n\nx = np.linspace(0, 2, num=d+1)\ny = np.linspace(0, 2 * h \/ d, num=h+1)\n\nA, B = np.meshgrid(x - 1, y - h \/ d)\nC = (2.0 + 1.0j) * (A + B * 1j) - 0.5\n\nZ, dZ, ddZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C)\nD, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape)\n\nfor k in range(n):\n    M = abs(Z) < r\n    S[M], T[M] = S[M] + np.sin(stripes * np.angle(Z[M])), T[M] + 1\n    Z[M], dZ[M], ddZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1, 2 * (dZ[M] ** 2 + Z[M] * ddZ[M])\n\nN = abs(Z) >= r  # basic normal map effect and stripe average coloring (potential function)\nP, Q = S[N] \/ T[N], (S[N] + np.sin(stripes * np.angle(Z[N]))) \/ (T[N] + 1)\nU, V = Z[N] \/ dZ[N], 1 + (np.log2(np.log(np.abs(Z[N])) \/ np.log(r)) * (P - Q) + Q) \/ damping\nU, v = U \/ abs(U), np.exp(direction \/ 180 * np.pi * 1j)  # unit normal vectors and light\nD[N] = np.maximum((U.real * v.real + U.imag * v.imag + V * height) \/ (1 + height), 0)\n\nplt.imshow(D ** 1.0, cmap=plt.cm.bone, origin=\"lower\")\nplt.savefig(\"Mandelbrot_normal_map_1.png\", dpi=200)\n\nN = abs(Z) > 2  # advanced normal map effect using higher derivatives (distance estimation)\nU = Z[N] * dZ[N] * ((1 + np.log(abs(Z[N]))) * np.conj(dZ[N] ** 2) - np.log(abs(Z[N])) * np.conj(Z[N] * ddZ[N]))\nU, v = U \/ abs(U), np.exp(direction \/ 180 * np.pi * 1j)  # unit normal vectors and light\nD[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) \/ (1 + height), 0)\n\nplt.imshow(D ** 1.0, cmap=plt.cm.afmhot, origin=\"lower\")\nplt.savefig(\"Mandelbrot_normal_map_2.png\", dpi=200)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nd, h = 200, 1200  # pixel density (= image width) and image height\nn, r = 8000, 10000  # number of iterations and escape radius (r > 2)\n\na = -.743643887037158704752191506114774  # https:\/\/mathr.co.uk\/web\/m-location-analysis.html\nb = 0.131825904205311970493132056385139  # try: a, b, n = -1.748764520194788535, 3e-13, 800\n\nx = np.linspace(0, 2, num=d+1)\ny = np.linspace(0, 2 * h \/ d, num=h+1)\n\nA, B = np.meshgrid(x * np.pi, y * np.pi)\nC = 8.0 * np.exp((A + B * 1j) * 1j) + (a + b * 1j)\n\nZ, dZ = np.zeros_like(C), np.zeros_like(C)\nD = np.zeros(C.shape)\n\nfor k in range(n):\n    M = Z.real ** 2 + Z.imag ** 2 < r ** 2\n    Z[M], dZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1\n\nN = abs(Z) > 2  # exterior distance estimation\nD[N] = np.log(abs(Z[N])) * abs(Z[N]) \/ abs(dZ[N])\n\nplt.imshow(D.T ** 0.05, cmap=plt.cm.nipy_spectral, origin=\"lower\")\nplt.savefig(\"Mercator_Mandelbrot_map.png\", dpi=200)\n\nX, Y = C.real, C.imag  # zoom images (adjust circle size 100 and zoom level 20 as needed)\nR, c, z = 100 * (2 \/ d) * np.pi * np.exp(- B), min(d, h) + 1, max(0, h - d) \/\/ 20\n\nfig, ax = plt.subplots(2, 2, figsize=(12, 12))\nax[0,0].scatter(X[1*z:1*z+c,0:d], Y[1*z:1*z+c,0:d], s=R[0:c,0:d]**2, c=D[1*z:1*z+c,0:d]**.5, cmap=plt.cm.nipy_spectral)\nax[0,1].scatter(X[2*z:2*z+c,0:d], Y[2*z:2*z+c,0:d], s=R[0:c,0:d]**2, c=D[2*z:2*z+c,0:d]**.4, cmap=plt.cm.nipy_spectral)\nax[1,0].scatter(X[3*z:3*z+c,0:d], Y[3*z:3*z+c,0:d], s=R[0:c,0:d]**2, c=D[3*z:3*z+c,0:d]**.3, cmap=plt.cm.nipy_spectral)\nax[1,1].scatter(X[4*z:4*z+c,0:d], Y[4*z:4*z+c,0:d], s=R[0:c,0:d]**2, c=D[4*z:4*z+c,0:d]**.2, cmap=plt.cm.nipy_spectral)\nplt.savefig(\"Mercator_Mandelbrot_zoom.png\", dpi=100)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport decimal as dc  # decimal floating point arithmetic with arbitrary precision\ndc.getcontext().prec = 80  # set precision to 80 digits (about 256 bits)\n\nd, h = 50, 1000  # pixel density (= image width) and image height\nn, r = 80000, 100000  # number of iterations and escape radius (r > 2)\n\na = dc.Decimal(\"-1.256827152259138864846434197797294538253477389787308085590211144291\")\nb = dc.Decimal(\".37933802890364143684096784819544060002129071484943239316486643285025\")\n\nS = np.zeros(n+1, dtype=np.complex128)\nu, v = dc.Decimal(0), dc.Decimal(0)\n\nfor k in range(n+1):\n    S[k] = float(u) + float(v) * 1j\n    if u ** 2 + v ** 2 < r ** 2:\n        u, v = u ** 2 - v ** 2 + a, 2 * u * v + b\n    else:\n        print(\"The reference sequence diverges within %s iterations.\"\u00a0% k)\n        break\n\nx = np.linspace(0, 2, num=d+1)\ny = np.linspace(0, 2 * h \/ d, num=h+1)\n\nA, B = np.meshgrid(x * np.pi, y * np.pi)\nC = 8.0 * np.exp((A + B * 1j) * 1j)\n\nE, Z, dZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C)\nD, I, J = np.zeros(C.shape), np.zeros(C.shape, dtype=np.int64), np.zeros(C.shape, dtype=np.int64)\n\nfor k in range(n):\n    Z2 = Z.real ** 2 + Z.imag ** 2\n    M, R = Z2 < r ** 2, Z2 < E.real ** 2 + E.imag ** 2\n    E[R], I[R] = Z[R], J[R]  # rebase when z is closer to zero\n    E[M], I[M] = (2 * S[I[M]] + E[M]) * E[M] + C[M], I[M] + 1\n    Z[M], dZ[M] = S[I[M]] + E[M], 2 * Z[M] * dZ[M] + 1\n\nN = abs(Z) > 2  # exterior distance estimation\nD[N] = np.log(abs(Z[N])) * abs(Z[N]) \/ abs(dZ[N])\n\nplt.imshow(D.T ** 0.015, cmap=plt.cm.nipy_spectral, origin=\"lower\")\nplt.savefig(\"Mercator_Mandelbrot_deep_map.png\", dpi=200)\n\nprint(\n'\\n'.join(\n    ''.join(\n        ' *'[(z:=0, c:=x\/50+y\/50j, [z:=z*z+c for _ in range(99)], abs(z))[-1]<2]\n        for x in range(-100,25)\n    )\n    for y in range(-50,50)\n))\n\nfrom functools import reduce\n\ndef mandelbrot(x, y, c): return ' *'[abs(reduce(lambda z, _: z*z + c, range(99), 0)) < 2]\n\nprint('\\n'.join(''.join(mandelbrot(x, y, x\/50 + y\/50j) for x in range(-100, 25)) for y in range(-50, 50)))\n","human_summarization":"The code generates and visualizes the Mandelbrot set using various algorithms and functions. It employs different coloring algorithms for dynamical systems in the complex plane, including Normal Maps and Stripe Average Coloring. It also creates Mercator maps of the Mandelbrot set and zoom images with maximum magnification. The code uses perturbation theory for deep zoom images and rebasing to reduce glitches.","id":4786}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.5\nnumbers = [1, 2, 3]\ntotal = sum(numbers)\n\nproduct = 1\nfor i in numbers:\n    product *= i\n\nWorks with: Python version 2.5\nfrom operator import mul, add\nsum = reduce(add, numbers) # note: this version doesn't work with empty lists\nsum = reduce(add, numbers, 0)\nproduct = reduce(mul, numbers) # note: this version doesn't work with empty lists\nproduct = reduce(mul, numbers, 1)\nLibrary: NumPy\nfrom numpy import r_\nnumbers = r_[1:4]\ntotal = numbers.sum()\nproduct = numbers.prod()\n\nWorks with: Python version 2.6, 3.x\nimport math\ntotal = math.fsum(floats)\n\n","human_summarization":"calculate the sum and product of an array of integers. For summing floats in Python 2.6+, math.fsum() is used to prevent precision loss.","id":4787}
    {"lang_cluster":"Python","source_code":"\nimport calendar\ncalendar.isleap(year)\n\ndef is_leap_year(year):\n    return not year\u00a0% (4 if year\u00a0% 100 else 400)\n\nimport datetime\n\ndef is_leap_year(year):\n    try:\n        datetime.date(year, 2, 29)\n    except ValueError:\n        return False\n    return True\n","human_summarization":"\"Determines if a given year is a leap year in the Gregorian calendar.\"","id":4788}
    {"lang_cluster":"Python","source_code":"\n\"\"\"One-time pad using an XOR cipher. Requires Python >=3.6.\"\"\"\n\nimport argparse\nimport itertools\nimport pathlib\nimport re\nimport secrets\nimport sys\n\n\n# One-time pad file signature.\nMAGIC = \"#one-time pad\"\n\n\ndef make_keys(n, size):\n    \"\"\"Generate ``n`` secure, random keys of ``size`` bytes.\"\"\"\n    # We're generating and storing keys in their hexadecimal form to make\n    # one-time pad files a little more human readable and to ensure a key\n    # can not start with a hyphen.\n    return (secrets.token_hex(size) for _ in range(n))\n\n\ndef make_pad(name, pad_size, key_size):\n    \"\"\"Create a new one-time pad identified by the given name.\n\n    Args:\n        name (str): Unique one-time pad identifier.\n        pad_size (int): The number of keys (or pages) in the pad.\n        key_size (int): The number of bytes per key.\n    Returns:\n        The new one-time pad as a string.\n    \"\"\"\n    pad = [\n        MAGIC,\n        f\"#name={name}\",\n        f\"#size={pad_size}\",\n        *make_keys(pad_size, key_size),\n    ]\n\n    return \"\\n\".join(pad)\n\n\ndef xor(message, key):\n    \"\"\"Return ``message`` XOR-ed with ``key``.\n\n    Args:\n        message (bytes): Plaintext or cyphertext to be encrypted or decrypted.\n        key (bytes): Encryption and decryption key.\n    Returns:\n        Plaintext or cyphertext as a byte string.\n    \"\"\"\n    return bytes(mc ^ kc for mc, kc in zip(message, itertools.cycle(key)))\n\n\ndef use_key(pad):\n    \"\"\"Use the next available key from the given one-time pad.\n\n    Args:\n        pad (str): A one-time pad.\n    Returns:\n        (str, str) A two-tuple of updated pad and key.\n    \"\"\"\n    match = re.search(r\"^[a-f0-9]+$\", pad, re.MULTILINE)\n    if not match:\n        error(\"pad is all used up\")\n\n    key = match.group()\n    pos = match.start()\n\n    return (f\"{pad[:pos]}-{pad[pos:]}\", key)\n\n\ndef log(msg):\n    \"\"\"Log a message.\"\"\"\n    sys.stderr.write(msg)\n    sys.stderr.write(\"\\n\")\n\n\ndef error(msg):\n    \"\"\"Exit with an error message.\"\"\"\n    sys.stderr.write(msg)\n    sys.stderr.write(\"\\n\")\n    sys.exit(1)\n\n\ndef write_pad(path, pad_size, key_size):\n    \"\"\"Write a new one-time pad to the given path.\n\n    Args:\n        path (pathlib.Path): Path to write one-time pad to.\n        length (int): Number of keys in the pad.\n    \"\"\"\n    if path.exists():\n        error(f\"pad '{path}' already exists\")\n\n    with path.open(\"w\") as fd:\n        fd.write(make_pad(path.name, pad_size, key_size))\n\n    log(f\"New one-time pad written to {path}\")\n\n\ndef main(pad, message, outfile):\n    \"\"\"Encrypt or decrypt ``message`` using the given pad.\n\n    Args:\n        pad (pathlib.Path): Path to one-time pad.\n        message (bytes): Plaintext or ciphertext message to encrypt or decrypt.\n        outfile: File-like object to write to.\n    \"\"\"\n    if not pad.exists():\n        error(f\"no such pad '{pad}'\")\n\n    with pad.open(\"r\") as fd:\n        if fd.readline().strip() != MAGIC:\n            error(f\"file '{pad}' does not look like a one-time pad\")\n\n    # Rewrites the entire one-time pad every time\n    with pad.open(\"r+\") as fd:\n        updated, key = use_key(fd.read())\n\n        fd.seek(0)\n        fd.write(updated)\n\n    outfile.write(xor(message, bytes.fromhex(key)))\n\n\nif __name__ == \"__main__\":\n    # Command line interface\n    parser = argparse.ArgumentParser(description=\"One-time pad.\")\n\n    parser.add_argument(\n        \"pad\",\n        help=(\n            \"Path to one-time pad. If neither --encrypt or --decrypt \"\n            \"are given, will create a new pad.\"\n        ),\n    )\n\n    parser.add_argument(\n        \"--length\",\n        type=int,\n        default=10,\n        help=\"Pad size. Ignored if --encrypt or --decrypt are given. Defaults to 10.\",\n    )\n\n    parser.add_argument(\n        \"--key-size\",\n        type=int,\n        default=64,\n        help=\"Key size in bytes. Ignored if --encrypt or --decrypt are given. Defaults to 64.\",\n    )\n\n    parser.add_argument(\n        \"-o\",\n        \"--outfile\",\n        type=argparse.FileType(\"wb\"),\n        default=sys.stdout.buffer,\n        help=(\n            \"Write encoded\/decoded message to a file. Ignored if --encrypt or \"\n            \"--decrypt is not given. Defaults to stdout.\"\n        ),\n    )\n\n    group = parser.add_mutually_exclusive_group()\n\n    group.add_argument(\n        \"--encrypt\",\n        metavar=\"FILE\",\n        type=argparse.FileType(\"rb\"),\n        help=\"Encrypt FILE using the next available key from pad.\",\n    )\n    group.add_argument(\n        \"--decrypt\",\n        metavar=\"FILE\",\n        type=argparse.FileType(\"rb\"),\n        help=\"Decrypt FILE using the next available key from pad.\",\n    )\n\n    args = parser.parse_args()\n\n    if args.encrypt:\n        message = args.encrypt.read()\n    elif args.decrypt:\n        message = args.decrypt.read()\n    else:\n        message = None\n\n    # Sometimes necessary if message came from stdin\n    if isinstance(message, str):\n        message = message.encode()\n\n    pad = pathlib.Path(args.pad).with_suffix(\".1tp\")\n\n    if message:\n        main(pad, message, args.outfile)\n    else:\n        write_pad(pad, args.length, args.key_size)\n\n\n","human_summarization":"The code implements a One-time pad for encrypting and decrypting messages using only letters. It generates a One-time pad data based on user-specified filename and length, using true random numbers. The encryption\/decryption operation is similar to Rot-13 and reuses much of the Vigen\u00e8re cipher. The code also optionally manages One-time pads, including listing, marking as used, and deleting. It supports the management of pad-files with a \".1tp\" extension, and handles metadata and used status. The code also provides a command-line interface for creating a new one-time pad, distributing it, encrypting a message, and decrypting a message using the shared one-time pad.","id":4789}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 3.2\n\nimport math\n\nrotate_amounts = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n                  5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20, 5,  9, 14, 20,\n                  4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n                  6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]\n\nconstants = [int(abs(math.sin(i+1)) * 2**32) & 0xFFFFFFFF for i in range(64)]\n\ninit_values = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]\n\nfunctions = 16*[lambda b, c, d: (b & c) | (~b & d)] + \\\n            16*[lambda b, c, d: (d & b) | (~d & c)] + \\\n            16*[lambda b, c, d: b ^ c ^ d] + \\\n            16*[lambda b, c, d: c ^ (b | ~d)]\n\nindex_functions = 16*[lambda i: i] + \\\n                  16*[lambda i: (5*i + 1)%16] + \\\n                  16*[lambda i: (3*i + 5)%16] + \\\n                  16*[lambda i: (7*i)%16]\n\ndef left_rotate(x, amount):\n    x &= 0xFFFFFFFF\n    return ((x<<amount) | (x>>(32-amount))) & 0xFFFFFFFF\n\ndef md5(message):\n\n    message = bytearray(message) #copy our input into a mutable buffer\n    orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff\n    message.append(0x80)\n    while len(message)%64 != 56:\n        message.append(0)\n    message += orig_len_in_bits.to_bytes(8, byteorder='little')\n\n    hash_pieces = init_values[:]\n\n    for chunk_ofst in range(0, len(message), 64):\n        a, b, c, d = hash_pieces\n        chunk = message[chunk_ofst:chunk_ofst+64]\n        for i in range(64):\n            f = functions[i](b, c, d)\n            g = index_functions[i](i)\n            to_rotate = a + f + constants[i] + int.from_bytes(chunk[4*g:4*g+4], byteorder='little')\n            new_b = (b + left_rotate(to_rotate, rotate_amounts[i])) & 0xFFFFFFFF\n            a, b, c, d = d, new_b, b, c\n        for i, val in enumerate([a, b, c, d]):\n            hash_pieces[i] += val\n            hash_pieces[i] &= 0xFFFFFFFF\n    \n    return sum(x<<(32*i) for i, x in enumerate(hash_pieces))\n        \ndef md5_to_hex(digest):\n    raw = digest.to_bytes(16, byteorder='little')\n    return '{:032x}'.format(int.from_bytes(raw, byteorder='big'))\n\nif __name__=='__main__':\n    demo = [b\"\", b\"a\", b\"abc\", b\"message digest\", b\"abcdefghijklmnopqrstuvwxyz\",\n            b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\",\n            b\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\"]\n    for message in demo:\n        print(md5_to_hex(md5(message)),' <= \"',message.decode('ascii'),'\"', sep='')\n\n\nThe code works with whole bytes, arbitrary message length is not supported.\nInstead of doing an if-else chain in the inner loop, we build a list of functions to use for each iteration. An if-else chain would probably be faster, but this shows off the language features better.\nPython integers don't ever overflow (they are implemented internally as bignums), so the code actually has to emulate 32-bit overflow by masking manually where it matters. On the other hand, this allows us to return the digest as a regular 128-bit number instead of a bytes object.\nThe code makes heavy use of int.from_bytes() and int.to_bytes() to convert between bytes and integers. These methods were introduced in Python 3.2. In earlier versions, you needed to use more cumbersome ways to convert between the two types.\nThe multiple assignment feature allows us to easily decompose the four items in hash_pieces into individual variables, and to shuffle around the four helper variables at the end of every iteration without introducing a temporary variable.\n","human_summarization":"implement the MD5 Message Digest Algorithm without using built-in or external hashing libraries. The implementation focuses on producing a correct message digest for an input string, and does not necessarily mimic all calling modes. It provides practical illustrations of bit manipulation, unsigned integers, and working with little-endian data. The code also includes handling of boundary conditions. The implementation is developed from the specification, reference implementation, or pseudo-code, or it could be a translation from another language. The implementation should not use built-in MD5 functions or library routines written in other languages.","id":4790}
    {"lang_cluster":"Python","source_code":"\nfrom itertools import permutations\n \ndef solve():\n    c, p, f, s = \"\\\\,Police,Fire,Sanitation\".split(',')\n    print(f\"{c:>3}  {p:^6} {f:^4} {s:^10}\")\n    c = 1\n    for p, f, s in permutations(range(1, 8), r=3):\n        if p + s + f == 12 and p % 2 == 0:\n            print(f\"{c:>3}: {p:^6} {f:^4} {s:^10}\")\n            c += 1\n \nif __name__ == '__main__':\n    solve()\n\n\n","human_summarization":"all possible combinations of department numbers for the police, sanitation, and fire departments where each department has a unique number between 1 and 7, the total sum of the numbers is 12, and the police department's number is even. The combinations are generated using a constraint solver.","id":4791}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.3, 2.4, and 2.5\n\n>>> src = \"hello\"\n>>> a = src\n>>> b = src[:]\n>>> import copy\n>>> c = copy.copy(src)\n>>> d = copy.deepcopy(src)\n>>> src is a is b is c is d\nTrue\n\n>>> a = 'hello'\n>>> b = ''.join(a)\n>>> a == b\nTrue\n>>> b is a  ### Might be True ... depends on \"interning\" implementation details!\nFalse\n\n","human_summarization":"\"Implements a function to copy a string, considering the distinction between copying the contents of a string and making an additional reference to an existing string. It handles the immutability of strings and the potential object interning of Python. It also includes precautions for using the 'is' operator for object identity comparison.\"","id":4792}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 3.0.Works with: Python version 2.6\ndef F(n): return 1 if n == 0 else n - M(F(n-1))\ndef M(n): return 0 if n == 0 else n - F(M(n-1))\n\nprint ([ F(n) for n in range(20) ])\nprint ([ M(n) for n in range(20) ])\n\n\n","human_summarization":"implement two mutually recursive functions to compute the Hofstadter Female and Male sequences. The functions use each other in their definitions and computations. The Female sequence starts with 1 and the Male sequence starts with 0. For any number n greater than 0, the Female sequence is computed as n minus the Male sequence at the index of the previous Female sequence, and the Male sequence is computed as n minus the Female sequence at the index of the previous Male sequence. The functions are defined in such a way that they can be used in languages that do not require pre-declaration of functions.","id":4793}
    {"lang_cluster":"Python","source_code":"\n>>> import random\n>>> random.choice(['foo', 'bar', 'baz'])\n'baz'\n\n","human_summarization":"demonstrate how to select a random element from a list.","id":4794}
    {"lang_cluster":"Python","source_code":"\n#Python 2.X\nimport urllib\nprint urllib.unquote(\"http%3A%2F%2Ffoo%20bar%2F\")\n#Python 3.5+\nfrom urllib.parse import unquote\nprint(unquote('http%3A%2F%2Ffoo%20bar%2F'))\n\n","human_summarization":"provide a function to convert URL-encoded strings back into their original unencoded form. It includes test cases for strings like \"http%3A%2F%2Ffoo%20bar%2F\", \"google.com\/search?q=%60Abdu%27l-Bah%C3%A1\", and \"%25%32%35\".","id":4795}
    {"lang_cluster":"Python","source_code":"\ndef binary_search(l, value):\n    low = 0\n    high = len(l)-1\n    while low <= high: \n        mid = (low+high)\/\/2\n        if l[mid] > value: high = mid-1\n        elif l[mid] < value: low = mid+1\n        else: return mid\n    return -1\n\n# findIndexBinary\u00a0:: (a -> Ordering) -> [a] -> Maybe Int\ndef findIndexBinary(p):\n    def isFound(bounds):\n        (lo, hi) = bounds\n        return lo > hi or 0 == hi\n\n    def half(xs):\n        def choice(lh):\n            (lo, hi) = lh\n            mid = (lo + hi) \/\/ 2\n            cmpr = p(xs[mid])\n            return (lo, mid - 1) if cmpr < 0 else (\n                (1 + mid, hi) if cmpr > 0 else (\n                    mid, 0\n                )\n            )\n        return lambda bounds: choice(bounds)\n\n    def go(xs):\n        (lo, hi) = until(isFound)(\n            half(xs)\n        )((0, len(xs) - 1)) if xs else None\n        return None if 0\u00a0!= hi else lo\n\n    return lambda xs: go(xs)\n\n\n# COMPARISON CONSTRUCTORS ---------------------------------\n\n# compare\u00a0:: a -> a -> Ordering\ndef compare(a):\n    '''Simple comparison of x and y -> LT|EQ|GT'''\n    return lambda b: -1 if a < b else (1 if a > b else 0)\n\n\n# byKV\u00a0:: (a -> b) -> a -> a -> Ordering\ndef byKV(f):\n    '''Property accessor function -> target value -> x -> LT|EQ|GT'''\n    def go(v, x):\n        fx = f(x)\n        return -1 if v < fx else 1 if v > fx else 0\n    return lambda v: lambda x: go(v, x)\n\n\n# TESTS ---------------------------------------------------\ndef main():\n\n    # BINARY SEARCH FOR WORD IN AZ-SORTED LIST\n\n    mb1 = findIndexBinary(compare('iota'))(\n        # Sorted AZ\n        ['alpha', 'beta', 'delta', 'epsilon', 'eta', 'gamma', 'iota',\n         'kappa', 'lambda', 'mu', 'theta', 'zeta']\n    )\n\n    print (\n        'Not found' if None is mb1 else (\n            'Word found at index ' + str(mb1)\n        )\n    )\n\n    # BINARY SEARCH FOR WORD OF GIVEN LENGTH (IN WORD-LENGTH SORTED LIST)\n\n    mb2 = findIndexBinary(byKV(len)(7))(\n        # Sorted by rising length\n        ['mu', 'eta', 'beta', 'iota', 'zeta', 'alpha', 'delta', 'gamma',\n         'kappa', 'theta', 'lambda', 'epsilon']\n    )\n\n    print (\n        'Not found' if None is mb2 else (\n            'Word of given length found at index ' + str(mb2)\n        )\n    )\n\n\n# GENERIC -------------------------------------------------\n\n# until\u00a0:: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n    def go(f, x):\n        v = x\n        while not p(v):\n            v = f(v)\n        return v\n    return lambda f: lambda x: go(f, x)\n\n\nif __name__ == '__main__':\n    main()\n\n","human_summarization":"The code implements a binary search algorithm that searches for a specific number within a sorted integer array. The search can be either recursive or iterative. The code also handles multiple values equal to the given value, and indicates whether the element was found or not. It also provides the index of the found element. The code also includes versions that return the leftmost and rightmost insertion points for the given element. It also handles potential overflow bugs. The code can be generalized to use a custom comparator function for more complex searches.","id":4796}
    {"lang_cluster":"Python","source_code":"\n\nimport sys\nprogram_name = sys.argv[0]\narguments = sys.argv[1:]\ncount = len(arguments)\n\n\n","human_summarization":"The code retrieves and processes command-line arguments given to the program, including the program name. It uses the sys.argv list to access these arguments. The code also handles scenarios where the module is run directly by Python, ensuring all arguments are accessible. It provides the ability to modify the command-line arguments within the Python program, without affecting the arguments seen by other processes. Additionally, it utilizes the optparse module for advanced option parsing capabilities.","id":4797}
    {"lang_cluster":"Python","source_code":"import pygame, sys\nfrom pygame.locals import *\nfrom math import sin, cos, radians\n\npygame.init()\n\nWINDOWSIZE = 250\nTIMETICK = 100\nBOBSIZE = 15\n\nwindow = pygame.display.set_mode((WINDOWSIZE, WINDOWSIZE))\npygame.display.set_caption(\"Pendulum\")\n\nscreen = pygame.display.get_surface()\nscreen.fill((255,255,255))\n\nPIVOT = (WINDOWSIZE\/2, WINDOWSIZE\/10)\nSWINGLENGTH = PIVOT[1]*4\n\nclass BobMass(pygame.sprite.Sprite):\n    def __init__(self):\n        pygame.sprite.Sprite.__init__(self)\n        self.theta = 45\n        self.dtheta = 0\n        self.rect = pygame.Rect(PIVOT[0]-SWINGLENGTH*cos(radians(self.theta)),\n                                PIVOT[1]+SWINGLENGTH*sin(radians(self.theta)),\n                                1,1)\n        self.draw()\n\n    def recomputeAngle(self):\n        scaling = 3000.0\/(SWINGLENGTH**2)\n\n        firstDDtheta = -sin(radians(self.theta))*scaling\n        midDtheta = self.dtheta + firstDDtheta\n        midtheta = self.theta + (self.dtheta + midDtheta)\/2.0\n\n        midDDtheta = -sin(radians(midtheta))*scaling\n        midDtheta = self.dtheta + (firstDDtheta + midDDtheta)\/2\n        midtheta = self.theta + (self.dtheta + midDtheta)\/2\n\n        midDDtheta = -sin(radians(midtheta)) * scaling\n        lastDtheta = midDtheta + midDDtheta\n        lasttheta = midtheta + (midDtheta + lastDtheta)\/2.0\n        \n        lastDDtheta = -sin(radians(lasttheta)) * scaling\n        lastDtheta = midDtheta + (midDDtheta + lastDDtheta)\/2.0\n        lasttheta = midtheta + (midDtheta + lastDtheta)\/2.0\n\n        self.dtheta = lastDtheta\n        self.theta = lasttheta\n        self.rect = pygame.Rect(PIVOT[0]-\n                                SWINGLENGTH*sin(radians(self.theta)), \n                                PIVOT[1]+\n                                SWINGLENGTH*cos(radians(self.theta)),1,1)\n\n\n    def draw(self):\n        pygame.draw.circle(screen, (0,0,0), PIVOT, 5, 0)\n        pygame.draw.circle(screen, (0,0,0), self.rect.center, BOBSIZE, 0)\n        pygame.draw.aaline(screen, (0,0,0), PIVOT, self.rect.center)\n        pygame.draw.line(screen, (0,0,0), (0, PIVOT[1]), (WINDOWSIZE, PIVOT[1]))\n\n    def update(self):\n        self.recomputeAngle()\n        screen.fill((255,255,255))\n        self.draw()\n\nbob = BobMass()\n\nTICK = USEREVENT + 2\npygame.time.set_timer(TICK, TIMETICK)\n\ndef input(events):\n    for event in events:\n        if event.type == QUIT:\n            sys.exit(0)\n        elif event.type == TICK:\n            bob.update()\n\nwhile True:\n    input(pygame.event.get())\n    pygame.display.flip()\n\n''' Python 3.6.5 code using Tkinter graphical user interface.''' \n\nfrom tkinter import *\nimport math\n\nclass Animation:\n    def __init__(self, gw):\n        self.window = gw\n        self.xoff, self.yoff = 300, 100\n        self.angle = 0\n        self.sina = math.sin(self.angle)\n        self.cosa = math.cos(self.angle)\n        self.rodhyp = 170\n        self.bobr = 30\n        self.bobhyp = self.rodhyp + self.bobr\n        self.rodx0, self.rody0 = self.xoff, self.yoff\n        self.ra = self.rodx0\n        self.rb = self.rody0\n        self.rc = self.xoff + self.rodhyp*self.sina\n        self.rd = self.yoff + self.rodhyp*self.cosa\n        self.ba = self.xoff - self.bobr + self.bobhyp*self.sina\n        self.bb = self.yoff - self.bobr + self.bobhyp*self.cosa\n        self.bc = self.xoff + self.bobr + self.bobhyp*self.sina\n        self.bd = self.yoff + self.bobr + self.bobhyp*self.cosa\n        self.da = math.pi \/ 360\n\n        # create \/ fill canvas:\n        self.cnv = Canvas(gw, bg='lemon chiffon')\n        self.cnv.pack(fill=BOTH, expand=True)\n\n        self.cnv.create_line(0, 100, 600, 100,\n                             fill='dodger blue',\n                             width=3)\n        radius = 8\n        self.cnv.create_oval(300-radius, 100-radius,\n                             300+radius, 100+radius,\n                             fill='navy')    \n\n        self.bob = self.cnv.create_oval(self.ba,\n                                        self.bb,\n                                        self.bc,\n                                        self.bd,\n                                        fill='red',\n                                        width=2)\n\n        self.rod = self.cnv.create_line(self.ra,\n                                        self.rb,\n                                        self.rc,\n                                        self.rd,\n                                        fill='dodger blue',\n                                        width=6)\n\n        self.animate()\n\n    def animate(self):\n        if abs(self.angle) > math.pi \/ 2:\n            self.da = - self.da\n        self.angle += self.da\n        self.sina = math.sin(self.angle)\n        self.cosa = math.cos(self.angle)\n        self.ra = self.rodx0\n        self.rb = self.rody0\n        self.rc = self.xoff + self.rodhyp*self.sina\n        self.rd = self.yoff + self.rodhyp*self.cosa\n        self.ba = self.xoff - self.bobr + self.bobhyp*self.sina\n        self.bb = self.yoff - self.bobr + self.bobhyp*self.cosa\n        self.bc = self.xoff + self.bobr + self.bobhyp*self.sina\n        self.bd = self.yoff + self.bobr + self.bobhyp*self.cosa\n        \n        self.cnv.coords(self.rod,\n                        self.ra,\n                        self.rb,\n                        self.rc,\n                        self.rd)\n        self.cnv.coords(self.bob,\n                        self.ba,\n                        self.bb,\n                        self.bc,\n                        self.bd)\n        self.window.update()\n        self.cnv.after(5, self.animate)\n         \nroot = Tk()\nroot.title('Pendulum')\nroot.geometry('600x400+100+50')\nroot.resizable(False, False)\na = Animation(root)\nroot.mainloop()\n\n","human_summarization":"create and animate a simple physical model of a gravity pendulum.","id":4798}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.6+Works with: Python version 3.0+\n>>> import json\n>>> data = json.loads('{ \"foo\": 1, \"bar\": [10, \"apples\"] }')\n>>> sample = { \"blue\": [1,2], \"ocean\": \"water\" }\n>>> json_string = json.dumps(sample)\n>>> json_string\n'{\"blue\": [1, 2], \"ocean\": \"water\"}'\n>>> sample\n{'blue': [1, 2], 'ocean': 'water'}\n>>> data\n{'foo': 1, 'bar': [10, 'apples']}\n\n\n>>> true = True; false = False; null = None\n>>> data = eval('{ \"foo\": 1, \"bar\": [10, \"apples\"] }')\n>>> data\n{'foo': 1, 'bar': [10, 'apples']}\n\n","human_summarization":"\"Load a JSON string into a data structure, create a new data structure, serialize it into JSON using objects and arrays, and ensure the JSON is valid. Also, it demonstrates an alternative (not recommended) way to parse JSON using eval() in Python.\"","id":4799}
    {"lang_cluster":"Python","source_code":"\nfrom decimal import Decimal, getcontext\n\ndef nthroot (n, A, precision):\n    getcontext().prec = precision\n    \n    n = Decimal(n)\n    x_0 = A \/ n #step 1: make a while guess.\n    x_1 = 1     #need it to exist before step 2\n    while True:\n        #step 2:\n        x_0, x_1 = x_1, (1 \/ n)*((n - 1)*x_0 + (A \/ (x_0 ** (n - 1))))\n        if x_0 == x_1:\n            return x_1\n\nprint nthroot(5, 34, 10)\nprint nthroot(10,42, 20)\nprint nthroot(2, 5, 400)\n\n\nWorks with: Python version 3.7\n'''Nth Root'''\n\nfrom decimal import Decimal, getcontext\nfrom operator import eq\n\n\n# nthRoot\u00a0:: Int -> Int -> Int -> Real\ndef nthRoot(precision):\n    '''The nth root of x at the given precision.'''\n    def go(n, x):\n        getcontext().prec = precision\n        dcn = Decimal(n)\n\n        def same(ab):\n            return eq(*ab)\n\n        def step(ab):\n            a, b = ab\n            predn = pred(dcn)\n            return (\n                b,\n                reciprocal(dcn) * (\n                    predn * a + (\n                        x \/ (a ** predn)\n                    )\n                )\n            )\n        return until(same)(step)(\n            (x \/ dcn, 1)\n        )[0]\n    return lambda n: lambda x: go(n, x)\n\n\n# --------------------------TEST---------------------------\ndef main():\n    '''Nth roots at various precisions'''\n\n    def xShow(tpl):\n        p, n, x = tpl\n        return rootName(n) + (\n            ' of ' + str(x) + ' at precision ' + str(p)\n        )\n\n    def f(tpl):\n        p, n, x = tpl\n        return nthRoot(p)(n)(x)\n\n    print(\n        fTable(main.__doc__ + ':\\n')(xShow)(str)(f)(\n            [(10, 5, 34), (20, 10, 42), (30, 2, 5)]\n        )\n    )\n\n\n# -------------------------DISPLAY-------------------------\n\n# fTable\u00a0:: String -> (a -> String) ->\n# (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n    '''Heading -> x display function -> fx display function ->\n       f -> xs -> tabular string.\n    '''\n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n# -------------------------GENERIC-------------------------\n\n# rootName\u00a0:: Int -> String\ndef rootName(n):\n    '''English ordinal suffix.'''\n    return ['identity', 'square root', 'cube root'][n - 1] if (\n        4 > n or 1 > n\n    ) else (str(n) + 'th root')\n\n\n# pred\u00a0::  Enum a => a -> a\ndef pred(x):\n    '''The predecessor of a value. For numeric types, (- 1).'''\n    return x - 1\n\n\n# reciprocal\u00a0:: Num -> Num\ndef reciprocal(x):\n    '''Arithmetic reciprocal of x.'''\n    return 1 \/ x\n\n\n# until\u00a0:: (a -> Bool) -> (a -> a) -> a -> a\ndef until(p):\n    '''The result of repeatedly applying f until p holds.\n       The initial seed value is x.\n    '''\n    def go(f, x):\n        v = x\n        while not p(v):\n            v = f(v)\n        return v\n    return lambda f: lambda x: go(f, x)\n\n\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"Implement the principal nth root algorithm for a positive real number A.","id":4800}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.5\nimport socket\nhost = socket.gethostname()\n\n","human_summarization":"\"Determines and outputs the hostname of the current system where the routine is running.\"","id":4801}
    {"lang_cluster":"Python","source_code":"\ndef Leonardo(L_Zero, L_One, Add, Amount):\n    terms = [L_Zero,L_One]\n    while len(terms) < Amount:\n        new = terms[-1] + terms[-2]\n        new += Add\n        terms.append(new)\n    return terms\n\nout = \"\"\nprint \"First 25 Leonardo numbers:\"\nfor term in Leonardo(1,1,1,25):\n    out += str(term) + \" \"\nprint out\n\nout = \"\"\nprint \"Leonardo numbers with fibonacci parameters:\"\nfor term in Leonardo(0,1,0,25):\n    out += str(term) + \" \"\nprint out\n\n\n","human_summarization":"The code generates the first 25 Leonardo numbers, starting from L(0). It allows the initial two Leonardo numbers (L(0) and L(1)) and the add number to be specified, with 1 as the default add number. The code also provides the functionality to generate the Fibonacci sequence by setting 0 and 1 for L(0) and L(1), and 0 for the add number. Additionally, it includes a Python generator for producing a non-finite stream of Leonardo numbers.","id":4802}
    {"lang_cluster":"Python","source_code":"\n\n'''\n The 24 Game\n\n Given any four digits in the range 1 to 9, which may have repetitions,\n Using just the +, -, *, and \/ operators; and the possible use of\n brackets, (), show how to make an answer of 24.\n\n An answer of \"q\" will quit the game.\n An answer of \"!\" will generate a new set of four digits.\n Otherwise you are repeatedly asked for an expression until it evaluates to 24\n\n Note: you cannot form multiple digit numbers from the supplied digits,\n so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed.\n\n'''\n\nfrom __future__ import division, print_function\nimport random, ast, re\nimport sys\n\nif sys.version_info[0] < 3: input = raw_input\n\ndef choose4():\n    'four random digits >0 as characters'\n    return [str(random.randint(1,9)) for i in range(4)]\n\ndef welcome(digits):\n    print (__doc__)\n    print (\"Your four digits: \" + ' '.join(digits))\n\ndef check(answer, digits):\n    allowed = set('() +-*\/\\t'+''.join(digits))\n    ok = all(ch in allowed for ch in answer) and \\\n         all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \\\n         and not re.search('\\d\\d', answer)\n    if ok:\n        try:\n            ast.parse(answer)\n        except:\n            ok = False\n    return ok\n\ndef main():    \n    digits = choose4()\n    welcome(digits)\n    trial = 0\n    answer = ''\n    chk = ans = False\n    while not (chk and ans == 24):\n        trial +=1\n        answer = input(\"Expression %i: \" % trial)\n        chk = check(answer, digits)\n        if answer.lower() == 'q':\n            break\n        if answer == '!':\n            digits = choose4()\n            print (\"New digits:\", ' '.join(digits))\n            continue\n        if not chk:\n            print (\"The input '%s' was wonky!\" % answer)\n        else:\n            ans = eval(answer)\n            print (\" = \", ans)\n            if ans == 24:\n                print (\"Thats right!\")\n    print (\"Thank you and goodbye\")   \n\nif __name__ == '__main__': main()\n\n\n","human_summarization":"generate and display four random digits from 1 to 9, prompt the player to form an arithmetic expression using these digits exactly once, and check if the expression evaluates to 24. The allowed operations are addition, subtraction, multiplication, and division with floating point or rational arithmetic. The program does not generate or test the validity of the expression.","id":4803}
    {"lang_cluster":"Python","source_code":"\ndef encode(input_string):\n    count = 1\n    prev = None\n    lst = []\n    for character in input_string:\n        if character != prev:\n            if prev:\n                entry = (prev, count)\n                lst.append(entry)\n            count = 1\n            prev = character\n        else:\n            count += 1\n    else:\n        try:\n            entry = (character, count)\n            lst.append(entry)\n            return (lst, 0)\n        except Exception as e:\n            print(\"Exception encountered {e}\".format(e=e)) \n            return (e, 1)\n \ndef decode(lst):\n    q = []\n    for character, count in lst:\n        q.append(character * count)\n    return ''.join(q)\n \n#Method call\nvalue = encode(\"aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa\")\nif value[1] == 0:\n    print(\"Encoded value is {}\".format(value[0]))\n    decode(value[0])\n\n\nWorks with: Python version 2.4\nfrom itertools import groupby\ndef encode(input_string):\n    return [(len(list(g)), k) for k,g in groupby(input_string)]\n\ndef decode(lst):\n    return ''.join(c * n for n,c in lst)\n\nencode(\"aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa\")\ndecode([(5, 'a'), (6, 'h'), (7, 'm'), (1, 'u'), (7, 'i'), (6, 'a')])\n\n\nfrom re import sub\n\ndef encode(text):\n    '''\n    Doctest:\n        >>> encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW')\n        '12W1B12W3B24W1B14W'    \n    '''\n    return sub(r'(.)\\1*', lambda m: str(len(m.group(0))) + m.group(1),\n               text)\n\ndef decode(text):\n    '''\n    Doctest:\n        >>> decode('12W1B12W3B24W1B14W')\n        'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'\n    '''\n    return sub(r'(\\d+)(\\D)', lambda m: m.group(2) * int(m.group(1)),\n               text)\n\ntextin = \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\"\nassert decode(encode(textin)) == textin\n\n","human_summarization":"The code compresses a string of uppercase characters by encoding repeated sequences of the same character with the length of the sequence followed by the character. It also provides a function to reverse this compression. For example, the string \"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW\" is compressed to \"12W1B12W3B24W1B14W\". The code uses regular expressions for both encoding and decoding processes.","id":4804}
    {"lang_cluster":"Python","source_code":"\ns1 = \"hello\"\nprint s1 + \" world\"\n\ns2 = s1 + \" world\"\nprint s2\n\n\n","human_summarization":"The code initializes two string variables, one with a predefined text value and the other as a concatenation of the original string with another string literal. It also demonstrates the use of the 'join' method for efficient string concatenation when dealing with multiple strings, using a specific string as a separator.","id":4805}
    {"lang_cluster":"Python","source_code":"\nimport urllib\ns = 'http:\/\/foo\/bar\/'\ns = urllib.quote(s)\n\n\n","human_summarization":"\"Implements a function to convert a given string into URL encoding format. It converts special, control, and extended characters into a percent symbol followed by a two-digit hexadecimal code. Characters requiring conversion include ASCII control codes, ASCII symbols, and extended characters with codes of 128 and above. The function also supports variations such as lowercase escapes and different encoding standards like RFC 3986 and HTML 5. An optional feature includes the use of an exception string for symbols that don't require conversion.\"","id":4806}
    {"lang_cluster":"Python","source_code":"\n'''Common sorted list'''\n\nfrom itertools import chain\n\n\n# ------------------------- TEST -------------------------\n# main\u00a0:: IO ()\ndef main():\n    '''Sorted union of lists'''\n\n    print(\n        sorted(nub(concat([\n            [5, 1, 3, 8, 9, 4, 8, 7],\n            [3, 5, 9, 8, 4],\n            [1, 3, 7, 9]\n        ])))\n    )\n\n\n# ----------------------- GENERIC ------------------------\n\n# concat\u00a0:: [[a]] -> [a]\n# concat\u00a0:: [String] -> String\ndef concat(xs):\n    '''The concatenation of all the elements in a list.\n    '''\n    return list(chain(*xs))\n\n\n# nub\u00a0:: [a] -> [a]\ndef nub(xs):\n    '''A list containing the same elements as xs,\n       without duplicates, in the order of their\n       first occurrence.\n    '''\n    return list(dict.fromkeys(xs))\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"generates a common sorted list with unique elements from multiple integer arrays.","id":4807}
    {"lang_cluster":"Python","source_code":"\n\n#        NAME, WEIGHT, VALUE (for this weight)\nitems = [(\"beef\",    3.8, 36.0),\n         (\"pork\",    5.4, 43.0),\n         (\"ham\",     3.6, 90.0),\n         (\"greaves\", 2.4, 45.0),\n         (\"flitch\",  4.0, 30.0),\n         (\"brawn\",   2.5, 56.0),\n         (\"welt\",    3.7, 67.0),\n         (\"salami\",  3.0, 95.0),\n         (\"sausage\", 5.9, 98.0)]\n\nMAXWT = 15.0\n\nsorted_items = sorted(((value\/amount, amount, name)\n                       for name, amount, value in items),\n                      reverse = True)\nwt = val = 0\nbagged = []\nfor unit_value, amount, name in sorted_items:\n    portion = min(MAXWT - wt, amount)\n    wt     += portion\n    addval  = portion * unit_value\n    val    += addval\n    bagged += [(name, portion, addval)]\n    if wt >= MAXWT:\n        break\n\nprint(\"    ITEM   PORTION VALUE\")\nprint(\"\\n\".join(\"%10s %6.2f %6.2f\" % item for item in bagged))\nprint(\"\\nTOTAL WEIGHT: %5.2f\\nTOTAL VALUE: %5.2f\" % (wt, val))\n\n\n    ITEM   PORTION VALUE\n    salami   3.00  95.00\n       ham   3.60  90.00\n     brawn   2.50  56.00\n   greaves   2.40  45.00\n      welt   3.50  63.38\n\nTOTAL WEIGHT: 15.00\nTOTAL VALUE: 349.38\n","human_summarization":"implement a solution for the continuous knapsack problem. The thief can select and cut items from a butcher's shop to maximize profit without exceeding a total weight of 15 kg. The items' value reduces proportionally when cut. The solution uses a greedy algorithm to select items based on their value per unit weight.","id":4808}
    {"lang_cluster":"Python","source_code":"\n\n>>> import urllib.request\n>>> from collections import defaultdict\n>>> words = urllib.request.urlopen('http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt').read().split()\n>>> anagram = defaultdict(list) # map sorted chars to anagrams\n>>> for word in words:\n\tanagram[tuple(sorted(word))].append( word )\n\n\t\n>>> count = max(len(ana) for ana in anagram.values())\n>>> for ana in anagram.values():\n\tif len(ana) >= count:\n\t\tprint ([x.decode() for x in ana])\n\n\n>>> import urllib\n>>> from collections import defaultdict\n>>> words = urllib.urlopen('http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt').read().split()\n>>> len(words)\n25104\n>>> anagram = defaultdict(list) # map sorted chars to anagrams\n>>> for word in words:\n\tanagram[tuple(sorted(word))].append( word )\n\n\t\n>>> count = max(len(ana) for ana in anagram.itervalues())\n>>> for ana in anagram.itervalues():\n\tif len(ana) >= count:\n\t\tprint ana\n\n\t\t\n['angel', 'angle', 'galen', 'glean', 'lange']\n['alger', 'glare', 'lager', 'large', 'regal']\n['caret', 'carte', 'cater', 'crate', 'trace']\n['evil', 'levi', 'live', 'veil', 'vile']\n['elan', 'lane', 'lean', 'lena', 'neal']\n['abel', 'able', 'bale', 'bela', 'elba']\n>>> count\n5\n>>>\nWorks with: Python version 2.6 sort and then group using groupby()\n>>> import urllib, itertools\n>>> words = urllib.urlopen('http:\/\/wiki.puzzlers.org\/pub\/wordlists\/unixdict.txt').read().split()\n>>> len(words)\n25104\n>>> anagrams = [list(g) for k,g in itertools.groupby(sorted(words, key=sorted), key=sorted)]\n\n\n>>> count = max(len(ana) for ana in anagrams)\n>>> for ana in anagrams:\n\tif len(ana) >= count:\n\t\tprint ana\n\n\t\t\n['abel', 'able', 'bale', 'bela', 'elba']\n['caret', 'carte', 'cater', 'crate', 'trace']\n['angel', 'angle', 'galen', 'glean', 'lange']\n['alger', 'glare', 'lager', 'large', 'regal']\n['elan', 'lane', 'lean', 'lena', 'neal']\n['evil', 'levi', 'live', 'veil', 'vile']\n>>> count\n5\n>>>\n\n\nWorks with: Python version 3.7\n'''Largest anagram groups found in list of words.'''\n\nfrom os.path import expanduser\nfrom itertools import groupby\nfrom operator import eq\n\n\n# main\u00a0:: IO ()\ndef main():\n    '''Largest anagram groups in local unixdict.txt'''\n\n    print(unlines(\n        largestAnagramGroups(\n            lines(readFile('unixdict.txt'))\n        )\n    ))\n\n\n# largestAnagramGroups\u00a0:: [String] -> [[String]]\ndef largestAnagramGroups(ws):\n    '''A list of the anagram groups of\n       of the largest size found in a\n       given list of words.\n    '''\n\n    # wordChars\u00a0:: String -> (String, String)\n    def wordChars(w):\n        '''A word paired with its\n           AZ sorted characters\n        '''\n        return (''.join(sorted(w)), w)\n\n    groups = list(map(\n        compose(list)(snd),\n        groupby(\n            sorted(\n                map(wordChars, ws),\n                key=fst\n            ),\n            key=fst\n        )\n    ))\n\n    intMax = max(map(len, groups))\n    return list(map(\n        compose(unwords)(curry(map)(snd)),\n        filter(compose(curry(eq)(intMax))(len), groups)\n    ))\n\n\n# GENERIC -------------------------------------------------\n\n# compose (<<<)\u00a0:: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n    '''Right to left function composition.'''\n    return lambda f: lambda x: g(f(x))\n\n\n# curry\u00a0:: ((a, b) -> c) -> a -> b -> c\ndef curry(f):\n    '''A curried function derived\n       from an uncurried function.'''\n    return lambda a: lambda b: f(a, b)\n\n\n# fst\u00a0:: (a, b) -> a\ndef fst(tpl):\n    '''First member of a pair.'''\n    return tpl[0]\n\n\n# lines\u00a0:: String -> [String]\ndef lines(s):\n    '''A list of strings,\n       (containing no newline characters)\n       derived from a single new-line delimited string.'''\n    return s.splitlines()\n\n\n# from os.path import expanduser\n# readFile\u00a0:: FilePath -> IO String\ndef readFile(fp):\n    '''The contents of any file at the path\n       derived by expanding any ~ in fp.'''\n    with open(expanduser(fp), 'r', encoding='utf-8') as f:\n        return f.read()\n\n\n# snd\u00a0:: (a, b) -> b\ndef snd(tpl):\n    '''Second member of a pair.'''\n    return tpl[1]\n\n\n# unlines\u00a0:: [String] -> String\ndef unlines(xs):\n    '''A single string derived by the intercalation\n       of a list of strings with the newline character.'''\n    return '\\n'.join(xs)\n\n\n# unwords\u00a0:: [String] -> String\ndef unwords(xs):\n    '''A space-separated string derived from\n       a list of words.'''\n    return ' '.join(xs)\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"\"Find the largest sets of anagrams from a given word list using Python 3.2 or 2.7, with optimization for speed by avoiding the use of sorted as a key and using a local unixdict.txt file.\"","id":4809}
    {"lang_cluster":"Python","source_code":"\n\ndef in_carpet(x, y):\n    while True:\n        if x == 0 or y == 0:\n            return True\n        elif x % 3 == 1 and y % 3 == 1:\n            return False\n        \n        x \/= 3\n        y \/= 3\n\ndef carpet(n):\n    for i in xrange(3 ** n):\n        for j in xrange(3 ** n):\n            if in_carpet(i, j):\n                print '*',\n            else:\n                print ' ',\n        print\n\ndef sierpinski_carpet(n):\n  carpet = [\"#\"]\n  for i in xrange(n):\n    carpet = [x + x + x for x in carpet] + \\\n             [x + x.replace(\"#\",\" \") + x for x in carpet] + \\\n             [x + x + x for x in carpet]\n  return \"\\n\".join(carpet)\n\nprint sierpinski_carpet(3)\n\nWorks with: Python version 3.7\n'''Iterations of the Sierpinski carpet'''\n\nfrom itertools import chain, islice\nfrom inspect import signature\nfrom operator import add\n\n\n# sierpinskiCarpet\u00a0:: Int -> [String]\ndef sierpinskiCarpet(n):\n    '''A string representing the nth\n       iteration of a Sierpinski carpet.\n    '''\n    f = zipWith(add)\n    g = flip(f)\n\n    # weave\u00a0:: [String] -> [String]\n    def weave(xs):\n        return bind([\n            xs,\n            [' ' * len(s) for s in xs],\n            xs\n        ])(compose(g(xs))(f(xs)))\n\n    return index(\n        iterate(weave)(['\u2593\u2593'])\n    )(n)\n\n\n# TEST ----------------------------------------------------\ndef main():\n    '''Test iteration of the Sierpinski carpet'''\n\n    levels = enumFromTo(0)(3)\n    t = ' ' * (\n        len(' -> ') +\n        max(map(compose(len)(str), levels))\n    )\n    print(\n        fTable(__doc__ + ':')(lambda x: '\\n' + str(x))(\n            lambda xs: xs[0] + '\\n' + (\n                unlines(map(lambda x: t + x, xs[1:])))\n        )\n        (sierpinskiCarpet)(levels)\n    )\n\n\n# GENERIC -------------------------------------------------\n\n# bind (>>=)\u00a0:: [a] -> (a -> [b]) -> [b]\ndef bind(xs):\n    '''List monad injection operator.\n       Two computations sequentially composed,\n       with any value produced by the first\n       passed as an argument to the second.'''\n    return lambda f: list(chain.from_iterable(\n        map(f, xs)\n    ))\n\n\n# compose (<<<)\u00a0:: (b -> c) -> (a -> b) -> a -> c\ndef compose(g):\n    '''Right to left function composition.'''\n    return lambda f: lambda x: g(f(x))\n\n\n# enumFromTo\u00a0:: (Int, Int) -> [Int]\ndef enumFromTo(m):\n    '''Integer enumeration from m to n.'''\n    return lambda n: list(range(m, 1 + n))\n\n\n# flip\u00a0:: (a -> b -> c) -> b -> a -> c\ndef flip(f):\n    '''The (curried or uncurried) function f with its\n       arguments reversed.'''\n    if 1 < len(signature(f).parameters):\n        return lambda a, b: f(b, a)\n    else:\n        return lambda a: lambda b: f(b)(a)\n\n\n# index (!!)\u00a0:: [a] -> Int -> a\ndef index(xs):\n    '''Item at given (zero-based) index.'''\n    return lambda n: None if 0 > n else (\n        xs[n] if (\n            hasattr(xs, \"__getitem__\")\n        ) else next(islice(xs, n, None))\n    )\n\n\n# iterate\u00a0:: (a -> a) -> a -> Gen [a]\ndef iterate(f):\n    '''An infinite list of repeated\n       applications of f to x.\n    '''\n    def go(x):\n        v = x\n        while True:\n            yield v\n            v = f(v)\n    return lambda x: go(x)\n\n\n# unlines\u00a0:: [String] -> String\ndef unlines(xs):\n    '''A single string derived by the intercalation\n       of a list of strings with the newline character.'''\n    return '\\n'.join(xs)\n\n\n# zipWith\u00a0:: (a -> b -> c) -> [a] -> [b] -> [c]\ndef zipWith(f):\n    '''A list constructed by zipping with a\n       custom function, rather than with the\n       default tuple constructor.'''\n    return lambda xs: lambda ys: (\n        map(f, xs, ys)\n    )\n\n\n# OUTPUT FORMATTING ---------------------------------------\n\n# fTable\u00a0:: String -> (a -> String) ->\n#                     (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n    '''Heading -> x display function -> fx display function ->\n                     f -> xs -> tabular string.\n    '''\n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"generate an ASCII-art or graphical representation of a Sierpinski carpet of a given order N, where the placement of whitespace and non-whitespace characters is crucial. The non-whitespace characters can be any character, not necessarily '#'. The code also includes a version that defines a Sierpinski carpet weave declaratively using generic abstractions like zipWith and bind.","id":4810}
    {"lang_cluster":"Python","source_code":"\n\nfrom heapq import heappush, heappop, heapify\nfrom collections import defaultdict\n\ndef encode(symb2freq):\n    \"\"\"Huffman encode the given dict mapping symbols to weights\"\"\"\n    heap = [[wt, [sym, \"\"]] for sym, wt in symb2freq.items()]\n    heapify(heap)\n    while len(heap) > 1:\n        lo = heappop(heap)\n        hi = heappop(heap)\n        for pair in lo[1:]:\n            pair[1] = '0' + pair[1]\n        for pair in hi[1:]:\n            pair[1] = '1' + pair[1]\n        heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])\n    return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))\n\ntxt = \"this is an example for huffman encoding\"\nsymb2freq = defaultdict(int)\nfor ch in txt:\n    symb2freq[ch] += 1\n# in Python 3.1+:\n# symb2freq = collections.Counter(txt)\nhuff = encode(symb2freq)\nprint \"Symbol\\tWeight\\tHuffman Code\"\nfor p in huff:\n    print \"%s\\t%s\\t%s\" % (p[0], symb2freq[p[0]], p[1])\n\n\n","human_summarization":"The code generates a Huffman encoding for each character in a given string. It first creates a tree of nodes based on the frequency of each character, with higher frequency characters having fewer bits in their encoding. The code then traverses the binary tree from root to leaves, assigning and accumulating a '0' for one branch and a '1' for the other at each node. The accumulated zeros and ones at each leaf constitute the Huffman encoding for those characters. The output is a table of characters and their corresponding Huffman encoding, sorted first on length of the code, then on the symbols. The code also includes a method for handling end of file symbols and padding bits for file operations.","id":4811}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 3.7\nfrom functools import partial\nimport tkinter as tk\n\ndef on_click(label: tk.Label,\n             counter: tk.IntVar) -> None:\n    counter.set(counter.get() + 1)\n    label[\"text\"] = f\"Number of clicks: {counter.get()}\"\n\ndef main():\n    window = tk.Tk()\n    window.geometry(\"200x50+100+100\")\n    label = tk.Label(master=window,\n                     text=\"There have been no clicks yet\")\n    label.pack()\n    counter = tk.IntVar()\n    update_counter = partial(on_click,\n                             label=label,\n                             counter=counter)\n    button = tk.Button(master=window,\n                       text=\"click me\",\n                       command=update_counter)\n    button.pack()\n    window.mainloop()\n\nif __name__ == '__main__':\n    main()\n\n\nimport tkinter as tk\n\nclass ClickCounter(tk.Frame):\n    def __init__(self, master=None):\n        super().__init__(master)\n        tk.Pack.config(self)\n        self.label = tk.Label(self, text='There have been no clicks yet')\n        self.label.pack()\n        self.button = tk.Button(self,\n                                text='click me',\n                                command=self.click)\n        self.button.pack()\n        self.count = 0\n\n    def click(self):\n        self.count += 1\n        self.label['text'] = f'Number of clicks: {self.count}'\n\n\nif __name__ == \"__main__\":\n    ClickCounter().mainloop()\n\nfrom functools import partial\nfrom itertools import count\n\nfrom PyQt5.QtWidgets import (QApplication,\n                             QLabel,\n                             QPushButton,\n                             QWidget)\nfrom PyQt5.QtCore import QRect\n\nLABEL_GEOMETRY = QRect(0, 15, 200, 25)\nBUTTON_GEOMETRY = QRect(50, 50, 100, 25)\n\n\ndef on_click(_, label, counter=count(1)):\n    label.setText(f\"Number of clicks: {next(counter)}\")\n\n\ndef main():\n    application = QApplication([])\n    window = QWidget()\n    label = QLabel(text=\"There have been no clicks yet\",\n                   parent=window)\n    label.setGeometry(LABEL_GEOMETRY)\n    button = QPushButton(text=\"click me\",\n                         parent=window)\n    button.setGeometry(BUTTON_GEOMETRY)\n    update_counter = partial(on_click,\n                             label=label)\n    button.clicked.connect(update_counter)\n    window.show()\n    application.lastWindowClosed.connect(window.close)\n    application.exec_()\n\n\nif __name__ == '__main__':\n    main()\n\nimport wx\n\n\nclass ClickCounter(wx.Frame):\n    def __init__(self):\n        super().__init__(parent=None)\n        self.count = 0\n        self.button = wx.Button(parent=self,\n                                label=\"Click me!\")\n        self.label = wx.StaticText(parent=self,\n                                   label=\"There have been no clicks yet\")\n        self.Bind(event=wx.EVT_BUTTON,\n                  handler=self.click,\n                  source=self.button)\n\n        self.sizer = wx.BoxSizer(wx.VERTICAL)\n        self.sizer.Add(window=self.button,\n                       proportion=1,\n                       flag=wx.EXPAND)\n        self.sizer.Add(window=self.label,\n                       proportion=1,\n                       flag=wx.EXPAND)\n        self.SetSizer(self.sizer)\n        self.sizer.Fit(self)\n\n    def click(self, _):\n        self.count += 1\n        self.label.SetLabel(f\"Count: {self.count}\")\n\n\nif __name__ == '__main__':\n    app = wx.App()\n    frame = ClickCounter()\n    frame.Show()\n    app.MainLoop()\n\n","human_summarization":"implement a windowed application with a label and a button. The label initially displays \"There have been no clicks yet\". When the button labeled \"click me\" is clicked, the label updates to show the number of times the button has been clicked.","id":4812}
    {"lang_cluster":"Python","source_code":"\nfor i in xrange(10, -1, -1):\n    print i\n[i for i in xrange(10, -1, -1)]\nimport pprint\npprint.pprint([i for i in xrange(10, -1, -1)])\n","human_summarization":"The code performs a countdown from 10 to 0 using a downward for loop.","id":4813}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 3'''Vigenere encryption and decryption'''\n\nfrom itertools import starmap, cycle\n\n\ndef encrypt(message, key):\n    '''Vigenere encryption of message using key.'''\n\n    # Converted to uppercase.\n    # Non-alpha characters stripped out.\n    message = filter(str.isalpha, message.upper())\n\n    def enc(c, k):\n        '''Single letter encryption.'''\n\n        return chr(((ord(k) + ord(c) - 2 * ord('A')) % 26) + ord('A'))\n\n    return ''.join(starmap(enc, zip(message, cycle(key))))\n\n\ndef decrypt(message, key):\n    '''Vigenere decryption of message using key.'''\n\n    def dec(c, k):\n        '''Single letter decryption.'''\n\n        return chr(((ord(c) - ord(k) - 2 * ord('A')) % 26) + ord('A'))\n\n    return ''.join(starmap(dec, zip(message, cycle(key))))\n\n\ndef main():\n    '''Demonstration'''\n\n    text = 'Beware the Jabberwock, my son! The jaws that bite, ' + (\n           'the claws that catch!'\n    )\n    key = 'VIGENERECIPHER'\n\n    encr = encrypt(text, key)\n    decr = decrypt(encr, key)\n\n    print(text)\n    print(encr)\n    print(decr)\n\n\nif __name__ == '__main__':\n    main()\n\n\n","human_summarization":"Implement both encryption and decryption of a Vigen\u00e8re cipher. The codes handle keys and text of unequal length, capitalize all characters, and discard non-alphabetic characters. Any different handling of non-alphabetic characters is noted.","id":4814}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.x\nfor i in xrange(2, 9, 2):\n    print \"%d,\"\u00a0% i,\nprint \"who do we appreciate?\"\nWorks with: Python version 3.x\nfor i in range(2, 9, 2):\n    print(\"%d, \"\u00a0% i, end=\"\")\nprint(\"who do we appreciate?\")\n\n","human_summarization":"demonstrate a for-loop with a step-value greater than one.","id":4815}
    {"lang_cluster":"Python","source_code":"\nclass Ref(object):\n    def __init__(self, value=None):\n        self.value = value\n\ndef harmonic_sum(i, lo, hi, term):\n    # term is passed by-name, and so is i\n    temp = 0\n    i.value = lo\n    while i.value <= hi:  # Python \"for\" loop creates a distinct which\n        temp += term() # would not be shared with the passed \"i\"\n        i.value += 1   # Here the actual passed \"i\" is incremented.\n    return temp\n\ni = Ref()\n\n# note the correspondence between the mathematical notation and the\n# call to sum it's almost as good as sum(1\/i for i in range(1,101))\nprint harmonic_sum(i, 1, 100, lambda: 1.0\/i.value)\n\n\ndef harmonic_sum(i, lo, hi, term):\n    return sum(term() for i[0] in range(lo, hi + 1))\n \ni = [0]\nprint(harmonic_sum(i, 1, 100, lambda: 1.0 \/ i[0]))\n\n\ndef harmonic_sum(i, lo, hi, term):\n    return sum(eval(term) for i[0] in range(lo, hi + 1))\n \ni = [0]\nprint(harmonic_sum(i, 1, 100, \"1.0 \/ i[0]\"))\n\n\n","human_summarization":"\"Implement Jensen's Device, a programming technique that illustrates the concept of call by name. The code calculates the 100th harmonic number using a sum procedure that takes four parameters. It exploits call by name to re-evaluate an expression passed as a parameter in the caller's context every time the corresponding formal parameter's value is required. The result is the correct harmonic number, 5.18737751764.\"","id":4816}
    {"lang_cluster":"Python","source_code":"\nLibrary: PIL\nimport Image, ImageDraw\n\nimage = Image.new(\"RGB\", (256, 256))\ndrawingTool = ImageDraw.Draw(image)\n\nfor x in range(256):\n    for y in range(256):\n        drawingTool.point((x, y), (0, x^y, 0))\n\ndel drawingTool\nimage.save(\"xorpic.png\", \"PNG\")\n\n\n","human_summarization":"generate a graphical pattern by coloring each pixel based on the 'x xor y' value from a given color table, as described in the Munching Squares programming task.","id":4817}
    {"lang_cluster":"Python","source_code":"\nfrom random import shuffle, randrange\n\ndef make_maze(w = 16, h = 8):\n    vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]\n    ver = [[\"|  \"] * w + ['|'] for _ in range(h)] + [[]]\n    hor = [[\"+--\"] * w + ['+'] for _ in range(h + 1)]\n\n    def walk(x, y):\n        vis[y][x] = 1\n\n        d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]\n        shuffle(d)\n        for (xx, yy) in d:\n            if vis[yy][xx]: continue\n            if xx == x: hor[max(y, yy)][x] = \"+  \"\n            if yy == y: ver[y][max(x, xx)] = \"   \"\n            walk(xx, yy)\n\n    walk(randrange(w), randrange(h))\n\n    s = \"\"\n    for (a, b) in zip(hor, ver):\n        s += ''.join(a + ['\\n'] + b + ['\\n'])\n    return s\n\nif __name__ == '__main__':\n    print(make_maze())\n\n\n","human_summarization":"generate and display a maze using the Depth-first search algorithm. It starts from a random cell, marks it as visited, and gets a list of its neighbors. For each unvisited neighbor, it removes the wall between the current cell and the neighbor, and then recursively continues the process with the neighbor as the current cell.","id":4818}
    {"lang_cluster":"Python","source_code":"\ndef calcPi():\n    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3\n    while True:\n        if 4*q+r-t < n*t:\n            yield n\n            nr = 10*(r-n*t)\n            n  = ((10*(3*q+r))\/\/t)-10*n\n            q  *= 10\n            r  = nr\n        else:\n            nr = (2*q+r)*l\n            nn = (q*(7*k)+2+(r*l))\/\/(t*l)\n            q  *= k\n            t  *= l\n            l  += 2\n            k += 1\n            n  = nn\n            r  = nr\n\nimport sys\npi_digits = calcPi()\ni = 0\nfor d in pi_digits:\n    sys.stdout.write(str(d))\n    i += 1\n    if i == 40: print(\"\"); i = 0\noutput\n3141592653589793238462643383279502884197\n1693993751058209749445923078164062862089\n9862803482534211706798214808651328230664\n7093844609550582231725359408128481117450\n2841027019385211055596446229489549303819\n6442881097566593344612847564823378678316\n5271201909145648566923460348610454326648\n2133936072602491412737245870066063155881\n7488152092096282925409171536436789259036\n0011330530548820466521384146951941511609\n4330572703657595919530921861173819326117\n...\n\n","human_summarization":"are designed to continuously calculate and output the next decimal digit of Pi, starting from 3.14159265, until the user aborts the operation. The calculation of Pi is not based on any built-in constants or functions.","id":4819}
    {"lang_cluster":"Python","source_code":"\n\n>>> [1,2,1,3,2] < [1,2,0,4,4,0,0,0]\nFalse\n\n","human_summarization":"\"Function to compare two numerical lists lexicographically and return true if the first list should be ordered before the second, false otherwise.\"","id":4820}
    {"lang_cluster":"Python","source_code":"\nWorks with: Python version 2.5\ndef ack1(M, N):\n   return (N + 1) if M == 0 else (\n      ack1(M-1, 1) if N == 0 else ack1(M-1, ack1(M, N-1)))\n\nfrom functools import lru_cache\n\n@lru_cache(None)\ndef ack2(M, N):\n    if M == 0:\n        return N + 1\n    elif N == 0:\n        return ack2(M - 1, 1)\n    else:\n        return ack2(M - 1, ack2(M, N - 1))\n\nExample of use:\n>>> import sys\n>>> sys.setrecursionlimit(3000)\n>>> ack1(0,0)\n1\n>>> ack1(3,4)\n125\n>>> ack2(0,0)\n1\n>>> ack2(3,4)\n125\n\ndef ack2(M, N):\n   return (N + 1)   if M == 0 else (\n          (N + 2)   if M == 1 else (\n          (2*N + 3) if M == 2 else (\n          (8*(2**N - 1) + 5) if M == 3 else (\n          ack2(M-1, 1) if N == 0 else ack2(M-1, ack2(M, N-1))))))\n\n\nfrom collections import deque\n\ndef ack_ix(m, n):\n    \"Paddy3118's iterative with optimisations on m\"\n\n    stack = deque([])\n    stack.extend([m, n])\n\n    while  len(stack) > 1:\n        n, m = stack.pop(), stack.pop()\n\n        if   m == 0:\n            stack.append(n + 1)\n        elif m == 1:\n            stack.append(n + 2)\n        elif m == 2:\n            stack.append(2*n + 3)\n        elif m == 3:\n            stack.append(2**(n + 3) - 3)\n        elif n == 0:\n            stack.extend([m-1, 1])\n        else:\n            stack.extend([m-1, m, n-1])\n\n    return stack[0]\n\n","human_summarization":"Implement the Ackermann function, a non-primitive recursive function that always terminates and never takes negative arguments. The function returns the value of A(m, n) with preferred arbitrary precision due to its rapid growth. The implementation also confirms results with Mathematica for ack(4,1) and ack(4,2). The function uses an explicit stack to replace explicit recursive function calls.","id":4821}
    {"lang_cluster":"Python","source_code":"_a =    ( 1.00000000000000000000, 0.57721566490153286061, -0.65587807152025388108,\n         -0.04200263503409523553, 0.16653861138229148950, -0.04219773455554433675,\n         -0.00962197152787697356, 0.00721894324666309954, -0.00116516759185906511,\n         -0.00021524167411495097, 0.00012805028238811619, -0.00002013485478078824,\n         -0.00000125049348214267, 0.00000113302723198170, -0.00000020563384169776,\n          0.00000000611609510448, 0.00000000500200764447, -0.00000000118127457049,\n          0.00000000010434267117, 0.00000000000778226344, -0.00000000000369680562,\n          0.00000000000051003703, -0.00000000000002058326, -0.00000000000000534812,\n          0.00000000000000122678, -0.00000000000000011813, 0.00000000000000000119,\n          0.00000000000000000141, -0.00000000000000000023, 0.00000000000000000002\n       )\ndef gamma (x): \n   y  = float(x) - 1.0;\n   sm = _a[-1];\n   for an in _a[-2::-1]:\n      sm = sm * y + an;\n   return 1.0 \/ sm;\n \n\nif __name__ == '__main__':\n    for i in range(1,11):\n        print \"  %20.14e\" % gamma(i\/3.0)\n\n\n","human_summarization":"implement an algorithm to compute the Gamma function using numerical integration, Lanczos approximation, or Stirling's approximation. It also compares the results with built-in\/library function if available.","id":4822}
    {"lang_cluster":"Python","source_code":"\n\nfrom itertools import permutations\n\nn = 8\ncols = range(n)\nfor vec in permutations(cols):\n    if n == len(set(vec[i]+i for i in cols)) \\\n         == len(set(vec[i]-i for i in cols)):\n        print ( vec )\n\ndef board(vec):\n    print (\"\\n\".join('.' * i + 'Q' + '.' * (n-i-1) for i in vec) + \"\\n===\\n\")\n\nWith the solution represented as a vector with one queen in each row, we don't have to check to see if two queens are on the same row. By using a permutation generator, we know that no value in the vector is repeated, so we don't have to check to see if two queens are on the same column. Since rook moves don't need to be checked, we only need to check bishop moves.\nThe technique for checking the diagonals is to add or subtract the column number from each entry, so any two entries on the same diagonal will have the same value (in other words, the sum or difference is unique for each diagonal). Now all we have to do is make sure that the diagonals for each of the eight queens are distinct. So, we put them in a set (which eliminates duplicates) and check that the set length is eight (no duplicates were removed).\nAny permutation with non-overlapping diagonals is a solution. So, we print it and continue checking other permutations.\n\n\nWorks with: Python version 2.6, 3.x\n# From: http:\/\/wiki.python.org\/moin\/SimplePrograms, with permission from the author, Steve Howell\nBOARD_SIZE = 8\n\ndef under_attack(col, queens):\n    return col in queens or \\\n           any(abs(col - x) == len(queens)-i for i,x in enumerate(queens))\n\ndef solve(n):\n    solutions = [[]]\n    for row in range(n):\n        solutions = [solution+[i+1]\n                       for solution in solutions\n                       for i in range(BOARD_SIZE)\n                       if not under_attack(i+1, solution)]\n    return solutions\n\nfor answer in solve(BOARD_SIZE): print(list(enumerate(answer, start=1)))\n\nWorks with: Python version 2.6, 3.x\nBOARD_SIZE = 8\n\ndef under_attack(col, queens):\n    return col in queens or \\\n           any(abs(col - x) == len(queens)-i for i,x in enumerate(queens))\n\ndef solve(n):\n    solutions = [[]]\n    for row in range(n):\n        solutions = (solution+[i+1]\n                       for solution in solutions # first for clause is evaluated immediately,\n                                                 # so \"solutions\" is correctly captured\n                       for i in range(BOARD_SIZE)\n                       if not under_attack(i+1, solution))\n    return solutions\n\nanswers = solve(BOARD_SIZE)\nfirst_answer = next(answers)\nprint(list(enumerate(first_answer, start=1)))\n\ndef queens(n, i, a, b, c):\n    if i < n:\n        for j in range(n):\n            if j not in a and i + j not in b and i - j not in c:\n                yield from queens(n, i + 1, a + [j], b + [i + j], c + [i - j])\n    else:\n        yield a\n\nfor solution in queens(8, 0, [], [], []):\n    print(solution)\n\ndef queens(x, i, a, b, c):\n    if a:  # a is not empty\n        for j in a:\n            if i + j not in b and i - j not in c:\n                yield from queens(x + [j], i + 1, a - {j}, b | {i + j}, c | {i - j})\n    else:\n        yield x\n\nfor solution in queens([], 0, set(range(8)), set(), set()):\n    print(solution)\n\ndef queens(n):\n    a = list(range(n))\n    up = [True]*(2*n - 1)\n    down = [True]*(2*n - 1)\n    def sub(i):\n        if i == n:\n            yield tuple(a)\n        else:\n            for k in range(i, n):\n                j = a[k]\n                p = i + j\n                q = i - j + n - 1\n                if up[p] and down[q]:\n                    up[p] = down[q] = False\n                    a[i], a[k] = a[k], a[i]\n                    yield from sub(i + 1)\n                    up[p] = down[q] = True\n                    a[i], a[k] = a[k], a[i]\n    yield from sub(0)\n\n#Count solutions for n=8:\nsum(1 for p in queens(8))\n92\n\ndef queens_lex(n):\n    a = list(range(n))\n    up = [True]*(2*n - 1)\n    down = [True]*(2*n - 1)\n    def sub(i):\n        if i == n:\n            yield tuple(a)\n        else:\n            for k in range(i, n):\n                a[i], a[k] = a[k], a[i]\n                j = a[i]\n                p = i + j\n                q = i - j + n - 1\n                if up[p] and down[q]:\n                    up[p] = down[q] = False\n                    yield from sub(i + 1)\n                    up[p] = down[q] = True\n            x = a[i]\n            for k in range(i + 1, n):\n                a[k - 1] = a[k]\n            a[n - 1] = x\n    yield from sub(0)\n\nnext(queens(31))\n(0, 2, 4, 1, 3, 8, 10, 12, 14, 6, 17, 21, 26, 28, 25, 27, 24, 30, 7, 5, 29, 15, 13, 11, 9, 18, 22, 19, 23, 16, 20)\n\nnext(queens_lex(31))\n(0, 2, 4, 1, 3, 8, 10, 12, 14, 5, 17, 22, 25, 27, 30, 24, 26, 29, 6, 16, 28, 13, 9, 7, 19, 11, 15, 18, 21, 23, 20)\n\n#Compare to A065188\n#1, 3, 5, 2, 4, 9, 11, 13, 15, 6, 8, 19, 7, 22, 10, 25, 27, 29, 31, 12, 14, 35, 37, ...\n\nWorks with: Python version 3.7\n'''N Queens problem'''\n\nfrom functools import reduce\nfrom itertools import chain\n\n\n# queenPuzzle\u00a0:: Int -> Int -> [[Int]]\ndef queenPuzzle(nCols):\n    '''All board patterns of this dimension\n       in which no two Queens share a row,\n       column, or diagonal.\n    '''\n    def go(nRows):\n        lessRows = nRows - 1\n        return reduce(\n            lambda a, xys: a + reduce(\n                lambda b, iCol: b + [xys + [iCol]] if (\n                    safe(lessRows, iCol, xys)\n                ) else b,\n                enumFromTo(1)(nCols),\n                []\n            ),\n            go(lessRows),\n            []\n        ) if 0 < nRows else [[]]\n    return go\n\n\n# safe\u00a0:: Int -> Int -> [Int] -> Bool\ndef safe(iRow, iCol, pattern):\n    '''True if no two queens in the pattern\n       share a row, column or diagonal.\n    '''\n    def p(sc, sr):\n        return (iCol == sc) or (\n            sc + sr == (iCol + iRow)\n        ) or (sc - sr == (iCol - iRow))\n    return not any(map(p, pattern, range(0, iRow)))\n\n\n# ------------------------- TEST -------------------------\n# main\u00a0:: IO ()\ndef main():\n    '''Number of solutions for boards of various sizes'''\n\n    n = 5\n    xs = queenPuzzle(n)(n)\n\n    print(\n        str(len(xs)) + ' solutions for a {n} * {n} board:\\n'.format(n=n)\n    )\n    print(showBoards(10)(xs))\n\n    print(\n        fTable(\n            '\\n\\n' + main.__doc__ + ':\\n'\n        )(str)(lambda n: str(n).rjust(3, ' '))(\n            lambda n: len(queenPuzzle(n)(n))\n        )(enumFromTo(1)(10))\n    )\n\n\n# ---------------------- FORMATTING ----------------------\n\n# showBoards\u00a0:: Int -> [[Int]] -> String\ndef showBoards(nCols):\n    '''String representation, with N columns\n       of a set of board patterns.\n    '''\n    def showBlock(b):\n        return '\\n'.join(map(intercalate('  '), zip(*b)))\n\n    def go(bs):\n        return '\\n\\n'.join(map(\n            showBlock,\n            chunksOf(nCols)([\n                showBoard(b) for b in bs\n            ])\n        ))\n    return go\n\n\n# showBoard\u00a0:: [Int] -> String\ndef showBoard(xs):\n    '''String representation of a Queens board.'''\n    lng = len(xs)\n\n    def showLine(n):\n        return ('.' * (n - 1)) + '\u265b' + ('.' * (lng - n))\n    return map(showLine, xs)\n\n\n# fTable\u00a0:: String -> (a -> String) ->\n#                     (b -> String) -> (a -> b) -> [a] -> String\ndef fTable(s):\n    '''Heading -> x display function -> fx display function ->\n                     f -> xs -> tabular string.\n    '''\n    def go(xShow, fxShow, f, xs):\n        ys = [xShow(x) for x in xs]\n        w = max(map(len, ys))\n        return s + '\\n' + '\\n'.join(map(\n            lambda x, y: y.rjust(w, ' ') + ' -> ' + fxShow(f(x)),\n            xs, ys\n        ))\n    return lambda xShow: lambda fxShow: lambda f: lambda xs: go(\n        xShow, fxShow, f, xs\n    )\n\n\n# ----------------------- GENERIC ------------------------\n\n# enumFromTo\u00a0:: (Int, Int) -> [Int]\ndef enumFromTo(m):\n    '''Integer enumeration from m to n.'''\n    return lambda n: range(m, 1 + n)\n\n\n# chunksOf\u00a0:: Int -> [a] -> [[a]]\ndef chunksOf(n):\n    '''A series of lists of length n, subdividing the\n       contents of xs. Where the length of xs is not evenly\n       divible, the final list will be shorter than n.\n    '''\n    return lambda xs: reduce(\n        lambda a, i: a + [xs[i:n + i]],\n        range(0, len(xs), n), []\n    ) if 0 < n else []\n\n\n# intercalate\u00a0:: [a] -> [[a]] -> [a]\n# intercalate\u00a0:: String -> [String] -> String\ndef intercalate(x):\n    '''The concatenation of xs\n       interspersed with copies of x.\n    '''\n    return lambda xs: x.join(xs) if isinstance(x, str) else list(\n        chain.from_iterable(\n            reduce(lambda a, v: a + [x, v], xs[1:], [xs[0]])\n        )\n    ) if xs else []\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n","human_summarization":"The code solves the N-queens puzzle by generating all possible solutions. It uses the itertools module and presents the output in vector form. The code also includes a backtracking solution and a translation of Niklaus Wirth's solution into Python. The algorithm can be improved by using sets instead of lists. The solutions are returned as a generator and the code allows for graphic display of results. It also lists the number of solutions found for boards of various sizes.","id":4823}
    {"lang_cluster":"Python","source_code":"\n\narr1 = [1, 2, 3]\narr2 = [4, 5, 6]\narr3 = [7, 8, 9]\narr4 = arr1 + arr2\nassert arr4 == [1, 2, 3, 4, 5, 6]\narr4.extend(arr3)\nassert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\narr5 = [4, 5, 6]\narr6 = [7, 8, 9]\narr6 += arr5\nassert arr6 == [7, 8, 9, 4, 5, 6]\n","human_summarization":"demonstrate how to concatenate two arrays in the given language, either using the + operator or the list.extend method, which is typically implemented with the += operator.","id":4824}
    {"lang_cluster":"Python","source_code":"\nfrom itertools import combinations\n\ndef anycomb(items):\n    ' return combinations of any length from the items '\n    return ( comb\n             for r in range(1, len(items)+1)\n             for comb in combinations(items, r)\n             )\n\ndef totalvalue(comb):\n    ' Totalise a particular combination of items'\n    totwt = totval = 0\n    for item, wt, val in comb:\n        totwt  += wt\n        totval += val\n    return (totval, -totwt) if totwt <= 400 else (0, 0)\n\nitems = (\n    (\"map\", 9, 150), (\"compass\", 13, 35), (\"water\", 153, 200), (\"sandwich\", 50, 160),\n    (\"glucose\", 15, 60), (\"tin\", 68, 45), (\"banana\", 27, 60), (\"apple\", 39, 40),\n    (\"cheese\", 23, 30), (\"beer\", 52, 10), (\"suntan cream\", 11, 70), (\"camera\", 32, 30),\n    (\"t-shirt\", 24, 15), (\"trousers\", 48, 10), (\"umbrella\", 73, 40),\n    (\"waterproof trousers\", 42, 70), (\"waterproof overclothes\", 43, 75),\n    (\"note-case\", 22, 80), (\"sunglasses\", 7, 20), (\"towel\", 18, 12),\n    (\"socks\", 4, 50), (\"book\", 30, 10),\n    )\nbagged = max( anycomb(items), key=totalvalue) # max val or min wt if values equal\nprint(\"Bagged the following items\\n  \" +\n      '\\n  '.join(sorted(item for item,_,_ in bagged)))\nval, wt = totalvalue(bagged)\nprint(\"for a total value of %i and a total weight of %i\" % (val, -wt))\n\n\n","human_summarization":"The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4kg (or 400 dag). It considers the weight and value of each item, ensuring the total weight does not exceed the limit and the total value is maximized. The code uses the 0-1 Knapsack problem approach, reducing the number of comparisons from N! to 2^N. It does not allow for cutting or diminishing the items.","id":4825}
    {"lang_cluster":"Python","source_code":"\nimport copy\n\nguyprefers = {\n 'abe':  ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay'],\n 'bob':  ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay'],\n 'col':  ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan'],\n 'dan':  ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi'],\n 'ed':   ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay'],\n 'fred': ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay'],\n 'gav':  ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay'],\n 'hal':  ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee'],\n 'ian':  ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve'],\n 'jon':  ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']}\ngalprefers = {\n 'abi':  ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal'],\n 'bea':  ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal'],\n 'cath': ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon'],\n 'dee':  ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed'],\n 'eve':  ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob'],\n 'fay':  ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal'],\n 'gay':  ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian'],\n 'hope': ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred'],\n 'ivy':  ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan'],\n 'jan':  ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']}\n\nguys = sorted(guyprefers.keys())\ngals = sorted(galprefers.keys())\n\n\ndef check(engaged):\n    inverseengaged = dict((v,k) for k,v in engaged.items())\n    for she, he in engaged.items():\n        shelikes = galprefers[she]\n        shelikesbetter = shelikes[:shelikes.index(he)]\n        helikes = guyprefers[he]\n        helikesbetter = helikes[:helikes.index(she)]\n        for guy in shelikesbetter:\n            guysgirl = inverseengaged[guy]\n            guylikes = guyprefers[guy]\n            if guylikes.index(guysgirl) > guylikes.index(she):\n                print(\"%s and %s like each other better than \"\n                      \"their present partners: %s and %s, respectively\"\n                      % (she, guy, he, guysgirl))\n                return False\n        for gal in helikesbetter:\n            girlsguy = engaged[gal]\n            gallikes = galprefers[gal]\n            if gallikes.index(girlsguy) > gallikes.index(he):\n                print(\"%s and %s like each other better than \"\n                      \"their present partners: %s and %s, respectively\"\n                      % (he, gal, she, girlsguy))\n                return False\n    return True\n\ndef matchmaker():\n    guysfree = guys[:]\n    engaged  = {}\n    guyprefers2 = copy.deepcopy(guyprefers)\n    galprefers2 = copy.deepcopy(galprefers)\n    while guysfree:\n        guy = guysfree.pop(0)\n        guyslist = guyprefers2[guy]\n        gal = guyslist.pop(0)\n        fiance = engaged.get(gal)\n        if not fiance:\n            # She's free\n            engaged[gal] = guy\n            print(\"  %s and %s\" % (guy, gal))\n        else:\n            # The bounder proposes to an engaged lass!\n            galslist = galprefers2[gal]\n            if galslist.index(fiance) > galslist.index(guy):\n                # She prefers new guy\n                engaged[gal] = guy\n                print(\"  %s dumped %s for %s\" % (gal, fiance, guy))\n                if guyprefers2[fiance]:\n                    # Ex has more girls to try\n                    guysfree.append(fiance)\n            else:\n                # She is faithful to old fiance\n                if guyslist:\n                    # Look again\n                    guysfree.append(guy)\n    return engaged\n\n\nprint('\\nEngagements:')\nengaged = matchmaker()\n\nprint('\\nCouples:')\nprint('  ' + ',\\n  '.join('%s is engaged to %s' % couple\n                          for couple in sorted(engaged.items())))\nprint()\nprint('Engagement stability check PASSED'\n      if check(engaged) else 'Engagement stability check FAILED')\n\nprint('\\n\\nSwapping two fiances to introduce an error')\nengaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]]\nfor gal in gals[:2]:\n    print('  %s is now engaged to %s' % (gal, engaged[gal]))\nprint()\nprint('Engagement stability check PASSED'\n      if check(engaged) else 'Engagement stability check FAILED')\n\n\n","human_summarization":"\"Implement the Gale-Shapley algorithm to solve the Stable Marriage problem. The program takes as input the preferences of ten men and ten women, and outputs a stable set of engagements. It then perturbs this set to form an unstable set of engagements and checks this new set for stability.\"","id":4826}
    {"lang_cluster":"Python","source_code":"\n\n>>> def a(answer):\n\tprint(\"  # Called function a(%r) -> %r\" % (answer, answer))\n\treturn answer\n\n>>> def b(answer):\n\tprint(\"  # Called function b(%r) -> %r\" % (answer, answer))\n\treturn answer\n\n>>> for i in (False, True):\n\tfor j in (False, True):\n\t\tprint (\"\\nCalculating: x = a(i) and b(j)\")\n\t\tx = a(i) and b(j)\n\t\tprint (\"Calculating: y = a(i) or  b(j)\")\n\t\ty = a(i) or  b(j)\n\n\t\t\n\nCalculating: x = a(i) and b(j)\n  # Called function a(False) -> False\nCalculating: y = a(i) or  b(j)\n  # Called function a(False) -> False\n  # Called function b(False) -> False\n\nCalculating: x = a(i) and b(j)\n  # Called function a(False) -> False\nCalculating: y = a(i) or  b(j)\n  # Called function a(False) -> False\n  # Called function b(True) -> True\n\nCalculating: x = a(i) and b(j)\n  # Called function a(True) -> True\n  # Called function b(False) -> False\nCalculating: y = a(i) or  b(j)\n  # Called function a(True) -> True\n\nCalculating: x = a(i) and b(j)\n  # Called function a(True) -> True\n  # Called function b(True) -> True\nCalculating: y = a(i) or  b(j)\n  # Called function a(True) -> True\n\n\n>>> for i in (False, True):\n\tfor j in (False, True):\n\t\tprint (\"\\nCalculating: x = a(i) and b(j) using x = b(j) if a(i) else False\")\n\t\tx = b(j) if a(i) else False\n\t\tprint (\"Calculating: y = a(i) or  b(j) using y = b(j) if not a(i) else True\")\n\t\ty = b(j) if not a(i) else True\n\n\t\t\n\nCalculating: x = a(i) and b(j) using x = b(j) if a(i) else False\n  # Called function a(False) -> False\nCalculating: y = a(i) or  b(j) using y = b(j) if not a(i) else True\n  # Called function a(False) -> False\n  # Called function b(False) -> False\n\nCalculating: x = a(i) and b(j) using x = b(j) if a(i) else False\n  # Called function a(False) -> False\nCalculating: y = a(i) or  b(j) using y = b(j) if not a(i) else True\n  # Called function a(False) -> False\n  # Called function b(True) -> True\n\nCalculating: x = a(i) and b(j) using x = b(j) if a(i) else False\n  # Called function a(True) -> True\n  # Called function b(False) -> False\nCalculating: y = a(i) or  b(j) using y = b(j) if not a(i) else True\n  # Called function a(True) -> True\n\nCalculating: x = a(i) and b(j) using x = b(j) if a(i) else False\n  # Called function a(True) -> True\n  # Called function b(True) -> True\nCalculating: y = a(i) or  b(j) using y = b(j) if not a(i) else True\n  # Called function a(True) -> True\n\n","human_summarization":"The code defines two functions, a and b, which take a boolean value as input, return the same value, and print their names when called. It then uses short-circuit evaluation to calculate the values of two boolean expressions, x = a(i) and b(j) and y = a(i) or b(j), in such a way that function b is only called when necessary. If the language does not support short-circuit evaluation, this is achieved using nested if statements.","id":4827}
    {"lang_cluster":"Python","source_code":"\nimport time, winsound #, sys\n\nchar2morse = {          \n          \"!\": \"---.\",      \"\\\"\": \".-..-.\",     \"$\": \"...-..-\",    \"'\": \".----.\",  \n          \"(\": \"-.--.\",      \")\": \"-.--.-\",     \"+\": \".-.-.\",      \",\": \"--..--\", \n          \"-\": \"-....-\",     \".\": \".-.-.-\",     \"\/\": \"-..-.\", \n          \"0\": \"-----\",      \"1\": \".----\",      \"2\": \"..---\",      \"3\": \"...--\", \n          \"4\": \"....-\",      \"5\": \".....\",      \"6\": \"-....\",      \"7\": \"--...\", \n          \"8\": \"---..\",      \"9\": \"----.\", \n          \":\": \"---...\",     \";\": \"-.-.-.\",     \"=\": \"-...-\",      \"?\": \"..--..\", \n          \"@\": \".--.-.\", \n          \"A\": \".-\",         \"B\": \"-...\",       \"C\": \"-.-.\",       \"D\": \"-..\", \n          \"E\": \".\",          \"F\": \"..-.\",       \"G\": \"--.\",        \"H\": \"....\", \n          \"I\": \"..\",         \"J\": \".---\",       \"K\": \"-.-\",        \"L\": \".-..\", \n          \"M\": \"--\",         \"N\": \"-.\",         \"O\": \"---\",        \"P\": \".--.\", \n          \"Q\": \"--.-\",       \"R\": \".-.\",        \"S\": \"...\",        \"T\": \"-\", \n          \"U\": \"..-\",        \"V\": \"...-\",       \"W\": \".--\",        \"X\": \"-..-\", \n          \"Y\": \"-.--\",       \"Z\": \"--..\", \n          \"[\": \"-.--.\",      \"]\": \"-.--.-\",     \"_\": \"..--.-\",\n }\n\ne = 50      # Element time in ms. one dit is on for e then off for e\nf = 1280    # Tone freq. in hertz\nchargap = 1 # Time between characters of a word, in units of e\nwordgap = 7 # Time between words, in units of e\n\ndef gap(n=1):\n    time.sleep(n * e \/ 1000)\noff = gap\n\ndef on(n=1):\n    winsound.Beep(f, n * e)\n\ndef dit():\n    on(); off()\n\ndef dah():\n    on(3); off()\n\ndef bloop(n=3):\n    winsound.Beep(f\/\/2, n * e)\n\ndef windowsmorse(text):\n    for word in text.strip().upper().split():\n        for char in word:\n            for element in char2morse.get(char, '?'):\n                if element == '-':\n                    dah()\n                elif element == '.':\n                    dit()\n                else:\n                    bloop()\n            gap(chargap)\n        gap(wordgap)\n\n# Outputs its own source file as Morse. An audible quine!\n#with open(sys.argv[0], 'r') as thisfile:\n#    windowsmorse(thisfile.read())\n    \nwhile True:\n    windowsmorse(input('A string to change into morse: '))\n\n","human_summarization":"<output> convert a given string into audible Morse code and send it to an audio device such as a PC speaker. It either ignores unknown characters or indicates them with a different pitch. <\/output>","id":4828}
    {"lang_cluster":"Python","source_code":"\n'''\nNote that this code is broken, e.g., it won't work when \nblocks = [(\"A\", \"B\"), (\"A\",\"C\")] and the word is \"AB\", where the answer\nshould be True, but the code returns False.\n'''\nblocks = [(\"B\", \"O\"),\n          (\"X\", \"K\"),\n          (\"D\", \"Q\"),\n          (\"C\", \"P\"),\n          (\"N\", \"A\"),\n          (\"G\", \"T\"),\n          (\"R\", \"E\"),\n          (\"T\", \"G\"),\n          (\"Q\", \"D\"),\n          (\"F\", \"S\"),\n          (\"J\", \"W\"),\n          (\"H\", \"U\"),\n          (\"V\", \"I\"),\n          (\"A\", \"N\"),\n          (\"O\", \"B\"),\n          (\"E\", \"R\"),\n          (\"F\", \"S\"),\n          (\"L\", \"Y\"),\n          (\"P\", \"C\"),\n          (\"Z\", \"M\")]\n\n\ndef can_make_word(word, block_collection=blocks):\n    \"\"\"\n    Return True if `word` can be made from the blocks in `block_collection`.\n\n    >>> can_make_word(\"\")\n    False\n    >>> can_make_word(\"a\")\n    True\n    >>> can_make_word(\"bark\")\n    True\n    >>> can_make_word(\"book\")\n    False\n    >>> can_make_word(\"treat\")\n    True\n    >>> can_make_word(\"common\")\n    False\n    >>> can_make_word(\"squad\")\n    True\n    >>> can_make_word(\"coNFused\")\n    True\n    \"\"\"\n    if not word:\n        return False\n\n    blocks_remaining = block_collection[:]\n    for char in word.upper():\n        for block in blocks_remaining:\n            if char in block:\n                blocks_remaining.remove(block)\n                break\n        else:\n            return False\n    return True\n\n\nif __name__ == \"__main__\":\n    import doctest\n    doctest.testmod()\n    print(\", \".join(\"'%s': %s\" % (w, can_make_word(w)) for w in\n                    [\"\", \"a\", \"baRk\", \"booK\", \"treat\", \n                     \"COMMON\", \"squad\", \"Confused\"]))\n\n\n","human_summarization":"The code implements a function that checks if a given word can be spelled using a predefined collection of ABC blocks. Each block contains two letters and can only be used once. The function is case-insensitive and returns a boolean value based on whether the word can be formed or not. It also handles the case of an empty string input.","id":4829}
    {"lang_cluster":"Python","source_code":"\n\nPython 3.x, 2.5 and later 2.x versions\n\n>>> import hashlib\n>>> # RFC 1321    test suite:\n>>> tests = (\n  (b\"\", 'd41d8cd98f00b204e9800998ecf8427e'),\n  (b\"a\", '0cc175b9c0f1b6a831c399e269772661'),\n  (b\"abc\", '900150983cd24fb0d6963f7d28e17f72'),\n  (b\"message digest\", 'f96b697d7cb7938d525a2f31aaf161d0'),\n  (b\"abcdefghijklmnopqrstuvwxyz\", 'c3fcd3d76192e4007dfb496cca67e13b'),\n  (b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", 'd174ab98d277d9f5a5611c2c9f419d9f'),\n  (b\"12345678901234567890123456789012345678901234567890123456789012345678901234567890\", '57edf4a22be3c955ac49da2e2107b67a') )\n>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden\n\n>>>\n\nPython 2.5 and later\n\n>>> import hashlib\n>>> print hashlib.md5(\"The quick brown fox jumped over the lazy dog's back\").hexdigest()\ne38ca1d920c4b8b8d3946b2c72f01680\n\nPre-2.5; removed in 3.x\n\n>>> import md5\n>>> print md5.md5(\"The quick brown fox jumped over the lazy dog's back\").hexdigest()\ne38ca1d920c4b8b8d3946b2c72f01680\n\n","human_summarization":"\"Encode a string using MD5 algorithm and optionally validate the implementation using IETF RFC (1321) test values. However, consider using stronger alternatives like SHA-256 or SHA-3 for production-grade cryptography due to MD5's known weaknesses.\"","id":4830}
    {"lang_cluster":"Python","source_code":"\n\ndata = [\n    '1.3.6.1.4.1.11.2.17.19.3.4.0.10',\n    '1.3.6.1.4.1.11.2.17.5.2.0.79',\n    '1.3.6.1.4.1.11.2.17.19.3.4.0.4',\n    '1.3.6.1.4.1.11150.3.4.0.1',\n    '1.3.6.1.4.1.11.2.17.19.3.4.0.1',\n    '1.3.6.1.4.1.11150.3.4.0'\n]\n\nfor s in sorted(data, key=lambda x: list(map(int, x.split('.')))):\n    print(s)\n\n","human_summarization":"sort a list of Object Identifiers (OIDs). OIDs are dot-separated strings of non-negative integers. The sorting is done lexicographically based on the numeric value of each field. The input is split and each part is mapped to an integer to prevent string comparison.","id":4831}
    {"lang_cluster":"Python","source_code":"\nimport socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.connect((\"localhost\", 256))\nsock.sendall(\"hello socket world\") \nsock.close()\n\n","human_summarization":"opens a socket to localhost on port 256, sends the message \"hello socket world\", and then closes the socket.","id":4832}
    {"lang_cluster":"Python","source_code":"\n\nimport smtplib\n\ndef sendemail(from_addr, to_addr_list, cc_addr_list,\n              subject, message,\n              login, password,\n              smtpserver='smtp.gmail.com:587'):\n    header  = 'From: %s\\n' % from_addr\n    header += 'To: %s\\n' % ','.join(to_addr_list)\n    header += 'Cc: %s\\n' % ','.join(cc_addr_list)\n    header += 'Subject: %s\\n\\n' % subject\n    message = header + message\n    \n    server = smtplib.SMTP(smtpserver)\n    server.starttls()\n    server.login(login,password)\n    problems = server.sendmail(from_addr, to_addr_list, message)\n    server.quit()\n    return problems\n\n\nsendemail(from_addr    = 'python@RC.net', \n          to_addr_list = ['RC@gmail.com'],\n          cc_addr_list = ['RC@xx.co.uk'], \n          subject      = 'Howdy', \n          message      = 'Howdy from a python function', \n          login        = 'pythonuser', \n          password     = 'XXXXX')\n\n\nSample Email received:\nMessage-ID: <4a4a1e78.0717d00a.1ba8.ffcfdbdd@xx.google.com>\nDate: Tue, 30 Jun 2009 22:04:56 -0700 (PDT)\nFrom: python@RC.net\nTo: RC@gmail.com\nCc: RC@xx.co.uk\nSubject: Howdy\n\nHowdy from a python function\n\n\nimport win32com.client\n\ndef sendmail(to, title, body):\n    olMailItem = 0\n    ol = win32com.client.Dispatch(\"Outlook.Application\")\n    msg = ol.CreateItem(olMailItem)\n    msg.To = to\n    msg.Subject = title\n    msg.Body = body\n    msg.Send()\n    ol.Quit()\n\nsendmail(\"somebody@somewhere\", \"Title\", \"Hello\")\n\n","human_summarization":"The code defines a function for sending an email, allowing parameters to set the From, To, Cc addresses, the Subject, and the message text, with optional fields for server name and login details. It returns a dictionary of any addresses it couldn't forward to, while other connection issues raise errors. The solution is portable across different operating systems and has been tested on Windows and all POSIX platforms. It uses the Outlook COM server with the Pywin32 library.","id":4833}
    {"lang_cluster":"Python","source_code":"\nimport sys\nfor n in xrange(sys.maxint):\n    print oct(n)\n\n","human_summarization":"generate a sequential count in octal, starting from zero and incrementing by one on each line until the program is terminated or the maximum numeric type value is reached.","id":4834}
    {"lang_cluster":"Python","source_code":"\n\na, b = b, a\n\ndef swap(a, b):\n    return b, a\n\n","human_summarization":"implement a generic swap function or operator that can interchange the values of two variables or storage places, regardless of their types. This function is designed to work with both statically and dynamically typed languages, with certain constraints for type compatibility. The function does not support swapping between incompatible types such as string and integer. The function also handles issues related to parametric polymorphism in static languages. In Python, the function returns a new pair with the elements' order switched, as tuples are immutable.","id":4835}
    {"lang_cluster":"Python","source_code":"\n\ndef is_palindrome(s):\n  return s == s[::-1]\n\ndef is_palindrome(s):\n  low = 0\n  high = len(s) - 1\n  while low < high:\n    if not s[low].isalpha():\n      low += 1\n    elif not s[high].isalpha():\n      high -= 1\n    else:\n      if s[low].lower()\u00a0!= s[high].lower():\n        return False\n      else:\n        low += 1\n        high -= 1\n        return True\n\ndef is_palindrome_r(s):\n  if len(s) <= 1:\n    return True\n  elif s[0]\u00a0!= s[-1]:\n    return False\n  else:\n    return is_palindrome_r(s[1:-1])\n\ndef is_palindrome_r2(s):\n  return not s or s[0] == s[-1] and is_palindrome_r2(s[1:-1])\n\ndef test(f, good, bad):\n  assert all(f(x) for x in good)\n  assert not any(f(x) for x in bad)\n  print '%s passed all %d tests'\u00a0% (f.__name__, len(good)+len(bad))\n\npals = ('', 'a', 'aa', 'aba', 'abba')\nnotpals = ('aA', 'abA', 'abxBa', 'abxxBa')\nfor ispal in is_palindrome, is_palindrome_r, is_palindrome_r2:\n  test(ispal, pals, notpals)\n\ndef p_loop():\n  import re, string\n  re1=\"\"       # Beginning of Regex\n  re2=\"\"       # End of Regex\n  pal=raw_input(\"Please Enter a word or phrase: \")\n  pd = pal.replace(' ','')\n  for c in string.punctuation:\n     pd = pd.replace(c,\"\")\n  if pal == \"\"\u00a0:\n    return -1\n  c=len(pd)   # Count of chars.\n  loops = (c+1)\/2 \n  for x in range(loops):\n    re1 = re1 + \"(\\w)\"\n    if (c%2 == 1 and x == 0):\n       continue \n    p = loops - x\n    re2 = re2 + \"\\\\\" + str(p)\n  regex= re1+re2+\"$\"   # regex is like \"(\\w)(\\w)(\\w)\\2\\1$\"\n  #print(regex)  # To test regex before re.search\n  m = re.search(r'^'+regex,pd,re.IGNORECASE)\n  if (m):\n     print(\"\\n   \"+'\"'+pal+'\"')\n     print(\"   is a Palindrome\\n\")\n     return 1\n  else:\n     print(\"Nope!\")\n     return 0\n\n'''Palindrome detection'''\n\n\n# isPalindrome\u00a0:: String -> Bool\ndef isPalindrome(s):\n    '''True if the string is unchanged under reversal.\n       (The left half is a reflection of the right half)\n    '''\n    d, m = divmod(len(s), 2)\n    return s[0:d] == s[d + m:][::-1]\n\n\n# ------------------------- TEST -------------------------\n# main\u00a0:: IO ()\ndef main():\n    '''Test'''\n\n    print('\\n'.join(\n        f'{repr(s)} -> {isPalindrome(cleaned(s))}' for s in [\n            \"\",\n            \"a\",\n            \"ab\",\n            \"aba\",\n            \"abba\",\n            \"In girum imus nocte et consumimur igni\"\n        ]\n    ))\n\n\n# cleaned\u00a0:: String -> String\ndef cleaned(s):\n    '''A lower-case copy of s, with spaces pruned.'''\n    return [c.lower() for c in s if ' '\u00a0!= c]\n\n\n# MAIN ---\nif __name__ == '__main__':\n    main()\n\n","human_summarization":"The code includes a function to check if a given sequence of characters is a palindrome. It supports Unicode characters and can detect inexact palindromes by ignoring white-space, punctuation, and case differences. The code uses string reversal technique and recursive function for palindrome detection. It also includes a test function for palindrome using regular expressions in Python 2.7 and a method to check the left half against a reflection of the right half. An unknown technique called \"Twiddle Indexing\" is also used.","id":4836}
    {"lang_cluster":"Python","source_code":"\n\nimport os\nos.environ['HOME']\n\n","human_summarization":"demonstrate how to retrieve a specific environment variable from a process using the os.environ dictionary. The variables available may differ based on the system, but common ones on Unix include PATH, HOME, and USER.","id":4837}
    {"lang_cluster":"Python","source_code":"# Aamrun, 11th July 2022\n\ndef F(n,x,y):\n  if n==0:\n    return x + y\n  elif y==0:\n    return x\n  else:\n    return F(n - 1, F(n, x, y - 1), F(n, x, y - 1) + y)\n    \n    \nprint(\"F(1,3,3) = \", F(1,3,3))\n\n\nF(1,3,3) =  35\n\n","human_summarization":"implement the Sudan function, a non-primitive recursive function. This function takes two inputs (x, y) and returns their sum for the base case. For other cases, it follows a specific recursive pattern as defined in the task.","id":4838}