repo_name
stringlengths
9
74
language
stringclasses
1 value
length_bytes
int64
11
9.34M
extension
stringclasses
2 values
content
stringlengths
11
9.34M
reznikmm/matreshka
Ada
5,031
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.Generic_Collections; package AMF.UML.Continuations.Collections is pragma Preelaborate; package UML_Continuation_Collections is new AMF.Generic_Collections (UML_Continuation, UML_Continuation_Access); type Set_Of_UML_Continuation is new UML_Continuation_Collections.Set with null record; Empty_Set_Of_UML_Continuation : constant Set_Of_UML_Continuation; type Ordered_Set_Of_UML_Continuation is new UML_Continuation_Collections.Ordered_Set with null record; Empty_Ordered_Set_Of_UML_Continuation : constant Ordered_Set_Of_UML_Continuation; type Bag_Of_UML_Continuation is new UML_Continuation_Collections.Bag with null record; Empty_Bag_Of_UML_Continuation : constant Bag_Of_UML_Continuation; type Sequence_Of_UML_Continuation is new UML_Continuation_Collections.Sequence with null record; Empty_Sequence_Of_UML_Continuation : constant Sequence_Of_UML_Continuation; private Empty_Set_Of_UML_Continuation : constant Set_Of_UML_Continuation := (UML_Continuation_Collections.Set with null record); Empty_Ordered_Set_Of_UML_Continuation : constant Ordered_Set_Of_UML_Continuation := (UML_Continuation_Collections.Ordered_Set with null record); Empty_Bag_Of_UML_Continuation : constant Bag_Of_UML_Continuation := (UML_Continuation_Collections.Bag with null record); Empty_Sequence_Of_UML_Continuation : constant Sequence_Of_UML_Continuation := (UML_Continuation_Collections.Sequence with null record); end AMF.UML.Continuations.Collections;
stcarrez/jason
Ada
3,442
ads
----------------------------------------------------------------------- -- jason-projects-modules -- Module projects -- Copyright (C) 2016, 2019 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with ASF.Applications; with ADO; with AWA.Modules; with AWA.Tags.Beans; with AWA.Wikis.Models; with AWA.Wikis.Modules; with Jason.Projects.Models; with Security.Permissions; private with ASF.Converters.Numbers; package Jason.Projects.Modules is -- The name under which the module is registered. NAME : constant String := "projects"; package ACL_View_Projects is new Security.Permissions.Definition ("project-view"); package ACL_Create_Projects is new Security.Permissions.Definition ("project-create"); package ACL_Delete_Projects is new Security.Permissions.Definition ("project-delete"); package ACL_Update_Projects is new Security.Permissions.Definition ("project-update"); -- ------------------------------ -- Module projects -- ------------------------------ type Project_Module is new AWA.Modules.Module with private; type Project_Module_Access is access all Project_Module'Class; -- Initialize the projects module. overriding procedure Initialize (Plugin : in out Project_Module; App : in AWA.Modules.Application_Access; Props : in ASF.Applications.Config); -- Get the projects module. function Get_Project_Module return Project_Module_Access; -- Create procedure Create (Model : in Project_Module; Entity : in out Jason.Projects.Models.Project_Ref'Class); -- Save procedure Save (Model : in Project_Module; Entity : in out Jason.Projects.Models.Project_Ref'Class); -- Create the project wiki space. procedure Create_Wiki (Model : in Project_Module; Entity : in out Jason.Projects.Models.Project_Ref'Class; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class); -- Load the project information. procedure Load_Project (Model : in Project_Module; Project : in out Jason.Projects.Models.Project_Ref'Class; Wiki : in out AWA.Wikis.Models.Wiki_Space_Ref'Class; Tags : in out AWA.Tags.Beans.Tag_List_Bean; Id : in ADO.Identifier; Wiki_Id : in ADO.Identifier); private type Project_Module is new AWA.Modules.Module with record Wiki : AWA.Wikis.Modules.Wiki_Module_Access; Percent_Converter : aliased ASF.Converters.Numbers.Number_Converter; Hour_Converter : aliased ASF.Converters.Numbers.Number_Converter; end record; end Jason.Projects.Modules;
jscparker/math_packages
Ada
45,598
adb
------------------------------------------------------------------------------- -- package body Disorderly.Basic_Rand.Deviates, Floating point random deviates. -- Copyright (C) 1995-2018 Jonathan S. Parker -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ------------------------------------------------------------------------------- with Ada.Numerics.Generic_elementary_functions; with Gamma; package body Disorderly.Basic_Rand.Deviates is Sqrt_Min_Real : constant Real := Two**(Real'Machine_Emin / 2); Sqrt_of_Two_Pi : constant Real := 2.506628274631000502415765284811; Natural_Log_of_2 : constant Real := 0.693147180559945309417232121458; package Math is new Ada.Numerics.Generic_elementary_functions (Real); use Math; package Gam is new Gamma (Real); use Gam; ------------------- -- Log_of_1_plus -- ------------------- -- More accurate than using Log (1 + x) for Abs x << 1. function Log_of_1_plus (x : Real) return Real is u : constant Real := One + x; Eps : constant Real := Two ** (-Real'Machine_Mantissa / 2 - 6); begin if u <= Zero then raise Constraint_Error; end if; -- Use Log(1+x) = x - x^2/2 + x^3/3 - ... = x*(1 - x/2 + x^2/3 ...) -- So if x is somewhat smaller than Sqrt (Real'Epsilon) then 1 + x^2/3 = 1: if Abs (u - One) < Eps then return x - Half * x * x; end if; return Log(u) * x / (u - One); -- u /= One; see above. end Log_of_1_plus; ---------- -- "**" -- ---------- function "**" (Left, Right : Real) return Real is Arg : Real; begin if Left < Zero then raise Constraint_Error; end if; if Right = Zero then -- notice this makes 0**0 = 1 return One; end if; if Left = Zero then return Zero; end if; Arg := Right * Log (Left); if Arg < -Two_to_the_Ninth then return Zero; end if; if Arg > Two_to_the_Ninth then -- or let Exp decide about this? raise Constraint_Error; end if; return Exp (Arg); end "**"; ----------------- -- Random_Real -- ----------------- -- Returns random reals in interval [0, 1). pragma Assert (Real'Digits >= 15); -- use 53+ bit Reals to get the most out of our 61 bit Generator. No_of_Bits_in_Mantissa : constant := 53; -- leave it here, even if using 18 digit reals. Scale : constant Real := Two**(-No_of_Bits_in_Mantissa); -- the Asserts below help optimize this. Its best to just leave -- No_of_Bits_in_Mantissa = 53 bits, and use Real'Digits = 15. procedure Get_Random_Real (Random_Real : out Real; Stream : in out State) is Test1 : Real := One - Scale; pragma Volatile (Test1); --if this is disabled, then assert test stops working pragma Assert (Test1 < One); -- Prevents: Random_Real = 1. -- If Real'Digits = 15, and you get the usual IEEE floats, then -- No_of_Bits_in_Mantissa = 53 bits passes this; 54 doesn't. X : Random_Int; begin Get_Random (X, Stream); Random_Real := Real (X mod 2**No_of_Bits_in_Mantissa) * Scale; end Get_Random_Real; --------------------- -- Get_Exponential -- --------------------- procedure Get_Exponential (Mean : in Real; Stream : in out State; Result : out Real) is X : Real; begin if Mean <= Zero then raise Constraint_Error; end if; Get_non_Zero_Rand: loop Get_Random_Real (X, Stream); exit Get_non_Zero_Rand when X > Zero; end loop Get_non_Zero_Rand; Result := -Mean * Log (X); end Get_Exponential; ------------------ -- Get_Rayleigh -- ------------------ -- The Rayleigh distribution probability density: -- -- f(x) = 2 * x * Exp (-x**2) -- procedure Get_Rayleigh (Stream : in out State; Result : out Real) is X : Real; begin Get_Exponential (Mean => One, Stream => Stream, Result => X); Result := Sqrt (X); end Get_Rayleigh; ----------------- -- Get_Weibull -- ----------------- -- The Weibull distribution probability density: -- -- f(x) = a * x**(a-1) * Exp (-x**a) -- procedure Get_Weibull (a : in Real; Stream : in out State; Result : out Real) is X : Real; begin if a = Zero then raise Constraint_Error; end if; Get_Exponential (Mean => One, Stream => Stream, Result => X); Result := X**(One / a); -- Get_Exponential should never return X=0. end Get_Weibull; ------------------------------ -- Neg_Binomial_Probability -- ------------------------------ -- [Gamma(r + k)/[(Gamma(r)*k!] * p^r * (1-p)^k -- -- Probability of r successes and k failures in n = k+r Bernoulli trials. -- Assumes that the final trial is a success, and p = success probability. function Neg_Binomial_Probability (r : in Real; k : in Integer; p : in Real) return Real is Arg : Real; begin if k < 0 then return Zero; end if; if not p'Valid then raise Constraint_Error; end if; if p <= Zero then raise Constraint_Error; end if; if p >= One then raise Constraint_Error; end if; if not r'Valid then raise Constraint_Error; end if; if r <= Zero then raise Constraint_Error; end if; Arg := (Log_Gamma (r + Real(k)) - Log_Gamma (r) - Log_Gamma (Real(k+1)) + Log (p) * r + Real (k) * Log_of_1_plus (-p)); if Arg < -Two_to_the_Ninth then return Zero; end if; return Exp (Arg); end Neg_Binomial_Probability; ---------------------- -- Get_Neg_Binomial -- ---------------------- -- Adapted from Fortran 77 code from the book: -- Dagpunar, J. 'Principles of random variate generation' -- Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9 -- Translated from Allan Miller's Fortran 90. -- -- Must have: r > 0.0 -- r = the `power' parameter of the negative binomial -- Must have: 0 < p < 1 -- p = Bernoulli success probability -- -- To make this routine conform to distribution returned by function -- Neg_Binomial_Probability, (the interpretation + formula given above is -- from the Wikipedia article on the negative binomial distribution), need -- to swap p and q = 1-p. ie, want r to be number of successes, not failures, -- with last trial being a success. procedure Get_Neg_Binomial (r : in Real; p : in Real; NB_Init : in out Neg_Binomial_Initializer; Stream : in out State; Result : out Real) is -- uln = -ln (2**Machine_Emin) = -Real'Machine_Emin * ln (2). uln : constant Real := -Real (Real'Machine_Emin) * Natural_Log_of_2; h : constant Real := 0.85; p1 : constant Real := One - p; -- the old q q1 : constant Real := p; -- the old p Trunc_r : constant Real := Real'Truncation (r); mr : constant Integer := Integer (Trunc_r); r1 : Real := r; k1, k2 : Real; Reciprocal_Log_q1 : Real; Reciprocal_Log_p1 : Real; begin Result := Zero; if r <= Zero then raise Constraint_Error; end if; if NB_Init.Uninitialized or else p /= NB_Init.p then if p <= Zero or p >= One then raise Constraint_Error; end if; Reciprocal_Log_q1 := One / Log (q1 + Min_Allowed_Real); Reciprocal_Log_p1 := One / Log (p1 + Min_Allowed_Real); NB_Init.p := p; NB_Init.Uninitialized := False; NB_Init.Reciprocal_Log_q1 := Reciprocal_Log_q1; NB_Init.Reciprocal_Log_p1 := Reciprocal_Log_p1; end if; Reciprocal_Log_q1 := NB_Init.Reciprocal_Log_q1; Reciprocal_Log_p1 := NB_Init.Reciprocal_Log_p1; -- The 2nd part (k2 calculation) is too slow if p1 is too near 1. -- The following (Get_k1) is used as an optimization if p1 > 0.85 = h. -- Increment k1, Decrement r1: k1 := Zero; if p1 > h and then mr > 0 then Get_k1: declare Z, del_k : Real; begin for i in 1 .. mr loop Get_Non_Zero: loop Get_Random_Real (Z, Stream); exit Get_Non_Zero when Z > Zero; end loop Get_Non_Zero; del_k := Real'Truncation (Reciprocal_Log_p1 * Log (Z)); k1 := k1 + del_k; --r1 := r1 - One; -- Moved outside loop as r1 := r1 - Trunc_r; assumes mr>0. end loop; r1 := r1 - Trunc_r; -- if Trunc_r = Real (mr) = Real'Truncation (r), then r1 is 0 always. -- When r1=0, the following calculation of k2 does nothing: k2=0. end Get_k1; end if; if r1 > Zero and then r1 > -uln * Reciprocal_Log_q1 then raise Constraint_Error; -- p1 too large (q1 near 0) for this value of r end if; k2 := Zero; Get_k2: declare y : Real := q1**r1; g : Real := r1; Z : Real; begin Get_Random_Real (Z, Stream); loop exit when Z < y; Z := Z - y; k2 := k2 + One; y := y * p1 * g / k2; g := g + One; end loop; end Get_k2; Result := Real'Truncation (k1 + k2 + Half); end Get_Neg_Binomial; -------------------------- -- Binomial_Probability -- -------------------------- -- [n!/(k!(n-k)!)] * p^k * (1-p)^(n-k) if 0 <= k <= n; -- returns 0 otherwise. function Binomial_Probability (n : in Positive; k : in Integer; p : in Real) return Real is Arg : Real; begin if not p'Valid then raise Constraint_Error; end if; if p <= Zero then raise Constraint_Error; end if; if p >= One then raise Constraint_Error; end if; if k > n then return Zero; end if; if k < 0 then return Zero; end if; Arg := (Log_Gamma (Real(n+1)) - Log_Gamma (Real(k+1)) - Log_Gamma (Real(n-k+1)) + Real (k) * Log (p) + Real (n-k) * Log_of_1_plus (-p)); if Arg < -Two_to_the_Ninth then return Zero; end if; return Exp (Arg); end Binomial_Probability; -------------------- -- Reset_Binomial -- -------------------- -- procedure Get_Binomial must call this each time n or p is changed. -- p = Bernoulli success probability -- 0 < p < 1 -- n = number of bernoulli trials : Positive -- n >= 1 procedure Reset_Binomial (n : in Positive; p : in Real; B_Init : out Binomial_Initializer) is begin if p >= One then raise Constraint_Error; end if; if p <= Zero then raise Constraint_Error; end if; B_Init.n := n; B_Init.p := p; B_Init.r0 := Integer (Real'Truncation (Real (n+1) * p)); if B_Init.r0 > n then B_Init.r0 := n; end if; B_Init.p_r := Binomial_Probability (n, B_Init.r0, p); B_Init.Odds_Ratio := p / (One - p); B_Init.Uninitialized := False; end Reset_Binomial; ------------------ -- Get_Binomial -- ------------------ -- function generates a random binomial deviate using C.D.Kemp's method. -- p = Bernoulli success probability -- Must have 0 < p < 1. -- n = number of Bernoulli trials -- Must have n >= 1, (n integer valued). -- Reference: Kemp, C.D. (1986). `A modal method for generating binomial -- variables', Commun. Statist. - Theor. Meth. 15(3), 805-813. -- Author: Allan Miller (Fortran90 version) procedure Get_Binomial (n : in Positive; p : in Real; B_Init : in out Binomial_Initializer; Stream : in out State; Result : out Real) is pragma Assert(Integer'Last >= 2**31-1); -- really should make n 64 bit. Odds_Ratio : Real; p_r : Real; ru, rd, r0 : Integer; u, pd, pu : Real; begin if B_Init.Uninitialized or p /= B_Init.p or n /= B_Init.n then Reset_Binomial (n, p, B_Init); end if; r0 := B_Init.r0; -- r0 almost always = np = mean Odds_Ratio := B_Init.Odds_Ratio; p_r := B_Init.p_r; Result := Real (r0); -- Init Get_Random_Real (u, Stream); u := u - p_r; if u < Zero then Result := Real (r0); return; end if; pu := p_r; ru := r0; pd := p_r; rd := r0; loop rd := rd - 1; if rd >= 0 then pd := pd * Real (rd+1) / (Odds_Ratio * Real (n-rd)); u := u - pd; if u < Zero then Result := Real (rd); return; end if; end if; ru := ru + 1; if (ru <= n) then pu := pu * Real (n-ru+1) * Odds_Ratio / Real (ru); u := u - pu; if u < Zero then Result := Real (ru); return; end if; end if; end loop; end Get_Binomial; ------------------------- -- Poisson_Probability -- ------------------------- -- The Poisson distribution (probability mass function): -- -- f(k) = Mean^k * Exp (-Mean) / k! -- -- Input includes 0. function Poisson_Probability (Mean : in Real; k : in Integer) return Real is Arg : Real; begin if not Mean'Valid then raise Constraint_Error; end if; if Mean <= Zero then raise Constraint_Error; end if; if k < 0 then return Zero; end if; Arg := ( Log (Mean) * Real (k) -Mean -Log_Gamma (Real(k+1)) ); if Arg < -Two_to_the_Ninth then return Zero; end if; return Exp (Arg); end Poisson_Probability; ------------------------ -- Get_Poisson_Tocher -- ------------------------ -- Tocher's algorithm for generating Poisson deviates. -- Slow for Mean ~ 8 or greater. -- Notice should think of it as single-precision, 30 bit. procedure Get_Poisson_Tocher (Mean : in Real; Stream : in out State; Result : out Real) is S : Real := One; A, Random_Real_1, Random_Real_2 : Real; X, X1, X2 : Random_Int; Bits_Per_X : constant := 30; Top_Shift : constant := Bits_per_Random_Number - Bits_Per_X; Scale_30 : constant Real := Two**(-Bits_Per_X); begin Result := Zero; if Mean <= Zero then raise Constraint_Error; end if; A := Exp (-Mean); loop Get_Random (X, Stream); X1 := (X mod 2**Bits_Per_X); -- bottom 30 bits Random_Real_1 := Real (X1) * Scale_30; S := S * Random_Real_1; exit when S < A; Result := Result + One; X2 := (X / 2**Top_Shift); -- top 30 bits Random_Real_2 := Real (X2) * Scale_30; S := S * Random_Real_2; exit when S < A; Result := Result + One; end loop; end Get_Poisson_Tocher; pragma Inline (Get_Poisson_Tocher); ----------------- -- Get_Poisson -- ----------------- -- Use Binomial with small p if mean > 8, else use tocher's algorithm. procedure Get_Poisson (Mean : in Real; P_Init : in out Poisson_Initializer; Stream : in out State; Result : out Real) is Reciprocal_p : constant := 2.0**(-p_Shift); p : constant := 2.0**(p_Shift); n : Integer; begin --if Mean <= Zero then raise Constraint_Error; end if; -- Checked by Get_Poisson_Tocher if Mean < Eight then Get_Poisson_Tocher (Mean, Stream, Result); else -- if Mean > 2.0**11 then raise Constraint_Error; end if; -- if n0 >= Real (Integer'Last) then raise Constraint_Error; end if; -- Let Integer () raise these in next step: n := Integer (Mean * Reciprocal_p); -- p := Mean / Real (n); -- waste of time: error is about the same if p off by this amount. -- In other words can use n-1, n, n+1, doesn't matter. Get_Binomial (n => n, p => p, B_Init => P_Init, Stream => Stream, Result => Result); end if; end Get_Poisson; ------------------------ -- Normal_Probability -- ------------------------ -- The Normal probability density: -- -- f(X) = A * Exp (-(X - Mean)**2 / (Two*Sigma**2)) -- -- A = 1.0 / (Sigma * Sqrt (2*Pi)) function Normal_Probability (Mean : in Real; -- Mean of random variable X Sigma : in Real; -- Std Dev of random variable X X : in Real) return Real is A, B, Arg : Real; begin if Sigma < Sqrt_Min_Real then raise Constraint_Error; end if; Arg := (X - Mean)**2 / (Two*Sigma**2); if Arg > Two_to_the_Ninth then return Zero; end if; B := Exp (-Arg); A := Sigma * Sqrt_of_Two_Pi; return B / A; end Normal_Probability; ------------------ -- Get_Normal_2 -- ------------------ -- Marsaglia-Bray method. -- -- Sigma = Standard_Deviation procedure Get_Normal_2 (Mean : in Real; Sigma : in Real; Stream : in out State; X1, X2 : out Real) is S, Z1, Z2, Coeff_S : Real; begin loop Get_Random_Real (Z1, Stream); Get_Random_Real (Z2, Stream); Z1 := Two * Z1 - One; Z2 := Two * Z2 - One; S := Z1*Z1 + Z2*Z2; exit when S < One and then S > Zero; end loop; Coeff_S := Sigma * Sqrt (-Two * Log (S) / S); X1 := Mean + Z1 * Coeff_S; X2 := Mean + Z2 * Coeff_S; end Get_Normal_2; pragma Inline (Get_Normal_2); ---------------- -- Get_Normal -- ---------------- -- Marsaglia-Bray method. -- -- Sigma = Standard_Deviation procedure Get_Normal (Mean : in Real; Sigma : in Real; N_Init : in out Normal_Initializer; Stream : in out State; Result : out Real) is X1, X2 : Real; begin if N_Init.Uninitialized or else Mean /= N_Init.Mean or else Sigma /= N_Init.Sigma then N_Init.Mean := Mean; N_Init.Sigma := Sigma; Get_Normal_2 (Mean, Sigma, Stream, X1, X2); Result := X1; -- return X1 N_Init.X2 := X2; -- store X2 N_Init.Uninitialized := False; -- Store of X's not empty. else Result := N_Init.X2; -- return X2 N_Init.Uninitialized := True; -- have depleted store of X's end if; end Get_Normal; ---------------------------- -- Log_Normal_Probability -- ---------------------------- -- The Log_Normal probability density: -- -- f(X) = Exp (-(Log(X) - Mean_Z)**2 / (2*Sigma_Z**2)) / (A * X) -- -- f(X) = 0 (for X <= 0) -- -- A = Sigma_Z * Sqrt (2*Pi) -- Z = Log(X) function Log_Normal_Probability (Mean_Z : in Real; -- Mean of random variable Z = Log (X) Sigma_Z : in Real; -- Std Dev of random variable Z = Log (X) X : in Real) return Real is A, B : Real; begin if X < Sqrt_Min_Real then return Zero; end if; if Sigma_Z < Sqrt_Min_Real then raise Constraint_Error; end if; B := Exp (-(Log(X) - Mean_Z)**2 / (Two*Sigma_Z**2)); A := Sigma_Z * Sqrt_of_Two_Pi; return B / (A * X); end Log_Normal_Probability; -------------------- -- Get_Log_Normal -- -------------------- procedure Get_Log_Normal -- outputs random variable X (Mean_Z : in Real; -- Mean of random variable Z = Log (X) Sigma_Z : in Real; -- Std Dev of random variable Z = Log (X) LN_Init : in out Log_Normal_Initializer; Stream : in out State; Result : out Real) -- X is Z1, Z2 : Real; begin if LN_Init.Uninitialized or else Mean_Z /= LN_Init.Mean or else Sigma_Z /= LN_Init.Sigma then LN_Init.Mean := Mean_Z; LN_Init.Sigma := Sigma_Z; Get_Normal_2 (Mean_Z, Sigma_Z, Stream, Z1, Z2); Result := Exp (Z1); -- return X1 LN_Init.X2 := Exp (Z2); -- store X2 LN_Init.Uninitialized := False; -- Store of X's not empty. else Result := LN_Init.X2; -- return X2 LN_Init.Uninitialized := True; -- have depleted store of X's end if; end Get_Log_Normal; ---------------- -- Get_Cauchy -- ---------------- -- The Cauchy (Lorentzian) distribution probability density: -- -- f(X) = A / [(A*A + X*X) * Pi] -- normalized and scaled -- -- Generates random deviates X in range (-inf, inf). procedure Get_Cauchy (A : in Real; Stream : in out State; Result : out Real) is S, X1, X2 : Real; begin Result := Zero; loop Get_Random_Real (X1, Stream); Get_Random_Real (X2, Stream); X1 := Two * X1 - One; X2 := Two * X2 - One; S := X1*X1 + X2*X2; exit when S < One and then X2 > Min_Allowed_Real; -- X2=0 is extremely rare. end loop; Result := A * X1 / X2; end Get_Cauchy; --------------------------- -- Student_t_Probability -- --------------------------- -- Gamma((m+1)/2) * (1 + x*x/m)^(-(m+1)/2) / [Sqrt (m*Pi) * Gamma(m/2)] function Student_t_Probability (m : in Positive; x : in Real) return Real is r : constant Real := Half * Real (m + 1); s : constant Real := Half * Real (m); m_Pi : constant Real := Real (m) * 3.141_592_653_589_793_238_463; Arg, Result : Real := Zero; begin Arg := (Log_Gamma (r) -Log_Gamma (s) -Log (m_Pi) * Half -r * Log_of_1_plus (x*x / Real(m))); if Arg < -Two_to_the_Ninth then Result := Zero; else Result := Exp (Arg); end if; return Result; end Student_t_Probability; ------------------- -- Get_Student_t -- ------------------- -- generates a random deviate from a -- t distribution using Kinderman and Monahan's ratio method. -- -- Must have m >= 1. -- m = degrees of freedom of distribution; -- -- Adapted from Fortran 77 code from the book: -- Dagpunar, J. 'Principles of random variate generation' -- Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9 -- Translated from Allan Miller's Fortran 90 version. procedure Get_Student_t (m : in Positive; Student_t_Init : in out Student_t_Initializer; Stream : in out State; Result : out Real) is s, c, a, f, g : Real; r, x, v : Real; begin s := Real (m); c := -Quarter * (s + One); if Student_t_Init.Uninitialized or Student_t_Init.m /= m then a := Four / (One + One / s)**c; f := Sixteen / a; if m > 1 then g := s - One; g := ((s + One) / g)**c * Sqrt ((s + s) / g); else g := One; end if; Student_t_Init.a := a; Student_t_Init.f := f; Student_t_Init.g := g; Student_t_Init.m := m; else a := Student_t_Init.a; f := Student_t_Init.f; g := Student_t_Init.g; end if; Student_t_Init.Uninitialized := False; Keep_Trying: loop This_Attempt: loop Get_Random_Real (r, Stream); exit This_Attempt when r <= Zero; Get_Random_Real (v, Stream); x := (Two*v - One) * g / r; v := x*x; if v > (Five - a*r) then exit This_Attempt when f < r*(v + Three); exit This_Attempt when r > (One + v/s)**c; end if; exit Keep_Trying; -- if we got this far we're done. end loop This_Attempt; end loop Keep_Trying; Result := x; end Get_Student_t; ---------------------- -- Beta_Probability -- ---------------------- -- f(x) = x**(aa-1) * (1-x)**(bb-1) * -- Gamma (aa + bb) / (Gamma (bb)*Gamma (aa)) -- must have 1 > x > 0. function Beta_Probability (aa, bb : in Real; x : in Real) return Real is Arg, Result : Real := Zero; begin if x <= Zero then raise Constraint_Error; end if; if x >= One then raise Constraint_Error; end if; Arg := Log_Gamma (aa + bb) -Log_Gamma (aa) -Log_Gamma (bb) +Log (x) * (aa - One) +Log_of_1_plus (-x) * (bb - One); if Arg < -Two_to_the_Ninth then Result := Zero; else Result := Exp (Arg); end if; return Result; end Beta_Probability; -------------- -- Get_Beta -- -------------- -- Adapted from Fortran 77 code from the book: -- Dagpunar, J. 'Principles of random variate generation' -- Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9 -- translated from Alan Miller's Fortran 90 version. -- -- Get_Beta generates a random deviate in [0,1] from a beta distribution -- with density proportional to x**(aa-1) * (1-x)**(bb-1), using -- cheng's log logistic method. -- -- Must have aa > 0, bb > 0. -- -- f(x) = x**(aa-1) * (1-x)**(bb-1) * -- Gamma (aa + bb) / (Gamma (bb)*Gamma (aa)) -- procedure Get_Beta (aa : in Real; bb : in Real; Beta_Init : in out Beta_Initializer; Stream : in out State; Result : out Real) is log_of_4 : constant Real := 1.38629436111989061883; --1.38629436112 is gd a, b, g, r, s, x, y, z, test2 : Real; d, f, h, t, c : Real; Swap : Boolean; begin if (aa <= Zero) or (bb <= Zero) then raise Constraint_Error; end if; if Beta_Init.Alpha /= aa then Beta_Init.Uninitialized := True; end if; if Beta_Init.Beta /= bb then Beta_Init.Uninitialized := True; end if; if Beta_Init.Uninitialized then a := aa; b := bb; Swap := b > a; if Swap then g := b; b := a; a := g; end if; d := a / b; f := a + b; if (b > One) then h := Sqrt ((Two*a*b - f) / (f - Two)); t := One; else h := b; t := One / (One + (a / (Max_Allowed_Real*b))**b); end if; c := a + h; Beta_Init.Alpha := aa; Beta_Init.Beta := bb; Beta_Init.d := d; Beta_Init.f := f; Beta_Init.h := h; Beta_Init.t := t; Beta_Init.c := c; Beta_Init.Swap := Swap; Beta_Init.Uninitialized := False; else d := Beta_Init.d; f := Beta_Init.f; h := Beta_Init.h; t := Beta_Init.t; c := Beta_Init.c; Swap := Beta_Init.Swap; end if; Keep_Trying :loop This_Attempt: loop Get_Random_Real (r, Stream); Get_Random_Real (x, Stream); s := r*r*x; exit This_Attempt when (r < Min_Allowed_Real or else s <= Zero); if r < t then x := Log (r / (One - r)) / h; y := d*Exp (x); z := c*x + f*Log ((One + d) / (One + y)) - log_of_4; if (s - One) > z then exit This_Attempt when (s - s*z) > One; exit This_Attempt when Log (s) > z; end if; Result := y / (One + y); else Test2 := (One + One / d)**f; exit This_Attempt when (Four*s > Test2); Result := One; end if; exit Keep_Trying; -- We are done. Only way out. end loop This_Attempt; -- Make another attempt. end loop Keep_Trying; if Swap then Result := One - Result; end if; end Get_Beta; ----------------------------- -- Chi_Squared_Probability -- ----------------------------- -- f(x) = (1 / 2) * (x / 2)**(s-1) * Exp (-x / 2) / Gamma (s) -- -- (where s = 0.5 * Degrees_of_Freedom). function Chi_Squared_Probability (Degrees_of_Freedom : in Real; x : in Real) return Real is s : constant Real := Half * Degrees_of_Freedom; Arg, Result : Real := Zero; begin if s <= Zero then raise Constraint_Error; end if; if x <= Zero then return Zero; end if; Arg := Log (x * Half) * (s - One) -x * Half -Log_Gamma (s); if Arg < -Two_to_the_Ninth then Result := Zero; else Result := Half * Exp (Arg); end if; return Result; end Chi_Squared_Probability; ----------------------- -- Gamma_Probability -- ----------------------- -- f(x) = x**(s-1) * Exp (-x) / Gamma (s) function Gamma_Probability (s : in Real; x : in Real) return Real is Arg, Result : Real := Zero; begin if s <= Zero then raise Constraint_Error; end if; if x <= Zero then return Zero; end if; Arg := Log (x) * (s - One) -x -Log_Gamma (s); if Arg < -Two_to_the_Ninth then Result := Zero; else Result := Exp (Arg); end if; return Result; end Gamma_Probability; ----------------- -- Get_Gamma_1 -- ----------------- -- Uses the algorithm in -- Marsaglia, G. and Tsang, W.W. (2000) `A simple method for generating -- gamma variables', Trans. on Math. Software (TOMS), vol.26(3), pp.363-372. -- translated from Alan Miller's Fortran 90. -- -- Generates a random gamma deviate for shape parameter s >= 1. -- s := Shape parameter of Gamma distribution -- Must have s > 0.0 -- Must have s < 1.0 procedure Get_Gamma_1 (s : in Real; Stream : in out State; Result : out Real) is c, d : Real; u, v, x, y : Real; begin d := s - One / Three; c := One / (Three * Sqrt (d)); loop loop Get_Normal_2 (Zero, One, Stream, x, y); -- Mean=0, Sigma=1 v := (One + c*x)**3; exit when v > Zero; v := (One + c*y)**3; -- 1st try failed exit when v > Zero; end loop; Get_Random_Real (u, Stream); if u < One - 0.0331 * x**4 then Result := d*v; exit; elsif Log (u) < Half * x**2 + d * (One - v + Log (v)) then Result := d*v; exit; end if; end loop; end Get_Gamma_1; ----------------- -- Get_Gamma_2 -- ----------------- -- Adapted from Fortran 77 code from the book: -- Dagpunar, J. 'Principles of random variate generation' -- Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9 -- -- Generates a random deviate in [0,infinity) from a gamma distribution. -- s = Shape parameter of distribution Gamma. -- -- s := Shape parameter of Gamma distribution -- Must have s > 0.0 -- Must have s < 1.0 procedure Get_Gamma_2 (s : in Real; Gamma_Init : in out Gamma_Initializer; Stream : in out State; Result : out Real) is a, r, x, w : Real; p, c, d, uf, vr : Real; begin if (s <= Zero or s >= One) then raise Constraint_Error; end if; a := One - s; if Gamma_Init.Uninitialized or Gamma_Init.s /= s then p := a / (a + s*Exp (-a)); if s < Min_Allowed_Real then raise Constraint_Error; end if; c := One / s; uf := p * (Min_Allowed_Real / a)**s; vr := One - Min_Allowed_Real; d := a * Log (a); Gamma_Init.s := s; Gamma_Init.p := p; Gamma_Init.c := c; Gamma_Init.d := d; Gamma_Init.uf := uf; Gamma_Init.vr := vr; Gamma_Init.Uninitialized := False; else p := Gamma_Init.p; c := Gamma_Init.c; d := Gamma_Init.d; uf := Gamma_Init.uf; vr := Gamma_Init.vr; end if; Keep_Trying: loop This_Attempt: loop Get_Random_Real (r, Stream); if (r >= vr) then exit This_Attempt; elsif (r > p) then x := a - Log ((One - r) / (One - p)); w := a * Log (x) - d; elsif (r > uf) then x := a * (r / p)**c; w := x; else Result := Zero; return; end if; Get_Random_Real (r, Stream); if (One-r <= w and r > Zero) then exit This_Attempt when r*(w + One) >= One; exit This_Attempt when -Log(r) <= w; end if; exit Keep_Trying; end loop This_Attempt; end loop Keep_Trying; Result := x; end Get_Gamma_2; --------------- -- Get_Gamma -- --------------- -- Adapted from Fortran 77 code from the book: -- Dagpunar, J. 'Principles of random variate generation' -- Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9 -- -- s := Shape parameter of Gamma distribution -- Must have s > 0. procedure Get_Gamma (s : in Real; Gamma_Init : in out Gamma_Initializer; Stream : in out State; Result : out Real) is begin if s <= Zero then raise Constraint_Error; end if; if s > One then Get_Gamma_1 (s, Stream, Result); elsif s < One then Get_Gamma_2 (s, Gamma_Init, Stream, Result); else Get_Exponential (One, Stream, Result); -- Mean = 1 end if; end Get_Gamma; --------------------- -- Get_Chi_Squared -- --------------------- -- Generates a random variate from the chi-squared distribution procedure Get_Chi_Squared (Degrees_of_Freedom : in Real; Chi_Init : in out Chi_Initializer; -- subtype of Gamma_Initializer Stream : in out State; Result : out Real) is X: Real; begin if Degrees_of_Freedom <= Zero then raise Constraint_Error; end if; Get_Gamma (Half*Degrees_of_Freedom, Chi_Init, Stream, X); Result := Two * X; end Get_Chi_Squared; -------------- -- LU_Solve -- -------------- -- Solve for X in: Sqrt_Cov*X = b procedure LU_Solve (L : in Matrix; -- L is lower triangle produced by Choleski decomp. b : in Vector; X : out Vector) -- solve for this is Index_First : constant Natural := b'First; -- Index of Matrix is Pos. Index_Last : constant Natural := b'Last; Z : Vector (Index_First..Index_Last); Sum : Real; begin if L'Length(1) <= 1 then raise Constraint_Error; end if; if L'First(2) /= Index_First then raise Constraint_Error; end if; if L'Last(2) /= Index_Last then raise Constraint_Error; end if; -- U' = L -- Solve for Z in L*Z = b. Z(Index_First) := b(Index_First) / L(Index_First,Index_First); for Row in Index_First+1 .. Index_Last loop Sum := Zero; for Col in Index_First .. Row-1 loop Sum := Sum + L(Row,Col) * Z(Col); end loop; Z(Row) := (b(Row) - Sum) / L(Row,Row); end loop; --Row -- Solve for X in U*X = Z. X(Index_Last) := Z(Index_Last) / L(Index_Last,Index_Last); for Row in reverse Index_First .. Index_Last-1 loop Sum := Zero; for Col in Row+1 .. Index_Last loop Sum := Sum + L(Col,Row) * X(Col); -- U = Tr(L) = Tr(L) end loop; X(Row) := (Z(Row) - Sum) / L(Row,Row); end loop; --Row end LU_Solve; ------------------------ -- Choleski_Decompose -- ------------------------ procedure Choleski_Decompose (Covariance : in Matrix; LU_of_Covariance : out Matrix) -- Choleski Decomp of Covariance matrix. is A : Matrix renames LU_of_Covariance; Index_First : constant Natural := Covariance'First(1); -- Index of Matrix is Pos. Index_Last : constant Natural := Covariance'Last(1); Reciprocal_Sqrt_Pivot, Pivot, Sum : Real; Max_Diag_Element : Real := Zero; Safety_Shift : Real; Safety_Fraction : constant Real := Two**(-(Real'Machine_Mantissa * 5) / 6); -- here Safety_Shift is about 10^(-13) begin if Covariance'Length(1) <= 1 then raise Constraint_Error; end if; if Covariance'First(2) /= Index_First then raise Constraint_Error; end if; if Covariance'Last(2) /= Index_Last then raise Constraint_Error; end if; A := Covariance; -- Positive semi-definite matrices have non-neg diag elements. -- If they're < 0, something went wrong only the client knows how to fix: for i in Index_First .. Index_Last loop if A(i,i) < Zero then raise Constraint_Error; end if; end loop; -- Otherwise, add a constant. First find max element of diagonal: Max_Diag_Element := Zero; for i in Index_First .. Index_Last loop if A(i,i) > Max_Diag_Element then Max_Diag_Element := A(i,i); end if; end loop; Safety_Shift := Max_Diag_Element * Safety_Fraction; for i in Index_First .. Index_Last loop A(i,i) := A(i,i) + Safety_Shift; end loop; for i in Index_First .. Index_Last loop Sum := Zero; for Col in Index_First .. i-1 loop Sum := Sum + A(i,Col) * A(i,Col); end loop; Pivot := A(i,i) - Sum; if (Pivot <= Zero) then raise Constraint_Error; end if; -- NOT Positive definite. A(i,i) := Sqrt (Pivot); Reciprocal_Sqrt_Pivot := One / A(i,i); for Row in i+1 .. Index_Last loop Sum := Zero; for Col in Index_First .. i-1 loop Sum := Sum + A(i,Col) * A(Row,Col); end loop; -- Col A(Row,i) := (A(Row,i) - Sum) * Reciprocal_Sqrt_Pivot; end loop; -- Row end loop; -- i end Choleski_Decompose; ----------------------------- -- Get_Multivariate_Normal -- ----------------------------- -- Adapted from Fortran 77 code from the book: -- Dagpunar, J. 'Principles of random variate generation' -- Clarendon Press, Oxford, 1988. ISBN 0-19-852202-9 -- procedure Get_Multivariate_Normal (Mean : in Vector; LU_of_Covariance : in Matrix; MV_Init : in out MV_Normal_Initializer; Stream : in out State; Result : out Vector) is Z : Real; Index_First : constant Natural := Mean'First; -- Index of Mat must be Positive. Index_Last : constant Natural := Mean'Last; begin if Mean'Length < 1 then raise Constraint_Error; end if; if Index_First /= LU_of_Covariance'First(1) then raise Constraint_Error; end if; if Index_Last /= LU_of_Covariance'Last(1) then raise Constraint_Error; end if; Result := Mean; for Col in LU_of_Covariance'Range(2) loop Get_Normal (Zero, One, MV_Init, Stream, Z); --mean=0,sigma=1 for Row in Col .. Index_Last loop Result(Row) := Result(Row) + LU_of_Covariance(Row,Col) * Z; end loop; end loop; end Get_Multivariate_Normal; ------------------------------------- -- Multivariate_Normal_Probability -- ------------------------------------- -- -- f(X) = A * Exp (-(X - Mean)*Covariance_Mat_Inverse*(X - Mean) / 2) -- -- A = 1.0 / Sqrt (Determinant(Covariance_Mat_Inverse) * (2*Pi)^N) -- -- where N = number of variables (length of vector X). function Multivariate_Normal_Probability (Mean : in Vector; -- Means of random variables X LU_of_Covariance : in Matrix; -- L of LU decomp of Covariance matrix X : in Vector) return Real is Index_First : constant Natural := Mean'First; Index_Last : constant Natural := Mean'Last;--Index of Matrix is type Positive. Y, Solution : Vector (Index_First..Index_Last); A, B, Arg, Sum, Prod, Log_Sqrt_Determinant : Real; begin Prod := One; for i in Index_First .. Index_Last loop Prod := Prod * LU_of_Covariance(i,i); end loop; Log_Sqrt_Determinant := Log (Prod + Min_Allowed_Real); for i in Index_First .. Index_Last loop Y(i) := X(i) - Mean (i); end loop; LU_Solve (LU_of_Covariance, Y, Solution); Sum := Zero; for i in Index_First .. Index_Last loop Sum := Sum + Y(i) * Solution (i); end loop; Arg := Half * Sum +Log_Sqrt_Determinant; if Arg > Two_to_the_Ninth then return Zero; end if; B := Exp (-Arg); A := Sqrt_of_Two_Pi ** Integer (X'Length); return B / A; end Multivariate_Normal_Probability; ------------ -- Invert -- ------------ -- Get Inverse of the Matrix: procedure Invert (M : in Matrix; M_Inv : out Matrix; Max_Error : out Real) is Index_Last : constant Positive := M'Last(1); Index_First : constant Positive := M'First(1); Solution_Vector : Vector(Index_First..Index_Last); Unit_Vector : Vector(Index_First..Index_Last) := (others => 0.0); Product : Vector(Index_First..Index_Last) := (others => 0.0); Error : Vector(Index_First..Index_Last) := (others => 0.0); M_LU : Matrix(Index_First..Index_Last,Index_First..Index_Last); Sum : Real; begin Max_Error := 0.0; Choleski_Decompose (Covariance => M, LU_of_Covariance => M_LU); for I in Index_First .. Index_Last loop if I > Index_First then Unit_Vector(I-1) := 0.0; end if; Unit_Vector(I) := 1.0; -- Solve A*X = B: LU_Solve (L => M_LU, B => Unit_Vector, X => Solution_Vector); -- get Error = Unit_Vector - M*Solution_Vector -- Matrix vector product: for Row in Index_First .. Index_Last loop Sum := Zero; for k in Index_First .. Index_Last loop Sum := Sum + M(Row, k) * Solution_Vector(k); end loop; Product(Row) := Sum; end loop; for Row in Index_First .. Index_Last loop Error(Row) := Unit_Vector(Row) - Product(Row); end loop; for I in Index_First..Index_Last loop if Abs(Error(I)) > Max_Error then Max_Error := Abs(Error(I)); end if; end loop; -- Solution vector is the I-th column of M_Inverse: for J in Index_First .. Index_Last loop M_Inv (J, I) := Solution_Vector(J); end loop; end loop; end Invert; ------------------- -- Test_Choleski -- ------------------- procedure Test_Choleski is Index_First : constant := 1; Index_Last : constant := 5; Test : Matrix(Index_First .. Index_Last, Index_First .. Index_Last); T_Inv : Matrix(Index_First .. Index_Last, Index_First .. Index_Last); Max_Error, X : Real; begin X := 0.1234; for i in Index_First .. Index_Last loop for j in Index_First .. Index_Last loop X := X + 1.2345; Test(i,j) := X; end loop; end loop; for i in Index_First .. Index_Last loop for j in i .. Index_Last loop Test(i,j) := Test(j,i); end loop; end loop; for i in Index_First .. Index_Last loop Test(i,i) := Test(i,i) + 20.0 * Real (i); end loop; Invert (M => Test, M_Inv => T_Inv, Max_Error => Max_Error); if Max_Error > 1.0e-8 then raise Constraint_Error; end if; end Test_Choleski; end Disorderly.Basic_Rand.Deviates;
reznikmm/matreshka
Ada
4,719
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Draw.Handle_Mirror_Horizontal_Attributes is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Draw_Handle_Mirror_Horizontal_Attribute_Node is begin return Self : Draw_Handle_Mirror_Horizontal_Attribute_Node do Matreshka.ODF_Draw.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Draw_Prefix); end return; end Create; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Draw_Handle_Mirror_Horizontal_Attribute_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Handle_Mirror_Horizontal_Attribute; end Get_Local_Name; begin Matreshka.DOM_Documents.Register_Attribute (Matreshka.ODF_String_Constants.Draw_URI, Matreshka.ODF_String_Constants.Handle_Mirror_Horizontal_Attribute, Draw_Handle_Mirror_Horizontal_Attribute_Node'Tag); end Matreshka.ODF_Draw.Handle_Mirror_Horizontal_Attributes;
BrickBot/Bound-T-H8-300
Ada
26,188
ads
-- Calculator.Formulas (decl) -- -- Formula construction and execution for the Calculator subsystem. -- Also provides creation of new pools and fluxes. -- -- A component of the Bound-T Worst-Case Execution Time Tool. -- ------------------------------------------------------------------------------- -- Copyright (c) 1999 .. 2015 Tidorum Ltd -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- -- This software is provided by the copyright holders and contributors "as is" and -- any express or implied warranties, including, but not limited to, the implied -- warranties of merchantability and fitness for a particular purpose are -- disclaimed. In no event shall the copyright owner or contributors be liable for -- any direct, indirect, incidental, special, exemplary, or consequential damages -- (including, but not limited to, procurement of substitute goods or services; -- loss of use, data, or profits; or business interruption) however caused and -- on any theory of liability, whether in contract, strict liability, or tort -- (including negligence or otherwise) arising in any way out of the use of this -- software, even if advised of the possibility of such damage. -- -- Other modules (files) of this software composition should contain their -- own copyright statements, which may have different copyright and usage -- conditions. The above conditions apply to this file. ------------------------------------------------------------------------------- -- -- $Revision: 1.22 $ -- $Date: 2015/10/24 19:36:47 $ -- -- $Log: calculator-formulas.ads,v $ -- Revision 1.22 2015/10/24 19:36:47 niklas -- Moved to free licence. -- -- Revision 1.21 2013/12/22 20:14:56 niklas -- Value enumerators obey Storage.Bounds.Opt.Max_Listed_Values and raise -- Unbounded_Set or Storage.Bounds.Unbounded if more values are offered; -- they do not return a truncated list. -- -- Revision 1.20 2013-02-12 08:47:19 niklas -- BT-CH-0245: Global volatile cells and "volatile" assertions. -- -- Revision 1.19 2009-11-27 11:28:07 niklas -- BT-CH-0184: Bit-widths, Word_T, failed modular analysis. -- -- Revision 1.18 2009-10-07 19:26:09 niklas -- BT-CH-0183: Cell-sets are a tagged-type class. -- -- Revision 1.17 2008-04-26 19:19:43 niklas -- BT-CH-0124: Joint loop counters and induction variables. -- -- Revision 1.16 2008/04/22 12:43:30 niklas -- Added function Is_Null (Set). -- -- Revision 1.15 2006/04/28 09:37:13 niklas -- Noted that the default initial value of Formula_T is Nil. -- Added function Interval (Interval_T) return Set. -- Corrected parameter Hull_Bound.Set to be type Set_T. -- Added function Values (Set) giving Value_List_T or -- the new exception Unbounded_Set. -- -- Revision 1.14 2005/10/20 11:28:29 niklas -- BT-CH-0015. -- -- Revision 1.13 2005/02/16 21:11:40 niklas -- BT-CH-0002. -- -- Revision 1.12 2004/05/01 20:12:17 niklas -- First Tidorum version. -- Taking Cell_T stuff from Storage, not from Arithmetic. Removed "use" for -- Arithmetic, added some "use type" for Storage types. -- Added predicates Is_Nil and Not_Nil. -- Added function Set to formulate Range_Pre constraints. -- Added Null_Relation to model false conditions. -- Replaced the function Relation (Effect) by Transformation that maps -- a null Effect to a Nil relation, for use in Join or Apply. -- Changed the Apply function to treat the Nil relation as a neutral -- element (no change in the set). -- Replaced the Convert function by two variants of the Adapted function, -- for pools and fluxes respectively. The new functions detect when no real -- adaptation is required (no change in the cell set) and return the -- input without any further calculation. -- Added some support for unsigned expressions. -- Operators that are not "calculable", such as bit-wise logical operators, -- are mapped to inequalities or to unknown values (unconstrained). -- A conditional assignment with an unknown (or not calculable) condition -- can give valid constraints because the true/false cases can imply some -- common constraints. -- A bound that admits only a single value is now expressed as an equality -- constraint, not two inequalities. -- Added a set of Conjoin operations to build formulas from conjuncts. -- Added support for range assignment constraints. -- Added support for the option Keep_Files. -- -- Revision 1.11 2001/01/07 21:58:15 holsti -- Comment operation added. -- -- Revision 1.10 2001/01/04 16:09:23 saarinen -- Moved function Convert for calculator to here. -- -- Revision 1.9 2000/12/28 13:28:22 saarinen -- Added function Complement. -- -- Revision 1.8 2000/11/23 12:49:22 saarinen -- Deleted procedure Symbolic and variables -- Next_Pool_ID and Next_Flux_ID. -- -- Revision 1.7 2000/09/20 18:46:23 saarinen -- Added function Symbolic. -- Made little changes regarding modified Calc_Handle_T. -- -- Revision 1.6 2000/08/17 13:00:15 holsti -- Mapping domain to expression added. -- -- Revision 1.5 2000/07/17 21:00:07 holsti -- Cell_Set_T instead of Cell_List_T for domains and ranges. -- -- Revision 1.4 2000/07/16 18:40:33 holsti -- Transitive_Closure added. -- -- Revision 1.3 2000/07/14 20:32:20 holsti -- Include creation of new pools and fluxes. -- -- Revision 1.2 2000/07/12 20:47:41 holsti -- Start/Stop calculator implemented here. -- -- Revision 1.1 2000/07/12 12:26:13 holsti -- Calculator.Formulas added and used. -- with Ada.Strings.Unbounded; private package Calculator.Formulas is subtype Formula_T is -- private! Ada.Strings.Unbounded.Unbounded_String; -- -- Contains a calculation formula expressed in Omega syntax. -- Please treat this type as a private type, although it is -- publicly declared. -- -- The default initial value of every Formula_T is the -- special value Nil, which means "no formula" but acts -- as a neutral element in some formula-combining operations. subtype Identifier_T is Formula_T; -- -- A formula that is just the identifier of a set or relation. subtype Set_T is Formula_T; -- -- A formula that denotes a set. subtype Relation_T is Set_T; -- -- A formula that denotes a relation. subtype Tuple_T is Formula_T; -- -- A formula (well, almost) that denotes a tuple, as in -- the domain or range of a set or relation. -- --- Formula-construction operations. -- -- NOTE that the operations DO NOT ensure that the precedence -- and associativity of the Omega operations in the resulting -- formula (string) match the construction tree (since the -- operations do not insert parentheses everywhere). -- -- To control precedence and association, please use the -- function Parens to enclose subexpressions. -- function Nil return Formula_T; -- -- An "empty" formula that acts as a neutral element in -- union, intersection and join operations. -- -- This is also the default initial value of any Formula_T. function Is_Nil (Item : Formula_T) return Boolean; -- -- Whether the Item is a null, empty formula. function Not_Nil (Item : Formula_T) return Boolean; -- -- Whether the Item is a non-null formula. -- Same as not Is_Nil (Item). function Parens (Item : Formula_T) return Formula_T; -- -- The given formula "in parentheses" to ensure that it -- is evaluated as a subformula and its operands are not -- associated with adjacent operators outside the formula. function Id (Item : Pool_T'Class) return Identifier_T; -- -- The formula-identifier for the given pool. function Id (Item : Flux_T'Class) return Identifier_T; -- -- The formula-identifier for the given flux. function Tuple (Cells : Cell_Set_T) return Tuple_T; -- -- The tuple that contains the given cells. function Tuple (Cell : Storage.Cell_T) return Tuple_T; -- -- The singleton tuple that contains just the given cell. function Tuple ( Cells : Cell_Set_T; Dashed : Cell_Set_T; Dash_Volatile : Boolean) return Tuple_T; -- -- The tuple that contains the given cells, with a -- dash mark for the cells that are in Dashed. -- Note that Dashed does not have to be a subset of Cells. -- Moreover, if Dash_Volatile is True, all the Cells that are -- volatile, are also dashed. function Null_Set (Cells : Tuple_T) return Set_T; -- -- The empty set of tuples of the given Cells. function Set ( Cells : Tuple_T; Cond : Arithmetic.Condition_T) return Set_T; -- -- The set that consists of those tuples of the given cells -- that satisfy the given condition. function Interval (Within : Storage.Bounds.Interval_T) return Set_T; -- -- The one-dimensional set that consists of the values Within -- the given interval, which may be unbounded at either end. -- If the interval is unbounded at both ends, the result is Nil. -- The basis cell is not named. function Set ( Cells : Tuple_T; Bounds : Storage.Bounds.Cell_Interval_List_T) return Set_T; -- -- The set that consists of those tuples of the given cells -- that satisfy the given bounds. function Set ( Cells : Tuple_T; Pre : Arithmetic.Effect_T) return Set_T; -- -- The set that consists of those tuples of the given cells -- that satisfy the Range_Pre assignment constraints in Pre. -- Other kinds of assignments in Pre are ignored. function Singleton (Value : Arithmetic.Value_T) return Set_T; -- -- The one-dimensional singleton set {[Value]}. function Singleton (Values : Storage.Bounds.Value_List_T) return Set_T; -- -- The set that consists of a single tuple that has the values -- in the given list. The basis cells are not named. function Identity_Relation (Domain : Tuple_T) return Relation_T; -- -- The identity relation that maps the given domain cells to -- the same range cells with the same values. function Identity_Relation (Domain : Cell_Set_T) return Relation_T; -- -- The identity relation that maps the given domain cells to -- the same range cells with the same values. function Null_Relation (Domain : Tuple_T) return Relation_T; -- -- The relation that maps the given domain cells to the same -- range cells with the same values, but is empty (False -- condition). function Relation ( Domain : Tuple_T; Rainge : Tuple_T) return Relation_T; -- -- The relation that maps the cells in Domain to the cells -- in Rainge (should be Range, but that word is reserved), -- listed in the given orders, with no constraints, except -- for the equality constraints implied by cells that occur -- both in Domain and in Rainge (and are not dashed in the -- Rainge). function Relation ( Domain : Tuple_T; Rainge : Tuple_T; Where : Formula_T) return Relation_T; -- -- The relation that maps the cells in Domain to the cells -- in Rainge (should be Range, but that word is reserved), -- listed in the given orders, constrained by the Where formula -- and the equality constraints implied by cells that occur -- both in Domain and in Rainge (and are not dashed in the -- Rainge). function Warp ( From : Cell_Set_T; To : Cell_Set_T) return Relation_T; -- -- The relation with domain defined by From and range defined -- by To, which preserves the cells in common to From and To, -- discards the cells in From - To, and leaves free (introduces -- new free variables for) the cells in To - From. -- -- If From and To are not the same set, the result is the same -- as from Relation (Domain => From, Rainge => To). -- -- If From and To are identical, Nil is returned. Thus, the -- result should nearly always be used as a Join operand or in -- an Apply operation, where Nil is an identity element function Transformation ( Domain : Cell_Set_T; Effect : Arithmetic.Effect_T) return Relation_T; -- -- The relation that transforms the given domain cells as -- defined by the cell assignments in the given effect. -- -- If the Effect is null (no assignments), the Nil relation -- is returned. Therefore, the result should ordinarily be used -- only as an operand for Join or Apply, where Nil is a neutral -- value. If a real "no transformation" relation is desired, use -- Identity_Relation (Domain). -- -- Assignments to volatile cells result in no constraint. The -- target cell is left free. function Projection ( Domain : Cell_Set_T; To : Storage.Cell_T) return Relation_T; -- -- The relation that projects the Domain cells, To the -- one-dimensional space consisting of the single cell. -- -- If the Width of the Cell is not too large, the projection -- also applies the "mod 2**Width" function. function Mapping ( Domain : Cell_Set_T; Value : Arithmetic.Expr_Ref) return Relation_T; -- -- The relation that transforms the given domain cells into -- one value defined by the arithmetic expression. -- -- If the Width of the Value is not too large, the mapping -- also applies the "mod 2**Width" function. function First_Of_Two return Relation_T; -- -- The relation { [a, b] -> [a] }. function Second_Of_Two return Relation_T; -- -- The relation { [a, b] -> [b] }. function Sum_Of_Two return Relation_T; -- -- The relation { [a, b] -> [a+b] }. function Union (Left, Right : Set_T) return Set_T; -- -- The union of two sets or relations. -- If either operand is Nil, the result is the other operand. function Intersection (Left, Right : Set_T) return Set_T; -- -- The Intersection of two sets or relations. -- If either operand is Nil, the result is the other operand. function Difference (Left, Right : Set_T) return Set_T; -- -- The difference set: Left minus Right. -- If Left is Nil, the result is Nil. -- If Right is Nil, the result is Left. function "-" (Left, Right : Set_T) return Set_T renames Difference; -- -- Infix set difference. function Join (Left, Right : Relation_T) return Relation_T; -- -- The join (.) of two relations. -- If either operand is Nil, the result is the other operand. function Transitive_Closure (Item : Relation_T) return Relation_T; -- -- The transitive closure of the given relation. -- This is defined as the union of the relation sequence -- R(i) where R(0) = Item and R(i+1) = Join (R(i), Item). -- Note that the Omega Calculator may compute an approximation -- of the real transitive closure. -- -- As an exception to the general rule about user-controlled -- precedence and association, the result of this function -- is protected and will not mix harmfully with adjacent -- parts of a formula. function Domain (Item : Relation_T) return Set_T; -- -- The domain of the relation, including all constraints -- of the relation. function Rainge (Item : Relation_T) return Set_T; -- -- The range of the relation, including all constraints -- of the relation. Sorry for the ugly spelling, but -- "range" is a reserved word. function Complement (Item : Set_T) return Set_T; -- -- The complement of the set. function Apply ( Relation : Relation_T; To_Set : Set_T) return Set_T; -- -- The set that results from applying the given relation to -- the given set as domain, and collecting the related range -- tuples. -- -- If Relation is Nil, To_Set is returned with no change. function Restrict_Range ( Relation : Relation_T; Subrange : Set_T) return Relation_T; -- -- The given relation, restricted to only those tuple pairs -- where the range part is in the given Subrange. function Restrict_Domain ( Relation : Relation_T; Subdomain : Set_T) return Relation_T; -- -- The given relation, restricted to only those tuple pairs -- where the domain part is in the given Subdomain. function Adapted ( Pool : Pool_T'Class; To : Cell_Set_T) return Set_T; -- -- The set defined by the given Pool, but adapted (projected, widened) -- To a different (usually larget) set of cells, so that the adapted -- set is based on the To domain. -- -- The adapted set equals Pool when projected to Pool.Cells. It does -- not constrain the remaining cells in To, that is To - Pool.Cells. -- -- If the To set is not a superset of Pool.Cells, the constraints -- implied by Pool on the cells in Pool.Cells - To are lost in the -- result, because these cells are elided. -- -- If it happens that Pool.Cells equals the To set, the function -- returns the Id of Pool without any further calculation. function Adapted ( Flux : Flux_T; To : Cell_Set_T) return Relation_T; -- -- The relation defined by the given Flux, but adapted To a different -- (usually larger) set of domain and range cells, so that the -- adapted relation is To -> To. -- -- The adapted relation equals Flux on the sub-domain formed by -- Flux.Cells and is the identity relation on the sub-domain formed -- by the remaining cells in To, that is To - Flux.Cells. -- -- In other words, the adapted relation corresponds to a computation -- that takes a valuation of the cells in To, changes the values of the -- cells in Flux.Cells as defined by Flux, and leaves the other cells -- unchanged. -- -- If the To set is not a superset of Flux.Cells, the adapted relation -- hides the effect of Flux on the cells in Flux.Cells - To, because -- these cells are elided from the domain and range. -- -- If it happens that Flux.Cells equals the To set, the function -- returns the Id of Flux without any further calculation. -- --- Induction variables and iteration counters -- -- In a loop, induction variables are those cells that have a -- bounded (at least from one side) step (additive change) on -- each loop iteration. To find loop bounds, we introduce a -- synthetic, joint iteration counter and constrain each induction -- variable to its initial value plus its step times the counter. -- -- Note that this joint iteration counter is not a Storage.Cell_T -- and is therefore not included in the set of Cells of fluxes and -- pools, even if included in the domain and/or range. In the -- calculator formulae, the iteration counter is represented by -- an identifier that must not equal the Name_Of any real cell. function Counter_Tuple return Tuple_T; -- -- The tuple that contains only the synthetic joint iteration -- counter, with no dash mark. function Tuple_With_Counter (Cells : Cell_Set_T) return Tuple_T; -- -- The tuple that contains the given Cells, followed by the -- synthetic joint iteration counter. No dash marks. function Induction_Model ( Cells : Cell_Set_T; Invariant : Cell_Set_T; Induction : Storage.Cell_List_T; Step : Storage.Bounds.Interval_List_T) return Relation_T; -- -- The relation that expresses the constraints on the values of -- the Induction variables as a function of the initial values, -- the Steps of the Induction variables, and the iteration counter. -- -- The domain of the relation is the Cells, representing the initial -- values on entry to the loop, plus the iteration counter, -- representing the number of the iteration: 0, 1, 2, ... -- -- The range of the relation is the Cells, representing the values -- at the start of the loop on the given iteration. A cell is marked -- with a dash (changed) if it is an Induction variable or is not -- an Invariant cell. Each Induction variable is constrained to its -- initial value (from the domain) plus its Step times the iteration -- counter. -- -- This relation expresses no other loop properties, such as the -- actual initial values or the termination conditions. -- --- Calculation operations -- function Start return Calc_Handle_T; -- -- Starts a calculator instance. -- -- Using : nothing -- Giving : calculator handle. procedure Stop (Calc : in out Calc_Handle_T); -- -- Stops a calculator instance. -- -- Using : calculator-handle -- Giving : updated (now invalid) calculator handle. procedure Comment ( Text : in String; Calc : in Calc_Handle_T); -- -- Provides a textual comment or description of the calculation -- about to be performed, or of the result(s) just calculated. -- This has no effect on the calculation, but may help the user -- understand problems and correct them. procedure Assign ( Target : in Identifier_T; Value : in Formula_T; Calc : in Calc_Handle_T); -- -- Assigns the given value to the named target in the -- specified calculator. There are no output parameters, -- but the calculator stores the Value under the Target -- identifier for later access in formulae. function Value ( Formula : Formula_T; Calc : Calc_Handle_T) return Formula_T; -- -- Evaluates a formula in the specified calculator and -- returns the result (with echos and empty lines removed). function Subset ( Left : Set_T; Right : Set_T; Calc : Calc_Handle_T) return Boolean; -- -- Whether Left is calculated to be a subset of Right. function Is_Null ( Set : Set_T; Cells : Tuple_T; Calc : Calc_Handle_T) return Boolean; -- -- Whether the Set is calculated to be a null (empty) set -- for the given Cells. function Is_Null ( Set : Set_T; Calc : Calc_Handle_T) return Boolean; -- -- Whether the one-dimensional Set is calculated to be a null -- (empty) set. The cells contained in the Set are irrelevant. function Superset ( Set : Set_T; Of_Interval : Storage.Bounds.Interval_T; Calc : Calc_Handle_T) return Boolean; -- -- Whether the one-dimensional Set is calculated to be a superset -- Of the given Interval, that is, whether the Interval is a -- subset of the Set. function Hull_Bound ( Set : Set_T; Calc : Calc_Handle_T) return Storage.Bounds.Interval_T; -- -- Given a one-dimensional set, this function computes bounds -- on the convex hull of the set. Unbounded_Set : exception; -- -- Signals an attempt to list the Values in an unbounded set. function Values ( Set : Set_T; Calc : Calc_Handle_T) return Storage.Bounds.Value_List_T; -- -- The list of values in the one-dimensional Set, provided -- that the set is bounded (using Hull_Bound). Propagates -- Unbounded_Set otherwise. -- -- The length of the result is bounded by -- Storage.Bounds.Opt.Max_Listed_Values. If there are more -- values, the function propagates Unbounded_Set. -- -- Creation of new pools and fluxes: -- function New_Pool ( Cells : Cell_Set_T; Value : Set_T; Calc : Calc_Handle_T) return Pool_T; -- -- Creates a new pool, with the given cells as the domain -- tuple, and assigns it the given set value using the given -- calculator. function New_Flux ( Cells : Cell_Set_T; Value : Relation_T; Calc : Calc_Handle_T) return Flux_T; -- -- Creates a new flux, with the given cells as the domain -- and range tuples, and assigns it the given relation value -- using the given calculator. function Identity_Flux ( Domain : Cell_Set_T; Calc : Calc_Handle_T) return Flux_T; -- -- The identity-relation flux on the given cells, with -- no domain or range constraints. -- --- Identifiers specific to Bound-T algorithms -- function Into_Id (Step : Flow.Step_T ) return Identifier_T; function Into_Id (Node : Flow.Node_Index_T) return Identifier_T; -- -- The identifier for the "Into" set or relation for the step/node. -- This set or relation is the union of the incoming pools or fluxes, -- as represented by the "flow" sets or relations on the incoming edges. -- The node is given by a node index, rather than a node, so that -- this function can be applied as well to "slimmed" nodes. function Eff_Id (Step : Flow.Step_T ) return Identifier_T; function Eff_Id (Node : Flow.Node_Index_T) return Identifier_T; -- -- The identifier for the "Effect" relation for the step/node. -- This relation contains the cell-value transformations that -- represent the arithmetic effect of the instructions in the node. function From_Id (Step : Flow.Step_T ) return Identifier_T; function From_Id (Node : Flow.Node_Index_T) return Identifier_T; -- -- The identifier for the "From" set or relation for the step/node. -- This set or relation represents the data state after the node -- is executed, and is just "Into" joined with "Effect". function Flow_Id (Edge : Flow.Step_Edge_T ) return Identifier_T; function Flow_Id (Edge : Flow.Edge_Index_T) return Identifier_T; -- -- The identifier for the "Flow" set or relation for the edge. -- This set or relation represents the data flowing along the edge, -- and is the "From" set or relation of the source node, restricted -- to the range defined by the precondition of the edge. end Calculator.Formulas;
OneWingedShark/Byron
Ada
188
ads
Pragma Ada_2012; Pragma Assertion_Policy( Check ); With Lexington.Token_Vector_Pkg; -- Generate based float literals. Procedure Lexington.Aux.P16(Data : in out Token_Vector_Pkg.Vector);
AdaCore/training_material
Ada
4,058
adb
with Ada.Exceptions; with Movies; use Movies; with Char_Display_Driver; use Char_Display_Driver; with Ada.Calendar; use type Ada.Calendar.Time; with Logs; with Drawable_Chars.Latin_1; package body Movie_Servers is protected body Play_Settings_T is function FPS return Positive is (FPS_Value); procedure Set_FPS (Value : Positive) is begin --$ begin question -- TODO null; --$ end question --$ line answer FPS_Value := Value; end Set_FPS; function Charset return Sorted_Charset_T is (Charset_Value); procedure Set_Charset (Value : Sorted_Charset_T) is begin --$ begin question -- TODO null; --$ end question --$ line answer Charset_Value := Value; end Set_Charset; end Play_Settings_T; function Make_Default return Movie_Server_Task_T is --$ line answer S : constant Play_Settings_Access_T := new Play_Settings_T; begin --$ begin question -- How to return a task there? return XXX; -- TODO --$ end question --$ begin answer S.Set_FPS (4); S.Set_Charset (Drawable_Chars.Latin_1.By_Black); return T : Movie_Server_Task_T (Play_Settings => S); --$ end answer end Make_Default; procedure Display_Frame (CD : in out Char_Display; Movie : Movie_T; Frame : Frame_T) is begin --$ line question null; -- TODO --$ begin answer CD.Surf := Movies.Frame (Movie, Frame); Char_Display_Driver.Display (CD); --$ end answer end Display_Frame; task body Movie_Server_Task_T is --$ begin answer Playing : Boolean := False; Frame : Frame_T; End_Of_Times : constant Ada.Calendar.Time := Ada.Calendar.Time_Of (Ada.Calendar.Year_Number'Last, 12, 31); Next_Frame_Time : Ada.Calendar.Time := End_Of_Times; Movie : Movies.Movie_T := Null_Movie; CD : Char_Display; --$ end answer begin --$ begin question -- TODO null; --$ end question --$ begin answer loop select accept Play_Loop (Dir : String) do Movie := Movies.Load_From (Dir); declare Res : constant Resolution_T := Resolution (Movie); begin CD := (Rows => Res.Rows, Columns => Res.Columns, others => <>); end; Playing := True; Frame := Frame_T'First; Next_Frame_Time := Ada.Calendar.Clock; end Play_Loop; or accept Pause do Playing := False; end Pause; or accept Resume do Playing := True; Next_Frame_Time := Ada.Calendar.Clock; end Resume; or accept Stop do Movie := Null_Movie; end Stop; or accept Finish; exit; or delay until Next_Frame_Time; end select; if Playing and Movie /= Null_Movie then CD.Lux_Charset := Play_Settings.Charset; Display_Frame (CD, Movie, Frame); Logs.Put_Line (File_Name (Movie)); if Frame = Frames_Number (Movie) then Frame := Frame_T'First; else Frame := Frame_T'Succ (Frame); end if; Next_Frame_Time := Next_Frame_Time + 1.0 / Duration (Play_Settings.FPS); else Next_Frame_Time := End_Of_Times; end if; end loop; exception when E : others => Logs.Put (Sty => Logs.White_On_Red, S => " error "); Logs.Put_Line (" " & Ada.Exceptions.Exception_Name (E)); Logs.Put_Line (Ada.Exceptions.Exception_Message (E)); --$ end answer end Movie_Server_Task_T; end Movie_Servers;
zhmu/ananas
Ada
2,510
ads
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . E X P O N R -- -- -- -- S p e c -- -- -- -- Copyright (C) 2021-2022, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Real exponentiation (checks off) generic type Num is digits <>; function System.Exponr (Left : Num; Right : Integer) return Num;
tum-ei-rcs/StratoX
Ada
586
ads
with Ada.Real_Time; use Ada.Real_Time; package mylog with SPARK_Mode is type msgtype is (NONE, TEXT, GPS); type logmsg (typ : msgtype := NONE) is record t : Time := Time_First; case typ is when NONE => null; when TEXT => txt : String (1 .. 128) := (others => Character'Val (0)); txt_last : Integer := 0; when GPS => lat : Float := 0.0; lon : Float := 0.0; end case; end record; type msgarray is array (Positive range <>) of logmsg; -- primitive ops procedure Print (m : logmsg); end mylog;
optikos/oasis
Ada
1,564
ads
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Program.Elements.Expressions; with Program.Lexical_Elements; package Program.Elements.Indexed_Components is pragma Pure (Program.Elements.Indexed_Components); type Indexed_Component is limited interface and Program.Elements.Expressions.Expression; type Indexed_Component_Access is access all Indexed_Component'Class with Storage_Size => 0; not overriding function Prefix (Self : Indexed_Component) return not null Program.Elements.Expressions.Expression_Access is abstract; not overriding function Expressions (Self : Indexed_Component) return Program.Elements.Expressions.Expression_Vector_Access is abstract; type Indexed_Component_Text is limited interface; type Indexed_Component_Text_Access is access all Indexed_Component_Text'Class with Storage_Size => 0; not overriding function To_Indexed_Component_Text (Self : aliased in out Indexed_Component) return Indexed_Component_Text_Access is abstract; not overriding function Left_Bracket_Token (Self : Indexed_Component_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Right_Bracket_Token (Self : Indexed_Component_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; end Program.Elements.Indexed_Components;
stcarrez/ada-css
Ada
2,204
adb
----------------------------------------------------------------------- -- css-core-tests -- Unit tests for CSS core package -- Copyright (C) 2017 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with CSS.Core.Values; package body CSS.Core.Properties.Tests is package Caller is new Util.Test_Caller (Test, "CSS.Core"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test CSS.Core.Properties.Append", Test_Append'Access); end Add_Tests; -- ------------------------------ -- Test stylesheet creation. -- ------------------------------ procedure Test_Append (T : in out Test) is Sheet : Stylesheet; List : CSSProperty_List; Repo : CSS.Core.Values.Repository_Type; N : constant CSSProperty_Name := Sheet.Create_Property_Name ("border"); V : constant Value_Type := Repo.Create_Number ("23"); P : CSSProperty; begin Util.Tests.Assert_Equals (T, 0, List.Get_Length, "Get_Length returned invalid length"); List.Append (N, V); Util.Tests.Assert_Equals (T, 1, List.Get_Length, "Get_Length returned invalid length"); P := List.Get_Property ("border"); Util.Tests.Assert_Equals (T, "border", P.Name.all, "Get_Property returned invalid property"); Util.Tests.Assert_Equals (T, "23", P.Value.To_String, "Get_Property returned invalid property"); end Test_Append; end CSS.Core.Properties.Tests;
stcarrez/ada-util
Ada
1,696
ads
----------------------------------------------------------------------- -- files.tests -- Unit tests for files -- Copyright (C) 2009, 2010, 2011, 2012, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Tests; package Util.Files.Tests is procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite); type Test is new Util.Tests.Test with null record; procedure Test_Read_File (T : in out Test); procedure Test_Read_File_Missing (T : in out Test); procedure Test_Read_File_Truncate (T : in out Test); procedure Test_Write_File (T : in out Test); procedure Test_Find_File_Path (T : in out Test); procedure Test_Iterate_Path (T : in out Test); procedure Test_Compose_Path (T : in out Test); -- Test the Get_Relative_Path operation. procedure Test_Get_Relative_Path (T : in out Test); -- Test the Delete_Tree operation. procedure Test_Delete_Tree (T : in out Test); -- Test the Realpath function. procedure Test_Realpath (T : in out Test); end Util.Files.Tests;
charlie5/lace
Ada
879
ads
with openGL.Geometry; package openGL.Model.capsule.lit_colored -- -- Models a lit and colored capsule. -- is type Item is new Model.capsule.item with private; type View is access all Item'Class; --------- --- Forge -- function new_Capsule (Radius : in Real; Height : in Real; Color : in lucid_Color) return View; -------------- --- Attributes -- overriding function to_GL_Geometries (Self : access Item; Textures : access Texture.name_Map_of_texture'Class; Fonts : in Font.font_id_Map_of_font) return Geometry.views; private type Item is new Model.capsule.item with record Radius : Real; Height : Real; Color : rgba_Color; end record; end openGL.Model.capsule.lit_colored;
Salvatore-tech/Sistemas-de-Tiempo-Real
Ada
471
ads
with Ada.Real_Time; use Ada.Real_Time; package Pck_tareas is task Control_cs is pragma Priority(1); entry CS1; entry CS2; entry CS3; entry CS4; entry CS5; end control_cs; task Modulo_MD is pragma Priority(2); entry MD1; entry MD2; entry MD3; entry MD4; entry MD5; end Modulo_MD; task Seguridad is pragma Priority(3); entry S; end Seguridad; end Pck_tareas;
reznikmm/matreshka
Ada
3,635
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with XML.DOM.Attributes; package ODF.DOM.Attributes.FO.Border_Top is type ODF_FO_Border_Top is new XML.DOM.Attributes.DOM_Attribute with private; private type ODF_FO_Border_Top is new XML.DOM.Attributes.DOM_Attribute with null record; end ODF.DOM.Attributes.FO.Border_Top;
twdroeger/ada-awa
Ada
23,012
ads
----------------------------------------------------------------------- -- awa-wikis-beans -- Beans for module wikis -- Copyright (C) 2015, 2016 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Strings.Hash; with Ada.Strings.Wide_Wide_Unbounded; with Ada.Strings.Wide_Wide_Hash; with Ada.Containers.Indefinite_Hashed_Maps; with Util.Beans.Basic; with Util.Beans.Objects; with ADO; with ADO.Objects; with ASF.Helpers.Beans; with Wiki.Strings; with Wiki.Attributes; with Wiki.Plugins.Templates; with Wiki.Plugins.Conditions; with AWA.Wikis.Modules; with AWA.Wikis.Models; with AWA.Tags.Beans; with AWA.Counters.Beans; with AWA.Components.Wikis; -- == Ada Beans == -- Several bean types are provided to represent and manage the blogs and their posts. -- The blog module registers the bean constructors when it is initialized. -- To use them, one must declare a bean definition in the application XML configuration. -- -- @include-bean wikis.xml -- @include-bean wiki-page.xml -- @include-bean wiki-pages.xml -- @include-bean wiki-history.xml -- @include-bean wiki-list.xml package AWA.Wikis.Beans is use Ada.Strings.Wide_Wide_Unbounded; package Image_Info_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => Wiki.Strings.WString, Element_Type => Wikis.Models.Wiki_Image_Info, Hash => Ada.Strings.Wide_Wide_Hash, Equivalent_Keys => "=", "=" => AWA.Wikis.Models."="); package Template_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Wiki.Strings.UString, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); type Wiki_Links_Bean is new AWA.Components.Wikis.Link_Renderer_Bean and Util.Beans.Basic.List_Bean with record -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; Images : Image_Info_Maps.Map; -- The info bean used for the list iterator. Info : aliased AWA.Wikis.Models.Wiki_Image_Info; Info_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- Current index when iterating over the list. Pos : Image_Info_Maps.Cursor; end record; procedure Make_Image_Link (Renderer : in out Wiki_Links_Bean; Link : in Wiki.Strings.WString; Info : in AWA.Wikis.Models.Wiki_Image_Info; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); procedure Find_Image_Link (Renderer : in out Wiki_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the image link that must be rendered from the wiki image link. overriding procedure Make_Image_Link (Renderer : in out Wiki_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Width : in out Natural; Height : in out Natural); -- Get the page link that must be rendered from the wiki page link. overriding procedure Make_Page_Link (Renderer : in out Wiki_Links_Bean; Link : in Wiki.Strings.WString; URI : out Unbounded_Wide_Wide_String; Exists : out Boolean); -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Links_Bean; Name : in String) return Util.Beans.Objects.Object; -- Get the number of elements in the list. overriding function Get_Count (From : Wiki_Links_Bean) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out Wiki_Links_Bean; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in Wiki_Links_Bean) return Util.Beans.Objects.Object; -- The Wiki template plugin that retrieves the template content from the Wiki space. type Wiki_Template_Bean is new Wiki.Plugins.Templates.Template_Plugin and Wiki.Plugins.Plugin_Factory and Util.Beans.Basic.List_Bean with record -- The wiki space identifier. Wiki_Space_Id : ADO.Identifier; -- The list of templates that have been loaded. Templates : Template_Maps.Map; -- Condition plugin. Condition : aliased Wiki.Plugins.Conditions.Condition_Plugin; -- The info bean used for the list iterator. Info : aliased AWA.Wikis.Models.Wiki_Info; Info_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- Current index when iterating over the list. Pos : Template_Maps.Cursor; end record; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Template_Bean; Name : in String) return Util.Beans.Objects.Object; -- Get the number of elements in the list. overriding function Get_Count (From : Wiki_Template_Bean) return Natural; -- Set the current row index. Valid row indexes start at 1. overriding procedure Set_Row_Index (From : in out Wiki_Template_Bean; Index : in Natural); -- Get the element at the current row index. overriding function Get_Row (From : in Wiki_Template_Bean) return Util.Beans.Objects.Object; -- Get the template content for the plugin evaluation. overriding procedure Get_Template (Plugin : in out Wiki_Template_Bean; Params : in out Wiki.Attributes.Attribute_List; Template : out Wiki.Strings.UString); -- Find a plugin knowing its name. overriding function Find (Factory : in Wiki_Template_Bean; Name : in String) return Wiki.Plugins.Wiki_Plugin_Access; type Wiki_Space_Bean is new AWA.Wikis.Models.Wiki_Space_Bean with record Module : Modules.Wiki_Module_Access := null; -- List of tags associated with the question. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Space_Bean_Access is access all Wiki_Space_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Space_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Space_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki space. overriding procedure Save (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki space information. overriding procedure Load (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki space. procedure Delete (Bean : in out Wiki_Space_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Space_Bean bean instance. function Create_Wiki_Space_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; function Get_Wiki_Space_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Wiki_Space_Bean, Element_Access => Wiki_Space_Bean_Access); type Wiki_View_Bean is new AWA.Wikis.Models.Wiki_View_Info with record -- The wiki module instance. Module : Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Space : Wiki_Space_Bean_Access; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The read page counter associated with the wiki page. Counter : aliased AWA.Counters.Beans.Counter_Bean (Of_Type => ADO.Objects.KEY_INTEGER, Of_Class => Models.WIKI_PAGE_TABLE); Counter_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The wiki page links. Links : aliased Wiki_Links_Bean; Links_Bean : Util.Beans.Basic.Readonly_Bean_Access; -- The wiki plugins. Plugins : aliased Wiki_Template_Bean; Plugins_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_View_Bean_Access is access all Wiki_View_Bean'Class; -- Set the wiki identifier. procedure Set_Wiki_Id (Into : in out Wiki_View_Bean; Id : in ADO.Identifier); -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_View_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_View_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Get the wiki syntax for the page. function Get_Syntax (From : in Wiki_View_Bean) return Wiki.Wiki_Syntax; -- Load the information about the wiki page to display it. overriding procedure Load (Bean : in out Wiki_View_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_View_Bean bean instance. function Create_Wiki_View_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; function Get_Wiki_View_Bean is new ASF.Helpers.Beans.Get_Bean (Element_Type => Wiki_View_Bean, Element_Access => Wiki_View_Bean_Access); -- Get a select item list which contains a list of wiki formats. function Create_Format_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Page Bean -- ------------------------------ -- The <tt>Wiki_Page_Bean</tt> is used to edit a wiki page. The model type inherit from -- the <tt>Wiki_Page</tt> and the wiki page text is hold in the <tt>Content</tt> member. -- When a new content is updated, the <tt>Set_Value</tt> procedure sets it in the -- <tt>New_Content</tt> member. It is compared to the current wiki text to decide whether -- we have to create a new version or not. type Wiki_Page_Bean is new AWA.Wikis.Models.Wiki_Page_Bean with record Module : Modules.Wiki_Module_Access := null; -- The page content. Content : Models.Wiki_Content_Ref; Has_Content : Boolean := False; Format : AWA.Wikis.Models.Format_Type := AWA.Wikis.Models.FORMAT_CREOLE; New_Content : Ada.Strings.Unbounded.Unbounded_String; New_Comment : Ada.Strings.Unbounded.Unbounded_String; Wiki_Space : Wiki_Space_Bean_Access; -- List of tags associated with the wiki page. Tags : aliased AWA.Tags.Beans.Tag_List_Bean; Tags_Bean : Util.Beans.Basic.Readonly_Bean_Access; end record; type Wiki_Page_Bean_Access is access all Wiki_Page_Bean'Class; -- Returns True if the wiki page has a new text content and requires -- a new version to be created. function Has_New_Content (Bean : in Wiki_Page_Bean) return Boolean; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Create or save the wiki page. overriding procedure Save (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the wiki page. overriding procedure Load (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Setup the wiki page for the creation. overriding procedure Setup (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Delete the wiki page. overriding procedure Delete (Bean : in out Wiki_Page_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Bean bean instance. function Create_Wiki_Page_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki List Bean -- ------------------------------ -- The <b>Wiki_List_Bean</b> gives a list of visible wikis to be displayed to users. -- The list can be filtered by a given tag. The list pagination is supported. type Wiki_List_Bean is new AWA.Wikis.Models.Wiki_Page_List_Bean with record Module : Modules.Wiki_Module_Access := null; Pages : aliased AWA.Wikis.Models.Wiki_Page_Info_List_Bean; Tags : AWA.Tags.Beans.Entity_Tag_Map; Pages_Bean : AWA.Wikis.Models.Wiki_Page_Info_List_Bean_Access; -- The wiki space identifier. Wiki_Space : Wiki_Space_Bean_Access; end record; type Wiki_List_Bean_Access is access all Wiki_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (From : in out Wiki_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Load the list of pages. If a tag was set, filter the list of pages with the tag. procedure Load_List (Into : in out Wiki_List_Bean); -- Create the Post_List_Bean bean instance. function Create_Wiki_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki Version List Bean -- ------------------------------ type Wiki_Version_List_Bean is new AWA.Wikis.Models.Wiki_Version_List_Bean with record Module : Modules.Wiki_Module_Access := null; Versions : aliased AWA.Wikis.Models.Wiki_Version_Info_List_Bean; Versions_Bean : AWA.Wikis.Models.Wiki_Version_Info_List_Bean_Access; end record; type Wiki_Version_List_Bean_Access is access all Wiki_Version_List_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Version_List_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Version_List_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (Into : in out Wiki_Version_List_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Post_List_Bean bean instance. function Create_Wiki_Version_List_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki page info Bean -- ------------------------------ -- The <tt>Wiki_Page_Info_Bean</tt> is used to provide information about a wiki page. -- It analyzes the page content and extract the list of links, images, words, templates -- used in the page. type Wiki_Page_Info_Bean is new AWA.Wikis.Models.Wiki_Page_Info_Bean with record Module : Modules.Wiki_Module_Access := null; Page : Wiki_View_Bean_Access; -- List of words contained in the wiki page. Words : aliased AWA.Tags.Beans.Tag_Info_List_Bean; Words_Bean : AWA.Tags.Beans.Tag_Info_List_Bean_Access; -- List of wiki page links used in the wiki page. Links : aliased AWA.Tags.Beans.Tag_Info_List_Bean; Links_Bean : AWA.Tags.Beans.Tag_Info_List_Bean_Access; -- List of external links used in the wiki page. Ext_Links : aliased AWA.Tags.Beans.Tag_Info_List_Bean; Ext_Links_Bean : AWA.Tags.Beans.Tag_Info_List_Bean_Access; end record; type Wiki_Page_Info_Bean_Access is access all Wiki_Page_Info_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Page_Info_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Page_Info_Bean; Name : in String; Value : in Util.Beans.Objects.Object); overriding procedure Load (Into : in out Wiki_Page_Info_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Page_Info_Bean bean instance. function Create_Wiki_Page_Info_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; -- ------------------------------ -- Wiki image info Bean -- ------------------------------ -- The <tt>Wiki_Image_Info_Bean</tt> is used to provide information about a wiki image. type Wiki_Image_Info_Bean is new AWA.Wikis.Models.Wiki_Image_Bean with record Module : Modules.Wiki_Module_Access := null; Page : Wiki_View_Bean_Access; -- The folder name and image name. Folder_Name : Ada.Strings.Unbounded.Unbounded_String; Name : Ada.Strings.Unbounded.Unbounded_String; -- The wiki space identifier and wiki page identifer that uses the image. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; Page_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- Information about images. List : aliased AWA.Wikis.Models.Wiki_Image_Info_List_Bean; List_Bean : AWA.Wikis.Models.Wiki_Image_Info_List_Bean_Access; end record; type Wiki_Image_Info_Bean_Access is access all Wiki_Image_Info_Bean'Class; -- Get the value identified by the name. overriding function Get_Value (From : in Wiki_Image_Info_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Image_Info_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the information about the image. overriding procedure Load (Into : in out Wiki_Image_Info_Bean; Outcome : in out Ada.Strings.Unbounded.Unbounded_String); -- Create the Wiki_Image_Info_BEan bean instance. function Create_Wiki_Image_Info_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; type Init_Flag is (INIT_WIKI_LIST); type Init_Map is array (Init_Flag) of Boolean; -- ------------------------------ -- Admin List Bean -- ------------------------------ -- The <b>Wiki_Admin_Bean</b> is used for the administration of a wiki. It gives the -- list of wikis and pages that are created, published or not. type Wiki_Admin_Bean is new Util.Beans.Basic.Bean with record Module : AWA.Wikis.Modules.Wiki_Module_Access := null; -- The wiki space identifier. Wiki_Id : ADO.Identifier := ADO.NO_IDENTIFIER; -- List of blogs. Wiki_List : aliased AWA.Wikis.Models.Wiki_Info_List_Bean; Wiki_List_Bean : AWA.Wikis.Models.Wiki_Info_List_Bean_Access; -- Initialization flags. Init_Flags : aliased Init_Map := (others => False); Flags : access Init_Map; end record; type Wiki_Admin_Bean_Access is access all Wiki_Admin_Bean; -- Get the wiki space identifier. function Get_Wiki_Id (List : in Wiki_Admin_Bean) return ADO.Identifier; overriding function Get_Value (List : in Wiki_Admin_Bean; Name : in String) return Util.Beans.Objects.Object; -- Set the value identified by the name. overriding procedure Set_Value (From : in out Wiki_Admin_Bean; Name : in String; Value : in Util.Beans.Objects.Object); -- Load the list of wikis. procedure Load_Wikis (List : in Wiki_Admin_Bean); -- Create the Wiki_Admin_Bean bean instance. function Create_Wiki_Admin_Bean (Module : in AWA.Wikis.Modules.Wiki_Module_Access) return Util.Beans.Basic.Readonly_Bean_Access; end AWA.Wikis.Beans;
reznikmm/slimp
Ada
4,959
adb
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with System.Storage_Elements; with Ada.Storage_IO; package body Slim.Messages is ----------------- -- Read_Fields -- ----------------- procedure Read_Fields (Self : in out Base_Message'Class; List : Field_Description_Array; Data : League.Stream_Element_Vectors.Stream_Element_Vector) is use type Ada.Streams.Stream_Element_Offset; generic type Element is private; procedure Read (Result : out Element); Input : Ada.Streams.Stream_Element_Offset := 1; ---------- -- Read -- ---------- procedure Read (Result : out Element) is package IO is new Ada.Storage_IO (Element); Buffer : IO.Buffer_Type; begin for J in reverse Buffer'Range loop Buffer (J) := System.Storage_Elements.Storage_Element (Data.Element (Input)); Input := Input + 1; end loop; IO.Read (Buffer, Result); end Read; procedure Read_8 is new Read (Interfaces.Unsigned_8); procedure Read_16 is new Read (Interfaces.Unsigned_16); procedure Read_32 is new Read (Interfaces.Unsigned_32); procedure Read_64 is new Read (Interfaces.Unsigned_64); Kind : Field_Kinds; Fields : Field_Description_Array := List; Index : Positive := Fields'First; Counts : array (Field_Kinds) of Natural := (others => 0); begin while Index <= Fields'Last loop Kind := Fields (Index).Kind; Counts (Kind) := Counts (Kind) + 1; case Kind is when Uint_8_Field => Read_8 (Self.Data_8 (Counts (Kind))); when Uint_16_Field => Read_16 (Self.Data_16 (Counts (Kind))); when Uint_32_Field => Read_32 (Self.Data_32 (Counts (Kind))); when Uint_64_Field => Read_64 (Self.Data_64 (Counts (Kind))); when others => Self.Read_Custom_Field (Index => Counts (Kind), Input => Input, Data => Data); end case; if Fields (Index).Count = 1 then Index := Index + 1; else Fields (Index).Count := Fields (Index).Count - 1; end if; end loop; end Read_Fields; ----------- -- Slice -- ----------- procedure Slice (Result : out Ada.Streams.Stream_Element_Array; From : Ada.Streams.Stream_Element_Offset) is use type Ada.Streams.Stream_Element_Offset; begin for J in Result'Range loop Result (J) := Data.Element (From + J - Result'First); end loop; end Slice; ------------------ -- Write_Fields -- ------------------ procedure Write_Fields (Self : Base_Message'Class; List : Field_Description_Array; Data : in out League.Stream_Element_Vectors.Stream_Element_Vector) is generic type Element is private; procedure Write (Result : Element); ----------- -- Write -- ----------- procedure Write (Result : Element) is package IO is new Ada.Storage_IO (Element); Buffer : IO.Buffer_Type; begin IO.Write (Buffer, Result); -- Use network byte order, so use 'reverse' for J in reverse Buffer'Range loop Data.Append (Ada.Streams.Stream_Element (Buffer (J))); end loop; end Write; procedure Write_8 is new Write (Interfaces.Unsigned_8); procedure Write_16 is new Write (Interfaces.Unsigned_16); procedure Write_32 is new Write (Interfaces.Unsigned_32); procedure Write_64 is new Write (Interfaces.Unsigned_64); Kind : Field_Kinds; Fields : Field_Description_Array := List; Index : Positive := Fields'First; Counts : array (Field_Kinds) of Natural := (others => 0); begin while Index <= Fields'Last loop Kind := Fields (Index).Kind; Counts (Kind) := Counts (Kind) + 1; case Kind is when Uint_8_Field => Write_8 (Self.Data_8 (Counts (Kind))); when Uint_16_Field => Write_16 (Self.Data_16 (Counts (Kind))); when Uint_32_Field => Write_32 (Self.Data_32 (Counts (Kind))); when Uint_64_Field => Write_64 (Self.Data_64 (Counts (Kind))); when others => Self.Write_Custom_Field (Index => Counts (Kind), Data => Data); end case; if Fields (Index).Count = 1 then Index := Index + 1; else Fields (Index).Count := Fields (Index).Count - 1; end if; end loop; end Write_Fields; end Slim.Messages;
MinimSecure/unum-sdk
Ada
1,008
adb
-- Copyright 2012-2016 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. With Classes; use Classes; procedure P is SP_Access : Shape_Access := new Circle'(My_Circle); DP_Access : Drawable_Access := new Circle'(My_Circle); SP_Array : Shape_Array := (others => S_Access); DP_Array : Drawable_Array := (others => D_Access); begin null; -- BREAK end P;
zhmu/ananas
Ada
287
adb
-- { dg-do compile } -- { dg-options "-O" } package body Opt78 is procedure Proc (P : UC; Msg : String) is Default : UC := (1, "!"); begin if P = Default then raise Program_Error; else raise Constraint_Error; end if; end; end Opt78;
riccardo-bernardini/eugen
Ada
2,850
adb
with Ada.Strings.Unbounded; with Tokenize; package body EU_Projects.Identifiers.Full is --------- -- ">" -- --------- function "<" (X, Y : Full_ID) return Boolean is use ID_Vectors; Tx : ID_Vectors.Vector := X.Segments; Ty : ID_Vectors.Vector := Y.Segments; begin while not (Tx.Is_Empty or Ty.Is_Empty) loop if Tx.First_Element > Ty.First_Element then return False; elsif Tx.First_Element < Ty.First_Element then return True; else Tx.Delete_First; Ty.Delete_First; end if; end loop; -- -- If Ty is not empty it means that Tx x, therefore X < Y. -- If Ty is empty, it can be -- -- + Also Tx is empty => X = Y -- + Tx is not empty => X > Y -- -- Therefore, X < Y iff Ty is empty -- return not Ty.Is_Empty; end "<"; ----------- -- Parse -- ----------- function Parse (X : String) return Full_ID is use Ada.Strings.Unbounded; Segments : constant Tokenize.Token_List := Tokenize.Split (To_Be_Splitted => X, Separator => '.'); Result : Full_ID; begin for Seg of Segments loop Result.Segments.Append (To_ID (To_String (Seg))); end loop; return Result; end Parse; ----------- -- Image -- ----------- function Image (X : Full_ID) return String is use Ada.Strings.Unbounded; Result : Unbounded_String := Null_Unbounded_String; begin for Segment of X.Segments loop if Result /= Null_Unbounded_String then Result := Result & "."; end if; Result := Result & Image(Segment); end loop; return To_String (Result); end Image; ------------ -- Header -- ------------ function Header (Item : Full_ID) return Full_ID is Result : Full_ID := Item; begin Result.Segments.Delete_Last; return Result; end Header; ------------- -- Trailer -- ------------- function Trailer (Item : Full_ID) return Full_ID is Result : Full_ID := Item; begin Result.Segments.Delete_First; return Result; end Trailer; ------------- -- Resolve -- ------------- function Resolve (Item : Full_ID; Prefix : Full_ID; Resolver : Resolver_Type'Class) return Full_ID is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Resolve unimplemented"); raise Program_Error with "Unimplemented function Resolve"; return Resolve (Item => Item, Prefix => Prefix, Resolver => Resolver); end Resolve; end EU_Projects.Identifiers.Full;
AdaCore/libadalang
Ada
360
adb
procedure Test is task type T is entry E (I : Integer); end T; task body T is B : Boolean; begin select accept E (I : Integer) do B := I = 1; pragma Test_Statement; B := E.I = 1; pragma Test_Statement; end E; end select; end T; begin null; end Test;
wooky/aoc
Ada
4,571
adb
with Ada.Containers; use Ada.Containers; with Ada.Containers.Indefinite_Hashed_Maps; with Ada.Containers.Vectors; with Ada.Strings; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings.Hash; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with AOC; use AOC; function Day07 (F : Aoc_File) return Solution is type Content_Type is (File, Directory); type Content (Kind : Content_Type := File) is record case Kind is when File => Size : Natural; when Directory => Full_Path: Unbounded_String; end case; end record; package Directory_Contents_Vector is new Ada.Containers.Vectors ( Index_Type => Natural, Element_Type => Content ); subtype Directory_Contents is Directory_Contents_Vector.Vector; type Directory_Information is record Size : Natural := 0; Contents : Directory_Contents; end record; -- To satisfy Directory_Listing_Map."=" function "=" (X, Y : Directory_Contents) return Boolean is begin return False; end "="; package Directory_Listing_Map is new Ada.Containers.Indefinite_Hashed_Maps ( Key_Type => String, Element_Type => Directory_Information, Hash => Ada.Strings.Hash, Equivalent_Keys => "=" ); subtype Directory_Listing is Directory_Listing_Map.Map; function Change_Directory (Current_Directory : Unbounded_String ; Where_To : String) return String is begin if Where_To = "/" then return "/"; elsif Where_To = ".." then declare Idx : Positive := Index (Current_Directory, "/", Length (Current_Directory) - 1, Ada.Strings.Backward); begin return Slice (Current_Directory, 1, Idx); end; else return To_String (Current_Directory & Where_To & "/"); end if; end Change_Directory; procedure Fill_Directory_Size ( Directory_Listings : in out Directory_Listing; Current_Directory : String ) is Total_Size : Natural := 0; begin for Contents of Directory_Listings (Current_Directory).Contents loop case Contents.Kind is when File => Total_Size := Total_Size + Contents.Size; when Directory => Fill_Directory_Size (Directory_Listings, To_String (Contents.Full_Path)); Total_Size := Total_Size + Directory_Listings (To_String (Contents.Full_Path)).Size; end case; end loop; Directory_Listings.Reference (Current_Directory).Size := Total_Size; end Fill_Directory_Size; Directory_Listings : Directory_Listing; Current_Directory : Unbounded_String; begin declare begin while not End_Of_File (F) loop declare Line : String := Get_Line (F); Space1 : Positive := Index (Line, " "); Token1 : String := Line (Line'First .. Space1 - 1); Token2 : String := Line (Space1 + 1 .. Line'Last); Space2 : Natural := Index (Line, " ", Space1 + 1); Current_Directory_String : String := To_String (Current_Directory); begin if Token1 = "$" then if Space2 /= 0 then Current_Directory := To_Unbounded_String (Change_Directory (Current_Directory, Line (Space2 + 1 .. Line'Last))); end if; else if not Directory_Listings.Contains (Current_Directory_String) then Directory_Listings.Insert (Current_Directory_String, ( Size => 0, Contents => Directory_Contents_Vector.Empty_Vector )); end if; if Token1 = "dir" then Directory_Listings (Current_Directory_String).Contents.Append (( Kind => Directory, Full_Path => To_Unbounded_String (Change_Directory (Current_Directory, Token2)) )); else Directory_Listings (Current_Directory_String).Contents.Append (( Kind => File, Size => Natural'Value (Token1) )); end if; end if; end; end loop; end; Fill_Directory_Size (Directory_Listings, "/"); declare Space_Required : Positive := 30000000 - 70000000 + Directory_Listings ("/").Size; Filtered_Size : Natural := 0; Smallest_Deleted_Size : Positive := Positive'Last; begin for Info of Directory_Listings loop if Info.Size <= 100000 then Filtered_Size := Filtered_Size + Info.Size; end if; if Info.Size in Space_Required .. Smallest_Deleted_Size - 1 then Smallest_Deleted_Size := Info.Size; end if; end loop; return New_Solution (S1 => Filtered_Size'Image, S2 => Smallest_Deleted_Size'Image); end; end Day07;
zhmu/ananas
Ada
21,934
ads
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- G N A T . D Y N A M I C _ H T A B L E S -- -- -- -- S p e c -- -- -- -- Copyright (C) 1995-2022, AdaCore -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Hash table searching routines -- This package contains two separate packages. The Simple_HTable package -- provides a very simple abstraction that associates one element to one key -- value and takes care of all allocations automatically using the heap. The -- Static_HTable package provides a more complex interface that allows full -- control over allocation. -- This package provides a facility similar to that of GNAT.HTable, except -- that this package declares types that can be used to define dynamic -- instances of hash tables, while instantiations in GNAT.HTable creates a -- single instance of the hash table. -- Note that this interface should remain synchronized with those in -- GNAT.HTable to keep as much coherency as possible between these two -- related units. -- Note: this unit is used during bootstrap, see ADA_GENERATED_FILES in -- gcc-interface/Make-lang.in for details on the constraints. package GNAT.Dynamic_HTables is function Hash_Two_Keys (Left : Bucket_Range_Type; Right : Bucket_Range_Type) return Bucket_Range_Type; pragma Inline (Hash_Two_Keys); -- Obtain the hash value of keys Left and Right ------------------- -- Static_HTable -- ------------------- -- A low-level Hash-Table abstraction, not as easy to instantiate as -- Simple_HTable. This mirrors the interface of GNAT.HTable.Static_HTable, -- but does require dynamic allocation (since we allow multiple instances -- of the table). The model is that each Element contains its own Key that -- can be retrieved by Get_Key. Furthermore, Element provides a link that -- can be used by the HTable for linking elements with same hash codes: -- Element -- +-------------------+ -- | Key | -- +-------------------+ -- : other data : -- +-------------------+ -- | Next Elmt | -- +-------------------+ generic type Header_Num is range <>; -- An integer type indicating the number and range of hash headers type Element (<>) is limited private; -- The type of element to be stored type Elmt_Ptr is private; -- The type used to reference an element (will usually be an access -- type, but could be some other form of type such as an integer type). Null_Ptr : Elmt_Ptr; -- The null value of the Elmt_Ptr type with function Next (E : Elmt_Ptr) return Elmt_Ptr; with procedure Set_Next (E : Elmt_Ptr; Next : Elmt_Ptr); -- The type must provide an internal link for the sake of the -- staticness of the HTable. type Key is limited private; with function Get_Key (E : Elmt_Ptr) return Key; with function Hash (F : Key) return Header_Num; with function Equal (F1 : Key; F2 : Key) return Boolean; package Static_HTable is type Instance is private; Nil : constant Instance; procedure Reset (T : in out Instance); -- Resets the hash table by releasing all memory associated with it. The -- hash table can safely be reused after this call. For the most common -- case where Elmt_Ptr is an access type, and Null_Ptr is null, this is -- only needed if the same table is reused in a new context. If Elmt_Ptr -- is other than an access type, or Null_Ptr is other than null, then -- Reset must be called before the first use of the hash table. procedure Set (T : in out Instance; E : Elmt_Ptr); -- Insert the element pointer in the HTable function Get (T : Instance; K : Key) return Elmt_Ptr; -- Returns the latest inserted element pointer with the given Key or -- null if none. procedure Remove (T : Instance; K : Key); -- Removes the latest inserted element pointer associated with the given -- key if any, does nothing if none. function Get_First (T : Instance) return Elmt_Ptr; -- Returns Null_Ptr if the Htable is empty, otherwise returns one -- unspecified element. There is no guarantee that 2 calls to this -- function will return the same element. function Get_Next (T : Instance) return Elmt_Ptr; -- Returns an unspecified element that has not been returned by the same -- function since the last call to Get_First or Null_Ptr if there is no -- such element or Get_First has never been called. If there is no call -- to 'Set' in between Get_Next calls, all the elements of the Htable -- will be traversed. private type Table_Type is array (Header_Num) of Elmt_Ptr; type Instance_Data is record Table : Table_Type; Iterator_Index : Header_Num; Iterator_Ptr : Elmt_Ptr; Iterator_Started : Boolean := False; end record; type Instance is access all Instance_Data; Nil : constant Instance := null; end Static_HTable; ------------------- -- Simple_HTable -- ------------------- -- A simple hash table abstraction, easy to instantiate, easy to use. -- The table associates one element to one key with the procedure Set. -- Get retrieves the Element stored for a given Key. The efficiency of -- retrieval is function of the size of the Table parameterized by -- Header_Num and the hashing function Hash. generic type Header_Num is range <>; -- An integer type indicating the number and range of hash headers type Element is private; -- The type of element to be stored No_Element : Element; -- The object that is returned by Get when no element has been set for -- a given key type Key is private; with function Hash (F : Key) return Header_Num; with function Equal (F1 : Key; F2 : Key) return Boolean; package Simple_HTable is type Instance is private; Nil : constant Instance; type Key_Option (Present : Boolean := False) is record case Present is when True => K : Key; when False => null; end case; end record; procedure Set (T : in out Instance; K : Key; E : Element); -- Associates an element with a given key. Overrides any previously -- associated element. procedure Reset (T : in out Instance); -- Releases all memory associated with the table. The table can be -- reused after this call (it is automatically allocated on the first -- access to the table). function Get (T : Instance; K : Key) return Element; -- Returns the Element associated with a key or No_Element if the given -- key has not associated element procedure Remove (T : Instance; K : Key); -- Removes the latest inserted element pointer associated with the given -- key if any, does nothing if none. function Get_First (T : Instance) return Element; -- Returns No_Element if the Htable is empty, otherwise returns one -- unspecified element. There is no guarantee that two calls to this -- function will return the same element, if the Htable has been -- modified between the two calls. function Get_First_Key (T : Instance) return Key_Option; -- Returns an option type giving an unspecified key. If the Htable -- is empty, the discriminant will have field Present set to False, -- otherwise its Present field is set to True and the field K contains -- the key. There is no guarantee that two calls to this function will -- return the same key, if the Htable has been modified between the two -- calls. function Get_Next (T : Instance) return Element; -- Returns an unspecified element that has not been returned by the -- same function since the last call to Get_First or No_Element if -- there is no such element. If there is no call to 'Set' in between -- Get_Next calls, all the elements of the Htable will be traversed. -- To guarantee that all the elements of the Htable will be traversed, -- no modification of the Htable (Set, Reset, Remove) should occur -- between a call to Get_First and subsequent consecutive calls to -- Get_Next, until one of these calls returns No_Element. function Get_Next_Key (T : Instance) return Key_Option; -- Same as Get_Next except that this returns an option type having field -- Present set either to False if there no key never returned before by -- either Get_First_Key or this very same function, or to True if there -- is one, with the field K containing the key specified as before. The -- same restrictions apply as Get_Next. private type Element_Wrapper; type Elmt_Ptr is access all Element_Wrapper; type Element_Wrapper is record K : Key; E : Element; Next : Elmt_Ptr; end record; procedure Set_Next (E : Elmt_Ptr; Next : Elmt_Ptr); function Next (E : Elmt_Ptr) return Elmt_Ptr; function Get_Key (E : Elmt_Ptr) return Key; package Tab is new Static_HTable (Header_Num => Header_Num, Element => Element_Wrapper, Elmt_Ptr => Elmt_Ptr, Null_Ptr => null, Set_Next => Set_Next, Next => Next, Key => Key, Get_Key => Get_Key, Hash => Hash, Equal => Equal); type Instance is new Tab.Instance; Nil : constant Instance := Instance (Tab.Nil); end Simple_HTable; ------------------------- -- Dynamic_Hash_Tables -- ------------------------- -- The following package offers a hash table abstraction with the following -- characteristics: -- -- * Dynamic resizing based on load factor -- * Creation of multiple instances, of different sizes -- * Iterable keys -- -- This type of hash table is best used in scenarios where the size of the -- key set is not known. The dynamic resizing aspect allows for performance -- to remain within reasonable bounds as the size of the key set grows. -- -- The following use pattern must be employed when operating this table: -- -- Table : Dynamic_Hash_Table := Create (<some size>); -- -- <various operations> -- -- Destroy (Table); -- -- The destruction of the table reclaims all storage occupied by it. -- The following type denotes the multiplicative factor used in expansion -- and compression of the hash table. subtype Factor_Type is Bucket_Range_Type range 2 .. 100; -- The following type denotes the threshold range used in expansion and -- compression of the hash table. subtype Threshold_Type is Long_Float range 0.0 .. Long_Float'Last; generic type Key_Type is private; type Value_Type is private; -- The types of the key-value pairs stored in the hash table No_Value : Value_Type; -- An indicator for a non-existent value Expansion_Threshold : Threshold_Type; Expansion_Factor : Factor_Type; -- Once the load factor goes over Expansion_Threshold, the size of the -- buckets is increased using the formula -- -- New_Size = Old_Size * Expansion_Factor -- -- An Expansion_Threshold of 1.5 and Expansion_Factor of 2 indicate that -- the size of the buckets will be doubled once the load factor exceeds -- 1.5. Compression_Threshold : Threshold_Type; Compression_Factor : Factor_Type; -- Once the load factor drops below Compression_Threshold, the size of -- the buckets is decreased using the formula -- -- New_Size = Old_Size / Compression_Factor -- -- A Compression_Threshold of 0.5 and Compression_Factor of 2 indicate -- that the size of the buckets will be halved once the load factor -- drops below 0.5. with function "=" (Left : Key_Type; Right : Key_Type) return Boolean; with procedure Destroy_Value (Val : in out Value_Type); -- Value destructor with function Hash (Key : Key_Type) return Bucket_Range_Type; -- Map an arbitrary key into the range of buckets package Dynamic_Hash_Tables is ---------------------- -- Table operations -- ---------------------- -- The following type denotes a hash table handle. Each instance must be -- created using routine Create. type Dynamic_Hash_Table is private; Nil : constant Dynamic_Hash_Table; function Contains (T : Dynamic_Hash_Table; Key : Key_Type) return Boolean; -- Determine whether key Key exists in hash table T function Create (Initial_Size : Positive) return Dynamic_Hash_Table; -- Create a new table with bucket capacity Initial_Size. This routine -- must be called at the start of a hash table's lifetime. procedure Delete (T : Dynamic_Hash_Table; Key : Key_Type); -- Delete the value which corresponds to key Key from hash table T. The -- routine has no effect if the value is not present in the hash table. -- This action will raise Iterated if the hash table has outstanding -- iterators. If the load factor drops below Compression_Threshold, the -- size of the buckets is decreased by Copression_Factor. procedure Destroy (T : in out Dynamic_Hash_Table); -- Destroy the contents of hash table T, rendering it unusable. This -- routine must be called at the end of a hash table's lifetime. This -- action will raise Iterated if the hash table has outstanding -- iterators. function Get (T : Dynamic_Hash_Table; Key : Key_Type) return Value_Type; -- Obtain the value which corresponds to key Key from hash table T. If -- the value does not exist, return No_Value. function Is_Empty (T : Dynamic_Hash_Table) return Boolean; -- Determine whether hash table T is empty function Present (T : Dynamic_Hash_Table) return Boolean; -- Determine whether hash table T exists procedure Put (T : Dynamic_Hash_Table; Key : Key_Type; Value : Value_Type); -- Associate value Value with key Key in hash table T. If the table -- already contains a mapping of the same key to a previous value, the -- previous value is overwritten. This action will raise Iterated if -- the hash table has outstanding iterators. If the load factor goes -- over Expansion_Threshold, the size of the buckets is increased by -- Expansion_Factor. procedure Reset (T : Dynamic_Hash_Table); -- Destroy the contents of hash table T, and reset it to its initial -- created state. This action will raise Iterated if the hash table -- has outstanding iterators. function Size (T : Dynamic_Hash_Table) return Natural; -- Obtain the number of key-value pairs in hash table T ------------------------- -- Iterator operations -- ------------------------- -- The following type represents a key iterator. An iterator locks -- all mutation operations, and unlocks them once it is exhausted. -- The iterator must be used with the following pattern: -- -- Iter := Iterate (My_Table); -- while Has_Next (Iter) loop -- Key := Next (Iter); -- . . . -- end loop; -- -- It is possible to advance the iterator by using Next only, however -- this risks raising Iterator_Exhausted. type Iterator is private; function Has_Next (Iter : Iterator) return Boolean; -- Determine whether iterator Iter has more keys to examine. If the -- iterator has been exhausted, restore all mutation functionality of -- the associated hash table. function Iterate (T : Dynamic_Hash_Table) return Iterator; -- Obtain an iterator over the keys of hash table T. This action locks -- all mutation functionality of the associated hash table. procedure Next (Iter : in out Iterator; Key : out Key_Type); -- Return the current key referenced by iterator Iter and advance to -- the next available key. If the iterator has been exhausted and -- further attempts are made to advance it, this routine restores -- mutation functionality of the associated hash table, and then -- raises Iterator_Exhausted. private -- The following type represents a doubly linked list node used to -- store a key-value pair. There are several reasons to use a doubly -- linked list: -- -- * Most read and write operations utilize the same primitve -- routines to locate, create, and delete a node, allowing for -- greater degree of code sharing. -- -- * Special cases are eliminated by maintaining a circular node -- list with a dummy head (see type Bucket_Table). -- -- A node is said to be "valid" if it is non-null, and does not refer to -- the dummy head of some bucket. type Node; type Node_Ptr is access all Node; type Node is record Key : Key_Type; Value : Value_Type := No_Value; -- Key-value pair stored in a bucket Prev : Node_Ptr := null; Next : Node_Ptr := null; end record; -- The following type represents a bucket table. Each bucket contains a -- circular doubly linked list of nodes with a dummy head. Initially, -- the head does not refer to itself. This is intentional because it -- improves the performance of creation, compression, and expansion by -- avoiding a separate pass to link a head to itself. Several routines -- ensure that the head is properly formed. type Bucket_Table is array (Bucket_Range_Type range <>) of aliased Node; type Bucket_Table_Ptr is access Bucket_Table; -- The following type represents a hash table type Dynamic_Hash_Table_Attributes is record Buckets : Bucket_Table_Ptr := null; -- Reference to the compressing / expanding buckets Initial_Size : Bucket_Range_Type := 0; -- The initial size of the buckets as specified at creation time Iterators : Natural := 0; -- Number of outstanding iterators Pairs : Natural := 0; -- Number of key-value pairs in the buckets end record; type Dynamic_Hash_Table is access Dynamic_Hash_Table_Attributes; Nil : constant Dynamic_Hash_Table := null; -- The following type represents a key iterator type Iterator is record Curr_Idx : Bucket_Range_Type := 0; -- Index of the current bucket being examined. This index is always -- kept within the range of the buckets. Curr_Nod : Node_Ptr := null; -- Reference to the current node being examined within the current -- bucket. The invariant of the iterator requires that this field -- always point to a valid node. A value of null indicates that the -- iterator is exhausted. Table : Dynamic_Hash_Table := null; -- Reference to the associated hash table end record; end Dynamic_Hash_Tables; end GNAT.Dynamic_HTables;
reznikmm/matreshka
Ada
4,292
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with AMF.CMOF.Classes; with AMF.CMOF.Properties; with AMF.Extents; with AMF.Internals.Elements; with League.Holders; package AMF.Internals.Utp_Elements is type Utp_Element_Proxy is abstract limited new AMF.Internals.Elements.Element_Base with null record; overriding function Get (Self : not null access constant Utp_Element_Proxy; Property : not null AMF.CMOF.Properties.CMOF_Property_Access) return League.Holders.Holder; overriding function Get_Meta_Class (Self : not null access constant Utp_Element_Proxy) return AMF.CMOF.Classes.CMOF_Class_Access; overriding procedure Set (Self : not null access Utp_Element_Proxy; Property : not null AMF.CMOF.Properties.CMOF_Property_Access; Value : League.Holders.Holder); overriding function Extent (Self : not null access constant Utp_Element_Proxy) return AMF.Extents.Extent_Access; end AMF.Internals.Utp_Elements;
johnperry-math/hac
Ada
21,602
adb
with Ada.Numerics.Float_Random, Ada.Numerics.Generic_Elementary_Functions, Ada.Strings.Fixed; package body HAC_Pack is use Ada.Characters.Handling, VStr_Pkg; package REF is new Ada.Numerics.Generic_Elementary_Functions (Real); function "**" (F1, F2 : Real) return Real is begin return REF."**" (F1, F2); end "**"; function Sqrt (I : Integer) return Real is begin return REF.Sqrt (Real (I)); end Sqrt; function Sqrt (F : Real) return Real is begin return REF.Sqrt (F); end Sqrt; function Chr (I : Integer) return Character is begin return Character'Val (I); end Chr; function Ord (C : Character) return Integer is begin return Character'Pos (C); end Ord; function Succ (C : Character) return Character is begin return Character'Succ (C); end Succ; function Pred (C : Character) return Character is begin return Character'Pred (C); end Pred; function Round (F : Real) return Integer is begin return Integer (F); end Round; function Trunc (F : Real) return Integer is begin return Integer (Real'Floor (F)); end Trunc; function Sin (F : Real) return Real is begin return REF.Sin (F); end Sin; function Cos (F : Real) return Real is begin return REF.Cos (F); end Cos; function Arctan (F : Real) return Real is begin return REF.Arctan (F); end Arctan; function Log (F : Real) return Real is begin return REF.Log (F); end Log; function Exp (F : Real) return Real is begin return REF.Exp (F); end Exp; function Rand (I : Integer) return Integer is begin return Trunc (Rnd * Real (I + 1)); end Rand; gen : Ada.Numerics.Float_Random.Generator; function Rnd return Real is begin return Real (Ada.Numerics.Float_Random.Random (gen)); end Rnd; function HAC_Image (I : Integer) return String is Im : constant String := Integer'Image (I); begin if I < 0 then return Im; else return Im (Im'First + 1 .. Im'Last); end if; end HAC_Image; function HAC_Image (T : Ada.Calendar.Time) return String is use Ada; -- Time_display returns date & time, current or given. -- E.g.: "2013/08/01 05:49:51" -- Useful for a log file or a display of a lengthy operation. -- This is Ada 83 compatible. Format accepted by SQL queries. -- -- 32- or 64-bit: DEC/Compaq/HP Ada (83), GNAT (95/2005), ObjectAda (95) -- 16-bit: Meridian (83) -> Long_Integer is 32-bit -- 16-bit: Janus 2.x (83): KO: no Long_Integer -- -- Test program in following comment: -- -- with Text_IO,Time_display;procedure Test is begin Text_IO.Put(Time_display);end; -- function Time_display ( T : Calendar.Time := Calendar.Clock; Seconds : Boolean := True; Intra_day : Boolean := True ) return String is subtype Sec_int is Long_Integer; -- must contain 86_400 s : constant Sec_int := Sec_int (Calendar.Seconds (T)); m : constant Sec_int := s / 60; -- + 100: trick for obtaining 0x sY : constant String := Integer'Image (Year (T)); sM : constant String := Integer'Image (Month (T) + 100); sD : constant String := Integer'Image (Day (T) + 100); shr : constant String := Sec_int'Image (m / 60 + 100); smn : constant String := Sec_int'Image (m mod 60 + 100); ssc : constant String := Sec_int'Image (s mod 60 + 100); -- function Optional_seconds return String is begin if Seconds then return ':' & ssc (ssc'Last - 1 .. ssc'Last); else return ""; end if; end Optional_seconds; -- function Optional_intra_day return String is begin if Intra_day then return " " & shr (shr'Last - 1 .. shr'Last) & ':' & smn (smn'Last - 1 .. smn'Last) & Optional_seconds; else return ""; end if; end Optional_intra_day; begin return sY (sY'Last - 3 .. sY'Last) & '/' & -- not Year 10'000 compliant. sM (sM'Last - 1 .. sM'Last) & '/' & sD (sD'Last - 1 .. sD'Last) & Optional_intra_day; end Time_display; begin return Time_display (T); end HAC_Image; function To_VString (C : Character) return VString is begin return To_VString ((1 => C)); end To_VString; function Slice (Source : VString; From : Positive; To : Natural) return VString is begin return +VStr_Pkg.Slice (Source, From, To); end Slice; function "&" (I : Integer; V : VString) return VString is begin return HAC_Image (I) & V; end "&"; function "&" (V : VString; I : Integer) return VString is begin return V & HAC_Image (I); end "&"; function "&" (R : Real; V : VString) return VString is begin return HAC_Image (R) & V; end "&"; function "&" (V : VString; R : Real) return VString is begin return V & HAC_Image (R); end "&"; function To_Lower (Item : VString) return VString is begin return +To_Lower (To_String (Item)); end To_Lower; function To_Upper (Item : VString) return VString is begin return +To_Upper (To_String (Item)); end To_Upper; function Head (Source : VString; Count : Natural) return VString is begin return VStr_Pkg.Head (Source, Count); -- We use the default padding: ' '. end Head; function Tail (Source : VString; Count : Natural) return VString is begin return VStr_Pkg.Tail (Source, Count); -- We use the default padding: ' '. end Tail; function Starts_With (Item : VString; Pattern : String) return Boolean is begin return Pattern'Length <= Length (Item) and then To_String (VStr_Pkg.Head (Item, Pattern'Length)) = Pattern; end Starts_With; function Starts_With (Item : VString; Pattern : VString) return Boolean is begin return Length (Pattern) <= Length (Item) and then VStr_Pkg.Head (Item, Length (Pattern)) = Pattern; end Starts_With; function Ends_With (Item : VString; Pattern : String) return Boolean is begin return Pattern'Length <= Length (Item) and then To_String (VStr_Pkg.Tail (Item, Pattern'Length)) = Pattern; end Ends_With; function Ends_With (Item : VString; Pattern : VString) return Boolean is begin return Length (Pattern) <= Length (Item) and then VStr_Pkg.Tail (Item, Length (Pattern)) = Pattern; end Ends_With; function Index (Source : VString; Pattern : String) return Natural is begin return VStr_Pkg.Index (Source, Pattern); end Index; function Index (Source : VString; Pattern : VString) return Natural is begin return VStr_Pkg.Index (Source, To_String (Pattern)); end Index; function "*" (Num : Natural; Pattern : String) return VString is begin return +Ada.Strings.Fixed."*" (Num, Pattern); end "*"; function Trim_Left (Source : VString) return VString is begin return Trim (Source, Ada.Strings.Left); end Trim_Left; function Trim_Right (Source : VString) return VString is begin return Trim (Source, Ada.Strings.Right); end Trim_Right; function Trim_Both (Source : VString) return VString is begin return Trim (Source, Ada.Strings.Both); end Trim_Both; function Image (I : Integer) return VString is function HAC_Image_for_Integer is new HAC_Pack.HAC_Generic_Image (Abstract_Integer => Integer); begin return +HAC_Image_for_Integer (I); end Image; function Image (F : Real) return VString is begin return +HAC_Image (F); end Image; function Image_Attribute (F : Real) return VString is begin return +Real'Image (F); end Image_Attribute; function Image (T : Ada.Calendar.Time) return VString is begin return +HAC_Image (T); end Image; function Image (D : Duration) return VString is begin return +Duration'Image (D); end Image; function Integer_Value (V : VString) return Integer is begin return Integer'Value (To_String (V)); end Integer_Value; function Float_Value (V : VString) return Real is begin return Real'Value (To_String (V)); end Float_Value; procedure Open (File : in out File_Type; Name : String) is use Ada.Text_IO; begin Open (File, In_File, Name); end Open; procedure Open (File : in out File_Type; Name : VString) is begin Open (File, To_String (Name)); end Open; procedure Create (File : in out File_Type; Name : String) is use Ada.Text_IO; begin Create (File, Out_File, Name); end Create; procedure Create (File : in out File_Type; Name : VString) is begin Create (File, To_String (Name)); end Create; procedure Append (File : in out File_Type; Name : String) is use Ada.Text_IO; begin Open (File, Append_File, Name); end Append; procedure Append (File : in out File_Type; Name : VString) is begin Append (File, To_String (Name)); end Append; --------- -- GET -- --------- procedure Get (I : out Integer) is begin IIO.Get (I); end Get; procedure Get (File : File_Type; I : out Integer) is begin IIO.Get (File, I); end Get; procedure Get (F : out Real) is begin RIO.Get (F); end Get; procedure Get (File : File_Type; F : out Real) is begin RIO.Get (File, F); end Get; -------------- -- GET_LINE -- -------------- procedure Get_Line (C : out Character) is begin Get (C); Skip_Line; end Get_Line; procedure Get_Line (File : File_Type; C : out Character) is begin Get (File, C); Skip_Line (File); end Get_Line; procedure Get_Line (I : out Integer) is begin Get (I); Skip_Line; end Get_Line; procedure Get_Line (File : File_Type; I : out Integer) is begin Get (File, I); Skip_Line (File); end Get_Line; procedure Get_Line (F : out Real) is begin Get (F); Skip_Line; end Get_Line; procedure Get_Line (File : File_Type; F : out Real) is begin Get (File, F); Skip_Line (File); end Get_Line; procedure Get_Line (V : out VString) is begin V := +Ada.Text_IO.Get_Line; end Get_Line; procedure Get_Line (File : File_Type; V : out VString) is begin V := +Ada.Text_IO.Get_Line (File); end Get_Line; -- Ada.Text_IO's Skip_Line is called without the optional parameter, Spacing. procedure Skip_Line is begin Ada.Text_IO.Skip_Line; end Skip_Line; procedure Skip_Line (File : File_Type) is begin Ada.Text_IO.Skip_Line (File); end Skip_Line; --------- -- PUT -- --------- procedure Put (C : in Character) is begin Ada.Text_IO.Put (C); end Put; procedure Put (File : File_Type; C : in Character) is begin Ada.Text_IO.Put (File, C); end Put; procedure Put (I : in Integer; Width : Ada.Text_IO.Field := IIO.Default_Width; Base : Ada.Text_IO.Number_Base := IIO.Default_Base) is begin IIO.Put (I, Width, Base); end Put; procedure Put (File : File_Type; I : in Integer; Width : Ada.Text_IO.Field := IIO.Default_Width; Base : Ada.Text_IO.Number_Base := IIO.Default_Base) is begin IIO.Put (File, I, Width, Base); end Put; procedure Put (F : in Real; Fore : Integer := RIO.Default_Fore; Aft : Integer := RIO.Default_Aft; Expo : Integer := RIO.Default_Exp) is begin RIO.Put (F, Fore, Aft, Expo); end Put; procedure Put (File : File_Type; F : in Real; Fore : Integer := RIO.Default_Fore; Aft : Integer := RIO.Default_Aft; Expo : Integer := RIO.Default_Exp) is begin RIO.Put (File, F, Fore, Aft, Expo); end Put; procedure Put (B : in Boolean; Width : Ada.Text_IO.Field := BIO.Default_Width) is begin BIO.Put (B, Width); end Put; procedure Put (File : File_Type; B : in Boolean; Width : Ada.Text_IO.Field := BIO.Default_Width) is begin BIO.Put (File, B, Width); end Put; procedure Put (S : in String) is begin Ada.Text_IO.Put (S); end Put; procedure Put (File : File_Type; S : in String) is begin Ada.Text_IO.Put (File, S); end Put; procedure Put (V : in VString) is begin Put (To_String (V)); end Put; procedure Put (File : File_Type; V : in VString) is begin Put (File, To_String (V)); end Put; -------------- -- PUT_LINE -- -------------- procedure Put_Line (C : Character) is begin Put (C); New_Line; end Put_Line; procedure Put_Line (File : File_Type; C : in Character) is begin Put (File, C); New_Line (File); end Put_Line; procedure Put_Line (I : Integer; Width : Ada.Text_IO.Field := IIO.Default_Width; Base : Ada.Text_IO.Number_Base := IIO.Default_Base) is begin Put (I, Width, Base); New_Line; end Put_Line; procedure Put_Line (File : File_Type; I : Integer; Width : Ada.Text_IO.Field := IIO.Default_Width; Base : Ada.Text_IO.Number_Base := IIO.Default_Base) is begin Put (File, I, Width, Base); New_Line (File); end Put_Line; procedure Put_Line (F : Real; Fore : Integer := RIO.Default_Fore; Aft : Integer := RIO.Default_Aft; Expo : Integer := RIO.Default_Exp) is begin Put (F, Fore, Aft, Expo); New_Line; end Put_Line; procedure Put_Line (File : File_Type; F : Real; Fore : Integer := RIO.Default_Fore; Aft : Integer := RIO.Default_Aft; Expo : Integer := RIO.Default_Exp) is begin Put (File, F, Fore, Aft, Expo); New_Line (File); end Put_Line; procedure Put_Line (B : Boolean; Width : Ada.Text_IO.Field := BIO.Default_Width) is begin Put (B, Width); New_Line; end Put_Line; procedure Put_Line (File : File_Type; B : Boolean; Width : Ada.Text_IO.Field := BIO.Default_Width) is begin Put (File, B, Width); New_Line (File); end Put_Line; procedure Put_Line (S : String) is begin Ada.Text_IO.Put_Line (S); end Put_Line; procedure Put_Line (File : File_Type; S : String) is begin Ada.Text_IO.Put_Line (File, S); end Put_Line; procedure Put_Line (V : VString) is begin Put_Line (To_String (V)); end Put_Line; procedure Put_Line (File : File_Type; V : VString) is begin Put_Line (File, To_String (V)); end Put_Line; procedure New_Line is begin Ada.Text_IO.New_Line; end New_Line; procedure New_Line (File : File_Type) is begin Ada.Text_IO.New_Line (File); end New_Line; ---------- -- WAIT -- ---------- procedure Wait (S : Semaphore) is begin raise Program_Error with "WAIT unimplemented"; end Wait; ------------ -- SIGNAL -- ------------ procedure Signal (S : Semaphore) is begin raise Program_Error with "SIGNAL unimplemented"; end Signal; function Argument (Number : Positive) return VString is begin return +Ada.Command_Line.Argument (Number); end Argument; function Command_Name return VString is begin return +Ada.Command_Line.Command_Name; end Command_Name; procedure Set_Exit_Status (Code : in Integer) is begin Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Exit_Status (Code)); end Set_Exit_Status; function Get_Env (Name : String) return VString is use Ada.Environment_Variables; begin if Ada.Environment_Variables.Exists (Name) then return +Value (Name); else return Null_VString; end if; end Get_Env; function Get_Env (Name : VString) return VString is begin return Get_Env (To_String (Name)); end Get_Env; procedure Set_Env (Name : VString; Value : String) is begin Set_Env (To_String (Name), Value); end Set_Env; procedure Set_Env (Name : String; Value : VString) is begin Set_Env (Name, To_String (Value)); end Set_Env; procedure Set_Env (Name : VString; Value : VString) is begin Set_Env (To_String (Name), To_String (Value)); end Set_Env; function Current_Directory return VString is begin return +Ada.Directories.Current_Directory; end Current_Directory; procedure Set_Directory (Directory : VString) is begin Set_Directory (To_String (Directory)); end Set_Directory; procedure Copy_File (Source_Name : String; Target_Name : String) is begin Ada.Directories.Copy_File (Source_Name, Target_Name); -- Form: default value "". end Copy_File; procedure Copy_File (Source_Name : VString; Target_Name : String) is begin Copy_File (To_String (Source_Name), Target_Name); end Copy_File; procedure Copy_File (Source_Name : String; Target_Name : VString) is begin Copy_File (Source_Name, To_String (Target_Name)); end Copy_File; procedure Copy_File (Source_Name : VString; Target_Name : VString) is begin Copy_File (To_String (Source_Name), To_String (Target_Name)); end Copy_File; procedure Delete_File (Name : VString) is begin Delete_File (To_String (Name)); end Delete_File; function Exists (Name : VString) return Boolean is begin return Exists (To_String (Name)); end Exists; procedure Rename (Old_Name : VString; New_Name : String) is begin Rename (To_String (Old_Name), New_Name); end Rename; procedure Rename (Old_Name : String; New_Name : VString) is begin Rename (Old_Name, To_String (New_Name)); end Rename; procedure Rename (Old_Name : VString; New_Name : VString) is begin Rename (To_String (Old_Name), To_String (New_Name)); end Rename; function HAC_Generic_Image (I : Abstract_Integer) return String is Im : constant String := Abstract_Integer'Image (I); begin if I < 0 then return Im; else return Im (Im'First + 1 .. Im'Last); -- Remove the leading ' '. end if; end HAC_Generic_Image; function HAC_Image (F : Real) return String is -- Code from TeXCAD (tc.adb, TeX_Number), -- less a few simplifications. s : String (1 .. Real'Digits + 15); na, nb, np, ne : Natural; function Image_with_exponent return String is begin RIO.Put (s, F); na := s'First; for i in s'Range loop case s (i) is when ' ' => na := i + 1; -- * Trim spaces on the left when others => null; end case; end loop; ne := Ada.Strings.Fixed.Index (s, "0E"); if ne > 0 then -- Simplify "4.56000000000000E+68" into "4.56E+68". -- * Remove extra '0's... nb := ne - 1; while s (nb) = '0' loop nb := nb - 1; end loop; if s (nb) = '.' then -- "4.E+68" from "4.00000000000000E+68" would be too much trimming... nb := nb + 1; -- We keep one '0' -> "4.0E+68". end if; return s (na .. nb) & s (ne + 1 .. s'Last); end if; return s (na .. s'Last); end Image_with_exponent; -- function Count_Nonzero_Digits (any : String) return Natural is n : Natural := 0; begin for i in any'Range loop exit when any (i) = 'E'; -- Ignore exponent part. if any (i) in '1' .. '9' then n := n + 1; end if; end loop; return n; end Count_Nonzero_Digits; begin -- Image without exponent (E). -- If the number is too large for this layout, a Layout_Error -- is raised and we call Image_with_exponent. RIO.Put (s, F, Exp => 0); if Count_Nonzero_Digits (s) < Count_Nonzero_Digits (Real'Image (F)) then return Image_with_exponent; -- Loss of significant digits. end if; -- We don't lose any digits in decimal representation without exponent. na := s'First; nb := s'Last; np := 0; for i in s'Range loop case s (i) is when '.' => np := i; exit; -- Find a decimal point when ' ' => na := i + 1; -- * Trim spaces on the left when others => null; end case; end loop; if np > 0 then -- In case of a decimal point. while nb > np + 1 and then s (nb) = '0' loop nb := nb - 1; -- * Remove extra '0's except for "x.0" end loop; end if; return s (na .. nb); exception when Ada.Text_IO.Layout_Error => -- Number too large, we fall back to show the version with exponent. return Image_with_exponent; end HAC_Image; package Non_Standard is procedure Sys (Command : String; Result : out Integer); function Directory_Separator return Character; end Non_Standard; package body Non_Standard is separate; procedure Shell_Execute (Command : String; Result : out Integer) is -- https://rosettacode.org/wiki/Execute_a_system_command#Ada begin Non_Standard.Sys (Command, Result); end Shell_Execute; procedure Shell_Execute (Command : VString; Result : out Integer) is begin Shell_Execute (To_String (Command), Result); end Shell_Execute; procedure Shell_Execute (Command : String) is Dummy : Integer; begin Shell_Execute (Command, Dummy); end Shell_Execute; procedure Shell_Execute (Command : VString) is begin Shell_Execute (To_String (Command)); end Shell_Execute; function Directory_Separator return Character is begin return Non_Standard.Directory_Separator; end Directory_Separator; begin Ada.Numerics.Float_Random.Reset (gen); -- Randomize. end HAC_Pack;
sungyeon/drake
Ada
437
ads
pragma License (Unrestricted); -- runtime unit specialized for Darwin with C.pthread; with C.signal; package System.Stack is pragma Preelaborate; procedure Get ( Thread : C.pthread.pthread_t := C.pthread.pthread_self; Top, Bottom : out Address); procedure Fake_Return_From_Signal_Handler; function Fault_Address (Info : C.signal.siginfo_t) return Address; pragma Inline (Fault_Address); end System.Stack;
reznikmm/matreshka
Ada
5,093
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Tools Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2015, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Asis.Elements; with Asis.Expressions; package body Properties.Expressions.Array_Component_Association is ---------- -- Code -- ---------- function Code (Engine : access Engines.Contexts.Context; Element : Asis.Association; Name : Engines.Text_Property) return League.Strings.Universal_String is Result : League.Strings.Universal_String; List : constant Asis.Element_List := Asis.Expressions.Array_Component_Choices (Element); Value : constant Asis.Expression := Asis.Expressions.Component_Expression (Element); Down : League.Strings.Universal_String; Kind : Asis.Definition_Kinds; begin Result.Append ("["); -- Push actual value Down := Engine.Text.Get_Property (Value, Name); Result.Append (Down); if List'Length > 0 then Result.Append (", "); end if; -- Then push bounds as pairs of values for J in List'Range loop Kind := Asis.Elements.Definition_Kind (List (J)); case Kind is when Asis.An_Others_Choice => Result.Append ("undefined, undefined"); when Asis.A_Discrete_Range => -- FIXME: Only empty range is supported Result.Append ("1, 0"); when others => Down := Engine.Text.Get_Property (List (J), Name); Result.Append (Down); Result.Append (", "); Result.Append ("undefined"); end case; if J /= List'Last then Result.Append (", "); end if; end loop; Result.Append ("], "); return Result; end Code; end Properties.Expressions.Array_Component_Association;
faelys/natools
Ada
2,560
ads
------------------------------------------------------------------------------ -- Copyright (c) 2015, Natacha Porté -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- Natools.S_Expressions.Conditionals.Generic_Evaluate provides an -- -- evaluation function based on elementary names and functions, allowing -- -- boolean combination of them. -- -- For example Simple_Evaluate might evaluate the word "is_empty", while -- -- Parameteric_Evaluate might check "contains", then Generic_Evaluate -- -- handles expressions like: -- -- (or is-empty (contains part_1) (and (not is-empty) (contains part_2))) -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Lockable; generic type Context_Type (<>) is limited private; with function Parametric_Evaluate (Context : in Context_Type; Name : in Natools.S_Expressions.Atom; Arguments : in out Natools.S_Expressions.Lockable.Descriptor'Class) return Boolean; with function Simple_Evaluate (Context : in Context_Type; Name : in Natools.S_Expressions.Atom) return Boolean; function Natools.S_Expressions.Conditionals.Generic_Evaluate (Context : in Context_Type; Expression : in out Lockable.Descriptor'Class) return Boolean; pragma Pure (Natools.S_Expressions.Conditionals.Generic_Evaluate);
Heziode/lsystem-editor
Ada
8,923
adb
------------------------------------------------------------------------------- -- LSE -- L-System Editor -- Author: Heziode -- -- License: -- MIT License -- -- Copyright (c) 2018 Quentin Dauprat (Heziode) <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- with Ada.Directories; with Glib.Convert; with Gtk.Builder; with Gtk.Main; with LSE.IO.Export_Factory; with LSE.Model.IO.Turtle; with LSE.Model.L_System.L_System; with LSE.Utils.Colors; with LSE.View.View; package body LSE.Presenter.Presenter is -- Constructor procedure Initialize (This : out Instance) is use Glib.Convert; use Gtk.Builder; use LSE.Model.IO.Turtle; use LSE.Model.L_System.Concrete_Builder; use LSE.Model.L_System.L_System; use LSE.View.View; Builder : Gtk_Builder; LS_Builder : LSE.Model.L_System.Concrete_Builder.Instance; begin Ada.Directories.Set_Directory (Exec_Dir); Gtk.Main.Init; Gtk_New_From_File (Builder, Locale_To_UTF8 (Main_UI)); This.View := new LSE.View.View.Instance '(Initialize (Builder, This'Access)); This.Turtle := To_Holder (Initialize); if LS_Builder.Make (Default_LSystem) then This.LS := To_Holder (LS_Builder.Get_Product (This.Turtle)); end if; end Initialize; function Get_View (This : Instance) return LSE.View.View.Instance is begin return This.View.all; end Get_View; procedure Start (This : Instance) is pragma Unreferenced (This); begin Gtk.Main.Main; end Start; procedure LS_Level (This : out Instance; Value : Integer) is begin This.LS.Reference.Set_State (Natural (Value)); end LS_Level; function Validate (This : in out Instance; Input : String) return Boolean is begin if This.Builder.Make (Input) then This.LS := To_Holder (This.Builder.Get_Product (This.Turtle)); return True; else return False; end if; end Validate; function Get_Error (This : Instance) return String is begin return This.Builder.Get_Error; end Get_Error; procedure Develop (This : out Instance) is begin This.LS.Reference.Develop; end Develop; procedure Interpret (This : out Instance) is begin This.LS.Reference.Interpret (This.Turtle); end Interpret; procedure Export (This : in out Instance; Format : String; Path : String; Width, Height, Margin_Top, Margin_Right, Margin_Bottom, Margin_Left : Gint; Bg_Rgba, Fg_Rgba : Gdk_RGBA; Have_Bg : Boolean) is use LSE.IO.Export_Factory; use LSE.Model.IO.Drawing_Area.Drawing_Area_Ptr; use LSE.Model.IO.Turtle; use LSE.Utils.Colors; Turtle : LSE.Model.IO.Turtle_Utils.Holder; Medium : LSE.Model.IO.Drawing_Area.Drawing_Area_Ptr.Holder; begin Turtle := To_Holder (Initialize); Make (Medium, Format, Path); Turtle.Reference.Set_Medium (Medium); Turtle.Reference.Set_Width (Positive (Width)); Turtle.Reference.Set_Height (Positive (Height)); Turtle.Reference.Set_Margin_Top (Natural (Margin_Top)); Turtle.Reference.Set_Margin_Right (Natural (Margin_Right)); Turtle.Reference.Set_Margin_Bottom (Natural (Margin_Bottom)); Turtle.Reference.Set_Margin_Left (Natural (Margin_Left)); if Have_Bg then Turtle.Reference.Set_Background_Color (RGB_To_Hex_String (Float (Bg_Rgba.Red), Float (Bg_Rgba.Green), Float (Bg_Rgba.Blue))); else Turtle.Reference.Set_Background_Color (""); end if; Turtle.Reference.Set_Foreground_Color (RGB_To_Hex_String (Float (Fg_Rgba.Red), Float (Fg_Rgba.Green), Float (Fg_Rgba.Blue))); This.LS.Reference.Interpret (Turtle); end Export; function Get_Width (This : Instance) return Positive is begin return This.Turtle.Element.Get_Width; end Get_Width; function Get_Height (This : Instance) return Positive is begin return This.Turtle.Element.Get_Height; end Get_Height; function Get_Background_Color (This : Instance) return String is begin return This.Turtle.Element.Get_Background_Color; end Get_Background_Color; function Get_Foreground_Color (This : Instance) return String is begin return This.Turtle.Element.Get_Foreground_Color; end Get_Foreground_Color; function Get_Margin_Top (This : Instance) return Float is begin return This.Turtle.Element.Get_Margin_Top; end Get_Margin_Top; function Get_Margin_Right (This : Instance) return Float is begin return This.Turtle.Element.Get_Margin_Right; end Get_Margin_Right; function Get_Margin_Bottom (This : Instance) return Float is begin return This.Turtle.Element.Get_Margin_Bottom; end Get_Margin_Bottom; function Get_Margin_Left (This : Instance) return Float is begin return This.Turtle.Element.Get_Margin_Left; end Get_Margin_Left; -- Mutator of Width procedure Set_Width (This : out Instance; Value : Gint) is begin This.Turtle.Reference.Set_Width (Positive (Value)); end Set_Width; -- Mutator of Height procedure Set_Height (This : out Instance; Value : Gint) is begin This.Turtle.Reference.Set_Height (Positive (Value)); end Set_Height; -- Mutator of background color procedure Set_Background_Color (This : out Instance; Value : Gdk_RGBA) is use LSE.Utils.Colors; begin This.Turtle.Reference.Set_Background_Color (RGB_To_Hex_String (Float (Value.Red), Float (Value.Green), Float (Value.Blue))); end Set_Background_Color; procedure Set_Background_Color_Clear (This : out Instance) is begin This.Turtle.Reference.Set_Background_Color (""); end Set_Background_Color_Clear; -- Mutator of foreground color procedure Set_Foreground_Color (This : out Instance; Value : Gdk_RGBA) is use LSE.Utils.Colors; begin This.Turtle.Reference.Set_Foreground_Color (RGB_To_Hex_String (Float (Value.Red), Float (Value.Green), Float (Value.Blue))); end Set_Foreground_Color; -- Mutator of margin top procedure Set_Margin_Top (This : out Instance; Value : Gint) is begin This.Turtle.Reference.Set_Margin_Top (Natural (Value)); end Set_Margin_Top; -- Mutator of margin right procedure Set_Margin_Right (This : out Instance; Value : Gint) is begin This.Turtle.Reference.Set_Margin_Right (Natural (Value)); end Set_Margin_Right; -- Mutator of margin Bottom procedure Set_Margin_Bottom (This : out Instance; Value : Gint) is begin This.Turtle.Reference.Set_Margin_Bottom (Natural (Value)); end Set_Margin_Bottom; -- Mutator of margin left procedure Set_Margin_Left (This : out Instance; Value : Gint) is begin This.Turtle.Reference.Set_Margin_Left (Natural (Value)); end Set_Margin_Left; function Get_Extension (This : Instance; Value : String) return String is pragma Unreferenced (This); use LSE.IO.Export_Factory; begin return Get_Extension (Value); end Get_Extension; procedure Set_Medium (This : out Instance; Value : LSE.Model.IO.Drawing_Area. Drawing_Area_Ptr.Holder) is begin This.Turtle.Reference.Set_Medium (Value); end Set_Medium; end LSE.Presenter.Presenter;
rveenker/sdlada
Ada
3,277
adb
-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2013-2020, Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- with Interfaces.C; with Interfaces.C.Strings; private with SDL.C_Pointers; with SDL.Error; package body SDL.Video.Windows.Makers is package C renames Interfaces.C; use type SDL.C_Pointers.Windows_Pointer; procedure Create (Win : in out Window; Title : in Ada.Strings.UTF_Encoding.UTF_8_String; Position : in SDL.Natural_Coordinates; Size : in SDL.Positive_Sizes; Flags : in Window_Flags := OpenGL) is function SDL_Create (Title : C.Strings.chars_ptr; X, Y, W, H : in C.int; F : in Window_Flags) return SDL.C_Pointers.Windows_Pointer with Import => True, Convention => C, External_Name => "SDL_CreateWindow"; C_Title_Str : C.Strings.chars_ptr := C.Strings.New_String (Title); begin Win.Internal := SDL_Create (C_Title_Str, Position.X, Position.Y, Size.Width, Size.Height, Flags); C.Strings.Free (C_Title_Str); if Win.Internal = null then raise Window_Error with SDL.Error.Get; end if; Increment_Windows; end Create; procedure Create (Win : in out Window; Title : in Ada.Strings.UTF_Encoding.UTF_8_String; X : in SDL.Natural_Coordinate; Y : in SDL.Natural_Coordinate; Width : in SDL.Positive_Dimension; Height : in SDL.Positive_Dimension; Flags : in Window_Flags := OpenGL) is begin Create (Win, Title, SDL.Natural_Coordinates'(X, Y), SDL.Positive_Sizes'(Width, Height), Flags); end Create; procedure Create (Win : in out Window; Native : in Native_Window) is function SDL_Create_Window_From (Native : Native_Window) return SDL.C_Pointers.Windows_Pointer with Import => True, Convention => C, External_Name => "SDL_CreateWindowFrom"; begin Win.Internal := SDL_Create_Window_From (Native); Win.Owns := True; if Win.Internal = null then raise Window_Error with SDL.Error.Get; end if; Increment_Windows; end Create; end SDL.Video.Windows.Makers;
stcarrez/ada-asf
Ada
3,884
adb
----------------------------------------------------------------------- -- asf-components-html-links -- ASF HTML Components -- Copyright (C) 2009, 2010, 2012, 2019, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with EL.Objects; with Util.Strings; with ASF.Utils; package body ASF.Components.Html.Links is LINK_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set; -- ------------------------------ -- Get the value to write on the output. -- ------------------------------ function Get_Value (UI : in UIOutputLink) return EL.Objects.Object is begin return UI.Get_Attribute (UI.Get_Context.all, "value"); -- return UI.Value; end Get_Value; -- ------------------------------ -- Set the value to write on the output. -- ------------------------------ procedure Set_Value (UI : in out UIOutputLink; Value : in EL.Objects.Object) is begin UI.Value := Value; end Set_Value; -- ------------------------------ -- Get the link to be rendered in the <b>href</b> attribute. -- ------------------------------ function Get_Link (UI : in UIOutputLink; Context : in Faces_Context'Class) return String is Value : constant String := UI.Get_Attribute ("value", Context, ""); begin return Value; end Get_Link; -- ------------------------------ -- Encode the beginning of the link. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIOutputLink; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Writer : constant Response_Writer_Access := Context.Get_Response_Writer; Disabled : constant Boolean := UI.Get_Attribute ("disabled", Context, False); begin if Disabled then Writer.Start_Optional_Element ("span"); else Writer.Start_Element ("a"); Writer.Write_Attribute ("href", UIOutputLink'Class (UI).Get_Link (Context)); end if; UI.Render_Attributes (Context, Writer); end; end Encode_Begin; -- ------------------------------ -- Encode the end of the link. -- ------------------------------ overriding procedure Encode_End (UI : in UIOutputLink; Context : in out Faces_Context'Class) is begin if not UI.Is_Rendered (Context) then return; end if; declare Disabled : constant Boolean := UI.Get_Attribute ("disabled", Context, False); Writer : constant Response_Writer_Access := Context.Get_Response_Writer; begin if Disabled then Writer.End_Optional_Element ("span"); else Writer.End_Element ("a"); end if; end; end Encode_End; begin Utils.Set_Text_Attributes (LINK_ATTRIBUTE_NAMES); Utils.Set_Interactive_Attributes (LINK_ATTRIBUTE_NAMES); Utils.Set_Link_Attributes (LINK_ATTRIBUTE_NAMES); end ASF.Components.Html.Links;
reznikmm/matreshka
Ada
4,123
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with ODF.DOM.Style_Border_Line_Width_Bottom_Attributes; package Matreshka.ODF_Style.Border_Line_Width_Bottom_Attributes is type Style_Border_Line_Width_Bottom_Attribute_Node is new Matreshka.ODF_Style.Abstract_Style_Attribute_Node and ODF.DOM.Style_Border_Line_Width_Bottom_Attributes.ODF_Style_Border_Line_Width_Bottom_Attribute with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Style_Border_Line_Width_Bottom_Attribute_Node; overriding function Get_Local_Name (Self : not null access constant Style_Border_Line_Width_Bottom_Attribute_Node) return League.Strings.Universal_String; end Matreshka.ODF_Style.Border_Line_Width_Bottom_Attributes;
reznikmm/matreshka
Ada
5,658
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2013, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- Implementation of proleptic Gregorian calendar with astronomical year -- numbering. ------------------------------------------------------------------------------ package Matreshka.Internals.Calendars.Gregorian is pragma Preelaborate; subtype Year_Number is Integer range -9_999 .. 9_999; subtype Month_Number is Integer range 1 .. 12; subtype Day_Number is Integer range 1 .. 31; subtype Day_Of_Week_Number is Integer range 1 .. 7; subtype Day_Of_Year_Number is Integer range 1 .. 366; subtype Week_Of_Year_Number is Integer range 1 .. 53; function Is_Leap_Year (Date : Julian_Day_Number) return Boolean; function Is_Leap_Year (Year : Year_Number) return Boolean; -- Returns True when year is a leap year. function Julian_Day (Year : Year_Number; Month : Month_Number; Day : Day_Number) return Julian_Day_Number; -- Returns Juliad Day of the specified date. function Year (Julian_Day : Julian_Day_Number) return Year_Number; -- Returns year of the specified julian day. function Month (Julian_Day : Julian_Day_Number) return Month_Number; -- Returns month of the specified julian day. function Day (Julian_Day : Julian_Day_Number) return Day_Number; -- Returns day of the specified julian day. function Day_Of_Week (Julian_Day : Julian_Day_Number) return Day_Of_Week_Number; -- Returns the weekday for this julian day. First day is Monday. function Day_Of_Year (Julian_Day : Julian_Day_Number) return Day_Of_Year_Number; -- Returns the day of the year (1 to 365 or 366 on leap years) for this -- julian day. function Days_In_Month (Date : Julian_Day_Number) return Day_Number; function Days_In_Month (Year : Year_Number; Month : Year_Number) return Day_Number; -- Returns number of days in the specified month of the specified year. function Days_In_Year (Date : Julian_Day_Number) return Day_Of_Year_Number; function Days_In_Year (Year : Year_Number) return Day_Of_Year_Number; -- Returns number of days in the specified year. procedure Split (Date : Julian_Day_Number; Year : out Year_Number; Month : out Month_Number; Day : out Day_Number); -- Splits date into year, month and day components. end Matreshka.Internals.Calendars.Gregorian;
reznikmm/matreshka
Ada
3,719
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with XML.DOM.Attributes; package ODF.DOM.Style_Num_Suffix_Attributes is pragma Preelaborate; type ODF_Style_Num_Suffix_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Style_Num_Suffix_Attribute_Access is access all ODF_Style_Num_Suffix_Attribute'Class with Storage_Size => 0; end ODF.DOM.Style_Num_Suffix_Attributes;
stcarrez/ada-awa
Ada
17,394
adb
----------------------------------------------------------------------- -- awa-users-tests -- Unit tests for AWA users -- Copyright (C) 2009, 2010, 2011, 2012, 2017, 2018, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Log; with Util.Test_Caller; with ASF.Tests; with AWA.Users.Models; with AWA.Tests.Helpers.Users; with AWA.Users.Services; with AWA.Tests.Helpers; with Servlet.Requests.Mockup; with Servlet.Responses.Mockup; with Security; package body AWA.Users.Tests is use ASF.Tests; use type Security.Principal_Access; use type AWA.Users.Services.User_Service_Access; package Caller is new Util.Test_Caller (Test, "Users.Tests"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (/users/register.xhtml)", Test_Create_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Create_User (Disabled)", Test_Registration_Disabled'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Close_Session", Test_Logout_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Tests.Login_User (/users/login.xhtml)", Test_Login_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password, Reset_Password", Test_Reset_Password_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Lost_Password (No user)", Test_Reset_Password_Invalid_User'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Authenticate", Test_OAuth_Login'Access); Caller.Add_Test (Suite, "Test AWA.Users.Services.Verify_User (Bad Key)", Test_Validate_Bad_Key'Access); end Add_Tests; -- ------------------------------ -- Test creation of user by simulating web requests. -- ------------------------------ procedure Test_Create_User (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Helpers.Users.Initialize (Principal); Do_Get (Request, Reply, "/auth/register.html", "create-user-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("password2", "asdf"); Request.Set_Parameter ("firstName", "joe"); Request.Set_Parameter ("lastName", "dalton"); Request.Set_Parameter ("register-button", "1"); ASF.Tests.Set_CSRF (Request, "register", "create-user-1.html"); Do_Post (Request, Reply, "/auth/register.html", "create-user-2.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); -- Now, get the access key and simulate a click on the validation link. declare Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); Do_Get (Request, Reply, "/auth/validate/" & Key.Get_Access_Key, "validate-user-1.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); end; -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); -- Check that the logout removes the principal Do_Get (Request, Reply, "/auth/logout.html", "logout-created-user-1.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirection after logout"); end Test_Create_User; -- ------------------------------ -- Test creation of user when the registration is disabled. -- ------------------------------ procedure Test_Registration_Disabled (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; Email : constant String := "Joe-" & Util.Tests.Get_Uuid & "@gmail.com"; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Helpers.Users.Initialize (Principal); T.Assert (Principal.Manager /= null, "No User Manager defined"); Principal.Manager.Set_Allow_Register (False); Do_Get (Request, Reply, "/auth/register.html", "register-disabled-1.html"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("password", "asdf"); Request.Set_Parameter ("password2", "asdf"); Request.Set_Parameter ("firstName", "joe"); Request.Set_Parameter ("lastName", "dalton"); Request.Set_Parameter ("register-button", "1"); ASF.Tests.Set_CSRF (Request, "register", "register-disabled-1.html"); Do_Post (Request, Reply, "/auth/register.html", "register-disabled-2.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); -- Check that we are redirected to the /auth/login.html page with the -- user registration disabled message. ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirection when registration disabled"); Do_Get (Request, Reply, "/auth/login.html", "register-disabled-3.html"); ASF.Tests.Assert_Matches (T, "The user registration is disabled on this server.", Reply, "Invalid error page after user creation (disabled)", Servlet.Responses.SC_OK); -- Second test using the OAuth2 fake provider. Do_Get (Request, Reply, "/auth/auth/google", "oauth-google.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("id", "oauth-user-id-not-registered-fake"); Request.Set_Parameter ("claimed_id", "oauth-user-unreg-claimed_id-fake"); Do_Get (Request, Reply, "/auth/[email protected]&" & "id=oauth-user-id-not-registered-fake&claimed_id=oauth-user-unreg-claimed_id-fake", "oauth-verify-unreg.html"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal must not be defined"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirection when registration disabled"); Do_Get (Request, Reply, "/auth/login.html", "register-disabled-4.html"); ASF.Tests.Assert_Matches (T, "The user registration is disabled on this server.", Reply, "Invalid error page after user creation (disabled)", Servlet.Responses.SC_OK); -- Restore user registration for other tests. Principal.Manager.Set_Allow_Register (True); exception when others => Principal.Manager.Set_Allow_Register (True); raise; end Test_Registration_Disabled; procedure Test_Logout_User (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/auth/logout.html", "logout.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirection after logout"); T.Assert (Request.Get_User_Principal = null, "A user principal must be removed"); end Test_Logout_User; -- ------------------------------ -- Test user authentication by simulating a web request. -- ------------------------------ procedure Test_Login_User (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; Principal : AWA.Tests.Helpers.Users.Test_User; begin AWA.Tests.Set_Application_Context; AWA.Tests.Get_Application.Dump_Routes (Util.Log.INFO_LEVEL); begin AWA.Tests.Helpers.Users.Create_User (Principal, "[email protected]"); -- It sometimes happen that Joe's password is changed by another test. -- Recover the password and make sure it is 'admin'. exception when others => T.Recover_Password ("[email protected]", "admin"); end; Do_Get (Request, Reply, "/auth/login.html", "login-user-1.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK, "Invalid response"); -- Check that the user is NOT logged. T.Assert (Request.Get_User_Principal = null, "A user principal should not be defined"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("password", "admin"); Request.Set_Parameter ("login-button", "1"); ASF.Tests.Set_CSRF (Request, "login", "login-user-1.html"); Do_Post (Request, Reply, "/auth/login.html", "login-user-2.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end Test_Login_User; -- ------------------------------ -- Test OAuth access using a fake OAuth provider. -- ------------------------------ procedure Test_OAuth_Login (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/auth/auth/google", "oauth-google.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("id", "oauth-user-id-fake"); Request.Set_Parameter ("claimed_id", "oauth-user-claimed_id-fake"); Do_Get (Request, Reply, "/auth/[email protected]&" & "id=oauth-user-id-fake&claimed_id=oauth-user-claimed-id-fake", "oauth-verify.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_MOVED_TEMPORARILY, "Invalid response"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); Util.Tests.Assert_Equals (T, "Oauth-user", Request.Get_User_Principal.Get_Name, "Invalid user name after OAuth authentication"); end Test_OAuth_Login; -- ------------------------------ -- Test validation with an invalid access key. -- ------------------------------ procedure Test_Validate_Bad_Key (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/auth/validate/", "validate-bad-key-1.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirection when validation key is empty"); Do_Get (Request, Reply, "/auth/login.html", "validate-bad-key-msg-1.html"); ASF.Tests.Assert_Matches (T, "The access key is invalid or has expired.", Reply, "Invalid error page after validate key (bad key)", Servlet.Responses.SC_OK); Do_Get (Request, Reply, "/auth/validate/abcde", "validate-bad-key-2.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirection when validation key is empty"); Do_Get (Request, Reply, "/auth/login.html", "validate-bad-key-msg-2.html"); ASF.Tests.Assert_Matches (T, "The access key is invalid or has expired.", Reply, "Invalid error page after validate key (bad key)", Servlet.Responses.SC_OK); end Test_Validate_Bad_Key; -- ------------------------------ -- Run the recovery password process for the given user and change the password. -- ------------------------------ procedure Recover_Password (T : in out Test; Email : in String; Password : in String) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-1.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK, "Invalid response"); Request.Set_Parameter ("email", Email); Request.Set_Parameter ("lost-password-button", "1"); ASF.Tests.Set_CSRF (Request, "lost-password", "lost-password-1.html"); Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-2.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirect after lost password"); Do_Get (Request, Reply, "/auth/login.html", "lost-password-3.html"); ASF.Tests.Assert_Matches (T, "A message was sent to your email address.", Reply, "Invalid message after lost password", Servlet.Responses.SC_OK); -- Now, get the access key and simulate a click on the reset password link. declare Principal : AWA.Tests.Helpers.Users.Test_User; Key : AWA.Users.Models.Access_Key_Ref; begin AWA.Tests.Set_Application_Context; AWA.Tests.Helpers.Users.Find_Access_Key (Principal, Email, Key); T.Assert (not Key.Is_Null, "There is no access key associated with the user"); Do_Get (Request, Reply, "/auth/change-password/" & Key.Get_Access_Key, "recover-password-get-2.html"); -- Simulate user clicking on the reset password link. -- This verifies the key, login the user and redirect him to the change-password page Request.Set_Parameter ("key", Key.Get_Access_Key); Request.Set_Parameter ("password", Password); Request.Set_Parameter ("reset-password", "1"); ASF.Tests.Set_CSRF (Request, "reset-password-form", "recover-password-get-2.html"); Do_Post (Request, Reply, "/auth/change-password/" & Key.Get_Access_Key, "recover-password-2.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/workspaces/main.html", Reply, "Invalid redirect after lost password"); -- Check that the user is logged and we have a user principal now. T.Assert (Request.Get_User_Principal /= null, "A user principal should be defined"); end; end Recover_Password; -- ------------------------------ -- Test the reset password by simulating web requests. -- ------------------------------ procedure Test_Reset_Password_User (T : in out Test) is begin T.Recover_Password ("[email protected]", "asf"); T.Recover_Password ("[email protected]", "admin"); end Test_Reset_Password_User; -- ------------------------------ -- Test the reset password with an invalid user. -- ------------------------------ procedure Test_Reset_Password_Invalid_User (T : in out Test) is Request : Servlet.Requests.Mockup.Request; Reply : Servlet.Responses.Mockup.Response; begin Do_Get (Request, Reply, "/auth/lost-password.html", "lost-password-4.html"); T.Assert (Reply.Get_Status = Servlet.Responses.SC_OK, "Invalid response"); Request.Set_Parameter ("email", "[email protected]"); Request.Set_Parameter ("lost-password-button", "1"); ASF.Tests.Set_CSRF (Request, "lost-password", "lost-password-4.html"); Do_Post (Request, Reply, "/auth/lost-password.html", "lost-password-5.html"); ASF.Tests.Assert_Redirect (T, "/asfunit/auth/login.html", Reply, "Invalid redirect after lost password"); end Test_Reset_Password_Invalid_User; end AWA.Users.Tests;
annexi-strayline/ASAP-CLI
Ada
10,227
ads
------------------------------------------------------------------------------ -- -- -- Command Line Interface Toolkit -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2019-2020, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Ensi Martini (ANNEXI-STRAYLINE) -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- -- -- * Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ package CLI is -- Note: CLI is line-oriented. Any widgets updated after New_Line will -- be rendered on the new line type Text_Style is private; function "+" (Left, Right : Text_Style) return Text_Style; -- This operator works like an "overwrite" -- Will keep any attributes of Left, adding to it the attributes of Right -- that it does not currently have -- NOTE: The color for the new Text_Style will always be the same as the -- color of the Right cursor, so if a user wishes to make a cursor that is -- the same as their current one, just with a different color, they should -- use: New_Style : Text_Style := Current_Style + New_Desired_Color_Style -- NOT the other way around function "-" (Left, Right : Text_Style) return Text_Style; -- This operator works like a "clear" for all attributes that appear in both -- Will retain all Left attributes that are not in Right cursor -- NOTE: The color for the new Text_Style will always be the same as the -- color of the Left cursor, because this is the one we are subtracting from -- With the preceding two operators and the following presets, any style -- and color combination cursor can be made -- COLOR PRESET CURSORS -- Neutral : constant Text_Style; -- Follow the text-style set from prior output -- Foreground Colors -- Black_FG : constant Text_Style; Red_FG : constant Text_Style; Green_FG : constant Text_Style; Yellow_FG : constant Text_Style; Blue_FG : constant Text_Style; Magenta_FG : constant Text_Style; Cyan_FG : constant Text_Style; White_FG : constant Text_Style; -- Background Colors -- Black_BG : constant Text_Style; Red_BG : constant Text_Style; Green_BG : constant Text_Style; Yellow_BG : constant Text_Style; Blue_BG : constant Text_Style; Magenta_BG : constant Text_Style; Cyan_BG : constant Text_Style; White_BG : constant Text_Style; -- ATTRIBUTE PRESET CURSORS -- Bold : constant Text_Style; Underline : constant Text_Style; Blink : constant Text_Style; Reverse_Vid : constant Text_Style; function Terminal_Width return Positive; -- Width of the terminal in columns. If the output is not a terminal, -- a value of 80 is always returned procedure Set_Column (Col: in Positive); function Current_Column return Positive; -- Sets or returns the current column number of the cursor. procedure Clear_Screen; procedure Clear_Line; procedure Clear_To_End; -- Note: all Wide_Wide_Strings/Characters are encoded in UTF-8 prior to -- output procedure Put (Char : in Character; Style: in Text_Style := Neutral); procedure Put (Message: in String; Style : in Text_Style := Neutral); procedure Wide_Wide_Put (Char : in Wide_Wide_Character; Style: in Text_Style := Neutral); procedure Wide_Wide_Put (Message: in Wide_Wide_String; Style : in Text_Style := Neutral); procedure Put_At (Char : in Character; Column : in Positive; Style : in Text_Style := Neutral); procedure Put_At (Message: in String; Column : in Positive; Style : in Text_Style := Neutral); procedure Wide_Wide_Put_At (Char : in Wide_Wide_Character; Column: in Positive; Style : in Text_Style := Neutral); procedure Wide_Wide_Put_At (Message: in Wide_Wide_String; Column : in Positive; Style : in Text_Style := Neutral); -- Put_At opeartions do not change the cursor position procedure Put_Line (Message: String; Style : Text_Style := Neutral); procedure Wide_Wide_Put_Line (Message: Wide_Wide_String; Style : Text_Style := Neutral); procedure New_Line; procedure Get (Item: out String); procedure Get (Item: out Character); procedure Get_Line (Item: out String; Last: out Natural); procedure Get_Immediate (Item: out Character; Available: out Boolean); function Output_Is_Terminal return Boolean; -- True if Standard_Output is a terminal, and False otherwise. -- If False, all ANSI code output is supressed. -- -- The use should avoid using widgets if Is_TTY is False private -- Clears to the end of the line from the current column type Color is (Black, Red, Green, Yellow, Blue, Magenta, Cyan, White, Default); type Text_Style is record Bold : Boolean := False; Underscore : Boolean := False; Blink : Boolean := False; Reverse_Vid : Boolean := False; Concealed : Boolean := False; Foreground : Color := Default; Background : Color := Default; end record; Neutral : constant Text_Style := (others => <>); Black_FG : constant Text_Style := (Foreground => Black, others => <>); Red_FG : constant Text_Style := (Foreground => Red, others => <>); Green_FG : constant Text_Style := (Foreground => Green, others => <>); Yellow_FG : constant Text_Style := (Foreground => Yellow, others => <>); Blue_FG : constant Text_Style := (Foreground => Blue, others => <>); Magenta_FG : constant Text_Style := (Foreground => Magenta, others => <>); Cyan_FG : constant Text_Style := (Foreground => Cyan, others => <>); White_FG : constant Text_Style := (Foreground => White, others => <>); Black_BG : constant Text_Style := (Background => Black, others => <>); Red_BG : constant Text_Style := (Background => Red, others => <>); Green_BG : constant Text_Style := (Background => Green, others => <>); Yellow_BG : constant Text_Style := (Background => Yellow, others => <>); Blue_BG : constant Text_Style := (Background => Blue, others => <>); Magenta_BG : constant Text_Style := (Background => Magenta, others => <>); Cyan_BG : constant Text_Style := (Background => Cyan, others => <>); White_BG : constant Text_Style := (Background => White, others => <>); Bold : constant Text_Style := (Bold => True, others => <>); Underline : constant Text_Style := (Underscore => True, others => <>); Blink : constant Text_Style := (Blink => True, others => <>); Reverse_Vid: constant Text_Style := (Reverse_Vid => True, others => <>); procedure Apply_Style (Style: Text_Style); procedure Clear_Style; end CLI;
reznikmm/spawn
Ada
5,477
adb
-- -- Copyright (C) 2021-2023, AdaCore -- -- SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -- with Ada.Command_Line; with Ada.Directories; with Ada.Streams; with Ada.Strings.Unbounded; with Ada.Text_IO; with Spawn.String_Vectors; with Spawn.Processes; with Spawn.Processes.Monitor_Loop; with Signals; pragma Unreferenced (Signals); procedure Spawn_Kill is pragma Assertion_Policy (Check); package Listeners is type Listener is limited new Spawn.Processes.Process_Listener with record Proc : Spawn.Processes.Process; Stdout : Ada.Strings.Unbounded.Unbounded_String; Stderr : Ada.Strings.Unbounded.Unbounded_String; Started : Boolean := False; Stopped : Boolean := False; Error : Integer := 0; end record; overriding procedure Standard_Output_Available (Self : in out Listener); overriding procedure Standard_Error_Available (Self : in out Listener); overriding procedure Started (Self : in out Listener); overriding procedure Finished (Self : in out Listener; Exit_Status : Spawn.Processes.Process_Exit_Status; Exit_Code : Spawn.Processes.Process_Exit_Code); overriding procedure Error_Occurred (Self : in out Listener; Process_Error : Integer); end Listeners; package body Listeners is overriding procedure Standard_Output_Available (Self : in out Listener) is use type Ada.Streams.Stream_Element_Count; begin loop declare Data : Ada.Streams.Stream_Element_Array (1 .. 5); Last : Ada.Streams.Stream_Element_Count; Success : Boolean := True; begin Self.Proc.Read_Standard_Output (Data, Last, Success); pragma Assert (Success); exit when Last < Data'First; for Char of Data (1 .. Last) loop if Char not in 16#0D# | 16#0A# then Ada.Strings.Unbounded.Append (Self.Stdout, Character'Val (Char)); end if; end loop; end; end loop; end Standard_Output_Available; overriding procedure Standard_Error_Available (Self : in out Listener) is use type Ada.Streams.Stream_Element_Count; begin loop declare Data : Ada.Streams.Stream_Element_Array (1 .. 5); Last : Ada.Streams.Stream_Element_Count; Success : Boolean := True; begin Self.Proc.Read_Standard_Error (Data, Last, Success); exit when Last < Data'First; for Char of Data (1 .. Last) loop if Char not in 16#0D# | 16#0A# then Ada.Strings.Unbounded.Append (Self.Stderr, Character'Val (Char)); end if; end loop; end; end loop; Self.Proc.Close_Standard_Input; end Standard_Error_Available; overriding procedure Started (Self : in out Listener) is begin Self.Started := True; end Started; overriding procedure Finished (Self : in out Listener; Exit_Status : Spawn.Processes.Process_Exit_Status; Exit_Code : Spawn.Processes.Process_Exit_Code) is use type Spawn.Processes.Process_Exit_Code; begin if Exit_Code /= 9 then Ada.Text_IO.Put_Line ("Unexpected exit code" & (Exit_Code'Img)); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); end if; Self.Stopped := True; end Finished; overriding procedure Error_Occurred (Self : in out Listener; Process_Error : Integer) is begin Ada.Text_IO.Put_Line ("Error_Occurred:" & (Process_Error'Img)); Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure); Self.Stopped := True; Self.Error := Process_Error; end Error_Occurred; end Listeners; Command : constant String := Ada.Directories.Full_Name (Ada.Command_Line.Command_Name); Args : Spawn.String_Vectors.UTF_8_String_Vector; L : aliased Listeners.Listener; begin if Ada.Command_Line.Argument_Count > 0 then Ada.Text_IO.Put_Line (Ada.Text_IO.Get_Line); return; end if; -- Otherwise launch a driven process. Args.Append ("Wait for signal"); L.Proc.Set_Program (Command); L.Proc.Set_Arguments (Args); L.Proc.Set_Working_Directory (Ada.Directories.Current_Directory); L.Proc.Set_Listener (L'Unchecked_Access); L.Proc.Start; while not L.Started loop Spawn.Processes.Monitor_Loop (0.001); end loop; L.Proc.Terminate_Process; while Ada.Strings.Unbounded.Length (L.Stdout) = 0 loop Spawn.Processes.Monitor_Loop (0.001); end loop; L.Proc.Kill_Process; while not L.Stopped loop Spawn.Processes.Monitor_Loop (0.001); end loop; declare Stdout : constant String := Ada.Strings.Unbounded.To_String (L.Stdout); Stderr : constant String := Ada.Strings.Unbounded.To_String (L.Stderr); begin pragma Assert (Stdout = "Got TERM"); pragma Assert (Stderr = ""); pragma Assert (L.Started); pragma Assert (L.Error = 0); end; end Spawn_Kill;
reznikmm/matreshka
Ada
6,086
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Testsuite Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2015, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with League.Unbounded_Integers; with League.Strings; procedure Big_Num_Test is use type League.Strings.Universal_String; use type League.Unbounded_Integers.Unbounded_Integer; Left : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("12345678901234567890"); Right : constant League.Strings.Universal_String := League.Strings.To_Universal_String ("45678901234567890123"); L : constant League.Unbounded_Integers.Unbounded_Integer := League.Unbounded_Integers.From_Universal_String (Left); R : constant League.Unbounded_Integers.Unbounded_Integer := League.Unbounded_Integers.From_Universal_String (Right); V : constant League.Unbounded_Integers.Unbounded_Integer := League.Unbounded_Integers.From_Integer (1_000_000_000); begin if L = R then raise Constraint_Error; elsif L /= L then raise Constraint_Error; elsif R < L then raise Constraint_Error; elsif R <= L then raise Constraint_Error; elsif L > R then raise Constraint_Error; elsif L >= R then raise Constraint_Error; elsif League.Unbounded_Integers.To_Universal_String (-L) /= League.Strings.To_Universal_String ("-12345678901234567890") then raise Constraint_Error; elsif League.Unbounded_Integers.To_Universal_String (L + R) /= League.Strings.To_Universal_String ("58024580135802458013") then raise Constraint_Error; elsif League.Unbounded_Integers.To_Universal_String (R - L) /= League.Strings.To_Universal_String ("33333222333333322233") then raise Constraint_Error; elsif League.Unbounded_Integers.To_Universal_String (L - R) /= League.Strings.To_Universal_String ("-33333222333333322233") then raise Constraint_Error; elsif League.Unbounded_Integers.To_Universal_String (L * R) /= League.Strings.To_Universal_String ("563937047203182456423718379870903950470") then raise Constraint_Error; elsif League.Unbounded_Integers.To_Universal_String (R / L) /= League.Strings.To_Universal_String ("3") then raise Constraint_Error; elsif League.Unbounded_Integers.To_Universal_String (L / R) /= League.Strings.To_Universal_String ("0") then raise Constraint_Error; elsif League.Unbounded_Integers.To_Universal_String (R mod L) /= League.Strings.To_Universal_String ("8641864530864186453") then raise Constraint_Error; elsif L mod R /= L then raise Constraint_Error; elsif League.Unbounded_Integers.To_Universal_String ((L / V) ** 5) /= League.Strings.To_Universal_String ("286797186146124672141322529603829810439261970494501") then raise Constraint_Error; end if; end Big_Num_Test;
reznikmm/matreshka
Ada
4,673
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with XML.DOM.Visitors; with ODF.DOM.Text_Change_Elements; package Matreshka.ODF_Text.Change_Elements is type Text_Change_Element_Node is new Matreshka.ODF_Text.Abstract_Text_Element_Node and ODF.DOM.Text_Change_Elements.ODF_Text_Change with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Text_Change_Element_Node; overriding function Get_Local_Name (Self : not null access constant Text_Change_Element_Node) return League.Strings.Universal_String; overriding procedure Enter_Node (Self : not null access Text_Change_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Leave_Node (Self : not null access Text_Change_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Visit_Node (Self : not null access Text_Change_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); end Matreshka.ODF_Text.Change_Elements;
jpuente/Temperature_Sensor
Ada
2,012
adb
-- test mqtt connection with MQTT_Clients; use MQTT_Clients; with GNAT.Sockets; use GNAT.Sockets; with GNAT.Sockets.MQTT; use GNAT.Sockets.MQTT; with GNAT.Sockets.Server; use GNAT.Sockets.Server; with GNAT.Sockets.Server.Handles; use GNAT.Sockets.Server.Handles; with Ada.Real_Time; use Ada.Real_time; with System.IO; use System.IO; with GNAT.Exception_Traces; procedure Test is Server_Name : constant String := "xxxZZ.dit.upm.es"; Client_Name : constant String := "b318"; Port : constant GNAT.Sockets.Port_Type := 1883; QoS : QoS_Level := Exactly_Once; Topic_Text : constant String := "test/temperature"; Message_text : constant String := "this is a test"; Factory : aliased Connections_Factory; Server : aliased Connections_Server (Factory'Access, 0); Reference : Handle; begin GNAT.Exception_Traces.Trace_On (GNAT.Exception_Traces.Every_Raise); Set (Reference, new MQTT_Client (Listener => Server'Unchecked_Access, Input_Size => 80, Output_Size => 80, Max_Subscribe_Topics => 20)); declare Client : MQTT_Client renames MQTT_Client (Ptr (Reference).all); begin -- connect to server System.IO.Put_Line("Connect to " & Server_Name & ":" & Port'Img); Connect (Server, Client'Unchecked_Access, Server_Name, Port); -- wait for actual connection System.IO.Put_Line("Wait for connection"); while not Is_Connected (Client) loop -- busy waiting --pragma Debug(System.IO.Put(".")); delay until Clock + Milliseconds(100); end loop; delay until Clock+Milliseconds(1000); if Is_Connected(Client) then System.IO.Put_Line("Connected"); else System.IO.Put_Line("Not connected"); end if; end; end Test;
AdaCore/Ada_Drivers_Library
Ada
6,358
ads
-- This spec has been automatically generated from STM32F40x.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with System; -- STM32F40x package STM32_SVD is pragma Preelaborate; -------------------- -- Base addresses -- -------------------- RNG_Base : constant System.Address := System'To_Address (16#50060800#); DCMI_Base : constant System.Address := System'To_Address (16#50050000#); FSMC_Base : constant System.Address := System'To_Address (16#A0000000#); DBG_Base : constant System.Address := System'To_Address (16#E0042000#); DMA2_Base : constant System.Address := System'To_Address (16#40026400#); DMA1_Base : constant System.Address := System'To_Address (16#40026000#); RCC_Base : constant System.Address := System'To_Address (16#40023800#); GPIOI_Base : constant System.Address := System'To_Address (16#40022000#); GPIOH_Base : constant System.Address := System'To_Address (16#40021C00#); GPIOG_Base : constant System.Address := System'To_Address (16#40021800#); GPIOF_Base : constant System.Address := System'To_Address (16#40021400#); GPIOE_Base : constant System.Address := System'To_Address (16#40021000#); GPIOD_Base : constant System.Address := System'To_Address (16#40020C00#); GPIOC_Base : constant System.Address := System'To_Address (16#40020800#); GPIOB_Base : constant System.Address := System'To_Address (16#40020400#); GPIOA_Base : constant System.Address := System'To_Address (16#40020000#); SYSCFG_Base : constant System.Address := System'To_Address (16#40013800#); SPI1_Base : constant System.Address := System'To_Address (16#40013000#); SPI2_Base : constant System.Address := System'To_Address (16#40003800#); SPI3_Base : constant System.Address := System'To_Address (16#40003C00#); I2S2ext_Base : constant System.Address := System'To_Address (16#40003400#); I2S3ext_Base : constant System.Address := System'To_Address (16#40004000#); SDIO_Base : constant System.Address := System'To_Address (16#40012C00#); ADC1_Base : constant System.Address := System'To_Address (16#40012000#); ADC2_Base : constant System.Address := System'To_Address (16#40012100#); ADC3_Base : constant System.Address := System'To_Address (16#40012200#); USART6_Base : constant System.Address := System'To_Address (16#40011400#); USART1_Base : constant System.Address := System'To_Address (16#40011000#); USART2_Base : constant System.Address := System'To_Address (16#40004400#); USART3_Base : constant System.Address := System'To_Address (16#40004800#); DAC_Base : constant System.Address := System'To_Address (16#40007400#); PWR_Base : constant System.Address := System'To_Address (16#40007000#); I2C3_Base : constant System.Address := System'To_Address (16#40005C00#); I2C2_Base : constant System.Address := System'To_Address (16#40005800#); I2C1_Base : constant System.Address := System'To_Address (16#40005400#); IWDG_Base : constant System.Address := System'To_Address (16#40003000#); WWDG_Base : constant System.Address := System'To_Address (16#40002C00#); RTC_Base : constant System.Address := System'To_Address (16#40002800#); UART4_Base : constant System.Address := System'To_Address (16#40004C00#); UART5_Base : constant System.Address := System'To_Address (16#40005000#); C_ADC_Base : constant System.Address := System'To_Address (16#40012300#); TIM1_Base : constant System.Address := System'To_Address (16#40010000#); TIM8_Base : constant System.Address := System'To_Address (16#40010400#); TIM2_Base : constant System.Address := System'To_Address (16#40000000#); TIM3_Base : constant System.Address := System'To_Address (16#40000400#); TIM4_Base : constant System.Address := System'To_Address (16#40000800#); TIM5_Base : constant System.Address := System'To_Address (16#40000C00#); TIM9_Base : constant System.Address := System'To_Address (16#40014000#); TIM12_Base : constant System.Address := System'To_Address (16#40001800#); TIM10_Base : constant System.Address := System'To_Address (16#40014400#); TIM13_Base : constant System.Address := System'To_Address (16#40001C00#); TIM14_Base : constant System.Address := System'To_Address (16#40002000#); TIM11_Base : constant System.Address := System'To_Address (16#40014800#); TIM6_Base : constant System.Address := System'To_Address (16#40001000#); TIM7_Base : constant System.Address := System'To_Address (16#40001400#); Ethernet_MAC_Base : constant System.Address := System'To_Address (16#40028000#); Ethernet_MMC_Base : constant System.Address := System'To_Address (16#40028100#); Ethernet_PTP_Base : constant System.Address := System'To_Address (16#40028700#); Ethernet_DMA_Base : constant System.Address := System'To_Address (16#40029000#); CRC_Base : constant System.Address := System'To_Address (16#40023000#); OTG_FS_GLOBAL_Base : constant System.Address := System'To_Address (16#50000000#); OTG_FS_HOST_Base : constant System.Address := System'To_Address (16#50000400#); OTG_FS_DEVICE_Base : constant System.Address := System'To_Address (16#50000800#); OTG_FS_PWRCLK_Base : constant System.Address := System'To_Address (16#50000E00#); CAN1_Base : constant System.Address := System'To_Address (16#40006400#); CAN2_Base : constant System.Address := System'To_Address (16#40006800#); FLASH_Base : constant System.Address := System'To_Address (16#40023C00#); EXTI_Base : constant System.Address := System'To_Address (16#40013C00#); OTG_HS_GLOBAL_Base : constant System.Address := System'To_Address (16#40040000#); OTG_HS_HOST_Base : constant System.Address := System'To_Address (16#40040400#); OTG_HS_DEVICE_Base : constant System.Address := System'To_Address (16#40040800#); OTG_HS_PWRCLK_Base : constant System.Address := System'To_Address (16#40040E00#); NVIC_Base : constant System.Address := System'To_Address (16#E000E000#); end STM32_SVD;
charlie5/aIDE
Ada
1,685
adb
with AdaM.Factory; package body AdaM.context_Item is -- Storage Pool -- record_Version : constant := 1; pool_Size : constant := 5_000; package Pool is new AdaM.Factory.Pools (".adam-store", "context_Items", pool_Size, record_Version, context_Item.item, context_Item.view); -- Forge -- procedure define (Self : in out Item) is begin null; end define; procedure destruct (Self : in out Item) is begin null; end destruct; function new_Subprogram return View is new_View : constant context_Item.view := Pool.new_Item; begin define (context_Item.item (new_View.all)); return new_View; end new_Subprogram; procedure free (Self : in out context_Item.view) is begin destruct (context_Item.item (Self.all)); Pool.free (Self); end free; -- Attributes -- overriding function Id (Self : access Item) return AdaM.Id is begin return Pool.to_Id (Self); end Id; -- Streams -- procedure View_write (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Self : in View) renames Pool.View_write; procedure View_read (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Self : out View) renames Pool.View_read; end AdaM.context_Item;
stcarrez/ada-wiki
Ada
4,995
adb
----------------------------------------------------------------------- -- wiki-parsers-google -- Google Code parser operations -- Copyright (C) 2011 - 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Wiki.Nodes; with Wiki.Helpers; with Wiki.Parsers.Common; package body Wiki.Parsers.Google is use Wiki.Helpers; use Wiki.Buffers; use type Wiki.Nodes.Node_Kind; procedure Parse_Line (Parser : in out Parser_Type; Text : in Wiki.Buffers.Buffer_Access) is Pos : Natural := 1; C : Wiki.Strings.WChar; Buffer : Wiki.Buffers.Buffer_Access := Text; begin -- Feed the HTML parser if there are some pending state. if not Wiki.Html_Parser.Is_Empty (Parser.Html) then Common.Parse_Html_Element (Parser, Buffer, Pos, Start => False); if Buffer = null then return; end if; end if; if Parser.Pre_Tag_Counter > 0 then Common.Parse_Html_Preformatted (Parser, Buffer, Pos); if Buffer = null then return; end if; end if; if Parser.Current_Node = Nodes.N_PREFORMAT then if Buffer.Content (Pos) = ' ' then Common.Append (Parser.Text, Buffer, Pos + 1); return; end if; Pop_Block (Parser); end if; if Parser.Current_Node = Nodes.N_HEADER then Pop_Block (Parser); end if; C := Buffer.Content (Pos); case C is when CR | LF => Common.Parse_Paragraph (Parser, Buffer, Pos); return; when '=' => Common.Parse_Header (Parser, Buffer, Pos, '='); if Buffer = null then return; end if; when '*' | '#' => if Common.Is_List (Buffer, Pos) then Common.Parse_List (Parser, Buffer, Pos); end if; when others => if Parser.Current_Node /= Nodes.N_PARAGRAPH then Pop_List (Parser); Push_Block (Parser, Nodes.N_PARAGRAPH); end if; end case; Main : while Buffer /= null loop declare Last : constant Natural := Buffer.Last; begin while Pos <= Last loop C := Buffer.Content (Pos); case C is when '_' => Parse_Format (Parser, Buffer, Pos, '_', Wiki.ITALIC); exit Main when Buffer = null; when '*' => Parse_Format (Parser, Buffer, Pos, '*', Wiki.BOLD); exit Main when Buffer = null; when '^' => Parse_Format (Parser, Buffer, Pos, '^', Wiki.SUPERSCRIPT); exit Main when Buffer = null; when '`' => Parse_Format (Parser, Buffer, Pos, '`', Wiki.CODE); exit Main when Buffer = null; when ',' => Parse_Format_Double (Parser, Buffer, Pos, ',', Wiki.SUBSCRIPT); exit Main when Buffer = null; when '~' => Parse_Format_Double (Parser, Buffer, Pos, '~', Wiki.STRIKEOUT); exit Main when Buffer = null; when '[' => Common.Parse_Link (Parser, Buffer, Pos); exit Main when Buffer = null; when '{' => Common.Parse_Template (Parser, Buffer, Pos, '{'); exit Main when Buffer = null; when CR | LF => Append (Parser.Text, ' '); Pos := Pos + 1; when '<' => Common.Parse_Html_Element (Parser, Buffer, Pos, Start => True); exit Main when Buffer = null; when '&' => Common.Parse_Entity (Parser, Buffer, Pos); exit Main when Buffer = null; when others => Append (Parser.Text, C); Pos := Pos + 1; end case; end loop; end; Buffer := Buffer.Next_Block; Pos := 1; end loop Main; end Parse_Line; end Wiki.Parsers.Google;
britown88/todo-helper
Ada
5,187
adb
-- Model IED Simulator -- COL Gene Ressler, 1 December 2007 -- TODO testing123 with Ada.Text_IO; with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; with Ada.Strings.Fixed; use Ada.Strings.Fixed; with Ada.Strings; with Ada.Strings.Bounded; with Binary_Search; with Ada.Containers.Generic_Array_Sort; package body Scanner is Constant_123 : constant Character := Character'Val (16#00#); MAX_KEYWORD_LENGTH_C : constant Natural := 24; New_Constant : constant New_Type := 2; KEYWORDS_C : constant Keyword_Array_T := (To_BS("description"), To_BS("with")); procedure Blah; procedure blah is begin Declaration: declare Joe : Type_Type := Random; begin Do_Something; end Declaration; Loop_ID: loop Loop_Do; exit when 1=2; end loop Loop_ID; if True or else False then Do_This(); elsif not False and then True then Do_That; else Panic; end if; end blah; function "*" (Left, Right : in Integer) return Integer is begin <<Goto_Label>> goto Goto_Label; return Left + Right; end "*"; function Function_Specification (Param_1 : in Blah; Param2, param3 : in access Blah_Type := 0) return It_Type; package Rename_Check renames Ada.Text_IO; type New_Float is delta 0.001 digits 12; package Package_Inst is new Ada.Strings.Bounded.Generic_Bounded_Length (Max => MAX_KEYWORD_LENGTH_C); type Array_Decl12 is array (Positive range <>) of SB.Bounded_String; type Array_Decl3 is array (New_Type range Thing_1 .. Thing_2) of SB.Bounded_String; type Boring_Type is (Start, End_Error); subtype Sub_Type_check is Character range '0' .. '9'; Initialized_Array : constant Transistion_Array_T := (Start => (Letter_Lower | Letter_Upper => Saw_Alpha, ' ' | HT | CR | LF => Start, others => Begin_Error), End_Error => (others => Start) ); type Recorder is record Advance : Boolean; Return_Token : Token_T; end record; for Recorder use 8; type Null_Record is null record; type Discriminated_Record (Size : Natural) is record A : String (1 .. Size); end record; pragma Unchecked_Union (Union); pragma Convention (C, Union); type Person is tagged record Name : String (1 .. 10); Gender : Gender_Type; end record; type Programmer is new Person with record Skilled_In : Language_List; Favorite_Langauge : Python_Type; end record; type Programmer is new Person and Printable with record Skilled_In : Language_List; Blah : aliased Integer; end record; --------------------- -- Scan_Next_Token -- --------------------- task Cyclic_Buffer_Task_Type is entry Insert (An_Item : in Item); entry Remove (An_Item : out Item); end Cyclic_Buffer_Task_Type; task body Cyclic_Buffer_Task_Type is Q_Size : constant := 100; subtype Q_Range is Positive range 1 .. Q_Size; Length : Natural range 0 .. Q_Size := 0; Head, Tail : Q_Range := 1; Data : array (Q_Range) of Item; begin loop select when Length < Q_Size => accept Insert (An_Item : in Item) do Data(Tail) := An_Item; end Insert; Tail := Tail mod Q_Size + 1; Length := Length + 1; or when Length > 0 => accept Remove (An_Item : out Item) do An_Item := Data(Head); end Remove; Head := Head mod Q_Size + 1; Length := Length - 1; end select; end loop; end Cyclic_Buffer_Task_Type; procedure Scan_Next_Token (S : in String; Start_Index : out Positive; End_Index : in out Natural; -- Tricky comment Line_Number : in out Positive; Token : out Token_T); procedure Scan_Next_Token (S : in String; Start_Index : out Positive; End_Index : in out Natural; -- Another comment Line_Number : in out Positive; Token : out Token_T) is begin Scanner_Loop: loop if New_State = End_Error then exit Scanner_Loop; end if; if State = Start and New_State /= Start then Start_Index := Peek_Index; end if; end loop Scanner_Loop; end Scan_Next_Token; procedure Advance is begin Peek_Index := Peek_Index + 1; end Advance; -- Eliminate the leading space that Ada puts in front of positive -- integer images. -- TODO testing123 function Image(N : in Integer) return String is S : String := Integer'Image(N); begin if S(1) = ' ' then return S(2 .. S'Last); end if; return S; end Image; end Scanner;
MinimSecure/unum-sdk
Ada
932
adb
-- Copyright 2015-2016 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. package body Pck is function Ident (R : Record_Type) return Record_Type is begin return R; end Ident; procedure Do_Nothing (A : System.Address) is begin null; end Do_Nothing; end Pck;
jrcarter/Ada_GUI
Ada
6,125
ads
-- -- -- package Copyright (c) Dmitry A. Kazakov -- -- GNAT.Sockets.Connection_State_Machine. Luebeck -- -- Big_Endian.Unsigneds Winter, 2012 -- -- Interface -- -- Last revision : 22:45 07 Apr 2016 -- -- -- -- This library is free software; you can redistribute it and/or -- -- modify it under the terms of the GNU General Public License as -- -- published by the Free Software Foundation; either version 2 of -- -- the License, or (at your option) any later version. This library -- -- is distributed in the hope that it will be useful, but WITHOUT -- -- ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- General Public License for more details. You should have -- -- received a copy of the GNU General Public License along with -- -- this library; if not, write to the Free Software Foundation, -- -- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -- -- -- -- As a special exception, if other files instantiate generics from -- -- this unit, or you link this unit with other files to produce an -- -- executable, this unit does not by itself cause the resulting -- -- executable to be covered by the GNU General Public License. This -- -- exception does not however invalidate any other reasons why the -- -- executable file might be covered by the GNU Public License. -- --____________________________________________________________________-- package GNAT.Sockets.Connection_State_Machine.Big_Endian.Unsigneds is use Interfaces; -- -- Unsigned_{8|16|32|64}_Data_Item -- Big endian-encoded unsigned number -- type Unsigned_8_Data_Item is new Data_Item with record Value : Unsigned_8; end record; type Unsigned_16_Data_Item is new Data_Item with record Value : Unsigned_16; end record; type Unsigned_32_Data_Item is new Data_Item with record Value : Unsigned_32; end record; type Unsigned_64_Data_Item is new Data_Item with record Value : Unsigned_64; end record; -- -- Feed -- Implementation of the feed operation -- procedure Feed ( Item : in out Unsigned_8_Data_Item; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ); procedure Feed ( Item : in out Unsigned_16_Data_Item; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ); procedure Feed ( Item : in out Unsigned_32_Data_Item; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ); procedure Feed ( Item : in out Unsigned_64_Data_Item; Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Client : in out State_Machine'Class; State : in out Stream_Element_Offset ); -- -- Get -- Number from stream element array -- -- Data - The stream element array -- Pointer - The first element to read -- Value - The result -- -- The parameter Pointer is advanced beyond the value obtained -- -- Exceptions : -- -- End_Error - Not enough data -- Layout_Error - Pointer is outside bounds -- procedure Get ( Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Value : out Unsigned_8 ); procedure Get ( Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Value : out Unsigned_16 ); procedure Get ( Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Value : out Unsigned_32 ); procedure Get ( Data : Stream_Element_Array; Pointer : in out Stream_Element_Offset; Value : out Unsigned_64 ); -- -- Put -- Number into stream element array -- -- Data - The stream element array -- Pointer - The first element to write -- Value - The value to encode -- -- The parameter Pointer is advanced beyond the value output -- -- Exceptions : -- -- End_Error - No room for output -- Layout_Error - Pointer is outside bounds -- procedure Put ( Data : in out Stream_Element_Array; Pointer : in out Stream_Element_Offset; Value : Unsigned_8 ); procedure Put ( Data : in out Stream_Element_Array; Pointer : in out Stream_Element_Offset; Value : Unsigned_16 ); procedure Put ( Data : in out Stream_Element_Array; Pointer : in out Stream_Element_Offset; Value : Unsigned_32 ); procedure Put ( Data : in out Stream_Element_Array; Pointer : in out Stream_Element_Offset; Value : Unsigned_64 ); private pragma Assert (Stream_Element'Size = 8); end GNAT.Sockets.Connection_State_Machine.Big_Endian.Unsigneds;
stcarrez/ada-servlet
Ada
2,477
ads
----------------------------------------------------------------------- -- upload_servlet -- Servlet example to upload files on the server -- Copyright (C) 2012, 2018, 2021, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Servlet.Core; with Servlet.Requests; with Servlet.Responses; with Servlet.Streams; package Upload_Servlet is use Servlet; type File_Type is (IMAGE, PDF, TAR_GZ, TAR, ZIP, UNKNOWN); -- Guess a file type depending on a content type or a file name. function Get_File_Type (Content_Type : in String; Name : in String) return File_Type; -- Execute a command and write the result to the output stream. procedure Execute (Command : in String; Output : in out Streams.Print_Stream); -- The <b>Servlet</b> represents the component that will handle -- an HTTP request received by the server. type Servlet is new Core.Servlet with null record; -- Called by the servlet container when a GET request is received. -- Display the upload form page. overriding procedure Do_Get (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); -- Called by the servlet container when a POST request is received. -- Receives the uploaded files and identify them using some external command. overriding procedure Do_Post (Server : in Servlet; Request : in out Requests.Request'Class; Response : in out Responses.Response'Class); private -- Write the upload form page with an optional response message. procedure Write (Response : in out Responses.Response'Class; Message : in String); end Upload_Servlet;
simonjwright/sdlada
Ada
21,329
adb
-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2013-2020, Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- with Ada.Unchecked_Conversion; with System.Address_To_Access_Conversions; with System.Storage_Elements; with SDL.Error; package body SDL.Video.Surfaces is function Pixel_Format (Self : in Surface) return Pixel_Formats.Pixel_Format_Access is begin return Self.Internal.Pixel_Format; end Pixel_Format; function Size (Self : in Surface) return SDL.Sizes is begin return SDL.Sizes'(Self.Internal.Width, Self.Internal.Height); end Size; function Pitch (Self : in Surface) return C.int is begin return Self.Internal.Pitch; end Pitch; function Pixels (Self : in Surface) return System.Address is begin if Must_Lock (Self) and then Self.Internal.Locked <= 0 then raise Surface_Error with "Surface must be locked before access can be gained to the pixel data."; end if; return Self.Internal.Pixels; end Pixels; package body Pixel_Data is use System.Storage_Elements; package Convert is new System.Address_To_Access_Conversions (Object => Element); function Get (Self : in Surface) return Element_Pointer is begin return Element_Pointer (Convert.To_Pointer (Self.Pixels)); end Get; function Get_Row (Self : in Surface; Y : in SDL.Coordinate) return Element_Pointer is begin -- Two conversions required, because there's no legal -- direct conversion from System.Address and arbitrary Pointer. return Element_Pointer (Convert.To_Pointer (Self.Pixels + Storage_Offset (Self.Internal.Pitch) * Storage_Offset (Y))); end Get_Row; end Pixel_Data; package body User_Data is function Convert is new Ada.Unchecked_Conversion (Source => Data_Pointer, Target => User_Data_Pointer); function Convert is new Ada.Unchecked_Conversion (Source => User_Data_Pointer, Target => Data_Pointer); function Get (Self : in Surface) return Data_Pointer is begin return Convert (Self.Internal.User_Data); end Get; procedure Set (Self : in out Surface; Data : in Data_Pointer) is begin Self.Internal.User_Data := Convert (Data); end Set; end User_Data; procedure Blit (Self : in out Surface; Source : in Surface) is function SDL_Blit_Surface (S : in Internal_Surface_Pointer; SR : access Rectangles.Rectangle; D : in Internal_Surface_Pointer; DR : access Rectangles.Rectangle) return C.int with Import => True, Convention => C, External_Name => "SDL_UpperBlit"; -- SDL_BlitSurface is a macro in SDL_surface.h Result : constant C.int := SDL_Blit_Surface (Source.Internal, null, Self.Internal, null); begin if Result /= SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Blit; procedure Blit (Self : in out Surface; Self_Area : in out Rectangles.Rectangle; Source : in Surface; Source_Area : in out Rectangles.Rectangle) is function SDL_Blit_Surface (S : in Internal_Surface_Pointer; SR : access Rectangles.Rectangle; D : in Internal_Surface_Pointer; DR : access Rectangles.Rectangle) return C.int with Import => True, Convention => C, External_Name => "SDL_UpperBlit"; -- SDL_BlitSurface is a macro in SDL_surface.h use type Rectangles.Rectangle; Result : C.int := 0; Src_Area : aliased Rectangles.Rectangle := Source_Area; Dest_Area : aliased Rectangles.Rectangle := Self_Area; begin if Dest_Area = Rectangles.Null_Rectangle then if Src_Area = Rectangles.Null_Rectangle then Result := SDL_Blit_Surface (Source.Internal, null, Self.Internal, null); else Result := SDL_Blit_Surface (Source.Internal, Src_Area'Access, Self.Internal, null); Source_Area := Src_Area; end if; else if Src_Area = Rectangles.Null_Rectangle then Result := SDL_Blit_Surface (Source.Internal, null, Self.Internal, Dest_Area'Access); else Result := SDL_Blit_Surface (Source.Internal, Src_Area'Access, Self.Internal, Dest_Area'Access); Source_Area := Src_Area; end if; Self_Area := Dest_Area; end if; if Result /= SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Blit; procedure Blit_Scaled (Self : in out Surface; Source : in Surface) is function SDL_Blit_Scaled (S : in Internal_Surface_Pointer; SR : access Rectangles.Rectangle; D : in Internal_Surface_Pointer; DR : access Rectangles.Rectangle) return C.int with Import => True, Convention => C, External_Name => "SDL_UpperBlitScaled"; -- SDL_BlitScaled is a macro in SDL_surface.h Result : constant C.int := SDL_Blit_Scaled (Source.Internal, null, Self.Internal, null); begin if Result /= SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Blit_Scaled; -- Blit_Scaled -- -- Self : The destination surface to blit onto. -- Self_Area : The coordinates and size of the area to blit into. -- Source : The surface to blit onto Self. -- Source_Area : The coordinates and size of the area to blit from. procedure Blit_Scaled (Self : in out Surface; Self_Area : in out Rectangles.Rectangle; Source : in Surface; Source_Area : in Rectangles.Rectangle := Rectangles.Null_Rectangle) is function SDL_Blit_Scaled (S : in Internal_Surface_Pointer; SR : access Rectangles.Rectangle; D : in Internal_Surface_Pointer; DR : access Rectangles.Rectangle) return C.int with Import => True, Convention => C, External_Name => "SDL_UpperBlitScaled"; -- SDL_BlitScaled is a macro in SDL_surface.h use type Rectangles.Rectangle; Result : C.int := 0; Area : aliased Rectangles.Rectangle := Self_Area; Src_Area : aliased Rectangles.Rectangle := Source_Area; begin if Self_Area = Rectangles.Null_Rectangle then if Source_Area = Rectangles.Null_Rectangle then Result := SDL_Blit_Scaled (Source.Internal, null, Self.Internal, null); else Result := SDL_Blit_Scaled (Source.Internal, Src_Area'Access, Self.Internal, null); end if; else if Source_Area = Rectangles.Null_Rectangle then Result := SDL_Blit_Scaled (Source.Internal, null, Self.Internal, Area'Access); else Result := SDL_Blit_Scaled (Source.Internal, Src_Area'Access, Self.Internal, Area'Access); end if; Self_Area := Area; end if; if Result /= SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Blit_Scaled; procedure Lower_Blit (Self : in out Surface; Self_Area : in Rectangles.Rectangle; Source : in Surface; Source_Area : in Rectangles.Rectangle) is function SDL_Lower_Blit (S : in Internal_Surface_Pointer; SR : in Rectangles.Rectangle; D : in Internal_Surface_Pointer; DR : in Rectangles.Rectangle) return C.int with Import => True, Convention => C, External_Name => "SDL_LowerBlit"; Result : constant C.int := SDL_Lower_Blit (Source.Internal, Source_Area, Self.Internal, Self_Area); begin if Result /= SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Lower_Blit; procedure Lower_Blit_Scaled (Self : in out Surface; Self_Area : in Rectangles.Rectangle; Source : in Surface; Source_Area : in Rectangles.Rectangle) is function SDL_Lower_Blit_Scaled (S : in Internal_Surface_Pointer; SR : in Rectangles.Rectangle; D : in Internal_Surface_Pointer; DR : in Rectangles.Rectangle) return C.int with Import => True, Convention => C, External_Name => "SDL_LowerBlitScaled"; Result : constant C.int := SDL_Lower_Blit_Scaled (Source.Internal, Source_Area, Self.Internal, Self_Area); begin if Result /= SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Lower_Blit_Scaled; procedure Fill (Self : in out Surface; Area : in Rectangles.Rectangle; Colour : in Interfaces.Unsigned_32) is function SDL_Fill_Rect (S : in Internal_Surface_Pointer; Rect : in Rectangles.Rectangle; Colour : in Interfaces.Unsigned_32) return C.int with Import => True, Convention => C, External_Name => "SDL_FillRect"; Result : constant C.int := SDL_Fill_Rect (Self.Internal, Area, Colour); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Fill; procedure Fill (Self : in out Surface; Areas : in Rectangles.Rectangle_Arrays; Colour : in Interfaces.Unsigned_32) is function SDL_Fill_Rects (S : in Internal_Surface_Pointer; Rects : in Rectangles.Rectangle_Arrays; Count : in C.int; Colour : in Interfaces.Unsigned_32) return C.int with Import => True, Convention => C, External_Name => "SDL_FillRects"; Result : constant C.int := SDL_Fill_Rects (Self.Internal, Areas, Areas'Length, Colour); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Fill; function Clip_Rectangle (Self : in Surface) return Rectangles.Rectangle is procedure SDL_Get_Clip_Rect (S : in Internal_Surface_Pointer; R : out Rectangles.Rectangle) with Import => True, Convention => C, External_Name => "SDL_GetClipRect"; begin return Result : Rectangles.Rectangle := Rectangles.Null_Rectangle do SDL_Get_Clip_Rect (Self.Internal, Result); end return; end Clip_Rectangle; procedure Set_Clip_Rectangle (Self : in out Surface; Now : in Rectangles.Rectangle) is function SDL_Set_Clip_Rect (S : in Internal_Surface_Pointer; R : in Rectangles.Rectangle) return SDL_Bool with Import => True, Convention => C, External_Name => "SDL_SetClipRect"; Result : constant SDL_Bool := SDL_Set_Clip_Rect (S => Self.Internal, R => Now); begin if Result = SDL_False then raise Surface_Error with SDL.Error.Get; end if; end Set_Clip_Rectangle; function Colour_Key (Self : in Surface) return Palettes.Colour is function SDL_Get_Color_Key (S : in Internal_Surface_Pointer; K : out Interfaces.Unsigned_32) return C.int with Import => True, Convention => C, External_Name => "SDL_GetColorKey"; Key : Interfaces.Unsigned_32; Result : constant C.int := SDL_Get_Color_Key (Self.Internal, Key); begin if Result < SDL.Success then -- TODO: The SDL source does not set an error message, see https://bugzilla.libsdl.org/show_bug.cgi?id=3992 raise Surface_Error with "No colour key set for this surface."; -- with SDL.Error.Get; end if; return Pixel_Formats.To_Colour (Pixel => Key, Format => Self.Pixel_Format); end Colour_Key; procedure Set_Colour_Key (Self : in out Surface; Now : in Palettes.Colour; Enable : in Boolean := True) is -- TODO: This can work as an "in out Internal_Surface" as the compiler will pass the object as a reference. -- Should the entire API use this? For review! function SDL_Set_Color_Key (S : in Internal_Surface_Pointer; F : in C.int; K : in Interfaces.Unsigned_32) return C.int with Import => True, Convention => C, External_Name => "SDL_SetColorKey"; Result : constant C.int := SDL_Set_Color_Key (S => Self.Internal, F => (if Enable then 1 else 0), K => Pixel_Formats.To_Pixel (Colour => Now, Format => Self.Pixel_Format)); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Set_Colour_Key; function Alpha_Blend (Self : in Surface) return Palettes.Colour_Component is function SDL_Get_Surface_Alpha_Mod (S : in Internal_Surface_Pointer; A : out Palettes.Colour_Component) return C.int with Import => True, Convention => C, External_Name => "SDL_GetSurfaceAlphaMod"; Alpha : Palettes.Colour_Component; Result : constant C.int := SDL_Get_Surface_Alpha_Mod (S => Self.Internal, A => Alpha); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; return Alpha; end Alpha_Blend; procedure Set_Alpha_Blend (Self : in out Surface; Now : in Palettes.Colour_Component) is function SDL_Set_Surface_Alpha_Mod (S : in Internal_Surface_Pointer; A : in Palettes.Colour_Component) return C.int with Import => True, Convention => C, External_Name => "SDL_SetSurfaceAlphaMod"; Result : constant C.int := SDL_Set_Surface_Alpha_Mod (S => Self.Internal, A => Now); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Set_Alpha_Blend; function Blend_Mode (Self : in Surface) return Blend_Modes is function SDL_Get_Surface_Blend_Mode (S : in Internal_Surface_Pointer; B : out Blend_Modes) return C.int with Import => True, Convention => C, External_Name => "SDL_GetSurfaceAlphaMod"; Blend_Mode : Blend_Modes; Result : constant C.int := SDL_Get_Surface_Blend_Mode (S => Self.Internal, B => Blend_Mode); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; return Blend_Mode; end Blend_Mode; procedure Set_Blend_Mode (Self : in out Surface; Now : in Blend_Modes) is function SDL_Set_Surface_Blend_Mode (S : in Internal_Surface_Pointer; B : in Blend_Modes) return C.int with Import => True, Convention => C, External_Name => "SDL_SetSurfaceBlendMode"; Result : constant C.int := SDL_Set_Surface_Blend_Mode (S => Self.Internal, B => Now); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Set_Blend_Mode; function Colour (Self : in Surface) return Palettes.RGB_Colour is function SDL_Get_Surface_Color_Mod (S : in Internal_Surface_Pointer; R : out Palettes.Colour_Component; G : out Palettes.Colour_Component; B : out Palettes.Colour_Component) return C.int with Import => True, Convention => C, External_Name => "SDL_GetSurfaceColorMod"; Red : Palettes.Colour_Component; Green : Palettes.Colour_Component; Blue : Palettes.Colour_Component; Result : constant C.int := SDL_Get_Surface_Color_Mod (S => Self.Internal, R => Red, G => Green, B => Blue); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; return (Red, Green, Blue); end Colour; procedure Set_Colour (Self : in out Surface; Now : in Palettes.RGB_Colour) is function SDL_Set_Surface_Color_Mod (S : in Internal_Surface_Pointer; R : in Palettes.Colour_Component; G : in Palettes.Colour_Component; B : in Palettes.Colour_Component) return C.int with Import => True, Convention => C, External_Name => "SDL_SetSurfaceColorMod"; Result : constant C.int := SDL_Set_Surface_Color_Mod (S => Self.Internal, R => Now.Red, G => Now.Green, B => Now.Blue); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Set_Colour; procedure Lock (Self : in out Surface) is function SDL_Lock_Surface (Self : in Internal_Surface_Pointer) return C.int with Import => True, Convention => C, External_Name => "SDL_LockSurface"; Result : constant C.int := SDL_Lock_Surface (Self.Internal); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Lock; procedure Unlock (Self : in out Surface) is procedure SDL_Unlock_Surface (Self : in Internal_Surface_Pointer) with Import => True, Convention => C, External_Name => "SDL_UnlockSurface"; begin SDL_Unlock_Surface (Self.Internal); end Unlock; procedure Set_RLE (Self : in out Surface; Enabled : in Boolean) is function SDL_Set_Surface_RLE (Self : in Internal_Surface_Pointer; Enabled : in C.int) return C.int with Import => True, Convention => C, External_Name => "SDL_SetSurfaceRLE"; Result : constant C.int := SDL_Set_Surface_RLE (Self.Internal, C.int (if Enabled then 1 else 0)); begin if Result < SDL.Success then raise Surface_Error with SDL.Error.Get; end if; end Set_RLE; -- This is equivalent to the macro SDL_MUSTLOCK in SDL_surface.h. function Must_Lock (Self : in Surface) return Boolean is begin return (Self.Internal.Flags and RLE_Encoded) = RLE_Encoded; end Must_Lock; overriding procedure Adjust (Self : in out Surface) is begin -- if Self.Internal.Flags and Dont_Free = Dont_Free then -- end if; if Self.Internal /= null and Self.Owns then Self.Internal.Reference_Count := Self.Internal.Reference_Count + 1; end if; end Adjust; overriding procedure Finalize (Self : in out Surface) is procedure SDL_Free_Surface (S : in Internal_Surface_Pointer) with Import => True, Convention => C, External_Name => "SDL_FreeSurface"; begin if Self.Internal /= null and then Self.Owns then SDL_Free_Surface (Self.Internal); end if; end Finalize; end SDL.Video.Surfaces;
iyan22/AprendeAda
Ada
536
adb
with Datos; use Datos; function Media ( L : Lista ) return Float is -- pre: Dada una lista, calcular la media de sus valores -- post: La media de los valores de la lista Suma / longitud numelementos : Natural; acumulador : Float; LCopia : Lista; begin numelementos := 0; acumulador := 0.0; LCopia := L; while LCopia /= null loop numelementos := numelementos+1; acumulador := acumulador + Float(LCopia.all.info); LCopia := LCopia.all.sig; end loop; return acumulador / Float(numelementos); end Media;
sonneveld/adazmq
Ada
502
ads
with ZMQ; package ZHelper is function Rand_Of (First : Integer; Last : Integer) return Integer; function Rand_Of (First : Float; Last : Float) return Float; -- Provide random number from First .. Last procedure Dump (S : ZMQ.Socket_Type'Class); -- Receives all message parts from socket, prints neatly function Set_Id (S : ZMQ.Socket_Type'Class) return String; procedure Set_Id (S : ZMQ.Socket_Type'Class); -- Set simple random printable identity on socket end ZHelper;
reznikmm/matreshka
Ada
3,729
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with XML.DOM.Attributes; package ODF.DOM.Text_Track_Changes_Attributes is pragma Preelaborate; type ODF_Text_Track_Changes_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Text_Track_Changes_Attribute_Access is access all ODF_Text_Track_Changes_Attribute'Class with Storage_Size => 0; end ODF.DOM.Text_Track_Changes_Attributes;
AdaCore/gpr
Ada
2,482
ads
------------------------------------------------------------------------------ -- -- -- GPR2 PROJECT MANAGER -- -- -- -- Copyright (C) 2019-2023, AdaCore -- -- -- -- This is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. This software is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public -- -- License for more details. You should have received a copy of the GNU -- -- General Public License distributed with GNAT; see file COPYING. If not, -- -- see <http://www.gnu.org/licenses/>. -- -- -- ------------------------------------------------------------------------------ with GNAT.OS_Lib; private with Ada.Strings.Unbounded; private with GPR2.Path_Name.Set; package GPRinstall is DS : constant Character := GNAT.OS_Lib.Directory_Separator; private Sig_Line : constant String := "S "; -- The prefix of the line containing the original project's signature Search_Paths : GPR2.Path_Name.Set.Object; procedure Delete_Empty_Directory (Prefix, Dir_Name : String); -- Delete Dir_Name if empty, if removed try with parent directory but not -- above the given prefix. GPRinstall_Error : exception; -- General GPRinstall exception that is supposed to have associated error -- message attached. GPRinstall_Error_No_Message : exception; -- Special exception for cases that require multiple line diagnostics -- that are supposed to be printed before raising the exception. function "-" (S : Ada.Strings.Unbounded.Unbounded_String) return String renames Ada.Strings.Unbounded.To_String; function "-" (S : String) return Ada.Strings.Unbounded.Unbounded_String renames Ada.Strings.Unbounded.To_Unbounded_String; end GPRinstall;
reznikmm/matreshka
Ada
4,623
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Draw.Symbol_Color_Attributes is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Draw_Symbol_Color_Attribute_Node is begin return Self : Draw_Symbol_Color_Attribute_Node do Matreshka.ODF_Draw.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Draw_Prefix); end return; end Create; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Draw_Symbol_Color_Attribute_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Symbol_Color_Attribute; end Get_Local_Name; begin Matreshka.DOM_Documents.Register_Attribute (Matreshka.ODF_String_Constants.Draw_URI, Matreshka.ODF_String_Constants.Symbol_Color_Attribute, Draw_Symbol_Color_Attribute_Node'Tag); end Matreshka.ODF_Draw.Symbol_Color_Attributes;
ekoeppen/STM32_Generic_Ada_Drivers
Ada
6,646
ads
pragma Style_Checks (Off); -- This spec has been automatically generated from STM32L0x1.svd pragma Restrictions (No_Elaboration_Code); with System; package STM32_SVD.MPU is pragma Preelaborate; --------------- -- Registers -- --------------- subtype MPU_TYPER_SEPARATE_Field is STM32_SVD.Bit; subtype MPU_TYPER_DREGION_Field is STM32_SVD.Byte; subtype MPU_TYPER_IREGION_Field is STM32_SVD.Byte; -- MPU type register type MPU_TYPER_Register is record -- Read-only. Separate flag SEPARATE_k : MPU_TYPER_SEPARATE_Field; -- unspecified Reserved_1_7 : STM32_SVD.UInt7; -- Read-only. Number of MPU data regions DREGION : MPU_TYPER_DREGION_Field; -- Read-only. Number of MPU instruction regions IREGION : MPU_TYPER_IREGION_Field; -- unspecified Reserved_24_31 : STM32_SVD.Byte; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for MPU_TYPER_Register use record SEPARATE_k at 0 range 0 .. 0; Reserved_1_7 at 0 range 1 .. 7; DREGION at 0 range 8 .. 15; IREGION at 0 range 16 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype MPU_CTRL_ENABLE_Field is STM32_SVD.Bit; subtype MPU_CTRL_HFNMIENA_Field is STM32_SVD.Bit; subtype MPU_CTRL_PRIVDEFENA_Field is STM32_SVD.Bit; -- MPU control register type MPU_CTRL_Register is record -- Read-only. Enables the MPU ENABLE : MPU_CTRL_ENABLE_Field; -- Read-only. Enables the operation of MPU during hard fault HFNMIENA : MPU_CTRL_HFNMIENA_Field; -- Read-only. Enable priviliged software access to default memory map PRIVDEFENA : MPU_CTRL_PRIVDEFENA_Field; -- unspecified Reserved_3_31 : STM32_SVD.UInt29; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for MPU_CTRL_Register use record ENABLE at 0 range 0 .. 0; HFNMIENA at 0 range 1 .. 1; PRIVDEFENA at 0 range 2 .. 2; Reserved_3_31 at 0 range 3 .. 31; end record; subtype MPU_RNR_REGION_Field is STM32_SVD.Byte; -- MPU region number register type MPU_RNR_Register is record -- MPU region REGION : MPU_RNR_REGION_Field := 16#0#; -- unspecified Reserved_8_31 : STM32_SVD.UInt24 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for MPU_RNR_Register use record REGION at 0 range 0 .. 7; Reserved_8_31 at 0 range 8 .. 31; end record; subtype MPU_RBAR_REGION_Field is STM32_SVD.UInt4; subtype MPU_RBAR_VALID_Field is STM32_SVD.Bit; subtype MPU_RBAR_ADDR_Field is STM32_SVD.UInt27; -- MPU region base address register type MPU_RBAR_Register is record -- MPU region field REGION : MPU_RBAR_REGION_Field := 16#0#; -- MPU region number valid VALID : MPU_RBAR_VALID_Field := 16#0#; -- Region base address field ADDR : MPU_RBAR_ADDR_Field := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for MPU_RBAR_Register use record REGION at 0 range 0 .. 3; VALID at 0 range 4 .. 4; ADDR at 0 range 5 .. 31; end record; subtype MPU_RASR_ENABLE_Field is STM32_SVD.Bit; subtype MPU_RASR_SIZE_Field is STM32_SVD.UInt5; subtype MPU_RASR_SRD_Field is STM32_SVD.Byte; subtype MPU_RASR_B_Field is STM32_SVD.Bit; subtype MPU_RASR_C_Field is STM32_SVD.Bit; subtype MPU_RASR_S_Field is STM32_SVD.Bit; subtype MPU_RASR_TEX_Field is STM32_SVD.UInt3; subtype MPU_RASR_AP_Field is STM32_SVD.UInt3; subtype MPU_RASR_XN_Field is STM32_SVD.Bit; -- MPU region attribute and size register type MPU_RASR_Register is record -- Region enable bit. ENABLE : MPU_RASR_ENABLE_Field := 16#0#; -- Size of the MPU protection region SIZE : MPU_RASR_SIZE_Field := 16#0#; -- unspecified Reserved_6_7 : STM32_SVD.UInt2 := 16#0#; -- Subregion disable bits SRD : MPU_RASR_SRD_Field := 16#0#; -- memory attribute B : MPU_RASR_B_Field := 16#0#; -- memory attribute C : MPU_RASR_C_Field := 16#0#; -- Shareable memory attribute S : MPU_RASR_S_Field := 16#0#; -- memory attribute TEX : MPU_RASR_TEX_Field := 16#0#; -- unspecified Reserved_22_23 : STM32_SVD.UInt2 := 16#0#; -- Access permission AP : MPU_RASR_AP_Field := 16#0#; -- unspecified Reserved_27_27 : STM32_SVD.Bit := 16#0#; -- Instruction access disable bit XN : MPU_RASR_XN_Field := 16#0#; -- unspecified Reserved_29_31 : STM32_SVD.UInt3 := 16#0#; end record with Volatile_Full_Access, Object_Size => 32, Bit_Order => System.Low_Order_First; for MPU_RASR_Register use record ENABLE at 0 range 0 .. 0; SIZE at 0 range 1 .. 5; Reserved_6_7 at 0 range 6 .. 7; SRD at 0 range 8 .. 15; B at 0 range 16 .. 16; C at 0 range 17 .. 17; S at 0 range 18 .. 18; TEX at 0 range 19 .. 21; Reserved_22_23 at 0 range 22 .. 23; AP at 0 range 24 .. 26; Reserved_27_27 at 0 range 27 .. 27; XN at 0 range 28 .. 28; Reserved_29_31 at 0 range 29 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Memory protection unit type MPU_Peripheral is record -- MPU type register MPU_TYPER : aliased MPU_TYPER_Register; -- MPU control register MPU_CTRL : aliased MPU_CTRL_Register; -- MPU region number register MPU_RNR : aliased MPU_RNR_Register; -- MPU region base address register MPU_RBAR : aliased MPU_RBAR_Register; -- MPU region attribute and size register MPU_RASR : aliased MPU_RASR_Register; end record with Volatile; for MPU_Peripheral use record MPU_TYPER at 16#0# range 0 .. 31; MPU_CTRL at 16#4# range 0 .. 31; MPU_RNR at 16#8# range 0 .. 31; MPU_RBAR at 16#C# range 0 .. 31; MPU_RASR at 16#10# range 0 .. 31; end record; -- Memory protection unit MPU_Periph : aliased MPU_Peripheral with Import, Address => MPU_Base; end STM32_SVD.MPU;
stcarrez/ada-asf
Ada
4,332
ads
----------------------------------------------------------------------- -- asf-validators-texts -- ASF Texts Validators -- Copyright (C) 2011, 2020, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with GNAT.Regpat; with EL.Objects; with ASF.Components.Base; with ASF.Contexts.Faces; -- == Length validator == -- The `ASF.Validators.Texts.Length_Validator` implements the validator for the -- `<f:validateLength>` XHTML validator. -- -- == Regex validator == -- The `ASF.Validators.Texts.Regex_Validator` implements the validator for the -- `<f:validateRegex>` XHTML validator. -- package ASF.Validators.Texts is MAXIMUM_MESSAGE_ID : constant String := "asf.validators.length.maximum"; MINIMUM_MESSAGE_ID : constant String := "asf.validators.length.minimum"; REGEX_MESSAGE_ID : constant String := "asf.validators.regex"; -- ------------------------------ -- Length_Validator -- ------------------------------ -- The <b>Length_Validator</b> implements the length validator whereby the given -- value must have a minimum length and a maximum length. type Length_Validator is new Validator with private; type Length_Validator_Access is access all Length_Validator'Class; -- Create a length validator. function Create_Length_Validator (Minimum : in Natural; Maximum : in Natural) return Validator_Access; -- Verify that the value's length is between the validator minimum and maximum -- boundaries. -- If some error are found, the procedure should create a <b>FacesMessage</b> -- describing the problem and add that message to the current faces context. -- The procedure can examine the state and modify the component tree. -- It must raise the <b>Invalid_Value</b> exception if the value is not valid. overriding procedure Validate (Valid : in Length_Validator; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Component : in out ASF.Components.Base.UIComponent'Class; Value : in EL.Objects.Object); -- ------------------------------ -- Regex_Validator -- ------------------------------ -- The <b>Regex_Validator</b> implements the regular expression validator -- whereby the given value must match a regular expression. type Regex_Validator (Size : GNAT.Regpat.Program_Size) is new Validator with private; type Regex_Validator_Access is access all Regex_Validator'Class; -- Create a regex validator. function Create_Regex_Validator (Pattern : in GNAT.Regpat.Pattern_Matcher) return Validator_Access; -- Verify that the value matches the regular expression. -- If some error are found, the procedure should create a <b>FacesMessage</b> -- describing the problem and add that message to the current faces context. -- The procedure can examine the state and modify the component tree. -- It must raise the <b>Invalid_Value</b> exception if the value is not valid. overriding procedure Validate (Valid : in Regex_Validator; Context : in out ASF.Contexts.Faces.Faces_Context'Class; Component : in out ASF.Components.Base.UIComponent'Class; Value : in EL.Objects.Object); private type Length_Validator is new Validator with record Minimum : Natural; Maximum : Natural; end record; type Regex_Validator (Size : GNAT.Regpat.Program_Size) is new Validator with record Pattern : GNAT.Regpat.Pattern_Matcher (Size); end record; end ASF.Validators.Texts;
kontena/ruby-packer
Ada
6,878
adb
------------------------------------------------------------------------------ -- -- -- GNAT ncurses Binding Samples -- -- -- -- ncurses -- -- -- -- B O D Y -- -- -- ------------------------------------------------------------------------------ -- Copyright (c) 2000-2014,2015 Free Software Foundation, Inc. -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining a -- -- copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, distribute with modifications, sublicense, and/or sell -- -- copies of the Software, and to permit persons to whom the Software is -- -- furnished to do so, subject to the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be included -- -- in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -- -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR -- -- THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- -- -- Except as contained in this notice, the name(s) of the above copyright -- -- holders shall not be used in advertising or otherwise to promote the -- -- sale, use or other dealings in this Software without prior written -- -- authorization. -- ------------------------------------------------------------------------------ -- Author: Eugene V. Melaragno <[email protected]> 2000 -- Version Control -- $Revision: 1.7 $ -- $Date: 2015/07/25 23:43:19 $ -- Binding Version 01.00 ------------------------------------------------------------------------------ with ncurses2.util; use ncurses2.util; with Terminal_Interface.Curses; use Terminal_Interface.Curses; -- test effects of overlapping windows procedure ncurses2.overlap_test is procedure fillwin (win : Window; ch : Character); procedure crosswin (win : Window; ch : Character); procedure fillwin (win : Window; ch : Character) is y1 : Line_Position; x1 : Column_Position; begin Get_Size (win, y1, x1); for y in 0 .. y1 - 1 loop Move_Cursor (win, y, 0); for x in 0 .. x1 - 1 loop Add (win, Ch => ch); end loop; end loop; exception when Curses_Exception => null; -- write to lower right corner end fillwin; procedure crosswin (win : Window; ch : Character) is y1 : Line_Position; x1 : Column_Position; begin Get_Size (win, y1, x1); for y in 0 .. y1 - 1 loop for x in 0 .. x1 - 1 loop if ((x > (x1 - 1) / 3) and (x <= (2 * (x1 - 1)) / 3)) or (((y > (y1 - 1) / 3) and (y <= (2 * (y1 - 1)) / 3))) then Move_Cursor (win, y, x); Add (win, Ch => ch); end if; end loop; end loop; end crosswin; -- In a 24x80 screen like some xterms are, the instructions will -- be overwritten. ch : Character; win1 : Window := New_Window (9, 20, 3, 3); win2 : Window := New_Window (9, 20, 9, 16); begin Set_Raw_Mode (SwitchOn => True); Refresh; Move_Cursor (Line => 0, Column => 0); Add (Str => "This test shows the behavior of wnoutrefresh() with " & "respect to"); Add (Ch => newl); Add (Str => "the shared region of two overlapping windows A and B. " & "The cross"); Add (Ch => newl); Add (Str => "pattern in each window does not overlap the other."); Add (Ch => newl); Move_Cursor (Line => 18, Column => 0); Add (Str => "a = refresh A, then B, then doupdate. b = refresh B, " & "then A, then doupdate"); Add (Ch => newl); Add (Str => "c = fill window A with letter A. d = fill window B " & "with letter B."); Add (Ch => newl); Add (Str => "e = cross pattern in window A. f = cross pattern " & "in window B."); Add (Ch => newl); Add (Str => "g = clear window A. h = clear window B."); Add (Ch => newl); Add (Str => "i = overwrite A onto B. j = overwrite " & "B onto A."); Add (Ch => newl); Add (Str => "^Q/ESC = terminate test."); loop ch := Code_To_Char (Getchar); exit when ch = CTRL ('Q') or ch = CTRL ('['); -- QUIT or ESCAPE case ch is when 'a' => -- refresh window A first, then B Refresh_Without_Update (win1); Refresh_Without_Update (win2); Update_Screen; when 'b' => -- refresh window B first, then A Refresh_Without_Update (win2); Refresh_Without_Update (win1); Update_Screen; when 'c' => -- fill window A so it's visible fillwin (win1, 'A'); when 'd' => -- fill window B so it's visible fillwin (win2, 'B'); when 'e' => -- cross test pattern in window A crosswin (win1, 'A'); when 'f' => -- cross test pattern in window B crosswin (win2, 'B'); when 'g' => -- clear window A Clear (win1); Move_Cursor (win1, 0, 0); when 'h' => -- clear window B Clear (win2); Move_Cursor (win2, 0, 0); when 'i' => -- overwrite A onto B Overwrite (win1, win2); when 'j' => -- overwrite B onto A Overwrite (win2, win1); when others => null; end case; end loop; Delete (win2); Delete (win1); Erase; End_Windows; end ncurses2.overlap_test;
zhmu/ananas
Ada
275
ads
package Opt90b_Pkg is type Rec is record A : Short_Short_Integer; B : Integer; C : Short_Integer; D : String (1 .. 12); end record; pragma Pack (Rec); for Rec'Alignment use 1; type Data is tagged record R : Rec; end record; end Opt90b_Pkg;
AdaCore/Ada_Drivers_Library
Ada
2,430
ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2022, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with MCP23x17.I2C; package MCP23017 renames MCP23x17.I2C;
pat-rogers/LmcpGen
Ada
2,430
ads
with -<full_parent_datatype_package>-; use -<full_parent_datatype_package>-; with -<full_series_name_dots>-.enumerations; use -<full_series_name_dots>-.enumerations; with avtas.lmcp.byteBuffers; use avtas.lmcp.byteBuffers; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Streams; with Ada.Containers.Indefinite_Vectors; -<with_all_field_types>- package -<full_series_name_dots>-.-<datatype_name>- is type -<datatype_name>- is new -<full_parent_datatype>- with private; type -<datatype_name>-_Acc is access all -<datatype_name>-; type -<datatype_name>-_Any is access all -<datatype_name>-'Class; Subscription : constant String := "-<full_datatype_name_dots>-"; TypeName : constant String := "-<datatype_name>-"; SeriesName : constant String := "-<series_name>-"; TypeId : constant := -<series_name>-Enum'Pos(-<datatype_name_caps>-_ENUM) + 1; -- The other languages start their enums at 1, whereas Ada starts at 0, -- so add 1. This is critical in the case statement (switch) in the -- factories so that an object of the right subclass is created. -<vector_package_import>- overriding function getFullLmcpTypeName(this : -<datatype_name>-) return String is (Subscription); overriding function getLmcpTypeName(this : -<datatype_name>-) return String is (TypeName); overriding function getLmcpType(this : -<datatype_name>-) return UInt32 is (TypeId); -<get_and_set_methods_spec>- overriding function calculatePackedSize(this: -<datatype_name>-) return UInt32; overriding procedure Pack (This : -<datatype_name>-; Buffer : in out ByteBuffer); overriding procedure Unpack (This : out -<datatype_name>-; Buffer : in out ByteBuffer); --function toString(this : -<datatype_name>-; depth : Integer) return String; package String_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => String); -- TODO: move to a single, shared instantiation function -<datatype_name>-_Descendants return String_Vectors.Vector; private type -<datatype_name>- is new -<full_parent_datatype>- with record -<record_fields>- end record; overriding procedure XML_Write (this : -<datatype_name>-; S : access Ada.Streams.Root_Stream_Type'Class; Level : Natural); end -<full_series_name_dots>-.-<datatype_name>-;
jamiepg1/sdlada
Ada
5,775
adb
-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2014 Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- with Interfaces.C; with Interfaces.C.Strings; package body SDL.Log is package C renames Interfaces.C; procedure Put (Message : in String) is procedure SDL_Log (Message : in C.char_array) with Import => True, Convention => C, External_Name => "SDL_Log"; begin SDL_Log (C.To_C (Message)); end Put; procedure Put (Message : in String; Category : in Categories; Priority : in Priorities) is procedure SDL_Log (Category : in Categories; Priority : in Priorities; Message : in C.char_array) with Import => True, Convention => C, External_Name => "SDL_LogMessage"; begin SDL_Log (Category, Priority, C.To_C (Message)); end Put; procedure Put_Critical (Message : in String; Category : in Categories := Application) is procedure SDL_Log (Category : in Categories; Message : in C.char_array) with Import => True, Convention => C, External_Name => "SDL_LogCritical"; begin SDL_Log (Category, C.To_C (Message)); end Put_Critical; procedure Put_Debug (Message : in String; Category : in Categories := Application) is procedure SDL_Log (Category : in Categories; Message : in C.char_array) with Import => True, Convention => C, External_Name => "SDL_LogDebug"; begin SDL_Log (Category, C.To_C (Message)); end Put_Debug; procedure Put_Error (Message : in String; Category : in Categories := Application) is procedure SDL_Log (Category : in Categories; Message : in C.char_array) with Import => True, Convention => C, External_Name => "SDL_LogError"; begin SDL_Log (Category, C.To_C (Message)); end Put_Error; procedure Put_Info (Message : in String; Category : in Categories := Application) is procedure SDL_Log (Category : in Categories; Message : in C.char_array) with Import => True, Convention => C, External_Name => "SDL_LogInfo"; begin SDL_Log (Category, C.To_C (Message)); end Put_Info; procedure Put_Verbose (Message : in String; Category : in Categories := Application) is procedure SDL_Log (Category : in Categories; Message : in C.char_array) with Import => True, Convention => C, External_Name => "SDL_LogVerbose"; begin SDL_Log (Category, C.To_C (Message)); end Put_Verbose; procedure Put_Warn (Message : in String; Category : in Categories := Application) is procedure SDL_Log (Category : in Categories; Message : in C.char_array) with Import => True, Convention => C, External_Name => "SDL_LogWarn"; begin SDL_Log (Category, C.To_C (Message)); end Put_Warn; procedure Reset_Priorities is procedure SDL_Reset_Priorities with Import => True, Convention => C, External_Name => "SDL_LogResetPriorities"; begin SDL_Reset_Priorities; end Reset_Priorities; procedure Set (Priority : in Priorities) is procedure SDL_Set_All_Priorities (Priority : in Priorities) with Import => True, Convention => C, External_Name => "SDL_LogSetAllPriority"; begin SDL_Set_All_Priorities (Priority); end Set; procedure Set (Category : in Categories; Priority : in Priorities) is procedure SDL_Set_Priority (Category : in Categories; Priority : in Priorities) with Import => True, Convention => C, External_Name => "SDL_LogSetPriority"; begin SDL_Set_Priority (Category, Priority); end Set; -- Logging. -- A local record type which gets initialised with an access to callback -- and a copy to the actual user data. type Local_User_Data is record Callback : Output_Callback; Data : Root_User_Data; end record with Convention => C; procedure Local_Callback (User_Data : in Local_User_Data; Category : in Categories; Priority : in Priorities; Message : in C.Strings.chars_ptr) with Convention => C; procedure Local_Callback (User_Data : in Local_User_Data; Category : in Categories; Priority : in Priorities; Message : in C.Strings.chars_ptr) is begin -- Call the Ada callback now. User_Data.Callback (User_Data.Data, Category, Priority, C.Strings.Value (Message)); end Local_Callback; end SDL.Log;
reznikmm/matreshka
Ada
3,691
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with XML.DOM.Attributes; package ODF.DOM.Attributes.Style.Default_Outline_Level is type ODF_Style_Default_Outline_Level is new XML.DOM.Attributes.DOM_Attribute with private; private type ODF_Style_Default_Outline_Level is new XML.DOM.Attributes.DOM_Attribute with null record; end ODF.DOM.Attributes.Style.Default_Outline_Level;
zhmu/ananas
Ada
3,225
ads
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . P A C K _ 0 7 -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2022, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Handling of packed arrays with Component_Size = 7 package System.Pack_07 is pragma Preelaborate; Bits : constant := 7; type Bits_07 is mod 2 ** Bits; for Bits_07'Size use Bits; -- In all subprograms below, Rev_SSO is set True if the array has the -- non-default scalar storage order. function Get_07 (Arr : System.Address; N : Natural; Rev_SSO : Boolean) return Bits_07 with Inline; -- Arr is the address of the packed array, N is the zero-based -- subscript. This element is extracted and returned. procedure Set_07 (Arr : System.Address; N : Natural; E : Bits_07; Rev_SSO : Boolean) with Inline; -- Arr is the address of the packed array, N is the zero-based -- subscript. This element is set to the given value. end System.Pack_07;
jhumphry/PRNG_Zoo
Ada
4,309
adb
-- -- PRNG Zoo -- Copyright (c) 2014 - 2015, James Humphry -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -- OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -- PERFORMANCE OF THIS SOFTWARE. with PRNG_Zoo.Stats; package body PRNG_Zoo.Tests.EquiDist is ----------- -- Reset -- ----------- procedure Reset (T : in out EquiDist) is Num_Bins : constant Natural := 2**(T.t * T.l); begin if T.l >= T.n then raise Constraint_Error with "Cannot have finer subdivisions per dimension than the number of input bits"; end if; T.next_dimension := 1; T.current := (others => 0); if T.bins = null then T.bins := new Counter_array(1..Num_Bins); end if; if T.bins'Length /= Num_Bins then raise Constraint_Error with "Somehow an incorrect number of bins have been allocated."; end if; T.bins.all := (others => 0); T.chi2_cdf_result := -1.0; end Reset; ---------- -- Feed -- ---------- procedure Feed (T : in out EquiDist; X : in U64) is stride : Positive; position : Natural; begin T.current(T.next_dimension) := Shift_Right((X and T.mask), T.n-T.l); if T.next_dimension = T.t then stride := 1; position := 0; for I in T.current'Range loop position := position + Natural(T.current(I)) * stride; stride := stride * 2 ** T.l; end loop; T.bins(position+1) := T.bins(position+1) + 1; T.next_dimension := 1; else T.next_dimension := T.next_dimension + 1; end if; end Feed; -------------------- -- Compute_Result -- -------------------- procedure Compute_Result(T : in out EquiDist) is N : constant Positive := 2 ** (T.t * T.l); Expected : constant Long_Float := 1.0 / Long_Float(N); B : Binned(N); begin B.Bin_Counts := T.bins.all; B.Bin_Expected := (others => Expected); B.Distribution_DF := 1; T.chi2_cdf_result := Stats.Chi2_CDF_Bins(B); end Compute_Result; ------------------ -- Result_Ready -- ------------------ function Result_Ready(T: EquiDist) return Boolean is begin return T.chi2_cdf_result /= -1.0; end Result_Ready; ------------ -- Passed -- ------------ function Passed (T : in EquiDist; p : in Long_Float := 0.01) return Boolean is begin return T.chi2_cdf_result > p and T.chi2_cdf_result < (1.0-p); end Passed; ------- -- p -- ------- function p (T : in EquiDist) return Long_Float is begin return T.chi2_cdf_result; end p; --------------------- -- Describe_Result -- --------------------- function Describe_Result (T : in EquiDist) return String is begin return "Chi2 Equidistribution test (" & Integer'Image(T.t) & "," & Integer'Image(T.l) & ") with result := " & Long_Float'Image(T.chi2_cdf_result); end Describe_Result; ------------------- -- Make_EquiDist -- ------------------- function Make_EquiDist (t, l: Positive; n : Positive := 64) return EquiDist is Num_Bins : constant Natural := 2**(t * l); begin if l >= n then raise Constraint_Error with "Cannot have finer subdivisions per dimension than the number of input bits"; end if; return Result: EquiDist(t, l, n) do Result.next_dimension := 1; Result.current := (others => 0); Result.bins := new Counter_array(1..Num_Bins); Result.bins.all := (others => 0); Result.chi2_cdf_result := -1.0; end return; end Make_EquiDist; end PRNG_Zoo.Tests.EquiDist;
reznikmm/clic
Ada
1,226
ads
with AAA.Strings; with CLIC.Subcommand; package CLIC_Ex.Commands.TTY is type Instance is new CLIC.Subcommand.Command with private; overriding function Name (Cmd : Instance) return CLIC.Subcommand.Identifier is ("tty"); overriding function Switches_As_Args (This : Instance) return Boolean is (False); overriding procedure Execute (Cmd : in out Instance; Args : AAA.Strings.Vector); overriding function Long_Description (Cmd : Instance) return AAA.Strings.Vector is (AAA.Strings.Empty_Vector .Append ("Long description of the TTY command.") .Append ("Multiple lines:") .Append (" - 1") .Append (" - 2") .Append (" - 3") ); overriding procedure Setup_Switches (Cmd : in out Instance; Config : in out CLIC.Subcommand.Switches_Configuration); overriding function Short_Description (Cmd : Instance) return String is ("Show tty colors"); overriding function Usage_Custom_Parameters (Cmd : Instance) return String is (""); private type Instance is new CLIC.Subcommand.Command with record Blink : aliased Boolean; end record; end CLIC_Ex.Commands.TTY;
AdaCore/libadalang
Ada
146
ads
with Base; package Test_Pkg is type A is new Base.Base_Type with null record; function My_Method (Self : A) return Integer; end Test_Pkg;
dan76/Amass
Ada
3,428
ads
-- Copyright © by Jeff Foley 2017-2023. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. -- SPDX-License-Identifier: Apache-2.0 local json = require("json") name = "Spamhaus" type = "api" function start() set_rate_limit(1) end function check() local c local cfg = datasrc_config() if (cfg ~= nil) then c = cfg.credentials end if (c ~= nil and c.username ~= nil and c.password ~= nil and c.username ~= "" and c.password ~= "") then return true end return false end function vertical(ctx, domain) local c local cfg = datasrc_config() if (cfg ~= nil) then c = cfg.credentials end if (c == nil or c.username == nil or c.username == "" or c.password == nil or c.password == "") then return end local token = bearer_token(ctx, c.username, c.password) if (token == "") then return end local resp, err = request(ctx, { ['url']=build_url(domain), ['header']={ ['Accept']="application/json", ['Content-Type']="application/json", ['Authorization']="Bearer " .. token, }, }) if (err ~= nil and err ~= "") then log(ctx, "vertical request to service failed: " .. err) return elseif (resp.status_code < 200 or resp.status_code >= 400) then log(ctx, "vertical request to service returned with status: " .. resp.status) return end local d = json.decode(resp.body) if (d == nil) then log(ctx, "failed to decode the JSON response") return elseif (d.error ~= nil and d.error == true) then log(ctx, "error returned in the JSON response") return elseif (d.hits == nil or d.hits == 0 or d.results == nil) then return end for _, r in pairs(d.records) do if (r.rrname ~= nil and r.rrname ~= "") then new_name(ctx, r.rrname) end if (r.rrtype ~= nil and (r.rrtype == "A" or r.rrtype == "AAAA")) then new_addr(ctx, r.rdata, r.rrname) end end end function build_url(domain) return "https://api-pdns.spamhaustech.com/v2/_search/rrset/" .. domain .. "/ANY?stype=rm&limit=1000" end function bearer_token(ctx, username, password) local body, err = json.encode({ ['username']=username, ['password']=password, }) if (err ~= nil and err ~= "") then return "" end local resp, err = request(ctx, { ['url']="https://api-pdns.spamhaustech.com/v2/login", ['method']="POST", ['header']={ ['Accept']="application/json", ['Content-Type']="application/json", }, ['body']=body, }) if (err ~= nil and err ~= "") then log(ctx, "bearer_token request to service failed: " .. err) return "" elseif (resp.status_code < 200 or resp.status_code >= 400) then log(ctx, "bearer_token request to service returned with status: " .. resp.status) return "" end local d = json.decode(resp.body) if (d == nil) then log(ctx, "failed to decode the bearer_token response") return "" elseif (d.token == nil or d.token == "") then log(ctx, "the bearer_token response did not include the token data") return "" end return d.token end
charlie5/lace
Ada
2,133
adb
with openGL.Context, interfaces.C; package body openGL.Surface is use -- Glx, Interfaces; -- visual_attribs : array (Positive range <>) of aliased C.int := (GLX_X_RENDERABLE, 1, -- GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, -- GLX_RENDER_TYPE, GLX_RGBA_BIT, -- GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR, -- GLX_RED_SIZE, 8, -- GLX_GREEN_SIZE, 8, -- GLX_BLUE_SIZE, 8, -- GLX_ALPHA_SIZE, 8, -- GLX_DEPTH_SIZE, 24, -- GLX_STENCIL_SIZE, 8, -- GLX_DOUBLEBUFFER, 1, -- -- GLX_SAMPLE_BUFFERS , 1, -- -- GLX_SAMPLES , 4, -- 0 -- ); procedure define (Self : in out Item; surface_Profile : in openGL.surface_Profile.item'Class; Display : in openGL.Display.Item; Window_Id : in Natural) is pragma Unreferenced (Window_Id); the_surface_Profile : constant openGL.surface_Profile.item'Class := surface_Profile; begin Self.Display := Display; end define; -- Operations -- procedure swap_Buffers (Self : in Item) is begin null; end swap_Buffers; end openGL.Surface;
Tim-Tom/scratch
Ada
9,605
adb
with Ada.Text_IO; with Ada.Command_Line; procedure Symbolica is NumColors : constant := 4; NumSymbols : constant := 3; Length : constant := 5; Width : constant := 5; package IO renames Ada.Text_IO; type Color_T is new Natural range 0 .. NumColors - 1; type Symbol_T is new Natural range 0 .. NumSymbols - 1; type Column_T is new Natural range 1 .. Length; type Row_T is new Natural range 1 .. Width; type Tile_T is record Color : Color_T; Symbol : Symbol_T; end record; type Board_T is Array(Row_T, Column_T) of Tile_T; type Count_T is Array(Color_T, Symbol_T) of Natural; colors : constant Array(Color_T) of Character := ('R', 'B', 'G', 'Y'); symbols : constant Array(Symbol_T) of Character := ('a', 'b', 'c'); original_board, best_board, board : Board_T; best_distance : Natural := Length * Width; total_solutions : Natural := 0; iterations : Natural := 0; tile_count : Count_T := (others => (others => 0)); function TileImage(tile : Tile_T) return String is begin return (colors(tile.Color), symbols(tile.Symbol)); end TileImage; procedure PrintBoard(b : Board_T) is begin for r in Row_T loop for c in Column_T loop IO.Put(TileImage(b(r,c)) & " "); end loop; IO.New_Line; end loop; end PrintBoard; procedure ReadBoard(filename: in String; b : out Board_T) is Not_In : exception; function GetColor(c: Character) return Color_T is begin for color in Color_T'Range loop if colors(color) = c then return color; end if; end loop; raise Not_In; end GetColor; function GetSymbol(s: Character) return Symbol_T is begin for symbol in Symbol_T'Range loop if symbols(symbol) = s then return symbol; end if; end loop; raise Not_In; end GetSymbol; f : IO.File_Type; c,s : Character; eol : Boolean; begin IO.Open(f, IO.In_File, filename); for row in Row_T'Range loop for col in Column_T'Range loop IO.Get(f, c); IO.Get(f, s); b(row, col) := (GetColor(c), GetSymbol(s)); loop IO.Look_Ahead(f,c,eol); exit when eol or else c /= ' '; IO.Get(f, c); end loop; end loop; end loop; IO.Put_Line("Read in original Board"); PrintBoard(b); end ReadBoard; procedure Validate_Counts is counts : Array(Color_T, Symbol_T) of Integer := (others => (others => 0)); count_incorrect : exception; begin for row in Row_T'range loop for col in Column_T'range loop declare o : Tile_T renames original_board(row, col); b : Tile_T renames board(row, col); begin counts(o.Color, o.Symbol) := counts(o.Color, o.Symbol) + 1; counts(b.Color, b.Symbol) := counts(b.Color, b.Symbol) - 1; end; end loop; end loop; for c in Color_T'range loop for s in Symbol_T'range loop if counts(c, s) /= 0 then IO.Put_Line("New Board has incorrect count of " & (colors(c), symbols(s)) & ": " & Integer'Image(counts(c, s))); PrintBoard(board); raise count_incorrect; end if; end loop; end loop; end Validate_Counts; procedure Validate_Integrity is board_integrity : exception; function Pair_Is_Valid(a, b : Tile_T) return Boolean is begin return (a.Color = b.Color and then a.Symbol /= b.Symbol) or else (a.Color /= b.Color and then a.Symbol = b.Symbol); end Pair_Is_Valid; begin for row in Row_T'range loop for col in Column_T'range loop declare b : Tile_T renames board(row, col); begin if (row > Row_T'First and then not Pair_Is_Valid(b, board(row-1, col))) or else (row < Row_T'Last and then not Pair_Is_Valid(b, board(row+1, col))) or else (col > Column_T'First and then not Pair_Is_Valid(b, board(row, col-1))) or else (col < Column_T'Last and then not Pair_Is_Valid(b, board(row, col+1))) then IO.Put_Line("New Board has incorrect incorrectly placed " & TileImage(b) & " at " & Row_T'Image(row) & "," & Column_T'Image(col)); PrintBoard(board); raise board_integrity; end if; end; end loop; end loop; end Validate_Integrity; Perform_Additional_Validation : constant Boolean := False; procedure CompareBoards is distance : Natural := 0; chain : Natural := 0; waiting : Array(Color_T, Symbol_T, Color_T, Symbol_T) of Natural := (others => (others => (others => (others => 0)))); begin if Perform_Additional_Validation then Validate_Counts; Validate_Integrity; end if; total_solutions := total_solutions + 1; for row in Row_T'Range loop for col in Column_T'Range loop declare o : Tile_T renames original_board(row, col); b : Tile_T renames board(row, col); w : natural renames waiting(o.Color, o.Symbol, b.Color, b.Symbol); ow : natural renames waiting(b.Color, b.Symbol, o.Color, o.Symbol); begin if o.Color /= b.Color or else o.Symbol /= b.Symbol then if ow > 0 then ow := ow - 1; chain := chain - 1; distance := distance + 1; else chain := chain + 1; w := w + 1; end if; end if; end; end loop; end loop; if chain > 0 then distance := distance + chain - 1; end if; if distance < best_distance then best_board := board; best_distance := distance; end if; end CompareBoards; procedure Solve(row : Row_T; col : Column_T); procedure Pick(row : Row_T; col : Column_T; c : Color_T; s : Symbol_T) is tc : Natural renames tile_count(c, s); begin if tc = 0 then return; end if; board(row, col) := (c, s); if col = Column_T'Last then if row = Row_T'Last then CompareBoards; else tc := tc - 1; Solve(row + 1, 1); tc := tc + 1; end if; else tc := tc - 1; Solve(row, col + 1); tc := tc + 1; end if; end Pick; pragma inline(Pick); procedure Solve(row : Row_T; col : Column_T) is begin iterations := iterations + 1; if row = 1 then declare left : Tile_T renames board(row, col - 1); begin for color in Color_T'Range loop if color /= left.Color then Pick(row, col, color, left.Symbol); end if; end loop; for symbol in Symbol_T'Range loop if symbol /= left.Symbol then Pick(row, col, left.Color, symbol); end if; end loop; end; elsif col = 1 then declare above : Tile_T renames board(row - 1, col); begin for color in Color_T'Range loop if color /= above.Color then Pick(row, col, color, above.Symbol); end if; end loop; for symbol in Symbol_T'Range loop if symbol /= above.Symbol then Pick(row, col, above.Color, symbol); end if; end loop; end; else declare left : Tile_T renames board(row, col -1); above : Tile_T renames board(row - 1, col); begin if left.Color = above.Color then for symbol in Symbol_T'Range loop if symbol /= left.Symbol and then symbol /= above.Symbol then Pick(row, col, left.Color, symbol); end if; end loop; elsif left.Symbol = above.Symbol then for color in Color_T'Range loop if color /= left.Color and then color /= above.Color then Pick(row, col, color, left.Symbol); end if; end loop; else Pick(row, col, left.Color, above.Symbol); Pick(row, col, above.Color, left.Symbol); end if; end; end if; end Solve; begin ReadBoard(Ada.Command_Line.Argument(1), original_board); for row in Row_T'Range loop for col in Column_T'Range loop declare tile : constant Tile_T := original_board(row, col); begin tile_count(tile.Color, tile.Symbol) := tile_count(tile.Color, tile.Symbol) + 1; end; end loop; end loop; for color in Color_T'Range loop for symbol in Symbol_T'Range loop Pick(1, 1, color, symbol); end loop; end loop; IO.Put_Line("Total Iterations" & Natural'Image(iterations)); IO.Put_Line("Total Solutions found:" & Natural'Image(total_solutions)); IO.Put_Line("Total Swaps: " & Natural'Image(best_distance)); PrintBoard(best_board); end Symbolica;
AaronC98/PlaneSystem
Ada
24,876
adb
------------------------------------------------------------------------------ -- Templates Parser -- -- -- -- Copyright (C) 1999-2013, AdaCore -- -- -- -- This library is free software; you can redistribute it and/or modify -- -- it under terms of the GNU General Public License as published by the -- -- Free Software Foundation; either version 3, or (at your option) any -- -- later version. This library is distributed in the hope that it will be -- -- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ------------------------------------------------------------------------------ pragma Ada_2012; with Ada.Text_IO; separate (Templates_Parser) package body Expr is use Ada.Strings.Maps; -- BNF definition of the expression language: -- -- <expr> ::= <relation> {<Logic_Op> <relation>} -- <relation> ::= <term> {<comp_op> <term>} -- <term> ::= ["not"] <primary> -- <primary> ::= <valvar> | "(" <expr> ")" -- <varval> ::= {<value> | <var>} [ "&" <varval>] -- <logic_op> ::= "and" | "or" | "xor" -- <comp_op> ::= "<" | "<=" | "=" | ">=" | ">" | "/=" subtype Comp_Op is Ops range O_Sup .. O_In; subtype Logic_Op is Ops range O_And .. O_Cat; Separator : constant Character_Set := Blank or To_Set ("<>=/()"); ------------- -- Analyze -- ------------- function Analyze (E : Expr.Tree) return String is type Ops_Fct is access function (L, R : Expr.Tree) return String; function F_And (L, R : Expr.Tree) return String; function F_Or (L, R : Expr.Tree) return String; function F_Xor (L, R : Expr.Tree) return String; function F_Sup (L, R : Expr.Tree) return String; function F_Esup (L, R : Expr.Tree) return String; function F_Einf (L, R : Expr.Tree) return String; function F_Inf (L, R : Expr.Tree) return String; function F_Equ (L, R : Expr.Tree) return String; function F_Diff (L, R : Expr.Tree) return String; function F_In (L, R : Expr.Tree) return String; function F_Cat (L, R : Expr.Tree) return String; type U_Ops_Fct is access function (N : Expr.Tree) return String; function F_Not (N : Expr.Tree) return String; ----------- -- F_And -- ----------- function F_And (L, R : Expr.Tree) return String is LV : constant String := Analyze (L); RV : constant String := Analyze (R); begin if LV = Unknown or else RV = Unknown then return Unknown; elsif Is_True (LV) and then Is_True (RV) then return "TRUE"; else return "FALSE"; end if; end F_And; ----------- -- F_Cat -- ----------- function F_Cat (L, R : Expr.Tree) return String is LV : constant String := Analyze (L); RV : constant String := Analyze (R); begin if LV = Unknown or else RV = Unknown then return Unknown; else return LV & RV; end if; end F_Cat; ------------ -- F_Diff -- ------------ function F_Diff (L, R : Expr.Tree) return String is LV : constant String := Analyze (L); RV : constant String := Analyze (R); begin if LV = Unknown or else RV = Unknown then return Unknown; elsif Analyze (L) /= Analyze (R) then return "TRUE"; else return "FALSE"; end if; end F_Diff; ------------ -- F_Einf -- ------------ function F_Einf (L, R : Expr.Tree) return String is LV : constant String := Analyze (L); RV : constant String := Analyze (R); begin if LV = Unknown or else RV = Unknown then return Unknown; elsif Utils.Is_Number (LV) and then Utils.Is_Number (RV) then if Integer'Value (LV) <= Integer'Value (RV) then return "TRUE"; else return "FALSE"; end if; else if LV <= RV then return "TRUE"; else return "FALSE"; end if; end if; end F_Einf; ----------- -- F_Equ -- ----------- function F_Equ (L, R : Expr.Tree) return String is LV : constant String := Analyze (L); RV : constant String := Analyze (R); begin if LV = Unknown or else RV = Unknown then return Unknown; elsif LV = RV then return "TRUE"; else return "FALSE"; end if; end F_Equ; ------------ -- F_Esup -- ------------ function F_Esup (L, R : Expr.Tree) return String is LV : constant String := Analyze (L); RV : constant String := Analyze (R); begin if LV = Unknown or else RV = Unknown then return Unknown; elsif Utils.Is_Number (LV) and then Utils.Is_Number (RV) then if Integer'Value (LV) >= Integer'Value (RV) then return "TRUE"; else return "FALSE"; end if; else if LV >= RV then return "TRUE"; else return "FALSE"; end if; end if; end F_Esup; ---------- -- F_In -- ---------- function F_In (L, R : Expr.Tree) return String is pragma Unreferenced (L, R); begin -- Always unknown as an in expression contains a variable return Unknown; end F_In; ----------- -- F_Inf -- ----------- function F_Inf (L, R : Expr.Tree) return String is LV : constant String := Analyze (L); RV : constant String := Analyze (R); begin if LV = Unknown or else RV = Unknown then return Unknown; elsif Utils.Is_Number (LV) and then Utils.Is_Number (RV) then if Integer'Value (LV) < Integer'Value (RV) then return "TRUE"; else return "FALSE"; end if; else if LV < RV then return "TRUE"; else return "FALSE"; end if; end if; end F_Inf; ----------- -- F_Not -- ----------- function F_Not (N : Expr.Tree) return String is NV : constant String := Analyze (N); begin if NV = Unknown then return Unknown; elsif Is_True (NV) then return "FALSE"; else return "TRUE"; end if; end F_Not; ---------- -- F_Or -- ---------- function F_Or (L, R : Expr.Tree) return String is LV : constant String := Analyze (L); RV : constant String := Analyze (R); begin if LV = Unknown or else RV = Unknown then return Unknown; elsif Is_True (LV) or else Is_True (RV) then return "TRUE"; else return "FALSE"; end if; end F_Or; ----------- -- F_Sup -- ----------- function F_Sup (L, R : Expr.Tree) return String is LV : constant String := Analyze (L); RV : constant String := Analyze (R); begin if LV = Unknown or else RV = Unknown then return Unknown; elsif Utils.Is_Number (LV) and then Utils.Is_Number (RV) then if Integer'Value (LV) > Integer'Value (RV) then return "TRUE"; else return "FALSE"; end if; else if LV > RV then return "TRUE"; else return "FALSE"; end if; end if; end F_Sup; ----------- -- F_Xor -- ----------- function F_Xor (L, R : Expr.Tree) return String is LV : constant String := Analyze (L); RV : constant String := Analyze (R); begin if LV = Unknown or else RV = Unknown then return Unknown; elsif Is_True (LV) xor Is_True (RV) then return "TRUE"; else return "FALSE"; end if; end F_Xor; Op_Table : constant array (Expr.Ops) of Ops_Fct := (Expr.O_And => F_And'Access, Expr.O_Or => F_Or'Access, Expr.O_Xor => F_Xor'Access, Expr.O_Sup => F_Sup'Access, Expr.O_Inf => F_Inf'Access, Expr.O_Esup => F_Esup'Access, Expr.O_Einf => F_Einf'Access, Expr.O_Equal => F_Equ'Access, Expr.O_Diff => F_Diff'Access, Expr.O_In => F_In'Access, Expr.O_Cat => F_Cat'Access); U_Op_Table : constant array (Expr.U_Ops) of U_Ops_Fct := (Expr.O_Not => F_Not'Access); begin case E.Kind is when Expr.Value => return To_String (E.V); when Expr.Var => return Unknown; when Expr.Op => return Op_Table (E.O) (E.Left, E.Right); when Expr.U_Op => return U_Op_Table (E.U_O) (E.Next); end case; end Analyze; ----------- -- Clone -- ----------- function Clone (E : Tree) return Tree is N : Tree; begin if E = null then return null; else N := new Node'(E.all); end if; case E.Kind is when Value => null; when Var => N.Var := Data.Clone (E.Var); when Op => N.Left := Clone (N.Left); N.Right := Clone (N.Right); when U_Op => N.Next := Clone (N.Next); end case; return N; end Clone; ----------- -- Image -- ----------- function Image (O : Ops) return String is begin case O is when O_And => return "and"; when O_Or => return "or"; when O_Xor => return "xor"; when O_Sup => return ">"; when O_Inf => return "<"; when O_Esup => return ">="; when O_Einf => return "<="; when O_Equal => return "="; when O_Diff => return "/="; when O_In => return "in"; when O_Cat => return "&"; end case; end Image; function Image (O : U_Ops) return String is begin case O is when O_Not => return "not"; end case; end Image; ------------- -- Is_True -- ------------- function Is_True (Str : String) return Boolean is L_Str : constant String := Characters.Handling.To_Upper (Str); begin return L_Str = "TRUE" or else L_Str = "T" or else L_Str = "1"; end Is_True; ----------- -- Parse -- ----------- function Parse (Expression : String) return Tree is Start_Index : Natural := Expression'First; Index : Natural := Expression'First; type Token_Kind is (Open_Par, Close_Par, Binary_Op, Unary_Op, Value, Var, End_Expr); type Token (Kind : Token_Kind := Var) is record case Kind is when Open_Par | Close_Par | End_Expr => null; when Binary_Op => Bin_Op : Ops; when Unary_Op => Un_Op : U_Ops; when Value | Var => Start : Positive; -- range of the token Stop : Positive; -- in Expression string end case; end record; Current_Token : Token; procedure Error (Mess : String) with No_Return; -- Raises Internal_Error with the column of the condition function Expr return Tree; -- Parse a logical operator function Term return Tree; -- Parse a term (unary operator) function Relation return Tree; -- Parse a relational operator function Primary return Tree; -- ??? ----------- -- Error -- ----------- procedure Error (Mess : String) is begin raise Internal_Error with "col" & Integer'Image (Start_Index) & " condition, " & Mess; end Error; procedure Next_Token; -- Moves Current_Token to next token. Set Index after the last analysed -- consumed from expression. ---------- -- Expr -- ---------- function Expr return Tree is N : Tree; O : Ops; begin N := Relation; while Current_Token.Kind = Binary_Op and then Current_Token.Bin_Op in Logic_Op loop O := Current_Token.Bin_Op; Next_Token; N := new Node'(Op, O, N, Relation); end loop; return N; end Expr; ---------------- -- Next_Token -- ---------------- procedure Next_Token is use Ada.Characters.Handling; I : Natural; begin -- Skip blanks while Index <= Expression'Last and then Is_In (Expression (Index), Blank) loop Index := Index + 1; end loop; Start_Index := Index; if Index > Expression'Last then -- No more data to read Current_Token := (Kind => End_Expr); -- Check symbolic operators elsif Expression (Index) = '(' then Current_Token := (Kind => Open_Par); Index := Index + 1; elsif Expression (Index) = ')' then Current_Token := (Kind => Close_Par); Index := Index + 1; elsif Expression (Index) = '=' then Current_Token := (Kind => Binary_Op, Bin_Op => O_Equal); Index := Index + 1; elsif Expression (Index) = '/' and then Index < Expression'Last and then Expression (Index + 1) = '=' then Current_Token := (Kind => Binary_Op, Bin_Op => O_Diff); Index := Index + 2; elsif Expression (Index) = '<' then Index := Index + 1; if Expression (Index) = '=' then Current_Token := (Kind => Binary_Op, Bin_Op => O_Einf); Index := Index + 1; else Current_Token := (Kind => Binary_Op, Bin_Op => O_Inf); end if; elsif Expression (Index) = '>' then Index := Index + 1; if Expression (Index) = '=' then Current_Token := (Kind => Binary_Op, Bin_Op => O_Esup); Index := Index + 1; else Current_Token := (Kind => Binary_Op, Bin_Op => O_Sup); end if; elsif Expression (Index) = '"' then -- This is a string, return it Current_Token := (Kind => Value, Start => Index + 1, Stop => Index); loop if Current_Token.Stop = Expression'Last then Error ("condition, no matching closing quote string"); elsif Expression (Current_Token.Stop + 1) = '"' then exit; else Current_Token.Stop := Current_Token.Stop + 1; end if; end loop; Index := Current_Token.Stop + 2; else -- We have found the start of a string token, look for end of it I := Index; loop Index := Fixed.Index (Expression (Index .. Expression'Last), Separator); if Index = 0 then -- Token end is the end of Expression Index := Expression'Last + 1; exit; end if; -- Special case for '/': it is a separator only if appearing -- in '/='. Without this test, the "/" filter is not recognized -- Moreover, this allows comparisons of file paths (with '/') exit when Expression (Index) /= '/' or else Expression (Index + 1) = '='; Index := Index + 1; end loop; declare Token_Image : constant String := To_Lower (Expression (I .. Index - 1)); begin if Token_Image = "not" then Current_Token := (Kind => Unary_Op, Un_Op => O_Not); elsif Token_Image = "and" then Current_Token := (Kind => Binary_Op, Bin_Op => O_And); elsif Token_Image = "or" then Current_Token := (Kind => Binary_Op, Bin_Op => O_Or); elsif Token_Image = "xor" then Current_Token := (Kind => Binary_Op, Bin_Op => O_Xor); elsif Token_Image = "in" then Current_Token := (Kind => Binary_Op, Bin_Op => O_In); elsif Token_Image = "&" then Current_Token := (Kind => Binary_Op, Bin_Op => O_Cat); elsif Token_Image'Length > Length (Begin_Tag) and then Token_Image (Token_Image'First .. Token_Image'First + Length (Begin_Tag) - 1) = Begin_Tag then -- This is a variable, we have the start of it, now look -- for the end of the variable. if Index <= Expression'Last and then Expression (Index) = '(' then -- This is not the end of the tag variable but the -- start of the tag parameters. Look for tag variable -- end. Index := Fixed.Index (Expression (Index .. Expression'Last), To_String (End_Tag)); Index := Index + Length (End_Tag); end if; if Index = 0 then Error ("variable end not found"); else Current_Token := (Kind => Var, Start => I, Stop => Index - 1); end if; else Current_Token := (Kind => Value, Start => I, Stop => Index - 1); end if; end; end if; end Next_Token; ------------- -- Primary -- ------------- function Primary return Tree is function Var_Val return Tree; -- Handles a set of catenated values and variables ------------- -- Var_Val -- ------------- function Var_Val return Tree is N : Tree; Start, Stop : Natural; begin case Current_Token.Kind is when Value => Start := Current_Token.Start; Stop := Current_Token.Stop; N := new Node' (Value, V => To_Unbounded_String (Expression (Start .. Stop))); when Var => Start := Current_Token.Start; Stop := Current_Token.Stop; N := new Node' (Var, Var => Data.Build (Expression (Start .. Stop))); when others => return null; end case; Next_Token; if Current_Token.Kind = Binary_Op and then Current_Token.Bin_Op = O_Cat then -- We have a &, let's catenate the result Next_Token; return new Node'(Op, O_Cat, N, Var_Val); else return N; end if; end Var_Val; Result : Tree; begin case Current_Token.Kind is -- Normal cases when Open_Par => Next_Token; Result := Expr; if Current_Token.Kind = Close_Par then Next_Token; return Result; else Error ("missing closing parenthesis"); end if; when Value | Var => return Var_Val; -- Errors when Unary_Op => Error ("misplaced operator """ & Image (Current_Token.Un_Op) & '"'); when Binary_Op => Error ("misplaced operator """ & Image (Current_Token.Bin_Op) & '"'); when Close_Par => Error ("unexpected right parenthesis"); when End_Expr => Error ("missing operand"); end case; end Primary; -------------- -- Relation -- -------------- function Relation return Tree is N : Tree; O : Ops; begin N := Term; while Current_Token.Kind = Binary_Op and then Current_Token.Bin_Op in Comp_Op loop O := Current_Token.Bin_Op; Next_Token; N := new Node'(Op, O, N, Term); end loop; return N; end Relation; ---------- -- Term -- ---------- function Term return Tree is O : U_Ops; begin if Current_Token.Kind = Unary_Op then O := Current_Token.Un_Op; Next_Token; return new Node'(U_Op, U_O => O, Next => Primary); else return Primary; end if; end Term; Result : Tree; begin Next_Token; Result := Expr; case Current_Token.Kind is when End_Expr => null; when Open_Par | Close_Par | Value | Var => Error ("Missing operator"); when Binary_Op | Unary_Op => Error ("Missing operand"); end case; return Result; end Parse; ---------------- -- Print_Tree -- ---------------- procedure Print_Tree (E : Tree) is begin case E.Kind is when Value => Text_IO.Put (Quote (To_String (E.V))); when Var => Text_IO.Put (Data.Image (E.Var)); when Op => Text_IO.Put ('('); Print_Tree (E.Left); Text_IO.Put (' ' & Image (E.O) & ' '); Print_Tree (E.Right); Text_IO.Put (')'); when U_Op => Text_IO.Put ('('); Text_IO.Put (Image (E.U_O) & ' '); Print_Tree (E.Next); Text_IO.Put (')'); end case; end Print_Tree; ------------- -- Release -- ------------- procedure Release (E : in out Tree; Single : Boolean := False) is procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Node, Tree); begin case E.Kind is when Value => null; when Var => Data.Release (E.Var); when Op => if not Single then Release (E.Left); Release (E.Right); end if; when U_Op => if not Single then Release (E.Next); end if; end case; Unchecked_Free (E); end Release; end Expr;
sungyeon/drake
Ada
36
ads
../machine-apple-darwin/s-synobj.ads
riccardo-bernardini/eugen
Ada
394
ads
with Project_Processor.Parsers.Abstract_Parsers; with Plugins.Tables; package Project_Processor.Parsers.Parser_Tables is new Plugins.Tables (Root_Plugin_Type => Abstract_Parsers.Abstract_Parser, Plugin_Parameters => Plugins.Parameter_Maps.Map, Plugin_ID => Parser_ID, Constructor => Abstract_Parsers.Create);
AdaCore/training_material
Ada
3,094
adb
package body Radar is function "=" (X, Y : Ship) return Boolean is begin return X.Unique_ID = Y.Unique_ID; end "="; protected body Short_List is procedure Add_Ship (E : Ship) is begin if Num_Tracked_Ships < Max_Tracked_Ships then Ships (Num_Tracked_Ships) := E; Num_Tracked_Ships := Num_Tracked_Ships + 1; else Num_Untracked_Ships := Num_Untracked_Ships + 1; Saturated_Combat_Zone := True; end if; end Add_Ship; procedure Remove_Ship (E : Ship) is begin for J in Ships'First .. Num_Tracked_Ships loop if Ships (J) = E then -- Ship E was found. First remove it. for K in J + 1 .. Num_Tracked_Ships loop Ships (K - 1) := Ships (K); end loop; -- Then update the number of tracked ships and return. Num_Tracked_Ships := Num_Tracked_Ships - 1; return; end if; end loop; -- Ship E was not found, so it is an untracked ship. -- Update the number of untracked ships and possibly leave the mode -- where combat zone is saturated. if Num_Untracked_Ships = 0 then Saturated_Combat_Zone := False; end if; Num_Untracked_Ships := Num_Untracked_Ships - 1; end Remove_Ship; function Biggest_Ship return Ship is Current : Class_Of_Ship := Not_A_Ship; Index : Integer; begin for J in Ships'First .. Num_Tracked_Ships loop if Current < Ships (J).Category then -- Found a bigger ship. Update Current and Index. Current := Ships (J).Category; Index := J; end if; end loop; return Ships (Index); end Biggest_Ship; end Short_List; task body Track_Ship is Current : Ship; begin -- Define the ship being tracked. accept New_Ship (E : Ship) do Current := E; end New_Ship; loop -- Following a movement of the ship entering or leaving the short -- range, add or remove it from the corresponding short list. accept Update_Position (Distance : Kilometer) do Current.Distance := Distance; if Distance < Short_Distance then case Current.Quality is when Friend => Friends.Add_Ship (Current); when Foe => Foes.Add_Ship (Current); when Unknown => null; end case; else case Current.Quality is when Friend => Friends.Remove_Ship (Current); when Foe => Foes.Remove_Ship (Current); when Unknown => null; end case; end if; end; end loop; end Track_Ship; end Radar;
OneWingedShark/Byron
Ada
1,938
adb
Pragma Ada_2012; Pragma Assertion_Policy( Check ); With Byron.Generics.Updater, Lexington.Token_Vector_Pkg.Tie_In, Ada.Characters.Wide_Wide_Latin_1; -- Normalizes line endings. Procedure Lexington.Aux.P2(Data : in out Token_Vector_Pkg.Vector) is Use Lexington.Aux.Token_Pkg; Package L renames Ada.Characters.Wide_Wide_Latin_1; -- Returns TRUE when the Item at Index is WHITESPACE *AND* -- Matches the indicated termination-character. (CR is default.) Function Is_EOL( Item : Token; CR : Boolean ) return Boolean; Function Is_EOL( Index : Positive; CR : Boolean ) return Boolean is ( Is_EOL(Data(Index), CR) ); Function Is_EOL( Item : Token; CR : Boolean ) return Boolean is Value : Wide_Wide_String renames Lexeme(Item); WS : constant Boolean := ID(Item) = Whitespace; Begin return WS and then Value(Value'First) = (if CR then L.CR else L.LF); End Is_EOL; Procedure Handle_Unix_and_Apple( Item : in out Token ) is Begin if Is_EOL(Item, True) or Is_EOL(Item, False) then Item := Make_Token(End_of_Line, ""); end if; End Handle_Unix_and_Apple; Procedure Handle_LF is new Byron.Generics.Updater( Vector_Package => Lexington.Token_Vector_Pkg.Tie_In, Replace_Element => Lexington.Token_Vector_Pkg.Replace_Element, Operation => Handle_Unix_and_Apple ); Index : Positive; Begin if Data.Is_Empty then return; end if; -- RFC822-style (CRLF) Index:= Data.First_Index; loop exit when Index >= Data.Last_Index-1; if Is_EOL(Index, True) and then Is_EOL(Index+1,False) then Data.Replace_Element( Index => Index, New_Item => Make_Token(End_of_Line, "") ); Data.Delete(Index+1); end if; Index:= Positive'Succ( Index ); end loop; -- Unix and Apple (LF & CR) Handle_LF( Data ); End Lexington.Aux.P2;
reznikmm/matreshka
Ada
4,948
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Interfaces; package Matreshka.Internals.Strings.Handlers.X86_Utilities is pragma Preelaborate; procedure Update_Index_Forward_Generic (Mask : Interfaces.Unsigned_32; Index : in out Positive); -- Update character index based on value of the exclusion mask. It -- increments Index by 8 excluding 1 for each pair of 1 bits in exclusion -- mask. This is generic version of function, it doesn't use and specific -- CPU instructions. procedure Update_Index_Forward_POPCNT (Mask : Interfaces.Unsigned_32; Index : in out Positive); pragma Inline (Update_Index_Forward_POPCNT); -- Update character index based on value of the exclusion mask. It -- increments Index by 8 excluding 1 for each pair of 1 bits in exclusion -- mask. This version uses POPCNT instruction. procedure Update_Index_Backward_Generic (Mask : Interfaces.Unsigned_32; Index : in out Positive); -- Update character index based on value of the exclusion mask. It -- decrements Index by 8 excluding 1 for each pair of 1 bits in exclusion -- mask. This is generic version of function, it doesn't use and specific -- CPU instructions. procedure Update_Index_Backward_POPCNT (Mask : Interfaces.Unsigned_32; Index : in out Positive); pragma Inline (Update_Index_Backward_POPCNT); -- Update character index based on value of the exclusion mask. It -- decrements Index by 8 excluding 1 for each pair of 1 bits in exclusion -- mask. This version uses POPCNT instruction. end Matreshka.Internals.Strings.Handlers.X86_Utilities;
kylelk/ada-examples
Ada
271
adb
with Ada.integer_text_IO; use Ada; procedure add_by_referance is procedure add(a, b: in Integer; c: out Integer) is begin c := a + b; end add; answer : Integer; begin add(3, 5, answer); integer_text_IO.put(answer); end add_by_referance;
sungyeon/drake
Ada
339
ads
pragma License (Unrestricted); -- implementation unit required by compiler package System.Img_LLD is pragma Pure; -- required for Fixed'Image by compiler (s-imglld.ads) procedure Image_Long_Long_Decimal ( V : Long_Long_Integer; S : in out String; P : out Natural; Scale : Integer); end System.Img_LLD;
optikos/oasis
Ada
7,813
adb
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- package body Program.Nodes.Object_Renaming_Declarations is function Create (Names : not null Program.Elements.Defining_Identifiers .Defining_Identifier_Vector_Access; Colon_Token : not null Program.Lexical_Elements .Lexical_Element_Access; Not_Token : Program.Lexical_Elements.Lexical_Element_Access; Null_Token : Program.Lexical_Elements.Lexical_Element_Access; Object_Subtype : not null Program.Elements.Element_Access; Renames_Token : not null Program.Lexical_Elements .Lexical_Element_Access; Renamed_Object : not null Program.Elements.Expressions.Expression_Access; With_Token : Program.Lexical_Elements.Lexical_Element_Access; Aspects : Program.Elements.Aspect_Specifications .Aspect_Specification_Vector_Access; Semicolon_Token : not null Program.Lexical_Elements .Lexical_Element_Access) return Object_Renaming_Declaration is begin return Result : Object_Renaming_Declaration := (Names => Names, Colon_Token => Colon_Token, Not_Token => Not_Token, Null_Token => Null_Token, Object_Subtype => Object_Subtype, Renames_Token => Renames_Token, Renamed_Object => Renamed_Object, With_Token => With_Token, Aspects => Aspects, Semicolon_Token => Semicolon_Token, Enclosing_Element => null) do Initialize (Result); end return; end Create; function Create (Names : not null Program.Elements.Defining_Identifiers .Defining_Identifier_Vector_Access; Object_Subtype : not null Program.Elements.Element_Access; Renamed_Object : not null Program.Elements.Expressions .Expression_Access; Aspects : Program.Elements.Aspect_Specifications .Aspect_Specification_Vector_Access; Is_Part_Of_Implicit : Boolean := False; Is_Part_Of_Inherited : Boolean := False; Is_Part_Of_Instance : Boolean := False; Has_Not_Null : Boolean := False) return Implicit_Object_Renaming_Declaration is begin return Result : Implicit_Object_Renaming_Declaration := (Names => Names, Object_Subtype => Object_Subtype, Renamed_Object => Renamed_Object, Aspects => Aspects, Is_Part_Of_Implicit => Is_Part_Of_Implicit, Is_Part_Of_Inherited => Is_Part_Of_Inherited, Is_Part_Of_Instance => Is_Part_Of_Instance, Has_Not_Null => Has_Not_Null, Enclosing_Element => null) do Initialize (Result); end return; end Create; overriding function Names (Self : Base_Object_Renaming_Declaration) return not null Program.Elements.Defining_Identifiers .Defining_Identifier_Vector_Access is begin return Self.Names; end Names; overriding function Object_Subtype (Self : Base_Object_Renaming_Declaration) return not null Program.Elements.Element_Access is begin return Self.Object_Subtype; end Object_Subtype; overriding function Renamed_Object (Self : Base_Object_Renaming_Declaration) return not null Program.Elements.Expressions.Expression_Access is begin return Self.Renamed_Object; end Renamed_Object; overriding function Aspects (Self : Base_Object_Renaming_Declaration) return Program.Elements.Aspect_Specifications .Aspect_Specification_Vector_Access is begin return Self.Aspects; end Aspects; overriding function Colon_Token (Self : Object_Renaming_Declaration) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Colon_Token; end Colon_Token; overriding function Not_Token (Self : Object_Renaming_Declaration) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Not_Token; end Not_Token; overriding function Null_Token (Self : Object_Renaming_Declaration) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Null_Token; end Null_Token; overriding function Renames_Token (Self : Object_Renaming_Declaration) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Renames_Token; end Renames_Token; overriding function With_Token (Self : Object_Renaming_Declaration) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.With_Token; end With_Token; overriding function Semicolon_Token (Self : Object_Renaming_Declaration) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Semicolon_Token; end Semicolon_Token; overriding function Has_Not_Null (Self : Object_Renaming_Declaration) return Boolean is begin return Self.Null_Token.Assigned; end Has_Not_Null; overriding function Is_Part_Of_Implicit (Self : Implicit_Object_Renaming_Declaration) return Boolean is begin return Self.Is_Part_Of_Implicit; end Is_Part_Of_Implicit; overriding function Is_Part_Of_Inherited (Self : Implicit_Object_Renaming_Declaration) return Boolean is begin return Self.Is_Part_Of_Inherited; end Is_Part_Of_Inherited; overriding function Is_Part_Of_Instance (Self : Implicit_Object_Renaming_Declaration) return Boolean is begin return Self.Is_Part_Of_Instance; end Is_Part_Of_Instance; overriding function Has_Not_Null (Self : Implicit_Object_Renaming_Declaration) return Boolean is begin return Self.Has_Not_Null; end Has_Not_Null; procedure Initialize (Self : aliased in out Base_Object_Renaming_Declaration'Class) is begin for Item in Self.Names.Each_Element loop Set_Enclosing_Element (Item.Element, Self'Unchecked_Access); end loop; Set_Enclosing_Element (Self.Object_Subtype, Self'Unchecked_Access); Set_Enclosing_Element (Self.Renamed_Object, Self'Unchecked_Access); for Item in Self.Aspects.Each_Element loop Set_Enclosing_Element (Item.Element, Self'Unchecked_Access); end loop; null; end Initialize; overriding function Is_Object_Renaming_Declaration_Element (Self : Base_Object_Renaming_Declaration) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Object_Renaming_Declaration_Element; overriding function Is_Declaration_Element (Self : Base_Object_Renaming_Declaration) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Declaration_Element; overriding procedure Visit (Self : not null access Base_Object_Renaming_Declaration; Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is begin Visitor.Object_Renaming_Declaration (Self); end Visit; overriding function To_Object_Renaming_Declaration_Text (Self : aliased in out Object_Renaming_Declaration) return Program.Elements.Object_Renaming_Declarations .Object_Renaming_Declaration_Text_Access is begin return Self'Unchecked_Access; end To_Object_Renaming_Declaration_Text; overriding function To_Object_Renaming_Declaration_Text (Self : aliased in out Implicit_Object_Renaming_Declaration) return Program.Elements.Object_Renaming_Declarations .Object_Renaming_Declaration_Text_Access is pragma Unreferenced (Self); begin return null; end To_Object_Renaming_Declaration_Text; end Program.Nodes.Object_Renaming_Declarations;
CopyPasteBugs/ActionGameContestProject
Ada
607
adb
<AnimDB FragDef="Animations/Mannequin/ADB/PandaFragmentIds.xml" TagDef="Animations/Mannequin/ADB/PandaTags.xml"> <FragmentList> <Walk> <Fragment BlendOutDuration="0.2" Tags=""> <AnimLayer> <Blend ExitTime="0" StartTime="0" Duration="0.2"/> <Animation name="1DONE-BSpace_forward" flags="Loop+ForceSkelUpdate"/> </AnimLayer> </Fragment> <Fragment BlendOutDuration="0.2" Tags=""> <AnimLayer> <Blend ExitTime="0" StartTime="0" Duration="0.2"/> <Animation name="Idle" flags="Loop+ForceSkelUpdate"/> </AnimLayer> </Fragment> </Walk> </FragmentList> </AnimDB>
reznikmm/matreshka
Ada
3,629
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with XML.DOM.Elements; package ODF.DOM.Elements.Style.Tab_Stops is type ODF_Style_Tab_Stops is new XML.DOM.Elements.DOM_Element with private; private type ODF_Style_Tab_Stops is new XML.DOM.Elements.DOM_Element with null record; end ODF.DOM.Elements.Style.Tab_Stops;
damaki/SPARKNaCl
Ada
1,260
adb
with SPARKNaCl; use SPARKNaCl; with SPARKNaCl.Debug; use SPARKNaCl.Debug; with SPARKNaCl.Sign; use SPARKNaCl.Sign; with Ada.Text_IO; use Ada.Text_IO; with Interfaces; use Interfaces; with Random; procedure Sign is Raw_SK : Bytes_32; PK : Signing_PK; SK : Signing_SK; M : constant Byte_Seq (0 .. 255) := (0 => 16#55#, others => 16#aa#); SM : Byte_Seq (0 .. 319) := (others => 0); M2 : Byte_Seq (0 .. 319) := (others => 0); M3 : Byte_Seq (0 .. 255); ML : I32; S : Boolean; -- I : I64 := 1; begin -- loop -- Put_Line ("Iteration " & I'Img); Random.Random_Bytes (Raw_SK); Keypair (Raw_SK, PK, SK); begin Sign (SM, M, SK); exception when Constraint_Error => Debug.DH ("In Sign, SK was ", Serialize (SK)); raise; end; begin Open (M2, S, ML, SM, PK); exception when Constraint_Error => Debug.DH ("In Open, PK was ", Serialize (PK)); Debug.DH ("In Open, SM was ", SM); raise; end; M3 := M2 (0 .. 255); -- I := I + 1; DH ("M3 is ", M3); Put_Line ("Status is " & Img (S)); Put_Line ("ML is " & ML'Img); -- end loop; end Sign;
reznikmm/matreshka
Ada
4,750
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with XML.DOM.Visitors; with ODF.DOM.Text_Sequence_Decl_Elements; package Matreshka.ODF_Text.Sequence_Decl_Elements is type Text_Sequence_Decl_Element_Node is new Matreshka.ODF_Text.Abstract_Text_Element_Node and ODF.DOM.Text_Sequence_Decl_Elements.ODF_Text_Sequence_Decl with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Text_Sequence_Decl_Element_Node; overriding function Get_Local_Name (Self : not null access constant Text_Sequence_Decl_Element_Node) return League.Strings.Universal_String; overriding procedure Enter_Node (Self : not null access Text_Sequence_Decl_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Leave_Node (Self : not null access Text_Sequence_Decl_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Visit_Node (Self : not null access Text_Sequence_Decl_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); end Matreshka.ODF_Text.Sequence_Decl_Elements;
reznikmm/matreshka
Ada
6,838
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with Matreshka.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Db.Key_Columns_Elements is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Db_Key_Columns_Element_Node is begin return Self : Db_Key_Columns_Element_Node do Matreshka.ODF_Db.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Db_Prefix); end return; end Create; ---------------- -- Enter_Node -- ---------------- overriding procedure Enter_Node (Self : not null access Db_Key_Columns_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then ODF.DOM.Visitors.Abstract_ODF_Visitor'Class (Visitor).Enter_Db_Key_Columns (ODF.DOM.Db_Key_Columns_Elements.ODF_Db_Key_Columns_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Enter_Node (Visitor, Control); end if; end Enter_Node; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Db_Key_Columns_Element_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Key_Columns_Element; end Get_Local_Name; ---------------- -- Leave_Node -- ---------------- overriding procedure Leave_Node (Self : not null access Db_Key_Columns_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then ODF.DOM.Visitors.Abstract_ODF_Visitor'Class (Visitor).Leave_Db_Key_Columns (ODF.DOM.Db_Key_Columns_Elements.ODF_Db_Key_Columns_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Leave_Node (Visitor, Control); end if; end Leave_Node; ---------------- -- Visit_Node -- ---------------- overriding procedure Visit_Node (Self : not null access Db_Key_Columns_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Iterator in ODF.DOM.Iterators.Abstract_ODF_Iterator'Class then ODF.DOM.Iterators.Abstract_ODF_Iterator'Class (Iterator).Visit_Db_Key_Columns (Visitor, ODF.DOM.Db_Key_Columns_Elements.ODF_Db_Key_Columns_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Visit_Node (Iterator, Visitor, Control); end if; end Visit_Node; begin Matreshka.DOM_Documents.Register_Element (Matreshka.ODF_String_Constants.Db_URI, Matreshka.ODF_String_Constants.Key_Columns_Element, Db_Key_Columns_Element_Node'Tag); end Matreshka.ODF_Db.Key_Columns_Elements;
alvaromb/Compilemon
Ada
1,477
ads
-- Copyright (c) 1990 Regents of the University of California. -- All rights reserved. -- -- This software was developed by John Self of the Arcadia project -- at the University of California, Irvine. -- -- Redistribution and use in source and binary forms are permitted -- provided that the above copyright notice and this paragraph are -- duplicated in all such forms and that any documentation, -- advertising materials, and other materials related to such -- distribution and use acknowledge that the software was developed -- by the University of California, Irvine. The name of the -- University may not be used to endorse or promote products derived -- from this software without specific prior written permission. -- THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED -- WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. -- TITLE main body -- AUTHOR: John Self (UCI) -- DESCRIPTION driver routines for aflex. Calls drivers for all -- high level routines from other packages. -- $Header: /co/ua/self/arcadia/aflex/ada/src/RCS/mainS.a,v 1.5 90/01/12 15:20:14 self Exp Locker: self $ -- aflex - tool to generate fast lexical analyzers package main_body is procedure AFLEXEND(STATUS : in INTEGER); procedure AFLEXINIT; procedure READIN; procedure SET_UP_INITIAL_ALLOCATIONS; AFLEX_TERMINATE : exception; TERMINATION_STATUS : INTEGER; end main_body;
stcarrez/ada-util
Ada
3,192
ads
----------------------------------------------------------------------- -- util-streams-raw -- Raw streams for Windows based systems -- Copyright (C) 2011, 2019, 2023 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Finalization; with Util.Systems.Os; with Util.Systems.Types; -- The <b>Util.Streams.Raw</b> package provides a stream directly on top of -- file system operations <b>ReadFile</b> and <b>WriteFile</b>. package Util.Streams.Raw is subtype File_Type is Util.Systems.Os.File_Type; -- ----------------------- -- File stream -- ----------------------- -- The <b>Raw_Stream</b> is an output/input stream that reads or writes -- into a file-based stream. type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with private; type Raw_Stream_Access is access all Raw_Stream'Class; -- Initialize the raw stream to read and write on the given file descriptor. procedure Initialize (Stream : in out Raw_Stream; File : in File_Type); -- Get the file descriptor associated with the stream. function Get_File (Stream : in Raw_Stream) return Util.Systems.Os.File_Type; -- Set the file descriptor to be used by the stream. procedure Set_File (Stream : in out Raw_Stream; File : in Util.Systems.Os.File_Type); -- Close the stream. overriding procedure Close (Stream : in out Raw_Stream); -- Write the buffer array to the output stream. overriding procedure Write (Stream : in out Raw_Stream; Buffer : in Ada.Streams.Stream_Element_Array); -- Read into the buffer as many bytes as possible and return in -- <b>last</b> the position of the last byte read. overriding procedure Read (Stream : in out Raw_Stream; Into : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Reposition the read/write file offset. procedure Seek (Stream : in out Raw_Stream; Pos : in Util.Systems.Types.off_t; Mode : in Util.Systems.Types.Seek_Mode); private use Ada.Streams; -- Flush the stream and release the buffer. overriding procedure Finalize (Object : in out Raw_Stream); type Raw_Stream is new Ada.Finalization.Limited_Controlled and Output_Stream and Input_Stream with record File : File_Type := Util.Systems.Os.NO_FILE; end record; end Util.Streams.Raw;
Heziode/lsystem-editor
Ada
1,839
adb
------------------------------------------------------------------------------- -- LSE -- L-System Editor -- Author: Heziode -- -- License: -- MIT License -- -- Copyright (c) 2018 Quentin Dauprat (Heziode) <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------- package body LSE.Model.Grammar.Symbol.LogoForwardTrace is procedure Initialize (This : out Instance) is begin This := Instance '(Representation => 'F'); end Initialize; procedure Interpret (This : in out Instance; T : in out Holder) is pragma Unreferenced (This); begin T.Reference.Forward (True); end Interpret; end LSE.Model.Grammar.Symbol.LogoForwardTrace;
BrickBot/Bound-T-H8-300
Ada
6,124
ads
-- Flow.Execution.Times (decl) -- -- Computation of the execution time for each node in a flow-graph, -- possibly depending on modified times for step edges. -- -- A component of the Bound-T Worst-Case Execution Time Tool. -- ------------------------------------------------------------------------------- -- Copyright (c) 1999 .. 2015 Tidorum Ltd -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- -- This software is provided by the copyright holders and contributors "as is" and -- any express or implied warranties, including, but not limited to, the implied -- warranties of merchantability and fitness for a particular purpose are -- disclaimed. In no event shall the copyright owner or contributors be liable for -- any direct, indirect, incidental, special, exemplary, or consequential damages -- (including, but not limited to, procurement of substitute goods or services; -- loss of use, data, or profits; or business interruption) however caused and -- on any theory of liability, whether in contract, strict liability, or tort -- (including negligence or otherwise) arising in any way out of the use of this -- software, even if advised of the possibility of such damage. -- -- Other modules (files) of this software composition should contain their -- own copyright statements, which may have different copyright and usage -- conditions. The above conditions apply to this file. ------------------------------------------------------------------------------- -- -- $Revision: 1.2 $ -- $Date: 2015/10/24 19:36:48 $ -- -- $Log: flow-execution-times.ads,v $ -- Revision 1.2 2015/10/24 19:36:48 niklas -- Moved to free licence. -- -- Revision 1.1 2008-07-14 19:16:56 niklas -- BT-CH-0135: Assertions on "instructions". -- --:dbpool with GNAT.Debug_Pools; with Assertions; with Processor; with Programs; package Flow.Execution.Times is type Node_Times_T is array (Node_Index_T range <>) of Processor.Time_T; -- -- Execution times of nodes of a graph. -- May depend on the call-path. type Node_Times_Ref is access Node_Times_T; --:dbpool Node_Times_Pool : GNAT.Debug_Pools.Debug_Pool; --:dbpool for Node_Times_Ref'Storage_Pool use Node_Times_Pool; procedure Discard (Item : in out Node_Times_Ref); -- -- Discards the Item, releasing the allocated memory. type Step_Edge_Times_T is array (Step_Edge_Index_T range <>) of Processor.Time_T; -- -- Execution times of the step-edges of a graph. -- May depend on the call-path. type Step_Edge_Times_Ref is access Step_Edge_Times_T; --:dbpool Step_Edge_Times_Pool : GNAT.Debug_Pools.Debug_Pool; --:dbpool for Step_Edge_Times_Ref'Storage_Pool use Step_Edge_Times_Pool; procedure Discard (Item : in out Step_Edge_Times_Ref); -- -- Discards the Item, releasing the allocated memory. function Step_Edge_Times (Graph : Graph_T) return Step_Edge_Times_T; -- -- The execution time of each step-edge in the flow-graph, copied -- from the execution-time attribute of the step-edges. function Work ( Done_By : Node_T; Taking : Step_Edge_Times_T; Using : Processor.Power_T) return Processor.Work_T; -- -- The total work required to execute one node in a flow-graph, -- when executing the step-edges takes a specified time, and -- using a specific amount of processor power. This work can -- then be converted into an execution time. -- -- Done_By -- The node that is doing the work. The work includes the -- computational and other effort of the steps in the node, -- and the time taken by the edges between the steps. -- Taking -- Supplies the execution time of the step-edges. -- Using -- The processor power that is available for executing -- the node. It may depend on local properties of the node, -- for example in which type of memory the instructions lie. -- -- The total work of the node is computed by summing the steps and -- edges between steps, in the execution order. The edges entering -- and leaving the node are not included, only internal edges. function Node_Times ( Subprogram : Programs.Subprogram_T; Step_Edge_Times : Step_Edge_Times_T; Asserts : Assertions.Assertion_Map_T) return Node_Times_T; -- -- The local execution time of all nodes of a Subprogram, that -- is the time for executing the instructions in the subprogram -- itself without including the time spent in callees as part of -- call nodes (call steps). -- -- The time is computed from the effort per instruction (as -- given by the Decoder and embedded in the flow-graph), from -- the Step_Edge_Times and from assertions on processor power -- or memory wait states etc. (as given by the user). The power -- assertions can be localized to specific parts of the -- subprogram (e.g. loops) and are therefore given by an -- assertion-map. -- -- The execution time can also depend on the resolved dynamic data -- accessed (thru e.g. address-dependent memory wait-states) and -- on other target-specific properties asserted for this subprogram. type Edge_Times_T is array (Edge_Index_T range <>) of Processor.Time_T; -- -- Execution times of the node-edges of a graph. -- May depend on the call-path. function Edge_Times ( Graph : Graph_T; Step_Edge_Times : Step_Edge_Times_T) return Edge_Times_T; -- -- The execution time of each node-edge in the flow-graph, copied -- from the corresponding and given step-edge times. end Flow.Execution.Times;
stcarrez/ada-servlet
Ada
3,340
adb
----------------------------------------------------------------------- -- servlet-routes -- Request routing -- Copyright (C) 2015, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Unchecked_Deallocation; package body Servlet.Routes.Servlets is use type Servlet.Filters.Filter_Access; use type Servlet.Filters.Filter_List_Access; procedure Free is new Ada.Unchecked_Deallocation (Object => Servlet.Filters.Filter_List, Name => Servlet.Filters.Filter_List_Access); -- ------------------------------ -- Get the servlet to call for the route. -- ------------------------------ function Get_Servlet (Route : in Servlet_Route_Type) return Servlet.Core.Servlet_Access is begin return Route.Servlet; end Get_Servlet; -- ------------------------------ -- Append the filter to the filter list defined by the mapping node. -- ------------------------------ procedure Append_Filter (Route : in out Servlet_Route_Type; Filter : in Servlet.Filters.Filter_Access) is List : Servlet.Filters.Filter_List_Access; begin -- Filters are executed through the <b>Filter_Chain.Do_Filter</b> method -- starting from the last position to the first. To append a filter, -- it must be inserted as first position of the list. if Route.Filters = null then List := new Servlet.Filters.Filter_List (1 .. 1); else -- Check that the filter is not already executed. for I in Route.Filters'Range loop if Route.Filters (I) = Filter then return; end if; end loop; List := new Servlet.Filters.Filter_List (1 .. Route.Filters'Last + 1); List (2 .. List'Last) := Route.Filters.all; Free (Route.Filters); end if; List (List'First) := Filter; Route.Filters := List; end Append_Filter; -- ------------------------------ -- Release the storage held by the route. -- ------------------------------ overriding procedure Finalize (Route : in out Servlet_Route_Type) is begin Free (Route.Filters); end Finalize; -- ------------------------------ -- Get the servlet to call for the route. -- ------------------------------ overriding function Get_Servlet (Route : in Proxy_Route_Type) return Servlet.Core.Servlet_Access is begin if not Route.Route.Is_Null then return Servlet_Route_Type'Class (Route.Route.Value.Element.all).Get_Servlet; else return Route.Servlet; end if; end Get_Servlet; end Servlet.Routes.Servlets;
mimo/Tracker
Ada
476
ads
with Surface.Window; package tracker.presentation is type instance is new Surface.Window.Instance with record Book_Completion : Collection; end record; overriding procedure Setup (self : in out instance); overriding procedure Update (self : in out instance ; dt : Float); type Element is (BG, SHADE, HIGHLIGHT, SHADOW, TEXT, LABEL); type Color_Value is mod 2**32; procedure Set_Color (E : Element ; C : Color_Value); end tracker.presentation;
Fabien-Chouteau/AGATE
Ada
5,681
ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2018, Fabien Chouteau -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ package AGATE.Arch.RISCV is function CPU_Frequency return Word; function Stvec return Word with Inline_Always; procedure Write_Stvec (Val : Word) with Inline_Always; function Mtvec return Word with Inline_Always; procedure Write_Mtvec (Val : Word) with Inline_Always; function Mscratch return Word with Inline_Always; procedure Write_Mcratch (Val : Word) with Inline_Always; function Mbadaddr return Word with Inline_Always; function Mcycle_Low return Word with Inline_Always; function Mcycle_Hi return Word with Inline_Always; type Mstatus_Reg is record UIE : Boolean; SIE : Boolean; HIE : Boolean; MIE : Boolean; UPIE : Boolean; SPIE : Boolean; HPIE : Boolean; MPIE : Boolean; SPP : Bit; HPP : UInt2; MPP : UInt2; FS : UInt2; XS : UInt2; MPRV : Boolean; PUM : Boolean; MXR : Boolean; WPRI_1 : UInt4; -- Reserved Writes Preserve Values, Reads Ignore VM : UInt5; WPRI_2 : UInt2; -- Reserved Writes Preserve Values, Reads Ignore SD : Boolean; end record with Size => 32; for Mstatus_Reg use record UIE at 0 range 0 .. 0; SIE at 0 range 1 .. 1; HIE at 0 range 2 .. 2; MIE at 0 range 3 .. 3; UPIE at 0 range 4 .. 4; SPIE at 0 range 5 .. 5; HPIE at 0 range 6 .. 6; MPIE at 0 range 7 .. 7; SPP at 0 range 8 .. 8; HPP at 0 range 9 .. 10; MPP at 0 range 11 .. 12; FS at 0 range 13 .. 14; XS at 0 range 15 .. 16; MPRV at 0 range 17 .. 17; PUM at 0 range 18 .. 18; MXR at 0 range 19 .. 19; WPRI_1 at 0 range 20 .. 23; VM at 0 range 24 .. 28; WPRI_2 at 0 range 29 .. 30; SD at 0 range 31 .. 31; end record; function Mstatus return Mstatus_Reg with Inline_Always; procedure Write_Mstatus (Val : Mstatus_Reg) with Inline_Always; type Interrupt_Register is record USI : Boolean; SSI : Boolean; HSI : Boolean; MSI : Boolean; UTI : Boolean; STI : Boolean; HTI : Boolean; MTI : Boolean; UEI : Boolean; SEI : Boolean; HEI : Boolean; MEI : Boolean; Reserved : UInt18; end record with Size => 32; for Interrupt_Register use record USI at 0 range 0 .. 0; SSI at 0 range 1 .. 1; HSI at 0 range 2 .. 2; MSI at 0 range 3 .. 3; UTI at 0 range 4 .. 4; STI at 0 range 5 .. 5; HTI at 0 range 6 .. 6; MTI at 0 range 7 .. 7; UEI at 0 range 8 .. 8; SEI at 0 range 9 .. 9; HEI at 0 range 10 .. 10; MEI at 0 range 11 .. 11; Reserved at 0 range 12 .. 31; end record; function Mip return Interrupt_Register with Inline_Always; procedure Write_Mip (Val : Interrupt_Register) with Inline_Always; function Mie return Interrupt_Register with Inline_Always; procedure Write_Mie (Val : Interrupt_Register) with Inline_Always; end AGATE.Arch.RISCV;
micahwelf/FLTK-Ada
Ada
5,729
adb
with Interfaces.C, System; use type System.Address; package body FLTK.Widgets.Buttons is procedure button_set_draw_hook (W, D : in System.Address); pragma Import (C, button_set_draw_hook, "button_set_draw_hook"); pragma Inline (button_set_draw_hook); procedure button_set_handle_hook (W, H : in System.Address); pragma Import (C, button_set_handle_hook, "button_set_handle_hook"); pragma Inline (button_set_handle_hook); function new_fl_button (X, Y, W, H : in Interfaces.C.int; Text : in Interfaces.C.char_array) return System.Address; pragma Import (C, new_fl_button, "new_fl_button"); pragma Inline (new_fl_button); procedure free_fl_button (B : in System.Address); pragma Import (C, free_fl_button, "free_fl_button"); pragma Inline (free_fl_button); function fl_button_get_state (B : in System.Address) return Interfaces.C.int; pragma Import (C, fl_button_get_state, "fl_button_get_state"); pragma Inline (fl_button_get_state); procedure fl_button_set_state (B : in System.Address; S : in Interfaces.C.int); pragma Import (C, fl_button_set_state, "fl_button_set_state"); pragma Inline (fl_button_set_state); procedure fl_button_set_only (B : in System.Address); pragma Import (C, fl_button_set_only, "fl_button_set_only"); pragma Inline (fl_button_set_only); function fl_button_get_down_box (B : in System.Address) return Interfaces.C.int; pragma Import (C, fl_button_get_down_box, "fl_button_get_down_box"); pragma Inline (fl_button_get_down_box); procedure fl_button_set_down_box (B : in System.Address; T : in Interfaces.C.int); pragma Import (C, fl_button_set_down_box, "fl_button_set_down_box"); pragma Inline (fl_button_set_down_box); function fl_button_get_shortcut (B : in System.Address) return Interfaces.C.int; pragma Import (C, fl_button_get_shortcut, "fl_button_get_shortcut"); pragma Inline (fl_button_get_shortcut); procedure fl_button_set_shortcut (B : in System.Address; T : in Interfaces.C.int); pragma Import (C, fl_button_set_shortcut, "fl_button_set_shortcut"); pragma Inline (fl_button_set_shortcut); procedure fl_button_draw (W : in System.Address); pragma Import (C, fl_button_draw, "fl_button_draw"); pragma Inline (fl_button_draw); function fl_button_handle (W : in System.Address; E : in Interfaces.C.int) return Interfaces.C.int; pragma Import (C, fl_button_handle, "fl_button_handle"); pragma Inline (fl_button_handle); procedure Finalize (This : in out Button) is begin if This.Void_Ptr /= System.Null_Address and then This in Button'Class then free_fl_button (This.Void_Ptr); This.Void_Ptr := System.Null_Address; end if; Finalize (Widget (This)); end Finalize; package body Forge is function Create (X, Y, W, H : in Integer; Text : in String) return Button is begin return This : Button do This.Void_Ptr := new_fl_button (Interfaces.C.int (X), Interfaces.C.int (Y), Interfaces.C.int (W), Interfaces.C.int (H), Interfaces.C.To_C (Text)); fl_widget_set_user_data (This.Void_Ptr, Widget_Convert.To_Address (This'Unchecked_Access)); button_set_draw_hook (This.Void_Ptr, Draw_Hook'Address); button_set_handle_hook (This.Void_Ptr, Handle_Hook'Address); end return; end Create; end Forge; function Get_State (This : in Button) return State is begin return State'Val (fl_button_get_state (This.Void_Ptr)); end Get_State; procedure Set_State (This : in out Button; St : in State) is begin fl_button_set_state (This.Void_Ptr, State'Pos (St)); end Set_State; procedure Set_Only (This : in out Button) is begin fl_button_set_only (This.Void_Ptr); end Set_Only; function Get_Down_Box (This : in Button) return Box_Kind is begin return Box_Kind'Val (fl_button_get_down_box (This.Void_Ptr)); end Get_Down_Box; procedure Set_Down_Box (This : in out Button; To : in Box_Kind) is begin fl_button_set_down_box (This.Void_Ptr, Box_Kind'Pos (To)); end Set_Down_Box; function Get_Shortcut (This : in Button) return Key_Combo is begin return To_Ada (Interfaces.C.unsigned_long (fl_button_get_shortcut (This.Void_Ptr))); end Get_Shortcut; procedure Set_Shortcut (This : in out Button; Key : in Key_Combo) is begin fl_button_set_shortcut (This.Void_Ptr, Interfaces.C.int (To_C (Key))); end Set_Shortcut; procedure Draw (This : in out Button) is begin fl_button_draw (This.Void_Ptr); end Draw; function Handle (This : in out Button; Event : in Event_Kind) return Event_Outcome is begin return Event_Outcome'Val (fl_button_handle (This.Void_Ptr, Event_Kind'Pos (Event))); end Handle; end FLTK.Widgets.Buttons;
reznikmm/matreshka
Ada
4,053
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with ODF.DOM.Number_Decimal_Places_Attributes; package Matreshka.ODF_Number.Decimal_Places_Attributes is type Number_Decimal_Places_Attribute_Node is new Matreshka.ODF_Number.Abstract_Number_Attribute_Node and ODF.DOM.Number_Decimal_Places_Attributes.ODF_Number_Decimal_Places_Attribute with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Number_Decimal_Places_Attribute_Node; overriding function Get_Local_Name (Self : not null access constant Number_Decimal_Places_Attribute_Node) return League.Strings.Universal_String; end Matreshka.ODF_Number.Decimal_Places_Attributes;
FredPraca/distributed_cbsg
Ada
14,687
adb
pragma Style_Checks ("NM32766"); --------------------------------------------------- -- This file has been generated automatically from -- cbsg.idl -- by IAC (IDL to Ada Compiler) 20.0w (rev. 90136cd4). --------------------------------------------------- -- NOTE: If you modify this file by hand, your -- changes will be lost when you re-run the -- IDL to Ada compiler. --------------------------------------------------- with CorbaCBSG.CBSG.Impl; with CorbaCBSG.Helper; with PolyORB.Any; with CORBA; pragma Elaborate_All (CORBA); with CORBA.ServerRequest; with CORBA.NVList; with PolyORB.CORBA_P.IR_Hooks; with CORBA.Object; with CORBA.Object.Helper; with PolyORB.CORBA_P.Domain_Management; with CorbaCBSG_CBSG_Hash; with PolyORB.Std; with PortableServer; with CORBA.ORB; with PolyORB.CORBA_P.Exceptions; with PolyORB.Qos.Exception_Informations; with PolyORB.Utils.Strings; with PolyORB.Utils.Strings.Lists; with PolyORB.Initialization; package body CorbaCBSG.CBSG.Skel is N_Operations : constant PolyORB.Std.Natural := 10; type String_Ptr is access PolyORB.Std.String; Invoke_Db : array (0 .. (N_Operations - 1)) of String_Ptr := (others => null); procedure Register_Procedure (Operation_Name : PolyORB.Std.String); ------------------------ -- Register_Procedure -- ------------------------ procedure Register_Procedure (Operation_Name : PolyORB.Std.String) is Index_Ü : PolyORB.Std.Natural; Invoke_Name_Access : String_Ptr; begin Index_Ü := CorbaCBSG_CBSG_Hash.Hash (Operation_Name); if (Invoke_Db (Index_Ü) /= null) then raise Program_Error; end if; Invoke_Name_Access := new PolyORB.Std.String' (Operation_Name); Invoke_Db (Index_Ü) := Invoke_Name_Access; end Register_Procedure; procedure Invoke (Self : PortableServer.Servant; Request : CORBA.ServerRequest.Object_Ptr); ------------ -- Invoke -- ------------ procedure Invoke (Self : PortableServer.Servant; Request : CORBA.ServerRequest.Object_Ptr) is Operation_Ü : constant PolyORB.Std.String := CORBA.To_Standard_String (CORBA.ServerRequest.Operation (Request.all)); Argument_List_Ü : CORBA.NVList.Ref; Index_Ü : PolyORB.Std.Natural; Invoke_Name_Access : String_Ptr; procedure Invoke_createTimestampedSentence; -------------------------------------- -- Invoke_createTimestampedSentence -- -------------------------------------- procedure Invoke_createTimestampedSentence is Result_Ü : CorbaCBSG.timestamped_Sentence; pragma Warnings (Off, Result_Ü); pragma Suppress (Validity_Check, Result_Ü); Arg_CC_Result_Ü_Ü : aliased PolyORB.Any.Content'Class := CorbaCBSG.Helper.Internals.Wrap (Result_Ü'Unrestricted_Access); Arg_Any_Result_Ü_Ü : constant CORBA.Any := CORBA.Internals.Get_Wrapper_Any (CorbaCBSG.Helper.TC_timestamped_Sentence, Arg_CC_Result_Ü_Ü'Unchecked_Access); begin -- Processing request CORBA.ServerRequest.Arguments (Request, Argument_List_Ü); -- Call Implementation Result_Ü := CorbaCBSG.CBSG.Impl.createTimestampedSentence (CorbaCBSG.CBSG.Impl.Object'Class (Self.all)'Access); -- Setting the result CORBA.ServerRequest.Set_Result (Request, Arg_Any_Result_Ü_Ü); CORBA.NVList.Internals.Clone_Out_Args (Argument_List_Ü); end Invoke_createTimestampedSentence; procedure Invoke_createSentence; --------------------------- -- Invoke_createSentence -- --------------------------- procedure Invoke_createSentence is Result_Ü : CORBA.String; pragma Warnings (Off, Result_Ü); pragma Suppress (Validity_Check, Result_Ü); Arg_CC_Result_Ü_Ü : aliased PolyORB.Any.Content'Class := CORBA.Wrap (Result_Ü'Unrestricted_Access); Arg_Any_Result_Ü_Ü : constant CORBA.Any := CORBA.Internals.Get_Wrapper_Any (CORBA.TC_String, Arg_CC_Result_Ü_Ü'Unchecked_Access); begin -- Processing request CORBA.ServerRequest.Arguments (Request, Argument_List_Ü); -- Call Implementation Result_Ü := CorbaCBSG.CBSG.Impl.createSentence (CorbaCBSG.CBSG.Impl.Object'Class (Self.all)'Access); -- Setting the result CORBA.ServerRequest.Set_Result (Request, Arg_Any_Result_Ü_Ü); CORBA.NVList.Internals.Clone_Out_Args (Argument_List_Ü); end Invoke_createSentence; procedure Invoke_createWorkshop; --------------------------- -- Invoke_createWorkshop -- --------------------------- procedure Invoke_createWorkshop is Result_Ü : CORBA.String; pragma Warnings (Off, Result_Ü); pragma Suppress (Validity_Check, Result_Ü); Arg_CC_Result_Ü_Ü : aliased PolyORB.Any.Content'Class := CORBA.Wrap (Result_Ü'Unrestricted_Access); Arg_Any_Result_Ü_Ü : constant CORBA.Any := CORBA.Internals.Get_Wrapper_Any (CORBA.TC_String, Arg_CC_Result_Ü_Ü'Unchecked_Access); begin -- Processing request CORBA.ServerRequest.Arguments (Request, Argument_List_Ü); -- Call Implementation Result_Ü := CorbaCBSG.CBSG.Impl.createWorkshop (CorbaCBSG.CBSG.Impl.Object'Class (Self.all)'Access); -- Setting the result CORBA.ServerRequest.Set_Result (Request, Arg_Any_Result_Ü_Ü); CORBA.NVList.Internals.Clone_Out_Args (Argument_List_Ü); end Invoke_createWorkshop; procedure Invoke_createShortWorkshop; -------------------------------- -- Invoke_createShortWorkshop -- -------------------------------- procedure Invoke_createShortWorkshop is Result_Ü : CORBA.String; pragma Warnings (Off, Result_Ü); pragma Suppress (Validity_Check, Result_Ü); Arg_CC_Result_Ü_Ü : aliased PolyORB.Any.Content'Class := CORBA.Wrap (Result_Ü'Unrestricted_Access); Arg_Any_Result_Ü_Ü : constant CORBA.Any := CORBA.Internals.Get_Wrapper_Any (CORBA.TC_String, Arg_CC_Result_Ü_Ü'Unchecked_Access); begin -- Processing request CORBA.ServerRequest.Arguments (Request, Argument_List_Ü); -- Call Implementation Result_Ü := CorbaCBSG.CBSG.Impl.createShortWorkshop (CorbaCBSG.CBSG.Impl.Object'Class (Self.all)'Access); -- Setting the result CORBA.ServerRequest.Set_Result (Request, Arg_Any_Result_Ü_Ü); CORBA.NVList.Internals.Clone_Out_Args (Argument_List_Ü); end Invoke_createShortWorkshop; procedure Invoke_createFinancialReport; ---------------------------------- -- Invoke_createFinancialReport -- ---------------------------------- procedure Invoke_createFinancialReport is Result_Ü : CORBA.String; pragma Warnings (Off, Result_Ü); pragma Suppress (Validity_Check, Result_Ü); Arg_CC_Result_Ü_Ü : aliased PolyORB.Any.Content'Class := CORBA.Wrap (Result_Ü'Unrestricted_Access); Arg_Any_Result_Ü_Ü : constant CORBA.Any := CORBA.Internals.Get_Wrapper_Any (CORBA.TC_String, Arg_CC_Result_Ü_Ü'Unchecked_Access); begin -- Processing request CORBA.ServerRequest.Arguments (Request, Argument_List_Ü); -- Call Implementation Result_Ü := CorbaCBSG.CBSG.Impl.createFinancialReport (CorbaCBSG.CBSG.Impl.Object'Class (Self.all)'Access); -- Setting the result CORBA.ServerRequest.Set_Result (Request, Arg_Any_Result_Ü_Ü); CORBA.NVList.Internals.Clone_Out_Args (Argument_List_Ü); end Invoke_createFinancialReport; procedure Invoke_Uis_a; ------------------ -- Invoke_Uis_a -- ------------------ procedure Invoke_Uis_a is Type_Id_Ü : CORBA.String; Arg_Name_Type_Id_Ü : constant CORBA.Identifier := CORBA.To_CORBA_String ("Type_Id_Ü"); Argument_Type_Id_Ü : constant CORBA.Any := CORBA.To_Any (Type_Id_Ü); Result_Ü : CORBA.Boolean; begin CORBA.NVList.Add_Item (Argument_List_Ü, Arg_Name_Type_Id_Ü, Argument_Type_Id_Ü, CORBA.ARG_IN); CORBA.ServerRequest.Arguments (Request, Argument_List_Ü); Type_Id_Ü := CORBA.From_Any (Argument_Type_Id_Ü); Result_Ü := Is_A (CORBA.To_Standard_String (Type_Id_Ü)); CORBA.ServerRequest.Set_Result (Request, CORBA.To_Any (Result_Ü)); end Invoke_Uis_a; procedure Invoke_Uinterface; ----------------------- -- Invoke_Uinterface -- ----------------------- procedure Invoke_Uinterface is begin CORBA.ServerRequest.Arguments (Request, Argument_List_Ü); CORBA.ServerRequest.Set_Result (Request, CORBA.Object.Helper.To_Any (CORBA.Object.Ref (PolyORB.CORBA_P.IR_Hooks.Get_Interface_Definition (CORBA.To_CORBA_String (Repository_Id))))); end Invoke_Uinterface; procedure Invoke_Udomain_managers; ----------------------------- -- Invoke_Udomain_managers -- ----------------------------- procedure Invoke_Udomain_managers is begin CORBA.ServerRequest.Arguments (Request, Argument_List_Ü); CORBA.ServerRequest.Set_Result (Request, PolyORB.CORBA_P.Domain_Management.Get_Domain_Managers (Self)); end Invoke_Udomain_managers; procedure Invoke_Unon_existent; -------------------------- -- Invoke_Unon_existent -- -------------------------- procedure Invoke_Unon_existent is begin CORBA.ServerRequest.Arguments (Request, Argument_List_Ü); CORBA.ServerRequest.Set_Result (Request, CORBA.To_Any (CORBA.Boolean' (False))); end Invoke_Unon_existent; procedure Dispatch; -------------- -- Dispatch -- -------------- procedure Dispatch is begin case Index_Ü is when 0 => Invoke_createTimestampedSentence; when 1 => Invoke_createSentence; when 2 => Invoke_createWorkshop; when 3 => Invoke_createShortWorkshop; when 4 => Invoke_createFinancialReport; when 6 => Invoke_Uinterface; when 7 => Invoke_Udomain_managers; when 8 | 9 => Invoke_Unon_existent; when 5 => Invoke_Uis_a; pragma Warnings (Off); when others => raise Program_Error; pragma Warnings (On); end case; end Dispatch; begin CORBA.ORB.Create_List (0, Argument_List_Ü); Index_Ü := CorbaCBSG_CBSG_Hash.Hash (Operation_Ü); Invoke_Name_Access := Invoke_Db (Index_Ü); begin if (Operation_Ü = Invoke_Name_Access.all) then Dispatch; else CORBA.Raise_Bad_Operation (CORBA.Default_Sys_Member); end if; exception when E : others => CORBA.ServerRequest.Set_Exception (Request, PolyORB.CORBA_P.Exceptions.System_Exception_To_Any (E)); PolyORB.Qos.Exception_Informations.Set_Exception_Information (Request.all, E); end; end Invoke; function Servant_Is_A (Obj : PortableServer.Servant) return Boolean; ------------------ -- Servant_Is_A -- ------------------ function Servant_Is_A (Obj : PortableServer.Servant) return Boolean is begin return (Obj.all in CorbaCBSG.CBSG.Impl.Object'Class); end Servant_Is_A; ----------------------------- -- Deferred_Initialization -- ----------------------------- procedure Deferred_Initialization is begin PortableServer.Internals.Register_Skeleton (CorbaCBSG.CBSG.Repository_Id, Servant_Is_A'Access, Is_A'Access, Invoke'Access); Register_Procedure ("createTimestampedSentence"); Register_Procedure ("createSentence"); Register_Procedure ("createWorkshop"); Register_Procedure ("createShortWorkshop"); Register_Procedure ("createFinancialReport"); Register_Procedure ("_is_a"); Register_Procedure ("_interface"); Register_Procedure ("_domain_managers"); Register_Procedure ("_non_existent"); Register_Procedure ("_not_existent"); end Deferred_Initialization; begin declare use PolyORB.Utils.Strings; use PolyORB.Utils.Strings.Lists; begin PolyORB.Initialization.Register_Module (PolyORB.Initialization.Module_Info' (Name => +"CorbaCBSG.CBSG.Skel", Conflicts => PolyORB.Utils.Strings.Lists.Empty, Depends => PolyORB.Utils.Strings.Lists.Empty, Provides => PolyORB.Utils.Strings.Lists.Empty, Implicit => False, Init => Deferred_Initialization'Access, Shutdown => null)); end; end CorbaCBSG.CBSG.Skel;
charlie5/cBound
Ada
1,578
ads
-- This file is generated by SWIG. Please do not modify by hand. -- with Interfaces; with swig; with Interfaces.C; with Interfaces.C.Pointers; package xcb.xcb_intern_atom_request_t is -- Item -- type Item is record major_opcode : aliased Interfaces.Unsigned_8; only_if_exists : aliased Interfaces.Unsigned_8; length : aliased Interfaces.Unsigned_16; name_len : aliased Interfaces.Unsigned_16; pad0 : aliased swig.int8_t_Array (0 .. 1); end record; -- Item_Array -- type Item_Array is array (Interfaces.C.size_t range <>) of aliased xcb.xcb_intern_atom_request_t .Item; -- Pointer -- package C_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_intern_atom_request_t.Item, Element_Array => xcb.xcb_intern_atom_request_t.Item_Array, Default_Terminator => (others => <>)); subtype Pointer is C_Pointers.Pointer; -- Pointer_Array -- type Pointer_Array is array (Interfaces.C.size_t range <>) of aliased xcb.xcb_intern_atom_request_t .Pointer; -- Pointer_Pointer -- package C_Pointer_Pointers is new Interfaces.C.Pointers (Index => Interfaces.C.size_t, Element => xcb.xcb_intern_atom_request_t.Pointer, Element_Array => xcb.xcb_intern_atom_request_t.Pointer_Array, Default_Terminator => null); subtype Pointer_Pointer is C_Pointer_Pointers.Pointer; end xcb.xcb_intern_atom_request_t;
AdaCore/gpr
Ada
309
adb
-- -- Copyright (C) 2020-2023, AdaCore -- -- SPDX-License-Identifier: Apache-2.0 -- package body Counters is procedure Bump (C : in out Counter) is begin C.Value := C.Value + 9; end Bump; procedure Reset (C : in out Counter) is begin C.Value := 0; end Reset; end Counters;
Gabriel-Degret/adalib
Ada
3,168
ads
-- Standard Ada library specification -- Copyright (c) 2003-2018 Maxim Reznik <[email protected]> -- Copyright (c) 2004-2016 AXE Consultants -- Copyright (c) 2004, 2005, 2006 Ada-Europe -- Copyright (c) 2000 The MITRE Corporation, Inc. -- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc. -- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual --------------------------------------------------------------------------- package Interfaces is pragma Pure(Interfaces); type Integer_8 is range -2**(8-1) .. 2**(8-1) - 1; type Unsigned_8 is mod 2**8; function Shift_Left (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Shift_Right (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Shift_Right_Arithmetic (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Rotate_Left (Value : Unsigned_8; Amount : Natural) return Unsigned_8; function Rotate_Right (Value : Unsigned_8; Amount : Natural) return Unsigned_8; type Integer_16 is range -2**(16-1) .. 2**(16-1) - 1; type Unsigned_16 is mod 2**16; function Shift_Left (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Shift_Right (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Shift_Right_Arithmetic (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Rotate_Left (Value : Unsigned_16; Amount : Natural) return Unsigned_16; function Rotate_Right (Value : Unsigned_16; Amount : Natural) return Unsigned_16; type Integer_32 is range -2**(32-1) .. 2**(32-1) - 1; type Unsigned_32 is mod 2**32; function Shift_Left (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Shift_Right (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Shift_Right_Arithmetic (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Rotate_Left (Value : Unsigned_32; Amount : Natural) return Unsigned_32; function Rotate_Right (Value : Unsigned_32; Amount : Natural) return Unsigned_32; type Integer_64 is range -2**(64-1) .. 2**(64-1) - 1; type Unsigned_64 is mod 2**64; function Shift_Left (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Shift_Right (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Shift_Right_Arithmetic (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Rotate_Left (Value : Unsigned_64; Amount : Natural) return Unsigned_64; function Rotate_Right (Value : Unsigned_64; Amount : Natural) return Unsigned_64; end Interfaces;
zhmu/ananas
Ada
6,135
ads
------------------------------------------------------------------------------ -- -- -- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- S Y S T E M . L I N U X -- -- -- -- S p e c -- -- -- -- Copyright (C) 2008-2022, Free Software Foundation, Inc. -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- -- ------------------------------------------------------------------------------ -- This is the hppa version of this package -- This package encapsulates cpu specific differences between implementations -- of GNU/Linux, in order to share s-osinte-linux.ads. -- PLEASE DO NOT add any with-clauses to this package or remove the pragma -- Preelaborate. This package is designed to be a bottom-level (leaf) package. with Interfaces.C; with System.Parameters; package System.Linux is pragma Preelaborate; ---------- -- Time -- ---------- subtype long is Interfaces.C.long; subtype suseconds_t is Interfaces.C.long; type time_t is range -2 ** (System.Parameters.time_t_bits - 1) .. 2 ** (System.Parameters.time_t_bits - 1) - 1; subtype clockid_t is Interfaces.C.int; type timespec is record tv_sec : time_t; tv_nsec : long; end record; pragma Convention (C, timespec); type timeval is record tv_sec : time_t; tv_usec : suseconds_t; end record; pragma Convention (C, timeval); ----------- -- Errno -- ----------- EAGAIN : constant := 11; EINTR : constant := 4; EINVAL : constant := 22; ENOMEM : constant := 12; EPERM : constant := 1; ETIMEDOUT : constant := 238; ------------- -- Signals -- ------------- SIGHUP : constant := 1; -- hangup SIGINT : constant := 2; -- interrupt (rubout) SIGQUIT : constant := 3; -- quit (ASCD FS) SIGILL : constant := 4; -- illegal instruction (not reset) SIGTRAP : constant := 5; -- trace trap (not reset) SIGIOT : constant := 6; -- IOT instruction SIGABRT : constant := 6; -- used by abort, replace SIGIOT in the future SIGEMT : constant := 7; -- EMT SIGFPE : constant := 8; -- floating point exception SIGKILL : constant := 9; -- kill (cannot be caught or ignored) SIGBUS : constant := 10; -- bus error SIGSEGV : constant := 11; -- segmentation violation SIGSYS : constant := 12; -- bad system call SIGPIPE : constant := 13; -- write on a pipe with no one to read it SIGALRM : constant := 14; -- alarm clock SIGTERM : constant := 15; -- software termination signal from kill SIGUSR1 : constant := 16; -- user defined signal 1 SIGUSR2 : constant := 17; -- user defined signal 2 SIGCLD : constant := 18; -- alias for SIGCHLD SIGCHLD : constant := 18; -- child status change SIGPWR : constant := 19; -- power-fail restart SIGVTALRM : constant := 20; -- virtual timer expired SIGPROF : constant := 21; -- profiling timer expired SIGPOLL : constant := 22; -- pollable event occurred SIGIO : constant := 22; -- I/O now possible (4.2 BSD) SIGWINCH : constant := 23; -- window size change SIGSTOP : constant := 24; -- stop (cannot be caught or ignored) SIGTSTP : constant := 25; -- user stop requested from tty SIGCONT : constant := 26; -- stopped process has been continued SIGTTIN : constant := 27; -- background tty read attempted SIGTTOU : constant := 28; -- background tty write attempted SIGURG : constant := 29; -- urgent condition on IO channel SIGLOST : constant := 30; -- File lock lost SIGUNUSED : constant := 31; -- unused signal (GNU/Linux) SIGXCPU : constant := 33; -- CPU time limit exceeded SIGXFSZ : constant := 34; -- filesize limit exceeded SIGSTKFLT : constant := 36; -- coprocessor stack fault (Linux) SIG32 : constant := 37; -- glibc internal signal SIG33 : constant := 38; -- glibc internal signal SIG34 : constant := 39; -- glibc internal signal -- struct_sigaction offsets sa_handler_pos : constant := 0; sa_flags_pos : constant := Standard'Address_Size / 8; sa_mask_pos : constant := sa_flags_pos * 2; SA_SIGINFO : constant := 16#10#; SA_ONSTACK : constant := 16#01#; end System.Linux;
Componolit/libsparkcrypto
Ada
11,459
ads
------------------------------------------------------------------------------- -- This file is part of libsparkcrypto. -- -- Copyright (C) 2012, Stefan Berghofer -- Copyright (C) 2012, secunet Security Networks AG -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- * Neither the name of the author nor the names of its contributors may be -- used to endorse or promote products derived from this software without -- specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS -- BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- with LSC.Internal.Types; with LSC.Internal.Bignum; with LSC.Internal.EC; with LSC.Internal.Math_Int; use type LSC.Internal.Math_Int.Math_Int; use type LSC.Internal.Types.Word32; package LSC.Internal.EC_Signature is pragma Pure; type Signature_Type is (ECDSA, ECGDSA); procedure Sign (Sign1 : out Bignum.Big_Int; Sign1_First : in Natural; Sign1_Last : in Natural; Sign2 : out Bignum.Big_Int; Sign2_First : in Natural; Hash : in Bignum.Big_Int; Hash_First : in Natural; Rand : in Bignum.Big_Int; Rand_First : in Natural; T : in Signature_Type; Priv : in Bignum.Big_Int; Priv_First : in Natural; BX : in Bignum.Big_Int; BX_First : in Natural; BY : in Bignum.Big_Int; BY_First : in Natural; A : in Bignum.Big_Int; A_First : in Natural; M : in Bignum.Big_Int; M_First : in Natural; M_Inv : in Types.Word32; RM : in Bignum.Big_Int; RM_First : in Natural; N : in Bignum.Big_Int; N_First : in Natural; N_Inv : in Types.Word32; RN : in Bignum.Big_Int; RN_First : in Natural; Success : out Boolean) with Depends => (Sign1 =>+ (Sign1_First, Sign1_Last, Rand, Rand_First, BX, BX_First, BY, BY_First, A, A_First, M, M_First, M_Inv, RM, RM_First, N, N_First, N_Inv, RN, RN_First), (Sign2, Success) => (Sign1, Sign1_First, Sign1_Last, Sign2, Sign2_First, Hash, Hash_First, Rand, Rand_First, T, Priv, Priv_First, BX, BX_First, BY, BY_First, A, A_First, M, M_First, M_Inv, RM, RM_First, N, N_First, N_Inv, RN, RN_First)), Pre => Sign1_First in Sign1'Range and then Sign1_Last in Sign1'Range and then Sign1_First < Sign1_Last and then Sign1_Last - Sign1_First < EC.Max_Coord_Length and then Sign2_First in Sign2'Range and then Sign2_First + (Sign1_Last - Sign1_First) in Sign2'Range and then Hash_First in Hash'Range and then Hash_First + (Sign1_Last - Sign1_First) in Hash'Range and then Rand_First in Rand'Range and then Rand_First + (Sign1_Last - Sign1_First) in Rand'Range and then Priv_First in Priv'Range and then Priv_First + (Sign1_Last - Sign1_First) in Priv'Range and then BX_First in BX'Range and then BX_First + (Sign1_Last - Sign1_First) in BX'Range and then BY_First in BY'Range and then BY_First + (Sign1_Last - Sign1_First) in BY'Range and then A_First in A'Range and then A_First + (Sign1_Last - Sign1_First) in A'Range and then M_First in M'Range and then M_First + (Sign1_Last - Sign1_First) in M'Range and then RM_First in RM'Range and then RM_First + (Sign1_Last - Sign1_First) in RM'Range and then N_First in N'Range and then N_First + (Sign1_Last - Sign1_First) in N'Range and then RN_First in RN'Range and then RN_First + (Sign1_Last - Sign1_First) in RN'Range and then Bignum.Num_Of_Big_Int (BX, BX_First, Sign1_Last - Sign1_First + 1) < Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then Bignum.Num_Of_Big_Int (BY, BY_First, Sign1_Last - Sign1_First + 1) < Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then Bignum.Num_Of_Big_Int (A, A_First, Sign1_Last - Sign1_First + 1) < Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then Math_Int.From_Word32 (1) < Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then 1 + M_Inv * M (M_First) = 0 and then Math_Int.From_Word32 (1) < Bignum.Num_Of_Big_Int (N, N_First, Sign1_Last - Sign1_First + 1) and then 1 + N_Inv * N (N_First) = 0 and then Bignum.Num_Of_Big_Int (RM, RM_First, Sign1_Last - Sign1_First + 1) = Bignum.Base ** (Math_Int.From_Integer (2) * Math_Int.From_Integer (Sign1_Last - Sign1_First + 1)) mod Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then Bignum.Num_Of_Big_Int (RN, RN_First, Sign1_Last - Sign1_First + 1) = Bignum.Base ** (Math_Int.From_Integer (2) * Math_Int.From_Integer (Sign1_Last - Sign1_First + 1)) mod Bignum.Num_Of_Big_Int (N, N_First, Sign1_Last - Sign1_First + 1), Post => (if Success then (Math_Int.From_Word32 (0) < Bignum.Num_Of_Big_Int (Sign1, Sign1_First, Sign1_Last - Sign1_First + 1) and Bignum.Num_Of_Big_Int (Sign1, Sign1_First, Sign1_Last - Sign1_First + 1) < Bignum.Num_Of_Big_Int (N, N_First, Sign1_Last - Sign1_First + 1) and Math_Int.From_Word32 (0) < Bignum.Num_Of_Big_Int (Sign2, Sign2_First, Sign1_Last - Sign1_First + 1) and Bignum.Num_Of_Big_Int (Sign2, Sign2_First, Sign1_Last - Sign1_First + 1) < Bignum.Num_Of_Big_Int (N, N_First, Sign1_Last - Sign1_First + 1))); function Verify (Sign1 : Bignum.Big_Int; Sign1_First : Natural; Sign1_Last : Natural; Sign2 : Bignum.Big_Int; Sign2_First : Natural; Hash : Bignum.Big_Int; Hash_First : Natural; T : Signature_Type; PubX : Bignum.Big_Int; PubX_First : Natural; PubY : Bignum.Big_Int; PubY_First : Natural; BX : Bignum.Big_Int; BX_First : Natural; BY : Bignum.Big_Int; BY_First : Natural; A : Bignum.Big_Int; A_First : Natural; M : Bignum.Big_Int; M_First : Natural; M_Inv : Types.Word32; RM : Bignum.Big_Int; RM_First : Natural; N : Bignum.Big_Int; N_First : Natural; N_Inv : Types.Word32; RN : Bignum.Big_Int; RN_First : Natural) return Boolean with Pre => Sign1_First in Sign1'Range and then Sign1_Last in Sign1'Range and then Sign1_First < Sign1_Last and then Sign1_Last - Sign1_First < EC.Max_Coord_Length and then Sign2_First in Sign2'Range and then Sign2_First + (Sign1_Last - Sign1_First) in Sign2'Range and then Hash_First in Hash'Range and then Hash_First + (Sign1_Last - Sign1_First) in Hash'Range and then PubX_First in PubX'Range and then PubX_First + (Sign1_Last - Sign1_First) in PubX'Range and then PubY_First in PubY'Range and then PubY_First + (Sign1_Last - Sign1_First) in PubY'Range and then BX_First in BX'Range and then BX_First + (Sign1_Last - Sign1_First) in BX'Range and then BY_First in BY'Range and then BY_First + (Sign1_Last - Sign1_First) in BY'Range and then A_First in A'Range and then A_First + (Sign1_Last - Sign1_First) in A'Range and then M_First in M'Range and then M_First + (Sign1_Last - Sign1_First) in M'Range and then RM_First in RM'Range and then RM_First + (Sign1_Last - Sign1_First) in RM'Range and then N_First in N'Range and then N_First + (Sign1_Last - Sign1_First) in N'Range and then RN_First in RN'Range and then RN_First + (Sign1_Last - Sign1_First) in RN'Range and then Bignum.Num_Of_Big_Int (PubX, PubX_First, Sign1_Last - Sign1_First + 1) < Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then Bignum.Num_Of_Big_Int (PubY, PubY_First, Sign1_Last - Sign1_First + 1) < Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then Bignum.Num_Of_Big_Int (BX, BX_First, Sign1_Last - Sign1_First + 1) < Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then Bignum.Num_Of_Big_Int (BY, BY_First, Sign1_Last - Sign1_First + 1) < Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then Bignum.Num_Of_Big_Int (A, A_First, Sign1_Last - Sign1_First + 1) < Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then Math_Int.From_Word32 (1) < Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then 1 + M_Inv * M (M_First) = 0 and then Math_Int.From_Word32 (1) < Bignum.Num_Of_Big_Int (N, N_First, Sign1_Last - Sign1_First + 1) and then 1 + N_Inv * N (N_First) = 0 and then Bignum.Num_Of_Big_Int (RM, RM_First, Sign1_Last - Sign1_First + 1) = Bignum.Base ** (Math_Int.From_Integer (2) * Math_Int.From_Integer (Sign1_Last - Sign1_First + 1)) mod Bignum.Num_Of_Big_Int (M, M_First, Sign1_Last - Sign1_First + 1) and then Bignum.Num_Of_Big_Int (RN, RN_First, Sign1_Last - Sign1_First + 1) = Bignum.Base ** (Math_Int.From_Integer (2) * Math_Int.From_Integer (Sign1_Last - Sign1_First + 1)) mod Bignum.Num_Of_Big_Int (N, N_First, Sign1_Last - Sign1_First + 1); end LSC.Internal.EC_Signature;
iyan22/AprendeAda
Ada
1,565
adb
with Ada.Text_Io, Ada.Float_Text_Io, Datos; with Crear_Lista_Vacia, Ins, Esc, Media; use Datos; use Ada.Text_Io, Ada.Float_Text_Io; procedure Prueba_Media is Lis : Lista; -- variable del programa principal procedure Pedir_Return is begin Put_Line("pulsa return para continuar "); Skip_Line; end Pedir_Return; begin -- programa principal -- Casos de prueba: -- 1. Lista vacia. Resultado: cero -- 2. Lista no vacia. Lista de un elemento -- 3. Lista no vacia. Varios elementos Put_Line("Programa de prueba: "); Put_Line("*********"); Crear_Lista_Vacia(Lis); Put_Line("Caso de prueba 1: Lista vacia "); Put_Line("En este caso no existe ningun elemento en la lista, por lo que no existira una media"); Put_Line("Ahora deberia escribir NaN: "); Put(Media(Lis), exp => 0); New_Line; New_Line; Pedir_Return; Crear_Lista_Vacia(Lis); Ins(Lis, 4); Put_Line("Caso de prueba 2: lista de un solo elemento."); Put_Line("La lista inicial contiene "); Esc(Lis); Put_Line("Ahora deberia escribir 4.00: "); Put(Media(Lis), exp => 0); New_Line; New_Line; Pedir_Return; Crear_Lista_Vacia(Lis); Ins(Lis, 6); Ins(Lis, 8); Ins(Lis, 9); Ins(Lis, 10); Put_Line("Caso de prueba 3: lista de varios elementos."); Put_Line("La lista inicial contiene "); Esc(Lis); Put_Line("Ahora deberia escribir 8.25: "); Put(Media(Lis), exp => 0); New_Line; New_Line; Pedir_Return; Put_Line("Se acabo la prueba. Agur "); end Prueba_Media ;
pdibez/mundo-aspiradora
Ada
219
ads
package direccion is type t_direccion is (Izquierda,Derecha); subtype t_posicion is t_direccion range Izquierda .. Derecha ; function direccion_opuesta(d : in t_direccion) return t_direccion; end direccion;
reznikmm/matreshka
Ada
4,041
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with ODF.DOM.Draw_Color_Inversion_Attributes; package Matreshka.ODF_Draw.Color_Inversion_Attributes is type Draw_Color_Inversion_Attribute_Node is new Matreshka.ODF_Draw.Abstract_Draw_Attribute_Node and ODF.DOM.Draw_Color_Inversion_Attributes.ODF_Draw_Color_Inversion_Attribute with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Draw_Color_Inversion_Attribute_Node; overriding function Get_Local_Name (Self : not null access constant Draw_Color_Inversion_Attribute_Node) return League.Strings.Universal_String; end Matreshka.ODF_Draw.Color_Inversion_Attributes;